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 <boost/algorithm/string.hpp>
18 #include <boost/container/flat_map.hpp>
19 #include <boost/process.hpp>
20 #include <commandutils.hpp>
21 #include <filesystem>
22 #include <functional>
23 #include <iostream>
24 #include <ipmi_to_redfish_hooks.hpp>
25 #include <ipmid/api.hpp>
26 #include <phosphor-ipmi-host/selutility.hpp>
27 #include <phosphor-logging/log.hpp>
28 #include <sdbusplus/message/types.hpp>
29 #include <sdbusplus/timer.hpp>
30 #include <sdrutils.hpp>
31 #include <stdexcept>
32 #include <storagecommands.hpp>
33 #include <string_view>
34 
35 namespace intel_oem::ipmi::sel
36 {
37 static const std::filesystem::path selLogDir = "/var/log";
38 static const std::string selLogFilename = "ipmi_sel";
39 
40 static int getFileTimestamp(const std::filesystem::path& file)
41 {
42     struct stat st;
43 
44     if (stat(file.c_str(), &st) >= 0)
45     {
46         return st.st_mtime;
47     }
48     return ::ipmi::sel::invalidTimeStamp;
49 }
50 
51 namespace erase_time
52 {
53 static constexpr const char* selEraseTimestamp = "/var/lib/ipmi/sel_erase_time";
54 
55 void save()
56 {
57     // open the file, creating it if necessary
58     int fd = open(selEraseTimestamp, O_WRONLY | O_CREAT | O_CLOEXEC, 0644);
59     if (fd < 0)
60     {
61         std::cerr << "Failed to open file\n";
62         return;
63     }
64 
65     // update the file timestamp to the current time
66     if (futimens(fd, NULL) < 0)
67     {
68         std::cerr << "Failed to update timestamp: "
69                   << std::string(strerror(errno));
70     }
71     close(fd);
72 }
73 
74 int get()
75 {
76     return getFileTimestamp(selEraseTimestamp);
77 }
78 } // namespace erase_time
79 } // namespace intel_oem::ipmi::sel
80 
81 namespace ipmi
82 {
83 
84 namespace storage
85 {
86 
87 constexpr static const size_t maxMessageSize = 64;
88 constexpr static const size_t maxFruSdrNameSize = 16;
89 using ManagedObjectType = boost::container::flat_map<
90     sdbusplus::message::object_path,
91     boost::container::flat_map<
92         std::string, boost::container::flat_map<std::string, DbusVariant>>>;
93 using ManagedEntry = std::pair<
94     sdbusplus::message::object_path,
95     boost::container::flat_map<
96         std::string, boost::container::flat_map<std::string, DbusVariant>>>;
97 
98 constexpr static const char* fruDeviceServiceName =
99     "xyz.openbmc_project.FruDevice";
100 constexpr static const size_t cacheTimeoutSeconds = 10;
101 
102 // event direction is bit[7] of eventType where 1b = Deassertion event
103 constexpr static const uint8_t deassertionEvent = 0x80;
104 
105 static std::vector<uint8_t> fruCache;
106 static uint8_t cacheBus = 0xFF;
107 static uint8_t cacheAddr = 0XFF;
108 
109 std::unique_ptr<phosphor::Timer> cacheTimer = nullptr;
110 
111 // we unfortunately have to build a map of hashes in case there is a
112 // collision to verify our dev-id
113 boost::container::flat_map<uint8_t, std::pair<uint8_t, uint8_t>> deviceHashes;
114 
115 void registerStorageFunctions() __attribute__((constructor));
116 
117 bool writeFru()
118 {
119     std::shared_ptr<sdbusplus::asio::connection> dbus = getSdBus();
120     sdbusplus::message::message writeFru = dbus->new_method_call(
121         fruDeviceServiceName, "/xyz/openbmc_project/FruDevice",
122         "xyz.openbmc_project.FruDeviceManager", "WriteFru");
123     writeFru.append(cacheBus, cacheAddr, fruCache);
124     try
125     {
126         sdbusplus::message::message writeFruResp = dbus->call(writeFru);
127     }
128     catch (sdbusplus::exception_t&)
129     {
130         // todo: log sel?
131         phosphor::logging::log<phosphor::logging::level::ERR>(
132             "error writing fru");
133         return false;
134     }
135     return true;
136 }
137 
138 void createTimer()
139 {
140     if (cacheTimer == nullptr)
141     {
142         cacheTimer = std::make_unique<phosphor::Timer>(writeFru);
143     }
144 }
145 
146 ipmi_ret_t replaceCacheFru(uint8_t devId)
147 {
148     static uint8_t lastDevId = 0xFF;
149 
150     bool timerRunning = (cacheTimer != nullptr) && !cacheTimer->isExpired();
151     if (lastDevId == devId && timerRunning)
152     {
153         return IPMI_CC_OK; // cache already up to date
154     }
155     // if timer is running, stop it and writeFru manually
156     else if (timerRunning)
157     {
158         cacheTimer->stop();
159         writeFru();
160     }
161 
162     std::shared_ptr<sdbusplus::asio::connection> dbus = getSdBus();
163     sdbusplus::message::message getObjects = dbus->new_method_call(
164         fruDeviceServiceName, "/", "org.freedesktop.DBus.ObjectManager",
165         "GetManagedObjects");
166     ManagedObjectType frus;
167     try
168     {
169         sdbusplus::message::message resp = dbus->call(getObjects);
170         resp.read(frus);
171     }
172     catch (sdbusplus::exception_t&)
173     {
174         phosphor::logging::log<phosphor::logging::level::ERR>(
175             "replaceCacheFru: error getting managed objects");
176         return IPMI_CC_RESPONSE_ERROR;
177     }
178 
179     deviceHashes.clear();
180 
181     // hash the object paths to create unique device id's. increment on
182     // collision
183     std::hash<std::string> hasher;
184     for (const auto& fru : frus)
185     {
186         auto fruIface = fru.second.find("xyz.openbmc_project.FruDevice");
187         if (fruIface == fru.second.end())
188         {
189             continue;
190         }
191 
192         auto busFind = fruIface->second.find("BUS");
193         auto addrFind = fruIface->second.find("ADDRESS");
194         if (busFind == fruIface->second.end() ||
195             addrFind == fruIface->second.end())
196         {
197             phosphor::logging::log<phosphor::logging::level::INFO>(
198                 "fru device missing Bus or Address",
199                 phosphor::logging::entry("FRU=%s", fru.first.str.c_str()));
200             continue;
201         }
202 
203         uint8_t fruBus = std::get<uint32_t>(busFind->second);
204         uint8_t fruAddr = std::get<uint32_t>(addrFind->second);
205 
206         uint8_t fruHash = 0;
207         if (fruBus != 0 || fruAddr != 0)
208         {
209             fruHash = hasher(fru.first.str);
210             // can't be 0xFF based on spec, and 0 is reserved for baseboard
211             if (fruHash == 0 || fruHash == 0xFF)
212             {
213                 fruHash = 1;
214             }
215         }
216         std::pair<uint8_t, uint8_t> newDev(fruBus, fruAddr);
217 
218         bool emplacePassed = false;
219         while (!emplacePassed)
220         {
221             auto resp = deviceHashes.emplace(fruHash, newDev);
222             emplacePassed = resp.second;
223             if (!emplacePassed)
224             {
225                 fruHash++;
226                 // can't be 0xFF based on spec, and 0 is reserved for
227                 // baseboard
228                 if (fruHash == 0XFF)
229                 {
230                     fruHash = 0x1;
231                 }
232             }
233         }
234     }
235     auto deviceFind = deviceHashes.find(devId);
236     if (deviceFind == deviceHashes.end())
237     {
238         return IPMI_CC_SENSOR_INVALID;
239     }
240 
241     fruCache.clear();
242     sdbusplus::message::message getRawFru = dbus->new_method_call(
243         fruDeviceServiceName, "/xyz/openbmc_project/FruDevice",
244         "xyz.openbmc_project.FruDeviceManager", "GetRawFru");
245     cacheBus = deviceFind->second.first;
246     cacheAddr = deviceFind->second.second;
247     getRawFru.append(cacheBus, cacheAddr);
248     try
249     {
250         sdbusplus::message::message getRawResp = dbus->call(getRawFru);
251         getRawResp.read(fruCache);
252     }
253     catch (sdbusplus::exception_t&)
254     {
255         lastDevId = 0xFF;
256         cacheBus = 0xFF;
257         cacheAddr = 0xFF;
258         return IPMI_CC_RESPONSE_ERROR;
259     }
260 
261     lastDevId = devId;
262     return IPMI_CC_OK;
263 }
264 
265 /** @brief implements the read FRU data command
266  *  @param fruDeviceId        - FRU Device ID
267  *  @param fruInventoryOffset - FRU Inventory Offset to write
268  *  @param countToRead        - Count to read
269  *
270  *  @returns ipmi completion code plus response data
271  *   - countWritten  - Count written
272  */
273 ipmi::RspType<uint8_t,             // Count
274               std::vector<uint8_t> // Requested data
275               >
276     ipmiStorageReadFruData(uint8_t fruDeviceId, uint16_t fruInventoryOffset,
277                            uint8_t countToRead)
278 {
279     if (fruDeviceId == 0xFF)
280     {
281         return ipmi::responseInvalidFieldRequest();
282     }
283 
284     ipmi::Cc status = replaceCacheFru(fruDeviceId);
285 
286     if (status != ipmi::ccSuccess)
287     {
288         return ipmi::response(status);
289     }
290 
291     size_t fromFruByteLen = 0;
292     if (countToRead + fruInventoryOffset < fruCache.size())
293     {
294         fromFruByteLen = countToRead;
295     }
296     else if (fruCache.size() > fruInventoryOffset)
297     {
298         fromFruByteLen = fruCache.size() - fruInventoryOffset;
299     }
300     else
301     {
302         return ipmi::responseInvalidFieldRequest();
303     }
304 
305     std::vector<uint8_t> requestedData;
306 
307     requestedData.insert(
308         requestedData.begin(), fruCache.begin() + fruInventoryOffset,
309         fruCache.begin() + fruInventoryOffset + fromFruByteLen);
310 
311     return ipmi::responseSuccess(countToRead, requestedData);
312 }
313 
314 /** @brief implements the write FRU data command
315  *  @param fruDeviceId        - FRU Device ID
316  *  @param fruInventoryOffset - FRU Inventory Offset to write
317  *  @param dataToWrite        - Data to write
318  *
319  *  @returns ipmi completion code plus response data
320  *   - countWritten  - Count written
321  */
322 ipmi::RspType<uint8_t>
323     ipmiStorageWriteFruData(uint8_t fruDeviceId, uint16_t fruInventoryOffset,
324                             std::vector<uint8_t>& dataToWrite)
325 {
326     if (fruDeviceId == 0xFF)
327     {
328         return ipmi::responseInvalidFieldRequest();
329     }
330 
331     size_t writeLen = dataToWrite.size();
332 
333     ipmi::Cc status = replaceCacheFru(fruDeviceId);
334     if (status != ipmi::ccSuccess)
335     {
336         return ipmi::response(status);
337     }
338     int lastWriteAddr = fruInventoryOffset + writeLen;
339     if (fruCache.size() < lastWriteAddr)
340     {
341         fruCache.resize(fruInventoryOffset + writeLen);
342     }
343 
344     std::copy(dataToWrite.begin(), dataToWrite.begin() + writeLen,
345               fruCache.begin() + fruInventoryOffset);
346 
347     bool atEnd = false;
348 
349     if (fruCache.size() >= sizeof(FRUHeader))
350     {
351         FRUHeader* header = reinterpret_cast<FRUHeader*>(fruCache.data());
352 
353         int lastRecordStart = std::max(
354             header->internalOffset,
355             std::max(header->chassisOffset,
356                      std::max(header->boardOffset, header->productOffset)));
357         // TODO: Handle Multi-Record FRUs?
358 
359         lastRecordStart *= 8; // header starts in are multiples of 8 bytes
360 
361         // get the length of the area in multiples of 8 bytes
362         if (lastWriteAddr > (lastRecordStart + 1))
363         {
364             // second byte in record area is the length
365             int areaLength(fruCache[lastRecordStart + 1]);
366             areaLength *= 8; // it is in multiples of 8 bytes
367 
368             if (lastWriteAddr >= (areaLength + lastRecordStart))
369             {
370                 atEnd = true;
371             }
372         }
373     }
374     uint8_t countWritten = 0;
375     if (atEnd)
376     {
377         // cancel timer, we're at the end so might as well send it
378         cacheTimer->stop();
379         if (!writeFru())
380         {
381             return ipmi::responseInvalidFieldRequest();
382         }
383         countWritten = std::min(fruCache.size(), static_cast<size_t>(0xFF));
384     }
385     else
386     {
387         // start a timer, if no further data is sent in cacheTimeoutSeconds
388         // seconds, check to see if it is valid
389         createTimer();
390         cacheTimer->start(std::chrono::duration_cast<std::chrono::microseconds>(
391             std::chrono::seconds(cacheTimeoutSeconds)));
392         countWritten = 0;
393     }
394 
395     return ipmi::responseSuccess(countWritten);
396 }
397 
398 /** @brief implements the get FRU inventory area info command
399  *  @param fruDeviceId  - FRU Device ID
400  *
401  *  @returns IPMI completion code plus response data
402  *   - inventorySize - Number of possible allocation units
403  *   - accessType    - Allocation unit size in bytes.
404  */
405 ipmi::RspType<uint16_t, // inventorySize
406               uint8_t>  // accessType
407     ipmiStorageGetFruInvAreaInfo(uint8_t fruDeviceId)
408 {
409     if (fruDeviceId == 0xFF)
410     {
411         return ipmi::responseInvalidFieldRequest();
412     }
413 
414     ipmi::Cc status = replaceCacheFru(fruDeviceId);
415 
416     if (status != IPMI_CC_OK)
417     {
418         return ipmi::response(status);
419     }
420 
421     constexpr uint8_t accessType =
422         static_cast<uint8_t>(GetFRUAreaAccessType::byte);
423 
424     return ipmi::responseSuccess(fruCache.size(), accessType);
425 }
426 
427 ipmi_ret_t getFruSdrCount(size_t& count)
428 {
429     ipmi_ret_t ret = replaceCacheFru(0);
430     if (ret != IPMI_CC_OK)
431     {
432         return ret;
433     }
434     count = deviceHashes.size();
435     return IPMI_CC_OK;
436 }
437 
438 ipmi_ret_t getFruSdrs(size_t index, get_sdr::SensorDataFruRecord& resp)
439 {
440     ipmi_ret_t ret = replaceCacheFru(0); // this will update the hash list
441     if (ret != IPMI_CC_OK)
442     {
443         return ret;
444     }
445     if (deviceHashes.size() < index)
446     {
447         return IPMI_CC_INVALID_FIELD_REQUEST;
448     }
449     auto device = deviceHashes.begin() + index;
450     uint8_t& bus = device->second.first;
451     uint8_t& address = device->second.second;
452 
453     ManagedObjectType frus;
454 
455     std::shared_ptr<sdbusplus::asio::connection> dbus = getSdBus();
456     sdbusplus::message::message getObjects = dbus->new_method_call(
457         fruDeviceServiceName, "/", "org.freedesktop.DBus.ObjectManager",
458         "GetManagedObjects");
459     try
460     {
461         sdbusplus::message::message resp = dbus->call(getObjects);
462         resp.read(frus);
463     }
464     catch (sdbusplus::exception_t&)
465     {
466         return IPMI_CC_RESPONSE_ERROR;
467     }
468     boost::container::flat_map<std::string, DbusVariant>* fruData = nullptr;
469     auto fru =
470         std::find_if(frus.begin(), frus.end(),
471                      [bus, address, &fruData](ManagedEntry& entry) {
472                          auto findFruDevice =
473                              entry.second.find("xyz.openbmc_project.FruDevice");
474                          if (findFruDevice == entry.second.end())
475                          {
476                              return false;
477                          }
478                          fruData = &(findFruDevice->second);
479                          auto findBus = findFruDevice->second.find("BUS");
480                          auto findAddress =
481                              findFruDevice->second.find("ADDRESS");
482                          if (findBus == findFruDevice->second.end() ||
483                              findAddress == findFruDevice->second.end())
484                          {
485                              return false;
486                          }
487                          if (std::get<uint32_t>(findBus->second) != bus)
488                          {
489                              return false;
490                          }
491                          if (std::get<uint32_t>(findAddress->second) != address)
492                          {
493                              return false;
494                          }
495                          return true;
496                      });
497     if (fru == frus.end())
498     {
499         return IPMI_CC_RESPONSE_ERROR;
500     }
501     std::string name;
502     auto findProductName = fruData->find("BOARD_PRODUCT_NAME");
503     auto findBoardName = fruData->find("PRODUCT_PRODUCT_NAME");
504     if (findProductName != fruData->end())
505     {
506         name = std::get<std::string>(findProductName->second);
507     }
508     else if (findBoardName != fruData->end())
509     {
510         name = std::get<std::string>(findBoardName->second);
511     }
512     else
513     {
514         name = "UNKNOWN";
515     }
516     if (name.size() > maxFruSdrNameSize)
517     {
518         name = name.substr(0, maxFruSdrNameSize);
519     }
520     size_t sizeDiff = maxFruSdrNameSize - name.size();
521 
522     resp.header.record_id_lsb = 0x0; // calling code is to implement these
523     resp.header.record_id_msb = 0x0;
524     resp.header.sdr_version = ipmiSdrVersion;
525     resp.header.record_type = 0x11; // FRU Device Locator
526     resp.header.record_length = sizeof(resp.body) + sizeof(resp.key) - sizeDiff;
527     resp.key.deviceAddress = 0x20;
528     resp.key.fruID = device->first;
529     resp.key.accessLun = 0x80; // logical / physical fru device
530     resp.key.channelNumber = 0x0;
531     resp.body.reserved = 0x0;
532     resp.body.deviceType = 0x10;
533     resp.body.deviceTypeModifier = 0x0;
534     resp.body.entityID = 0x0;
535     resp.body.entityInstance = 0x1;
536     resp.body.oem = 0x0;
537     resp.body.deviceIDLen = name.size();
538     name.copy(resp.body.deviceID, name.size());
539 
540     return IPMI_CC_OK;
541 }
542 
543 static bool getSELLogFiles(std::vector<std::filesystem::path>& selLogFiles)
544 {
545     // Loop through the directory looking for ipmi_sel log files
546     for (const std::filesystem::directory_entry& dirEnt :
547          std::filesystem::directory_iterator(intel_oem::ipmi::sel::selLogDir))
548     {
549         std::string filename = dirEnt.path().filename();
550         if (boost::starts_with(filename, intel_oem::ipmi::sel::selLogFilename))
551         {
552             // If we find an ipmi_sel log file, save the path
553             selLogFiles.emplace_back(intel_oem::ipmi::sel::selLogDir /
554                                      filename);
555         }
556     }
557     // As the log files rotate, they are appended with a ".#" that is higher for
558     // the older logs. Since we don't expect more than 10 log files, we
559     // can just sort the list to get them in order from newest to oldest
560     std::sort(selLogFiles.begin(), selLogFiles.end());
561 
562     return !selLogFiles.empty();
563 }
564 
565 static int countSELEntries()
566 {
567     // Get the list of ipmi_sel log files
568     std::vector<std::filesystem::path> selLogFiles;
569     if (!getSELLogFiles(selLogFiles))
570     {
571         return 0;
572     }
573     int numSELEntries = 0;
574     // Loop through each log file and count the number of logs
575     for (const std::filesystem::path& file : selLogFiles)
576     {
577         std::ifstream logStream(file);
578         if (!logStream.is_open())
579         {
580             continue;
581         }
582 
583         std::string line;
584         while (std::getline(logStream, line))
585         {
586             numSELEntries++;
587         }
588     }
589     return numSELEntries;
590 }
591 
592 static bool findSELEntry(const int recordID,
593                          const std::vector<std::filesystem::path>& selLogFiles,
594                          std::string& entry)
595 {
596     // Record ID is the first entry field following the timestamp. It is
597     // preceded by a space and followed by a comma
598     std::string search = " " + std::to_string(recordID) + ",";
599 
600     // Loop through the ipmi_sel log entries
601     for (const std::filesystem::path& file : selLogFiles)
602     {
603         std::ifstream logStream(file);
604         if (!logStream.is_open())
605         {
606             continue;
607         }
608 
609         while (std::getline(logStream, entry))
610         {
611             // Check if the record ID matches
612             if (entry.find(search) != std::string::npos)
613             {
614                 return true;
615             }
616         }
617     }
618     return false;
619 }
620 
621 static uint16_t
622     getNextRecordID(const uint16_t recordID,
623                     const std::vector<std::filesystem::path>& selLogFiles)
624 {
625     uint16_t nextRecordID = recordID + 1;
626     std::string entry;
627     if (findSELEntry(nextRecordID, selLogFiles, entry))
628     {
629         return nextRecordID;
630     }
631     else
632     {
633         return ipmi::sel::lastEntry;
634     }
635 }
636 
637 static int fromHexStr(const std::string& hexStr, std::vector<uint8_t>& data)
638 {
639     for (unsigned int i = 0; i < hexStr.size(); i += 2)
640     {
641         try
642         {
643             data.push_back(static_cast<uint8_t>(
644                 std::stoul(hexStr.substr(i, 2), nullptr, 16)));
645         }
646         catch (std::invalid_argument& e)
647         {
648             phosphor::logging::log<phosphor::logging::level::ERR>(e.what());
649             return -1;
650         }
651         catch (std::out_of_range& e)
652         {
653             phosphor::logging::log<phosphor::logging::level::ERR>(e.what());
654             return -1;
655         }
656     }
657     return 0;
658 }
659 
660 ipmi::RspType<uint8_t,  // SEL version
661               uint16_t, // SEL entry count
662               uint16_t, // free space
663               uint32_t, // last add timestamp
664               uint32_t, // last erase timestamp
665               uint8_t>  // operation support
666     ipmiStorageGetSELInfo()
667 {
668     constexpr uint8_t selVersion = ipmi::sel::selVersion;
669     uint16_t entries = countSELEntries();
670     uint32_t addTimeStamp = intel_oem::ipmi::sel::getFileTimestamp(
671         intel_oem::ipmi::sel::selLogDir / intel_oem::ipmi::sel::selLogFilename);
672     uint32_t eraseTimeStamp = intel_oem::ipmi::sel::erase_time::get();
673     constexpr uint8_t operationSupport =
674         intel_oem::ipmi::sel::selOperationSupport;
675     constexpr uint16_t freeSpace =
676         0xffff; // Spec indicates that more than 64kB is free
677 
678     return ipmi::responseSuccess(selVersion, entries, freeSpace, addTimeStamp,
679                                  eraseTimeStamp, operationSupport);
680 }
681 
682 using systemEventType = std::tuple<
683     uint32_t, // Timestamp
684     uint16_t, // Generator ID
685     uint8_t,  // EvM Rev
686     uint8_t,  // Sensor Type
687     uint8_t,  // Sensor Number
688     uint7_t,  // Event Type
689     bool,     // Event Direction
690     std::array<uint8_t, intel_oem::ipmi::sel::systemEventSize>>; // Event Data
691 using oemTsEventType = std::tuple<
692     uint32_t,                                                   // Timestamp
693     std::array<uint8_t, intel_oem::ipmi::sel::oemTsEventSize>>; // Event Data
694 using oemEventType =
695     std::array<uint8_t, intel_oem::ipmi::sel::oemEventSize>; // Event Data
696 
697 ipmi::RspType<uint16_t, // Next Record ID
698               uint16_t, // Record ID
699               uint8_t,  // Record Type
700               std::variant<systemEventType, oemTsEventType,
701                            oemEventType>> // Record Content
702     ipmiStorageGetSELEntry(uint16_t reservationID, uint16_t targetID,
703                            uint8_t offset, uint8_t size)
704 {
705     // Only support getting the entire SEL record. If a partial size or non-zero
706     // offset is requested, return an error
707     if (offset != 0 || size != ipmi::sel::entireRecord)
708     {
709         return ipmi::responseRetBytesUnavailable();
710     }
711 
712     // Check the reservation ID if one is provided or required (only if the
713     // offset is non-zero)
714     if (reservationID != 0 || offset != 0)
715     {
716         if (!checkSELReservation(reservationID))
717         {
718             return ipmi::responseInvalidReservationId();
719         }
720     }
721 
722     // Get the ipmi_sel log files
723     std::vector<std::filesystem::path> selLogFiles;
724     if (!getSELLogFiles(selLogFiles))
725     {
726         return ipmi::responseSensorInvalid();
727     }
728 
729     std::string targetEntry;
730 
731     if (targetID == ipmi::sel::firstEntry)
732     {
733         // The first entry will be at the top of the oldest log file
734         std::ifstream logStream(selLogFiles.back());
735         if (!logStream.is_open())
736         {
737             return ipmi::responseUnspecifiedError();
738         }
739 
740         if (!std::getline(logStream, targetEntry))
741         {
742             return ipmi::responseUnspecifiedError();
743         }
744     }
745     else if (targetID == ipmi::sel::lastEntry)
746     {
747         // The last entry will be at the bottom of the newest log file
748         std::ifstream logStream(selLogFiles.front());
749         if (!logStream.is_open())
750         {
751             return ipmi::responseUnspecifiedError();
752         }
753 
754         std::string line;
755         while (std::getline(logStream, line))
756         {
757             targetEntry = line;
758         }
759     }
760     else
761     {
762         if (!findSELEntry(targetID, selLogFiles, targetEntry))
763         {
764             return ipmi::responseSensorInvalid();
765         }
766     }
767 
768     // The format of the ipmi_sel message is "<Timestamp>
769     // <ID>,<Type>,<EventData>,[<Generator ID>,<Path>,<Direction>]".
770     // First get the Timestamp
771     size_t space = targetEntry.find_first_of(" ");
772     if (space == std::string::npos)
773     {
774         return ipmi::responseUnspecifiedError();
775     }
776     std::string entryTimestamp = targetEntry.substr(0, space);
777     // Then get the log contents
778     size_t entryStart = targetEntry.find_first_not_of(" ", space);
779     if (entryStart == std::string::npos)
780     {
781         return ipmi::responseUnspecifiedError();
782     }
783     std::string_view entry(targetEntry);
784     entry.remove_prefix(entryStart);
785     // Use split to separate the entry into its fields
786     std::vector<std::string> targetEntryFields;
787     boost::split(targetEntryFields, entry, boost::is_any_of(","),
788                  boost::token_compress_on);
789     if (targetEntryFields.size() < 3)
790     {
791         return ipmi::responseUnspecifiedError();
792     }
793     std::string& recordIDStr = targetEntryFields[0];
794     std::string& recordTypeStr = targetEntryFields[1];
795     std::string& eventDataStr = targetEntryFields[2];
796 
797     uint16_t recordID;
798     uint8_t recordType;
799     try
800     {
801         recordID = std::stoul(recordIDStr);
802         recordType = std::stoul(recordTypeStr, nullptr, 16);
803     }
804     catch (const std::invalid_argument&)
805     {
806         return ipmi::responseUnspecifiedError();
807     }
808     uint16_t nextRecordID = getNextRecordID(recordID, selLogFiles);
809     std::vector<uint8_t> eventDataBytes;
810     if (fromHexStr(eventDataStr, eventDataBytes) < 0)
811     {
812         return ipmi::responseUnspecifiedError();
813     }
814 
815     if (recordType == intel_oem::ipmi::sel::systemEvent)
816     {
817         // Get the timestamp
818         std::tm timeStruct = {};
819         std::istringstream entryStream(entryTimestamp);
820 
821         uint32_t timestamp = ipmi::sel::invalidTimeStamp;
822         if (entryStream >> std::get_time(&timeStruct, "%Y-%m-%dT%H:%M:%S"))
823         {
824             timestamp = std::mktime(&timeStruct);
825         }
826 
827         // Set the event message revision
828         uint8_t evmRev = intel_oem::ipmi::sel::eventMsgRev;
829 
830         uint16_t generatorID = 0;
831         uint8_t sensorType = 0;
832         uint8_t sensorNum = 0xFF;
833         uint7_t eventType = 0;
834         bool eventDir = 0;
835         // System type events should have six fields
836         if (targetEntryFields.size() >= 6)
837         {
838             std::string& generatorIDStr = targetEntryFields[3];
839             std::string& sensorPath = targetEntryFields[4];
840             std::string& eventDirStr = targetEntryFields[5];
841 
842             // Get the generator ID
843             try
844             {
845                 generatorID = std::stoul(generatorIDStr, nullptr, 16);
846             }
847             catch (const std::invalid_argument&)
848             {
849                 std::cerr << "Invalid Generator ID\n";
850             }
851 
852             // Get the sensor type, sensor number, and event type for the sensor
853             sensorType = getSensorTypeFromPath(sensorPath);
854             sensorNum = getSensorNumberFromPath(sensorPath);
855             eventType = getSensorEventTypeFromPath(sensorPath);
856 
857             // Get the event direction
858             try
859             {
860                 eventDir = std::stoul(eventDirStr) ? 0 : 1;
861             }
862             catch (const std::invalid_argument&)
863             {
864                 std::cerr << "Invalid Event Direction\n";
865             }
866         }
867 
868         // Only keep the eventData bytes that fit in the record
869         std::array<uint8_t, intel_oem::ipmi::sel::systemEventSize> eventData{};
870         std::copy_n(eventDataBytes.begin(),
871                     std::min(eventDataBytes.size(), eventData.size()),
872                     eventData.begin());
873 
874         return ipmi::responseSuccess(
875             nextRecordID, recordID, recordType,
876             systemEventType{timestamp, generatorID, evmRev, sensorType,
877                             sensorNum, eventType, eventDir, eventData});
878     }
879     else if (recordType >= intel_oem::ipmi::sel::oemTsEventFirst &&
880              recordType <= intel_oem::ipmi::sel::oemTsEventLast)
881     {
882         // Get the timestamp
883         std::tm timeStruct = {};
884         std::istringstream entryStream(entryTimestamp);
885 
886         uint32_t timestamp = ipmi::sel::invalidTimeStamp;
887         if (entryStream >> std::get_time(&timeStruct, "%Y-%m-%dT%H:%M:%S"))
888         {
889             timestamp = std::mktime(&timeStruct);
890         }
891 
892         // Only keep the bytes that fit in the record
893         std::array<uint8_t, intel_oem::ipmi::sel::oemTsEventSize> eventData{};
894         std::copy_n(eventDataBytes.begin(),
895                     std::min(eventDataBytes.size(), eventData.size()),
896                     eventData.begin());
897 
898         return ipmi::responseSuccess(nextRecordID, recordID, recordType,
899                                      oemTsEventType{timestamp, eventData});
900     }
901     else if (recordType >= intel_oem::ipmi::sel::oemEventFirst &&
902              recordType <= intel_oem::ipmi::sel::oemEventLast)
903     {
904         // Only keep the bytes that fit in the record
905         std::array<uint8_t, intel_oem::ipmi::sel::oemEventSize> eventData{};
906         std::copy_n(eventDataBytes.begin(),
907                     std::min(eventDataBytes.size(), eventData.size()),
908                     eventData.begin());
909 
910         return ipmi::responseSuccess(nextRecordID, recordID, recordType,
911                                      eventData);
912     }
913 
914     return ipmi::responseUnspecifiedError();
915 }
916 
917 ipmi::RspType<uint16_t> ipmiStorageAddSELEntry(
918     uint16_t recordID, uint8_t recordType, uint32_t timestamp,
919     uint16_t generatorID, uint8_t evmRev, uint8_t sensorType, uint8_t sensorNum,
920     uint8_t eventType, uint8_t eventData1, uint8_t eventData2,
921     uint8_t eventData3)
922 {
923     // Per the IPMI spec, need to cancel any reservation when a SEL entry is
924     // added
925     cancelSELReservation();
926 
927     // Send this request to the Redfish hooks to log it as a Redfish message
928     // instead.  There is no need to add it to the SEL, so just return success.
929     intel_oem::ipmi::sel::checkRedfishHooks(
930         recordID, recordType, timestamp, generatorID, evmRev, sensorType,
931         sensorNum, eventType, eventData1, eventData2, eventData3);
932 
933     uint16_t responseID = 0xFFFF;
934     return ipmi::responseSuccess(responseID);
935 }
936 
937 ipmi::RspType<uint8_t> ipmiStorageClearSEL(ipmi::Context::ptr ctx,
938                                            uint16_t reservationID,
939                                            const std::array<uint8_t, 3>& clr,
940                                            uint8_t eraseOperation)
941 {
942     if (!checkSELReservation(reservationID))
943     {
944         return ipmi::responseInvalidReservationId();
945     }
946 
947     static constexpr std::array<uint8_t, 3> clrExpected = {'C', 'L', 'R'};
948     if (clr != clrExpected)
949     {
950         return ipmi::responseInvalidFieldRequest();
951     }
952 
953     // Erasure status cannot be fetched, so always return erasure status as
954     // `erase completed`.
955     if (eraseOperation == ipmi::sel::getEraseStatus)
956     {
957         return ipmi::responseSuccess(ipmi::sel::eraseComplete);
958     }
959 
960     // Check that initiate erase is correct
961     if (eraseOperation != ipmi::sel::initiateErase)
962     {
963         return ipmi::responseInvalidFieldRequest();
964     }
965 
966     // Per the IPMI spec, need to cancel any reservation when the SEL is
967     // cleared
968     cancelSELReservation();
969 
970     // Save the erase time
971     intel_oem::ipmi::sel::erase_time::save();
972 
973     // Clear the SEL by deleting the log files
974     std::vector<std::filesystem::path> selLogFiles;
975     if (getSELLogFiles(selLogFiles))
976     {
977         for (const std::filesystem::path& file : selLogFiles)
978         {
979             std::error_code ec;
980             std::filesystem::remove(file, ec);
981         }
982     }
983 
984     // Reload rsyslog so it knows to start new log files
985     std::shared_ptr<sdbusplus::asio::connection> dbus = getSdBus();
986     sdbusplus::message::message rsyslogReload = dbus->new_method_call(
987         "org.freedesktop.systemd1", "/org/freedesktop/systemd1",
988         "org.freedesktop.systemd1.Manager", "ReloadUnit");
989     rsyslogReload.append("rsyslog.service", "replace");
990     try
991     {
992         sdbusplus::message::message reloadResponse = dbus->call(rsyslogReload);
993     }
994     catch (sdbusplus::exception_t& e)
995     {
996         phosphor::logging::log<phosphor::logging::level::ERR>(e.what());
997     }
998 
999     return ipmi::responseSuccess(ipmi::sel::eraseComplete);
1000 }
1001 
1002 ipmi::RspType<uint32_t> ipmiStorageGetSELTime()
1003 {
1004     struct timespec selTime = {};
1005 
1006     if (clock_gettime(CLOCK_REALTIME, &selTime) < 0)
1007     {
1008         return ipmi::responseUnspecifiedError();
1009     }
1010 
1011     return ipmi::responseSuccess(selTime.tv_sec);
1012 }
1013 
1014 ipmi::RspType<> ipmiStorageSetSELTime(uint32_t selTime)
1015 {
1016     // Set SEL Time is not supported
1017     return ipmi::responseInvalidCommand();
1018 }
1019 
1020 std::vector<uint8_t> getType12SDRs(uint16_t index, uint16_t recordId)
1021 {
1022     std::vector<uint8_t> resp;
1023     if (index == 0)
1024     {
1025         Type12Record bmc = {};
1026         bmc.header.record_id_lsb = recordId;
1027         bmc.header.record_id_msb = recordId >> 8;
1028         bmc.header.sdr_version = ipmiSdrVersion;
1029         bmc.header.record_type = 0x12;
1030         bmc.header.record_length = 0x1b;
1031         bmc.slaveAddress = 0x20;
1032         bmc.channelNumber = 0;
1033         bmc.powerStateNotification = 0;
1034         bmc.deviceCapabilities = 0xBF;
1035         bmc.reserved = 0;
1036         bmc.entityID = 0x2E;
1037         bmc.entityInstance = 1;
1038         bmc.oem = 0;
1039         bmc.typeLengthCode = 0xD0;
1040         std::string bmcName = "Basbrd Mgmt Ctlr";
1041         std::copy(bmcName.begin(), bmcName.end(), bmc.name);
1042         uint8_t* bmcPtr = reinterpret_cast<uint8_t*>(&bmc);
1043         resp.insert(resp.end(), bmcPtr, bmcPtr + sizeof(Type12Record));
1044     }
1045     else if (index == 1)
1046     {
1047         Type12Record me = {};
1048         me.header.record_id_lsb = recordId;
1049         me.header.record_id_msb = recordId >> 8;
1050         me.header.sdr_version = ipmiSdrVersion;
1051         me.header.record_type = 0x12;
1052         me.header.record_length = 0x16;
1053         me.slaveAddress = 0x2C;
1054         me.channelNumber = 6;
1055         me.powerStateNotification = 0x24;
1056         me.deviceCapabilities = 0x21;
1057         me.reserved = 0;
1058         me.entityID = 0x2E;
1059         me.entityInstance = 2;
1060         me.oem = 0;
1061         me.typeLengthCode = 0xCB;
1062         std::string meName = "Mgmt Engine";
1063         std::copy(meName.begin(), meName.end(), me.name);
1064         uint8_t* mePtr = reinterpret_cast<uint8_t*>(&me);
1065         resp.insert(resp.end(), mePtr, mePtr + sizeof(Type12Record));
1066     }
1067     else
1068     {
1069         throw std::runtime_error("getType12SDRs:: Illegal index " +
1070                                  std::to_string(index));
1071     }
1072 
1073     return resp;
1074 }
1075 
1076 void registerStorageFunctions()
1077 {
1078     // <Get FRU Inventory Area Info>
1079     ipmi::registerHandler(ipmi::prioOemBase, ipmi::netFnStorage,
1080                           ipmi::storage::cmdGetFruInventoryAreaInfo,
1081                           ipmi::Privilege::User, ipmiStorageGetFruInvAreaInfo);
1082     // <READ FRU Data>
1083     ipmi::registerHandler(ipmi::prioOpenBmcBase, ipmi::netFnStorage,
1084                           ipmi::storage::cmdReadFruData, ipmi::Privilege::User,
1085                           ipmiStorageReadFruData);
1086 
1087     // <WRITE FRU Data>
1088     ipmi::registerHandler(ipmi::prioOpenBmcBase, ipmi::netFnStorage,
1089                           ipmi::storage::cmdWriteFruData,
1090                           ipmi::Privilege::Operator, ipmiStorageWriteFruData);
1091 
1092     // <Get SEL Info>
1093     ipmi::registerHandler(ipmi::prioOpenBmcBase, ipmi::netFnStorage,
1094                           ipmi::storage::cmdGetSelInfo, ipmi::Privilege::User,
1095                           ipmiStorageGetSELInfo);
1096 
1097     // <Get SEL Entry>
1098     ipmi::registerHandler(ipmi::prioOpenBmcBase, ipmi::netFnStorage,
1099                           ipmi::storage::cmdGetSelEntry, ipmi::Privilege::User,
1100                           ipmiStorageGetSELEntry);
1101 
1102     // <Add SEL Entry>
1103     ipmi::registerHandler(ipmi::prioOpenBmcBase, ipmi::netFnStorage,
1104                           ipmi::storage::cmdAddSelEntry,
1105                           ipmi::Privilege::Operator, ipmiStorageAddSELEntry);
1106 
1107     // <Clear SEL>
1108     ipmi::registerHandler(ipmi::prioOpenBmcBase, ipmi::netFnStorage,
1109                           ipmi::storage::cmdClearSel, ipmi::Privilege::Operator,
1110                           ipmiStorageClearSEL);
1111 
1112     // <Get SEL Time>
1113     ipmi::registerHandler(ipmi::prioOpenBmcBase, ipmi::netFnStorage,
1114                           ipmi::storage::cmdGetSelTime, ipmi::Privilege::User,
1115                           ipmiStorageGetSELTime);
1116 
1117     // <Set SEL Time>
1118     ipmi::registerHandler(ipmi::prioOpenBmcBase, ipmi::netFnStorage,
1119                           ipmi::storage::cmdSetSelTime,
1120                           ipmi::Privilege::Operator, ipmiStorageSetSELTime);
1121 }
1122 } // namespace storage
1123 } // namespace ipmi
1124