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