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