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 <mapper.h>
9 #include <netinet/in.h>
10 
11 #include <array>
12 #include <chrono>
13 #include <cstring>
14 #include <filesystem>
15 #include <fstream>
16 #include <future>
17 #include <ipmid/api.hpp>
18 #include <ipmid/types.hpp>
19 #include <ipmid/utils.hpp>
20 #include <map>
21 #include <phosphor-logging/elog-errors.hpp>
22 #include <phosphor-logging/log.hpp>
23 #include <sdbusplus/bus.hpp>
24 #include <sdbusplus/message/types.hpp>
25 #include <sdbusplus/server/object.hpp>
26 #include <sdbusplus/timer.hpp>
27 #include <settings.hpp>
28 #include <sstream>
29 #include <string>
30 #include <xyz/openbmc_project/Common/error.hpp>
31 #include <xyz/openbmc_project/Control/Boot/Mode/server.hpp>
32 #include <xyz/openbmc_project/Control/Boot/Source/server.hpp>
33 #include <xyz/openbmc_project/Control/Power/RestorePolicy/server.hpp>
34 #include <xyz/openbmc_project/State/Host/server.hpp>
35 #include <xyz/openbmc_project/State/PowerOnHours/server.hpp>
36 
37 // Defines
38 #define SET_PARM_VERSION 0x01
39 #define SET_PARM_BOOT_FLAGS_PERMANENT 0x40
40 #define SET_PARM_BOOT_FLAGS_VALID_ONE_TIME 0x80
41 #define SET_PARM_BOOT_FLAGS_VALID_PERMANENT 0xC0
42 
43 std::unique_ptr<phosphor::Timer> identifyTimer
44     __attribute__((init_priority(101)));
45 
46 constexpr size_t SIZE_MAC = 18;
47 constexpr size_t SIZE_BOOT_OPTION = (uint8_t)
48     BootOptionResponseSize::OPAL_NETWORK_SETTINGS; // Maximum size of the boot
49                                                    // option parametrs
50 constexpr size_t SIZE_PREFIX = 7;
51 constexpr size_t MAX_PREFIX_VALUE = 32;
52 constexpr size_t SIZE_COOKIE = 4;
53 constexpr size_t SIZE_VERSION = 2;
54 constexpr size_t DEFAULT_IDENTIFY_TIME_OUT = 15;
55 
56 // PetiBoot-Specific
57 static constexpr uint8_t net_conf_initial_bytes[] = {0x80, 0x21, 0x70, 0x62,
58                                                      0x21, 0x00, 0x01, 0x06};
59 
60 static constexpr size_t COOKIE_OFFSET = 1;
61 static constexpr size_t VERSION_OFFSET = 5;
62 static constexpr size_t ADDR_SIZE_OFFSET = 8;
63 static constexpr size_t MAC_OFFSET = 9;
64 static constexpr size_t ADDRTYPE_OFFSET = 16;
65 static constexpr size_t IPADDR_OFFSET = 17;
66 
67 static constexpr size_t encIdentifyObjectsSize = 1;
68 static constexpr size_t chassisIdentifyReqLength = 2;
69 static constexpr size_t identifyIntervalPos = 0;
70 static constexpr size_t forceIdentifyPos = 1;
71 
72 void register_netfn_chassis_functions() __attribute__((constructor));
73 
74 // Host settings in dbus
75 // Service name should be referenced by connection name got via object mapper
76 const char* settings_object_name = "/org/openbmc/settings/host0";
77 const char* settings_intf_name = "org.freedesktop.DBus.Properties";
78 const char* identify_led_object_name =
79     "/xyz/openbmc_project/led/groups/enclosure_identify";
80 
81 constexpr auto SETTINGS_ROOT = "/";
82 constexpr auto SETTINGS_MATCH = "host0";
83 
84 constexpr auto IP_INTERFACE = "xyz.openbmc_project.Network.IP";
85 constexpr auto MAC_INTERFACE = "xyz.openbmc_project.Network.MACAddress";
86 
87 static constexpr auto chassisStateRoot = "/xyz/openbmc_project/state";
88 static constexpr auto chassisPOHStateIntf =
89     "xyz.openbmc_project.State.PowerOnHours";
90 static constexpr auto pOHCounterProperty = "POHCounter";
91 static constexpr auto match = "chassis0";
92 const static constexpr char chassisCapIntf[] =
93     "xyz.openbmc_project.Control.ChassisCapabilities";
94 const static constexpr char chassisCapFlagsProp[] = "CapabilitiesFlags";
95 const static constexpr char chassisFRUDevAddrProp[] = "FRUDeviceAddress";
96 const static constexpr char chassisSDRDevAddrProp[] = "SDRDeviceAddress";
97 const static constexpr char chassisSELDevAddrProp[] = "SELDeviceAddress";
98 const static constexpr char chassisSMDevAddrProp[] = "SMDeviceAddress";
99 const static constexpr char chassisBridgeDevAddrProp[] = "BridgeDeviceAddress";
100 static constexpr uint8_t chassisCapFlagMask = 0x0f;
101 static constexpr uint8_t chassisCapAddrMask = 0xfe;
102 static constexpr const char* powerButtonIntf =
103     "xyz.openbmc_project.Chassis.Buttons.Power";
104 static constexpr const char* powerButtonPath =
105     "/xyz/openbmc_project/Chassis/Buttons/Power0";
106 static constexpr const char* resetButtonIntf =
107     "xyz.openbmc_project.Chassis.Buttons.Reset";
108 static constexpr const char* resetButtonPath =
109     "/xyz/openbmc_project/Chassis/Buttons/Reset0";
110 
111 typedef struct
112 {
113     uint8_t cap_flags;
114     uint8_t fru_info_dev_addr;
115     uint8_t sdr_dev_addr;
116     uint8_t sel_dev_addr;
117     uint8_t system_management_dev_addr;
118     uint8_t bridge_dev_addr;
119 } __attribute__((packed)) ipmi_chassis_cap_t;
120 
121 typedef struct
122 {
123     uint8_t cur_power_state;
124     uint8_t last_power_event;
125     uint8_t misc_power_state;
126     uint8_t front_panel_button_cap_status;
127 } __attribute__((packed)) ipmi_get_chassis_status_t;
128 
129 // Phosphor Host State manager
130 namespace State = sdbusplus::xyz::openbmc_project::State::server;
131 
132 namespace fs = std::filesystem;
133 
134 using namespace phosphor::logging;
135 using namespace sdbusplus::xyz::openbmc_project::Common::Error;
136 using namespace sdbusplus::xyz::openbmc_project::Control::Boot::server;
137 
138 namespace chassis
139 {
140 namespace internal
141 {
142 
143 constexpr auto bootModeIntf = "xyz.openbmc_project.Control.Boot.Mode";
144 constexpr auto bootSourceIntf = "xyz.openbmc_project.Control.Boot.Source";
145 constexpr auto powerRestoreIntf =
146     "xyz.openbmc_project.Control.Power.RestorePolicy";
147 sdbusplus::bus::bus dbus(ipmid_get_sd_bus_connection());
148 
149 namespace cache
150 {
151 
152 settings::Objects objects(dbus,
153                           {bootModeIntf, bootSourceIntf, powerRestoreIntf});
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 
166 struct get_sys_boot_options_t
167 {
168     uint8_t parameter;
169     uint8_t set;
170     uint8_t block;
171 } __attribute__((packed));
172 
173 struct get_sys_boot_options_response_t
174 {
175     uint8_t version;
176     uint8_t parm;
177     uint8_t data[SIZE_BOOT_OPTION];
178 } __attribute__((packed));
179 
180 struct set_sys_boot_options_t
181 {
182     uint8_t parameter;
183     uint8_t data[SIZE_BOOT_OPTION];
184 } __attribute__((packed));
185 
186 int getHostNetworkData(get_sys_boot_options_response_t* respptr)
187 {
188     ipmi::PropertyMap properties;
189     int rc = 0;
190     uint8_t addrSize = ipmi::network::IPV4_ADDRESS_SIZE_BYTE;
191 
192     try
193     {
194         // TODO There may be cases where an interface is implemented by multiple
195         // objects,to handle such cases we are interested on that object
196         //  which are on interested busname.
197         //  Currenlty mapper doesn't give the readable busname(gives busid)
198         //  so we can't match with bus name so giving some object specific info
199         //  as SETTINGS_MATCH.
200         //  Later SETTINGS_MATCH will be replaced with busname.
201 
202         sdbusplus::bus::bus bus(ipmid_get_sd_bus_connection());
203 
204         auto ipObjectInfo = ipmi::getDbusObject(bus, IP_INTERFACE,
205                                                 SETTINGS_ROOT, SETTINGS_MATCH);
206 
207         auto macObjectInfo = ipmi::getDbusObject(bus, MAC_INTERFACE,
208                                                  SETTINGS_ROOT, SETTINGS_MATCH);
209 
210         properties = ipmi::getAllDbusProperties(
211             bus, ipObjectInfo.second, ipObjectInfo.first, IP_INTERFACE);
212         auto variant = ipmi::getDbusProperty(bus, macObjectInfo.second,
213                                              macObjectInfo.first, MAC_INTERFACE,
214                                              "MACAddress");
215 
216         auto ipAddress = std::get<std::string>(properties["Address"]);
217 
218         auto gateway = std::get<std::string>(properties["Gateway"]);
219 
220         auto prefix = std::get<uint8_t>(properties["PrefixLength"]);
221 
222         uint8_t isStatic =
223             (std::get<std::string>(properties["Origin"]) ==
224              "xyz.openbmc_project.Network.IP.AddressOrigin.Static")
225                 ? 1
226                 : 0;
227 
228         auto MACAddress = std::get<std::string>(variant);
229 
230         // it is expected here that we should get the valid data
231         // but we may also get the default values.
232         // Validation of the data is done by settings.
233         //
234         // if mac address is default mac address then
235         // don't send blank override.
236         if ((MACAddress == ipmi::network::DEFAULT_MAC_ADDRESS))
237         {
238             std::memset(respptr->data, 0, SIZE_BOOT_OPTION);
239             rc = -1;
240             return rc;
241         }
242         // if addr is static then ipaddress,gateway,prefix
243         // should not be default one,don't send blank override.
244         if (isStatic)
245         {
246             if ((ipAddress == ipmi::network::DEFAULT_ADDRESS) ||
247                 (gateway == ipmi::network::DEFAULT_ADDRESS) || (!prefix))
248             {
249                 std::memset(respptr->data, 0, SIZE_BOOT_OPTION);
250                 rc = -1;
251                 return rc;
252             }
253         }
254 
255         sscanf(
256             MACAddress.c_str(), ipmi::network::MAC_ADDRESS_FORMAT,
257             (respptr->data + MAC_OFFSET), (respptr->data + MAC_OFFSET + 1),
258             (respptr->data + MAC_OFFSET + 2), (respptr->data + MAC_OFFSET + 3),
259             (respptr->data + MAC_OFFSET + 4), (respptr->data + MAC_OFFSET + 5));
260 
261         respptr->data[MAC_OFFSET + 6] = 0x00;
262 
263         std::memcpy(respptr->data + ADDRTYPE_OFFSET, &isStatic,
264                     sizeof(isStatic));
265 
266         uint8_t addressFamily = (std::get<std::string>(properties["Type"]) ==
267                                  "xyz.openbmc_project.Network.IP.Protocol.IPv4")
268                                     ? AF_INET
269                                     : AF_INET6;
270 
271         addrSize = (addressFamily == AF_INET)
272                        ? ipmi::network::IPV4_ADDRESS_SIZE_BYTE
273                        : ipmi::network::IPV6_ADDRESS_SIZE_BYTE;
274 
275         // ipaddress and gateway would be in IPv4 format
276         inet_pton(addressFamily, ipAddress.c_str(),
277                   (respptr->data + IPADDR_OFFSET));
278 
279         uint8_t prefixOffset = IPADDR_OFFSET + addrSize;
280 
281         std::memcpy(respptr->data + prefixOffset, &prefix, sizeof(prefix));
282 
283         uint8_t gatewayOffset = prefixOffset + sizeof(decltype(prefix));
284 
285         inet_pton(addressFamily, gateway.c_str(),
286                   (respptr->data + gatewayOffset));
287     }
288     catch (InternalFailure& e)
289     {
290         commit<InternalFailure>();
291         std::memset(respptr->data, 0, SIZE_BOOT_OPTION);
292         rc = -1;
293         return rc;
294     }
295 
296     // PetiBoot-Specific
297     // If success then copy the first 9 bytes to the data
298     std::memcpy(respptr->data, net_conf_initial_bytes,
299                 sizeof(net_conf_initial_bytes));
300 
301     std::memcpy(respptr->data + ADDR_SIZE_OFFSET, &addrSize, sizeof(addrSize));
302 
303 #ifdef _IPMI_DEBUG_
304     std::printf("\n===Printing the IPMI Formatted Data========\n");
305 
306     for (uint8_t pos = 0; pos < index; pos++)
307     {
308         std::printf("%02x ", respptr->data[pos]);
309     }
310 #endif
311 
312     return rc;
313 }
314 
315 /** @brief convert IPv4 and IPv6 addresses from binary to text form.
316  *  @param[in] family - IPv4/Ipv6
317  *  @param[in] data - req data pointer.
318  *  @param[in] offset - offset in the data.
319  *  @param[in] addrSize - size of the data which needs to be read from offset.
320  *  @returns address in text form.
321  */
322 
323 std::string getAddrStr(uint8_t family, uint8_t* data, uint8_t offset,
324                        uint8_t addrSize)
325 {
326     char ipAddr[INET6_ADDRSTRLEN] = {};
327 
328     switch (family)
329     {
330         case AF_INET:
331         {
332             struct sockaddr_in addr4
333             {
334             };
335             std::memcpy(&addr4.sin_addr.s_addr, &data[offset], addrSize);
336 
337             inet_ntop(AF_INET, &addr4.sin_addr, ipAddr, INET_ADDRSTRLEN);
338 
339             break;
340         }
341         case AF_INET6:
342         {
343             struct sockaddr_in6 addr6
344             {
345             };
346             std::memcpy(&addr6.sin6_addr.s6_addr, &data[offset], addrSize);
347 
348             inet_ntop(AF_INET6, &addr6.sin6_addr, ipAddr, INET6_ADDRSTRLEN);
349 
350             break;
351         }
352         default:
353         {
354             return {};
355         }
356     }
357 
358     return ipAddr;
359 }
360 
361 int setHostNetworkData(set_sys_boot_options_t* reqptr)
362 {
363     using namespace std::string_literals;
364     std::string host_network_config;
365     char mac[]{"00:00:00:00:00:00"};
366     std::string ipAddress, gateway;
367     char addrOrigin{0};
368     uint8_t addrSize{0};
369     std::string addressOrigin =
370         "xyz.openbmc_project.Network.IP.AddressOrigin.DHCP";
371     std::string addressType = "xyz.openbmc_project.Network.IP.Protocol.IPv4";
372     uint8_t prefix{0};
373     uint32_t zeroCookie = 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             if (memcmp(&(reqptr->data[COOKIE_OFFSET]),
385                        (net_conf_initial_bytes + COOKIE_OFFSET),
386                        SIZE_COOKIE) != 0)
387             {
388                 // cookie == 0
389                 if (memcmp(&(reqptr->data[COOKIE_OFFSET]), &zeroCookie,
390                            SIZE_COOKIE) == 0)
391                 {
392                     // need to zero out the network settings.
393                     break;
394                 }
395 
396                 log<level::ERR>("Invalid Cookie");
397                 elog<InternalFailure>();
398             }
399 
400             // vesion == 0x00 0x01
401             if (memcmp(&(reqptr->data[VERSION_OFFSET]),
402                        (net_conf_initial_bytes + VERSION_OFFSET),
403                        SIZE_VERSION) != 0)
404             {
405 
406                 log<level::ERR>("Invalid Version");
407                 elog<InternalFailure>();
408             }
409 
410             std::snprintf(
411                 mac, SIZE_MAC, ipmi::network::MAC_ADDRESS_FORMAT,
412                 reqptr->data[MAC_OFFSET], reqptr->data[MAC_OFFSET + 1],
413                 reqptr->data[MAC_OFFSET + 2], reqptr->data[MAC_OFFSET + 3],
414                 reqptr->data[MAC_OFFSET + 4], reqptr->data[MAC_OFFSET + 5]);
415 
416             std::memcpy(&addrOrigin, &(reqptr->data[ADDRTYPE_OFFSET]),
417                         sizeof(decltype(addrOrigin)));
418 
419             if (addrOrigin)
420             {
421                 addressOrigin =
422                     "xyz.openbmc_project.Network.IP.AddressOrigin.Static";
423             }
424 
425             // Get the address size
426             std::memcpy(&addrSize, &reqptr->data[ADDR_SIZE_OFFSET],
427                         sizeof(addrSize));
428 
429             uint8_t prefixOffset = IPADDR_OFFSET + addrSize;
430 
431             std::memcpy(&prefix, &(reqptr->data[prefixOffset]),
432                         sizeof(decltype(prefix)));
433 
434             uint8_t gatewayOffset = prefixOffset + sizeof(decltype(prefix));
435 
436             if (addrSize != ipmi::network::IPV4_ADDRESS_SIZE_BYTE)
437             {
438                 addressType = "xyz.openbmc_project.Network.IP.Protocol.IPv6";
439                 family = AF_INET6;
440             }
441 
442             ipAddress =
443                 getAddrStr(family, reqptr->data, IPADDR_OFFSET, addrSize);
444 
445             gateway = getAddrStr(family, reqptr->data, gatewayOffset, addrSize);
446 
447         } while (0);
448 
449         // Cookie == 0 or it is a valid cookie
450         host_network_config += "ipaddress="s + ipAddress + ",prefix="s +
451                                std::to_string(prefix) + ",gateway="s + gateway +
452                                ",mac="s + mac + ",addressOrigin="s +
453                                addressOrigin;
454 
455         sdbusplus::bus::bus bus(ipmid_get_sd_bus_connection());
456 
457         auto ipObjectInfo = ipmi::getDbusObject(bus, IP_INTERFACE,
458                                                 SETTINGS_ROOT, SETTINGS_MATCH);
459         auto macObjectInfo = ipmi::getDbusObject(bus, MAC_INTERFACE,
460                                                  SETTINGS_ROOT, SETTINGS_MATCH);
461         // set the dbus property
462         ipmi::setDbusProperty(bus, ipObjectInfo.second, ipObjectInfo.first,
463                               IP_INTERFACE, "Address", std::string(ipAddress));
464         ipmi::setDbusProperty(bus, ipObjectInfo.second, ipObjectInfo.first,
465                               IP_INTERFACE, "PrefixLength", prefix);
466         ipmi::setDbusProperty(bus, ipObjectInfo.second, ipObjectInfo.first,
467                               IP_INTERFACE, "Origin", addressOrigin);
468         ipmi::setDbusProperty(bus, ipObjectInfo.second, ipObjectInfo.first,
469                               IP_INTERFACE, "Gateway", std::string(gateway));
470         ipmi::setDbusProperty(
471             bus, ipObjectInfo.second, ipObjectInfo.first, IP_INTERFACE, "Type",
472             std::string("xyz.openbmc_project.Network.IP.Protocol.IPv4"));
473         ipmi::setDbusProperty(bus, macObjectInfo.second, macObjectInfo.first,
474                               MAC_INTERFACE, "MACAddress", std::string(mac));
475 
476         log<level::DEBUG>(
477             "Network configuration changed",
478             entry("NETWORKCONFIG=%s", host_network_config.c_str()));
479     }
480     catch (InternalFailure& e)
481     {
482         commit<InternalFailure>();
483         return -1;
484     }
485 
486     return 0;
487 }
488 
489 uint32_t getPOHCounter()
490 {
491     sdbusplus::bus::bus bus{ipmid_get_sd_bus_connection()};
492 
493     auto chassisStateObj =
494         ipmi::getDbusObject(bus, chassisPOHStateIntf, chassisStateRoot, match);
495 
496     auto service =
497         ipmi::getService(bus, chassisPOHStateIntf, chassisStateObj.first);
498 
499     auto propValue =
500         ipmi::getDbusProperty(bus, service, chassisStateObj.first,
501                               chassisPOHStateIntf, pOHCounterProperty);
502 
503     return std::get<uint32_t>(propValue);
504 }
505 
506 ipmi_ret_t ipmi_chassis_wildcard(ipmi_netfn_t netfn, ipmi_cmd_t cmd,
507                                  ipmi_request_t request,
508                                  ipmi_response_t response,
509                                  ipmi_data_len_t data_len,
510                                  ipmi_context_t context)
511 {
512     // Status code.
513     ipmi_ret_t rc = IPMI_CC_INVALID;
514     *data_len = 0;
515     return rc;
516 }
517 
518 ipmi_ret_t ipmi_get_chassis_cap(ipmi_netfn_t netfn, ipmi_cmd_t cmd,
519                                 ipmi_request_t request,
520                                 ipmi_response_t response,
521                                 ipmi_data_len_t data_len,
522                                 ipmi_context_t context)
523 {
524     // sd_bus error
525     ipmi_ret_t rc = IPMI_CC_OK;
526 
527     ipmi_chassis_cap_t chassis_cap{};
528 
529     if (*data_len != 0)
530     {
531         return IPMI_CC_REQ_DATA_LEN_INVALID;
532     }
533 
534     *data_len = sizeof(ipmi_chassis_cap_t);
535 
536     try
537     {
538         sdbusplus::bus::bus bus{ipmid_get_sd_bus_connection()};
539 
540         ipmi::DbusObjectInfo chassisCapObject =
541             ipmi::getDbusObject(bus, chassisCapIntf);
542 
543         // capabilities flags
544         // [7..4] - reserved
545         // [3] – 1b = provides power interlock  (IPM 1.5)
546         // [2] – 1b = provides Diagnostic Interrupt (FP NMI)
547         // [1] – 1b = provides “Front Panel Lockout” (indicates that the chassis
548         // has capabilities
549         //            to lock out external power control and reset button or
550         //            front panel interfaces and/or detect tampering with those
551         //            interfaces).
552         // [0] -1b = Chassis provides intrusion (physical security) sensor.
553         // set to default value 0x0.
554         ipmi::Value variant = ipmi::getDbusProperty(
555             bus, chassisCapObject.second, chassisCapObject.first,
556             chassisCapIntf, chassisCapFlagsProp);
557         chassis_cap.cap_flags = std::get<uint8_t>(variant);
558 
559         variant = ipmi::getDbusProperty(bus, chassisCapObject.second,
560                                         chassisCapObject.first, chassisCapIntf,
561                                         chassisFRUDevAddrProp);
562         // Chassis FRU info Device Address.
563         chassis_cap.fru_info_dev_addr = std::get<uint8_t>(variant);
564 
565         variant = ipmi::getDbusProperty(bus, chassisCapObject.second,
566                                         chassisCapObject.first, chassisCapIntf,
567                                         chassisSDRDevAddrProp);
568         // Chassis SDR Device Address.
569         chassis_cap.sdr_dev_addr = std::get<uint8_t>(variant);
570 
571         variant = ipmi::getDbusProperty(bus, chassisCapObject.second,
572                                         chassisCapObject.first, chassisCapIntf,
573                                         chassisSELDevAddrProp);
574         // Chassis SEL Device Address.
575         chassis_cap.sel_dev_addr = std::get<uint8_t>(variant);
576 
577         variant = ipmi::getDbusProperty(bus, chassisCapObject.second,
578                                         chassisCapObject.first, chassisCapIntf,
579                                         chassisSMDevAddrProp);
580         // Chassis System Management Device Address.
581         chassis_cap.system_management_dev_addr = std::get<uint8_t>(variant);
582 
583         variant = ipmi::getDbusProperty(bus, chassisCapObject.second,
584                                         chassisCapObject.first, chassisCapIntf,
585                                         chassisBridgeDevAddrProp);
586         // Chassis Bridge Device Address.
587         chassis_cap.bridge_dev_addr = std::get<uint8_t>(variant);
588         uint8_t* respP = reinterpret_cast<uint8_t*>(response);
589         uint8_t* chassisP = reinterpret_cast<uint8_t*>(&chassis_cap);
590         std::copy(chassisP, chassisP + *data_len, respP);
591     }
592     catch (std::exception& e)
593     {
594         log<level::ERR>(e.what());
595         rc = IPMI_CC_UNSPECIFIED_ERROR;
596         *data_len = 0;
597         return rc;
598     }
599 
600     return rc;
601 }
602 
603 ipmi_ret_t ipmi_set_chassis_cap(ipmi_netfn_t netfn, ipmi_cmd_t cmd,
604                                 ipmi_request_t request,
605                                 ipmi_response_t response,
606                                 ipmi_data_len_t data_len,
607                                 ipmi_context_t context)
608 {
609     ipmi_ret_t rc = IPMI_CC_OK;
610 
611     if (*data_len != sizeof(ipmi_chassis_cap_t))
612     {
613         log<level::ERR>("Unsupported request length",
614                         entry("LEN=0x%x", *data_len));
615         *data_len = 0;
616         return IPMI_CC_REQ_DATA_LEN_INVALID;
617     }
618 
619     ipmi_chassis_cap_t* chassisCap = static_cast<ipmi_chassis_cap_t*>(request);
620 
621     *data_len = 0;
622 
623     // check input data
624     if (0 != (chassisCap->cap_flags & ~chassisCapFlagMask))
625     {
626         log<level::ERR>("Unsupported request parameter(CAP Flags)",
627                         entry("REQ=0x%x", chassisCap->cap_flags));
628         return IPMI_CC_INVALID_FIELD_REQUEST;
629     }
630 
631     if (0 != (chassisCap->fru_info_dev_addr & ~chassisCapAddrMask))
632     {
633         log<level::ERR>("Unsupported request parameter(FRU Addr)",
634                         entry("REQ=0x%x", chassisCap->fru_info_dev_addr));
635         return IPMI_CC_INVALID_FIELD_REQUEST;
636     }
637 
638     if (0 != (chassisCap->sdr_dev_addr & ~chassisCapAddrMask))
639     {
640         log<level::ERR>("Unsupported request parameter(SDR Addr)",
641                         entry("REQ=0x%x", chassisCap->sdr_dev_addr));
642         return IPMI_CC_INVALID_FIELD_REQUEST;
643     }
644 
645     if (0 != (chassisCap->sel_dev_addr & ~chassisCapAddrMask))
646     {
647         log<level::ERR>("Unsupported request parameter(SEL Addr)",
648                         entry("REQ=0x%x", chassisCap->sel_dev_addr));
649         return IPMI_CC_INVALID_FIELD_REQUEST;
650     }
651 
652     if (0 != (chassisCap->system_management_dev_addr & ~chassisCapAddrMask))
653     {
654         log<level::ERR>(
655             "Unsupported request parameter(SM Addr)",
656             entry("REQ=0x%x", chassisCap->system_management_dev_addr));
657         return IPMI_CC_INVALID_FIELD_REQUEST;
658     }
659 
660     if (0 != (chassisCap->bridge_dev_addr & ~chassisCapAddrMask))
661     {
662         log<level::ERR>("Unsupported request parameter(Bridge Addr)",
663                         entry("REQ=0x%x", chassisCap->bridge_dev_addr));
664         return IPMI_CC_INVALID_FIELD_REQUEST;
665     }
666 
667     try
668     {
669         sdbusplus::bus::bus bus(ipmid_get_sd_bus_connection());
670         ipmi::DbusObjectInfo chassisCapObject =
671             ipmi::getDbusObject(bus, chassisCapIntf);
672 
673         ipmi::setDbusProperty(bus, chassisCapObject.second,
674                               chassisCapObject.first, chassisCapIntf,
675                               chassisCapFlagsProp, chassisCap->cap_flags);
676 
677         ipmi::setDbusProperty(bus, chassisCapObject.second,
678                               chassisCapObject.first, chassisCapIntf,
679                               chassisFRUDevAddrProp,
680                               chassisCap->fru_info_dev_addr);
681 
682         ipmi::setDbusProperty(bus, chassisCapObject.second,
683                               chassisCapObject.first, chassisCapIntf,
684                               chassisSDRDevAddrProp, chassisCap->sdr_dev_addr);
685 
686         ipmi::setDbusProperty(bus, chassisCapObject.second,
687                               chassisCapObject.first, chassisCapIntf,
688                               chassisSELDevAddrProp, chassisCap->sel_dev_addr);
689 
690         ipmi::setDbusProperty(bus, chassisCapObject.second,
691                               chassisCapObject.first, chassisCapIntf,
692                               chassisSMDevAddrProp,
693                               chassisCap->system_management_dev_addr);
694 
695         ipmi::setDbusProperty(bus, chassisCapObject.second,
696                               chassisCapObject.first, chassisCapIntf,
697                               chassisBridgeDevAddrProp,
698                               chassisCap->bridge_dev_addr);
699     }
700     catch (std::exception& e)
701     {
702         log<level::ERR>(e.what());
703         rc = IPMI_CC_UNSPECIFIED_ERROR;
704         return rc;
705     }
706 
707     return rc;
708 }
709 
710 //------------------------------------------
711 // Calls into Host State Manager Dbus object
712 //------------------------------------------
713 int initiate_state_transition(State::Host::Transition transition)
714 {
715     // OpenBMC Host State Manager dbus framework
716     constexpr auto HOST_STATE_MANAGER_ROOT = "/xyz/openbmc_project/state/host0";
717     constexpr auto HOST_STATE_MANAGER_IFACE = "xyz.openbmc_project.State.Host";
718     constexpr auto DBUS_PROPERTY_IFACE = "org.freedesktop.DBus.Properties";
719     constexpr auto PROPERTY = "RequestedHostTransition";
720 
721     // sd_bus error
722     int rc = 0;
723     char* busname = NULL;
724 
725     // SD Bus error report mechanism.
726     sd_bus_error bus_error = SD_BUS_ERROR_NULL;
727 
728     // Gets a hook onto either a SYSTEM or SESSION bus
729     sd_bus* bus_type = ipmid_get_sd_bus_connection();
730     rc = mapper_get_service(bus_type, HOST_STATE_MANAGER_ROOT, &busname);
731     if (rc < 0)
732     {
733         log<level::ERR>(
734             "Failed to get bus name",
735             entry("ERRNO=0x%X, OBJPATH=%s", -rc, HOST_STATE_MANAGER_ROOT));
736         return rc;
737     }
738 
739     // Convert to string equivalent of the passed in transition enum.
740     auto request = State::convertForMessage(transition);
741 
742     rc = sd_bus_call_method(bus_type,                // On the system bus
743                             busname,                 // Service to contact
744                             HOST_STATE_MANAGER_ROOT, // Object path
745                             DBUS_PROPERTY_IFACE,     // Interface name
746                             "Set",                   // Method to be called
747                             &bus_error,              // object to return error
748                             nullptr,                 // Response buffer if any
749                             "ssv",                   // Takes 3 arguments
750                             HOST_STATE_MANAGER_IFACE, PROPERTY, "s",
751                             request.c_str());
752     if (rc < 0)
753     {
754         log<level::ERR>("Failed to initiate transition",
755                         entry("ERRNO=0x%X, REQUEST=%s", -rc, request.c_str()));
756     }
757     else
758     {
759         log<level::INFO>("Transition request initiated successfully");
760     }
761 
762     sd_bus_error_free(&bus_error);
763     free(busname);
764 
765     return rc;
766 }
767 
768 namespace power_policy
769 {
770 
771 using namespace sdbusplus::xyz::openbmc_project::Control::Power::server;
772 using IpmiValue = uint8_t;
773 using DbusValue = RestorePolicy::Policy;
774 
775 const std::map<DbusValue, IpmiValue> dbusToIpmi = {
776     {RestorePolicy::Policy::AlwaysOff, 0x00},
777     {RestorePolicy::Policy::Restore, 0x01},
778     {RestorePolicy::Policy::AlwaysOn, 0x02}};
779 
780 static constexpr uint8_t noChange = 0x03;
781 static constexpr uint8_t allSupport = 0x01 | 0x02 | 0x04;
782 static constexpr uint8_t policyBitMask = 0x07;
783 static constexpr uint8_t setPolicyReqLen = 1;
784 
785 /* helper function for Get Chassis Status Command
786  */
787 std::optional<uint2_t> getPowerRestorePolicy()
788 {
789     uint2_t restorePolicy = 0;
790     using namespace chassis::internal;
791 
792     try
793     {
794         const auto& powerRestoreSetting =
795             cache::objects.map.at(powerRestoreIntf).front();
796         ipmi::Value result = ipmi::getDbusProperty(
797             *getSdBus(),
798             cache::objects.service(powerRestoreSetting, powerRestoreIntf)
799                 .c_str(),
800             powerRestoreSetting.c_str(), powerRestoreIntf,
801             "PowerRestorePolicy");
802         auto powerRestore = RestorePolicy::convertPolicyFromString(
803             std::get<std::string>(result));
804         restorePolicy = dbusToIpmi.at(powerRestore);
805     }
806     catch (const std::exception& e)
807     {
808         log<level::ERR>(
809             "Failed to fetch pgood property", entry("ERROR=%s", e.what()),
810             entry("PATH=%s",
811                   cache::objects.map.at(powerRestoreIntf).front().c_str()),
812             entry("INTERFACE=%s", powerRestoreIntf));
813         return std::nullopt;
814     }
815     return std::make_optional(restorePolicy);
816 }
817 
818 /*
819  * getPowerStatus
820  * helper function for Get Chassis Status Command
821  * return - optional value for pgood (no value on error)
822  */
823 std::optional<bool> getPowerStatus()
824 {
825     constexpr const char* powerControlObj =
826         "/xyz/openbmc_project/Chassis/Control/Power0";
827     constexpr const char* powerControlIntf =
828         "xyz.openbmc_project.Chassis.Control.Power";
829     bool powerGood = false;
830     std::shared_ptr<sdbusplus::asio::connection> busp = getSdBus();
831     try
832     {
833         auto service =
834             ipmi::getService(*busp, powerControlIntf, powerControlObj);
835 
836         ipmi::Value variant = ipmi::getDbusProperty(
837             *busp, service, powerControlObj, powerControlIntf, "pgood");
838         powerGood = static_cast<bool>(std::get<int>(variant));
839     }
840     catch (const std::exception& e)
841     {
842         try
843         {
844             // FIXME: some legacy modules use the older path; try that next
845             constexpr const char* legacyPwrCtrlObj =
846                 "/org/openbmc/control/power0";
847             constexpr const char* legacyPwrCtrlIntf =
848                 "org.openbmc.control.Power";
849             auto service =
850                 ipmi::getService(*busp, legacyPwrCtrlIntf, legacyPwrCtrlObj);
851 
852             ipmi::Value variant = ipmi::getDbusProperty(
853                 *busp, service, legacyPwrCtrlObj, legacyPwrCtrlIntf, "pgood");
854             powerGood = static_cast<bool>(std::get<int>(variant));
855         }
856         catch (const std::exception& e)
857         {
858             log<level::ERR>("Failed to fetch pgood property",
859                             entry("ERROR=%s", e.what()),
860                             entry("PATH=%s", powerControlObj),
861                             entry("INTERFACE=%s", powerControlIntf));
862             return std::nullopt;
863         }
864     }
865     return std::make_optional(powerGood);
866 }
867 
868 } // namespace power_policy
869 
870 static std::optional<bool> getButtonEnabled(const std::string& buttonPath,
871                                             const std::string& buttonIntf)
872 {
873     std::shared_ptr<sdbusplus::asio::connection> busp = getSdBus();
874     bool buttonDisabled = false;
875     try
876     {
877         auto service = ipmi::getService(*busp, buttonIntf, buttonPath);
878         ipmi::Value enabled = ipmi::getDbusProperty(*busp, service, buttonPath,
879                                                     buttonIntf, "Enabled");
880         buttonDisabled = !std::get<bool>(enabled);
881     }
882     catch (sdbusplus::exception::SdBusError& e)
883     {
884         log<level::ERR>("Fail to get button Enabled property",
885                         entry("PATH=%s", buttonPath.c_str()),
886                         entry("ERROR=%s", e.what()));
887         return std::nullopt;
888     }
889     return std::make_optional(buttonDisabled);
890 }
891 
892 //----------------------------------------------------------------------
893 // Get Chassis Status commands
894 //----------------------------------------------------------------------
895 ipmi::RspType<bool,    // Power is on
896               bool,    // Power overload
897               bool,    // Interlock
898               bool,    // power fault
899               bool,    // power control fault
900               uint2_t, // power restore policy
901               bool,    // reserved
902 
903               bool, // AC failed
904               bool, // last power down caused by a Power overload
905               bool, // last power down caused by a power interlock
906               bool, // last power down caused by power fault
907               bool, // last ‘Power is on’ state was entered via IPMI command
908               uint3_t, // reserved
909 
910               bool,    // Chassis intrusion active
911               bool,    // Front Panel Lockout active
912               bool,    // Drive Fault
913               bool,    // Cooling/fan fault detected
914               uint2_t, // Chassis Identify State
915               bool,    // Chassis Identify command and state info supported
916               bool,    // reserved
917 
918               bool, // Power off button disabled
919               bool, // Reset button disabled
920               bool, // Diagnostic Interrupt button disabled
921               bool, // Standby (sleep) button disabled
922               bool, // Power off button disable allowed
923               bool, // Reset button disable allowed
924               bool, // Diagnostic Interrupt button disable allowed
925               bool  // Standby (sleep) button disable allowed
926               >
927     ipmiGetChassisStatus()
928 {
929     using namespace chassis::internal;
930     std::optional<uint2_t> restorePolicy =
931         power_policy::getPowerRestorePolicy();
932     std::optional<bool> powerGood = power_policy::getPowerStatus();
933     if (!restorePolicy || !powerGood)
934     {
935         return ipmi::responseUnspecifiedError();
936     }
937 
938     //  Front Panel Button Capabilities and disable/enable status(Optional)
939     std::optional<bool> powerButtonDisabled =
940         getButtonEnabled(powerButtonPath, powerButtonIntf);
941     constexpr bool powerButtonDisableAllow = true;
942 
943     std::optional<bool> resetButtonDisabled =
944         getButtonEnabled(resetButtonPath, resetButtonIntf);
945     constexpr bool resetButtonDisableAllow = true;
946 
947     if (!powerButtonDisabled || !resetButtonDisabled)
948     {
949         return ipmi::responseUnspecifiedError();
950     }
951 
952     // This response has a lot of hard-coded, unsupported fields
953     // They are set to false or 0
954     constexpr bool powerOverload = false;
955     constexpr bool chassisInterlock = false;
956     constexpr bool powerFault = false;
957     constexpr bool powerControlFault = false;
958     constexpr bool powerDownAcFailed = false;
959     constexpr bool powerDownOverload = false;
960     constexpr bool powerDownInterlock = false;
961     constexpr bool powerDownPowerFault = false;
962     constexpr bool powerStatusIPMI = false;
963     constexpr bool chassisIntrusionActive = false;
964     constexpr bool frontPanelLockoutActive = false;
965     constexpr bool driveFault = false;
966     constexpr bool coolingFanFault = false;
967     // chassisIdentifySupport set because this command is implemented
968     constexpr bool chassisIdentifySupport = true;
969     constexpr uint2_t chassisIdentifyState(0);
970     constexpr bool diagButtonDisabled = false;
971     constexpr bool sleepButtonDisabled = false;
972     constexpr bool diagButtonDisableAllow = false;
973     constexpr bool sleepButtonDisableAllow = false;
974 
975     return ipmi::responseSuccess(
976         *powerGood, powerOverload, chassisInterlock, powerFault,
977         powerControlFault, *restorePolicy,
978         false, // reserved
979 
980         powerDownAcFailed, powerDownOverload, powerDownInterlock,
981         powerDownPowerFault, powerStatusIPMI,
982         uint3_t(0), // reserved
983 
984         chassisIntrusionActive, frontPanelLockoutActive, driveFault,
985         coolingFanFault, chassisIdentifyState, chassisIdentifySupport,
986         false, // reserved
987 
988         *powerButtonDisabled, *resetButtonDisabled, diagButtonDisabled,
989         sleepButtonDisabled, powerButtonDisableAllow, resetButtonDisableAllow,
990         diagButtonDisableAllow, sleepButtonDisableAllow);
991 }
992 
993 //-------------------------------------------------------------
994 // Send a command to SoftPowerOff application to stop any timer
995 //-------------------------------------------------------------
996 int stop_soft_off_timer()
997 {
998     constexpr auto iface = "org.freedesktop.DBus.Properties";
999     constexpr auto soft_off_iface = "xyz.openbmc_project.Ipmi.Internal."
1000                                     "SoftPowerOff";
1001 
1002     constexpr auto property = "ResponseReceived";
1003     constexpr auto value = "xyz.openbmc_project.Ipmi.Internal."
1004                            "SoftPowerOff.HostResponse.HostShutdown";
1005 
1006     // Get the system bus where most system services are provided.
1007     auto bus = ipmid_get_sd_bus_connection();
1008 
1009     // Get the service name
1010     // TODO openbmc/openbmc#1661 - Mapper refactor
1011     //
1012     // See openbmc/openbmc#1743 for some details but high level summary is that
1013     // for now the code will directly call the soft off interface due to a
1014     // race condition with mapper usage
1015     //
1016     // char *busname = nullptr;
1017     // auto r = mapper_get_service(bus, SOFTOFF_OBJPATH, &busname);
1018     // if (r < 0)
1019     //{
1020     //    fprintf(stderr, "Failed to get %s bus name: %s\n",
1021     //            SOFTOFF_OBJPATH, -r);
1022     //    return r;
1023     //}
1024 
1025     // No error object or reply expected.
1026     int rc = sd_bus_call_method(bus, SOFTOFF_BUSNAME, SOFTOFF_OBJPATH, iface,
1027                                 "Set", nullptr, nullptr, "ssv", soft_off_iface,
1028                                 property, "s", value);
1029     if (rc < 0)
1030     {
1031         log<level::ERR>("Failed to set property in SoftPowerOff object",
1032                         entry("ERRNO=0x%X", -rc));
1033     }
1034 
1035     // TODO openbmc/openbmc#1661 - Mapper refactor
1036     // free(busname);
1037     return rc;
1038 }
1039 
1040 //----------------------------------------------------------------------
1041 // Create file to indicate there is no need for softoff notification to host
1042 //----------------------------------------------------------------------
1043 void indicate_no_softoff_needed()
1044 {
1045     fs::path path{HOST_INBAND_REQUEST_DIR};
1046     if (!fs::is_directory(path))
1047     {
1048         fs::create_directory(path);
1049     }
1050 
1051     // Add the host instance (default 0 for now) to the file name
1052     std::string file{HOST_INBAND_REQUEST_FILE};
1053     auto size = std::snprintf(nullptr, 0, file.c_str(), 0);
1054     size++; // null
1055     std::unique_ptr<char[]> buf(new char[size]);
1056     std::snprintf(buf.get(), size, file.c_str(), 0);
1057 
1058     // Append file name to directory and create it
1059     path /= buf.get();
1060     std::ofstream(path.c_str());
1061 }
1062 
1063 /** @brief Implementation of chassis control command
1064  *
1065  *  @param - chassisControl command byte
1066  *
1067  *  @return  Success or InvalidFieldRequest.
1068  */
1069 ipmi::RspType<> ipmiChassisControl(uint8_t chassisControl)
1070 {
1071     int rc = 0;
1072     switch (chassisControl)
1073     {
1074         case CMD_POWER_ON:
1075             rc = initiate_state_transition(State::Host::Transition::On);
1076             break;
1077         case CMD_POWER_OFF:
1078             // This path would be hit in 2 conditions.
1079             // 1: When user asks for power off using ipmi chassis command 0x04
1080             // 2: Host asking for power off post shutting down.
1081 
1082             // If it's a host requested power off, then need to nudge Softoff
1083             // application that it needs to stop the watchdog timer if running.
1084             // If it is a user requested power off, then this is not really
1085             // needed. But then we need to differentiate between user and host
1086             // calling this same command
1087 
1088             // For now, we are going ahead with trying to nudge the soft off and
1089             // interpret the failure to do so as a non softoff case
1090             rc = stop_soft_off_timer();
1091 
1092             // Only request the Off transition if the soft power off
1093             // application is not running
1094             if (rc < 0)
1095             {
1096                 // First create a file to indicate to the soft off application
1097                 // that it should not run. Not doing this will result in State
1098                 // manager doing a default soft power off when asked for power
1099                 // off.
1100                 indicate_no_softoff_needed();
1101 
1102                 // Now request the shutdown
1103                 rc = initiate_state_transition(State::Host::Transition::Off);
1104             }
1105             else
1106             {
1107                 log<level::INFO>("Soft off is running, so let shutdown target "
1108                                  "stop the host");
1109             }
1110             break;
1111 
1112         case CMD_HARD_RESET:
1113         case CMD_POWER_CYCLE:
1114             // SPEC has a section that says certain implementations can trigger
1115             // PowerOn if power is Off when a command to power cycle is
1116             // requested
1117 
1118             // First create a file to indicate to the soft off application
1119             // that it should not run since this is a direct user initiated
1120             // power reboot request (i.e. a reboot request that is not
1121             // originating via a soft power off SMS request)
1122             indicate_no_softoff_needed();
1123 
1124             rc = initiate_state_transition(State::Host::Transition::Reboot);
1125             break;
1126 
1127         case CMD_SOFT_OFF_VIA_OVER_TEMP:
1128             // Request Host State Manager to do a soft power off
1129             rc = initiate_state_transition(State::Host::Transition::Off);
1130             break;
1131 
1132         default:
1133         {
1134             log<level::ERR>("Invalid Chassis Control command",
1135                             entry("CMD=0x%X", chassisControl));
1136             return ipmi::responseInvalidFieldRequest();
1137         }
1138     }
1139 
1140     return ((rc < 0) ? ipmi::responseUnspecifiedError()
1141                      : ipmi::responseSuccess());
1142 }
1143 
1144 /** @brief Return D-Bus connection string to enclosure identify LED object
1145  *
1146  *  @param[in, out] connection - connection to D-Bus object
1147  *  @return a IPMI return code
1148  */
1149 std::string getEnclosureIdentifyConnection()
1150 {
1151     // lookup enclosure_identify group owner(s) in mapper
1152     auto mapperCall = chassis::internal::dbus.new_method_call(
1153         ipmi::MAPPER_BUS_NAME, ipmi::MAPPER_OBJ, ipmi::MAPPER_INTF,
1154         "GetObject");
1155 
1156     mapperCall.append(identify_led_object_name);
1157     static const std::vector<std::string> interfaces = {
1158         "xyz.openbmc_project.Led.Group"};
1159     mapperCall.append(interfaces);
1160     auto mapperReply = chassis::internal::dbus.call(mapperCall);
1161     if (mapperReply.is_method_error())
1162     {
1163         log<level::ERR>("Chassis Identify: Error communicating to mapper.");
1164         elog<InternalFailure>();
1165     }
1166     std::vector<std::pair<std::string, std::vector<std::string>>> mapperResp;
1167     mapperReply.read(mapperResp);
1168 
1169     if (mapperResp.size() != encIdentifyObjectsSize)
1170     {
1171         log<level::ERR>(
1172             "Invalid number of enclosure identify objects.",
1173             entry("ENC_IDENTITY_OBJECTS_SIZE=%d", mapperResp.size()));
1174         elog<InternalFailure>();
1175     }
1176     auto pair = mapperResp[encIdentifyObjectsSize - 1];
1177     return pair.first;
1178 }
1179 
1180 /** @brief Turn On/Off enclosure identify LED
1181  *
1182  *  @param[in] flag - true to turn on LED, false to turn off
1183  *  @return a IPMI return code
1184  */
1185 void enclosureIdentifyLed(bool flag)
1186 {
1187     using namespace chassis::internal;
1188     std::string connection = std::move(getEnclosureIdentifyConnection());
1189     auto msg = std::string("enclosureIdentifyLed(") +
1190                boost::lexical_cast<std::string>(flag) + ")";
1191     log<level::DEBUG>(msg.c_str());
1192     auto led =
1193         dbus.new_method_call(connection.c_str(), identify_led_object_name,
1194                              "org.freedesktop.DBus.Properties", "Set");
1195     led.append("xyz.openbmc_project.Led.Group", "Asserted",
1196                std::variant<bool>(flag));
1197     auto ledReply = dbus.call(led);
1198     if (ledReply.is_method_error())
1199     {
1200         log<level::ERR>("Chassis Identify: Error Setting State On/Off\n",
1201                         entry("LED_STATE=%d", flag));
1202         elog<InternalFailure>();
1203     }
1204 }
1205 
1206 /** @brief Callback method to turn off LED
1207  */
1208 void enclosureIdentifyLedOff()
1209 {
1210     try
1211     {
1212         enclosureIdentifyLed(false);
1213     }
1214     catch (const InternalFailure& e)
1215     {
1216         report<InternalFailure>();
1217     }
1218 }
1219 
1220 /** @brief Create timer to turn on and off the enclosure LED
1221  */
1222 void createIdentifyTimer()
1223 {
1224     if (!identifyTimer)
1225     {
1226         identifyTimer =
1227             std::make_unique<phosphor::Timer>(enclosureIdentifyLedOff);
1228     }
1229 }
1230 
1231 ipmi::RspType<> ipmiChassisIdentify(std::optional<uint8_t> interval,
1232                                     std::optional<uint8_t> force)
1233 {
1234     uint8_t identifyInterval = interval.value_or(DEFAULT_IDENTIFY_TIME_OUT);
1235     bool forceIdentify = force.value_or(0) & 0x01;
1236 
1237     if (identifyInterval || forceIdentify)
1238     {
1239         // stop the timer if already started;
1240         // for force identify we should not turn off LED
1241         identifyTimer->stop();
1242         try
1243         {
1244             enclosureIdentifyLed(true);
1245         }
1246         catch (const InternalFailure& e)
1247         {
1248             report<InternalFailure>();
1249             return ipmi::responseResponseError();
1250         }
1251 
1252         if (forceIdentify)
1253         {
1254             return ipmi::responseSuccess();
1255         }
1256         // start the timer
1257         auto time = std::chrono::duration_cast<std::chrono::microseconds>(
1258             std::chrono::seconds(identifyInterval));
1259         identifyTimer->start(time);
1260     }
1261     else if (!identifyInterval)
1262     {
1263         identifyTimer->stop();
1264         enclosureIdentifyLedOff();
1265     }
1266     return ipmi::responseSuccess();
1267 }
1268 
1269 namespace boot_options
1270 {
1271 
1272 using namespace sdbusplus::xyz::openbmc_project::Control::Boot::server;
1273 using IpmiValue = uint8_t;
1274 constexpr auto ipmiDefault = 0;
1275 
1276 std::map<IpmiValue, Source::Sources> sourceIpmiToDbus = {
1277     {0x01, Source::Sources::Network},
1278     {0x02, Source::Sources::Disk},
1279     {0x05, Source::Sources::ExternalMedia},
1280     {ipmiDefault, Source::Sources::Default}};
1281 
1282 std::map<IpmiValue, Mode::Modes> modeIpmiToDbus = {
1283     {0x03, Mode::Modes::Safe},
1284     {0x06, Mode::Modes::Setup},
1285     {ipmiDefault, Mode::Modes::Regular}};
1286 
1287 std::map<Source::Sources, IpmiValue> sourceDbusToIpmi = {
1288     {Source::Sources::Network, 0x01},
1289     {Source::Sources::Disk, 0x02},
1290     {Source::Sources::ExternalMedia, 0x05},
1291     {Source::Sources::Default, ipmiDefault}};
1292 
1293 std::map<Mode::Modes, IpmiValue> modeDbusToIpmi = {
1294     {Mode::Modes::Safe, 0x03},
1295     {Mode::Modes::Setup, 0x06},
1296     {Mode::Modes::Regular, ipmiDefault}};
1297 
1298 } // namespace boot_options
1299 
1300 /** @brief Set the property value for boot source
1301  *  @param[in] source - boot source value
1302  *  @return On failure return IPMI error.
1303  */
1304 static ipmi_ret_t setBootSource(const Source::Sources& source)
1305 {
1306     using namespace chassis::internal;
1307     using namespace chassis::internal::cache;
1308     std::variant<std::string> property = convertForMessage(source);
1309     auto bootSetting = settings::boot::setting(objects, bootSourceIntf);
1310     const auto& bootSourceSetting = std::get<settings::Path>(bootSetting);
1311     auto method = dbus.new_method_call(
1312         objects.service(bootSourceSetting, bootSourceIntf).c_str(),
1313         bootSourceSetting.c_str(), ipmi::PROP_INTF, "Set");
1314     method.append(bootSourceIntf, "BootSource", property);
1315     auto reply = dbus.call(method);
1316     if (reply.is_method_error())
1317     {
1318         log<level::ERR>("Error in BootSource Set");
1319         report<InternalFailure>();
1320         return IPMI_CC_UNSPECIFIED_ERROR;
1321     }
1322     return IPMI_CC_OK;
1323 }
1324 
1325 /** @brief Set the property value for boot mode
1326  *  @param[in] mode - boot mode value
1327  *  @return On failure return IPMI error.
1328  */
1329 static ipmi_ret_t setBootMode(const Mode::Modes& mode)
1330 {
1331     using namespace chassis::internal;
1332     using namespace chassis::internal::cache;
1333     std::variant<std::string> property = convertForMessage(mode);
1334     auto bootSetting = settings::boot::setting(objects, bootModeIntf);
1335     const auto& bootModeSetting = std::get<settings::Path>(bootSetting);
1336     auto method = dbus.new_method_call(
1337         objects.service(bootModeSetting, bootModeIntf).c_str(),
1338         bootModeSetting.c_str(), ipmi::PROP_INTF, "Set");
1339     method.append(bootModeIntf, "BootMode", property);
1340     auto reply = dbus.call(method);
1341     if (reply.is_method_error())
1342     {
1343         log<level::ERR>("Error in BootMode Set");
1344         report<InternalFailure>();
1345         return IPMI_CC_UNSPECIFIED_ERROR;
1346     }
1347     return IPMI_CC_OK;
1348 }
1349 
1350 ipmi_ret_t ipmi_chassis_get_sys_boot_options(ipmi_netfn_t netfn, ipmi_cmd_t cmd,
1351                                              ipmi_request_t request,
1352                                              ipmi_response_t response,
1353                                              ipmi_data_len_t data_len,
1354                                              ipmi_context_t context)
1355 {
1356     using namespace boot_options;
1357     ipmi_ret_t rc = IPMI_CC_PARM_NOT_SUPPORTED;
1358     char* p = NULL;
1359     get_sys_boot_options_response_t* resp =
1360         (get_sys_boot_options_response_t*)response;
1361     get_sys_boot_options_t* reqptr = (get_sys_boot_options_t*)request;
1362     IpmiValue bootOption = ipmiDefault;
1363 
1364     std::memset(resp, 0, sizeof(*resp));
1365     resp->version = SET_PARM_VERSION;
1366     resp->parm = 5;
1367     resp->data[0] = SET_PARM_BOOT_FLAGS_VALID_ONE_TIME;
1368 
1369     /*
1370      * Parameter #5 means boot flags. Please refer to 28.13 of ipmi doc.
1371      * This is the only parameter used by petitboot.
1372      */
1373     if (reqptr->parameter ==
1374         static_cast<uint8_t>(BootOptionParameter::BOOT_FLAGS))
1375     {
1376 
1377         *data_len = static_cast<uint8_t>(BootOptionResponseSize::BOOT_FLAGS);
1378         using namespace chassis::internal;
1379         using namespace chassis::internal::cache;
1380 
1381         try
1382         {
1383             auto bootSetting = settings::boot::setting(objects, bootSourceIntf);
1384             const auto& bootSourceSetting =
1385                 std::get<settings::Path>(bootSetting);
1386             auto oneTimeEnabled =
1387                 std::get<settings::boot::OneTimeEnabled>(bootSetting);
1388             auto method = dbus.new_method_call(
1389                 objects.service(bootSourceSetting, bootSourceIntf).c_str(),
1390                 bootSourceSetting.c_str(), ipmi::PROP_INTF, "Get");
1391             method.append(bootSourceIntf, "BootSource");
1392             auto reply = dbus.call(method);
1393             if (reply.is_method_error())
1394             {
1395                 log<level::ERR>("Error in BootSource Get");
1396                 report<InternalFailure>();
1397                 *data_len = 0;
1398                 return IPMI_CC_UNSPECIFIED_ERROR;
1399             }
1400             std::variant<std::string> result;
1401             reply.read(result);
1402             auto bootSource =
1403                 Source::convertSourcesFromString(std::get<std::string>(result));
1404 
1405             bootSetting = settings::boot::setting(objects, bootModeIntf);
1406             const auto& bootModeSetting = std::get<settings::Path>(bootSetting);
1407             method = dbus.new_method_call(
1408                 objects.service(bootModeSetting, bootModeIntf).c_str(),
1409                 bootModeSetting.c_str(), ipmi::PROP_INTF, "Get");
1410             method.append(bootModeIntf, "BootMode");
1411             reply = dbus.call(method);
1412             if (reply.is_method_error())
1413             {
1414                 log<level::ERR>("Error in BootMode Get");
1415                 report<InternalFailure>();
1416                 *data_len = 0;
1417                 return IPMI_CC_UNSPECIFIED_ERROR;
1418             }
1419             reply.read(result);
1420             auto bootMode =
1421                 Mode::convertModesFromString(std::get<std::string>(result));
1422 
1423             bootOption = sourceDbusToIpmi.at(bootSource);
1424             if ((Mode::Modes::Regular == bootMode) &&
1425                 (Source::Sources::Default == bootSource))
1426             {
1427                 bootOption = ipmiDefault;
1428             }
1429             else if (Source::Sources::Default == bootSource)
1430             {
1431                 bootOption = modeDbusToIpmi.at(bootMode);
1432             }
1433             resp->data[1] = (bootOption << 2);
1434 
1435             resp->data[0] = oneTimeEnabled
1436                                 ? SET_PARM_BOOT_FLAGS_VALID_ONE_TIME
1437                                 : SET_PARM_BOOT_FLAGS_VALID_PERMANENT;
1438 
1439             rc = IPMI_CC_OK;
1440         }
1441         catch (InternalFailure& e)
1442         {
1443             report<InternalFailure>();
1444             *data_len = 0;
1445             return IPMI_CC_UNSPECIFIED_ERROR;
1446         }
1447     }
1448     else if (reqptr->parameter ==
1449              static_cast<uint8_t>(BootOptionParameter::OPAL_NETWORK_SETTINGS))
1450     {
1451 
1452         *data_len =
1453             static_cast<uint8_t>(BootOptionResponseSize::OPAL_NETWORK_SETTINGS);
1454 
1455         resp->parm =
1456             static_cast<uint8_t>(BootOptionParameter::OPAL_NETWORK_SETTINGS);
1457 
1458         int ret = getHostNetworkData(resp);
1459 
1460         if (ret < 0)
1461         {
1462 
1463             log<level::ERR>(
1464                 "getHostNetworkData failed for get_sys_boot_options.");
1465             rc = IPMI_CC_UNSPECIFIED_ERROR;
1466         }
1467         else
1468             rc = IPMI_CC_OK;
1469     }
1470 
1471     else
1472     {
1473         log<level::ERR>("Unsupported parameter",
1474                         entry("PARAM=0x%x", reqptr->parameter));
1475     }
1476 
1477     if (p)
1478         free(p);
1479 
1480     if (rc == IPMI_CC_OK)
1481     {
1482         *data_len += 2;
1483     }
1484 
1485     return rc;
1486 }
1487 
1488 ipmi_ret_t ipmi_chassis_set_sys_boot_options(ipmi_netfn_t netfn, ipmi_cmd_t cmd,
1489                                              ipmi_request_t request,
1490                                              ipmi_response_t response,
1491                                              ipmi_data_len_t data_len,
1492                                              ipmi_context_t context)
1493 {
1494     using namespace boot_options;
1495     ipmi_ret_t rc = IPMI_CC_OK;
1496     set_sys_boot_options_t* reqptr = (set_sys_boot_options_t*)request;
1497 
1498     std::printf("IPMI SET_SYS_BOOT_OPTIONS reqptr->parameter =[%d]\n",
1499                 reqptr->parameter);
1500 
1501     // This IPMI command does not have any resposne data
1502     *data_len = 0;
1503 
1504     /*  000101
1505      * Parameter #5 means boot flags. Please refer to 28.13 of ipmi doc.
1506      * This is the only parameter used by petitboot.
1507      */
1508 
1509     if (reqptr->parameter == (uint8_t)BootOptionParameter::BOOT_FLAGS)
1510     {
1511         IpmiValue bootOption = ((reqptr->data[1] & 0x3C) >> 2);
1512         using namespace chassis::internal;
1513         using namespace chassis::internal::cache;
1514         auto oneTimeEnabled = false;
1515         constexpr auto enabledIntf = "xyz.openbmc_project.Object.Enable";
1516         constexpr auto oneTimePath =
1517             "/xyz/openbmc_project/control/host0/boot/one_time";
1518 
1519         try
1520         {
1521             bool permanent =
1522                 (reqptr->data[0] & SET_PARM_BOOT_FLAGS_PERMANENT) ==
1523                 SET_PARM_BOOT_FLAGS_PERMANENT;
1524 
1525             auto bootSetting = settings::boot::setting(objects, bootSourceIntf);
1526 
1527             oneTimeEnabled =
1528                 std::get<settings::boot::OneTimeEnabled>(bootSetting);
1529 
1530             /*
1531              * Check if the current boot setting is onetime or permanent, if the
1532              * request in the command is otherwise, then set the "Enabled"
1533              * property in one_time object path to 'True' to indicate onetime
1534              * and 'False' to indicate permanent.
1535              *
1536              * Once the onetime/permanent setting is applied, then the bootMode
1537              * and bootSource is updated for the corresponding object.
1538              */
1539             if ((permanent && oneTimeEnabled) ||
1540                 (!permanent && !oneTimeEnabled))
1541             {
1542                 auto service = ipmi::getService(dbus, enabledIntf, oneTimePath);
1543 
1544                 ipmi::setDbusProperty(dbus, service, oneTimePath, enabledIntf,
1545                                       "Enabled", !permanent);
1546             }
1547 
1548             auto modeItr = modeIpmiToDbus.find(bootOption);
1549             auto sourceItr = sourceIpmiToDbus.find(bootOption);
1550             if (sourceIpmiToDbus.end() != sourceItr)
1551             {
1552                 rc = setBootSource(sourceItr->second);
1553                 if (rc != IPMI_CC_OK)
1554                 {
1555                     *data_len = 0;
1556                     return rc;
1557                 }
1558                 // If a set boot device is mapping to a boot source, then reset
1559                 // the boot mode D-Bus property to default.
1560                 // This way the ipmid code can determine which property is not
1561                 // at the default value
1562                 if (sourceItr->second != Source::Sources::Default)
1563                 {
1564                     setBootMode(Mode::Modes::Regular);
1565                 }
1566             }
1567             if (modeIpmiToDbus.end() != modeItr)
1568             {
1569                 rc = setBootMode(modeItr->second);
1570                 if (rc != IPMI_CC_OK)
1571                 {
1572                     *data_len = 0;
1573                     return rc;
1574                 }
1575                 // If a set boot device is mapping to a boot mode, then reset
1576                 // the boot source D-Bus property to default.
1577                 // This way the ipmid code can determine which property is not
1578                 // at the default value
1579                 if (modeItr->second != Mode::Modes::Regular)
1580                 {
1581                     setBootSource(Source::Sources::Default);
1582                 }
1583             }
1584         }
1585         catch (InternalFailure& e)
1586         {
1587             report<InternalFailure>();
1588             *data_len = 0;
1589             return IPMI_CC_UNSPECIFIED_ERROR;
1590         }
1591     }
1592     else if (reqptr->parameter ==
1593              (uint8_t)BootOptionParameter::OPAL_NETWORK_SETTINGS)
1594     {
1595 
1596         int ret = setHostNetworkData(reqptr);
1597         if (ret < 0)
1598         {
1599             log<level::ERR>(
1600                 "setHostNetworkData failed for set_sys_boot_options");
1601             rc = IPMI_CC_UNSPECIFIED_ERROR;
1602         }
1603     }
1604     else if (reqptr->parameter ==
1605              static_cast<uint8_t>(BootOptionParameter::BOOT_INFO))
1606     {
1607         // Handle parameter #4 and return command completed normally
1608         // (IPMI_CC_OK). There is no implementation in OpenBMC for this
1609         // parameter. This is added to support the ipmitool command `chassis
1610         // bootdev` which sends set on parameter #4, before setting the boot
1611         // flags.
1612         rc = IPMI_CC_OK;
1613     }
1614     else
1615     {
1616         log<level::ERR>("Unsupported parameter",
1617                         entry("PARAM=0x%x", reqptr->parameter));
1618         rc = IPMI_CC_PARM_NOT_SUPPORTED;
1619     }
1620 
1621     return rc;
1622 }
1623 
1624 /** @brief implements Get POH counter command
1625  *  @parameter
1626  *   -  none
1627  *  @returns IPMI completion code plus response data
1628  *   - minPerCount - Minutes per count
1629  *   - counterReading - counter reading
1630  */
1631 ipmi::RspType<uint8_t, // Minutes per count
1632               uint32_t // Counter reading
1633               >
1634     ipmiGetPOHCounter()
1635 {
1636     // sd_bus error
1637     try
1638     {
1639         return ipmi::responseSuccess(static_cast<uint8_t>(poh::minutesPerCount),
1640                                      getPOHCounter());
1641     }
1642     catch (std::exception& e)
1643     {
1644         log<level::ERR>(e.what());
1645         return ipmi::responseUnspecifiedError();
1646     }
1647 }
1648 
1649 ipmi::RspType<uint8_t>
1650     ipmiChassisSetPowerRestorePolicy(boost::asio::yield_context yield,
1651                                      uint8_t policy)
1652 {
1653     constexpr uint8_t ccParamNotSupported = 0x80;
1654     power_policy::DbusValue value =
1655         power_policy::RestorePolicy::Policy::AlwaysOff;
1656 
1657     if (policy & ~power_policy::policyBitMask)
1658     {
1659         phosphor::logging::log<level::ERR>(
1660             "Reserved request parameter",
1661             entry("REQ=0x%x", static_cast<int>(policy)));
1662         return ipmi::response(ccParamNotSupported);
1663     }
1664 
1665     if (policy == power_policy::noChange)
1666     {
1667         // just return the supported policy
1668         return ipmi::responseSuccess(power_policy::allSupport);
1669     }
1670 
1671     for (auto const& it : power_policy::dbusToIpmi)
1672     {
1673         if (it.second == policy)
1674         {
1675             value = it.first;
1676             break;
1677         }
1678     }
1679 
1680     try
1681     {
1682         const settings::Path& powerRestoreSetting =
1683             chassis::internal::cache::objects.map
1684                 .at(chassis::internal::powerRestoreIntf)
1685                 .front();
1686         std::variant<std::string> property = convertForMessage(value);
1687 
1688         auto sdbusp = getSdBus();
1689         boost::system::error_code ec;
1690         sdbusp->yield_method_call<void>(
1691             yield, ec,
1692             chassis::internal::cache::objects
1693                 .service(powerRestoreSetting,
1694                          chassis::internal::powerRestoreIntf)
1695                 .c_str(),
1696             powerRestoreSetting, ipmi::PROP_INTF, "Set",
1697             chassis::internal::powerRestoreIntf, "PowerRestorePolicy",
1698             property);
1699         if (ec)
1700         {
1701             phosphor::logging::log<level::ERR>("Unspecified Error");
1702             return ipmi::responseUnspecifiedError();
1703         }
1704     }
1705     catch (InternalFailure& e)
1706     {
1707         report<InternalFailure>();
1708         return ipmi::responseUnspecifiedError();
1709     }
1710 
1711     return ipmi::responseSuccess(power_policy::allSupport);
1712 }
1713 
1714 void register_netfn_chassis_functions()
1715 {
1716     createIdentifyTimer();
1717 
1718     // <Wildcard Command>
1719     ipmi_register_callback(NETFUN_CHASSIS, IPMI_CMD_WILDCARD, NULL,
1720                            ipmi_chassis_wildcard, PRIVILEGE_USER);
1721 
1722     // Get Chassis Capabilities
1723     ipmi_register_callback(NETFUN_CHASSIS, IPMI_CMD_GET_CHASSIS_CAP, NULL,
1724                            ipmi_get_chassis_cap, PRIVILEGE_USER);
1725 
1726     // Set Chassis Capabilities
1727     ipmi_register_callback(NETFUN_CHASSIS, IPMI_CMD_SET_CHASSIS_CAP, NULL,
1728                            ipmi_set_chassis_cap, PRIVILEGE_USER);
1729 
1730     // <Get System Boot Options>
1731     ipmi_register_callback(NETFUN_CHASSIS, IPMI_CMD_GET_SYS_BOOT_OPTIONS, NULL,
1732                            ipmi_chassis_get_sys_boot_options,
1733                            PRIVILEGE_OPERATOR);
1734 
1735     // <Get Chassis Status>
1736     ipmi::registerHandler(ipmi::prioOpenBmcBase, ipmi::netFnChassis,
1737                           ipmi::chassis::cmdGetChassisStatus,
1738                           ipmi::Privilege::User, ipmiGetChassisStatus);
1739 
1740     // <Chassis Control>
1741     ipmi::registerHandler(ipmi::prioOpenBmcBase, ipmi::netFnChassis,
1742                           ipmi::chassis::cmdChassisControl,
1743                           ipmi::Privilege::Operator, ipmiChassisControl);
1744 
1745     // <Chassis Identify>
1746     ipmi::registerHandler(ipmi::prioOpenBmcBase, ipmi::netFnChassis,
1747                           ipmi::chassis::cmdChassisIdentify,
1748                           ipmi::Privilege::Operator, ipmiChassisIdentify);
1749 
1750     // <Set System Boot Options>
1751     ipmi_register_callback(NETFUN_CHASSIS, IPMI_CMD_SET_SYS_BOOT_OPTIONS, NULL,
1752                            ipmi_chassis_set_sys_boot_options,
1753                            PRIVILEGE_OPERATOR);
1754     // <Get POH Counter>
1755     ipmi::registerHandler(ipmi::prioOpenBmcBase, ipmi::netFnChassis,
1756                           ipmi::chassis::cmdGetPohCounter,
1757                           ipmi::Privilege::User, ipmiGetPOHCounter);
1758 
1759     // <Set Power Restore Policy>
1760     ipmi::registerHandler(ipmi::prioOpenBmcBase, ipmi::netFnChassis,
1761                           ipmi::chassis::cmdSetPowerRestorePolicy,
1762                           ipmi::Privilege::Operator,
1763                           ipmiChassisSetPowerRestorePolicy);
1764 }
1765