xref: /openbmc/phosphor-host-ipmid/ipmid-new.cpp (revision de1420dcc29bbe9d70968428e96ba34bfededad3)
1 /**
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 <boost/algorithm/string.hpp>
23 #include <boost/asio/detached.hpp>
24 #include <boost/asio/io_context.hpp>
25 #include <boost/asio/spawn.hpp>
26 #include <host-cmd-manager.hpp>
27 #include <ipmid-host/cmd.hpp>
28 #include <ipmid/api.hpp>
29 #include <ipmid/handler.hpp>
30 #include <ipmid/message.hpp>
31 #include <ipmid/oemrouter.hpp>
32 #include <ipmid/types.hpp>
33 #include <ipmid/utils.hpp>
34 #include <phosphor-logging/lg2.hpp>
35 #include <sdbusplus/asio/connection.hpp>
36 #include <sdbusplus/asio/object_server.hpp>
37 #include <sdbusplus/asio/sd_event.hpp>
38 #include <sdbusplus/bus.hpp>
39 #include <sdbusplus/bus/match.hpp>
40 #include <sdbusplus/timer.hpp>
41 
42 #include <algorithm>
43 #include <any>
44 #include <exception>
45 #include <filesystem>
46 #include <forward_list>
47 #include <map>
48 #include <memory>
49 #include <optional>
50 #include <tuple>
51 #include <unordered_map>
52 #include <utility>
53 #include <vector>
54 
55 namespace fs = std::filesystem;
56 
57 using namespace phosphor::logging;
58 
59 // IPMI Spec, shared Reservation ID.
60 static unsigned short selReservationID = 0xFFFF;
61 static bool selReservationValid = false;
62 
reserveSel(void)63 unsigned short reserveSel(void)
64 {
65     // IPMI spec, Reservation ID, the value simply increases against each
66     // execution of the Reserve SEL command.
67     if (++selReservationID == 0)
68     {
69         selReservationID = 1;
70     }
71     selReservationValid = true;
72     return selReservationID;
73 }
74 
checkSELReservation(unsigned short id)75 bool checkSELReservation(unsigned short id)
76 {
77     return (selReservationValid && selReservationID == id);
78 }
79 
cancelSELReservation(void)80 void cancelSELReservation(void)
81 {
82     selReservationValid = false;
83 }
84 
getInterfaceIndex(void)85 EInterfaceIndex getInterfaceIndex(void)
86 {
87     return interfaceKCS;
88 }
89 
90 sd_bus* bus;
91 sd_event* events = nullptr;
ipmid_get_sd_event_connection(void)92 sd_event* ipmid_get_sd_event_connection(void)
93 {
94     return events;
95 }
ipmid_get_sd_bus_connection(void)96 sd_bus* ipmid_get_sd_bus_connection(void)
97 {
98     return bus;
99 }
100 
101 namespace ipmi
102 {
103 
makeCmdKey(unsigned int cluster,unsigned int cmd)104 static inline unsigned int makeCmdKey(unsigned int cluster, unsigned int cmd)
105 {
106     return (cluster << 8) | cmd;
107 }
108 
109 using HandlerTuple = std::tuple<int,                        /* prio */
110                                 Privilege, HandlerBase::ptr /* handler */
111                                 >;
112 
113 /* map to handle standard registered commands */
114 static std::unordered_map<unsigned int, /* key is NetFn/Cmd */
115                           HandlerTuple>
116     handlerMap;
117 
118 /* special map for decoding Group registered commands (NetFn 2Ch) */
119 static std::unordered_map<unsigned int, /* key is Group/Cmd (NetFn is 2Ch) */
120                           HandlerTuple>
121     groupHandlerMap;
122 
123 /* special map for decoding OEM registered commands (NetFn 2Eh) */
124 static std::unordered_map<unsigned int, /* key is Iana/Cmd (NetFn is 2Eh) */
125                           HandlerTuple>
126     oemHandlerMap;
127 
128 using FilterTuple = std::tuple<int,            /* prio */
129                                FilterBase::ptr /* filter */
130                                >;
131 
132 /* list to hold all registered ipmi command filters */
133 static std::forward_list<FilterTuple> filterList;
134 
135 namespace impl
136 {
137 /* common function to register all standard IPMI handlers */
registerHandler(int prio,NetFn netFn,Cmd cmd,Privilege priv,HandlerBase::ptr handler)138 bool registerHandler(int prio, NetFn netFn, Cmd cmd, Privilege priv,
139                      HandlerBase::ptr handler)
140 {
141     // check for valid NetFn: even; 00-0Ch, 30-3Eh
142     if (netFn & 1 || (netFn > netFnTransport && netFn < netFnGroup) ||
143         netFn > netFnOemEight)
144     {
145         return false;
146     }
147 
148     // create key and value for this handler
149     unsigned int netFnCmd = makeCmdKey(netFn, cmd);
150     HandlerTuple item(prio, priv, handler);
151 
152     // consult the handler map and look for a match
153     auto& mapCmd = handlerMap[netFnCmd];
154     if (!std::get<HandlerBase::ptr>(mapCmd) || std::get<int>(mapCmd) <= prio)
155     {
156         mapCmd = item;
157         return true;
158     }
159     return false;
160 }
161 
162 /* common function to register all Group IPMI handlers */
registerGroupHandler(int prio,Group group,Cmd cmd,Privilege priv,HandlerBase::ptr handler)163 bool registerGroupHandler(int prio, Group group, Cmd cmd, Privilege priv,
164                           HandlerBase::ptr handler)
165 {
166     // create key and value for this handler
167     unsigned int netFnCmd = makeCmdKey(group, cmd);
168     HandlerTuple item(prio, priv, handler);
169 
170     // consult the handler map and look for a match
171     auto& mapCmd = groupHandlerMap[netFnCmd];
172     if (!std::get<HandlerBase::ptr>(mapCmd) || std::get<int>(mapCmd) <= prio)
173     {
174         mapCmd = item;
175         return true;
176     }
177     return false;
178 }
179 
180 /* common function to register all OEM IPMI handlers */
registerOemHandler(int prio,Iana iana,Cmd cmd,Privilege priv,HandlerBase::ptr handler)181 bool registerOemHandler(int prio, Iana iana, Cmd cmd, Privilege priv,
182                         HandlerBase::ptr handler)
183 {
184     // create key and value for this handler
185     unsigned int netFnCmd = makeCmdKey(iana, cmd);
186     HandlerTuple item(prio, priv, handler);
187 
188     // consult the handler map and look for a match
189     auto& mapCmd = oemHandlerMap[netFnCmd];
190     if (!std::get<HandlerBase::ptr>(mapCmd) || std::get<int>(mapCmd) <= prio)
191     {
192         mapCmd = item;
193         lg2::debug("registered OEM Handler: NetFn/Cmd={NETFNCMD}", "IANA",
194                    lg2::hex, iana, "CMD", lg2::hex, cmd, "NETFNCMD", lg2::hex,
195                    netFnCmd);
196         return true;
197     }
198 
199     lg2::warning("could not register OEM Handler: NetFn/Cmd={NETFNCMD}", "IANA",
200                  lg2::hex, iana, "CMD", lg2::hex, cmd, "NETFNCMD", lg2::hex,
201                  netFnCmd);
202     return false;
203 }
204 
205 /* common function to register all IPMI filter handlers */
registerFilter(int prio,FilterBase::ptr filter)206 void registerFilter(int prio, FilterBase::ptr filter)
207 {
208     // check for initial placement
209     if (filterList.empty() || std::get<int>(filterList.front()) < prio)
210     {
211         filterList.emplace_front(std::make_tuple(prio, filter));
212         return;
213     }
214     // walk the list and put it in the right place
215     auto j = filterList.begin();
216     for (auto i = j; i != filterList.end() && std::get<int>(*i) > prio; i++)
217     {
218         j = i;
219     }
220     filterList.emplace_after(j, std::make_tuple(prio, filter));
221 }
222 
223 } // namespace impl
224 
filterIpmiCommand(message::Request::ptr request)225 message::Response::ptr filterIpmiCommand(message::Request::ptr request)
226 {
227     // pass the command through the filter mechanism
228     // This can be the firmware firewall or any OEM mechanism like
229     // whitelist filtering based on operational mode
230     for (auto& item : filterList)
231     {
232         FilterBase::ptr filter = std::get<FilterBase::ptr>(item);
233         ipmi::Cc cc = filter->call(request);
234         if (ipmi::ccSuccess != cc)
235         {
236             return errorResponse(request, cc);
237         }
238     }
239     return message::Response::ptr();
240 }
241 
executeIpmiCommandCommon(std::unordered_map<unsigned int,HandlerTuple> & handlers,unsigned int keyCommon,message::Request::ptr request)242 message::Response::ptr executeIpmiCommandCommon(
243     std::unordered_map<unsigned int, HandlerTuple>& handlers,
244     unsigned int keyCommon, message::Request::ptr request)
245 {
246     // filter the command first; a non-null message::Response::ptr
247     // means that the message has been rejected for some reason
248     message::Response::ptr filterResponse = filterIpmiCommand(request);
249 
250     Cmd cmd = request->ctx->cmd;
251     unsigned int key = makeCmdKey(keyCommon, cmd);
252     auto cmdIter = handlers.find(key);
253     if (cmdIter != handlers.end())
254     {
255         // only return the filter response if the command is found
256         if (filterResponse)
257         {
258             lg2::debug("request for NetFn/Cmd {NETFN}/{CMD} has been filtered",
259                        "NETFN", lg2::hex, keyCommon, "CMD", lg2::hex, cmd);
260             return filterResponse;
261         }
262         HandlerTuple& chosen = cmdIter->second;
263         if (request->ctx->priv < std::get<Privilege>(chosen))
264         {
265             return errorResponse(request, ccInsufficientPrivilege);
266         }
267         return std::get<HandlerBase::ptr>(chosen)->call(request);
268     }
269     else
270     {
271         unsigned int wildcard = makeCmdKey(keyCommon, cmdWildcard);
272         cmdIter = handlers.find(wildcard);
273         if (cmdIter != handlers.end())
274         {
275             // only return the filter response if the command is found
276             if (filterResponse)
277             {
278                 lg2::debug(
279                     "request for NetFn/Cmd {NETFN}/{CMD} has been filtered",
280                     "NETFN", lg2::hex, keyCommon, "CMD", lg2::hex, cmd);
281                 return filterResponse;
282             }
283             HandlerTuple& chosen = cmdIter->second;
284             if (request->ctx->priv < std::get<Privilege>(chosen))
285             {
286                 return errorResponse(request, ccInsufficientPrivilege);
287             }
288             return std::get<HandlerBase::ptr>(chosen)->call(request);
289         }
290     }
291     return errorResponse(request, ccInvalidCommand);
292 }
293 
executeIpmiGroupCommand(message::Request::ptr request)294 message::Response::ptr executeIpmiGroupCommand(message::Request::ptr request)
295 {
296     // look up the group for this request
297     uint8_t bytes;
298     if (0 != request->payload.unpack(bytes))
299     {
300         return errorResponse(request, ccReqDataLenInvalid);
301     }
302     auto group = static_cast<Group>(bytes);
303     message::Response::ptr response =
304         executeIpmiCommandCommon(groupHandlerMap, group, request);
305     ipmi::message::Payload prefix;
306     prefix.pack(bytes);
307     response->prepend(prefix);
308     return response;
309 }
310 
executeIpmiOemCommand(message::Request::ptr request)311 message::Response::ptr executeIpmiOemCommand(message::Request::ptr request)
312 {
313     // look up the iana for this request
314     uint24_t bytes;
315     if (0 != request->payload.unpack(bytes))
316     {
317         return errorResponse(request, ccReqDataLenInvalid);
318     }
319     auto iana = static_cast<Iana>(bytes);
320 
321     lg2::debug("unpack IANA {IANA}", "IANA", lg2::hex, iana);
322 
323     message::Response::ptr response =
324         executeIpmiCommandCommon(oemHandlerMap, iana, request);
325     ipmi::message::Payload prefix;
326     prefix.pack(bytes);
327     response->prepend(prefix);
328     return response;
329 }
330 
executeIpmiCommand(message::Request::ptr request)331 message::Response::ptr executeIpmiCommand(message::Request::ptr request)
332 {
333     NetFn netFn = request->ctx->netFn;
334     if (netFnGroup == netFn)
335     {
336         return executeIpmiGroupCommand(request);
337     }
338     else if (netFnOem == netFn)
339     {
340         return executeIpmiOemCommand(request);
341     }
342     return executeIpmiCommandCommon(handlerMap, netFn, request);
343 }
344 
345 namespace utils
346 {
347 template <typename AssocContainer, typename UnaryPredicate>
assoc_erase_if(AssocContainer & c,UnaryPredicate p)348 void assoc_erase_if(AssocContainer& c, UnaryPredicate p)
349 {
350     typename AssocContainer::iterator next = c.begin();
351     typename AssocContainer::iterator last = c.end();
352     while ((next = std::find_if(next, last, p)) != last)
353     {
354         c.erase(next++);
355     }
356 }
357 } // namespace utils
358 
359 namespace
360 {
361 std::unordered_map<std::string, uint8_t> uniqueNameToChannelNumber;
362 
363 // sdbusplus::bus::match::rules::arg0namespace() wants the prefix
364 // to match without any trailing '.'
365 constexpr const char ipmiDbusChannelMatch[] =
366     "xyz.openbmc_project.Ipmi.Channel";
updateOwners(sdbusplus::asio::connection & conn,const std::string & name)367 void updateOwners(sdbusplus::asio::connection& conn, const std::string& name)
368 {
369     conn.async_method_call(
370         [name](const boost::system::error_code ec,
371                const std::string& nameOwner) {
372             if (ec)
373             {
374                 lg2::error("Error getting dbus owner for {INTERFACE}",
375                            "INTERFACE", name);
376                 return;
377             }
378             // start after ipmiDbusChannelPrefix (after the '.')
379             std::string chName =
380                 name.substr(std::strlen(ipmiDbusChannelMatch) + 1);
381             try
382             {
383                 uint8_t channel = getChannelByName(chName);
384                 uniqueNameToChannelNumber[nameOwner] = channel;
385                 lg2::info(
386                     "New interface mapping: {INTERFACE} -> channel {CHANNEL}",
387                     "INTERFACE", name, "CHANNEL", channel);
388             }
389             catch (const std::exception& e)
390             {
391                 lg2::info("Failed interface mapping, no such name: {INTERFACE}",
392                           "INTERFACE", name);
393             }
394         },
395         "org.freedesktop.DBus", "/", "org.freedesktop.DBus", "GetNameOwner",
396         name);
397 }
398 
doListNames(sdbusplus::asio::connection & conn)399 void doListNames(sdbusplus::asio::connection& conn)
400 {
401     conn.async_method_call(
402         [&conn](const boost::system::error_code ec,
403                 std::vector<std::string> busNames) {
404             if (ec)
405             {
406                 lg2::error("Error getting dbus names: {ERROR}", "ERROR",
407                            ec.message());
408                 std::exit(EXIT_FAILURE);
409                 return;
410             }
411             // Try to make startup consistent
412             std::sort(busNames.begin(), busNames.end());
413 
414             const std::string channelPrefix =
415                 std::string(ipmiDbusChannelMatch) + ".";
416             for (const std::string& busName : busNames)
417             {
418                 if (busName.find(channelPrefix) == 0)
419                 {
420                     updateOwners(conn, busName);
421                 }
422             }
423         },
424         "org.freedesktop.DBus", "/org/freedesktop/DBus", "org.freedesktop.DBus",
425         "ListNames");
426 }
427 
nameChangeHandler(sdbusplus::message_t & message)428 void nameChangeHandler(sdbusplus::message_t& message)
429 {
430     std::string name;
431     std::string oldOwner;
432     std::string newOwner;
433 
434     message.read(name, oldOwner, newOwner);
435 
436     if (!oldOwner.empty())
437     {
438         if (boost::starts_with(oldOwner, ":"))
439         {
440             // Connection removed
441             auto it = uniqueNameToChannelNumber.find(oldOwner);
442             if (it != uniqueNameToChannelNumber.end())
443             {
444                 uniqueNameToChannelNumber.erase(it);
445             }
446         }
447     }
448     if (!newOwner.empty())
449     {
450         // start after ipmiDbusChannelMatch (and after the '.')
451         std::string chName = name.substr(std::strlen(ipmiDbusChannelMatch) + 1);
452         try
453         {
454             uint8_t channel = getChannelByName(chName);
455             uniqueNameToChannelNumber[newOwner] = channel;
456             lg2::info("New interface mapping: {INTERFACE} -> channel {CHANNEL}",
457                       "INTERFACE", name, "CHANNEL", channel);
458         }
459         catch (const std::exception& e)
460         {
461             lg2::info("Failed interface mapping, no such name: {INTERFACE}",
462                       "INTERFACE", name);
463         }
464     }
465 };
466 
467 } // anonymous namespace
468 
469 static constexpr const char intraBmcName[] = "INTRABMC";
channelFromMessage(sdbusplus::message_t & msg)470 uint8_t channelFromMessage(sdbusplus::message_t& msg)
471 {
472     // channel name for ipmitool to resolve to
473     std::string sender = msg.get_sender();
474     auto chIter = uniqueNameToChannelNumber.find(sender);
475     if (chIter != uniqueNameToChannelNumber.end())
476     {
477         return chIter->second;
478     }
479     // FIXME: currently internal connections are ephemeral and hard to pin down
480     try
481     {
482         return getChannelByName(intraBmcName);
483     }
484     catch (const std::exception& e)
485     {
486         return invalidChannel;
487     }
488 } // namespace ipmi
489 
490 /* called from sdbus async server context */
executionEntry(boost::asio::yield_context yield,sdbusplus::message_t & m,NetFn netFn,uint8_t lun,Cmd cmd,ipmi::SecureBuffer & data,std::map<std::string,ipmi::Value> & options)491 auto executionEntry(boost::asio::yield_context yield, sdbusplus::message_t& m,
492                     NetFn netFn, uint8_t lun, Cmd cmd, ipmi::SecureBuffer& data,
493                     std::map<std::string, ipmi::Value>& options)
494 {
495     const auto dbusResponse =
496         [netFn, lun, cmd](Cc cc, const ipmi::SecureBuffer& data = {}) {
497             constexpr uint8_t netFnResponse = 0x01;
498             uint8_t retNetFn = netFn | netFnResponse;
499             return std::make_tuple(retNetFn, lun, cmd, cc, data);
500         };
501     std::string sender = m.get_sender();
502     Privilege privilege = Privilege::None;
503     int rqSA = 0;
504     int hostIdx = 0;
505     uint8_t userId = 0; // undefined user
506     uint32_t sessionId = 0;
507 
508     // figure out what channel the request came in on
509     uint8_t channel = channelFromMessage(m);
510     if (channel == invalidChannel)
511     {
512         // unknown sender channel; refuse to service the request
513         lg2::error("ERROR determining source IPMI channel from "
514                    "{SENDER} NetFn/Cmd {NETFN}/{CMD}",
515                    "SENDER", sender, "NETFN", lg2::hex, netFn, "CMD", lg2::hex,
516                    cmd);
517         return dbusResponse(ipmi::ccDestinationUnavailable);
518     }
519 
520     // session-based channels are required to provide userId, privilege and
521     // sessionId
522     if (getChannelSessionSupport(channel) != EChannelSessSupported::none)
523     {
524         try
525         {
526             Value requestPriv = options.at("privilege");
527             Value requestUserId = options.at("userId");
528             Value requestSessionId = options.at("currentSessionId");
529             privilege = static_cast<Privilege>(std::get<int>(requestPriv));
530             userId = static_cast<uint8_t>(std::get<int>(requestUserId));
531             sessionId =
532                 static_cast<uint32_t>(std::get<uint32_t>(requestSessionId));
533         }
534         catch (const std::exception& e)
535         {
536             lg2::error("ERROR determining IPMI session credentials on "
537                        "channel {CHANNEL} for userid {USERID}",
538                        "CHANNEL", channel, "USERID", userId, "NETFN", lg2::hex,
539                        netFn, "CMD", lg2::hex, cmd);
540             return dbusResponse(ipmi::ccUnspecifiedError);
541         }
542     }
543     else
544     {
545         // get max privilege for session-less channels
546         // For now, there is not a way to configure this, default to Admin
547         privilege = Privilege::Admin;
548 
549         // ipmb should supply rqSA
550         ChannelInfo chInfo;
551         getChannelInfo(channel, chInfo);
552         if (static_cast<EChannelMediumType>(chInfo.mediumType) ==
553             EChannelMediumType::ipmb)
554         {
555             const auto iter = options.find("rqSA");
556             if (iter != options.end())
557             {
558                 if (std::holds_alternative<int>(iter->second))
559                 {
560                     rqSA = std::get<int>(iter->second);
561                 }
562             }
563             const auto iteration = options.find("hostId");
564             if (iteration != options.end())
565             {
566                 if (std::holds_alternative<int>(iteration->second))
567                 {
568                     hostIdx = std::get<int>(iteration->second);
569                 }
570             }
571         }
572     }
573     // check to see if the requested priv/username is valid
574     lg2::debug("Set up ipmi context: Ch:NetFn/Cmd={CHANNEL}:{NETFN}/{CMD}",
575                "SENDER", sender, "NETFN", lg2::hex, netFn, "LUN", lg2::hex, lun,
576                "CMD", lg2::hex, cmd, "CHANNEL", channel, "USERID", userId,
577                "SESSIONID", lg2::hex, sessionId, "PRIVILEGE",
578                static_cast<uint8_t>(privilege), "RQSA", lg2::hex, rqSA);
579 
580     auto ctx = std::make_shared<ipmi::Context>(
581         getSdBus(), netFn, lun, cmd, channel, userId, sessionId, privilege,
582         rqSA, hostIdx, yield);
583     auto request = std::make_shared<ipmi::message::Request>(
584         ctx, std::forward<ipmi::SecureBuffer>(data));
585     message::Response::ptr response = executeIpmiCommand(request);
586 
587     return dbusResponse(response->cc, response->payload.raw);
588 }
589 
590 /** @struct IpmiProvider
591  *
592  *  RAII wrapper for dlopen so that dlclose gets called on exit
593  */
594 struct IpmiProvider
595 {
596   public:
597     /** @brief address of the opened library */
598     void* addr;
599     std::string name;
600 
601     IpmiProvider() = delete;
602     IpmiProvider(const IpmiProvider&) = delete;
603     IpmiProvider& operator=(const IpmiProvider&) = delete;
604     IpmiProvider(IpmiProvider&&) = delete;
605     IpmiProvider& operator=(IpmiProvider&&) = delete;
606 
607     /** @brief dlopen a shared object file by path
608      *  @param[in]  filename - path of shared object to open
609      */
IpmiProvideripmi::IpmiProvider610     explicit IpmiProvider(const char* fname) : addr(nullptr), name(fname)
611     {
612         lg2::debug("Open IPMI provider library: {PROVIDER}", "PROVIDER", name);
613         try
614         {
615             addr = dlopen(name.c_str(), RTLD_NOW);
616         }
617         catch (const std::exception& e)
618         {
619             lg2::error("ERROR opening IPMI provider {PROVIDER}: {ERROR}",
620                        "PROVIDER", name, "ERROR", e);
621         }
622         catch (...)
623         {
624             const char* what = currentExceptionType();
625             lg2::error("ERROR opening IPMI provider {PROVIDER}: {ERROR}",
626                        "PROVIDER", name, "ERROR", what);
627         }
628         if (!isOpen())
629         {
630             lg2::error("ERROR opening IPMI provider {PROVIDER}: {ERROR}",
631                        "PROVIDER", name, "ERROR", dlerror());
632         }
633     }
634 
~IpmiProvideripmi::IpmiProvider635     ~IpmiProvider()
636     {
637         if (isOpen())
638         {
639             dlclose(addr);
640         }
641     }
isOpenipmi::IpmiProvider642     bool isOpen() const
643     {
644         return (nullptr != addr);
645     }
646 };
647 
648 // Plugin libraries need to contain .so either at the end or in the middle
649 constexpr const char ipmiPluginExtn[] = ".so";
650 
651 /* return a list of self-closing library handles */
loadProviders(const fs::path & ipmiLibsPath)652 std::forward_list<IpmiProvider> loadProviders(const fs::path& ipmiLibsPath)
653 {
654     std::vector<fs::path> libs;
655     for (const auto& libPath : fs::directory_iterator(ipmiLibsPath))
656     {
657         std::error_code ec;
658         fs::path fname = libPath.path();
659         if (fs::is_symlink(fname, ec) || ec)
660         {
661             // it's a symlink or some other error; skip it
662             continue;
663         }
664         while (fname.has_extension())
665         {
666             fs::path extn = fname.extension();
667             if (extn == ipmiPluginExtn)
668             {
669                 libs.push_back(libPath.path());
670                 break;
671             }
672             fname.replace_extension();
673         }
674     }
675     std::sort(libs.begin(), libs.end());
676 
677     std::forward_list<IpmiProvider> handles;
678     for (auto& lib : libs)
679     {
680 #ifdef __IPMI_DEBUG__
681         lg2::debug("Registering handler {HANDLER}", "HANDLER", lib);
682 #endif
683         handles.emplace_front(lib.c_str());
684     }
685     return handles;
686 }
687 
688 } // namespace ipmi
689 
690 #ifdef ALLOW_DEPRECATED_API
691 /* legacy registration */
ipmi_register_callback(ipmi_netfn_t netFn,ipmi_cmd_t cmd,ipmi_context_t context,ipmid_callback_t handler,ipmi_cmd_privilege_t priv)692 void ipmi_register_callback(ipmi_netfn_t netFn, ipmi_cmd_t cmd,
693                             ipmi_context_t context, ipmid_callback_t handler,
694                             ipmi_cmd_privilege_t priv)
695 {
696     auto h = ipmi::makeLegacyHandler(handler, context);
697     // translate priv from deprecated enum to current
698     ipmi::Privilege realPriv;
699     switch (priv)
700     {
701         case PRIVILEGE_CALLBACK:
702             realPriv = ipmi::Privilege::Callback;
703             break;
704         case PRIVILEGE_USER:
705             realPriv = ipmi::Privilege::User;
706             break;
707         case PRIVILEGE_OPERATOR:
708             realPriv = ipmi::Privilege::Operator;
709             break;
710         case PRIVILEGE_ADMIN:
711             realPriv = ipmi::Privilege::Admin;
712             break;
713         case PRIVILEGE_OEM:
714             realPriv = ipmi::Privilege::Oem;
715             break;
716         case SYSTEM_INTERFACE:
717             realPriv = ipmi::Privilege::Admin;
718             break;
719         default:
720             realPriv = ipmi::Privilege::Admin;
721             break;
722     }
723     // The original ipmi_register_callback allowed for group OEM handlers
724     // to be registered via this same interface. It just so happened that
725     // all the handlers were part of the DCMI group, so default to that.
726     if (netFn == NETFUN_GRPEXT)
727     {
728         ipmi::impl::registerGroupHandler(ipmi::prioOpenBmcBase, ipmi::groupDCMI,
729                                          cmd, realPriv, h);
730     }
731     else
732     {
733         ipmi::impl::registerHandler(ipmi::prioOpenBmcBase, netFn, cmd, realPriv,
734                                     h);
735     }
736 }
737 
738 namespace oem
739 {
740 
741 class LegacyRouter : public oem::Router
742 {
743   public:
~LegacyRouter()744     virtual ~LegacyRouter() {}
745 
746     /// Enable message routing to begin.
activate()747     void activate() override {}
748 
registerHandler(Number oen,ipmi_cmd_t cmd,Handler handler)749     void registerHandler(Number oen, ipmi_cmd_t cmd, Handler handler) override
750     {
751         auto h = ipmi::makeLegacyHandler(std::forward<Handler>(handler));
752         ipmi::impl::registerOemHandler(ipmi::prioOpenBmcBase, oen, cmd,
753                                        ipmi::Privilege::Admin, h);
754     }
755 };
756 static LegacyRouter legacyRouter;
757 
mutableRouter()758 Router* mutableRouter()
759 {
760     return &legacyRouter;
761 }
762 
763 } // namespace oem
764 
765 /* legacy alternative to executionEntry */
handleLegacyIpmiCommand(sdbusplus::message_t & m)766 void handleLegacyIpmiCommand(sdbusplus::message_t& m)
767 {
768     // make a copy so the next two moves don't wreak havoc on the stack
769     sdbusplus::message_t b{m};
770     boost::asio::spawn(
771         *getIoContext(),
772         [b = std::move(b)](boost::asio::yield_context yield) {
773             sdbusplus::message_t m{std::move(b)};
774             unsigned char seq = 0, netFn = 0, lun = 0, cmd = 0;
775             ipmi::SecureBuffer data;
776 
777             m.read(seq, netFn, lun, cmd, data);
778             std::shared_ptr<sdbusplus::asio::connection> bus = getSdBus();
779             auto ctx = std::make_shared<ipmi::Context>(
780                 bus, netFn, lun, cmd, 0, 0, 0, ipmi::Privilege::Admin, 0, 0,
781                 yield);
782             auto request = std::make_shared<ipmi::message::Request>(
783                 ctx, std::forward<ipmi::SecureBuffer>(data));
784             ipmi::message::Response::ptr response =
785                 ipmi::executeIpmiCommand(request);
786 
787             // Responses in IPMI require a bit set.  So there ya go...
788             netFn |= 0x01;
789 
790             constexpr const char* DBUS_INTF = "org.openbmc.HostIpmi";
791 
792             std::string dest = m.get_sender();
793             std::string path = m.get_path();
794             boost::system::error_code ec = ipmi::callDbusMethod(
795                 ctx, dest, path, DBUS_INTF, "sendMessage", seq, netFn, lun, cmd,
796                 response->cc, response->payload.raw);
797 
798             if (ec)
799             {
800                 lg2::error(
801                     "Failed to send response to requestor ({NETFN}/{CMD}): {ERROR}",
802                     "ERROR", ec.message(), "SENDER", dest, "NETFN", lg2::hex,
803                     netFn, "CMD", lg2::hex, cmd);
804             }
805         },
806         boost::asio::detached);
807 }
808 
809 #endif /* ALLOW_DEPRECATED_API */
810 
811 // Calls host command manager to do the right thing for the command
812 using CommandHandler = phosphor::host::command::CommandHandler;
813 std::unique_ptr<phosphor::host::command::Manager> cmdManager;
ipmid_send_cmd_to_host(CommandHandler && cmd)814 void ipmid_send_cmd_to_host(CommandHandler&& cmd)
815 {
816     cmdManager->execute(std::forward<CommandHandler>(cmd));
817 }
818 
ipmid_get_host_cmd_manager()819 std::unique_ptr<phosphor::host::command::Manager>& ipmid_get_host_cmd_manager()
820 {
821     return cmdManager;
822 }
823 
824 // These are symbols that are present in libipmid, but not expected
825 // to be used except here (or maybe a unit test), so declare them here
826 extern void setIoContext(std::shared_ptr<boost::asio::io_context>& newIo);
827 extern void setSdBus(std::shared_ptr<sdbusplus::asio::connection>& newBus);
828 
main(int argc,char * argv[])829 int main(int argc, char* argv[])
830 {
831     // Connect to system bus
832     auto io = std::make_shared<boost::asio::io_context>();
833     setIoContext(io);
834     if (argc > 1 && std::string(argv[1]) == "-session")
835     {
836         sd_bus_default_user(&bus);
837     }
838     else
839     {
840         sd_bus_default_system(&bus);
841     }
842     auto sdbusp = std::make_shared<sdbusplus::asio::connection>(*io, bus);
843     setSdBus(sdbusp);
844 
845     // TODO: Hack to keep the sdEvents running.... Not sure why the sd_event
846     //       queue stops running if we don't have a timer that keeps re-arming
847     sdbusplus::Timer t2([]() { ; });
848     t2.start(std::chrono::microseconds(500000), true);
849 
850     // TODO: Remove all vestiges of sd_event from phosphor-host-ipmid
851     //       until that is done, add the sd_event wrapper to the io object
852     sdbusplus::asio::sd_event_wrapper sdEvents(*io);
853 
854     cmdManager = std::make_unique<phosphor::host::command::Manager>(*sdbusp);
855 
856     // Register all command providers and filters
857     std::forward_list<ipmi::IpmiProvider> providers =
858         ipmi::loadProviders(HOST_IPMI_LIB_PATH);
859 
860 #ifdef ALLOW_DEPRECATED_API
861     // listen on deprecated signal interface for kcs/bt commands
862     constexpr const char* FILTER = "type='signal',interface='org.openbmc."
863                                    "HostIpmi',member='ReceivedMessage'";
864     sdbusplus::bus::match_t oldIpmiInterface(*sdbusp, FILTER,
865                                              handleLegacyIpmiCommand);
866 #endif /* ALLOW_DEPRECATED_API */
867 
868     // set up bus name watching to match channels with bus names
869     sdbusplus::bus::match_t nameOwnerChanged(
870         *sdbusp,
871         sdbusplus::bus::match::rules::nameOwnerChanged() +
872             sdbusplus::bus::match::rules::arg0namespace(
873                 ipmi::ipmiDbusChannelMatch),
874         ipmi::nameChangeHandler);
875     ipmi::doListNames(*sdbusp);
876 
877     int exitCode = 0;
878     // set up boost::asio signal handling
879     std::function<SignalResponse(int)> stopAsioRunLoop = [&io, &exitCode](
880                                                              int signalNumber) {
881         lg2::info("Received signal {SIGNAL}; quitting", "SIGNAL", signalNumber);
882         io->stop();
883         exitCode = signalNumber;
884         return SignalResponse::breakExecution;
885     };
886     registerSignalHandler(ipmi::prioOpenBmcBase, SIGINT, stopAsioRunLoop);
887     registerSignalHandler(ipmi::prioOpenBmcBase, SIGTERM, stopAsioRunLoop);
888 
889     sdbusp->request_name("xyz.openbmc_project.Ipmi.Host");
890     // Add bindings for inbound IPMI requests
891     auto server = sdbusplus::asio::object_server(sdbusp);
892     auto iface = server.add_interface("/xyz/openbmc_project/Ipmi",
893                                       "xyz.openbmc_project.Ipmi.Server");
894     iface->register_method("execute", ipmi::executionEntry);
895     iface->initialize();
896 
897     io->run();
898 
899     // destroy all the IPMI handlers so the providers can unload safely
900     ipmi::handlerMap.clear();
901     ipmi::groupHandlerMap.clear();
902     ipmi::oemHandlerMap.clear();
903     ipmi::filterList.clear();
904     // unload the provider libraries
905     providers.clear();
906 
907     std::exit(exitCode);
908 }
909