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 <grpc/support/port_platform.h>
20
21 #include <string.h>
22
23 #include "absl/strings/str_cat.h"
24
25 #include <grpc/support/log.h>
26 #include <grpc/support/string_util.h>
27
28 #include "src/core/lib/iomgr/error.h"
29 #include "src/core/lib/security/util/json_util.h"
30
grpc_json_get_string_property(const grpc_core::Json & json,const char * prop_name,grpc_error ** error)31 const char* grpc_json_get_string_property(const grpc_core::Json& json,
32 const char* prop_name,
33 grpc_error** error) {
34 if (json.type() != grpc_core::Json::Type::OBJECT) {
35 if (error != nullptr) {
36 *error =
37 GRPC_ERROR_CREATE_FROM_STATIC_STRING("JSON value is not an object");
38 }
39 return nullptr;
40 }
41 auto it = json.object_value().find(prop_name);
42 if (it == json.object_value().end()) {
43 if (error != nullptr) {
44 *error = GRPC_ERROR_CREATE_FROM_COPIED_STRING(
45 absl::StrCat("Property ", prop_name, " not found in JSON object.")
46 .c_str());
47 }
48 return nullptr;
49 }
50 if (it->second.type() != grpc_core::Json::Type::STRING) {
51 if (error != nullptr) {
52 *error = GRPC_ERROR_CREATE_FROM_COPIED_STRING(
53 absl::StrCat("Property ", prop_name,
54 " n JSON object is not a string.")
55 .c_str());
56 }
57 return nullptr;
58 }
59 return it->second.string_value().c_str();
60 }
61
grpc_copy_json_string_property(const grpc_core::Json & json,const char * prop_name,char ** copied_value)62 bool grpc_copy_json_string_property(const grpc_core::Json& json,
63 const char* prop_name,
64 char** copied_value) {
65 grpc_error* error = GRPC_ERROR_NONE;
66 const char* prop_value =
67 grpc_json_get_string_property(json, prop_name, &error);
68 GRPC_LOG_IF_ERROR("Could not copy JSON property", error);
69 if (prop_value == nullptr) return false;
70 *copied_value = gpr_strdup(prop_value);
71 return true;
72 }
73