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