1 #include "config.h"
2 
3 #include <arpa/inet.h>
4 #include <fcntl.h>
5 #include <limits.h>
6 #include <linux/i2c-dev.h>
7 #include <linux/i2c.h>
8 #include <sys/ioctl.h>
9 #include <sys/stat.h>
10 #include <sys/types.h>
11 #include <systemd/sd-bus.h>
12 #include <unistd.h>
13 
14 #include <app/channel.hpp>
15 #include <app/watchdog.hpp>
16 #include <apphandler.hpp>
17 #include <ipmid/api.hpp>
18 #include <ipmid/sessiondef.hpp>
19 #include <ipmid/sessionhelper.hpp>
20 #include <ipmid/types.hpp>
21 #include <ipmid/utils.hpp>
22 #include <nlohmann/json.hpp>
23 #include <phosphor-logging/elog-errors.hpp>
24 #include <phosphor-logging/lg2.hpp>
25 #include <sdbusplus/message/types.hpp>
26 #include <sys_info_param.hpp>
27 #include <xyz/openbmc_project/Common/error.hpp>
28 #include <xyz/openbmc_project/Control/Power/ACPIPowerState/server.hpp>
29 #include <xyz/openbmc_project/Software/Activation/server.hpp>
30 #include <xyz/openbmc_project/Software/Version/server.hpp>
31 #include <xyz/openbmc_project/State/BMC/server.hpp>
32 
33 #include <algorithm>
34 #include <array>
35 #include <charconv>
36 #include <cstddef>
37 #include <cstdint>
38 #include <filesystem>
39 #include <fstream>
40 #include <memory>
41 #include <regex>
42 #include <string>
43 #include <string_view>
44 #include <tuple>
45 #include <vector>
46 
47 extern sd_bus* bus;
48 
49 constexpr auto bmc_state_interface = "xyz.openbmc_project.State.BMC";
50 constexpr auto bmc_state_property = "CurrentBMCState";
51 
52 static constexpr auto redundancyIntf =
53     "xyz.openbmc_project.Software.RedundancyPriority";
54 static constexpr auto versionIntf = "xyz.openbmc_project.Software.Version";
55 static constexpr auto activationIntf =
56     "xyz.openbmc_project.Software.Activation";
57 static constexpr auto softwareRoot = "/xyz/openbmc_project/software";
58 
59 void register_netfn_app_functions() __attribute__((constructor));
60 
61 using namespace phosphor::logging;
62 using namespace sdbusplus::error::xyz::openbmc_project::common;
63 using Version = sdbusplus::server::xyz::openbmc_project::software::Version;
64 using Activation =
65     sdbusplus::server::xyz::openbmc_project::software::Activation;
66 using BMC = sdbusplus::server::xyz::openbmc_project::state::BMC;
67 namespace fs = std::filesystem;
68 
69 #ifdef ENABLE_I2C_WHITELIST_CHECK
70 typedef struct
71 {
72     uint8_t busId;
73     uint8_t targetAddr;
74     uint8_t targetAddrMask;
75     std::vector<uint8_t> data;
76     std::vector<uint8_t> dataMask;
77 } i2cControllerWRAllowlist;
78 
79 static std::vector<i2cControllerWRAllowlist>& getWRAllowlist()
80 {
81     static std::vector<i2cControllerWRAllowlist> wrAllowlist;
82     return wrAllowlist;
83 }
84 
85 static constexpr const char* i2cControllerWRAllowlistFile =
86     "/usr/share/ipmi-providers/master_write_read_white_list.json";
87 
88 static constexpr const char* filtersStr = "filters";
89 static constexpr const char* busIdStr = "busId";
90 static constexpr const char* targetAddrStr = "slaveAddr";
91 static constexpr const char* targetAddrMaskStr = "slaveAddrMask";
92 static constexpr const char* cmdStr = "command";
93 static constexpr const char* cmdMaskStr = "commandMask";
94 static constexpr int base_16 = 16;
95 #endif // ENABLE_I2C_WHITELIST_CHECK
96 static constexpr uint8_t oemCmdStart = 192;
97 static constexpr uint8_t invalidParamSelectorStart = 8;
98 static constexpr uint8_t invalidParamSelectorEnd = 191;
99 
100 /**
101  * @brief Returns the Version info from primary s/w object
102  *
103  * Get the Version info from the active s/w object which is having high
104  * "Priority" value(a smaller number is a higher priority) and "Purpose"
105  * is "BMC" from the list of all s/w objects those are implementing
106  * RedundancyPriority interface from the given softwareRoot path.
107  *
108  * @return On success returns the Version info from primary s/w object.
109  *
110  */
111 std::string getActiveSoftwareVersionInfo(ipmi::Context::ptr ctx)
112 {
113     std::string revision{};
114     ipmi::ObjectTree objectTree;
115     try
116     {
117         objectTree =
118             ipmi::getAllDbusObjects(*ctx->bus, softwareRoot, redundancyIntf);
119     }
120     catch (const sdbusplus::exception_t& e)
121     {
122         lg2::error("Failed to fetch redundancy object from dbus, "
123                    "interface: {INTERFACE},  error: {ERROR}",
124                    "INTERFACE", redundancyIntf, "ERROR", e);
125         elog<InternalFailure>();
126     }
127 
128     auto objectFound = false;
129     for (auto& softObject : objectTree)
130     {
131         auto service =
132             ipmi::getService(*ctx->bus, redundancyIntf, softObject.first);
133         auto objValueTree =
134             ipmi::getManagedObjects(*ctx->bus, service, softwareRoot);
135 
136         auto minPriority = 0xFF;
137         for (const auto& objIter : objValueTree)
138         {
139             try
140             {
141                 auto& intfMap = objIter.second;
142                 auto& redundancyPriorityProps = intfMap.at(redundancyIntf);
143                 auto& versionProps = intfMap.at(versionIntf);
144                 auto& activationProps = intfMap.at(activationIntf);
145                 auto priority =
146                     std::get<uint8_t>(redundancyPriorityProps.at("Priority"));
147                 auto purpose =
148                     std::get<std::string>(versionProps.at("Purpose"));
149                 auto activation =
150                     std::get<std::string>(activationProps.at("Activation"));
151                 auto version =
152                     std::get<std::string>(versionProps.at("Version"));
153                 if ((Version::convertVersionPurposeFromString(purpose) ==
154                      Version::VersionPurpose::BMC) &&
155                     (Activation::convertActivationsFromString(activation) ==
156                      Activation::Activations::Active))
157                 {
158                     if (priority < minPriority)
159                     {
160                         minPriority = priority;
161                         objectFound = true;
162                         revision = std::move(version);
163                     }
164                 }
165             }
166             catch (const std::exception& e)
167             {
168                 lg2::error("error message: {ERROR}", "ERROR", e);
169             }
170         }
171     }
172 
173     if (!objectFound)
174     {
175         lg2::error("Could not found an BMC software Object");
176         elog<InternalFailure>();
177     }
178 
179     return revision;
180 }
181 
182 bool getCurrentBmcState()
183 {
184     sdbusplus::bus_t bus{ipmid_get_sd_bus_connection()};
185 
186     // Get the Inventory object implementing the BMC interface
187     ipmi::DbusObjectInfo bmcObject =
188         ipmi::getDbusObject(bus, bmc_state_interface);
189     auto variant =
190         ipmi::getDbusProperty(bus, bmcObject.second, bmcObject.first,
191                               bmc_state_interface, bmc_state_property);
192 
193     return std::holds_alternative<std::string>(variant) &&
194            BMC::convertBMCStateFromString(std::get<std::string>(variant)) ==
195                BMC::BMCState::Ready;
196 }
197 
198 bool getCurrentBmcStateWithFallback(const bool fallbackAvailability)
199 {
200     try
201     {
202         return getCurrentBmcState();
203     }
204     catch (...)
205     {
206         // Nothing provided the BMC interface, therefore return whatever was
207         // configured as the default.
208         return fallbackAvailability;
209     }
210 }
211 
212 namespace acpi_state
213 {
214 using namespace sdbusplus::server::xyz::openbmc_project::control::power;
215 
216 const static constexpr char* acpiObjPath =
217     "/xyz/openbmc_project/control/host0/acpi_power_state";
218 const static constexpr char* acpiInterface =
219     "xyz.openbmc_project.Control.Power.ACPIPowerState";
220 const static constexpr char* sysACPIProp = "SysACPIStatus";
221 const static constexpr char* devACPIProp = "DevACPIStatus";
222 
223 enum class PowerStateType : uint8_t
224 {
225     sysPowerState = 0x00,
226     devPowerState = 0x01,
227 };
228 
229 // Defined in 20.6 of ipmi doc
230 enum class PowerState : uint8_t
231 {
232     s0G0D0 = 0x00,
233     s1D1 = 0x01,
234     s2D2 = 0x02,
235     s3D3 = 0x03,
236     s4 = 0x04,
237     s5G2 = 0x05,
238     s4S5 = 0x06,
239     g3 = 0x07,
240     sleep = 0x08,
241     g1Sleep = 0x09,
242     override = 0x0a,
243     legacyOn = 0x20,
244     legacyOff = 0x21,
245     unknown = 0x2a,
246     noChange = 0x7f,
247 };
248 
249 static constexpr uint8_t stateChanged = 0x80;
250 
251 std::map<ACPIPowerState::ACPI, PowerState> dbusToIPMI = {
252     {ACPIPowerState::ACPI::S0_G0_D0, PowerState::s0G0D0},
253     {ACPIPowerState::ACPI::S1_D1, PowerState::s1D1},
254     {ACPIPowerState::ACPI::S2_D2, PowerState::s2D2},
255     {ACPIPowerState::ACPI::S3_D3, PowerState::s3D3},
256     {ACPIPowerState::ACPI::S4, PowerState::s4},
257     {ACPIPowerState::ACPI::S5_G2, PowerState::s5G2},
258     {ACPIPowerState::ACPI::S4_S5, PowerState::s4S5},
259     {ACPIPowerState::ACPI::G3, PowerState::g3},
260     {ACPIPowerState::ACPI::SLEEP, PowerState::sleep},
261     {ACPIPowerState::ACPI::G1_SLEEP, PowerState::g1Sleep},
262     {ACPIPowerState::ACPI::OVERRIDE, PowerState::override},
263     {ACPIPowerState::ACPI::LEGACY_ON, PowerState::legacyOn},
264     {ACPIPowerState::ACPI::LEGACY_OFF, PowerState::legacyOff},
265     {ACPIPowerState::ACPI::Unknown, PowerState::unknown}};
266 
267 bool isValidACPIState(acpi_state::PowerStateType type, uint8_t state)
268 {
269     if (type == acpi_state::PowerStateType::sysPowerState)
270     {
271         if ((state <= static_cast<uint8_t>(acpi_state::PowerState::override)) ||
272             (state == static_cast<uint8_t>(acpi_state::PowerState::legacyOn)) ||
273             (state ==
274              static_cast<uint8_t>(acpi_state::PowerState::legacyOff)) ||
275             (state == static_cast<uint8_t>(acpi_state::PowerState::unknown)) ||
276             (state == static_cast<uint8_t>(acpi_state::PowerState::noChange)))
277         {
278             return true;
279         }
280         else
281         {
282             return false;
283         }
284     }
285     else if (type == acpi_state::PowerStateType::devPowerState)
286     {
287         if ((state <= static_cast<uint8_t>(acpi_state::PowerState::s3D3)) ||
288             (state == static_cast<uint8_t>(acpi_state::PowerState::unknown)) ||
289             (state == static_cast<uint8_t>(acpi_state::PowerState::noChange)))
290         {
291             return true;
292         }
293         else
294         {
295             return false;
296         }
297     }
298     else
299     {
300         return false;
301     }
302     return false;
303 }
304 } // namespace acpi_state
305 
306 /** @brief implements Set ACPI Power State command
307  * @param sysAcpiState - ACPI system power state to set
308  * @param devAcpiState - ACPI device power state to set
309  *
310  * @return IPMI completion code on success
311  **/
312 ipmi::RspType<> ipmiSetAcpiPowerState(uint8_t sysAcpiState,
313                                       uint8_t devAcpiState)
314 {
315     auto s = static_cast<uint8_t>(acpi_state::PowerState::unknown);
316 
317     sdbusplus::bus_t bus{ipmid_get_sd_bus_connection()};
318 
319     auto value = acpi_state::ACPIPowerState::ACPI::Unknown;
320 
321     if (sysAcpiState & acpi_state::stateChanged)
322     {
323         // set system power state
324         s = sysAcpiState & ~acpi_state::stateChanged;
325 
326         if (!acpi_state::isValidACPIState(
327                 acpi_state::PowerStateType::sysPowerState, s))
328         {
329             lg2::error("set_acpi_power sys invalid input, S: {S}", "S", s);
330             return ipmi::responseParmOutOfRange();
331         }
332 
333         // valid input
334         if (s == static_cast<uint8_t>(acpi_state::PowerState::noChange))
335         {
336             lg2::debug("No change for system power state");
337         }
338         else
339         {
340             auto found = std::find_if(
341                 acpi_state::dbusToIPMI.begin(), acpi_state::dbusToIPMI.end(),
342                 [&s](const auto& iter) {
343                     return (static_cast<uint8_t>(iter.second) == s);
344                 });
345 
346             value = found->first;
347 
348             try
349             {
350                 auto acpiObject =
351                     ipmi::getDbusObject(bus, acpi_state::acpiInterface);
352                 ipmi::setDbusProperty(bus, acpiObject.second, acpiObject.first,
353                                       acpi_state::acpiInterface,
354                                       acpi_state::sysACPIProp,
355                                       convertForMessage(value));
356             }
357             catch (const InternalFailure& e)
358             {
359                 lg2::error("Failed in set ACPI system property: {ERROR}",
360                            "ERROR", e);
361                 return ipmi::responseUnspecifiedError();
362             }
363         }
364     }
365     else
366     {
367         lg2::debug("Do not change system power state");
368     }
369 
370     if (devAcpiState & acpi_state::stateChanged)
371     {
372         // set device power state
373         s = devAcpiState & ~acpi_state::stateChanged;
374         if (!acpi_state::isValidACPIState(
375                 acpi_state::PowerStateType::devPowerState, s))
376         {
377             lg2::error("set_acpi_power dev invalid input, S: {S}", "S", s);
378             return ipmi::responseParmOutOfRange();
379         }
380 
381         // valid input
382         if (s == static_cast<uint8_t>(acpi_state::PowerState::noChange))
383         {
384             lg2::debug("No change for device power state");
385         }
386         else
387         {
388             auto found = std::find_if(
389                 acpi_state::dbusToIPMI.begin(), acpi_state::dbusToIPMI.end(),
390                 [&s](const auto& iter) {
391                     return (static_cast<uint8_t>(iter.second) == s);
392                 });
393 
394             value = found->first;
395 
396             try
397             {
398                 auto acpiObject =
399                     ipmi::getDbusObject(bus, acpi_state::acpiInterface);
400                 ipmi::setDbusProperty(bus, acpiObject.second, acpiObject.first,
401                                       acpi_state::acpiInterface,
402                                       acpi_state::devACPIProp,
403                                       convertForMessage(value));
404             }
405             catch (const InternalFailure& e)
406             {
407                 lg2::error("Failed in set ACPI device property: {ERROR}",
408                            "ERROR", e);
409                 return ipmi::responseUnspecifiedError();
410             }
411         }
412     }
413     else
414     {
415         lg2::debug("Do not change device power state");
416     }
417     return ipmi::responseSuccess();
418 }
419 
420 /**
421  *  @brief implements the get ACPI power state command
422  *
423  *  @return IPMI completion code plus response data on success.
424  *   -  ACPI system power state
425  *   -  ACPI device power state
426  **/
427 ipmi::RspType<uint8_t, // acpiSystemPowerState
428               uint8_t  // acpiDevicePowerState
429               >
430     ipmiGetAcpiPowerState()
431 {
432     uint8_t sysAcpiState;
433     uint8_t devAcpiState;
434 
435     sdbusplus::bus_t bus{ipmid_get_sd_bus_connection()};
436 
437     try
438     {
439         auto acpiObject = ipmi::getDbusObject(bus, acpi_state::acpiInterface);
440 
441         auto sysACPIVal = ipmi::getDbusProperty(
442             bus, acpiObject.second, acpiObject.first, acpi_state::acpiInterface,
443             acpi_state::sysACPIProp);
444         auto sysACPI = acpi_state::ACPIPowerState::convertACPIFromString(
445             std::get<std::string>(sysACPIVal));
446         sysAcpiState = static_cast<uint8_t>(acpi_state::dbusToIPMI.at(sysACPI));
447 
448         auto devACPIVal = ipmi::getDbusProperty(
449             bus, acpiObject.second, acpiObject.first, acpi_state::acpiInterface,
450             acpi_state::devACPIProp);
451         auto devACPI = acpi_state::ACPIPowerState::convertACPIFromString(
452             std::get<std::string>(devACPIVal));
453         devAcpiState = static_cast<uint8_t>(acpi_state::dbusToIPMI.at(devACPI));
454     }
455     catch (const InternalFailure& e)
456     {
457         return ipmi::responseUnspecifiedError();
458     }
459 
460     return ipmi::responseSuccess(sysAcpiState, devAcpiState);
461 }
462 
463 typedef struct
464 {
465     char major;
466     char minor;
467     uint8_t aux[4];
468 } Revision;
469 
470 /* Use regular expression searching matched pattern X.Y, and convert it to  */
471 /* Major (X) and Minor (Y) version.                                         */
472 /* Example:                                                                 */
473 /* version = 2.14.0-dev                                                     */
474 /*           ^ ^                                                            */
475 /*           | |---------------- Minor                                      */
476 /*           |------------------ Major                                      */
477 /*                                                                          */
478 /* Default regex string only tries to match Major and Minor version.        */
479 /*                                                                          */
480 /* To match more firmware version info, platforms need to define it own     */
481 /* regex string to match more strings, and assign correct mapping index in  */
482 /* matches array.                                                           */
483 /*                                                                          */
484 /* matches[0]: matched index for major ver                                  */
485 /* matches[1]: matched index for minor ver                                  */
486 /* matches[2]: matched index for aux[0] (set 0 to skip)                     */
487 /* matches[3]: matched index for aux[1] (set 0 to skip)                     */
488 /* matches[4]: matched index for aux[2] (set 0 to skip)                     */
489 /* matches[5]: matched index for aux[3] (set 0 to skip)                     */
490 /* Example:                                                                 */
491 /* regex = "([\d]+).([\d]+).([\d]+)-dev-([\d]+)-g([0-9a-fA-F]{2})           */
492 /*          ([0-9a-fA-F]{2})([0-9a-fA-F]{2})([0-9a-fA-F]{2})"               */
493 /* matches = {1,2,5,6,7,8}                                                  */
494 /* version = 2.14.0-dev-750-g37a7c5ad1-dirty                                */
495 /*           ^ ^  ^     ^    ^ ^ ^ ^                                        */
496 /*           | |  |     |    | | | |                                        */
497 /*           | |  |     |    | | | |-- Aux byte 3 (0xAD), index 8           */
498 /*           | |  |     |    | | |---- Aux byte 2 (0xC5), index 7           */
499 /*           | |  |     |    | |------ Aux byte 1 (0xA7), index 6           */
500 /*           | |  |     |    |-------- Aux byte 0 (0x37), index 5           */
501 /*           | |  |     |------------- Not used, index 4                    */
502 /*           | |  |------------------- Not used, index 3                    */
503 /*           | |---------------------- Minor (14), index 2                  */
504 /*           |------------------------ Major (2), index 1                   */
505 int convertVersion(std::string s, Revision& rev)
506 {
507     static const std::vector<size_t> matches = {
508         MAJOR_MATCH_INDEX, MINOR_MATCH_INDEX, AUX_0_MATCH_INDEX,
509         AUX_1_MATCH_INDEX, AUX_2_MATCH_INDEX, AUX_3_MATCH_INDEX};
510     std::regex fw_regex(FW_VER_REGEX);
511     std::smatch m;
512     Revision r = {0};
513     size_t val;
514 
515     if (std::regex_search(s, m, fw_regex))
516     {
517         if (m.size() < *std::max_element(matches.begin(), matches.end()))
518         { // max index higher than match count
519             return -1;
520         }
521 
522         // convert major
523         {
524             std::string_view str = m[matches[0]].str();
525             auto [ptr, ec]{std::from_chars(str.begin(), str.end(), val)};
526             if (ec != std::errc() || ptr != str.begin() + str.size())
527             { // failed to convert major string
528                 return -1;
529             }
530 
531             if (val >= 2000)
532             { // For the platforms use year as major version, it would expect to
533               // have major version between 0 - 99. If the major version is
534               // greater than or equal to 2000, it is treated as a year and
535               // converted to 0 - 99.
536                 r.major = val % 100;
537             }
538             else
539             {
540                 r.major = val & 0x7F;
541             }
542         }
543 
544         // convert minor
545         {
546             std::string_view str = m[matches[1]].str();
547             auto [ptr, ec]{std::from_chars(str.begin(), str.end(), val)};
548             if (ec != std::errc() || ptr != str.begin() + str.size())
549             { // failed to convert minor string
550                 return -1;
551             }
552             r.minor = val & 0xFF;
553         }
554 
555         // convert aux bytes
556         {
557             size_t i;
558             for (i = 0; i < 4; i++)
559             {
560                 if (matches[i + 2] == 0)
561                 {
562                     continue;
563                 }
564 
565                 std::string_view str = m[matches[i + 2]].str();
566                 auto [ptr,
567                       ec]{std::from_chars(str.begin(), str.end(), val, 16)};
568                 if (ec != std::errc() || ptr != str.begin() + str.size())
569                 { // failed to convert aux byte string
570                     break;
571                 }
572 
573                 r.aux[i] = val & 0xFF;
574             }
575 
576             if (i != 4)
577             { // something wrong durign converting aux bytes
578                 return -1;
579             }
580         }
581 
582         // all matched
583         rev = r;
584         return 0;
585     }
586 
587     return -1;
588 }
589 
590 /* @brief: Implement the Get Device ID IPMI command per the IPMI spec
591  *  @param[in] ctx - shared_ptr to an IPMI context struct
592  *
593  *  @returns IPMI completion code plus response data
594  *   - Device ID (manufacturer defined)
595  *   - Device revision[4 bits]; reserved[3 bits]; SDR support[1 bit]
596  *   - FW revision major[7 bits] (binary encoded); available[1 bit]
597  *   - FW Revision minor (BCD encoded)
598  *   - IPMI version (0x02 for IPMI 2.0)
599  *   - device support (bitfield of supported options)
600  *   - MFG IANA ID (3 bytes)
601  *   - product ID (2 bytes)
602  *   - AUX info (4 bytes)
603  */
604 ipmi::RspType<uint8_t,  // Device ID
605               uint8_t,  // Device Revision
606               uint8_t,  // Firmware Revision Major
607               uint8_t,  // Firmware Revision minor
608               uint8_t,  // IPMI version
609               uint8_t,  // Additional device support
610               uint24_t, // MFG ID
611               uint16_t, // Product ID
612               uint32_t  // AUX info
613               >
614     ipmiAppGetDeviceId([[maybe_unused]] ipmi::Context::ptr ctx)
615 {
616     static struct
617     {
618         uint8_t id;
619         uint8_t revision;
620         uint8_t fw[2];
621         uint8_t ipmiVer;
622         uint8_t addnDevSupport;
623         uint24_t manufId;
624         uint16_t prodId;
625         uint32_t aux;
626     } devId;
627     static bool dev_id_initialized = false;
628     static bool defaultActivationSetting = true;
629     const char* filename = "/usr/share/ipmi-providers/dev_id.json";
630     constexpr auto ipmiDevIdStateShift = 7;
631     constexpr auto ipmiDevIdFw1Mask = ~(1 << ipmiDevIdStateShift);
632 
633 #ifdef GET_DBUS_ACTIVE_SOFTWARE
634     static bool haveBMCVersion = false;
635     if (!haveBMCVersion || !dev_id_initialized)
636     {
637         int r = -1;
638         Revision rev = {0, 0, 0, 0};
639         try
640         {
641             auto version = getActiveSoftwareVersionInfo(ctx);
642             r = convertVersion(version, rev);
643         }
644         catch (const std::exception& e)
645         {
646             lg2::error("error message: {ERROR}", "ERROR", e);
647         }
648 
649         if (r >= 0)
650         {
651             // bit7 identifies if the device is available
652             // 0=normal operation
653             // 1=device firmware, SDR update,
654             // or self-initialization in progress.
655             // The availability may change in run time, so mask here
656             // and initialize later.
657             devId.fw[0] = rev.major & ipmiDevIdFw1Mask;
658 
659             rev.minor = (rev.minor > 99 ? 99 : rev.minor);
660             devId.fw[1] = rev.minor % 10 + (rev.minor / 10) * 16;
661             std::memcpy(&devId.aux, rev.aux, sizeof(rev.aux));
662             haveBMCVersion = true;
663         }
664     }
665 #endif
666     if (!dev_id_initialized)
667     {
668         // IPMI Spec version 2.0
669         devId.ipmiVer = 2;
670 
671         std::ifstream devIdFile(filename);
672         if (devIdFile.is_open())
673         {
674             auto data = nlohmann::json::parse(devIdFile, nullptr, false);
675             if (!data.is_discarded())
676             {
677                 devId.id = data.value("id", 0);
678                 devId.revision = data.value("revision", 0);
679                 devId.addnDevSupport = data.value("addn_dev_support", 0);
680                 devId.manufId = data.value("manuf_id", 0);
681                 devId.prodId = data.value("prod_id", 0);
682 #ifdef GET_DBUS_ACTIVE_SOFTWARE
683                 if (!(AUX_0_MATCH_INDEX || AUX_1_MATCH_INDEX ||
684                       AUX_2_MATCH_INDEX || AUX_3_MATCH_INDEX))
685 #endif
686                 {
687                     devId.aux = data.value("aux", 0);
688                 }
689 
690                 if (data.contains("firmware_revision"))
691                 {
692                     const auto& firmwareRevision = data.at("firmware_revision");
693                     if (firmwareRevision.contains("major"))
694                     {
695                         firmwareRevision.at("major").get_to(devId.fw[0]);
696                     }
697                     if (firmwareRevision.contains("minor"))
698                     {
699                         firmwareRevision.at("minor").get_to(devId.fw[1]);
700                     }
701                 }
702 
703                 // Set the availablitity of the BMC.
704                 defaultActivationSetting = data.value("availability", true);
705 
706                 // Don't read the file every time if successful
707                 dev_id_initialized = true;
708             }
709             else
710             {
711                 lg2::error("Device ID JSON parser failure");
712                 return ipmi::responseUnspecifiedError();
713             }
714         }
715         else
716         {
717             lg2::error("Device ID file not found");
718             return ipmi::responseUnspecifiedError();
719         }
720     }
721 
722     // Set availability to the actual current BMC state
723     devId.fw[0] &= ipmiDevIdFw1Mask;
724     if (!getCurrentBmcStateWithFallback(defaultActivationSetting))
725     {
726         devId.fw[0] |= (1 << ipmiDevIdStateShift);
727     }
728 
729     return ipmi::responseSuccess(
730         devId.id, devId.revision, devId.fw[0], devId.fw[1], devId.ipmiVer,
731         devId.addnDevSupport, devId.manufId, devId.prodId, devId.aux);
732 }
733 
734 auto ipmiAppGetSelfTestResults() -> ipmi::RspType<uint8_t, uint8_t>
735 {
736     // Byte 2:
737     //  55h - No error.
738     //  56h - Self Test function not implemented in this controller.
739     //  57h - Corrupted or inaccesssible data or devices.
740     //  58h - Fatal hardware error.
741     //  FFh - reserved.
742     //  all other: Device-specific 'internal failure'.
743     //  Byte 3:
744     //      For byte 2 = 55h, 56h, FFh:     00h
745     //      For byte 2 = 58h, all other:    Device-specific
746     //      For byte 2 = 57h:   self-test error bitfield.
747     //      Note: returning 57h does not imply that all test were run.
748     //      [7] 1b = Cannot access SEL device.
749     //      [6] 1b = Cannot access SDR Repository.
750     //      [5] 1b = Cannot access BMC FRU device.
751     //      [4] 1b = IPMB signal lines do not respond.
752     //      [3] 1b = SDR Repository empty.
753     //      [2] 1b = Internal Use Area of BMC FRU corrupted.
754     //      [1] 1b = controller update 'boot block' firmware corrupted.
755     //      [0] 1b = controller operational firmware corrupted.
756     constexpr uint8_t notImplemented = 0x56;
757     constexpr uint8_t zero = 0;
758     return ipmi::responseSuccess(notImplemented, zero);
759 }
760 
761 static constexpr size_t uuidBinaryLength = 16;
762 static std::array<uint8_t, uuidBinaryLength> rfc4122ToIpmi(std::string rfc4122)
763 {
764     using Argument = xyz::openbmc_project::common::InvalidArgument;
765     // UUID is in RFC4122 format. Ex: 61a39523-78f2-11e5-9862-e6402cfc3223
766     // Per IPMI Spec 2.0 need to convert to 16 hex bytes and reverse the byte
767     // order
768     // Ex: 0x2332fc2c40e66298e511f2782395a361
769     constexpr size_t uuidHexLength = (2 * uuidBinaryLength);
770     constexpr size_t uuidRfc4122Length = (uuidHexLength + 4);
771     std::array<uint8_t, uuidBinaryLength> uuid;
772     if (rfc4122.size() == uuidRfc4122Length)
773     {
774         rfc4122.erase(std::remove(rfc4122.begin(), rfc4122.end(), '-'),
775                       rfc4122.end());
776     }
777     if (rfc4122.size() != uuidHexLength)
778     {
779         elog<InvalidArgument>(Argument::ARGUMENT_NAME("rfc4122"),
780                               Argument::ARGUMENT_VALUE(rfc4122.c_str()));
781     }
782     for (size_t ind = 0; ind < uuidHexLength; ind += 2)
783     {
784         char v[3];
785         v[0] = rfc4122[ind];
786         v[1] = rfc4122[ind + 1];
787         v[2] = 0;
788         size_t err;
789         long b;
790         try
791         {
792             b = std::stoul(v, &err, 16);
793         }
794         catch (const std::exception& e)
795         {
796             elog<InvalidArgument>(Argument::ARGUMENT_NAME("rfc4122"),
797                                   Argument::ARGUMENT_VALUE(rfc4122.c_str()));
798         }
799         // check that exactly two ascii bytes were converted
800         if (err != 2)
801         {
802             elog<InvalidArgument>(Argument::ARGUMENT_NAME("rfc4122"),
803                                   Argument::ARGUMENT_VALUE(rfc4122.c_str()));
804         }
805         uuid[uuidBinaryLength - (ind / 2) - 1] = static_cast<uint8_t>(b);
806     }
807     return uuid;
808 }
809 
810 auto ipmiAppGetDeviceGuid()
811     -> ipmi::RspType<std::array<uint8_t, uuidBinaryLength>>
812 {
813     // return a fixed GUID based on /etc/machine-id
814     // This should match the /redfish/v1/Managers/bmc's UUID data
815 
816     // machine specific application ID (for BMC ID)
817     // generated by systemd-id128 -p new as per man page
818     static constexpr sd_id128_t bmcUuidAppId = SD_ID128_MAKE(
819         e0, e1, 73, 76, 64, 61, 47, da, a5, 0c, d0, cc, 64, 12, 45, 78);
820 
821     sd_id128_t bmcUuid;
822     // create the UUID from /etc/machine-id via the systemd API
823     sd_id128_get_machine_app_specific(bmcUuidAppId, &bmcUuid);
824 
825     char bmcUuidCstr[SD_ID128_STRING_MAX];
826     std::string systemUuid = sd_id128_to_string(bmcUuid, bmcUuidCstr);
827 
828     std::array<uint8_t, uuidBinaryLength> uuid = rfc4122ToIpmi(systemUuid);
829     return ipmi::responseSuccess(uuid);
830 }
831 
832 auto ipmiAppGetBtCapabilities()
833     -> ipmi::RspType<uint8_t, uint8_t, uint8_t, uint8_t, uint8_t>
834 {
835     // Per IPMI 2.0 spec, the input and output buffer size must be the max
836     // buffer size minus one byte to allocate space for the length byte.
837     constexpr uint8_t nrOutstanding = 0x01;
838     constexpr uint8_t inputBufferSize = MAX_IPMI_BUFFER - 1;
839     constexpr uint8_t outputBufferSize = MAX_IPMI_BUFFER - 1;
840     constexpr uint8_t transactionTime = 0x0A;
841     constexpr uint8_t nrRetries = 0x01;
842 
843     return ipmi::responseSuccess(nrOutstanding, inputBufferSize,
844                                  outputBufferSize, transactionTime, nrRetries);
845 }
846 
847 auto ipmiAppGetSystemGuid(ipmi::Context::ptr& ctx)
848     -> ipmi::RspType<std::array<uint8_t, 16>>
849 {
850     static constexpr auto uuidInterface = "xyz.openbmc_project.Common.UUID";
851     static constexpr auto uuidProperty = "UUID";
852 
853     // Get the Inventory object implementing BMC interface
854     ipmi::DbusObjectInfo objectInfo{};
855     boost::system::error_code ec =
856         ipmi::getDbusObject(ctx, uuidInterface, objectInfo);
857     if (ec.value())
858     {
859         lg2::error("Failed to locate System UUID object, "
860                    "interface: {INTERFACE}, error: {ERROR}",
861                    "INTERFACE", uuidInterface, "ERROR", ec.message());
862     }
863 
864     // Read UUID property value from bmcObject
865     // UUID is in RFC4122 format Ex: 61a39523-78f2-11e5-9862-e6402cfc3223
866     std::string rfc4122Uuid{};
867     ec = ipmi::getDbusProperty(ctx, objectInfo.second, objectInfo.first,
868                                uuidInterface, uuidProperty, rfc4122Uuid);
869     if (ec.value())
870     {
871         lg2::error("Failed to read System UUID property, "
872                    "interface: {INTERFACE}, property: {PROPERTY}, "
873                    "error: {ERROR}",
874                    "INTERFACE", uuidInterface, "PROPERTY", uuidProperty,
875                    "ERROR", ec.message());
876         return ipmi::responseUnspecifiedError();
877     }
878     std::array<uint8_t, 16> uuid;
879     try
880     {
881         // convert to IPMI format
882         uuid = rfc4122ToIpmi(rfc4122Uuid);
883     }
884     catch (const InvalidArgument& e)
885     {
886         lg2::error("Failed in parsing BMC UUID property, "
887                    "interface: {INTERFACE}, property: {PROPERTY}, "
888                    "value: {VALUE}, error: {ERROR}",
889                    "INTERFACE", uuidInterface, "PROPERTY", uuidProperty,
890                    "VALUE", rfc4122Uuid, "ERROR", e);
891         return ipmi::responseUnspecifiedError();
892     }
893     return ipmi::responseSuccess(uuid);
894 }
895 
896 /**
897  * @brief set the session state as teardown
898  *
899  * This function is to set the session state to tear down in progress if the
900  * state is active.
901  *
902  * @param[in] busp - Dbus obj
903  * @param[in] service - service name
904  * @param[in] obj - object path
905  *
906  * @return success completion code if it sets the session state to
907  * tearDownInProgress else return the corresponding error completion code.
908  **/
909 uint8_t setSessionState(std::shared_ptr<sdbusplus::asio::connection>& busp,
910                         const std::string& service, const std::string& obj)
911 {
912     try
913     {
914         uint8_t sessionState = std::get<uint8_t>(ipmi::getDbusProperty(
915             *busp, service, obj, session::sessionIntf, "State"));
916 
917         if (sessionState == static_cast<uint8_t>(session::State::active))
918         {
919             ipmi::setDbusProperty(
920                 *busp, service, obj, session::sessionIntf, "State",
921                 static_cast<uint8_t>(session::State::tearDownInProgress));
922             return ipmi::ccSuccess;
923         }
924     }
925     catch (const std::exception& e)
926     {
927         lg2::error("Failed in getting session state property, "
928                    "service: {SERVICE}, object path: {OBJECT_PATH}, "
929                    "interface: {INTERFACE}, error: {ERROR}",
930                    "SERVICE", service, "OBJECT_PATH", obj, "INTERFACE",
931                    session::sessionIntf, "ERROR", e);
932         return ipmi::ccUnspecifiedError;
933     }
934 
935     return ipmi::ccInvalidFieldRequest;
936 }
937 
938 ipmi::RspType<> ipmiAppCloseSession(uint32_t reqSessionId,
939                                     std::optional<uint8_t> requestSessionHandle)
940 {
941     auto busp = getSdBus();
942     uint8_t reqSessionHandle =
943         requestSessionHandle.value_or(session::defaultSessionHandle);
944 
945     if (reqSessionId == session::sessionZero &&
946         reqSessionHandle == session::defaultSessionHandle)
947     {
948         return ipmi::response(session::ccInvalidSessionId);
949     }
950 
951     if (reqSessionId == session::sessionZero &&
952         reqSessionHandle == session::invalidSessionHandle)
953     {
954         return ipmi::response(session::ccInvalidSessionHandle);
955     }
956 
957     if (reqSessionId != session::sessionZero &&
958         reqSessionHandle != session::defaultSessionHandle)
959     {
960         return ipmi::response(ipmi::ccInvalidFieldRequest);
961     }
962 
963     try
964     {
965         ipmi::ObjectTree objectTree = ipmi::getAllDbusObjects(
966             *busp, session::sessionManagerRootPath, session::sessionIntf);
967 
968         for (auto& objectTreeItr : objectTree)
969         {
970             const std::string obj = objectTreeItr.first;
971 
972             if (isSessionObjectMatched(obj, reqSessionId, reqSessionHandle))
973             {
974                 auto& serviceMap = objectTreeItr.second;
975 
976                 // Session id and session handle are unique for each session.
977                 // Session id and handler are retrived from the object path and
978                 // object path will be unique for each session. Checking if
979                 // multiple objects exist with same object path under multiple
980                 // services.
981                 if (serviceMap.size() != 1)
982                 {
983                     return ipmi::responseUnspecifiedError();
984                 }
985 
986                 auto itr = serviceMap.begin();
987                 const std::string service = itr->first;
988                 return ipmi::response(setSessionState(busp, service, obj));
989             }
990         }
991     }
992     catch (const sdbusplus::exception_t& e)
993     {
994         lg2::error("Failed to fetch object from dbus, "
995                    "interface: {INTERFACE}, error: {ERROR}",
996                    "INTERFACE", session::sessionIntf, "ERROR", e);
997         return ipmi::responseUnspecifiedError();
998     }
999 
1000     return ipmi::responseInvalidFieldRequest();
1001 }
1002 
1003 uint8_t getTotalSessionCount()
1004 {
1005     uint8_t count = 0, ch = 0;
1006 
1007     while (ch < ipmi::maxIpmiChannels &&
1008            count < session::maxNetworkInstanceSupported)
1009     {
1010         ipmi::ChannelInfo chInfo{};
1011         ipmi::getChannelInfo(ch, chInfo);
1012         if (static_cast<ipmi::EChannelMediumType>(chInfo.mediumType) ==
1013             ipmi::EChannelMediumType::lan8032)
1014         {
1015             count++;
1016         }
1017         ch++;
1018     }
1019     return count * session::maxSessionCountPerChannel;
1020 }
1021 
1022 /**
1023  * @brief get session info request data.
1024  *
1025  * This function validates the request data and retrive request session id,
1026  * session handle.
1027  *
1028  * @param[in] ctx - context of current session.
1029  * @param[in] sessionIndex - request session index
1030  * @param[in] payload - input payload
1031  * @param[in] reqSessionId - unpacked session Id will be asigned
1032  * @param[in] reqSessionHandle - unpacked session handle will be asigned
1033  *
1034  * @return success completion code if request data is valid
1035  * else return the correcponding error completion code.
1036  **/
1037 uint8_t getSessionInfoRequestData(
1038     const ipmi::Context::ptr ctx, const uint8_t sessionIndex,
1039     ipmi::message::Payload& payload, uint32_t& reqSessionId,
1040     uint8_t& reqSessionHandle)
1041 {
1042     if ((sessionIndex > session::maxSessionCountPerChannel) &&
1043         (sessionIndex < session::searchSessionByHandle))
1044     {
1045         return ipmi::ccInvalidFieldRequest;
1046     }
1047 
1048     switch (sessionIndex)
1049     {
1050         case session::searchCurrentSession:
1051 
1052             ipmi::ChannelInfo chInfo;
1053             ipmi::getChannelInfo(ctx->channel, chInfo);
1054 
1055             if (static_cast<ipmi::EChannelMediumType>(chInfo.mediumType) !=
1056                 ipmi::EChannelMediumType::lan8032)
1057             {
1058                 return ipmi::ccInvalidFieldRequest;
1059             }
1060 
1061             if (!payload.fullyUnpacked())
1062             {
1063                 return ipmi::ccReqDataLenInvalid;
1064             }
1065             // Check if current sessionId is 0, sessionId 0 is reserved.
1066             if (ctx->sessionId == session::sessionZero)
1067             {
1068                 return session::ccInvalidSessionId;
1069             }
1070             reqSessionId = ctx->sessionId;
1071             break;
1072 
1073         case session::searchSessionByHandle:
1074 
1075             if ((payload.unpack(reqSessionHandle)) ||
1076                 (!payload.fullyUnpacked()))
1077             {
1078                 return ipmi::ccReqDataLenInvalid;
1079             }
1080 
1081             if ((reqSessionHandle == session::sessionZero) ||
1082                 ((reqSessionHandle & session::multiIntfaceSessionHandleMask) >
1083                  session::maxSessionCountPerChannel))
1084             {
1085                 return session::ccInvalidSessionHandle;
1086             }
1087             break;
1088 
1089         case session::searchSessionById:
1090 
1091             if ((payload.unpack(reqSessionId)) || (!payload.fullyUnpacked()))
1092             {
1093                 return ipmi::ccReqDataLenInvalid;
1094             }
1095 
1096             if (reqSessionId == session::sessionZero)
1097             {
1098                 return session::ccInvalidSessionId;
1099             }
1100             break;
1101 
1102         default:
1103             if (!payload.fullyUnpacked())
1104             {
1105                 return ipmi::ccReqDataLenInvalid;
1106             }
1107             break;
1108     }
1109     return ipmi::ccSuccess;
1110 }
1111 
1112 uint8_t getSessionState(ipmi::Context::ptr ctx, const std::string& service,
1113                         const std::string& objPath, uint8_t& sessionState)
1114 {
1115     boost::system::error_code ec = ipmi::getDbusProperty(
1116         ctx, service, objPath, session::sessionIntf, "State", sessionState);
1117     if (ec)
1118     {
1119         lg2::error("Failed to fetch state property, service: {SERVICE}, "
1120                    "object path: {OBJECTPATH}, interface: {INTERFACE}, "
1121                    "error: {ERROR}",
1122                    "SERVICE", service, "OBJECTPATH", objPath, "INTERFACE",
1123                    session::sessionIntf, "ERROR", ec.message());
1124         return ipmi::ccUnspecifiedError;
1125     }
1126     return ipmi::ccSuccess;
1127 }
1128 
1129 static constexpr uint8_t macAddrLen = 6;
1130 /** Alias SessionDetails - contain the optional information about an
1131  *        RMCP+ session.
1132  *
1133  *  @param userID - uint6_t session user ID (0-63)
1134  *  @param reserved - uint2_t reserved
1135  *  @param privilege - uint4_t session privilege (0-5)
1136  *  @param reserved - uint4_t reserved
1137  *  @param channel - uint4_t session channel number
1138  *  @param protocol - uint4_t session protocol
1139  *  @param remoteIP - uint32_t remote IP address
1140  *  @param macAddr - std::array<uint8_t, 6> mac address
1141  *  @param port - uint16_t remote port
1142  */
1143 using SessionDetails =
1144     std::tuple<uint2_t, uint6_t, uint4_t, uint4_t, uint4_t, uint4_t, uint32_t,
1145                std::array<uint8_t, macAddrLen>, uint16_t>;
1146 
1147 /** @brief get session details for a given session
1148  *
1149  *  @param[in] ctx - ipmi::Context pointer for accessing D-Bus
1150  *  @param[in] service - D-Bus service name to fetch details from
1151  *  @param[in] objPath - D-Bus object path for session
1152  *  @param[out] sessionHandle - return session handle for session
1153  *  @param[out] sessionState - return session state for session
1154  *  @param[out] details - return a SessionDetails tuple containing other
1155  *                        session info
1156  *  @return - ipmi::Cc success or error code
1157  */
1158 ipmi::Cc getSessionDetails(ipmi::Context::ptr ctx, const std::string& service,
1159                            const std::string& objPath, uint8_t& sessionHandle,
1160                            uint8_t& sessionState, SessionDetails& details)
1161 {
1162     ipmi::PropertyMap sessionProps;
1163     boost::system::error_code ec = ipmi::getAllDbusProperties(
1164         ctx, service, objPath, session::sessionIntf, sessionProps);
1165 
1166     if (ec)
1167     {
1168         lg2::error("Failed to fetch state property, service: {SERVICE}, "
1169                    "object path: {OBJECTPATH}, interface: {INTERFACE}, "
1170                    "error: {ERROR}",
1171                    "SERVICE", service, "OBJECTPATH", objPath, "INTERFACE",
1172                    session::sessionIntf, "ERROR", ec.message());
1173         return ipmi::ccUnspecifiedError;
1174     }
1175 
1176     sessionState = ipmi::mappedVariant<uint8_t>(
1177         sessionProps, "State", static_cast<uint8_t>(session::State::inactive));
1178     if (sessionState == static_cast<uint8_t>(session::State::active))
1179     {
1180         sessionHandle =
1181             ipmi::mappedVariant<uint8_t>(sessionProps, "SessionHandle", 0);
1182         std::get<0>(details) =
1183             ipmi::mappedVariant<uint8_t>(sessionProps, "UserID", 0xff);
1184         // std::get<1>(details) = 0; // (default constructed to 0)
1185         std::get<2>(details) =
1186             ipmi::mappedVariant<uint8_t>(sessionProps, "CurrentPrivilege", 0);
1187         // std::get<3>(details) = 0; // (default constructed to 0)
1188         std::get<4>(details) =
1189             ipmi::mappedVariant<uint8_t>(sessionProps, "ChannelNum", 0xff);
1190         constexpr uint4_t rmcpPlusProtocol = 1;
1191         std::get<5>(details) = rmcpPlusProtocol;
1192         std::get<6>(details) =
1193             ipmi::mappedVariant<uint32_t>(sessionProps, "RemoteIPAddr", 0);
1194         // std::get<7>(details) = {{0}}; // default constructed to all 0
1195         std::get<8>(details) =
1196             ipmi::mappedVariant<uint16_t>(sessionProps, "RemotePort", 0);
1197     }
1198 
1199     return ipmi::ccSuccess;
1200 }
1201 
1202 ipmi::RspType<uint8_t, // session handle,
1203               uint8_t, // total session count
1204               uint8_t, // active session count
1205               std::optional<SessionDetails>>
1206     ipmiAppGetSessionInfo(ipmi::Context::ptr ctx, uint8_t sessionIndex,
1207                           ipmi::message::Payload& payload)
1208 {
1209     uint32_t reqSessionId = 0;
1210     uint8_t reqSessionHandle = session::defaultSessionHandle;
1211     // initializing state to 0xff as 0 represents state as inactive.
1212     uint8_t state = 0xFF;
1213 
1214     uint8_t completionCode = getSessionInfoRequestData(
1215         ctx, sessionIndex, payload, reqSessionId, reqSessionHandle);
1216 
1217     if (completionCode)
1218     {
1219         return ipmi::response(completionCode);
1220     }
1221     ipmi::ObjectTree objectTree;
1222     boost::system::error_code ec = ipmi::getAllDbusObjects(
1223         ctx, session::sessionManagerRootPath, session::sessionIntf, objectTree);
1224     if (ec)
1225     {
1226         lg2::error("Failed to fetch object from dbus, "
1227                    "interface: {INTERFACE}, error: {ERROR}",
1228                    "INTERFACE", session::sessionIntf, "ERROR", ec.message());
1229         return ipmi::responseUnspecifiedError();
1230     }
1231 
1232     uint8_t totalSessionCount = getTotalSessionCount();
1233     uint8_t activeSessionCount = 0;
1234     uint8_t sessionHandle = session::defaultSessionHandle;
1235     uint8_t activeSessionHandle = 0;
1236     std::optional<SessionDetails> maybeDetails;
1237     uint8_t index = 0;
1238     for (auto& objectTreeItr : objectTree)
1239     {
1240         uint32_t sessionId = 0;
1241         std::string objectPath = objectTreeItr.first;
1242 
1243         if (!parseCloseSessionInputPayload(objectPath, sessionId,
1244                                            sessionHandle))
1245         {
1246             continue;
1247         }
1248         index++;
1249         auto& serviceMap = objectTreeItr.second;
1250         auto itr = serviceMap.begin();
1251 
1252         if (serviceMap.size() != 1)
1253         {
1254             return ipmi::responseUnspecifiedError();
1255         }
1256 
1257         std::string service = itr->first;
1258         uint8_t sessionState = 0;
1259         completionCode =
1260             getSessionState(ctx, service, objectPath, sessionState);
1261         if (completionCode)
1262         {
1263             return ipmi::response(completionCode);
1264         }
1265 
1266         if (sessionState == static_cast<uint8_t>(session::State::active))
1267         {
1268             activeSessionCount++;
1269         }
1270 
1271         if (index == sessionIndex || reqSessionId == sessionId ||
1272             reqSessionHandle == sessionHandle)
1273         {
1274             SessionDetails details{};
1275             completionCode = getSessionDetails(ctx, service, objectPath,
1276                                                sessionHandle, state, details);
1277 
1278             if (completionCode)
1279             {
1280                 return ipmi::response(completionCode);
1281             }
1282             activeSessionHandle = sessionHandle;
1283             maybeDetails = std::move(details);
1284         }
1285     }
1286 
1287     if (state == static_cast<uint8_t>(session::State::active) ||
1288         state == static_cast<uint8_t>(session::State::tearDownInProgress))
1289     {
1290         return ipmi::responseSuccess(activeSessionHandle, totalSessionCount,
1291                                      activeSessionCount, maybeDetails);
1292     }
1293 
1294     return ipmi::responseInvalidFieldRequest();
1295 }
1296 
1297 static std::unique_ptr<SysInfoParamStore> sysInfoParamStore;
1298 
1299 static std::string sysInfoReadSystemName()
1300 {
1301     // Use the BMC hostname as the "System Name."
1302     char hostname[HOST_NAME_MAX + 1] = {};
1303     if (gethostname(hostname, HOST_NAME_MAX) != 0)
1304     {
1305         perror("System info parameter: system name");
1306     }
1307     return hostname;
1308 }
1309 
1310 static constexpr uint8_t paramRevision = 0x11;
1311 static constexpr size_t configParameterLength = 16;
1312 
1313 static constexpr size_t smallChunkSize = 14;
1314 static constexpr size_t fullChunkSize = 16;
1315 static constexpr uint8_t progressMask = 0x3;
1316 static constexpr uint8_t maxValidEncodingData = 0x02;
1317 
1318 static constexpr uint8_t setComplete = 0x0;
1319 static constexpr uint8_t setInProgress = 0x1;
1320 static constexpr uint8_t commitWrite = 0x2;
1321 static uint8_t transferStatus = setComplete;
1322 
1323 static constexpr uint8_t configDataOverhead = 2;
1324 
1325 // For EFI based system, 256 bytes is recommended.
1326 static constexpr size_t maxBytesPerParameter = 256;
1327 
1328 namespace ipmi
1329 {
1330 constexpr Cc ccParmNotSupported = 0x80;
1331 constexpr Cc ccSetInProgressActive = 0x81;
1332 constexpr Cc ccSystemInfoParameterSetReadOnly = 0x82;
1333 
1334 static inline auto responseParmNotSupported()
1335 {
1336     return response(ccParmNotSupported);
1337 }
1338 static inline auto responseSetInProgressActive()
1339 {
1340     return response(ccSetInProgressActive);
1341 }
1342 static inline auto responseSystemInfoParameterSetReadOnly()
1343 {
1344     return response(ccSystemInfoParameterSetReadOnly);
1345 }
1346 } // namespace ipmi
1347 
1348 ipmi::RspType<uint8_t,                // Parameter revision
1349               std::optional<uint8_t>, // data1 / setSelector / ProgressStatus
1350               std::optional<std::vector<uint8_t>>> // data2-17
1351     ipmiAppGetSystemInfo(uint7_t reserved, bool getRevision,
1352                          uint8_t paramSelector, uint8_t setSelector,
1353                          uint8_t BlockSelector)
1354 {
1355     if (reserved || (paramSelector >= invalidParamSelectorStart &&
1356                      paramSelector <= invalidParamSelectorEnd))
1357     {
1358         return ipmi::responseInvalidFieldRequest();
1359     }
1360     if (paramSelector >= oemCmdStart)
1361     {
1362         return ipmi::responseParmNotSupported();
1363     }
1364     if (getRevision)
1365     {
1366         return ipmi::responseSuccess(paramRevision, std::nullopt, std::nullopt);
1367     }
1368 
1369     if (paramSelector == 0)
1370     {
1371         return ipmi::responseSuccess(paramRevision, transferStatus,
1372                                      std::nullopt);
1373     }
1374 
1375     if (BlockSelector != 0) // 00h if parameter does not require a block number
1376     {
1377         return ipmi::responseParmNotSupported();
1378     }
1379 
1380     if (sysInfoParamStore == nullptr)
1381     {
1382         sysInfoParamStore = std::make_unique<SysInfoParamStore>();
1383         sysInfoParamStore->update(IPMI_SYSINFO_SYSTEM_NAME,
1384                                   sysInfoReadSystemName);
1385     }
1386 
1387     // Parameters other than Set In Progress are assumed to be strings.
1388     std::tuple<bool, std::string> ret =
1389         sysInfoParamStore->lookup(paramSelector);
1390     bool found = std::get<0>(ret);
1391     if (!found)
1392     {
1393         return ipmi::responseSensorInvalid();
1394     }
1395     std::string& paramString = std::get<1>(ret);
1396     std::vector<uint8_t> configData;
1397     size_t count = 0;
1398     if (setSelector == 0)
1399     {                               // First chunk has only 14 bytes.
1400         configData.emplace_back(0); // encoding
1401         configData.emplace_back(paramString.length()); // string length
1402         count = std::min(paramString.length(), smallChunkSize);
1403         configData.resize(count + configDataOverhead);
1404         std::copy_n(paramString.begin(), count,
1405                     configData.begin() + configDataOverhead); // 14 bytes chunk
1406 
1407         // Append zero's to remaining bytes
1408         if (configData.size() < configParameterLength)
1409         {
1410             std::fill_n(std::back_inserter(configData),
1411                         configParameterLength - configData.size(), 0x00);
1412         }
1413     }
1414     else
1415     {
1416         size_t offset = (setSelector * fullChunkSize) - configDataOverhead;
1417         if (offset >= paramString.length())
1418         {
1419             return ipmi::responseParmOutOfRange();
1420         }
1421         count = std::min(paramString.length() - offset, fullChunkSize);
1422         configData.resize(count);
1423         std::copy_n(paramString.begin() + offset, count,
1424                     configData.begin()); // 16 bytes chunk
1425     }
1426     return ipmi::responseSuccess(paramRevision, setSelector, configData);
1427 }
1428 
1429 ipmi::RspType<> ipmiAppSetSystemInfo(uint8_t paramSelector, uint8_t data1,
1430                                      std::vector<uint8_t> configData)
1431 {
1432     if (paramSelector >= invalidParamSelectorStart &&
1433         paramSelector <= invalidParamSelectorEnd)
1434     {
1435         return ipmi::responseInvalidFieldRequest();
1436     }
1437     if (paramSelector >= oemCmdStart)
1438     {
1439         return ipmi::responseParmNotSupported();
1440     }
1441 
1442     if (paramSelector == 0)
1443     {
1444         // attempt to set the 'set in progress' value (in parameter #0)
1445         // when not in the set complete state.
1446         if ((transferStatus != setComplete) && (data1 == setInProgress))
1447         {
1448             return ipmi::responseSetInProgressActive();
1449         }
1450         // only following 2 states are supported
1451         if (data1 > setInProgress)
1452         {
1453             lg2::error("illegal SetInProgress status");
1454             return ipmi::responseInvalidFieldRequest();
1455         }
1456 
1457         transferStatus = data1 & progressMask;
1458         return ipmi::responseSuccess();
1459     }
1460 
1461     if (configData.size() > configParameterLength)
1462     {
1463         return ipmi::responseInvalidFieldRequest();
1464     }
1465 
1466     // Append zero's to remaining bytes
1467     if (configData.size() < configParameterLength)
1468     {
1469         fill_n(back_inserter(configData),
1470                (configParameterLength - configData.size()), 0x00);
1471     }
1472 
1473     if (!sysInfoParamStore)
1474     {
1475         sysInfoParamStore = std::make_unique<SysInfoParamStore>();
1476         sysInfoParamStore->update(IPMI_SYSINFO_SYSTEM_NAME,
1477                                   sysInfoReadSystemName);
1478     }
1479 
1480     // lookup
1481     std::tuple<bool, std::string> ret =
1482         sysInfoParamStore->lookup(paramSelector);
1483     bool found = std::get<0>(ret);
1484     std::string& paramString = std::get<1>(ret);
1485     if (!found)
1486     {
1487         // parameter does not exist. Init new
1488         paramString = "";
1489     }
1490 
1491     uint8_t setSelector = data1;
1492     size_t count = 0;
1493     if (setSelector == 0) // First chunk has only 14 bytes.
1494     {
1495         uint8_t encoding = configData.at(0);
1496         if (encoding > maxValidEncodingData)
1497         {
1498             return ipmi::responseInvalidFieldRequest();
1499         }
1500 
1501         size_t stringLen = configData.at(1); // string length
1502         // maxBytesPerParamter is 256. It will always be greater than stringLen
1503         // (unit8_t) if maxBytes changes in future, then following line is
1504         // needed.
1505         // stringLen = std::min(stringLen, maxBytesPerParameter);
1506         count = std::min(stringLen, smallChunkSize);
1507         count = std::min(count, configData.size());
1508         paramString.resize(stringLen); // reserve space
1509         std::copy_n(configData.begin() + configDataOverhead, count,
1510                     paramString.begin());
1511     }
1512     else
1513     {
1514         size_t offset = (setSelector * fullChunkSize) - configDataOverhead;
1515         if (offset >= paramString.length())
1516         {
1517             return ipmi::responseParmOutOfRange();
1518         }
1519         count = std::min(paramString.length() - offset, configData.size());
1520         std::copy_n(configData.begin(), count, paramString.begin() + offset);
1521     }
1522     sysInfoParamStore->update(paramSelector, paramString);
1523     return ipmi::responseSuccess();
1524 }
1525 
1526 #ifdef ENABLE_I2C_WHITELIST_CHECK
1527 inline std::vector<uint8_t> convertStringToData(const std::string& command)
1528 {
1529     std::istringstream iss(command);
1530     std::string token;
1531     std::vector<uint8_t> dataValue;
1532     while (std::getline(iss, token, ' '))
1533     {
1534         dataValue.emplace_back(
1535             static_cast<uint8_t>(std::stoul(token, nullptr, base_16)));
1536     }
1537     return dataValue;
1538 }
1539 
1540 static bool populateI2CControllerWRAllowlist()
1541 {
1542     nlohmann::json data = nullptr;
1543     std::ifstream jsonFile(i2cControllerWRAllowlistFile);
1544 
1545     if (!jsonFile.good())
1546     {
1547         lg2::warning("i2c allow list file not found! file name: {FILE_NAME}",
1548                      "FILE_NAME", i2cControllerWRAllowlistFile);
1549         return false;
1550     }
1551 
1552     try
1553     {
1554         data = nlohmann::json::parse(jsonFile, nullptr, false);
1555     }
1556     catch (const nlohmann::json::parse_error& e)
1557     {
1558         lg2::error("Corrupted i2c allow list config file, "
1559                    "file name: {FILE_NAME}, error: {ERROR}",
1560                    "FILE_NAME", i2cControllerWRAllowlistFile, "ERROR", e);
1561         return false;
1562     }
1563 
1564     try
1565     {
1566         // Example JSON Structure format
1567         // "filters": [
1568         //    {
1569         //      "Description": "Allow full read - ignore first byte write value
1570         //      for 0x40 to 0x4F",
1571         //      "busId": "0x01",
1572         //      "slaveAddr": "0x40",
1573         //      "slaveAddrMask": "0x0F",
1574         //      "command": "0x00",
1575         //      "commandMask": "0xFF"
1576         //    },
1577         //    {
1578         //      "Description": "Allow full read - first byte match 0x05 and
1579         //      ignore second byte",
1580         //      "busId": "0x01",
1581         //      "slaveAddr": "0x57",
1582         //      "slaveAddrMask": "0x00",
1583         //      "command": "0x05 0x00",
1584         //      "commandMask": "0x00 0xFF"
1585         //    },]
1586 
1587         nlohmann::json filters = data[filtersStr].get<nlohmann::json>();
1588         std::vector<i2cControllerWRAllowlist>& allowlist = getWRAllowlist();
1589         for (const auto& it : filters.items())
1590         {
1591             nlohmann::json filter = it.value();
1592             if (filter.is_null())
1593             {
1594                 lg2::error(
1595                     "Corrupted I2C controller write read allowlist config file, "
1596                     "file name: {FILE_NAME}",
1597                     "FILE_NAME", i2cControllerWRAllowlistFile);
1598                 return false;
1599             }
1600             const std::vector<uint8_t>& writeData =
1601                 convertStringToData(filter[cmdStr].get<std::string>());
1602             const std::vector<uint8_t>& writeDataMask =
1603                 convertStringToData(filter[cmdMaskStr].get<std::string>());
1604             if (writeDataMask.size() != writeData.size())
1605             {
1606                 lg2::error("I2C controller write read allowlist filter "
1607                            "mismatch for command & mask size");
1608                 return false;
1609             }
1610             allowlist.push_back(
1611                 {static_cast<uint8_t>(std::stoul(
1612                      filter[busIdStr].get<std::string>(), nullptr, base_16)),
1613                  static_cast<uint8_t>(
1614                      std::stoul(filter[targetAddrStr].get<std::string>(),
1615                                 nullptr, base_16)),
1616                  static_cast<uint8_t>(
1617                      std::stoul(filter[targetAddrMaskStr].get<std::string>(),
1618                                 nullptr, base_16)),
1619                  writeData, writeDataMask});
1620         }
1621         if (allowlist.size() != filters.size())
1622         {
1623             lg2::error(
1624                 "I2C controller write read allowlist filter size mismatch");
1625             return false;
1626         }
1627     }
1628     catch (const std::exception& e)
1629     {
1630         lg2::error("I2C controller write read allowlist "
1631                    "unexpected exception: {ERROR}",
1632                    "ERROR", e);
1633         return false;
1634     }
1635     return true;
1636 }
1637 
1638 static inline bool isWriteDataAllowlisted(const std::vector<uint8_t>& data,
1639                                           const std::vector<uint8_t>& dataMask,
1640                                           const std::vector<uint8_t>& writeData)
1641 {
1642     std::vector<uint8_t> processedDataBuf(data.size());
1643     std::vector<uint8_t> processedReqBuf(dataMask.size());
1644     std::transform(writeData.begin(), writeData.end(), dataMask.begin(),
1645                    processedReqBuf.begin(), std::bit_or<uint8_t>());
1646     std::transform(data.begin(), data.end(), dataMask.begin(),
1647                    processedDataBuf.begin(), std::bit_or<uint8_t>());
1648 
1649     return (processedDataBuf == processedReqBuf);
1650 }
1651 
1652 static bool isCmdAllowlisted(uint8_t busId, uint8_t targetAddr,
1653                              std::vector<uint8_t>& writeData)
1654 {
1655     std::vector<i2cControllerWRAllowlist>& allowList = getWRAllowlist();
1656     for (const auto& wlEntry : allowList)
1657     {
1658         if ((busId == wlEntry.busId) &&
1659             ((targetAddr | wlEntry.targetAddrMask) ==
1660              (wlEntry.targetAddr | wlEntry.targetAddrMask)))
1661         {
1662             const std::vector<uint8_t>& dataMask = wlEntry.dataMask;
1663             // Skip as no-match, if requested write data is more than the
1664             // write data mask size
1665             if (writeData.size() > dataMask.size())
1666             {
1667                 continue;
1668             }
1669             if (isWriteDataAllowlisted(wlEntry.data, dataMask, writeData))
1670             {
1671                 return true;
1672             }
1673         }
1674     }
1675     return false;
1676 }
1677 #else
1678 static bool populateI2CControllerWRAllowlist()
1679 {
1680     lg2::info("I2C_WHITELIST_CHECK is disabled, do not populate allowlist");
1681     return true;
1682 }
1683 #endif // ENABLE_I2C_WHITELIST_CHECK
1684 
1685 /** @brief implements controller write read IPMI command which can be used for
1686  * low-level I2C/SMBus write, read or write-read access
1687  *  @param isPrivateBus -to indicate private bus usage
1688  *  @param busId - bus id
1689  *  @param channelNum - channel number
1690  *  @param reserved - skip 1 bit
1691  *  @param targetAddr - target address
1692  *  @param read count - number of bytes to be read
1693  *  @param writeData - data to be written
1694  *
1695  *  @returns IPMI completion code plus response data
1696  *   - readData - i2c response data
1697  */
1698 ipmi::RspType<std::vector<uint8_t>> ipmiControllerWriteRead(
1699     [[maybe_unused]] bool isPrivateBus, uint3_t busId,
1700     [[maybe_unused]] uint4_t channelNum, bool reserved, uint7_t targetAddr,
1701     uint8_t readCount, std::vector<uint8_t> writeData)
1702 {
1703     if (reserved)
1704     {
1705         return ipmi::responseInvalidFieldRequest();
1706     }
1707     const size_t writeCount = writeData.size();
1708     if (!readCount && !writeCount)
1709     {
1710         lg2::error("Controller write read command: Read & write count are 0");
1711         return ipmi::responseInvalidFieldRequest();
1712     }
1713 #ifdef ENABLE_I2C_WHITELIST_CHECK
1714     if (!isCmdAllowlisted(static_cast<uint8_t>(busId),
1715                           static_cast<uint8_t>(targetAddr), writeData))
1716     {
1717         lg2::error("Controller write read request blocked!, "
1718                    "bus: {BUS}, addr: {ADDR}",
1719                    "BUS", static_cast<uint8_t>(busId), "ADDR", lg2::hex,
1720                    static_cast<uint8_t>(targetAddr));
1721     }
1722 #endif // ENABLE_I2C_WHITELIST_CHECK
1723     std::vector<uint8_t> readBuf(readCount);
1724     std::string i2cBus =
1725         "/dev/i2c-" + std::to_string(static_cast<uint8_t>(busId));
1726 
1727     ipmi::Cc ret = ipmi::i2cWriteRead(i2cBus, static_cast<uint8_t>(targetAddr),
1728                                       writeData, readBuf);
1729     if (ret != ipmi::ccSuccess)
1730     {
1731         return ipmi::response(ret);
1732     }
1733     return ipmi::responseSuccess(readBuf);
1734 }
1735 
1736 void register_netfn_app_functions()
1737 {
1738     // <Get Device ID>
1739     ipmi::registerHandler(ipmi::prioOpenBmcBase, ipmi::netFnApp,
1740                           ipmi::app::cmdGetDeviceId, ipmi::Privilege::User,
1741                           ipmiAppGetDeviceId);
1742 
1743     // <Get BT Interface Capabilities>
1744     ipmi::registerHandler(ipmi::prioOpenBmcBase, ipmi::netFnApp,
1745                           ipmi::app::cmdGetBtIfaceCapabilities,
1746                           ipmi::Privilege::User, ipmiAppGetBtCapabilities);
1747 
1748     // <Reset Watchdog Timer>
1749     ipmi::registerHandler(ipmi::prioOpenBmcBase, ipmi::netFnApp,
1750                           ipmi::app::cmdResetWatchdogTimer,
1751                           ipmi::Privilege::Operator, ipmiAppResetWatchdogTimer);
1752 
1753     ipmi::registerHandler(ipmi::prioOpenBmcBase, ipmi::netFnApp,
1754                           ipmi::app::cmdGetSessionInfo, ipmi::Privilege::User,
1755                           ipmiAppGetSessionInfo);
1756 
1757     // <Set Watchdog Timer>
1758     ipmi::registerHandler(ipmi::prioOpenBmcBase, ipmi::netFnApp,
1759                           ipmi::app::cmdSetWatchdogTimer,
1760                           ipmi::Privilege::Operator, ipmiSetWatchdogTimer);
1761 
1762     ipmi::registerHandler(ipmi::prioOpenBmcBase, ipmi::netFnApp,
1763                           ipmi::app::cmdCloseSession, ipmi::Privilege::Callback,
1764                           ipmiAppCloseSession);
1765 
1766     // <Get Watchdog Timer>
1767     ipmi::registerHandler(ipmi::prioOpenBmcBase, ipmi::netFnApp,
1768                           ipmi::app::cmdGetWatchdogTimer, ipmi::Privilege::User,
1769                           ipmiGetWatchdogTimer);
1770 
1771     // <Get Self Test Results>
1772     ipmi::registerHandler(ipmi::prioOpenBmcBase, ipmi::netFnApp,
1773                           ipmi::app::cmdGetSelfTestResults,
1774                           ipmi::Privilege::User, ipmiAppGetSelfTestResults);
1775 
1776     // <Get Device GUID>
1777     ipmi::registerHandler(ipmi::prioOpenBmcBase, ipmi::netFnApp,
1778                           ipmi::app::cmdGetDeviceGuid, ipmi::Privilege::User,
1779                           ipmiAppGetDeviceGuid);
1780 
1781     // <Set ACPI Power State>
1782     ipmi::registerHandler(ipmi::prioOpenBmcBase, ipmi::netFnApp,
1783                           ipmi::app::cmdSetAcpiPowerState,
1784                           ipmi::Privilege::Admin, ipmiSetAcpiPowerState);
1785     // <Get ACPI Power State>
1786     ipmi::registerHandler(ipmi::prioOpenBmcBase, ipmi::netFnApp,
1787                           ipmi::app::cmdGetAcpiPowerState,
1788                           ipmi::Privilege::User, ipmiGetAcpiPowerState);
1789 
1790     // Note: For security reason, this command will be registered only when
1791     // there are proper I2C Controller write read allowlist
1792     if (populateI2CControllerWRAllowlist())
1793     {
1794         // Note: For security reasons, registering controller write read as
1795         // admin privilege command, even though IPMI 2.0 specification allows it
1796         // as operator privilege.
1797         ipmi::registerHandler(ipmi::prioOpenBmcBase, ipmi::netFnApp,
1798                               ipmi::app::cmdMasterWriteRead,
1799                               ipmi::Privilege::Admin, ipmiControllerWriteRead);
1800     }
1801 
1802     // <Get System GUID Command>
1803     ipmi::registerHandler(ipmi::prioOpenBmcBase, ipmi::netFnApp,
1804                           ipmi::app::cmdGetSystemGuid, ipmi::Privilege::User,
1805                           ipmiAppGetSystemGuid);
1806 
1807     // <Get Channel Cipher Suites Command>
1808     ipmi::registerHandler(ipmi::prioOpenBmcBase, ipmi::netFnApp,
1809                           ipmi::app::cmdGetChannelCipherSuites,
1810                           ipmi::Privilege::None, getChannelCipherSuites);
1811 
1812     // <Get System Info Command>
1813     ipmi::registerHandler(ipmi::prioOpenBmcBase, ipmi::netFnApp,
1814                           ipmi::app::cmdGetSystemInfoParameters,
1815                           ipmi::Privilege::User, ipmiAppGetSystemInfo);
1816     // <Set System Info Command>
1817     ipmi::registerHandler(ipmi::prioOpenBmcBase, ipmi::netFnApp,
1818                           ipmi::app::cmdSetSystemInfoParameters,
1819                           ipmi::Privilege::Admin, ipmiAppSetSystemInfo);
1820     return;
1821 }
1822