folly::json: allow skipping invalid UTF8
[folly.git] / folly / json.cpp
1 /*
2  * Copyright 2013 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   void skipWhitespace() {
312     // Spaces other than ' ' characters are less common but should be
313     // checked.  This configuration where we loop on the ' '
314     // separately from oddspaces was empirically fastest.
315     auto oddspace = [] (char c) {
316       return c == '\n' || c == '\t' || c == '\r';
317     };
318
319   loop:
320     for (; !range_.empty() && range_.front() == ' '; range_.pop_front()) {
321     }
322     if (!range_.empty() && oddspace(range_.front())) {
323       range_.pop_front();
324       goto loop;
325     }
326     storeCurrent();
327   }
328
329   void expect(char c) {
330     if (**this != c) {
331       throw ParseError(lineNum_, context(),
332         to<std::string>("expected '", c, '\''));
333     }
334     ++*this;
335   }
336
337   std::size_t size() const {
338     return range_.size();
339   }
340
341   int operator*() const {
342     return current_;
343   }
344
345   void operator++() {
346     range_.pop_front();
347     storeCurrent();
348   }
349
350   template<class T>
351   T extract() {
352     try {
353       return to<T>(&range_);
354     } catch (std::exception const& e) {
355       error(e.what());
356     }
357   }
358
359   bool consume(StringPiece str) {
360     if (boost::starts_with(range_, str)) {
361       range_.advance(str.size());
362       storeCurrent();
363       return true;
364     }
365     return false;
366   }
367
368   std::string context() const {
369     return range_.subpiece(0, 16 /* arbitrary */).toString();
370   }
371
372   dynamic error(char const* what) const {
373     throw ParseError(lineNum_, context(), what);
374   }
375
376   json::serialization_opts const& getOpts() {
377     return opts_;
378   }
379
380 private:
381   void storeCurrent() {
382     current_ = range_.empty() ? EOF : range_.front();
383   }
384
385 private:
386   StringPiece range_;
387   json::serialization_opts const& opts_;
388   unsigned lineNum_;
389   int current_;
390 };
391
392 dynamic parseValue(Input& in);
393 fbstring parseString(Input& in);
394 dynamic parseNumber(Input& in);
395
396 dynamic parseObject(Input& in) {
397   assert(*in == '{');
398   ++in;
399
400   dynamic ret = dynamic::object;
401
402   in.skipWhitespace();
403   if (*in == '}') {
404     ++in;
405     return ret;
406   }
407
408   for (;;) {
409     if (in.getOpts().allow_trailing_comma && *in == '}') {
410       break;
411     }
412     if (*in == '\"') { // string
413       auto key = parseString(in);
414       in.skipWhitespace();
415       in.expect(':');
416       in.skipWhitespace();
417       ret.insert(std::move(key), parseValue(in));
418     } else if (!in.getOpts().allow_non_string_keys) {
419       in.error("expected string for object key name");
420     } else {
421       auto key = parseValue(in);
422       in.skipWhitespace();
423       in.expect(':');
424       in.skipWhitespace();
425       ret.insert(std::move(key), parseValue(in));
426     }
427
428     in.skipWhitespace();
429     if (*in != ',') {
430       break;
431     }
432     ++in;
433     in.skipWhitespace();
434   }
435   in.expect('}');
436
437   return ret;
438 }
439
440 dynamic parseArray(Input& in) {
441   assert(*in == '[');
442   ++in;
443
444   dynamic ret = {};
445
446   in.skipWhitespace();
447   if (*in == ']') {
448     ++in;
449     return ret;
450   }
451
452   for (;;) {
453     if (in.getOpts().allow_trailing_comma && *in == ']') {
454       break;
455     }
456     ret.push_back(parseValue(in));
457     in.skipWhitespace();
458     if (*in != ',') {
459       break;
460     }
461     ++in;
462     in.skipWhitespace();
463   }
464   in.expect(']');
465
466   return ret;
467 }
468
469 dynamic parseNumber(Input& in) {
470   bool const negative = (*in == '-');
471   if (negative) {
472     ++in;
473     if (in.consume("Infinity")) {
474       return -std::numeric_limits<double>::infinity();
475     }
476   }
477
478   auto integral = in.skipDigits();
479   if (integral.empty()) {
480     in.error("expected digits after `-'");
481   }
482   auto const wasE = *in == 'e' || *in == 'E';
483   if (*in != '.' && !wasE) {
484     auto val = to<int64_t>(integral);
485     if (negative) {
486       val = -val;
487     }
488     in.skipWhitespace();
489     return val;
490   }
491
492   auto end = !wasE ? (++in, in.skipDigits().end()) : in.begin();
493   if (*in == 'e' || *in == 'E') {
494     ++in;
495     if (*in == '+' || *in == '-') {
496       ++in;
497     }
498     auto expPart = in.skipDigits();
499     end = expPart.end();
500   }
501   auto fullNum = makeRange(integral.begin(), end);
502
503   auto val = to<double>(fullNum);
504   if (negative) {
505     val *= -1;
506   }
507   return val;
508 }
509
510 fbstring decodeUnicodeEscape(Input& in) {
511   auto hexVal = [&] (char c) -> unsigned {
512     return c >= '0' && c <= '9' ? c - '0' :
513            c >= 'a' && c <= 'f' ? c - 'a' + 10 :
514            c >= 'A' && c <= 'F' ? c - 'A' + 10 :
515            (in.error("invalid hex digit"), 0);
516   };
517
518   auto readHex = [&]() -> uint16_t {
519     if (in.size() < 4) {
520       in.error("expected 4 hex digits");
521     }
522
523     uint16_t ret = hexVal(*in) * 4096;
524     ++in;
525     ret += hexVal(*in) * 256;
526     ++in;
527     ret += hexVal(*in) * 16;
528     ++in;
529     ret += hexVal(*in);
530     ++in;
531     return ret;
532   };
533
534   /*
535    * If the value encoded is in the surrogate pair range, we need to
536    * make sure there is another escape that we can use also.
537    */
538   uint32_t codePoint = readHex();
539   if (codePoint >= 0xd800 && codePoint <= 0xdbff) {
540     if (!in.consume("\\u")) {
541       in.error("expected another unicode escape for second half of "
542         "surrogate pair");
543     }
544     uint16_t second = readHex();
545     if (second >= 0xdc00 && second <= 0xdfff) {
546       codePoint = 0x10000 + ((codePoint & 0x3ff) << 10) +
547                   (second & 0x3ff);
548     } else {
549       in.error("second character in surrogate pair is invalid");
550     }
551   } else if (codePoint >= 0xdc00 && codePoint <= 0xdfff) {
552     in.error("invalid unicode code point (in range [0xdc00,0xdfff])");
553   }
554
555   return codePointToUtf8(codePoint);
556 }
557
558 fbstring parseString(Input& in) {
559   assert(*in == '\"');
560   ++in;
561
562   fbstring ret;
563   for (;;) {
564     auto range = in.skipWhile(
565       [] (char c) { return c != '\"' && c != '\\'; }
566     );
567     ret.append(range.begin(), range.end());
568
569     if (*in == '\"') {
570       ++in;
571       break;
572     }
573     if (*in == '\\') {
574       ++in;
575       switch (*in) {
576       case '\"':    ret.push_back('\"'); ++in; break;
577       case '\\':    ret.push_back('\\'); ++in; break;
578       case '/':     ret.push_back('/');  ++in; break;
579       case 'b':     ret.push_back('\b'); ++in; break;
580       case 'f':     ret.push_back('\f'); ++in; break;
581       case 'n':     ret.push_back('\n'); ++in; break;
582       case 'r':     ret.push_back('\r'); ++in; break;
583       case 't':     ret.push_back('\t'); ++in; break;
584       case 'u':     ++in; ret += decodeUnicodeEscape(in); break;
585       default:      in.error(to<fbstring>("unknown escape ", *in,
586                                           " in string").c_str());
587       }
588       continue;
589     }
590     if (*in == EOF) {
591       in.error("unterminated string");
592     }
593     if (!*in) {
594       /*
595        * Apparently we're actually supposed to ban all control
596        * characters from strings.  This seems unnecessarily
597        * restrictive, so we're only banning zero bytes.  (Since the
598        * string is presumed to be UTF-8 encoded it's fine to just
599        * check this way.)
600        */
601       in.error("null byte in string");
602     }
603
604     ret.push_back(*in);
605     ++in;
606   }
607
608   return ret;
609 }
610
611 dynamic parseValue(Input& in) {
612   in.skipWhitespace();
613   return *in == '[' ? parseArray(in) :
614          *in == '{' ? parseObject(in) :
615          *in == '\"' ? parseString(in) :
616          (*in == '-' || (*in >= '0' && *in <= '9')) ? parseNumber(in) :
617          in.consume("true") ? true :
618          in.consume("false") ? false :
619          in.consume("null") ? nullptr :
620          in.consume("Infinity") ? std::numeric_limits<double>::infinity() :
621          in.consume("NaN") ? std::numeric_limits<double>::quiet_NaN() :
622          in.error("expected json value");
623 }
624
625 }
626
627 //////////////////////////////////////////////////////////////////////
628
629 fbstring serialize(dynamic const& dyn, serialization_opts const& opts) {
630   fbstring ret;
631   unsigned indentLevel = 0;
632   Printer p(ret, opts.pretty_formatting ? &indentLevel : nullptr, &opts);
633   p(dyn);
634   return ret;
635 }
636
637 // Escape a string so that it is legal to print it in JSON text.
638 void escapeString(StringPiece input,
639                   fbstring& out,
640                   const serialization_opts& opts) {
641   auto hexDigit = [] (int c) -> char {
642     return c < 10 ? c + '0' : c - 10 + 'a';
643   };
644
645   out.reserve(out.size() + input.size() + 2);
646   out.push_back('\"');
647
648   auto* p = reinterpret_cast<const unsigned char*>(input.begin());
649   auto* q = reinterpret_cast<const unsigned char*>(input.begin());
650   auto* e = reinterpret_cast<const unsigned char*>(input.end());
651
652   while (p < e) {
653     // Since non-ascii encoding inherently does utf8 validation
654     // we explicitly validate utf8 only if non-ascii encoding is disabled.
655     if ((opts.validate_utf8 || opts.skip_invalid_utf8)
656         && !opts.encode_non_ascii) {
657       // to achieve better spatial and temporal coherence
658       // we do utf8 validation progressively along with the
659       // string-escaping instead of two separate passes
660
661       // as the encoding progresses, q will stay at or ahead of p
662       CHECK(q >= p);
663
664       // as p catches up with q, move q forward
665       if (q == p) {
666         // calling utf8_decode has the side effect of
667         // checking that utf8 encodings are valid
668         char32_t v = decodeUtf8(q, e, opts.skip_invalid_utf8);
669         if (opts.skip_invalid_utf8 && v == U'\ufffd') {
670           out.append("\ufffd");
671           p = q;
672           continue;
673         }
674       }
675     }
676     if (opts.encode_non_ascii && (*p & 0x80)) {
677       // note that this if condition captures utf8 chars
678       // with value > 127, so size > 1 byte
679       char32_t v = decodeUtf8(p, e, opts.skip_invalid_utf8);
680       out.append("\\u");
681       out.push_back(hexDigit(v >> 12));
682       out.push_back(hexDigit((v >> 8) & 0x0f));
683       out.push_back(hexDigit((v >> 4) & 0x0f));
684       out.push_back(hexDigit(v & 0x0f));
685     } else if (*p == '\\' || *p == '\"') {
686       out.push_back('\\');
687       out.push_back(*p++);
688     } else if (*p <= 0x1f) {
689       switch (*p) {
690         case '\b': out.append("\\b"); p++; break;
691         case '\f': out.append("\\f"); p++; break;
692         case '\n': out.append("\\n"); p++; break;
693         case '\r': out.append("\\r"); p++; break;
694         case '\t': out.append("\\t"); p++; break;
695         default:
696           // note that this if condition captures non readable chars
697           // with value < 32, so size = 1 byte (e.g control chars).
698           out.append("\\u00");
699           out.push_back(hexDigit((*p & 0xf0) >> 4));
700           out.push_back(hexDigit(*p & 0xf));
701           p++;
702       }
703     } else {
704       out.push_back(*p++);
705     }
706   }
707
708   out.push_back('\"');
709 }
710
711 }
712
713 //////////////////////////////////////////////////////////////////////
714
715 dynamic parseJson(StringPiece range) {
716   return parseJson(range, json::serialization_opts());
717 }
718
719 dynamic parseJson(
720     StringPiece range,
721     json::serialization_opts const& opts) {
722
723   json::Input in(range, &opts);
724
725   auto ret = parseValue(in);
726   in.skipWhitespace();
727   if (in.size() && *in != '\0') {
728     in.error("parsing didn't consume all input");
729   }
730   return ret;
731 }
732
733 fbstring toJson(dynamic const& dyn) {
734   return json::serialize(dyn, json::serialization_opts());
735 }
736
737 fbstring toPrettyJson(dynamic const& dyn) {
738   json::serialization_opts opts;
739   opts.pretty_formatting = true;
740   return json::serialize(dyn, opts);
741 }
742
743 //////////////////////////////////////////////////////////////////////
744 // dynamic::print_as_pseudo_json() is implemented here for header
745 // ordering reasons (most of the dynamic implementation is in
746 // dynamic-inl.h, which we don't want to include json.h).
747
748 void dynamic::print_as_pseudo_json(std::ostream& out) const {
749   json::serialization_opts opts;
750   opts.allow_non_string_keys = true;
751   out << json::serialize(*this, opts);
752 }
753
754 //////////////////////////////////////////////////////////////////////
755
756 }