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 <algorithm> 23 #include <any> 24 #include <boost/algorithm/string.hpp> 25 #include <dcmihandler.hpp> 26 #include <exception> 27 #include <filesystem> 28 #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> 35 #include <ipmid/types.hpp> 36 #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> 47 #include <unordered_map> 48 #include <utility> 49 #include <vector> 50 51 namespace fs = std::filesystem; 52 53 using namespace phosphor::logging; 54 55 // IPMI Spec, shared Reservation ID. 56 static unsigned short selReservationID = 0xFFFF; 57 static bool selReservationValid = false; 58 59 unsigned 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 71 bool checkSELReservation(unsigned short id) 72 { 73 return (selReservationValid && selReservationID == id); 74 } 75 76 void cancelSELReservation(void) 77 { 78 selReservationValid = false; 79 } 80 81 EInterfaceIndex getInterfaceIndex(void) 82 { 83 return interfaceKCS; 84 } 85 86 sd_bus* bus; 87 sd_event* events = nullptr; 88 sd_event* ipmid_get_sd_event_connection(void) 89 { 90 return events; 91 } 92 sd_bus* ipmid_get_sd_bus_connection(void) 93 { 94 return bus; 95 } 96 97 namespace ipmi 98 { 99 100 static inline unsigned int makeCmdKey(unsigned int cluster, unsigned int cmd) 101 { 102 return (cluster << 8) | cmd; 103 } 104 105 using HandlerTuple = std::tuple<int, /* prio */ 106 Privilege, HandlerBase::ptr /* handler */ 107 >; 108 109 /* map to handle standard registered commands */ 110 static std::unordered_map<unsigned int, /* key is NetFn/Cmd */ 111 HandlerTuple> 112 handlerMap; 113 114 /* special map for decoding Group registered commands (NetFn 2Ch) */ 115 static 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) */ 120 static std::unordered_map<unsigned int, /* key is Iana/Cmd (NetFn is 2Eh) */ 121 HandlerTuple> 122 oemHandlerMap; 123 124 using FilterTuple = std::tuple<int, /* prio */ 125 FilterBase::ptr /* filter */ 126 >; 127 128 /* list to hold all registered ipmi command filters */ 129 static std::forward_list<FilterTuple> filterList; 130 131 namespace impl 132 { 133 /* common function to register all standard IPMI handlers */ 134 bool 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 158 /* common function to register all Group IPMI handlers */ 159 bool 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 */ 177 bool 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 194 /* common function to register all IPMI filter handlers */ 195 void 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 211 } // namespace impl 212 213 message::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 230 message::Response::ptr executeIpmiCommandCommon( 231 std::unordered_map<unsigned int, HandlerTuple>& handlers, 232 unsigned int keyCommon, message::Request::ptr request) 233 { 234 // 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 242 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 271 message::Response::ptr executeIpmiGroupCommand(message::Request::ptr request) 272 { 273 // look up the group for this request 274 uint8_t bytes; 275 if (0 != request->payload.unpack(bytes)) 276 { 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 auto group = static_cast<Group>(bytes); 282 message::Response::ptr response = 283 executeIpmiCommandCommon(groupHandlerMap, group, request); 284 // if the handler should add the group; executeIpmiCommandCommon does not 285 if (response->cc != ccSuccess && response->payload.size() == 0) 286 { 287 response->pack(bytes); 288 } 289 return response; 290 } 291 292 message::Response::ptr executeIpmiOemCommand(message::Request::ptr request) 293 { 294 // look up the iana for this request 295 uint24_t bytes; 296 if (0 != request->payload.unpack(bytes)) 297 { 298 return errorResponse(request, ccReqDataLenInvalid); 299 } 300 request->payload.reset(); 301 auto iana = static_cast<Iana>(bytes); 302 message::Response::ptr response = 303 executeIpmiCommandCommon(oemHandlerMap, iana, request); 304 // if the handler should add the iana; executeIpmiCommandCommon does not 305 if (response->cc != ccSuccess && response->payload.size() == 0) 306 { 307 response->pack(bytes); 308 } 309 return response; 310 } 311 312 message::Response::ptr executeIpmiCommand(message::Request::ptr request) 313 { 314 NetFn netFn = request->ctx->netFn; 315 if (netFnGroup == netFn) 316 { 317 return executeIpmiGroupCommand(request); 318 } 319 else if (netFnOem == netFn) 320 { 321 return executeIpmiOemCommand(request); 322 } 323 return executeIpmiCommandCommon(handlerMap, netFn, request); 324 } 325 326 namespace utils 327 { 328 template <typename AssocContainer, typename UnaryPredicate> 329 void assoc_erase_if(AssocContainer& c, UnaryPredicate p) 330 { 331 typename AssocContainer::iterator next = c.begin(); 332 typename AssocContainer::iterator last = c.end(); 333 while ((next = std::find_if(next, last, p)) != last) 334 { 335 c.erase(next++); 336 } 337 } 338 } // namespace utils 339 340 namespace 341 { 342 std::unordered_map<std::string, uint8_t> uniqueNameToChannelNumber; 343 344 // sdbusplus::bus::match::rules::arg0namespace() wants the prefix 345 // to match without any trailing '.' 346 constexpr const char ipmiDbusChannelMatch[] = 347 "xyz.openbmc_project.Ipmi.Channel"; 348 void updateOwners(sdbusplus::asio::connection& conn, const std::string& name) 349 { 350 conn.async_method_call( 351 [name](const boost::system::error_code ec, 352 const std::string& nameOwner) { 353 if (ec) 354 { 355 log<level::ERR>("Error getting dbus owner", 356 entry("INTERFACE=%s", name.c_str())); 357 return; 358 } 359 // start after ipmiDbusChannelPrefix (after the '.') 360 std::string chName = 361 name.substr(std::strlen(ipmiDbusChannelMatch) + 1); 362 try 363 { 364 uint8_t channel = getChannelByName(chName); 365 uniqueNameToChannelNumber[nameOwner] = channel; 366 log<level::INFO>("New interface mapping", 367 entry("INTERFACE=%s", name.c_str()), 368 entry("CHANNEL=%u", channel)); 369 } 370 catch (const std::exception& e) 371 { 372 log<level::INFO>("Failed interface mapping, no such name", 373 entry("INTERFACE=%s", name.c_str())); 374 } 375 }, 376 "org.freedesktop.DBus", "/", "org.freedesktop.DBus", "GetNameOwner", 377 name); 378 } 379 380 void doListNames(boost::asio::io_service& io, sdbusplus::asio::connection& conn) 381 { 382 conn.async_method_call( 383 [&io, &conn](const boost::system::error_code ec, 384 std::vector<std::string> busNames) { 385 if (ec) 386 { 387 log<level::ERR>("Error getting dbus names"); 388 std::exit(EXIT_FAILURE); 389 return; 390 } 391 // Try to make startup consistent 392 std::sort(busNames.begin(), busNames.end()); 393 394 const std::string channelPrefix = 395 std::string(ipmiDbusChannelMatch) + "."; 396 for (const std::string& busName : busNames) 397 { 398 if (busName.find(channelPrefix) == 0) 399 { 400 updateOwners(conn, busName); 401 } 402 } 403 }, 404 "org.freedesktop.DBus", "/org/freedesktop/DBus", "org.freedesktop.DBus", 405 "ListNames"); 406 } 407 408 void nameChangeHandler(sdbusplus::message::message& message) 409 { 410 std::string name; 411 std::string oldOwner; 412 std::string newOwner; 413 414 message.read(name, oldOwner, newOwner); 415 416 if (!oldOwner.empty()) 417 { 418 if (boost::starts_with(oldOwner, ":")) 419 { 420 // Connection removed 421 auto it = uniqueNameToChannelNumber.find(oldOwner); 422 if (it != uniqueNameToChannelNumber.end()) 423 { 424 uniqueNameToChannelNumber.erase(it); 425 } 426 } 427 } 428 if (!newOwner.empty()) 429 { 430 // start after ipmiDbusChannelMatch (and after the '.') 431 std::string chName = name.substr(std::strlen(ipmiDbusChannelMatch) + 1); 432 try 433 { 434 uint8_t channel = getChannelByName(chName); 435 uniqueNameToChannelNumber[newOwner] = channel; 436 log<level::INFO>("New interface mapping", 437 entry("INTERFACE=%s", name.c_str()), 438 entry("CHANNEL=%u", channel)); 439 } 440 catch (const std::exception& e) 441 { 442 log<level::INFO>("Failed interface mapping, no such name", 443 entry("INTERFACE=%s", name.c_str())); 444 } 445 } 446 }; 447 448 } // anonymous namespace 449 450 static constexpr const char intraBmcName[] = "INTRABMC"; 451 uint8_t channelFromMessage(sdbusplus::message::message& msg) 452 { 453 // channel name for ipmitool to resolve to 454 std::string sender = msg.get_sender(); 455 auto chIter = uniqueNameToChannelNumber.find(sender); 456 if (chIter != uniqueNameToChannelNumber.end()) 457 { 458 return chIter->second; 459 } 460 // FIXME: currently internal connections are ephemeral and hard to pin down 461 try 462 { 463 return getChannelByName(intraBmcName); 464 } 465 catch (const std::exception& e) 466 { 467 return invalidChannel; 468 } 469 } // namespace ipmi 470 471 /* called from sdbus async server context */ 472 auto executionEntry(boost::asio::yield_context yield, 473 sdbusplus::message::message& m, NetFn netFn, uint8_t lun, 474 Cmd cmd, std::vector<uint8_t>& data, 475 std::map<std::string, ipmi::Value>& options) 476 { 477 const auto dbusResponse = 478 [netFn, lun, cmd](Cc cc, const std::vector<uint8_t>& data = {}) { 479 constexpr uint8_t netFnResponse = 0x01; 480 uint8_t retNetFn = netFn | netFnResponse; 481 return std::make_tuple(retNetFn, lun, cmd, cc, data); 482 }; 483 std::string sender = m.get_sender(); 484 Privilege privilege = Privilege::None; 485 int rqSA = 0; 486 uint8_t userId = 0; // undefined user 487 488 // figure out what channel the request came in on 489 uint8_t channel = channelFromMessage(m); 490 if (channel == invalidChannel) 491 { 492 // unknown sender channel; refuse to service the request 493 log<level::ERR>("ERROR determining source IPMI channel", 494 entry("SENDER=%s", sender.c_str()), 495 entry("NETFN=0x%X", netFn), entry("CMD=0x%X", cmd)); 496 return dbusResponse(ipmi::ccDestinationUnavailable); 497 } 498 499 // session-based channels are required to provide userId/privilege 500 if (getChannelSessionSupport(channel) != EChannelSessSupported::none) 501 { 502 try 503 { 504 Value requestPriv = options.at("privilege"); 505 Value requestUserId = options.at("userId"); 506 privilege = static_cast<Privilege>(std::get<int>(requestPriv)); 507 userId = static_cast<uint8_t>(std::get<int>(requestUserId)); 508 } 509 catch (const std::exception& e) 510 { 511 log<level::ERR>("ERROR determining IPMI session credentials", 512 entry("CHANNEL=%u", channel), 513 entry("NETFN=0x%X", netFn), entry("CMD=0x%X", cmd)); 514 return dbusResponse(ipmi::ccUnspecifiedError); 515 } 516 } 517 else 518 { 519 // get max privilege for session-less channels 520 // For now, there is not a way to configure this, default to Admin 521 privilege = Privilege::Admin; 522 523 // ipmb should supply rqSA 524 ChannelInfo chInfo; 525 getChannelInfo(channel, chInfo); 526 if (static_cast<EChannelMediumType>(chInfo.mediumType) == 527 EChannelMediumType::ipmb) 528 { 529 const auto iter = options.find("rqSA"); 530 if (iter != options.end()) 531 { 532 if (std::holds_alternative<int>(iter->second)) 533 { 534 rqSA = std::get<int>(iter->second); 535 } 536 } 537 } 538 } 539 // check to see if the requested priv/username is valid 540 log<level::DEBUG>("Set up ipmi context", entry("SENDER=%s", sender.c_str()), 541 entry("NETFN=0x%X", netFn), entry("CMD=0x%X", cmd), 542 entry("CHANNEL=%u", channel), entry("USERID=%u", userId), 543 entry("PRIVILEGE=%u", static_cast<uint8_t>(privilege)), 544 entry("RQSA=%x", rqSA)); 545 546 auto ctx = std::make_shared<ipmi::Context>(netFn, cmd, channel, userId, 547 privilege, rqSA, &yield); 548 auto request = std::make_shared<ipmi::message::Request>( 549 ctx, std::forward<std::vector<uint8_t>>(data)); 550 message::Response::ptr response = executeIpmiCommand(request); 551 552 return dbusResponse(response->cc, response->payload.raw); 553 } 554 555 /** @struct IpmiProvider 556 * 557 * RAII wrapper for dlopen so that dlclose gets called on exit 558 */ 559 struct IpmiProvider 560 { 561 public: 562 /** @brief address of the opened library */ 563 void* addr; 564 std::string name; 565 566 IpmiProvider() = delete; 567 IpmiProvider(const IpmiProvider&) = delete; 568 IpmiProvider& operator=(const IpmiProvider&) = delete; 569 IpmiProvider(IpmiProvider&&) = delete; 570 IpmiProvider& operator=(IpmiProvider&&) = delete; 571 572 /** @brief dlopen a shared object file by path 573 * @param[in] filename - path of shared object to open 574 */ 575 explicit IpmiProvider(const char* fname) : addr(nullptr), name(fname) 576 { 577 log<level::DEBUG>("Open IPMI provider library", 578 entry("PROVIDER=%s", name.c_str())); 579 try 580 { 581 addr = dlopen(name.c_str(), RTLD_NOW); 582 } 583 catch (std::exception& e) 584 { 585 log<level::ERR>("ERROR opening IPMI provider", 586 entry("PROVIDER=%s", name.c_str()), 587 entry("ERROR=%s", e.what())); 588 } 589 catch (...) 590 { 591 std::exception_ptr eptr = std::current_exception(); 592 try 593 { 594 std::rethrow_exception(eptr); 595 } 596 catch (std::exception& e) 597 { 598 log<level::ERR>("ERROR opening IPMI provider", 599 entry("PROVIDER=%s", name.c_str()), 600 entry("ERROR=%s", e.what())); 601 } 602 } 603 if (!isOpen()) 604 { 605 log<level::ERR>("ERROR opening IPMI provider", 606 entry("PROVIDER=%s", name.c_str()), 607 entry("ERROR=%s", dlerror())); 608 } 609 } 610 611 ~IpmiProvider() 612 { 613 if (isOpen()) 614 { 615 dlclose(addr); 616 } 617 } 618 bool isOpen() const 619 { 620 return (nullptr != addr); 621 } 622 }; 623 624 // Plugin libraries need to contain .so either at the end or in the middle 625 constexpr const char ipmiPluginExtn[] = ".so"; 626 627 /* return a list of self-closing library handles */ 628 std::forward_list<IpmiProvider> loadProviders(const fs::path& ipmiLibsPath) 629 { 630 std::vector<fs::path> libs; 631 for (const auto& libPath : fs::directory_iterator(ipmiLibsPath)) 632 { 633 std::error_code ec; 634 fs::path fname = libPath.path(); 635 if (fs::is_symlink(fname, ec) || ec) 636 { 637 // it's a symlink or some other error; skip it 638 continue; 639 } 640 while (fname.has_extension()) 641 { 642 fs::path extn = fname.extension(); 643 if (extn == ipmiPluginExtn) 644 { 645 libs.push_back(libPath.path()); 646 break; 647 } 648 fname.replace_extension(); 649 } 650 } 651 std::sort(libs.begin(), libs.end()); 652 653 std::forward_list<IpmiProvider> handles; 654 for (auto& lib : libs) 655 { 656 #ifdef __IPMI_DEBUG__ 657 log<level::DEBUG>("Registering handler", 658 entry("HANDLER=%s", lib.c_str())); 659 #endif 660 handles.emplace_front(lib.c_str()); 661 } 662 return handles; 663 } 664 665 } // namespace ipmi 666 667 #ifdef ALLOW_DEPRECATED_API 668 /* legacy registration */ 669 void ipmi_register_callback(ipmi_netfn_t netFn, ipmi_cmd_t cmd, 670 ipmi_context_t context, ipmid_callback_t handler, 671 ipmi_cmd_privilege_t priv) 672 { 673 auto h = ipmi::makeLegacyHandler(handler, context); 674 // translate priv from deprecated enum to current 675 ipmi::Privilege realPriv; 676 switch (priv) 677 { 678 case PRIVILEGE_CALLBACK: 679 realPriv = ipmi::Privilege::Callback; 680 break; 681 case PRIVILEGE_USER: 682 realPriv = ipmi::Privilege::User; 683 break; 684 case PRIVILEGE_OPERATOR: 685 realPriv = ipmi::Privilege::Operator; 686 break; 687 case PRIVILEGE_ADMIN: 688 realPriv = ipmi::Privilege::Admin; 689 break; 690 case PRIVILEGE_OEM: 691 realPriv = ipmi::Privilege::Oem; 692 break; 693 case SYSTEM_INTERFACE: 694 realPriv = ipmi::Privilege::Admin; 695 break; 696 default: 697 realPriv = ipmi::Privilege::Admin; 698 break; 699 } 700 // The original ipmi_register_callback allowed for group OEM handlers 701 // to be registered via this same interface. It just so happened that 702 // all the handlers were part of the DCMI group, so default to that. 703 if (netFn == NETFUN_GRPEXT) 704 { 705 ipmi::impl::registerGroupHandler(ipmi::prioOpenBmcBase, 706 dcmi::groupExtId, cmd, realPriv, h); 707 } 708 else 709 { 710 ipmi::impl::registerHandler(ipmi::prioOpenBmcBase, netFn, cmd, realPriv, 711 h); 712 } 713 } 714 715 namespace oem 716 { 717 718 class LegacyRouter : public oem::Router 719 { 720 public: 721 virtual ~LegacyRouter() 722 { 723 } 724 725 /// Enable message routing to begin. 726 void activate() override 727 { 728 } 729 730 void registerHandler(Number oen, ipmi_cmd_t cmd, Handler handler) override 731 { 732 auto h = ipmi::makeLegacyHandler(std::forward<Handler>(handler)); 733 ipmi::impl::registerOemHandler(ipmi::prioOpenBmcBase, oen, cmd, 734 ipmi::Privilege::Admin, h); 735 } 736 }; 737 static LegacyRouter legacyRouter; 738 739 Router* mutableRouter() 740 { 741 return &legacyRouter; 742 } 743 744 } // namespace oem 745 746 /* legacy alternative to executionEntry */ 747 void handleLegacyIpmiCommand(sdbusplus::message::message& m) 748 { 749 unsigned char seq, netFn, lun, cmd; 750 std::vector<uint8_t> data; 751 752 m.read(seq, netFn, lun, cmd, data); 753 754 auto ctx = std::make_shared<ipmi::Context>(netFn, cmd, 0, 0, 755 ipmi::Privilege::Admin); 756 auto request = std::make_shared<ipmi::message::Request>( 757 ctx, std::forward<std::vector<uint8_t>>(data)); 758 ipmi::message::Response::ptr response = ipmi::executeIpmiCommand(request); 759 760 // Responses in IPMI require a bit set. So there ya go... 761 netFn |= 0x01; 762 763 const char *dest, *path; 764 constexpr const char* DBUS_INTF = "org.openbmc.HostIpmi"; 765 766 dest = m.get_sender(); 767 path = m.get_path(); 768 getSdBus()->async_method_call([](boost::system::error_code ec) {}, dest, 769 path, DBUS_INTF, "sendMessage", seq, netFn, 770 lun, cmd, response->cc, 771 response->payload.raw); 772 } 773 774 #endif /* ALLOW_DEPRECATED_API */ 775 776 // Calls host command manager to do the right thing for the command 777 using CommandHandler = phosphor::host::command::CommandHandler; 778 std::unique_ptr<phosphor::host::command::Manager> cmdManager; 779 void ipmid_send_cmd_to_host(CommandHandler&& cmd) 780 { 781 return cmdManager->execute(std::forward<CommandHandler>(cmd)); 782 } 783 784 std::unique_ptr<phosphor::host::command::Manager>& ipmid_get_host_cmd_manager() 785 { 786 return cmdManager; 787 } 788 789 // These are symbols that are present in libipmid, but not expected 790 // to be used except here (or maybe a unit test), so declare them here 791 extern void setIoContext(std::shared_ptr<boost::asio::io_context>& newIo); 792 extern void setSdBus(std::shared_ptr<sdbusplus::asio::connection>& newBus); 793 794 int main(int argc, char* argv[]) 795 { 796 // Connect to system bus 797 auto io = std::make_shared<boost::asio::io_context>(); 798 setIoContext(io); 799 if (argc > 1 && std::string(argv[1]) == "-session") 800 { 801 sd_bus_default_user(&bus); 802 } 803 else 804 { 805 sd_bus_default_system(&bus); 806 } 807 auto sdbusp = std::make_shared<sdbusplus::asio::connection>(*io, bus); 808 setSdBus(sdbusp); 809 sdbusp->request_name("xyz.openbmc_project.Ipmi.Host"); 810 811 // TODO: Hack to keep the sdEvents running.... Not sure why the sd_event 812 // queue stops running if we don't have a timer that keeps re-arming 813 phosphor::Timer t2([]() { ; }); 814 t2.start(std::chrono::microseconds(500000), true); 815 816 // TODO: Remove all vestiges of sd_event from phosphor-host-ipmid 817 // until that is done, add the sd_event wrapper to the io object 818 sdbusplus::asio::sd_event_wrapper sdEvents(*io); 819 820 cmdManager = std::make_unique<phosphor::host::command::Manager>(*sdbusp); 821 822 // Register all command providers and filters 823 std::forward_list<ipmi::IpmiProvider> providers = 824 ipmi::loadProviders(HOST_IPMI_LIB_PATH); 825 826 // Add bindings for inbound IPMI requests 827 auto server = sdbusplus::asio::object_server(sdbusp); 828 auto iface = server.add_interface("/xyz/openbmc_project/Ipmi", 829 "xyz.openbmc_project.Ipmi.Server"); 830 iface->register_method("execute", ipmi::executionEntry); 831 iface->initialize(); 832 833 #ifdef ALLOW_DEPRECATED_API 834 // listen on deprecated signal interface for kcs/bt commands 835 constexpr const char* FILTER = "type='signal',interface='org.openbmc." 836 "HostIpmi',member='ReceivedMessage'"; 837 sdbusplus::bus::match::match oldIpmiInterface(*sdbusp, FILTER, 838 handleLegacyIpmiCommand); 839 #endif /* ALLOW_DEPRECATED_API */ 840 841 // set up bus name watching to match channels with bus names 842 sdbusplus::bus::match::match nameOwnerChanged( 843 *sdbusp, 844 sdbusplus::bus::match::rules::nameOwnerChanged() + 845 sdbusplus::bus::match::rules::arg0namespace( 846 ipmi::ipmiDbusChannelMatch), 847 ipmi::nameChangeHandler); 848 ipmi::doListNames(*io, *sdbusp); 849 850 // set up boost::asio signal handling 851 std::function<SignalResponse(int)> stopAsioRunLoop = 852 [&io](int signalNumber) { 853 log<level::INFO>("Received signal; quitting", 854 entry("SIGNAL=%d", signalNumber)); 855 io->stop(); 856 return SignalResponse::breakExecution; 857 }; 858 registerSignalHandler(ipmi::prioOpenBmcBase, SIGINT, stopAsioRunLoop); 859 registerSignalHandler(ipmi::prioOpenBmcBase, SIGTERM, stopAsioRunLoop); 860 861 io->run(); 862 863 // destroy all the IPMI handlers so the providers can unload safely 864 ipmi::handlerMap.clear(); 865 ipmi::groupHandlerMap.clear(); 866 ipmi::oemHandlerMap.clear(); 867 ipmi::filterList.clear(); 868 // unload the provider libraries 869 providers.clear(); 870 871 return 0; 872 } 873