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