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