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 #include "utils/json_utils.hpp"
17 
18 #include "error_messages.hpp"
19 #include "http/http_request.hpp"
20 #include "http/http_response.hpp"
21 #include "http/parsing.hpp"
22 
23 #include <nlohmann/json.hpp>
24 
25 #include <cstdint>
26 #include <string>
27 
28 namespace redfish
29 {
30 
31 namespace json_util
32 {
33 
34 bool processJsonFromRequest(crow::Response& res, const crow::Request& req,
35                             nlohmann::json& reqJson)
36 {
37     JsonParseResult ret = parseRequestAsJson(req, reqJson);
38     if (ret == JsonParseResult::BadContentType)
39     {
40         messages::unrecognizedRequestBody(res);
41         return false;
42     }
43     reqJson = nlohmann::json::parse(req.body(), nullptr, false);
44 
45     if (reqJson.is_discarded())
46     {
47         messages::malformedJSON(res);
48         return false;
49     }
50 
51     return true;
52 }
53 
54 uint64_t getEstimatedJsonSize(const nlohmann::json& root)
55 {
56     if (root.is_null())
57     {
58         return 4;
59     }
60     if (root.is_number())
61     {
62         return 8;
63     }
64     if (root.is_boolean())
65     {
66         return 5;
67     }
68     if (root.is_string())
69     {
70         constexpr uint64_t quotesSize = 2;
71         return root.get<std::string>().size() + quotesSize;
72     }
73     if (root.is_binary())
74     {
75         return root.get_binary().size();
76     }
77     const nlohmann::json::array_t* arr =
78         root.get_ptr<const nlohmann::json::array_t*>();
79     if (arr != nullptr)
80     {
81         uint64_t sum = 0;
82         for (const auto& element : *arr)
83         {
84             sum += getEstimatedJsonSize(element);
85         }
86         return sum;
87     }
88     const nlohmann::json::object_t* object =
89         root.get_ptr<const nlohmann::json::object_t*>();
90     if (object != nullptr)
91     {
92         uint64_t sum = 0;
93         for (const auto& [k, v] : *object)
94         {
95             constexpr uint64_t colonQuoteSpaceSize = 4;
96             sum += k.size() + getEstimatedJsonSize(v) + colonQuoteSpaceSize;
97         }
98         return sum;
99     }
100     return 0;
101 }
102 
103 } // namespace json_util
104 } // namespace redfish
105