1 #include "config.h"
2 
3 #include "chassishandler.hpp"
4 
5 #include <arpa/inet.h>
6 #include <endian.h>
7 #include <limits.h>
8 #include <netinet/in.h>
9 
10 #include <ipmid/api.hpp>
11 #include <ipmid/types.hpp>
12 #include <ipmid/utils.hpp>
13 #include <phosphor-logging/elog-errors.hpp>
14 #include <phosphor-logging/lg2.hpp>
15 #include <sdbusplus/bus.hpp>
16 #include <sdbusplus/message/types.hpp>
17 #include <sdbusplus/server/object.hpp>
18 #include <sdbusplus/timer.hpp>
19 #include <settings.hpp>
20 #include <xyz/openbmc_project/Common/error.hpp>
21 #include <xyz/openbmc_project/Control/Boot/Mode/server.hpp>
22 #include <xyz/openbmc_project/Control/Boot/Source/server.hpp>
23 #include <xyz/openbmc_project/Control/Boot/Type/server.hpp>
24 #include <xyz/openbmc_project/Control/Power/RestorePolicy/server.hpp>
25 #include <xyz/openbmc_project/State/Chassis/server.hpp>
26 #include <xyz/openbmc_project/State/Host/server.hpp>
27 #include <xyz/openbmc_project/State/PowerOnHours/server.hpp>
28 
29 #include <array>
30 #include <chrono>
31 #include <cstring>
32 #include <filesystem>
33 #include <fstream>
34 #include <future>
35 #include <map>
36 #include <sstream>
37 #include <string>
38 
39 std::unique_ptr<sdbusplus::Timer> identifyTimer
40     __attribute__((init_priority(101)));
41 
42 static ChassisIDState chassisIDState = ChassisIDState::reserved;
43 
44 constexpr size_t sizeVersion = 2;
45 constexpr size_t DEFAULT_IDENTIFY_TIME_OUT = 15;
46 
47 // PetiBoot-Specific
48 static constexpr uint8_t netConfInitialBytes[] = {0x80, 0x21, 0x70, 0x62,
49                                                   0x21, 0x00, 0x01, 0x06};
50 static constexpr uint8_t oemParmStart = 96;
51 static constexpr uint8_t oemParmEnd = 127;
52 
53 static constexpr size_t cookieOffset = 1;
54 static constexpr size_t versionOffset = 5;
55 static constexpr size_t addrSizeOffset = 8;
56 static constexpr size_t macOffset = 9;
57 static constexpr size_t addrTypeOffset = 16;
58 static constexpr size_t ipAddrOffset = 17;
59 
60 namespace ipmi
61 {
62 constexpr Cc ccParmNotSupported = 0x80;
63 
responseParmNotSupported()64 static inline auto responseParmNotSupported()
65 {
66     return response(ccParmNotSupported);
67 }
68 } // namespace ipmi
69 
70 void register_netfn_chassis_functions() __attribute__((constructor));
71 
72 // Host settings in dbus
73 // Service name should be referenced by connection name got via object mapper
74 const char* settings_object_name = "/org/openbmc/settings/host0";
75 const char* settings_intf_name = "org.freedesktop.DBus.Properties";
76 const char* identify_led_object_name =
77     "/xyz/openbmc_project/led/groups/enclosure_identify";
78 
79 constexpr auto SETTINGS_ROOT = "/";
80 constexpr auto SETTINGS_MATCH = "host0";
81 
82 constexpr auto IP_INTERFACE = "xyz.openbmc_project.Network.IP";
83 constexpr auto MAC_INTERFACE = "xyz.openbmc_project.Network.MACAddress";
84 
85 static constexpr auto chassisStateRoot = "/xyz/openbmc_project/state";
86 static constexpr auto chassisPOHStateIntf =
87     "xyz.openbmc_project.State.PowerOnHours";
88 static constexpr auto pohCounterProperty = "POHCounter";
89 static constexpr auto match = "chassis0";
90 const static constexpr char chassisCapIntf[] =
91     "xyz.openbmc_project.Control.ChassisCapabilities";
92 const static constexpr char chassisIntrusionProp[] = "ChassisIntrusionEnabled";
93 const static constexpr char chassisFrontPanelLockoutProp[] =
94     "ChassisFrontPanelLockoutEnabled";
95 const static constexpr char chassisNMIProp[] = "ChassisNMIEnabled";
96 const static constexpr char chassisPowerInterlockProp[] =
97     "ChassisPowerInterlockEnabled";
98 const static constexpr char chassisFRUDevAddrProp[] = "FRUDeviceAddress";
99 const static constexpr char chassisSDRDevAddrProp[] = "SDRDeviceAddress";
100 const static constexpr char chassisSELDevAddrProp[] = "SELDeviceAddress";
101 const static constexpr char chassisSMDevAddrProp[] = "SMDeviceAddress";
102 const static constexpr char chassisBridgeDevAddrProp[] = "BridgeDeviceAddress";
103 static constexpr uint8_t chassisCapAddrMask = 0xfe;
104 static constexpr const char* powerButtonIntf =
105     "xyz.openbmc_project.Chassis.Buttons.Power";
106 static constexpr const char* powerButtonPath =
107     "/xyz/openbmc_project/Chassis/Buttons/Power0";
108 static constexpr const char* resetButtonIntf =
109     "xyz.openbmc_project.Chassis.Buttons.Reset";
110 static constexpr const char* resetButtonPath =
111     "/xyz/openbmc_project/Chassis/Buttons/Reset0";
112 
113 // Phosphor Host State manager
114 namespace State = sdbusplus::server::xyz::openbmc_project::state;
115 namespace fs = std::filesystem;
116 
117 using namespace phosphor::logging;
118 using namespace sdbusplus::error::xyz::openbmc_project::common;
119 using namespace sdbusplus::server::xyz::openbmc_project::control::boot;
120 
121 namespace chassis
122 {
123 namespace internal
124 {
125 
126 constexpr auto bootSettingsPath = "/xyz/openbmc_project/control/host0/boot";
127 constexpr auto bootEnableIntf = "xyz.openbmc_project.Object.Enable";
128 constexpr auto bootModeIntf = "xyz.openbmc_project.Control.Boot.Mode";
129 constexpr auto bootTypeIntf = "xyz.openbmc_project.Control.Boot.Type";
130 constexpr auto bootSourceIntf = "xyz.openbmc_project.Control.Boot.Source";
131 constexpr auto bootSettingsOneTimePath =
132     "/xyz/openbmc_project/control/host0/boot/one_time";
133 constexpr auto bootOneTimeIntf = "xyz.openbmc_project.Object.Enable";
134 
135 constexpr auto powerRestoreIntf =
136     "xyz.openbmc_project.Control.Power.RestorePolicy";
137 sdbusplus::bus_t dbus(ipmid_get_sd_bus_connection());
138 
139 namespace cache
140 {
141 
142 std::unique_ptr<settings::Objects> objectsPtr = nullptr;
143 
getObjects()144 settings::Objects& getObjects()
145 {
146     if (objectsPtr == nullptr)
147     {
148         objectsPtr = std::make_unique<settings::Objects>(
149             dbus, std::vector<std::string>{bootModeIntf, bootTypeIntf,
150                                            bootSourceIntf, powerRestoreIntf});
151     }
152     return *objectsPtr;
153 }
154 
155 } // namespace cache
156 } // namespace internal
157 } // namespace chassis
158 
159 namespace poh
160 {
161 
162 constexpr auto minutesPerCount = 60;
163 
164 } // namespace poh
165 
getHostNetworkData(ipmi::message::Payload & payload)166 int getHostNetworkData(ipmi::message::Payload& payload)
167 {
168     ipmi::PropertyMap properties;
169     int rc = 0;
170     uint8_t addrSize = ipmi::network::IPV4_ADDRESS_SIZE_BYTE;
171 
172     try
173     {
174         // TODO There may be cases where an interface is implemented by multiple
175         // objects,to handle such cases we are interested on that object
176         //  which are on interested busname.
177         //  Currenlty mapper doesn't give the readable busname(gives busid)
178         //  so we can't match with bus name so giving some object specific info
179         //  as SETTINGS_MATCH.
180         //  Later SETTINGS_MATCH will be replaced with busname.
181 
182         sdbusplus::bus_t bus(ipmid_get_sd_bus_connection());
183 
184         auto ipObjectInfo = ipmi::getDbusObject(bus, IP_INTERFACE,
185                                                 SETTINGS_ROOT, SETTINGS_MATCH);
186 
187         auto macObjectInfo = ipmi::getDbusObject(bus, MAC_INTERFACE,
188                                                  SETTINGS_ROOT, SETTINGS_MATCH);
189 
190         properties = ipmi::getAllDbusProperties(
191             bus, ipObjectInfo.second, ipObjectInfo.first, IP_INTERFACE);
192         auto variant = ipmi::getDbusProperty(
193             bus, macObjectInfo.second, macObjectInfo.first, MAC_INTERFACE,
194             "MACAddress");
195 
196         auto ipAddress = std::get<std::string>(properties["Address"]);
197 
198         auto gateway = std::get<std::string>(properties["Gateway"]);
199 
200         auto prefix = std::get<uint8_t>(properties["PrefixLength"]);
201 
202         uint8_t isStatic =
203             (std::get<std::string>(properties["Origin"]) ==
204              "xyz.openbmc_project.Network.IP.AddressOrigin.Static")
205                 ? 1
206                 : 0;
207 
208         auto MACAddress = std::get<std::string>(variant);
209 
210         // it is expected here that we should get the valid data
211         // but we may also get the default values.
212         // Validation of the data is done by settings.
213         //
214         // if mac address is default mac address then
215         // don't send blank override.
216         if ((MACAddress == ipmi::network::DEFAULT_MAC_ADDRESS))
217         {
218             rc = -1;
219             return rc;
220         }
221         // if addr is static then ipaddress,gateway,prefix
222         // should not be default one,don't send blank override.
223         if (isStatic)
224         {
225             if ((ipAddress == ipmi::network::DEFAULT_ADDRESS) ||
226                 (gateway == ipmi::network::DEFAULT_ADDRESS) || (!prefix))
227             {
228                 rc = -1;
229                 return rc;
230             }
231         }
232 
233         std::string token;
234         std::stringstream ss(MACAddress);
235 
236         // First pack macOffset no of bytes in payload.
237         // Latter this PetiBoot-Specific data will be populated.
238         std::vector<uint8_t> payloadInitialBytes(macOffset);
239         payload.pack(payloadInitialBytes);
240 
241         while (std::getline(ss, token, ':'))
242         {
243             payload.pack(stoi(token, nullptr, 16));
244         }
245 
246         payload.pack(0x00);
247 
248         payload.pack(isStatic);
249 
250         uint8_t addressFamily = (std::get<std::string>(properties["Type"]) ==
251                                  "xyz.openbmc_project.Network.IP.Protocol.IPv4")
252                                     ? AF_INET
253                                     : AF_INET6;
254 
255         addrSize = (addressFamily == AF_INET)
256                        ? ipmi::network::IPV4_ADDRESS_SIZE_BYTE
257                        : ipmi::network::IPV6_ADDRESS_SIZE_BYTE;
258 
259         // ipaddress and gateway would be in IPv4 format
260         std::vector<uint8_t> addrInBinary(addrSize);
261         inet_pton(addressFamily, ipAddress.c_str(),
262                   reinterpret_cast<void*>(addrInBinary.data()));
263 
264         payload.pack(addrInBinary);
265 
266         payload.pack(prefix);
267 
268         std::vector<uint8_t> gatewayDetails(addrSize);
269         inet_pton(addressFamily, gateway.c_str(),
270                   reinterpret_cast<void*>(gatewayDetails.data()));
271         payload.pack(gatewayDetails);
272     }
273     catch (const InternalFailure& e)
274     {
275         commit<InternalFailure>();
276         rc = -1;
277         return rc;
278     }
279 
280     // PetiBoot-Specific
281     // If success then copy the first 9 bytes to the payload message
282     // payload first 2 bytes contain the parameter values. Skip that 2 bytes.
283     uint8_t skipFirstTwoBytes = 2;
284     size_t payloadSize = payload.size();
285     uint8_t* configDataStartingAddress = payload.data() + skipFirstTwoBytes;
286 
287     if (payloadSize < skipFirstTwoBytes + sizeof(netConfInitialBytes))
288     {
289         lg2::error("Invalid net config");
290         rc = -1;
291         return rc;
292     }
293     std::copy(netConfInitialBytes,
294               netConfInitialBytes + sizeof(netConfInitialBytes),
295               configDataStartingAddress);
296 
297     if (payloadSize < skipFirstTwoBytes + addrSizeOffset + sizeof(addrSize))
298     {
299         lg2::error("Invalid length of address size");
300         rc = -1;
301         return rc;
302     }
303     std::copy(&addrSize, &(addrSize) + sizeof(addrSize),
304               configDataStartingAddress + addrSizeOffset);
305 
306 #ifdef _IPMI_DEBUG_
307     std::printf("\n===Printing the IPMI Formatted Data========\n");
308 
309     for (uint8_t pos = 0; pos < index; pos++)
310     {
311         std::printf("%02x ", payloadStartingAddress[pos]);
312     }
313 #endif
314 
315     return rc;
316 }
317 
318 /** @brief convert IPv4 and IPv6 addresses from binary to text form.
319  *  @param[in] family - IPv4/Ipv6
320  *  @param[in] data - req data pointer.
321  *  @param[in] offset - offset in the data.
322  *  @param[in] addrSize - size of the data which needs to be read from offset.
323  *  @returns address in text form.
324  */
325 
getAddrStr(uint8_t family,uint8_t * data,uint8_t offset,uint8_t addrSize)326 std::string getAddrStr(uint8_t family, uint8_t* data, uint8_t offset,
327                        uint8_t addrSize)
328 {
329     char ipAddr[INET6_ADDRSTRLEN] = {};
330 
331     switch (family)
332     {
333         case AF_INET:
334         {
335             struct sockaddr_in addr4
336             {};
337             std::memcpy(&addr4.sin_addr.s_addr, &data[offset], addrSize);
338 
339             inet_ntop(AF_INET, &addr4.sin_addr, ipAddr, INET_ADDRSTRLEN);
340 
341             break;
342         }
343         case AF_INET6:
344         {
345             struct sockaddr_in6 addr6
346             {};
347             std::memcpy(&addr6.sin6_addr.s6_addr, &data[offset], addrSize);
348 
349             inet_ntop(AF_INET6, &addr6.sin6_addr, ipAddr, INET6_ADDRSTRLEN);
350 
351             break;
352         }
353         default:
354         {
355             return {};
356         }
357     }
358 
359     return ipAddr;
360 }
361 
setHostNetworkData(ipmi::message::Payload & data)362 ipmi::Cc setHostNetworkData(ipmi::message::Payload& data)
363 {
364     using namespace std::string_literals;
365     std::string hostNetworkConfig;
366     std::string mac("00:00:00:00:00:00");
367     std::string ipAddress, gateway;
368     std::string addrOrigin{0};
369     uint8_t addrSize{0};
370     std::string addressOrigin =
371         "xyz.openbmc_project.Network.IP.AddressOrigin.DHCP";
372     std::string addressType = "xyz.openbmc_project.Network.IP.Protocol.IPv4";
373     uint8_t prefix{0};
374     uint8_t family = AF_INET;
375 
376     // cookie starts from second byte
377     // version starts from sixth byte
378 
379     try
380     {
381         do
382         {
383             // cookie ==  0x21 0x70 0x62 0x21
384             data.trailingOk = true;
385             auto msgLen = data.size();
386             std::vector<uint8_t> msgPayloadBytes(msgLen);
387             if (data.unpack(msgPayloadBytes) != 0 || !data.fullyUnpacked())
388             {
389                 lg2::error("Error in unpacking message of setHostNetworkData");
390                 return ipmi::ccReqDataLenInvalid;
391             }
392 
393             uint8_t* msgPayloadStartingPos = msgPayloadBytes.data();
394             constexpr size_t cookieSize = 4;
395             if (msgLen < cookieOffset + cookieSize)
396             {
397                 lg2::error("Error in cookie getting of setHostNetworkData");
398                 return ipmi::ccReqDataLenInvalid;
399             }
400             if (std::equal(msgPayloadStartingPos + cookieOffset,
401                            msgPayloadStartingPos + cookieOffset + cookieSize,
402                            (netConfInitialBytes + cookieOffset)) != 0)
403             {
404                 // all cookie == 0
405                 if (std::all_of(msgPayloadStartingPos + cookieOffset,
406                                 msgPayloadStartingPos + cookieOffset +
407                                     cookieSize,
408                                 [](int i) { return i == 0; }) == true)
409                 {
410                     // need to zero out the network settings.
411                     break;
412                 }
413 
414                 lg2::error("Invalid Cookie");
415                 elog<InternalFailure>();
416             }
417 
418             // vesion == 0x00 0x01
419             if (msgLen < versionOffset + sizeVersion)
420             {
421                 lg2::error("Error in version getting of setHostNetworkData");
422                 return ipmi::ccReqDataLenInvalid;
423             }
424             if (std::equal(msgPayloadStartingPos + versionOffset,
425                            msgPayloadStartingPos + versionOffset + sizeVersion,
426                            (netConfInitialBytes + versionOffset)) != 0)
427             {
428                 lg2::error("Invalid Version");
429                 elog<InternalFailure>();
430             }
431 
432             if (msgLen < macOffset + 6)
433             {
434                 lg2::error(
435                     "Error in mac address getting of setHostNetworkData");
436                 return ipmi::ccReqDataLenInvalid;
437             }
438             std::stringstream result;
439             std::copy((msgPayloadStartingPos + macOffset),
440                       (msgPayloadStartingPos + macOffset + 5),
441                       std::ostream_iterator<int>(result, ":"));
442             mac = result.str();
443 
444             if (msgLen < addrTypeOffset + sizeof(decltype(addrOrigin)))
445             {
446                 lg2::error(
447                     "Error in original address getting of setHostNetworkData");
448                 return ipmi::ccReqDataLenInvalid;
449             }
450             std::copy(msgPayloadStartingPos + addrTypeOffset,
451                       msgPayloadStartingPos + addrTypeOffset +
452                           sizeof(decltype(addrOrigin)),
453                       std::ostream_iterator<int>(result, ""));
454             addrOrigin = result.str();
455 
456             if (!addrOrigin.empty())
457             {
458                 addressOrigin =
459                     "xyz.openbmc_project.Network.IP.AddressOrigin.Static";
460             }
461 
462             if (msgLen < addrSizeOffset + sizeof(decltype(addrSize)))
463             {
464                 lg2::error(
465                     "Error in address size getting of setHostNetworkData");
466                 return ipmi::ccReqDataLenInvalid;
467             }
468             // Get the address size
469             std::copy(msgPayloadStartingPos + addrSizeOffset,
470                       (msgPayloadStartingPos + addrSizeOffset +
471                        sizeof(decltype(addrSize))),
472                       &addrSize);
473 
474             uint8_t prefixOffset = ipAddrOffset + addrSize;
475             if (msgLen < prefixOffset + sizeof(decltype(prefix)))
476             {
477                 lg2::error("Error in prefix getting of setHostNetworkData");
478                 return ipmi::ccReqDataLenInvalid;
479             }
480             // std::copy(msgPayloadStartingPos + prefixOffset,
481             //           msgPayloadStartingPos + prefixOffset +
482             //               sizeof(decltype(prefix)),
483             //           &prefix);
484             // Workaround compiler misdetecting out of bounds memcpy
485             prefix = msgPayloadStartingPos[prefixOffset];
486 
487             uint8_t gatewayOffset = prefixOffset + sizeof(decltype(prefix));
488             if (addrSize != ipmi::network::IPV4_ADDRESS_SIZE_BYTE)
489             {
490                 addressType = "xyz.openbmc_project.Network.IP.Protocol.IPv6";
491                 family = AF_INET6;
492             }
493 
494             if (msgLen < ipAddrOffset + addrSize)
495             {
496                 lg2::error("Error in IP address getting of setHostNetworkData");
497                 return ipmi::ccReqDataLenInvalid;
498             }
499             ipAddress = getAddrStr(family, msgPayloadStartingPos, ipAddrOffset,
500                                    addrSize);
501 
502             if (msgLen < gatewayOffset + addrSize)
503             {
504                 lg2::error(
505                     "Error in gateway address getting of setHostNetworkData");
506                 return ipmi::ccReqDataLenInvalid;
507             }
508             gateway = getAddrStr(family, msgPayloadStartingPos, gatewayOffset,
509                                  addrSize);
510 
511         } while (0);
512 
513         // Cookie == 0 or it is a valid cookie
514         hostNetworkConfig +=
515             "ipaddress="s + ipAddress + ",prefix="s + std::to_string(prefix) +
516             ",gateway="s + gateway + ",mac="s + mac + ",addressOrigin="s +
517             addressOrigin;
518 
519         sdbusplus::bus_t bus(ipmid_get_sd_bus_connection());
520 
521         auto ipObjectInfo = ipmi::getDbusObject(bus, IP_INTERFACE,
522                                                 SETTINGS_ROOT, SETTINGS_MATCH);
523         auto macObjectInfo = ipmi::getDbusObject(bus, MAC_INTERFACE,
524                                                  SETTINGS_ROOT, SETTINGS_MATCH);
525         // set the dbus property
526         ipmi::setDbusProperty(bus, ipObjectInfo.second, ipObjectInfo.first,
527                               IP_INTERFACE, "Address", std::string(ipAddress));
528         ipmi::setDbusProperty(bus, ipObjectInfo.second, ipObjectInfo.first,
529                               IP_INTERFACE, "PrefixLength", prefix);
530         ipmi::setDbusProperty(bus, ipObjectInfo.second, ipObjectInfo.first,
531                               IP_INTERFACE, "Origin", addressOrigin);
532         ipmi::setDbusProperty(bus, ipObjectInfo.second, ipObjectInfo.first,
533                               IP_INTERFACE, "Gateway", std::string(gateway));
534         ipmi::setDbusProperty(
535             bus, ipObjectInfo.second, ipObjectInfo.first, IP_INTERFACE, "Type",
536             std::string("xyz.openbmc_project.Network.IP.Protocol.IPv4"));
537         ipmi::setDbusProperty(bus, macObjectInfo.second, macObjectInfo.first,
538                               MAC_INTERFACE, "MACAddress", std::string(mac));
539 
540         lg2::debug("Network configuration changed: {NETWORKCONFIG}",
541                    "NETWORKCONFIG", hostNetworkConfig);
542     }
543     catch (const sdbusplus::exception_t& e)
544     {
545         commit<InternalFailure>();
546         lg2::error("Error in ipmiChassisSetSysBootOptions call");
547         return ipmi::ccUnspecifiedError;
548     }
549 
550     return ipmi::ccSuccess;
551 }
552 
getPOHCounter()553 uint32_t getPOHCounter()
554 {
555     sdbusplus::bus_t bus{ipmid_get_sd_bus_connection()};
556 
557     auto chassisStateObj =
558         ipmi::getDbusObject(bus, chassisPOHStateIntf, chassisStateRoot, match);
559 
560     auto service =
561         ipmi::getService(bus, chassisPOHStateIntf, chassisStateObj.first);
562 
563     auto propValue =
564         ipmi::getDbusProperty(bus, service, chassisStateObj.first,
565                               chassisPOHStateIntf, pohCounterProperty);
566 
567     return std::get<uint32_t>(propValue);
568 }
569 
570 /** @brief Implements the get chassis capabilities command
571  *
572  *  @returns IPMI completion code plus response data
573  *  chassisCapFlags        - chassis capability flag
574  *  chassisFRUInfoDevAddr  - chassis FRU info Device Address
575  *  chassisSDRDevAddr      - chassis SDR device address
576  *  chassisSELDevAddr      - chassis SEL device address
577  *  chassisSMDevAddr       - chassis system management device address
578  *  chassisBridgeDevAddr   - chassis bridge device address
579  */
580 ipmi::RspType<bool,    // chassis intrusion sensor
581               bool,    // chassis Front panel lockout
582               bool,    // chassis NMI
583               bool,    // chassis power interlock
584               uint4_t, // reserved
585               uint8_t, // chassis FRU info Device Address
586               uint8_t, // chassis SDR device address
587               uint8_t, // chassis SEL device address
588               uint8_t, // chassis system management device address
589               uint8_t  // chassis bridge device address
590               >
ipmiGetChassisCap()591     ipmiGetChassisCap()
592 {
593     ipmi::PropertyMap properties;
594     try
595     {
596         sdbusplus::bus_t bus{ipmid_get_sd_bus_connection()};
597 
598         ipmi::DbusObjectInfo chassisCapObject =
599             ipmi::getDbusObject(bus, chassisCapIntf);
600 
601         // capabilities flags
602         // [7..4] - reserved
603         // [3] – 1b = provides power interlock  (IPM 1.5)
604         // [2] – 1b = provides Diagnostic Interrupt (FP NMI)
605         // [1] – 1b = provides “Front Panel Lockout” (indicates that the chassis
606         // has capabilities
607         //            to lock out external power control and reset button or
608         //            front panel interfaces and/or detect tampering with those
609         //            interfaces).
610         // [0] -1b = Chassis provides intrusion (physical security) sensor.
611         // set to default value 0x0.
612 
613         properties =
614             ipmi::getAllDbusProperties(bus, chassisCapObject.second,
615                                        chassisCapObject.first, chassisCapIntf);
616     }
617     catch (const std::exception& e)
618     {
619         lg2::error("Failed to fetch Chassis Capability properties: {ERROR}",
620                    "ERROR", e);
621         return ipmi::responseUnspecifiedError();
622     }
623 
624     bool* chassisIntrusionFlag =
625         std::get_if<bool>(&properties[chassisIntrusionProp]);
626     if (chassisIntrusionFlag == nullptr)
627     {
628         lg2::error("Error to get chassis Intrusion flags");
629         return ipmi::responseUnspecifiedError();
630     }
631     bool* chassisFrontPanelFlag =
632         std::get_if<bool>(&properties[chassisFrontPanelLockoutProp]);
633     if (chassisFrontPanelFlag == nullptr)
634     {
635         lg2::error("Error to get chassis intrusion flags");
636         return ipmi::responseUnspecifiedError();
637     }
638     bool* chassisNMIFlag = std::get_if<bool>(&properties[chassisNMIProp]);
639     if (chassisNMIFlag == nullptr)
640     {
641         lg2::error("Error to get chassis NMI flags");
642         return ipmi::responseUnspecifiedError();
643     }
644     bool* chassisPowerInterlockFlag =
645         std::get_if<bool>(&properties[chassisPowerInterlockProp]);
646     if (chassisPowerInterlockFlag == nullptr)
647     {
648         lg2::error("Error to get chassis power interlock flags");
649         return ipmi::responseUnspecifiedError();
650     }
651     uint8_t* chassisFRUInfoDevAddr =
652         std::get_if<uint8_t>(&properties[chassisFRUDevAddrProp]);
653     if (chassisFRUInfoDevAddr == nullptr)
654     {
655         lg2::error("Error to get chassis FRU info device address");
656         return ipmi::responseUnspecifiedError();
657     }
658     uint8_t* chassisSDRDevAddr =
659         std::get_if<uint8_t>(&properties[chassisSDRDevAddrProp]);
660     if (chassisSDRDevAddr == nullptr)
661     {
662         lg2::error("Error to get chassis SDR device address");
663         return ipmi::responseUnspecifiedError();
664     }
665     uint8_t* chassisSELDevAddr =
666         std::get_if<uint8_t>(&properties[chassisSELDevAddrProp]);
667     if (chassisSELDevAddr == nullptr)
668     {
669         lg2::error("Error to get chassis SEL device address");
670         return ipmi::responseUnspecifiedError();
671     }
672     uint8_t* chassisSMDevAddr =
673         std::get_if<uint8_t>(&properties[chassisSMDevAddrProp]);
674     if (chassisSMDevAddr == nullptr)
675     {
676         lg2::error("Error to get chassis SM device address");
677         return ipmi::responseUnspecifiedError();
678     }
679     uint8_t* chassisBridgeDevAddr =
680         std::get_if<uint8_t>(&properties[chassisBridgeDevAddrProp]);
681     if (chassisBridgeDevAddr == nullptr)
682     {
683         lg2::error("Error to get chassis bridge device address");
684         return ipmi::responseUnspecifiedError();
685     }
686 
687     return ipmi::responseSuccess(
688         *chassisIntrusionFlag, *chassisFrontPanelFlag, *chassisNMIFlag,
689         *chassisPowerInterlockFlag, 0, *chassisFRUInfoDevAddr,
690         *chassisSDRDevAddr, *chassisSELDevAddr, *chassisSMDevAddr,
691         *chassisBridgeDevAddr);
692 }
693 
694 /** @brief implements set chassis capalibities command
695  *  @param intrusion        - chassis intrusion
696  *  @param fpLockout        - frontpannel lockout
697  *  @param reserved1        - skip one bit
698  *  @param fruDeviceAddr    - chassis FRU info Device Address
699  *  @param sdrDeviceAddr    - chassis SDR device address
700  *  @param selDeviceAddr    - chassis SEL device address
701  *  @param smDeviceAddr     - chassis system management device address
702  *  @param bridgeDeviceAddr - chassis bridge device address
703  *
704  *  @returns IPMI completion code
705  */
ipmiSetChassisCap(bool intrusion,bool fpLockout,uint6_t reserved1,uint8_t fruDeviceAddr,uint8_t sdrDeviceAddr,uint8_t selDeviceAddr,uint8_t smDeviceAddr,uint8_t bridgeDeviceAddr)706 ipmi::RspType<> ipmiSetChassisCap(
707     bool intrusion, bool fpLockout, uint6_t reserved1,
708 
709     uint8_t fruDeviceAddr,
710 
711     uint8_t sdrDeviceAddr,
712 
713     uint8_t selDeviceAddr,
714 
715     uint8_t smDeviceAddr,
716 
717     uint8_t bridgeDeviceAddr)
718 {
719     // check input data
720     if (reserved1 != 0)
721     {
722         lg2::error("Unsupported request parameter");
723         return ipmi::responseInvalidFieldRequest();
724     }
725 
726     if ((fruDeviceAddr & ~chassisCapAddrMask) != 0)
727     {
728         lg2::error("Unsupported request parameter(FRU Addr) for REQ={REQ}",
729                    "REQ", lg2::hex, fruDeviceAddr);
730         return ipmi::responseInvalidFieldRequest();
731     }
732     if ((sdrDeviceAddr & ~chassisCapAddrMask) != 0)
733     {
734         lg2::error("Unsupported request parameter(SDR Addr) for REQ={REQ}",
735                    "REQ", lg2::hex, sdrDeviceAddr);
736         return ipmi::responseInvalidFieldRequest();
737     }
738 
739     if ((selDeviceAddr & ~chassisCapAddrMask) != 0)
740     {
741         lg2::error("Unsupported request parameter(SEL Addr) for REQ={REQ}",
742                    "REQ", lg2::hex, selDeviceAddr);
743         return ipmi::responseInvalidFieldRequest();
744     }
745 
746     if ((smDeviceAddr & ~chassisCapAddrMask) != 0)
747     {
748         lg2::error("Unsupported request parameter(SM Addr) for REQ={REQ}",
749                    "REQ", lg2::hex, smDeviceAddr);
750         return ipmi::responseInvalidFieldRequest();
751     }
752 
753     if ((bridgeDeviceAddr & ~chassisCapAddrMask) != 0)
754     {
755         lg2::error("Unsupported request parameter(Bridge Addr) for REQ={REQ}",
756                    "REQ", lg2::hex, bridgeDeviceAddr);
757         return ipmi::responseInvalidFieldRequest();
758     }
759 
760     try
761     {
762         sdbusplus::bus_t bus(ipmid_get_sd_bus_connection());
763         ipmi::DbusObjectInfo chassisCapObject =
764             ipmi::getDbusObject(bus, chassisCapIntf);
765 
766         ipmi::setDbusProperty(bus, chassisCapObject.second,
767                               chassisCapObject.first, chassisCapIntf,
768                               chassisIntrusionProp, intrusion);
769 
770         ipmi::setDbusProperty(bus, chassisCapObject.second,
771                               chassisCapObject.first, chassisCapIntf,
772                               chassisFrontPanelLockoutProp, fpLockout);
773 
774         ipmi::setDbusProperty(bus, chassisCapObject.second,
775                               chassisCapObject.first, chassisCapIntf,
776                               chassisFRUDevAddrProp, fruDeviceAddr);
777 
778         ipmi::setDbusProperty(bus, chassisCapObject.second,
779                               chassisCapObject.first, chassisCapIntf,
780                               chassisSDRDevAddrProp, sdrDeviceAddr);
781 
782         ipmi::setDbusProperty(bus, chassisCapObject.second,
783                               chassisCapObject.first, chassisCapIntf,
784                               chassisSELDevAddrProp, selDeviceAddr);
785 
786         ipmi::setDbusProperty(bus, chassisCapObject.second,
787                               chassisCapObject.first, chassisCapIntf,
788                               chassisSMDevAddrProp, smDeviceAddr);
789 
790         ipmi::setDbusProperty(bus, chassisCapObject.second,
791                               chassisCapObject.first, chassisCapIntf,
792                               chassisBridgeDevAddrProp, bridgeDeviceAddr);
793     }
794     catch (const std::exception& e)
795     {
796         lg2::error("Failed to set chassis capability properties: {ERR}", "ERR",
797                    e);
798         return ipmi::responseUnspecifiedError();
799     }
800     return ipmi::responseSuccess();
801 }
802 
803 //------------------------------------------
804 // Calls into Host State Manager Dbus object
805 //------------------------------------------
initiateHostStateTransition(ipmi::Context::ptr & ctx,State::Host::Transition transition)806 int initiateHostStateTransition(ipmi::Context::ptr& ctx,
807                                 State::Host::Transition transition)
808 {
809     // OpenBMC Host State Manager dbus framework
810     constexpr auto hostStatePath = "/xyz/openbmc_project/state/host0";
811     constexpr auto hostStateIntf = "xyz.openbmc_project.State.Host";
812 
813     // Convert to string equivalent of the passed in transition enum.
814     auto request =
815         sdbusplus::common::xyz::openbmc_project::state::convertForMessage(
816             transition);
817 
818     std::string service;
819     boost::system::error_code ec =
820         ipmi::getService(ctx, hostStateIntf, hostStatePath, service);
821 
822     if (!ec)
823     {
824         ec = ipmi::setDbusProperty(ctx, service, hostStatePath, hostStateIntf,
825                                    "RequestedHostTransition", request);
826     }
827     if (ec)
828     {
829         lg2::error(
830             "Failed to initiate transition for request {REQUEST}: {EXCEPTION}",
831             "REQUEST", request, "EXCEPTION", ec.message());
832         return -1;
833     }
834     lg2::info(
835         "Transition request {REQUEST} initiated successfully by user {USERID}",
836         "REQUEST", request, "USERID", ctx->userId);
837     return 0;
838 }
839 
840 //------------------------------------------
841 // Calls into Chassis State Manager Dbus object
842 //------------------------------------------
initiateChassisStateTransition(ipmi::Context::ptr & ctx,State::Chassis::Transition transition)843 int initiateChassisStateTransition(ipmi::Context::ptr& ctx,
844                                    State::Chassis::Transition transition)
845 {
846     // OpenBMC Chassis State Manager dbus framework
847     constexpr auto chassisStatePath = "/xyz/openbmc_project/state/chassis0";
848     constexpr auto chassisStateIntf = "xyz.openbmc_project.State.Chassis";
849 
850     std::string service;
851     boost::system::error_code ec =
852         ipmi::getService(ctx, chassisStateIntf, chassisStatePath, service);
853 
854     // Convert to string equivalent of the passed in transition enum.
855     auto request =
856         sdbusplus::common::xyz::openbmc_project::state::convertForMessage(
857             transition);
858 
859     if (!ec)
860     {
861         ec = ipmi::setDbusProperty(ctx, service, chassisStatePath,
862                                    chassisStateIntf, "RequestedPowerTransition",
863                                    request);
864     }
865     if (ec)
866     {
867         lg2::error("Failed to initiate transition {REQUEST}: {EXCEPTION}",
868                    "REQUEST", request, "EXCEPTION", ec.message());
869 
870         return -1;
871     }
872 
873     return 0;
874 }
875 
876 //------------------------------------------
877 // Trigger an NMI on the host via dbus
878 //------------------------------------------
doNmi(ipmi::Context::ptr & ctx)879 static int doNmi(ipmi::Context::ptr& ctx)
880 {
881     constexpr const char* nmiIntfName = "xyz.openbmc_project.Control.Host.NMI";
882     ipmi::DbusObjectInfo nmiObj{};
883     boost::system::error_code ec;
884 
885     ec = ipmi::getDbusObject(ctx, nmiIntfName, nmiObj);
886     if (ec)
887     {
888         lg2::error("Failed to find NMI service: {ERROR}", "ERROR",
889                    ec.message());
890         return -1;
891     }
892 
893     ctx->bus->yield_method_call<void>(ctx->yield, ec, nmiObj.second,
894                                       nmiObj.first, nmiIntfName, "NMI");
895     if (ec)
896     {
897         lg2::error("NMI call failed: {ERROR}", "ERROR", ec.message());
898         elog<InternalFailure>();
899         return -1;
900     }
901 
902     return 0;
903 }
904 
905 namespace power_policy
906 {
907 
908 using namespace sdbusplus::server::xyz::openbmc_project::control::power;
909 using IpmiValue = uint8_t;
910 using DbusValue = RestorePolicy::Policy;
911 
912 const std::map<DbusValue, IpmiValue> dbusToIpmi = {
913     {RestorePolicy::Policy::AlwaysOff, 0x00},
914     {RestorePolicy::Policy::Restore, 0x01},
915     {RestorePolicy::Policy::AlwaysOn, 0x02},
916     {RestorePolicy::Policy::None, 0x03}};
917 
918 static constexpr uint8_t noChange = 0x03;
919 static constexpr uint8_t allSupport = 0x01 | 0x02 | 0x04;
920 
921 /* helper function for Get Chassis Status Command
922  */
getPowerRestorePolicy()923 std::optional<uint2_t> getPowerRestorePolicy()
924 {
925     uint2_t restorePolicy = 0;
926     using namespace chassis::internal;
927 
928     settings::Objects& objects = cache::getObjects();
929 
930     try
931     {
932         const auto& powerRestoreSetting =
933             objects.map.at(powerRestoreIntf).front();
934         ipmi::Value result = ipmi::getDbusProperty(
935             *getSdBus(),
936             objects.service(powerRestoreSetting, powerRestoreIntf).c_str(),
937             powerRestoreSetting.c_str(), powerRestoreIntf,
938             "PowerRestorePolicy");
939         auto powerRestore = RestorePolicy::convertPolicyFromString(
940             std::get<std::string>(result));
941         restorePolicy = dbusToIpmi.at(powerRestore);
942     }
943     catch (const std::exception& e)
944     {
945         lg2::error(
946             "Failed to fetch pgood property ({PATH}/{INTERFACE}): {ERROR}",
947             "PATH", objects.map.at(powerRestoreIntf).front(), "INTERFACE",
948             powerRestoreIntf, "ERROR", e);
949         cache::objectsPtr.reset();
950         return std::nullopt;
951     }
952     return std::make_optional(restorePolicy);
953 }
954 
955 /*
956  * getPowerStatus
957  * helper function for Get Chassis Status Command
958  * return - optional value for pgood (no value on error)
959  */
getPowerStatus()960 std::optional<bool> getPowerStatus()
961 {
962     bool powerGood = false;
963     std::shared_ptr<sdbusplus::asio::connection> busp = getSdBus();
964     try
965     {
966         constexpr const char* chassisStatePath =
967             "/xyz/openbmc_project/state/chassis0";
968         constexpr const char* chassisStateIntf =
969             "xyz.openbmc_project.State.Chassis";
970         auto service =
971             ipmi::getService(*busp, chassisStateIntf, chassisStatePath);
972 
973         ipmi::Value powerState =
974             ipmi::getDbusProperty(*busp, service, chassisStatePath,
975                                   chassisStateIntf, "CurrentPowerState");
976         powerGood = std::get<std::string>(powerState) ==
977                     "xyz.openbmc_project.State.Chassis.PowerState.On";
978     }
979     catch (const std::exception& e)
980     {
981         try
982         {
983             // FIXME: some legacy modules use the older path; try that next
984             constexpr const char* legacyPwrCtrlObj =
985                 "/org/openbmc/control/power0";
986             constexpr const char* legacyPwrCtrlIntf =
987                 "org.openbmc.control.Power";
988             auto service =
989                 ipmi::getService(*busp, legacyPwrCtrlIntf, legacyPwrCtrlObj);
990 
991             ipmi::Value variant = ipmi::getDbusProperty(
992                 *busp, service, legacyPwrCtrlObj, legacyPwrCtrlIntf, "pgood");
993             powerGood = static_cast<bool>(std::get<int>(variant));
994         }
995         catch (const std::exception& e)
996         {
997             lg2::error("Failed to fetch pgood property: {ERROR}", "ERROR", e);
998             return std::nullopt;
999         }
1000     }
1001     return std::make_optional(powerGood);
1002 }
1003 
1004 /*
1005  * getACFailStatus
1006  * helper function for Get Chassis Status Command
1007  * return - bool value for ACFail (false on error)
1008  */
getACFailStatus()1009 bool getACFailStatus()
1010 {
1011     constexpr const char* powerControlObj =
1012         "/xyz/openbmc_project/Chassis/Control/Power0";
1013     constexpr const char* powerControlIntf =
1014         "xyz.openbmc_project.Chassis.Control.Power";
1015     bool acFail = false;
1016     std::shared_ptr<sdbusplus::asio::connection> bus = getSdBus();
1017     try
1018     {
1019         auto service =
1020             ipmi::getService(*bus, powerControlIntf, powerControlObj);
1021 
1022         ipmi::Value variant = ipmi::getDbusProperty(
1023             *bus, service, powerControlObj, powerControlIntf, "PFail");
1024         acFail = std::get<bool>(variant);
1025     }
1026     catch (const std::exception& e)
1027     {
1028         lg2::error(
1029             "Failed to fetch PFail property ({PATH}/{INTERFAC}): {ERROR}",
1030             "PATH", powerControlObj, "INTERFACE", powerControlIntf, "ERROR", e);
1031     }
1032     return acFail;
1033 }
1034 } // namespace power_policy
1035 
getButtonEnabled(const std::string & buttonPath,const std::string & buttonIntf)1036 static std::optional<bool> getButtonEnabled(const std::string& buttonPath,
1037                                             const std::string& buttonIntf)
1038 {
1039     std::shared_ptr<sdbusplus::asio::connection> busp = getSdBus();
1040     bool buttonDisabled = false;
1041     try
1042     {
1043         auto service = ipmi::getService(*busp, buttonIntf, buttonPath);
1044         ipmi::Value enabled = ipmi::getDbusProperty(*busp, service, buttonPath,
1045                                                     buttonIntf, "Enabled");
1046         buttonDisabled = !std::get<bool>(enabled);
1047     }
1048     catch (const sdbusplus::exception_t& e)
1049     {
1050         lg2::error("Fail to get button Enabled property ({PATH}): {ERROR}",
1051                    "PATH", buttonPath, "ERROR", e);
1052         return std::nullopt;
1053     }
1054     return std::make_optional(buttonDisabled);
1055 }
1056 
setButtonEnabled(ipmi::Context::ptr & ctx,const std::string & buttonPath,const std::string & buttonIntf,bool enable)1057 static bool setButtonEnabled(ipmi::Context::ptr& ctx,
1058                              const std::string& buttonPath,
1059                              const std::string& buttonIntf, bool enable)
1060 {
1061     std::string service;
1062     boost::system::error_code ec;
1063     ec = ipmi::getService(ctx, buttonIntf, buttonPath, service);
1064     if (!ec)
1065     {
1066         ec = ipmi::setDbusProperty(ctx, service, buttonPath, buttonIntf,
1067                                    "Enabled", enable);
1068     }
1069     if (ec)
1070     {
1071         lg2::error(
1072             "Fail to set button Enabled property ({SERVICE}:{PATH}): {ERROR}",
1073             "SERVICE", service, "PATH", buttonPath, "ERROR", ec.message());
1074         return false;
1075     }
1076     return true;
1077 }
1078 
getChassisIntrusionStatus(ipmi::Context::ptr & ctx)1079 static std::optional<bool> getChassisIntrusionStatus(ipmi::Context::ptr& ctx)
1080 {
1081     constexpr const char* chassisIntrusionPath =
1082         "/xyz/openbmc_project/Chassis/Intrusion";
1083     constexpr const char* chassisIntrusionInf =
1084         "xyz.openbmc_project.Chassis.Intrusion";
1085 
1086     std::string service;
1087     boost::system::error_code ec = ipmi::getService(
1088         ctx, chassisIntrusionInf, chassisIntrusionPath, service);
1089     if (!ec)
1090     {
1091         std::string chassisIntrusionStr;
1092         ec = ipmi::getDbusProperty<std::string>(
1093             ctx, service, chassisIntrusionPath, chassisIntrusionInf, "Status",
1094             chassisIntrusionStr);
1095         if (!ec)
1096         {
1097             bool ret =
1098                 (chassisIntrusionStr == "HardwareIntrusion") ? true : false;
1099             return std::make_optional(ret);
1100         }
1101     }
1102     lg2::error("Fail to get Chassis Intrusion Status property "
1103                "({PATH}/{INTERFACE}): {ERROR}",
1104                "PATH", chassisIntrusionPath, "INTERFACE", chassisIntrusionInf,
1105                "ERROR", ec.message());
1106     return std::nullopt;
1107 }
1108 
1109 //----------------------------------------------------------------------
1110 // Get Chassis Status commands
1111 //----------------------------------------------------------------------
1112 ipmi::RspType<bool,    // Power is on
1113               bool,    // Power overload
1114               bool,    // Interlock
1115               bool,    // power fault
1116               bool,    // power control fault
1117               uint2_t, // power restore policy
1118               bool,    // reserved
1119 
1120               bool,    // AC failed
1121               bool,    // last power down caused by a Power overload
1122               bool,    // last power down caused by a power interlock
1123               bool,    // last power down caused by power fault
1124               bool, // last ‘Power is on’ state was entered via IPMI command
1125               uint3_t, // reserved
1126 
1127               bool,    // Chassis intrusion active
1128               bool,    // Front Panel Lockout active
1129               bool,    // Drive Fault
1130               bool,    // Cooling/fan fault detected
1131               uint2_t, // Chassis Identify State
1132               bool,    // Chassis Identify command and state info supported
1133               bool,    // reserved
1134 
1135               bool,    // Power off button disabled
1136               bool,    // Reset button disabled
1137               bool,    // Diagnostic Interrupt button disabled
1138               bool,    // Standby (sleep) button disabled
1139               bool,    // Power off button disable allowed
1140               bool,    // Reset button disable allowed
1141               bool,    // Diagnostic Interrupt button disable allowed
1142               bool     // Standby (sleep) button disable allowed
1143               >
ipmiGetChassisStatus(ipmi::Context::ptr & ctx)1144     ipmiGetChassisStatus(ipmi::Context::ptr& ctx)
1145 {
1146     using namespace chassis::internal;
1147     std::optional<uint2_t> restorePolicy =
1148         power_policy::getPowerRestorePolicy();
1149     std::optional<bool> powerGood = power_policy::getPowerStatus();
1150     if (!restorePolicy || !powerGood)
1151     {
1152         return ipmi::responseUnspecifiedError();
1153     }
1154 
1155     //  Front Panel Button Capabilities and disable/enable status(Optional)
1156     std::optional<bool> powerButtonReading =
1157         getButtonEnabled(powerButtonPath, powerButtonIntf);
1158     // allow disable if the interface is present
1159     bool powerButtonDisableAllow = static_cast<bool>(powerButtonReading);
1160     // default return the button is enabled (not disabled)
1161     bool powerButtonDisabled = false;
1162     if (powerButtonDisableAllow)
1163     {
1164         // return the real value of the button status, if present
1165         powerButtonDisabled = *powerButtonReading;
1166     }
1167 
1168     std::optional<bool> resetButtonReading =
1169         getButtonEnabled(resetButtonPath, resetButtonIntf);
1170     // allow disable if the interface is present
1171     bool resetButtonDisableAllow = static_cast<bool>(resetButtonReading);
1172     // default return the button is enabled (not disabled)
1173     bool resetButtonDisabled = false;
1174     if (resetButtonDisableAllow)
1175     {
1176         // return the real value of the button status, if present
1177         resetButtonDisabled = *resetButtonReading;
1178     }
1179 
1180     bool powerDownAcFailed = power_policy::getACFailStatus();
1181 
1182     bool chassisIntrusionActive = false;
1183     std::optional<bool> chassisIntrusionStatus = getChassisIntrusionStatus(ctx);
1184     if (chassisIntrusionStatus)
1185     {
1186         chassisIntrusionActive = chassisIntrusionStatus.value();
1187     }
1188 
1189     // This response has a lot of hard-coded, unsupported fields
1190     // They are set to false or 0
1191     constexpr bool powerOverload = false;
1192     constexpr bool chassisInterlock = false;
1193     constexpr bool powerFault = false;
1194     constexpr bool powerControlFault = false;
1195     constexpr bool powerDownOverload = false;
1196     constexpr bool powerDownInterlock = false;
1197     constexpr bool powerDownPowerFault = false;
1198     constexpr bool powerStatusIPMI = false;
1199     constexpr bool frontPanelLockoutActive = false;
1200     constexpr bool driveFault = false;
1201     constexpr bool coolingFanFault = false;
1202     // chassisIdentifySupport set because this command is implemented
1203     constexpr bool chassisIdentifySupport = true;
1204     uint2_t chassisIdentifyState = types::enum_cast<uint2_t>(chassisIDState);
1205     constexpr bool diagButtonDisabled = false;
1206     constexpr bool sleepButtonDisabled = false;
1207     constexpr bool diagButtonDisableAllow = false;
1208     constexpr bool sleepButtonDisableAllow = false;
1209 
1210     return ipmi::responseSuccess(
1211         *powerGood, powerOverload, chassisInterlock, powerFault,
1212         powerControlFault, *restorePolicy,
1213         false, // reserved
1214 
1215         powerDownAcFailed, powerDownOverload, powerDownInterlock,
1216         powerDownPowerFault, powerStatusIPMI,
1217         uint3_t(0), // reserved
1218 
1219         chassisIntrusionActive, frontPanelLockoutActive, driveFault,
1220         coolingFanFault, chassisIdentifyState, chassisIdentifySupport,
1221         false, // reserved
1222 
1223         powerButtonDisabled, resetButtonDisabled, diagButtonDisabled,
1224         sleepButtonDisabled, powerButtonDisableAllow, resetButtonDisableAllow,
1225         diagButtonDisableAllow, sleepButtonDisableAllow);
1226 }
1227 
1228 enum class IpmiRestartCause
1229 {
1230     Unknown = 0x0,
1231     RemoteCommand = 0x1,
1232     ResetButton = 0x2,
1233     PowerButton = 0x3,
1234     WatchdogTimer = 0x4,
1235     PowerPolicyAlwaysOn = 0x6,
1236     PowerPolicyPreviousState = 0x7,
1237     SoftReset = 0xa,
1238 };
1239 
1240 static IpmiRestartCause
restartCauseToIpmiRestartCause(State::Host::RestartCause cause)1241     restartCauseToIpmiRestartCause(State::Host::RestartCause cause)
1242 {
1243     switch (cause)
1244     {
1245         case State::Host::RestartCause::Unknown:
1246         {
1247             return IpmiRestartCause::Unknown;
1248         }
1249         case State::Host::RestartCause::RemoteCommand:
1250         {
1251             return IpmiRestartCause::RemoteCommand;
1252         }
1253         case State::Host::RestartCause::ResetButton:
1254         {
1255             return IpmiRestartCause::ResetButton;
1256         }
1257         case State::Host::RestartCause::PowerButton:
1258         {
1259             return IpmiRestartCause::PowerButton;
1260         }
1261         case State::Host::RestartCause::WatchdogTimer:
1262         {
1263             return IpmiRestartCause::WatchdogTimer;
1264         }
1265         case State::Host::RestartCause::PowerPolicyAlwaysOn:
1266         {
1267             return IpmiRestartCause::PowerPolicyAlwaysOn;
1268         }
1269         case State::Host::RestartCause::PowerPolicyPreviousState:
1270         {
1271             return IpmiRestartCause::PowerPolicyPreviousState;
1272         }
1273         case State::Host::RestartCause::SoftReset:
1274         {
1275             return IpmiRestartCause::SoftReset;
1276         }
1277         default:
1278         {
1279             return IpmiRestartCause::Unknown;
1280         }
1281     }
1282 }
1283 
1284 /*
1285  * getRestartCause
1286  * helper function for Get Host restart cause Command
1287  * return - optional value for RestartCause (no value on error)
1288  */
getRestartCause(ipmi::Context::ptr ctx)1289 static std::optional<uint4_t> getRestartCause(ipmi::Context::ptr ctx)
1290 {
1291     constexpr const char* restartCausePath = "/xyz/openbmc_project/state/host0";
1292     constexpr const char* restartCauseIntf = "xyz.openbmc_project.State.Host";
1293 
1294     std::string service;
1295     boost::system::error_code ec =
1296         ipmi::getService(ctx, restartCauseIntf, restartCausePath, service);
1297     if (!ec)
1298     {
1299         std::string restartCauseStr;
1300         ec = ipmi::getDbusProperty<std::string>(
1301             ctx, service, restartCausePath, restartCauseIntf, "RestartCause",
1302             restartCauseStr);
1303         if (!ec)
1304         {
1305             auto cause =
1306                 State::Host::convertRestartCauseFromString(restartCauseStr);
1307             return types::enum_cast<uint4_t>(
1308                 restartCauseToIpmiRestartCause(cause));
1309         }
1310     }
1311 
1312     lg2::error(
1313         "Failed to fetch RestartCause property ({PATH}/{INTERFACE}): {ERROR}",
1314         "ERROR", ec.message(), "PATH", restartCausePath, "INTERFACE",
1315         restartCauseIntf);
1316     return std::nullopt;
1317 }
1318 
1319 ipmi::RspType<uint4_t, // Restart Cause
1320               uint4_t, // reserved
1321               uint8_t  // channel number (not supported)
1322               >
ipmiGetSystemRestartCause(ipmi::Context::ptr ctx)1323     ipmiGetSystemRestartCause(ipmi::Context::ptr ctx)
1324 {
1325     std::optional<uint4_t> cause = getRestartCause(ctx);
1326     if (!cause)
1327     {
1328         return ipmi::responseUnspecifiedError();
1329     }
1330 
1331     constexpr uint4_t reserved = 0;
1332     auto channel = static_cast<uint8_t>(ctx->channel);
1333     return ipmi::responseSuccess(cause.value(), reserved, channel);
1334 }
1335 /** @brief Implementation of chassis control command
1336  *
1337  *  @param - chassisControl command byte
1338  *
1339  *  @return  Success or InvalidFieldRequest.
1340  */
ipmiChassisControl(ipmi::Context::ptr & ctx,uint8_t chassisControl)1341 ipmi::RspType<> ipmiChassisControl(ipmi::Context::ptr& ctx,
1342                                    uint8_t chassisControl)
1343 {
1344     int rc = 0;
1345     switch (chassisControl)
1346     {
1347         case CMD_POWER_ON:
1348             rc = initiateHostStateTransition(ctx, State::Host::Transition::On);
1349             break;
1350         case CMD_POWER_OFF:
1351             rc = initiateChassisStateTransition(
1352                 ctx, State::Chassis::Transition::Off);
1353             break;
1354         case CMD_HARD_RESET:
1355             rc = initiateHostStateTransition(
1356                 ctx, State::Host::Transition::ForceWarmReboot);
1357             break;
1358         case CMD_POWER_CYCLE:
1359             rc = initiateHostStateTransition(ctx,
1360                                              State::Host::Transition::Reboot);
1361             break;
1362         case CMD_SOFT_OFF_VIA_OVER_TEMP:
1363             rc = initiateHostStateTransition(ctx, State::Host::Transition::Off);
1364             break;
1365         case CMD_PULSE_DIAGNOSTIC_INTR:
1366             rc = doNmi(ctx);
1367             break;
1368 
1369         default:
1370         {
1371             lg2::error("Invalid Chassis Control command: {CMD}", "CMD",
1372                        lg2::hex, chassisControl);
1373             return ipmi::responseInvalidFieldRequest();
1374         }
1375     }
1376 
1377     return ((rc < 0) ? ipmi::responseUnspecifiedError()
1378                      : ipmi::responseSuccess());
1379 }
1380 
1381 /** @brief Return D-Bus connection string to enclosure identify LED object
1382  *
1383  *  @param[in, out] connection - connection to D-Bus object
1384  *  @return a IPMI return code
1385  */
getEnclosureIdentifyConnection()1386 std::string getEnclosureIdentifyConnection()
1387 {
1388     // lookup enclosure_identify group owner(s) in mapper
1389     try
1390     {
1391         return ipmi::getService(*getSdBus(), "xyz.openbmc_project.Led.Group",
1392                                 identify_led_object_name);
1393     }
1394     catch (const std::exception& e)
1395     {
1396         lg2::error("Chassis Identify: Error communicating to mapper: {ERROR}",
1397                    "ERROR", e);
1398         elog<InternalFailure>();
1399     }
1400 }
1401 
1402 /** @brief Turn On/Off enclosure identify LED
1403  *
1404  *  @param[in] flag - true to turn on LED, false to turn off
1405  *  @return a IPMI return code
1406  */
enclosureIdentifyLed(bool flag)1407 void enclosureIdentifyLed(bool flag)
1408 {
1409     using namespace chassis::internal;
1410     try
1411     {
1412         std::string connection = getEnclosureIdentifyConnection();
1413 
1414         auto msg = std::string("enclosureIdentifyLed(") +
1415                    boost::lexical_cast<std::string>(flag) + ")";
1416         lg2::debug(msg.c_str());
1417 
1418         ipmi::setDbusProperty(*getSdBus(), connection, identify_led_object_name,
1419                               "xyz.openbmc_project.Led.Group", "Asserted",
1420                               flag);
1421     }
1422     catch (const std::exception& e)
1423     {
1424         lg2::error("Chassis Identify: Error Setting State {LED_STATE}: {ERROR}",
1425                    "LED_STATE", flag, "ERROR", e);
1426         elog<InternalFailure>();
1427     }
1428 }
1429 
1430 /** @brief Callback method to turn off LED
1431  */
enclosureIdentifyLedOff()1432 void enclosureIdentifyLedOff()
1433 {
1434     try
1435     {
1436         chassisIDState = ChassisIDState::off;
1437         enclosureIdentifyLed(false);
1438     }
1439     catch (const InternalFailure& e)
1440     {
1441         report<InternalFailure>();
1442     }
1443 }
1444 
1445 /** @brief Create timer to turn on and off the enclosure LED
1446  */
createIdentifyTimer()1447 void createIdentifyTimer()
1448 {
1449     if (!identifyTimer)
1450     {
1451         identifyTimer =
1452             std::make_unique<sdbusplus::Timer>(enclosureIdentifyLedOff);
1453     }
1454 }
1455 
ipmiChassisIdentify(std::optional<uint8_t> interval,std::optional<uint8_t> force)1456 ipmi::RspType<> ipmiChassisIdentify(std::optional<uint8_t> interval,
1457                                     std::optional<uint8_t> force)
1458 {
1459     uint8_t identifyInterval = interval.value_or(DEFAULT_IDENTIFY_TIME_OUT);
1460     bool forceIdentify = force.value_or(0) & 0x01;
1461 
1462     if (identifyInterval || forceIdentify)
1463     {
1464         // stop the timer if already started;
1465         // for force identify we should not turn off LED
1466         identifyTimer->stop();
1467         try
1468         {
1469             chassisIDState = ChassisIDState::temporaryOn;
1470             enclosureIdentifyLed(true);
1471         }
1472         catch (const InternalFailure& e)
1473         {
1474             report<InternalFailure>();
1475             return ipmi::responseResponseError();
1476         }
1477 
1478         if (forceIdentify)
1479         {
1480             chassisIDState = ChassisIDState::indefiniteOn;
1481             return ipmi::responseSuccess();
1482         }
1483         // start the timer
1484         auto time = std::chrono::duration_cast<std::chrono::microseconds>(
1485             std::chrono::seconds(identifyInterval));
1486         identifyTimer->start(time);
1487     }
1488     else if (!identifyInterval)
1489     {
1490         identifyTimer->stop();
1491         enclosureIdentifyLedOff();
1492     }
1493     return ipmi::responseSuccess();
1494 }
1495 
1496 namespace boot_options
1497 {
1498 
1499 using namespace sdbusplus::server::xyz::openbmc_project::control::boot;
1500 using IpmiValue = uint8_t;
1501 constexpr auto ipmiDefault = 0;
1502 
1503 std::map<IpmiValue, Type::Types> typeIpmiToDbus = {{0x00, Type::Types::Legacy},
1504                                                    {0x01, Type::Types::EFI}};
1505 
1506 std::map<IpmiValue, Source::Sources> sourceIpmiToDbus = {
1507     {0x01, Source::Sources::Network},
1508     {0x02, Source::Sources::Disk},
1509     {0x05, Source::Sources::ExternalMedia},
1510     {0x0f, Source::Sources::RemovableMedia},
1511     {ipmiDefault, Source::Sources::Default}};
1512 
1513 std::map<IpmiValue, Mode::Modes> modeIpmiToDbus = {
1514 #ifdef ENABLE_BOOT_FLAG_SAFE_MODE_SUPPORT
1515     {0x03, Mode::Modes::Safe},
1516 #endif // ENABLE_BOOT_SAFE_MODE_SUPPORT
1517     {0x06, Mode::Modes::Setup},
1518     {ipmiDefault, Mode::Modes::Regular}};
1519 
1520 std::map<Type::Types, IpmiValue> typeDbusToIpmi = {{Type::Types::Legacy, 0x00},
1521                                                    {Type::Types::EFI, 0x01}};
1522 
1523 std::map<Source::Sources, IpmiValue> sourceDbusToIpmi = {
1524     {Source::Sources::Network, 0x01},
1525     {Source::Sources::Disk, 0x02},
1526     {Source::Sources::ExternalMedia, 0x05},
1527     {Source::Sources::RemovableMedia, 0x0f},
1528     {Source::Sources::Default, ipmiDefault}};
1529 
1530 std::map<Mode::Modes, IpmiValue> modeDbusToIpmi = {
1531 #ifdef ENABLE_BOOT_FLAG_SAFE_MODE_SUPPORT
1532     {Mode::Modes::Safe, 0x03},
1533 #endif // ENABLE_BOOT_SAFE_MODE_SUPPORT
1534     {Mode::Modes::Setup, 0x06},
1535     {Mode::Modes::Regular, ipmiDefault}};
1536 
1537 } // namespace boot_options
1538 
1539 /** @brief Get the property value for boot source
1540  *  @param[in] ctx - context pointer
1541  *  @param[out] source - boot source value
1542  *  @return On failure return IPMI error.
1543  */
getBootSource(ipmi::Context::ptr & ctx,Source::Sources & source)1544 static ipmi::Cc getBootSource(ipmi::Context::ptr& ctx, Source::Sources& source)
1545 {
1546     using namespace chassis::internal;
1547     std::string result;
1548     std::string service;
1549     boost::system::error_code ec =
1550         getService(ctx, bootSourceIntf, bootSettingsPath, service);
1551     if (!ec)
1552     {
1553         ec = ipmi::getDbusProperty(ctx, service, bootSettingsPath,
1554                                    bootSourceIntf, "BootSource", result);
1555         if (!ec)
1556         {
1557             source = Source::convertSourcesFromString(result);
1558             return ipmi::ccSuccess;
1559         }
1560     }
1561     lg2::error("Error in BootSource Get: {ERROR}", "ERROR", ec.message());
1562     return ipmi::ccUnspecifiedError;
1563 }
1564 
1565 /** @brief Set the property value for boot source
1566  *  @param[in] ctx - context pointer
1567  *  @param[in] source - boot source value
1568  *  @return On failure return IPMI error.
1569  */
setBootSource(ipmi::Context::ptr & ctx,const Source::Sources & source)1570 static ipmi::Cc setBootSource(ipmi::Context::ptr& ctx,
1571                               const Source::Sources& source)
1572 {
1573     using namespace chassis::internal;
1574     std::string service;
1575     boost::system::error_code ec =
1576         getService(ctx, bootSourceIntf, bootSettingsPath, service);
1577     if (!ec)
1578     {
1579         ec = ipmi::setDbusProperty(ctx, service, bootSettingsPath,
1580                                    bootSourceIntf, "BootSource",
1581                                    convertForMessage(source));
1582         if (!ec)
1583         {
1584             return ipmi::ccSuccess;
1585         }
1586     }
1587     lg2::error("Error in BootSource Set: {ERROR}", "ERROR", ec.message());
1588     return ipmi::ccUnspecifiedError;
1589 }
1590 
1591 /** @brief Get the property value for boot mode
1592  *  @param[in] ctx - context pointer
1593  *  @param[out] mode - boot mode value
1594  *  @return On failure return IPMI error.
1595  */
getBootMode(ipmi::Context::ptr & ctx,Mode::Modes & mode)1596 static ipmi::Cc getBootMode(ipmi::Context::ptr& ctx, Mode::Modes& mode)
1597 {
1598     using namespace chassis::internal;
1599     std::string result;
1600     std::string service;
1601     boost::system::error_code ec =
1602         getService(ctx, bootModeIntf, bootSettingsPath, service);
1603     if (!ec)
1604     {
1605         ec = ipmi::getDbusProperty(ctx, service, bootSettingsPath, bootModeIntf,
1606                                    "BootMode", result);
1607         if (!ec)
1608         {
1609             mode = Mode::convertModesFromString(result);
1610             return ipmi::ccSuccess;
1611         }
1612     }
1613     lg2::error("Error in BootMode Get: {ERROR}", "ERROR", ec.message());
1614     return ipmi::ccUnspecifiedError;
1615 }
1616 
1617 /** @brief Set the property value for boot mode
1618  *  @param[in] ctx - context pointer
1619  *  @param[in] mode - boot mode value
1620  *  @return On failure return IPMI error.
1621  */
setBootMode(ipmi::Context::ptr & ctx,const Mode::Modes & mode)1622 static ipmi::Cc setBootMode(ipmi::Context::ptr& ctx, const Mode::Modes& mode)
1623 {
1624     using namespace chassis::internal;
1625     std::string service;
1626     boost::system::error_code ec =
1627         getService(ctx, bootModeIntf, bootSettingsPath, service);
1628     if (!ec)
1629     {
1630         ec = ipmi::setDbusProperty(ctx, service, bootSettingsPath, bootModeIntf,
1631                                    "BootMode", convertForMessage(mode));
1632         if (!ec)
1633         {
1634             return ipmi::ccSuccess;
1635         }
1636     }
1637     lg2::error("Error in BootMode Set: {ERROR}", "ERROR", ec.message());
1638     return ipmi::ccUnspecifiedError;
1639 }
1640 
1641 /** @brief Get the property value for boot type
1642  *  @param[in] ctx - context pointer
1643  *  @param[out] type - boot type value
1644  *  @return On failure return IPMI error.
1645  */
getBootType(ipmi::Context::ptr & ctx,Type::Types & type)1646 static ipmi::Cc getBootType(ipmi::Context::ptr& ctx, Type::Types& type)
1647 {
1648     using namespace chassis::internal;
1649     std::string result;
1650     std::string service;
1651     boost::system::error_code ec =
1652         getService(ctx, bootTypeIntf, bootSettingsPath, service);
1653 
1654     // Don't throw error if BootType interface is not present.
1655     // This interface is not relevant for some Host architectures
1656     // (for example POWER). In this case we don't won't IPMI to
1657     // return an error, but simply return bootType as EFI.
1658     type = Type::Types::EFI;
1659     if (!ec)
1660     {
1661         ec = ipmi::getDbusProperty(ctx, service, bootSettingsPath, bootTypeIntf,
1662                                    "BootType", result);
1663         if (ec)
1664         {
1665             lg2::error("Error in BootType Get: {ERROR}", "ERROR", ec.message());
1666             return ipmi::ccUnspecifiedError;
1667         }
1668         type = Type::convertTypesFromString(result);
1669     }
1670 
1671     return ipmi::ccSuccess;
1672 }
1673 
1674 /** @brief Set the property value for boot type
1675  *  @param[in] ctx - context pointer
1676  *  @param[in] type - boot type value
1677  *  @return On failure return IPMI error.
1678  */
setBootType(ipmi::Context::ptr & ctx,const Type::Types & type)1679 static ipmi::Cc setBootType(ipmi::Context::ptr& ctx, const Type::Types& type)
1680 {
1681     using namespace chassis::internal;
1682     std::string service;
1683     boost::system::error_code ec =
1684         getService(ctx, bootTypeIntf, bootSettingsPath, service);
1685     if (!ec)
1686     {
1687         ec = ipmi::setDbusProperty(ctx, service, bootSettingsPath, bootTypeIntf,
1688                                    "BootType", convertForMessage(type));
1689         if (ec)
1690         {
1691             lg2::error("Error in BootType Set: {ERROR}", "ERROR", ec.message());
1692             return ipmi::ccUnspecifiedError;
1693         }
1694     }
1695     // Don't throw error if BootType interface is not present.
1696     // This interface is not relevant for some Host architectures
1697     // (for example POWER). In this case we don't won't IPMI to
1698     // return an error, but want to just skip this function.
1699     return ipmi::ccSuccess;
1700 }
1701 
1702 /** @brief Get the property value for boot override enable
1703  *  @param[in] ctx - context pointer
1704  *  @param[out] enable - boot override enable
1705  *  @return On failure return IPMI error.
1706  */
getBootEnable(ipmi::Context::ptr & ctx,bool & enable)1707 static ipmi::Cc getBootEnable(ipmi::Context::ptr& ctx, bool& enable)
1708 {
1709     using namespace chassis::internal;
1710     std::string result;
1711     std::string service;
1712     boost::system::error_code ec =
1713         getService(ctx, bootEnableIntf, bootSettingsPath, service);
1714     if (!ec)
1715     {
1716         ec = ipmi::getDbusProperty(ctx, service, bootSettingsPath,
1717                                    bootEnableIntf, "Enabled", enable);
1718         if (!ec)
1719         {
1720             return ipmi::ccSuccess;
1721         }
1722     }
1723     lg2::error("Error in Boot Override Enable Get: {ERROR}", "ERROR",
1724                ec.message());
1725     return ipmi::ccUnspecifiedError;
1726 }
1727 
1728 /** @brief Set the property value for boot override enable
1729  *  @param[in] ctx - context pointer
1730  *  @param[in] enable - boot override enable
1731  *  @return On failure return IPMI error.
1732  */
setBootEnable(ipmi::Context::ptr & ctx,const bool & enable)1733 static ipmi::Cc setBootEnable(ipmi::Context::ptr& ctx, const bool& enable)
1734 {
1735     using namespace chassis::internal;
1736     std::string service;
1737     boost::system::error_code ec =
1738         getService(ctx, bootEnableIntf, bootSettingsPath, service);
1739     if (!ec)
1740     {
1741         ec = ipmi::setDbusProperty(ctx, service, bootSettingsPath,
1742                                    bootEnableIntf, "Enabled", enable);
1743         if (!ec)
1744         {
1745             return ipmi::ccSuccess;
1746         }
1747     }
1748     lg2::error("Error in Boot Source Override Enable Set: {ERROR}", "ERROR",
1749                ec.message());
1750     return ipmi::ccUnspecifiedError;
1751 }
1752 
1753 /** @brief Get the property value for boot override one-time
1754  *  @param[in] ctx - context pointer
1755  *  @param[out] onetime - boot override one-time
1756  *  @return On failure return IPMI error.
1757  */
getBootOneTime(ipmi::Context::ptr & ctx,bool & onetime)1758 static ipmi::Cc getBootOneTime(ipmi::Context::ptr& ctx, bool& onetime)
1759 {
1760     using namespace chassis::internal;
1761     std::string result;
1762     std::string service;
1763     boost::system::error_code ec =
1764         getService(ctx, bootOneTimeIntf, bootSettingsOneTimePath, service);
1765     if (!ec)
1766     {
1767         ec = ipmi::getDbusProperty(ctx, service, bootSettingsOneTimePath,
1768                                    bootOneTimeIntf, "Enabled", onetime);
1769         if (!ec)
1770         {
1771             return ipmi::ccSuccess;
1772         }
1773     }
1774     lg2::error("Error in Boot Override OneTime Get: {ERROR}", "ERROR",
1775                ec.message());
1776     return ipmi::ccUnspecifiedError;
1777 }
1778 
1779 /** @brief Set the property value for boot override one-time
1780  *  @param[in] ctx - context pointer
1781  *  @param[in] onetime - boot override one-time
1782  *  @return On failure return IPMI error.
1783  */
setBootOneTime(ipmi::Context::ptr & ctx,const bool & onetime)1784 static ipmi::Cc setBootOneTime(ipmi::Context::ptr& ctx, const bool& onetime)
1785 {
1786     using namespace chassis::internal;
1787     std::string service;
1788     boost::system::error_code ec =
1789         getService(ctx, bootOneTimeIntf, bootSettingsOneTimePath, service);
1790     if (!ec)
1791     {
1792         ec = ipmi::setDbusProperty(ctx, service, bootSettingsOneTimePath,
1793                                    bootOneTimeIntf, "Enabled", onetime);
1794         if (!ec)
1795         {
1796             return ipmi::ccSuccess;
1797         }
1798     }
1799     lg2::error("Error in Boot Source Override OneTime Set: {ERROR}", "ERROR",
1800                ec.message());
1801     return ipmi::ccUnspecifiedError;
1802 }
1803 
1804 static constexpr uint8_t setComplete = 0x0;
1805 static constexpr uint8_t setInProgress = 0x1;
1806 static uint8_t transferStatus = setComplete;
1807 static uint8_t bootFlagValidBitClr = 0;
1808 static uint5_t bootInitiatorAckData = 0x0;
1809 static bool cmosClear = false;
1810 
1811 /** @brief implements the Get Chassis system boot option
1812  *  @param ctx - context pointer
1813  *  @param bootOptionParameter   - boot option parameter selector
1814  *  @param reserved1    - reserved bit
1815  *  @param setSelector  - selects a particular block or set of parameters
1816  *                        under the given parameter selector
1817  *                        write as 00h if parameter doesn't use a setSelector
1818  *  @param blockSelector- selects a particular block within a set of
1819  *                        parameters write as 00h if parameter doesn't use a
1820  *                        blockSelector
1821  *
1822  *  @return IPMI completion code plus response data
1823  *  @return Payload contains below parameters:
1824  *   version             - parameter version
1825  *   bootOptionParameter - boot option parameter selector
1826  *   parmIndicator - parameter valid/invalid indicator
1827  *   data          - configuration parameter data
1828  */
ipmiChassisGetSysBootOptions(ipmi::Context::ptr ctx,uint7_t bootOptionParameter,bool reserved1,uint8_t setSelector,uint8_t blockSelector)1829 ipmi::RspType<ipmi::message::Payload> ipmiChassisGetSysBootOptions(
1830     ipmi::Context::ptr ctx, uint7_t bootOptionParameter, bool reserved1,
1831     [[maybe_unused]] uint8_t setSelector,
1832     [[maybe_unused]] uint8_t blockSelector)
1833 {
1834     ipmi::Cc rc;
1835     if (reserved1)
1836     {
1837         return ipmi::responseInvalidFieldRequest();
1838     }
1839 
1840     constexpr uint4_t version = 0x01;
1841     ipmi::message::Payload response;
1842     response.pack(version, uint4_t{});
1843     using namespace boot_options;
1844 
1845     IpmiValue bootOption = ipmiDefault;
1846 
1847     if (types::enum_cast<BootOptionParameter>(bootOptionParameter) ==
1848         BootOptionParameter::setInProgress)
1849     {
1850         response.pack(bootOptionParameter, reserved1, transferStatus);
1851         return ipmi::responseSuccess(std::move(response));
1852     }
1853 
1854     if (types::enum_cast<BootOptionParameter>(bootOptionParameter) ==
1855         BootOptionParameter::bootInfo)
1856     {
1857         constexpr uint8_t writeMask = 0;
1858         response.pack(bootOptionParameter, reserved1, writeMask,
1859                       bootInitiatorAckData);
1860         return ipmi::responseSuccess(std::move(response));
1861     }
1862 
1863     if (types::enum_cast<BootOptionParameter>(bootOptionParameter) ==
1864         BootOptionParameter::bootFlagValidClr)
1865     {
1866         response.pack(bootOptionParameter, reserved1,
1867                       uint5_t{bootFlagValidBitClr}, uint3_t{});
1868         return ipmi::responseSuccess(std::move(response));
1869     }
1870 
1871     /*
1872      * Parameter #5 means boot flags. Please refer to 28.13 of ipmi doc.
1873      * This is the only parameter used by petitboot.
1874      */
1875     if (types::enum_cast<BootOptionParameter>(bootOptionParameter) ==
1876         BootOptionParameter::bootFlags)
1877     {
1878         using namespace chassis::internal;
1879         using namespace chassis::internal::cache;
1880 
1881         try
1882         {
1883             Source::Sources bootSource;
1884             rc = getBootSource(ctx, bootSource);
1885             if (rc != ipmi::ccSuccess)
1886             {
1887                 return ipmi::response(rc);
1888             }
1889 
1890             Type::Types bootType;
1891             rc = getBootType(ctx, bootType);
1892             if (rc != ipmi::ccSuccess)
1893             {
1894                 return ipmi::response(rc);
1895             }
1896 
1897             Mode::Modes bootMode;
1898             rc = getBootMode(ctx, bootMode);
1899             if (rc != ipmi::ccSuccess)
1900             {
1901                 return ipmi::response(rc);
1902             }
1903 
1904             bootOption = sourceDbusToIpmi.at(bootSource);
1905             if ((Mode::Modes::Regular == bootMode) &&
1906                 (Source::Sources::Default == bootSource))
1907             {
1908                 bootOption = ipmiDefault;
1909             }
1910             else if (Source::Sources::Default == bootSource)
1911             {
1912                 bootOption = modeDbusToIpmi.at(bootMode);
1913             }
1914 
1915             IpmiValue biosBootType = typeDbusToIpmi.at(bootType);
1916 
1917             bool oneTimeEnabled;
1918             rc = getBootOneTime(ctx, oneTimeEnabled);
1919             if (rc != ipmi::ccSuccess)
1920             {
1921                 return ipmi::response(rc);
1922             }
1923 
1924             uint1_t permanent = oneTimeEnabled ? 0 : 1;
1925 
1926             bool valid;
1927             rc = getBootEnable(ctx, valid);
1928             if (rc != ipmi::ccSuccess)
1929             {
1930                 return ipmi::response(rc);
1931             }
1932 
1933             uint1_t validFlag = valid ? 1 : 0;
1934 
1935             response.pack(bootOptionParameter, reserved1, uint5_t{},
1936                           uint1_t{biosBootType}, uint1_t{permanent},
1937                           uint1_t{validFlag}, uint2_t{}, uint4_t{bootOption},
1938                           uint1_t{}, cmosClear, uint8_t{}, uint8_t{},
1939                           uint8_t{});
1940             return ipmi::responseSuccess(std::move(response));
1941         }
1942         catch (const InternalFailure& e)
1943         {
1944             cache::objectsPtr.reset();
1945             report<InternalFailure>();
1946             return ipmi::responseUnspecifiedError();
1947         }
1948     }
1949     else
1950     {
1951         if ((bootOptionParameter >= oemParmStart) &&
1952             (bootOptionParameter <= oemParmEnd))
1953         {
1954             if (types::enum_cast<BootOptionParameter>(bootOptionParameter) ==
1955                 BootOptionParameter::opalNetworkSettings)
1956             {
1957                 response.pack(bootOptionParameter, reserved1);
1958                 int ret = getHostNetworkData(response);
1959                 if (ret < 0)
1960                 {
1961                     response.trailingOk = true;
1962                     lg2::error(
1963                         "getHostNetworkData failed for GetSysBootOptions.");
1964                     return ipmi::responseUnspecifiedError();
1965                 }
1966                 else
1967                 {
1968                     return ipmi::responseSuccess(std::move(response));
1969                 }
1970             }
1971             else
1972             {
1973                 lg2::error(
1974                     "ipmiChassisGetSysBootOptions: Unsupported parameter {PARAM}",
1975                     "PARAM", lg2::hex,
1976                     static_cast<uint8_t>(bootOptionParameter));
1977                 return ipmi::responseParmNotSupported();
1978             }
1979         }
1980         else
1981         {
1982             lg2::error(
1983                 "ipmiChassisGetSysBootOptions: Unsupported parameter {PARAM}",
1984                 "PARAM", lg2::hex, static_cast<uint8_t>(bootOptionParameter));
1985             return ipmi::responseParmNotSupported();
1986         }
1987     }
1988     return ipmi::responseUnspecifiedError();
1989 }
1990 
ipmiChassisSetSysBootOptions(ipmi::Context::ptr ctx,uint7_t parameterSelector,bool,ipmi::message::Payload & data)1991 ipmi::RspType<> ipmiChassisSetSysBootOptions(ipmi::Context::ptr ctx,
1992                                              uint7_t parameterSelector, bool,
1993                                              ipmi::message::Payload& data)
1994 {
1995     using namespace boot_options;
1996     ipmi::Cc rc;
1997 
1998     if (types::enum_cast<BootOptionParameter>(parameterSelector) ==
1999         BootOptionParameter::setInProgress)
2000     {
2001         uint2_t setInProgressFlag;
2002         uint6_t rsvd;
2003         if (data.unpack(setInProgressFlag, rsvd) != 0 || !data.fullyUnpacked())
2004         {
2005             return ipmi::responseReqDataLenInvalid();
2006         }
2007         if (rsvd)
2008         {
2009             return ipmi::responseInvalidFieldRequest();
2010         }
2011         if ((transferStatus == setInProgress) &&
2012             (static_cast<uint8_t>(setInProgressFlag) != setComplete))
2013         {
2014             return ipmi::response(IPMI_CC_FAIL_SET_IN_PROGRESS);
2015         }
2016         transferStatus = static_cast<uint8_t>(setInProgressFlag);
2017         return ipmi::responseSuccess();
2018     }
2019 
2020     /*  000101
2021      * Parameter #5 means boot flags. Please refer to 28.13 of ipmi doc.
2022      * This is the only parameter used by petitboot.
2023      */
2024 
2025     if (types::enum_cast<BootOptionParameter>(parameterSelector) ==
2026         BootOptionParameter::bootFlags)
2027     {
2028         uint5_t rsvd;
2029         bool validFlag;
2030         bool permanent;
2031         bool biosBootType;
2032         bool lockOutResetButton;
2033         bool screenBlank;
2034         uint4_t bootDeviceSelector;
2035         bool lockKeyboard;
2036         uint8_t data3;
2037         uint4_t biosInfo;
2038         uint4_t rsvd1;
2039         uint5_t deviceInstance;
2040         uint3_t rsvd2;
2041 
2042         if (data.unpack(rsvd, biosBootType, permanent, validFlag,
2043                         lockOutResetButton, screenBlank, bootDeviceSelector,
2044                         lockKeyboard, cmosClear, data3, biosInfo, rsvd1,
2045                         deviceInstance, rsvd2) != 0 ||
2046             !data.fullyUnpacked())
2047         {
2048             return ipmi::responseReqDataLenInvalid();
2049         }
2050         if (rsvd || rsvd1 || rsvd2)
2051         {
2052             return ipmi::responseInvalidFieldRequest();
2053         }
2054 
2055         using namespace chassis::internal;
2056         using namespace chassis::internal::cache;
2057 
2058         try
2059         {
2060             rc = setBootOneTime(ctx, !permanent);
2061             if (rc != ipmi::ccSuccess)
2062             {
2063                 return ipmi::response(rc);
2064             }
2065 
2066             rc = setBootEnable(ctx, validFlag);
2067             if (rc != ipmi::ccSuccess)
2068             {
2069                 return ipmi::response(rc);
2070             }
2071 
2072             auto modeItr =
2073                 modeIpmiToDbus.find(static_cast<uint8_t>(bootDeviceSelector));
2074             auto typeItr =
2075                 typeIpmiToDbus.find(static_cast<uint8_t>(biosBootType));
2076             auto sourceItr =
2077                 sourceIpmiToDbus.find(static_cast<uint8_t>(bootDeviceSelector));
2078             if (sourceIpmiToDbus.end() != sourceItr)
2079             {
2080                 rc = setBootSource(ctx, sourceItr->second);
2081                 if (rc != ipmi::ccSuccess)
2082                 {
2083                     return ipmi::response(rc);
2084                 }
2085                 // If a set boot device is mapping to a boot source, then reset
2086                 // the boot mode D-Bus property to default.
2087                 // This way the ipmid code can determine which property is not
2088                 // at the default value
2089                 if (sourceItr->second != Source::Sources::Default)
2090                 {
2091                     rc = setBootMode(ctx, Mode::Modes::Regular);
2092                     if (rc != ipmi::ccSuccess)
2093                     {
2094                         return ipmi::response(rc);
2095                     }
2096                 }
2097             }
2098 
2099             if (typeIpmiToDbus.end() != typeItr)
2100             {
2101                 rc = setBootType(ctx, typeItr->second);
2102                 if (rc != ipmi::ccSuccess)
2103                 {
2104                     return ipmi::response(rc);
2105                 }
2106             }
2107 
2108             if (modeIpmiToDbus.end() != modeItr)
2109             {
2110                 rc = setBootMode(ctx, modeItr->second);
2111                 if (rc != ipmi::ccSuccess)
2112                 {
2113                     return ipmi::response(rc);
2114                 }
2115                 // If a set boot device is mapping to a boot mode, then reset
2116                 // the boot source D-Bus property to default.
2117                 // This way the ipmid code can determine which property is not
2118                 // at the default value
2119                 if (modeItr->second != Mode::Modes::Regular)
2120                 {
2121                     rc = setBootSource(ctx, Source::Sources::Default);
2122                     if (rc != ipmi::ccSuccess)
2123                     {
2124                         return ipmi::response(rc);
2125                     }
2126                 }
2127             }
2128             if ((modeIpmiToDbus.end() == modeItr) &&
2129                 (typeIpmiToDbus.end() == typeItr) &&
2130                 (sourceIpmiToDbus.end() == sourceItr))
2131             {
2132                 // return error if boot option is not supported
2133                 lg2::error(
2134                     "ipmiChassisSetSysBootOptions: Boot option not supported");
2135                 return ipmi::responseInvalidFieldRequest();
2136             }
2137         }
2138         catch (const sdbusplus::exception_t& e)
2139         {
2140             objectsPtr.reset();
2141             report<InternalFailure>();
2142             lg2::error("ipmiChassisSetSysBootOptions: Error in setting Boot "
2143                        "flag parameters");
2144             return ipmi::responseUnspecifiedError();
2145         }
2146     }
2147     else if (types::enum_cast<BootOptionParameter>(parameterSelector) ==
2148              BootOptionParameter::bootInfo)
2149     {
2150         uint8_t writeMak;
2151         uint5_t bootInfoAck;
2152         uint3_t rsvd;
2153 
2154         if (data.unpack(writeMak, bootInfoAck, rsvd) != 0 ||
2155             !data.fullyUnpacked())
2156         {
2157             return ipmi::responseReqDataLenInvalid();
2158         }
2159         if (rsvd)
2160         {
2161             return ipmi::responseInvalidFieldRequest();
2162         }
2163         bootInitiatorAckData &= ~writeMak;
2164         bootInitiatorAckData |= (writeMak & bootInfoAck);
2165         lg2::info("ipmiChassisSetSysBootOptions: bootInfo parameter set "
2166                   "successfully");
2167         data.trailingOk = true;
2168         return ipmi::responseSuccess();
2169     }
2170     else if (types::enum_cast<BootOptionParameter>(parameterSelector) ==
2171              BootOptionParameter::bootFlagValidClr)
2172     {
2173         uint5_t bootFlagValidClr;
2174         uint3_t rsvd;
2175 
2176         if (data.unpack(bootFlagValidClr, rsvd) != 0 || !data.fullyUnpacked())
2177         {
2178             return ipmi::responseReqDataLenInvalid();
2179         }
2180         if (rsvd)
2181         {
2182             return ipmi::responseInvalidFieldRequest();
2183         }
2184         // store boot flag valid bits clear value
2185         bootFlagValidBitClr = static_cast<uint8_t>(bootFlagValidClr);
2186         lg2::info(
2187             "ipmiChassisSetSysBootOptions: bootFlagValidBits parameter set "
2188             "successfully to {VALUE}",
2189             "VALUE", lg2::hex, bootFlagValidBitClr);
2190         return ipmi::responseSuccess();
2191     }
2192     else
2193     {
2194         if ((parameterSelector >= static_cast<uint7_t>(oemParmStart)) &&
2195             (parameterSelector <= static_cast<uint7_t>(oemParmEnd)))
2196         {
2197             if (types::enum_cast<BootOptionParameter>(parameterSelector) ==
2198                 BootOptionParameter::opalNetworkSettings)
2199             {
2200                 ipmi::Cc ret = setHostNetworkData(data);
2201                 if (ret != ipmi::ccSuccess)
2202                 {
2203                     lg2::error("ipmiChassisSetSysBootOptions: Error in "
2204                                "setHostNetworkData");
2205                     data.trailingOk = true;
2206                     return ipmi::response(ret);
2207                 }
2208                 data.trailingOk = true;
2209                 return ipmi::responseSuccess();
2210             }
2211             else
2212             {
2213                 lg2::error(
2214                     "ipmiChassisSetSysBootOptions: Unsupported param: {PARAM}",
2215                     "PARAM", lg2::hex, static_cast<uint8_t>(parameterSelector));
2216                 data.trailingOk = true;
2217                 return ipmi::responseParmNotSupported();
2218             }
2219         }
2220         data.trailingOk = true;
2221         return ipmi::responseParmNotSupported();
2222     }
2223     return ipmi::responseSuccess();
2224 }
2225 
2226 /** @brief implements Get POH counter command
2227  *  @parameter
2228  *   -  none
2229  *  @returns IPMI completion code plus response data
2230  *   - minPerCount - Minutes per count
2231  *   - counterReading - counter reading
2232  */
2233 ipmi::RspType<uint8_t, // Minutes per count
2234               uint32_t // Counter reading
2235               >
ipmiGetPOHCounter()2236     ipmiGetPOHCounter()
2237 {
2238     // sd_bus error
2239     try
2240     {
2241         return ipmi::responseSuccess(static_cast<uint8_t>(poh::minutesPerCount),
2242                                      getPOHCounter());
2243     }
2244     catch (const std::exception& e)
2245     {
2246         lg2::error("getPOHCounter error: {ERROR}", "ERROR", e);
2247         return ipmi::responseUnspecifiedError();
2248     }
2249 }
2250 
2251 ipmi::RspType<uint3_t, // policy support
2252               uint5_t  // reserved
2253               >
ipmiChassisSetPowerRestorePolicy(boost::asio::yield_context yield,uint3_t policy,uint5_t reserved)2254     ipmiChassisSetPowerRestorePolicy(boost::asio::yield_context yield,
2255                                      uint3_t policy, uint5_t reserved)
2256 {
2257     power_policy::DbusValue value =
2258         power_policy::RestorePolicy::Policy::AlwaysOff;
2259 
2260     if (reserved || (policy > power_policy::noChange))
2261     {
2262         lg2::error("Reserved request parameter: {REQ}", "REQ", lg2::hex,
2263                    static_cast<int>(policy));
2264         return ipmi::responseInvalidFieldRequest();
2265     }
2266 
2267     if (policy == power_policy::noChange)
2268     {
2269         // just return the supported policy
2270         return ipmi::responseSuccess(power_policy::allSupport, reserved);
2271     }
2272 
2273     for (const auto& it : power_policy::dbusToIpmi)
2274     {
2275         if (it.second == policy)
2276         {
2277             value = it.first;
2278             break;
2279         }
2280     }
2281 
2282     try
2283     {
2284         settings::Objects& objects = chassis::internal::cache::getObjects();
2285         const settings::Path& powerRestoreSetting =
2286             objects.map.at(chassis::internal::powerRestoreIntf).front();
2287         std::variant<std::string> property = convertForMessage(value);
2288 
2289         auto sdbusp = getSdBus();
2290         boost::system::error_code ec;
2291         sdbusp->yield_method_call<void>(
2292             yield, ec,
2293             objects
2294                 .service(powerRestoreSetting,
2295                          chassis::internal::powerRestoreIntf)
2296                 .c_str(),
2297             powerRestoreSetting, ipmi::PROP_INTF, "Set",
2298             chassis::internal::powerRestoreIntf, "PowerRestorePolicy",
2299             property);
2300         if (ec)
2301         {
2302             lg2::error("Unspecified Error");
2303             return ipmi::responseUnspecifiedError();
2304         }
2305     }
2306     catch (const InternalFailure& e)
2307     {
2308         chassis::internal::cache::objectsPtr.reset();
2309         report<InternalFailure>();
2310         return ipmi::responseUnspecifiedError();
2311     }
2312 
2313     return ipmi::responseSuccess(power_policy::allSupport, reserved);
2314 }
2315 
ipmiSetFrontPanelButtonEnables(ipmi::Context::ptr ctx,bool disablePowerButton,bool disableResetButton,bool,bool,uint4_t)2316 ipmi::RspType<> ipmiSetFrontPanelButtonEnables(
2317     ipmi::Context::ptr ctx, bool disablePowerButton, bool disableResetButton,
2318     bool, bool, uint4_t)
2319 {
2320     using namespace chassis::internal;
2321 
2322     // set power button Enabled property
2323     bool success = setButtonEnabled(ctx, powerButtonPath, powerButtonIntf,
2324                                     !disablePowerButton);
2325 
2326     // set reset button Enabled property
2327     success &= setButtonEnabled(ctx, resetButtonPath, resetButtonIntf,
2328                                 !disableResetButton);
2329 
2330     if (!success)
2331     {
2332         // not all buttons were successfully set
2333         return ipmi::responseUnspecifiedError();
2334     }
2335     return ipmi::responseSuccess();
2336 }
2337 
register_netfn_chassis_functions()2338 void register_netfn_chassis_functions()
2339 {
2340     createIdentifyTimer();
2341 
2342     // Get Chassis Capabilities
2343     ipmi::registerHandler(ipmi::prioOpenBmcBase, ipmi::netFnChassis,
2344                           ipmi::chassis::cmdGetChassisCapabilities,
2345                           ipmi::Privilege::User, ipmiGetChassisCap);
2346 
2347     // Set Front Panel Button Enables
2348     ipmi::registerHandler(ipmi::prioOpenBmcBase, ipmi::netFnChassis,
2349                           ipmi::chassis::cmdSetFrontPanelButtonEnables,
2350                           ipmi::Privilege::Admin,
2351                           ipmiSetFrontPanelButtonEnables);
2352 
2353     // Set Chassis Capabilities
2354     ipmi::registerHandler(ipmi::prioOpenBmcBase, ipmi::netFnChassis,
2355                           ipmi::chassis::cmdSetChassisCapabilities,
2356                           ipmi::Privilege::User, ipmiSetChassisCap);
2357 
2358     // <Get System Boot Options>
2359     ipmi::registerHandler(ipmi::prioOpenBmcBase, ipmi::netFnChassis,
2360                           ipmi::chassis::cmdGetSystemBootOptions,
2361                           ipmi::Privilege::Operator,
2362                           ipmiChassisGetSysBootOptions);
2363 
2364     // <Get Chassis Status>
2365     ipmi::registerHandler(ipmi::prioOpenBmcBase, ipmi::netFnChassis,
2366                           ipmi::chassis::cmdGetChassisStatus,
2367                           ipmi::Privilege::User, ipmiGetChassisStatus);
2368 
2369     // <Chassis Get System Restart Cause>
2370     ipmi::registerHandler(ipmi::prioOpenBmcBase, ipmi::netFnChassis,
2371                           ipmi::chassis::cmdGetSystemRestartCause,
2372                           ipmi::Privilege::User, ipmiGetSystemRestartCause);
2373 
2374     // <Chassis Control>
2375     ipmi::registerHandler(ipmi::prioOpenBmcBase, ipmi::netFnChassis,
2376                           ipmi::chassis::cmdChassisControl,
2377                           ipmi::Privilege::Operator, ipmiChassisControl);
2378 
2379     // <Chassis Identify>
2380     ipmi::registerHandler(ipmi::prioOpenBmcBase, ipmi::netFnChassis,
2381                           ipmi::chassis::cmdChassisIdentify,
2382                           ipmi::Privilege::Operator, ipmiChassisIdentify);
2383 
2384     // <Set System Boot Options>
2385     ipmi::registerHandler(ipmi::prioOpenBmcBase, ipmi::netFnChassis,
2386                           ipmi::chassis::cmdSetSystemBootOptions,
2387                           ipmi::Privilege::Operator,
2388                           ipmiChassisSetSysBootOptions);
2389 
2390     // <Get POH Counter>
2391     ipmi::registerHandler(ipmi::prioOpenBmcBase, ipmi::netFnChassis,
2392                           ipmi::chassis::cmdGetPohCounter,
2393                           ipmi::Privilege::User, ipmiGetPOHCounter);
2394 
2395     // <Set Power Restore Policy>
2396     ipmi::registerHandler(ipmi::prioOpenBmcBase, ipmi::netFnChassis,
2397                           ipmi::chassis::cmdSetPowerRestorePolicy,
2398                           ipmi::Privilege::Operator,
2399                           ipmiChassisSetPowerRestorePolicy);
2400 }
2401