xref: /openbmc/entity-manager/src/fru_utils.cpp (revision 32a4c129)
1 /*
2 // Copyright (c) 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 /// \file fru_utils.cpp
17 
18 #include "fru_utils.hpp"
19 
20 #include <array>
21 #include <cstddef>
22 #include <cstdint>
23 #include <filesystem>
24 #include <iomanip>
25 #include <iostream>
26 #include <numeric>
27 #include <set>
28 #include <sstream>
29 #include <string>
30 #include <vector>
31 
32 extern "C"
33 {
34 // Include for I2C_SMBUS_BLOCK_MAX
35 #include <linux/i2c.h>
36 }
37 
38 static constexpr bool debug = false;
39 constexpr size_t fruVersion = 1; // Current FRU spec version number is 1
40 
41 std::tm intelEpoch()
42 {
43     std::tm val = {};
44     val.tm_year = 1996 - 1900;
45     val.tm_mday = 1;
46     return val;
47 }
48 
49 char sixBitToChar(uint8_t val)
50 {
51     return static_cast<char>((val & 0x3f) + ' ');
52 }
53 
54 char bcdPlusToChar(uint8_t val)
55 {
56     val &= 0xf;
57     return (val < 10) ? static_cast<char>(val + '0') : bcdHighChars[val - 10];
58 }
59 
60 enum FRUDataEncoding
61 {
62     binary = 0x0,
63     bcdPlus = 0x1,
64     sixBitASCII = 0x2,
65     languageDependent = 0x3,
66 };
67 
68 enum MultiRecordType : uint8_t
69 {
70     powerSupplyInfo = 0x00,
71     dcOutput = 0x01,
72     dcLoad = 0x02,
73     managementAccessRecord = 0x03,
74     baseCompatibilityRecord = 0x04,
75     extendedCompatibilityRecord = 0x05,
76     resvASFSMBusDeviceRecord = 0x06,
77     resvASFLegacyDeviceAlerts = 0x07,
78     resvASFRemoteControl = 0x08,
79     extendedDCOutput = 0x09,
80     extendedDCLoad = 0x0A
81 };
82 
83 enum SubManagementAccessRecord : uint8_t
84 {
85     systemManagementURL = 0x01,
86     systemName = 0x02,
87     systemPingAddress = 0x03,
88     componentManagementURL = 0x04,
89     componentName = 0x05,
90     componentPingAddress = 0x06,
91     systemUniqueID = 0x07
92 };
93 
94 /* Decode FRU data into a std::string, given an input iterator and end. If the
95  * state returned is fruDataOk, then the resulting string is the decoded FRU
96  * data. The input iterator is advanced past the data consumed.
97  *
98  * On fruDataErr, we have lost synchronisation with the length bytes, so the
99  * iterator is no longer usable.
100  */
101 std::pair<DecodeState, std::string>
102     decodeFRUData(std::vector<uint8_t>::const_iterator& iter,
103                   const std::vector<uint8_t>::const_iterator& end,
104                   bool isLangEng)
105 {
106     std::string value;
107     unsigned int i = 0;
108 
109     /* we need at least one byte to decode the type/len header */
110     if (iter == end)
111     {
112         std::cerr << "Truncated FRU data\n";
113         return make_pair(DecodeState::err, value);
114     }
115 
116     uint8_t c = *(iter++);
117 
118     /* 0xc1 is the end marker */
119     if (c == 0xc1)
120     {
121         return make_pair(DecodeState::end, value);
122     }
123 
124     /* decode type/len byte */
125     uint8_t type = static_cast<uint8_t>(c >> 6);
126     uint8_t len = static_cast<uint8_t>(c & 0x3f);
127 
128     /* we should have at least len bytes of data available overall */
129     if (iter + len > end)
130     {
131         std::cerr << "FRU data field extends past end of FRU area data\n";
132         return make_pair(DecodeState::err, value);
133     }
134 
135     switch (type)
136     {
137         case FRUDataEncoding::binary:
138         {
139             std::stringstream ss;
140             ss << std::hex << std::setfill('0');
141             for (i = 0; i < len; i++, iter++)
142             {
143                 uint8_t val = static_cast<uint8_t>(*iter);
144                 ss << std::setw(2) << static_cast<int>(val);
145             }
146             value = ss.str();
147             break;
148         }
149         case FRUDataEncoding::languageDependent:
150             /* For language-code dependent encodings, assume 8-bit ASCII */
151             value = std::string(iter, iter + len);
152             iter += len;
153 
154             /* English text is encoded in 8-bit ASCII + Latin 1. All other
155              * languages are required to use 2-byte unicode. FruDevice does not
156              * handle unicode.
157              */
158             if (!isLangEng)
159             {
160                 std::cerr << "Error: Non english string is not supported \n";
161                 return make_pair(DecodeState::err, value);
162             }
163 
164             break;
165 
166         case FRUDataEncoding::bcdPlus:
167             value = std::string();
168             for (i = 0; i < len; i++, iter++)
169             {
170                 uint8_t val = *iter;
171                 value.push_back(bcdPlusToChar(val >> 4));
172                 value.push_back(bcdPlusToChar(val & 0xf));
173             }
174             break;
175 
176         case FRUDataEncoding::sixBitASCII:
177         {
178             unsigned int accum = 0;
179             unsigned int accumBitLen = 0;
180             value = std::string();
181             for (i = 0; i < len; i++, iter++)
182             {
183                 accum |= *iter << accumBitLen;
184                 accumBitLen += 8;
185                 while (accumBitLen >= 6)
186                 {
187                     value.push_back(sixBitToChar(accum & 0x3f));
188                     accum >>= 6;
189                     accumBitLen -= 6;
190                 }
191             }
192         }
193         break;
194 
195         default:
196         {
197             return make_pair(DecodeState::err, value);
198         }
199     }
200 
201     return make_pair(DecodeState::ok, value);
202 }
203 
204 bool checkLangEng(uint8_t lang)
205 {
206     // If Lang is not English then the encoding is defined as 2-byte UNICODE,
207     // but we don't support that.
208     if ((lang != 0U) && lang != 25)
209     {
210         std::cerr << "Warning: languages other than English is not "
211                      "supported\n";
212         // Return language flag as non english
213         return false;
214     }
215     return true;
216 }
217 
218 /* This function verifies for other offsets to check if they are not
219  * falling under other field area
220  *
221  * fruBytes:    Start of Fru data
222  * currentArea: Index of current area offset to be compared against all area
223  *              offset and it is a multiple of 8 bytes as per specification
224  * len:         Length of current area space and it is a multiple of 8 bytes
225  *              as per specification
226  */
227 bool verifyOffset(const std::vector<uint8_t>& fruBytes, fruAreas currentArea,
228                   uint8_t len)
229 {
230     unsigned int fruBytesSize = fruBytes.size();
231 
232     // check if Fru data has at least 8 byte header
233     if (fruBytesSize <= fruBlockSize)
234     {
235         std::cerr << "Error: trying to parse empty FRU\n";
236         return false;
237     }
238 
239     // Check range of passed currentArea value
240     if (currentArea > fruAreas::fruAreaMultirecord)
241     {
242         std::cerr << "Error: Fru area is out of range\n";
243         return false;
244     }
245 
246     unsigned int currentAreaIndex = getHeaderAreaFieldOffset(currentArea);
247     if (currentAreaIndex > fruBytesSize)
248     {
249         std::cerr << "Error: Fru area index is out of range\n";
250         return false;
251     }
252 
253     unsigned int start = fruBytes[currentAreaIndex];
254     unsigned int end = start + len;
255 
256     /* Verify each offset within the range of start and end */
257     for (fruAreas area = fruAreas::fruAreaInternal;
258          area <= fruAreas::fruAreaMultirecord; ++area)
259     {
260         // skip the current offset
261         if (area == currentArea)
262         {
263             continue;
264         }
265 
266         unsigned int areaIndex = getHeaderAreaFieldOffset(area);
267         if (areaIndex > fruBytesSize)
268         {
269             std::cerr << "Error: Fru area index is out of range\n";
270             return false;
271         }
272 
273         unsigned int areaOffset = fruBytes[areaIndex];
274         // if areaOffset is 0 means this area is not available so skip
275         if (areaOffset == 0)
276         {
277             continue;
278         }
279 
280         // check for overlapping of current offset with given areaoffset
281         if (areaOffset == start || (areaOffset > start && areaOffset < end))
282         {
283             std::cerr << getFruAreaName(currentArea)
284                       << " offset is overlapping with " << getFruAreaName(area)
285                       << " offset\n";
286             return false;
287         }
288     }
289     return true;
290 }
291 
292 static void parseMultirecordUUID(
293     const std::vector<uint8_t>& device,
294     boost::container::flat_map<std::string, std::string>& result)
295 {
296     constexpr size_t uuidDataLen = 16;
297     constexpr size_t multiRecordHeaderLen = 5;
298     /* UUID record data, plus one to skip past the sub-record type byte */
299     constexpr size_t uuidRecordData = multiRecordHeaderLen + 1;
300     constexpr size_t multiRecordEndOfListMask = 0x80;
301     /* The UUID {00112233-4455-6677-8899-AABBCCDDEEFF} would thus be represented
302      * as: 0x33 0x22 0x11 0x00 0x55 0x44 0x77 0x66 0x88 0x99 0xAA 0xBB 0xCC 0xDD
303      * 0xEE 0xFF
304      */
305     const std::array<uint8_t, uuidDataLen> uuidCharOrder = {
306         3, 2, 1, 0, 5, 4, 7, 6, 8, 9, 10, 11, 12, 13, 14, 15};
307     uint32_t areaOffset =
308         device.at(getHeaderAreaFieldOffset(fruAreas::fruAreaMultirecord));
309 
310     if (areaOffset == 0)
311     {
312         return;
313     }
314 
315     areaOffset *= fruBlockSize;
316     std::vector<uint8_t>::const_iterator fruBytesIter = device.begin() +
317                                                         areaOffset;
318 
319     /* Verify area offset */
320     if (!verifyOffset(device, fruAreas::fruAreaMultirecord, *fruBytesIter))
321     {
322         return;
323     }
324     while (areaOffset + uuidRecordData + uuidDataLen <= device.size())
325     {
326         if ((areaOffset < device.size()) &&
327             (device[areaOffset] ==
328              (uint8_t)MultiRecordType::managementAccessRecord))
329         {
330             if ((areaOffset + multiRecordHeaderLen < device.size()) &&
331                 (device[areaOffset + multiRecordHeaderLen] ==
332                  (uint8_t)SubManagementAccessRecord::systemUniqueID))
333             {
334                 /* Layout of UUID:
335                  * source: https://www.ietf.org/rfc/rfc4122.txt
336                  *
337                  * UUID binary format (16 bytes):
338                  * 4B-2B-2B-2B-6B (big endian)
339                  *
340                  * UUID string is 36 length of characters (36 bytes):
341                  * 0        9    14   19   24
342                  * xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx
343                  *    be     be   be   be       be
344                  * be means it should be converted to big endian.
345                  */
346                 /* Get UUID bytes to UUID string */
347                 std::stringstream tmp;
348                 tmp << std::hex << std::setfill('0');
349                 for (size_t i = 0; i < uuidDataLen; i++)
350                 {
351                     tmp << std::setw(2)
352                         << static_cast<uint16_t>(
353                                device[areaOffset + uuidRecordData +
354                                       uuidCharOrder[i]]);
355                 }
356                 std::string uuidStr = tmp.str();
357                 result["MULTIRECORD_UUID"] =
358                     uuidStr.substr(0, 8) + '-' + uuidStr.substr(8, 4) + '-' +
359                     uuidStr.substr(12, 4) + '-' + uuidStr.substr(16, 4) + '-' +
360                     uuidStr.substr(20, 12);
361                 break;
362             }
363         }
364         if ((device[areaOffset + 1] & multiRecordEndOfListMask) != 0)
365         {
366             break;
367         }
368         areaOffset = areaOffset + device[areaOffset + 2] + multiRecordHeaderLen;
369     }
370 }
371 
372 resCodes
373     formatIPMIFRU(const std::vector<uint8_t>& fruBytes,
374                   boost::container::flat_map<std::string, std::string>& result)
375 {
376     resCodes ret = resCodes::resOK;
377     if (fruBytes.size() <= fruBlockSize)
378     {
379         std::cerr << "Error: trying to parse empty FRU \n";
380         return resCodes::resErr;
381     }
382     result["Common_Format_Version"] =
383         std::to_string(static_cast<int>(*fruBytes.begin()));
384 
385     const std::vector<std::string>* fruAreaFieldNames = nullptr;
386 
387     // Don't parse Internal and Multirecord areas
388     for (fruAreas area = fruAreas::fruAreaChassis;
389          area <= fruAreas::fruAreaProduct; ++area)
390     {
391         size_t offset = *(fruBytes.begin() + getHeaderAreaFieldOffset(area));
392         if (offset == 0)
393         {
394             continue;
395         }
396         offset *= fruBlockSize;
397         std::vector<uint8_t>::const_iterator fruBytesIter = fruBytes.begin() +
398                                                             offset;
399         if (fruBytesIter + fruBlockSize >= fruBytes.end())
400         {
401             std::cerr << "Not enough data to parse \n";
402             return resCodes::resErr;
403         }
404         // check for format version 1
405         if (*fruBytesIter != 0x01)
406         {
407             std::cerr << "Unexpected version " << *fruBytesIter << "\n";
408             return resCodes::resErr;
409         }
410         ++fruBytesIter;
411 
412         /* Verify other area offset for overlap with current area by passing
413          * length of current area offset pointed by *fruBytesIter
414          */
415         if (!verifyOffset(fruBytes, area, *fruBytesIter))
416         {
417             return resCodes::resErr;
418         }
419 
420         size_t fruAreaSize = *fruBytesIter * fruBlockSize;
421         std::vector<uint8_t>::const_iterator fruBytesIterEndArea =
422             fruBytes.begin() + offset + fruAreaSize - 1;
423         ++fruBytesIter;
424 
425         uint8_t fruComputedChecksum =
426             calculateChecksum(fruBytes.begin() + offset, fruBytesIterEndArea);
427         if (fruComputedChecksum != *fruBytesIterEndArea)
428         {
429             std::stringstream ss;
430             ss << std::hex << std::setfill('0');
431             ss << "Checksum error in FRU area " << getFruAreaName(area) << "\n";
432             ss << "\tComputed checksum: 0x" << std::setw(2)
433                << static_cast<int>(fruComputedChecksum) << "\n";
434             ss << "\tThe read checksum: 0x" << std::setw(2)
435                << static_cast<int>(*fruBytesIterEndArea) << "\n";
436             std::cerr << ss.str();
437             ret = resCodes::resWarn;
438         }
439 
440         /* Set default language flag to true as Chassis Fru area are always
441          * encoded in English defined in Section 10 of Fru specification
442          */
443 
444         bool isLangEng = true;
445         switch (area)
446         {
447             case fruAreas::fruAreaChassis:
448             {
449                 result["CHASSIS_TYPE"] =
450                     std::to_string(static_cast<int>(*fruBytesIter));
451                 fruBytesIter += 1;
452                 fruAreaFieldNames = &chassisFruAreas;
453                 break;
454             }
455             case fruAreas::fruAreaBoard:
456             {
457                 uint8_t lang = *fruBytesIter;
458                 result["BOARD_LANGUAGE_CODE"] =
459                     std::to_string(static_cast<int>(lang));
460                 isLangEng = checkLangEng(lang);
461                 fruBytesIter += 1;
462 
463                 unsigned int minutes = *fruBytesIter |
464                                        *(fruBytesIter + 1) << 8 |
465                                        *(fruBytesIter + 2) << 16;
466                 std::tm fruTime = intelEpoch();
467                 std::time_t timeValue = timegm(&fruTime);
468                 timeValue += static_cast<long>(minutes) * 60;
469                 fruTime = *std::gmtime(&timeValue);
470 
471                 // Tue Nov 20 23:08:00 2018
472                 std::array<char, 32> timeString = {};
473                 auto bytes = std::strftime(timeString.data(), timeString.size(),
474                                            "%Y%m%dT%H%M%SZ", &fruTime);
475                 if (bytes == 0)
476                 {
477                     std::cerr << "invalid time string encountered\n";
478                     return resCodes::resErr;
479                 }
480 
481                 result["BOARD_MANUFACTURE_DATE"] =
482                     std::string_view(timeString.data(), bytes);
483                 fruBytesIter += 3;
484                 fruAreaFieldNames = &boardFruAreas;
485                 break;
486             }
487             case fruAreas::fruAreaProduct:
488             {
489                 uint8_t lang = *fruBytesIter;
490                 result["PRODUCT_LANGUAGE_CODE"] =
491                     std::to_string(static_cast<int>(lang));
492                 isLangEng = checkLangEng(lang);
493                 fruBytesIter += 1;
494                 fruAreaFieldNames = &productFruAreas;
495                 break;
496             }
497             default:
498             {
499                 std::cerr << "Internal error: unexpected FRU area index: "
500                           << static_cast<int>(area) << " \n";
501                 return resCodes::resErr;
502             }
503         }
504         size_t fieldIndex = 0;
505         DecodeState state = DecodeState::ok;
506         do
507         {
508             auto res = decodeFRUData(fruBytesIter, fruBytesIterEndArea,
509                                      isLangEng);
510             state = res.first;
511             std::string value = res.second;
512             std::string name;
513             if (fieldIndex < fruAreaFieldNames->size())
514             {
515                 name = std::string(getFruAreaName(area)) + "_" +
516                        fruAreaFieldNames->at(fieldIndex);
517             }
518             else
519             {
520                 name =
521                     std::string(getFruAreaName(area)) + "_" +
522                     fruCustomFieldName +
523                     std::to_string(fieldIndex - fruAreaFieldNames->size() + 1);
524             }
525 
526             if (state == DecodeState::ok)
527             {
528                 // Strip non null characters from the end
529                 value.erase(std::find_if(value.rbegin(), value.rend(),
530                                          [](char ch) {
531                     return ch != 0;
532                 }).base(),
533                             value.end());
534 
535                 result[name] = std::move(value);
536                 ++fieldIndex;
537             }
538             else if (state == DecodeState::err)
539             {
540                 std::cerr << "Error while parsing " << name << "\n";
541                 ret = resCodes::resWarn;
542                 // Cancel decoding if failed to parse any of mandatory
543                 // fields
544                 if (fieldIndex < fruAreaFieldNames->size())
545                 {
546                     std::cerr << "Failed to parse mandatory field \n";
547                     return resCodes::resErr;
548                 }
549             }
550             else
551             {
552                 if (fieldIndex < fruAreaFieldNames->size())
553                 {
554                     std::cerr << "Mandatory fields absent in FRU area "
555                               << getFruAreaName(area) << " after " << name
556                               << "\n";
557                     ret = resCodes::resWarn;
558                 }
559             }
560         } while (state == DecodeState::ok);
561         for (; fruBytesIter < fruBytesIterEndArea; fruBytesIter++)
562         {
563             uint8_t c = *fruBytesIter;
564             if (c != 0U)
565             {
566                 std::cerr << "Non-zero byte after EndOfFields in FRU area "
567                           << getFruAreaName(area) << "\n";
568                 ret = resCodes::resWarn;
569                 break;
570             }
571         }
572     }
573 
574     /* Parsing the Multirecord UUID */
575     parseMultirecordUUID(fruBytes, result);
576 
577     return ret;
578 }
579 
580 // Calculate new checksum for fru info area
581 uint8_t calculateChecksum(std::vector<uint8_t>::const_iterator iter,
582                           std::vector<uint8_t>::const_iterator end)
583 {
584     constexpr int checksumMod = 256;
585     uint8_t sum = std::accumulate(iter, end, static_cast<uint8_t>(0));
586     return (checksumMod - sum) % checksumMod;
587 }
588 
589 uint8_t calculateChecksum(std::vector<uint8_t>& fruAreaData)
590 {
591     return calculateChecksum(fruAreaData.begin(), fruAreaData.end());
592 }
593 
594 // Update new fru area length &
595 // Update checksum at new checksum location
596 // Return the offset of the area checksum byte
597 unsigned int updateFRUAreaLenAndChecksum(std::vector<uint8_t>& fruData,
598                                          size_t fruAreaStart,
599                                          size_t fruAreaEndOfFieldsOffset,
600                                          size_t fruAreaEndOffset)
601 {
602     size_t traverseFRUAreaIndex = fruAreaEndOfFieldsOffset - fruAreaStart;
603 
604     // fill zeros for any remaining unused space
605     std::fill(fruData.begin() + fruAreaEndOfFieldsOffset,
606               fruData.begin() + fruAreaEndOffset, 0);
607 
608     size_t mod = traverseFRUAreaIndex % fruBlockSize;
609     size_t checksumLoc = 0;
610     if (mod == 0U)
611     {
612         traverseFRUAreaIndex += (fruBlockSize);
613         checksumLoc = fruAreaEndOfFieldsOffset + (fruBlockSize - 1);
614     }
615     else
616     {
617         traverseFRUAreaIndex += (fruBlockSize - mod);
618         checksumLoc = fruAreaEndOfFieldsOffset + (fruBlockSize - mod - 1);
619     }
620 
621     size_t newFRUAreaLen =
622         (traverseFRUAreaIndex / fruBlockSize) +
623         static_cast<unsigned long>((traverseFRUAreaIndex % fruBlockSize) != 0);
624     size_t fruAreaLengthLoc = fruAreaStart + 1;
625     fruData[fruAreaLengthLoc] = static_cast<uint8_t>(newFRUAreaLen);
626 
627     // Calculate new checksum
628     std::vector<uint8_t> finalFRUData;
629     std::copy_n(fruData.begin() + fruAreaStart, checksumLoc - fruAreaStart,
630                 std::back_inserter(finalFRUData));
631 
632     fruData[checksumLoc] = calculateChecksum(finalFRUData);
633     return checksumLoc;
634 }
635 
636 ssize_t getFieldLength(uint8_t fruFieldTypeLenValue)
637 {
638     constexpr uint8_t typeLenMask = 0x3F;
639     constexpr uint8_t endOfFields = 0xC1;
640     if (fruFieldTypeLenValue == endOfFields)
641     {
642         return -1;
643     }
644     return fruFieldTypeLenValue & typeLenMask;
645 }
646 
647 bool validateHeader(const std::array<uint8_t, I2C_SMBUS_BLOCK_MAX>& blockData)
648 {
649     // ipmi spec format version number is currently at 1, verify it
650     if (blockData[0] != fruVersion)
651     {
652         if (debug)
653         {
654             std::cerr << "FRU spec version " << (int)(blockData[0])
655                       << " not supported. Supported version is "
656                       << (int)(fruVersion) << "\n";
657         }
658         return false;
659     }
660 
661     // verify pad is set to 0
662     if (blockData[6] != 0x0)
663     {
664         if (debug)
665         {
666             std::cerr << "PAD value in header is non zero, value is "
667                       << (int)(blockData[6]) << "\n";
668         }
669         return false;
670     }
671 
672     // verify offsets are 0, or don't point to another offset
673     std::set<uint8_t> foundOffsets;
674     for (int ii = 1; ii < 6; ii++)
675     {
676         if (blockData[ii] == 0)
677         {
678             continue;
679         }
680         auto inserted = foundOffsets.insert(blockData[ii]);
681         if (!inserted.second)
682         {
683             return false;
684         }
685     }
686 
687     // validate checksum
688     size_t sum = 0;
689     for (int jj = 0; jj < 7; jj++)
690     {
691         sum += blockData[jj];
692     }
693     sum = (256 - sum) & 0xFF;
694 
695     if (sum != blockData[7])
696     {
697         if (debug)
698         {
699             std::cerr << "Checksum " << (int)(blockData[7])
700                       << " is invalid. calculated checksum is " << (int)(sum)
701                       << "\n";
702         }
703         return false;
704     }
705     return true;
706 }
707 
708 bool findFRUHeader(FRUReader& reader, const std::string& errorHelp,
709                    std::array<uint8_t, I2C_SMBUS_BLOCK_MAX>& blockData,
710                    off_t& baseOffset)
711 {
712     if (reader.read(baseOffset, 0x8, blockData.data()) < 0)
713     {
714         std::cerr << "failed to read " << errorHelp << " base offset "
715                   << baseOffset << "\n";
716         return false;
717     }
718 
719     // check the header checksum
720     if (validateHeader(blockData))
721     {
722         return true;
723     }
724 
725     // only continue the search if we just looked at 0x0.
726     if (baseOffset != 0)
727     {
728         return false;
729     }
730 
731     // now check for special cases where the IPMI data is at an offset
732 
733     // check if blockData starts with tyanHeader
734     const std::vector<uint8_t> tyanHeader = {'$', 'T', 'Y', 'A', 'N', '$'};
735     if (blockData.size() >= tyanHeader.size() &&
736         std::equal(tyanHeader.begin(), tyanHeader.end(), blockData.begin()))
737     {
738         // look for the FRU header at offset 0x6000
739         baseOffset = 0x6000;
740         return findFRUHeader(reader, errorHelp, blockData, baseOffset);
741     }
742 
743     if (debug)
744     {
745         std::cerr << "Illegal header " << errorHelp << " base offset "
746                   << baseOffset << "\n";
747     }
748 
749     return false;
750 }
751 
752 std::pair<std::vector<uint8_t>, bool>
753     readFRUContents(FRUReader& reader, const std::string& errorHelp)
754 {
755     std::array<uint8_t, I2C_SMBUS_BLOCK_MAX> blockData{};
756     off_t baseOffset = 0x0;
757 
758     if (!findFRUHeader(reader, errorHelp, blockData, baseOffset))
759     {
760         return {{}, false};
761     }
762 
763     std::vector<uint8_t> device;
764     device.insert(device.end(), blockData.begin(), blockData.begin() + 8);
765 
766     bool hasMultiRecords = false;
767     size_t fruLength = fruBlockSize; // At least FRU header is present
768     unsigned int prevOffset = 0;
769     for (fruAreas area = fruAreas::fruAreaInternal;
770          area <= fruAreas::fruAreaMultirecord; ++area)
771     {
772         // Offset value can be 255.
773         unsigned int areaOffset = device[getHeaderAreaFieldOffset(area)];
774         if (areaOffset == 0)
775         {
776             continue;
777         }
778 
779         /* Check for offset order, as per Section 17 of FRU specification, FRU
780          * information areas are required to be in order in FRU data layout
781          * which means all offset value should be in increasing order or can be
782          * 0 if that area is not present
783          */
784         if (areaOffset <= prevOffset)
785         {
786             std::cerr << "Fru area offsets are not in required order as per "
787                          "Section 17 of Fru specification\n";
788             return {{}, true};
789         }
790         prevOffset = areaOffset;
791 
792         // MultiRecords are different. area is not tracking section, it's
793         // walking the common header.
794         if (area == fruAreas::fruAreaMultirecord)
795         {
796             hasMultiRecords = true;
797             break;
798         }
799 
800         areaOffset *= fruBlockSize;
801 
802         if (reader.read(baseOffset + areaOffset, 0x2, blockData.data()) < 0)
803         {
804             std::cerr << "failed to read " << errorHelp << " base offset "
805                       << baseOffset << "\n";
806             return {{}, true};
807         }
808 
809         // Ignore data type (blockData is already unsigned).
810         size_t length = blockData[1] * fruBlockSize;
811         areaOffset += length;
812         fruLength = (areaOffset > fruLength) ? areaOffset : fruLength;
813     }
814 
815     if (hasMultiRecords)
816     {
817         // device[area count] is the index to the last area because the 0th
818         // entry is not an offset in the common header.
819         unsigned int areaOffset =
820             device[getHeaderAreaFieldOffset(fruAreas::fruAreaMultirecord)];
821         areaOffset *= fruBlockSize;
822 
823         // the multi-area record header is 5 bytes long.
824         constexpr size_t multiRecordHeaderSize = 5;
825         constexpr uint8_t multiRecordEndOfListMask = 0x80;
826 
827         // Sanity hard-limit to 64KB.
828         while (areaOffset < std::numeric_limits<uint16_t>::max())
829         {
830             // In multi-area, the area offset points to the 0th record, each
831             // record has 3 bytes of the header we care about.
832             if (reader.read(baseOffset + areaOffset, 0x3, blockData.data()) < 0)
833             {
834                 std::cerr << "failed to read " << errorHelp << " base offset "
835                           << baseOffset << "\n";
836                 return {{}, true};
837             }
838 
839             // Ok, let's check the record length, which is in bytes (unsigned,
840             // up to 255, so blockData should hold uint8_t not char)
841             size_t recordLength = blockData[2];
842             areaOffset += (recordLength + multiRecordHeaderSize);
843             fruLength = (areaOffset > fruLength) ? areaOffset : fruLength;
844 
845             // If this is the end of the list bail.
846             if ((blockData[1] & multiRecordEndOfListMask) != 0)
847             {
848                 break;
849             }
850         }
851     }
852 
853     // You already copied these first 8 bytes (the ipmi fru header size)
854     fruLength -= std::min(fruBlockSize, fruLength);
855 
856     int readOffset = fruBlockSize;
857 
858     while (fruLength > 0)
859     {
860         size_t requestLength =
861             std::min(static_cast<size_t>(I2C_SMBUS_BLOCK_MAX), fruLength);
862 
863         if (reader.read(baseOffset + readOffset, requestLength,
864                         blockData.data()) < 0)
865         {
866             std::cerr << "failed to read " << errorHelp << " base offset "
867                       << baseOffset << "\n";
868             return {{}, true};
869         }
870 
871         device.insert(device.end(), blockData.begin(),
872                       blockData.begin() + requestLength);
873 
874         readOffset += requestLength;
875         fruLength -= std::min(requestLength, fruLength);
876     }
877 
878     return {device, true};
879 }
880 
881 unsigned int getHeaderAreaFieldOffset(fruAreas area)
882 {
883     return static_cast<unsigned int>(area) + 1;
884 }
885 
886 std::vector<uint8_t>& getFRUInfo(const uint16_t& bus, const uint8_t& address)
887 {
888     auto deviceMap = busMap.find(bus);
889     if (deviceMap == busMap.end())
890     {
891         throw std::invalid_argument("Invalid Bus.");
892     }
893     auto device = deviceMap->second->find(address);
894     if (device == deviceMap->second->end())
895     {
896         throw std::invalid_argument("Invalid Address.");
897     }
898     std::vector<uint8_t>& ret = device->second;
899 
900     return ret;
901 }
902 
903 // Iterate FruArea Names and find start and size of the fru area that contains
904 // the propertyName and the field start location for the property. fruAreaParams
905 // struct values fruAreaStart, fruAreaSize, fruAreaEnd, fieldLoc values gets
906 // updated/returned if successful.
907 
908 bool findFruAreaLocationAndField(std::vector<uint8_t>& fruData,
909                                  const std::string& propertyName,
910                                  struct FruArea& fruAreaParams)
911 {
912     const std::vector<std::string>* fruAreaFieldNames = nullptr;
913 
914     uint8_t fruAreaOffsetFieldValue = 0;
915     size_t offset = 0;
916     std::string areaName = propertyName.substr(0, propertyName.find('_'));
917     std::string propertyNamePrefix = areaName + "_";
918     auto it = std::find(fruAreaNames.begin(), fruAreaNames.end(), areaName);
919     if (it == fruAreaNames.end())
920     {
921         std::cerr << "Can't parse area name for property " << propertyName
922                   << " \n";
923         return false;
924     }
925     fruAreas fruAreaToUpdate = static_cast<fruAreas>(it - fruAreaNames.begin());
926     fruAreaOffsetFieldValue =
927         fruData[getHeaderAreaFieldOffset(fruAreaToUpdate)];
928     switch (fruAreaToUpdate)
929     {
930         case fruAreas::fruAreaChassis:
931             offset = 3; // chassis part number offset. Skip fixed first 3 bytes
932             fruAreaFieldNames = &chassisFruAreas;
933             break;
934         case fruAreas::fruAreaBoard:
935             offset = 6; // board manufacturer offset. Skip fixed first 6 bytes
936             fruAreaFieldNames = &boardFruAreas;
937             break;
938         case fruAreas::fruAreaProduct:
939             // Manufacturer name offset. Skip fixed first 3 product fru bytes
940             // i.e. version, area length and language code
941             offset = 3;
942             fruAreaFieldNames = &productFruAreas;
943             break;
944         default:
945             std::cerr << "Invalid PropertyName " << propertyName << " \n";
946             return false;
947     }
948     if (fruAreaOffsetFieldValue == 0)
949     {
950         std::cerr << "FRU Area for " << propertyName << " not present \n";
951         return false;
952     }
953 
954     fruAreaParams.start = fruAreaOffsetFieldValue * fruBlockSize;
955     fruAreaParams.size = fruData[fruAreaParams.start + 1] * fruBlockSize;
956     fruAreaParams.end = fruAreaParams.start + fruAreaParams.size;
957     size_t fruDataIter = fruAreaParams.start + offset;
958     size_t skipToFRUUpdateField = 0;
959     ssize_t fieldLength = 0;
960 
961     bool found = false;
962     for (const auto& field : *fruAreaFieldNames)
963     {
964         skipToFRUUpdateField++;
965         if (propertyName == propertyNamePrefix + field)
966         {
967             found = true;
968             break;
969         }
970     }
971     if (!found)
972     {
973         std::size_t pos = propertyName.find(fruCustomFieldName);
974         if (pos == std::string::npos)
975         {
976             std::cerr << "PropertyName doesn't exist in FRU Area Vectors: "
977                       << propertyName << "\n";
978             return false;
979         }
980         std::string fieldNumStr =
981             propertyName.substr(pos + fruCustomFieldName.length());
982         size_t fieldNum = std::stoi(fieldNumStr);
983         if (fieldNum == 0)
984         {
985             std::cerr << "PropertyName not recognized: " << propertyName
986                       << "\n";
987             return false;
988         }
989         skipToFRUUpdateField += fieldNum;
990     }
991 
992     for (size_t i = 1; i < skipToFRUUpdateField; i++)
993     {
994         if (fruDataIter < fruData.size())
995         {
996             fieldLength = getFieldLength(fruData[fruDataIter]);
997 
998             if (fieldLength < 0)
999             {
1000                 break;
1001             }
1002             fruDataIter += 1 + fieldLength;
1003         }
1004     }
1005     fruAreaParams.updateFieldLoc = fruDataIter;
1006 
1007     return true;
1008 }
1009 
1010 // Copy the FRU Area fields and properties into restFRUAreaFieldsData vector.
1011 // Return true for success and false for failure.
1012 
1013 bool copyRestFRUArea(std::vector<uint8_t>& fruData,
1014                      const std::string& propertyName,
1015                      struct FruArea& fruAreaParams,
1016                      std::vector<uint8_t>& restFRUAreaFieldsData)
1017 {
1018     size_t fieldLoc = fruAreaParams.updateFieldLoc;
1019     size_t start = fruAreaParams.start;
1020     size_t fruAreaSize = fruAreaParams.size;
1021 
1022     // Push post update fru field bytes to a vector
1023     ssize_t fieldLength = getFieldLength(fruData[fieldLoc]);
1024     if (fieldLength < 0)
1025     {
1026         std::cerr << "Property " << propertyName << " not present \n";
1027         return false;
1028     }
1029 
1030     size_t fruDataIter = 0;
1031     fruDataIter = fieldLoc;
1032     fruDataIter += 1 + fieldLength;
1033     size_t restFRUFieldsLoc = fruDataIter;
1034     size_t endOfFieldsLoc = 0;
1035 
1036     if (fruDataIter < fruData.size())
1037     {
1038         while ((fieldLength = getFieldLength(fruData[fruDataIter])) >= 0)
1039         {
1040             if (fruDataIter >= (start + fruAreaSize))
1041             {
1042                 fruDataIter = start + fruAreaSize;
1043                 break;
1044             }
1045             fruDataIter += 1 + fieldLength;
1046         }
1047         endOfFieldsLoc = fruDataIter;
1048     }
1049 
1050     std::copy_n(fruData.begin() + restFRUFieldsLoc,
1051                 endOfFieldsLoc - restFRUFieldsLoc + 1,
1052                 std::back_inserter(restFRUAreaFieldsData));
1053 
1054     fruAreaParams.restFieldsLoc = restFRUFieldsLoc;
1055     fruAreaParams.restFieldsEnd = endOfFieldsLoc;
1056 
1057     return true;
1058 }
1059 
1060 // Get all device dbus path and match path with product name using
1061 // regular expression and find the device index for all devices.
1062 
1063 std::optional<int> findIndexForFRU(
1064     boost::container::flat_map<
1065         std::pair<size_t, size_t>,
1066         std::shared_ptr<sdbusplus::asio::dbus_interface>>& dbusInterfaceMap,
1067     std::string& productName)
1068 {
1069     int highest = -1;
1070     bool found = false;
1071 
1072     for (const auto& busIface : dbusInterfaceMap)
1073     {
1074         std::string path = busIface.second->get_object_path();
1075         if (std::regex_match(path, std::regex(productName + "(_\\d+|)$")))
1076         {
1077             // Check if the match named has extra information.
1078             found = true;
1079             std::smatch baseMatch;
1080 
1081             bool match = std::regex_match(path, baseMatch,
1082                                           std::regex(productName + "_(\\d+)$"));
1083             if (match)
1084             {
1085                 if (baseMatch.size() == 2)
1086                 {
1087                     std::ssub_match baseSubMatch = baseMatch[1];
1088                     std::string base = baseSubMatch.str();
1089 
1090                     int value = std::stoi(base);
1091                     highest = (value > highest) ? value : highest;
1092                 }
1093             }
1094         }
1095     } // end searching objects
1096 
1097     if (!found)
1098     {
1099         return std::nullopt;
1100     }
1101     return highest;
1102 }
1103 
1104 // This function does format fru data as per IPMI format and find the
1105 // productName in the formatted fru data, get that productName and return
1106 // productName if found or return NULL.
1107 
1108 std::optional<std::string> getProductName(
1109     std::vector<uint8_t>& device,
1110     boost::container::flat_map<std::string, std::string>& formattedFRU,
1111     uint32_t bus, uint32_t address, size_t& unknownBusObjectCount)
1112 {
1113     std::string productName;
1114 
1115     resCodes res = formatIPMIFRU(device, formattedFRU);
1116     if (res == resCodes::resErr)
1117     {
1118         std::cerr << "failed to parse FRU for device at bus " << bus
1119                   << " address " << address << "\n";
1120         return std::nullopt;
1121     }
1122     if (res == resCodes::resWarn)
1123     {
1124         std::cerr << "Warnings while parsing FRU for device at bus " << bus
1125                   << " address " << address << "\n";
1126     }
1127 
1128     auto productNameFind = formattedFRU.find("BOARD_PRODUCT_NAME");
1129     // Not found under Board section or an empty string.
1130     if (productNameFind == formattedFRU.end() ||
1131         productNameFind->second.empty())
1132     {
1133         productNameFind = formattedFRU.find("PRODUCT_PRODUCT_NAME");
1134     }
1135     // Found under Product section and not an empty string.
1136     if (productNameFind != formattedFRU.end() &&
1137         !productNameFind->second.empty())
1138     {
1139         productName = productNameFind->second;
1140         std::regex illegalObject("[^A-Za-z0-9_]");
1141         productName = std::regex_replace(productName, illegalObject, "_");
1142     }
1143     else
1144     {
1145         productName = "UNKNOWN" + std::to_string(unknownBusObjectCount);
1146         unknownBusObjectCount++;
1147     }
1148     return productName;
1149 }
1150 
1151 bool getFruData(std::vector<uint8_t>& fruData, uint32_t bus, uint32_t address)
1152 {
1153     try
1154     {
1155         fruData = getFRUInfo(static_cast<uint16_t>(bus),
1156                              static_cast<uint8_t>(address));
1157     }
1158     catch (const std::invalid_argument& e)
1159     {
1160         std::cerr << "Failure getting FRU Info" << e.what() << "\n";
1161         return false;
1162     }
1163 
1164     return !fruData.empty();
1165 }
1166