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