1 // Protocol Buffers - Google's data interchange format
2 // Copyright 2008 Google Inc.  All rights reserved.
3 // https://developers.google.com/protocol-buffers/
4 //
5 // Redistribution and use in source and binary forms, with or without
6 // modification, are permitted provided that the following conditions are
7 // met:
8 //
9 //     * Redistributions of source code must retain the above copyright
10 // notice, this list of conditions and the following disclaimer.
11 //     * Redistributions in binary form must reproduce the above
12 // copyright notice, this list of conditions and the following disclaimer
13 // in the documentation and/or other materials provided with the
14 // distribution.
15 //     * Neither the name of Google Inc. nor the names of its
16 // contributors may be used to endorse or promote products derived from
17 // this software without specific prior written permission.
18 //
19 // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
20 // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
21 // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
22 // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
23 // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
24 // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
25 // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
26 // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
27 // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
28 // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
29 // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
30 
31 #ifndef GOOGLE_PROTOBUF_UTIL_CONVERTER_PROTOSTREAM_OBJECTSOURCE_H__
32 #define GOOGLE_PROTOBUF_UTIL_CONVERTER_PROTOSTREAM_OBJECTSOURCE_H__
33 
34 #include <functional>
35 #include <string>
36 #include <unordered_map>
37 
38 #include <google/protobuf/stubs/common.h>
39 #include <google/protobuf/type.pb.h>
40 #include <google/protobuf/util/internal/type_info.h>
41 #include <google/protobuf/util/internal/object_source.h>
42 #include <google/protobuf/util/internal/object_writer.h>
43 #include <google/protobuf/util/type_resolver.h>
44 #include <google/protobuf/stubs/strutil.h>
45 #include <google/protobuf/stubs/hash.h>
46 #include <google/protobuf/stubs/status.h>
47 #include <google/protobuf/stubs/statusor.h>
48 
49 
50 #include <google/protobuf/port_def.inc>
51 
52 namespace google {
53 namespace protobuf {
54 namespace util {
55 namespace converter {
56 
57 class TypeInfo;
58 
59 // An ObjectSource that can parse a stream of bytes as a protocol buffer.
60 // Its WriteTo() method can be given an ObjectWriter.
61 // This implementation uses a google.protobuf.Type for tag and name lookup.
62 // The field names are converted into lower camel-case when writing to the
63 // ObjectWriter.
64 //
65 // Sample usage: (suppose input is: string proto)
66 //   ArrayInputStream arr_stream(proto.data(), proto.size());
67 //   CodedInputStream in_stream(&arr_stream);
68 //   ProtoStreamObjectSource os(&in_stream, /*ServiceTypeInfo*/ typeinfo,
69 //                              <your message google::protobuf::Type>);
70 //
71 //   Status status = os.WriteTo(<some ObjectWriter>);
72 class PROTOBUF_EXPORT ProtoStreamObjectSource : public ObjectSource {
73  public:
74   ProtoStreamObjectSource(io::CodedInputStream* stream,
75                           TypeResolver* type_resolver,
76                           const google::protobuf::Type& type);
77 
78   ~ProtoStreamObjectSource() override;
79 
80   util::Status NamedWriteTo(StringPiece name,
81                               ObjectWriter* ow) const override;
82 
83   // Sets whether or not to use lowerCamelCase casing for enum values. If set to
84   // false, enum values are output without any case conversions.
85   //
86   // For example, if we have an enum:
87   // enum Type {
88   //   ACTION_AND_ADVENTURE = 1;
89   // }
90   // Type type = 20;
91   //
92   // And this option is set to true. Then the rendered "type" field will have
93   // the string "actionAndAdventure".
94   // {
95   //   ...
96   //   "type": "actionAndAdventure",
97   //   ...
98   // }
99   //
100   // If set to false, the rendered "type" field will have the string
101   // "ACTION_AND_ADVENTURE".
102   // {
103   //   ...
104   //   "type": "ACTION_AND_ADVENTURE",
105   //   ...
106   // }
set_use_lower_camel_for_enums(bool value)107   void set_use_lower_camel_for_enums(bool value) {
108     use_lower_camel_for_enums_ = value;
109   }
110 
111   // Sets whether to always output enums as ints, by default this is off, and
112   // enums are rendered as strings.
set_use_ints_for_enums(bool value)113   void set_use_ints_for_enums(bool value) { use_ints_for_enums_ = value; }
114 
115   // Sets whether to use original proto field names
set_preserve_proto_field_names(bool value)116   void set_preserve_proto_field_names(bool value) {
117     preserve_proto_field_names_ = value;
118   }
119 
120   // Sets the max recursion depth of proto message to be deserialized. Proto
121   // messages over this depth will fail to be deserialized.
122   // Default value is 64.
set_max_recursion_depth(int max_depth)123   void set_max_recursion_depth(int max_depth) {
124     max_recursion_depth_ = max_depth;
125   }
126 
127 
128  protected:
129   // Writes a proto2 Message to the ObjectWriter. When the given end_tag is
130   // found this method will complete, allowing it to be used for parsing both
131   // nested messages (end with 0) and nested groups (end with group end tag).
132   // The include_start_and_end parameter allows this method to be called when
133   // already inside of an object, and skip calling StartObject and EndObject.
134   virtual util::Status WriteMessage(const google::protobuf::Type& descriptor,
135                                       StringPiece name,
136                                       const uint32 end_tag,
137                                       bool include_start_and_end,
138                                       ObjectWriter* ow) const;
139 
140   // Renders a repeating field (packed or unpacked).  Returns the next tag after
141   // reading all sequential repeating elements. The caller should use this tag
142   // before reading more tags from the stream.
143   virtual util::StatusOr<uint32> RenderList(
144       const google::protobuf::Field* field, StringPiece name,
145       uint32 list_tag, ObjectWriter* ow) const;
146 
147   // Looks up a field and verify its consistency with wire type in tag.
148   const google::protobuf::Field* FindAndVerifyField(
149       const google::protobuf::Type& type, uint32 tag) const;
150 
151   // Renders a field value to the ObjectWriter.
152   virtual util::Status RenderField(const google::protobuf::Field* field,
153                                      StringPiece field_name,
154                                      ObjectWriter* ow) const;
155 
156   // Reads field value according to Field spec in 'field' and returns the read
157   // value as string. This only works for primitive datatypes (no message
158   // types).
159   const std::string ReadFieldValueAsString(
160       const google::protobuf::Field& field) const;
161 
162 
163  private:
164   ProtoStreamObjectSource(io::CodedInputStream* stream,
165                           const TypeInfo* typeinfo,
166                           const google::protobuf::Type& type);
167   // Function that renders a well known type with a modified behavior.
168   typedef util::Status (*TypeRenderer)(const ProtoStreamObjectSource*,
169                                          const google::protobuf::Type&,
170                                          StringPiece, ObjectWriter*);
171 
172   // TODO(skarvaje): Mark these methods as non-const as they modify internal
173   // state (stream_).
174   //
175   // Renders a NWP map.
176   // Returns the next tag after reading all map entries. The caller should use
177   // this tag before reading more tags from the stream.
178   util::StatusOr<uint32> RenderMap(const google::protobuf::Field* field,
179                                      StringPiece name, uint32 list_tag,
180                                      ObjectWriter* ow) const;
181 
182   // Renders a packed repeating field. A packed field is stored as:
183   // {tag length item1 item2 item3} instead of the less efficient
184   // {tag item1 tag item2 tag item3}.
185   util::Status RenderPacked(const google::protobuf::Field* field,
186                               ObjectWriter* ow) const;
187 
188   // Renders a google.protobuf.Timestamp value to ObjectWriter
189   static util::Status RenderTimestamp(const ProtoStreamObjectSource* os,
190                                         const google::protobuf::Type& type,
191                                         StringPiece name,
192                                         ObjectWriter* ow);
193 
194   // Renders a google.protobuf.Duration value to ObjectWriter
195   static util::Status RenderDuration(const ProtoStreamObjectSource* os,
196                                        const google::protobuf::Type& type,
197                                        StringPiece name,
198                                        ObjectWriter* ow);
199 
200   // Following RenderTYPE functions render well known types in
201   // google/protobuf/wrappers.proto corresponding to TYPE.
202   static util::Status RenderDouble(const ProtoStreamObjectSource* os,
203                                      const google::protobuf::Type& type,
204                                      StringPiece name, ObjectWriter* ow);
205   static util::Status RenderFloat(const ProtoStreamObjectSource* os,
206                                     const google::protobuf::Type& type,
207                                     StringPiece name, ObjectWriter* ow);
208   static util::Status RenderInt64(const ProtoStreamObjectSource* os,
209                                     const google::protobuf::Type& type,
210                                     StringPiece name, ObjectWriter* ow);
211   static util::Status RenderUInt64(const ProtoStreamObjectSource* os,
212                                      const google::protobuf::Type& type,
213                                      StringPiece name, ObjectWriter* ow);
214   static util::Status RenderInt32(const ProtoStreamObjectSource* os,
215                                     const google::protobuf::Type& type,
216                                     StringPiece name, ObjectWriter* ow);
217   static util::Status RenderUInt32(const ProtoStreamObjectSource* os,
218                                      const google::protobuf::Type& type,
219                                      StringPiece name, ObjectWriter* ow);
220   static util::Status RenderBool(const ProtoStreamObjectSource* os,
221                                    const google::protobuf::Type& type,
222                                    StringPiece name, ObjectWriter* ow);
223   static util::Status RenderString(const ProtoStreamObjectSource* os,
224                                      const google::protobuf::Type& type,
225                                      StringPiece name, ObjectWriter* ow);
226   static util::Status RenderBytes(const ProtoStreamObjectSource* os,
227                                     const google::protobuf::Type& type,
228                                     StringPiece name, ObjectWriter* ow);
229 
230   // Renders a google.protobuf.Struct to ObjectWriter.
231   static util::Status RenderStruct(const ProtoStreamObjectSource* os,
232                                      const google::protobuf::Type& type,
233                                      StringPiece name, ObjectWriter* ow);
234 
235   // Helper to render google.protobuf.Struct's Value fields to ObjectWriter.
236   static util::Status RenderStructValue(const ProtoStreamObjectSource* os,
237                                           const google::protobuf::Type& type,
238                                           StringPiece name,
239                                           ObjectWriter* ow);
240 
241   // Helper to render google.protobuf.Struct's ListValue fields to ObjectWriter.
242   static util::Status RenderStructListValue(
243       const ProtoStreamObjectSource* os, const google::protobuf::Type& type,
244       StringPiece name, ObjectWriter* ow);
245 
246   // Render the "Any" type.
247   static util::Status RenderAny(const ProtoStreamObjectSource* os,
248                                   const google::protobuf::Type& type,
249                                   StringPiece name, ObjectWriter* ow);
250 
251   // Render the "FieldMask" type.
252   static util::Status RenderFieldMask(const ProtoStreamObjectSource* os,
253                                         const google::protobuf::Type& type,
254                                         StringPiece name,
255                                         ObjectWriter* ow);
256 
257   static std::unordered_map<std::string, TypeRenderer>* renderers_;
258   static void InitRendererMap();
259   static void DeleteRendererMap();
260   static TypeRenderer* FindTypeRenderer(const std::string& type_url);
261 
262   // Same as above but renders all non-message field types. Callers don't call
263   // this function directly. They just use RenderField.
264   util::Status RenderNonMessageField(const google::protobuf::Field* field,
265                                        StringPiece field_name,
266                                        ObjectWriter* ow) const;
267 
268 
269   // Utility function to detect proto maps. The 'field' MUST be repeated.
270   bool IsMap(const google::protobuf::Field& field) const;
271 
272   // Utility to read int64 and int32 values from a message type in stream_.
273   // Used for reading google.protobuf.Timestamp and Duration messages.
274   std::pair<int64, int32> ReadSecondsAndNanos(
275       const google::protobuf::Type& type) const;
276 
277   // Helper function to check recursion depth and increment it. It will return
278   // Status::OK if the current depth is allowed. Otherwise an error is returned.
279   // type_name and field_name are used for error reporting.
280   util::Status IncrementRecursionDepth(StringPiece type_name,
281                                          StringPiece field_name) const;
282 
283   // Input stream to read from. Ownership rests with the caller.
284   io::CodedInputStream* stream_;
285 
286   // Type information for all the types used in the descriptor. Used to find
287   // google::protobuf::Type of nested messages/enums.
288   const TypeInfo* typeinfo_;
289 
290   // Whether this class owns the typeinfo_ object. If true the typeinfo_ object
291   // should be deleted in the destructor.
292   bool own_typeinfo_;
293 
294   // google::protobuf::Type of the message source.
295   const google::protobuf::Type& type_;
296 
297 
298   // Whether to render enums using lowerCamelCase. Defaults to false.
299   bool use_lower_camel_for_enums_;
300 
301   // Whether to render enums as ints always. Defaults to false.
302   bool use_ints_for_enums_;
303 
304   // Whether to preserve proto field names
305   bool preserve_proto_field_names_;
306 
307   // Tracks current recursion depth.
308   mutable int recursion_depth_;
309 
310   // Maximum allowed recursion depth.
311   int max_recursion_depth_;
312 
313   // Whether to render unknown fields.
314   bool render_unknown_fields_;
315 
316   // Whether to render unknown enum values.
317   bool render_unknown_enum_values_;
318 
319   // Whether to add trailing zeros for timestamp and duration.
320   bool add_trailing_zeros_for_timestamp_and_duration_;
321 
322   // Whether output the empty object or not. If false, output JSON string like:
323   // "'objectName' : {}". If true, then no outputs. This only happens when all
324   // the fields of the message are filtered out by field mask.
325   bool suppress_empty_object_;
326 
327   bool use_legacy_json_map_format_;
328 
329   GOOGLE_DISALLOW_IMPLICIT_CONSTRUCTORS(ProtoStreamObjectSource);
330 };
331 
332 }  // namespace converter
333 }  // namespace util
334 }  // namespace protobuf
335 }  // namespace google
336 
337 #include <google/protobuf/port_undef.inc>
338 
339 #endif  // GOOGLE_PROTOBUF_UTIL_CONVERTER_PROTOSTREAM_OBJECTSOURCE_H__
340