1 #include "config.h" 2 3 #include <arpa/inet.h> 4 #include <fcntl.h> 5 #include <limits.h> 6 #include <linux/i2c-dev.h> 7 #include <linux/i2c.h> 8 #include <mapper.h> 9 #include <sys/ioctl.h> 10 #include <sys/stat.h> 11 #include <sys/types.h> 12 #include <systemd/sd-bus.h> 13 #include <unistd.h> 14 15 #include <app/channel.hpp> 16 #include <app/watchdog.hpp> 17 #include <apphandler.hpp> 18 #include <ipmid/api.hpp> 19 #include <ipmid/sessiondef.hpp> 20 #include <ipmid/sessionhelper.hpp> 21 #include <ipmid/types.hpp> 22 #include <ipmid/utils.hpp> 23 #include <nlohmann/json.hpp> 24 #include <phosphor-logging/elog-errors.hpp> 25 #include <phosphor-logging/log.hpp> 26 #include <sdbusplus/message/types.hpp> 27 #include <sys_info_param.hpp> 28 #include <xyz/openbmc_project/Common/error.hpp> 29 #include <xyz/openbmc_project/Control/Power/ACPIPowerState/server.hpp> 30 #include <xyz/openbmc_project/Software/Activation/server.hpp> 31 #include <xyz/openbmc_project/Software/Version/server.hpp> 32 #include <xyz/openbmc_project/State/BMC/server.hpp> 33 34 #include <algorithm> 35 #include <array> 36 #include <charconv> 37 #include <cstddef> 38 #include <cstdint> 39 #include <filesystem> 40 #include <fstream> 41 #include <memory> 42 #include <regex> 43 #include <string> 44 #include <string_view> 45 #include <tuple> 46 #include <vector> 47 48 extern sd_bus* bus; 49 50 constexpr auto bmc_state_interface = "xyz.openbmc_project.State.BMC"; 51 constexpr auto bmc_state_property = "CurrentBMCState"; 52 53 static constexpr auto redundancyIntf = 54 "xyz.openbmc_project.Software.RedundancyPriority"; 55 static constexpr auto versionIntf = "xyz.openbmc_project.Software.Version"; 56 static constexpr auto activationIntf = 57 "xyz.openbmc_project.Software.Activation"; 58 static constexpr auto softwareRoot = "/xyz/openbmc_project/software"; 59 60 void register_netfn_app_functions() __attribute__((constructor)); 61 62 using namespace phosphor::logging; 63 using namespace sdbusplus::xyz::openbmc_project::Common::Error; 64 using Version = sdbusplus::xyz::openbmc_project::Software::server::Version; 65 using Activation = 66 sdbusplus::xyz::openbmc_project::Software::server::Activation; 67 using BMC = sdbusplus::xyz::openbmc_project::State::server::BMC; 68 namespace fs = std::filesystem; 69 70 #ifdef ENABLE_I2C_WHITELIST_CHECK 71 typedef struct 72 { 73 uint8_t busId; 74 uint8_t slaveAddr; 75 uint8_t slaveAddrMask; 76 std::vector<uint8_t> data; 77 std::vector<uint8_t> dataMask; 78 } i2cMasterWRWhitelist; 79 80 static std::vector<i2cMasterWRWhitelist>& getWRWhitelist() 81 { 82 static std::vector<i2cMasterWRWhitelist> wrWhitelist; 83 return wrWhitelist; 84 } 85 86 static constexpr const char* i2cMasterWRWhitelistFile = 87 "/usr/share/ipmi-providers/master_write_read_white_list.json"; 88 89 static constexpr const char* filtersStr = "filters"; 90 static constexpr const char* busIdStr = "busId"; 91 static constexpr const char* slaveAddrStr = "slaveAddr"; 92 static constexpr const char* slaveAddrMaskStr = "slaveAddrMask"; 93 static constexpr const char* cmdStr = "command"; 94 static constexpr const char* cmdMaskStr = "commandMask"; 95 static constexpr int base_16 = 16; 96 #endif // ENABLE_I2C_WHITELIST_CHECK 97 static constexpr uint8_t maxIPMIWriteReadSize = 255; 98 static constexpr uint8_t oemCmdStart = 192; 99 static constexpr uint8_t oemCmdEnd = 255; 100 static constexpr uint8_t invalidParamSelectorStart = 8; 101 static constexpr uint8_t invalidParamSelectorEnd = 191; 102 103 /** 104 * @brief Returns the Version info from primary s/w object 105 * 106 * Get the Version info from the active s/w object which is having high 107 * "Priority" value(a smaller number is a higher priority) and "Purpose" 108 * is "BMC" from the list of all s/w objects those are implementing 109 * RedundancyPriority interface from the given softwareRoot path. 110 * 111 * @return On success returns the Version info from primary s/w object. 112 * 113 */ 114 std::string getActiveSoftwareVersionInfo(ipmi::Context::ptr ctx) 115 { 116 std::string revision{}; 117 ipmi::ObjectTree objectTree; 118 try 119 { 120 objectTree = ipmi::getAllDbusObjects(*ctx->bus, softwareRoot, 121 redundancyIntf); 122 } 123 catch (const sdbusplus::exception_t& e) 124 { 125 log<level::ERR>("Failed to fetch redundancy object from dbus", 126 entry("INTERFACE=%s", redundancyIntf), 127 entry("ERRMSG=%s", e.what())); 128 elog<InternalFailure>(); 129 } 130 131 auto objectFound = false; 132 for (auto& softObject : objectTree) 133 { 134 auto service = ipmi::getService(*ctx->bus, redundancyIntf, 135 softObject.first); 136 auto objValueTree = ipmi::getManagedObjects(*ctx->bus, service, 137 softwareRoot); 138 139 auto minPriority = 0xFF; 140 for (const auto& objIter : objValueTree) 141 { 142 try 143 { 144 auto& intfMap = objIter.second; 145 auto& redundancyPriorityProps = intfMap.at(redundancyIntf); 146 auto& versionProps = intfMap.at(versionIntf); 147 auto& activationProps = intfMap.at(activationIntf); 148 auto priority = 149 std::get<uint8_t>(redundancyPriorityProps.at("Priority")); 150 auto purpose = 151 std::get<std::string>(versionProps.at("Purpose")); 152 auto activation = 153 std::get<std::string>(activationProps.at("Activation")); 154 auto version = 155 std::get<std::string>(versionProps.at("Version")); 156 if ((Version::convertVersionPurposeFromString(purpose) == 157 Version::VersionPurpose::BMC) && 158 (Activation::convertActivationsFromString(activation) == 159 Activation::Activations::Active)) 160 { 161 if (priority < minPriority) 162 { 163 minPriority = priority; 164 objectFound = true; 165 revision = std::move(version); 166 } 167 } 168 } 169 catch (const std::exception& e) 170 { 171 log<level::ERR>(e.what()); 172 } 173 } 174 } 175 176 if (!objectFound) 177 { 178 log<level::ERR>("Could not found an BMC software Object"); 179 elog<InternalFailure>(); 180 } 181 182 return revision; 183 } 184 185 bool getCurrentBmcState() 186 { 187 sdbusplus::bus_t bus{ipmid_get_sd_bus_connection()}; 188 189 // Get the Inventory object implementing the BMC interface 190 ipmi::DbusObjectInfo bmcObject = ipmi::getDbusObject(bus, 191 bmc_state_interface); 192 auto variant = ipmi::getDbusProperty(bus, bmcObject.second, bmcObject.first, 193 bmc_state_interface, 194 bmc_state_property); 195 196 return std::holds_alternative<std::string>(variant) && 197 BMC::convertBMCStateFromString(std::get<std::string>(variant)) == 198 BMC::BMCState::Ready; 199 } 200 201 bool getCurrentBmcStateWithFallback(const bool fallbackAvailability) 202 { 203 try 204 { 205 return getCurrentBmcState(); 206 } 207 catch (...) 208 { 209 // Nothing provided the BMC interface, therefore return whatever was 210 // configured as the default. 211 return fallbackAvailability; 212 } 213 } 214 215 namespace acpi_state 216 { 217 using namespace sdbusplus::xyz::openbmc_project::Control::Power::server; 218 219 const static constexpr char* acpiObjPath = 220 "/xyz/openbmc_project/control/host0/acpi_power_state"; 221 const static constexpr char* acpiInterface = 222 "xyz.openbmc_project.Control.Power.ACPIPowerState"; 223 const static constexpr char* sysACPIProp = "SysACPIStatus"; 224 const static constexpr char* devACPIProp = "DevACPIStatus"; 225 226 enum class PowerStateType : uint8_t 227 { 228 sysPowerState = 0x00, 229 devPowerState = 0x01, 230 }; 231 232 // Defined in 20.6 of ipmi doc 233 enum class PowerState : uint8_t 234 { 235 s0G0D0 = 0x00, 236 s1D1 = 0x01, 237 s2D2 = 0x02, 238 s3D3 = 0x03, 239 s4 = 0x04, 240 s5G2 = 0x05, 241 s4S5 = 0x06, 242 g3 = 0x07, 243 sleep = 0x08, 244 g1Sleep = 0x09, 245 override = 0x0a, 246 legacyOn = 0x20, 247 legacyOff = 0x21, 248 unknown = 0x2a, 249 noChange = 0x7f, 250 }; 251 252 static constexpr uint8_t stateChanged = 0x80; 253 254 std::map<ACPIPowerState::ACPI, PowerState> dbusToIPMI = { 255 {ACPIPowerState::ACPI::S0_G0_D0, PowerState::s0G0D0}, 256 {ACPIPowerState::ACPI::S1_D1, PowerState::s1D1}, 257 {ACPIPowerState::ACPI::S2_D2, PowerState::s2D2}, 258 {ACPIPowerState::ACPI::S3_D3, PowerState::s3D3}, 259 {ACPIPowerState::ACPI::S4, PowerState::s4}, 260 {ACPIPowerState::ACPI::S5_G2, PowerState::s5G2}, 261 {ACPIPowerState::ACPI::S4_S5, PowerState::s4S5}, 262 {ACPIPowerState::ACPI::G3, PowerState::g3}, 263 {ACPIPowerState::ACPI::SLEEP, PowerState::sleep}, 264 {ACPIPowerState::ACPI::G1_SLEEP, PowerState::g1Sleep}, 265 {ACPIPowerState::ACPI::OVERRIDE, PowerState::override}, 266 {ACPIPowerState::ACPI::LEGACY_ON, PowerState::legacyOn}, 267 {ACPIPowerState::ACPI::LEGACY_OFF, PowerState::legacyOff}, 268 {ACPIPowerState::ACPI::Unknown, PowerState::unknown}}; 269 270 bool isValidACPIState(acpi_state::PowerStateType type, uint8_t state) 271 { 272 if (type == acpi_state::PowerStateType::sysPowerState) 273 { 274 if ((state <= static_cast<uint8_t>(acpi_state::PowerState::override)) || 275 (state == static_cast<uint8_t>(acpi_state::PowerState::legacyOn)) || 276 (state == 277 static_cast<uint8_t>(acpi_state::PowerState::legacyOff)) || 278 (state == static_cast<uint8_t>(acpi_state::PowerState::unknown)) || 279 (state == static_cast<uint8_t>(acpi_state::PowerState::noChange))) 280 { 281 return true; 282 } 283 else 284 { 285 return false; 286 } 287 } 288 else if (type == acpi_state::PowerStateType::devPowerState) 289 { 290 if ((state <= static_cast<uint8_t>(acpi_state::PowerState::s3D3)) || 291 (state == static_cast<uint8_t>(acpi_state::PowerState::unknown)) || 292 (state == static_cast<uint8_t>(acpi_state::PowerState::noChange))) 293 { 294 return true; 295 } 296 else 297 { 298 return false; 299 } 300 } 301 else 302 { 303 return false; 304 } 305 return false; 306 } 307 } // namespace acpi_state 308 309 /** @brief implements Set ACPI Power State command 310 * @param sysAcpiState - ACPI system power state to set 311 * @param devAcpiState - ACPI device power state to set 312 * 313 * @return IPMI completion code on success 314 **/ 315 ipmi::RspType<> ipmiSetAcpiPowerState(uint8_t sysAcpiState, 316 uint8_t devAcpiState) 317 { 318 auto s = static_cast<uint8_t>(acpi_state::PowerState::unknown); 319 320 sdbusplus::bus_t bus{ipmid_get_sd_bus_connection()}; 321 322 auto value = acpi_state::ACPIPowerState::ACPI::Unknown; 323 324 if (sysAcpiState & acpi_state::stateChanged) 325 { 326 // set system power state 327 s = sysAcpiState & ~acpi_state::stateChanged; 328 329 if (!acpi_state::isValidACPIState( 330 acpi_state::PowerStateType::sysPowerState, s)) 331 { 332 log<level::ERR>("set_acpi_power sys invalid input", 333 entry("S=%x", s)); 334 return ipmi::responseParmOutOfRange(); 335 } 336 337 // valid input 338 if (s == static_cast<uint8_t>(acpi_state::PowerState::noChange)) 339 { 340 log<level::DEBUG>("No change for system power state"); 341 } 342 else 343 { 344 auto found = std::find_if(acpi_state::dbusToIPMI.begin(), 345 acpi_state::dbusToIPMI.end(), 346 [&s](const auto& iter) { 347 return (static_cast<uint8_t>(iter.second) == s); 348 }); 349 350 value = found->first; 351 352 try 353 { 354 auto acpiObject = 355 ipmi::getDbusObject(bus, acpi_state::acpiInterface); 356 ipmi::setDbusProperty(bus, acpiObject.second, acpiObject.first, 357 acpi_state::acpiInterface, 358 acpi_state::sysACPIProp, 359 convertForMessage(value)); 360 } 361 catch (const InternalFailure& e) 362 { 363 log<level::ERR>("Failed in set ACPI system property", 364 entry("EXCEPTION=%s", e.what())); 365 return ipmi::responseUnspecifiedError(); 366 } 367 } 368 } 369 else 370 { 371 log<level::DEBUG>("Do not change system power state"); 372 } 373 374 if (devAcpiState & acpi_state::stateChanged) 375 { 376 // set device power state 377 s = devAcpiState & ~acpi_state::stateChanged; 378 if (!acpi_state::isValidACPIState( 379 acpi_state::PowerStateType::devPowerState, s)) 380 { 381 log<level::ERR>("set_acpi_power dev invalid input", 382 entry("S=%x", s)); 383 return ipmi::responseParmOutOfRange(); 384 } 385 386 // valid input 387 if (s == static_cast<uint8_t>(acpi_state::PowerState::noChange)) 388 { 389 log<level::DEBUG>("No change for device power state"); 390 } 391 else 392 { 393 auto found = std::find_if(acpi_state::dbusToIPMI.begin(), 394 acpi_state::dbusToIPMI.end(), 395 [&s](const auto& iter) { 396 return (static_cast<uint8_t>(iter.second) == s); 397 }); 398 399 value = found->first; 400 401 try 402 { 403 auto acpiObject = 404 ipmi::getDbusObject(bus, acpi_state::acpiInterface); 405 ipmi::setDbusProperty(bus, acpiObject.second, acpiObject.first, 406 acpi_state::acpiInterface, 407 acpi_state::devACPIProp, 408 convertForMessage(value)); 409 } 410 catch (const InternalFailure& e) 411 { 412 log<level::ERR>("Failed in set ACPI device property", 413 entry("EXCEPTION=%s", e.what())); 414 return ipmi::responseUnspecifiedError(); 415 } 416 } 417 } 418 else 419 { 420 log<level::DEBUG>("Do not change device power state"); 421 } 422 return ipmi::responseSuccess(); 423 } 424 425 /** 426 * @brief implements the get ACPI power state command 427 * 428 * @return IPMI completion code plus response data on success. 429 * - ACPI system power state 430 * - ACPI device power state 431 **/ 432 ipmi::RspType<uint8_t, // acpiSystemPowerState 433 uint8_t // acpiDevicePowerState 434 > 435 ipmiGetAcpiPowerState() 436 { 437 uint8_t sysAcpiState; 438 uint8_t devAcpiState; 439 440 sdbusplus::bus_t bus{ipmid_get_sd_bus_connection()}; 441 442 try 443 { 444 auto acpiObject = ipmi::getDbusObject(bus, acpi_state::acpiInterface); 445 446 auto sysACPIVal = ipmi::getDbusProperty( 447 bus, acpiObject.second, acpiObject.first, acpi_state::acpiInterface, 448 acpi_state::sysACPIProp); 449 auto sysACPI = acpi_state::ACPIPowerState::convertACPIFromString( 450 std::get<std::string>(sysACPIVal)); 451 sysAcpiState = static_cast<uint8_t>(acpi_state::dbusToIPMI.at(sysACPI)); 452 453 auto devACPIVal = ipmi::getDbusProperty( 454 bus, acpiObject.second, acpiObject.first, acpi_state::acpiInterface, 455 acpi_state::devACPIProp); 456 auto devACPI = acpi_state::ACPIPowerState::convertACPIFromString( 457 std::get<std::string>(devACPIVal)); 458 devAcpiState = static_cast<uint8_t>(acpi_state::dbusToIPMI.at(devACPI)); 459 } 460 catch (const InternalFailure& e) 461 { 462 return ipmi::responseUnspecifiedError(); 463 } 464 465 return ipmi::responseSuccess(sysAcpiState, devAcpiState); 466 } 467 468 typedef struct 469 { 470 char major; 471 char minor; 472 uint8_t aux[4]; 473 } Revision; 474 475 /* Use regular expression searching matched pattern X.Y, and convert it to */ 476 /* Major (X) and Minor (Y) version. */ 477 /* Example: */ 478 /* version = 2.14.0-dev */ 479 /* ^ ^ */ 480 /* | |---------------- Minor */ 481 /* |------------------ Major */ 482 /* */ 483 /* Default regex string only tries to match Major and Minor version. */ 484 /* */ 485 /* To match more firmware version info, platforms need to define it own */ 486 /* regex string to match more strings, and assign correct mapping index in */ 487 /* matches array. */ 488 /* */ 489 /* matches[0]: matched index for major ver */ 490 /* matches[1]: matched index for minor ver */ 491 /* matches[2]: matched index for aux[0] (set 0 to skip) */ 492 /* matches[3]: matched index for aux[1] (set 0 to skip) */ 493 /* matches[4]: matched index for aux[2] (set 0 to skip) */ 494 /* matches[5]: matched index for aux[3] (set 0 to skip) */ 495 /* Example: */ 496 /* regex = "([\d]+).([\d]+).([\d]+)-dev-([\d]+)-g([0-9a-fA-F]{2}) */ 497 /* ([0-9a-fA-F]{2})([0-9a-fA-F]{2})([0-9a-fA-F]{2})" */ 498 /* matches = {1,2,5,6,7,8} */ 499 /* version = 2.14.0-dev-750-g37a7c5ad1-dirty */ 500 /* ^ ^ ^ ^ ^ ^ ^ ^ */ 501 /* | | | | | | | | */ 502 /* | | | | | | | |-- Aux byte 3 (0xAD), index 8 */ 503 /* | | | | | | |---- Aux byte 2 (0xC5), index 7 */ 504 /* | | | | | |------ Aux byte 1 (0xA7), index 6 */ 505 /* | | | | |-------- Aux byte 0 (0x37), index 5 */ 506 /* | | | |------------- Not used, index 4 */ 507 /* | | |------------------- Not used, index 3 */ 508 /* | |---------------------- Minor (14), index 2 */ 509 /* |------------------------ Major (2), index 1 */ 510 int convertVersion(std::string s, Revision& rev) 511 { 512 static const std::vector<size_t> matches = { 513 MAJOR_MATCH_INDEX, MINOR_MATCH_INDEX, AUX_0_MATCH_INDEX, 514 AUX_1_MATCH_INDEX, AUX_2_MATCH_INDEX, AUX_3_MATCH_INDEX}; 515 std::regex fw_regex(FW_VER_REGEX); 516 std::smatch m; 517 Revision r = {0}; 518 size_t val; 519 520 if (std::regex_search(s, m, fw_regex)) 521 { 522 if (m.size() < *std::max_element(matches.begin(), matches.end())) 523 { // max index higher than match count 524 return -1; 525 } 526 527 // convert major 528 { 529 std::string_view str = m[matches[0]].str(); 530 auto [ptr, ec]{std::from_chars(str.begin(), str.end(), val)}; 531 if (ec != std::errc() || ptr != str.begin() + str.size()) 532 { // failed to convert major string 533 return -1; 534 } 535 r.major = val & 0x7F; 536 } 537 538 // convert minor 539 { 540 std::string_view str = m[matches[1]].str(); 541 auto [ptr, ec]{std::from_chars(str.begin(), str.end(), val)}; 542 if (ec != std::errc() || ptr != str.begin() + str.size()) 543 { // failed to convert minor string 544 return -1; 545 } 546 r.minor = val & 0xFF; 547 } 548 549 // convert aux bytes 550 { 551 size_t i; 552 for (i = 0; i < 4; i++) 553 { 554 if (matches[i + 2] == 0) 555 { 556 continue; 557 } 558 559 std::string_view str = m[matches[i + 2]].str(); 560 auto [ptr, 561 ec]{std::from_chars(str.begin(), str.end(), val, 16)}; 562 if (ec != std::errc() || ptr != str.begin() + str.size()) 563 { // failed to convert aux byte string 564 break; 565 } 566 567 r.aux[i] = val & 0xFF; 568 } 569 570 if (i != 4) 571 { // something wrong durign converting aux bytes 572 return -1; 573 } 574 } 575 576 // all matched 577 rev = r; 578 return 0; 579 } 580 581 return -1; 582 } 583 584 /* @brief: Implement the Get Device ID IPMI command per the IPMI spec 585 * @param[in] ctx - shared_ptr to an IPMI context struct 586 * 587 * @returns IPMI completion code plus response data 588 * - Device ID (manufacturer defined) 589 * - Device revision[4 bits]; reserved[3 bits]; SDR support[1 bit] 590 * - FW revision major[7 bits] (binary encoded); available[1 bit] 591 * - FW Revision minor (BCD encoded) 592 * - IPMI version (0x02 for IPMI 2.0) 593 * - device support (bitfield of supported options) 594 * - MFG IANA ID (3 bytes) 595 * - product ID (2 bytes) 596 * - AUX info (4 bytes) 597 */ 598 ipmi::RspType<uint8_t, // Device ID 599 uint8_t, // Device Revision 600 uint8_t, // Firmware Revision Major 601 uint8_t, // Firmware Revision minor 602 uint8_t, // IPMI version 603 uint8_t, // Additional device support 604 uint24_t, // MFG ID 605 uint16_t, // Product ID 606 uint32_t // AUX info 607 > 608 ipmiAppGetDeviceId([[maybe_unused]] ipmi::Context::ptr ctx) 609 { 610 static struct 611 { 612 uint8_t id; 613 uint8_t revision; 614 uint8_t fw[2]; 615 uint8_t ipmiVer; 616 uint8_t addnDevSupport; 617 uint24_t manufId; 618 uint16_t prodId; 619 uint32_t aux; 620 } devId; 621 static bool dev_id_initialized = false; 622 static bool defaultActivationSetting = true; 623 const char* filename = "/usr/share/ipmi-providers/dev_id.json"; 624 constexpr auto ipmiDevIdStateShift = 7; 625 constexpr auto ipmiDevIdFw1Mask = ~(1 << ipmiDevIdStateShift); 626 627 #ifdef GET_DBUS_ACTIVE_SOFTWARE 628 static bool haveBMCVersion = false; 629 if (!haveBMCVersion || !dev_id_initialized) 630 { 631 int r = -1; 632 Revision rev = {0, 0, 0, 0}; 633 try 634 { 635 auto version = getActiveSoftwareVersionInfo(ctx); 636 r = convertVersion(version, rev); 637 } 638 catch (const std::exception& e) 639 { 640 log<level::ERR>(e.what()); 641 } 642 643 if (r >= 0) 644 { 645 // bit7 identifies if the device is available 646 // 0=normal operation 647 // 1=device firmware, SDR update, 648 // or self-initialization in progress. 649 // The availability may change in run time, so mask here 650 // and initialize later. 651 devId.fw[0] = rev.major & ipmiDevIdFw1Mask; 652 653 rev.minor = (rev.minor > 99 ? 99 : rev.minor); 654 devId.fw[1] = rev.minor % 10 + (rev.minor / 10) * 16; 655 std::memcpy(&devId.aux, rev.aux, sizeof(rev.aux)); 656 haveBMCVersion = true; 657 } 658 } 659 #endif 660 if (!dev_id_initialized) 661 { 662 // IPMI Spec version 2.0 663 devId.ipmiVer = 2; 664 665 std::ifstream devIdFile(filename); 666 if (devIdFile.is_open()) 667 { 668 auto data = nlohmann::json::parse(devIdFile, nullptr, false); 669 if (!data.is_discarded()) 670 { 671 devId.id = data.value("id", 0); 672 devId.revision = data.value("revision", 0); 673 devId.addnDevSupport = data.value("addn_dev_support", 0); 674 devId.manufId = data.value("manuf_id", 0); 675 devId.prodId = data.value("prod_id", 0); 676 devId.aux = data.value("aux", 0); 677 678 if (data.contains("firmware_revision")) 679 { 680 const auto& firmwareRevision = data.at("firmware_revision"); 681 if (firmwareRevision.contains("major")) 682 { 683 firmwareRevision.at("major").get_to(devId.fw[0]); 684 } 685 if (firmwareRevision.contains("minor")) 686 { 687 firmwareRevision.at("minor").get_to(devId.fw[1]); 688 } 689 } 690 691 // Set the availablitity of the BMC. 692 defaultActivationSetting = data.value("availability", true); 693 694 // Don't read the file every time if successful 695 dev_id_initialized = true; 696 } 697 else 698 { 699 log<level::ERR>("Device ID JSON parser failure"); 700 return ipmi::responseUnspecifiedError(); 701 } 702 } 703 else 704 { 705 log<level::ERR>("Device ID file not found"); 706 return ipmi::responseUnspecifiedError(); 707 } 708 } 709 710 // Set availability to the actual current BMC state 711 devId.fw[0] &= ipmiDevIdFw1Mask; 712 if (!getCurrentBmcStateWithFallback(defaultActivationSetting)) 713 { 714 devId.fw[0] |= (1 << ipmiDevIdStateShift); 715 } 716 717 return ipmi::responseSuccess( 718 devId.id, devId.revision, devId.fw[0], devId.fw[1], devId.ipmiVer, 719 devId.addnDevSupport, devId.manufId, devId.prodId, devId.aux); 720 } 721 722 auto ipmiAppGetSelfTestResults() -> ipmi::RspType<uint8_t, uint8_t> 723 { 724 // Byte 2: 725 // 55h - No error. 726 // 56h - Self Test function not implemented in this controller. 727 // 57h - Corrupted or inaccesssible data or devices. 728 // 58h - Fatal hardware error. 729 // FFh - reserved. 730 // all other: Device-specific 'internal failure'. 731 // Byte 3: 732 // For byte 2 = 55h, 56h, FFh: 00h 733 // For byte 2 = 58h, all other: Device-specific 734 // For byte 2 = 57h: self-test error bitfield. 735 // Note: returning 57h does not imply that all test were run. 736 // [7] 1b = Cannot access SEL device. 737 // [6] 1b = Cannot access SDR Repository. 738 // [5] 1b = Cannot access BMC FRU device. 739 // [4] 1b = IPMB signal lines do not respond. 740 // [3] 1b = SDR Repository empty. 741 // [2] 1b = Internal Use Area of BMC FRU corrupted. 742 // [1] 1b = controller update 'boot block' firmware corrupted. 743 // [0] 1b = controller operational firmware corrupted. 744 constexpr uint8_t notImplemented = 0x56; 745 constexpr uint8_t zero = 0; 746 return ipmi::responseSuccess(notImplemented, zero); 747 } 748 749 static constexpr size_t uuidBinaryLength = 16; 750 static std::array<uint8_t, uuidBinaryLength> rfc4122ToIpmi(std::string rfc4122) 751 { 752 using Argument = xyz::openbmc_project::Common::InvalidArgument; 753 // UUID is in RFC4122 format. Ex: 61a39523-78f2-11e5-9862-e6402cfc3223 754 // Per IPMI Spec 2.0 need to convert to 16 hex bytes and reverse the byte 755 // order 756 // Ex: 0x2332fc2c40e66298e511f2782395a361 757 constexpr size_t uuidHexLength = (2 * uuidBinaryLength); 758 constexpr size_t uuidRfc4122Length = (uuidHexLength + 4); 759 std::array<uint8_t, uuidBinaryLength> uuid; 760 if (rfc4122.size() == uuidRfc4122Length) 761 { 762 rfc4122.erase(std::remove(rfc4122.begin(), rfc4122.end(), '-'), 763 rfc4122.end()); 764 } 765 if (rfc4122.size() != uuidHexLength) 766 { 767 elog<InvalidArgument>(Argument::ARGUMENT_NAME("rfc4122"), 768 Argument::ARGUMENT_VALUE(rfc4122.c_str())); 769 } 770 for (size_t ind = 0; ind < uuidHexLength; ind += 2) 771 { 772 char v[3]; 773 v[0] = rfc4122[ind]; 774 v[1] = rfc4122[ind + 1]; 775 v[2] = 0; 776 size_t err; 777 long b; 778 try 779 { 780 b = std::stoul(v, &err, 16); 781 } 782 catch (const std::exception& e) 783 { 784 elog<InvalidArgument>(Argument::ARGUMENT_NAME("rfc4122"), 785 Argument::ARGUMENT_VALUE(rfc4122.c_str())); 786 } 787 // check that exactly two ascii bytes were converted 788 if (err != 2) 789 { 790 elog<InvalidArgument>(Argument::ARGUMENT_NAME("rfc4122"), 791 Argument::ARGUMENT_VALUE(rfc4122.c_str())); 792 } 793 uuid[uuidBinaryLength - (ind / 2) - 1] = static_cast<uint8_t>(b); 794 } 795 return uuid; 796 } 797 798 auto ipmiAppGetDeviceGuid() 799 -> ipmi::RspType<std::array<uint8_t, uuidBinaryLength>> 800 { 801 // return a fixed GUID based on /etc/machine-id 802 // This should match the /redfish/v1/Managers/bmc's UUID data 803 804 // machine specific application ID (for BMC ID) 805 // generated by systemd-id128 -p new as per man page 806 static constexpr sd_id128_t bmcUuidAppId = SD_ID128_MAKE( 807 e0, e1, 73, 76, 64, 61, 47, da, a5, 0c, d0, cc, 64, 12, 45, 78); 808 809 sd_id128_t bmcUuid; 810 // create the UUID from /etc/machine-id via the systemd API 811 sd_id128_get_machine_app_specific(bmcUuidAppId, &bmcUuid); 812 813 char bmcUuidCstr[SD_ID128_STRING_MAX]; 814 std::string systemUuid = sd_id128_to_string(bmcUuid, bmcUuidCstr); 815 816 std::array<uint8_t, uuidBinaryLength> uuid = rfc4122ToIpmi(systemUuid); 817 return ipmi::responseSuccess(uuid); 818 } 819 820 auto ipmiAppGetBtCapabilities() 821 -> ipmi::RspType<uint8_t, uint8_t, uint8_t, uint8_t, uint8_t> 822 { 823 // Per IPMI 2.0 spec, the input and output buffer size must be the max 824 // buffer size minus one byte to allocate space for the length byte. 825 constexpr uint8_t nrOutstanding = 0x01; 826 constexpr uint8_t inputBufferSize = MAX_IPMI_BUFFER - 1; 827 constexpr uint8_t outputBufferSize = MAX_IPMI_BUFFER - 1; 828 constexpr uint8_t transactionTime = 0x0A; 829 constexpr uint8_t nrRetries = 0x01; 830 831 return ipmi::responseSuccess(nrOutstanding, inputBufferSize, 832 outputBufferSize, transactionTime, nrRetries); 833 } 834 835 auto ipmiAppGetSystemGuid() -> ipmi::RspType<std::array<uint8_t, 16>> 836 { 837 static constexpr auto uuidInterface = "xyz.openbmc_project.Common.UUID"; 838 static constexpr auto uuidProperty = "UUID"; 839 840 ipmi::Value propValue; 841 try 842 { 843 // Get the Inventory object implementing BMC interface 844 auto busPtr = getSdBus(); 845 auto objectInfo = ipmi::getDbusObject(*busPtr, uuidInterface); 846 847 // Read UUID property value from bmcObject 848 // UUID is in RFC4122 format Ex: 61a39523-78f2-11e5-9862-e6402cfc3223 849 propValue = ipmi::getDbusProperty(*busPtr, objectInfo.second, 850 objectInfo.first, uuidInterface, 851 uuidProperty); 852 } 853 catch (const InternalFailure& e) 854 { 855 log<level::ERR>("Failed in reading BMC UUID property", 856 entry("INTERFACE=%s", uuidInterface), 857 entry("PROPERTY=%s", uuidProperty)); 858 return ipmi::responseUnspecifiedError(); 859 } 860 std::array<uint8_t, 16> uuid; 861 std::string rfc4122Uuid = std::get<std::string>(propValue); 862 try 863 { 864 // convert to IPMI format 865 uuid = rfc4122ToIpmi(rfc4122Uuid); 866 } 867 catch (const InvalidArgument& e) 868 { 869 log<level::ERR>("Failed in parsing BMC UUID property", 870 entry("INTERFACE=%s", uuidInterface), 871 entry("PROPERTY=%s", uuidProperty), 872 entry("VALUE=%s", rfc4122Uuid.c_str())); 873 return ipmi::responseUnspecifiedError(); 874 } 875 return ipmi::responseSuccess(uuid); 876 } 877 878 /** 879 * @brief set the session state as teardown 880 * 881 * This function is to set the session state to tear down in progress if the 882 * state is active. 883 * 884 * @param[in] busp - Dbus obj 885 * @param[in] service - service name 886 * @param[in] obj - object path 887 * 888 * @return success completion code if it sets the session state to 889 * tearDownInProgress else return the corresponding error completion code. 890 **/ 891 uint8_t setSessionState(std::shared_ptr<sdbusplus::asio::connection>& busp, 892 const std::string& service, const std::string& obj) 893 { 894 try 895 { 896 uint8_t sessionState = std::get<uint8_t>(ipmi::getDbusProperty( 897 *busp, service, obj, session::sessionIntf, "State")); 898 899 if (sessionState == static_cast<uint8_t>(session::State::active)) 900 { 901 ipmi::setDbusProperty( 902 *busp, service, obj, session::sessionIntf, "State", 903 static_cast<uint8_t>(session::State::tearDownInProgress)); 904 return ipmi::ccSuccess; 905 } 906 } 907 catch (const std::exception& e) 908 { 909 log<level::ERR>("Failed in getting session state property", 910 entry("service=%s", service.c_str()), 911 entry("object path=%s", obj.c_str()), 912 entry("interface=%s", session::sessionIntf)); 913 return ipmi::ccUnspecifiedError; 914 } 915 916 return ipmi::ccInvalidFieldRequest; 917 } 918 919 ipmi::RspType<> ipmiAppCloseSession(uint32_t reqSessionId, 920 std::optional<uint8_t> requestSessionHandle) 921 { 922 auto busp = getSdBus(); 923 uint8_t reqSessionHandle = 924 requestSessionHandle.value_or(session::defaultSessionHandle); 925 926 if (reqSessionId == session::sessionZero && 927 reqSessionHandle == session::defaultSessionHandle) 928 { 929 return ipmi::response(session::ccInvalidSessionId); 930 } 931 932 if (reqSessionId == session::sessionZero && 933 reqSessionHandle == session::invalidSessionHandle) 934 { 935 return ipmi::response(session::ccInvalidSessionHandle); 936 } 937 938 if (reqSessionId != session::sessionZero && 939 reqSessionHandle != session::defaultSessionHandle) 940 { 941 return ipmi::response(ipmi::ccInvalidFieldRequest); 942 } 943 944 try 945 { 946 ipmi::ObjectTree objectTree = ipmi::getAllDbusObjects( 947 *busp, session::sessionManagerRootPath, session::sessionIntf); 948 949 for (auto& objectTreeItr : objectTree) 950 { 951 const std::string obj = objectTreeItr.first; 952 953 if (isSessionObjectMatched(obj, reqSessionId, reqSessionHandle)) 954 { 955 auto& serviceMap = objectTreeItr.second; 956 957 // Session id and session handle are unique for each session. 958 // Session id and handler are retrived from the object path and 959 // object path will be unique for each session. Checking if 960 // multiple objects exist with same object path under multiple 961 // services. 962 if (serviceMap.size() != 1) 963 { 964 return ipmi::responseUnspecifiedError(); 965 } 966 967 auto itr = serviceMap.begin(); 968 const std::string service = itr->first; 969 return ipmi::response(setSessionState(busp, service, obj)); 970 } 971 } 972 } 973 catch (const sdbusplus::exception_t& e) 974 { 975 log<level::ERR>("Failed to fetch object from dbus", 976 entry("INTERFACE=%s", session::sessionIntf), 977 entry("ERRMSG=%s", e.what())); 978 return ipmi::responseUnspecifiedError(); 979 } 980 981 return ipmi::responseInvalidFieldRequest(); 982 } 983 984 uint8_t getTotalSessionCount() 985 { 986 uint8_t count = 0, ch = 0; 987 988 while (ch < ipmi::maxIpmiChannels && 989 count < session::maxNetworkInstanceSupported) 990 { 991 ipmi::ChannelInfo chInfo{}; 992 ipmi::getChannelInfo(ch, chInfo); 993 if (static_cast<ipmi::EChannelMediumType>(chInfo.mediumType) == 994 ipmi::EChannelMediumType::lan8032) 995 { 996 count++; 997 } 998 ch++; 999 } 1000 return count * session::maxSessionCountPerChannel; 1001 } 1002 1003 /** 1004 * @brief get session info request data. 1005 * 1006 * This function validates the request data and retrive request session id, 1007 * session handle. 1008 * 1009 * @param[in] ctx - context of current session. 1010 * @param[in] sessionIndex - request session index 1011 * @param[in] payload - input payload 1012 * @param[in] reqSessionId - unpacked session Id will be asigned 1013 * @param[in] reqSessionHandle - unpacked session handle will be asigned 1014 * 1015 * @return success completion code if request data is valid 1016 * else return the correcponding error completion code. 1017 **/ 1018 uint8_t getSessionInfoRequestData(const ipmi::Context::ptr ctx, 1019 const uint8_t sessionIndex, 1020 ipmi::message::Payload& payload, 1021 uint32_t& reqSessionId, 1022 uint8_t& reqSessionHandle) 1023 { 1024 if ((sessionIndex > session::maxSessionCountPerChannel) && 1025 (sessionIndex < session::searchSessionByHandle)) 1026 { 1027 return ipmi::ccInvalidFieldRequest; 1028 } 1029 1030 switch (sessionIndex) 1031 { 1032 case session::searchCurrentSession: 1033 1034 ipmi::ChannelInfo chInfo; 1035 ipmi::getChannelInfo(ctx->channel, chInfo); 1036 1037 if (static_cast<ipmi::EChannelMediumType>(chInfo.mediumType) != 1038 ipmi::EChannelMediumType::lan8032) 1039 { 1040 return ipmi::ccInvalidFieldRequest; 1041 } 1042 1043 if (!payload.fullyUnpacked()) 1044 { 1045 return ipmi::ccReqDataLenInvalid; 1046 } 1047 // Check if current sessionId is 0, sessionId 0 is reserved. 1048 if (ctx->sessionId == session::sessionZero) 1049 { 1050 return session::ccInvalidSessionId; 1051 } 1052 reqSessionId = ctx->sessionId; 1053 break; 1054 1055 case session::searchSessionByHandle: 1056 1057 if ((payload.unpack(reqSessionHandle)) || 1058 (!payload.fullyUnpacked())) 1059 { 1060 return ipmi::ccReqDataLenInvalid; 1061 } 1062 1063 if ((reqSessionHandle == session::sessionZero) || 1064 ((reqSessionHandle & session::multiIntfaceSessionHandleMask) > 1065 session::maxSessionCountPerChannel)) 1066 { 1067 return session::ccInvalidSessionHandle; 1068 } 1069 break; 1070 1071 case session::searchSessionById: 1072 1073 if ((payload.unpack(reqSessionId)) || (!payload.fullyUnpacked())) 1074 { 1075 return ipmi::ccReqDataLenInvalid; 1076 } 1077 1078 if (reqSessionId == session::sessionZero) 1079 { 1080 return session::ccInvalidSessionId; 1081 } 1082 break; 1083 1084 default: 1085 if (!payload.fullyUnpacked()) 1086 { 1087 return ipmi::ccReqDataLenInvalid; 1088 } 1089 break; 1090 } 1091 return ipmi::ccSuccess; 1092 } 1093 1094 uint8_t getSessionState(ipmi::Context::ptr ctx, const std::string& service, 1095 const std::string& objPath, uint8_t& sessionState) 1096 { 1097 boost::system::error_code ec = ipmi::getDbusProperty( 1098 ctx, service, objPath, session::sessionIntf, "State", sessionState); 1099 if (ec) 1100 { 1101 log<level::ERR>("Failed to fetch state property ", 1102 entry("SERVICE=%s", service.c_str()), 1103 entry("OBJECTPATH=%s", objPath.c_str()), 1104 entry("INTERFACE=%s", session::sessionIntf), 1105 entry("ERRMSG=%s", ec.message().c_str())); 1106 return ipmi::ccUnspecifiedError; 1107 } 1108 return ipmi::ccSuccess; 1109 } 1110 1111 static constexpr uint8_t macAddrLen = 6; 1112 /** Alias SessionDetails - contain the optional information about an 1113 * RMCP+ session. 1114 * 1115 * @param userID - uint6_t session user ID (0-63) 1116 * @param reserved - uint2_t reserved 1117 * @param privilege - uint4_t session privilege (0-5) 1118 * @param reserved - uint4_t reserved 1119 * @param channel - uint4_t session channel number 1120 * @param protocol - uint4_t session protocol 1121 * @param remoteIP - uint32_t remote IP address 1122 * @param macAddr - std::array<uint8_t, 6> mac address 1123 * @param port - uint16_t remote port 1124 */ 1125 using SessionDetails = 1126 std::tuple<uint2_t, uint6_t, uint4_t, uint4_t, uint4_t, uint4_t, uint32_t, 1127 std::array<uint8_t, macAddrLen>, uint16_t>; 1128 1129 /** @brief get session details for a given session 1130 * 1131 * @param[in] ctx - ipmi::Context pointer for accessing D-Bus 1132 * @param[in] service - D-Bus service name to fetch details from 1133 * @param[in] objPath - D-Bus object path for session 1134 * @param[out] sessionHandle - return session handle for session 1135 * @param[out] sessionState - return session state for session 1136 * @param[out] details - return a SessionDetails tuple containing other 1137 * session info 1138 * @return - ipmi::Cc success or error code 1139 */ 1140 ipmi::Cc getSessionDetails(ipmi::Context::ptr ctx, const std::string& service, 1141 const std::string& objPath, uint8_t& sessionHandle, 1142 uint8_t& sessionState, SessionDetails& details) 1143 { 1144 ipmi::PropertyMap sessionProps; 1145 boost::system::error_code ec = ipmi::getAllDbusProperties( 1146 ctx, service, objPath, session::sessionIntf, sessionProps); 1147 1148 if (ec) 1149 { 1150 log<level::ERR>("Failed to fetch state property ", 1151 entry("SERVICE=%s", service.c_str()), 1152 entry("OBJECTPATH=%s", objPath.c_str()), 1153 entry("INTERFACE=%s", session::sessionIntf), 1154 entry("ERRMSG=%s", ec.message().c_str())); 1155 return ipmi::ccUnspecifiedError; 1156 } 1157 1158 sessionState = ipmi::mappedVariant<uint8_t>( 1159 sessionProps, "State", static_cast<uint8_t>(session::State::inactive)); 1160 if (sessionState == static_cast<uint8_t>(session::State::active)) 1161 { 1162 sessionHandle = ipmi::mappedVariant<uint8_t>(sessionProps, 1163 "SessionHandle", 0); 1164 std::get<0>(details) = ipmi::mappedVariant<uint8_t>(sessionProps, 1165 "UserID", 0xff); 1166 // std::get<1>(details) = 0; // (default constructed to 0) 1167 std::get<2>(details) = 1168 ipmi::mappedVariant<uint8_t>(sessionProps, "CurrentPrivilege", 0); 1169 // std::get<3>(details) = 0; // (default constructed to 0) 1170 std::get<4>(details) = ipmi::mappedVariant<uint8_t>(sessionProps, 1171 "ChannelNum", 0xff); 1172 constexpr uint4_t rmcpPlusProtocol = 1; 1173 std::get<5>(details) = rmcpPlusProtocol; 1174 std::get<6>(details) = ipmi::mappedVariant<uint32_t>(sessionProps, 1175 "RemoteIPAddr", 0); 1176 // std::get<7>(details) = {{0}}; // default constructed to all 0 1177 std::get<8>(details) = ipmi::mappedVariant<uint16_t>(sessionProps, 1178 "RemotePort", 0); 1179 } 1180 1181 return ipmi::ccSuccess; 1182 } 1183 1184 ipmi::RspType<uint8_t, // session handle, 1185 uint8_t, // total session count 1186 uint8_t, // active session count 1187 std::optional<SessionDetails>> 1188 ipmiAppGetSessionInfo(ipmi::Context::ptr ctx, uint8_t sessionIndex, 1189 ipmi::message::Payload& payload) 1190 { 1191 uint32_t reqSessionId = 0; 1192 uint8_t reqSessionHandle = session::defaultSessionHandle; 1193 // initializing state to 0xff as 0 represents state as inactive. 1194 uint8_t state = 0xFF; 1195 1196 uint8_t completionCode = getSessionInfoRequestData( 1197 ctx, sessionIndex, payload, reqSessionId, reqSessionHandle); 1198 1199 if (completionCode) 1200 { 1201 return ipmi::response(completionCode); 1202 } 1203 ipmi::ObjectTree objectTree; 1204 boost::system::error_code ec = ipmi::getAllDbusObjects( 1205 ctx, session::sessionManagerRootPath, session::sessionIntf, objectTree); 1206 if (ec) 1207 { 1208 log<level::ERR>("Failed to fetch object from dbus", 1209 entry("INTERFACE=%s", session::sessionIntf), 1210 entry("ERRMSG=%s", ec.message().c_str())); 1211 return ipmi::responseUnspecifiedError(); 1212 } 1213 1214 uint8_t totalSessionCount = getTotalSessionCount(); 1215 uint8_t activeSessionCount = 0; 1216 uint8_t sessionHandle = session::defaultSessionHandle; 1217 uint8_t activeSessionHandle = 0; 1218 std::optional<SessionDetails> maybeDetails; 1219 uint8_t index = 0; 1220 for (auto& objectTreeItr : objectTree) 1221 { 1222 uint32_t sessionId = 0; 1223 std::string objectPath = objectTreeItr.first; 1224 1225 if (!parseCloseSessionInputPayload(objectPath, sessionId, 1226 sessionHandle)) 1227 { 1228 continue; 1229 } 1230 index++; 1231 auto& serviceMap = objectTreeItr.second; 1232 auto itr = serviceMap.begin(); 1233 1234 if (serviceMap.size() != 1) 1235 { 1236 return ipmi::responseUnspecifiedError(); 1237 } 1238 1239 std::string service = itr->first; 1240 uint8_t sessionState = 0; 1241 completionCode = getSessionState(ctx, service, objectPath, 1242 sessionState); 1243 if (completionCode) 1244 { 1245 return ipmi::response(completionCode); 1246 } 1247 1248 if (sessionState == static_cast<uint8_t>(session::State::active)) 1249 { 1250 activeSessionCount++; 1251 } 1252 1253 if (index == sessionIndex || reqSessionId == sessionId || 1254 reqSessionHandle == sessionHandle) 1255 { 1256 SessionDetails details{}; 1257 completionCode = getSessionDetails(ctx, service, objectPath, 1258 sessionHandle, state, details); 1259 1260 if (completionCode) 1261 { 1262 return ipmi::response(completionCode); 1263 } 1264 activeSessionHandle = sessionHandle; 1265 maybeDetails = std::move(details); 1266 } 1267 } 1268 1269 if (state == static_cast<uint8_t>(session::State::active) || 1270 state == static_cast<uint8_t>(session::State::tearDownInProgress)) 1271 { 1272 return ipmi::responseSuccess(activeSessionHandle, totalSessionCount, 1273 activeSessionCount, maybeDetails); 1274 } 1275 1276 return ipmi::responseInvalidFieldRequest(); 1277 } 1278 1279 static std::unique_ptr<SysInfoParamStore> sysInfoParamStore; 1280 1281 static std::string sysInfoReadSystemName() 1282 { 1283 // Use the BMC hostname as the "System Name." 1284 char hostname[HOST_NAME_MAX + 1] = {}; 1285 if (gethostname(hostname, HOST_NAME_MAX) != 0) 1286 { 1287 perror("System info parameter: system name"); 1288 } 1289 return hostname; 1290 } 1291 1292 static constexpr uint8_t paramRevision = 0x11; 1293 static constexpr size_t configParameterLength = 16; 1294 1295 static constexpr size_t smallChunkSize = 14; 1296 static constexpr size_t fullChunkSize = 16; 1297 static constexpr uint8_t progressMask = 0x3; 1298 1299 static constexpr uint8_t setComplete = 0x0; 1300 static constexpr uint8_t setInProgress = 0x1; 1301 static constexpr uint8_t commitWrite = 0x2; 1302 static uint8_t transferStatus = setComplete; 1303 1304 static constexpr uint8_t configDataOverhead = 2; 1305 1306 // For EFI based system, 256 bytes is recommended. 1307 static constexpr size_t maxBytesPerParameter = 256; 1308 1309 namespace ipmi 1310 { 1311 constexpr Cc ccParmNotSupported = 0x80; 1312 constexpr Cc ccSetInProgressActive = 0x81; 1313 constexpr Cc ccSystemInfoParameterSetReadOnly = 0x82; 1314 1315 static inline auto responseParmNotSupported() 1316 { 1317 return response(ccParmNotSupported); 1318 } 1319 static inline auto responseSetInProgressActive() 1320 { 1321 return response(ccSetInProgressActive); 1322 } 1323 static inline auto responseSystemInfoParameterSetReadOnly() 1324 { 1325 return response(ccSystemInfoParameterSetReadOnly); 1326 } 1327 } // namespace ipmi 1328 1329 ipmi::RspType<uint8_t, // Parameter revision 1330 std::optional<uint8_t>, // data1 / setSelector / ProgressStatus 1331 std::optional<std::vector<uint8_t>>> // data2-17 1332 ipmiAppGetSystemInfo(uint7_t reserved, bool getRevision, 1333 uint8_t paramSelector, uint8_t setSelector, 1334 uint8_t BlockSelector) 1335 { 1336 if (reserved || (paramSelector >= invalidParamSelectorStart && 1337 paramSelector <= invalidParamSelectorEnd)) 1338 { 1339 return ipmi::responseInvalidFieldRequest(); 1340 } 1341 if ((paramSelector >= oemCmdStart) && (paramSelector <= oemCmdEnd)) 1342 { 1343 return ipmi::responseParmNotSupported(); 1344 } 1345 if (getRevision) 1346 { 1347 return ipmi::responseSuccess(paramRevision, std::nullopt, std::nullopt); 1348 } 1349 1350 if (paramSelector == 0) 1351 { 1352 return ipmi::responseSuccess(paramRevision, transferStatus, 1353 std::nullopt); 1354 } 1355 1356 if (BlockSelector != 0) // 00h if parameter does not require a block number 1357 { 1358 return ipmi::responseParmNotSupported(); 1359 } 1360 1361 if (sysInfoParamStore == nullptr) 1362 { 1363 sysInfoParamStore = std::make_unique<SysInfoParamStore>(); 1364 sysInfoParamStore->update(IPMI_SYSINFO_SYSTEM_NAME, 1365 sysInfoReadSystemName); 1366 } 1367 1368 // Parameters other than Set In Progress are assumed to be strings. 1369 std::tuple<bool, std::string> ret = 1370 sysInfoParamStore->lookup(paramSelector); 1371 bool found = std::get<0>(ret); 1372 if (!found) 1373 { 1374 return ipmi::responseSensorInvalid(); 1375 } 1376 std::string& paramString = std::get<1>(ret); 1377 std::vector<uint8_t> configData; 1378 size_t count = 0; 1379 if (setSelector == 0) 1380 { // First chunk has only 14 bytes. 1381 configData.emplace_back(0); // encoding 1382 configData.emplace_back(paramString.length()); // string length 1383 count = std::min(paramString.length(), smallChunkSize); 1384 configData.resize(count + configDataOverhead); 1385 std::copy_n(paramString.begin(), count, 1386 configData.begin() + configDataOverhead); // 14 bytes chunk 1387 1388 // Append zero's to remaining bytes 1389 if (configData.size() < configParameterLength) 1390 { 1391 std::fill_n(std::back_inserter(configData), 1392 configParameterLength - configData.size(), 0x00); 1393 } 1394 } 1395 else 1396 { 1397 size_t offset = (setSelector * fullChunkSize) - configDataOverhead; 1398 if (offset >= paramString.length()) 1399 { 1400 return ipmi::responseParmOutOfRange(); 1401 } 1402 count = std::min(paramString.length() - offset, fullChunkSize); 1403 configData.resize(count); 1404 std::copy_n(paramString.begin() + offset, count, 1405 configData.begin()); // 16 bytes chunk 1406 } 1407 return ipmi::responseSuccess(paramRevision, setSelector, configData); 1408 } 1409 1410 ipmi::RspType<> ipmiAppSetSystemInfo(uint8_t paramSelector, uint8_t data1, 1411 std::vector<uint8_t> configData) 1412 { 1413 if (paramSelector >= invalidParamSelectorStart && 1414 paramSelector <= invalidParamSelectorEnd) 1415 { 1416 return ipmi::responseInvalidFieldRequest(); 1417 } 1418 if ((paramSelector >= oemCmdStart) && (paramSelector <= oemCmdEnd)) 1419 { 1420 return ipmi::responseParmNotSupported(); 1421 } 1422 1423 if (paramSelector == 0) 1424 { 1425 // attempt to set the 'set in progress' value (in parameter #0) 1426 // when not in the set complete state. 1427 if ((transferStatus != setComplete) && (data1 == setInProgress)) 1428 { 1429 return ipmi::responseSetInProgressActive(); 1430 } 1431 // only following 2 states are supported 1432 if (data1 > setInProgress) 1433 { 1434 phosphor::logging::log<phosphor::logging::level::ERR>( 1435 "illegal SetInProgress status"); 1436 return ipmi::responseInvalidFieldRequest(); 1437 } 1438 1439 transferStatus = data1 & progressMask; 1440 return ipmi::responseSuccess(); 1441 } 1442 1443 if (configData.size() > configParameterLength) 1444 { 1445 return ipmi::responseInvalidFieldRequest(); 1446 } 1447 1448 // Append zero's to remaining bytes 1449 if (configData.size() < configParameterLength) 1450 { 1451 fill_n(back_inserter(configData), 1452 (configParameterLength - configData.size()), 0x00); 1453 } 1454 1455 if (!sysInfoParamStore) 1456 { 1457 sysInfoParamStore = std::make_unique<SysInfoParamStore>(); 1458 sysInfoParamStore->update(IPMI_SYSINFO_SYSTEM_NAME, 1459 sysInfoReadSystemName); 1460 } 1461 1462 // lookup 1463 std::tuple<bool, std::string> ret = 1464 sysInfoParamStore->lookup(paramSelector); 1465 bool found = std::get<0>(ret); 1466 std::string& paramString = std::get<1>(ret); 1467 if (!found) 1468 { 1469 // parameter does not exist. Init new 1470 paramString = ""; 1471 } 1472 1473 uint8_t setSelector = data1; 1474 size_t count = 0; 1475 if (setSelector == 0) // First chunk has only 14 bytes. 1476 { 1477 size_t stringLen = configData.at(1); // string length 1478 // maxBytesPerParamter is 256. It will always be greater than stringLen 1479 // (unit8_t) if maxBytes changes in future, then following line is 1480 // needed. 1481 // stringLen = std::min(stringLen, maxBytesPerParameter); 1482 count = std::min(stringLen, smallChunkSize); 1483 count = std::min(count, configData.size()); 1484 paramString.resize(stringLen); // reserve space 1485 std::copy_n(configData.begin() + configDataOverhead, count, 1486 paramString.begin()); 1487 } 1488 else 1489 { 1490 size_t offset = (setSelector * fullChunkSize) - configDataOverhead; 1491 if (offset >= paramString.length()) 1492 { 1493 return ipmi::responseParmOutOfRange(); 1494 } 1495 count = std::min(paramString.length() - offset, configData.size()); 1496 std::copy_n(configData.begin(), count, paramString.begin() + offset); 1497 } 1498 sysInfoParamStore->update(paramSelector, paramString); 1499 return ipmi::responseSuccess(); 1500 } 1501 1502 #ifdef ENABLE_I2C_WHITELIST_CHECK 1503 inline std::vector<uint8_t> convertStringToData(const std::string& command) 1504 { 1505 std::istringstream iss(command); 1506 std::string token; 1507 std::vector<uint8_t> dataValue; 1508 while (std::getline(iss, token, ' ')) 1509 { 1510 dataValue.emplace_back( 1511 static_cast<uint8_t>(std::stoul(token, nullptr, base_16))); 1512 } 1513 return dataValue; 1514 } 1515 1516 static bool populateI2CMasterWRWhitelist() 1517 { 1518 nlohmann::json data = nullptr; 1519 std::ifstream jsonFile(i2cMasterWRWhitelistFile); 1520 1521 if (!jsonFile.good()) 1522 { 1523 log<level::WARNING>("i2c white list file not found!", 1524 entry("FILE_NAME: %s", i2cMasterWRWhitelistFile)); 1525 return false; 1526 } 1527 1528 try 1529 { 1530 data = nlohmann::json::parse(jsonFile, nullptr, false); 1531 } 1532 catch (const nlohmann::json::parse_error& e) 1533 { 1534 log<level::ERR>("Corrupted i2c white list config file", 1535 entry("FILE_NAME: %s", i2cMasterWRWhitelistFile), 1536 entry("MSG: %s", e.what())); 1537 return false; 1538 } 1539 1540 try 1541 { 1542 // Example JSON Structure format 1543 // "filters": [ 1544 // { 1545 // "Description": "Allow full read - ignore first byte write value 1546 // for 0x40 to 0x4F", 1547 // "busId": "0x01", 1548 // "slaveAddr": "0x40", 1549 // "slaveAddrMask": "0x0F", 1550 // "command": "0x00", 1551 // "commandMask": "0xFF" 1552 // }, 1553 // { 1554 // "Description": "Allow full read - first byte match 0x05 and 1555 // ignore second byte", 1556 // "busId": "0x01", 1557 // "slaveAddr": "0x57", 1558 // "slaveAddrMask": "0x00", 1559 // "command": "0x05 0x00", 1560 // "commandMask": "0x00 0xFF" 1561 // },] 1562 1563 nlohmann::json filters = data[filtersStr].get<nlohmann::json>(); 1564 std::vector<i2cMasterWRWhitelist>& whitelist = getWRWhitelist(); 1565 for (const auto& it : filters.items()) 1566 { 1567 nlohmann::json filter = it.value(); 1568 if (filter.is_null()) 1569 { 1570 log<level::ERR>( 1571 "Corrupted I2C master write read whitelist config file", 1572 entry("FILE_NAME: %s", i2cMasterWRWhitelistFile)); 1573 return false; 1574 } 1575 const std::vector<uint8_t>& writeData = 1576 convertStringToData(filter[cmdStr].get<std::string>()); 1577 const std::vector<uint8_t>& writeDataMask = 1578 convertStringToData(filter[cmdMaskStr].get<std::string>()); 1579 if (writeDataMask.size() != writeData.size()) 1580 { 1581 log<level::ERR>("I2C master write read whitelist filter " 1582 "mismatch for command & mask size"); 1583 return false; 1584 } 1585 whitelist.push_back( 1586 {static_cast<uint8_t>(std::stoul( 1587 filter[busIdStr].get<std::string>(), nullptr, base_16)), 1588 static_cast<uint8_t>( 1589 std::stoul(filter[slaveAddrStr].get<std::string>(), 1590 nullptr, base_16)), 1591 static_cast<uint8_t>( 1592 std::stoul(filter[slaveAddrMaskStr].get<std::string>(), 1593 nullptr, base_16)), 1594 writeData, writeDataMask}); 1595 } 1596 if (whitelist.size() != filters.size()) 1597 { 1598 log<level::ERR>( 1599 "I2C master write read whitelist filter size mismatch"); 1600 return false; 1601 } 1602 } 1603 catch (const std::exception& e) 1604 { 1605 log<level::ERR>("I2C master write read whitelist unexpected exception", 1606 entry("ERROR=%s", e.what())); 1607 return false; 1608 } 1609 return true; 1610 } 1611 1612 static inline bool isWriteDataWhitelisted(const std::vector<uint8_t>& data, 1613 const std::vector<uint8_t>& dataMask, 1614 const std::vector<uint8_t>& writeData) 1615 { 1616 std::vector<uint8_t> processedDataBuf(data.size()); 1617 std::vector<uint8_t> processedReqBuf(dataMask.size()); 1618 std::transform(writeData.begin(), writeData.end(), dataMask.begin(), 1619 processedReqBuf.begin(), std::bit_or<uint8_t>()); 1620 std::transform(data.begin(), data.end(), dataMask.begin(), 1621 processedDataBuf.begin(), std::bit_or<uint8_t>()); 1622 1623 return (processedDataBuf == processedReqBuf); 1624 } 1625 1626 static bool isCmdWhitelisted(uint8_t busId, uint8_t slaveAddr, 1627 std::vector<uint8_t>& writeData) 1628 { 1629 std::vector<i2cMasterWRWhitelist>& whiteList = getWRWhitelist(); 1630 for (const auto& wlEntry : whiteList) 1631 { 1632 if ((busId == wlEntry.busId) && 1633 ((slaveAddr | wlEntry.slaveAddrMask) == 1634 (wlEntry.slaveAddr | wlEntry.slaveAddrMask))) 1635 { 1636 const std::vector<uint8_t>& dataMask = wlEntry.dataMask; 1637 // Skip as no-match, if requested write data is more than the 1638 // write data mask size 1639 if (writeData.size() > dataMask.size()) 1640 { 1641 continue; 1642 } 1643 if (isWriteDataWhitelisted(wlEntry.data, dataMask, writeData)) 1644 { 1645 return true; 1646 } 1647 } 1648 } 1649 return false; 1650 } 1651 #else 1652 static bool populateI2CMasterWRWhitelist() 1653 { 1654 log<level::INFO>( 1655 "I2C_WHITELIST_CHECK is disabled, do not populate whitelist"); 1656 return true; 1657 } 1658 #endif // ENABLE_I2C_WHITELIST_CHECK 1659 1660 /** @brief implements master write read IPMI command which can be used for 1661 * low-level I2C/SMBus write, read or write-read access 1662 * @param isPrivateBus -to indicate private bus usage 1663 * @param busId - bus id 1664 * @param channelNum - channel number 1665 * @param reserved - skip 1 bit 1666 * @param slaveAddr - slave address 1667 * @param read count - number of bytes to be read 1668 * @param writeData - data to be written 1669 * 1670 * @returns IPMI completion code plus response data 1671 * - readData - i2c response data 1672 */ 1673 ipmi::RspType<std::vector<uint8_t>> 1674 ipmiMasterWriteRead([[maybe_unused]] bool isPrivateBus, uint3_t busId, 1675 [[maybe_unused]] uint4_t channelNum, bool reserved, 1676 uint7_t slaveAddr, uint8_t readCount, 1677 std::vector<uint8_t> writeData) 1678 { 1679 if (reserved) 1680 { 1681 return ipmi::responseInvalidFieldRequest(); 1682 } 1683 if (readCount > maxIPMIWriteReadSize) 1684 { 1685 log<level::ERR>("Master write read command: Read count exceeds limit"); 1686 return ipmi::responseParmOutOfRange(); 1687 } 1688 const size_t writeCount = writeData.size(); 1689 if (!readCount && !writeCount) 1690 { 1691 log<level::ERR>("Master write read command: Read & write count are 0"); 1692 return ipmi::responseInvalidFieldRequest(); 1693 } 1694 #ifdef ENABLE_I2C_WHITELIST_CHECK 1695 if (!isCmdWhitelisted(static_cast<uint8_t>(busId), 1696 static_cast<uint8_t>(slaveAddr), writeData)) 1697 { 1698 log<level::ERR>("Master write read request blocked!", 1699 entry("BUS=%d", static_cast<uint8_t>(busId)), 1700 entry("ADDR=0x%x", static_cast<uint8_t>(slaveAddr))); 1701 return ipmi::responseInvalidFieldRequest(); 1702 } 1703 #endif // ENABLE_I2C_WHITELIST_CHECK 1704 std::vector<uint8_t> readBuf(readCount); 1705 std::string i2cBus = "/dev/i2c-" + 1706 std::to_string(static_cast<uint8_t>(busId)); 1707 1708 ipmi::Cc ret = ipmi::i2cWriteRead(i2cBus, static_cast<uint8_t>(slaveAddr), 1709 writeData, readBuf); 1710 if (ret != ipmi::ccSuccess) 1711 { 1712 return ipmi::response(ret); 1713 } 1714 return ipmi::responseSuccess(readBuf); 1715 } 1716 1717 void register_netfn_app_functions() 1718 { 1719 // <Get Device ID> 1720 ipmi::registerHandler(ipmi::prioOpenBmcBase, ipmi::netFnApp, 1721 ipmi::app::cmdGetDeviceId, ipmi::Privilege::User, 1722 ipmiAppGetDeviceId); 1723 1724 // <Get BT Interface Capabilities> 1725 ipmi::registerHandler(ipmi::prioOpenBmcBase, ipmi::netFnApp, 1726 ipmi::app::cmdGetBtIfaceCapabilities, 1727 ipmi::Privilege::User, ipmiAppGetBtCapabilities); 1728 1729 // <Reset Watchdog Timer> 1730 ipmi::registerHandler(ipmi::prioOpenBmcBase, ipmi::netFnApp, 1731 ipmi::app::cmdResetWatchdogTimer, 1732 ipmi::Privilege::Operator, ipmiAppResetWatchdogTimer); 1733 1734 ipmi::registerHandler(ipmi::prioOpenBmcBase, ipmi::netFnApp, 1735 ipmi::app::cmdGetSessionInfo, ipmi::Privilege::User, 1736 ipmiAppGetSessionInfo); 1737 1738 // <Set Watchdog Timer> 1739 ipmi::registerHandler(ipmi::prioOpenBmcBase, ipmi::netFnApp, 1740 ipmi::app::cmdSetWatchdogTimer, 1741 ipmi::Privilege::Operator, ipmiSetWatchdogTimer); 1742 1743 ipmi::registerHandler(ipmi::prioOpenBmcBase, ipmi::netFnApp, 1744 ipmi::app::cmdCloseSession, ipmi::Privilege::Callback, 1745 ipmiAppCloseSession); 1746 1747 // <Get Watchdog Timer> 1748 ipmi::registerHandler(ipmi::prioOpenBmcBase, ipmi::netFnApp, 1749 ipmi::app::cmdGetWatchdogTimer, ipmi::Privilege::User, 1750 ipmiGetWatchdogTimer); 1751 1752 // <Get Self Test Results> 1753 ipmi::registerHandler(ipmi::prioOpenBmcBase, ipmi::netFnApp, 1754 ipmi::app::cmdGetSelfTestResults, 1755 ipmi::Privilege::User, ipmiAppGetSelfTestResults); 1756 1757 // <Get Device GUID> 1758 ipmi::registerHandler(ipmi::prioOpenBmcBase, ipmi::netFnApp, 1759 ipmi::app::cmdGetDeviceGuid, ipmi::Privilege::User, 1760 ipmiAppGetDeviceGuid); 1761 1762 // <Set ACPI Power State> 1763 ipmi::registerHandler(ipmi::prioOpenBmcBase, ipmi::netFnApp, 1764 ipmi::app::cmdSetAcpiPowerState, 1765 ipmi::Privilege::Admin, ipmiSetAcpiPowerState); 1766 // <Get ACPI Power State> 1767 ipmi::registerHandler(ipmi::prioOpenBmcBase, ipmi::netFnApp, 1768 ipmi::app::cmdGetAcpiPowerState, 1769 ipmi::Privilege::User, ipmiGetAcpiPowerState); 1770 1771 // Note: For security reason, this command will be registered only when 1772 // there are proper I2C Master write read whitelist 1773 if (populateI2CMasterWRWhitelist()) 1774 { 1775 // Note: For security reasons, registering master write read as admin 1776 // privilege command, even though IPMI 2.0 specification allows it as 1777 // operator privilege. 1778 ipmi::registerHandler(ipmi::prioOpenBmcBase, ipmi::netFnApp, 1779 ipmi::app::cmdMasterWriteRead, 1780 ipmi::Privilege::Admin, ipmiMasterWriteRead); 1781 } 1782 1783 // <Get System GUID Command> 1784 ipmi::registerHandler(ipmi::prioOpenBmcBase, ipmi::netFnApp, 1785 ipmi::app::cmdGetSystemGuid, ipmi::Privilege::User, 1786 ipmiAppGetSystemGuid); 1787 1788 // <Get Channel Cipher Suites Command> 1789 ipmi::registerHandler(ipmi::prioOpenBmcBase, ipmi::netFnApp, 1790 ipmi::app::cmdGetChannelCipherSuites, 1791 ipmi::Privilege::None, getChannelCipherSuites); 1792 1793 // <Get System Info Command> 1794 ipmi::registerHandler(ipmi::prioOpenBmcBase, ipmi::netFnApp, 1795 ipmi::app::cmdGetSystemInfoParameters, 1796 ipmi::Privilege::User, ipmiAppGetSystemInfo); 1797 // <Set System Info Command> 1798 ipmi::registerHandler(ipmi::prioOpenBmcBase, ipmi::netFnApp, 1799 ipmi::app::cmdSetSystemInfoParameters, 1800 ipmi::Privilege::Admin, ipmiAppSetSystemInfo); 1801 return; 1802 } 1803