1 /*
2  *
3  * Copyright 2016 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 "test/cpp/util/proto_file_parser.h"
20 
21 #include <algorithm>
22 #include <iostream>
23 #include <sstream>
24 #include <unordered_set>
25 
26 #include <grpcpp/support/config.h>
27 
28 namespace grpc {
29 namespace testing {
30 namespace {
31 
32 // Match the user input method string to the full_name from method descriptor.
MethodNameMatch(const grpc::string & full_name,const grpc::string & input)33 bool MethodNameMatch(const grpc::string& full_name, const grpc::string& input) {
34   grpc::string clean_input = input;
35   std::replace(clean_input.begin(), clean_input.end(), '/', '.');
36   if (clean_input.size() > full_name.size()) {
37     return false;
38   }
39   return full_name.compare(full_name.size() - clean_input.size(),
40                            clean_input.size(), clean_input) == 0;
41 }
42 }  // namespace
43 
44 class ErrorPrinter : public protobuf::compiler::MultiFileErrorCollector {
45  public:
ErrorPrinter(ProtoFileParser * parser)46   explicit ErrorPrinter(ProtoFileParser* parser) : parser_(parser) {}
47 
AddError(const grpc::string & filename,int line,int column,const grpc::string & message)48   void AddError(const grpc::string& filename, int line, int column,
49                 const grpc::string& message) override {
50     std::ostringstream oss;
51     oss << "error " << filename << " " << line << " " << column << " "
52         << message << "\n";
53     parser_->LogError(oss.str());
54   }
55 
AddWarning(const grpc::string & filename,int line,int column,const grpc::string & message)56   void AddWarning(const grpc::string& filename, int line, int column,
57                   const grpc::string& message) override {
58     std::cerr << "warning " << filename << " " << line << " " << column << " "
59               << message << std::endl;
60   }
61 
62  private:
63   ProtoFileParser* parser_;  // not owned
64 };
65 
ProtoFileParser(const std::shared_ptr<grpc::Channel> & channel,const grpc::string & proto_path,const grpc::string & protofiles)66 ProtoFileParser::ProtoFileParser(const std::shared_ptr<grpc::Channel>& channel,
67                                  const grpc::string& proto_path,
68                                  const grpc::string& protofiles)
69     : has_error_(false),
70       dynamic_factory_(new protobuf::DynamicMessageFactory()) {
71   std::vector<grpc::string> service_list;
72   if (channel) {
73     reflection_db_.reset(new grpc::ProtoReflectionDescriptorDatabase(channel));
74     reflection_db_->GetServices(&service_list);
75   }
76 
77   std::unordered_set<grpc::string> known_services;
78   if (!protofiles.empty()) {
79     source_tree_.MapPath("", proto_path);
80     error_printer_.reset(new ErrorPrinter(this));
81     importer_.reset(
82         new protobuf::compiler::Importer(&source_tree_, error_printer_.get()));
83 
84     grpc::string file_name;
85     std::stringstream ss(protofiles);
86     while (std::getline(ss, file_name, ',')) {
87       const auto* file_desc = importer_->Import(file_name);
88       if (file_desc) {
89         for (int i = 0; i < file_desc->service_count(); i++) {
90           service_desc_list_.push_back(file_desc->service(i));
91           known_services.insert(file_desc->service(i)->full_name());
92         }
93       } else {
94         std::cerr << file_name << " not found" << std::endl;
95       }
96     }
97 
98     file_db_.reset(new protobuf::DescriptorPoolDatabase(*importer_->pool()));
99   }
100 
101   if (!reflection_db_ && !file_db_) {
102     LogError("No available proto database");
103     return;
104   }
105 
106   if (!reflection_db_) {
107     desc_db_ = std::move(file_db_);
108   } else if (!file_db_) {
109     desc_db_ = std::move(reflection_db_);
110   } else {
111     desc_db_.reset(new protobuf::MergedDescriptorDatabase(reflection_db_.get(),
112                                                           file_db_.get()));
113   }
114 
115   desc_pool_.reset(new protobuf::DescriptorPool(desc_db_.get()));
116 
117   for (auto it = service_list.begin(); it != service_list.end(); it++) {
118     if (known_services.find(*it) == known_services.end()) {
119       if (const protobuf::ServiceDescriptor* service_desc =
120               desc_pool_->FindServiceByName(*it)) {
121         service_desc_list_.push_back(service_desc);
122         known_services.insert(*it);
123       }
124     }
125   }
126 }
127 
~ProtoFileParser()128 ProtoFileParser::~ProtoFileParser() {}
129 
GetFullMethodName(const grpc::string & method)130 grpc::string ProtoFileParser::GetFullMethodName(const grpc::string& method) {
131   has_error_ = false;
132 
133   if (known_methods_.find(method) != known_methods_.end()) {
134     return known_methods_[method];
135   }
136 
137   const protobuf::MethodDescriptor* method_descriptor = nullptr;
138   for (auto it = service_desc_list_.begin(); it != service_desc_list_.end();
139        it++) {
140     const auto* service_desc = *it;
141     for (int j = 0; j < service_desc->method_count(); j++) {
142       const auto* method_desc = service_desc->method(j);
143       if (MethodNameMatch(method_desc->full_name(), method)) {
144         if (method_descriptor) {
145           std::ostringstream error_stream;
146           error_stream << "Ambiguous method names: ";
147           error_stream << method_descriptor->full_name() << " ";
148           error_stream << method_desc->full_name();
149           LogError(error_stream.str());
150         }
151         method_descriptor = method_desc;
152       }
153     }
154   }
155   if (!method_descriptor) {
156     LogError("Method name not found");
157   }
158   if (has_error_) {
159     return "";
160   }
161 
162   known_methods_[method] = method_descriptor->full_name();
163 
164   return method_descriptor->full_name();
165 }
166 
GetFormattedMethodName(const grpc::string & method)167 grpc::string ProtoFileParser::GetFormattedMethodName(
168     const grpc::string& method) {
169   has_error_ = false;
170   grpc::string formatted_method_name = GetFullMethodName(method);
171   if (has_error_) {
172     return "";
173   }
174   size_t last_dot = formatted_method_name.find_last_of('.');
175   if (last_dot != grpc::string::npos) {
176     formatted_method_name[last_dot] = '/';
177   }
178   formatted_method_name.insert(formatted_method_name.begin(), '/');
179   return formatted_method_name;
180 }
181 
GetMessageTypeFromMethod(const grpc::string & method,bool is_request)182 grpc::string ProtoFileParser::GetMessageTypeFromMethod(
183     const grpc::string& method, bool is_request) {
184   has_error_ = false;
185   grpc::string full_method_name = GetFullMethodName(method);
186   if (has_error_) {
187     return "";
188   }
189   const protobuf::MethodDescriptor* method_desc =
190       desc_pool_->FindMethodByName(full_method_name);
191   if (!method_desc) {
192     LogError("Method not found");
193     return "";
194   }
195 
196   return is_request ? method_desc->input_type()->full_name()
197                     : method_desc->output_type()->full_name();
198 }
199 
IsStreaming(const grpc::string & method,bool is_request)200 bool ProtoFileParser::IsStreaming(const grpc::string& method, bool is_request) {
201   has_error_ = false;
202 
203   grpc::string full_method_name = GetFullMethodName(method);
204   if (has_error_) {
205     return false;
206   }
207 
208   const protobuf::MethodDescriptor* method_desc =
209       desc_pool_->FindMethodByName(full_method_name);
210   if (!method_desc) {
211     LogError("Method not found");
212     return false;
213   }
214 
215   return is_request ? method_desc->client_streaming()
216                     : method_desc->server_streaming();
217 }
218 
GetSerializedProtoFromMethod(const grpc::string & method,const grpc::string & formatted_proto,bool is_request,bool is_json_format)219 grpc::string ProtoFileParser::GetSerializedProtoFromMethod(
220     const grpc::string& method, const grpc::string& formatted_proto,
221     bool is_request, bool is_json_format) {
222   has_error_ = false;
223   grpc::string message_type_name = GetMessageTypeFromMethod(method, is_request);
224   if (has_error_) {
225     return "";
226   }
227   return GetSerializedProtoFromMessageType(message_type_name, formatted_proto,
228                                            is_json_format);
229 }
230 
GetFormattedStringFromMethod(const grpc::string & method,const grpc::string & serialized_proto,bool is_request,bool is_json_format)231 grpc::string ProtoFileParser::GetFormattedStringFromMethod(
232     const grpc::string& method, const grpc::string& serialized_proto,
233     bool is_request, bool is_json_format) {
234   has_error_ = false;
235   grpc::string message_type_name = GetMessageTypeFromMethod(method, is_request);
236   if (has_error_) {
237     return "";
238   }
239   return GetFormattedStringFromMessageType(message_type_name, serialized_proto,
240                                            is_json_format);
241 }
242 
GetSerializedProtoFromMessageType(const grpc::string & message_type_name,const grpc::string & formatted_proto,bool is_json_format)243 grpc::string ProtoFileParser::GetSerializedProtoFromMessageType(
244     const grpc::string& message_type_name, const grpc::string& formatted_proto,
245     bool is_json_format) {
246   has_error_ = false;
247   grpc::string serialized;
248   const protobuf::Descriptor* desc =
249       desc_pool_->FindMessageTypeByName(message_type_name);
250   if (!desc) {
251     LogError("Message type not found");
252     return "";
253   }
254   std::unique_ptr<grpc::protobuf::Message> msg(
255       dynamic_factory_->GetPrototype(desc)->New());
256 
257   bool ok;
258   if (is_json_format) {
259     ok = grpc::protobuf::json::JsonStringToMessage(formatted_proto, msg.get())
260              .ok();
261     if (!ok) {
262       LogError("Failed to convert json format to proto.");
263       return "";
264     }
265   } else {
266     ok = protobuf::TextFormat::ParseFromString(formatted_proto, msg.get());
267     if (!ok) {
268       LogError("Failed to convert text format to proto.");
269       return "";
270     }
271   }
272 
273   ok = msg->SerializeToString(&serialized);
274   if (!ok) {
275     LogError("Failed to serialize proto.");
276     return "";
277   }
278   return serialized;
279 }
280 
GetFormattedStringFromMessageType(const grpc::string & message_type_name,const grpc::string & serialized_proto,bool is_json_format)281 grpc::string ProtoFileParser::GetFormattedStringFromMessageType(
282     const grpc::string& message_type_name, const grpc::string& serialized_proto,
283     bool is_json_format) {
284   has_error_ = false;
285   const protobuf::Descriptor* desc =
286       desc_pool_->FindMessageTypeByName(message_type_name);
287   if (!desc) {
288     LogError("Message type not found");
289     return "";
290   }
291   std::unique_ptr<grpc::protobuf::Message> msg(
292       dynamic_factory_->GetPrototype(desc)->New());
293   if (!msg->ParseFromString(serialized_proto)) {
294     LogError("Failed to deserialize proto.");
295     return "";
296   }
297   grpc::string formatted_string;
298 
299   if (is_json_format) {
300     grpc::protobuf::json::JsonPrintOptions jsonPrintOptions;
301     jsonPrintOptions.add_whitespace = true;
302     if (!grpc::protobuf::json::MessageToJsonString(
303              *msg.get(), &formatted_string, jsonPrintOptions)
304              .ok()) {
305       LogError("Failed to print proto message to json format");
306       return "";
307     }
308   } else {
309     if (!protobuf::TextFormat::PrintToString(*msg.get(), &formatted_string)) {
310       LogError("Failed to print proto message to text format");
311       return "";
312     }
313   }
314   return formatted_string;
315 }
316 
LogError(const grpc::string & error_msg)317 void ProtoFileParser::LogError(const grpc::string& error_msg) {
318   if (!error_msg.empty()) {
319     std::cerr << error_msg << std::endl;
320   }
321   has_error_ = true;
322 }
323 
324 }  // namespace testing
325 }  // namespace grpc
326