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