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