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