1 /*
2  * Licensed to the Apache Software Foundation (ASF) under one
3  * or more contributor license agreements. See the NOTICE file
4  * distributed with this work for additional information
5  * regarding copyright ownership. The ASF licenses this file
6  * to you under the Apache License, Version 2.0 (the
7  * "License"); you may not use this file except in compliance
8  * with the License. You may obtain a copy of the License at
9  *
10  *   http://www.apache.org/licenses/LICENSE-2.0
11  *
12  * Unless required by applicable law or agreed to in writing,
13  * software distributed under the License is distributed on an
14  * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
15  * KIND, either express or implied. See the License for the
16  * specific language governing permissions and limitations
17  * under the License.
18  */
19 
20 #ifndef _THRIFT_PROTOCOL_TJSONPROTOCOL_H_
21 #define _THRIFT_PROTOCOL_TJSONPROTOCOL_H_ 1
22 
23 #include <thrift/protocol/TVirtualProtocol.h>
24 
25 #include <stack>
26 
27 namespace apache {
28 namespace thrift {
29 namespace protocol {
30 
31 // Forward declaration
32 class TJSONContext;
33 
34 /**
35  * JSON protocol for Thrift.
36  *
37  * Implements a protocol which uses JSON as the wire-format.
38  *
39  * Thrift types are represented as described below:
40  *
41  * 1. Every Thrift integer type is represented as a JSON number.
42  *
43  * 2. Thrift doubles are represented as JSON numbers. Some special values are
44  *    represented as strings:
45  *    a. "NaN" for not-a-number values
46  *    b. "Infinity" for positive infinity
47  *    c. "-Infinity" for negative infinity
48  *
49  * 3. Thrift string values are emitted as JSON strings, with appropriate
50  *    escaping.
51  *
52  * 4. Thrift binary values are encoded into Base64 and emitted as JSON strings.
53  *    The readBinary() method is written such that it will properly skip if
54  *    called on a Thrift string (although it will decode garbage data).
55  *
56  *    NOTE: Base64 padding is optional for Thrift binary value encoding. So
57  *    the readBinary() method needs to decode both input strings with padding
58  *    and those without one.
59  *
60  * 5. Thrift structs are represented as JSON objects, with the field ID as the
61  *    key, and the field value represented as a JSON object with a single
62  *    key-value pair. The key is a short string identifier for that type,
63  *    followed by the value. The valid type identifiers are: "tf" for bool,
64  *    "i8" for byte, "i16" for 16-bit integer, "i32" for 32-bit integer, "i64"
65  *    for 64-bit integer, "dbl" for double-precision loating point, "str" for
66  *    string (including binary), "rec" for struct ("records"), "map" for map,
67  *    "lst" for list, "set" for set.
68  *
69  * 6. Thrift lists and sets are represented as JSON arrays, with the first
70  *    element of the JSON array being the string identifier for the Thrift
71  *    element type and the second element of the JSON array being the count of
72  *    the Thrift elements. The Thrift elements then follow.
73  *
74  * 7. Thrift maps are represented as JSON arrays, with the first two elements
75  *    of the JSON array being the string identifiers for the Thrift key type
76  *    and value type, followed by the count of the Thrift pairs, followed by a
77  *    JSON object containing the key-value pairs. Note that JSON keys can only
78  *    be strings, which means that the key type of the Thrift map should be
79  *    restricted to numeric or string types -- in the case of numerics, they
80  *    are serialized as strings.
81  *
82  * 8. Thrift messages are represented as JSON arrays, with the protocol
83  *    version #, the message name, the message type, and the sequence ID as
84  *    the first 4 elements.
85  *
86  * More discussion of the double handling is probably warranted. The aim of
87  * the current implementation is to match as closely as possible the behavior
88  * of Java's Double.toString(), which has no precision loss.  Implementors in
89  * other languages should strive to achieve that where possible. I have not
90  * yet verified whether std::istringstream::operator>>, which is doing that
91  * work for me in C++, loses any precision, but I am leaving this as a future
92  * improvement. I may try to provide a C component for this, so that other
93  * languages could bind to the same underlying implementation for maximum
94  * consistency.
95  *
96  */
97 class TJSONProtocol : public TVirtualProtocol<TJSONProtocol> {
98 public:
99   TJSONProtocol(std::shared_ptr<TTransport> ptrans);
100 
101   ~TJSONProtocol() override;
102 
103 private:
104   void pushContext(std::shared_ptr<TJSONContext> c);
105 
106   void popContext();
107 
108   uint32_t writeJSONEscapeChar(uint8_t ch);
109 
110   uint32_t writeJSONChar(uint8_t ch);
111 
112   uint32_t writeJSONString(const std::string& str);
113 
114   uint32_t writeJSONBase64(const std::string& str);
115 
116   template <typename NumberType>
117   uint32_t writeJSONInteger(NumberType num);
118 
119   uint32_t writeJSONDouble(double num);
120 
121   uint32_t writeJSONObjectStart();
122 
123   uint32_t writeJSONObjectEnd();
124 
125   uint32_t writeJSONArrayStart();
126 
127   uint32_t writeJSONArrayEnd();
128 
129   uint32_t readJSONSyntaxChar(uint8_t ch);
130 
131   uint32_t readJSONEscapeChar(uint16_t* out);
132 
133   uint32_t readJSONString(std::string& str, bool skipContext = false);
134 
135   uint32_t readJSONBase64(std::string& str);
136 
137   uint32_t readJSONNumericChars(std::string& str);
138 
139   template <typename NumberType>
140   uint32_t readJSONInteger(NumberType& num);
141 
142   uint32_t readJSONDouble(double& num);
143 
144   uint32_t readJSONObjectStart();
145 
146   uint32_t readJSONObjectEnd();
147 
148   uint32_t readJSONArrayStart();
149 
150   uint32_t readJSONArrayEnd();
151 
152 public:
153   /**
154    * Writing functions.
155    */
156 
157   uint32_t writeMessageBegin(const std::string& name,
158                              const TMessageType messageType,
159                              const int32_t seqid);
160 
161   uint32_t writeMessageEnd();
162 
163   uint32_t writeStructBegin(const char* name);
164 
165   uint32_t writeStructEnd();
166 
167   uint32_t writeFieldBegin(const char* name, const TType fieldType, const int16_t fieldId);
168 
169   uint32_t writeFieldEnd();
170 
171   uint32_t writeFieldStop();
172 
173   uint32_t writeMapBegin(const TType keyType, const TType valType, const uint32_t size);
174 
175   uint32_t writeMapEnd();
176 
177   uint32_t writeListBegin(const TType elemType, const uint32_t size);
178 
179   uint32_t writeListEnd();
180 
181   uint32_t writeSetBegin(const TType elemType, const uint32_t size);
182 
183   uint32_t writeSetEnd();
184 
185   uint32_t writeBool(const bool value);
186 
187   uint32_t writeByte(const int8_t byte);
188 
189   uint32_t writeI16(const int16_t i16);
190 
191   uint32_t writeI32(const int32_t i32);
192 
193   uint32_t writeI64(const int64_t i64);
194 
195   uint32_t writeDouble(const double dub);
196 
197   uint32_t writeString(const std::string& str);
198 
199   uint32_t writeBinary(const std::string& str);
200 
201   /**
202    * Reading functions
203    */
204 
205   uint32_t readMessageBegin(std::string& name, TMessageType& messageType, int32_t& seqid);
206 
207   uint32_t readMessageEnd();
208 
209   uint32_t readStructBegin(std::string& name);
210 
211   uint32_t readStructEnd();
212 
213   uint32_t readFieldBegin(std::string& name, TType& fieldType, int16_t& fieldId);
214 
215   uint32_t readFieldEnd();
216 
217   uint32_t readMapBegin(TType& keyType, TType& valType, uint32_t& size);
218 
219   uint32_t readMapEnd();
220 
221   uint32_t readListBegin(TType& elemType, uint32_t& size);
222 
223   uint32_t readListEnd();
224 
225   uint32_t readSetBegin(TType& elemType, uint32_t& size);
226 
227   uint32_t readSetEnd();
228 
229   uint32_t readBool(bool& value);
230 
231   // Provide the default readBool() implementation for std::vector<bool>
232   using TVirtualProtocol<TJSONProtocol>::readBool;
233 
234   uint32_t readByte(int8_t& byte);
235 
236   uint32_t readI16(int16_t& i16);
237 
238   uint32_t readI32(int32_t& i32);
239 
240   uint32_t readI64(int64_t& i64);
241 
242   uint32_t readDouble(double& dub);
243 
244   uint32_t readString(std::string& str);
245 
246   uint32_t readBinary(std::string& str);
247 
248   int getMinSerializedSize(TType type) override;
249 
checkReadBytesAvailable(TSet & set)250   void checkReadBytesAvailable(TSet& set) override
251   {
252       trans_->checkReadBytesAvailable(set.size_ * getMinSerializedSize(set.elemType_));
253   }
254 
checkReadBytesAvailable(TList & list)255   void checkReadBytesAvailable(TList& list) override
256   {
257       trans_->checkReadBytesAvailable(list.size_ * getMinSerializedSize(list.elemType_));
258   }
259 
checkReadBytesAvailable(TMap & map)260   void checkReadBytesAvailable(TMap& map) override
261   {
262       int elmSize = getMinSerializedSize(map.keyType_) + getMinSerializedSize(map.valueType_);
263       trans_->checkReadBytesAvailable(map.size_ * elmSize);
264   }
265 
266   class LookaheadReader {
267 
268   public:
LookaheadReader(TTransport & trans)269     LookaheadReader(TTransport& trans) : trans_(&trans), hasData_(false), data_(0) {}
270 
read()271     uint8_t read() {
272       if (hasData_) {
273         hasData_ = false;
274       } else {
275         trans_->readAll(&data_, 1);
276       }
277       return data_;
278     }
279 
peek()280     uint8_t peek() {
281       if (!hasData_) {
282         trans_->readAll(&data_, 1);
283       }
284       hasData_ = true;
285       return data_;
286     }
287 
288   private:
289     TTransport* trans_;
290     bool hasData_;
291     uint8_t data_;
292   };
293 
294 private:
295   TTransport* trans_;
296 
297   std::stack<std::shared_ptr<TJSONContext> > contexts_;
298   std::shared_ptr<TJSONContext> context_;
299   LookaheadReader reader_;
300 };
301 
302 /**
303  * Constructs input and output protocol objects given transports.
304  */
305 class TJSONProtocolFactory : public TProtocolFactory {
306 public:
307   TJSONProtocolFactory() = default;
308 
309   ~TJSONProtocolFactory() override = default;
310 
getProtocol(std::shared_ptr<TTransport> trans)311   std::shared_ptr<TProtocol> getProtocol(std::shared_ptr<TTransport> trans) override {
312     return std::shared_ptr<TProtocol>(new TJSONProtocol(trans));
313   }
314 };
315 }
316 }
317 } // apache::thrift::protocol
318 
319 // TODO(dreiss): Move part of ThriftJSONString into a .cpp file and remove this.
320 #include <thrift/transport/TBufferTransports.h>
321 
322 namespace apache {
323 namespace thrift {
324 
325 template <typename ThriftStruct>
ThriftJSONString(const ThriftStruct & ts)326 std::string ThriftJSONString(const ThriftStruct& ts) {
327   using namespace apache::thrift::transport;
328   using namespace apache::thrift::protocol;
329   auto* buffer = new TMemoryBuffer;
330   std::shared_ptr<TTransport> trans(buffer);
331   TJSONProtocol protocol(trans);
332 
333   ts.write(&protocol);
334 
335   uint8_t* buf;
336   uint32_t size;
337   buffer->getBuffer(&buf, &size);
338   return std::string((char*)buf, (unsigned int)size);
339 }
340 }
341 } // apache::thrift
342 
343 #endif // #define _THRIFT_PROTOCOL_TJSONPROTOCOL_H_ 1
344