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