xref: /openbmc/pldm/common/utils.hpp (revision 869b776f)
1 #pragma once
2 
3 #include "libpldm/base.h"
4 #include "libpldm/bios.h"
5 #include "libpldm/platform.h"
6 #include "libpldm/utils.h"
7 
8 #include "types.hpp"
9 
10 #include <stdint.h>
11 #include <systemd/sd-bus.h>
12 #include <unistd.h>
13 
14 #include <nlohmann/json.hpp>
15 #include <sdbusplus/server.hpp>
16 #include <xyz/openbmc_project/Logging/Entry/server.hpp>
17 
18 #include <exception>
19 #include <filesystem>
20 #include <iostream>
21 #include <string>
22 #include <variant>
23 #include <vector>
24 
25 namespace pldm
26 {
27 namespace utils
28 {
29 
30 namespace fs = std::filesystem;
31 using Json = nlohmann::json;
32 constexpr bool Tx = true;
33 constexpr bool Rx = false;
34 
35 /** @struct CustomFD
36  *
37  *  RAII wrapper for file descriptor.
38  */
39 struct CustomFD
40 {
41     CustomFD(const CustomFD&) = delete;
42     CustomFD& operator=(const CustomFD&) = delete;
43     CustomFD(CustomFD&&) = delete;
44     CustomFD& operator=(CustomFD&&) = delete;
45 
46     CustomFD(int fd) : fd(fd)
47     {}
48 
49     ~CustomFD()
50     {
51         if (fd >= 0)
52         {
53             close(fd);
54         }
55     }
56 
57     int operator()() const
58     {
59         return fd;
60     }
61 
62   private:
63     int fd = -1;
64 };
65 
66 /** @brief Calculate the pad for PLDM data
67  *
68  *  @param[in] data - Length of the data
69  *  @return - uint8_t - number of pad bytes
70  */
71 uint8_t getNumPadBytes(uint32_t data);
72 
73 /** @brief Convert uint64 to date
74  *
75  *  @param[in] data - time date of uint64
76  *  @param[out] year - year number in dec
77  *  @param[out] month - month number in dec
78  *  @param[out] day - day of the month in dec
79  *  @param[out] hour - number of hours in dec
80  *  @param[out] min - number of minutes in dec
81  *  @param[out] sec - number of seconds in dec
82  *  @return true if decode success, false if decode faild
83  */
84 bool uintToDate(uint64_t data, uint16_t* year, uint8_t* month, uint8_t* day,
85                 uint8_t* hour, uint8_t* min, uint8_t* sec);
86 
87 /** @brief Convert effecter data to structure of set_effecter_state_field
88  *
89  *  @param[in] effecterData - the date of effecter
90  *  @param[in] effecterCount - the number of individual sets of effecter
91  *                              information
92  *  @return[out] parse success and get a valid set_effecter_state_field
93  *               structure, return nullopt means parse failed
94  */
95 std::optional<std::vector<set_effecter_state_field>>
96     parseEffecterData(const std::vector<uint8_t>& effecterData,
97                       uint8_t effecterCount);
98 
99 /**
100  *  @brief creates an error log
101  *  @param[in] errorMsg - the error message
102  */
103 void reportError(const char* errorMsg);
104 
105 /** @brief Convert any Decimal number to BCD
106  *
107  *  @tparam[in] decimal - Decimal number
108  *  @return Corresponding BCD number
109  */
110 template <typename T>
111 T decimalToBcd(T decimal)
112 {
113     T bcd = 0;
114     T rem = 0;
115     auto cnt = 0;
116 
117     while (decimal)
118     {
119         rem = decimal % 10;
120         bcd = bcd + (rem << cnt);
121         decimal = decimal / 10;
122         cnt += 4;
123     }
124 
125     return bcd;
126 }
127 
128 constexpr auto dbusProperties = "org.freedesktop.DBus.Properties";
129 constexpr auto mapperService = "xyz.openbmc_project.ObjectMapper";
130 
131 struct DBusMapping
132 {
133     std::string objectPath;   //!< D-Bus object path
134     std::string interface;    //!< D-Bus interface
135     std::string propertyName; //!< D-Bus property name
136     std::string propertyType; //!< D-Bus property type
137 };
138 
139 using PropertyValue =
140     std::variant<bool, uint8_t, int16_t, uint16_t, int32_t, uint32_t, int64_t,
141                  uint64_t, double, std::string>;
142 using DbusProp = std::string;
143 using DbusChangedProps = std::map<DbusProp, PropertyValue>;
144 using DBusInterfaceAdded = std::vector<
145     std::pair<pldm::dbus::Interface,
146               std::vector<std::pair<pldm::dbus::Property,
147                                     std::variant<pldm::dbus::Property>>>>>;
148 using ObjectPath = std::string;
149 using ServiceName = std::string;
150 using Interfaces = std::vector<std::string>;
151 using MapperServiceMap = std::vector<std::pair<ServiceName, Interfaces>>;
152 using GetSubTreeResponse = std::vector<std::pair<ObjectPath, MapperServiceMap>>;
153 
154 /**
155  * @brief The interface for DBusHandler
156  */
157 class DBusHandlerInterface
158 {
159   public:
160     virtual ~DBusHandlerInterface() = default;
161 
162     virtual std::string getService(const char* path,
163                                    const char* interface) const = 0;
164     virtual GetSubTreeResponse
165         getSubtree(const std::string& path, int depth,
166                    const std::vector<std::string>& ifaceList) const = 0;
167 
168     virtual void setDbusProperty(const DBusMapping& dBusMap,
169                                  const PropertyValue& value) const = 0;
170 
171     virtual PropertyValue
172         getDbusPropertyVariant(const char* objPath, const char* dbusProp,
173                                const char* dbusInterface) const = 0;
174 };
175 
176 /**
177  *  @class DBusHandler
178  *
179  *  Wrapper class to handle the D-Bus calls
180  *
181  *  This class contains the APIs to handle the D-Bus calls
182  *  to cater the request from pldm requester.
183  *  A class is created to mock the apis in the test cases
184  */
185 class DBusHandler : public DBusHandlerInterface
186 {
187   public:
188     /** @brief Get the bus connection. */
189     static auto& getBus()
190     {
191         static auto bus = sdbusplus::bus::new_default();
192         return bus;
193     }
194 
195     /**
196      *  @brief Get the DBUS Service name for the input dbus path
197      *
198      *  @param[in] path - DBUS object path
199      *  @param[in] interface - DBUS Interface
200      *
201      *  @return std::string - the dbus service name
202      *
203      *  @throw sdbusplus::exception::exception when it fails
204      */
205     std::string getService(const char* path,
206                            const char* interface) const override;
207 
208     /**
209      *  @brief Get the Subtree response from the mapper
210      *
211      *  @param[in] path - DBUS object path
212      *  @param[in] depth - Search depth
213      *  @param[in] ifaceList - list of the interface that are being
214      *                         queried from the mapper
215      *
216      *  @return GetSubTreeResponse - the mapper subtree response
217      *
218      *  @throw sdbusplus::exception::exception when it fails
219      */
220     GetSubTreeResponse
221         getSubtree(const std::string& path, int depth,
222                    const std::vector<std::string>& ifaceList) const override;
223 
224     /** @brief Get property(type: variant) from the requested dbus
225      *
226      *  @param[in] objPath - The Dbus object path
227      *  @param[in] dbusProp - The property name to get
228      *  @param[in] dbusInterface - The Dbus interface
229      *
230      *  @return The value of the property(type: variant)
231      *
232      *  @throw sdbusplus::exception::exception when it fails
233      */
234     PropertyValue
235         getDbusPropertyVariant(const char* objPath, const char* dbusProp,
236                                const char* dbusInterface) const override;
237 
238     /** @brief The template function to get property from the requested dbus
239      *         path
240      *
241      *  @tparam Property - Excepted type of the property on dbus
242      *
243      *  @param[in] objPath - The Dbus object path
244      *  @param[in] dbusProp - The property name to get
245      *  @param[in] dbusInterface - The Dbus interface
246      *
247      *  @return The value of the property
248      *
249      *  @throw sdbusplus::exception::exception when dbus request fails
250      *         std::bad_variant_access when \p Property and property on dbus do
251      *         not match
252      */
253     template <typename Property>
254     auto getDbusProperty(const char* objPath, const char* dbusProp,
255                          const char* dbusInterface)
256     {
257         auto VariantValue =
258             getDbusPropertyVariant(objPath, dbusProp, dbusInterface);
259         return std::get<Property>(VariantValue);
260     }
261 
262     /** @brief Set Dbus property
263      *
264      *  @param[in] dBusMap - Object path, property name, interface and property
265      *                       type for the D-Bus object
266      *  @param[in] value - The value to be set
267      *
268      *  @throw sdbusplus::exception::exception when it fails
269      */
270     void setDbusProperty(const DBusMapping& dBusMap,
271                          const PropertyValue& value) const override;
272 };
273 
274 /** @brief Fetch parent D-Bus object based on pathname
275  *
276  *  @param[in] dbusObj - child D-Bus object
277  *
278  *  @return std::string - the parent D-Bus object path
279  */
280 inline std::string findParent(const std::string& dbusObj)
281 {
282     fs::path p(dbusObj);
283     return p.parent_path().string();
284 }
285 
286 /** @brief Read (static) MCTP EID of host firmware from a file
287  *
288  *  @return uint8_t - MCTP EID
289  */
290 uint8_t readHostEID();
291 
292 /** @brief Convert a value in the JSON to a D-Bus property value
293  *
294  *  @param[in] type - type of the D-Bus property
295  *  @param[in] value - value in the JSON file
296  *
297  *  @return PropertyValue - the D-Bus property value
298  */
299 PropertyValue jsonEntryToDbusVal(std::string_view type,
300                                  const nlohmann::json& value);
301 
302 /** @brief Find State Effecter PDR
303  *  @param[in] tid - PLDM terminus ID.
304  *  @param[in] entityID - entity that can be associated with PLDM State set.
305  *  @param[in] stateSetId - value that identifies PLDM State set.
306  *  @param[in] repo - pointer to BMC's primary PDR repo.
307  *  @return array[array[uint8_t]] - StateEffecterPDRs
308  */
309 std::vector<std::vector<uint8_t>> findStateEffecterPDR(uint8_t tid,
310                                                        uint16_t entityID,
311                                                        uint16_t stateSetId,
312                                                        const pldm_pdr* repo);
313 /** @brief Find State Sensor PDR
314  *  @param[in] tid - PLDM terminus ID.
315  *  @param[in] entityID - entity that can be associated with PLDM State set.
316  *  @param[in] stateSetId - value that identifies PLDM State set.
317  *  @param[in] repo - pointer to BMC's primary PDR repo.
318  *  @return array[array[uint8_t]] - StateSensorPDRs
319  */
320 std::vector<std::vector<uint8_t>> findStateSensorPDR(uint8_t tid,
321                                                      uint16_t entityID,
322                                                      uint16_t stateSetId,
323                                                      const pldm_pdr* repo);
324 
325 /** @brief Find sensor id from a state sensor PDR
326  *
327  *  @param[in] pdrRepo - PDR repository
328  *  @param[in] tid - terminus id
329  *  @param[in] entityType - entity type
330  *  @param[in] entityInstance - entity instance number
331  *  @param[in] containerId - container id
332  *  @param[in] stateSetId - state set id
333  *
334  *  @return uint16_t - the sensor id
335  */
336 uint16_t findStateSensorId(const pldm_pdr* pdrRepo, uint8_t tid,
337                            uint16_t entityType, uint16_t entityInstance,
338                            uint16_t containerId, uint16_t stateSetId);
339 
340 /** @brief Find effecter id from a state effecter pdr
341  *  @param[in] pdrRepo - PDR repository
342  *  @param[in] entityType - entity type
343  *  @param[in] entityInstance - entity instance number
344  *  @param[in] containerId - container id
345  *  @param[in] stateSetId - state set id
346  *  @param[in] localOrRemote - true for checking local repo and false for remote
347  *                             repo
348  *
349  *  @return uint16_t - the effecter id
350  */
351 uint16_t findStateEffecterId(const pldm_pdr* pdrRepo, uint16_t entityType,
352                              uint16_t entityInstance, uint16_t containerId,
353                              uint16_t stateSetId, bool localOrRemote);
354 
355 /** @brief Emit the sensor event signal
356  *
357  *	@param[in] tid - the terminus id
358  *  @param[in] sensorId - sensorID value of the sensor
359  *  @param[in] sensorOffset - Identifies which state sensor within a
360  * composite state sensor the event is being returned for
361  *  @param[in] eventState - The event state value from the state change that
362  * triggered the event message
363  *  @param[in] previousEventState - The event state value for the state from
364  * which the present event state was entered.
365  *  @return PLDM completion code
366  */
367 int emitStateSensorEventSignal(uint8_t tid, uint16_t sensorId,
368                                uint8_t sensorOffset, uint8_t eventState,
369                                uint8_t previousEventState);
370 
371 /** @brief Print the buffer
372  *
373  *  @param[in]  isTx - True if the buffer is an outgoing PLDM message, false if
374                        the buffer is an incoming PLDM message
375  *  @param[in]  buffer - Buffer to print
376  *
377  *  @return - None
378  */
379 void printBuffer(bool isTx, const std::vector<uint8_t>& buffer);
380 
381 /** @brief Convert the buffer to std::string
382  *
383  *  If there are characters that are not printable characters, it is replaced
384  *  with space(0x20).
385  *
386  *  @param[in] var - pointer to data and length of the data
387  *
388  *  @return std::string equivalent of variable field
389  */
390 std::string toString(const struct variable_field& var);
391 
392 /** @brief Split strings according to special identifiers
393  *
394  *  We can split the string according to the custom identifier(';', ',', '&' or
395  *  others) and store it to vector.
396  *
397  *  @param[in] srcStr       - The string to be split
398  *  @param[in] delim        - The custom identifier
399  *  @param[in] trimStr      - The first and last string to be trimmed
400  *
401  *  @return std::vector<std::string> Vectors are used to store strings
402  */
403 std::vector<std::string> split(std::string_view srcStr, std::string_view delim,
404                                std::string_view trimStr = "");
405 
406 } // namespace utils
407 } // namespace pldm
408