• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 //
2 //
3 // Copyright 2015 gRPC authors.
4 //
5 // Licensed under the Apache License, Version 2.0 (the "License");
6 // you may not use this file except in compliance with the License.
7 // You may obtain a copy of the License at
8 //
9 //     http://www.apache.org/licenses/LICENSE-2.0
10 //
11 // Unless required by applicable law or agreed to in writing, software
12 // distributed under the License is distributed on an "AS IS" BASIS,
13 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14 // See the License for the specific language governing permissions and
15 // limitations under the License.
16 //
17 //
18 
19 #include "src/core/lib/security/util/json_util.h"
20 
21 #include <grpc/support/json.h>
22 #include <grpc/support/port_platform.h>
23 #include <grpc/support/string_util.h>
24 
25 #include <map>
26 #include <string>
27 #include <utility>
28 
29 #include "absl/strings/str_cat.h"
30 #include "src/core/lib/iomgr/error.h"
31 
grpc_json_get_string_property(const grpc_core::Json & json,const char * prop_name,grpc_error_handle * error)32 const char* grpc_json_get_string_property(const grpc_core::Json& json,
33                                           const char* prop_name,
34                                           grpc_error_handle* error) {
35   if (json.type() != grpc_core::Json::Type::kObject) {
36     if (error != nullptr) {
37       *error = GRPC_ERROR_CREATE("JSON value is not an object");
38     }
39     return nullptr;
40   }
41   auto it = json.object().find(prop_name);
42   if (it == json.object().end()) {
43     if (error != nullptr) {
44       *error = GRPC_ERROR_CREATE(
45           absl::StrCat("Property ", prop_name, " not found in JSON object."));
46     }
47     return nullptr;
48   }
49   if (it->second.type() != grpc_core::Json::Type::kString) {
50     if (error != nullptr) {
51       *error = GRPC_ERROR_CREATE(absl::StrCat(
52           "Property ", prop_name, " n JSON object is not a string."));
53     }
54     return nullptr;
55   }
56   return it->second.string().c_str();
57 }
58 
grpc_copy_json_string_property(const grpc_core::Json & json,const char * prop_name,char ** copied_value)59 bool grpc_copy_json_string_property(const grpc_core::Json& json,
60                                     const char* prop_name,
61                                     char** copied_value) {
62   grpc_error_handle error;
63   const char* prop_value =
64       grpc_json_get_string_property(json, prop_name, &error);
65   GRPC_LOG_IF_ERROR("Could not copy JSON property", error);
66   if (prop_value == nullptr) return false;
67   *copied_value = gpr_strdup(prop_value);
68   return true;
69 }
70