xref: /openbmc/bmcweb/features/redfish/include/utils/json_utils.hpp (revision 0627a2c77b7600a53c84bbfec49d04588c260608)
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>
70 void unpackValue(nlohmann::json& jsonValue, const std::string& key,
71                  crow::Response& res, Type& value)
72 {
73     if constexpr (std::is_arithmetic_v<Type>)
74     {
75         using NumType =
76             std::conditional_t<std::is_signed_v<Type>, int64_t, uint64_t>;
77 
78         NumType* jsonPtr = jsonValue.get_ptr<NumType*>();
79         if (jsonPtr == nullptr)
80         {
81             BMCWEB_LOG_DEBUG
82                 << "Value for key " << key
83                 << " was incorrect type: " << jsonValue.type_name();
84             messages::propertyValueTypeError(res, jsonValue.dump(), key);
85             return;
86         }
87         if (*jsonPtr > std::numeric_limits<Type>::max())
88         {
89             BMCWEB_LOG_DEBUG << "Value for key " << key
90                              << " was out of range: " << jsonValue.type_name();
91             messages::propertyValueNotInList(res, jsonValue.dump(), key);
92             return;
93         }
94         if (*jsonPtr < std::numeric_limits<Type>::min())
95         {
96             BMCWEB_LOG_DEBUG << "Value for key " << key
97                              << " was out of range: " << jsonValue.type_name();
98             messages::propertyValueNotInList(res, jsonValue.dump(), key);
99             return;
100         }
101         value = static_cast<Type>(*jsonPtr);
102     }
103     else if constexpr (is_optional_v<Type>)
104     {
105         value.emplace();
106         unpackValue<typename Type::value_type>(jsonValue, key, res, *value);
107     }
108     else if constexpr (std::is_same_v<nlohmann::json, Type>)
109     {
110         // Must be a complex type.  Simple types (int string etc) should be
111         // unpacked directly
112         if (!jsonValue.is_object() && !jsonValue.is_array())
113         {
114             messages::propertyValueTypeError(res, jsonValue.dump(), key);
115             return;
116         }
117 
118         value = std::move(jsonValue);
119     }
120     else if constexpr (is_vector_v<Type>)
121     {
122         if (!jsonValue.is_array())
123         {
124             messages::propertyValueTypeError(res, res.jsonValue.dump(), key);
125             return;
126         }
127 
128         for (const auto& val : jsonValue.items())
129         {
130             value.emplace_back();
131             unpackValue<typename Type::value_type>(val.value(), key, res,
132                                                    value.back());
133         }
134     }
135     else
136     {
137         using JsonType = std::add_const_t<std::add_pointer_t<Type>>;
138         JsonType jsonPtr = jsonValue.get_ptr<JsonType>();
139         if (jsonPtr == nullptr)
140         {
141             BMCWEB_LOG_DEBUG
142                 << "Value for key " << key
143                 << " was incorrect type: " << jsonValue.type_name();
144             messages::propertyValueTypeError(res, jsonValue.dump(), key);
145             return;
146         }
147         value = std::move(*jsonPtr);
148     }
149 }
150 
151 template <size_t Count, size_t Index>
152 void readJsonValues(const std::string& key, nlohmann::json& jsonValue,
153                     crow::Response& res, std::bitset<Count>& handled)
154 {
155     BMCWEB_LOG_DEBUG << "Unable to find variable for key" << key;
156     messages::propertyUnknown(res, key);
157 }
158 
159 template <size_t Count, size_t Index, typename ValueType,
160           typename... UnpackTypes>
161 void readJsonValues(const std::string& key, nlohmann::json& jsonValue,
162                     crow::Response& res, std::bitset<Count>& handled,
163                     const char* keyToCheck, ValueType& valueToFill,
164                     UnpackTypes&... in)
165 {
166     if (key != keyToCheck)
167     {
168         readJsonValues<Count, Index + 1>(key, jsonValue, res, handled, in...);
169         return;
170     }
171 
172     handled.set(Index);
173 
174     unpackValue<ValueType>(jsonValue, key, res, valueToFill);
175 }
176 
177 template <size_t Index = 0, size_t Count>
178 void handleMissing(std::bitset<Count>& handled, crow::Response& res)
179 {
180 }
181 
182 template <size_t Index = 0, size_t Count, typename ValueType,
183           typename... UnpackTypes>
184 void handleMissing(std::bitset<Count>& handled, crow::Response& res,
185                    const char* key, ValueType& unused, UnpackTypes&... in)
186 {
187     if (!handled.test(Index) && !is_optional_v<ValueType>)
188     {
189         messages::propertyMissing(res, key);
190     }
191     details::handleMissing<Index + 1, Count>(handled, res, in...);
192 }
193 } // namespace details
194 
195 template <typename... UnpackTypes>
196 bool readJson(nlohmann::json& jsonRequest, crow::Response& res, const char* key,
197               UnpackTypes&... in)
198 {
199     if (!jsonRequest.is_object())
200     {
201         BMCWEB_LOG_DEBUG << "Json value is not an object";
202         messages::unrecognizedRequestBody(res);
203         return false;
204     }
205 
206     if (jsonRequest.empty())
207     {
208         BMCWEB_LOG_DEBUG << "Json value is empty";
209         messages::emptyJSON(res);
210         return false;
211     }
212 
213     std::bitset<(sizeof...(in) + 1) / 2> handled(0);
214     for (const auto& item : jsonRequest.items())
215     {
216         details::readJsonValues<(sizeof...(in) + 1) / 2, 0, UnpackTypes...>(
217             item.key(), item.value(), res, handled, key, in...);
218     }
219 
220     details::handleMissing(handled, res, key, in...);
221 
222     return res.result() == boost::beast::http::status::ok;
223 }
224 
225 template <typename... UnpackTypes>
226 bool readJson(const crow::Request& req, crow::Response& res, const char* key,
227               UnpackTypes&... in)
228 {
229     nlohmann::json jsonRequest;
230     if (!json_util::processJsonFromRequest(res, req, jsonRequest))
231     {
232         BMCWEB_LOG_DEBUG << "Json value not readable";
233         return false;
234     }
235     return readJson(jsonRequest, res, key, in...);
236 }
237 
238 } // namespace json_util
239 } // namespace redfish
240