blob: 58f68686d5679aee0da417acdd8810a1a106f4e2 [file] [log] [blame]
Potin Lai5d214202023-01-16 18:11:49 +08001#include "config.h"
2
Patrick Venture0b02be92018-08-31 11:55:55 -07003#include <arpa/inet.h>
Richard Marian Thomaiyar84bf9be2019-04-26 22:59:16 +05304#include <fcntl.h>
Xo Wang87651332017-08-11 10:17:59 -07005#include <limits.h>
Richard Marian Thomaiyar84bf9be2019-04-26 22:59:16 +05306#include <linux/i2c-dev.h>
7#include <linux/i2c.h>
Patrick Venture0b02be92018-08-31 11:55:55 -07008#include <mapper.h>
Richard Marian Thomaiyar84bf9be2019-04-26 22:59:16 +05309#include <sys/ioctl.h>
10#include <sys/stat.h>
11#include <sys/types.h>
Patrick Venture0b02be92018-08-31 11:55:55 -070012#include <systemd/sd-bus.h>
Xo Wang87651332017-08-11 10:17:59 -070013#include <unistd.h>
Patrick Venture0b02be92018-08-31 11:55:55 -070014
Patrick Venture3a5071a2018-09-12 13:27:42 -070015#include <algorithm>
Vernon Mauery0120b682019-03-25 13:08:54 -070016#include <app/channel.hpp>
17#include <app/watchdog.hpp>
18#include <apphandler.hpp>
Patrick Venture3a5071a2018-09-12 13:27:42 -070019#include <array>
Willy Tu886d6842022-06-03 02:50:47 -070020#include <charconv>
Patrick Venture3a5071a2018-09-12 13:27:42 -070021#include <cstddef>
Vernon Mauery0120b682019-03-25 13:08:54 -070022#include <cstdint>
Vernon Mauerybdda8002019-02-26 10:18:51 -080023#include <filesystem>
Patrick Venture3a5071a2018-09-12 13:27:42 -070024#include <fstream>
Vernon Mauery0120b682019-03-25 13:08:54 -070025#include <ipmid/api.hpp>
Rajashekar Gade Reddye7023922019-07-10 16:54:55 +000026#include <ipmid/sessiondef.hpp>
27#include <ipmid/sessionhelper.hpp>
Vernon Mauery33250242019-03-12 16:49:26 -070028#include <ipmid/types.hpp>
Vernon Mauery6a98fe72019-03-11 15:57:48 -070029#include <ipmid/utils.hpp>
Patrick Venture3a5071a2018-09-12 13:27:42 -070030#include <memory>
Patrick Venture46470a32018-09-07 19:26:25 -070031#include <nlohmann/json.hpp>
Patrick Venture3a5071a2018-09-12 13:27:42 -070032#include <phosphor-logging/elog-errors.hpp>
33#include <phosphor-logging/log.hpp>
Potin Lai5d214202023-01-16 18:11:49 +080034#include <regex>
William A. Kennington III4c008022018-10-12 17:18:14 -070035#include <sdbusplus/message/types.hpp>
Patrick Venture3a5071a2018-09-12 13:27:42 -070036#include <string>
Willy Tu886d6842022-06-03 02:50:47 -070037#include <string_view>
Vernon Mauery0120b682019-03-25 13:08:54 -070038#include <sys_info_param.hpp>
Patrick Venture3a5071a2018-09-12 13:27:42 -070039#include <tuple>
40#include <vector>
41#include <xyz/openbmc_project/Common/error.hpp>
Yong Li18d77262018-10-09 01:59:45 +080042#include <xyz/openbmc_project/Control/Power/ACPIPowerState/server.hpp>
Patrick Venture3a5071a2018-09-12 13:27:42 -070043#include <xyz/openbmc_project/Software/Activation/server.hpp>
44#include <xyz/openbmc_project/Software/Version/server.hpp>
45#include <xyz/openbmc_project/State/BMC/server.hpp>
Ratan Guptab8e99552017-07-27 07:07:48 +053046
Patrick Venture0b02be92018-08-31 11:55:55 -070047extern sd_bus* bus;
vishwabmcba0bd5f2015-09-30 16:50:23 +053048
Alexander Amelkinba19c182018-09-04 15:49:36 +030049constexpr auto bmc_state_interface = "xyz.openbmc_project.State.BMC";
50constexpr auto bmc_state_property = "CurrentBMCState";
Marri Devender Rao5e007a52018-01-08 06:18:36 -060051
Nagaraju Goruganti744398d2018-02-20 09:52:00 -060052static constexpr auto redundancyIntf =
53 "xyz.openbmc_project.Software.RedundancyPriority";
Patrick Venture0b02be92018-08-31 11:55:55 -070054static constexpr auto versionIntf = "xyz.openbmc_project.Software.Version";
Nagaraju Goruganti744398d2018-02-20 09:52:00 -060055static constexpr auto activationIntf =
56 "xyz.openbmc_project.Software.Activation";
57static constexpr auto softwareRoot = "/xyz/openbmc_project/software";
58
Chris Austen6caf28b2015-10-13 12:40:40 -050059void register_netfn_app_functions() __attribute__((constructor));
vishwabmcba0bd5f2015-09-30 16:50:23 +053060
Ratan Guptab8e99552017-07-27 07:07:48 +053061using namespace phosphor::logging;
62using namespace sdbusplus::xyz::openbmc_project::Common::Error;
Nagaraju Goruganti744398d2018-02-20 09:52:00 -060063using Version = sdbusplus::xyz::openbmc_project::Software::server::Version;
64using Activation =
65 sdbusplus::xyz::openbmc_project::Software::server::Activation;
Alexander Amelkinba19c182018-09-04 15:49:36 +030066using BMC = sdbusplus::xyz::openbmc_project::State::server::BMC;
Vernon Mauery185b9f82018-07-20 10:52:36 -070067namespace fs = std::filesystem;
Ratan Guptab8e99552017-07-27 07:07:48 +053068
Yong Libd0503a2019-08-22 17:17:17 +080069#ifdef ENABLE_I2C_WHITELIST_CHECK
Richard Marian Thomaiyar84bf9be2019-04-26 22:59:16 +053070typedef struct
71{
72 uint8_t busId;
73 uint8_t slaveAddr;
74 uint8_t slaveAddrMask;
75 std::vector<uint8_t> data;
76 std::vector<uint8_t> dataMask;
77} i2cMasterWRWhitelist;
78
79static std::vector<i2cMasterWRWhitelist>& getWRWhitelist()
80{
81 static std::vector<i2cMasterWRWhitelist> wrWhitelist;
82 return wrWhitelist;
83}
84
85static constexpr const char* i2cMasterWRWhitelistFile =
86 "/usr/share/ipmi-providers/master_write_read_white_list.json";
87
Richard Marian Thomaiyar84bf9be2019-04-26 22:59:16 +053088static constexpr const char* filtersStr = "filters";
89static constexpr const char* busIdStr = "busId";
90static constexpr const char* slaveAddrStr = "slaveAddr";
91static constexpr const char* slaveAddrMaskStr = "slaveAddrMask";
92static constexpr const char* cmdStr = "command";
93static constexpr const char* cmdMaskStr = "commandMask";
94static constexpr int base_16 = 16;
Yong Libd0503a2019-08-22 17:17:17 +080095#endif // ENABLE_I2C_WHITELIST_CHECK
Joshi-Mansi7fd91fa2021-06-11 07:18:15 +053096static constexpr uint8_t maxIPMIWriteReadSize = 255;
jayaprakash Mutyala3c5e4132020-04-27 23:00:05 +000097static constexpr uint8_t oemCmdStart = 192;
98static constexpr uint8_t oemCmdEnd = 255;
99static constexpr uint8_t invalidParamSelectorStart = 8;
100static constexpr uint8_t invalidParamSelectorEnd = 191;
Richard Marian Thomaiyar84bf9be2019-04-26 22:59:16 +0530101
Nagaraju Goruganti744398d2018-02-20 09:52:00 -0600102/**
103 * @brief Returns the Version info from primary s/w object
104 *
105 * Get the Version info from the active s/w object which is having high
106 * "Priority" value(a smaller number is a higher priority) and "Purpose"
107 * is "BMC" from the list of all s/w objects those are implementing
108 * RedundancyPriority interface from the given softwareRoot path.
109 *
110 * @return On success returns the Version info from primary s/w object.
111 *
112 */
Vernon Maueryea1c4012019-05-24 13:26:16 -0700113std::string getActiveSoftwareVersionInfo(ipmi::Context::ptr ctx)
Nagaraju Goruganti744398d2018-02-20 09:52:00 -0600114{
Nagaraju Goruganti744398d2018-02-20 09:52:00 -0600115 std::string revision{};
Vernon Mauery86a50822019-03-25 13:11:36 -0700116 ipmi::ObjectTree objectTree;
117 try
Nagaraju Goruganti744398d2018-02-20 09:52:00 -0600118 {
Vernon Mauery86a50822019-03-25 13:11:36 -0700119 objectTree =
Vernon Maueryea1c4012019-05-24 13:26:16 -0700120 ipmi::getAllDbusObjects(*ctx->bus, softwareRoot, redundancyIntf);
Vernon Mauery86a50822019-03-25 13:11:36 -0700121 }
Patrick Williams5d82f472022-07-22 19:26:53 -0500122 catch (const sdbusplus::exception_t& e)
Vernon Mauery86a50822019-03-25 13:11:36 -0700123 {
124 log<level::ERR>("Failed to fetch redundancy object from dbus",
125 entry("INTERFACE=%s", redundancyIntf),
126 entry("ERRMSG=%s", e.what()));
Nagaraju Goruganti744398d2018-02-20 09:52:00 -0600127 elog<InternalFailure>();
128 }
129
130 auto objectFound = false;
131 for (auto& softObject : objectTree)
132 {
Vernon Mauery86a50822019-03-25 13:11:36 -0700133 auto service =
Vernon Maueryea1c4012019-05-24 13:26:16 -0700134 ipmi::getService(*ctx->bus, redundancyIntf, softObject.first);
Vernon Mauery86a50822019-03-25 13:11:36 -0700135 auto objValueTree =
Vernon Maueryea1c4012019-05-24 13:26:16 -0700136 ipmi::getManagedObjects(*ctx->bus, service, softwareRoot);
Nagaraju Goruganti744398d2018-02-20 09:52:00 -0600137
138 auto minPriority = 0xFF;
139 for (const auto& objIter : objValueTree)
140 {
141 try
142 {
143 auto& intfMap = objIter.second;
144 auto& redundancyPriorityProps = intfMap.at(redundancyIntf);
145 auto& versionProps = intfMap.at(versionIntf);
146 auto& activationProps = intfMap.at(activationIntf);
Vernon Maueryf442e112019-04-09 11:44:36 -0700147 auto priority =
148 std::get<uint8_t>(redundancyPriorityProps.at("Priority"));
William A. Kennington III4c008022018-10-12 17:18:14 -0700149 auto purpose =
Vernon Maueryf442e112019-04-09 11:44:36 -0700150 std::get<std::string>(versionProps.at("Purpose"));
151 auto activation =
152 std::get<std::string>(activationProps.at("Activation"));
William A. Kennington III4c008022018-10-12 17:18:14 -0700153 auto version =
Vernon Maueryf442e112019-04-09 11:44:36 -0700154 std::get<std::string>(versionProps.at("Version"));
Nagaraju Goruganti744398d2018-02-20 09:52:00 -0600155 if ((Version::convertVersionPurposeFromString(purpose) ==
156 Version::VersionPurpose::BMC) &&
157 (Activation::convertActivationsFromString(activation) ==
158 Activation::Activations::Active))
159 {
160 if (priority < minPriority)
161 {
162 minPriority = priority;
163 objectFound = true;
164 revision = std::move(version);
165 }
166 }
167 }
168 catch (const std::exception& e)
169 {
170 log<level::ERR>(e.what());
171 }
172 }
173 }
174
175 if (!objectFound)
176 {
177 log<level::ERR>("Could not found an BMC software Object");
178 elog<InternalFailure>();
179 }
180
181 return revision;
182}
183
Alexander Amelkinba19c182018-09-04 15:49:36 +0300184bool getCurrentBmcState()
185{
Patrick Williams5d82f472022-07-22 19:26:53 -0500186 sdbusplus::bus_t bus{ipmid_get_sd_bus_connection()};
Alexander Amelkinba19c182018-09-04 15:49:36 +0300187
188 // Get the Inventory object implementing the BMC interface
189 ipmi::DbusObjectInfo bmcObject =
190 ipmi::getDbusObject(bus, bmc_state_interface);
191 auto variant =
192 ipmi::getDbusProperty(bus, bmcObject.second, bmcObject.first,
193 bmc_state_interface, bmc_state_property);
194
Vernon Maueryf442e112019-04-09 11:44:36 -0700195 return std::holds_alternative<std::string>(variant) &&
196 BMC::convertBMCStateFromString(std::get<std::string>(variant)) ==
197 BMC::BMCState::Ready;
Alexander Amelkinba19c182018-09-04 15:49:36 +0300198}
199
Patrick Venture94930a12019-04-30 10:01:58 -0700200bool getCurrentBmcStateWithFallback(const bool fallbackAvailability)
201{
202 try
203 {
204 return getCurrentBmcState();
205 }
206 catch (...)
207 {
208 // Nothing provided the BMC interface, therefore return whatever was
209 // configured as the default.
210 return fallbackAvailability;
211 }
212}
213
Yong Li18d77262018-10-09 01:59:45 +0800214namespace acpi_state
215{
216using namespace sdbusplus::xyz::openbmc_project::Control::Power::server;
217
218const static constexpr char* acpiObjPath =
219 "/xyz/openbmc_project/control/host0/acpi_power_state";
220const static constexpr char* acpiInterface =
221 "xyz.openbmc_project.Control.Power.ACPIPowerState";
222const static constexpr char* sysACPIProp = "SysACPIStatus";
223const static constexpr char* devACPIProp = "DevACPIStatus";
224
225enum class PowerStateType : uint8_t
226{
227 sysPowerState = 0x00,
228 devPowerState = 0x01,
229};
230
231// Defined in 20.6 of ipmi doc
232enum class PowerState : uint8_t
233{
234 s0G0D0 = 0x00,
235 s1D1 = 0x01,
236 s2D2 = 0x02,
237 s3D3 = 0x03,
238 s4 = 0x04,
239 s5G2 = 0x05,
240 s4S5 = 0x06,
241 g3 = 0x07,
242 sleep = 0x08,
243 g1Sleep = 0x09,
244 override = 0x0a,
245 legacyOn = 0x20,
246 legacyOff = 0x21,
247 unknown = 0x2a,
248 noChange = 0x7f,
249};
250
251static constexpr uint8_t stateChanged = 0x80;
252
Yong Li18d77262018-10-09 01:59:45 +0800253std::map<ACPIPowerState::ACPI, PowerState> dbusToIPMI = {
254 {ACPIPowerState::ACPI::S0_G0_D0, PowerState::s0G0D0},
255 {ACPIPowerState::ACPI::S1_D1, PowerState::s1D1},
256 {ACPIPowerState::ACPI::S2_D2, PowerState::s2D2},
257 {ACPIPowerState::ACPI::S3_D3, PowerState::s3D3},
258 {ACPIPowerState::ACPI::S4, PowerState::s4},
259 {ACPIPowerState::ACPI::S5_G2, PowerState::s5G2},
260 {ACPIPowerState::ACPI::S4_S5, PowerState::s4S5},
261 {ACPIPowerState::ACPI::G3, PowerState::g3},
262 {ACPIPowerState::ACPI::SLEEP, PowerState::sleep},
263 {ACPIPowerState::ACPI::G1_SLEEP, PowerState::g1Sleep},
264 {ACPIPowerState::ACPI::OVERRIDE, PowerState::override},
265 {ACPIPowerState::ACPI::LEGACY_ON, PowerState::legacyOn},
266 {ACPIPowerState::ACPI::LEGACY_OFF, PowerState::legacyOff},
267 {ACPIPowerState::ACPI::Unknown, PowerState::unknown}};
268
269bool isValidACPIState(acpi_state::PowerStateType type, uint8_t state)
270{
271 if (type == acpi_state::PowerStateType::sysPowerState)
272 {
273 if ((state <= static_cast<uint8_t>(acpi_state::PowerState::override)) ||
274 (state == static_cast<uint8_t>(acpi_state::PowerState::legacyOn)) ||
275 (state ==
276 static_cast<uint8_t>(acpi_state::PowerState::legacyOff)) ||
277 (state == static_cast<uint8_t>(acpi_state::PowerState::unknown)) ||
278 (state == static_cast<uint8_t>(acpi_state::PowerState::noChange)))
279 {
280 return true;
281 }
282 else
283 {
284 return false;
285 }
286 }
287 else if (type == acpi_state::PowerStateType::devPowerState)
288 {
289 if ((state <= static_cast<uint8_t>(acpi_state::PowerState::s3D3)) ||
290 (state == static_cast<uint8_t>(acpi_state::PowerState::unknown)) ||
291 (state == static_cast<uint8_t>(acpi_state::PowerState::noChange)))
292 {
293 return true;
294 }
295 else
296 {
297 return false;
298 }
299 }
300 else
301 {
302 return false;
303 }
304 return false;
305}
306} // namespace acpi_state
307
Deepak Kumar Sahu520c1312019-05-17 18:14:09 +0000308/** @brief implements Set ACPI Power State command
309 * @param sysAcpiState - ACPI system power state to set
310 * @param devAcpiState - ACPI device power state to set
311 *
312 * @return IPMI completion code on success
313 **/
314ipmi::RspType<> ipmiSetAcpiPowerState(uint8_t sysAcpiState,
315 uint8_t devAcpiState)
Chris Austen6caf28b2015-10-13 12:40:40 -0500316{
Yong Li18d77262018-10-09 01:59:45 +0800317 auto s = static_cast<uint8_t>(acpi_state::PowerState::unknown);
Yong Li18d77262018-10-09 01:59:45 +0800318
Patrick Williams5d82f472022-07-22 19:26:53 -0500319 sdbusplus::bus_t bus{ipmid_get_sd_bus_connection()};
Yong Li18d77262018-10-09 01:59:45 +0800320
321 auto value = acpi_state::ACPIPowerState::ACPI::Unknown;
322
Deepak Kumar Sahu520c1312019-05-17 18:14:09 +0000323 if (sysAcpiState & acpi_state::stateChanged)
Yong Li18d77262018-10-09 01:59:45 +0800324 {
325 // set system power state
Deepak Kumar Sahu520c1312019-05-17 18:14:09 +0000326 s = sysAcpiState & ~acpi_state::stateChanged;
Yong Li18d77262018-10-09 01:59:45 +0800327
328 if (!acpi_state::isValidACPIState(
329 acpi_state::PowerStateType::sysPowerState, s))
330 {
331 log<level::ERR>("set_acpi_power sys invalid input",
332 entry("S=%x", s));
Deepak Kumar Sahu520c1312019-05-17 18:14:09 +0000333 return ipmi::responseParmOutOfRange();
Yong Li18d77262018-10-09 01:59:45 +0800334 }
335
336 // valid input
337 if (s == static_cast<uint8_t>(acpi_state::PowerState::noChange))
338 {
339 log<level::DEBUG>("No change for system power state");
340 }
341 else
342 {
343 auto found = std::find_if(
344 acpi_state::dbusToIPMI.begin(), acpi_state::dbusToIPMI.end(),
345 [&s](const auto& iter) {
346 return (static_cast<uint8_t>(iter.second) == s);
347 });
348
349 value = found->first;
350
351 try
352 {
353 auto acpiObject =
354 ipmi::getDbusObject(bus, acpi_state::acpiInterface);
355 ipmi::setDbusProperty(bus, acpiObject.second, acpiObject.first,
356 acpi_state::acpiInterface,
357 acpi_state::sysACPIProp,
358 convertForMessage(value));
359 }
360 catch (const InternalFailure& e)
361 {
362 log<level::ERR>("Failed in set ACPI system property",
363 entry("EXCEPTION=%s", e.what()));
Deepak Kumar Sahu520c1312019-05-17 18:14:09 +0000364 return ipmi::responseUnspecifiedError();
Yong Li18d77262018-10-09 01:59:45 +0800365 }
366 }
367 }
368 else
369 {
370 log<level::DEBUG>("Do not change system power state");
371 }
372
Deepak Kumar Sahu520c1312019-05-17 18:14:09 +0000373 if (devAcpiState & acpi_state::stateChanged)
Yong Li18d77262018-10-09 01:59:45 +0800374 {
375 // set device power state
Deepak Kumar Sahu520c1312019-05-17 18:14:09 +0000376 s = devAcpiState & ~acpi_state::stateChanged;
Yong Li18d77262018-10-09 01:59:45 +0800377 if (!acpi_state::isValidACPIState(
378 acpi_state::PowerStateType::devPowerState, s))
379 {
380 log<level::ERR>("set_acpi_power dev invalid input",
381 entry("S=%x", s));
Deepak Kumar Sahu520c1312019-05-17 18:14:09 +0000382 return ipmi::responseParmOutOfRange();
Yong Li18d77262018-10-09 01:59:45 +0800383 }
384
385 // valid input
386 if (s == static_cast<uint8_t>(acpi_state::PowerState::noChange))
387 {
388 log<level::DEBUG>("No change for device power state");
389 }
390 else
391 {
392 auto found = std::find_if(
393 acpi_state::dbusToIPMI.begin(), acpi_state::dbusToIPMI.end(),
394 [&s](const auto& iter) {
395 return (static_cast<uint8_t>(iter.second) == s);
396 });
397
398 value = found->first;
399
400 try
401 {
402 auto acpiObject =
403 ipmi::getDbusObject(bus, acpi_state::acpiInterface);
404 ipmi::setDbusProperty(bus, acpiObject.second, acpiObject.first,
405 acpi_state::acpiInterface,
406 acpi_state::devACPIProp,
407 convertForMessage(value));
408 }
409 catch (const InternalFailure& e)
410 {
411 log<level::ERR>("Failed in set ACPI device property",
412 entry("EXCEPTION=%s", e.what()));
Deepak Kumar Sahu520c1312019-05-17 18:14:09 +0000413 return ipmi::responseUnspecifiedError();
Yong Li18d77262018-10-09 01:59:45 +0800414 }
415 }
416 }
417 else
418 {
419 log<level::DEBUG>("Do not change device power state");
420 }
Deepak Kumar Sahu520c1312019-05-17 18:14:09 +0000421 return ipmi::responseSuccess();
Yong Li18d77262018-10-09 01:59:45 +0800422}
423
Deepak Kumar Sahu4e6d2572019-05-07 19:53:37 +0000424/**
425 * @brief implements the get ACPI power state command
426 *
427 * @return IPMI completion code plus response data on success.
428 * - ACPI system power state
429 * - ACPI device power state
430 **/
431ipmi::RspType<uint8_t, // acpiSystemPowerState
432 uint8_t // acpiDevicePowerState
433 >
434 ipmiGetAcpiPowerState()
Yong Li18d77262018-10-09 01:59:45 +0800435{
Deepak Kumar Sahu4e6d2572019-05-07 19:53:37 +0000436 uint8_t sysAcpiState;
437 uint8_t devAcpiState;
Yong Li18d77262018-10-09 01:59:45 +0800438
Patrick Williams5d82f472022-07-22 19:26:53 -0500439 sdbusplus::bus_t bus{ipmid_get_sd_bus_connection()};
Yong Li18d77262018-10-09 01:59:45 +0800440
Yong Li18d77262018-10-09 01:59:45 +0800441 try
442 {
443 auto acpiObject = ipmi::getDbusObject(bus, acpi_state::acpiInterface);
444
445 auto sysACPIVal = ipmi::getDbusProperty(
446 bus, acpiObject.second, acpiObject.first, acpi_state::acpiInterface,
447 acpi_state::sysACPIProp);
448 auto sysACPI = acpi_state::ACPIPowerState::convertACPIFromString(
Vernon Maueryf442e112019-04-09 11:44:36 -0700449 std::get<std::string>(sysACPIVal));
Deepak Kumar Sahu4e6d2572019-05-07 19:53:37 +0000450 sysAcpiState = static_cast<uint8_t>(acpi_state::dbusToIPMI.at(sysACPI));
Yong Li18d77262018-10-09 01:59:45 +0800451
452 auto devACPIVal = ipmi::getDbusProperty(
453 bus, acpiObject.second, acpiObject.first, acpi_state::acpiInterface,
454 acpi_state::devACPIProp);
455 auto devACPI = acpi_state::ACPIPowerState::convertACPIFromString(
Vernon Maueryf442e112019-04-09 11:44:36 -0700456 std::get<std::string>(devACPIVal));
Deepak Kumar Sahu4e6d2572019-05-07 19:53:37 +0000457 devAcpiState = static_cast<uint8_t>(acpi_state::dbusToIPMI.at(devACPI));
Yong Li18d77262018-10-09 01:59:45 +0800458 }
459 catch (const InternalFailure& e)
460 {
Deepak Kumar Sahu4e6d2572019-05-07 19:53:37 +0000461 return ipmi::responseUnspecifiedError();
Yong Li18d77262018-10-09 01:59:45 +0800462 }
Deepak Kumar Sahu4e6d2572019-05-07 19:53:37 +0000463
464 return ipmi::responseSuccess(sysAcpiState, devAcpiState);
Chris Austen6caf28b2015-10-13 12:40:40 -0500465}
466
Chris Austen7303bdc2016-04-17 11:50:54 -0500467typedef struct
468{
469 char major;
470 char minor;
Chris Austen176c9652016-04-30 16:32:17 -0500471 uint16_t d[2];
Vernon Mauery86a50822019-03-25 13:11:36 -0700472} Revision;
Chris Austen7303bdc2016-04-17 11:50:54 -0500473
Potin Lai5d214202023-01-16 18:11:49 +0800474/* Use regular expression searching matched pattern X.Y, and convert it to */
475/* Major (X) and Minor (Y) version. */
476/* Example: */
477/* version = 2.14.0-dev */
478/* ^ ^ */
479/* | |---------------- Minor */
480/* |------------------ Major */
481/* */
482int convertVersion(std::string s, Revision& rev)
Chris Austen7303bdc2016-04-17 11:50:54 -0500483{
Potin Lai5d214202023-01-16 18:11:49 +0800484 std::regex fw_regex(FW_VER_REGEX);
485 std::smatch m;
486 Revision r = {0};
487 size_t val;
Chris Austen7303bdc2016-04-17 11:50:54 -0500488
Potin Laidcde04e2023-03-16 18:44:15 +0800489 if (std::regex_search(s, m, fw_regex))
Dinesh Chinari2b7e07d2017-11-08 15:38:50 -0600490 {
Potin Laidcde04e2023-03-16 18:44:15 +0800491 if (m.size() < 3)
492 { // required m.size() to be at lease 3 to convert both major and minor
493 return -1;
494 }
495
Potin Lai5d214202023-01-16 18:11:49 +0800496 // convert major
497 {
498 std::string_view str = m[1].str();
499 auto [ptr, ec]{std::from_chars(str.begin(), str.end(), val)};
500 if (ec != std::errc() || ptr != str.begin() + str.size())
501 { // failed to convert major string
Potin Laidcde04e2023-03-16 18:44:15 +0800502 return -1;
Potin Lai5d214202023-01-16 18:11:49 +0800503 }
504 r.major = val & 0x7F;
505 }
506
507 // convert minor
508 {
509 std::string_view str = m[2].str();
510 auto [ptr, ec]{std::from_chars(str.begin(), str.end(), val)};
511 if (ec != std::errc() || ptr != str.begin() + str.size())
512 { // failed to convert minor string
Potin Laidcde04e2023-03-16 18:44:15 +0800513 return -1;
Potin Lai5d214202023-01-16 18:11:49 +0800514 }
515 r.minor = val & 0xFF;
516 }
517
518 // all matched
519 rev = r;
520 return 0;
Chris Austen176c9652016-04-30 16:32:17 -0500521 }
Chris Austen7303bdc2016-04-17 11:50:54 -0500522
Potin Lai5d214202023-01-16 18:11:49 +0800523 return -1;
Chris Austen7303bdc2016-04-17 11:50:54 -0500524}
525
Vernon Maueryea1c4012019-05-24 13:26:16 -0700526/* @brief: Implement the Get Device ID IPMI command per the IPMI spec
527 * @param[in] ctx - shared_ptr to an IPMI context struct
528 *
529 * @returns IPMI completion code plus response data
530 * - Device ID (manufacturer defined)
531 * - Device revision[4 bits]; reserved[3 bits]; SDR support[1 bit]
532 * - FW revision major[7 bits] (binary encoded); available[1 bit]
533 * - FW Revision minor (BCD encoded)
534 * - IPMI version (0x02 for IPMI 2.0)
535 * - device support (bitfield of supported options)
536 * - MFG IANA ID (3 bytes)
537 * - product ID (2 bytes)
538 * - AUX info (4 bytes)
539 */
540ipmi::RspType<uint8_t, // Device ID
541 uint8_t, // Device Revision
542 uint8_t, // Firmware Revision Major
543 uint8_t, // Firmware Revision minor
544 uint8_t, // IPMI version
545 uint8_t, // Additional device support
546 uint24_t, // MFG ID
547 uint16_t, // Product ID
548 uint32_t // AUX info
549 >
Willy Tu11d68892022-01-20 10:37:34 -0800550 ipmiAppGetDeviceId([[maybe_unused]] ipmi::Context::ptr ctx)
Chris Austen6caf28b2015-10-13 12:40:40 -0500551{
Vernon Mauery86a50822019-03-25 13:11:36 -0700552 static struct
553 {
554 uint8_t id;
555 uint8_t revision;
556 uint8_t fw[2];
557 uint8_t ipmiVer;
558 uint8_t addnDevSupport;
559 uint24_t manufId;
560 uint16_t prodId;
561 uint32_t aux;
562 } devId;
David Cobbleya1adb072017-11-21 15:58:13 -0800563 static bool dev_id_initialized = false;
Patrick Venture94930a12019-04-30 10:01:58 -0700564 static bool defaultActivationSetting = true;
David Cobbleya1adb072017-11-21 15:58:13 -0800565 const char* filename = "/usr/share/ipmi-providers/dev_id.json";
Alexander Amelkinba19c182018-09-04 15:49:36 +0300566 constexpr auto ipmiDevIdStateShift = 7;
567 constexpr auto ipmiDevIdFw1Mask = ~(1 << ipmiDevIdStateShift);
Willy Tub78184e2022-10-27 22:57:38 +0000568
569#ifdef GET_DBUS_ACTIVE_SOFTWARE
570 static bool haveBMCVersion = false;
JeffLin27a62ec2021-11-24 15:40:33 +0800571 if (!haveBMCVersion || !dev_id_initialized)
David Cobbleya1adb072017-11-21 15:58:13 -0800572 {
Willy Tub78184e2022-10-27 22:57:38 +0000573 int r = -1;
574 Revision rev = {0, 0, 0, 0};
Nagaraju Goruganti744398d2018-02-20 09:52:00 -0600575 try
576 {
Vernon Maueryea1c4012019-05-24 13:26:16 -0700577 auto version = getActiveSoftwareVersionInfo(ctx);
Vernon Mauery86a50822019-03-25 13:11:36 -0700578 r = convertVersion(version, rev);
David Cobbleya1adb072017-11-21 15:58:13 -0800579 }
Nagaraju Goruganti744398d2018-02-20 09:52:00 -0600580 catch (const std::exception& e)
581 {
582 log<level::ERR>(e.what());
583 }
Nan Liee0cb902016-07-11 15:38:03 +0800584
Patrick Venture0b02be92018-08-31 11:55:55 -0700585 if (r >= 0)
586 {
Nagaraju Goruganti744398d2018-02-20 09:52:00 -0600587 // bit7 identifies if the device is available
588 // 0=normal operation
589 // 1=device firmware, SDR update,
590 // or self-initialization in progress.
Alexander Amelkinba19c182018-09-04 15:49:36 +0300591 // The availability may change in run time, so mask here
592 // and initialize later.
Vernon Mauery86a50822019-03-25 13:11:36 -0700593 devId.fw[0] = rev.major & ipmiDevIdFw1Mask;
Nagaraju Goruganti744398d2018-02-20 09:52:00 -0600594
595 rev.minor = (rev.minor > 99 ? 99 : rev.minor);
Vernon Mauery86a50822019-03-25 13:11:36 -0700596 devId.fw[1] = rev.minor % 10 + (rev.minor / 10) * 16;
597 std::memcpy(&devId.aux, rev.d, 4);
Brandon Kimc1f5aca2022-03-17 17:54:06 -0700598 haveBMCVersion = true;
David Cobbleya1adb072017-11-21 15:58:13 -0800599 }
JeffLin27a62ec2021-11-24 15:40:33 +0800600 }
Willy Tub78184e2022-10-27 22:57:38 +0000601#endif
JeffLin27a62ec2021-11-24 15:40:33 +0800602 if (!dev_id_initialized)
603 {
David Cobbleya1adb072017-11-21 15:58:13 -0800604 // IPMI Spec version 2.0
Vernon Mauery86a50822019-03-25 13:11:36 -0700605 devId.ipmiVer = 2;
Adriana Kobylak0e912642016-06-22 16:54:39 -0500606
Vernon Mauery86a50822019-03-25 13:11:36 -0700607 std::ifstream devIdFile(filename);
608 if (devIdFile.is_open())
David Cobbleya1adb072017-11-21 15:58:13 -0800609 {
Vernon Mauery86a50822019-03-25 13:11:36 -0700610 auto data = nlohmann::json::parse(devIdFile, nullptr, false);
David Cobbleya1adb072017-11-21 15:58:13 -0800611 if (!data.is_discarded())
612 {
Vernon Mauery86a50822019-03-25 13:11:36 -0700613 devId.id = data.value("id", 0);
614 devId.revision = data.value("revision", 0);
615 devId.addnDevSupport = data.value("addn_dev_support", 0);
616 devId.manufId = data.value("manuf_id", 0);
617 devId.prodId = data.value("prod_id", 0);
618 devId.aux = data.value("aux", 0);
David Cobbleya1adb072017-11-21 15:58:13 -0800619
Willy Tubfd3a172022-05-31 13:57:54 -0700620 if (data.contains("firmware_revision"))
621 {
622 const auto& firmwareRevision = data.at("firmware_revision");
623 if (firmwareRevision.contains("major"))
624 {
625 firmwareRevision.at("major").get_to(devId.fw[0]);
626 }
627 if (firmwareRevision.contains("minor"))
628 {
629 firmwareRevision.at("minor").get_to(devId.fw[1]);
630 }
631 }
632
Patrick Venture94930a12019-04-30 10:01:58 -0700633 // Set the availablitity of the BMC.
634 defaultActivationSetting = data.value("availability", true);
635
Patrick Venture0b02be92018-08-31 11:55:55 -0700636 // Don't read the file every time if successful
David Cobbleya1adb072017-11-21 15:58:13 -0800637 dev_id_initialized = true;
638 }
639 else
640 {
641 log<level::ERR>("Device ID JSON parser failure");
Vernon Maueryf2587fc2019-04-09 14:28:15 -0700642 return ipmi::responseUnspecifiedError();
David Cobbleya1adb072017-11-21 15:58:13 -0800643 }
644 }
645 else
646 {
647 log<level::ERR>("Device ID file not found");
Vernon Maueryf2587fc2019-04-09 14:28:15 -0700648 return ipmi::responseUnspecifiedError();
Chris Austen7303bdc2016-04-17 11:50:54 -0500649 }
650 }
Chris Austen6caf28b2015-10-13 12:40:40 -0500651
Alexander Amelkinba19c182018-09-04 15:49:36 +0300652 // Set availability to the actual current BMC state
Vernon Mauery86a50822019-03-25 13:11:36 -0700653 devId.fw[0] &= ipmiDevIdFw1Mask;
Patrick Venture94930a12019-04-30 10:01:58 -0700654 if (!getCurrentBmcStateWithFallback(defaultActivationSetting))
Alexander Amelkinba19c182018-09-04 15:49:36 +0300655 {
Vernon Mauery86a50822019-03-25 13:11:36 -0700656 devId.fw[0] |= (1 << ipmiDevIdStateShift);
Alexander Amelkinba19c182018-09-04 15:49:36 +0300657 }
658
Vernon Mauery86a50822019-03-25 13:11:36 -0700659 return ipmi::responseSuccess(
660 devId.id, devId.revision, devId.fw[0], devId.fw[1], devId.ipmiVer,
661 devId.addnDevSupport, devId.manufId, devId.prodId, devId.aux);
Chris Austen6caf28b2015-10-13 12:40:40 -0500662}
663
Vernon Maueryb84a5282019-03-25 13:39:03 -0700664auto ipmiAppGetSelfTestResults() -> ipmi::RspType<uint8_t, uint8_t>
Nan Li41fa24a2016-11-10 20:12:37 +0800665{
Nan Li41fa24a2016-11-10 20:12:37 +0800666 // Byte 2:
667 // 55h - No error.
Gunnar Mills8991dd62017-10-25 17:11:29 -0500668 // 56h - Self Test function not implemented in this controller.
Nan Li41fa24a2016-11-10 20:12:37 +0800669 // 57h - Corrupted or inaccesssible data or devices.
670 // 58h - Fatal hardware error.
671 // FFh - reserved.
672 // all other: Device-specific 'internal failure'.
673 // Byte 3:
674 // For byte 2 = 55h, 56h, FFh: 00h
675 // For byte 2 = 58h, all other: Device-specific
676 // For byte 2 = 57h: self-test error bitfield.
677 // Note: returning 57h does not imply that all test were run.
678 // [7] 1b = Cannot access SEL device.
679 // [6] 1b = Cannot access SDR Repository.
680 // [5] 1b = Cannot access BMC FRU device.
681 // [4] 1b = IPMB signal lines do not respond.
682 // [3] 1b = SDR Repository empty.
683 // [2] 1b = Internal Use Area of BMC FRU corrupted.
684 // [1] 1b = controller update 'boot block' firmware corrupted.
685 // [0] 1b = controller operational firmware corrupted.
Vernon Maueryb84a5282019-03-25 13:39:03 -0700686 constexpr uint8_t notImplemented = 0x56;
687 constexpr uint8_t zero = 0;
688 return ipmi::responseSuccess(notImplemented, zero);
Nan Li41fa24a2016-11-10 20:12:37 +0800689}
690
Vernon Mauery15541322019-03-25 13:33:03 -0700691static constexpr size_t uuidBinaryLength = 16;
692static std::array<uint8_t, uuidBinaryLength> rfc4122ToIpmi(std::string rfc4122)
Adriana Kobylakd100ee52015-10-20 17:02:37 -0500693{
Vernon Mauery15541322019-03-25 13:33:03 -0700694 using Argument = xyz::openbmc_project::Common::InvalidArgument;
Adriana Kobylakd100ee52015-10-20 17:02:37 -0500695 // UUID is in RFC4122 format. Ex: 61a39523-78f2-11e5-9862-e6402cfc3223
Patrick Ventured2117022018-02-06 08:54:37 -0800696 // Per IPMI Spec 2.0 need to convert to 16 hex bytes and reverse the byte
697 // order
Adriana Kobylakd100ee52015-10-20 17:02:37 -0500698 // Ex: 0x2332fc2c40e66298e511f2782395a361
Vernon Mauery15541322019-03-25 13:33:03 -0700699 constexpr size_t uuidHexLength = (2 * uuidBinaryLength);
700 constexpr size_t uuidRfc4122Length = (uuidHexLength + 4);
701 std::array<uint8_t, uuidBinaryLength> uuid;
702 if (rfc4122.size() == uuidRfc4122Length)
Patrick Venture0b02be92018-08-31 11:55:55 -0700703 {
Vernon Mauery15541322019-03-25 13:33:03 -0700704 rfc4122.erase(std::remove(rfc4122.begin(), rfc4122.end(), '-'),
705 rfc4122.end());
Sergey Solomineb9b8142016-08-23 09:07:28 -0500706 }
Vernon Mauery15541322019-03-25 13:33:03 -0700707 if (rfc4122.size() != uuidHexLength)
vishwa1eaea4f2016-02-26 11:57:40 -0600708 {
Vernon Mauery15541322019-03-25 13:33:03 -0700709 elog<InvalidArgument>(Argument::ARGUMENT_NAME("rfc4122"),
710 Argument::ARGUMENT_VALUE(rfc4122.c_str()));
vishwa1eaea4f2016-02-26 11:57:40 -0600711 }
Vernon Mauery15541322019-03-25 13:33:03 -0700712 for (size_t ind = 0; ind < uuidHexLength; ind += 2)
vishwa1eaea4f2016-02-26 11:57:40 -0600713 {
Vernon Mauery15541322019-03-25 13:33:03 -0700714 char v[3];
715 v[0] = rfc4122[ind];
716 v[1] = rfc4122[ind + 1];
717 v[2] = 0;
718 size_t err;
719 long b;
720 try
Emily Shafferedb8bb02018-09-27 14:50:15 -0700721 {
Vernon Mauery15541322019-03-25 13:33:03 -0700722 b = std::stoul(v, &err, 16);
Emily Shafferedb8bb02018-09-27 14:50:15 -0700723 }
Patrick Williamsa2ad2da2021-10-06 12:21:46 -0500724 catch (const std::exception& e)
Adriana Kobylakd100ee52015-10-20 17:02:37 -0500725 {
Vernon Mauery15541322019-03-25 13:33:03 -0700726 elog<InvalidArgument>(Argument::ARGUMENT_NAME("rfc4122"),
727 Argument::ARGUMENT_VALUE(rfc4122.c_str()));
Adriana Kobylakd100ee52015-10-20 17:02:37 -0500728 }
Vernon Mauery15541322019-03-25 13:33:03 -0700729 // check that exactly two ascii bytes were converted
730 if (err != 2)
731 {
732 elog<InvalidArgument>(Argument::ARGUMENT_NAME("rfc4122"),
733 Argument::ARGUMENT_VALUE(rfc4122.c_str()));
734 }
735 uuid[uuidBinaryLength - (ind / 2) - 1] = static_cast<uint8_t>(b);
Adriana Kobylakd100ee52015-10-20 17:02:37 -0500736 }
Vernon Mauery15541322019-03-25 13:33:03 -0700737 return uuid;
738}
Adriana Kobylakd100ee52015-10-20 17:02:37 -0500739
Vernon Mauery15541322019-03-25 13:33:03 -0700740auto ipmiAppGetDeviceGuid()
741 -> ipmi::RspType<std::array<uint8_t, uuidBinaryLength>>
742{
743 // return a fixed GUID based on /etc/machine-id
744 // This should match the /redfish/v1/Managers/bmc's UUID data
Adriana Kobylakd100ee52015-10-20 17:02:37 -0500745
Vernon Mauery15541322019-03-25 13:33:03 -0700746 // machine specific application ID (for BMC ID)
747 // generated by systemd-id128 -p new as per man page
748 static constexpr sd_id128_t bmcUuidAppId = SD_ID128_MAKE(
749 e0, e1, 73, 76, 64, 61, 47, da, a5, 0c, d0, cc, 64, 12, 45, 78);
Adriana Kobylakd100ee52015-10-20 17:02:37 -0500750
Vernon Mauery15541322019-03-25 13:33:03 -0700751 sd_id128_t bmcUuid;
752 // create the UUID from /etc/machine-id via the systemd API
753 sd_id128_get_machine_app_specific(bmcUuidAppId, &bmcUuid);
Adriana Kobylakd100ee52015-10-20 17:02:37 -0500754
Vernon Mauery15541322019-03-25 13:33:03 -0700755 char bmcUuidCstr[SD_ID128_STRING_MAX];
756 std::string systemUuid = sd_id128_to_string(bmcUuid, bmcUuidCstr);
757
758 std::array<uint8_t, uuidBinaryLength> uuid = rfc4122ToIpmi(systemUuid);
759 return ipmi::responseSuccess(uuid);
Adriana Kobylakd100ee52015-10-20 17:02:37 -0500760}
Chris Austen6caf28b2015-10-13 12:40:40 -0500761
Vernon Mauerycc99ba42019-03-25 13:40:11 -0700762auto ipmiAppGetBtCapabilities()
763 -> ipmi::RspType<uint8_t, uint8_t, uint8_t, uint8_t, uint8_t>
vishwabmcba0bd5f2015-09-30 16:50:23 +0530764{
Adriana Kobylak88ad8152016-12-13 10:09:08 -0600765 // Per IPMI 2.0 spec, the input and output buffer size must be the max
766 // buffer size minus one byte to allocate space for the length byte.
Vernon Mauerycc99ba42019-03-25 13:40:11 -0700767 constexpr uint8_t nrOutstanding = 0x01;
768 constexpr uint8_t inputBufferSize = MAX_IPMI_BUFFER - 1;
769 constexpr uint8_t outputBufferSize = MAX_IPMI_BUFFER - 1;
770 constexpr uint8_t transactionTime = 0x0A;
771 constexpr uint8_t nrRetries = 0x01;
vishwabmcba0bd5f2015-09-30 16:50:23 +0530772
Vernon Mauerycc99ba42019-03-25 13:40:11 -0700773 return ipmi::responseSuccess(nrOutstanding, inputBufferSize,
774 outputBufferSize, transactionTime, nrRetries);
vishwabmcba0bd5f2015-09-30 16:50:23 +0530775}
776
Vernon Maueryb90a5322019-03-25 13:36:55 -0700777auto ipmiAppGetSystemGuid() -> ipmi::RspType<std::array<uint8_t, 16>>
Marri Devender Rao5e007a52018-01-08 06:18:36 -0600778{
Vernon Maueryb90a5322019-03-25 13:36:55 -0700779 static constexpr auto uuidInterface = "xyz.openbmc_project.Common.UUID";
780 static constexpr auto uuidProperty = "UUID";
Marri Devender Rao5e007a52018-01-08 06:18:36 -0600781
Vernon Maueryb90a5322019-03-25 13:36:55 -0700782 ipmi::Value propValue;
Marri Devender Rao5e007a52018-01-08 06:18:36 -0600783 try
784 {
785 // Get the Inventory object implementing BMC interface
Vernon Maueryb90a5322019-03-25 13:36:55 -0700786 auto busPtr = getSdBus();
Hieu Huynh45aed692022-10-12 10:58:26 +0000787 auto objectInfo = ipmi::getDbusObject(*busPtr, uuidInterface);
Marri Devender Rao5e007a52018-01-08 06:18:36 -0600788
789 // Read UUID property value from bmcObject
790 // UUID is in RFC4122 format Ex: 61a39523-78f2-11e5-9862-e6402cfc3223
Vernon Maueryb90a5322019-03-25 13:36:55 -0700791 propValue =
792 ipmi::getDbusProperty(*busPtr, objectInfo.second, objectInfo.first,
793 uuidInterface, uuidProperty);
Marri Devender Rao5e007a52018-01-08 06:18:36 -0600794 }
795 catch (const InternalFailure& e)
796 {
797 log<level::ERR>("Failed in reading BMC UUID property",
Vernon Maueryb90a5322019-03-25 13:36:55 -0700798 entry("INTERFACE=%s", uuidInterface),
799 entry("PROPERTY=%s", uuidProperty));
800 return ipmi::responseUnspecifiedError();
Marri Devender Rao5e007a52018-01-08 06:18:36 -0600801 }
Vernon Maueryb90a5322019-03-25 13:36:55 -0700802 std::array<uint8_t, 16> uuid;
803 std::string rfc4122Uuid = std::get<std::string>(propValue);
804 try
805 {
806 // convert to IPMI format
807 uuid = rfc4122ToIpmi(rfc4122Uuid);
808 }
809 catch (const InvalidArgument& e)
810 {
811 log<level::ERR>("Failed in parsing BMC UUID property",
812 entry("INTERFACE=%s", uuidInterface),
813 entry("PROPERTY=%s", uuidProperty),
814 entry("VALUE=%s", rfc4122Uuid.c_str()));
815 return ipmi::responseUnspecifiedError();
816 }
817 return ipmi::responseSuccess(uuid);
Marri Devender Rao5e007a52018-01-08 06:18:36 -0600818}
819
Rajashekar Gade Reddye7023922019-07-10 16:54:55 +0000820/**
821 * @brief set the session state as teardown
822 *
823 * This function is to set the session state to tear down in progress if the
824 * state is active.
825 *
826 * @param[in] busp - Dbus obj
827 * @param[in] service - service name
828 * @param[in] obj - object path
829 *
830 * @return success completion code if it sets the session state to
831 * tearDownInProgress else return the corresponding error completion code.
832 **/
833uint8_t setSessionState(std::shared_ptr<sdbusplus::asio::connection>& busp,
834 const std::string& service, const std::string& obj)
835{
836 try
837 {
838 uint8_t sessionState = std::get<uint8_t>(ipmi::getDbusProperty(
839 *busp, service, obj, session::sessionIntf, "State"));
840
841 if (sessionState == static_cast<uint8_t>(session::State::active))
842 {
843 ipmi::setDbusProperty(
844 *busp, service, obj, session::sessionIntf, "State",
845 static_cast<uint8_t>(session::State::tearDownInProgress));
846 return ipmi::ccSuccess;
847 }
848 }
Patrick Williamsa2ad2da2021-10-06 12:21:46 -0500849 catch (const std::exception& e)
Rajashekar Gade Reddye7023922019-07-10 16:54:55 +0000850 {
851 log<level::ERR>("Failed in getting session state property",
852 entry("service=%s", service.c_str()),
853 entry("object path=%s", obj.c_str()),
854 entry("interface=%s", session::sessionIntf));
855 return ipmi::ccUnspecifiedError;
856 }
857
858 return ipmi::ccInvalidFieldRequest;
859}
860
861ipmi::RspType<> ipmiAppCloseSession(uint32_t reqSessionId,
862 std::optional<uint8_t> requestSessionHandle)
863{
864 auto busp = getSdBus();
865 uint8_t reqSessionHandle =
866 requestSessionHandle.value_or(session::defaultSessionHandle);
867
868 if (reqSessionId == session::sessionZero &&
869 reqSessionHandle == session::defaultSessionHandle)
870 {
871 return ipmi::response(session::ccInvalidSessionId);
872 }
873
874 if (reqSessionId == session::sessionZero &&
875 reqSessionHandle == session::invalidSessionHandle)
876 {
877 return ipmi::response(session::ccInvalidSessionHandle);
878 }
879
880 if (reqSessionId != session::sessionZero &&
881 reqSessionHandle != session::defaultSessionHandle)
882 {
883 return ipmi::response(ipmi::ccInvalidFieldRequest);
884 }
885
886 try
887 {
888 ipmi::ObjectTree objectTree = ipmi::getAllDbusObjects(
889 *busp, session::sessionManagerRootPath, session::sessionIntf);
890
891 for (auto& objectTreeItr : objectTree)
892 {
893 const std::string obj = objectTreeItr.first;
894
895 if (isSessionObjectMatched(obj, reqSessionId, reqSessionHandle))
896 {
897 auto& serviceMap = objectTreeItr.second;
898
899 // Session id and session handle are unique for each session.
900 // Session id and handler are retrived from the object path and
901 // object path will be unique for each session. Checking if
902 // multiple objects exist with same object path under multiple
903 // services.
904 if (serviceMap.size() != 1)
905 {
906 return ipmi::responseUnspecifiedError();
907 }
908
909 auto itr = serviceMap.begin();
910 const std::string service = itr->first;
911 return ipmi::response(setSessionState(busp, service, obj));
912 }
913 }
914 }
Patrick Williams5d82f472022-07-22 19:26:53 -0500915 catch (const sdbusplus::exception_t& e)
Rajashekar Gade Reddye7023922019-07-10 16:54:55 +0000916 {
917 log<level::ERR>("Failed to fetch object from dbus",
918 entry("INTERFACE=%s", session::sessionIntf),
919 entry("ERRMSG=%s", e.what()));
920 return ipmi::responseUnspecifiedError();
921 }
922
923 return ipmi::responseInvalidFieldRequest();
924}
925
Rajashekar Gade Reddyf71444d2019-07-25 15:12:17 +0000926uint8_t getTotalSessionCount()
927{
Meera-Kattac1789482021-05-18 09:53:26 +0000928 uint8_t count = 0, ch = 0;
Rajashekar Gade Reddyf71444d2019-07-25 15:12:17 +0000929
930 while (ch < ipmi::maxIpmiChannels &&
931 count < session::maxNetworkInstanceSupported)
932 {
Jayaprakash Mutyala80207e62020-07-04 16:34:15 +0000933 ipmi::ChannelInfo chInfo{};
Rajashekar Gade Reddyf71444d2019-07-25 15:12:17 +0000934 ipmi::getChannelInfo(ch, chInfo);
935 if (static_cast<ipmi::EChannelMediumType>(chInfo.mediumType) ==
936 ipmi::EChannelMediumType::lan8032)
937 {
938 count++;
939 }
940 ch++;
941 }
942 return count * session::maxSessionCountPerChannel;
943}
944
945/**
946 * @brief get session info request data.
947 *
948 * This function validates the request data and retrive request session id,
949 * session handle.
950 *
Rajashekar Gade Reddy4d226402019-11-13 17:13:05 +0530951 * @param[in] ctx - context of current session.
Rajashekar Gade Reddyf71444d2019-07-25 15:12:17 +0000952 * @param[in] sessionIndex - request session index
953 * @param[in] payload - input payload
954 * @param[in] reqSessionId - unpacked session Id will be asigned
955 * @param[in] reqSessionHandle - unpacked session handle will be asigned
956 *
957 * @return success completion code if request data is valid
958 * else return the correcponding error completion code.
959 **/
Rajashekar Gade Reddy4d226402019-11-13 17:13:05 +0530960uint8_t getSessionInfoRequestData(const ipmi::Context::ptr ctx,
961 const uint8_t sessionIndex,
Rajashekar Gade Reddyf71444d2019-07-25 15:12:17 +0000962 ipmi::message::Payload& payload,
963 uint32_t& reqSessionId,
964 uint8_t& reqSessionHandle)
965{
Rajashekar Gade Reddy4d226402019-11-13 17:13:05 +0530966 if ((sessionIndex > session::maxSessionCountPerChannel) &&
967 (sessionIndex < session::searchSessionByHandle))
Rajashekar Gade Reddyf71444d2019-07-25 15:12:17 +0000968 {
969 return ipmi::ccInvalidFieldRequest;
970 }
971
972 switch (sessionIndex)
973 {
Rajashekar Gade Reddy4d226402019-11-13 17:13:05 +0530974 case session::searchCurrentSession:
975
976 ipmi::ChannelInfo chInfo;
977 ipmi::getChannelInfo(ctx->channel, chInfo);
978
979 if (static_cast<ipmi::EChannelMediumType>(chInfo.mediumType) !=
980 ipmi::EChannelMediumType::lan8032)
981 {
982 return ipmi::ccInvalidFieldRequest;
983 }
984
985 if (!payload.fullyUnpacked())
986 {
987 return ipmi::ccReqDataLenInvalid;
988 }
989 // Check if current sessionId is 0, sessionId 0 is reserved.
990 if (ctx->sessionId == session::sessionZero)
991 {
992 return session::ccInvalidSessionId;
993 }
994 reqSessionId = ctx->sessionId;
995 break;
996
Rajashekar Gade Reddyf71444d2019-07-25 15:12:17 +0000997 case session::searchSessionByHandle:
998
999 if ((payload.unpack(reqSessionHandle)) ||
1000 (!payload.fullyUnpacked()))
1001 {
1002 return ipmi::ccReqDataLenInvalid;
1003 }
1004
1005 if ((reqSessionHandle == session::sessionZero) ||
1006 ((reqSessionHandle & session::multiIntfaceSessionHandleMask) >
1007 session::maxSessionCountPerChannel))
1008 {
1009 return session::ccInvalidSessionHandle;
1010 }
1011 break;
1012
1013 case session::searchSessionById:
1014
1015 if ((payload.unpack(reqSessionId)) || (!payload.fullyUnpacked()))
1016 {
1017 return ipmi::ccReqDataLenInvalid;
1018 }
1019
1020 if (reqSessionId == session::sessionZero)
1021 {
1022 return session::ccInvalidSessionId;
1023 }
1024 break;
1025
1026 default:
1027 if (!payload.fullyUnpacked())
1028 {
1029 return ipmi::ccReqDataLenInvalid;
1030 }
1031 break;
1032 }
1033 return ipmi::ccSuccess;
1034}
1035
Vernon Mauerye7e8b812019-10-28 16:00:34 -07001036uint8_t getSessionState(ipmi::Context::ptr ctx, const std::string& service,
1037 const std::string& objPath, uint8_t& sessionState)
Rajashekar Gade Reddyf71444d2019-07-25 15:12:17 +00001038{
Vernon Mauerye7e8b812019-10-28 16:00:34 -07001039 boost::system::error_code ec = ipmi::getDbusProperty(
1040 ctx, service, objPath, session::sessionIntf, "State", sessionState);
1041 if (ec)
Rajashekar Gade Reddyf71444d2019-07-25 15:12:17 +00001042 {
1043 log<level::ERR>("Failed to fetch state property ",
1044 entry("SERVICE=%s", service.c_str()),
1045 entry("OBJECTPATH=%s", objPath.c_str()),
1046 entry("INTERFACE=%s", session::sessionIntf),
Vernon Mauerye7e8b812019-10-28 16:00:34 -07001047 entry("ERRMSG=%s", ec.message().c_str()));
Rajashekar Gade Reddyf71444d2019-07-25 15:12:17 +00001048 return ipmi::ccUnspecifiedError;
1049 }
Rajashekar Gade Reddyf71444d2019-07-25 15:12:17 +00001050 return ipmi::ccSuccess;
1051}
1052
1053static constexpr uint8_t macAddrLen = 6;
Vernon Mauerye7e8b812019-10-28 16:00:34 -07001054/** Alias SessionDetails - contain the optional information about an
1055 * RMCP+ session.
1056 *
1057 * @param userID - uint6_t session user ID (0-63)
1058 * @param reserved - uint2_t reserved
1059 * @param privilege - uint4_t session privilege (0-5)
1060 * @param reserved - uint4_t reserved
1061 * @param channel - uint4_t session channel number
1062 * @param protocol - uint4_t session protocol
1063 * @param remoteIP - uint32_t remote IP address
1064 * @param macAddr - std::array<uint8_t, 6> mac address
1065 * @param port - uint16_t remote port
1066 */
1067using SessionDetails =
1068 std::tuple<uint2_t, uint6_t, uint4_t, uint4_t, uint4_t, uint4_t, uint32_t,
1069 std::array<uint8_t, macAddrLen>, uint16_t>;
Rajashekar Gade Reddyf71444d2019-07-25 15:12:17 +00001070
Vernon Mauerye7e8b812019-10-28 16:00:34 -07001071/** @brief get session details for a given session
1072 *
1073 * @param[in] ctx - ipmi::Context pointer for accessing D-Bus
1074 * @param[in] service - D-Bus service name to fetch details from
1075 * @param[in] objPath - D-Bus object path for session
1076 * @param[out] sessionHandle - return session handle for session
1077 * @param[out] sessionState - return session state for session
1078 * @param[out] details - return a SessionDetails tuple containing other
1079 * session info
1080 * @return - ipmi::Cc success or error code
1081 */
1082ipmi::Cc getSessionDetails(ipmi::Context::ptr ctx, const std::string& service,
1083 const std::string& objPath, uint8_t& sessionHandle,
1084 uint8_t& sessionState, SessionDetails& details)
Rajashekar Gade Reddyf71444d2019-07-25 15:12:17 +00001085{
Vernon Mauerye7e8b812019-10-28 16:00:34 -07001086 ipmi::PropertyMap sessionProps;
1087 boost::system::error_code ec = ipmi::getAllDbusProperties(
1088 ctx, service, objPath, session::sessionIntf, sessionProps);
Rajashekar Gade Reddyf71444d2019-07-25 15:12:17 +00001089
Vernon Mauerye7e8b812019-10-28 16:00:34 -07001090 if (ec)
Rajashekar Gade Reddyf71444d2019-07-25 15:12:17 +00001091 {
1092 log<level::ERR>("Failed to fetch state property ",
1093 entry("SERVICE=%s", service.c_str()),
1094 entry("OBJECTPATH=%s", objPath.c_str()),
1095 entry("INTERFACE=%s", session::sessionIntf),
Vernon Mauerye7e8b812019-10-28 16:00:34 -07001096 entry("ERRMSG=%s", ec.message().c_str()));
Rajashekar Gade Reddyf71444d2019-07-25 15:12:17 +00001097 return ipmi::ccUnspecifiedError;
1098 }
1099
Vernon Mauerye7e8b812019-10-28 16:00:34 -07001100 sessionState = ipmi::mappedVariant<uint8_t>(
1101 sessionProps, "State", static_cast<uint8_t>(session::State::inactive));
1102 if (sessionState == static_cast<uint8_t>(session::State::active))
1103 {
1104 sessionHandle =
1105 ipmi::mappedVariant<uint8_t>(sessionProps, "SessionHandle", 0);
1106 std::get<0>(details) =
1107 ipmi::mappedVariant<uint8_t>(sessionProps, "UserID", 0xff);
1108 // std::get<1>(details) = 0; // (default constructed to 0)
1109 std::get<2>(details) =
1110 ipmi::mappedVariant<uint8_t>(sessionProps, "CurrentPrivilege", 0);
1111 // std::get<3>(details) = 0; // (default constructed to 0)
1112 std::get<4>(details) =
1113 ipmi::mappedVariant<uint8_t>(sessionProps, "ChannelNum", 0xff);
1114 constexpr uint4_t rmcpPlusProtocol = 1;
1115 std::get<5>(details) = rmcpPlusProtocol;
1116 std::get<6>(details) =
1117 ipmi::mappedVariant<uint32_t>(sessionProps, "RemoteIPAddr", 0);
1118 // std::get<7>(details) = {{0}}; // default constructed to all 0
1119 std::get<8>(details) =
1120 ipmi::mappedVariant<uint16_t>(sessionProps, "RemotePort", 0);
1121 }
1122
Rajashekar Gade Reddyf71444d2019-07-25 15:12:17 +00001123 return ipmi::ccSuccess;
1124}
1125
Vernon Mauerye7e8b812019-10-28 16:00:34 -07001126ipmi::RspType<uint8_t, // session handle,
1127 uint8_t, // total session count
1128 uint8_t, // active session count
1129 std::optional<SessionDetails>>
Rajashekar Gade Reddy4d226402019-11-13 17:13:05 +05301130 ipmiAppGetSessionInfo(ipmi::Context::ptr ctx, uint8_t sessionIndex,
1131 ipmi::message::Payload& payload)
Rajashekar Gade Reddyf71444d2019-07-25 15:12:17 +00001132{
1133 uint32_t reqSessionId = 0;
1134 uint8_t reqSessionHandle = session::defaultSessionHandle;
1135 // initializing state to 0xff as 0 represents state as inactive.
1136 uint8_t state = 0xFF;
1137
1138 uint8_t completionCode = getSessionInfoRequestData(
Rajashekar Gade Reddy4d226402019-11-13 17:13:05 +05301139 ctx, sessionIndex, payload, reqSessionId, reqSessionHandle);
Rajashekar Gade Reddyf71444d2019-07-25 15:12:17 +00001140
1141 if (completionCode)
1142 {
1143 return ipmi::response(completionCode);
1144 }
Vernon Mauerye7e8b812019-10-28 16:00:34 -07001145 ipmi::ObjectTree objectTree;
1146 boost::system::error_code ec = ipmi::getAllDbusObjects(
1147 ctx, session::sessionManagerRootPath, session::sessionIntf, objectTree);
1148 if (ec)
Rajashekar Gade Reddyf71444d2019-07-25 15:12:17 +00001149 {
1150 log<level::ERR>("Failed to fetch object from dbus",
1151 entry("INTERFACE=%s", session::sessionIntf),
Vernon Mauerye7e8b812019-10-28 16:00:34 -07001152 entry("ERRMSG=%s", ec.message().c_str()));
Rajashekar Gade Reddyf71444d2019-07-25 15:12:17 +00001153 return ipmi::responseUnspecifiedError();
1154 }
1155
Vernon Mauerye7e8b812019-10-28 16:00:34 -07001156 uint8_t totalSessionCount = getTotalSessionCount();
1157 uint8_t activeSessionCount = 0;
1158 uint8_t sessionHandle = session::defaultSessionHandle;
Johnathan Manteyca93bb12022-12-02 13:33:17 -08001159 uint8_t activeSessionHandle = 0;
Vernon Mauerye7e8b812019-10-28 16:00:34 -07001160 std::optional<SessionDetails> maybeDetails;
1161 uint8_t index = 0;
1162 for (auto& objectTreeItr : objectTree)
Rajashekar Gade Reddyf71444d2019-07-25 15:12:17 +00001163 {
Vernon Mauerye7e8b812019-10-28 16:00:34 -07001164 uint32_t sessionId = 0;
1165 std::string objectPath = objectTreeItr.first;
1166
1167 if (!parseCloseSessionInputPayload(objectPath, sessionId,
1168 sessionHandle))
1169 {
1170 continue;
1171 }
1172 index++;
1173 auto& serviceMap = objectTreeItr.second;
1174 auto itr = serviceMap.begin();
1175
1176 if (serviceMap.size() != 1)
1177 {
1178 return ipmi::responseUnspecifiedError();
1179 }
1180
1181 std::string service = itr->first;
1182 uint8_t sessionState = 0;
1183 completionCode =
1184 getSessionState(ctx, service, objectPath, sessionState);
1185 if (completionCode)
1186 {
1187 return ipmi::response(completionCode);
1188 }
1189
1190 if (sessionState == static_cast<uint8_t>(session::State::active))
1191 {
1192 activeSessionCount++;
1193 }
1194
Johnathan Manteyca93bb12022-12-02 13:33:17 -08001195 if (index == sessionIndex || reqSessionId == sessionId ||
1196 reqSessionHandle == sessionHandle)
Vernon Mauerye7e8b812019-10-28 16:00:34 -07001197 {
Johnathan Manteyca93bb12022-12-02 13:33:17 -08001198 SessionDetails details{};
1199 completionCode = getSessionDetails(ctx, service, objectPath,
1200 sessionHandle, state, details);
Vernon Mauerye7e8b812019-10-28 16:00:34 -07001201
Johnathan Manteyca93bb12022-12-02 13:33:17 -08001202 if (completionCode)
1203 {
1204 return ipmi::response(completionCode);
1205 }
1206 activeSessionHandle = sessionHandle;
1207 maybeDetails = std::move(details);
Vernon Mauerye7e8b812019-10-28 16:00:34 -07001208 }
Rajashekar Gade Reddyf71444d2019-07-25 15:12:17 +00001209 }
Vernon Mauerye7e8b812019-10-28 16:00:34 -07001210
1211 if (state == static_cast<uint8_t>(session::State::active) ||
1212 state == static_cast<uint8_t>(session::State::tearDownInProgress))
Rajashekar Gade Reddyf71444d2019-07-25 15:12:17 +00001213 {
Johnathan Manteyca93bb12022-12-02 13:33:17 -08001214 return ipmi::responseSuccess(activeSessionHandle, totalSessionCount,
Vernon Mauerye7e8b812019-10-28 16:00:34 -07001215 activeSessionCount, maybeDetails);
Rajashekar Gade Reddyf71444d2019-07-25 15:12:17 +00001216 }
1217
1218 return ipmi::responseInvalidFieldRequest();
1219}
1220
Xo Wangf542e8b2017-08-09 15:34:16 -07001221static std::unique_ptr<SysInfoParamStore> sysInfoParamStore;
1222
Xo Wang87651332017-08-11 10:17:59 -07001223static std::string sysInfoReadSystemName()
1224{
1225 // Use the BMC hostname as the "System Name."
1226 char hostname[HOST_NAME_MAX + 1] = {};
1227 if (gethostname(hostname, HOST_NAME_MAX) != 0)
1228 {
1229 perror("System info parameter: system name");
1230 }
1231 return hostname;
1232}
1233
Jia, chunhui98b43ba2019-09-05 15:54:23 +08001234static constexpr uint8_t paramRevision = 0x11;
1235static constexpr size_t configParameterLength = 16;
Xo Wangf542e8b2017-08-09 15:34:16 -07001236
Jia, chunhui98b43ba2019-09-05 15:54:23 +08001237static constexpr size_t smallChunkSize = 14;
1238static constexpr size_t fullChunkSize = 16;
Jia, chunhui449f2162019-09-11 16:51:51 +08001239static constexpr uint8_t progressMask = 0x3;
Xo Wangf542e8b2017-08-09 15:34:16 -07001240
Jia, chunhui98b43ba2019-09-05 15:54:23 +08001241static constexpr uint8_t setComplete = 0x0;
1242static constexpr uint8_t setInProgress = 0x1;
1243static constexpr uint8_t commitWrite = 0x2;
1244static uint8_t transferStatus = setComplete;
1245
Jia, chunhui449f2162019-09-11 16:51:51 +08001246static constexpr uint8_t configDataOverhead = 2;
1247
1248// For EFI based system, 256 bytes is recommended.
1249static constexpr size_t maxBytesPerParameter = 256;
1250
Jia, chunhui98b43ba2019-09-05 15:54:23 +08001251namespace ipmi
1252{
1253constexpr Cc ccParmNotSupported = 0x80;
Jia, chunhui449f2162019-09-11 16:51:51 +08001254constexpr Cc ccSetInProgressActive = 0x81;
1255constexpr Cc ccSystemInfoParameterSetReadOnly = 0x82;
Jia, chunhui98b43ba2019-09-05 15:54:23 +08001256
1257static inline auto responseParmNotSupported()
1258{
1259 return response(ccParmNotSupported);
Xo Wangf542e8b2017-08-09 15:34:16 -07001260}
Jia, chunhui449f2162019-09-11 16:51:51 +08001261static inline auto responseSetInProgressActive()
1262{
1263 return response(ccSetInProgressActive);
1264}
1265static inline auto responseSystemInfoParameterSetReadOnly()
1266{
1267 return response(ccSystemInfoParameterSetReadOnly);
1268}
Jia, chunhui98b43ba2019-09-05 15:54:23 +08001269} // namespace ipmi
Xo Wangf542e8b2017-08-09 15:34:16 -07001270
Jia, chunhui449f2162019-09-11 16:51:51 +08001271ipmi::RspType<uint8_t, // Parameter revision
1272 std::optional<uint8_t>, // data1 / setSelector / ProgressStatus
1273 std::optional<std::vector<uint8_t>>> // data2-17
jayaprakash Mutyalac2566a92020-04-23 21:18:35 +00001274 ipmiAppGetSystemInfo(uint7_t reserved, bool getRevision,
1275 uint8_t paramSelector, uint8_t setSelector,
1276 uint8_t BlockSelector)
Xo Wangf542e8b2017-08-09 15:34:16 -07001277{
Snehalatha Va5ae7722020-05-02 18:18:57 +00001278 if (reserved || (paramSelector >= invalidParamSelectorStart &&
1279 paramSelector <= invalidParamSelectorEnd))
jayaprakash Mutyalac2566a92020-04-23 21:18:35 +00001280 {
1281 return ipmi::responseInvalidFieldRequest();
1282 }
Snehalatha Va5ae7722020-05-02 18:18:57 +00001283 if ((paramSelector >= oemCmdStart) && (paramSelector <= oemCmdEnd))
1284 {
1285 return ipmi::responseParmNotSupported();
1286 }
jayaprakash Mutyalac2566a92020-04-23 21:18:35 +00001287 if (getRevision)
Xo Wangf542e8b2017-08-09 15:34:16 -07001288 {
Jia, chunhui98b43ba2019-09-05 15:54:23 +08001289 return ipmi::responseSuccess(paramRevision, std::nullopt, std::nullopt);
Xo Wangf542e8b2017-08-09 15:34:16 -07001290 }
1291
Jia, chunhui98b43ba2019-09-05 15:54:23 +08001292 if (paramSelector == 0)
Xo Wangf542e8b2017-08-09 15:34:16 -07001293 {
Jia, chunhui98b43ba2019-09-05 15:54:23 +08001294 return ipmi::responseSuccess(paramRevision, transferStatus,
1295 std::nullopt);
Xo Wangf542e8b2017-08-09 15:34:16 -07001296 }
1297
Jia, chunhui98b43ba2019-09-05 15:54:23 +08001298 if (BlockSelector != 0) // 00h if parameter does not require a block number
Xo Wangf542e8b2017-08-09 15:34:16 -07001299 {
Jia, chunhui98b43ba2019-09-05 15:54:23 +08001300 return ipmi::responseParmNotSupported();
Xo Wangf542e8b2017-08-09 15:34:16 -07001301 }
1302
1303 if (sysInfoParamStore == nullptr)
1304 {
1305 sysInfoParamStore = std::make_unique<SysInfoParamStore>();
Xo Wang87651332017-08-11 10:17:59 -07001306 sysInfoParamStore->update(IPMI_SYSINFO_SYSTEM_NAME,
1307 sysInfoReadSystemName);
Xo Wangf542e8b2017-08-09 15:34:16 -07001308 }
1309
1310 // Parameters other than Set In Progress are assumed to be strings.
Jia, chunhui98b43ba2019-09-05 15:54:23 +08001311 std::tuple<bool, std::string> ret =
1312 sysInfoParamStore->lookup(paramSelector);
1313 bool found = std::get<0>(ret);
Xo Wangf542e8b2017-08-09 15:34:16 -07001314 if (!found)
1315 {
Snehalatha Va5ae7722020-05-02 18:18:57 +00001316 return ipmi::responseSensorInvalid();
Xo Wangf542e8b2017-08-09 15:34:16 -07001317 }
Jia, chunhui98b43ba2019-09-05 15:54:23 +08001318 std::string& paramString = std::get<1>(ret);
Jia, chunhui449f2162019-09-11 16:51:51 +08001319 std::vector<uint8_t> configData;
Jia, chunhui98b43ba2019-09-05 15:54:23 +08001320 size_t count = 0;
1321 if (setSelector == 0)
Jia, chunhui449f2162019-09-11 16:51:51 +08001322 { // First chunk has only 14 bytes.
1323 configData.emplace_back(0); // encoding
1324 configData.emplace_back(paramString.length()); // string length
1325 count = std::min(paramString.length(), smallChunkSize);
1326 configData.resize(count + configDataOverhead);
Jia, chunhui98b43ba2019-09-05 15:54:23 +08001327 std::copy_n(paramString.begin(), count,
Snehalatha Va5ae7722020-05-02 18:18:57 +00001328 configData.begin() + configDataOverhead); // 14 bytes chunk
1329
1330 // Append zero's to remaining bytes
1331 if (configData.size() < configParameterLength)
1332 {
1333 std::fill_n(std::back_inserter(configData),
1334 configParameterLength - configData.size(), 0x00);
1335 }
Jia, chunhui98b43ba2019-09-05 15:54:23 +08001336 }
1337 else
Xo Wangf542e8b2017-08-09 15:34:16 -07001338 {
Jia, chunhui449f2162019-09-11 16:51:51 +08001339 size_t offset = (setSelector * fullChunkSize) - configDataOverhead;
Jia, chunhui98b43ba2019-09-05 15:54:23 +08001340 if (offset >= paramString.length())
1341 {
1342 return ipmi::responseParmOutOfRange();
1343 }
Jia, chunhui449f2162019-09-11 16:51:51 +08001344 count = std::min(paramString.length() - offset, fullChunkSize);
1345 configData.resize(count);
Jia, chunhui98b43ba2019-09-05 15:54:23 +08001346 std::copy_n(paramString.begin() + offset, count,
1347 configData.begin()); // 16 bytes chunk
Xo Wangf542e8b2017-08-09 15:34:16 -07001348 }
Jia, chunhui98b43ba2019-09-05 15:54:23 +08001349 return ipmi::responseSuccess(paramRevision, setSelector, configData);
Xo Wangf542e8b2017-08-09 15:34:16 -07001350}
1351
Jia, chunhui449f2162019-09-11 16:51:51 +08001352ipmi::RspType<> ipmiAppSetSystemInfo(uint8_t paramSelector, uint8_t data1,
1353 std::vector<uint8_t> configData)
1354{
jayaprakash Mutyala3c5e4132020-04-27 23:00:05 +00001355 if (paramSelector >= invalidParamSelectorStart &&
1356 paramSelector <= invalidParamSelectorEnd)
1357 {
1358 return ipmi::responseInvalidFieldRequest();
1359 }
1360 if ((paramSelector >= oemCmdStart) && (paramSelector <= oemCmdEnd))
1361 {
1362 return ipmi::responseParmNotSupported();
1363 }
1364
Jia, chunhui449f2162019-09-11 16:51:51 +08001365 if (paramSelector == 0)
1366 {
1367 // attempt to set the 'set in progress' value (in parameter #0)
1368 // when not in the set complete state.
1369 if ((transferStatus != setComplete) && (data1 == setInProgress))
1370 {
1371 return ipmi::responseSetInProgressActive();
1372 }
1373 // only following 2 states are supported
1374 if (data1 > setInProgress)
1375 {
1376 phosphor::logging::log<phosphor::logging::level::ERR>(
1377 "illegal SetInProgress status");
1378 return ipmi::responseInvalidFieldRequest();
1379 }
1380
1381 transferStatus = data1 & progressMask;
1382 return ipmi::responseSuccess();
1383 }
1384
1385 if (configData.size() > configParameterLength)
1386 {
1387 return ipmi::responseInvalidFieldRequest();
1388 }
1389
jayaprakash Mutyala3c5e4132020-04-27 23:00:05 +00001390 // Append zero's to remaining bytes
1391 if (configData.size() < configParameterLength)
1392 {
1393 fill_n(back_inserter(configData),
1394 (configParameterLength - configData.size()), 0x00);
1395 }
1396
Jia, chunhui449f2162019-09-11 16:51:51 +08001397 if (!sysInfoParamStore)
1398 {
1399 sysInfoParamStore = std::make_unique<SysInfoParamStore>();
1400 sysInfoParamStore->update(IPMI_SYSINFO_SYSTEM_NAME,
1401 sysInfoReadSystemName);
1402 }
1403
1404 // lookup
1405 std::tuple<bool, std::string> ret =
1406 sysInfoParamStore->lookup(paramSelector);
1407 bool found = std::get<0>(ret);
1408 std::string& paramString = std::get<1>(ret);
1409 if (!found)
1410 {
1411 // parameter does not exist. Init new
1412 paramString = "";
1413 }
1414
1415 uint8_t setSelector = data1;
1416 size_t count = 0;
1417 if (setSelector == 0) // First chunk has only 14 bytes.
1418 {
1419 size_t stringLen = configData.at(1); // string length
1420 // maxBytesPerParamter is 256. It will always be greater than stringLen
1421 // (unit8_t) if maxBytes changes in future, then following line is
1422 // needed.
1423 // stringLen = std::min(stringLen, maxBytesPerParameter);
1424 count = std::min(stringLen, smallChunkSize);
1425 count = std::min(count, configData.size());
1426 paramString.resize(stringLen); // reserve space
1427 std::copy_n(configData.begin() + configDataOverhead, count,
1428 paramString.begin());
1429 }
1430 else
1431 {
1432 size_t offset = (setSelector * fullChunkSize) - configDataOverhead;
1433 if (offset >= paramString.length())
1434 {
1435 return ipmi::responseParmOutOfRange();
1436 }
1437 count = std::min(paramString.length() - offset, configData.size());
1438 std::copy_n(configData.begin(), count, paramString.begin() + offset);
1439 }
1440 sysInfoParamStore->update(paramSelector, paramString);
1441 return ipmi::responseSuccess();
1442}
1443
Yong Libd0503a2019-08-22 17:17:17 +08001444#ifdef ENABLE_I2C_WHITELIST_CHECK
Richard Marian Thomaiyar84bf9be2019-04-26 22:59:16 +05301445inline std::vector<uint8_t> convertStringToData(const std::string& command)
1446{
1447 std::istringstream iss(command);
1448 std::string token;
1449 std::vector<uint8_t> dataValue;
1450 while (std::getline(iss, token, ' '))
1451 {
1452 dataValue.emplace_back(
1453 static_cast<uint8_t>(std::stoul(token, nullptr, base_16)));
1454 }
1455 return dataValue;
1456}
1457
1458static bool populateI2CMasterWRWhitelist()
1459{
1460 nlohmann::json data = nullptr;
1461 std::ifstream jsonFile(i2cMasterWRWhitelistFile);
1462
1463 if (!jsonFile.good())
1464 {
1465 log<level::WARNING>("i2c white list file not found!",
1466 entry("FILE_NAME: %s", i2cMasterWRWhitelistFile));
1467 return false;
1468 }
1469
1470 try
1471 {
1472 data = nlohmann::json::parse(jsonFile, nullptr, false);
1473 }
Patrick Williamsa2ad2da2021-10-06 12:21:46 -05001474 catch (const nlohmann::json::parse_error& e)
Richard Marian Thomaiyar84bf9be2019-04-26 22:59:16 +05301475 {
1476 log<level::ERR>("Corrupted i2c white list config file",
1477 entry("FILE_NAME: %s", i2cMasterWRWhitelistFile),
1478 entry("MSG: %s", e.what()));
1479 return false;
1480 }
1481
1482 try
1483 {
1484 // Example JSON Structure format
1485 // "filters": [
1486 // {
1487 // "Description": "Allow full read - ignore first byte write value
1488 // for 0x40 to 0x4F",
1489 // "busId": "0x01",
1490 // "slaveAddr": "0x40",
1491 // "slaveAddrMask": "0x0F",
1492 // "command": "0x00",
1493 // "commandMask": "0xFF"
1494 // },
1495 // {
1496 // "Description": "Allow full read - first byte match 0x05 and
1497 // ignore second byte",
1498 // "busId": "0x01",
1499 // "slaveAddr": "0x57",
1500 // "slaveAddrMask": "0x00",
1501 // "command": "0x05 0x00",
1502 // "commandMask": "0x00 0xFF"
1503 // },]
1504
1505 nlohmann::json filters = data[filtersStr].get<nlohmann::json>();
1506 std::vector<i2cMasterWRWhitelist>& whitelist = getWRWhitelist();
1507 for (const auto& it : filters.items())
1508 {
1509 nlohmann::json filter = it.value();
1510 if (filter.is_null())
1511 {
1512 log<level::ERR>(
1513 "Corrupted I2C master write read whitelist config file",
1514 entry("FILE_NAME: %s", i2cMasterWRWhitelistFile));
1515 return false;
1516 }
1517 const std::vector<uint8_t>& writeData =
1518 convertStringToData(filter[cmdStr].get<std::string>());
1519 const std::vector<uint8_t>& writeDataMask =
1520 convertStringToData(filter[cmdMaskStr].get<std::string>());
1521 if (writeDataMask.size() != writeData.size())
1522 {
1523 log<level::ERR>("I2C master write read whitelist filter "
1524 "mismatch for command & mask size");
1525 return false;
1526 }
1527 whitelist.push_back(
1528 {static_cast<uint8_t>(std::stoul(
1529 filter[busIdStr].get<std::string>(), nullptr, base_16)),
1530 static_cast<uint8_t>(
1531 std::stoul(filter[slaveAddrStr].get<std::string>(),
1532 nullptr, base_16)),
1533 static_cast<uint8_t>(
1534 std::stoul(filter[slaveAddrMaskStr].get<std::string>(),
1535 nullptr, base_16)),
1536 writeData, writeDataMask});
1537 }
1538 if (whitelist.size() != filters.size())
1539 {
1540 log<level::ERR>(
1541 "I2C master write read whitelist filter size mismatch");
1542 return false;
1543 }
1544 }
Patrick Williamsa2ad2da2021-10-06 12:21:46 -05001545 catch (const std::exception& e)
Richard Marian Thomaiyar84bf9be2019-04-26 22:59:16 +05301546 {
1547 log<level::ERR>("I2C master write read whitelist unexpected exception",
1548 entry("ERROR=%s", e.what()));
1549 return false;
1550 }
1551 return true;
1552}
1553
1554static inline bool isWriteDataWhitelisted(const std::vector<uint8_t>& data,
1555 const std::vector<uint8_t>& dataMask,
1556 const std::vector<uint8_t>& writeData)
1557{
1558 std::vector<uint8_t> processedDataBuf(data.size());
1559 std::vector<uint8_t> processedReqBuf(dataMask.size());
1560 std::transform(writeData.begin(), writeData.end(), dataMask.begin(),
1561 processedReqBuf.begin(), std::bit_or<uint8_t>());
1562 std::transform(data.begin(), data.end(), dataMask.begin(),
1563 processedDataBuf.begin(), std::bit_or<uint8_t>());
1564
1565 return (processedDataBuf == processedReqBuf);
1566}
1567
1568static bool isCmdWhitelisted(uint8_t busId, uint8_t slaveAddr,
1569 std::vector<uint8_t>& writeData)
1570{
1571 std::vector<i2cMasterWRWhitelist>& whiteList = getWRWhitelist();
1572 for (const auto& wlEntry : whiteList)
1573 {
1574 if ((busId == wlEntry.busId) &&
1575 ((slaveAddr | wlEntry.slaveAddrMask) ==
1576 (wlEntry.slaveAddr | wlEntry.slaveAddrMask)))
1577 {
1578 const std::vector<uint8_t>& dataMask = wlEntry.dataMask;
1579 // Skip as no-match, if requested write data is more than the
1580 // write data mask size
1581 if (writeData.size() > dataMask.size())
1582 {
1583 continue;
1584 }
1585 if (isWriteDataWhitelisted(wlEntry.data, dataMask, writeData))
1586 {
1587 return true;
1588 }
1589 }
1590 }
1591 return false;
1592}
Yong Libd0503a2019-08-22 17:17:17 +08001593#else
1594static bool populateI2CMasterWRWhitelist()
1595{
1596 log<level::INFO>(
1597 "I2C_WHITELIST_CHECK is disabled, do not populate whitelist");
1598 return true;
1599}
1600#endif // ENABLE_I2C_WHITELIST_CHECK
Richard Marian Thomaiyar84bf9be2019-04-26 22:59:16 +05301601
1602/** @brief implements master write read IPMI command which can be used for
1603 * low-level I2C/SMBus write, read or write-read access
1604 * @param isPrivateBus -to indicate private bus usage
1605 * @param busId - bus id
1606 * @param channelNum - channel number
1607 * @param reserved - skip 1 bit
1608 * @param slaveAddr - slave address
1609 * @param read count - number of bytes to be read
1610 * @param writeData - data to be written
1611 *
1612 * @returns IPMI completion code plus response data
1613 * - readData - i2c response data
1614 */
1615ipmi::RspType<std::vector<uint8_t>>
Willy Tu11d68892022-01-20 10:37:34 -08001616 ipmiMasterWriteRead([[maybe_unused]] bool isPrivateBus, uint3_t busId,
1617 [[maybe_unused]] uint4_t channelNum, bool reserved,
1618 uint7_t slaveAddr, uint8_t readCount,
Richard Marian Thomaiyar84bf9be2019-04-26 22:59:16 +05301619 std::vector<uint8_t> writeData)
1620{
Jayaprakash Mutyalac2af98b2021-09-14 09:19:11 +00001621 if (reserved)
1622 {
1623 return ipmi::responseInvalidFieldRequest();
1624 }
Richard Marian Thomaiyar84bf9be2019-04-26 22:59:16 +05301625 if (readCount > maxIPMIWriteReadSize)
1626 {
1627 log<level::ERR>("Master write read command: Read count exceeds limit");
1628 return ipmi::responseParmOutOfRange();
1629 }
1630 const size_t writeCount = writeData.size();
1631 if (!readCount && !writeCount)
1632 {
1633 log<level::ERR>("Master write read command: Read & write count are 0");
1634 return ipmi::responseInvalidFieldRequest();
1635 }
Yong Libd0503a2019-08-22 17:17:17 +08001636#ifdef ENABLE_I2C_WHITELIST_CHECK
Richard Marian Thomaiyar84bf9be2019-04-26 22:59:16 +05301637 if (!isCmdWhitelisted(static_cast<uint8_t>(busId),
1638 static_cast<uint8_t>(slaveAddr), writeData))
1639 {
1640 log<level::ERR>("Master write read request blocked!",
1641 entry("BUS=%d", static_cast<uint8_t>(busId)),
1642 entry("ADDR=0x%x", static_cast<uint8_t>(slaveAddr)));
1643 return ipmi::responseInvalidFieldRequest();
1644 }
Yong Libd0503a2019-08-22 17:17:17 +08001645#endif // ENABLE_I2C_WHITELIST_CHECK
Richard Marian Thomaiyar84bf9be2019-04-26 22:59:16 +05301646 std::vector<uint8_t> readBuf(readCount);
1647 std::string i2cBus =
1648 "/dev/i2c-" + std::to_string(static_cast<uint8_t>(busId));
1649
Yong Li7dc4ac02019-08-23 17:44:32 +08001650 ipmi::Cc ret = ipmi::i2cWriteRead(i2cBus, static_cast<uint8_t>(slaveAddr),
1651 writeData, readBuf);
1652 if (ret != ipmi::ccSuccess)
Richard Marian Thomaiyar84bf9be2019-04-26 22:59:16 +05301653 {
Yong Li7dc4ac02019-08-23 17:44:32 +08001654 return ipmi::response(ret);
Richard Marian Thomaiyar84bf9be2019-04-26 22:59:16 +05301655 }
1656 return ipmi::responseSuccess(readBuf);
1657}
1658
Chris Austen6caf28b2015-10-13 12:40:40 -05001659void register_netfn_app_functions()
vishwabmcba0bd5f2015-09-30 16:50:23 +05301660{
Vernon Mauery86a50822019-03-25 13:11:36 -07001661 // <Get Device ID>
1662 ipmi::registerHandler(ipmi::prioOpenBmcBase, ipmi::netFnApp,
1663 ipmi::app::cmdGetDeviceId, ipmi::Privilege::User,
1664 ipmiAppGetDeviceId);
1665
Tom05732372016-09-06 17:21:23 +05301666 // <Get BT Interface Capabilities>
Vernon Mauerycc99ba42019-03-25 13:40:11 -07001667 ipmi::registerHandler(ipmi::prioOpenBmcBase, ipmi::netFnApp,
1668 ipmi::app::cmdGetBtIfaceCapabilities,
1669 ipmi::Privilege::User, ipmiAppGetBtCapabilities);
Chris Austen6caf28b2015-10-13 12:40:40 -05001670
Tom05732372016-09-06 17:21:23 +05301671 // <Reset Watchdog Timer>
Vernon Mauery11df4f62019-03-25 14:17:54 -07001672 ipmi::registerHandler(ipmi::prioOpenBmcBase, ipmi::netFnApp,
1673 ipmi::app::cmdResetWatchdogTimer,
1674 ipmi::Privilege::Operator, ipmiAppResetWatchdogTimer);
Chris Austen6caf28b2015-10-13 12:40:40 -05001675
Rajashekar Gade Reddyf71444d2019-07-25 15:12:17 +00001676 ipmi::registerHandler(ipmi::prioOpenBmcBase, ipmi::netFnApp,
AppaRao Puli5a98ea62019-11-10 21:15:02 +05301677 ipmi::app::cmdGetSessionInfo, ipmi::Privilege::User,
1678 ipmiAppGetSessionInfo);
Rajashekar Gade Reddyf71444d2019-07-25 15:12:17 +00001679
Tom05732372016-09-06 17:21:23 +05301680 // <Set Watchdog Timer>
Deepak Kumar Sahucfae9482019-05-20 14:58:58 +00001681 ipmi::registerHandler(ipmi::prioOpenBmcBase, ipmi::netFnApp,
1682 ipmi::app::cmdSetWatchdogTimer,
1683 ipmi::Privilege::Operator, ipmiSetWatchdogTimer);
Chris Austen6caf28b2015-10-13 12:40:40 -05001684
Rajashekar Gade Reddye7023922019-07-10 16:54:55 +00001685 ipmi::registerHandler(ipmi::prioOpenBmcBase, ipmi::netFnApp,
1686 ipmi::app::cmdCloseSession, ipmi::Privilege::Callback,
1687 ipmiAppCloseSession);
1688
William A. Kennington III73f44512018-02-09 15:28:46 -08001689 // <Get Watchdog Timer>
Deepak Kumar Sahucfae9482019-05-20 14:58:58 +00001690 ipmi::registerHandler(ipmi::prioOpenBmcBase, ipmi::netFnApp,
AppaRao Puli5a98ea62019-11-10 21:15:02 +05301691 ipmi::app::cmdGetWatchdogTimer, ipmi::Privilege::User,
1692 ipmiGetWatchdogTimer);
William A. Kennington III73f44512018-02-09 15:28:46 -08001693
Tom05732372016-09-06 17:21:23 +05301694 // <Get Self Test Results>
Vernon Maueryb84a5282019-03-25 13:39:03 -07001695 ipmi::registerHandler(ipmi::prioOpenBmcBase, ipmi::netFnApp,
1696 ipmi::app::cmdGetSelfTestResults,
1697 ipmi::Privilege::User, ipmiAppGetSelfTestResults);
Nan Li41fa24a2016-11-10 20:12:37 +08001698
Tom05732372016-09-06 17:21:23 +05301699 // <Get Device GUID>
Vernon Mauery15541322019-03-25 13:33:03 -07001700 ipmi::registerHandler(ipmi::prioOpenBmcBase, ipmi::netFnApp,
1701 ipmi::app::cmdGetDeviceGuid, ipmi::Privilege::User,
1702 ipmiAppGetDeviceGuid);
Adriana Kobylakd100ee52015-10-20 17:02:37 -05001703
Tom05732372016-09-06 17:21:23 +05301704 // <Set ACPI Power State>
Deepak Kumar Sahu520c1312019-05-17 18:14:09 +00001705 ipmi::registerHandler(ipmi::prioOpenBmcBase, ipmi::netFnApp,
1706 ipmi::app::cmdSetAcpiPowerState,
1707 ipmi::Privilege::Admin, ipmiSetAcpiPowerState);
Yong Li18d77262018-10-09 01:59:45 +08001708 // <Get ACPI Power State>
Deepak Kumar Sahu4e6d2572019-05-07 19:53:37 +00001709 ipmi::registerHandler(ipmi::prioOpenBmcBase, ipmi::netFnApp,
1710 ipmi::app::cmdGetAcpiPowerState,
AppaRao Puli5a98ea62019-11-10 21:15:02 +05301711 ipmi::Privilege::User, ipmiGetAcpiPowerState);
Yong Li18d77262018-10-09 01:59:45 +08001712
Richard Marian Thomaiyar84bf9be2019-04-26 22:59:16 +05301713 // Note: For security reason, this command will be registered only when
1714 // there are proper I2C Master write read whitelist
1715 if (populateI2CMasterWRWhitelist())
1716 {
1717 // Note: For security reasons, registering master write read as admin
1718 // privilege command, even though IPMI 2.0 specification allows it as
1719 // operator privilege.
1720 ipmi::registerHandler(ipmi::prioOpenBmcBase, ipmi::netFnApp,
1721 ipmi::app::cmdMasterWriteRead,
1722 ipmi::Privilege::Admin, ipmiMasterWriteRead);
1723 }
1724
Marri Devender Rao5e007a52018-01-08 06:18:36 -06001725 // <Get System GUID Command>
Vernon Maueryb90a5322019-03-25 13:36:55 -07001726 ipmi::registerHandler(ipmi::prioOpenBmcBase, ipmi::netFnApp,
1727 ipmi::app::cmdGetSystemGuid, ipmi::Privilege::User,
1728 ipmiAppGetSystemGuid);
Tom Joseph7cbe2282018-03-21 21:17:33 +05301729
1730 // <Get Channel Cipher Suites Command>
Ayushi Smriti5c3b72c2019-08-30 13:47:31 +00001731 ipmi::registerHandler(ipmi::prioOpenBmcBase, ipmi::netFnApp,
1732 ipmi::app::cmdGetChannelCipherSuites,
Vernon Mauery79b4eea2019-11-07 09:51:39 -08001733 ipmi::Privilege::None, getChannelCipherSuites);
Vernon Maueryd2a57de2019-03-25 12:45:28 -07001734
Xo Wangf542e8b2017-08-09 15:34:16 -07001735 // <Get System Info Command>
Jia, chunhui98b43ba2019-09-05 15:54:23 +08001736 ipmi::registerHandler(ipmi::prioOpenBmcBase, ipmi::netFnApp,
1737 ipmi::app::cmdGetSystemInfoParameters,
1738 ipmi::Privilege::User, ipmiAppGetSystemInfo);
Jia, chunhui449f2162019-09-11 16:51:51 +08001739 // <Set System Info Command>
1740 ipmi::registerHandler(ipmi::prioOpenBmcBase, ipmi::netFnApp,
1741 ipmi::app::cmdSetSystemInfoParameters,
1742 ipmi::Privilege::Admin, ipmiAppSetSystemInfo);
vishwabmcba0bd5f2015-09-30 16:50:23 +05301743 return;
1744}