frozen.c 45 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470
  1. /*
  2. * Copyright (c) 2004-2013 Sergey Lyubka <[email protected]>
  3. * Copyright (c) 2018 Cesanta Software Limited
  4. * All rights reserved
  5. *
  6. * Licensed under the Apache License, Version 2.0 (the ""License"");
  7. * you may not use this file except in compliance with the License.
  8. * You may obtain a copy of the License at
  9. *
  10. * http://www.apache.org/licenses/LICENSE-2.0
  11. *
  12. * Unless required by applicable law or agreed to in writing, software
  13. * distributed under the License is distributed on an ""AS IS"" BASIS,
  14. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  15. * See the License for the specific language governing permissions and
  16. * limitations under the License.
  17. */
  18. #define _CRT_SECURE_NO_WARNINGS /* Disable deprecation warning in VS2005+ */
  19. #include "frozen.h"
  20. #include "stacktrace.h"
  21. #include <ctype.h>
  22. #include <stdarg.h>
  23. #include <stdio.h>
  24. #include <stdlib.h>
  25. #include <string.h>
  26. #if !defined(WEAK)
  27. #if (defined(__GNUC__) || defined(__TI_COMPILER_VERSION__)) && !defined(_WIN32)
  28. #define WEAK __attribute__((weak))
  29. #else
  30. #define WEAK
  31. #endif
  32. #endif
  33. #ifdef _WIN32
  34. #undef snprintf
  35. #undef vsnprintf
  36. #define snprintf cs_win_snprintf
  37. #define vsnprintf cs_win_vsnprintf
  38. int cs_win_snprintf(char *str, size_t size, const char *format, ...);
  39. int cs_win_vsnprintf(char *str, size_t size, const char *format, va_list ap);
  40. #if _MSC_VER >= 1700
  41. #include <stdint.h>
  42. #else
  43. typedef _int64 int64_t;
  44. typedef unsigned _int64 uint64_t;
  45. #endif
  46. #define PRId64 "I64d"
  47. #define PRIu64 "I64u"
  48. #else /* _WIN32 */
  49. /* <inttypes.h> wants this for C++ */
  50. #ifndef __STDC_FORMAT_MACROS
  51. #define __STDC_FORMAT_MACROS
  52. #endif
  53. #include <inttypes.h>
  54. #endif /* _WIN32 */
  55. #ifndef INT64_FMT
  56. #define INT64_FMT PRId64
  57. #endif
  58. #ifndef UINT64_FMT
  59. #define UINT64_FMT PRIu64
  60. #endif
  61. #ifndef va_copy
  62. #define va_copy(x, y) x = y
  63. #endif
  64. #ifndef JSON_ENABLE_ARRAY
  65. #define JSON_ENABLE_ARRAY 1
  66. #endif
  67. struct frozen {
  68. const char *end;
  69. const char *cur;
  70. const char *cur_name;
  71. size_t cur_name_len;
  72. /* For callback API */
  73. char path[JSON_MAX_PATH_LEN];
  74. size_t path_len;
  75. void *callback_data;
  76. json_walk_callback_t callback;
  77. };
  78. struct fstate {
  79. const char *ptr;
  80. size_t path_len;
  81. };
  82. #define SET_STATE(fr, ptr, str, len) \
  83. struct fstate fstate = {(ptr), (fr)->path_len}; \
  84. json_append_to_path((fr), (str), (len));
  85. #define CALL_BACK(fr, tok, value, len) \
  86. do { \
  87. if ((fr)->callback && \
  88. ((fr)->path_len == 0 || (fr)->path[(fr)->path_len - 1] != '.')) { \
  89. struct json_token t = {(value), (int) (len), (tok)}; \
  90. \
  91. /* Call the callback with the given value and current name */ \
  92. (fr)->callback((fr)->callback_data, (fr)->cur_name, (fr)->cur_name_len, \
  93. (fr)->path, &t); \
  94. \
  95. /* Reset the name */ \
  96. (fr)->cur_name = NULL; \
  97. (fr)->cur_name_len = 0; \
  98. } \
  99. } while (0)
  100. static int json_append_to_path(struct frozen *f, const char *str, int size) {
  101. int n = f->path_len;
  102. int left = sizeof(f->path) - n - 1;
  103. if (size > left) size = left;
  104. memcpy(f->path + n, str, size);
  105. f->path[n + size] = '\0';
  106. f->path_len += size;
  107. return n;
  108. }
  109. static void json_truncate_path(struct frozen *f, size_t len) {
  110. f->path_len = len;
  111. f->path[len] = '\0';
  112. }
  113. static int json_parse_object(struct frozen *f);
  114. static int json_parse_value(struct frozen *f);
  115. #define EXPECT(cond, err_code) \
  116. do { \
  117. if (!(cond)) return (err_code); \
  118. } while (0)
  119. #define TRY(expr) \
  120. do { \
  121. int _n = expr; \
  122. if (_n < 0) return _n; \
  123. } while (0)
  124. #define END_OF_STRING (-1)
  125. static int json_left(const struct frozen *f) {
  126. return f->end - f->cur;
  127. }
  128. static int json_isspace(int ch) {
  129. return ch == ' ' || ch == '\t' || ch == '\r' || ch == '\n';
  130. }
  131. static void json_skip_whitespaces(struct frozen *f) {
  132. while (f->cur < f->end && json_isspace(*f->cur)) f->cur++;
  133. }
  134. static int json_cur(struct frozen *f) {
  135. json_skip_whitespaces(f);
  136. return f->cur >= f->end ? END_OF_STRING : *(unsigned char *) f->cur;
  137. }
  138. static int json_test_and_skip(struct frozen *f, int expected) {
  139. int ch = json_cur(f);
  140. if (ch == expected) {
  141. f->cur++;
  142. return 0;
  143. }
  144. return ch == END_OF_STRING ? JSON_STRING_INCOMPLETE : JSON_STRING_INVALID;
  145. }
  146. static int json_isalpha(int ch) {
  147. return (ch >= 'a' && ch <= 'z') || (ch >= 'A' && ch <= 'Z');
  148. }
  149. static int json_isdigit(int ch) {
  150. return ch >= '0' && ch <= '9';
  151. }
  152. static int json_isxdigit(int ch) {
  153. return json_isdigit(ch) || (ch >= 'a' && ch <= 'f') ||
  154. (ch >= 'A' && ch <= 'F');
  155. }
  156. static int json_get_escape_len(const char *s, int len) {
  157. switch (*s) {
  158. case 'u':
  159. return len < 6 ? JSON_STRING_INCOMPLETE
  160. : json_isxdigit(s[1]) && json_isxdigit(s[2]) &&
  161. json_isxdigit(s[3]) && json_isxdigit(s[4])
  162. ? 5
  163. : JSON_STRING_INVALID;
  164. case '"':
  165. case '\\':
  166. case '/':
  167. case 'b':
  168. case 'f':
  169. case 'n':
  170. case 'r':
  171. case 't':
  172. return len < 2 ? JSON_STRING_INCOMPLETE : 1;
  173. default:
  174. return JSON_STRING_INVALID;
  175. }
  176. }
  177. /* identifier = letter { letter | digit | '_' } */
  178. static int json_parse_identifier(struct frozen *f) {
  179. EXPECT(json_isalpha(json_cur(f)), JSON_STRING_INVALID);
  180. {
  181. SET_STATE(f, f->cur, "", 0);
  182. while (f->cur < f->end &&
  183. (*f->cur == '_' || json_isalpha(*f->cur) || json_isdigit(*f->cur))) {
  184. f->cur++;
  185. }
  186. json_truncate_path(f, fstate.path_len);
  187. CALL_BACK(f, JSON_TYPE_STRING, fstate.ptr, f->cur - fstate.ptr);
  188. }
  189. return 0;
  190. }
  191. int json_get_utf8_char_len(unsigned char ch) {
  192. if ((ch & 0x80) == 0) return 1;
  193. switch (ch & 0xf0) {
  194. case 0xf0:
  195. return 4;
  196. case 0xe0:
  197. return 3;
  198. default:
  199. return 2;
  200. }
  201. }
  202. /* string = '"' { quoted_printable_chars } '"' */
  203. static int json_parse_string(struct frozen *f) {
  204. int n, ch = 0, len = 0;
  205. TRY(json_test_and_skip(f, '"'));
  206. {
  207. SET_STATE(f, f->cur, "", 0);
  208. for (; f->cur < f->end; f->cur += len) {
  209. ch = *(unsigned char *) f->cur;
  210. len = json_get_utf8_char_len((unsigned char) ch);
  211. EXPECT(ch >= 32 && len > 0, JSON_STRING_INVALID); /* No control chars */
  212. EXPECT(len <= json_left(f), JSON_STRING_INCOMPLETE);
  213. if (ch == '\\') {
  214. EXPECT((n = json_get_escape_len(f->cur + 1, json_left(f))) > 0, n);
  215. len += n;
  216. } else if (ch == '"') {
  217. json_truncate_path(f, fstate.path_len);
  218. CALL_BACK(f, JSON_TYPE_STRING, fstate.ptr, f->cur - fstate.ptr);
  219. f->cur++;
  220. break;
  221. };
  222. }
  223. }
  224. return ch == '"' ? 0 : JSON_STRING_INCOMPLETE;
  225. }
  226. /* number = [ '-' ] digit+ [ '.' digit+ ] [ ['e'|'E'] ['+'|'-'] digit+ ] */
  227. static int json_parse_number(struct frozen *f) {
  228. int ch = json_cur(f);
  229. SET_STATE(f, f->cur, "", 0);
  230. if (ch == '-') f->cur++;
  231. EXPECT(f->cur < f->end, JSON_STRING_INCOMPLETE);
  232. if (f->cur + 1 < f->end && f->cur[0] == '0' && f->cur[1] == 'x') {
  233. f->cur += 2;
  234. EXPECT(f->cur < f->end, JSON_STRING_INCOMPLETE);
  235. EXPECT(json_isxdigit(f->cur[0]), JSON_STRING_INVALID);
  236. while (f->cur < f->end && json_isxdigit(f->cur[0])) f->cur++;
  237. } else {
  238. EXPECT(json_isdigit(f->cur[0]), JSON_STRING_INVALID);
  239. while (f->cur < f->end && json_isdigit(f->cur[0])) f->cur++;
  240. if (f->cur < f->end && f->cur[0] == '.') {
  241. f->cur++;
  242. EXPECT(f->cur < f->end, JSON_STRING_INCOMPLETE);
  243. EXPECT(json_isdigit(f->cur[0]), JSON_STRING_INVALID);
  244. while (f->cur < f->end && json_isdigit(f->cur[0])) f->cur++;
  245. }
  246. if (f->cur < f->end && (f->cur[0] == 'e' || f->cur[0] == 'E')) {
  247. f->cur++;
  248. EXPECT(f->cur < f->end, JSON_STRING_INCOMPLETE);
  249. if ((f->cur[0] == '+' || f->cur[0] == '-')) f->cur++;
  250. EXPECT(f->cur < f->end, JSON_STRING_INCOMPLETE);
  251. EXPECT(json_isdigit(f->cur[0]), JSON_STRING_INVALID);
  252. while (f->cur < f->end && json_isdigit(f->cur[0])) f->cur++;
  253. }
  254. }
  255. json_truncate_path(f, fstate.path_len);
  256. CALL_BACK(f, JSON_TYPE_NUMBER, fstate.ptr, f->cur - fstate.ptr);
  257. return 0;
  258. }
  259. #if JSON_ENABLE_ARRAY
  260. /* array = '[' [ value { ',' value } ] ']' */
  261. static int json_parse_array(struct frozen *f) {
  262. int i = 0, current_path_len;
  263. char buf[20];
  264. CALL_BACK(f, JSON_TYPE_ARRAY_START, NULL, 0);
  265. TRY(json_test_and_skip(f, '['));
  266. {
  267. {
  268. SET_STATE(f, f->cur - 1, "", 0);
  269. while (json_cur(f) != ']') {
  270. snprintf(buf, sizeof(buf), "[%d]", i);
  271. i++;
  272. current_path_len = json_append_to_path(f, buf, strlen(buf));
  273. f->cur_name =
  274. f->path + strlen(f->path) - strlen(buf) + 1 /*opening brace*/;
  275. f->cur_name_len = strlen(buf) - 2 /*braces*/;
  276. TRY(json_parse_value(f));
  277. json_truncate_path(f, current_path_len);
  278. if (json_cur(f) == ',') f->cur++;
  279. }
  280. TRY(json_test_and_skip(f, ']'));
  281. json_truncate_path(f, fstate.path_len);
  282. CALL_BACK(f, JSON_TYPE_ARRAY_END, fstate.ptr, f->cur - fstate.ptr);
  283. }
  284. }
  285. return 0;
  286. }
  287. #endif /* JSON_ENABLE_ARRAY */
  288. static int json_expect(struct frozen *f, const char *s, int len,
  289. enum json_token_type tok_type) {
  290. int i, n = json_left(f);
  291. SET_STATE(f, f->cur, "", 0);
  292. for (i = 0; i < len; i++) {
  293. if (i >= n) return JSON_STRING_INCOMPLETE;
  294. if (f->cur[i] != s[i]) return JSON_STRING_INVALID;
  295. }
  296. f->cur += len;
  297. json_truncate_path(f, fstate.path_len);
  298. CALL_BACK(f, tok_type, fstate.ptr, f->cur - fstate.ptr);
  299. return 0;
  300. }
  301. /* value = 'null' | 'true' | 'false' | number | string | array | object */
  302. static int json_parse_value(struct frozen *f) {
  303. int ch = json_cur(f);
  304. switch (ch) {
  305. case '"':
  306. TRY(json_parse_string(f));
  307. break;
  308. case '{':
  309. TRY(json_parse_object(f));
  310. break;
  311. #if JSON_ENABLE_ARRAY
  312. case '[':
  313. TRY(json_parse_array(f));
  314. break;
  315. #endif
  316. case 'n':
  317. TRY(json_expect(f, "null", 4, JSON_TYPE_NULL));
  318. break;
  319. case 't':
  320. TRY(json_expect(f, "true", 4, JSON_TYPE_TRUE));
  321. break;
  322. case 'f':
  323. TRY(json_expect(f, "false", 5, JSON_TYPE_FALSE));
  324. break;
  325. case '-':
  326. case '0':
  327. case '1':
  328. case '2':
  329. case '3':
  330. case '4':
  331. case '5':
  332. case '6':
  333. case '7':
  334. case '8':
  335. case '9':
  336. TRY(json_parse_number(f));
  337. break;
  338. default:
  339. return ch == END_OF_STRING ? JSON_STRING_INCOMPLETE : JSON_STRING_INVALID;
  340. }
  341. return 0;
  342. }
  343. /* key = identifier | string */
  344. static int json_parse_key(struct frozen *f) {
  345. int ch = json_cur(f);
  346. if (json_isalpha(ch)) {
  347. TRY(json_parse_identifier(f));
  348. } else if (ch == '"') {
  349. TRY(json_parse_string(f));
  350. } else {
  351. return ch == END_OF_STRING ? JSON_STRING_INCOMPLETE : JSON_STRING_INVALID;
  352. }
  353. return 0;
  354. }
  355. /* pair = key ':' value */
  356. static int json_parse_pair(struct frozen *f) {
  357. int current_path_len;
  358. const char *tok;
  359. json_skip_whitespaces(f);
  360. tok = f->cur;
  361. TRY(json_parse_key(f));
  362. {
  363. f->cur_name = *tok == '"' ? tok + 1 : tok;
  364. f->cur_name_len = *tok == '"' ? f->cur - tok - 2 : f->cur - tok;
  365. current_path_len = json_append_to_path(f, f->cur_name, f->cur_name_len);
  366. }
  367. TRY(json_test_and_skip(f, ':'));
  368. TRY(json_parse_value(f));
  369. json_truncate_path(f, current_path_len);
  370. return 0;
  371. }
  372. /* object = '{' pair { ',' pair } '}' */
  373. static int json_parse_object(struct frozen *f) {
  374. CALL_BACK(f, JSON_TYPE_OBJECT_START, NULL, 0);
  375. TRY(json_test_and_skip(f, '{'));
  376. {
  377. SET_STATE(f, f->cur - 1, ".", 1);
  378. while (json_cur(f) != '}') {
  379. TRY(json_parse_pair(f));
  380. if (json_cur(f) == ',') f->cur++;
  381. }
  382. TRY(json_test_and_skip(f, '}'));
  383. json_truncate_path(f, fstate.path_len);
  384. CALL_BACK(f, JSON_TYPE_OBJECT_END, fstate.ptr, f->cur - fstate.ptr);
  385. }
  386. return 0;
  387. }
  388. static int json_doit(struct frozen *f) {
  389. if (f->cur == 0 || f->end < f->cur) return JSON_STRING_INVALID;
  390. if (f->end == f->cur) return JSON_STRING_INCOMPLETE;
  391. return json_parse_value(f);
  392. }
  393. int json_escape(struct json_out *out, const char *p, size_t len) WEAK;
  394. int json_escape(struct json_out *out, const char *p, size_t len) {
  395. size_t i, cl, n = 0;
  396. const char *hex_digits = "0123456789abcdef";
  397. const char *specials = "btnvfr";
  398. for (i = 0; i < len; i++) {
  399. unsigned char ch = ((unsigned char *) p)[i];
  400. if (ch == '"' || ch == '\\') {
  401. n += out->printer(out, "\\", 1);
  402. n += out->printer(out, p + i, 1);
  403. } else if (ch >= '\b' && ch <= '\r') {
  404. n += out->printer(out, "\\", 1);
  405. n += out->printer(out, &specials[ch - '\b'], 1);
  406. } else if (isprint(ch)) {
  407. n += out->printer(out, p + i, 1);
  408. } else if ((cl = json_get_utf8_char_len(ch)) == 1) {
  409. n += out->printer(out, "\\u00", 4);
  410. n += out->printer(out, &hex_digits[(ch >> 4) % 0xf], 1);
  411. n += out->printer(out, &hex_digits[ch % 0xf], 1);
  412. } else {
  413. n += out->printer(out, p + i, cl);
  414. i += cl - 1;
  415. }
  416. }
  417. return n;
  418. }
  419. int json_printer_buf(struct json_out *out, const char *buf, size_t len) WEAK;
  420. int json_printer_buf(struct json_out *out, const char *buf, size_t len) {
  421. size_t avail = out->u.buf.size - out->u.buf.len;
  422. size_t n = len < avail ? len : avail;
  423. memcpy(out->u.buf.buf + out->u.buf.len, buf, n);
  424. out->u.buf.len += n;
  425. if (out->u.buf.size > 0) {
  426. size_t idx = out->u.buf.len;
  427. if (idx >= out->u.buf.size) idx = out->u.buf.size - 1;
  428. out->u.buf.buf[idx] = '\0';
  429. }
  430. return len;
  431. }
  432. int json_printer_file(struct json_out *out, const char *buf, size_t len) WEAK;
  433. int json_printer_file(struct json_out *out, const char *buf, size_t len) {
  434. return fwrite(buf, 1, len, out->u.fp);
  435. }
  436. #if JSON_ENABLE_BASE64
  437. static int b64idx(int c) {
  438. if (c < 26) {
  439. return c + 'A';
  440. } else if (c < 52) {
  441. return c - 26 + 'a';
  442. } else if (c < 62) {
  443. return c - 52 + '0';
  444. } else {
  445. return c == 62 ? '+' : '/';
  446. }
  447. }
  448. static int b64rev(int c) {
  449. if (c >= 'A' && c <= 'Z') {
  450. return c - 'A';
  451. } else if (c >= 'a' && c <= 'z') {
  452. return c + 26 - 'a';
  453. } else if (c >= '0' && c <= '9') {
  454. return c + 52 - '0';
  455. } else if (c == '+') {
  456. return 62;
  457. } else if (c == '/') {
  458. return 63;
  459. } else {
  460. return 64;
  461. }
  462. }
  463. static int b64enc(struct json_out *out, const unsigned char *p, int n) {
  464. char buf[4];
  465. int i, len = 0;
  466. for (i = 0; i < n; i += 3) {
  467. int a = p[i], b = i + 1 < n ? p[i + 1] : 0, c = i + 2 < n ? p[i + 2] : 0;
  468. buf[0] = b64idx(a >> 2);
  469. buf[1] = b64idx((a & 3) << 4 | (b >> 4));
  470. buf[2] = b64idx((b & 15) << 2 | (c >> 6));
  471. buf[3] = b64idx(c & 63);
  472. if (i + 1 >= n) buf[2] = '=';
  473. if (i + 2 >= n) buf[3] = '=';
  474. len += out->printer(out, buf, sizeof(buf));
  475. }
  476. return len;
  477. }
  478. static int b64dec(const char *src, int n, char *dst) {
  479. const char *end = src + n;
  480. int len = 0;
  481. while (src + 3 < end) {
  482. int a = b64rev(src[0]), b = b64rev(src[1]), c = b64rev(src[2]),
  483. d = b64rev(src[3]);
  484. dst[len++] = (a << 2) | (b >> 4);
  485. if (src[2] != '=') {
  486. dst[len++] = (b << 4) | (c >> 2);
  487. if (src[3] != '=') {
  488. dst[len++] = (c << 6) | d;
  489. }
  490. }
  491. src += 4;
  492. }
  493. return len;
  494. }
  495. #endif /* JSON_ENABLE_BASE64 */
  496. static unsigned char hexdec(const char *s) {
  497. #define HEXTOI(x) (x >= '0' && x <= '9' ? x - '0' : x - 'W')
  498. int a = tolower(*(const unsigned char *) s);
  499. int b = tolower(*(const unsigned char *) (s + 1));
  500. return (HEXTOI(a) << 4) | HEXTOI(b);
  501. }
  502. int json_vprintf(struct json_out *out, const char *fmt, va_list xap) WEAK;
  503. int json_vprintf(struct json_out *out, const char *fmt, va_list xap) {
  504. int len = 0;
  505. const char *quote = "\"", *null = "null";
  506. va_list ap;
  507. va_copy(ap, xap);
  508. while (*fmt != '\0') {
  509. if (strchr(":, \r\n\t[]{}\"", *fmt) != NULL) {
  510. len += out->printer(out, fmt, 1);
  511. fmt++;
  512. } else if (fmt[0] == '%') {
  513. char buf[21];
  514. size_t skip = 2;
  515. if (fmt[1] == 'l' && fmt[2] == 'l' && (fmt[3] == 'd' || fmt[3] == 'u')) {
  516. int64_t val = va_arg(ap, int64_t);
  517. const char *fmt2 = fmt[3] == 'u' ? "%" UINT64_FMT : "%" INT64_FMT;
  518. snprintf(buf, sizeof(buf), fmt2, val);
  519. len += out->printer(out, buf, strlen(buf));
  520. skip += 2;
  521. } else if (fmt[1] == 'z' && fmt[2] == 'u') {
  522. size_t val = va_arg(ap, size_t);
  523. snprintf(buf, sizeof(buf), "%lu", (unsigned long) val);
  524. len += out->printer(out, buf, strlen(buf));
  525. skip += 1;
  526. } else if (fmt[1] == 'M') {
  527. json_printf_callback_t f = va_arg(ap, json_printf_callback_t);
  528. len += f(out, &ap);
  529. } else if (fmt[1] == 'B') {
  530. int val = va_arg(ap, int);
  531. const char *str = val ? "true" : "false";
  532. len += out->printer(out, str, strlen(str));
  533. } else if (fmt[1] == 'H') {
  534. #if JSON_ENABLE_HEX
  535. const char *hex = "0123456789abcdef";
  536. int i, n = va_arg(ap, int);
  537. const unsigned char *p = va_arg(ap, const unsigned char *);
  538. len += out->printer(out, quote, 1);
  539. for (i = 0; i < n; i++) {
  540. len += out->printer(out, &hex[(p[i] >> 4) & 0xf], 1);
  541. len += out->printer(out, &hex[p[i] & 0xf], 1);
  542. }
  543. len += out->printer(out, quote, 1);
  544. #endif /* JSON_ENABLE_HEX */
  545. } else if (fmt[1] == 'V') {
  546. #if JSON_ENABLE_BASE64
  547. const unsigned char *p = va_arg(ap, const unsigned char *);
  548. int n = va_arg(ap, int);
  549. len += out->printer(out, quote, 1);
  550. len += b64enc(out, p, n);
  551. len += out->printer(out, quote, 1);
  552. #endif /* JSON_ENABLE_BASE64 */
  553. } else if (fmt[1] == 'Q' ||
  554. (fmt[1] == '.' && fmt[2] == '*' && fmt[3] == 'Q')) {
  555. size_t l = 0;
  556. const char *p;
  557. if (fmt[1] == '.') {
  558. l = (size_t) va_arg(ap, int);
  559. skip += 2;
  560. }
  561. p = va_arg(ap, char *);
  562. if (p == NULL) {
  563. len += out->printer(out, null, 4);
  564. } else {
  565. if (fmt[1] == 'Q') {
  566. l = strlen(p);
  567. }
  568. len += out->printer(out, quote, 1);
  569. len += json_escape(out, p, l);
  570. len += out->printer(out, quote, 1);
  571. }
  572. } else {
  573. /*
  574. * we delegate printing to the system printf.
  575. * The goal here is to delegate all modifiers parsing to the system
  576. * printf, as you can see below we still have to parse the format
  577. * types.
  578. *
  579. * Currently, %s with strings longer than 20 chars will require
  580. * double-buffering (an auxiliary buffer will be allocated from heap).
  581. * TODO(dfrank): reimplement %s and %.*s in order to avoid that.
  582. */
  583. const char *end_of_format_specifier = "sdfFeEgGlhuIcx.*-0123456789";
  584. int n = strspn(fmt + 1, end_of_format_specifier);
  585. char *pbuf = buf;
  586. int need_len, size = sizeof(buf);
  587. char fmt2[20];
  588. va_list ap_copy;
  589. strncpy(fmt2, fmt,
  590. n + 1 > (int) sizeof(fmt2) ? sizeof(fmt2) : (size_t) n + 1);
  591. fmt2[n + 1] = '\0';
  592. va_copy(ap_copy, ap);
  593. need_len = vsnprintf(pbuf, size, fmt2, ap_copy);
  594. va_end(ap_copy);
  595. if (need_len < 0) {
  596. /*
  597. * Windows & eCos vsnprintf implementation return -1 on overflow
  598. * instead of needed size.
  599. */
  600. pbuf = NULL;
  601. while (need_len < 0) {
  602. allocator.free(pbuf);
  603. size *= 2;
  604. if ((pbuf = (char *) allocator.alloc(size)) == NULL) break;
  605. va_copy(ap_copy, ap);
  606. need_len = vsnprintf(pbuf, size, fmt2, ap_copy);
  607. va_end(ap_copy);
  608. }
  609. } else if (need_len >= (int) sizeof(buf)) {
  610. /*
  611. * resulting string doesn't fit into a stack-allocated buffer `buf`,
  612. * so we need to allocate a new buffer from heap and use it
  613. */
  614. if ((pbuf = (char *) allocator.alloc(need_len + 1)) != NULL) {
  615. va_copy(ap_copy, ap);
  616. vsnprintf(pbuf, need_len + 1, fmt2, ap_copy);
  617. va_end(ap_copy);
  618. }
  619. }
  620. if (pbuf == NULL) {
  621. buf[0] = '\0';
  622. pbuf = buf;
  623. }
  624. /*
  625. * however we need to parse the type ourselves in order to advance
  626. * the va_list by the correct amount; there is no portable way to
  627. * inherit the advancement made by vprintf.
  628. * 32-bit (linux or windows) passes va_list by value.
  629. */
  630. if ((n + 1 == strlen("%" PRId64) && strcmp(fmt2, "%" PRId64) == 0) ||
  631. (n + 1 == strlen("%" PRIu64) && strcmp(fmt2, "%" PRIu64) == 0)) {
  632. (void) va_arg(ap, int64_t);
  633. } else if (strcmp(fmt2, "%.*s") == 0) {
  634. (void) va_arg(ap, int);
  635. (void) va_arg(ap, char *);
  636. } else {
  637. switch (fmt2[n]) {
  638. case 'u':
  639. case 'd':
  640. (void) va_arg(ap, int);
  641. break;
  642. case 'g':
  643. case 'f':
  644. (void) va_arg(ap, double);
  645. break;
  646. case 'p':
  647. (void) va_arg(ap, void *);
  648. break;
  649. default:
  650. /* many types are promoted to int */
  651. (void) va_arg(ap, int);
  652. }
  653. }
  654. len += out->printer(out, pbuf, strlen(pbuf));
  655. skip = n + 1;
  656. /* If buffer was allocated from heap, free it */
  657. if (pbuf != buf) {
  658. allocator.free(pbuf);
  659. pbuf = NULL;
  660. }
  661. }
  662. fmt += skip;
  663. } else if (*fmt == '_' || json_isalpha(*fmt)) {
  664. len += out->printer(out, quote, 1);
  665. while (*fmt == '_' || json_isalpha(*fmt) || json_isdigit(*fmt)) {
  666. len += out->printer(out, fmt, 1);
  667. fmt++;
  668. }
  669. len += out->printer(out, quote, 1);
  670. } else {
  671. len += out->printer(out, fmt, 1);
  672. fmt++;
  673. }
  674. }
  675. va_end(ap);
  676. return len;
  677. }
  678. int json_printf(struct json_out *out, const char *fmt, ...) WEAK;
  679. int json_printf(struct json_out *out, const char *fmt, ...) {
  680. int n;
  681. va_list ap;
  682. va_start(ap, fmt);
  683. n = json_vprintf(out, fmt, ap);
  684. va_end(ap);
  685. return n;
  686. }
  687. int json_printf_array(struct json_out *out, va_list *ap) WEAK;
  688. int json_printf_array(struct json_out *out, va_list *ap) {
  689. int len = 0;
  690. char *arr = va_arg(*ap, char *);
  691. size_t i, arr_size = va_arg(*ap, size_t);
  692. size_t elem_size = va_arg(*ap, size_t);
  693. const char *fmt = va_arg(*ap, char *);
  694. len += json_printf(out, "[", 1);
  695. for (i = 0; arr != NULL && i < arr_size / elem_size; i++) {
  696. union {
  697. int64_t i;
  698. double d;
  699. } val;
  700. memcpy(&val, arr + i * elem_size,
  701. elem_size > sizeof(val) ? sizeof(val) : elem_size);
  702. if (i > 0) len += json_printf(out, ", ");
  703. if (strpbrk(fmt, "efg") != NULL) {
  704. len += json_printf(out, fmt, val.d);
  705. } else {
  706. len += json_printf(out, fmt, val.i);
  707. }
  708. }
  709. len += json_printf(out, "]", 1);
  710. return len;
  711. }
  712. #ifdef _WIN32
  713. int cs_win_vsnprintf(char *str, size_t size, const char *format,
  714. va_list ap) WEAK;
  715. int cs_win_vsnprintf(char *str, size_t size, const char *format, va_list ap) {
  716. int res = _vsnprintf(str, size, format, ap);
  717. va_end(ap);
  718. if (res >= size) {
  719. str[size - 1] = '\0';
  720. }
  721. return res;
  722. }
  723. int cs_win_snprintf(char *str, size_t size, const char *format, ...) WEAK;
  724. int cs_win_snprintf(char *str, size_t size, const char *format, ...) {
  725. int res;
  726. va_list ap;
  727. va_start(ap, format);
  728. res = vsnprintf(str, size, format, ap);
  729. va_end(ap);
  730. return res;
  731. }
  732. #endif /* _WIN32 */
  733. int json_walk(const char *json_string, int json_string_length,
  734. json_walk_callback_t callback, void *callback_data) WEAK;
  735. int json_walk(const char *json_string, int json_string_length,
  736. json_walk_callback_t callback, void *callback_data) {
  737. struct frozen frozen;
  738. memset(&frozen, 0, sizeof(frozen));
  739. frozen.end = json_string + json_string_length;
  740. frozen.cur = json_string;
  741. frozen.callback_data = callback_data;
  742. frozen.callback = callback;
  743. TRY(json_doit(&frozen));
  744. return frozen.cur - json_string;
  745. }
  746. struct scan_array_info {
  747. int found;
  748. char path[JSON_MAX_PATH_LEN];
  749. struct json_token *token;
  750. };
  751. static void json_scanf_array_elem_cb(void *callback_data, const char *name,
  752. size_t name_len, const char *path,
  753. const struct json_token *token) {
  754. struct scan_array_info *info = (struct scan_array_info *) callback_data;
  755. (void) name;
  756. (void) name_len;
  757. if (strcmp(path, info->path) == 0) {
  758. *info->token = *token;
  759. info->found = 1;
  760. }
  761. }
  762. int json_scanf_array_elem(const char *s, int len, const char *path, int idx,
  763. struct json_token *token) WEAK;
  764. int json_scanf_array_elem(const char *s, int len, const char *path, int idx,
  765. struct json_token *token) {
  766. struct scan_array_info info;
  767. info.token = token;
  768. info.found = 0;
  769. memset(token, 0, sizeof(*token));
  770. snprintf(info.path, sizeof(info.path), "%s[%d]", path, idx);
  771. json_walk(s, len, json_scanf_array_elem_cb, &info);
  772. return info.found ? token->len : -1;
  773. }
  774. struct json_scanf_info {
  775. int num_conversions;
  776. char *path;
  777. const char *fmt;
  778. void *target;
  779. void *user_data;
  780. int type;
  781. };
  782. int json_unescape(const char *src, int slen, char *dst, int dlen) WEAK;
  783. int json_unescape(const char *src, int slen, char *dst, int dlen) {
  784. char *send = (char *) src + slen, *dend = dst + dlen, *orig_dst = dst, *p;
  785. const char *esc1 = "\"\\/bfnrt", *esc2 = "\"\\/\b\f\n\r\t";
  786. while (src < send) {
  787. if (*src == '\\') {
  788. if (++src >= send) return JSON_STRING_INCOMPLETE;
  789. if (*src == 'u') {
  790. if (send - src < 5) return JSON_STRING_INCOMPLETE;
  791. /* Here we go: this is a \u.... escape. Process simple one-byte chars */
  792. if (src[1] == '0' && src[2] == '0') {
  793. /* This is \u00xx character from the ASCII range */
  794. if (dst < dend) *dst = hexdec(src + 3);
  795. src += 4;
  796. } else {
  797. /* Complex \uXXXX escapes drag utf8 lib... Do it at some stage */
  798. return JSON_STRING_INVALID;
  799. }
  800. } else if ((p = (char *) strchr(esc1, *src)) != NULL) {
  801. if (dst < dend) *dst = esc2[p - esc1];
  802. } else {
  803. return JSON_STRING_INVALID;
  804. }
  805. } else {
  806. if (dst < dend) *dst = *src;
  807. }
  808. dst++;
  809. src++;
  810. }
  811. return dst - orig_dst;
  812. }
  813. static void json_scanf_cb(void *callback_data, const char *name,
  814. size_t name_len, const char *path,
  815. const struct json_token *token) {
  816. struct json_scanf_info *info = (struct json_scanf_info *) callback_data;
  817. char buf[32]; /* Must be enough to hold numbers */
  818. (void) name;
  819. (void) name_len;
  820. if (token->ptr == NULL) {
  821. /*
  822. * We're not interested here in the events for which we have no value;
  823. * namely, JSON_TYPE_OBJECT_START and JSON_TYPE_ARRAY_START
  824. */
  825. return;
  826. }
  827. if (strcmp(path, info->path) != 0) {
  828. /* It's not the path we're looking for, so, just ignore this callback */
  829. return;
  830. }
  831. switch (info->type) {
  832. case 'B':
  833. info->num_conversions++;
  834. switch (sizeof(bool)) {
  835. case sizeof(char):
  836. *(char *) info->target = (token->type == JSON_TYPE_TRUE ? 1 : 0);
  837. break;
  838. case sizeof(int):
  839. *(int *) info->target = (token->type == JSON_TYPE_TRUE ? 1 : 0);
  840. break;
  841. default:
  842. /* should never be here */
  843. abort();
  844. }
  845. break;
  846. case 'M': {
  847. union {
  848. void *p;
  849. json_scanner_t f;
  850. } u = {info->target};
  851. info->num_conversions++;
  852. u.f(token->ptr, token->len, info->user_data);
  853. break;
  854. }
  855. case 'Q': {
  856. char **dst = (char **) info->target;
  857. if (token->type == JSON_TYPE_NULL) {
  858. *dst = NULL;
  859. } else {
  860. int unescaped_len = json_unescape(token->ptr, token->len, NULL, 0);
  861. if (unescaped_len >= 0 &&
  862. (*dst = (char *) allocator.alloc(unescaped_len + 1)) != NULL) {
  863. info->num_conversions++;
  864. if (json_unescape(token->ptr, token->len, *dst, unescaped_len) ==
  865. unescaped_len) {
  866. (*dst)[unescaped_len] = '\0';
  867. } else {
  868. allocator.free(*dst);
  869. *dst = NULL;
  870. }
  871. }
  872. }
  873. break;
  874. }
  875. case 'H': {
  876. #if JSON_ENABLE_HEX
  877. char **dst = (char **) info->user_data;
  878. int i, len = token->len / 2;
  879. *(int *) info->target = len;
  880. if ((*dst = (char *) allocator.alloc(len + 1)) != NULL) {
  881. for (i = 0; i < len; i++) {
  882. (*dst)[i] = hexdec(token->ptr + 2 * i);
  883. }
  884. (*dst)[len] = '\0';
  885. info->num_conversions++;
  886. }
  887. #endif /* JSON_ENABLE_HEX */
  888. break;
  889. }
  890. case 'V': {
  891. #if JSON_ENABLE_BASE64
  892. char **dst = (char **) info->target;
  893. int len = token->len * 4 / 3 + 2;
  894. if ((*dst = (char *) allocator.alloc(len + 1)) != NULL) {
  895. int n = b64dec(token->ptr, token->len, *dst);
  896. (*dst)[n] = '\0';
  897. *(int *) info->user_data = n;
  898. info->num_conversions++;
  899. }
  900. #endif /* JSON_ENABLE_BASE64 */
  901. break;
  902. }
  903. case 'T':
  904. info->num_conversions++;
  905. *(struct json_token *) info->target = *token;
  906. break;
  907. default:
  908. if (token->len >= (int) sizeof(buf)) break;
  909. /* Before converting, copy into tmp buffer in order to 0-terminate it */
  910. memcpy(buf, token->ptr, token->len);
  911. buf[token->len] = '\0';
  912. /* NB: Use of base 0 for %d, %ld, %u and %lu is intentional. */
  913. if (info->fmt[1] == 'd' || (info->fmt[1] == 'l' && info->fmt[2] == 'd') ||
  914. info->fmt[1] == 'i') {
  915. char *endptr = NULL;
  916. long r = strtol(buf, &endptr, 0 /* base */);
  917. if (*endptr == '\0') {
  918. if (info->fmt[1] == 'l') {
  919. *((long *) info->target) = r;
  920. } else {
  921. *((int *) info->target) = (int) r;
  922. }
  923. info->num_conversions++;
  924. }
  925. } else if (info->fmt[1] == 'u' ||
  926. (info->fmt[1] == 'l' && info->fmt[2] == 'u')) {
  927. char *endptr = NULL;
  928. unsigned long r = strtoul(buf, &endptr, 0 /* base */);
  929. if (*endptr == '\0') {
  930. if (info->fmt[1] == 'l') {
  931. *((unsigned long *) info->target) = r;
  932. } else {
  933. *((unsigned int *) info->target) = (unsigned int) r;
  934. }
  935. info->num_conversions++;
  936. }
  937. } else {
  938. #if !JSON_MINIMAL
  939. info->num_conversions += sscanf(buf, info->fmt, info->target);
  940. #endif
  941. }
  942. break;
  943. }
  944. }
  945. int json_vscanf(const char *s, int len, const char *fmt, va_list ap) WEAK;
  946. int json_vscanf(const char *s, int len, const char *fmt, va_list ap) {
  947. char path[JSON_MAX_PATH_LEN] = "", fmtbuf[20];
  948. int i = 0;
  949. char *p = NULL;
  950. struct json_scanf_info info = {0, path, fmtbuf, NULL, NULL, 0};
  951. while (fmt[i] != '\0') {
  952. if (fmt[i] == '{') {
  953. strcat(path, ".");
  954. i++;
  955. } else if (fmt[i] == '}') {
  956. if ((p = strrchr(path, '.')) != NULL) *p = '\0';
  957. i++;
  958. } else if (fmt[i] == '%') {
  959. info.target = va_arg(ap, void *);
  960. info.type = fmt[i + 1];
  961. switch (fmt[i + 1]) {
  962. case 'M':
  963. case 'V':
  964. case 'H':
  965. info.user_data = va_arg(ap, void *);
  966. /* FALLTHROUGH */
  967. case 'B':
  968. case 'Q':
  969. case 'T':
  970. i += 2;
  971. break;
  972. default: {
  973. const char *delims = ", \t\r\n]}";
  974. int conv_len = strcspn(fmt + i + 1, delims) + 1;
  975. memcpy(fmtbuf, fmt + i, conv_len);
  976. fmtbuf[conv_len] = '\0';
  977. i += conv_len;
  978. i += strspn(fmt + i, delims);
  979. break;
  980. }
  981. }
  982. json_walk(s, len, json_scanf_cb, &info);
  983. } else if (json_isalpha(fmt[i]) || json_get_utf8_char_len(fmt[i]) > 1) {
  984. char *pe;
  985. const char *delims = ": \r\n\t";
  986. int key_len = strcspn(&fmt[i], delims);
  987. if ((p = strrchr(path, '.')) != NULL) p[1] = '\0';
  988. pe = path + strlen(path);
  989. memcpy(pe, fmt + i, key_len);
  990. pe[key_len] = '\0';
  991. i += key_len + strspn(fmt + i + key_len, delims);
  992. } else {
  993. i++;
  994. }
  995. }
  996. return info.num_conversions;
  997. }
  998. int json_scanf(const char *str, int len, const char *fmt, ...) WEAK;
  999. int json_scanf(const char *str, int len, const char *fmt, ...) {
  1000. int result;
  1001. va_list ap;
  1002. va_start(ap, fmt);
  1003. result = json_vscanf(str, len, fmt, ap);
  1004. va_end(ap);
  1005. return result;
  1006. }
  1007. int json_vfprintf(const char *file_name, const char *fmt, va_list ap) WEAK;
  1008. int json_vfprintf(const char *file_name, const char *fmt, va_list ap) {
  1009. int res = -1;
  1010. FILE *fp = fopen(file_name, "wb");
  1011. if (fp != NULL) {
  1012. struct json_out out = JSON_OUT_FILE(fp);
  1013. res = json_vprintf(&out, fmt, ap);
  1014. fputc('\n', fp);
  1015. fclose(fp);
  1016. }
  1017. return res;
  1018. }
  1019. int json_fprintf(const char *file_name, const char *fmt, ...) WEAK;
  1020. int json_fprintf(const char *file_name, const char *fmt, ...) {
  1021. int result;
  1022. va_list ap;
  1023. va_start(ap, fmt);
  1024. result = json_vfprintf(file_name, fmt, ap);
  1025. va_end(ap);
  1026. return result;
  1027. }
  1028. char *json_fread(const char *path) WEAK;
  1029. char *json_fread(const char *path) {
  1030. FILE *fp;
  1031. char *data = NULL;
  1032. if ((fp = fopen(path, "rb")) == NULL) {
  1033. } else if (fseek(fp, 0, SEEK_END) != 0) {
  1034. fclose(fp);
  1035. } else {
  1036. long size = ftell(fp);
  1037. if (size > 0 && (data = (char *) allocator.alloc(size + 1)) != NULL) {
  1038. fseek(fp, 0, SEEK_SET); /* Some platforms might not have rewind(), Oo */
  1039. if (fread(data, 1, size, fp) != (size_t) size) {
  1040. allocator.free(data);
  1041. data = NULL;
  1042. } else {
  1043. data[size] = '\0';
  1044. }
  1045. }
  1046. fclose(fp);
  1047. }
  1048. return data;
  1049. }
  1050. struct json_setf_data {
  1051. const char *json_path;
  1052. const char *base; /* Pointer to the source JSON string */
  1053. int matched; /* Matched part of json_path */
  1054. int pos; /* Offset of the mutated value begin */
  1055. int end; /* Offset of the mutated value end */
  1056. int prev; /* Offset of the previous token end */
  1057. };
  1058. static int get_matched_prefix_len(const char *s1, const char *s2) {
  1059. int i = 0;
  1060. while (s1[i] && s2[i] && s1[i] == s2[i]) i++;
  1061. return i;
  1062. }
  1063. static void json_vsetf_cb(void *userdata, const char *name, size_t name_len,
  1064. const char *path, const struct json_token *t) {
  1065. struct json_setf_data *data = (struct json_setf_data *) userdata;
  1066. int off, len = get_matched_prefix_len(path, data->json_path);
  1067. if (t->ptr == NULL) return;
  1068. off = t->ptr - data->base;
  1069. if (len > data->matched) data->matched = len;
  1070. /*
  1071. * If there is no exact path match, set the mutation position to tbe end
  1072. * of the object or array
  1073. */
  1074. if (len < data->matched && data->pos == 0 &&
  1075. (t->type == JSON_TYPE_OBJECT_END || t->type == JSON_TYPE_ARRAY_END)) {
  1076. data->pos = data->end = data->prev;
  1077. }
  1078. /* Exact path match. Set mutation position to the value of this token */
  1079. if (strcmp(path, data->json_path) == 0 && t->type != JSON_TYPE_OBJECT_START &&
  1080. t->type != JSON_TYPE_ARRAY_START) {
  1081. data->pos = off;
  1082. data->end = off + t->len;
  1083. }
  1084. /*
  1085. * For deletion, we need to know where the previous value ends, because
  1086. * we don't know where matched value key starts.
  1087. * When the mutation position is not yet set, remember each value end.
  1088. * When the mutation position is already set, but it is at the beginning
  1089. * of the object/array, we catch the end of the object/array and see
  1090. * whether the object/array start is closer then previously stored prev.
  1091. */
  1092. if (data->pos == 0) {
  1093. data->prev = off + t->len; /* pos is not yet set */
  1094. } else if ((t->ptr[0] == '[' || t->ptr[0] == '{') && off + 1 < data->pos &&
  1095. off + 1 > data->prev) {
  1096. data->prev = off + 1;
  1097. }
  1098. (void) name;
  1099. (void) name_len;
  1100. }
  1101. int json_vsetf(const char *s, int len, struct json_out *out,
  1102. const char *json_path, const char *json_fmt, va_list ap) WEAK;
  1103. int json_vsetf(const char *s, int len, struct json_out *out,
  1104. const char *json_path, const char *json_fmt, va_list ap) {
  1105. struct json_setf_data data;
  1106. memset(&data, 0, sizeof(data));
  1107. data.json_path = json_path;
  1108. data.base = s;
  1109. data.end = len;
  1110. json_walk(s, len, json_vsetf_cb, &data);
  1111. if (json_fmt == NULL) {
  1112. /* Deletion codepath */
  1113. json_printf(out, "%.*s", data.prev, s);
  1114. /* Trim comma after the value that begins at object/array start */
  1115. if (s[data.prev - 1] == '{' || s[data.prev - 1] == '[') {
  1116. int i = data.end;
  1117. while (i < len && json_isspace(s[i])) i++;
  1118. if (s[i] == ',') data.end = i + 1; /* Point after comma */
  1119. }
  1120. json_printf(out, "%.*s", len - data.end, s + data.end);
  1121. } else {
  1122. /* Modification codepath */
  1123. int n, off = data.matched, depth = 0;
  1124. /* Print the unchanged beginning */
  1125. json_printf(out, "%.*s", data.pos, s);
  1126. /* Add missing keys */
  1127. while ((n = strcspn(&json_path[off], ".[")) > 0) {
  1128. if (s[data.prev - 1] != '{' && s[data.prev - 1] != '[' && depth == 0) {
  1129. json_printf(out, ",");
  1130. }
  1131. if (off > 0 && json_path[off - 1] != '.') break;
  1132. json_printf(out, "%.*Q:", n, json_path + off);
  1133. off += n;
  1134. if (json_path[off] != '\0') {
  1135. json_printf(out, "%c", json_path[off] == '.' ? '{' : '[');
  1136. depth++;
  1137. off++;
  1138. }
  1139. }
  1140. /* Print the new value */
  1141. json_vprintf(out, json_fmt, ap);
  1142. /* Close brackets/braces of the added missing keys */
  1143. for (; off > data.matched; off--) {
  1144. int ch = json_path[off];
  1145. const char *p = ch == '.' ? "}" : ch == '[' ? "]" : "";
  1146. json_printf(out, "%s", p);
  1147. }
  1148. /* Print the rest of the unchanged string */
  1149. json_printf(out, "%.*s", len - data.end, s + data.end);
  1150. }
  1151. return data.end > data.pos ? 1 : 0;
  1152. }
  1153. int json_setf(const char *s, int len, struct json_out *out,
  1154. const char *json_path, const char *json_fmt, ...) WEAK;
  1155. int json_setf(const char *s, int len, struct json_out *out,
  1156. const char *json_path, const char *json_fmt, ...) {
  1157. int result;
  1158. va_list ap;
  1159. va_start(ap, json_fmt);
  1160. result = json_vsetf(s, len, out, json_path, json_fmt, ap);
  1161. va_end(ap);
  1162. return result;
  1163. }
  1164. struct prettify_data {
  1165. struct json_out *out;
  1166. int level;
  1167. int last_token;
  1168. };
  1169. static void indent(struct json_out *out, int level) {
  1170. while (level-- > 0) out->printer(out, " ", 2);
  1171. }
  1172. static void print_key(struct prettify_data *pd, const char *path,
  1173. const char *name, int name_len) {
  1174. if (pd->last_token != JSON_TYPE_INVALID &&
  1175. pd->last_token != JSON_TYPE_ARRAY_START &&
  1176. pd->last_token != JSON_TYPE_OBJECT_START) {
  1177. pd->out->printer(pd->out, ",", 1);
  1178. }
  1179. if (path[0] != '\0') pd->out->printer(pd->out, "\n", 1);
  1180. indent(pd->out, pd->level);
  1181. if (path[0] != '\0' && path[strlen(path) - 1] != ']') {
  1182. pd->out->printer(pd->out, "\"", 1);
  1183. pd->out->printer(pd->out, name, (int) name_len);
  1184. pd->out->printer(pd->out, "\"", 1);
  1185. pd->out->printer(pd->out, ": ", 2);
  1186. }
  1187. }
  1188. static void prettify_cb(void *userdata, const char *name, size_t name_len,
  1189. const char *path, const struct json_token *t) {
  1190. struct prettify_data *pd = (struct prettify_data *) userdata;
  1191. switch (t->type) {
  1192. case JSON_TYPE_OBJECT_START:
  1193. case JSON_TYPE_ARRAY_START:
  1194. print_key(pd, path, name, name_len);
  1195. pd->out->printer(pd->out, t->type == JSON_TYPE_ARRAY_START ? "[" : "{",
  1196. 1);
  1197. pd->level++;
  1198. break;
  1199. case JSON_TYPE_OBJECT_END:
  1200. case JSON_TYPE_ARRAY_END:
  1201. pd->level--;
  1202. if (pd->last_token != JSON_TYPE_INVALID &&
  1203. pd->last_token != JSON_TYPE_ARRAY_START &&
  1204. pd->last_token != JSON_TYPE_OBJECT_START) {
  1205. pd->out->printer(pd->out, "\n", 1);
  1206. indent(pd->out, pd->level);
  1207. }
  1208. pd->out->printer(pd->out, t->type == JSON_TYPE_ARRAY_END ? "]" : "}", 1);
  1209. break;
  1210. case JSON_TYPE_NUMBER:
  1211. case JSON_TYPE_NULL:
  1212. case JSON_TYPE_TRUE:
  1213. case JSON_TYPE_FALSE:
  1214. case JSON_TYPE_STRING:
  1215. print_key(pd, path, name, name_len);
  1216. if (t->type == JSON_TYPE_STRING) pd->out->printer(pd->out, "\"", 1);
  1217. pd->out->printer(pd->out, t->ptr, t->len);
  1218. if (t->type == JSON_TYPE_STRING) pd->out->printer(pd->out, "\"", 1);
  1219. break;
  1220. default:
  1221. break;
  1222. }
  1223. pd->last_token = t->type;
  1224. }
  1225. int json_prettify(const char *s, int len, struct json_out *out) WEAK;
  1226. int json_prettify(const char *s, int len, struct json_out *out) {
  1227. struct prettify_data pd = {out, 0, JSON_TYPE_INVALID};
  1228. return json_walk(s, len, prettify_cb, &pd);
  1229. }
  1230. int json_prettify_file(const char *file_name) WEAK;
  1231. int json_prettify_file(const char *file_name) {
  1232. int res = -1;
  1233. char *s = json_fread(file_name);
  1234. FILE *fp;
  1235. if (s != NULL && (fp = fopen(file_name, "wb")) != NULL) {
  1236. struct json_out out = JSON_OUT_FILE(fp);
  1237. res = json_prettify(s, strlen(s), &out);
  1238. if (res < 0) {
  1239. /* On error, restore the old content */
  1240. fclose(fp);
  1241. fp = fopen(file_name, "wb");
  1242. fseek(fp, 0, SEEK_SET);
  1243. fwrite(s, 1, strlen(s), fp);
  1244. } else {
  1245. fputc('\n', fp);
  1246. }
  1247. fclose(fp);
  1248. }
  1249. allocator.free(s);
  1250. return res;
  1251. }
  1252. struct next_data {
  1253. void *handle; // Passed handle. Changed if a next entry is found
  1254. const char *path; // Path to the iterated object/array
  1255. int path_len; // Path length - optimisation
  1256. int found; // Non-0 if found the next entry
  1257. struct json_token *key; // Object's key
  1258. struct json_token *val; // Object's value
  1259. int *idx; // Array index
  1260. };
  1261. static void next_set_key(struct next_data *d, const char *name, int name_len,
  1262. int is_array) {
  1263. if (is_array) {
  1264. /* Array. Set index and reset key */
  1265. if (d->key != NULL) {
  1266. d->key->len = 0;
  1267. d->key->ptr = NULL;
  1268. }
  1269. if (d->idx != NULL) *d->idx = atoi(name);
  1270. } else {
  1271. /* Object. Set key and make index -1 */
  1272. if (d->key != NULL) {
  1273. d->key->ptr = name;
  1274. d->key->len = name_len;
  1275. }
  1276. if (d->idx != NULL) *d->idx = -1;
  1277. }
  1278. }
  1279. static void json_next_cb(void *userdata, const char *name, size_t name_len,
  1280. const char *path, const struct json_token *t) {
  1281. struct next_data *d = (struct next_data *) userdata;
  1282. const char *p = path + d->path_len;
  1283. if (d->found) return;
  1284. if (d->path_len >= (int) strlen(path)) return;
  1285. if (strncmp(d->path, path, d->path_len) != 0) return;
  1286. if (strchr(p + 1, '.') != NULL) return; /* More nested objects - skip */
  1287. if (strchr(p + 1, '[') != NULL) return; /* Ditto for arrays */
  1288. // {OBJECT,ARRAY}_END types do not pass name, _START does. Save key.
  1289. if (t->type == JSON_TYPE_OBJECT_START || t->type == JSON_TYPE_ARRAY_START) {
  1290. next_set_key(d, name, name_len, p[0] == '[');
  1291. } else if (d->handle == NULL || d->handle < (void *) t->ptr) {
  1292. if (t->type != JSON_TYPE_OBJECT_END && t->type != JSON_TYPE_ARRAY_END) {
  1293. next_set_key(d, name, name_len, p[0] == '[');
  1294. }
  1295. if (d->val != NULL) *d->val = *t;
  1296. d->handle = (void *) t->ptr;
  1297. d->found = 1;
  1298. }
  1299. }
  1300. static void *json_next(const char *s, int len, void *handle, const char *path,
  1301. struct json_token *key, struct json_token *val, int *i) {
  1302. struct json_token tmpval, *v = val == NULL ? &tmpval : val;
  1303. struct json_token tmpkey, *k = key == NULL ? &tmpkey : key;
  1304. int tmpidx, *pidx = i == NULL ? &tmpidx : i;
  1305. struct next_data data = {handle, path, (int) strlen(path), 0, k, v, pidx};
  1306. json_walk(s, len, json_next_cb, &data);
  1307. return data.found ? data.handle : NULL;
  1308. }
  1309. void *json_next_key(const char *s, int len, void *handle, const char *path,
  1310. struct json_token *key, struct json_token *val) WEAK;
  1311. void *json_next_key(const char *s, int len, void *handle, const char *path,
  1312. struct json_token *key, struct json_token *val) {
  1313. return json_next(s, len, handle, path, key, val, NULL);
  1314. }
  1315. void *json_next_elem(const char *s, int len, void *handle, const char *path,
  1316. int *idx, struct json_token *val) WEAK;
  1317. void *json_next_elem(const char *s, int len, void *handle, const char *path,
  1318. int *idx, struct json_token *val) {
  1319. return json_next(s, len, handle, path, NULL, val, idx);
  1320. }
  1321. static int json_sprinter(struct json_out *out, const char *str, size_t len) {
  1322. trace_assert(0 && "Reimplement this garbage without realloc");
  1323. size_t old_len = out->u.buf.buf == NULL ? 0 : strlen(out->u.buf.buf);
  1324. size_t new_len = len + old_len;
  1325. char *p = (char *) realloc(out->u.buf.buf, new_len + 1);
  1326. if (p != NULL) {
  1327. memcpy(p + old_len, str, len);
  1328. p[new_len] = '\0';
  1329. out->u.buf.buf = p;
  1330. }
  1331. return len;
  1332. }
  1333. char *json_vasprintf(const char *fmt, va_list ap) WEAK;
  1334. char *json_vasprintf(const char *fmt, va_list ap) {
  1335. struct json_out out;
  1336. memset(&out, 0, sizeof(out));
  1337. out.printer = json_sprinter;
  1338. json_vprintf(&out, fmt, ap);
  1339. return out.u.buf.buf;
  1340. }
  1341. char *json_asprintf(const char *fmt, ...) WEAK;
  1342. char *json_asprintf(const char *fmt, ...) {
  1343. char *result = NULL;
  1344. va_list ap;
  1345. va_start(ap, fmt);
  1346. result = json_vasprintf(fmt, ap);
  1347. va_end(ap);
  1348. return result;
  1349. }