1 #include "writefrudata.hpp" 2 3 #include "fru_area.hpp" 4 #include "frup.hpp" 5 #include "types.hpp" 6 7 #include <ipmid/api.h> 8 #include <unistd.h> 9 10 #include <phosphor-logging/log.hpp> 11 #include <sdbusplus/bus.hpp> 12 13 #include <algorithm> 14 #include <cstdio> 15 #include <cstring> 16 #include <exception> 17 #include <fstream> 18 #include <iostream> 19 #include <map> 20 #include <memory> 21 #include <sstream> 22 #include <vector> 23 24 using namespace ipmi::vpd; 25 using namespace phosphor::logging; 26 27 extern const FruMap frus; 28 extern const std::map<Path, InterfaceMap> extras; 29 30 using FruAreaVector = std::vector<std::unique_ptr<IPMIFruArea>>; 31 32 namespace 33 { 34 35 /** 36 * Cleanup routine 37 * Must always be called as last reference to fruFilePointer. 38 * 39 * @param[in] fruFilePointer - FRU file pointer to close 40 * @param[in] fruAreaVec - vector of FRU areas 41 * @return -1 42 */ 43 int cleanupError(FILE* fruFilePointer, FruAreaVector& fruAreaVec) 44 { 45 if (fruFilePointer != NULL) 46 { 47 std::fclose(fruFilePointer); 48 } 49 50 if (!(fruAreaVec.empty())) 51 { 52 fruAreaVec.clear(); 53 } 54 55 return -1; 56 } 57 58 /** 59 * Gets the value of the key from the FRU dictionary of the given section. 60 * FRU dictionary is parsed FRU data for all the sections. 61 * 62 * @param[in] section - FRU section name 63 * @param[in] key - key for secion 64 * @param[in] delimiter - delimiter for parsing custom fields 65 * @param[in] fruData - the FRU data to search for the section 66 * @return FRU value 67 */ 68 std::string getFRUValue(const std::string& section, const std::string& key, 69 const std::string& delimiter, IPMIFruInfo& fruData) 70 { 71 auto minIndexValue = 0; 72 auto maxIndexValue = 0; 73 std::string fruValue = ""; 74 75 if (section == "Board") 76 { 77 minIndexValue = OPENBMC_VPD_KEY_BOARD_MFG_DATE; 78 maxIndexValue = OPENBMC_VPD_KEY_BOARD_MAX; 79 } 80 else if (section == "Product") 81 { 82 minIndexValue = OPENBMC_VPD_KEY_PRODUCT_MFR; 83 maxIndexValue = OPENBMC_VPD_KEY_PRODUCT_MAX; 84 } 85 else if (section == "Chassis") 86 { 87 minIndexValue = OPENBMC_VPD_KEY_CHASSIS_TYPE; 88 maxIndexValue = OPENBMC_VPD_KEY_CHASSIS_MAX; 89 } 90 91 auto first = fruData.cbegin() + minIndexValue; 92 auto last = first + (maxIndexValue - minIndexValue) + 1; 93 94 auto itr = std::find_if(first, last, 95 [&key](const auto& e) { return key == e.first; }); 96 97 if (itr != last) 98 { 99 fruValue = itr->second; 100 } 101 102 // if the key is custom property then the value could be in two formats. 103 // 1) custom field 2 = "value". 104 // 2) custom field 2 = "key:value". 105 // if delimiter length = 0 i.e custom field 2 = "value" 106 107 constexpr auto customProp = "Custom Field"; 108 if (key.find(customProp) != std::string::npos) 109 { 110 if (delimiter.length() > 0) 111 { 112 size_t delimiterpos = fruValue.find(delimiter); 113 if (delimiterpos != std::string::npos) 114 { 115 fruValue = fruValue.substr(delimiterpos + 1); 116 } 117 } 118 } 119 return fruValue; 120 } 121 122 /** 123 * Get the inventory service from the mapper. 124 * 125 * @param[in] bus - sdbusplus handle to use for dbus call 126 * @param[in] intf - interface 127 * @param[in] path - the object path 128 * @return the dbus service that owns the interface for that path 129 */ 130 auto getService(sdbusplus::bus_t& bus, const std::string& intf, 131 const std::string& path) 132 { 133 auto mapperCall = bus.new_method_call("xyz.openbmc_project.ObjectMapper", 134 "/xyz/openbmc_project/object_mapper", 135 "xyz.openbmc_project.ObjectMapper", 136 "GetObject"); 137 138 mapperCall.append(path); 139 mapperCall.append(std::vector<std::string>({intf})); 140 std::map<std::string, std::vector<std::string>> mapperResponse; 141 142 try 143 { 144 auto mapperResponseMsg = bus.call(mapperCall); 145 mapperResponseMsg.read(mapperResponse); 146 } 147 catch (const sdbusplus::exception_t& ex) 148 { 149 log<level::ERR>("Exception from sdbus call", 150 entry("WHAT=%s", ex.what())); 151 throw; 152 } 153 154 if (mapperResponse.begin() == mapperResponse.end()) 155 { 156 throw std::runtime_error("ERROR in reading the mapper response"); 157 } 158 159 return mapperResponse.begin()->first; 160 } 161 162 /** 163 * Takes FRU data, invokes Parser for each FRU record area and updates 164 * inventory. 165 * 166 * @param[in] areaVector - vector of FRU areas 167 * @param[in] bus - handle to sdbus for calling methods, etc 168 * @return return non-zero of failure 169 */ 170 int updateInventory(FruAreaVector& areaVector, sdbusplus::bus_t& bus) 171 { 172 // Generic error reporter 173 int rc = 0; 174 uint8_t fruid = 0; 175 IPMIFruInfo fruData; 176 177 // For each FRU area, extract the needed data , get it parsed and update 178 // the Inventory. 179 for (const auto& fruArea : areaVector) 180 { 181 fruid = fruArea->getFruID(); 182 // Fill the container with information 183 rc = parse_fru_area(fruArea->getType(), 184 static_cast<const void*>(fruArea->getData()), 185 fruArea->getLength(), fruData); 186 if (rc < 0) 187 { 188 log<level::ERR>("Error parsing FRU records"); 189 return rc; 190 } 191 } // END walking the vector of areas and updating 192 193 // For each FRU we have the list of instances which needs to be updated. 194 // Each instance object implements certain interfaces. 195 // Each Interface is having Dbus properties. 196 // Each Dbus Property would be having metaData(eg section,VpdPropertyName). 197 198 // Here we are just printing the object,interface and the properties. 199 // which needs to be called with the new inventory manager implementation. 200 using namespace std::string_literals; 201 static const auto intf = "xyz.openbmc_project.Inventory.Manager"s; 202 static const auto path = "/xyz/openbmc_project/inventory"s; 203 std::string service; 204 try 205 { 206 service = getService(bus, intf, path); 207 } 208 catch (const std::exception& e) 209 { 210 std::cerr << e.what() << "\n"; 211 return -1; 212 } 213 214 auto iter = frus.find(fruid); 215 if (iter == frus.end()) 216 { 217 log<level::ERR>("Unable to find FRUID in generated list", 218 entry("FRU=%d", static_cast<int>(fruid))); 219 return -1; 220 } 221 222 auto& instanceList = iter->second; 223 if (instanceList.size() <= 0) 224 { 225 log<level::DEBUG>("Object list empty for this FRU", 226 entry("FRU=%d", static_cast<int>(fruid))); 227 } 228 229 ObjectMap objects; 230 for (const auto& instance : instanceList) 231 { 232 InterfaceMap interfaces; 233 const auto& extrasIter = extras.find(instance.path); 234 235 for (const auto& interfaceList : instance.interfaces) 236 { 237 PropertyMap props; // store all the properties 238 for (const auto& properties : interfaceList.second) 239 { 240 std::string value; 241 decltype(auto) pdata = properties.second; 242 243 if (!pdata.section.empty() && !pdata.property.empty()) 244 { 245 value = getFRUValue(pdata.section, pdata.property, 246 pdata.delimiter, fruData); 247 } 248 props.emplace(std::move(properties.first), std::move(value)); 249 } 250 // Check and update extra properties 251 if (extras.end() != extrasIter) 252 { 253 const auto& propsIter = 254 (extrasIter->second).find(interfaceList.first); 255 if ((extrasIter->second).end() != propsIter) 256 { 257 for (const auto& map : propsIter->second) 258 { 259 props.emplace(map.first, map.second); 260 } 261 } 262 } 263 interfaces.emplace(std::move(interfaceList.first), 264 std::move(props)); 265 } 266 267 // Call the inventory manager 268 sdbusplus::message::object_path objectPath = instance.path; 269 // Check and update extra properties 270 if (extras.end() != extrasIter) 271 { 272 for (const auto& entry : extrasIter->second) 273 { 274 if (interfaces.end() == interfaces.find(entry.first)) 275 { 276 interfaces.emplace(entry.first, entry.second); 277 } 278 } 279 } 280 objects.emplace(objectPath, interfaces); 281 } 282 283 auto pimMsg = bus.new_method_call(service.c_str(), path.c_str(), 284 intf.c_str(), "Notify"); 285 pimMsg.append(std::move(objects)); 286 287 try 288 { 289 auto inventoryMgrResponseMsg = bus.call(pimMsg); 290 } 291 catch (const sdbusplus::exception_t& ex) 292 { 293 log<level::ERR>("Error in notify call", entry("WHAT=%s", ex.what()), 294 entry("SERVICE=%s", service.c_str()), 295 entry("PATH=%s", path.c_str())); 296 return -1; 297 } 298 299 return rc; 300 } 301 302 } // namespace 303 304 /** 305 * Takes the pointer to stream of bytes and length and returns the 8 bit 306 * checksum. This algo is per IPMI V2.0 spec 307 * 308 * @param[in] data - data for running crc 309 * @param[in] len - the length over which to run the crc 310 * @return the CRC value 311 */ 312 unsigned char calculateCRC(const unsigned char* data, size_t len) 313 { 314 char crc = 0; 315 size_t byte = 0; 316 317 for (byte = 0; byte < len; byte++) 318 { 319 crc += *data++; 320 } 321 322 return (-crc); 323 } 324 325 /** 326 * Accepts a FRU area offset into a commom header and tells which area it is. 327 * 328 * @param[in] areaOffset - offset to lookup the area type 329 * @return the ipmi_fru_area_type 330 */ 331 ipmi_fru_area_type getFruAreaType(uint8_t areaOffset) 332 { 333 ipmi_fru_area_type type = IPMI_FRU_AREA_TYPE_MAX; 334 335 switch (areaOffset) 336 { 337 case IPMI_FRU_INTERNAL_OFFSET: 338 type = IPMI_FRU_AREA_INTERNAL_USE; 339 break; 340 341 case IPMI_FRU_CHASSIS_OFFSET: 342 type = IPMI_FRU_AREA_CHASSIS_INFO; 343 break; 344 345 case IPMI_FRU_BOARD_OFFSET: 346 type = IPMI_FRU_AREA_BOARD_INFO; 347 break; 348 349 case IPMI_FRU_PRODUCT_OFFSET: 350 type = IPMI_FRU_AREA_PRODUCT_INFO; 351 break; 352 353 case IPMI_FRU_MULTI_OFFSET: 354 type = IPMI_FRU_AREA_MULTI_RECORD; 355 break; 356 357 default: 358 type = IPMI_FRU_AREA_TYPE_MAX; 359 } 360 361 return type; 362 } 363 364 /** 365 * Validates the data for multirecord fields and CRC if selected 366 * 367 * @param[in] data - the data to verify 368 * @param[in] len - the length of the region to verify 369 * @param[in] validateCrc - whether to validate the CRC 370 * @return non-zero on failure 371 */ 372 int verifyFruMultiRecData(const uint8_t* data, const size_t len, 373 bool validateCrc) 374 { 375 uint8_t checksum = 0; 376 int rc = -1; 377 378 if (!validateCrc) 379 { 380 // There's nothing else to do for this area. 381 return EXIT_SUCCESS; 382 } 383 384 // As per the IPMI platform spec, byte[3] is the record checksum. 385 checksum = calculateCRC(data, len); 386 if (checksum != data[3]) 387 { 388 #ifdef __IPMI_DEBUG__ 389 log<level::ERR>( 390 "Checksum mismatch", 391 entry("Calculated=0x%X", static_cast<uint32_t>(checksum)), 392 entry("Embedded=0x%X", static_cast<uint32_t>(data[3]))); 393 #endif 394 return rc; 395 } 396 #ifdef __IPMI_DEBUG__ 397 else 398 { 399 log<level::DEBUG>("Checksum matches"); 400 } 401 #endif 402 403 return EXIT_SUCCESS; 404 } 405 406 /** 407 * Validates the data for mandatory fields and CRC if selected. 408 * 409 * @param[in] data - the data to verify 410 * @param[in] len - the length of the region to verify 411 * @param[in] validateCrc - whether to validate the CRC 412 * @return non-zero on failure 413 */ 414 int verifyFruData(const uint8_t* data, const size_t len, bool validateCrc) 415 { 416 uint8_t checksum = 0; 417 int rc = -1; 418 419 // Validate for first byte to always have a value of [1] 420 if (data[0] != IPMI_FRU_HDR_BYTE_ZERO) 421 { 422 log<level::ERR>("Invalid entry in byte-0", 423 entry("ENTRY=0x%X", static_cast<uint32_t>(data[0]))); 424 return rc; 425 } 426 #ifdef __IPMI_DEBUG__ 427 else 428 { 429 log<level::DEBUG>("Validated in entry_1 of fruData", 430 entry("ENTRY=0x%X", static_cast<uint32_t>(data[0]))); 431 } 432 #endif 433 434 if (!validateCrc) 435 { 436 // There's nothing else to do for this area. 437 return EXIT_SUCCESS; 438 } 439 440 // See if the calculated CRC matches with the embedded one. 441 // CRC to be calculated on all except the last one that is CRC itself. 442 checksum = calculateCRC(data, len - 1); 443 if (checksum != data[len - 1]) 444 { 445 #ifdef __IPMI_DEBUG__ 446 log<level::ERR>( 447 "Checksum mismatch", 448 entry("Calculated=0x%X", static_cast<uint32_t>(checksum)), 449 entry("Embedded=0x%X", static_cast<uint32_t>(data[len]))); 450 #endif 451 return rc; 452 } 453 #ifdef __IPMI_DEBUG__ 454 else 455 { 456 log<level::DEBUG>("Checksum matches"); 457 } 458 #endif 459 460 return EXIT_SUCCESS; 461 } 462 463 /** 464 * Checks if a particular FRU area is populated or not. 465 * 466 * @param[in] reference to FRU area pointer 467 * @return true if the area is empty 468 */ 469 bool removeInvalidArea(const std::unique_ptr<IPMIFruArea>& fruArea) 470 { 471 // Filter the ones that are empty 472 if (!(fruArea->getLength())) 473 { 474 return true; 475 } 476 return false; 477 } 478 479 /** 480 * Populates various FRU areas. 481 * 482 * @prereq : This must be called only after validating common header 483 * @param[in] fruData - pointer to the FRU bytes 484 * @param[in] dataLen - the length of the FRU data 485 * @param[in] fruAreaVec - the FRU area vector to update 486 */ 487 int ipmiPopulateFruAreas(uint8_t* fruData, const size_t dataLen, 488 FruAreaVector& fruAreaVec) 489 { 490 // Now walk the common header and see if the file size has atleast the last 491 // offset mentioned by the struct common_header. If the file size is less 492 // than the offset of any if the FRU areas mentioned in the common header, 493 // then we do not have a complete file. 494 for (uint8_t fruEntry = IPMI_FRU_INTERNAL_OFFSET; 495 fruEntry < (sizeof(struct common_header) - 2); fruEntry++) 496 { 497 int rc = -1; 498 // Actual offset in the payload is the offset mentioned in common header 499 // multiplied by 8. Common header is always the first 8 bytes. 500 size_t areaOffset = fruData[fruEntry] * IPMI_EIGHT_BYTES; 501 if (areaOffset && (dataLen < (areaOffset + 2))) 502 { 503 // Our file size is less than what it needs to be. +2 because we are 504 // using area len that is at 2 byte off areaOffset 505 log<level::ERR>("FRU file is incomplete", 506 entry("SIZE=%d", dataLen)); 507 return rc; 508 } 509 else if (areaOffset) 510 { 511 // Read 3 bytes to know the actual size of area. 512 uint8_t areaHeader[3] = {0}; 513 std::memcpy(areaHeader, &((uint8_t*)fruData)[areaOffset], 514 sizeof(areaHeader)); 515 516 // Size of this area will be the 2nd byte in the FRU area header. 517 size_t areaLen; 518 if (fruEntry == IPMI_FRU_MULTI_OFFSET) 519 { 520 areaLen = areaHeader[2] + IPMI_FRU_MULTIREC_HDR_BYTES; 521 } 522 else 523 { 524 areaLen = areaHeader[1] * IPMI_EIGHT_BYTES; 525 } 526 527 uint8_t areaData[areaLen] = {0}; 528 529 log<level::DEBUG>("FRU Data", entry("SIZE=%d", dataLen), 530 entry("AREA OFFSET=%d", areaOffset), 531 entry("AREA_SIZE=%d", areaLen)); 532 533 // See if we really have that much buffer. We have area offset amd 534 // from there, the actual len. 535 if (dataLen < (areaLen + areaOffset)) 536 { 537 log<level::ERR>("Incomplete FRU file", 538 entry("SIZE=%d", dataLen)); 539 return rc; 540 } 541 542 // Save off the data. 543 std::memcpy(areaData, &((uint8_t*)fruData)[areaOffset], areaLen); 544 545 // Validate the CRC, but not for the internal use area, since its 546 // contents beyond the first byte are not defined in the spec and 547 // it may not end with a CRC byte. 548 bool validateCrc = fruEntry != IPMI_FRU_INTERNAL_OFFSET; 549 550 if (fruEntry == IPMI_FRU_MULTI_OFFSET) 551 { 552 rc = verifyFruMultiRecData(areaData, areaLen, validateCrc); 553 } 554 else 555 { 556 rc = verifyFruData(areaData, areaLen, validateCrc); 557 } 558 559 if (rc < 0) 560 { 561 log<level::ERR>("Err validating FRU area", 562 entry("OFFSET=%d", areaOffset)); 563 return rc; 564 } 565 else 566 { 567 log<level::DEBUG>("Successfully verified area.", 568 entry("OFFSET=%d", areaOffset)); 569 } 570 571 // We already have a vector that is passed to us containing all 572 // of the fields populated. Update the data portion now. 573 for (auto& iter : fruAreaVec) 574 { 575 if (iter->getType() == getFruAreaType(fruEntry)) 576 { 577 iter->setData(areaData, areaLen); 578 } 579 } 580 } // If we have FRU data present 581 } // Walk struct common_header 582 583 // Not all the fields will be populated in a FRU data. Mostly all cases will 584 // not have more than 2 or 3. 585 fruAreaVec.erase( 586 std::remove_if(fruAreaVec.begin(), fruAreaVec.end(), removeInvalidArea), 587 fruAreaVec.end()); 588 589 return EXIT_SUCCESS; 590 } 591 592 /** 593 * Validates the FRU data per ipmi common header constructs. 594 * Returns with updated struct common_header and also file_size 595 * 596 * @param[in] fruData - the FRU data 597 * @param[in] dataLen - the length of the data 598 * @return non-zero on failure 599 */ 600 int ipmiValidateCommonHeader(const uint8_t* fruData, const size_t dataLen) 601 { 602 int rc = -1; 603 604 uint8_t commonHdr[sizeof(struct common_header)] = {0}; 605 if (dataLen >= sizeof(commonHdr)) 606 { 607 std::memcpy(commonHdr, fruData, sizeof(commonHdr)); 608 } 609 else 610 { 611 log<level::ERR>("Incomplete FRU data file", entry("SIZE=%d", dataLen)); 612 return rc; 613 } 614 615 // Verify the CRC and size 616 rc = verifyFruData(commonHdr, sizeof(commonHdr), true); 617 if (rc < 0) 618 { 619 log<level::ERR>("Failed to validate common header"); 620 return rc; 621 } 622 623 return EXIT_SUCCESS; 624 } 625 626 int validateFRUArea(const uint8_t fruid, const char* fruFilename, 627 sdbusplus::bus_t& bus, const bool bmcOnlyFru) 628 { 629 size_t dataLen = 0; 630 size_t bytesRead = 0; 631 int rc = -1; 632 633 // Vector that holds individual IPMI FRU AREAs. Although MULTI and INTERNAL 634 // are not used, keeping it here for completeness. 635 FruAreaVector fruAreaVec; 636 637 for (uint8_t fruEntry = IPMI_FRU_INTERNAL_OFFSET; 638 fruEntry < (sizeof(struct common_header) - 2); fruEntry++) 639 { 640 // Create an object and push onto a vector. 641 std::unique_ptr<IPMIFruArea> fruArea = std::make_unique<IPMIFruArea>( 642 fruid, getFruAreaType(fruEntry), bmcOnlyFru); 643 644 // Physically being present 645 bool present = access(fruFilename, F_OK) == 0; 646 fruArea->setPresent(present); 647 648 fruAreaVec.emplace_back(std::move(fruArea)); 649 } 650 651 FILE* fruFilePointer = std::fopen(fruFilename, "rb"); 652 if (fruFilePointer == NULL) 653 { 654 log<level::ERR>("Unable to open FRU file", 655 entry("FILE=%s", fruFilename), 656 entry("ERRNO=%s", std::strerror(errno))); 657 return cleanupError(fruFilePointer, fruAreaVec); 658 } 659 660 // Get the size of the file to see if it meets minimum requirement 661 if (std::fseek(fruFilePointer, 0, SEEK_END)) 662 { 663 log<level::ERR>("Unable to seek FRU file", 664 entry("FILE=%s", fruFilename), 665 entry("ERRNO=%s", std::strerror(errno))); 666 return cleanupError(fruFilePointer, fruAreaVec); 667 } 668 669 // Allocate a buffer to hold entire file content 670 dataLen = std::ftell(fruFilePointer); 671 uint8_t fruData[dataLen] = {0}; 672 673 std::rewind(fruFilePointer); 674 bytesRead = std::fread(fruData, dataLen, 1, fruFilePointer); 675 if (bytesRead != 1) 676 { 677 log<level::ERR>("Failed reading FRU data.", 678 entry("BYTESREAD=%d", bytesRead), 679 entry("ERRNO=%s", std::strerror(errno))); 680 return cleanupError(fruFilePointer, fruAreaVec); 681 } 682 683 // We are done reading. 684 std::fclose(fruFilePointer); 685 fruFilePointer = NULL; 686 687 rc = ipmiValidateCommonHeader(fruData, dataLen); 688 if (rc < 0) 689 { 690 return cleanupError(fruFilePointer, fruAreaVec); 691 } 692 693 // Now that we validated the common header, populate various FRU sections if 694 // we have them here. 695 rc = ipmiPopulateFruAreas(fruData, dataLen, fruAreaVec); 696 if (rc < 0) 697 { 698 log<level::ERR>("Populating FRU areas failed", entry("FRU=%d", fruid)); 699 return cleanupError(fruFilePointer, fruAreaVec); 700 } 701 else 702 { 703 log<level::DEBUG>("Populated FRU areas", entry("FILE=%s", fruFilename)); 704 } 705 706 #ifdef __IPMI_DEBUG__ 707 for (const auto& iter : fruAreaVec) 708 { 709 std::printf("FRU ID : [%d]\n", iter->getFruID()); 710 std::printf("AREA NAME : [%s]\n", iter->getName()); 711 std::printf("TYPE : [%d]\n", iter->getType()); 712 std::printf("LEN : [%d]\n", iter->getLength()); 713 } 714 #endif 715 716 // If the vector is populated with everything, then go ahead and update the 717 // inventory. 718 if (!(fruAreaVec.empty())) 719 { 720 #ifdef __IPMI_DEBUG__ 721 std::printf("\n SIZE of vector is : [%d] \n", fruAreaVec.size()); 722 #endif 723 rc = updateInventory(fruAreaVec, bus); 724 if (rc < 0) 725 { 726 log<level::ERR>("Error updating inventory."); 727 } 728 } 729 730 // we are done with all that we wanted to do. This will do the job of 731 // calling any destructors too. 732 fruAreaVec.clear(); 733 734 return rc; 735 } 736