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