folly json bug fix: overflow for -1LL<<63
[folly.git] / folly / json.cpp
1 /*
2  * Copyright 2014 Facebook, Inc.
3  *
4  * Licensed under the Apache License, Version 2.0 (the "License");
5  * you may not use this file except in compliance with the License.
6  * You may obtain a copy of the License at
7  *
8  *   http://www.apache.org/licenses/LICENSE-2.0
9  *
10  * Unless required by applicable law or agreed to in writing, software
11  * distributed under the License is distributed on an "AS IS" BASIS,
12  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13  * See the License for the specific language governing permissions and
14  * limitations under the License.
15  */
16
17 #include "folly/json.h"
18 #include <cassert>
19 #include <boost/next_prior.hpp>
20 #include <boost/algorithm/string.hpp>
21
22 #include "folly/Range.h"
23 #include "folly/Unicode.h"
24 #include "folly/Conv.h"
25
26 namespace folly {
27
28 //////////////////////////////////////////////////////////////////////
29
30 namespace json {
31 namespace {
32
33 char32_t decodeUtf8(
34     const unsigned char*& p,
35     const unsigned char* const e,
36     bool skipOnError) {
37   /* The following encodings are valid, except for the 5 and 6 byte
38    * combinations:
39    * 0xxxxxxx
40    * 110xxxxx 10xxxxxx
41    * 1110xxxx 10xxxxxx 10xxxxxx
42    * 11110xxx 10xxxxxx 10xxxxxx 10xxxxxx
43    * 111110xx 10xxxxxx 10xxxxxx 10xxxxxx 10xxxxxx
44    * 1111110x 10xxxxxx 10xxxxxx 10xxxxxx 10xxxxxx 10xxxxxx
45    */
46
47   auto skip = [&] { ++p; return U'\ufffd'; };
48
49   if (p >= e) {
50     if (skipOnError) return skip();
51     throw std::runtime_error("folly::decodeUtf8 empty/invalid string");
52   }
53
54   unsigned char fst = *p;
55   if (!(fst & 0x80)) {
56     // trivial case
57     return *p++;
58   }
59
60   static const uint32_t bitMask[] = {
61     (1 << 7) - 1,
62     (1 << 11) - 1,
63     (1 << 16) - 1,
64     (1 << 21) - 1
65   };
66
67   // upper control bits are masked out later
68   uint32_t d = fst;
69
70   if ((fst & 0xC0) != 0xC0) {
71     if (skipOnError) return skip();
72     throw std::runtime_error(to<std::string>("folly::decodeUtf8 i=0 d=", d));
73   }
74
75   fst <<= 1;
76
77   for (unsigned int i = 1; i != 3 && p + i < e; ++i) {
78     unsigned char tmp = p[i];
79
80     if ((tmp & 0xC0) != 0x80) {
81       if (skipOnError) return skip();
82       throw std::runtime_error(
83         to<std::string>("folly::decodeUtf8 i=", i, " tmp=", (uint32_t)tmp));
84     }
85
86     d = (d << 6) | (tmp & 0x3F);
87     fst <<= 1;
88
89     if (!(fst & 0x80)) {
90       d &= bitMask[i];
91
92       // overlong, could have been encoded with i bytes
93       if ((d & ~bitMask[i - 1]) == 0) {
94         if (skipOnError) return skip();
95         throw std::runtime_error(
96           to<std::string>("folly::decodeUtf8 i=", i, " d=", d));
97       }
98
99       // check for surrogates only needed for 3 bytes
100       if (i == 2) {
101         if ((d >= 0xD800 && d <= 0xDFFF) || d > 0x10FFFF) {
102           if (skipOnError) return skip();
103           throw std::runtime_error(
104             to<std::string>("folly::decodeUtf8 i=", i, " d=", d));
105         }
106       }
107
108       p += i + 1;
109       return d;
110     }
111   }
112
113   if (skipOnError) return skip();
114   throw std::runtime_error("folly::decodeUtf8 encoding length maxed out");
115 }
116
117 struct Printer {
118   explicit Printer(fbstring& out,
119                    unsigned* indentLevel,
120                    serialization_opts const* opts)
121     : out_(out)
122     , indentLevel_(indentLevel)
123     , opts_(*opts)
124   {}
125
126   void operator()(dynamic const& v) const {
127     switch (v.type()) {
128     case dynamic::DOUBLE:
129       toAppend(v.asDouble(), &out_);
130       break;
131     case dynamic::INT64: {
132       auto intval = v.asInt();
133       if (opts_.javascript_safe) {
134         // Use folly::to to check that this integer can be represented
135         // as a double without loss of precision.
136         intval = int64_t(to<double>(intval));
137       }
138       toAppend(intval, &out_);
139       break;
140     }
141     case dynamic::BOOL:
142       out_ += v.asBool() ? "true" : "false";
143       break;
144     case dynamic::NULLT:
145       out_ += "null";
146       break;
147     case dynamic::STRING:
148       escapeString(v.asString(), out_, opts_);
149       break;
150     case dynamic::OBJECT:
151       printObject(v);
152       break;
153     case dynamic::ARRAY:
154       printArray(v);
155       break;
156     default:
157       CHECK(0) << "Bad type " << v.type();
158     }
159   }
160
161 private:
162   void printKV(const std::pair<const dynamic, dynamic>& p) const {
163     if (!opts_.allow_non_string_keys && !p.first.isString()) {
164       throw std::runtime_error("folly::toJson: JSON object key was not a "
165         "string");
166     }
167     (*this)(p.first);
168     mapColon();
169     (*this)(p.second);
170   }
171
172   template <typename Iterator>
173   void printKVPairs(Iterator begin, Iterator end) const {
174     printKV(*begin);
175     for (++begin; begin != end; ++begin) {
176       out_ += ',';
177       newline();
178       printKV(*begin);
179     }
180   }
181
182   void printObject(dynamic const& o) const {
183     if (o.empty()) {
184       out_ += "{}";
185       return;
186     }
187
188     out_ += '{';
189     indent();
190     newline();
191     if (opts_.sort_keys) {
192       std::vector<std::pair<dynamic, dynamic>> items(
193         o.items().begin(), o.items().end());
194       std::sort(items.begin(), items.end());
195       printKVPairs(items.begin(), items.end());
196     } else {
197       printKVPairs(o.items().begin(), o.items().end());
198     }
199     outdent();
200     newline();
201     out_ += '}';
202   }
203
204   void printArray(dynamic const& a) const {
205     if (a.empty()) {
206       out_ += "[]";
207       return;
208     }
209
210     out_ += '[';
211     indent();
212     newline();
213     (*this)(a[0]);
214     for (auto& val : makeRange(boost::next(a.begin()), a.end())) {
215       out_ += ',';
216       newline();
217       (*this)(val);
218     }
219     outdent();
220     newline();
221     out_ += ']';
222   }
223
224 private:
225   void outdent() const {
226     if (indentLevel_) {
227       --*indentLevel_;
228     }
229   }
230
231   void indent() const {
232     if (indentLevel_) {
233       ++*indentLevel_;
234     }
235   }
236
237   void newline() const {
238     if (indentLevel_) {
239       out_ += to<fbstring>('\n', fbstring(*indentLevel_ * 2, ' '));
240     }
241   }
242
243   void mapColon() const {
244     out_ += indentLevel_ ? " : " : ":";
245   }
246
247 private:
248   fbstring& out_;
249   unsigned* const indentLevel_;
250   serialization_opts const& opts_;
251 };
252
253 //////////////////////////////////////////////////////////////////////
254
255 struct ParseError : std::runtime_error {
256   explicit ParseError(int line)
257     : std::runtime_error(to<std::string>("json parse error on line ", line))
258   {}
259
260   explicit ParseError(int line, std::string const& context,
261       std::string const& expected)
262     : std::runtime_error(to<std::string>("json parse error on line ", line,
263         !context.empty() ? to<std::string>(" near `", context, '\'')
264                         : "",
265         ": ", expected))
266   {}
267
268   explicit ParseError(std::string const& what)
269     : std::runtime_error("json parse error: " + what)
270   {}
271 };
272
273 // Wraps our input buffer with some helper functions.
274 struct Input {
275   explicit Input(StringPiece range, json::serialization_opts const* opts)
276       : range_(range)
277       , opts_(*opts)
278       , lineNum_(0)
279   {
280     storeCurrent();
281   }
282
283   Input(Input const&) = delete;
284   Input& operator=(Input const&) = delete;
285
286   char const* begin() const { return range_.begin(); }
287
288   // Parse ahead for as long as the supplied predicate is satisfied,
289   // returning a range of what was skipped.
290   template<class Predicate>
291   StringPiece skipWhile(const Predicate& p) {
292     std::size_t skipped = 0;
293     for (; skipped < range_.size(); ++skipped) {
294       if (!p(range_[skipped])) {
295         break;
296       }
297       if (range_[skipped] == '\n') {
298         ++lineNum_;
299       }
300     }
301     auto ret = range_.subpiece(0, skipped);
302     range_.advance(skipped);
303     storeCurrent();
304     return ret;
305   }
306
307   StringPiece skipDigits() {
308     return skipWhile([] (char c) { return c >= '0' && c <= '9'; });
309   }
310
311   StringPiece skipMinusAndDigits() {
312     bool firstChar = true;
313     return skipWhile([&firstChar] (char c) {
314         bool result = (c >= '0' && c <= '9') || (firstChar && c == '-');
315         firstChar = false;
316         return result;
317       });
318   }
319
320   void skipWhitespace() {
321     // Spaces other than ' ' characters are less common but should be
322     // checked.  This configuration where we loop on the ' '
323     // separately from oddspaces was empirically fastest.
324     auto oddspace = [] (char c) {
325       return c == '\n' || c == '\t' || c == '\r';
326     };
327
328   loop:
329     for (; !range_.empty() && range_.front() == ' '; range_.pop_front()) {
330     }
331     if (!range_.empty() && oddspace(range_.front())) {
332       range_.pop_front();
333       goto loop;
334     }
335     storeCurrent();
336   }
337
338   void expect(char c) {
339     if (**this != c) {
340       throw ParseError(lineNum_, context(),
341         to<std::string>("expected '", c, '\''));
342     }
343     ++*this;
344   }
345
346   std::size_t size() const {
347     return range_.size();
348   }
349
350   int operator*() const {
351     return current_;
352   }
353
354   void operator++() {
355     range_.pop_front();
356     storeCurrent();
357   }
358
359   template<class T>
360   T extract() {
361     try {
362       return to<T>(&range_);
363     } catch (std::exception const& e) {
364       error(e.what());
365     }
366   }
367
368   bool consume(StringPiece str) {
369     if (boost::starts_with(range_, str)) {
370       range_.advance(str.size());
371       storeCurrent();
372       return true;
373     }
374     return false;
375   }
376
377   std::string context() const {
378     return range_.subpiece(0, 16 /* arbitrary */).toString();
379   }
380
381   dynamic error(char const* what) const {
382     throw ParseError(lineNum_, context(), what);
383   }
384
385   json::serialization_opts const& getOpts() {
386     return opts_;
387   }
388
389 private:
390   void storeCurrent() {
391     current_ = range_.empty() ? EOF : range_.front();
392   }
393
394 private:
395   StringPiece range_;
396   json::serialization_opts const& opts_;
397   unsigned lineNum_;
398   int current_;
399 };
400
401 dynamic parseValue(Input& in);
402 fbstring parseString(Input& in);
403 dynamic parseNumber(Input& in);
404
405 dynamic parseObject(Input& in) {
406   assert(*in == '{');
407   ++in;
408
409   dynamic ret = dynamic::object;
410
411   in.skipWhitespace();
412   if (*in == '}') {
413     ++in;
414     return ret;
415   }
416
417   for (;;) {
418     if (in.getOpts().allow_trailing_comma && *in == '}') {
419       break;
420     }
421     if (*in == '\"') { // string
422       auto key = parseString(in);
423       in.skipWhitespace();
424       in.expect(':');
425       in.skipWhitespace();
426       ret.insert(std::move(key), parseValue(in));
427     } else if (!in.getOpts().allow_non_string_keys) {
428       in.error("expected string for object key name");
429     } else {
430       auto key = parseValue(in);
431       in.skipWhitespace();
432       in.expect(':');
433       in.skipWhitespace();
434       ret.insert(std::move(key), parseValue(in));
435     }
436
437     in.skipWhitespace();
438     if (*in != ',') {
439       break;
440     }
441     ++in;
442     in.skipWhitespace();
443   }
444   in.expect('}');
445
446   return ret;
447 }
448
449 dynamic parseArray(Input& in) {
450   assert(*in == '[');
451   ++in;
452
453   dynamic ret = {};
454
455   in.skipWhitespace();
456   if (*in == ']') {
457     ++in;
458     return ret;
459   }
460
461   for (;;) {
462     if (in.getOpts().allow_trailing_comma && *in == ']') {
463       break;
464     }
465     ret.push_back(parseValue(in));
466     in.skipWhitespace();
467     if (*in != ',') {
468       break;
469     }
470     ++in;
471     in.skipWhitespace();
472   }
473   in.expect(']');
474
475   return ret;
476 }
477
478 dynamic parseNumber(Input& in) {
479   bool const negative = (*in == '-');
480   if (negative) {
481     if (in.consume("-Infinity")) {
482       return -std::numeric_limits<double>::infinity();
483     }
484   }
485
486   auto integral = in.skipMinusAndDigits();
487   if (negative && integral.size() < 2) {
488     in.error("expected digits after `-'");
489   }
490
491   auto const wasE = *in == 'e' || *in == 'E';
492   if (*in != '.' && !wasE) {
493     auto val = to<int64_t>(integral);
494     in.skipWhitespace();
495     return val;
496   }
497
498   auto end = !wasE ? (++in, in.skipDigits().end()) : in.begin();
499   if (*in == 'e' || *in == 'E') {
500     ++in;
501     if (*in == '+' || *in == '-') {
502       ++in;
503     }
504     auto expPart = in.skipDigits();
505     end = expPart.end();
506   }
507   auto fullNum = makeRange(integral.begin(), end);
508
509   auto val = to<double>(fullNum);
510   return val;
511 }
512
513 fbstring decodeUnicodeEscape(Input& in) {
514   auto hexVal = [&] (char c) -> unsigned {
515     return c >= '0' && c <= '9' ? c - '0' :
516            c >= 'a' && c <= 'f' ? c - 'a' + 10 :
517            c >= 'A' && c <= 'F' ? c - 'A' + 10 :
518            (in.error("invalid hex digit"), 0);
519   };
520
521   auto readHex = [&]() -> uint16_t {
522     if (in.size() < 4) {
523       in.error("expected 4 hex digits");
524     }
525
526     uint16_t ret = hexVal(*in) * 4096;
527     ++in;
528     ret += hexVal(*in) * 256;
529     ++in;
530     ret += hexVal(*in) * 16;
531     ++in;
532     ret += hexVal(*in);
533     ++in;
534     return ret;
535   };
536
537   /*
538    * If the value encoded is in the surrogate pair range, we need to
539    * make sure there is another escape that we can use also.
540    */
541   uint32_t codePoint = readHex();
542   if (codePoint >= 0xd800 && codePoint <= 0xdbff) {
543     if (!in.consume("\\u")) {
544       in.error("expected another unicode escape for second half of "
545         "surrogate pair");
546     }
547     uint16_t second = readHex();
548     if (second >= 0xdc00 && second <= 0xdfff) {
549       codePoint = 0x10000 + ((codePoint & 0x3ff) << 10) +
550                   (second & 0x3ff);
551     } else {
552       in.error("second character in surrogate pair is invalid");
553     }
554   } else if (codePoint >= 0xdc00 && codePoint <= 0xdfff) {
555     in.error("invalid unicode code point (in range [0xdc00,0xdfff])");
556   }
557
558   return codePointToUtf8(codePoint);
559 }
560
561 fbstring parseString(Input& in) {
562   assert(*in == '\"');
563   ++in;
564
565   fbstring ret;
566   for (;;) {
567     auto range = in.skipWhile(
568       [] (char c) { return c != '\"' && c != '\\'; }
569     );
570     ret.append(range.begin(), range.end());
571
572     if (*in == '\"') {
573       ++in;
574       break;
575     }
576     if (*in == '\\') {
577       ++in;
578       switch (*in) {
579       case '\"':    ret.push_back('\"'); ++in; break;
580       case '\\':    ret.push_back('\\'); ++in; break;
581       case '/':     ret.push_back('/');  ++in; break;
582       case 'b':     ret.push_back('\b'); ++in; break;
583       case 'f':     ret.push_back('\f'); ++in; break;
584       case 'n':     ret.push_back('\n'); ++in; break;
585       case 'r':     ret.push_back('\r'); ++in; break;
586       case 't':     ret.push_back('\t'); ++in; break;
587       case 'u':     ++in; ret += decodeUnicodeEscape(in); break;
588       default:      in.error(to<fbstring>("unknown escape ", *in,
589                                           " in string").c_str());
590       }
591       continue;
592     }
593     if (*in == EOF) {
594       in.error("unterminated string");
595     }
596     if (!*in) {
597       /*
598        * Apparently we're actually supposed to ban all control
599        * characters from strings.  This seems unnecessarily
600        * restrictive, so we're only banning zero bytes.  (Since the
601        * string is presumed to be UTF-8 encoded it's fine to just
602        * check this way.)
603        */
604       in.error("null byte in string");
605     }
606
607     ret.push_back(*in);
608     ++in;
609   }
610
611   return ret;
612 }
613
614 dynamic parseValue(Input& in) {
615   in.skipWhitespace();
616   return *in == '[' ? parseArray(in) :
617          *in == '{' ? parseObject(in) :
618          *in == '\"' ? parseString(in) :
619          (*in == '-' || (*in >= '0' && *in <= '9')) ? parseNumber(in) :
620          in.consume("true") ? true :
621          in.consume("false") ? false :
622          in.consume("null") ? nullptr :
623          in.consume("Infinity") ? std::numeric_limits<double>::infinity() :
624          in.consume("NaN") ? std::numeric_limits<double>::quiet_NaN() :
625          in.error("expected json value");
626 }
627
628 }
629
630 //////////////////////////////////////////////////////////////////////
631
632 fbstring serialize(dynamic const& dyn, serialization_opts const& opts) {
633   fbstring ret;
634   unsigned indentLevel = 0;
635   Printer p(ret, opts.pretty_formatting ? &indentLevel : nullptr, &opts);
636   p(dyn);
637   return ret;
638 }
639
640 // Escape a string so that it is legal to print it in JSON text.
641 void escapeString(StringPiece input,
642                   fbstring& out,
643                   const serialization_opts& opts) {
644   auto hexDigit = [] (int c) -> char {
645     return c < 10 ? c + '0' : c - 10 + 'a';
646   };
647
648   out.reserve(out.size() + input.size() + 2);
649   out.push_back('\"');
650
651   auto* p = reinterpret_cast<const unsigned char*>(input.begin());
652   auto* q = reinterpret_cast<const unsigned char*>(input.begin());
653   auto* e = reinterpret_cast<const unsigned char*>(input.end());
654
655   while (p < e) {
656     // Since non-ascii encoding inherently does utf8 validation
657     // we explicitly validate utf8 only if non-ascii encoding is disabled.
658     if ((opts.validate_utf8 || opts.skip_invalid_utf8)
659         && !opts.encode_non_ascii) {
660       // to achieve better spatial and temporal coherence
661       // we do utf8 validation progressively along with the
662       // string-escaping instead of two separate passes
663
664       // as the encoding progresses, q will stay at or ahead of p
665       CHECK(q >= p);
666
667       // as p catches up with q, move q forward
668       if (q == p) {
669         // calling utf8_decode has the side effect of
670         // checking that utf8 encodings are valid
671         char32_t v = decodeUtf8(q, e, opts.skip_invalid_utf8);
672         if (opts.skip_invalid_utf8 && v == U'\ufffd') {
673           out.append("\ufffd");
674           p = q;
675           continue;
676         }
677       }
678     }
679     if (opts.encode_non_ascii && (*p & 0x80)) {
680       // note that this if condition captures utf8 chars
681       // with value > 127, so size > 1 byte
682       char32_t v = decodeUtf8(p, e, opts.skip_invalid_utf8);
683       out.append("\\u");
684       out.push_back(hexDigit(v >> 12));
685       out.push_back(hexDigit((v >> 8) & 0x0f));
686       out.push_back(hexDigit((v >> 4) & 0x0f));
687       out.push_back(hexDigit(v & 0x0f));
688     } else if (*p == '\\' || *p == '\"') {
689       out.push_back('\\');
690       out.push_back(*p++);
691     } else if (*p <= 0x1f) {
692       switch (*p) {
693         case '\b': out.append("\\b"); p++; break;
694         case '\f': out.append("\\f"); p++; break;
695         case '\n': out.append("\\n"); p++; break;
696         case '\r': out.append("\\r"); p++; break;
697         case '\t': out.append("\\t"); p++; break;
698         default:
699           // note that this if condition captures non readable chars
700           // with value < 32, so size = 1 byte (e.g control chars).
701           out.append("\\u00");
702           out.push_back(hexDigit((*p & 0xf0) >> 4));
703           out.push_back(hexDigit(*p & 0xf));
704           p++;
705       }
706     } else {
707       out.push_back(*p++);
708     }
709   }
710
711   out.push_back('\"');
712 }
713
714 }
715
716 //////////////////////////////////////////////////////////////////////
717
718 dynamic parseJson(StringPiece range) {
719   return parseJson(range, json::serialization_opts());
720 }
721
722 dynamic parseJson(
723     StringPiece range,
724     json::serialization_opts const& opts) {
725
726   json::Input in(range, &opts);
727
728   auto ret = parseValue(in);
729   in.skipWhitespace();
730   if (in.size() && *in != '\0') {
731     in.error("parsing didn't consume all input");
732   }
733   return ret;
734 }
735
736 fbstring toJson(dynamic const& dyn) {
737   return json::serialize(dyn, json::serialization_opts());
738 }
739
740 fbstring toPrettyJson(dynamic const& dyn) {
741   json::serialization_opts opts;
742   opts.pretty_formatting = true;
743   return json::serialize(dyn, opts);
744 }
745
746 //////////////////////////////////////////////////////////////////////
747 // dynamic::print_as_pseudo_json() is implemented here for header
748 // ordering reasons (most of the dynamic implementation is in
749 // dynamic-inl.h, which we don't want to include json.h).
750
751 void dynamic::print_as_pseudo_json(std::ostream& out) const {
752   json::serialization_opts opts;
753   opts.allow_non_string_keys = true;
754   out << json::serialize(*this, opts);
755 }
756
757 //////////////////////////////////////////////////////////////////////
758
759 }