xref: /openbmc/bmcweb/features/redfish/include/utils/json_utils.hpp (revision 8a7c4b475469c8811dffe265992b903060aad65f)
177dd8813SKowalski, Kamil /*
277dd8813SKowalski, Kamil // Copyright (c) 2018 Intel Corporation
377dd8813SKowalski, Kamil //
477dd8813SKowalski, Kamil // Licensed under the Apache License, Version 2.0 (the "License");
577dd8813SKowalski, Kamil // you may not use this file except in compliance with the License.
677dd8813SKowalski, Kamil // You may obtain a copy of the License at
777dd8813SKowalski, Kamil //
877dd8813SKowalski, Kamil //      http://www.apache.org/licenses/LICENSE-2.0
977dd8813SKowalski, Kamil //
1077dd8813SKowalski, Kamil // Unless required by applicable law or agreed to in writing, software
1177dd8813SKowalski, Kamil // distributed under the License is distributed on an "AS IS" BASIS,
1277dd8813SKowalski, Kamil // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
1377dd8813SKowalski, Kamil // See the License for the specific language governing permissions and
1477dd8813SKowalski, Kamil // limitations under the License.
1577dd8813SKowalski, Kamil */
1677dd8813SKowalski, Kamil #pragma once
179712f8acSEd Tanous 
18d5c80ad9SNan Zhou #include "error_messages.hpp"
19*8a7c4b47SNan Zhou #include "http_connection.hpp"
20d5c80ad9SNan Zhou #include "http_request.hpp"
21d5c80ad9SNan Zhou #include "http_response.hpp"
22185444b1SNan Zhou #include "human_sort.hpp"
23d5c80ad9SNan Zhou #include "logging.hpp"
24faf100f9SEd Tanous 
25faf100f9SEd Tanous #include <nlohmann/json.hpp>
260627a2c7SEd Tanous 
27185444b1SNan Zhou #include <algorithm>
28d5c80ad9SNan Zhou #include <array>
29d5c80ad9SNan Zhou #include <cmath>
30d5c80ad9SNan Zhou #include <cstddef>
31d5c80ad9SNan Zhou #include <cstdint>
32d5c80ad9SNan Zhou #include <limits>
33d5c80ad9SNan Zhou #include <map>
34d5c80ad9SNan Zhou #include <optional>
35ea2e6eecSWilly Tu #include <span>
36d5c80ad9SNan Zhou #include <string>
37d5c80ad9SNan Zhou #include <string_view>
38d5c80ad9SNan Zhou #include <type_traits>
39d5c80ad9SNan Zhou #include <utility>
40d5c80ad9SNan Zhou #include <variant>
41d5c80ad9SNan Zhou #include <vector>
42d5c80ad9SNan Zhou 
43d5c80ad9SNan Zhou // IWYU pragma: no_include <stdint.h>
441e75e1ddSNan Zhou // IWYU pragma: no_forward_declare crow::Request
451214b7e7SGunnar Mills 
461abe55efSEd Tanous namespace redfish
471abe55efSEd Tanous {
481abe55efSEd Tanous 
491abe55efSEd Tanous namespace json_util
501abe55efSEd Tanous {
5177dd8813SKowalski, Kamil 
5277dd8813SKowalski, Kamil /**
5377dd8813SKowalski, Kamil  * @brief Processes request to extract JSON from its body. If it fails, adds
5477dd8813SKowalski, Kamil  *       MalformedJSON message to response and ends it.
5577dd8813SKowalski, Kamil  *
5677dd8813SKowalski, Kamil  * @param[io]  res       Response object
5777dd8813SKowalski, Kamil  * @param[in]  req       Request object
5877dd8813SKowalski, Kamil  * @param[out] reqJson   JSON object extracted from request's body
5977dd8813SKowalski, Kamil  *
6077dd8813SKowalski, Kamil  * @return true if JSON is valid, false when JSON is invalid and response has
6177dd8813SKowalski, Kamil  *         been filled with message and ended.
6277dd8813SKowalski, Kamil  */
6355c7b7a2SEd Tanous bool processJsonFromRequest(crow::Response& res, const crow::Request& req,
6477dd8813SKowalski, Kamil                             nlohmann::json& reqJson);
659712f8acSEd Tanous namespace details
669712f8acSEd Tanous {
67771cfa0fSJason M. Bills 
681214b7e7SGunnar Mills template <typename Type>
692c70f800SEd Tanous struct IsOptional : std::false_type
701214b7e7SGunnar Mills {};
719712f8acSEd Tanous 
72771cfa0fSJason M. Bills template <typename Type>
732c70f800SEd Tanous struct IsOptional<std::optional<Type>> : std::true_type
741214b7e7SGunnar Mills {};
759712f8acSEd Tanous 
76771cfa0fSJason M. Bills template <typename Type>
772c70f800SEd Tanous struct IsVector : std::false_type
781214b7e7SGunnar Mills {};
79b1556427SEd Tanous 
801214b7e7SGunnar Mills template <typename Type>
812c70f800SEd Tanous struct IsVector<std::vector<Type>> : std::true_type
821214b7e7SGunnar Mills {};
83b1556427SEd Tanous 
841214b7e7SGunnar Mills template <typename Type>
852c70f800SEd Tanous struct IsStdArray : std::false_type
861214b7e7SGunnar Mills {};
87318226c2SJames Feist 
88318226c2SJames Feist template <typename Type, std::size_t size>
892c70f800SEd Tanous struct IsStdArray<std::array<Type, size>> : std::true_type
901214b7e7SGunnar Mills {};
91318226c2SJames Feist 
92471a5eb8SAppaRao Puli enum class UnpackErrorCode
93471a5eb8SAppaRao Puli {
94471a5eb8SAppaRao Puli     success,
95471a5eb8SAppaRao Puli     invalidType,
96471a5eb8SAppaRao Puli     outOfRange
97471a5eb8SAppaRao Puli };
98471a5eb8SAppaRao Puli 
99a6acbb31SJames Feist template <typename ToType, typename FromType>
100ea2e6eecSWilly Tu bool checkRange(const FromType& from, std::string_view key)
101a6acbb31SJames Feist {
102ee344e0fSEd Tanous     if (from > std::numeric_limits<ToType>::max())
103a6acbb31SJames Feist     {
104a6acbb31SJames Feist         BMCWEB_LOG_DEBUG << "Value for key " << key
105a6acbb31SJames Feist                          << " was greater than max: " << __PRETTY_FUNCTION__;
106a6acbb31SJames Feist         return false;
107a6acbb31SJames Feist     }
108ee344e0fSEd Tanous     if (from < std::numeric_limits<ToType>::lowest())
109a6acbb31SJames Feist     {
110a6acbb31SJames Feist         BMCWEB_LOG_DEBUG << "Value for key " << key
111a6acbb31SJames Feist                          << " was less than min: " << __PRETTY_FUNCTION__;
112a6acbb31SJames Feist         return false;
113a6acbb31SJames Feist     }
114a6acbb31SJames Feist     if constexpr (std::is_floating_point_v<ToType>)
115a6acbb31SJames Feist     {
116ee344e0fSEd Tanous         if (std::isnan(from))
117a6acbb31SJames Feist         {
118a6acbb31SJames Feist             BMCWEB_LOG_DEBUG << "Value for key " << key << " was NAN";
119a6acbb31SJames Feist             return false;
120a6acbb31SJames Feist         }
121a6acbb31SJames Feist     }
122a6acbb31SJames Feist 
123a6acbb31SJames Feist     return true;
124a6acbb31SJames Feist }
125a6acbb31SJames Feist 
126771cfa0fSJason M. Bills template <typename Type>
127471a5eb8SAppaRao Puli UnpackErrorCode unpackValueWithErrorCode(nlohmann::json& jsonValue,
128ea2e6eecSWilly Tu                                          std::string_view key, Type& value)
129771cfa0fSJason M. Bills {
130471a5eb8SAppaRao Puli     UnpackErrorCode ret = UnpackErrorCode::success;
13141352c24SSantosh Puranik 
132a6acbb31SJames Feist     if constexpr (std::is_floating_point_v<Type>)
133771cfa0fSJason M. Bills     {
134a6acbb31SJames Feist         double helper = 0;
135a6acbb31SJames Feist         double* jsonPtr = jsonValue.get_ptr<double*>();
136771cfa0fSJason M. Bills 
137771cfa0fSJason M. Bills         if (jsonPtr == nullptr)
138771cfa0fSJason M. Bills         {
139a6acbb31SJames Feist             int64_t* intPtr = jsonValue.get_ptr<int64_t*>();
140a6acbb31SJames Feist             if (intPtr != nullptr)
141771cfa0fSJason M. Bills             {
142a6acbb31SJames Feist                 helper = static_cast<double>(*intPtr);
143a6acbb31SJames Feist                 jsonPtr = &helper;
144771cfa0fSJason M. Bills             }
145a6acbb31SJames Feist         }
1465eb2bef2SAppaRao Puli         if (jsonPtr == nullptr)
1475eb2bef2SAppaRao Puli         {
148471a5eb8SAppaRao Puli             return UnpackErrorCode::invalidType;
1495eb2bef2SAppaRao Puli         }
150cb13a392SEd Tanous         if (!checkRange<Type>(*jsonPtr, key))
151771cfa0fSJason M. Bills         {
152471a5eb8SAppaRao Puli             return UnpackErrorCode::outOfRange;
153771cfa0fSJason M. Bills         }
154771cfa0fSJason M. Bills         value = static_cast<Type>(*jsonPtr);
155771cfa0fSJason M. Bills     }
156a6acbb31SJames Feist 
157a6acbb31SJames Feist     else if constexpr (std::is_signed_v<Type>)
158a6acbb31SJames Feist     {
159a6acbb31SJames Feist         int64_t* jsonPtr = jsonValue.get_ptr<int64_t*>();
160271584abSEd Tanous         if (jsonPtr == nullptr)
161271584abSEd Tanous         {
162471a5eb8SAppaRao Puli             return UnpackErrorCode::invalidType;
163271584abSEd Tanous         }
164cb13a392SEd Tanous         if (!checkRange<Type>(*jsonPtr, key))
165a6acbb31SJames Feist         {
166471a5eb8SAppaRao Puli             return UnpackErrorCode::outOfRange;
167a6acbb31SJames Feist         }
168a6acbb31SJames Feist         value = static_cast<Type>(*jsonPtr);
169a6acbb31SJames Feist     }
170a6acbb31SJames Feist 
1718102ddbaSAppaRao Puli     else if constexpr ((std::is_unsigned_v<Type>)&&(
1728102ddbaSAppaRao Puli                            !std::is_same_v<bool, Type>))
173a6acbb31SJames Feist     {
174a6acbb31SJames Feist         uint64_t* jsonPtr = jsonValue.get_ptr<uint64_t*>();
175271584abSEd Tanous         if (jsonPtr == nullptr)
176271584abSEd Tanous         {
177471a5eb8SAppaRao Puli             return UnpackErrorCode::invalidType;
178271584abSEd Tanous         }
179cb13a392SEd Tanous         if (!checkRange<Type>(*jsonPtr, key))
180a6acbb31SJames Feist         {
181471a5eb8SAppaRao Puli             return UnpackErrorCode::outOfRange;
182a6acbb31SJames Feist         }
183a6acbb31SJames Feist         value = static_cast<Type>(*jsonPtr);
184a6acbb31SJames Feist     }
185a6acbb31SJames Feist 
1860627a2c7SEd Tanous     else if constexpr (std::is_same_v<nlohmann::json, Type>)
1870627a2c7SEd Tanous     {
1880627a2c7SEd Tanous         value = std::move(jsonValue);
1890627a2c7SEd Tanous     }
190471a5eb8SAppaRao Puli     else
191471a5eb8SAppaRao Puli     {
192471a5eb8SAppaRao Puli         using JsonType = std::add_const_t<std::add_pointer_t<Type>>;
193471a5eb8SAppaRao Puli         JsonType jsonPtr = jsonValue.get_ptr<JsonType>();
194471a5eb8SAppaRao Puli         if (jsonPtr == nullptr)
195471a5eb8SAppaRao Puli         {
196471a5eb8SAppaRao Puli             BMCWEB_LOG_DEBUG
197471a5eb8SAppaRao Puli                 << "Value for key " << key
198471a5eb8SAppaRao Puli                 << " was incorrect type: " << jsonValue.type_name();
199471a5eb8SAppaRao Puli             return UnpackErrorCode::invalidType;
200471a5eb8SAppaRao Puli         }
201471a5eb8SAppaRao Puli         value = std::move(*jsonPtr);
202471a5eb8SAppaRao Puli     }
203471a5eb8SAppaRao Puli     return ret;
204471a5eb8SAppaRao Puli }
205471a5eb8SAppaRao Puli 
206471a5eb8SAppaRao Puli template <typename Type>
207ea2e6eecSWilly Tu bool unpackValue(nlohmann::json& jsonValue, std::string_view key,
208471a5eb8SAppaRao Puli                  crow::Response& res, Type& value)
209471a5eb8SAppaRao Puli {
210471a5eb8SAppaRao Puli     bool ret = true;
211471a5eb8SAppaRao Puli 
2122c70f800SEd Tanous     if constexpr (IsOptional<Type>::value)
213471a5eb8SAppaRao Puli     {
214471a5eb8SAppaRao Puli         value.emplace();
215471a5eb8SAppaRao Puli         ret = unpackValue<typename Type::value_type>(jsonValue, key, res,
216471a5eb8SAppaRao Puli                                                      *value) &&
217471a5eb8SAppaRao Puli               ret;
218471a5eb8SAppaRao Puli     }
2192c70f800SEd Tanous     else if constexpr (IsStdArray<Type>::value)
220318226c2SJames Feist     {
221318226c2SJames Feist         if (!jsonValue.is_array())
222318226c2SJames Feist         {
2232e8c4bdaSEd Tanous             messages::propertyValueTypeError(res, res.jsonValue, key);
22441352c24SSantosh Puranik             return false;
225318226c2SJames Feist         }
226318226c2SJames Feist         if (jsonValue.size() != value.size())
227318226c2SJames Feist         {
2282e8c4bdaSEd Tanous             messages::propertyValueTypeError(res, res.jsonValue, key);
22941352c24SSantosh Puranik             return false;
230318226c2SJames Feist         }
231318226c2SJames Feist         size_t index = 0;
232318226c2SJames Feist         for (const auto& val : jsonValue.items())
233318226c2SJames Feist         {
23441352c24SSantosh Puranik             ret = unpackValue<typename Type::value_type>(val.value(), key, res,
23541352c24SSantosh Puranik                                                          value[index++]) &&
23641352c24SSantosh Puranik                   ret;
237318226c2SJames Feist         }
238318226c2SJames Feist     }
2392c70f800SEd Tanous     else if constexpr (IsVector<Type>::value)
240b1556427SEd Tanous     {
241b1556427SEd Tanous         if (!jsonValue.is_array())
242b1556427SEd Tanous         {
2432e8c4bdaSEd Tanous             messages::propertyValueTypeError(res, res.jsonValue, key);
24441352c24SSantosh Puranik             return false;
245b1556427SEd Tanous         }
246b1556427SEd Tanous 
247b1556427SEd Tanous         for (const auto& val : jsonValue.items())
248b1556427SEd Tanous         {
249b1556427SEd Tanous             value.emplace_back();
25041352c24SSantosh Puranik             ret = unpackValue<typename Type::value_type>(val.value(), key, res,
25141352c24SSantosh Puranik                                                          value.back()) &&
25241352c24SSantosh Puranik                   ret;
253b1556427SEd Tanous         }
254b1556427SEd Tanous     }
255771cfa0fSJason M. Bills     else
256771cfa0fSJason M. Bills     {
257471a5eb8SAppaRao Puli         UnpackErrorCode ec = unpackValueWithErrorCode(jsonValue, key, value);
258471a5eb8SAppaRao Puli         if (ec != UnpackErrorCode::success)
259771cfa0fSJason M. Bills         {
260471a5eb8SAppaRao Puli             if (ec == UnpackErrorCode::invalidType)
261471a5eb8SAppaRao Puli             {
2622e8c4bdaSEd Tanous                 messages::propertyValueTypeError(res, jsonValue, key);
263471a5eb8SAppaRao Puli             }
264471a5eb8SAppaRao Puli             else if (ec == UnpackErrorCode::outOfRange)
265471a5eb8SAppaRao Puli             {
266e2616cc5SEd Tanous                 messages::propertyValueNotInList(res, jsonValue, key);
267471a5eb8SAppaRao Puli             }
26841352c24SSantosh Puranik             return false;
269771cfa0fSJason M. Bills         }
270771cfa0fSJason M. Bills     }
271471a5eb8SAppaRao Puli 
272471a5eb8SAppaRao Puli     return ret;
273471a5eb8SAppaRao Puli }
274471a5eb8SAppaRao Puli 
275471a5eb8SAppaRao Puli template <typename Type>
276ea2e6eecSWilly Tu bool unpackValue(nlohmann::json& jsonValue, std::string_view key, Type& value)
277471a5eb8SAppaRao Puli {
278471a5eb8SAppaRao Puli     bool ret = true;
2792c70f800SEd Tanous     if constexpr (IsOptional<Type>::value)
280471a5eb8SAppaRao Puli     {
281471a5eb8SAppaRao Puli         value.emplace();
282471a5eb8SAppaRao Puli         ret = unpackValue<typename Type::value_type>(jsonValue, key, *value) &&
283471a5eb8SAppaRao Puli               ret;
284471a5eb8SAppaRao Puli     }
2852c70f800SEd Tanous     else if constexpr (IsStdArray<Type>::value)
286471a5eb8SAppaRao Puli     {
287471a5eb8SAppaRao Puli         if (!jsonValue.is_array())
288471a5eb8SAppaRao Puli         {
289471a5eb8SAppaRao Puli             return false;
290471a5eb8SAppaRao Puli         }
291471a5eb8SAppaRao Puli         if (jsonValue.size() != value.size())
292471a5eb8SAppaRao Puli         {
293471a5eb8SAppaRao Puli             return false;
294471a5eb8SAppaRao Puli         }
295471a5eb8SAppaRao Puli         size_t index = 0;
296471a5eb8SAppaRao Puli         for (const auto& val : jsonValue.items())
297471a5eb8SAppaRao Puli         {
298471a5eb8SAppaRao Puli             ret = unpackValue<typename Type::value_type>(val.value(), key,
299471a5eb8SAppaRao Puli                                                          value[index++]) &&
300471a5eb8SAppaRao Puli                   ret;
301471a5eb8SAppaRao Puli         }
302471a5eb8SAppaRao Puli     }
3032c70f800SEd Tanous     else if constexpr (IsVector<Type>::value)
304471a5eb8SAppaRao Puli     {
305471a5eb8SAppaRao Puli         if (!jsonValue.is_array())
306471a5eb8SAppaRao Puli         {
307471a5eb8SAppaRao Puli             return false;
308471a5eb8SAppaRao Puli         }
309471a5eb8SAppaRao Puli 
310471a5eb8SAppaRao Puli         for (const auto& val : jsonValue.items())
311471a5eb8SAppaRao Puli         {
312471a5eb8SAppaRao Puli             value.emplace_back();
313471a5eb8SAppaRao Puli             ret = unpackValue<typename Type::value_type>(val.value(), key,
314471a5eb8SAppaRao Puli                                                          value.back()) &&
315471a5eb8SAppaRao Puli                   ret;
316471a5eb8SAppaRao Puli         }
317471a5eb8SAppaRao Puli     }
318471a5eb8SAppaRao Puli     else
319471a5eb8SAppaRao Puli     {
320471a5eb8SAppaRao Puli         UnpackErrorCode ec = unpackValueWithErrorCode(jsonValue, key, value);
321471a5eb8SAppaRao Puli         if (ec != UnpackErrorCode::success)
322471a5eb8SAppaRao Puli         {
323471a5eb8SAppaRao Puli             return false;
324471a5eb8SAppaRao Puli         }
325471a5eb8SAppaRao Puli     }
326471a5eb8SAppaRao Puli 
32741352c24SSantosh Puranik     return ret;
328771cfa0fSJason M. Bills }
3299712f8acSEd Tanous } // namespace details
3309712f8acSEd Tanous 
331ea2e6eecSWilly Tu // clang-format off
332ea2e6eecSWilly Tu using UnpackVariant = std::variant<
333ea2e6eecSWilly Tu     uint8_t*,
334ea2e6eecSWilly Tu     uint16_t*,
335ea2e6eecSWilly Tu     int16_t*,
336ea2e6eecSWilly Tu     uint32_t*,
337ea2e6eecSWilly Tu     int32_t*,
338ea2e6eecSWilly Tu     uint64_t*,
339ea2e6eecSWilly Tu     int64_t*,
340ea2e6eecSWilly Tu     bool*,
341ea2e6eecSWilly Tu     double*,
342ea2e6eecSWilly Tu     std::string*,
343ea2e6eecSWilly Tu     nlohmann::json*,
344ea2e6eecSWilly Tu     std::vector<uint8_t>*,
345ea2e6eecSWilly Tu     std::vector<uint16_t>*,
346ea2e6eecSWilly Tu     std::vector<int16_t>*,
347ea2e6eecSWilly Tu     std::vector<uint32_t>*,
348ea2e6eecSWilly Tu     std::vector<int32_t>*,
349ea2e6eecSWilly Tu     std::vector<uint64_t>*,
350ea2e6eecSWilly Tu     std::vector<int64_t>*,
351ea2e6eecSWilly Tu     //std::vector<bool>*,
352ea2e6eecSWilly Tu     std::vector<double>*,
353ea2e6eecSWilly Tu     std::vector<std::string>*,
354ea2e6eecSWilly Tu     std::vector<nlohmann::json>*,
355ea2e6eecSWilly Tu     std::optional<uint8_t>*,
356ea2e6eecSWilly Tu     std::optional<uint16_t>*,
357ea2e6eecSWilly Tu     std::optional<int16_t>*,
358ea2e6eecSWilly Tu     std::optional<uint32_t>*,
359ea2e6eecSWilly Tu     std::optional<int32_t>*,
360ea2e6eecSWilly Tu     std::optional<uint64_t>*,
361ea2e6eecSWilly Tu     std::optional<int64_t>*,
362ea2e6eecSWilly Tu     std::optional<bool>*,
363ea2e6eecSWilly Tu     std::optional<double>*,
364ea2e6eecSWilly Tu     std::optional<std::string>*,
365ea2e6eecSWilly Tu     std::optional<nlohmann::json>*,
366ea2e6eecSWilly Tu     std::optional<std::vector<uint8_t>>*,
367ea2e6eecSWilly Tu     std::optional<std::vector<uint16_t>>*,
368ea2e6eecSWilly Tu     std::optional<std::vector<int16_t>>*,
369ea2e6eecSWilly Tu     std::optional<std::vector<uint32_t>>*,
370ea2e6eecSWilly Tu     std::optional<std::vector<int32_t>>*,
371ea2e6eecSWilly Tu     std::optional<std::vector<uint64_t>>*,
372ea2e6eecSWilly Tu     std::optional<std::vector<int64_t>>*,
373ea2e6eecSWilly Tu     //std::optional<std::vector<bool>>*,
374ea2e6eecSWilly Tu     std::optional<std::vector<double>>*,
375ea2e6eecSWilly Tu     std::optional<std::vector<std::string>>*,
376ea2e6eecSWilly Tu     std::optional<std::vector<nlohmann::json>>*
377ea2e6eecSWilly Tu >;
378ea2e6eecSWilly Tu // clang-format on
379ea2e6eecSWilly Tu 
380ea2e6eecSWilly Tu struct PerUnpack
381ea2e6eecSWilly Tu {
382ea2e6eecSWilly Tu     std::string_view key;
383ea2e6eecSWilly Tu     UnpackVariant value;
384ea2e6eecSWilly Tu     bool complete = false;
385ea2e6eecSWilly Tu };
386ea2e6eecSWilly Tu 
387ea2e6eecSWilly Tu inline bool readJsonHelper(nlohmann::json& jsonRequest, crow::Response& res,
388ea2e6eecSWilly Tu                            std::span<PerUnpack> toUnpack)
3899712f8acSEd Tanous {
39041352c24SSantosh Puranik     bool result = true;
391d91415c4SEd Tanous     nlohmann::json::object_t* obj =
392d91415c4SEd Tanous         jsonRequest.get_ptr<nlohmann::json::object_t*>();
393d91415c4SEd Tanous     if (obj == nullptr)
3949712f8acSEd Tanous     {
3959712f8acSEd Tanous         BMCWEB_LOG_DEBUG << "Json value is not an object";
396f12894f8SJason M. Bills         messages::unrecognizedRequestBody(res);
3979712f8acSEd Tanous         return false;
3989712f8acSEd Tanous     }
399d91415c4SEd Tanous     for (auto& item : *obj)
4009712f8acSEd Tanous     {
401ea2e6eecSWilly Tu         size_t unpackIndex = 0;
402ea2e6eecSWilly Tu         for (; unpackIndex < toUnpack.size(); unpackIndex++)
403ea2e6eecSWilly Tu         {
404ea2e6eecSWilly Tu             PerUnpack& unpackSpec = toUnpack[unpackIndex];
405ea2e6eecSWilly Tu             std::string_view key = unpackSpec.key;
406ea2e6eecSWilly Tu             size_t keysplitIndex = key.find('/');
407ea2e6eecSWilly Tu             std::string_view leftover;
408ea2e6eecSWilly Tu             if (keysplitIndex != std::string_view::npos)
409ea2e6eecSWilly Tu             {
410ea2e6eecSWilly Tu                 leftover = key.substr(keysplitIndex + 1);
411ea2e6eecSWilly Tu                 key = key.substr(0, keysplitIndex);
412ea2e6eecSWilly Tu             }
413ea2e6eecSWilly Tu 
414d91415c4SEd Tanous             if (key != item.first || unpackSpec.complete)
415ea2e6eecSWilly Tu             {
416ea2e6eecSWilly Tu                 continue;
417ea2e6eecSWilly Tu             }
418ea2e6eecSWilly Tu 
419ea2e6eecSWilly Tu             // Sublevel key
420ea2e6eecSWilly Tu             if (!leftover.empty())
421ea2e6eecSWilly Tu             {
422ea2e6eecSWilly Tu                 // Include the slash in the key so we can compare later
423ea2e6eecSWilly Tu                 key = unpackSpec.key.substr(0, keysplitIndex + 1);
424ea2e6eecSWilly Tu                 nlohmann::json j;
425d91415c4SEd Tanous                 result = details::unpackValue<nlohmann::json>(item.second, key,
426ea2e6eecSWilly Tu                                                               res, j) &&
42741352c24SSantosh Puranik                          result;
42855f79e6fSEd Tanous                 if (!result)
429ea2e6eecSWilly Tu                 {
430ea2e6eecSWilly Tu                     return result;
4319712f8acSEd Tanous                 }
4329712f8acSEd Tanous 
433ea2e6eecSWilly Tu                 std::vector<PerUnpack> nextLevel;
434ea2e6eecSWilly Tu                 for (PerUnpack& p : toUnpack)
435ea2e6eecSWilly Tu                 {
436ea2e6eecSWilly Tu                     if (!p.key.starts_with(key))
437ea2e6eecSWilly Tu                     {
438ea2e6eecSWilly Tu                         continue;
439ea2e6eecSWilly Tu                     }
440ea2e6eecSWilly Tu                     std::string_view thisLeftover = p.key.substr(key.size());
441ea2e6eecSWilly Tu                     nextLevel.push_back({thisLeftover, p.value, false});
442ea2e6eecSWilly Tu                     p.complete = true;
4439712f8acSEd Tanous                 }
44477dd8813SKowalski, Kamil 
445ea2e6eecSWilly Tu                 result = readJsonHelper(j, res, nextLevel) && result;
446ea2e6eecSWilly Tu                 break;
447ea2e6eecSWilly Tu             }
448ea2e6eecSWilly Tu 
449002d39b4SEd Tanous             result = std::visit(
450ea2e6eecSWilly Tu                          [&item, &unpackSpec, &res](auto&& val) {
451ea2e6eecSWilly Tu                 using ContainedT =
452ea2e6eecSWilly Tu                     std::remove_pointer_t<std::decay_t<decltype(val)>>;
453ea2e6eecSWilly Tu                 return details::unpackValue<ContainedT>(
454d91415c4SEd Tanous                     item.second, unpackSpec.key, res, *val);
455ea2e6eecSWilly Tu                          },
456ea2e6eecSWilly Tu                          unpackSpec.value) &&
457ea2e6eecSWilly Tu                 result;
458ea2e6eecSWilly Tu 
459ea2e6eecSWilly Tu             unpackSpec.complete = true;
460ea2e6eecSWilly Tu             break;
461ea2e6eecSWilly Tu         }
462ea2e6eecSWilly Tu 
463ea2e6eecSWilly Tu         if (unpackIndex == toUnpack.size())
464ea2e6eecSWilly Tu         {
465d91415c4SEd Tanous             messages::propertyUnknown(res, item.first);
466ea2e6eecSWilly Tu             result = false;
467ea2e6eecSWilly Tu         }
468ea2e6eecSWilly Tu     }
469ea2e6eecSWilly Tu 
470ea2e6eecSWilly Tu     for (PerUnpack& perUnpack : toUnpack)
471ea2e6eecSWilly Tu     {
47255f79e6fSEd Tanous         if (!perUnpack.complete)
473ea2e6eecSWilly Tu         {
474ea2e6eecSWilly Tu             bool isOptional = std::visit(
475ea2e6eecSWilly Tu                 [](auto&& val) {
476ea2e6eecSWilly Tu                 using ContainedType =
477ea2e6eecSWilly Tu                     std::remove_pointer_t<std::decay_t<decltype(val)>>;
478ea2e6eecSWilly Tu                 return details::IsOptional<ContainedType>::value;
479ea2e6eecSWilly Tu                 },
480ea2e6eecSWilly Tu                 perUnpack.value);
481ea2e6eecSWilly Tu             if (isOptional)
482ea2e6eecSWilly Tu             {
483ea2e6eecSWilly Tu                 continue;
484ea2e6eecSWilly Tu             }
485ea2e6eecSWilly Tu             messages::propertyMissing(res, perUnpack.key);
486ea2e6eecSWilly Tu             result = false;
487ea2e6eecSWilly Tu         }
488ea2e6eecSWilly Tu     }
489ea2e6eecSWilly Tu     return result;
490ea2e6eecSWilly Tu }
491ea2e6eecSWilly Tu 
49289492a15SPatrick Williams inline void packVariant(std::span<PerUnpack> /*toPack*/) {}
493ea2e6eecSWilly Tu 
494ea2e6eecSWilly Tu template <typename FirstType, typename... UnpackTypes>
495ea2e6eecSWilly Tu void packVariant(std::span<PerUnpack> toPack, std::string_view key,
496ea2e6eecSWilly Tu                  FirstType& first, UnpackTypes&&... in)
497ea2e6eecSWilly Tu {
498ea2e6eecSWilly Tu     if (toPack.empty())
499ea2e6eecSWilly Tu     {
500ea2e6eecSWilly Tu         return;
501ea2e6eecSWilly Tu     }
502ea2e6eecSWilly Tu     toPack[0].key = key;
503ea2e6eecSWilly Tu     toPack[0].value = &first;
504ea2e6eecSWilly Tu     // NOLINTNEXTLINE(cppcoreguidelines-pro-bounds-array-to-pointer-decay)
505ea2e6eecSWilly Tu     packVariant(toPack.subspan(1), std::forward<UnpackTypes&&>(in)...);
506ea2e6eecSWilly Tu }
507ea2e6eecSWilly Tu 
508ea2e6eecSWilly Tu template <typename FirstType, typename... UnpackTypes>
509ea2e6eecSWilly Tu bool readJson(nlohmann::json& jsonRequest, crow::Response& res,
510ea2e6eecSWilly Tu               std::string_view key, FirstType&& first, UnpackTypes&&... in)
511ea2e6eecSWilly Tu {
512ea2e6eecSWilly Tu     const std::size_t n = sizeof...(UnpackTypes) + 2;
513ea2e6eecSWilly Tu     std::array<PerUnpack, n / 2> toUnpack2;
514ea2e6eecSWilly Tu     packVariant(toUnpack2, key, first, std::forward<UnpackTypes&&>(in)...);
515ea2e6eecSWilly Tu     return readJsonHelper(jsonRequest, res, toUnpack2);
516ea2e6eecSWilly Tu }
517ea2e6eecSWilly Tu 
518ea2e6eecSWilly Tu inline std::optional<nlohmann::json>
519ea2e6eecSWilly Tu     readJsonPatchHelper(const crow::Request& req, crow::Response& res)
5200627a2c7SEd Tanous {
5210627a2c7SEd Tanous     nlohmann::json jsonRequest;
5220627a2c7SEd Tanous     if (!json_util::processJsonFromRequest(res, req, jsonRequest))
5230627a2c7SEd Tanous     {
5240627a2c7SEd Tanous         BMCWEB_LOG_DEBUG << "Json value not readable";
525ea2e6eecSWilly Tu         return std::nullopt;
5260627a2c7SEd Tanous     }
527357bb8f8SEd Tanous     nlohmann::json::object_t* object =
528357bb8f8SEd Tanous         jsonRequest.get_ptr<nlohmann::json::object_t*>();
529357bb8f8SEd Tanous     if (object == nullptr || object->empty())
53015ed6780SWilly Tu     {
53115ed6780SWilly Tu         BMCWEB_LOG_DEBUG << "Json value is empty";
53215ed6780SWilly Tu         messages::emptyJSON(res);
533ea2e6eecSWilly Tu         return std::nullopt;
534ea2e6eecSWilly Tu     }
535357bb8f8SEd Tanous     std::erase_if(*object,
536357bb8f8SEd Tanous                   [](const std::pair<std::string, nlohmann::json>& item) {
537357bb8f8SEd Tanous         return item.first.starts_with("@odata.");
538357bb8f8SEd Tanous     });
539357bb8f8SEd Tanous     if (object->empty())
540357bb8f8SEd Tanous     {
541357bb8f8SEd Tanous         //  If the update request only contains OData annotations, the service
542357bb8f8SEd Tanous         //  should return the HTTP 400 Bad Request status code with the
543357bb8f8SEd Tanous         //  NoOperation message from the Base Message Registry, ...
544357bb8f8SEd Tanous         messages::noOperation(res);
545357bb8f8SEd Tanous         return std::nullopt;
546357bb8f8SEd Tanous     }
547357bb8f8SEd Tanous 
548ea2e6eecSWilly Tu     return {std::move(jsonRequest)};
549ea2e6eecSWilly Tu }
550ea2e6eecSWilly Tu 
551ea2e6eecSWilly Tu template <typename... UnpackTypes>
552ea2e6eecSWilly Tu bool readJsonPatch(const crow::Request& req, crow::Response& res,
553ea2e6eecSWilly Tu                    std::string_view key, UnpackTypes&&... in)
554ea2e6eecSWilly Tu {
555ea2e6eecSWilly Tu     std::optional<nlohmann::json> jsonRequest = readJsonPatchHelper(req, res);
556ea2e6eecSWilly Tu     if (jsonRequest == std::nullopt)
557ea2e6eecSWilly Tu     {
55815ed6780SWilly Tu         return false;
55915ed6780SWilly Tu     }
56015ed6780SWilly Tu 
561ea2e6eecSWilly Tu     return readJson(*jsonRequest, res, key, std::forward<UnpackTypes&&>(in)...);
56215ed6780SWilly Tu }
56315ed6780SWilly Tu 
56415ed6780SWilly Tu template <typename... UnpackTypes>
56515ed6780SWilly Tu bool readJsonAction(const crow::Request& req, crow::Response& res,
566ea2e6eecSWilly Tu                     const char* key, UnpackTypes&&... in)
56715ed6780SWilly Tu {
56815ed6780SWilly Tu     nlohmann::json jsonRequest;
56915ed6780SWilly Tu     if (!json_util::processJsonFromRequest(res, req, jsonRequest))
57015ed6780SWilly Tu     {
57115ed6780SWilly Tu         BMCWEB_LOG_DEBUG << "Json value not readable";
57215ed6780SWilly Tu         return false;
57315ed6780SWilly Tu     }
574ea2e6eecSWilly Tu     return readJson(jsonRequest, res, key, std::forward<UnpackTypes&&>(in)...);
5750627a2c7SEd Tanous }
576185444b1SNan Zhou 
577185444b1SNan Zhou // Determines if two json objects are less, based on the presence of the
578185444b1SNan Zhou // @odata.id key
579185444b1SNan Zhou inline int odataObjectCmp(const nlohmann::json& a, const nlohmann::json& b)
580185444b1SNan Zhou {
581185444b1SNan Zhou     using object_t = nlohmann::json::object_t;
582185444b1SNan Zhou     const object_t* aObj = a.get_ptr<const object_t*>();
583185444b1SNan Zhou     const object_t* bObj = b.get_ptr<const object_t*>();
584185444b1SNan Zhou 
585185444b1SNan Zhou     if (aObj == nullptr)
586185444b1SNan Zhou     {
587185444b1SNan Zhou         if (bObj == nullptr)
588185444b1SNan Zhou         {
589185444b1SNan Zhou             return 0;
590185444b1SNan Zhou         }
591185444b1SNan Zhou         return -1;
592185444b1SNan Zhou     }
593185444b1SNan Zhou     if (bObj == nullptr)
594185444b1SNan Zhou     {
595185444b1SNan Zhou         return 1;
596185444b1SNan Zhou     }
597185444b1SNan Zhou     object_t::const_iterator aIt = aObj->find("@odata.id");
598185444b1SNan Zhou     object_t::const_iterator bIt = bObj->find("@odata.id");
599185444b1SNan Zhou     // If either object doesn't have the key, they get "sorted" to the end.
600185444b1SNan Zhou     if (aIt == aObj->end())
601185444b1SNan Zhou     {
602185444b1SNan Zhou         if (bIt == bObj->end())
603185444b1SNan Zhou         {
604185444b1SNan Zhou             return 0;
605185444b1SNan Zhou         }
606185444b1SNan Zhou         return -1;
607185444b1SNan Zhou     }
608185444b1SNan Zhou     if (bIt == bObj->end())
609185444b1SNan Zhou     {
610185444b1SNan Zhou         return 1;
611185444b1SNan Zhou     }
612185444b1SNan Zhou     const nlohmann::json::string_t* nameA =
613185444b1SNan Zhou         aIt->second.get_ptr<const std::string*>();
614185444b1SNan Zhou     const nlohmann::json::string_t* nameB =
615185444b1SNan Zhou         bIt->second.get_ptr<const std::string*>();
616185444b1SNan Zhou     // If either object doesn't have a string as the key, they get "sorted" to
617185444b1SNan Zhou     // the end.
618185444b1SNan Zhou     if (nameA == nullptr)
619185444b1SNan Zhou     {
620185444b1SNan Zhou         if (nameB == nullptr)
621185444b1SNan Zhou         {
622185444b1SNan Zhou             return 0;
623185444b1SNan Zhou         }
624185444b1SNan Zhou         return -1;
625185444b1SNan Zhou     }
626185444b1SNan Zhou     if (nameB == nullptr)
627185444b1SNan Zhou     {
628185444b1SNan Zhou         return 1;
629185444b1SNan Zhou     }
630185444b1SNan Zhou     boost::urls::url_view aUrl(*nameA);
631185444b1SNan Zhou     boost::urls::url_view bUrl(*nameB);
632185444b1SNan Zhou     auto segmentsAIt = aUrl.segments().begin();
633185444b1SNan Zhou     auto segmentsBIt = bUrl.segments().begin();
634185444b1SNan Zhou 
635185444b1SNan Zhou     while (true)
636185444b1SNan Zhou     {
637185444b1SNan Zhou         if (segmentsAIt == aUrl.segments().end())
638185444b1SNan Zhou         {
639185444b1SNan Zhou             if (segmentsBIt == bUrl.segments().end())
640185444b1SNan Zhou             {
641185444b1SNan Zhou                 return 0;
642185444b1SNan Zhou             }
643185444b1SNan Zhou             return -1;
644185444b1SNan Zhou         }
645185444b1SNan Zhou         if (segmentsBIt == bUrl.segments().end())
646185444b1SNan Zhou         {
647185444b1SNan Zhou             return 1;
648185444b1SNan Zhou         }
649185444b1SNan Zhou         int res = alphanumComp(*segmentsAIt, *segmentsBIt);
650185444b1SNan Zhou         if (res != 0)
651185444b1SNan Zhou         {
652185444b1SNan Zhou             return res;
653185444b1SNan Zhou         }
654185444b1SNan Zhou 
655185444b1SNan Zhou         segmentsAIt++;
656185444b1SNan Zhou         segmentsBIt++;
657185444b1SNan Zhou     }
658185444b1SNan Zhou };
659185444b1SNan Zhou 
660185444b1SNan Zhou struct ODataObjectLess
661185444b1SNan Zhou {
662185444b1SNan Zhou     bool operator()(const nlohmann::json& left,
663185444b1SNan Zhou                     const nlohmann::json& right) const
664185444b1SNan Zhou     {
665185444b1SNan Zhou         return odataObjectCmp(left, right) < 0;
666185444b1SNan Zhou     }
667185444b1SNan Zhou };
668185444b1SNan Zhou 
669185444b1SNan Zhou // Sort the JSON array by |element[key]|.
670185444b1SNan Zhou // Elements without |key| or type of |element[key]| is not string are smaller
671185444b1SNan Zhou // those whose |element[key]| is string.
672185444b1SNan Zhou inline void sortJsonArrayByOData(nlohmann::json::array_t& array)
673185444b1SNan Zhou {
674185444b1SNan Zhou     std::sort(array.begin(), array.end(), ODataObjectLess());
675185444b1SNan Zhou }
676185444b1SNan Zhou 
677*8a7c4b47SNan Zhou // Returns the estimated size of the JSON value
678*8a7c4b47SNan Zhou // The implementation walks through every key and every value, accumulates the
679*8a7c4b47SNan Zhou //  total size of keys and values.
680*8a7c4b47SNan Zhou // Ideally, we should use a custom allocator that nlohmann JSON supports.
681*8a7c4b47SNan Zhou 
682*8a7c4b47SNan Zhou // Assumption made:
683*8a7c4b47SNan Zhou //  1. number: 8 characters
684*8a7c4b47SNan Zhou //  2. boolean: 5 characters (False)
685*8a7c4b47SNan Zhou //  3. string: len(str) + 2 characters (quote)
686*8a7c4b47SNan Zhou //  4. bytes: len(bytes) characters
687*8a7c4b47SNan Zhou //  5. null: 4 characters (null)
688*8a7c4b47SNan Zhou uint64_t getEstimatedJsonSize(const nlohmann::json& root);
689*8a7c4b47SNan Zhou 
69077dd8813SKowalski, Kamil } // namespace json_util
69177dd8813SKowalski, Kamil } // namespace redfish
692