jsmn.c 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753
  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. // print amount of tokens
  450. FURI_LOG_I("JSMM.H", "Amount of tokens: %d", ret);
  451. // Ensure that the root element is an object
  452. if (ret < 1 || tokens[0].type != JSMN_OBJECT)
  453. {
  454. FURI_LOG_E("JSMM.H", "Root element is not an object.");
  455. free(tokens);
  456. return NULL;
  457. }
  458. // Loop through the tokens to find the key
  459. for (int i = 1; i < ret; i++)
  460. {
  461. if (jsoneq(json_data, &tokens[i], key) == 0)
  462. {
  463. // We found the key. Now, return the associated value.
  464. int length = tokens[i + 1].end - tokens[i + 1].start;
  465. char *value = malloc(length + 1);
  466. if (value == NULL)
  467. {
  468. FURI_LOG_E("JSMM.H", "Failed to allocate memory for value.");
  469. free(tokens);
  470. return NULL;
  471. }
  472. strncpy(value, json_data + tokens[i + 1].start, length);
  473. value[length] = '\0'; // Null-terminate the string
  474. free(tokens); // Free the token array
  475. return value; // Return the extracted value
  476. }
  477. }
  478. // Free the token array if key was not found
  479. free(tokens);
  480. }
  481. else
  482. {
  483. FURI_LOG_E("JSMM.H", "JSON data is NULL");
  484. }
  485. FURI_LOG_E("JSMM.H", "Failed to find the key in the JSON.");
  486. return NULL; // Return NULL if something goes wrong
  487. }
  488. // Revised get_json_array_value function
  489. char *get_json_array_value(char *key, uint32_t index, char *json_data, uint32_t max_tokens)
  490. {
  491. // Retrieve the array string for the given key
  492. char *array_str = get_json_value(key, json_data, max_tokens);
  493. if (array_str == NULL)
  494. {
  495. FURI_LOG_E("JSMM.H", "Failed to get array for key: %s", key);
  496. return NULL;
  497. }
  498. // Initialize the JSON parser
  499. jsmn_parser parser;
  500. jsmn_init(&parser);
  501. // Allocate memory for JSON tokens
  502. jsmntok_t *tokens = malloc(sizeof(jsmntok_t) * max_tokens);
  503. if (tokens == NULL)
  504. {
  505. FURI_LOG_E("JSMM.H", "Failed to allocate memory for JSON tokens.");
  506. free(array_str);
  507. return NULL;
  508. }
  509. // Parse the JSON array
  510. int ret = jsmn_parse(&parser, array_str, strlen(array_str), tokens, max_tokens);
  511. if (ret < 0)
  512. {
  513. FURI_LOG_E("JSMM.H", "Failed to parse JSON array: %d", ret);
  514. free(tokens);
  515. free(array_str);
  516. return NULL;
  517. }
  518. // print amount of tokens
  519. FURI_LOG_I("JSMM.H", "Amount of tokens: %d", ret);
  520. // Ensure the root element is an array
  521. if (ret < 1 || tokens[0].type != JSMN_ARRAY)
  522. {
  523. FURI_LOG_E("JSMM.H", "Value for key '%s' is not an array.", key);
  524. free(tokens);
  525. free(array_str);
  526. return NULL;
  527. }
  528. // Check if the index is within bounds
  529. if (index >= (uint32_t)tokens[0].size)
  530. {
  531. FURI_LOG_E("JSMM.H", "Index %lu out of bounds for array with size %d.", (unsigned long)index, tokens[0].size);
  532. free(tokens);
  533. free(array_str);
  534. return NULL;
  535. }
  536. // Locate the token corresponding to the desired array element
  537. int current_token = 1; // Start after the array token
  538. for (uint32_t i = 0; i < index; i++)
  539. {
  540. if (tokens[current_token].type == JSMN_OBJECT)
  541. {
  542. // For objects, skip all key-value pairs
  543. current_token += 1 + 2 * tokens[current_token].size;
  544. }
  545. else if (tokens[current_token].type == JSMN_ARRAY)
  546. {
  547. // For nested arrays, skip all elements
  548. current_token += 1 + tokens[current_token].size;
  549. }
  550. else
  551. {
  552. // For primitive types, simply move to the next token
  553. current_token += 1;
  554. }
  555. // Safety check to prevent out-of-bounds
  556. if (current_token >= ret)
  557. {
  558. FURI_LOG_E("JSMM.H", "Unexpected end of tokens while traversing array.");
  559. free(tokens);
  560. free(array_str);
  561. return NULL;
  562. }
  563. }
  564. // Extract the array element
  565. jsmntok_t element = tokens[current_token];
  566. int length = element.end - element.start;
  567. char *value = malloc(length + 1);
  568. if (value == NULL)
  569. {
  570. FURI_LOG_E("JSMM.H", "Failed to allocate memory for array element.");
  571. free(tokens);
  572. free(array_str);
  573. return NULL;
  574. }
  575. // Copy the element value to a new string
  576. strncpy(value, array_str + element.start, length);
  577. value[length] = '\0'; // Null-terminate the string
  578. // Clean up
  579. free(tokens);
  580. free(array_str);
  581. return value;
  582. }
  583. // Revised get_json_array_values function with correct token skipping
  584. char **get_json_array_values(char *key, char *json_data, uint32_t max_tokens, int *num_values)
  585. {
  586. // Retrieve the array string for the given key
  587. char *array_str = get_json_value(key, json_data, max_tokens);
  588. if (array_str == NULL)
  589. {
  590. FURI_LOG_E("JSMM.H", "Failed to get array for key: %s", key);
  591. return NULL;
  592. }
  593. // Initialize the JSON parser
  594. jsmn_parser parser;
  595. jsmn_init(&parser);
  596. // Allocate memory for JSON tokens
  597. jsmntok_t *tokens = malloc(sizeof(jsmntok_t) * max_tokens); // Allocate on the heap
  598. if (tokens == NULL)
  599. {
  600. FURI_LOG_E("JSMM.H", "Failed to allocate memory for JSON tokens.");
  601. free(array_str);
  602. return NULL;
  603. }
  604. // Parse the JSON array
  605. int ret = jsmn_parse(&parser, array_str, strlen(array_str), tokens, max_tokens);
  606. if (ret < 0)
  607. {
  608. FURI_LOG_E("JSMM.H", "Failed to parse JSON array: %d", ret);
  609. free(tokens);
  610. free(array_str);
  611. return NULL;
  612. }
  613. // Ensure the root element is an array
  614. if (tokens[0].type != JSMN_ARRAY)
  615. {
  616. FURI_LOG_E("JSMM.H", "Value for key '%s' is not an array.", key);
  617. free(tokens);
  618. free(array_str);
  619. return NULL;
  620. }
  621. // Allocate memory for the array of values (maximum possible)
  622. int array_size = tokens[0].size;
  623. char **values = malloc(array_size * sizeof(char *));
  624. if (values == NULL)
  625. {
  626. FURI_LOG_E("JSMM.H", "Failed to allocate memory for array of values.");
  627. free(tokens);
  628. free(array_str);
  629. return NULL;
  630. }
  631. int actual_num_values = 0;
  632. // Traverse the array and extract all object values
  633. int current_token = 1; // Start after the array token
  634. for (int i = 0; i < array_size; i++)
  635. {
  636. if (current_token >= ret)
  637. {
  638. FURI_LOG_E("JSMM.H", "Unexpected end of tokens while traversing array.");
  639. break;
  640. }
  641. jsmntok_t element = tokens[current_token];
  642. if (element.type != JSMN_OBJECT)
  643. {
  644. FURI_LOG_E("JSMM.H", "Array element %d is not an object, skipping.", i);
  645. // Skip this element
  646. current_token += 1;
  647. continue;
  648. }
  649. int length = element.end - element.start;
  650. // Allocate a new string for the value and copy the data
  651. char *value = malloc(length + 1);
  652. if (value == NULL)
  653. {
  654. FURI_LOG_E("JSMM.H", "Failed to allocate memory for array element.");
  655. for (int j = 0; j < actual_num_values; j++)
  656. {
  657. free(values[j]);
  658. }
  659. free(values);
  660. free(tokens);
  661. free(array_str);
  662. return NULL;
  663. }
  664. strncpy(value, array_str + element.start, length);
  665. value[length] = '\0'; // Null-terminate the string
  666. values[actual_num_values] = value;
  667. actual_num_values++;
  668. // Skip all tokens related to this object to avoid misparsing
  669. current_token += 1 + (2 * element.size); // Each key-value pair consumes two tokens
  670. }
  671. *num_values = actual_num_values;
  672. // Reallocate the values array to actual_num_values if necessary
  673. if (actual_num_values < array_size)
  674. {
  675. char **reduced_values = realloc(values, actual_num_values * sizeof(char *));
  676. if (reduced_values != NULL)
  677. {
  678. values = reduced_values;
  679. }
  680. // Free the remaining values
  681. for (int i = actual_num_values; i < array_size; i++)
  682. {
  683. free(values[i]);
  684. }
  685. }
  686. // Clean up
  687. free(tokens);
  688. free(array_str);
  689. return values;
  690. }