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