xref: /openbmc/bmcweb/features/redfish/include/utils/json_utils.hpp (revision 8ebc91f6b7f6820f0b2a7b99401002cb4524cd79)
1 /*
2 // Copyright (c) 2018 Intel Corporation
3 //
4 // Licensed under the Apache License, Version 2.0 (the "License");
5 // you may not use this file except in compliance with the License.
6 // You may obtain a copy of the License at
7 //
8 //      http://www.apache.org/licenses/LICENSE-2.0
9 //
10 // Unless required by applicable law or agreed to in writing, software
11 // distributed under the License is distributed on an "AS IS" BASIS,
12 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 // See the License for the specific language governing permissions and
14 // limitations under the License.
15 */
16 #pragma once
17 
18 #include <crow/http_request.h>
19 #include <crow/http_response.h>
20 
21 #include <bitset>
22 #include <error_messages.hpp>
23 #include <nlohmann/json.hpp>
24 
25 namespace redfish
26 {
27 
28 namespace json_util
29 {
30 
31 /**
32  * @brief Processes request to extract JSON from its body. If it fails, adds
33  *       MalformedJSON message to response and ends it.
34  *
35  * @param[io]  res       Response object
36  * @param[in]  req       Request object
37  * @param[out] reqJson   JSON object extracted from request's body
38  *
39  * @return true if JSON is valid, false when JSON is invalid and response has
40  *         been filled with message and ended.
41  */
42 bool processJsonFromRequest(crow::Response& res, const crow::Request& req,
43                             nlohmann::json& reqJson);
44 namespace details
45 {
46 
47 template <typename Type> struct is_optional : std::false_type
48 {
49 };
50 
51 template <typename Type>
52 struct is_optional<std::optional<Type>> : std::true_type
53 {
54 };
55 
56 template <typename Type>
57 constexpr bool is_optional_v = is_optional<Type>::value;
58 
59 template <typename Type> struct is_vector : std::false_type
60 {
61 };
62 
63 template <typename Type> struct is_vector<std::vector<Type>> : std::true_type
64 {
65 };
66 
67 template <typename Type> constexpr bool is_vector_v = is_vector<Type>::value;
68 
69 template <typename Type> struct is_std_array : std::false_type
70 {
71 };
72 
73 template <typename Type, std::size_t size>
74 struct is_std_array<std::array<Type, size>> : std::true_type
75 {
76 };
77 
78 template <typename Type>
79 constexpr bool is_std_array_v = is_std_array<Type>::value;
80 
81 template <typename ToType, typename FromType>
82 bool checkRange(const FromType& from, const std::string& key,
83                 nlohmann::json& jsonValue, crow::Response& res)
84 {
85     if (from > std::numeric_limits<ToType>::max())
86     {
87         BMCWEB_LOG_DEBUG << "Value for key " << key
88                          << " was greater than max: " << __PRETTY_FUNCTION__;
89         messages::propertyValueNotInList(res, jsonValue.dump(), key);
90         return false;
91     }
92     if (from < std::numeric_limits<ToType>::lowest())
93     {
94         BMCWEB_LOG_DEBUG << "Value for key " << key
95                          << " was less than min: " << __PRETTY_FUNCTION__;
96         messages::propertyValueNotInList(res, jsonValue.dump(), key);
97         return false;
98     }
99     if constexpr (std::is_floating_point_v<ToType>)
100     {
101         if (std::isnan(from))
102         {
103             BMCWEB_LOG_DEBUG << "Value for key " << key << " was NAN";
104             messages::propertyValueNotInList(res, jsonValue.dump(), key);
105             return false;
106         }
107     }
108 
109     return true;
110 }
111 
112 template <typename Type>
113 bool unpackValue(nlohmann::json& jsonValue, const std::string& key,
114                  crow::Response& res, Type& value)
115 {
116     bool ret = true;
117 
118     if constexpr (std::is_floating_point_v<Type>)
119     {
120         double helper = 0;
121         double* jsonPtr = jsonValue.get_ptr<double*>();
122 
123         if (jsonPtr == nullptr)
124         {
125             int64_t* intPtr = jsonValue.get_ptr<int64_t*>();
126             if (intPtr != nullptr)
127             {
128                 helper = static_cast<double>(*intPtr);
129                 jsonPtr = &helper;
130             }
131         }
132         if (!checkRange<Type>(*jsonPtr, key, jsonValue, res))
133         {
134             return false;
135         }
136         value = static_cast<Type>(*jsonPtr);
137     }
138 
139     else if constexpr (std::is_signed_v<Type>)
140     {
141         int64_t* jsonPtr = jsonValue.get_ptr<int64_t*>();
142         if (!checkRange<Type>(*jsonPtr, key, jsonValue, res))
143         {
144             return false;
145         }
146         value = static_cast<Type>(*jsonPtr);
147     }
148 
149     else if constexpr ((std::is_unsigned_v<Type>)&&(
150                            !std::is_same_v<bool, Type>))
151     {
152         uint64_t* jsonPtr = jsonValue.get_ptr<uint64_t*>();
153         if (!checkRange<Type>(*jsonPtr, key, jsonValue, res))
154         {
155             return false;
156         }
157         value = static_cast<Type>(*jsonPtr);
158     }
159 
160     else if constexpr (is_optional_v<Type>)
161     {
162         value.emplace();
163         ret = unpackValue<typename Type::value_type>(jsonValue, key, res,
164                                                      *value) &&
165               ret;
166     }
167     else if constexpr (std::is_same_v<nlohmann::json, Type>)
168     {
169         // Must be a complex type.  Simple types (int string etc) should be
170         // unpacked directly
171         if (!jsonValue.is_object() && !jsonValue.is_array() &&
172             !jsonValue.is_null())
173         {
174             messages::propertyValueTypeError(res, jsonValue.dump(), key);
175             return false;
176         }
177 
178         value = std::move(jsonValue);
179     }
180     else if constexpr (is_std_array_v<Type>)
181     {
182         if (!jsonValue.is_array())
183         {
184             messages::propertyValueTypeError(res, res.jsonValue.dump(), key);
185             return false;
186         }
187         if (jsonValue.size() != value.size())
188         {
189             messages::propertyValueTypeError(res, res.jsonValue.dump(), key);
190             return false;
191         }
192         size_t index = 0;
193         for (const auto& val : jsonValue.items())
194         {
195             ret = unpackValue<typename Type::value_type>(val.value(), key, res,
196                                                          value[index++]) &&
197                   ret;
198         }
199     }
200     else if constexpr (is_vector_v<Type>)
201     {
202         if (!jsonValue.is_array())
203         {
204             messages::propertyValueTypeError(res, res.jsonValue.dump(), key);
205             return false;
206         }
207 
208         for (const auto& val : jsonValue.items())
209         {
210             value.emplace_back();
211             ret = unpackValue<typename Type::value_type>(val.value(), key, res,
212                                                          value.back()) &&
213                   ret;
214         }
215     }
216     else
217     {
218         using JsonType = std::add_const_t<std::add_pointer_t<Type>>;
219         JsonType jsonPtr = jsonValue.get_ptr<JsonType>();
220         if (jsonPtr == nullptr)
221         {
222             BMCWEB_LOG_DEBUG
223                 << "Value for key " << key
224                 << " was incorrect type: " << jsonValue.type_name();
225             messages::propertyValueTypeError(res, jsonValue.dump(), key);
226             return false;
227         }
228         value = std::move(*jsonPtr);
229     }
230     return ret;
231 }
232 
233 template <size_t Count, size_t Index>
234 bool readJsonValues(const std::string& key, nlohmann::json& jsonValue,
235                     crow::Response& res, std::bitset<Count>& handled)
236 {
237     BMCWEB_LOG_DEBUG << "Unable to find variable for key" << key;
238     messages::propertyUnknown(res, key);
239     return false;
240 }
241 
242 template <size_t Count, size_t Index, typename ValueType,
243           typename... UnpackTypes>
244 bool readJsonValues(const std::string& key, nlohmann::json& jsonValue,
245                     crow::Response& res, std::bitset<Count>& handled,
246                     const char* keyToCheck, ValueType& valueToFill,
247                     UnpackTypes&... in)
248 {
249     bool ret = true;
250     if (key != keyToCheck)
251     {
252         ret = readJsonValues<Count, Index + 1>(key, jsonValue, res, handled,
253                                                in...) &&
254               ret;
255         return ret;
256     }
257 
258     handled.set(Index);
259 
260     return unpackValue<ValueType>(jsonValue, key, res, valueToFill) && ret;
261 }
262 
263 template <size_t Index = 0, size_t Count>
264 bool handleMissing(std::bitset<Count>& handled, crow::Response& res)
265 {
266     return true;
267 }
268 
269 template <size_t Index = 0, size_t Count, typename ValueType,
270           typename... UnpackTypes>
271 bool handleMissing(std::bitset<Count>& handled, crow::Response& res,
272                    const char* key, ValueType& unused, UnpackTypes&... in)
273 {
274     bool ret = true;
275     if (!handled.test(Index) && !is_optional_v<ValueType>)
276     {
277         ret = false;
278         messages::propertyMissing(res, key);
279     }
280     return details::handleMissing<Index + 1, Count>(handled, res, in...) && ret;
281 }
282 } // namespace details
283 
284 template <typename... UnpackTypes>
285 bool readJson(nlohmann::json& jsonRequest, crow::Response& res, const char* key,
286               UnpackTypes&... in)
287 {
288     bool result = true;
289     if (!jsonRequest.is_object())
290     {
291         BMCWEB_LOG_DEBUG << "Json value is not an object";
292         messages::unrecognizedRequestBody(res);
293         return false;
294     }
295 
296     if (jsonRequest.empty())
297     {
298         BMCWEB_LOG_DEBUG << "Json value is empty";
299         messages::emptyJSON(res);
300         return false;
301     }
302 
303     std::bitset<(sizeof...(in) + 1) / 2> handled(0);
304     for (const auto& item : jsonRequest.items())
305     {
306         result =
307             details::readJsonValues<(sizeof...(in) + 1) / 2, 0, UnpackTypes...>(
308                 item.key(), item.value(), res, handled, key, in...) &&
309             result;
310     }
311 
312     BMCWEB_LOG_DEBUG << "JSON result is: " << result;
313 
314     return details::handleMissing(handled, res, key, in...) && result;
315 }
316 
317 template <typename... UnpackTypes>
318 bool readJson(const crow::Request& req, crow::Response& res, const char* key,
319               UnpackTypes&... in)
320 {
321     nlohmann::json jsonRequest;
322     if (!json_util::processJsonFromRequest(res, req, jsonRequest))
323     {
324         BMCWEB_LOG_DEBUG << "Json value not readable";
325         return false;
326     }
327     return readJson(jsonRequest, res, key, in...);
328 }
329 
330 } // namespace json_util
331 } // namespace redfish
332