xref: /openbmc/entity-manager/src/fru_device/fru_utils.cpp (revision 8feb04544ae69154a47c4323f5ada2e6da34f50e)
1 // SPDX-License-Identifier: Apache-2.0
2 // SPDX-FileCopyrightText: Copyright 2018 Intel Corporation
3 
4 #include "fru_utils.hpp"
5 
6 #include <phosphor-logging/lg2.hpp>
7 
8 #include <array>
9 #include <cstddef>
10 #include <cstdint>
11 #include <filesystem>
12 #include <iomanip>
13 #include <numeric>
14 #include <set>
15 #include <sstream>
16 #include <string>
17 #include <vector>
18 
19 extern "C"
20 {
21 // Include for I2C_SMBUS_BLOCK_MAX
22 #include <linux/i2c.h>
23 }
24 
25 constexpr size_t fruVersion = 1; // Current FRU spec version number is 1
26 
27 std::tm intelEpoch()
28 {
29     std::tm val = {};
30     val.tm_year = 1996 - 1900;
31     val.tm_mday = 1;
32     return val;
33 }
34 
35 char sixBitToChar(uint8_t val)
36 {
37     return static_cast<char>((val & 0x3f) + ' ');
38 }
39 
40 char bcdPlusToChar(uint8_t val)
41 {
42     val &= 0xf;
43     return (val < 10) ? static_cast<char>(val + '0') : bcdHighChars[val - 10];
44 }
45 
46 enum FRUDataEncoding
47 {
48     binary = 0x0,
49     bcdPlus = 0x1,
50     sixBitASCII = 0x2,
51     languageDependent = 0x3,
52 };
53 
54 enum MultiRecordType : uint8_t
55 {
56     powerSupplyInfo = 0x00,
57     dcOutput = 0x01,
58     dcLoad = 0x02,
59     managementAccessRecord = 0x03,
60     baseCompatibilityRecord = 0x04,
61     extendedCompatibilityRecord = 0x05,
62     resvASFSMBusDeviceRecord = 0x06,
63     resvASFLegacyDeviceAlerts = 0x07,
64     resvASFRemoteControl = 0x08,
65     extendedDCOutput = 0x09,
66     extendedDCLoad = 0x0A
67 };
68 
69 enum SubManagementAccessRecord : uint8_t
70 {
71     systemManagementURL = 0x01,
72     systemName = 0x02,
73     systemPingAddress = 0x03,
74     componentManagementURL = 0x04,
75     componentName = 0x05,
76     componentPingAddress = 0x06,
77     systemUniqueID = 0x07
78 };
79 
80 /* Decode FRU data into a std::string, given an input iterator and end. If the
81  * state returned is fruDataOk, then the resulting string is the decoded FRU
82  * data. The input iterator is advanced past the data consumed.
83  *
84  * On fruDataErr, we have lost synchronisation with the length bytes, so the
85  * iterator is no longer usable.
86  */
87 std::pair<DecodeState, std::string> decodeFRUData(
88     std::span<const uint8_t>::const_iterator& iter,
89     std::span<const uint8_t>::const_iterator& end, bool isLangEng)
90 {
91     std::string value;
92     unsigned int i = 0;
93 
94     /* we need at least one byte to decode the type/len header */
95     if (iter == end)
96     {
97         lg2::error("Truncated FRU data");
98         return make_pair(DecodeState::err, value);
99     }
100 
101     uint8_t c = *(iter++);
102 
103     /* 0xc1 is the end marker */
104     if (c == 0xc1)
105     {
106         return make_pair(DecodeState::end, value);
107     }
108 
109     /* decode type/len byte */
110     uint8_t type = static_cast<uint8_t>(c >> 6);
111     uint8_t len = static_cast<uint8_t>(c & 0x3f);
112 
113     /* we should have at least len bytes of data available overall */
114     if (iter + len > end)
115     {
116         lg2::error("FRU data field extends past end of FRU area data");
117         return make_pair(DecodeState::err, value);
118     }
119 
120     switch (type)
121     {
122         case FRUDataEncoding::binary:
123         {
124             std::stringstream ss;
125             ss << std::hex << std::setfill('0');
126             for (i = 0; i < len; i++, iter++)
127             {
128                 uint8_t val = static_cast<uint8_t>(*iter);
129                 ss << std::setw(2) << static_cast<int>(val);
130             }
131             value = ss.str();
132             break;
133         }
134         case FRUDataEncoding::languageDependent:
135             /* For language-code dependent encodings, assume 8-bit ASCII */
136             value = std::string(iter, iter + len);
137             iter += len;
138 
139             /* English text is encoded in 8-bit ASCII + Latin 1. All other
140              * languages are required to use 2-byte unicode. FruDevice does not
141              * handle unicode.
142              */
143             if (!isLangEng)
144             {
145                 lg2::error("Error: Non english string is not supported ");
146                 return make_pair(DecodeState::err, value);
147             }
148 
149             break;
150 
151         case FRUDataEncoding::bcdPlus:
152             value = std::string();
153             for (i = 0; i < len; i++, iter++)
154             {
155                 uint8_t val = *iter;
156                 value.push_back(bcdPlusToChar(val >> 4));
157                 value.push_back(bcdPlusToChar(val & 0xf));
158             }
159             break;
160 
161         case FRUDataEncoding::sixBitASCII:
162         {
163             unsigned int accum = 0;
164             unsigned int accumBitLen = 0;
165             value = std::string();
166             for (i = 0; i < len; i++, iter++)
167             {
168                 accum |= *iter << accumBitLen;
169                 accumBitLen += 8;
170                 while (accumBitLen >= 6)
171                 {
172                     value.push_back(sixBitToChar(accum & 0x3f));
173                     accum >>= 6;
174                     accumBitLen -= 6;
175                 }
176             }
177         }
178         break;
179 
180         default:
181         {
182             return make_pair(DecodeState::err, value);
183         }
184     }
185 
186     return make_pair(DecodeState::ok, value);
187 }
188 
189 bool checkLangEng(uint8_t lang)
190 {
191     // If Lang is not English then the encoding is defined as 2-byte UNICODE,
192     // but we don't support that.
193     if ((lang != 0U) && lang != 25)
194     {
195         lg2::error("Warning: languages other than English is not supported");
196         // Return language flag as non english
197         return false;
198     }
199     return true;
200 }
201 
202 /* This function verifies for other offsets to check if they are not
203  * falling under other field area
204  *
205  * fruBytes:    Start of Fru data
206  * currentArea: Index of current area offset to be compared against all area
207  *              offset and it is a multiple of 8 bytes as per specification
208  * len:         Length of current area space and it is a multiple of 8 bytes
209  *              as per specification
210  */
211 bool verifyOffset(std::span<const uint8_t> fruBytes, fruAreas currentArea,
212                   uint8_t len)
213 {
214     unsigned int fruBytesSize = fruBytes.size();
215 
216     // check if Fru data has at least 8 byte header
217     if (fruBytesSize <= fruBlockSize)
218     {
219         lg2::error("Error: trying to parse empty FRU");
220         return false;
221     }
222 
223     // Check range of passed currentArea value
224     if (currentArea > fruAreas::fruAreaMultirecord)
225     {
226         lg2::error("Error: Fru area is out of range");
227         return false;
228     }
229 
230     unsigned int currentAreaIndex = getHeaderAreaFieldOffset(currentArea);
231     if (currentAreaIndex > fruBytesSize)
232     {
233         lg2::error("Error: Fru area index is out of range");
234         return false;
235     }
236 
237     unsigned int start = fruBytes[currentAreaIndex];
238     unsigned int end = start + len;
239 
240     /* Verify each offset within the range of start and end */
241     for (fruAreas area = fruAreas::fruAreaInternal;
242          area <= fruAreas::fruAreaMultirecord; ++area)
243     {
244         // skip the current offset
245         if (area == currentArea)
246         {
247             continue;
248         }
249 
250         unsigned int areaIndex = getHeaderAreaFieldOffset(area);
251         if (areaIndex > fruBytesSize)
252         {
253             lg2::error("Error: Fru area index is out of range");
254             return false;
255         }
256 
257         unsigned int areaOffset = fruBytes[areaIndex];
258         // if areaOffset is 0 means this area is not available so skip
259         if (areaOffset == 0)
260         {
261             continue;
262         }
263 
264         // check for overlapping of current offset with given areaoffset
265         if (areaOffset == start || (areaOffset > start && areaOffset < end))
266         {
267             lg2::error("{AREA1} offset is overlapping with {AREA2} offset",
268                        "AREA1", getFruAreaName(currentArea), "AREA2",
269                        getFruAreaName(area));
270             return false;
271         }
272     }
273     return true;
274 }
275 
276 static void parseMultirecordUUID(
277     std::span<const uint8_t> device,
278     boost::container::flat_map<std::string, std::string>& result)
279 {
280     constexpr size_t uuidDataLen = 16;
281     constexpr size_t multiRecordHeaderLen = 5;
282     /* UUID record data, plus one to skip past the sub-record type byte */
283     constexpr size_t uuidRecordData = multiRecordHeaderLen + 1;
284     constexpr size_t multiRecordEndOfListMask = 0x80;
285     /* The UUID {00112233-4455-6677-8899-AABBCCDDEEFF} would thus be represented
286      * as: 0x33 0x22 0x11 0x00 0x55 0x44 0x77 0x66 0x88 0x99 0xAA 0xBB 0xCC 0xDD
287      * 0xEE 0xFF
288      */
289     const std::array<uint8_t, uuidDataLen> uuidCharOrder = {
290         3, 2, 1, 0, 5, 4, 7, 6, 8, 9, 10, 11, 12, 13, 14, 15};
291     size_t offset = getHeaderAreaFieldOffset(fruAreas::fruAreaMultirecord);
292     if (offset >= device.size())
293     {
294         throw std::runtime_error("Multirecord UUID offset is out of range");
295     }
296     uint32_t areaOffset = device[offset];
297 
298     if (areaOffset == 0)
299     {
300         return;
301     }
302 
303     areaOffset *= fruBlockSize;
304     std::span<const uint8_t>::const_iterator fruBytesIter =
305         device.begin() + areaOffset;
306 
307     /* Verify area offset */
308     if (!verifyOffset(device, fruAreas::fruAreaMultirecord, *fruBytesIter))
309     {
310         return;
311     }
312     while (areaOffset + uuidRecordData + uuidDataLen <= device.size())
313     {
314         if ((areaOffset < device.size()) &&
315             (device[areaOffset] ==
316              (uint8_t)MultiRecordType::managementAccessRecord))
317         {
318             if ((areaOffset + multiRecordHeaderLen < device.size()) &&
319                 (device[areaOffset + multiRecordHeaderLen] ==
320                  (uint8_t)SubManagementAccessRecord::systemUniqueID))
321             {
322                 /* Layout of UUID:
323                  * source: https://www.ietf.org/rfc/rfc4122.txt
324                  *
325                  * UUID binary format (16 bytes):
326                  * 4B-2B-2B-2B-6B (big endian)
327                  *
328                  * UUID string is 36 length of characters (36 bytes):
329                  * 0        9    14   19   24
330                  * xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx
331                  *    be     be   be   be       be
332                  * be means it should be converted to big endian.
333                  */
334                 /* Get UUID bytes to UUID string */
335                 std::stringstream tmp;
336                 tmp << std::hex << std::setfill('0');
337                 for (size_t i = 0; i < uuidDataLen; i++)
338                 {
339                     tmp << std::setw(2)
340                         << static_cast<uint16_t>(
341                                device[areaOffset + uuidRecordData +
342                                       uuidCharOrder[i]]);
343                 }
344                 std::string uuidStr = tmp.str();
345                 result["MULTIRECORD_UUID"] =
346                     uuidStr.substr(0, 8) + '-' + uuidStr.substr(8, 4) + '-' +
347                     uuidStr.substr(12, 4) + '-' + uuidStr.substr(16, 4) + '-' +
348                     uuidStr.substr(20, 12);
349                 break;
350             }
351         }
352         if ((device[areaOffset + 1] & multiRecordEndOfListMask) != 0)
353         {
354             break;
355         }
356         areaOffset = areaOffset + device[areaOffset + 2] + multiRecordHeaderLen;
357     }
358 }
359 
360 resCodes decodeField(
361     std::span<const uint8_t>::const_iterator& fruBytesIter,
362     std::span<const uint8_t>::const_iterator& fruBytesIterEndArea,
363     const std::vector<std::string>& fruAreaFieldNames, size_t& fieldIndex,
364     DecodeState& state, bool isLangEng, const fruAreas& area,
365     boost::container::flat_map<std::string, std::string>& result)
366 {
367     auto res = decodeFRUData(fruBytesIter, fruBytesIterEndArea, isLangEng);
368     state = res.first;
369     std::string value = res.second;
370     std::string name;
371     bool isCustomField = false;
372     if (fieldIndex < fruAreaFieldNames.size())
373     {
374         name = std::string(getFruAreaName(area)) + "_" +
375                fruAreaFieldNames.at(fieldIndex);
376     }
377     else
378     {
379         isCustomField = true;
380         name = std::string(getFruAreaName(area)) + "_" + fruCustomFieldName +
381                std::to_string(fieldIndex - fruAreaFieldNames.size() + 1);
382     }
383 
384     if (state == DecodeState::ok)
385     {
386         // Strip non null characters and trailing spaces from the end
387         value.erase(
388             std::find_if(value.rbegin(), value.rend(),
389                          [](char ch) { return ((ch != 0) && (ch != ' ')); })
390                 .base(),
391             value.end());
392         if (isCustomField)
393         {
394             // Some MAC addresses are stored in a custom field, with
395             // "MAC:" prefixed on the value.  If we see that, create a
396             // new field with the decoded data
397             if (value.starts_with("MAC: "))
398             {
399                 result["MAC_" + name] = value.substr(5);
400             }
401         }
402         result[name] = std::move(value);
403         ++fieldIndex;
404     }
405     else if (state == DecodeState::err)
406     {
407         lg2::error("Error while parsing {NAME}", "NAME", name);
408 
409         // Cancel decoding if failed to parse any of mandatory
410         // fields
411         if (fieldIndex < fruAreaFieldNames.size())
412         {
413             lg2::error("Failed to parse mandatory field ");
414             return resCodes::resErr;
415         }
416         return resCodes::resWarn;
417     }
418     else
419     {
420         if (fieldIndex < fruAreaFieldNames.size())
421         {
422             lg2::error(
423                 "Mandatory fields absent in FRU area {AREA} after {NAME}",
424                 "AREA", getFruAreaName(area), "NAME", name);
425             return resCodes::resWarn;
426         }
427     }
428     return resCodes::resOK;
429 }
430 
431 resCodes formatIPMIFRU(
432     std::span<const uint8_t> fruBytes,
433     boost::container::flat_map<std::string, std::string>& result)
434 {
435     resCodes ret = resCodes::resOK;
436     if (fruBytes.size() <= fruBlockSize)
437     {
438         lg2::error("Error: trying to parse empty FRU ");
439         return resCodes::resErr;
440     }
441     result["Common_Format_Version"] =
442         std::to_string(static_cast<int>(*fruBytes.begin()));
443 
444     const std::vector<std::string>* fruAreaFieldNames = nullptr;
445 
446     // Don't parse Internal and Multirecord areas
447     for (fruAreas area = fruAreas::fruAreaChassis;
448          area <= fruAreas::fruAreaProduct; ++area)
449     {
450         size_t offset = *(fruBytes.begin() + getHeaderAreaFieldOffset(area));
451         if (offset == 0)
452         {
453             continue;
454         }
455         offset *= fruBlockSize;
456         std::span<const uint8_t>::const_iterator fruBytesIter =
457             fruBytes.begin() + offset;
458         if (fruBytesIter + fruBlockSize >= fruBytes.end())
459         {
460             lg2::error("Not enough data to parse ");
461             return resCodes::resErr;
462         }
463         // check for format version 1
464         if (*fruBytesIter != 0x01)
465         {
466             lg2::error("Unexpected version {VERSION}", "VERSION",
467                        *fruBytesIter);
468             return resCodes::resErr;
469         }
470         ++fruBytesIter;
471 
472         /* Verify other area offset for overlap with current area by passing
473          * length of current area offset pointed by *fruBytesIter
474          */
475         if (!verifyOffset(fruBytes, area, *fruBytesIter))
476         {
477             return resCodes::resErr;
478         }
479 
480         size_t fruAreaSize = *fruBytesIter * fruBlockSize;
481         std::span<const uint8_t>::const_iterator fruBytesIterEndArea =
482             fruBytes.begin() + offset + fruAreaSize - 1;
483         ++fruBytesIter;
484 
485         uint8_t fruComputedChecksum =
486             calculateChecksum(fruBytes.begin() + offset, fruBytesIterEndArea);
487         if (fruComputedChecksum != *fruBytesIterEndArea)
488         {
489             std::stringstream ss;
490             ss << std::hex << std::setfill('0');
491             ss << "Checksum error in FRU area " << getFruAreaName(area) << "\n";
492             ss << "\tComputed checksum: 0x" << std::setw(2)
493                << static_cast<int>(fruComputedChecksum) << "\n";
494             ss << "\tThe read checksum: 0x" << std::setw(2)
495                << static_cast<int>(*fruBytesIterEndArea) << "\n";
496             lg2::error("{ERR}", "ERR", ss.str());
497             ret = resCodes::resWarn;
498         }
499 
500         /* Set default language flag to true as Chassis Fru area are always
501          * encoded in English defined in Section 10 of Fru specification
502          */
503 
504         bool isLangEng = true;
505         switch (area)
506         {
507             case fruAreas::fruAreaChassis:
508             {
509                 result["CHASSIS_TYPE"] =
510                     std::to_string(static_cast<int>(*fruBytesIter));
511                 fruBytesIter += 1;
512                 fruAreaFieldNames = &chassisFruAreas;
513                 break;
514             }
515             case fruAreas::fruAreaBoard:
516             {
517                 uint8_t lang = *fruBytesIter;
518                 result["BOARD_LANGUAGE_CODE"] =
519                     std::to_string(static_cast<int>(lang));
520                 isLangEng = checkLangEng(lang);
521                 fruBytesIter += 1;
522 
523                 unsigned int minutes =
524                     *fruBytesIter | *(fruBytesIter + 1) << 8 |
525                     *(fruBytesIter + 2) << 16;
526                 std::tm fruTime = intelEpoch();
527                 std::time_t timeValue = timegm(&fruTime);
528                 timeValue += static_cast<long>(minutes) * 60;
529                 fruTime = *std::gmtime(&timeValue);
530 
531                 // Tue Nov 20 23:08:00 2018
532                 std::array<char, 32> timeString = {};
533                 auto bytes = std::strftime(timeString.data(), timeString.size(),
534                                            "%Y%m%dT%H%M%SZ", &fruTime);
535                 if (bytes == 0)
536                 {
537                     lg2::error("invalid time string encountered");
538                     return resCodes::resErr;
539                 }
540 
541                 result["BOARD_MANUFACTURE_DATE"] =
542                     std::string_view(timeString.data(), bytes);
543                 fruBytesIter += 3;
544                 fruAreaFieldNames = &boardFruAreas;
545                 break;
546             }
547             case fruAreas::fruAreaProduct:
548             {
549                 uint8_t lang = *fruBytesIter;
550                 result["PRODUCT_LANGUAGE_CODE"] =
551                     std::to_string(static_cast<int>(lang));
552                 isLangEng = checkLangEng(lang);
553                 fruBytesIter += 1;
554                 fruAreaFieldNames = &productFruAreas;
555                 break;
556             }
557             default:
558             {
559                 lg2::error(
560                     "Internal error: unexpected FRU area index: {INDEX} ",
561                     "INDEX", static_cast<int>(area));
562                 return resCodes::resErr;
563             }
564         }
565         size_t fieldIndex = 0;
566         DecodeState state = DecodeState::ok;
567         do
568         {
569             resCodes decodeRet = decodeField(fruBytesIter, fruBytesIterEndArea,
570                                              *fruAreaFieldNames, fieldIndex,
571                                              state, isLangEng, area, result);
572             if (decodeRet == resCodes::resErr)
573             {
574                 return resCodes::resErr;
575             }
576             if (decodeRet == resCodes::resWarn)
577             {
578                 ret = decodeRet;
579             }
580         } while (state == DecodeState::ok);
581         for (; fruBytesIter < fruBytesIterEndArea; fruBytesIter++)
582         {
583             uint8_t c = *fruBytesIter;
584             if (c != 0U)
585             {
586                 lg2::error("Non-zero byte after EndOfFields in FRU area {AREA}",
587                            "AREA", getFruAreaName(area));
588                 ret = resCodes::resWarn;
589                 break;
590             }
591         }
592     }
593 
594     /* Parsing the Multirecord UUID */
595     parseMultirecordUUID(fruBytes, result);
596 
597     return ret;
598 }
599 
600 // Calculate new checksum for fru info area
601 uint8_t calculateChecksum(std::span<const uint8_t>::const_iterator iter,
602                           std::span<const uint8_t>::const_iterator end)
603 {
604     constexpr int checksumMod = 256;
605     uint8_t sum = std::accumulate(iter, end, static_cast<uint8_t>(0));
606     return (checksumMod - sum) % checksumMod;
607 }
608 
609 uint8_t calculateChecksum(std::span<const uint8_t> fruAreaData)
610 {
611     return calculateChecksum(fruAreaData.begin(), fruAreaData.end());
612 }
613 
614 // Update new fru area length &
615 // Update checksum at new checksum location
616 // Return the offset of the area checksum byte
617 unsigned int updateFRUAreaLenAndChecksum(
618     std::vector<uint8_t>& fruData, size_t fruAreaStart,
619     size_t fruAreaEndOfFieldsOffset, size_t fruAreaEndOffset)
620 {
621     size_t traverseFRUAreaIndex = fruAreaEndOfFieldsOffset - fruAreaStart;
622 
623     // fill zeros for any remaining unused space
624     std::fill(fruData.begin() + fruAreaEndOfFieldsOffset,
625               fruData.begin() + fruAreaEndOffset, 0);
626 
627     size_t mod = traverseFRUAreaIndex % fruBlockSize;
628     size_t checksumLoc = 0;
629     if (mod == 0U)
630     {
631         traverseFRUAreaIndex += (fruBlockSize);
632         checksumLoc = fruAreaEndOfFieldsOffset + (fruBlockSize - 1);
633     }
634     else
635     {
636         traverseFRUAreaIndex += (fruBlockSize - mod);
637         checksumLoc = fruAreaEndOfFieldsOffset + (fruBlockSize - mod - 1);
638     }
639 
640     size_t newFRUAreaLen =
641         (traverseFRUAreaIndex / fruBlockSize) +
642         static_cast<unsigned long>((traverseFRUAreaIndex % fruBlockSize) != 0);
643     size_t fruAreaLengthLoc = fruAreaStart + 1;
644     fruData[fruAreaLengthLoc] = static_cast<uint8_t>(newFRUAreaLen);
645 
646     // Calculate new checksum
647     std::vector<uint8_t> finalFRUData;
648     std::copy_n(fruData.begin() + fruAreaStart, checksumLoc - fruAreaStart,
649                 std::back_inserter(finalFRUData));
650 
651     fruData[checksumLoc] = calculateChecksum(finalFRUData);
652     return checksumLoc;
653 }
654 
655 ssize_t getFieldLength(uint8_t fruFieldTypeLenValue)
656 {
657     constexpr uint8_t typeLenMask = 0x3F;
658     constexpr uint8_t endOfFields = 0xC1;
659     if (fruFieldTypeLenValue == endOfFields)
660     {
661         return -1;
662     }
663     return fruFieldTypeLenValue & typeLenMask;
664 }
665 
666 bool validateHeader(const std::array<uint8_t, I2C_SMBUS_BLOCK_MAX>& blockData)
667 {
668     // ipmi spec format version number is currently at 1, verify it
669     if (blockData[0] != fruVersion)
670     {
671         lg2::debug(
672             "FRU spec version {VERSION} not supported. Supported version is {SUPPORTED_VERSION}",
673             "VERSION", lg2::hex, blockData[0], "SUPPORTED_VERSION", lg2::hex,
674             fruVersion);
675         return false;
676     }
677 
678     // verify pad is set to 0
679     if (blockData[6] != 0x0)
680     {
681         lg2::debug("Pad value in header is non zero, value is {VALUE}", "VALUE",
682                    lg2::hex, blockData[6]);
683         return false;
684     }
685 
686     // verify offsets are 0, or don't point to another offset
687     std::set<uint8_t> foundOffsets;
688     for (int ii = 1; ii < 6; ii++)
689     {
690         if (blockData[ii] == 0)
691         {
692             continue;
693         }
694         auto inserted = foundOffsets.insert(blockData[ii]);
695         if (!inserted.second)
696         {
697             return false;
698         }
699     }
700 
701     // validate checksum
702     size_t sum = 0;
703     for (int jj = 0; jj < 7; jj++)
704     {
705         sum += blockData[jj];
706     }
707     sum = (256 - sum) & 0xFF;
708 
709     if (sum != blockData[7])
710     {
711         lg2::debug(
712             "Checksum {CHECKSUM} is invalid. calculated checksum is {CALCULATED_CHECKSUM}",
713             "CHECKSUM", lg2::hex, blockData[7], "CALCULATED_CHECKSUM", lg2::hex,
714             sum);
715         return false;
716     }
717     return true;
718 }
719 
720 bool findFRUHeader(FRUReader& reader, const std::string& errorHelp,
721                    std::array<uint8_t, I2C_SMBUS_BLOCK_MAX>& blockData,
722                    off_t& baseOffset)
723 {
724     if (reader.read(baseOffset, 0x8, blockData.data()) < 0)
725     {
726         lg2::error("failed to read {ERR} base offset {OFFSET}", "ERR",
727                    errorHelp, "OFFSET", baseOffset);
728         return false;
729     }
730 
731     // check the header checksum
732     if (validateHeader(blockData))
733     {
734         return true;
735     }
736 
737     // only continue the search if we just looked at 0x0.
738     if (baseOffset != 0)
739     {
740         return false;
741     }
742 
743     // now check for special cases where the IPMI data is at an offset
744 
745     // check if blockData starts with tyanHeader
746     const std::vector<uint8_t> tyanHeader = {'$', 'T', 'Y', 'A', 'N', '$'};
747     if (blockData.size() >= tyanHeader.size() &&
748         std::equal(tyanHeader.begin(), tyanHeader.end(), blockData.begin()))
749     {
750         // look for the FRU header at offset 0x6000
751         baseOffset = 0x6000;
752         return findFRUHeader(reader, errorHelp, blockData, baseOffset);
753     }
754 
755     // check if blockData starts with gigabyteHeader
756     const std::vector<uint8_t> gigabyteHeader = {'G', 'I', 'G', 'A',
757                                                  'B', 'Y', 'T', 'E'};
758     if (blockData.size() >= gigabyteHeader.size() &&
759         std::equal(gigabyteHeader.begin(), gigabyteHeader.end(),
760                    blockData.begin()))
761     {
762         // look for the FRU header at offset 0x4000
763         baseOffset = 0x4000;
764         return findFRUHeader(reader, errorHelp, blockData, baseOffset);
765     }
766 
767     lg2::debug("Illegal header {HEADER} base offset {OFFSET}", "HEADER",
768                errorHelp, "OFFSET", baseOffset);
769 
770     return false;
771 }
772 
773 std::pair<std::vector<uint8_t>, bool> readFRUContents(
774     FRUReader& reader, const std::string& errorHelp)
775 {
776     std::array<uint8_t, I2C_SMBUS_BLOCK_MAX> blockData{};
777     off_t baseOffset = 0x0;
778 
779     if (!findFRUHeader(reader, errorHelp, blockData, baseOffset))
780     {
781         return {{}, false};
782     }
783 
784     std::vector<uint8_t> device;
785     device.insert(device.end(), blockData.begin(),
786                   std::next(blockData.begin(), 8));
787 
788     bool hasMultiRecords = false;
789     size_t fruLength = fruBlockSize; // At least FRU header is present
790     unsigned int prevOffset = 0;
791     for (fruAreas area = fruAreas::fruAreaInternal;
792          area <= fruAreas::fruAreaMultirecord; ++area)
793     {
794         // Offset value can be 255.
795         unsigned int areaOffset = device[getHeaderAreaFieldOffset(area)];
796         if (areaOffset == 0)
797         {
798             continue;
799         }
800 
801         /* Check for offset order, as per Section 17 of FRU specification, FRU
802          * information areas are required to be in order in FRU data layout
803          * which means all offset value should be in increasing order or can be
804          * 0 if that area is not present
805          */
806         if (areaOffset <= prevOffset)
807         {
808             lg2::error(
809                 "Fru area offsets are not in required order as per Section 17 of Fru specification");
810             return {{}, true};
811         }
812         prevOffset = areaOffset;
813 
814         // MultiRecords are different. area is not tracking section, it's
815         // walking the common header.
816         if (area == fruAreas::fruAreaMultirecord)
817         {
818             hasMultiRecords = true;
819             break;
820         }
821 
822         areaOffset *= fruBlockSize;
823 
824         if (reader.read(baseOffset + areaOffset, 0x2, blockData.data()) < 0)
825         {
826             lg2::error("failed to read {ERR} base offset {OFFSET}", "ERR",
827                        errorHelp, "OFFSET", baseOffset);
828             return {{}, true};
829         }
830 
831         // Ignore data type (blockData is already unsigned).
832         size_t length = blockData[1] * fruBlockSize;
833         areaOffset += length;
834         fruLength = (areaOffset > fruLength) ? areaOffset : fruLength;
835     }
836 
837     if (hasMultiRecords)
838     {
839         // device[area count] is the index to the last area because the 0th
840         // entry is not an offset in the common header.
841         unsigned int areaOffset =
842             device[getHeaderAreaFieldOffset(fruAreas::fruAreaMultirecord)];
843         areaOffset *= fruBlockSize;
844 
845         // the multi-area record header is 5 bytes long.
846         constexpr size_t multiRecordHeaderSize = 5;
847         constexpr uint8_t multiRecordEndOfListMask = 0x80;
848 
849         // Sanity hard-limit to 64KB.
850         while (areaOffset < std::numeric_limits<uint16_t>::max())
851         {
852             // In multi-area, the area offset points to the 0th record, each
853             // record has 3 bytes of the header we care about.
854             if (reader.read(baseOffset + areaOffset, 0x3, blockData.data()) < 0)
855             {
856                 lg2::error("failed to read {STR} base offset {OFFSET}", "STR",
857                            errorHelp, "OFFSET", baseOffset);
858                 return {{}, true};
859             }
860 
861             // Ok, let's check the record length, which is in bytes (unsigned,
862             // up to 255, so blockData should hold uint8_t not char)
863             size_t recordLength = blockData[2];
864             areaOffset += (recordLength + multiRecordHeaderSize);
865             fruLength = (areaOffset > fruLength) ? areaOffset : fruLength;
866 
867             // If this is the end of the list bail.
868             if ((blockData[1] & multiRecordEndOfListMask) != 0)
869             {
870                 break;
871             }
872         }
873     }
874 
875     // You already copied these first 8 bytes (the ipmi fru header size)
876     fruLength -= std::min(fruBlockSize, fruLength);
877 
878     int readOffset = fruBlockSize;
879 
880     while (fruLength > 0)
881     {
882         size_t requestLength =
883             std::min(static_cast<size_t>(I2C_SMBUS_BLOCK_MAX), fruLength);
884 
885         if (reader.read(baseOffset + readOffset, requestLength,
886                         blockData.data()) < 0)
887         {
888             lg2::error("failed to read {ERR} base offset {OFFSET}", "ERR",
889                        errorHelp, "OFFSET", baseOffset);
890             return {{}, true};
891         }
892 
893         device.insert(device.end(), blockData.begin(),
894                       std::next(blockData.begin(), requestLength));
895 
896         readOffset += requestLength;
897         fruLength -= std::min(requestLength, fruLength);
898     }
899 
900     return {device, true};
901 }
902 
903 unsigned int getHeaderAreaFieldOffset(fruAreas area)
904 {
905     return static_cast<unsigned int>(area) + 1;
906 }
907 
908 std::vector<uint8_t>& getFRUInfo(const uint16_t& bus, const uint8_t& address)
909 {
910     auto deviceMap = busMap.find(bus);
911     if (deviceMap == busMap.end())
912     {
913         throw std::invalid_argument("Invalid Bus.");
914     }
915     auto device = deviceMap->second->find(address);
916     if (device == deviceMap->second->end())
917     {
918         throw std::invalid_argument("Invalid Address.");
919     }
920     std::vector<uint8_t>& ret = device->second;
921 
922     return ret;
923 }
924 
925 static bool updateHeaderChecksum(std::vector<uint8_t>& fruData)
926 {
927     if (fruData.size() < fruBlockSize)
928     {
929         lg2::debug("FRU data is too small to contain a valid header.");
930         return false;
931     }
932 
933     uint8_t& checksumInBytes = fruData[7];
934     uint8_t checksum =
935         calculateChecksum({fruData.begin(), fruData.begin() + 7});
936     std::swap(checksumInBytes, checksum);
937 
938     if (checksumInBytes != checksum)
939     {
940         lg2::debug(
941             "FRU header checksum updated from {OLD_CHECKSUM} to {NEW_CHECKSUM}",
942             "OLD_CHECKSUM", static_cast<int>(checksum), "NEW_CHECKSUM",
943             static_cast<int>(checksumInBytes));
944     }
945     return true;
946 }
947 
948 bool updateAreaChecksum(std::vector<uint8_t>& fruArea)
949 {
950     if (fruArea.size() < fruBlockSize)
951     {
952         lg2::debug("FRU area is too small to contain a valid header.");
953         return false;
954     }
955     if (fruArea.size() % fruBlockSize != 0)
956     {
957         lg2::debug("FRU area size is not a multiple of {SIZE} bytes.", "SIZE",
958                    fruBlockSize);
959         return false;
960     }
961 
962     uint8_t oldcksum = fruArea[fruArea.size() - 1];
963 
964     fruArea[fruArea.size() - 1] =
965         0; // Reset checksum byte to 0 before recalculating
966     fruArea[fruArea.size() - 1] = calculateChecksum(fruArea);
967 
968     if (oldcksum != fruArea[fruArea.size() - 1])
969     {
970         lg2::debug(
971             "FRU area checksum updated from {OLD_CHECKSUM} to {NEW_CHECKSUM}",
972             "OLD_CHECKSUM", static_cast<int>(oldcksum), "NEW_CHECKSUM",
973             static_cast<int>(fruArea[fruArea.size() - 1]));
974     }
975     return true;
976 }
977 
978 static std::optional<size_t> calculateAreaSize(
979     fruAreas area, std::span<const uint8_t> fruData, size_t areaOffset)
980 {
981     switch (area)
982     {
983         case fruAreas::fruAreaChassis:
984         case fruAreas::fruAreaBoard:
985         case fruAreas::fruAreaProduct:
986             if (areaOffset + 1 >= fruData.size())
987             {
988                 return std::nullopt;
989             }
990             return fruData[areaOffset + 1] * fruBlockSize; // Area size in bytes
991         case fruAreas::fruAreaInternal:
992         {
993             // Internal area size: It is difference between the next area
994             // offset and current area offset
995             for (fruAreas areaIt = fruAreas::fruAreaChassis;
996                  areaIt <= fruAreas::fruAreaMultirecord; ++areaIt)
997             {
998                 size_t headerOffset = getHeaderAreaFieldOffset(areaIt);
999                 if (headerOffset >= fruData.size())
1000                 {
1001                     return std::nullopt;
1002                 }
1003                 size_t nextAreaOffset = fruData[headerOffset];
1004                 if (nextAreaOffset != 0)
1005                 {
1006                     return nextAreaOffset * fruBlockSize - areaOffset;
1007                 }
1008             }
1009             return std::nullopt;
1010         }
1011         break;
1012         case fruAreas::fruAreaMultirecord:
1013             // Multirecord area size.
1014             return fruData.size() - areaOffset; // Area size in bytes
1015         default:
1016             lg2::error("Invalid FRU area: {AREA}", "AREA",
1017                        static_cast<int>(area));
1018     }
1019     return std::nullopt;
1020 }
1021 
1022 static size_t getBlockCount(size_t byteCount)
1023 {
1024     size_t blocks = (byteCount + fruBlockSize - 1) / fruBlockSize;
1025     // if we're perfectly aligned, we need another block for the checksum
1026     if ((byteCount % fruBlockSize) == 0)
1027     {
1028         blocks++;
1029     }
1030     return blocks;
1031 }
1032 
1033 bool disassembleFruData(std::vector<uint8_t>& fruData,
1034                         std::vector<std::vector<uint8_t>>& areasData)
1035 {
1036     if (fruData.size() < 8)
1037     {
1038         lg2::debug("FRU data is too small to contain a valid header.");
1039         return false;
1040     }
1041 
1042     // Clear areasData before disassembling
1043     areasData.clear();
1044 
1045     // Iterate through all areas & store each area data in a vector.
1046     for (fruAreas area = fruAreas::fruAreaInternal;
1047          area <= fruAreas::fruAreaMultirecord; ++area)
1048     {
1049         size_t areaOffset = fruData[getHeaderAreaFieldOffset(area)];
1050 
1051         if (areaOffset == 0)
1052         {
1053             // Store empty area data for areas that are not present
1054             areasData.emplace_back();
1055             continue;               // Skip areas that are not present
1056         }
1057         areaOffset *= fruBlockSize; // Convert to byte offset
1058 
1059         std::optional<size_t> areaSize =
1060             calculateAreaSize(area, fruData, areaOffset);
1061         if (!areaSize)
1062         {
1063             return false;
1064         }
1065 
1066         if ((areaOffset + *areaSize) > fruData.size())
1067         {
1068             lg2::error("Area offset + size exceeds FRU data size.");
1069             return false;
1070         }
1071 
1072         areasData.emplace_back(fruData.begin() + areaOffset,
1073                                fruData.begin() + areaOffset + *areaSize);
1074     }
1075 
1076     return true;
1077 }
1078 
1079 struct FieldInfo
1080 {
1081     size_t length;
1082     size_t index;
1083 };
1084 
1085 static std::optional<FieldInfo> findOrCreateField(
1086     std::vector<uint8_t>& areaData, const std::string& propertyName,
1087     const fruAreas& fruAreaToUpdate)
1088 {
1089     int fieldIndex = 0;
1090     int fieldLength = 0;
1091     std::string areaName = propertyName.substr(0, propertyName.find('_'));
1092     std::string propertyNamePrefix = areaName + "_";
1093     const std::vector<std::string>* fruAreaFieldNames = nullptr;
1094 
1095     switch (fruAreaToUpdate)
1096     {
1097         case fruAreas::fruAreaChassis:
1098             fruAreaFieldNames = &chassisFruAreas;
1099             fieldIndex = 3;
1100             break;
1101         case fruAreas::fruAreaBoard:
1102             fruAreaFieldNames = &boardFruAreas;
1103             fieldIndex = 6;
1104             break;
1105         case fruAreas::fruAreaProduct:
1106             fruAreaFieldNames = &productFruAreas;
1107             fieldIndex = 3;
1108             break;
1109         default:
1110             lg2::info("Invalid FRU area: {AREA}", "AREA",
1111                       static_cast<int>(fruAreaToUpdate));
1112             return std::nullopt;
1113     }
1114 
1115     for (const auto& field : *fruAreaFieldNames)
1116     {
1117         fieldLength = getFieldLength(areaData[fieldIndex]);
1118         if (fieldLength < 0)
1119         {
1120             areaData.insert(areaData.begin() + fieldIndex, 0xc0);
1121             fieldLength = 0;
1122         }
1123 
1124         if (propertyNamePrefix + field == propertyName)
1125         {
1126             return FieldInfo{static_cast<size_t>(fieldLength),
1127                              static_cast<size_t>(fieldIndex)};
1128         }
1129         fieldIndex += 1 + fieldLength;
1130     }
1131 
1132     size_t pos = propertyName.find(fruCustomFieldName);
1133     if (pos == std::string::npos)
1134     {
1135         return std::nullopt;
1136     }
1137 
1138     // Get field after pos
1139     std::string customFieldIdx =
1140         propertyName.substr(pos + fruCustomFieldName.size());
1141 
1142     // Check if customFieldIdx is a number
1143     if (!std::all_of(customFieldIdx.begin(), customFieldIdx.end(), ::isdigit))
1144     {
1145         return std::nullopt;
1146     }
1147 
1148     size_t customFieldIndex = std::stoi(customFieldIdx);
1149 
1150     // insert custom fields up to the index we want
1151     for (size_t i = 0; i < customFieldIndex; i++)
1152     {
1153         fieldLength = getFieldLength(areaData[fieldIndex]);
1154         if (fieldLength < 0)
1155         {
1156             areaData.insert(areaData.begin() + fieldIndex, 0xc0);
1157             fieldLength = 0;
1158         }
1159         fieldIndex += 1 + fieldLength;
1160     }
1161 
1162     fieldIndex -= (fieldLength + 1);
1163     fieldLength = getFieldLength(areaData[fieldIndex]);
1164     return FieldInfo{static_cast<size_t>(fieldLength),
1165                      static_cast<size_t>(fieldIndex)};
1166 }
1167 
1168 static std::optional<size_t> findEndOfFieldMarker(std::span<uint8_t> bytes)
1169 {
1170     // we're skipping the checksum
1171     // this function assumes a properly sized and formatted area
1172     static uint8_t constexpr endOfFieldsByte = 0xc1;
1173     for (int index = bytes.size() - 2; index >= 0; --index)
1174     {
1175         if (bytes[index] == endOfFieldsByte)
1176         {
1177             return index;
1178         }
1179     }
1180     return std::nullopt;
1181 }
1182 
1183 static std::optional<size_t> getNonPaddedSizeOfArea(std::span<uint8_t> bytes)
1184 {
1185     if (auto endOfFields = findEndOfFieldMarker(bytes))
1186     {
1187         return *endOfFields + 1;
1188     }
1189     return std::nullopt;
1190 }
1191 
1192 bool setField(const fruAreas& fruAreaToUpdate, std::vector<uint8_t>& areaData,
1193               const std::string& propertyName, const std::string& value)
1194 {
1195     if (value.size() == 1 || value.size() > 63)
1196     {
1197         lg2::error("Invalid value {VALUE} for field {PROP}", "VALUE", value,
1198                    "PROP", propertyName);
1199         return false;
1200     }
1201 
1202     // This is inneficient, but the alternative requires
1203     // a bunch of complicated indexing and search to
1204     // figure out if we cross a block boundary
1205     // if we feel that this is too inneficient in the future,
1206     // we can implement that.
1207     std::vector<uint8_t> tmpBuffer = areaData;
1208 
1209     auto fieldInfo =
1210         findOrCreateField(tmpBuffer, propertyName, fruAreaToUpdate);
1211 
1212     if (!fieldInfo)
1213     {
1214         lg2::error("Field {FIELD} not found in area {AREA}", "FIELD",
1215                    propertyName, "AREA", getFruAreaName(fruAreaToUpdate));
1216         return false;
1217     }
1218 
1219     auto fieldIt = tmpBuffer.begin() + fieldInfo->index;
1220     // Erase the existing field content.
1221     tmpBuffer.erase(fieldIt, fieldIt + fieldInfo->length + 1);
1222     // Insert the new field value
1223     tmpBuffer.insert(fieldIt, 0xc0 | value.size());
1224     tmpBuffer.insert_range(fieldIt + 1, value);
1225 
1226     auto newSize = getNonPaddedSizeOfArea(tmpBuffer);
1227     auto oldSize = getNonPaddedSizeOfArea(areaData);
1228 
1229     if (!oldSize || !newSize)
1230     {
1231         lg2::error("Failed to find the size of the area");
1232         return false;
1233     }
1234 
1235     size_t newSizePadded = getBlockCount(*newSize);
1236 #ifndef ENABLE_FRU_AREA_RESIZE
1237 
1238     size_t oldSizePadded = getBlockCount(*oldSize);
1239 
1240     if (newSizePadded != oldSizePadded)
1241     {
1242         lg2::error(
1243             "FRU area {AREA} resize is disabled, cannot increase size from {OLD_SIZE} to {NEW_SIZE}",
1244             "AREA", getFruAreaName(fruAreaToUpdate), "OLD_SIZE",
1245             static_cast<int>(oldSizePadded), "NEW_SIZE",
1246             static_cast<int>(newSizePadded));
1247         return false;
1248     }
1249 #endif
1250     // Resize the buffer as per numOfBlocks & pad with zeros
1251     tmpBuffer.resize(newSizePadded * fruBlockSize, 0);
1252 
1253     // Update the length field
1254     tmpBuffer[1] = newSizePadded;
1255     updateAreaChecksum(tmpBuffer);
1256 
1257     areaData = std::move(tmpBuffer);
1258 
1259     return true;
1260 }
1261 
1262 bool assembleFruData(std::vector<uint8_t>& fruData,
1263                      const std::vector<std::vector<uint8_t>>& areasData)
1264 {
1265     for (const auto& area : areasData)
1266     {
1267         if ((area.size() % fruBlockSize) != 0U)
1268         {
1269             lg2::error("unaligned area sent to assembleFruData");
1270             return false;
1271         }
1272     }
1273 
1274     // Clear the existing FRU data
1275     fruData.clear();
1276     fruData.resize(8); // Start with the header size
1277 
1278     // Write the header
1279     fruData[0] = fruVersion; // Version
1280     fruData[1] = 0;          // Internal area offset
1281     fruData[2] = 0;          // Chassis area offset
1282     fruData[3] = 0;          // Board area offset
1283     fruData[4] = 0;          // Product area offset
1284     fruData[5] = 0;          // Multirecord area offset
1285     fruData[6] = 0;          // Pad
1286     fruData[7] = 0;          // Checksum (to be updated later)
1287 
1288     size_t writeOffset = 8;  // Start writing after the header
1289 
1290     for (fruAreas area = fruAreas::fruAreaInternal;
1291          area <= fruAreas::fruAreaMultirecord; ++area)
1292     {
1293         const auto& areaBytes = areasData[static_cast<size_t>(area)];
1294 
1295         if (areaBytes.empty())
1296         {
1297             lg2::debug("Skipping empty area: {AREA}", "AREA",
1298                        getFruAreaName(area));
1299             continue; // Skip areas that are not present
1300         }
1301 
1302         // Set the area offset in the header
1303         fruData[getHeaderAreaFieldOffset(area)] = writeOffset / fruBlockSize;
1304         fruData.append_range(areaBytes);
1305         writeOffset += areaBytes.size();
1306     }
1307 
1308     // Update the header checksum
1309     if (!updateHeaderChecksum(fruData))
1310     {
1311         lg2::error("failed to update header checksum");
1312         return false;
1313     }
1314 
1315     return true;
1316 }
1317 
1318 // Create a dummy area in areData variable based on specified fruArea
1319 bool createDummyArea(fruAreas fruArea, std::vector<uint8_t>& areaData)
1320 {
1321     uint8_t numOfFields = 0;
1322     uint8_t numOfBlocks = 0;
1323     // Clear the areaData vector
1324     areaData.clear();
1325 
1326     // Set the version, length, and other fields
1327     areaData.push_back(fruVersion); // Version 1
1328     areaData.push_back(0);          // Length (to be updated later)
1329 
1330     switch (fruArea)
1331     {
1332         case fruAreas::fruAreaChassis:
1333             areaData.push_back(0x00); // Chassis type
1334             numOfFields = chassisFruAreas.size();
1335             break;
1336         case fruAreas::fruAreaBoard:
1337             areaData.push_back(0x00); // Board language code (default)
1338             areaData.insert(areaData.end(),
1339                             {0x00, 0x00,
1340                              0x00}); // Board manufacturer date (default)
1341             numOfFields = boardFruAreas.size();
1342             break;
1343         case fruAreas::fruAreaProduct:
1344             areaData.push_back(0x00); // Product language code (default)
1345             numOfFields = productFruAreas.size();
1346             break;
1347         default:
1348             lg2::debug("Invalid FRU area to create: {AREA}", "AREA",
1349                        static_cast<int>(fruArea));
1350             return false;
1351     }
1352 
1353     for (size_t i = 0; i < numOfFields; ++i)
1354     {
1355         areaData.push_back(0xc0); // Empty field type
1356     }
1357 
1358     // Add EndOfFields marker
1359     areaData.push_back(0xC1);
1360     numOfBlocks = (areaData.size() + fruBlockSize - 1) /
1361                   fruBlockSize; // Calculate number of blocks needed
1362     areaData.resize(numOfBlocks * fruBlockSize, 0); // Fill with zeros
1363     areaData[1] = numOfBlocks;                      // Update length field
1364     updateAreaChecksum(areaData);
1365 
1366     return true;
1367 }
1368 
1369 // Iterate FruArea Names and find start and size of the fru area that contains
1370 // the propertyName and the field start location for the property. fruAreaParams
1371 // struct values fruAreaStart, fruAreaSize, fruAreaEnd, fieldLoc values gets
1372 // updated/returned if successful.
1373 
1374 bool findFruAreaLocationAndField(std::vector<uint8_t>& fruData,
1375                                  const std::string& propertyName,
1376                                  struct FruArea& fruAreaParams)
1377 {
1378     const std::vector<std::string>* fruAreaFieldNames = nullptr;
1379 
1380     uint8_t fruAreaOffsetFieldValue = 0;
1381     size_t offset = 0;
1382     std::string areaName = propertyName.substr(0, propertyName.find('_'));
1383     std::string propertyNamePrefix = areaName + "_";
1384     auto it = std::find(fruAreaNames.begin(), fruAreaNames.end(), areaName);
1385     if (it == fruAreaNames.end())
1386     {
1387         lg2::error("Can't parse area name for property {PROP} ", "PROP",
1388                    propertyName);
1389         return false;
1390     }
1391     fruAreas fruAreaToUpdate = static_cast<fruAreas>(it - fruAreaNames.begin());
1392     fruAreaOffsetFieldValue =
1393         fruData[getHeaderAreaFieldOffset(fruAreaToUpdate)];
1394     switch (fruAreaToUpdate)
1395     {
1396         case fruAreas::fruAreaChassis:
1397             offset = 3; // chassis part number offset. Skip fixed first 3 bytes
1398             fruAreaFieldNames = &chassisFruAreas;
1399             break;
1400         case fruAreas::fruAreaBoard:
1401             offset = 6; // board manufacturer offset. Skip fixed first 6 bytes
1402             fruAreaFieldNames = &boardFruAreas;
1403             break;
1404         case fruAreas::fruAreaProduct:
1405             // Manufacturer name offset. Skip fixed first 3 product fru bytes
1406             // i.e. version, area length and language code
1407             offset = 3;
1408             fruAreaFieldNames = &productFruAreas;
1409             break;
1410         default:
1411             lg2::error("Invalid PropertyName {PROP}", "PROP", propertyName);
1412             return false;
1413     }
1414     if (fruAreaOffsetFieldValue == 0)
1415     {
1416         lg2::error("FRU Area for {PROP} not present ", "PROP", propertyName);
1417         return false;
1418     }
1419 
1420     fruAreaParams.start = fruAreaOffsetFieldValue * fruBlockSize;
1421     fruAreaParams.size = fruData[fruAreaParams.start + 1] * fruBlockSize;
1422     fruAreaParams.end = fruAreaParams.start + fruAreaParams.size;
1423     size_t fruDataIter = fruAreaParams.start + offset;
1424     size_t skipToFRUUpdateField = 0;
1425     ssize_t fieldLength = 0;
1426 
1427     bool found = false;
1428     for (const auto& field : *fruAreaFieldNames)
1429     {
1430         skipToFRUUpdateField++;
1431         if (propertyName == propertyNamePrefix + field)
1432         {
1433             found = true;
1434             break;
1435         }
1436     }
1437     if (!found)
1438     {
1439         std::size_t pos = propertyName.find(fruCustomFieldName);
1440         if (pos == std::string::npos)
1441         {
1442             lg2::error("PropertyName doesn't exist in FRU Area Vectors: {PROP}",
1443                        "PROP", propertyName);
1444             return false;
1445         }
1446         std::string fieldNumStr =
1447             propertyName.substr(pos + fruCustomFieldName.length());
1448         size_t fieldNum = std::stoi(fieldNumStr);
1449         if (fieldNum == 0)
1450         {
1451             lg2::error("PropertyName not recognized: {PROP}", "PROP",
1452                        propertyName);
1453             return false;
1454         }
1455         skipToFRUUpdateField += fieldNum;
1456     }
1457 
1458     for (size_t i = 1; i < skipToFRUUpdateField; i++)
1459     {
1460         if (fruDataIter < fruData.size())
1461         {
1462             fieldLength = getFieldLength(fruData[fruDataIter]);
1463 
1464             if (fieldLength < 0)
1465             {
1466                 break;
1467             }
1468             fruDataIter += 1 + fieldLength;
1469         }
1470     }
1471     fruAreaParams.updateFieldLoc = fruDataIter;
1472 
1473     return true;
1474 }
1475 
1476 // Copy the FRU Area fields and properties into restFRUAreaFieldsData vector.
1477 // Return true for success and false for failure.
1478 
1479 bool copyRestFRUArea(std::vector<uint8_t>& fruData,
1480                      const std::string& propertyName,
1481                      struct FruArea& fruAreaParams,
1482                      std::vector<uint8_t>& restFRUAreaFieldsData)
1483 {
1484     size_t fieldLoc = fruAreaParams.updateFieldLoc;
1485     size_t start = fruAreaParams.start;
1486     size_t fruAreaSize = fruAreaParams.size;
1487 
1488     // Push post update fru field bytes to a vector
1489     ssize_t fieldLength = getFieldLength(fruData[fieldLoc]);
1490     if (fieldLength < 0)
1491     {
1492         lg2::error("Property {PROP} not present ", "PROP", propertyName);
1493         return false;
1494     }
1495 
1496     size_t fruDataIter = 0;
1497     fruDataIter = fieldLoc;
1498     fruDataIter += 1 + fieldLength;
1499     size_t restFRUFieldsLoc = fruDataIter;
1500     size_t endOfFieldsLoc = 0;
1501 
1502     if (fruDataIter < fruData.size())
1503     {
1504         while ((fieldLength = getFieldLength(fruData[fruDataIter])) >= 0)
1505         {
1506             if (fruDataIter >= (start + fruAreaSize))
1507             {
1508                 fruDataIter = start + fruAreaSize;
1509                 break;
1510             }
1511             fruDataIter += 1 + fieldLength;
1512         }
1513         endOfFieldsLoc = fruDataIter;
1514     }
1515 
1516     std::copy_n(fruData.begin() + restFRUFieldsLoc,
1517                 endOfFieldsLoc - restFRUFieldsLoc + 1,
1518                 std::back_inserter(restFRUAreaFieldsData));
1519 
1520     fruAreaParams.restFieldsLoc = restFRUFieldsLoc;
1521     fruAreaParams.restFieldsEnd = endOfFieldsLoc;
1522 
1523     return true;
1524 }
1525 
1526 // Get all device dbus path and match path with product name using
1527 // regular expression and find the device index for all devices.
1528 
1529 std::optional<int> findIndexForFRU(
1530     boost::container::flat_map<
1531         std::pair<size_t, size_t>,
1532         std::shared_ptr<sdbusplus::asio::dbus_interface>>& dbusInterfaceMap,
1533     std::string& productName)
1534 {
1535     int highest = -1;
1536     bool found = false;
1537 
1538     for (const auto& busIface : dbusInterfaceMap)
1539     {
1540         std::string path = busIface.second->get_object_path();
1541         if (std::regex_match(path, std::regex(productName + "(_\\d+|)$")))
1542         {
1543             // Check if the match named has extra information.
1544             found = true;
1545             std::smatch baseMatch;
1546 
1547             bool match = std::regex_match(path, baseMatch,
1548                                           std::regex(productName + "_(\\d+)$"));
1549             if (match)
1550             {
1551                 if (baseMatch.size() == 2)
1552                 {
1553                     std::ssub_match baseSubMatch = baseMatch[1];
1554                     std::string base = baseSubMatch.str();
1555 
1556                     int value = std::stoi(base);
1557                     highest = (value > highest) ? value : highest;
1558                 }
1559             }
1560         }
1561     } // end searching objects
1562 
1563     if (!found)
1564     {
1565         return std::nullopt;
1566     }
1567     return highest;
1568 }
1569 
1570 // This function does format fru data as per IPMI format and find the
1571 // productName in the formatted fru data, get that productName and return
1572 // productName if found or return NULL.
1573 
1574 std::optional<std::string> getProductName(
1575     std::vector<uint8_t>& device,
1576     boost::container::flat_map<std::string, std::string>& formattedFRU,
1577     uint32_t bus, uint32_t address, size_t& unknownBusObjectCount)
1578 {
1579     std::string productName;
1580 
1581     resCodes res = formatIPMIFRU(device, formattedFRU);
1582     if (res == resCodes::resErr)
1583     {
1584         lg2::error("failed to parse FRU for device at bus {BUS} address {ADDR}",
1585                    "BUS", bus, "ADDR", address);
1586         return std::nullopt;
1587     }
1588     if (res == resCodes::resWarn)
1589     {
1590         lg2::error(
1591             "Warnings while parsing FRU for device at bus {BUS} address {ADDR}",
1592             "BUS", bus, "ADDR", address);
1593     }
1594 
1595     auto productNameFind = formattedFRU.find("BOARD_PRODUCT_NAME");
1596     // Not found under Board section or an empty string.
1597     if (productNameFind == formattedFRU.end() ||
1598         productNameFind->second.empty())
1599     {
1600         productNameFind = formattedFRU.find("PRODUCT_PRODUCT_NAME");
1601     }
1602     // Found under Product section and not an empty string.
1603     if (productNameFind != formattedFRU.end() &&
1604         !productNameFind->second.empty())
1605     {
1606         productName = productNameFind->second;
1607         std::regex illegalObject("[^A-Za-z0-9_]");
1608         productName = std::regex_replace(productName, illegalObject, "_");
1609     }
1610     else
1611     {
1612         productName = "UNKNOWN" + std::to_string(unknownBusObjectCount);
1613         unknownBusObjectCount++;
1614     }
1615     return productName;
1616 }
1617 
1618 bool getFruData(std::vector<uint8_t>& fruData, uint32_t bus, uint32_t address)
1619 {
1620     try
1621     {
1622         fruData = getFRUInfo(static_cast<uint16_t>(bus),
1623                              static_cast<uint8_t>(address));
1624     }
1625     catch (const std::invalid_argument& e)
1626     {
1627         lg2::error("Failure getting FRU Info: {ERR}", "ERR", e);
1628         return false;
1629     }
1630 
1631     return !fruData.empty();
1632 }
1633 
1634 bool isFieldEditable(std::string_view fieldName)
1635 {
1636     if (fieldName == "PRODUCT_ASSET_TAG")
1637     {
1638         return true; // PRODUCT_ASSET_TAG is always editable.
1639     }
1640 
1641     if (!ENABLE_FRU_UPDATE_PROPERTY)
1642     {
1643         return false; // If FRU update is disabled, no fields are editable.
1644     }
1645 
1646     // Editable fields
1647     constexpr std::array<std::string_view, 8> editableFields = {
1648         "MANUFACTURER",  "PRODUCT_NAME", "PART_NUMBER",    "VERSION",
1649         "SERIAL_NUMBER", "ASSET_TAG",    "FRU_VERSION_ID", "INFO_AM"};
1650 
1651     // Find position of first underscore
1652     std::size_t pos = fieldName.find('_');
1653     if (pos == std::string_view::npos || pos + 1 >= fieldName.size())
1654     {
1655         return false;
1656     }
1657 
1658     // Extract substring after the underscore
1659     std::string_view subField = fieldName.substr(pos + 1);
1660 
1661     // Trim trailing digits
1662     while (!subField.empty() && (std::isdigit(subField.back()) != 0))
1663     {
1664         subField.remove_suffix(1);
1665     }
1666 
1667     // Match against editable fields
1668     return std::ranges::contains(editableFields, subField);
1669 }
1670