jsmn.c 20 KB

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