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