xref: /openbmc/bmcweb/features/redfish/include/utils/json_utils.hpp (revision ee344e0fa76b2b24866d25b305e12ae82824f01b)
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         {
173             messages::propertyValueTypeError(res, jsonValue.dump(), key);
174             return false;
175         }
176 
177         value = std::move(jsonValue);
178     }
179     else if constexpr (is_std_array_v<Type>)
180     {
181         if (!jsonValue.is_array())
182         {
183             messages::propertyValueTypeError(res, res.jsonValue.dump(), key);
184             return false;
185         }
186         if (jsonValue.size() != value.size())
187         {
188             messages::propertyValueTypeError(res, res.jsonValue.dump(), key);
189             return false;
190         }
191         size_t index = 0;
192         for (const auto& val : jsonValue.items())
193         {
194             ret = unpackValue<typename Type::value_type>(val.value(), key, res,
195                                                          value[index++]) &&
196                   ret;
197         }
198     }
199     else if constexpr (is_vector_v<Type>)
200     {
201         if (!jsonValue.is_array())
202         {
203             messages::propertyValueTypeError(res, res.jsonValue.dump(), key);
204             return false;
205         }
206 
207         for (const auto& val : jsonValue.items())
208         {
209             value.emplace_back();
210             ret = unpackValue<typename Type::value_type>(val.value(), key, res,
211                                                          value.back()) &&
212                   ret;
213         }
214     }
215     else
216     {
217         using JsonType = std::add_const_t<std::add_pointer_t<Type>>;
218         JsonType jsonPtr = jsonValue.get_ptr<JsonType>();
219         if (jsonPtr == nullptr)
220         {
221             BMCWEB_LOG_DEBUG
222                 << "Value for key " << key
223                 << " was incorrect type: " << jsonValue.type_name();
224             messages::propertyValueTypeError(res, jsonValue.dump(), key);
225             return false;
226         }
227         value = std::move(*jsonPtr);
228     }
229     return ret;
230 }
231 
232 template <size_t Count, size_t Index>
233 bool readJsonValues(const std::string& key, nlohmann::json& jsonValue,
234                     crow::Response& res, std::bitset<Count>& handled)
235 {
236     BMCWEB_LOG_DEBUG << "Unable to find variable for key" << key;
237     messages::propertyUnknown(res, key);
238     return false;
239 }
240 
241 template <size_t Count, size_t Index, typename ValueType,
242           typename... UnpackTypes>
243 bool readJsonValues(const std::string& key, nlohmann::json& jsonValue,
244                     crow::Response& res, std::bitset<Count>& handled,
245                     const char* keyToCheck, ValueType& valueToFill,
246                     UnpackTypes&... in)
247 {
248     bool ret = true;
249     if (key != keyToCheck)
250     {
251         ret = readJsonValues<Count, Index + 1>(key, jsonValue, res, handled,
252                                                in...) &&
253               ret;
254         return ret;
255     }
256 
257     handled.set(Index);
258 
259     return unpackValue<ValueType>(jsonValue, key, res, valueToFill) && ret;
260 }
261 
262 template <size_t Index = 0, size_t Count>
263 bool handleMissing(std::bitset<Count>& handled, crow::Response& res)
264 {
265     return true;
266 }
267 
268 template <size_t Index = 0, size_t Count, typename ValueType,
269           typename... UnpackTypes>
270 bool handleMissing(std::bitset<Count>& handled, crow::Response& res,
271                    const char* key, ValueType& unused, UnpackTypes&... in)
272 {
273     bool ret = true;
274     if (!handled.test(Index) && !is_optional_v<ValueType>)
275     {
276         ret = false;
277         messages::propertyMissing(res, key);
278     }
279     return details::handleMissing<Index + 1, Count>(handled, res, in...) && ret;
280 }
281 } // namespace details
282 
283 template <typename... UnpackTypes>
284 bool readJson(nlohmann::json& jsonRequest, crow::Response& res, const char* key,
285               UnpackTypes&... in)
286 {
287     bool result = true;
288     if (!jsonRequest.is_object())
289     {
290         BMCWEB_LOG_DEBUG << "Json value is not an object";
291         messages::unrecognizedRequestBody(res);
292         return false;
293     }
294 
295     if (jsonRequest.empty())
296     {
297         BMCWEB_LOG_DEBUG << "Json value is empty";
298         messages::emptyJSON(res);
299         return false;
300     }
301 
302     std::bitset<(sizeof...(in) + 1) / 2> handled(0);
303     for (const auto& item : jsonRequest.items())
304     {
305         result =
306             details::readJsonValues<(sizeof...(in) + 1) / 2, 0, UnpackTypes...>(
307                 item.key(), item.value(), res, handled, key, in...) &&
308             result;
309     }
310 
311     BMCWEB_LOG_DEBUG << "JSON result is: " << result;
312 
313     return details::handleMissing(handled, res, key, in...) && result;
314 }
315 
316 template <typename... UnpackTypes>
317 bool readJson(const crow::Request& req, crow::Response& res, const char* key,
318               UnpackTypes&... in)
319 {
320     nlohmann::json jsonRequest;
321     if (!json_util::processJsonFromRequest(res, req, jsonRequest))
322     {
323         BMCWEB_LOG_DEBUG << "Json value not readable";
324         return false;
325     }
326     return readJson(jsonRequest, res, key, in...);
327 }
328 
329 } // namespace json_util
330 } // namespace redfish
331