xref: /openbmc/phosphor-host-ipmid/dbus-sdr/storagecommands.cpp (revision f60be6943395f0d9283debc6e5fc558b7fca89ef)
1 /*
2 // Copyright (c) 2017-2019 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 
17 #include "dbus-sdr/storagecommands.hpp"
18 
19 #include "dbus-sdr/sdrutils.hpp"
20 #include "selutility.hpp"
21 
22 #include <boost/algorithm/string.hpp>
23 #include <boost/asio/detached.hpp>
24 #include <boost/container/flat_map.hpp>
25 #include <ipmid/api.hpp>
26 #include <ipmid/message.hpp>
27 #include <ipmid/types.hpp>
28 #include <ipmid/utils.hpp>
29 #include <phosphor-logging/lg2.hpp>
30 #include <sdbusplus/message/types.hpp>
31 #include <sdbusplus/timer.hpp>
32 
33 #include <filesystem>
34 #include <fstream>
35 #include <functional>
36 #include <optional>
37 #include <stdexcept>
38 #include <string_view>
39 
40 static constexpr bool DEBUG = false;
41 
42 namespace dynamic_sensors::ipmi::sel
43 {
44 static const std::filesystem::path selLogDir = "/var/log";
45 static const std::string selLogFilename = "ipmi_sel";
46 
47 static int getFileTimestamp(const std::filesystem::path& file)
48 {
49     struct stat st;
50 
51     if (stat(file.c_str(), &st) >= 0)
52     {
53         return st.st_mtime;
54     }
55     return ::ipmi::sel::invalidTimeStamp;
56 }
57 
58 namespace erase_time
59 {
60 static constexpr const char* selEraseTimestamp = "/var/lib/ipmi/sel_erase_time";
61 
62 int get()
63 {
64     return getFileTimestamp(selEraseTimestamp);
65 }
66 } // namespace erase_time
67 } // namespace dynamic_sensors::ipmi::sel
68 
69 namespace ipmi
70 {
71 
72 namespace storage
73 {
74 
75 constexpr static const size_t maxFruSdrNameSize = 16;
76 using ObjectType =
77     boost::container::flat_map<std::string,
78                                boost::container::flat_map<std::string, Value>>;
79 using ManagedObjectType =
80     boost::container::flat_map<sdbusplus::message::object_path, ObjectType>;
81 using ManagedEntry = std::pair<sdbusplus::message::object_path, ObjectType>;
82 using Paths = std::vector<std::string>;
83 
84 constexpr static const char* fruDeviceServiceName =
85     "xyz.openbmc_project.FruDevice";
86 constexpr static const size_t writeTimeoutSeconds = 10;
87 constexpr static const char* chassisTypeRackMount = "23";
88 constexpr static const char* chassisTypeMainServer = "17";
89 
90 static std::vector<uint8_t> fruCache;
91 static constexpr uint16_t invalidBus = 0xFFFF;
92 static constexpr uint8_t invalidAddr = 0xFF;
93 static constexpr uint8_t typeASCIILatin8 = 0xC0;
94 static uint16_t cacheBus = invalidBus;
95 static uint8_t cacheAddr = invalidAddr;
96 static uint8_t lastDevId = 0xFF;
97 
98 static uint16_t writeBus = invalidBus;
99 static uint8_t writeAddr = invalidAddr;
100 
101 std::unique_ptr<sdbusplus::Timer> writeTimer = nullptr;
102 static std::vector<sdbusplus::bus::match_t> fruMatches;
103 
104 ManagedObjectType frus;
105 
106 // we unfortunately have to build a map of hashes in case there is a
107 // collision to verify our dev-id
108 boost::container::flat_map<uint8_t, std::pair<uint16_t, uint8_t>> deviceHashes;
109 void registerStorageFunctions() __attribute__((constructor));
110 
111 bool writeFru(const std::vector<uint8_t>& fru)
112 {
113     if (writeBus == invalidBus && writeAddr == invalidAddr)
114     {
115         return true;
116     }
117     lastDevId = 0xFF;
118     std::shared_ptr<sdbusplus::asio::connection> dbus = getSdBus();
119     sdbusplus::message_t writeFru = dbus->new_method_call(
120         fruDeviceServiceName, "/xyz/openbmc_project/FruDevice",
121         "xyz.openbmc_project.FruDeviceManager", "WriteFru");
122     writeFru.append(writeBus, writeAddr, fru);
123     try
124     {
125         sdbusplus::message_t writeFruResp = dbus->call(writeFru);
126     }
127     catch (const sdbusplus::exception_t&)
128     {
129         // todo: log sel?
130         lg2::error("error writing fru");
131         return false;
132     }
133     writeBus = invalidBus;
134     writeAddr = invalidAddr;
135     return true;
136 }
137 
138 void writeFruCache()
139 {
140     writeFru(fruCache);
141 }
142 
143 void createTimers()
144 {
145     writeTimer = std::make_unique<sdbusplus::Timer>(writeFruCache);
146 }
147 
148 void recalculateHashes()
149 {
150     deviceHashes.clear();
151     // hash the object paths to create unique device id's. increment on
152     // collision
153     std::hash<std::string> hasher;
154     for (const auto& fru : frus)
155     {
156         auto fruIface = fru.second.find("xyz.openbmc_project.FruDevice");
157         if (fruIface == fru.second.end())
158         {
159             continue;
160         }
161 
162         auto busFind = fruIface->second.find("BUS");
163         auto addrFind = fruIface->second.find("ADDRESS");
164         if (busFind == fruIface->second.end() ||
165             addrFind == fruIface->second.end())
166         {
167             lg2::info("fru device missing Bus or Address, fru: {FRU}", "FRU",
168                       fru.first.str);
169             continue;
170         }
171 
172         uint16_t fruBus = std::get<uint32_t>(busFind->second);
173         uint8_t fruAddr = std::get<uint32_t>(addrFind->second);
174         auto chassisFind = fruIface->second.find("CHASSIS_TYPE");
175         std::string chassisType;
176         if (chassisFind != fruIface->second.end())
177         {
178             chassisType = std::get<std::string>(chassisFind->second);
179         }
180 
181         uint8_t fruHash = 0;
182         if (chassisType.compare(chassisTypeRackMount) != 0 &&
183             chassisType.compare(chassisTypeMainServer) != 0)
184         {
185             fruHash = hasher(fru.first.str);
186             // can't be 0xFF based on spec, and 0 is reserved for baseboard
187             if (fruHash == 0 || fruHash == 0xFF)
188             {
189                 fruHash = 1;
190             }
191         }
192         std::pair<uint16_t, uint8_t> newDev(fruBus, fruAddr);
193 
194         bool emplacePassed = false;
195         while (!emplacePassed)
196         {
197             auto resp = deviceHashes.emplace(fruHash, newDev);
198             emplacePassed = resp.second;
199             if (!emplacePassed)
200             {
201                 fruHash++;
202                 // can't be 0xFF based on spec, and 0 is reserved for
203                 // baseboard
204                 if (fruHash == 0XFF)
205                 {
206                     fruHash = 0x1;
207                 }
208             }
209         }
210     }
211 }
212 
213 void replaceCacheFru(
214     const std::shared_ptr<sdbusplus::asio::connection>& bus,
215     boost::asio::yield_context& yield,
216     [[maybe_unused]] const std::optional<std::string>& path = std::nullopt)
217 {
218     boost::system::error_code ec;
219 
220     frus = bus->yield_method_call<ManagedObjectType>(
221         yield, ec, fruDeviceServiceName, "/",
222         "org.freedesktop.DBus.ObjectManager", "GetManagedObjects");
223     if (ec)
224     {
225         lg2::error("GetMangagedObjects for replaceCacheFru failed: {ERROR}",
226                    "ERROR", ec.message());
227 
228         return;
229     }
230     recalculateHashes();
231 }
232 
233 std::pair<ipmi::Cc, std::vector<uint8_t>> getFru(ipmi::Context::ptr ctx,
234                                                  uint8_t devId)
235 {
236     if (lastDevId == devId && devId != 0xFF)
237     {
238         return {ipmi::ccSuccess, fruCache};
239     }
240 
241     auto deviceFind = deviceHashes.find(devId);
242     if (deviceFind == deviceHashes.end())
243     {
244         return {ipmi::ccSensorInvalid, {}};
245     }
246 
247     cacheBus = deviceFind->second.first;
248     cacheAddr = deviceFind->second.second;
249 
250     boost::system::error_code ec;
251     std::vector<uint8_t> fru = ipmi::callDbusMethod<std::vector<uint8_t>>(
252         ctx, ec, fruDeviceServiceName, "/xyz/openbmc_project/FruDevice",
253         "xyz.openbmc_project.FruDeviceManager", "GetRawFru", cacheBus,
254         cacheAddr);
255 
256     if (ec)
257     {
258         lg2::error("Couldn't get raw fru: {ERROR}", "ERROR", ec.message());
259 
260         cacheBus = invalidBus;
261         cacheAddr = invalidAddr;
262         return {ipmi::ccResponseError, {}};
263     }
264 
265     fruCache.clear();
266     lastDevId = devId;
267     fruCache = fru;
268 
269     return {ipmi::ccSuccess, fru};
270 }
271 
272 void writeFruIfRunning()
273 {
274     if (!writeTimer->isRunning())
275     {
276         return;
277     }
278     writeTimer->stop();
279     writeFruCache();
280 }
281 
282 void startMatch(void)
283 {
284     if (fruMatches.size())
285     {
286         return;
287     }
288 
289     fruMatches.reserve(2);
290 
291     auto bus = getSdBus();
292     fruMatches.emplace_back(
293         *bus,
294         "type='signal',arg0path='/xyz/openbmc_project/"
295         "FruDevice/',member='InterfacesAdded'",
296         [](sdbusplus::message_t& message) {
297             sdbusplus::message::object_path path;
298             ObjectType object;
299             try
300             {
301                 message.read(path, object);
302             }
303             catch (const sdbusplus::exception_t&)
304             {
305                 return;
306             }
307             auto findType = object.find("xyz.openbmc_project.FruDevice");
308             if (findType == object.end())
309             {
310                 return;
311             }
312             writeFruIfRunning();
313             frus[path] = object;
314             recalculateHashes();
315             lastDevId = 0xFF;
316         });
317 
318     fruMatches.emplace_back(
319         *bus,
320         "type='signal',arg0path='/xyz/openbmc_project/"
321         "FruDevice/',member='InterfacesRemoved'",
322         [](sdbusplus::message_t& message) {
323             sdbusplus::message::object_path path;
324             std::set<std::string> interfaces;
325             try
326             {
327                 message.read(path, interfaces);
328             }
329             catch (const sdbusplus::exception_t&)
330             {
331                 return;
332             }
333             auto findType = interfaces.find("xyz.openbmc_project.FruDevice");
334             if (findType == interfaces.end())
335             {
336                 return;
337             }
338             writeFruIfRunning();
339             frus.erase(path);
340             recalculateHashes();
341             lastDevId = 0xFF;
342         });
343 
344     // call once to populate
345     boost::asio::spawn(
346         *getIoContext(),
347         [](boost::asio::yield_context yield) {
348             replaceCacheFru(getSdBus(), yield);
349         },
350         boost::asio::detached);
351 }
352 
353 /** @brief implements the read FRU data command
354  *  @param fruDeviceId        - FRU Device ID
355  *  @param fruInventoryOffset - FRU Inventory Offset to write
356  *  @param countToRead        - Count to read
357  *
358  *  @returns ipmi completion code plus response data
359  *   - countWritten  - Count written
360  */
361 ipmi::RspType<uint8_t,             // Count
362               std::vector<uint8_t> // Requested data
363               >
364     ipmiStorageReadFruData(ipmi::Context::ptr ctx, uint8_t fruDeviceId,
365                            uint16_t fruInventoryOffset, uint8_t countToRead)
366 {
367     if (fruDeviceId == 0xFF)
368     {
369         return ipmi::responseInvalidFieldRequest();
370     }
371 
372     auto [status, fru] = getFru(ctx, fruDeviceId);
373     if (status != ipmi::ccSuccess)
374     {
375         return ipmi::response(status);
376     }
377 
378     size_t fromFruByteLen = 0;
379     if (countToRead + fruInventoryOffset < fru.size())
380     {
381         fromFruByteLen = countToRead;
382     }
383     else if (fru.size() > fruInventoryOffset)
384     {
385         fromFruByteLen = fru.size() - fruInventoryOffset;
386     }
387     else
388     {
389         return ipmi::responseReqDataLenExceeded();
390     }
391 
392     std::vector<uint8_t> requestedData;
393 
394     requestedData.insert(requestedData.begin(),
395                          fru.begin() + fruInventoryOffset,
396                          fru.begin() + fruInventoryOffset + fromFruByteLen);
397 
398     return ipmi::responseSuccess(static_cast<uint8_t>(requestedData.size()),
399                                  requestedData);
400 }
401 
402 /** @brief implements the write FRU data command
403  *  @param fruDeviceId        - FRU Device ID
404  *  @param fruInventoryOffset - FRU Inventory Offset to write
405  *  @param dataToWrite        - Data to write
406  *
407  *  @returns ipmi completion code plus response data
408  *   - countWritten  - Count written
409  */
410 ipmi::RspType<uint8_t> ipmiStorageWriteFruData(
411     ipmi::Context::ptr ctx, uint8_t fruDeviceId, uint16_t fruInventoryOffset,
412     std::vector<uint8_t>& dataToWrite)
413 {
414     if (fruDeviceId == 0xFF)
415     {
416         return ipmi::responseInvalidFieldRequest();
417     }
418 
419     size_t writeLen = dataToWrite.size();
420 
421     auto [status, fru] = getFru(ctx, fruDeviceId);
422     if (status != ipmi::ccSuccess)
423     {
424         return ipmi::response(status);
425     }
426     size_t lastWriteAddr = fruInventoryOffset + writeLen;
427     if (fru.size() < lastWriteAddr)
428     {
429         fru.resize(fruInventoryOffset + writeLen);
430     }
431 
432     std::copy(dataToWrite.begin(), dataToWrite.begin() + writeLen,
433               fru.begin() + fruInventoryOffset);
434 
435     bool atEnd = false;
436 
437     if (fru.size() >= sizeof(FRUHeader))
438     {
439         FRUHeader* header = reinterpret_cast<FRUHeader*>(fru.data());
440 
441         size_t areaLength = 0;
442         size_t lastRecordStart = std::max(
443             {header->internalOffset, header->chassisOffset, header->boardOffset,
444              header->productOffset, header->multiRecordOffset});
445         lastRecordStart *= 8; // header starts in are multiples of 8 bytes
446 
447         if (header->multiRecordOffset)
448         {
449             // This FRU has a MultiRecord Area
450             uint8_t endOfList = 0;
451             // Walk the MultiRecord headers until the last record
452             while (!endOfList)
453             {
454                 // The MSB in the second byte of the MultiRecord header signals
455                 // "End of list"
456                 endOfList = fru[lastRecordStart + 1] & 0x80;
457                 // Third byte in the MultiRecord header is the length
458                 areaLength = fru[lastRecordStart + 2];
459                 // This length is in bytes (not 8 bytes like other headers)
460                 areaLength += 5; // The length omits the 5 byte header
461                 if (!endOfList)
462                 {
463                     // Next MultiRecord header
464                     lastRecordStart += areaLength;
465                 }
466             }
467         }
468         else
469         {
470             // This FRU does not have a MultiRecord Area
471             // Get the length of the area in multiples of 8 bytes
472             if (lastWriteAddr > (lastRecordStart + 1))
473             {
474                 // second byte in record area is the length
475                 areaLength = fru[lastRecordStart + 1];
476                 areaLength *= 8; // it is in multiples of 8 bytes
477             }
478         }
479         if (lastWriteAddr >= (areaLength + lastRecordStart))
480         {
481             atEnd = true;
482         }
483     }
484     uint8_t countWritten = 0;
485 
486     writeBus = cacheBus;
487     writeAddr = cacheAddr;
488     if (atEnd)
489     {
490         // cancel timer, we're at the end so might as well send it
491         writeTimer->stop();
492         if (!writeFru(fru))
493         {
494             return ipmi::responseInvalidFieldRequest();
495         }
496         countWritten = std::min(fru.size(), static_cast<size_t>(0xFF));
497     }
498     else
499     {
500         fruCache = fru; // Write-back
501         // start a timer, if no further data is sent  to check to see if it is
502         // valid
503         writeTimer->start(std::chrono::duration_cast<std::chrono::microseconds>(
504             std::chrono::seconds(writeTimeoutSeconds)));
505         countWritten = 0;
506     }
507 
508     return ipmi::responseSuccess(countWritten);
509 }
510 
511 /** @brief implements the get FRU inventory area info command
512  *  @param fruDeviceId  - FRU Device ID
513  *
514  *  @returns IPMI completion code plus response data
515  *   - inventorySize - Number of possible allocation units
516  *   - accessType    - Allocation unit size in bytes.
517  */
518 ipmi::RspType<uint16_t, // inventorySize
519               uint8_t>  // accessType
520     ipmiStorageGetFruInvAreaInfo(ipmi::Context::ptr ctx, uint8_t fruDeviceId)
521 {
522     if (fruDeviceId == 0xFF)
523     {
524         return ipmi::responseInvalidFieldRequest();
525     }
526 
527     auto [ret, fru] = getFru(ctx, fruDeviceId);
528     if (ret != ipmi::ccSuccess)
529     {
530         return ipmi::response(ret);
531     }
532 
533     constexpr uint8_t accessType =
534         static_cast<uint8_t>(GetFRUAreaAccessType::byte);
535 
536     return ipmi::responseSuccess(fru.size(), accessType);
537 }
538 
539 ipmi::Cc getFruSdrCount(ipmi::Context::ptr, size_t& count)
540 {
541     count = deviceHashes.size();
542     return ipmi::ccSuccess;
543 }
544 
545 ipmi::Cc getFruSdrs([[maybe_unused]] ipmi::Context::ptr ctx, size_t index,
546                     get_sdr::SensorDataFruRecord& resp)
547 {
548     if (deviceHashes.size() < index)
549     {
550         return ipmi::ccInvalidFieldRequest;
551     }
552     auto device = deviceHashes.begin() + index;
553     uint16_t& bus = device->second.first;
554     uint8_t& address = device->second.second;
555 
556     boost::container::flat_map<std::string, Value>* fruData = nullptr;
557     auto fru = std::find_if(
558         frus.begin(), frus.end(),
559         [bus, address, &fruData](ManagedEntry& entry) {
560             auto findFruDevice =
561                 entry.second.find("xyz.openbmc_project.FruDevice");
562             if (findFruDevice == entry.second.end())
563             {
564                 return false;
565             }
566             fruData = &(findFruDevice->second);
567             auto findBus = findFruDevice->second.find("BUS");
568             auto findAddress = findFruDevice->second.find("ADDRESS");
569             if (findBus == findFruDevice->second.end() ||
570                 findAddress == findFruDevice->second.end())
571             {
572                 return false;
573             }
574             if (std::get<uint32_t>(findBus->second) != bus)
575             {
576                 return false;
577             }
578             if (std::get<uint32_t>(findAddress->second) != address)
579             {
580                 return false;
581             }
582             return true;
583         });
584     if (fru == frus.end())
585     {
586         return ipmi::ccResponseError;
587     }
588     std::string name;
589     uint8_t entityID = 0;
590     uint8_t entityInstance = 0x1;
591 
592 #ifdef USING_ENTITY_MANAGER_DECORATORS
593     boost::system::error_code ec;
594 
595     Paths subtreePaths = ipmi::callDbusMethod<Paths>(
596         ctx, ec, "xyz.openbmc_project.ObjectMapper",
597         "/xyz/openbmc_project/object_mapper",
598         "xyz.openbmc_project.ObjectMapper", "GetSubTreePaths",
599         "/xyz/openbmc_project/inventory", 0,
600         std::array<const char*, 2>{
601             "xyz.openbmc_project.Inventory.Decorator.I2CDevice",
602             "xyz.openbmc_project.Inventory.Decorator.Ipmi",
603         });
604     if (ec)
605     {
606         lg2::error(
607             "GetSubTreePaths for ipmiStorageGetFruInvAreaInfo failed: {ERROR}",
608             "ERROR", ec.message());
609         return ipmi::ccResponseError;
610     }
611 
612     bool foundDevice = false;
613     for (const auto& path : subtreePaths)
614     {
615         ipmi::PropertyMap i2cProperties;
616         boost::system::error_code ec = ipmi::getAllDbusProperties(
617             ctx, "xyz.openbmc_project.EntityManager", path,
618             "xyz.openbmc_project.Inventory.Decorator.I2CDevice", i2cProperties);
619         if (ec)
620         {
621             continue;
622         }
623 
624         std::optional<uint64_t> maybeBus;
625         std::optional<uint64_t> maybeAddress;
626         std::optional<std::string> maybeName;
627         for (const auto& [key, val] : i2cProperties)
628         {
629             if (key == "Bus")
630             {
631                 maybeBus = std::get<uint64_t>(val);
632             }
633             else if (key == "Address")
634             {
635                 maybeAddress = std::get<uint64_t>(val);
636             }
637             else if (key == "Name")
638             {
639                 maybeName = std::get<std::string>(val);
640             }
641         }
642         if (!maybeBus || *maybeBus != bus || !maybeAddress ||
643             *maybeAddress != address)
644         {
645             continue;
646         }
647         // At this point we found the device entry and will populate the
648         // information if exist.
649         foundDevice = true;
650 
651         if (maybeName.has_value())
652         {
653             name = *maybeName;
654         }
655 
656         ipmi::PropertyMap entityData;
657         ec = ipmi::getAllDbusProperties(
658             ctx, "xyz.openbmc_project.EntityManager", path,
659             "xyz.openbmc_project.Inventory.Decorator.Ipmi", entityData);
660         if (!ec)
661         {
662             for (const auto& [key, val] : entityData)
663             {
664                 if (key == "EntityId")
665                 {
666                     entityID = std::get<uint64_t>(val);
667                 }
668                 else if (key == "EntityInstance")
669                 {
670                     entityInstance = std::get<uint64_t>(val);
671                 }
672             }
673         }
674         break;
675     }
676 
677     if (!foundDevice)
678     {
679         if constexpr (DEBUG)
680         {
681             std::fprintf(stderr, "Ipmi or FruDevice Decorator interface "
682                                  "not found for Fru\n");
683         }
684     }
685 #endif
686 
687     std::vector<std::string> nameProperties = {
688         "BOARD_PRODUCT_NAME",    "PRODUCT_PRODUCT_NAME", "PRODUCT_PART_NUMBER",
689         "BOARD_PART_NUMBER",     "PRODUCT_MANUFACTURER", "BOARD_MANUFACTURER",
690         "PRODUCT_SERIAL_NUMBER", "BOARD_SERIAL_NUMBER"};
691 
692     for (const std::string& prop : nameProperties)
693     {
694         auto findProp = fruData->find(prop);
695         if (findProp != fruData->end())
696         {
697             name = std::get<std::string>(findProp->second);
698             break;
699         }
700     }
701 
702     if (name.empty())
703     {
704         name = "UNKNOWN";
705     }
706     if (name.size() > maxFruSdrNameSize)
707     {
708         name = name.substr(0, maxFruSdrNameSize);
709     }
710     size_t sizeDiff = maxFruSdrNameSize - name.size();
711 
712     resp.header.recordId = 0x0; // calling code is to implement these
713     resp.header.sdrVersion = ipmiSdrVersion;
714     resp.header.recordType = get_sdr::SENSOR_DATA_FRU_RECORD;
715     resp.header.recordLength = sizeof(resp.body) + sizeof(resp.key) - sizeDiff;
716     resp.key.deviceAddress = 0x20;
717     resp.key.fruID = device->first;
718     resp.key.accessLun = 0x80; // logical / physical fru device
719     resp.key.channelNumber = 0x0;
720     resp.body.reserved = 0x0;
721     resp.body.deviceType = 0x10;
722     resp.body.deviceTypeModifier = 0x0;
723 
724     resp.body.entityID = entityID;
725     resp.body.entityInstance = entityInstance;
726 
727     resp.body.oem = 0x0;
728     resp.body.deviceIDLen = ipmi::storage::typeASCIILatin8 | name.size();
729     name.copy(resp.body.deviceID, name.size());
730 
731     return ipmi::ccSuccess;
732 }
733 
734 static bool getSELLogFiles(std::vector<std::filesystem::path>& selLogFiles)
735 {
736     // Loop through the directory looking for ipmi_sel log files
737     for (const std::filesystem::directory_entry& dirEnt :
738          std::filesystem::directory_iterator(
739              dynamic_sensors::ipmi::sel::selLogDir))
740     {
741         std::string filename = dirEnt.path().filename();
742         if (filename.starts_with(dynamic_sensors::ipmi::sel::selLogFilename))
743         {
744             // If we find an ipmi_sel log file, save the path
745             selLogFiles.emplace_back(
746                 dynamic_sensors::ipmi::sel::selLogDir / filename);
747         }
748     }
749     // As the log files rotate, they are appended with a ".#" that is higher for
750     // the older logs. Since we don't expect more than 10 log files, we
751     // can just sort the list to get them in order from newest to oldest
752     std::sort(selLogFiles.begin(), selLogFiles.end());
753 
754     return !selLogFiles.empty();
755 }
756 
757 static int countSELEntries()
758 {
759     // Get the list of ipmi_sel log files
760     std::vector<std::filesystem::path> selLogFiles;
761     if (!getSELLogFiles(selLogFiles))
762     {
763         return 0;
764     }
765     int numSELEntries = 0;
766     // Loop through each log file and count the number of logs
767     for (const std::filesystem::path& file : selLogFiles)
768     {
769         std::ifstream logStream(file);
770         if (!logStream.is_open())
771         {
772             continue;
773         }
774 
775         std::string line;
776         while (std::getline(logStream, line))
777         {
778             numSELEntries++;
779         }
780     }
781     return numSELEntries;
782 }
783 
784 static bool findSELEntry(const int recordID,
785                          const std::vector<std::filesystem::path>& selLogFiles,
786                          std::string& entry)
787 {
788     // Record ID is the first entry field following the timestamp. It is
789     // preceded by a space and followed by a comma
790     std::string search = " " + std::to_string(recordID) + ",";
791 
792     // Loop through the ipmi_sel log entries
793     for (const std::filesystem::path& file : selLogFiles)
794     {
795         std::ifstream logStream(file);
796         if (!logStream.is_open())
797         {
798             continue;
799         }
800 
801         while (std::getline(logStream, entry))
802         {
803             // Check if the record ID matches
804             if (entry.find(search) != std::string::npos)
805             {
806                 return true;
807             }
808         }
809     }
810     return false;
811 }
812 
813 static uint16_t getNextRecordID(
814     const uint16_t recordID,
815     const std::vector<std::filesystem::path>& selLogFiles)
816 {
817     uint16_t nextRecordID = recordID + 1;
818     std::string entry;
819     if (findSELEntry(nextRecordID, selLogFiles, entry))
820     {
821         return nextRecordID;
822     }
823     else
824     {
825         return ipmi::sel::lastEntry;
826     }
827 }
828 
829 static int fromHexStr(const std::string& hexStr, std::vector<uint8_t>& data)
830 {
831     for (unsigned int i = 0; i < hexStr.size(); i += 2)
832     {
833         try
834         {
835             data.push_back(static_cast<uint8_t>(
836                 std::stoul(hexStr.substr(i, 2), nullptr, 16)));
837         }
838         catch (const std::invalid_argument& e)
839         {
840             lg2::error("Invalid argument: {ERROR}", "ERROR", e);
841             return -1;
842         }
843         catch (const std::out_of_range& e)
844         {
845             lg2::error("Out of range: {ERROR}", "ERROR", e);
846             return -1;
847         }
848     }
849     return 0;
850 }
851 
852 ipmi::RspType<uint8_t,  // SEL version
853               uint16_t, // SEL entry count
854               uint16_t, // free space
855               uint32_t, // last add timestamp
856               uint32_t, // last erase timestamp
857               uint8_t>  // operation support
858     ipmiStorageGetSELInfo()
859 {
860     constexpr uint8_t selVersion = ipmi::sel::selVersion;
861     uint16_t entries = countSELEntries();
862     uint32_t addTimeStamp = dynamic_sensors::ipmi::sel::getFileTimestamp(
863         dynamic_sensors::ipmi::sel::selLogDir /
864         dynamic_sensors::ipmi::sel::selLogFilename);
865     uint32_t eraseTimeStamp = dynamic_sensors::ipmi::sel::erase_time::get();
866     constexpr uint8_t operationSupport =
867         dynamic_sensors::ipmi::sel::selOperationSupport;
868     constexpr uint16_t freeSpace =
869         0xffff; // Spec indicates that more than 64kB is free
870 
871     return ipmi::responseSuccess(selVersion, entries, freeSpace, addTimeStamp,
872                                  eraseTimeStamp, operationSupport);
873 }
874 
875 using systemEventType = std::tuple<
876     uint32_t, // Timestamp
877     uint16_t, // Generator ID
878     uint8_t,  // EvM Rev
879     uint8_t,  // Sensor Type
880     uint8_t,  // Sensor Number
881     uint7_t,  // Event Type
882     bool,     // Event Direction
883     std::array<uint8_t, dynamic_sensors::ipmi::sel::systemEventSize>>; // Event
884                                                                        // Data
885 using oemTsEventType = std::tuple<
886     uint32_t, // Timestamp
887     std::array<uint8_t, dynamic_sensors::ipmi::sel::oemTsEventSize>>; // Event
888                                                                       // Data
889 using oemEventType =
890     std::array<uint8_t, dynamic_sensors::ipmi::sel::oemEventSize>; // Event Data
891 
892 ipmi::RspType<uint16_t,                   // Next Record ID
893               uint16_t,                   // Record ID
894               uint8_t,                    // Record Type
895               std::variant<systemEventType, oemTsEventType,
896                            oemEventType>> // Record Content
897     ipmiStorageGetSELEntry(uint16_t reservationID, uint16_t targetID,
898                            uint8_t offset, uint8_t size)
899 {
900     // Only support getting the entire SEL record. If a partial size or non-zero
901     // offset is requested, return an error
902     if (offset != 0 || size != ipmi::sel::entireRecord)
903     {
904         return ipmi::responseRetBytesUnavailable();
905     }
906 
907     // Check the reservation ID if one is provided or required (only if the
908     // offset is non-zero)
909     if (reservationID != 0 || offset != 0)
910     {
911         if (!checkSELReservation(reservationID))
912         {
913             return ipmi::responseInvalidReservationId();
914         }
915     }
916 
917     // Get the ipmi_sel log files
918     std::vector<std::filesystem::path> selLogFiles;
919     if (!getSELLogFiles(selLogFiles))
920     {
921         return ipmi::responseSensorInvalid();
922     }
923 
924     std::string targetEntry;
925 
926     if (targetID == ipmi::sel::firstEntry)
927     {
928         // The first entry will be at the top of the oldest log file
929         std::ifstream logStream(selLogFiles.back());
930         if (!logStream.is_open())
931         {
932             return ipmi::responseUnspecifiedError();
933         }
934 
935         if (!std::getline(logStream, targetEntry))
936         {
937             return ipmi::responseUnspecifiedError();
938         }
939     }
940     else if (targetID == ipmi::sel::lastEntry)
941     {
942         // The last entry will be at the bottom of the newest log file
943         std::ifstream logStream(selLogFiles.front());
944         if (!logStream.is_open())
945         {
946             return ipmi::responseUnspecifiedError();
947         }
948 
949         std::string line;
950         while (std::getline(logStream, line))
951         {
952             targetEntry = line;
953         }
954     }
955     else
956     {
957         if (!findSELEntry(targetID, selLogFiles, targetEntry))
958         {
959             return ipmi::responseSensorInvalid();
960         }
961     }
962 
963     // The format of the ipmi_sel message is "<Timestamp>
964     // <ID>,<Type>,<EventData>,[<Generator ID>,<Path>,<Direction>]".
965     // First get the Timestamp
966     size_t space = targetEntry.find_first_of(" ");
967     if (space == std::string::npos)
968     {
969         return ipmi::responseUnspecifiedError();
970     }
971     std::string entryTimestamp = targetEntry.substr(0, space);
972     // Then get the log contents
973     size_t entryStart = targetEntry.find_first_not_of(" ", space);
974     if (entryStart == std::string::npos)
975     {
976         return ipmi::responseUnspecifiedError();
977     }
978     std::string_view entry(targetEntry);
979     entry.remove_prefix(entryStart);
980     // Use split to separate the entry into its fields
981     std::vector<std::string> targetEntryFields;
982     boost::split(targetEntryFields, entry, boost::is_any_of(","),
983                  boost::token_compress_on);
984     if (targetEntryFields.size() < 3)
985     {
986         return ipmi::responseUnspecifiedError();
987     }
988     std::string& recordIDStr = targetEntryFields[0];
989     std::string& recordTypeStr = targetEntryFields[1];
990     std::string& eventDataStr = targetEntryFields[2];
991 
992     uint16_t recordID;
993     uint8_t recordType;
994     try
995     {
996         recordID = std::stoul(recordIDStr);
997         recordType = std::stoul(recordTypeStr, nullptr, 16);
998     }
999     catch (const std::invalid_argument&)
1000     {
1001         return ipmi::responseUnspecifiedError();
1002     }
1003     uint16_t nextRecordID = getNextRecordID(recordID, selLogFiles);
1004     std::vector<uint8_t> eventDataBytes;
1005     if (fromHexStr(eventDataStr, eventDataBytes) < 0)
1006     {
1007         return ipmi::responseUnspecifiedError();
1008     }
1009 
1010     if (recordType == dynamic_sensors::ipmi::sel::systemEvent)
1011     {
1012         // Get the timestamp
1013         std::tm timeStruct = {};
1014         std::istringstream entryStream(entryTimestamp);
1015 
1016         uint32_t timestamp = ipmi::sel::invalidTimeStamp;
1017         if (entryStream >> std::get_time(&timeStruct, "%Y-%m-%dT%H:%M:%S"))
1018         {
1019             timeStruct.tm_isdst = -1;
1020             timestamp = std::mktime(&timeStruct);
1021         }
1022 
1023         // Set the event message revision
1024         uint8_t evmRev = dynamic_sensors::ipmi::sel::eventMsgRev;
1025 
1026         uint16_t generatorID = 0;
1027         uint8_t sensorType = 0;
1028         uint16_t sensorAndLun = 0;
1029         uint8_t sensorNum = 0xFF;
1030         uint7_t eventType = 0;
1031         bool eventDir = 0;
1032         // System type events should have six fields
1033         if (targetEntryFields.size() >= 6)
1034         {
1035             std::string& generatorIDStr = targetEntryFields[3];
1036             std::string& sensorPath = targetEntryFields[4];
1037             std::string& eventDirStr = targetEntryFields[5];
1038 
1039             // Get the generator ID
1040             try
1041             {
1042                 generatorID = std::stoul(generatorIDStr, nullptr, 16);
1043             }
1044             catch (const std::invalid_argument&)
1045             {
1046                 lg2::error("Invalid Generator ID");
1047             }
1048 
1049             // Get the sensor type, sensor number, and event type for the sensor
1050             sensorType = getSensorTypeFromPath(sensorPath);
1051             sensorAndLun = getSensorNumberFromPath(sensorPath);
1052             sensorNum = static_cast<uint8_t>(sensorAndLun);
1053             if ((generatorID & 0x0001) == 0)
1054             {
1055                 // IPMB Address
1056                 generatorID |= sensorAndLun & 0x0300;
1057             }
1058             else
1059             {
1060                 // system software
1061                 generatorID |= sensorAndLun >> 8;
1062             }
1063             eventType = getSensorEventTypeFromPath(sensorPath);
1064 
1065             // Get the event direction
1066             try
1067             {
1068                 eventDir = std::stoul(eventDirStr) ? 0 : 1;
1069             }
1070             catch (const std::invalid_argument&)
1071             {
1072                 lg2::error("Invalid Event Direction");
1073             }
1074         }
1075 
1076         // Only keep the eventData bytes that fit in the record
1077         std::array<uint8_t, dynamic_sensors::ipmi::sel::systemEventSize>
1078             eventData{};
1079         std::copy_n(eventDataBytes.begin(),
1080                     std::min(eventDataBytes.size(), eventData.size()),
1081                     eventData.begin());
1082 
1083         return ipmi::responseSuccess(
1084             nextRecordID, recordID, recordType,
1085             systemEventType{timestamp, generatorID, evmRev, sensorType,
1086                             sensorNum, eventType, eventDir, eventData});
1087     }
1088 
1089     if (recordType >= dynamic_sensors::ipmi::sel::oemTsEventFirst &&
1090         recordType <= dynamic_sensors::ipmi::sel::oemTsEventLast)
1091     {
1092         // Get the timestamp
1093         std::tm timeStruct = {};
1094         std::istringstream entryStream(entryTimestamp);
1095 
1096         uint32_t timestamp = ipmi::sel::invalidTimeStamp;
1097         if (entryStream >> std::get_time(&timeStruct, "%Y-%m-%dT%H:%M:%S"))
1098         {
1099             timeStruct.tm_isdst = -1;
1100             timestamp = std::mktime(&timeStruct);
1101         }
1102 
1103         // Only keep the bytes that fit in the record
1104         std::array<uint8_t, dynamic_sensors::ipmi::sel::oemTsEventSize>
1105             eventData{};
1106         std::copy_n(eventDataBytes.begin(),
1107                     std::min(eventDataBytes.size(), eventData.size()),
1108                     eventData.begin());
1109 
1110         return ipmi::responseSuccess(nextRecordID, recordID, recordType,
1111                                      oemTsEventType{timestamp, eventData});
1112     }
1113 
1114     if (recordType >= dynamic_sensors::ipmi::sel::oemEventFirst)
1115     {
1116         // Only keep the bytes that fit in the record
1117         std::array<uint8_t, dynamic_sensors::ipmi::sel::oemEventSize>
1118             eventData{};
1119         std::copy_n(eventDataBytes.begin(),
1120                     std::min(eventDataBytes.size(), eventData.size()),
1121                     eventData.begin());
1122 
1123         return ipmi::responseSuccess(nextRecordID, recordID, recordType,
1124                                      eventData);
1125     }
1126 
1127     return ipmi::responseUnspecifiedError();
1128 }
1129 
1130 /*
1131 Unused arguments
1132   uint16_t recordID, uint8_t recordType, uint32_t timestamp,
1133   uint16_t generatorID, uint8_t evmRev, uint8_t sensorType, uint8_t sensorNum,
1134   uint8_t eventType, uint8_t eventData1, uint8_t eventData2,
1135   uint8_t eventData3
1136 */
1137 ipmi::RspType<uint16_t> ipmiStorageAddSELEntry(
1138     uint16_t, uint8_t, uint32_t, uint16_t, uint8_t, uint8_t, uint8_t, uint8_t,
1139     uint8_t, uint8_t, uint8_t)
1140 {
1141     // Per the IPMI spec, need to cancel any reservation when a SEL entry is
1142     // added
1143     cancelSELReservation();
1144 
1145     uint16_t responseID = 0xFFFF;
1146     return ipmi::responseSuccess(responseID);
1147 }
1148 
1149 ipmi::RspType<uint8_t> ipmiStorageClearSEL(
1150     ipmi::Context::ptr ctx, uint16_t reservationID,
1151     const std::array<uint8_t, 3>& clr, uint8_t eraseOperation)
1152 {
1153     if (!checkSELReservation(reservationID))
1154     {
1155         return ipmi::responseInvalidReservationId();
1156     }
1157 
1158     static constexpr std::array<uint8_t, 3> clrExpected = {'C', 'L', 'R'};
1159     if (clr != clrExpected)
1160     {
1161         return ipmi::responseInvalidFieldRequest();
1162     }
1163 
1164     // Erasure status cannot be fetched, so always return erasure status as
1165     // `erase completed`.
1166     if (eraseOperation == ipmi::sel::getEraseStatus)
1167     {
1168         return ipmi::responseSuccess(ipmi::sel::eraseComplete);
1169     }
1170 
1171     // Check that initiate erase is correct
1172     if (eraseOperation != ipmi::sel::initiateErase)
1173     {
1174         return ipmi::responseInvalidFieldRequest();
1175     }
1176 
1177     // Per the IPMI spec, need to cancel any reservation when the SEL is
1178     // cleared
1179     cancelSELReservation();
1180 
1181     boost::system::error_code ec =
1182         ipmi::callDbusMethod(ctx, "xyz.openbmc_project.Logging.IPMI",
1183                              "/xyz/openbmc_project/Logging/IPMI",
1184                              "xyz.openbmc_project.Logging.IPMI", "Clear");
1185     if (ec)
1186     {
1187         lg2::error("error in clear SEL: {MSG}", "MSG", ec.message());
1188         return ipmi::responseUnspecifiedError();
1189     }
1190 
1191     return ipmi::responseSuccess(ipmi::sel::eraseComplete);
1192 }
1193 
1194 std::vector<uint8_t> getType8SDRs(
1195     ipmi::sensor::EntityInfoMap::const_iterator& entity, uint16_t recordId)
1196 {
1197     std::vector<uint8_t> resp;
1198     get_sdr::SensorDataEntityRecord data{};
1199 
1200     /* Header */
1201     // Based on IPMI Spec v2.0 rev 1.1
1202     data.header.recordId = recordId;
1203     data.header.sdrVersion = SDR_VERSION;
1204     data.header.recordType = 0x08;
1205     data.header.recordLength = sizeof(data.key) + sizeof(data.body);
1206 
1207     /* Key */
1208     data.key.containerEntityId = entity->second.containerEntityId;
1209     data.key.containerEntityInstance = entity->second.containerEntityInstance;
1210     get_sdr::key::setFlags(entity->second.isList, entity->second.isLinked,
1211                            data.key);
1212     data.key.entityId1 = entity->second.containedEntities[0].first;
1213     data.key.entityInstance1 = entity->second.containedEntities[0].second;
1214 
1215     /* Body */
1216     data.body.entityId2 = entity->second.containedEntities[1].first;
1217     data.body.entityInstance2 = entity->second.containedEntities[1].second;
1218     data.body.entityId3 = entity->second.containedEntities[2].first;
1219     data.body.entityInstance3 = entity->second.containedEntities[2].second;
1220     data.body.entityId4 = entity->second.containedEntities[3].first;
1221     data.body.entityInstance4 = entity->second.containedEntities[3].second;
1222 
1223     resp.insert(resp.end(), (uint8_t*)&data, ((uint8_t*)&data) + sizeof(data));
1224 
1225     return resp;
1226 }
1227 
1228 std::vector<uint8_t> getType12SDRs(uint16_t index, uint16_t recordId)
1229 {
1230     std::vector<uint8_t> resp;
1231     if (index == 0)
1232     {
1233         std::string bmcName = "Basbrd Mgmt Ctlr";
1234         Type12Record bmc(recordId, 0x20, 0, 0, 0xbf, 0x2e, 1, 0, bmcName);
1235         uint8_t* bmcPtr = reinterpret_cast<uint8_t*>(&bmc);
1236         resp.insert(resp.end(), bmcPtr, bmcPtr + sizeof(Type12Record));
1237     }
1238     else if (index == 1)
1239     {
1240         std::string meName = "Mgmt Engine";
1241         Type12Record me(recordId, 0x2c, 6, 0x24, 0x21, 0x2e, 2, 0, meName);
1242         uint8_t* mePtr = reinterpret_cast<uint8_t*>(&me);
1243         resp.insert(resp.end(), mePtr, mePtr + sizeof(Type12Record));
1244     }
1245     else
1246     {
1247         throw std::runtime_error(
1248             "getType12SDRs:: Illegal index " + std::to_string(index));
1249     }
1250 
1251     return resp;
1252 }
1253 
1254 void registerStorageFunctions()
1255 {
1256     createTimers();
1257     startMatch();
1258 
1259     // <Get FRU Inventory Area Info>
1260     ipmi::registerHandler(ipmi::prioOpenBmcBase, ipmi::netFnStorage,
1261                           ipmi::storage::cmdGetFruInventoryAreaInfo,
1262                           ipmi::Privilege::User, ipmiStorageGetFruInvAreaInfo);
1263     // <READ FRU Data>
1264     ipmi::registerHandler(ipmi::prioOpenBmcBase, ipmi::netFnStorage,
1265                           ipmi::storage::cmdReadFruData, ipmi::Privilege::User,
1266                           ipmiStorageReadFruData);
1267 
1268     // <WRITE FRU Data>
1269     ipmi::registerHandler(ipmi::prioOpenBmcBase, ipmi::netFnStorage,
1270                           ipmi::storage::cmdWriteFruData,
1271                           ipmi::Privilege::Operator, ipmiStorageWriteFruData);
1272 
1273     // <Get SEL Info>
1274     ipmi::registerHandler(ipmi::prioOpenBmcBase, ipmi::netFnStorage,
1275                           ipmi::storage::cmdGetSelInfo, ipmi::Privilege::User,
1276                           ipmiStorageGetSELInfo);
1277 
1278     // <Get SEL Entry>
1279     ipmi::registerHandler(ipmi::prioOpenBmcBase, ipmi::netFnStorage,
1280                           ipmi::storage::cmdGetSelEntry, ipmi::Privilege::User,
1281                           ipmiStorageGetSELEntry);
1282 
1283     // <Add SEL Entry>
1284     ipmi::registerHandler(ipmi::prioOpenBmcBase, ipmi::netFnStorage,
1285                           ipmi::storage::cmdAddSelEntry,
1286                           ipmi::Privilege::Operator, ipmiStorageAddSELEntry);
1287 
1288     // <Clear SEL>
1289     ipmi::registerHandler(ipmi::prioOpenBmcBase, ipmi::netFnStorage,
1290                           ipmi::storage::cmdClearSel, ipmi::Privilege::Operator,
1291                           ipmiStorageClearSEL);
1292 }
1293 } // namespace storage
1294 } // namespace ipmi
1295