blob: 73945f48acdfcdf922dc20df5ec9c106e9c9d2a8 [file] [log] [blame]
Vernon Mauery240b1862018-10-08 12:05:16 -07001/**
2 * Copyright © 2018 Intel Corporation
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16#include "config.h"
17
18#include "settings.hpp"
19
20#include <dlfcn.h>
21
22#include <algorithm>
23#include <any>
Vernon Mauery735ee952019-02-15 13:38:52 -080024#include <boost/algorithm/string.hpp>
Ed Tanous778418d2020-08-17 23:20:21 -070025#include <boost/asio/io_context.hpp>
Vernon Mauerye8d43232019-03-26 16:23:43 -070026#include <dcmihandler.hpp>
Vernon Mauery240b1862018-10-08 12:05:16 -070027#include <exception>
Vernon Mauerybdda8002019-02-26 10:18:51 -080028#include <filesystem>
Vernon Mauery240b1862018-10-08 12:05:16 -070029#include <forward_list>
30#include <host-cmd-manager.hpp>
31#include <ipmid-host/cmd.hpp>
32#include <ipmid/api.hpp>
33#include <ipmid/handler.hpp>
34#include <ipmid/message.hpp>
35#include <ipmid/oemrouter.hpp>
Vernon Mauery33250242019-03-12 16:49:26 -070036#include <ipmid/types.hpp>
Vernon Mauery240b1862018-10-08 12:05:16 -070037#include <map>
38#include <memory>
39#include <optional>
40#include <phosphor-logging/log.hpp>
41#include <sdbusplus/asio/connection.hpp>
42#include <sdbusplus/asio/object_server.hpp>
43#include <sdbusplus/asio/sd_event.hpp>
44#include <sdbusplus/bus.hpp>
45#include <sdbusplus/bus/match.hpp>
46#include <sdbusplus/timer.hpp>
47#include <tuple>
Vernon Mauery240b1862018-10-08 12:05:16 -070048#include <unordered_map>
49#include <utility>
50#include <vector>
51
Vernon Mauery240b1862018-10-08 12:05:16 -070052namespace fs = std::filesystem;
53
54using namespace phosphor::logging;
55
Vernon Mauery240b1862018-10-08 12:05:16 -070056// IPMI Spec, shared Reservation ID.
57static unsigned short selReservationID = 0xFFFF;
58static bool selReservationValid = false;
59
60unsigned short reserveSel(void)
61{
62 // IPMI spec, Reservation ID, the value simply increases against each
63 // execution of the Reserve SEL command.
64 if (++selReservationID == 0)
65 {
66 selReservationID = 1;
67 }
68 selReservationValid = true;
69 return selReservationID;
70}
71
72bool checkSELReservation(unsigned short id)
73{
74 return (selReservationValid && selReservationID == id);
75}
76
77void cancelSELReservation(void)
78{
79 selReservationValid = false;
80}
81
82EInterfaceIndex getInterfaceIndex(void)
83{
84 return interfaceKCS;
85}
86
87sd_bus* bus;
88sd_event* events = nullptr;
89sd_event* ipmid_get_sd_event_connection(void)
90{
91 return events;
92}
93sd_bus* ipmid_get_sd_bus_connection(void)
94{
95 return bus;
96}
97
98namespace ipmi
99{
100
101static inline unsigned int makeCmdKey(unsigned int cluster, unsigned int cmd)
102{
103 return (cluster << 8) | cmd;
104}
105
106using HandlerTuple = std::tuple<int, /* prio */
107 Privilege, HandlerBase::ptr /* handler */
108 >;
109
110/* map to handle standard registered commands */
111static std::unordered_map<unsigned int, /* key is NetFn/Cmd */
112 HandlerTuple>
113 handlerMap;
114
Vernon Maueryf984a012018-10-08 12:05:18 -0700115/* special map for decoding Group registered commands (NetFn 2Ch) */
116static std::unordered_map<unsigned int, /* key is Group/Cmd (NetFn is 2Ch) */
117 HandlerTuple>
118 groupHandlerMap;
119
120/* special map for decoding OEM registered commands (NetFn 2Eh) */
121static std::unordered_map<unsigned int, /* key is Iana/Cmd (NetFn is 2Eh) */
122 HandlerTuple>
123 oemHandlerMap;
124
Vernon Mauery08a70aa2018-11-07 09:36:22 -0800125using FilterTuple = std::tuple<int, /* prio */
126 FilterBase::ptr /* filter */
127 >;
128
129/* list to hold all registered ipmi command filters */
130static std::forward_list<FilterTuple> filterList;
131
Vernon Mauery240b1862018-10-08 12:05:16 -0700132namespace impl
133{
134/* common function to register all standard IPMI handlers */
135bool registerHandler(int prio, NetFn netFn, Cmd cmd, Privilege priv,
136 HandlerBase::ptr handler)
137{
138 // check for valid NetFn: even; 00-0Ch, 30-3Eh
139 if (netFn & 1 || (netFn > netFnTransport && netFn < netFnGroup) ||
140 netFn > netFnOemEight)
141 {
142 return false;
143 }
144
145 // create key and value for this handler
146 unsigned int netFnCmd = makeCmdKey(netFn, cmd);
147 HandlerTuple item(prio, priv, handler);
148
149 // consult the handler map and look for a match
150 auto& mapCmd = handlerMap[netFnCmd];
151 if (!std::get<HandlerBase::ptr>(mapCmd) || std::get<int>(mapCmd) <= prio)
152 {
153 mapCmd = item;
154 return true;
155 }
156 return false;
157}
158
Vernon Maueryf984a012018-10-08 12:05:18 -0700159/* common function to register all Group IPMI handlers */
160bool registerGroupHandler(int prio, Group group, Cmd cmd, Privilege priv,
161 HandlerBase::ptr handler)
162{
163 // create key and value for this handler
164 unsigned int netFnCmd = makeCmdKey(group, cmd);
165 HandlerTuple item(prio, priv, handler);
166
167 // consult the handler map and look for a match
168 auto& mapCmd = groupHandlerMap[netFnCmd];
169 if (!std::get<HandlerBase::ptr>(mapCmd) || std::get<int>(mapCmd) <= prio)
170 {
171 mapCmd = item;
172 return true;
173 }
174 return false;
175}
176
177/* common function to register all OEM IPMI handlers */
178bool registerOemHandler(int prio, Iana iana, Cmd cmd, Privilege priv,
179 HandlerBase::ptr handler)
180{
181 // create key and value for this handler
182 unsigned int netFnCmd = makeCmdKey(iana, cmd);
183 HandlerTuple item(prio, priv, handler);
184
185 // consult the handler map and look for a match
186 auto& mapCmd = oemHandlerMap[netFnCmd];
187 if (!std::get<HandlerBase::ptr>(mapCmd) || std::get<int>(mapCmd) <= prio)
188 {
189 mapCmd = item;
190 return true;
191 }
192 return false;
193}
194
Vernon Mauery08a70aa2018-11-07 09:36:22 -0800195/* common function to register all IPMI filter handlers */
196void registerFilter(int prio, FilterBase::ptr filter)
197{
198 // check for initial placement
199 if (filterList.empty() || std::get<int>(filterList.front()) < prio)
200 {
201 filterList.emplace_front(std::make_tuple(prio, filter));
202 }
203 // walk the list and put it in the right place
204 auto j = filterList.begin();
205 for (auto i = j; i != filterList.end() && std::get<int>(*i) > prio; i++)
206 {
207 j = i;
208 }
209 filterList.emplace_after(j, std::make_tuple(prio, filter));
210}
211
Vernon Mauery240b1862018-10-08 12:05:16 -0700212} // namespace impl
213
Vernon Mauery08a70aa2018-11-07 09:36:22 -0800214message::Response::ptr filterIpmiCommand(message::Request::ptr request)
215{
216 // pass the command through the filter mechanism
217 // This can be the firmware firewall or any OEM mechanism like
218 // whitelist filtering based on operational mode
219 for (auto& item : filterList)
220 {
221 FilterBase::ptr filter = std::get<FilterBase::ptr>(item);
222 ipmi::Cc cc = filter->call(request);
223 if (ipmi::ccSuccess != cc)
224 {
225 return errorResponse(request, cc);
226 }
227 }
228 return message::Response::ptr();
229}
230
Vernon Mauery240b1862018-10-08 12:05:16 -0700231message::Response::ptr executeIpmiCommandCommon(
232 std::unordered_map<unsigned int, HandlerTuple>& handlers,
233 unsigned int keyCommon, message::Request::ptr request)
234{
Vernon Mauery08a70aa2018-11-07 09:36:22 -0800235 // filter the command first; a non-null message::Response::ptr
236 // means that the message has been rejected for some reason
Vernon Mauery51f78142020-01-13 16:28:59 -0800237 message::Response::ptr filterResponse = filterIpmiCommand(request);
Vernon Mauery08a70aa2018-11-07 09:36:22 -0800238
Vernon Mauery240b1862018-10-08 12:05:16 -0700239 Cmd cmd = request->ctx->cmd;
240 unsigned int key = makeCmdKey(keyCommon, cmd);
241 auto cmdIter = handlers.find(key);
242 if (cmdIter != handlers.end())
243 {
Vernon Mauery51f78142020-01-13 16:28:59 -0800244 // only return the filter response if the command is found
245 if (filterResponse)
246 {
247 return filterResponse;
248 }
Vernon Mauery240b1862018-10-08 12:05:16 -0700249 HandlerTuple& chosen = cmdIter->second;
250 if (request->ctx->priv < std::get<Privilege>(chosen))
251 {
252 return errorResponse(request, ccInsufficientPrivilege);
253 }
254 return std::get<HandlerBase::ptr>(chosen)->call(request);
255 }
256 else
257 {
258 unsigned int wildcard = makeCmdKey(keyCommon, cmdWildcard);
259 cmdIter = handlers.find(wildcard);
260 if (cmdIter != handlers.end())
261 {
Vernon Mauery51f78142020-01-13 16:28:59 -0800262 // only return the filter response if the command is found
263 if (filterResponse)
264 {
265 return filterResponse;
266 }
Vernon Mauery240b1862018-10-08 12:05:16 -0700267 HandlerTuple& chosen = cmdIter->second;
268 if (request->ctx->priv < std::get<Privilege>(chosen))
269 {
270 return errorResponse(request, ccInsufficientPrivilege);
271 }
272 return std::get<HandlerBase::ptr>(chosen)->call(request);
273 }
274 }
275 return errorResponse(request, ccInvalidCommand);
276}
277
Vernon Maueryf984a012018-10-08 12:05:18 -0700278message::Response::ptr executeIpmiGroupCommand(message::Request::ptr request)
279{
280 // look up the group for this request
William A. Kennington IIId10d9052019-04-24 01:57:36 -0700281 uint8_t bytes;
282 if (0 != request->payload.unpack(bytes))
Vernon Maueryf984a012018-10-08 12:05:18 -0700283 {
284 return errorResponse(request, ccReqDataLenInvalid);
285 }
William A. Kennington IIId10d9052019-04-24 01:57:36 -0700286 auto group = static_cast<Group>(bytes);
Vernon Maueryf984a012018-10-08 12:05:18 -0700287 message::Response::ptr response =
288 executeIpmiCommandCommon(groupHandlerMap, group, request);
William A. Kennington IIIda31f9a2019-04-25 01:36:32 -0700289 ipmi::message::Payload prefix;
290 prefix.pack(bytes);
291 response->prepend(prefix);
Vernon Maueryf984a012018-10-08 12:05:18 -0700292 return response;
293}
294
295message::Response::ptr executeIpmiOemCommand(message::Request::ptr request)
296{
297 // look up the iana for this request
William A. Kennington IIId10d9052019-04-24 01:57:36 -0700298 uint24_t bytes;
299 if (0 != request->payload.unpack(bytes))
Vernon Maueryf984a012018-10-08 12:05:18 -0700300 {
301 return errorResponse(request, ccReqDataLenInvalid);
302 }
William A. Kennington IIId10d9052019-04-24 01:57:36 -0700303 auto iana = static_cast<Iana>(bytes);
Vernon Maueryf984a012018-10-08 12:05:18 -0700304 message::Response::ptr response =
305 executeIpmiCommandCommon(oemHandlerMap, iana, request);
William A. Kennington IIIda31f9a2019-04-25 01:36:32 -0700306 ipmi::message::Payload prefix;
307 prefix.pack(bytes);
308 response->prepend(prefix);
Vernon Maueryf984a012018-10-08 12:05:18 -0700309 return response;
310}
311
Vernon Mauery240b1862018-10-08 12:05:16 -0700312message::Response::ptr executeIpmiCommand(message::Request::ptr request)
313{
314 NetFn netFn = request->ctx->netFn;
Vernon Maueryf984a012018-10-08 12:05:18 -0700315 if (netFnGroup == netFn)
316 {
317 return executeIpmiGroupCommand(request);
318 }
319 else if (netFnOem == netFn)
320 {
321 return executeIpmiOemCommand(request);
322 }
Vernon Mauery240b1862018-10-08 12:05:16 -0700323 return executeIpmiCommandCommon(handlerMap, netFn, request);
324}
325
Vernon Mauery735ee952019-02-15 13:38:52 -0800326namespace utils
327{
328template <typename AssocContainer, typename UnaryPredicate>
329void assoc_erase_if(AssocContainer& c, UnaryPredicate p)
330{
331 typename AssocContainer::iterator next = c.begin();
332 typename AssocContainer::iterator last = c.end();
333 while ((next = std::find_if(next, last, p)) != last)
334 {
335 c.erase(next++);
336 }
337}
338} // namespace utils
339
340namespace
341{
342std::unordered_map<std::string, uint8_t> uniqueNameToChannelNumber;
343
344// sdbusplus::bus::match::rules::arg0namespace() wants the prefix
345// to match without any trailing '.'
346constexpr const char ipmiDbusChannelMatch[] =
347 "xyz.openbmc_project.Ipmi.Channel";
348void updateOwners(sdbusplus::asio::connection& conn, const std::string& name)
349{
350 conn.async_method_call(
351 [name](const boost::system::error_code ec,
352 const std::string& nameOwner) {
353 if (ec)
354 {
355 log<level::ERR>("Error getting dbus owner",
356 entry("INTERFACE=%s", name.c_str()));
357 return;
358 }
359 // start after ipmiDbusChannelPrefix (after the '.')
360 std::string chName =
361 name.substr(std::strlen(ipmiDbusChannelMatch) + 1);
362 try
363 {
364 uint8_t channel = getChannelByName(chName);
365 uniqueNameToChannelNumber[nameOwner] = channel;
366 log<level::INFO>("New interface mapping",
367 entry("INTERFACE=%s", name.c_str()),
368 entry("CHANNEL=%u", channel));
369 }
370 catch (const std::exception& e)
371 {
372 log<level::INFO>("Failed interface mapping, no such name",
373 entry("INTERFACE=%s", name.c_str()));
374 }
375 },
376 "org.freedesktop.DBus", "/", "org.freedesktop.DBus", "GetNameOwner",
377 name);
378}
379
Ed Tanous778418d2020-08-17 23:20:21 -0700380void doListNames(boost::asio::io_context& io, sdbusplus::asio::connection& conn)
Vernon Mauery735ee952019-02-15 13:38:52 -0800381{
382 conn.async_method_call(
383 [&io, &conn](const boost::system::error_code ec,
384 std::vector<std::string> busNames) {
385 if (ec)
386 {
387 log<level::ERR>("Error getting dbus names");
388 std::exit(EXIT_FAILURE);
389 return;
390 }
391 // Try to make startup consistent
392 std::sort(busNames.begin(), busNames.end());
393
394 const std::string channelPrefix =
395 std::string(ipmiDbusChannelMatch) + ".";
396 for (const std::string& busName : busNames)
397 {
398 if (busName.find(channelPrefix) == 0)
399 {
400 updateOwners(conn, busName);
401 }
402 }
403 },
404 "org.freedesktop.DBus", "/org/freedesktop/DBus", "org.freedesktop.DBus",
405 "ListNames");
406}
407
408void nameChangeHandler(sdbusplus::message::message& message)
409{
410 std::string name;
411 std::string oldOwner;
412 std::string newOwner;
413
414 message.read(name, oldOwner, newOwner);
415
416 if (!oldOwner.empty())
417 {
418 if (boost::starts_with(oldOwner, ":"))
419 {
420 // Connection removed
421 auto it = uniqueNameToChannelNumber.find(oldOwner);
422 if (it != uniqueNameToChannelNumber.end())
423 {
424 uniqueNameToChannelNumber.erase(it);
425 }
426 }
427 }
428 if (!newOwner.empty())
429 {
430 // start after ipmiDbusChannelMatch (and after the '.')
431 std::string chName = name.substr(std::strlen(ipmiDbusChannelMatch) + 1);
432 try
433 {
434 uint8_t channel = getChannelByName(chName);
435 uniqueNameToChannelNumber[newOwner] = channel;
436 log<level::INFO>("New interface mapping",
437 entry("INTERFACE=%s", name.c_str()),
438 entry("CHANNEL=%u", channel));
439 }
440 catch (const std::exception& e)
441 {
442 log<level::INFO>("Failed interface mapping, no such name",
443 entry("INTERFACE=%s", name.c_str()));
444 }
445 }
446};
447
448} // anonymous namespace
449
450static constexpr const char intraBmcName[] = "INTRABMC";
451uint8_t channelFromMessage(sdbusplus::message::message& msg)
452{
453 // channel name for ipmitool to resolve to
454 std::string sender = msg.get_sender();
455 auto chIter = uniqueNameToChannelNumber.find(sender);
456 if (chIter != uniqueNameToChannelNumber.end())
457 {
458 return chIter->second;
459 }
460 // FIXME: currently internal connections are ephemeral and hard to pin down
461 try
462 {
463 return getChannelByName(intraBmcName);
464 }
465 catch (const std::exception& e)
466 {
467 return invalidChannel;
468 }
469} // namespace ipmi
470
Vernon Mauery240b1862018-10-08 12:05:16 -0700471/* called from sdbus async server context */
Vernon Mauery735ee952019-02-15 13:38:52 -0800472auto executionEntry(boost::asio::yield_context yield,
473 sdbusplus::message::message& m, NetFn netFn, uint8_t lun,
Vernon Mauery240b1862018-10-08 12:05:16 -0700474 Cmd cmd, std::vector<uint8_t>& data,
475 std::map<std::string, ipmi::Value>& options)
476{
Vernon Mauery735ee952019-02-15 13:38:52 -0800477 const auto dbusResponse =
478 [netFn, lun, cmd](Cc cc, const std::vector<uint8_t>& data = {}) {
479 constexpr uint8_t netFnResponse = 0x01;
480 uint8_t retNetFn = netFn | netFnResponse;
481 return std::make_tuple(retNetFn, lun, cmd, cc, data);
482 };
483 std::string sender = m.get_sender();
484 Privilege privilege = Privilege::None;
Vernon Maueryd6a2da02019-04-09 16:00:46 -0700485 int rqSA = 0;
Vernon Mauery735ee952019-02-15 13:38:52 -0800486 uint8_t userId = 0; // undefined user
Rajashekar Gade Reddy4d226402019-11-13 17:13:05 +0530487 uint32_t sessionId = 0;
Vernon Mauery735ee952019-02-15 13:38:52 -0800488
489 // figure out what channel the request came in on
490 uint8_t channel = channelFromMessage(m);
491 if (channel == invalidChannel)
492 {
493 // unknown sender channel; refuse to service the request
494 log<level::ERR>("ERROR determining source IPMI channel",
495 entry("SENDER=%s", sender.c_str()),
496 entry("NETFN=0x%X", netFn), entry("CMD=0x%X", cmd));
497 return dbusResponse(ipmi::ccDestinationUnavailable);
498 }
499
Rajashekar Gade Reddy4d226402019-11-13 17:13:05 +0530500 // session-based channels are required to provide userId, privilege and
501 // sessionId
Vernon Mauery735ee952019-02-15 13:38:52 -0800502 if (getChannelSessionSupport(channel) != EChannelSessSupported::none)
503 {
504 try
505 {
506 Value requestPriv = options.at("privilege");
507 Value requestUserId = options.at("userId");
Rajashekar Gade Reddy4d226402019-11-13 17:13:05 +0530508 Value requestSessionId = options.at("currentSessionId");
Vernon Mauery735ee952019-02-15 13:38:52 -0800509 privilege = static_cast<Privilege>(std::get<int>(requestPriv));
510 userId = static_cast<uint8_t>(std::get<int>(requestUserId));
Rajashekar Gade Reddy4d226402019-11-13 17:13:05 +0530511 sessionId =
512 static_cast<uint32_t>(std::get<uint32_t>(requestSessionId));
Vernon Mauery735ee952019-02-15 13:38:52 -0800513 }
514 catch (const std::exception& e)
515 {
516 log<level::ERR>("ERROR determining IPMI session credentials",
517 entry("CHANNEL=%u", channel),
518 entry("NETFN=0x%X", netFn), entry("CMD=0x%X", cmd));
519 return dbusResponse(ipmi::ccUnspecifiedError);
520 }
521 }
522 else
523 {
524 // get max privilege for session-less channels
525 // For now, there is not a way to configure this, default to Admin
526 privilege = Privilege::Admin;
Vernon Maueryd6a2da02019-04-09 16:00:46 -0700527
528 // ipmb should supply rqSA
529 ChannelInfo chInfo;
530 getChannelInfo(channel, chInfo);
531 if (static_cast<EChannelMediumType>(chInfo.mediumType) ==
532 EChannelMediumType::ipmb)
533 {
534 const auto iter = options.find("rqSA");
535 if (iter != options.end())
536 {
537 if (std::holds_alternative<int>(iter->second))
538 {
539 rqSA = std::get<int>(iter->second);
540 }
541 }
542 }
Vernon Mauery735ee952019-02-15 13:38:52 -0800543 }
544 // check to see if the requested priv/username is valid
545 log<level::DEBUG>("Set up ipmi context", entry("SENDER=%s", sender.c_str()),
Johnathan Manteyc11cc5c2020-07-22 13:52:33 -0700546 entry("NETFN=0x%X", netFn), entry("LUN=0x%X", lun),
547 entry("CMD=0x%X", cmd), entry("CHANNEL=%u", channel),
548 entry("USERID=%u", userId),
Rajashekar Gade Reddy4d226402019-11-13 17:13:05 +0530549 entry("SESSIONID=0x%X", sessionId),
Vernon Maueryd6a2da02019-04-09 16:00:46 -0700550 entry("PRIVILEGE=%u", static_cast<uint8_t>(privilege)),
551 entry("RQSA=%x", rqSA));
Vernon Mauery735ee952019-02-15 13:38:52 -0800552
Johnathan Manteyc11cc5c2020-07-22 13:52:33 -0700553 auto ctx = std::make_shared<ipmi::Context>(getSdBus(), netFn, lun, cmd,
554 channel, userId, sessionId,
555 privilege, rqSA, yield);
Vernon Mauery240b1862018-10-08 12:05:16 -0700556 auto request = std::make_shared<ipmi::message::Request>(
557 ctx, std::forward<std::vector<uint8_t>>(data));
558 message::Response::ptr response = executeIpmiCommand(request);
559
Vernon Mauery735ee952019-02-15 13:38:52 -0800560 return dbusResponse(response->cc, response->payload.raw);
Vernon Mauery240b1862018-10-08 12:05:16 -0700561}
562
563/** @struct IpmiProvider
564 *
565 * RAII wrapper for dlopen so that dlclose gets called on exit
566 */
567struct IpmiProvider
568{
569 public:
570 /** @brief address of the opened library */
571 void* addr;
572 std::string name;
573
574 IpmiProvider() = delete;
575 IpmiProvider(const IpmiProvider&) = delete;
576 IpmiProvider& operator=(const IpmiProvider&) = delete;
577 IpmiProvider(IpmiProvider&&) = delete;
578 IpmiProvider& operator=(IpmiProvider&&) = delete;
579
580 /** @brief dlopen a shared object file by path
581 * @param[in] filename - path of shared object to open
582 */
583 explicit IpmiProvider(const char* fname) : addr(nullptr), name(fname)
584 {
585 log<level::DEBUG>("Open IPMI provider library",
586 entry("PROVIDER=%s", name.c_str()));
587 try
588 {
589 addr = dlopen(name.c_str(), RTLD_NOW);
590 }
591 catch (std::exception& e)
592 {
593 log<level::ERR>("ERROR opening IPMI provider",
594 entry("PROVIDER=%s", name.c_str()),
595 entry("ERROR=%s", e.what()));
596 }
597 catch (...)
598 {
599 std::exception_ptr eptr = std::current_exception();
600 try
601 {
602 std::rethrow_exception(eptr);
603 }
604 catch (std::exception& e)
605 {
606 log<level::ERR>("ERROR opening IPMI provider",
607 entry("PROVIDER=%s", name.c_str()),
608 entry("ERROR=%s", e.what()));
609 }
610 }
611 if (!isOpen())
612 {
613 log<level::ERR>("ERROR opening IPMI provider",
614 entry("PROVIDER=%s", name.c_str()),
615 entry("ERROR=%s", dlerror()));
616 }
617 }
618
619 ~IpmiProvider()
620 {
621 if (isOpen())
622 {
623 dlclose(addr);
624 }
625 }
626 bool isOpen() const
627 {
628 return (nullptr != addr);
629 }
630};
631
632// Plugin libraries need to contain .so either at the end or in the middle
633constexpr const char ipmiPluginExtn[] = ".so";
634
635/* return a list of self-closing library handles */
636std::forward_list<IpmiProvider> loadProviders(const fs::path& ipmiLibsPath)
637{
638 std::vector<fs::path> libs;
639 for (const auto& libPath : fs::directory_iterator(ipmiLibsPath))
640 {
Vernon Maueryb0ab5fe2019-03-06 14:03:00 -0800641 std::error_code ec;
Vernon Mauery240b1862018-10-08 12:05:16 -0700642 fs::path fname = libPath.path();
Vernon Maueryb0ab5fe2019-03-06 14:03:00 -0800643 if (fs::is_symlink(fname, ec) || ec)
644 {
645 // it's a symlink or some other error; skip it
646 continue;
647 }
Vernon Mauery240b1862018-10-08 12:05:16 -0700648 while (fname.has_extension())
649 {
650 fs::path extn = fname.extension();
651 if (extn == ipmiPluginExtn)
652 {
653 libs.push_back(libPath.path());
654 break;
655 }
656 fname.replace_extension();
657 }
658 }
659 std::sort(libs.begin(), libs.end());
660
661 std::forward_list<IpmiProvider> handles;
662 for (auto& lib : libs)
663 {
664#ifdef __IPMI_DEBUG__
665 log<level::DEBUG>("Registering handler",
666 entry("HANDLER=%s", lib.c_str()));
667#endif
668 handles.emplace_front(lib.c_str());
669 }
670 return handles;
671}
672
673} // namespace ipmi
674
Vernon Mauery240b1862018-10-08 12:05:16 -0700675#ifdef ALLOW_DEPRECATED_API
676/* legacy registration */
677void ipmi_register_callback(ipmi_netfn_t netFn, ipmi_cmd_t cmd,
678 ipmi_context_t context, ipmid_callback_t handler,
679 ipmi_cmd_privilege_t priv)
680{
Vernon Mauerybe376302019-03-21 13:02:05 -0700681 auto h = ipmi::makeLegacyHandler(handler, context);
Vernon Mauery240b1862018-10-08 12:05:16 -0700682 // translate priv from deprecated enum to current
683 ipmi::Privilege realPriv;
684 switch (priv)
685 {
686 case PRIVILEGE_CALLBACK:
687 realPriv = ipmi::Privilege::Callback;
688 break;
689 case PRIVILEGE_USER:
690 realPriv = ipmi::Privilege::User;
691 break;
692 case PRIVILEGE_OPERATOR:
693 realPriv = ipmi::Privilege::Operator;
694 break;
695 case PRIVILEGE_ADMIN:
696 realPriv = ipmi::Privilege::Admin;
697 break;
698 case PRIVILEGE_OEM:
699 realPriv = ipmi::Privilege::Oem;
700 break;
701 case SYSTEM_INTERFACE:
702 realPriv = ipmi::Privilege::Admin;
703 break;
704 default:
705 realPriv = ipmi::Privilege::Admin;
706 break;
707 }
Vernon Mauerye8d43232019-03-26 16:23:43 -0700708 // The original ipmi_register_callback allowed for group OEM handlers
709 // to be registered via this same interface. It just so happened that
710 // all the handlers were part of the DCMI group, so default to that.
711 if (netFn == NETFUN_GRPEXT)
712 {
713 ipmi::impl::registerGroupHandler(ipmi::prioOpenBmcBase,
714 dcmi::groupExtId, cmd, realPriv, h);
715 }
716 else
717 {
718 ipmi::impl::registerHandler(ipmi::prioOpenBmcBase, netFn, cmd, realPriv,
719 h);
720 }
Vernon Mauery240b1862018-10-08 12:05:16 -0700721}
722
Vernon Maueryf984a012018-10-08 12:05:18 -0700723namespace oem
724{
725
726class LegacyRouter : public oem::Router
727{
728 public:
729 virtual ~LegacyRouter()
730 {
731 }
732
733 /// Enable message routing to begin.
734 void activate() override
735 {
736 }
737
738 void registerHandler(Number oen, ipmi_cmd_t cmd, Handler handler) override
739 {
740 auto h = ipmi::makeLegacyHandler(std::forward<Handler>(handler));
741 ipmi::impl::registerOemHandler(ipmi::prioOpenBmcBase, oen, cmd,
742 ipmi::Privilege::Admin, h);
743 }
744};
745static LegacyRouter legacyRouter;
746
747Router* mutableRouter()
748{
749 return &legacyRouter;
750}
751
752} // namespace oem
753
Vernon Mauery240b1862018-10-08 12:05:16 -0700754/* legacy alternative to executionEntry */
755void handleLegacyIpmiCommand(sdbusplus::message::message& m)
756{
Vernon Mauery23b70212019-05-08 15:19:05 -0700757 // make a copy so the next two moves don't wreak havoc on the stack
758 sdbusplus::message::message b{m};
759 boost::asio::spawn(*getIoContext(), [b = std::move(b)](
760 boost::asio::yield_context yield) {
761 sdbusplus::message::message m{std::move(b)};
762 unsigned char seq, netFn, lun, cmd;
763 std::vector<uint8_t> data;
Vernon Mauery240b1862018-10-08 12:05:16 -0700764
Vernon Mauery23b70212019-05-08 15:19:05 -0700765 m.read(seq, netFn, lun, cmd, data);
Vernon Mauery33298af2019-05-13 15:32:37 -0700766 std::shared_ptr<sdbusplus::asio::connection> bus = getSdBus();
Vernon Mauery23b70212019-05-08 15:19:05 -0700767 auto ctx = std::make_shared<ipmi::Context>(
Johnathan Manteyc11cc5c2020-07-22 13:52:33 -0700768 bus, netFn, lun, cmd, 0, 0, 0, ipmi::Privilege::Admin, 0, yield);
Vernon Mauery23b70212019-05-08 15:19:05 -0700769 auto request = std::make_shared<ipmi::message::Request>(
770 ctx, std::forward<std::vector<uint8_t>>(data));
771 ipmi::message::Response::ptr response =
772 ipmi::executeIpmiCommand(request);
Vernon Mauery240b1862018-10-08 12:05:16 -0700773
Vernon Mauery23b70212019-05-08 15:19:05 -0700774 // Responses in IPMI require a bit set. So there ya go...
775 netFn |= 0x01;
Vernon Mauery240b1862018-10-08 12:05:16 -0700776
Vernon Mauery23b70212019-05-08 15:19:05 -0700777 const char *dest, *path;
778 constexpr const char* DBUS_INTF = "org.openbmc.HostIpmi";
Vernon Mauery240b1862018-10-08 12:05:16 -0700779
Vernon Mauery23b70212019-05-08 15:19:05 -0700780 dest = m.get_sender();
781 path = m.get_path();
782 boost::system::error_code ec;
Vernon Mauery33298af2019-05-13 15:32:37 -0700783 bus->yield_method_call(yield, ec, dest, path, DBUS_INTF, "sendMessage",
784 seq, netFn, lun, cmd, response->cc,
785 response->payload.raw);
Vernon Mauery23b70212019-05-08 15:19:05 -0700786 if (ec)
787 {
788 log<level::ERR>("Failed to send response to requestor",
789 entry("ERROR=%s", ec.message().c_str()),
790 entry("SENDER=%s", dest),
791 entry("NETFN=0x%X", netFn), entry("CMD=0x%X", cmd));
792 }
793 });
Vernon Mauery240b1862018-10-08 12:05:16 -0700794}
795
796#endif /* ALLOW_DEPRECATED_API */
797
798// Calls host command manager to do the right thing for the command
799using CommandHandler = phosphor::host::command::CommandHandler;
800std::unique_ptr<phosphor::host::command::Manager> cmdManager;
801void ipmid_send_cmd_to_host(CommandHandler&& cmd)
802{
Vernon Mauery1b7f6f22019-03-13 13:11:25 -0700803 return cmdManager->execute(std::forward<CommandHandler>(cmd));
Vernon Mauery240b1862018-10-08 12:05:16 -0700804}
805
806std::unique_ptr<phosphor::host::command::Manager>& ipmid_get_host_cmd_manager()
807{
808 return cmdManager;
809}
810
Vernon Mauery20ff3332019-03-01 16:52:25 -0800811// These are symbols that are present in libipmid, but not expected
812// to be used except here (or maybe a unit test), so declare them here
813extern void setIoContext(std::shared_ptr<boost::asio::io_context>& newIo);
814extern void setSdBus(std::shared_ptr<sdbusplus::asio::connection>& newBus);
815
Vernon Mauery240b1862018-10-08 12:05:16 -0700816int main(int argc, char* argv[])
817{
818 // Connect to system bus
Vernon Mauery20ff3332019-03-01 16:52:25 -0800819 auto io = std::make_shared<boost::asio::io_context>();
820 setIoContext(io);
Vernon Mauery240b1862018-10-08 12:05:16 -0700821 if (argc > 1 && std::string(argv[1]) == "-session")
822 {
823 sd_bus_default_user(&bus);
824 }
825 else
826 {
827 sd_bus_default_system(&bus);
828 }
Vernon Mauery20ff3332019-03-01 16:52:25 -0800829 auto sdbusp = std::make_shared<sdbusplus::asio::connection>(*io, bus);
830 setSdBus(sdbusp);
Vernon Mauery240b1862018-10-08 12:05:16 -0700831
832 // TODO: Hack to keep the sdEvents running.... Not sure why the sd_event
833 // queue stops running if we don't have a timer that keeps re-arming
834 phosphor::Timer t2([]() { ; });
835 t2.start(std::chrono::microseconds(500000), true);
836
837 // TODO: Remove all vestiges of sd_event from phosphor-host-ipmid
838 // until that is done, add the sd_event wrapper to the io object
839 sdbusplus::asio::sd_event_wrapper sdEvents(*io);
840
841 cmdManager = std::make_unique<phosphor::host::command::Manager>(*sdbusp);
842
843 // Register all command providers and filters
Vernon Mauery4ec4e402019-03-20 13:09:27 -0700844 std::forward_list<ipmi::IpmiProvider> providers =
845 ipmi::loadProviders(HOST_IPMI_LIB_PATH);
Vernon Mauery240b1862018-10-08 12:05:16 -0700846
Vernon Mauery240b1862018-10-08 12:05:16 -0700847#ifdef ALLOW_DEPRECATED_API
848 // listen on deprecated signal interface for kcs/bt commands
849 constexpr const char* FILTER = "type='signal',interface='org.openbmc."
850 "HostIpmi',member='ReceivedMessage'";
851 sdbusplus::bus::match::match oldIpmiInterface(*sdbusp, FILTER,
852 handleLegacyIpmiCommand);
853#endif /* ALLOW_DEPRECATED_API */
854
Vernon Mauery735ee952019-02-15 13:38:52 -0800855 // set up bus name watching to match channels with bus names
856 sdbusplus::bus::match::match nameOwnerChanged(
857 *sdbusp,
858 sdbusplus::bus::match::rules::nameOwnerChanged() +
859 sdbusplus::bus::match::rules::arg0namespace(
860 ipmi::ipmiDbusChannelMatch),
861 ipmi::nameChangeHandler);
862 ipmi::doListNames(*io, *sdbusp);
863
James Feistb0094a72019-11-26 09:07:15 -0800864 int exitCode = 0;
Vernon Mauery1b7f6f22019-03-13 13:11:25 -0700865 // set up boost::asio signal handling
866 std::function<SignalResponse(int)> stopAsioRunLoop =
James Feistb0094a72019-11-26 09:07:15 -0800867 [&io, &exitCode](int signalNumber) {
Vernon Mauery1b7f6f22019-03-13 13:11:25 -0700868 log<level::INFO>("Received signal; quitting",
869 entry("SIGNAL=%d", signalNumber));
870 io->stop();
James Feistb0094a72019-11-26 09:07:15 -0800871 exitCode = signalNumber;
Vernon Mauery1b7f6f22019-03-13 13:11:25 -0700872 return SignalResponse::breakExecution;
873 };
874 registerSignalHandler(ipmi::prioOpenBmcBase, SIGINT, stopAsioRunLoop);
875 registerSignalHandler(ipmi::prioOpenBmcBase, SIGTERM, stopAsioRunLoop);
876
Richard Marian Thomaiyar369406e2020-01-09 14:56:54 +0530877 sdbusp->request_name("xyz.openbmc_project.Ipmi.Host");
878 // Add bindings for inbound IPMI requests
879 auto server = sdbusplus::asio::object_server(sdbusp);
880 auto iface = server.add_interface("/xyz/openbmc_project/Ipmi",
881 "xyz.openbmc_project.Ipmi.Server");
882 iface->register_method("execute", ipmi::executionEntry);
883 iface->initialize();
884
Vernon Mauery240b1862018-10-08 12:05:16 -0700885 io->run();
886
Vernon Mauery1b7f6f22019-03-13 13:11:25 -0700887 // destroy all the IPMI handlers so the providers can unload safely
888 ipmi::handlerMap.clear();
889 ipmi::groupHandlerMap.clear();
890 ipmi::oemHandlerMap.clear();
891 ipmi::filterList.clear();
892 // unload the provider libraries
Vernon Mauery4ec4e402019-03-20 13:09:27 -0700893 providers.clear();
Vernon Mauery1b7f6f22019-03-13 13:11:25 -0700894
James Feistb0094a72019-11-26 09:07:15 -0800895 std::exit(exitCode);
Vernon Mauery240b1862018-10-08 12:05:16 -0700896}