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