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