blob: d2dcbfa7196ee3cd62f6a646c5aac4056064a882 [file] [log] [blame]
Sunny Srivastavafa5e4d32023-03-12 11:59:49 -05001#pragma once
2
3#include "constants.hpp"
Rekha Aparnac6159a22025-10-09 12:20:20 +05304#include "error_codes.hpp"
Sunny Srivastavafa5e4d32023-03-12 11:59:49 -05005#include "logger.hpp"
6
7#include <algorithm>
Sunny Srivastava995e1c22025-08-28 03:13:00 -05008#include <chrono>
Sunny Srivastavafa5e4d32023-03-12 11:59:49 -05009#include <cstdio>
10#include <cstdlib>
11#include <vector>
12
13/**
14 * @brief Namespace to host common utility methods.
15 *
16 * A method qualifies as a common utility function if,
17 * A)It is being used by the utility namespace at the same level as well as
18 * other files directly.
19 * B) The utility should be a leaf node and should not be dependent on any other
20 * utility.
21 * *******************
22 * | Commmon Utility | - - - - - - -
23 * ******************* |
24 * /\ |
25 * / \ |
26 * **************** **************** |
27 * | json utility | | dbus utility | |
28 * **************** **************** |
29 * \ / |
30 * \ / |
31 * ************************ |
32 * | Vpd specific Utility | - - - - - - -
33 * ************************
34 */
35
36namespace vpd
37{
38
39namespace commonUtility
40{
Rekha Aparnac6159a22025-10-09 12:20:20 +053041/**
42 * @brief API to get error code message.
43 *
44 * @param[in] i_errCode - error code.
45 *
46 * @return Error message set for that error code. Otherwise empty
47 * string.
48 */
49inline std::string getErrCodeMsg(const uint16_t& i_errCode)
50{
51 if (errorCodeMap.find(i_errCode) != errorCodeMap.end())
52 {
53 return errorCodeMap.at(i_errCode);
54 }
55
56 return std::string{};
57}
58
Sunny Srivastavafa5e4d32023-03-12 11:59:49 -050059/** @brief Return the hex representation of the incoming byte.
60 *
61 * @param [in] i_aByte - The input byte.
Rekha Aparnabffecd92025-04-08 13:01:41 -050062 * @returns Null character if input byte is out of bound else returns hex
63 * representation of the byte as a character.
Sunny Srivastavafa5e4d32023-03-12 11:59:49 -050064 */
Rekha Aparnabffecd92025-04-08 13:01:41 -050065constexpr auto toHex(const size_t& i_aByte) noexcept
Sunny Srivastavafa5e4d32023-03-12 11:59:49 -050066{
67 constexpr auto l_map = "0123456789abcdef";
Rekha Aparnabffecd92025-04-08 13:01:41 -050068
69 return (i_aByte < std::strlen(l_map)) ? l_map[i_aByte] : '\0';
Sunny Srivastavafa5e4d32023-03-12 11:59:49 -050070}
71
72/**
73 * @brief API to return null at the end of variadic template args.
74 *
75 * @return empty string.
76 */
77inline std::string getCommand()
78{
79 return "";
80}
81
82/**
83 * @brief API to arrange create command.
84 *
85 * @param[in] arguments to create the command
86 * @return Command string
87 */
88template <typename T, typename... Types>
89inline std::string getCommand(T i_arg1, Types... i_args)
90{
91 std::string l_cmd = " " + i_arg1 + getCommand(i_args...);
92
93 return l_cmd;
94}
95
96/**
97 * @brief API to create shell command and execute.
98 *
99 * @throw std::runtime_error.
100 *
101 * @param[in] arguments for command
Rekha Aparna719093d2025-11-13 03:13:12 -0600102 * @param[out] o_errCode - To set error code in case of error.
Sunny Srivastavafa5e4d32023-03-12 11:59:49 -0500103 * @returns output of that command
104 */
105template <typename T, typename... Types>
Rekha Aparna719093d2025-11-13 03:13:12 -0600106inline std::vector<std::string> executeCmd(T&& i_path, uint16_t& o_errCode,
107 Types... i_args)
Sunny Srivastavafa5e4d32023-03-12 11:59:49 -0500108{
Rekha Aparna719093d2025-11-13 03:13:12 -0600109 o_errCode = 0;
Sunny Srivastavafa5e4d32023-03-12 11:59:49 -0500110 std::vector<std::string> l_cmdOutput;
Sunny Srivastavafa5e4d32023-03-12 11:59:49 -0500111
Rekha Aparna719093d2025-11-13 03:13:12 -0600112 try
Sunny Srivastavafa5e4d32023-03-12 11:59:49 -0500113 {
Rekha Aparna719093d2025-11-13 03:13:12 -0600114 std::array<char, constants::CMD_BUFFER_LENGTH> l_buffer;
115
116 std::string l_cmd = i_path + getCommand(i_args...);
117
118 std::unique_ptr<FILE, decltype(&pclose)> l_cmdPipe(
119 popen(l_cmd.c_str(), "r"), pclose);
120
121 if (!l_cmdPipe)
122 {
123 o_errCode = error_code::POPEN_FAILED;
124 Logger::getLoggerInstance()->logMessage(
125 "popen failed with error " + std::string(strerror(errno)));
126 return l_cmdOutput;
127 }
128
129 while (fgets(l_buffer.data(), l_buffer.size(), l_cmdPipe.get()) !=
130 nullptr)
131 {
132 l_cmdOutput.emplace_back(l_buffer.data());
133 }
Sunny Srivastavafa5e4d32023-03-12 11:59:49 -0500134 }
Rekha Aparna719093d2025-11-13 03:13:12 -0600135 catch (const std::exception& l_ex)
Sunny Srivastavafa5e4d32023-03-12 11:59:49 -0500136 {
Rekha Aparna719093d2025-11-13 03:13:12 -0600137 o_errCode = error_code::STANDARD_EXCEPTION;
138 Logger::getLoggerInstance()->logMessage(
139 "Error while trying to execute command [" + std::string(i_path) +
140 "], error : " + std::string(l_ex.what()));
Sunny Srivastavafa5e4d32023-03-12 11:59:49 -0500141 }
142
143 return l_cmdOutput;
144}
145
146/** @brief Converts string to lower case.
147 *
148 * @param [in] i_string - Input string.
149 */
150inline void toLower(std::string& i_string)
151{
152 std::transform(i_string.begin(), i_string.end(), i_string.begin(),
153 [](unsigned char l_char) { return std::tolower(l_char); });
154}
Anupama B R6f142832025-04-11 04:17:49 -0500155
156/**
157 * @brief An API to get hex representation of the incoming bytes.
158 *
159 * The API returns the hex represented value of the given input in string format
160 * with 0x prefix.
161 *
162 * @param[in] i_keywordValue - Vector of input byte.
163 *
164 * @return - Returns the converted string value.
165 */
166inline std::string convertByteVectorToHex(
167 const types::BinaryVector& i_keywordValue)
168{
169 std::ostringstream l_oss;
170 l_oss << "0x";
171 for (const auto& l_byte : i_keywordValue)
172 {
173 l_oss << std::setfill('0') << std::setw(2) << std::hex
174 << static_cast<int>(l_byte);
175 }
176
177 return l_oss.str();
178}
Souvik Royaf528982025-07-16 13:50:18 -0500179
180/**
181 * @brief An API to convert binary value into ascii/hex representation.
182 *
183 * If given data contains printable characters, ASCII formated string value of
184 * the input data will be returned. Otherwise if the data has any non-printable
185 * value, returns the hex represented value of the given data in string format.
186 *
187 * @param[in] i_keywordValue - Data in binary format.
Rekha Aparnaa6fb3992025-11-18 21:40:42 -0600188 * @param[out] o_errCode - To set error code in case of error.
Souvik Royaf528982025-07-16 13:50:18 -0500189 *
190 * @return - Returns the converted string value.
191 */
Rekha Aparnaa6fb3992025-11-18 21:40:42 -0600192inline std::string getPrintableValue(const types::BinaryVector& i_keywordValue,
193 uint16_t& o_errCode)
Souvik Royaf528982025-07-16 13:50:18 -0500194{
Rekha Aparnaa6fb3992025-11-18 21:40:42 -0600195 o_errCode = 0;
Souvik Royaf528982025-07-16 13:50:18 -0500196 std::ostringstream l_oss;
Rekha Aparnaa6fb3992025-11-18 21:40:42 -0600197 try
Souvik Royaf528982025-07-16 13:50:18 -0500198 {
Rekha Aparnaa6fb3992025-11-18 21:40:42 -0600199 bool l_allPrintable = std::all_of(
200 i_keywordValue.begin(), i_keywordValue.end(),
201 [](const auto& l_byte) { return std::isprint(l_byte); });
202
203 if (l_allPrintable)
Souvik Royaf528982025-07-16 13:50:18 -0500204 {
Rekha Aparnaa6fb3992025-11-18 21:40:42 -0600205 l_oss << std::string(i_keywordValue.begin(), i_keywordValue.end());
Souvik Royaf528982025-07-16 13:50:18 -0500206 }
Rekha Aparnaa6fb3992025-11-18 21:40:42 -0600207 else
208 {
209 l_oss << "0x";
210 for (const auto& l_byte : i_keywordValue)
211 {
212 l_oss << std::setfill('0') << std::setw(2) << std::hex
213 << static_cast<int>(l_byte);
214 }
215 }
216 }
217 catch (const std::exception& l_ex)
218 {
219 o_errCode = error_code::STANDARD_EXCEPTION;
Souvik Royaf528982025-07-16 13:50:18 -0500220 }
221
222 return l_oss.str();
223}
224
225/**
226 * @brief API to get data in binary format.
227 *
228 * This API converts given string value present in hexadecimal or decimal format
229 * into array of binary data.
230 *
231 * @param[in] i_value - Input data.
232 *
233 * @return - Array of binary data on success, throws as exception in case
234 * of any error.
235 *
236 * @throw std::runtime_error, std::out_of_range, std::bad_alloc,
237 * std::invalid_argument
238 */
239inline types::BinaryVector convertToBinary(const std::string& i_value)
240{
241 if (i_value.empty())
242 {
243 throw std::runtime_error("Empty input provided");
244 }
245
246 types::BinaryVector l_binaryValue{};
247
248 if (i_value.substr(0, 2).compare("0x") == constants::STR_CMP_SUCCESS)
249 {
250 if (i_value.length() % 2 != 0)
251 {
252 throw std::runtime_error(
253 "Write option accepts 2 digit hex numbers. (Ex. 0x1 "
254 "should be given as 0x01).");
255 }
256
257 auto l_value = i_value.substr(2);
258
259 if (l_value.empty())
260 {
261 throw std::runtime_error(
262 "Provide a valid hexadecimal input. (Ex. 0x30313233)");
263 }
264
265 if (l_value.find_first_not_of("0123456789abcdefABCDEF") !=
266 std::string::npos)
267 {
268 throw std::runtime_error("Provide a valid hexadecimal input.");
269 }
270
271 for (size_t l_pos = 0; l_pos < l_value.length(); l_pos += 2)
272 {
273 uint8_t l_byte = static_cast<uint8_t>(
274 std::stoi(l_value.substr(l_pos, 2), nullptr, 16));
275 l_binaryValue.push_back(l_byte);
276 }
277 }
278 else
279 {
280 l_binaryValue.assign(i_value.begin(), i_value.end());
281 }
282 return l_binaryValue;
283}
284
Sunny Srivastava995e1c22025-08-28 03:13:00 -0500285/**
286 * @brief API to get current time stamp since Epoch.
287 *
288 * @return time stamp in seconds.
289 */
290inline size_t getCurrentTimeSinceEpoch() noexcept
291{
292 // Use high_resolution_clock for better precision
293 const auto l_now = std::chrono::high_resolution_clock::now();
294 auto l_durationSinceEpoch = l_now.time_since_epoch();
295
296 auto l_timeStampSeconds =
297 std::chrono::duration_cast<std::chrono::seconds>(l_durationSinceEpoch)
298 .count();
299 return static_cast<size_t>(l_timeStampSeconds);
300}
301
Souvik Royc4fa6182025-10-16 08:56:35 +0000302/**
303 * @brief API to check is field mode enabled.
304 *
305 * @return true, if field mode is enabled. otherwise false.
306 */
307inline bool isFieldModeEnabled() noexcept
308{
309 try
310 {
Rekha Aparna719093d2025-11-13 03:13:12 -0600311 uint16_t l_errCode = 0;
Souvik Royc4fa6182025-10-16 08:56:35 +0000312 std::vector<std::string> l_cmdOutput =
Rekha Aparna719093d2025-11-13 03:13:12 -0600313 executeCmd("/sbin/fw_printenv fieldmode", l_errCode);
Souvik Royc4fa6182025-10-16 08:56:35 +0000314
315 if (l_cmdOutput.size() > 0)
316 {
317 toLower(l_cmdOutput[0]);
318
319 // Remove the new line character from the string.
320 l_cmdOutput[0].erase(l_cmdOutput[0].length() - 1);
Souvik Royc4fa6182025-10-16 08:56:35 +0000321 return l_cmdOutput[0] == "fieldmode=true";
322 }
Rekha Aparna719093d2025-11-13 03:13:12 -0600323 else if (l_errCode)
324 {
325 // ToDo : Remove log and set error code.
326 Logger::getLoggerInstance()->logMessage(
327 "Failed to execute command, error : " +
328 getErrCodeMsg(l_errCode));
329 }
Souvik Royc4fa6182025-10-16 08:56:35 +0000330 }
331 catch (const std::exception& l_ex)
332 {}
333
334 return false;
335}
336
Souvik Royc1171732025-10-16 09:27:38 +0000337/**
338 * @brief API to get VPD collection mode
339 *
340 * VPD collection mode can be hardware, mixed mode or file mode. This is
341 * determined by reading a u-boot variable.
342 *
343 * @param[out] o_errCode - To set error code in case of error.
344 *
345 * @return Hardware mode, mixed mode or file mode.
346 */
347inline types::VpdCollectionMode getVpdCollectionMode(
348 uint16_t& o_errCode) noexcept
349{
Rekha Aparna719093d2025-11-13 03:13:12 -0600350 o_errCode = 0;
Souvik Royc1171732025-10-16 09:27:38 +0000351 types::VpdCollectionMode l_result{types::VpdCollectionMode::DEFAULT_MODE};
352 try
353 {
354 std::vector<std::string> l_cmdOutput =
Rekha Aparna719093d2025-11-13 03:13:12 -0600355 commonUtility::executeCmd("/sbin/fw_printenv vpdmode", o_errCode);
Souvik Royc1171732025-10-16 09:27:38 +0000356
357 if (l_cmdOutput.size() > 0)
358 {
359 commonUtility::toLower(l_cmdOutput[0]);
360
361 // Remove the new line character from the string.
362 l_cmdOutput[0].erase(l_cmdOutput[0].length() - 1);
363
364 if (l_cmdOutput[0] == "vpdmode=hardware")
365 {
366 l_result = types::VpdCollectionMode::HARDWARE_MODE;
367 }
368 else if (l_cmdOutput[0] == "vpdmode=mixed")
369 {
370 l_result = types::VpdCollectionMode::MIXED_MODE;
371 }
372 else if (l_cmdOutput[0] == "vpdmode=file")
373 {
374 l_result = types::VpdCollectionMode::FILE_MODE;
375 }
376 }
377 }
378 catch (const std::exception& l_ex)
379 {
380 o_errCode = error_code::STANDARD_EXCEPTION;
381 }
382
383 return l_result;
384}
385
Anupama B Rb5a80742025-11-20 01:48:35 -0600386/**
387 * @brief API to get effective FRU path
388 *
389 * API to get effective VPD path for a FRU based on the VPD collection mode.
390 *
391 * @param[in] i_vpdCollectionMode - VPD collection mode.
392 * @param[in,out] io_fruPath - Path to the EEPROM file.
393 * @param[out] o_errCode - To set error code in case of error.
394 *
395 */
396inline void getEffectiveFruPath(
397 const types::VpdCollectionMode& i_vpdCollectionMode,
398 std::string& io_fruPath, uint16_t& o_errCode) noexcept
399{
400 try
401 {
402 o_errCode = 0;
403 if (types::VpdCollectionMode::FILE_MODE == i_vpdCollectionMode)
404 {
405 io_fruPath.insert(0, constants::fileModeDirectoryPath);
406 }
407
408 // For Hardware mode and mixed mode FRU path is considered as EEPROM
409 // path. No change is needed.
410
411 // ToDo: Need to handle path for mixed mode, when mixed mode is fully
412 // implemented.
413 }
414 catch (std::exception& l_ex)
415 {
416 o_errCode = error_code::STANDARD_EXCEPTION;
417 Logger::getLoggerInstance()->logMessage(
418 "Error while getting effective path, reason: " +
419 std::string(l_ex.what()));
420 }
421}
422
Sunny Srivastavafa5e4d32023-03-12 11:59:49 -0500423} // namespace commonUtility
424} // namespace vpd