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