You can not select more than 25 topics Topics must start with a chinese character,a letter or number, can include dashes ('-') and can be up to 35 characters long.

json_tokener.c 35 kB

5 years ago
5 years ago
5 years ago
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293
  1. /*
  2. * $Id: json_tokener.c,v 1.20 2006/07/25 03:24:50 mclark Exp $
  3. *
  4. * Copyright (c) 2004, 2005 Metaparadigm Pte. Ltd.
  5. * Michael Clark <michael@metaparadigm.com>
  6. *
  7. * This library is free software; you can redistribute it and/or modify
  8. * it under the terms of the MIT license. See COPYING for details.
  9. *
  10. *
  11. * Copyright (c) 2008-2009 Yahoo! Inc. All rights reserved.
  12. * The copyrights to the contents of this file are licensed under the MIT License
  13. * (http://www.opensource.org/licenses/mit-license.php)
  14. */
  15. #include "config.h"
  16. #include "math_compat.h"
  17. #include <assert.h>
  18. #include <limits.h>
  19. #include <math.h>
  20. #include <stddef.h>
  21. #include <stdio.h>
  22. #include <stdlib.h>
  23. #include <string.h>
  24. #include "debug.h"
  25. #include "json_inttypes.h"
  26. #include "json_object.h"
  27. #include "json_object_private.h"
  28. #include "json_tokener.h"
  29. #include "json_util.h"
  30. #include "printbuf.h"
  31. #include "strdup_compat.h"
  32. #ifdef HAVE_LOCALE_H
  33. #include <locale.h>
  34. #endif /* HAVE_LOCALE_H */
  35. #ifdef HAVE_XLOCALE_H
  36. #include <xlocale.h>
  37. #endif
  38. #ifdef HAVE_STRINGS_H
  39. #include <strings.h>
  40. #endif /* HAVE_STRINGS_H */
  41. #define jt_hexdigit(x) (((x) <= '9') ? (x) - '0' : ((x)&7) + 9)
  42. #if !HAVE_STRNCASECMP && defined(_MSC_VER)
  43. /* MSC has the version as _strnicmp */
  44. #define strncasecmp _strnicmp
  45. #elif !HAVE_STRNCASECMP
  46. #error You do not have strncasecmp on your system.
  47. #endif /* HAVE_STRNCASECMP */
  48. /* The following helper functions are used to speed up parsing. They
  49. * are faster than their ctype counterparts because they assume that
  50. * the input is in ASCII and that the locale is set to "C". The
  51. * compiler will also inline these functions, providing an additional
  52. * speedup by saving on function calls.
  53. */
  54. static inline int is_ws_char(char c)
  55. {
  56. return c == ' '
  57. || c == '\t'
  58. || c == '\n'
  59. || c == '\r';
  60. }
  61. static inline int is_hex_char(char c)
  62. {
  63. return (c >= '0' && c <= '9')
  64. || (c >= 'A' && c <= 'F')
  65. || (c >= 'a' && c <= 'f');
  66. }
  67. /* Use C99 NAN by default; if not available, nan("") should work too. */
  68. #ifndef NAN
  69. #define NAN nan("")
  70. #endif /* !NAN */
  71. static const char json_null_str[] = "null";
  72. static const int json_null_str_len = sizeof(json_null_str) - 1;
  73. static const char json_inf_str[] = "Infinity";
  74. /* Swapped case "Infinity" to avoid need to call tolower() on input chars: */
  75. static const char json_inf_str_invert[] = "iNFINITY";
  76. static const unsigned int json_inf_str_len = sizeof(json_inf_str) - 1;
  77. static const char json_nan_str[] = "NaN";
  78. static const int json_nan_str_len = sizeof(json_nan_str) - 1;
  79. static const char json_true_str[] = "true";
  80. static const int json_true_str_len = sizeof(json_true_str) - 1;
  81. static const char json_false_str[] = "false";
  82. static const int json_false_str_len = sizeof(json_false_str) - 1;
  83. /* clang-format off */
  84. static const char *json_tokener_errors[] = {
  85. "success",
  86. "continue",
  87. "nesting too deep",
  88. "unexpected end of data",
  89. "unexpected character",
  90. "null expected",
  91. "boolean expected",
  92. "number expected",
  93. "array value separator ',' expected",
  94. "quoted object property name expected",
  95. "object property name separator ':' expected",
  96. "object value separator ',' expected",
  97. "invalid string sequence",
  98. "expected comment",
  99. "invalid utf-8 string",
  100. "buffer size overflow"
  101. };
  102. /* clang-format on */
  103. /**
  104. * validete the utf-8 string in strict model.
  105. * if not utf-8 format, return err.
  106. */
  107. static json_bool json_tokener_validate_utf8(const char c, unsigned int *nBytes);
  108. static int json_tokener_parse_double(const char *buf, int len, double *retval);
  109. const char *json_tokener_error_desc(enum json_tokener_error jerr)
  110. {
  111. int jerr_int = (int)jerr;
  112. if (jerr_int < 0 ||
  113. jerr_int >= (int)(sizeof(json_tokener_errors) / sizeof(json_tokener_errors[0])))
  114. return "Unknown error, "
  115. "invalid json_tokener_error value passed to json_tokener_error_desc()";
  116. return json_tokener_errors[jerr];
  117. }
  118. enum json_tokener_error json_tokener_get_error(struct json_tokener *tok)
  119. {
  120. return tok->err;
  121. }
  122. /* Stuff for decoding unicode sequences */
  123. #define IS_HIGH_SURROGATE(uc) (((uc)&0xFC00) == 0xD800)
  124. #define IS_LOW_SURROGATE(uc) (((uc)&0xFC00) == 0xDC00)
  125. #define DECODE_SURROGATE_PAIR(hi, lo) ((((hi)&0x3FF) << 10) + ((lo)&0x3FF) + 0x10000)
  126. static unsigned char utf8_replacement_char[3] = {0xEF, 0xBF, 0xBD};
  127. struct json_tokener *json_tokener_new_ex(int depth)
  128. {
  129. struct json_tokener *tok;
  130. tok = (struct json_tokener *)calloc(1, sizeof(struct json_tokener));
  131. if (!tok)
  132. return NULL;
  133. tok->stack = (struct json_tokener_srec *)calloc(depth, sizeof(struct json_tokener_srec));
  134. if (!tok->stack)
  135. {
  136. free(tok);
  137. return NULL;
  138. }
  139. tok->pb = printbuf_new();
  140. if (!tok->pb)
  141. {
  142. free(tok);
  143. free(tok->stack);
  144. return NULL;
  145. }
  146. tok->max_depth = depth;
  147. json_tokener_reset(tok);
  148. return tok;
  149. }
  150. struct json_tokener *json_tokener_new(void)
  151. {
  152. return json_tokener_new_ex(JSON_TOKENER_DEFAULT_DEPTH);
  153. }
  154. void json_tokener_free(struct json_tokener *tok)
  155. {
  156. json_tokener_reset(tok);
  157. if (tok->pb)
  158. printbuf_free(tok->pb);
  159. free(tok->stack);
  160. free(tok);
  161. }
  162. static void json_tokener_reset_level(struct json_tokener *tok, int depth)
  163. {
  164. tok->stack[depth].state = json_tokener_state_eatws;
  165. tok->stack[depth].saved_state = json_tokener_state_start;
  166. json_object_put(tok->stack[depth].current);
  167. tok->stack[depth].current = NULL;
  168. free(tok->stack[depth].obj_field_name);
  169. tok->stack[depth].obj_field_name = NULL;
  170. }
  171. void json_tokener_reset(struct json_tokener *tok)
  172. {
  173. int i;
  174. if (!tok)
  175. return;
  176. for (i = tok->depth; i >= 0; i--)
  177. json_tokener_reset_level(tok, i);
  178. tok->depth = 0;
  179. tok->err = json_tokener_success;
  180. }
  181. struct json_object *json_tokener_parse(const char *str)
  182. {
  183. enum json_tokener_error jerr_ignored;
  184. struct json_object *obj;
  185. obj = json_tokener_parse_verbose(str, &jerr_ignored);
  186. return obj;
  187. }
  188. struct json_object *json_tokener_parse_verbose(const char *str, enum json_tokener_error *error)
  189. {
  190. struct json_tokener *tok;
  191. struct json_object *obj;
  192. tok = json_tokener_new();
  193. if (!tok)
  194. return NULL;
  195. obj = json_tokener_parse_ex(tok, str, -1);
  196. *error = tok->err;
  197. if (tok->err != json_tokener_success
  198. #if 0
  199. /* This would be a more sensible default, and cause parsing
  200. * things like "null123" to fail when the caller can't know
  201. * where the parsing left off, but starting to fail would
  202. * be a notable behaviour change. Save for a 1.0 release.
  203. */
  204. || json_tokener_get_parse_end(tok) != strlen(str)
  205. #endif
  206. )
  207. {
  208. if (obj != NULL)
  209. json_object_put(obj);
  210. obj = NULL;
  211. }
  212. json_tokener_free(tok);
  213. return obj;
  214. }
  215. #define state tok->stack[tok->depth].state
  216. #define saved_state tok->stack[tok->depth].saved_state
  217. #define current tok->stack[tok->depth].current
  218. #define obj_field_name tok->stack[tok->depth].obj_field_name
  219. /* Optimization:
  220. * json_tokener_parse_ex() consumed a lot of CPU in its main loop,
  221. * iterating character-by character. A large performance boost is
  222. * achieved by using tighter loops to locally handle units such as
  223. * comments and strings. Loops that handle an entire token within
  224. * their scope also gather entire strings and pass them to
  225. * printbuf_memappend() in a single call, rather than calling
  226. * printbuf_memappend() one char at a time.
  227. *
  228. * PEEK_CHAR() and ADVANCE_CHAR() macros are used for code that is
  229. * common to both the main loop and the tighter loops.
  230. */
  231. /* PEEK_CHAR(dest, tok) macro:
  232. * Peeks at the current char and stores it in dest.
  233. * Returns 1 on success, sets tok->err and returns 0 if no more chars.
  234. * Implicit inputs: str, len, nBytesp vars
  235. */
  236. #define PEEK_CHAR(dest, tok) \
  237. (((tok)->char_offset == len) \
  238. ? (((tok)->depth == 0 && state == json_tokener_state_eatws && \
  239. saved_state == json_tokener_state_finish) \
  240. ? (((tok)->err = json_tokener_success), 0) \
  241. : (((tok)->err = json_tokener_continue), 0)) \
  242. : (((tok->flags & JSON_TOKENER_VALIDATE_UTF8) && \
  243. (!json_tokener_validate_utf8(*str, nBytesp))) \
  244. ? ((tok->err = json_tokener_error_parse_utf8_string), 0) \
  245. : (((dest) = *str), 1)))
  246. /* ADVANCE_CHAR() macro:
  247. * Increments str & tok->char_offset.
  248. * For convenience of existing conditionals, returns the old value of c (0 on eof)
  249. * Implicit inputs: c var
  250. */
  251. #define ADVANCE_CHAR(str, tok) (++(str), ((tok)->char_offset)++, c)
  252. /* End optimization macro defs */
  253. struct json_object *json_tokener_parse_ex(struct json_tokener *tok, const char *str, int len)
  254. {
  255. struct json_object *obj = NULL;
  256. char c = '\1';
  257. unsigned int nBytes = 0;
  258. unsigned int *nBytesp = &nBytes;
  259. #ifdef HAVE_USELOCALE
  260. locale_t oldlocale = uselocale(NULL);
  261. locale_t newloc;
  262. #elif defined(HAVE_SETLOCALE)
  263. char *oldlocale = NULL;
  264. #endif
  265. tok->char_offset = 0;
  266. tok->err = json_tokener_success;
  267. /* this interface is presently not 64-bit clean due to the int len argument
  268. * and the internal printbuf interface that takes 32-bit int len arguments
  269. * so the function limits the maximum string size to INT32_MAX (2GB).
  270. * If the function is called with len == -1 then strlen is called to check
  271. * the string length is less than INT32_MAX (2GB)
  272. */
  273. if ((len < -1) || (len == -1 && strlen(str) > INT32_MAX))
  274. {
  275. tok->err = json_tokener_error_size;
  276. return NULL;
  277. }
  278. #ifdef HAVE_USELOCALE
  279. {
  280. locale_t duploc = duplocale(oldlocale);
  281. newloc = newlocale(LC_NUMERIC_MASK, "C", duploc);
  282. if (newloc == NULL)
  283. {
  284. freelocale(duploc);
  285. return NULL;
  286. }
  287. uselocale(newloc);
  288. }
  289. #elif defined(HAVE_SETLOCALE)
  290. {
  291. char *tmplocale;
  292. tmplocale = setlocale(LC_NUMERIC, NULL);
  293. if (tmplocale)
  294. oldlocale = strdup(tmplocale);
  295. setlocale(LC_NUMERIC, "C");
  296. }
  297. #endif
  298. while (PEEK_CHAR(c, tok)) // Note: c might be '\0' !
  299. {
  300. redo_char:
  301. switch (state)
  302. {
  303. case json_tokener_state_eatws:
  304. /* Advance until we change state */
  305. while (is_ws_char(c))
  306. {
  307. if ((!ADVANCE_CHAR(str, tok)) || (!PEEK_CHAR(c, tok)))
  308. goto out;
  309. }
  310. if (c == '/' && !(tok->flags & JSON_TOKENER_STRICT))
  311. {
  312. printbuf_reset(tok->pb);
  313. printbuf_memappend_fast(tok->pb, &c, 1);
  314. state = json_tokener_state_comment_start;
  315. }
  316. else
  317. {
  318. state = saved_state;
  319. goto redo_char;
  320. }
  321. break;
  322. case json_tokener_state_start:
  323. switch (c)
  324. {
  325. case '{':
  326. state = json_tokener_state_eatws;
  327. saved_state = json_tokener_state_object_field_start;
  328. current = json_object_new_object();
  329. if (current == NULL)
  330. goto out;
  331. break;
  332. case '[':
  333. state = json_tokener_state_eatws;
  334. saved_state = json_tokener_state_array;
  335. current = json_object_new_array();
  336. if (current == NULL)
  337. goto out;
  338. break;
  339. case 'I':
  340. case 'i':
  341. state = json_tokener_state_inf;
  342. printbuf_reset(tok->pb);
  343. tok->st_pos = 0;
  344. goto redo_char;
  345. case 'N':
  346. case 'n':
  347. state = json_tokener_state_null; // or NaN
  348. printbuf_reset(tok->pb);
  349. tok->st_pos = 0;
  350. goto redo_char;
  351. case '\'':
  352. if (tok->flags & JSON_TOKENER_STRICT)
  353. {
  354. /* in STRICT mode only double-quote are allowed */
  355. tok->err = json_tokener_error_parse_unexpected;
  356. goto out;
  357. }
  358. /* FALLTHRU */
  359. case '"':
  360. state = json_tokener_state_string;
  361. printbuf_reset(tok->pb);
  362. tok->quote_char = c;
  363. break;
  364. case 'T':
  365. case 't':
  366. case 'F':
  367. case 'f':
  368. state = json_tokener_state_boolean;
  369. printbuf_reset(tok->pb);
  370. tok->st_pos = 0;
  371. goto redo_char;
  372. case '0':
  373. case '1':
  374. case '2':
  375. case '3':
  376. case '4':
  377. case '5':
  378. case '6':
  379. case '7':
  380. case '8':
  381. case '9':
  382. case '-':
  383. state = json_tokener_state_number;
  384. printbuf_reset(tok->pb);
  385. tok->is_double = 0;
  386. goto redo_char;
  387. default: tok->err = json_tokener_error_parse_unexpected; goto out;
  388. }
  389. break;
  390. case json_tokener_state_finish:
  391. if (tok->depth == 0)
  392. goto out;
  393. obj = json_object_get(current);
  394. json_tokener_reset_level(tok, tok->depth);
  395. tok->depth--;
  396. goto redo_char;
  397. case json_tokener_state_inf: /* aka starts with 'i' (or 'I', or "-i", or "-I") */
  398. {
  399. /* If we were guaranteed to have len set, then we could (usually) handle
  400. * the entire "Infinity" check in a single strncmp (strncasecmp), but
  401. * since len might be -1 (i.e. "read until \0"), we need to check it
  402. * a character at a time.
  403. * Trying to handle it both ways would make this code considerably more
  404. * complicated with likely little performance benefit.
  405. */
  406. int is_negative = 0;
  407. /* Note: tok->st_pos must be 0 when state is set to json_tokener_state_inf */
  408. while (tok->st_pos < (int)json_inf_str_len)
  409. {
  410. char inf_char = *str;
  411. if (inf_char != json_inf_str[tok->st_pos] &&
  412. ((tok->flags & JSON_TOKENER_STRICT) ||
  413. inf_char != json_inf_str_invert[tok->st_pos])
  414. )
  415. {
  416. tok->err = json_tokener_error_parse_unexpected;
  417. goto out;
  418. }
  419. tok->st_pos++;
  420. (void)ADVANCE_CHAR(str, tok);
  421. if (!PEEK_CHAR(c, tok))
  422. {
  423. /* out of input chars, for now at least */
  424. goto out;
  425. }
  426. }
  427. /* We checked the full length of "Infinity", so create the object.
  428. * When handling -Infinity, the number parsing code will have dropped
  429. * the "-" into tok->pb for us, so check it now.
  430. */
  431. if (printbuf_length(tok->pb) > 0 && *(tok->pb->buf) == '-')
  432. {
  433. is_negative = 1;
  434. }
  435. current = json_object_new_double(is_negative ? -INFINITY : INFINITY);
  436. if (current == NULL)
  437. goto out;
  438. saved_state = json_tokener_state_finish;
  439. state = json_tokener_state_eatws;
  440. goto redo_char;
  441. }
  442. break;
  443. case json_tokener_state_null: /* aka starts with 'n' */
  444. {
  445. int size;
  446. int size_nan;
  447. printbuf_memappend_fast(tok->pb, &c, 1);
  448. size = json_min(tok->st_pos + 1, json_null_str_len);
  449. size_nan = json_min(tok->st_pos + 1, json_nan_str_len);
  450. if ((!(tok->flags & JSON_TOKENER_STRICT) &&
  451. strncasecmp(json_null_str, tok->pb->buf, size) == 0) ||
  452. (strncmp(json_null_str, tok->pb->buf, size) == 0))
  453. {
  454. if (tok->st_pos == json_null_str_len)
  455. {
  456. current = NULL;
  457. saved_state = json_tokener_state_finish;
  458. state = json_tokener_state_eatws;
  459. goto redo_char;
  460. }
  461. }
  462. else if ((!(tok->flags & JSON_TOKENER_STRICT) &&
  463. strncasecmp(json_nan_str, tok->pb->buf, size_nan) == 0) ||
  464. (strncmp(json_nan_str, tok->pb->buf, size_nan) == 0))
  465. {
  466. if (tok->st_pos == json_nan_str_len)
  467. {
  468. current = json_object_new_double(NAN);
  469. if (current == NULL)
  470. goto out;
  471. saved_state = json_tokener_state_finish;
  472. state = json_tokener_state_eatws;
  473. goto redo_char;
  474. }
  475. }
  476. else
  477. {
  478. tok->err = json_tokener_error_parse_null;
  479. goto out;
  480. }
  481. tok->st_pos++;
  482. }
  483. break;
  484. case json_tokener_state_comment_start:
  485. if (c == '*')
  486. {
  487. state = json_tokener_state_comment;
  488. }
  489. else if (c == '/')
  490. {
  491. state = json_tokener_state_comment_eol;
  492. }
  493. else
  494. {
  495. tok->err = json_tokener_error_parse_comment;
  496. goto out;
  497. }
  498. printbuf_memappend_fast(tok->pb, &c, 1);
  499. break;
  500. case json_tokener_state_comment:
  501. {
  502. /* Advance until we change state */
  503. const char *case_start = str;
  504. while (c != '*')
  505. {
  506. if (!ADVANCE_CHAR(str, tok) || !PEEK_CHAR(c, tok))
  507. {
  508. printbuf_memappend_fast(tok->pb, case_start,
  509. str - case_start);
  510. goto out;
  511. }
  512. }
  513. printbuf_memappend_fast(tok->pb, case_start, 1 + str - case_start);
  514. state = json_tokener_state_comment_end;
  515. }
  516. break;
  517. case json_tokener_state_comment_eol:
  518. {
  519. /* Advance until we change state */
  520. const char *case_start = str;
  521. while (c != '\n')
  522. {
  523. if (!ADVANCE_CHAR(str, tok) || !PEEK_CHAR(c, tok))
  524. {
  525. printbuf_memappend_fast(tok->pb, case_start,
  526. str - case_start);
  527. goto out;
  528. }
  529. }
  530. printbuf_memappend_fast(tok->pb, case_start, str - case_start);
  531. MC_DEBUG("json_tokener_comment: %s\n", tok->pb->buf);
  532. state = json_tokener_state_eatws;
  533. }
  534. break;
  535. case json_tokener_state_comment_end:
  536. printbuf_memappend_fast(tok->pb, &c, 1);
  537. if (c == '/')
  538. {
  539. MC_DEBUG("json_tokener_comment: %s\n", tok->pb->buf);
  540. state = json_tokener_state_eatws;
  541. }
  542. else
  543. {
  544. state = json_tokener_state_comment;
  545. }
  546. break;
  547. case json_tokener_state_string:
  548. {
  549. /* Advance until we change state */
  550. const char *case_start = str;
  551. while (1)
  552. {
  553. if (c == tok->quote_char)
  554. {
  555. printbuf_memappend_fast(tok->pb, case_start,
  556. str - case_start);
  557. current =
  558. json_object_new_string_len(tok->pb->buf, tok->pb->bpos);
  559. if (current == NULL)
  560. goto out;
  561. saved_state = json_tokener_state_finish;
  562. state = json_tokener_state_eatws;
  563. break;
  564. }
  565. else if (c == '\\')
  566. {
  567. printbuf_memappend_fast(tok->pb, case_start,
  568. str - case_start);
  569. saved_state = json_tokener_state_string;
  570. state = json_tokener_state_string_escape;
  571. break;
  572. }
  573. if (!ADVANCE_CHAR(str, tok) || !PEEK_CHAR(c, tok))
  574. {
  575. printbuf_memappend_fast(tok->pb, case_start,
  576. str - case_start);
  577. goto out;
  578. }
  579. }
  580. }
  581. break;
  582. case json_tokener_state_string_escape:
  583. switch (c)
  584. {
  585. case '"':
  586. case '\\':
  587. case '/':
  588. printbuf_memappend_fast(tok->pb, &c, 1);
  589. state = saved_state;
  590. break;
  591. case 'b':
  592. case 'n':
  593. case 'r':
  594. case 't':
  595. case 'f':
  596. if (c == 'b')
  597. printbuf_memappend_fast(tok->pb, "\b", 1);
  598. else if (c == 'n')
  599. printbuf_memappend_fast(tok->pb, "\n", 1);
  600. else if (c == 'r')
  601. printbuf_memappend_fast(tok->pb, "\r", 1);
  602. else if (c == 't')
  603. printbuf_memappend_fast(tok->pb, "\t", 1);
  604. else if (c == 'f')
  605. printbuf_memappend_fast(tok->pb, "\f", 1);
  606. state = saved_state;
  607. break;
  608. case 'u':
  609. tok->ucs_char = 0;
  610. tok->st_pos = 0;
  611. state = json_tokener_state_escape_unicode;
  612. break;
  613. default: tok->err = json_tokener_error_parse_string; goto out;
  614. }
  615. break;
  616. // ===================================================
  617. case json_tokener_state_escape_unicode:
  618. {
  619. /* Handle a 4-byte \uNNNN sequence, or two sequences if a surrogate pair */
  620. while (1)
  621. {
  622. if (!c || !is_hex_char(c))
  623. {
  624. tok->err = json_tokener_error_parse_string;
  625. goto out;
  626. }
  627. tok->ucs_char |=
  628. ((unsigned int)jt_hexdigit(c) << ((3 - tok->st_pos) * 4));
  629. tok->st_pos++;
  630. if (tok->st_pos >= 4)
  631. break;
  632. (void)ADVANCE_CHAR(str, tok);
  633. if (!PEEK_CHAR(c, tok))
  634. {
  635. /*
  636. * We're out of characters in the current call to
  637. * json_tokener_parse(), but a subsequent call might
  638. * provide us with more, so leave our current state
  639. * as-is (including tok->high_surrogate) and return.
  640. */
  641. goto out;
  642. }
  643. }
  644. tok->st_pos = 0;
  645. /* Now, we have a full \uNNNN sequence in tok->ucs_char */
  646. /* If the *previous* sequence was a high surrogate ... */
  647. if (tok->high_surrogate)
  648. {
  649. if (IS_LOW_SURROGATE(tok->ucs_char))
  650. {
  651. /* Recalculate the ucs_char, then fall thru to process normally */
  652. tok->ucs_char = DECODE_SURROGATE_PAIR(tok->high_surrogate,
  653. tok->ucs_char);
  654. }
  655. else
  656. {
  657. /* High surrogate was not followed by a low surrogate
  658. * Replace the high and process the rest normally
  659. */
  660. printbuf_memappend_fast(tok->pb,
  661. (char *)utf8_replacement_char, 3);
  662. }
  663. tok->high_surrogate = 0;
  664. }
  665. if (tok->ucs_char < 0x80)
  666. {
  667. unsigned char unescaped_utf[1];
  668. unescaped_utf[0] = tok->ucs_char;
  669. printbuf_memappend_fast(tok->pb, (char *)unescaped_utf, 1);
  670. }
  671. else if (tok->ucs_char < 0x800)
  672. {
  673. unsigned char unescaped_utf[2];
  674. unescaped_utf[0] = 0xc0 | (tok->ucs_char >> 6);
  675. unescaped_utf[1] = 0x80 | (tok->ucs_char & 0x3f);
  676. printbuf_memappend_fast(tok->pb, (char *)unescaped_utf, 2);
  677. }
  678. else if (IS_HIGH_SURROGATE(tok->ucs_char))
  679. {
  680. /*
  681. * The next two characters should be \u, HOWEVER,
  682. * we can't simply peek ahead here, because the
  683. * characters we need might not be passed to us
  684. * until a subsequent call to json_tokener_parse.
  685. * Instead, transition throug a couple of states.
  686. * (now):
  687. * _escape_unicode => _unicode_need_escape
  688. * (see a '\\' char):
  689. * _unicode_need_escape => _unicode_need_u
  690. * (see a 'u' char):
  691. * _unicode_need_u => _escape_unicode
  692. * ...and we'll end up back around here.
  693. */
  694. tok->high_surrogate = tok->ucs_char;
  695. tok->ucs_char = 0;
  696. state = json_tokener_state_escape_unicode_need_escape;
  697. break;
  698. }
  699. else if (IS_LOW_SURROGATE(tok->ucs_char))
  700. {
  701. /* Got a low surrogate not preceded by a high */
  702. printbuf_memappend_fast(tok->pb, (char *)utf8_replacement_char, 3);
  703. }
  704. else if (tok->ucs_char < 0x10000)
  705. {
  706. unsigned char unescaped_utf[3];
  707. unescaped_utf[0] = 0xe0 | (tok->ucs_char >> 12);
  708. unescaped_utf[1] = 0x80 | ((tok->ucs_char >> 6) & 0x3f);
  709. unescaped_utf[2] = 0x80 | (tok->ucs_char & 0x3f);
  710. printbuf_memappend_fast(tok->pb, (char *)unescaped_utf, 3);
  711. }
  712. else if (tok->ucs_char < 0x110000)
  713. {
  714. unsigned char unescaped_utf[4];
  715. unescaped_utf[0] = 0xf0 | ((tok->ucs_char >> 18) & 0x07);
  716. unescaped_utf[1] = 0x80 | ((tok->ucs_char >> 12) & 0x3f);
  717. unescaped_utf[2] = 0x80 | ((tok->ucs_char >> 6) & 0x3f);
  718. unescaped_utf[3] = 0x80 | (tok->ucs_char & 0x3f);
  719. printbuf_memappend_fast(tok->pb, (char *)unescaped_utf, 4);
  720. }
  721. else
  722. {
  723. /* Don't know what we got--insert the replacement char */
  724. printbuf_memappend_fast(tok->pb, (char *)utf8_replacement_char, 3);
  725. }
  726. state = saved_state; // i.e. _state_string or _state_object_field
  727. }
  728. break;
  729. case json_tokener_state_escape_unicode_need_escape:
  730. // We get here after processing a high_surrogate
  731. // require a '\\' char
  732. if (!c || c != '\\')
  733. {
  734. /* Got a high surrogate without another sequence following
  735. * it. Put a replacement char in for the high surrogate
  736. * and pop back up to _state_string or _state_object_field.
  737. */
  738. printbuf_memappend_fast(tok->pb, (char *)utf8_replacement_char, 3);
  739. tok->high_surrogate = 0;
  740. tok->ucs_char = 0;
  741. tok->st_pos = 0;
  742. state = saved_state;
  743. goto redo_char;
  744. }
  745. state = json_tokener_state_escape_unicode_need_u;
  746. break;
  747. case json_tokener_state_escape_unicode_need_u:
  748. /* We already had a \ char, check that it's \u */
  749. if (!c || c != 'u')
  750. {
  751. /* Got a high surrogate with some non-unicode escape
  752. * sequence following it.
  753. * Put a replacement char in for the high surrogate
  754. * and handle the escape sequence normally.
  755. */
  756. printbuf_memappend_fast(tok->pb, (char *)utf8_replacement_char, 3);
  757. tok->high_surrogate = 0;
  758. tok->ucs_char = 0;
  759. tok->st_pos = 0;
  760. state = json_tokener_state_string_escape;
  761. goto redo_char;
  762. }
  763. state = json_tokener_state_escape_unicode;
  764. break;
  765. // ===================================================
  766. case json_tokener_state_boolean:
  767. {
  768. int size1, size2;
  769. printbuf_memappend_fast(tok->pb, &c, 1);
  770. size1 = json_min(tok->st_pos + 1, json_true_str_len);
  771. size2 = json_min(tok->st_pos + 1, json_false_str_len);
  772. if ((!(tok->flags & JSON_TOKENER_STRICT) &&
  773. strncasecmp(json_true_str, tok->pb->buf, size1) == 0) ||
  774. (strncmp(json_true_str, tok->pb->buf, size1) == 0))
  775. {
  776. if (tok->st_pos == json_true_str_len)
  777. {
  778. current = json_object_new_boolean(1);
  779. if (current == NULL)
  780. goto out;
  781. saved_state = json_tokener_state_finish;
  782. state = json_tokener_state_eatws;
  783. goto redo_char;
  784. }
  785. }
  786. else if ((!(tok->flags & JSON_TOKENER_STRICT) &&
  787. strncasecmp(json_false_str, tok->pb->buf, size2) == 0) ||
  788. (strncmp(json_false_str, tok->pb->buf, size2) == 0))
  789. {
  790. if (tok->st_pos == json_false_str_len)
  791. {
  792. current = json_object_new_boolean(0);
  793. if (current == NULL)
  794. goto out;
  795. saved_state = json_tokener_state_finish;
  796. state = json_tokener_state_eatws;
  797. goto redo_char;
  798. }
  799. }
  800. else
  801. {
  802. tok->err = json_tokener_error_parse_boolean;
  803. goto out;
  804. }
  805. tok->st_pos++;
  806. }
  807. break;
  808. case json_tokener_state_number:
  809. {
  810. /* Advance until we change state */
  811. const char *case_start = str;
  812. int case_len = 0;
  813. int is_exponent = 0;
  814. int neg_sign_ok = 1;
  815. int pos_sign_ok = 0;
  816. if (printbuf_length(tok->pb) > 0)
  817. {
  818. /* We don't save all state from the previous incremental parse
  819. so we need to re-generate it based on the saved string so far.
  820. */
  821. char *e_loc = strchr(tok->pb->buf, 'e');
  822. if (!e_loc)
  823. e_loc = strchr(tok->pb->buf, 'E');
  824. if (e_loc)
  825. {
  826. char *last_saved_char =
  827. &tok->pb->buf[printbuf_length(tok->pb) - 1];
  828. is_exponent = 1;
  829. pos_sign_ok = neg_sign_ok = 1;
  830. /* If the "e" isn't at the end, we can't start with a '-' */
  831. if (e_loc != last_saved_char)
  832. {
  833. neg_sign_ok = 0;
  834. pos_sign_ok = 0;
  835. }
  836. // else leave it set to 1, i.e. start of the new input
  837. }
  838. }
  839. while (c && ((c >= '0' && c <= '9') ||
  840. (!is_exponent && (c == 'e' || c == 'E')) ||
  841. (neg_sign_ok && c == '-') || (pos_sign_ok && c == '+') ||
  842. (!tok->is_double && c == '.')))
  843. {
  844. pos_sign_ok = neg_sign_ok = 0;
  845. ++case_len;
  846. /* non-digit characters checks */
  847. /* note: since the main loop condition to get here was
  848. * an input starting with 0-9 or '-', we are
  849. * protected from input starting with '.' or
  850. * e/E.
  851. */
  852. switch (c)
  853. {
  854. case '.':
  855. tok->is_double = 1;
  856. pos_sign_ok = 1;
  857. neg_sign_ok = 1;
  858. break;
  859. case 'e': /* FALLTHRU */
  860. case 'E':
  861. is_exponent = 1;
  862. tok->is_double = 1;
  863. /* the exponent part can begin with a negative sign */
  864. pos_sign_ok = neg_sign_ok = 1;
  865. break;
  866. default: break;
  867. }
  868. if (!ADVANCE_CHAR(str, tok) || !PEEK_CHAR(c, tok))
  869. {
  870. printbuf_memappend_fast(tok->pb, case_start, case_len);
  871. goto out;
  872. }
  873. }
  874. /*
  875. Now we know c isn't a valid number char, but check whether
  876. it might have been intended to be, and return a potentially
  877. more understandable error right away.
  878. However, if we're at the top-level, use the number as-is
  879. because c can be part of a new object to parse on the
  880. next call to json_tokener_parse().
  881. */
  882. if (tok->depth > 0 && c != ',' && c != ']' && c != '}' && c != '/' &&
  883. c != 'I' && c != 'i' && !is_ws_char(c))
  884. {
  885. tok->err = json_tokener_error_parse_number;
  886. goto out;
  887. }
  888. if (case_len > 0)
  889. printbuf_memappend_fast(tok->pb, case_start, case_len);
  890. // Check for -Infinity
  891. if (tok->pb->buf[0] == '-' && case_len <= 1 && (c == 'i' || c == 'I'))
  892. {
  893. state = json_tokener_state_inf;
  894. tok->st_pos = 0;
  895. goto redo_char;
  896. }
  897. if (tok->is_double && !(tok->flags & JSON_TOKENER_STRICT))
  898. {
  899. /* Trim some chars off the end, to allow things
  900. like "123e+" to parse ok. */
  901. while (printbuf_length(tok->pb) > 1)
  902. {
  903. char last_char = tok->pb->buf[printbuf_length(tok->pb) - 1];
  904. if (last_char != 'e' && last_char != 'E' &&
  905. last_char != '-' && last_char != '+')
  906. {
  907. break;
  908. }
  909. tok->pb->buf[printbuf_length(tok->pb) - 1] = '\0';
  910. printbuf_length(tok->pb)--;
  911. }
  912. }
  913. }
  914. {
  915. int64_t num64;
  916. uint64_t numuint64;
  917. double numd;
  918. if (!tok->is_double && tok->pb->buf[0] == '-' &&
  919. json_parse_int64(tok->pb->buf, &num64) == 0)
  920. {
  921. current = json_object_new_int64(num64);
  922. if (current == NULL)
  923. goto out;
  924. }
  925. else if (!tok->is_double && tok->pb->buf[0] != '-' &&
  926. json_parse_uint64(tok->pb->buf, &numuint64) == 0)
  927. {
  928. if (numuint64 && tok->pb->buf[0] == '0' &&
  929. (tok->flags & JSON_TOKENER_STRICT))
  930. {
  931. tok->err = json_tokener_error_parse_number;
  932. goto out;
  933. }
  934. if (numuint64 <= INT64_MAX)
  935. {
  936. num64 = (uint64_t)numuint64;
  937. current = json_object_new_int64(num64);
  938. if (current == NULL)
  939. goto out;
  940. }
  941. else
  942. {
  943. current = json_object_new_uint64(numuint64);
  944. if (current == NULL)
  945. goto out;
  946. }
  947. }
  948. else if (tok->is_double &&
  949. json_tokener_parse_double(
  950. tok->pb->buf, printbuf_length(tok->pb), &numd) == 0)
  951. {
  952. current = json_object_new_double_s(numd, tok->pb->buf);
  953. if (current == NULL)
  954. goto out;
  955. }
  956. else
  957. {
  958. tok->err = json_tokener_error_parse_number;
  959. goto out;
  960. }
  961. saved_state = json_tokener_state_finish;
  962. state = json_tokener_state_eatws;
  963. goto redo_char;
  964. }
  965. break;
  966. case json_tokener_state_array_after_sep:
  967. case json_tokener_state_array:
  968. if (c == ']')
  969. {
  970. // Minimize memory usage; assume parsed objs are unlikely to be changed
  971. json_object_array_shrink(current, 0);
  972. if (state == json_tokener_state_array_after_sep &&
  973. (tok->flags & JSON_TOKENER_STRICT))
  974. {
  975. tok->err = json_tokener_error_parse_unexpected;
  976. goto out;
  977. }
  978. saved_state = json_tokener_state_finish;
  979. state = json_tokener_state_eatws;
  980. }
  981. else
  982. {
  983. if (tok->depth >= tok->max_depth - 1)
  984. {
  985. tok->err = json_tokener_error_depth;
  986. goto out;
  987. }
  988. state = json_tokener_state_array_add;
  989. tok->depth++;
  990. json_tokener_reset_level(tok, tok->depth);
  991. goto redo_char;
  992. }
  993. break;
  994. case json_tokener_state_array_add:
  995. if (json_object_array_add(current, obj) != 0)
  996. goto out;
  997. saved_state = json_tokener_state_array_sep;
  998. state = json_tokener_state_eatws;
  999. goto redo_char;
  1000. case json_tokener_state_array_sep:
  1001. if (c == ']')
  1002. {
  1003. // Minimize memory usage; assume parsed objs are unlikely to be changed
  1004. json_object_array_shrink(current, 0);
  1005. saved_state = json_tokener_state_finish;
  1006. state = json_tokener_state_eatws;
  1007. }
  1008. else if (c == ',')
  1009. {
  1010. saved_state = json_tokener_state_array_after_sep;
  1011. state = json_tokener_state_eatws;
  1012. }
  1013. else
  1014. {
  1015. tok->err = json_tokener_error_parse_array;
  1016. goto out;
  1017. }
  1018. break;
  1019. case json_tokener_state_object_field_start:
  1020. case json_tokener_state_object_field_start_after_sep:
  1021. if (c == '}')
  1022. {
  1023. if (state == json_tokener_state_object_field_start_after_sep &&
  1024. (tok->flags & JSON_TOKENER_STRICT))
  1025. {
  1026. tok->err = json_tokener_error_parse_unexpected;
  1027. goto out;
  1028. }
  1029. saved_state = json_tokener_state_finish;
  1030. state = json_tokener_state_eatws;
  1031. }
  1032. else if (c == '"' || c == '\'')
  1033. {
  1034. tok->quote_char = c;
  1035. printbuf_reset(tok->pb);
  1036. state = json_tokener_state_object_field;
  1037. }
  1038. else
  1039. {
  1040. tok->err = json_tokener_error_parse_object_key_name;
  1041. goto out;
  1042. }
  1043. break;
  1044. case json_tokener_state_object_field:
  1045. {
  1046. /* Advance until we change state */
  1047. const char *case_start = str;
  1048. while (1)
  1049. {
  1050. if (c == tok->quote_char)
  1051. {
  1052. printbuf_memappend_fast(tok->pb, case_start,
  1053. str - case_start);
  1054. obj_field_name = strdup(tok->pb->buf);
  1055. saved_state = json_tokener_state_object_field_end;
  1056. state = json_tokener_state_eatws;
  1057. break;
  1058. }
  1059. else if (c == '\\')
  1060. {
  1061. printbuf_memappend_fast(tok->pb, case_start,
  1062. str - case_start);
  1063. saved_state = json_tokener_state_object_field;
  1064. state = json_tokener_state_string_escape;
  1065. break;
  1066. }
  1067. if (!ADVANCE_CHAR(str, tok) || !PEEK_CHAR(c, tok))
  1068. {
  1069. printbuf_memappend_fast(tok->pb, case_start,
  1070. str - case_start);
  1071. goto out;
  1072. }
  1073. }
  1074. }
  1075. break;
  1076. case json_tokener_state_object_field_end:
  1077. if (c == ':')
  1078. {
  1079. saved_state = json_tokener_state_object_value;
  1080. state = json_tokener_state_eatws;
  1081. }
  1082. else
  1083. {
  1084. tok->err = json_tokener_error_parse_object_key_sep;
  1085. goto out;
  1086. }
  1087. break;
  1088. case json_tokener_state_object_value:
  1089. if (tok->depth >= tok->max_depth - 1)
  1090. {
  1091. tok->err = json_tokener_error_depth;
  1092. goto out;
  1093. }
  1094. state = json_tokener_state_object_value_add;
  1095. tok->depth++;
  1096. json_tokener_reset_level(tok, tok->depth);
  1097. goto redo_char;
  1098. case json_tokener_state_object_value_add:
  1099. json_object_object_add(current, obj_field_name, obj);
  1100. free(obj_field_name);
  1101. obj_field_name = NULL;
  1102. saved_state = json_tokener_state_object_sep;
  1103. state = json_tokener_state_eatws;
  1104. goto redo_char;
  1105. case json_tokener_state_object_sep:
  1106. /* { */
  1107. if (c == '}')
  1108. {
  1109. saved_state = json_tokener_state_finish;
  1110. state = json_tokener_state_eatws;
  1111. }
  1112. else if (c == ',')
  1113. {
  1114. saved_state = json_tokener_state_object_field_start_after_sep;
  1115. state = json_tokener_state_eatws;
  1116. }
  1117. else
  1118. {
  1119. tok->err = json_tokener_error_parse_object_value_sep;
  1120. goto out;
  1121. }
  1122. break;
  1123. }
  1124. (void)ADVANCE_CHAR(str, tok);
  1125. if (!c) // This is the char *before* advancing
  1126. break;
  1127. } /* while(PEEK_CHAR) */
  1128. out:
  1129. if ((tok->flags & JSON_TOKENER_VALIDATE_UTF8) && (nBytes != 0))
  1130. {
  1131. tok->err = json_tokener_error_parse_utf8_string;
  1132. }
  1133. if (c && (state == json_tokener_state_finish) && (tok->depth == 0) &&
  1134. (tok->flags & (JSON_TOKENER_STRICT | JSON_TOKENER_ALLOW_TRAILING_CHARS)) ==
  1135. JSON_TOKENER_STRICT)
  1136. {
  1137. /* unexpected char after JSON data */
  1138. tok->err = json_tokener_error_parse_unexpected;
  1139. }
  1140. if (!c)
  1141. {
  1142. /* We hit an eof char (0) */
  1143. if (state != json_tokener_state_finish && saved_state != json_tokener_state_finish)
  1144. tok->err = json_tokener_error_parse_eof;
  1145. }
  1146. #ifdef HAVE_USELOCALE
  1147. uselocale(oldlocale);
  1148. freelocale(newloc);
  1149. #elif defined(HAVE_SETLOCALE)
  1150. setlocale(LC_NUMERIC, oldlocale);
  1151. free(oldlocale);
  1152. #endif
  1153. if (tok->err == json_tokener_success)
  1154. {
  1155. json_object *ret = json_object_get(current);
  1156. int ii;
  1157. /* Partially reset, so we parse additional objects on subsequent calls. */
  1158. for (ii = tok->depth; ii >= 0; ii--)
  1159. json_tokener_reset_level(tok, ii);
  1160. return ret;
  1161. }
  1162. MC_DEBUG("json_tokener_parse_ex: error %s at offset %d\n", json_tokener_errors[tok->err],
  1163. tok->char_offset);
  1164. return NULL;
  1165. }
  1166. static json_bool json_tokener_validate_utf8(const char c, unsigned int *nBytes)
  1167. {
  1168. unsigned char chr = c;
  1169. if (*nBytes == 0)
  1170. {
  1171. if (chr >= 0x80)
  1172. {
  1173. if ((chr & 0xe0) == 0xc0)
  1174. *nBytes = 1;
  1175. else if ((chr & 0xf0) == 0xe0)
  1176. *nBytes = 2;
  1177. else if ((chr & 0xf8) == 0xf0)
  1178. *nBytes = 3;
  1179. else
  1180. return 0;
  1181. }
  1182. }
  1183. else
  1184. {
  1185. if ((chr & 0xC0) != 0x80)
  1186. return 0;
  1187. (*nBytes)--;
  1188. }
  1189. return 1;
  1190. }
  1191. void json_tokener_set_flags(struct json_tokener *tok, int flags)
  1192. {
  1193. tok->flags = flags;
  1194. }
  1195. size_t json_tokener_get_parse_end(struct json_tokener *tok)
  1196. {
  1197. assert(tok->char_offset >= 0); /* Drop this line when char_offset becomes a size_t */
  1198. return (size_t)tok->char_offset;
  1199. }
  1200. static int json_tokener_parse_double(const char *buf, int len, double *retval)
  1201. {
  1202. char *end;
  1203. *retval = strtod(buf, &end);
  1204. if (buf + len == end)
  1205. return 0; // It worked
  1206. return 1;
  1207. }