jsmn.c 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747
  1. /*
  2. * MIT License
  3. *
  4. * Copyright (c) 2010 Serge Zaitsev
  5. *
  6. * [License text continues...]
  7. */
  8. #include <jsmn/jsmn.h>
  9. #include <stdlib.h>
  10. #include <string.h>
  11. /**
  12. * Allocates a fresh unused token from the token pool.
  13. */
  14. static jsmntok_t *jsmn_alloc_token(jsmn_parser *parser, jsmntok_t *tokens,
  15. const size_t num_tokens)
  16. {
  17. jsmntok_t *tok;
  18. if (parser->toknext >= num_tokens)
  19. {
  20. return NULL;
  21. }
  22. tok = &tokens[parser->toknext++];
  23. tok->start = tok->end = -1;
  24. tok->size = 0;
  25. #ifdef JSMN_PARENT_LINKS
  26. tok->parent = -1;
  27. #endif
  28. return tok;
  29. }
  30. /**
  31. * Fills token type and boundaries.
  32. */
  33. static void jsmn_fill_token(jsmntok_t *token, const jsmntype_t type,
  34. const int start, const int end)
  35. {
  36. token->type = type;
  37. token->start = start;
  38. token->end = end;
  39. token->size = 0;
  40. }
  41. /**
  42. * Fills next available token with JSON primitive.
  43. */
  44. static int jsmn_parse_primitive(jsmn_parser *parser, const char *js,
  45. const size_t len, jsmntok_t *tokens,
  46. const size_t num_tokens)
  47. {
  48. jsmntok_t *token;
  49. int start;
  50. start = parser->pos;
  51. for (; parser->pos < len && js[parser->pos] != '\0'; parser->pos++)
  52. {
  53. switch (js[parser->pos])
  54. {
  55. #ifndef JSMN_STRICT
  56. /* In strict mode primitive must be followed by "," or "}" or "]" */
  57. case ':':
  58. #endif
  59. case '\t':
  60. case '\r':
  61. case '\n':
  62. case ' ':
  63. case ',':
  64. case ']':
  65. case '}':
  66. goto found;
  67. default:
  68. /* to quiet a warning from gcc*/
  69. break;
  70. }
  71. if (js[parser->pos] < 32 || js[parser->pos] >= 127)
  72. {
  73. parser->pos = start;
  74. return JSMN_ERROR_INVAL;
  75. }
  76. }
  77. #ifdef JSMN_STRICT
  78. /* In strict mode primitive must be followed by a comma/object/array */
  79. parser->pos = start;
  80. return JSMN_ERROR_PART;
  81. #endif
  82. found:
  83. if (tokens == NULL)
  84. {
  85. parser->pos--;
  86. return 0;
  87. }
  88. token = jsmn_alloc_token(parser, tokens, num_tokens);
  89. if (token == NULL)
  90. {
  91. parser->pos = start;
  92. return JSMN_ERROR_NOMEM;
  93. }
  94. jsmn_fill_token(token, JSMN_PRIMITIVE, start, parser->pos);
  95. #ifdef JSMN_PARENT_LINKS
  96. token->parent = parser->toksuper;
  97. #endif
  98. parser->pos--;
  99. return 0;
  100. }
  101. /**
  102. * Fills next token with JSON string.
  103. */
  104. static int jsmn_parse_string(jsmn_parser *parser, const char *js,
  105. const size_t len, jsmntok_t *tokens,
  106. const size_t num_tokens)
  107. {
  108. jsmntok_t *token;
  109. int start = parser->pos;
  110. /* Skip starting quote */
  111. parser->pos++;
  112. for (; parser->pos < len && js[parser->pos] != '\0'; parser->pos++)
  113. {
  114. char c = js[parser->pos];
  115. /* Quote: end of string */
  116. if (c == '\"')
  117. {
  118. if (tokens == NULL)
  119. {
  120. return 0;
  121. }
  122. token = jsmn_alloc_token(parser, tokens, num_tokens);
  123. if (token == NULL)
  124. {
  125. parser->pos = start;
  126. return JSMN_ERROR_NOMEM;
  127. }
  128. jsmn_fill_token(token, JSMN_STRING, start + 1, parser->pos);
  129. #ifdef JSMN_PARENT_LINKS
  130. token->parent = parser->toksuper;
  131. #endif
  132. return 0;
  133. }
  134. /* Backslash: Quoted symbol expected */
  135. if (c == '\\' && parser->pos + 1 < len)
  136. {
  137. int i;
  138. parser->pos++;
  139. switch (js[parser->pos])
  140. {
  141. /* Allowed escaped symbols */
  142. case '\"':
  143. case '/':
  144. case '\\':
  145. case 'b':
  146. case 'f':
  147. case 'r':
  148. case 'n':
  149. case 't':
  150. break;
  151. /* Allows escaped symbol \uXXXX */
  152. case 'u':
  153. parser->pos++;
  154. for (i = 0; i < 4 && parser->pos < len && js[parser->pos] != '\0'; i++)
  155. {
  156. /* If it isn't a hex character we have an error */
  157. if (!((js[parser->pos] >= 48 && js[parser->pos] <= 57) || /* 0-9 */
  158. (js[parser->pos] >= 65 && js[parser->pos] <= 70) || /* A-F */
  159. (js[parser->pos] >= 97 && js[parser->pos] <= 102)))
  160. { /* a-f */
  161. parser->pos = start;
  162. return JSMN_ERROR_INVAL;
  163. }
  164. parser->pos++;
  165. }
  166. parser->pos--;
  167. break;
  168. /* Unexpected symbol */
  169. default:
  170. parser->pos = start;
  171. return JSMN_ERROR_INVAL;
  172. }
  173. }
  174. }
  175. parser->pos = start;
  176. return JSMN_ERROR_PART;
  177. }
  178. /**
  179. * Create JSON parser over an array of tokens
  180. */
  181. void jsmn_init(jsmn_parser *parser)
  182. {
  183. parser->pos = 0;
  184. parser->toknext = 0;
  185. parser->toksuper = -1;
  186. }
  187. /**
  188. * Parse JSON string and fill tokens.
  189. */
  190. int jsmn_parse(jsmn_parser *parser, const char *js, const size_t len,
  191. jsmntok_t *tokens, const unsigned int num_tokens)
  192. {
  193. int r;
  194. int i;
  195. jsmntok_t *token;
  196. int count = parser->toknext;
  197. for (; parser->pos < len && js[parser->pos] != '\0'; parser->pos++)
  198. {
  199. char c;
  200. jsmntype_t type;
  201. c = js[parser->pos];
  202. switch (c)
  203. {
  204. case '{':
  205. case '[':
  206. count++;
  207. if (tokens == NULL)
  208. {
  209. break;
  210. }
  211. token = jsmn_alloc_token(parser, tokens, num_tokens);
  212. if (token == NULL)
  213. {
  214. return JSMN_ERROR_NOMEM;
  215. }
  216. if (parser->toksuper != -1)
  217. {
  218. jsmntok_t *t = &tokens[parser->toksuper];
  219. #ifdef JSMN_STRICT
  220. /* In strict mode an object or array can't become a key */
  221. if (t->type == JSMN_OBJECT)
  222. {
  223. return JSMN_ERROR_INVAL;
  224. }
  225. #endif
  226. t->size++;
  227. #ifdef JSMN_PARENT_LINKS
  228. token->parent = parser->toksuper;
  229. #endif
  230. }
  231. token->type = (c == '{' ? JSMN_OBJECT : JSMN_ARRAY);
  232. token->start = parser->pos;
  233. parser->toksuper = parser->toknext - 1;
  234. break;
  235. case '}':
  236. case ']':
  237. if (tokens == NULL)
  238. {
  239. break;
  240. }
  241. type = (c == '}' ? JSMN_OBJECT : JSMN_ARRAY);
  242. #ifdef JSMN_PARENT_LINKS
  243. if (parser->toknext < 1)
  244. {
  245. return JSMN_ERROR_INVAL;
  246. }
  247. token = &tokens[parser->toknext - 1];
  248. for (;;)
  249. {
  250. if (token->start != -1 && token->end == -1)
  251. {
  252. if (token->type != type)
  253. {
  254. return JSMN_ERROR_INVAL;
  255. }
  256. token->end = parser->pos + 1;
  257. parser->toksuper = token->parent;
  258. break;
  259. }
  260. if (token->parent == -1)
  261. {
  262. if (token->type != type || parser->toksuper == -1)
  263. {
  264. return JSMN_ERROR_INVAL;
  265. }
  266. break;
  267. }
  268. token = &tokens[token->parent];
  269. }
  270. #else
  271. for (i = parser->toknext - 1; i >= 0; i--)
  272. {
  273. token = &tokens[i];
  274. if (token->start != -1 && token->end == -1)
  275. {
  276. if (token->type != type)
  277. {
  278. return JSMN_ERROR_INVAL;
  279. }
  280. parser->toksuper = -1;
  281. token->end = parser->pos + 1;
  282. break;
  283. }
  284. }
  285. /* Error if unmatched closing bracket */
  286. if (i == -1)
  287. {
  288. return JSMN_ERROR_INVAL;
  289. }
  290. for (; i >= 0; i--)
  291. {
  292. token = &tokens[i];
  293. if (token->start != -1 && token->end == -1)
  294. {
  295. parser->toksuper = i;
  296. break;
  297. }
  298. }
  299. #endif
  300. break;
  301. case '\"':
  302. r = jsmn_parse_string(parser, js, len, tokens, num_tokens);
  303. if (r < 0)
  304. {
  305. return r;
  306. }
  307. count++;
  308. if (parser->toksuper != -1 && tokens != NULL)
  309. {
  310. tokens[parser->toksuper].size++;
  311. }
  312. break;
  313. case '\t':
  314. case '\r':
  315. case '\n':
  316. case ' ':
  317. break;
  318. case ':':
  319. parser->toksuper = parser->toknext - 1;
  320. break;
  321. case ',':
  322. if (tokens != NULL && parser->toksuper != -1 &&
  323. tokens[parser->toksuper].type != JSMN_ARRAY &&
  324. tokens[parser->toksuper].type != JSMN_OBJECT)
  325. {
  326. #ifdef JSMN_PARENT_LINKS
  327. parser->toksuper = tokens[parser->toksuper].parent;
  328. #else
  329. for (i = parser->toknext - 1; i >= 0; i--)
  330. {
  331. if (tokens[i].type == JSMN_ARRAY || tokens[i].type == JSMN_OBJECT)
  332. {
  333. if (tokens[i].start != -1 && tokens[i].end == -1)
  334. {
  335. parser->toksuper = i;
  336. break;
  337. }
  338. }
  339. }
  340. #endif
  341. }
  342. break;
  343. #ifdef JSMN_STRICT
  344. /* In strict mode primitives are: numbers and booleans */
  345. case '-':
  346. case '0':
  347. case '1':
  348. case '2':
  349. case '3':
  350. case '4':
  351. case '5':
  352. case '6':
  353. case '7':
  354. case '8':
  355. case '9':
  356. case 't':
  357. case 'f':
  358. case 'n':
  359. /* And they must not be keys of the object */
  360. if (tokens != NULL && parser->toksuper != -1)
  361. {
  362. const jsmntok_t *t = &tokens[parser->toksuper];
  363. if (t->type == JSMN_OBJECT ||
  364. (t->type == JSMN_STRING && t->size != 0))
  365. {
  366. return JSMN_ERROR_INVAL;
  367. }
  368. }
  369. #else
  370. /* In non-strict mode every unquoted value is a primitive */
  371. default:
  372. #endif
  373. r = jsmn_parse_primitive(parser, js, len, tokens, num_tokens);
  374. if (r < 0)
  375. {
  376. return r;
  377. }
  378. count++;
  379. if (parser->toksuper != -1 && tokens != NULL)
  380. {
  381. tokens[parser->toksuper].size++;
  382. }
  383. break;
  384. #ifdef JSMN_STRICT
  385. /* Unexpected char in strict mode */
  386. default:
  387. return JSMN_ERROR_INVAL;
  388. #endif
  389. }
  390. }
  391. if (tokens != NULL)
  392. {
  393. for (i = parser->toknext - 1; i >= 0; i--)
  394. {
  395. /* Unmatched opened object or array */
  396. if (tokens[i].start != -1 && tokens[i].end == -1)
  397. {
  398. return JSMN_ERROR_PART;
  399. }
  400. }
  401. }
  402. return count;
  403. }
  404. // Helper function to create a JSON object
  405. char *jsmn(const char *key, const char *value)
  406. {
  407. int length = strlen(key) + strlen(value) + 8; // Calculate required length
  408. char *result = (char *)malloc(length * sizeof(char)); // Allocate memory
  409. if (result == NULL)
  410. {
  411. return NULL; // Handle memory allocation failure
  412. }
  413. snprintf(result, length, "{\"%s\":\"%s\"}", key, value);
  414. return result; // Caller is responsible for freeing this memory
  415. }
  416. // Helper function to compare JSON keys
  417. int jsoneq(const char *json, jsmntok_t *tok, const char *s)
  418. {
  419. if (tok->type == JSMN_STRING && (int)strlen(s) == tok->end - tok->start &&
  420. strncmp(json + tok->start, s, tok->end - tok->start) == 0)
  421. {
  422. return 0;
  423. }
  424. return -1;
  425. }
  426. // Return the value of the key in the JSON data
  427. char *get_json_value(char *key, char *json_data, uint32_t max_tokens)
  428. {
  429. // Parse the JSON feed
  430. if (json_data != NULL)
  431. {
  432. jsmn_parser parser;
  433. jsmn_init(&parser);
  434. // Allocate tokens array on the heap
  435. jsmntok_t *tokens = malloc(sizeof(jsmntok_t) * max_tokens);
  436. if (tokens == NULL)
  437. {
  438. FURI_LOG_E("JSMM.H", "Failed to allocate memory for JSON tokens.");
  439. return NULL;
  440. }
  441. int ret = jsmn_parse(&parser, json_data, strlen(json_data), tokens, max_tokens);
  442. if (ret < 0)
  443. {
  444. // Handle parsing errors
  445. FURI_LOG_E("JSMM.H", "Failed to parse JSON: %d", ret);
  446. free(tokens);
  447. return NULL;
  448. }
  449. // Ensure that the root element is an object
  450. if (ret < 1 || tokens[0].type != JSMN_OBJECT)
  451. {
  452. FURI_LOG_E("JSMM.H", "Root element is not an object.");
  453. free(tokens);
  454. return NULL;
  455. }
  456. // Loop through the tokens to find the key
  457. for (int i = 1; i < ret; i++)
  458. {
  459. if (jsoneq(json_data, &tokens[i], key) == 0)
  460. {
  461. // We found the key. Now, return the associated value.
  462. int length = tokens[i + 1].end - tokens[i + 1].start;
  463. char *value = malloc(length + 1);
  464. if (value == NULL)
  465. {
  466. FURI_LOG_E("JSMM.H", "Failed to allocate memory for value.");
  467. free(tokens);
  468. return NULL;
  469. }
  470. strncpy(value, json_data + tokens[i + 1].start, length);
  471. value[length] = '\0'; // Null-terminate the string
  472. free(tokens); // Free the token array
  473. return value; // Return the extracted value
  474. }
  475. }
  476. // Free the token array if key was not found
  477. free(tokens);
  478. }
  479. else
  480. {
  481. FURI_LOG_E("JSMM.H", "JSON data is NULL");
  482. }
  483. FURI_LOG_E("JSMM.H", "Failed to find the key in the JSON.");
  484. return NULL; // Return NULL if something goes wrong
  485. }
  486. // Revised get_json_array_value function
  487. char *get_json_array_value(char *key, uint32_t index, char *json_data, uint32_t max_tokens)
  488. {
  489. // Retrieve the array string for the given key
  490. char *array_str = get_json_value(key, json_data, max_tokens);
  491. if (array_str == NULL)
  492. {
  493. FURI_LOG_E("JSMM.H", "Failed to get array for key: %s", key);
  494. return NULL;
  495. }
  496. // Initialize the JSON parser
  497. jsmn_parser parser;
  498. jsmn_init(&parser);
  499. // Allocate memory for JSON tokens
  500. jsmntok_t *tokens = malloc(sizeof(jsmntok_t) * max_tokens);
  501. if (tokens == NULL)
  502. {
  503. FURI_LOG_E("JSMM.H", "Failed to allocate memory for JSON tokens.");
  504. free(array_str);
  505. return NULL;
  506. }
  507. // Parse the JSON array
  508. int ret = jsmn_parse(&parser, array_str, strlen(array_str), tokens, max_tokens);
  509. if (ret < 0)
  510. {
  511. FURI_LOG_E("JSMM.H", "Failed to parse JSON array: %d", ret);
  512. free(tokens);
  513. free(array_str);
  514. return NULL;
  515. }
  516. // Ensure the root element is an array
  517. if (ret < 1 || tokens[0].type != JSMN_ARRAY)
  518. {
  519. FURI_LOG_E("JSMM.H", "Value for key '%s' is not an array.", key);
  520. free(tokens);
  521. free(array_str);
  522. return NULL;
  523. }
  524. // Check if the index is within bounds
  525. if (index >= (uint32_t)tokens[0].size)
  526. {
  527. FURI_LOG_E("JSMM.H", "Index %lu out of bounds for array with size %d.", (unsigned long)index, tokens[0].size);
  528. free(tokens);
  529. free(array_str);
  530. return NULL;
  531. }
  532. // Locate the token corresponding to the desired array element
  533. int current_token = 1; // Start after the array token
  534. for (uint32_t i = 0; i < index; i++)
  535. {
  536. if (tokens[current_token].type == JSMN_OBJECT)
  537. {
  538. // For objects, skip all key-value pairs
  539. current_token += 1 + 2 * tokens[current_token].size;
  540. }
  541. else if (tokens[current_token].type == JSMN_ARRAY)
  542. {
  543. // For nested arrays, skip all elements
  544. current_token += 1 + tokens[current_token].size;
  545. }
  546. else
  547. {
  548. // For primitive types, simply move to the next token
  549. current_token += 1;
  550. }
  551. // Safety check to prevent out-of-bounds
  552. if (current_token >= ret)
  553. {
  554. FURI_LOG_E("JSMM.H", "Unexpected end of tokens while traversing array.");
  555. free(tokens);
  556. free(array_str);
  557. return NULL;
  558. }
  559. }
  560. // Extract the array element
  561. jsmntok_t element = tokens[current_token];
  562. int length = element.end - element.start;
  563. char *value = malloc(length + 1);
  564. if (value == NULL)
  565. {
  566. FURI_LOG_E("JSMM.H", "Failed to allocate memory for array element.");
  567. free(tokens);
  568. free(array_str);
  569. return NULL;
  570. }
  571. // Copy the element value to a new string
  572. strncpy(value, array_str + element.start, length);
  573. value[length] = '\0'; // Null-terminate the string
  574. // Clean up
  575. free(tokens);
  576. free(array_str);
  577. return value;
  578. }
  579. // Revised get_json_array_values function with correct token skipping
  580. char **get_json_array_values(char *key, char *json_data, uint32_t max_tokens, int *num_values)
  581. {
  582. // Retrieve the array string for the given key
  583. char *array_str = get_json_value(key, json_data, max_tokens);
  584. if (array_str == NULL)
  585. {
  586. FURI_LOG_E("JSMM.H", "Failed to get array for key: %s", key);
  587. return NULL;
  588. }
  589. // Initialize the JSON parser
  590. jsmn_parser parser;
  591. jsmn_init(&parser);
  592. // Allocate memory for JSON tokens
  593. jsmntok_t *tokens = malloc(sizeof(jsmntok_t) * max_tokens); // Allocate on the heap
  594. if (tokens == NULL)
  595. {
  596. FURI_LOG_E("JSMM.H", "Failed to allocate memory for JSON tokens.");
  597. free(array_str);
  598. return NULL;
  599. }
  600. // Parse the JSON array
  601. int ret = jsmn_parse(&parser, array_str, strlen(array_str), tokens, max_tokens);
  602. if (ret < 0)
  603. {
  604. FURI_LOG_E("JSMM.H", "Failed to parse JSON array: %d", ret);
  605. free(tokens);
  606. free(array_str);
  607. return NULL;
  608. }
  609. // Ensure the root element is an array
  610. if (tokens[0].type != JSMN_ARRAY)
  611. {
  612. FURI_LOG_E("JSMM.H", "Value for key '%s' is not an array.", key);
  613. free(tokens);
  614. free(array_str);
  615. return NULL;
  616. }
  617. // Allocate memory for the array of values (maximum possible)
  618. int array_size = tokens[0].size;
  619. char **values = malloc(array_size * sizeof(char *));
  620. if (values == NULL)
  621. {
  622. FURI_LOG_E("JSMM.H", "Failed to allocate memory for array of values.");
  623. free(tokens);
  624. free(array_str);
  625. return NULL;
  626. }
  627. int actual_num_values = 0;
  628. // Traverse the array and extract all object values
  629. int current_token = 1; // Start after the array token
  630. for (int i = 0; i < array_size; i++)
  631. {
  632. if (current_token >= ret)
  633. {
  634. FURI_LOG_E("JSMM.H", "Unexpected end of tokens while traversing array.");
  635. break;
  636. }
  637. jsmntok_t element = tokens[current_token];
  638. if (element.type != JSMN_OBJECT)
  639. {
  640. FURI_LOG_E("JSMM.H", "Array element %d is not an object, skipping.", i);
  641. // Skip this element
  642. current_token += 1;
  643. continue;
  644. }
  645. int length = element.end - element.start;
  646. // Allocate a new string for the value and copy the data
  647. char *value = malloc(length + 1);
  648. if (value == NULL)
  649. {
  650. FURI_LOG_E("JSMM.H", "Failed to allocate memory for array element.");
  651. for (int j = 0; j < actual_num_values; j++)
  652. {
  653. free(values[j]);
  654. }
  655. free(values);
  656. free(tokens);
  657. free(array_str);
  658. return NULL;
  659. }
  660. strncpy(value, array_str + element.start, length);
  661. value[length] = '\0'; // Null-terminate the string
  662. values[actual_num_values] = value;
  663. actual_num_values++;
  664. // Skip all tokens related to this object to avoid misparsing
  665. current_token += 1 + (2 * element.size); // Each key-value pair consumes two tokens
  666. }
  667. *num_values = actual_num_values;
  668. // Reallocate the values array to actual_num_values if necessary
  669. if (actual_num_values < array_size)
  670. {
  671. char **reduced_values = realloc(values, actual_num_values * sizeof(char *));
  672. if (reduced_values != NULL)
  673. {
  674. values = reduced_values;
  675. }
  676. // Free the remaining values
  677. for (int i = actual_num_values; i < array_size; i++)
  678. {
  679. free(values[i]);
  680. }
  681. }
  682. // Clean up
  683. free(tokens);
  684. free(array_str);
  685. return values;
  686. }