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