• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
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/stringpiece.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 
189   // Renders a google.protobuf.Timestamp value to ObjectWriter
190   static util::Status RenderTimestamp(const ProtoStreamObjectSource* os,
191                                         const google::protobuf::Type& type,
192                                         StringPiece name,
193                                         ObjectWriter* ow);
194 
195   // Renders a google.protobuf.Duration value to ObjectWriter
196   static util::Status RenderDuration(const ProtoStreamObjectSource* os,
197                                        const google::protobuf::Type& type,
198                                        StringPiece name,
199                                        ObjectWriter* ow);
200 
201   // Following RenderTYPE functions render well known types in
202   // google/protobuf/wrappers.proto corresponding to TYPE.
203   static util::Status RenderDouble(const ProtoStreamObjectSource* os,
204                                      const google::protobuf::Type& type,
205                                      StringPiece name, ObjectWriter* ow);
206   static util::Status RenderFloat(const ProtoStreamObjectSource* os,
207                                     const google::protobuf::Type& type,
208                                     StringPiece name, ObjectWriter* ow);
209   static util::Status RenderInt64(const ProtoStreamObjectSource* os,
210                                     const google::protobuf::Type& type,
211                                     StringPiece name, ObjectWriter* ow);
212   static util::Status RenderUInt64(const ProtoStreamObjectSource* os,
213                                      const google::protobuf::Type& type,
214                                      StringPiece name, ObjectWriter* ow);
215   static util::Status RenderInt32(const ProtoStreamObjectSource* os,
216                                     const google::protobuf::Type& type,
217                                     StringPiece name, ObjectWriter* ow);
218   static util::Status RenderUInt32(const ProtoStreamObjectSource* os,
219                                      const google::protobuf::Type& type,
220                                      StringPiece name, ObjectWriter* ow);
221   static util::Status RenderBool(const ProtoStreamObjectSource* os,
222                                    const google::protobuf::Type& type,
223                                    StringPiece name, ObjectWriter* ow);
224   static util::Status RenderString(const ProtoStreamObjectSource* os,
225                                      const google::protobuf::Type& type,
226                                      StringPiece name, ObjectWriter* ow);
227   static util::Status RenderBytes(const ProtoStreamObjectSource* os,
228                                     const google::protobuf::Type& type,
229                                     StringPiece name, ObjectWriter* ow);
230 
231   // Renders a google.protobuf.Struct to ObjectWriter.
232   static util::Status RenderStruct(const ProtoStreamObjectSource* os,
233                                      const google::protobuf::Type& type,
234                                      StringPiece name, ObjectWriter* ow);
235 
236   // Helper to render google.protobuf.Struct's Value fields to ObjectWriter.
237   static util::Status RenderStructValue(const ProtoStreamObjectSource* os,
238                                           const google::protobuf::Type& type,
239                                           StringPiece name,
240                                           ObjectWriter* ow);
241 
242   // Helper to render google.protobuf.Struct's ListValue fields to ObjectWriter.
243   static util::Status RenderStructListValue(
244       const ProtoStreamObjectSource* os, const google::protobuf::Type& type,
245       StringPiece name, ObjectWriter* ow);
246 
247   // Render the "Any" type.
248   static util::Status RenderAny(const ProtoStreamObjectSource* os,
249                                   const google::protobuf::Type& type,
250                                   StringPiece name, ObjectWriter* ow);
251 
252   // Render the "FieldMask" type.
253   static util::Status RenderFieldMask(const ProtoStreamObjectSource* os,
254                                         const google::protobuf::Type& type,
255                                         StringPiece name,
256                                         ObjectWriter* ow);
257 
258   static std::unordered_map<std::string, TypeRenderer>* renderers_;
259   static void InitRendererMap();
260   static void DeleteRendererMap();
261   static TypeRenderer* FindTypeRenderer(const std::string& type_url);
262 
263   // Same as above but renders all non-message field types. Callers don't call
264   // this function directly. They just use RenderField.
265   util::Status RenderNonMessageField(const google::protobuf::Field* field,
266                                        StringPiece field_name,
267                                        ObjectWriter* ow) const;
268 
269 
270   // Utility function to detect proto maps. The 'field' MUST be repeated.
271   bool IsMap(const google::protobuf::Field& field) const;
272 
273   // Utility to read int64 and int32 values from a message type in stream_.
274   // Used for reading google.protobuf.Timestamp and Duration messages.
275   std::pair<int64, int32> ReadSecondsAndNanos(
276       const google::protobuf::Type& type) const;
277 
278   // Helper function to check recursion depth and increment it. It will return
279   // Status::OK if the current depth is allowed. Otherwise an error is returned.
280   // type_name and field_name are used for error reporting.
281   util::Status IncrementRecursionDepth(StringPiece type_name,
282                                          StringPiece field_name) const;
283 
284   // Input stream to read from. Ownership rests with the caller.
285   io::CodedInputStream* stream_;
286 
287   // Type information for all the types used in the descriptor. Used to find
288   // google::protobuf::Type of nested messages/enums.
289   const TypeInfo* typeinfo_;
290 
291   // Whether this class owns the typeinfo_ object. If true the typeinfo_ object
292   // should be deleted in the destructor.
293   bool own_typeinfo_;
294 
295   // google::protobuf::Type of the message source.
296   const google::protobuf::Type& type_;
297 
298 
299   // Whether to render enums using lowerCamelCase. Defaults to false.
300   bool use_lower_camel_for_enums_;
301 
302   // Whether to render enums as ints always. Defaults to false.
303   bool use_ints_for_enums_;
304 
305   // Whether to preserve proto field names
306   bool preserve_proto_field_names_;
307 
308   // Tracks current recursion depth.
309   mutable int recursion_depth_;
310 
311   // Maximum allowed recursion depth.
312   int max_recursion_depth_;
313 
314   // Whether to render unknown fields.
315   bool render_unknown_fields_;
316 
317   // Whether to render unknown enum values.
318   bool render_unknown_enum_values_;
319 
320   // Whether to add trailing zeros for timestamp and duration.
321   bool add_trailing_zeros_for_timestamp_and_duration_;
322 
323   // Whether output the empty object or not. If false, output JSON string like:
324   // "'objectName' : {}". If true, then no outputs. This only happens when all
325   // the fields of the message are filtered out by field mask.
326   bool suppress_empty_object_;
327 
328   GOOGLE_DISALLOW_IMPLICIT_CONSTRUCTORS(ProtoStreamObjectSource);
329 };
330 
331 }  // namespace converter
332 }  // namespace util
333 }  // namespace protobuf
334 }  // namespace google
335 
336 #include <google/protobuf/port_undef.inc>
337 
338 #endif  // GOOGLE_PROTOBUF_UTIL_CONVERTER_PROTOSTREAM_OBJECTSOURCE_H__
339