frozen.c 44 KB

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