lua_cjson.c 41 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462
  1. /* Lua CJSON - JSON support for Lua
  2. *
  3. * Copyright (c) 2010-2012 Mark Pulford <mark@kyne.com.au>
  4. *
  5. * Permission is hereby granted, free of charge, to any person obtaining
  6. * a copy of this software and associated documentation files (the
  7. * "Software"), to deal in the Software without restriction, including
  8. * without limitation the rights to use, copy, modify, merge, publish,
  9. * distribute, sublicense, and/or sell copies of the Software, and to
  10. * permit persons to whom the Software is furnished to do so, subject to
  11. * the following conditions:
  12. *
  13. * The above copyright notice and this permission notice shall be
  14. * included in all copies or substantial portions of the Software.
  15. *
  16. * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
  17. * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
  18. * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
  19. * IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
  20. * CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
  21. * TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
  22. * SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
  23. */
  24. /* Caveats:
  25. * - JSON "null" values are represented as lightuserdata since Lua
  26. * tables cannot contain "nil". Compare with cjson.null.
  27. * - Invalid UTF-8 characters are not detected and will be passed
  28. * untouched. If required, UTF-8 error checking should be done
  29. * outside this library.
  30. * - Javascript comments are not part of the JSON spec, and are not
  31. * currently supported.
  32. *
  33. * Note: Decoding is slower than encoding. Lua spends significant
  34. * time (30%) managing tables when parsing JSON since it is
  35. * difficult to know object/array sizes ahead of time.
  36. */
  37. #include <assert.h>
  38. #include <string.h>
  39. #include <math.h>
  40. #include <limits.h>
  41. #include <lua.h>
  42. #include <lauxlib.h>
  43. #include <stdbool.h>
  44. #include "strbuf.h"
  45. #include "fpconv.h"
  46. #ifndef CJSON_MODNAME
  47. #define CJSON_MODNAME "cjson"
  48. #endif
  49. #ifndef CJSON_VERSION
  50. #define CJSON_VERSION "2.1devel"
  51. #endif
  52. /* Workaround for Solaris platforms missing isinf() */
  53. #if !defined(isinf) && (defined(USE_INTERNAL_ISINF) || defined(MISSING_ISINF))
  54. #define isinf(x) (!isnan(x) && isnan((x) - (x)))
  55. #endif
  56. #define DEFAULT_SPARSE_CONVERT 0
  57. #define DEFAULT_SPARSE_RATIO 2
  58. #define DEFAULT_SPARSE_SAFE 10
  59. #define DEFAULT_ENCODE_MAX_DEPTH 1000
  60. #define DEFAULT_DECODE_MAX_DEPTH 1000
  61. #define DEFAULT_ENCODE_INVALID_NUMBERS 0
  62. #define DEFAULT_DECODE_INVALID_NUMBERS 1
  63. #define DEFAULT_ENCODE_KEEP_BUFFER 1
  64. #define DEFAULT_ENCODE_NUMBER_PRECISION 14
  65. #ifdef DISABLE_INVALID_NUMBERS
  66. #undef DEFAULT_DECODE_INVALID_NUMBERS
  67. #define DEFAULT_DECODE_INVALID_NUMBERS 0
  68. #endif
  69. typedef enum {
  70. T_OBJ_BEGIN,
  71. T_OBJ_END,
  72. T_ARR_BEGIN,
  73. T_ARR_END,
  74. T_STRING,
  75. T_NUMBER,
  76. T_INTEGER,
  77. T_BOOLEAN,
  78. T_NULL,
  79. T_COLON,
  80. T_COMMA,
  81. T_END,
  82. T_WHITESPACE,
  83. T_ERROR,
  84. T_UNKNOWN
  85. } json_token_type_t;
  86. static const char *json_token_type_name[] = {
  87. "T_OBJ_BEGIN",
  88. "T_OBJ_END",
  89. "T_ARR_BEGIN",
  90. "T_ARR_END",
  91. "T_STRING",
  92. "T_NUMBER",
  93. "T_INTEGER",
  94. "T_BOOLEAN",
  95. "T_NULL",
  96. "T_COLON",
  97. "T_COMMA",
  98. "T_END",
  99. "T_WHITESPACE",
  100. "T_ERROR",
  101. "T_UNKNOWN",
  102. NULL
  103. };
  104. typedef struct {
  105. json_token_type_t ch2token[256];
  106. char escape2char[256]; /* Decoding */
  107. /* encode_buf is only allocated and used when
  108. * encode_keep_buffer is set */
  109. strbuf_t encode_buf;
  110. int encode_sparse_convert;
  111. int encode_sparse_ratio;
  112. int encode_sparse_safe;
  113. int encode_max_depth;
  114. int encode_invalid_numbers; /* 2 => Encode as "null" */
  115. int encode_number_precision;
  116. int encode_keep_buffer;
  117. int decode_invalid_numbers;
  118. int decode_max_depth;
  119. } json_config_t;
  120. typedef struct {
  121. const char *data;
  122. const char *ptr;
  123. strbuf_t *tmp; /* Temporary storage for strings */
  124. json_config_t *cfg;
  125. int current_depth;
  126. } json_parse_t;
  127. typedef struct {
  128. json_token_type_t type;
  129. int index;
  130. union {
  131. const char *string;
  132. double number;
  133. int boolean;
  134. int integer;
  135. } value;
  136. int string_len;
  137. } json_token_t;
  138. static const char *char2escape[256] = {
  139. "\\u0000", "\\u0001", "\\u0002", "\\u0003",
  140. "\\u0004", "\\u0005", "\\u0006", "\\u0007",
  141. "\\b", "\\t", "\\n", "\\u000b",
  142. "\\f", "\\r", "\\u000e", "\\u000f",
  143. "\\u0010", "\\u0011", "\\u0012", "\\u0013",
  144. "\\u0014", "\\u0015", "\\u0016", "\\u0017",
  145. "\\u0018", "\\u0019", "\\u001a", "\\u001b",
  146. "\\u001c", "\\u001d", "\\u001e", "\\u001f",
  147. NULL, NULL, "\\\"", NULL, NULL, NULL, NULL, NULL,
  148. NULL, NULL, NULL, NULL, NULL, NULL, NULL, "\\/",
  149. NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL,
  150. NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL,
  151. NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL,
  152. NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL,
  153. NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL,
  154. NULL, NULL, NULL, NULL, "\\\\", NULL, NULL, NULL,
  155. NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL,
  156. NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL,
  157. NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL,
  158. NULL, NULL, NULL, NULL, NULL, NULL, NULL, "\\u007f",
  159. NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL,
  160. NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL,
  161. NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL,
  162. NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL,
  163. NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL,
  164. NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL,
  165. NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL,
  166. NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL,
  167. NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL,
  168. NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL,
  169. NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL,
  170. NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL,
  171. NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL,
  172. NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL,
  173. NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL,
  174. NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL,
  175. };
  176. /* ===== CONFIGURATION ===== */
  177. static json_config_t *json_fetch_config(lua_State *l)
  178. {
  179. json_config_t *cfg;
  180. cfg = lua_touserdata(l, lua_upvalueindex(1));
  181. if (!cfg)
  182. luaL_error(l, "BUG: Unable to fetch CJSON configuration");
  183. return cfg;
  184. }
  185. /* Ensure the correct number of arguments have been provided.
  186. * Pad with nil to allow other functions to simply check arg[i]
  187. * to find whether an argument was provided */
  188. static json_config_t *json_arg_init(lua_State *l, int args)
  189. {
  190. luaL_argcheck(l, lua_gettop(l) <= args, args + 1,
  191. "found too many arguments");
  192. while (lua_gettop(l) < args)
  193. lua_pushnil(l);
  194. return json_fetch_config(l);
  195. }
  196. /* Process integer options for configuration functions */
  197. static int json_integer_option(lua_State *l, int optindex, int *setting,
  198. int min, int max)
  199. {
  200. char errmsg[64];
  201. int value;
  202. if (!lua_isnil(l, optindex)) {
  203. value = luaL_checkinteger(l, optindex);
  204. snprintf(errmsg, sizeof(errmsg), "expected integer between %d and %d", min, max);
  205. luaL_argcheck(l, min <= value && value <= max, 1, errmsg);
  206. *setting = value;
  207. }
  208. lua_pushinteger(l, *setting);
  209. return 1;
  210. }
  211. /* Process enumerated arguments for a configuration function */
  212. static int json_enum_option(lua_State *l, int optindex, int *setting,
  213. const char **options, int bool_true)
  214. {
  215. static const char *bool_options[] = { "off", "on", NULL };
  216. if (!options) {
  217. options = bool_options;
  218. bool_true = 1;
  219. }
  220. if (!lua_isnil(l, optindex)) {
  221. if (bool_true && lua_isboolean(l, optindex))
  222. *setting = lua_toboolean(l, optindex) * bool_true;
  223. else
  224. *setting = luaL_checkoption(l, optindex, NULL, options);
  225. }
  226. if (bool_true && (*setting == 0 || *setting == bool_true))
  227. lua_pushboolean(l, *setting);
  228. else
  229. lua_pushstring(l, options[*setting]);
  230. return 1;
  231. }
  232. /* Configures handling of extremely sparse arrays:
  233. * convert: Convert extremely sparse arrays into objects? Otherwise error.
  234. * ratio: 0: always allow sparse; 1: never allow sparse; >1: use ratio
  235. * safe: Always use an array when the max index <= safe */
  236. static int json_cfg_encode_sparse_array(lua_State *l)
  237. {
  238. json_config_t *cfg = json_arg_init(l, 3);
  239. json_enum_option(l, 1, &cfg->encode_sparse_convert, NULL, 1);
  240. json_integer_option(l, 2, &cfg->encode_sparse_ratio, 0, INT_MAX);
  241. json_integer_option(l, 3, &cfg->encode_sparse_safe, 0, INT_MAX);
  242. return 3;
  243. }
  244. /* Configures the maximum number of nested arrays/objects allowed when
  245. * encoding */
  246. static int json_cfg_encode_max_depth(lua_State *l)
  247. {
  248. json_config_t *cfg = json_arg_init(l, 1);
  249. return json_integer_option(l, 1, &cfg->encode_max_depth, 1, INT_MAX);
  250. }
  251. /* Configures the maximum number of nested arrays/objects allowed when
  252. * encoding */
  253. static int json_cfg_decode_max_depth(lua_State *l)
  254. {
  255. json_config_t *cfg = json_arg_init(l, 1);
  256. return json_integer_option(l, 1, &cfg->decode_max_depth, 1, INT_MAX);
  257. }
  258. /* Configures number precision when converting doubles to text */
  259. static int json_cfg_encode_number_precision(lua_State *l)
  260. {
  261. json_config_t *cfg = json_arg_init(l, 1);
  262. return json_integer_option(l, 1, &cfg->encode_number_precision, 1, 14);
  263. }
  264. /* Configures JSON encoding buffer persistence */
  265. static int json_cfg_encode_keep_buffer(lua_State *l)
  266. {
  267. json_config_t *cfg = json_arg_init(l, 1);
  268. int old_value;
  269. old_value = cfg->encode_keep_buffer;
  270. json_enum_option(l, 1, &cfg->encode_keep_buffer, NULL, 1);
  271. /* Init / free the buffer if the setting has changed */
  272. if (old_value ^ cfg->encode_keep_buffer) {
  273. if (cfg->encode_keep_buffer)
  274. strbuf_init(&cfg->encode_buf, 0);
  275. else
  276. strbuf_free(&cfg->encode_buf);
  277. }
  278. return 1;
  279. }
  280. #if defined(DISABLE_INVALID_NUMBERS) && !defined(USE_INTERNAL_FPCONV)
  281. void json_verify_invalid_number_setting(lua_State *l, int *setting)
  282. {
  283. if (*setting == 1) {
  284. *setting = 0;
  285. luaL_error(l, "Infinity, NaN, and/or hexadecimal numbers are not supported.");
  286. }
  287. }
  288. #else
  289. #define json_verify_invalid_number_setting(l, s) do { } while(0)
  290. #endif
  291. static int json_cfg_encode_invalid_numbers(lua_State *l)
  292. {
  293. static const char *options[] = { "off", "on", "null", NULL };
  294. json_config_t *cfg = json_arg_init(l, 1);
  295. json_enum_option(l, 1, &cfg->encode_invalid_numbers, options, 1);
  296. json_verify_invalid_number_setting(l, &cfg->encode_invalid_numbers);
  297. return 1;
  298. }
  299. static int json_cfg_decode_invalid_numbers(lua_State *l)
  300. {
  301. json_config_t *cfg = json_arg_init(l, 1);
  302. json_enum_option(l, 1, &cfg->decode_invalid_numbers, NULL, 1);
  303. json_verify_invalid_number_setting(l, &cfg->encode_invalid_numbers);
  304. return 1;
  305. }
  306. static int json_destroy_config(lua_State *l)
  307. {
  308. json_config_t *cfg;
  309. cfg = lua_touserdata(l, 1);
  310. if (cfg)
  311. strbuf_free(&cfg->encode_buf);
  312. cfg = NULL;
  313. return 0;
  314. }
  315. static void json_create_config(lua_State *l)
  316. {
  317. json_config_t *cfg;
  318. int i;
  319. cfg = lua_newuserdata(l, sizeof(*cfg));
  320. /* Create GC method to clean up strbuf */
  321. lua_newtable(l);
  322. lua_pushcfunction(l, json_destroy_config);
  323. lua_setfield(l, -2, "__gc");
  324. lua_setmetatable(l, -2);
  325. cfg->encode_sparse_convert = DEFAULT_SPARSE_CONVERT;
  326. cfg->encode_sparse_ratio = DEFAULT_SPARSE_RATIO;
  327. cfg->encode_sparse_safe = DEFAULT_SPARSE_SAFE;
  328. cfg->encode_max_depth = DEFAULT_ENCODE_MAX_DEPTH;
  329. cfg->decode_max_depth = DEFAULT_DECODE_MAX_DEPTH;
  330. cfg->encode_invalid_numbers = DEFAULT_ENCODE_INVALID_NUMBERS;
  331. cfg->decode_invalid_numbers = DEFAULT_DECODE_INVALID_NUMBERS;
  332. cfg->encode_keep_buffer = DEFAULT_ENCODE_KEEP_BUFFER;
  333. cfg->encode_number_precision = DEFAULT_ENCODE_NUMBER_PRECISION;
  334. #if DEFAULT_ENCODE_KEEP_BUFFER > 0
  335. strbuf_init(&cfg->encode_buf, 0);
  336. #endif
  337. /* Decoding init */
  338. /* Tag all characters as an error */
  339. for (i = 0; i < 256; i++)
  340. cfg->ch2token[i] = T_ERROR;
  341. /* Set tokens that require no further processing */
  342. cfg->ch2token['{'] = T_OBJ_BEGIN;
  343. cfg->ch2token['}'] = T_OBJ_END;
  344. cfg->ch2token['['] = T_ARR_BEGIN;
  345. cfg->ch2token[']'] = T_ARR_END;
  346. cfg->ch2token[','] = T_COMMA;
  347. cfg->ch2token[':'] = T_COLON;
  348. cfg->ch2token['\0'] = T_END;
  349. cfg->ch2token[' '] = T_WHITESPACE;
  350. cfg->ch2token['\t'] = T_WHITESPACE;
  351. cfg->ch2token['\n'] = T_WHITESPACE;
  352. cfg->ch2token['\r'] = T_WHITESPACE;
  353. /* Update characters that require further processing */
  354. cfg->ch2token['f'] = T_UNKNOWN; /* false? */
  355. cfg->ch2token['i'] = T_UNKNOWN; /* inf, ininity? */
  356. cfg->ch2token['I'] = T_UNKNOWN;
  357. cfg->ch2token['n'] = T_UNKNOWN; /* null, nan? */
  358. cfg->ch2token['N'] = T_UNKNOWN;
  359. cfg->ch2token['t'] = T_UNKNOWN; /* true? */
  360. cfg->ch2token['"'] = T_UNKNOWN; /* string? */
  361. cfg->ch2token['+'] = T_UNKNOWN; /* number? */
  362. cfg->ch2token['-'] = T_UNKNOWN;
  363. for (i = 0; i < 10; i++)
  364. cfg->ch2token['0' + i] = T_UNKNOWN;
  365. /* Lookup table for parsing escape characters */
  366. for (i = 0; i < 256; i++)
  367. cfg->escape2char[i] = 0; /* String error */
  368. cfg->escape2char['"'] = '"';
  369. cfg->escape2char['\\'] = '\\';
  370. cfg->escape2char['/'] = '/';
  371. cfg->escape2char['b'] = '\b';
  372. cfg->escape2char['t'] = '\t';
  373. cfg->escape2char['n'] = '\n';
  374. cfg->escape2char['f'] = '\f';
  375. cfg->escape2char['r'] = '\r';
  376. cfg->escape2char['u'] = 'u'; /* Unicode parsing required */
  377. }
  378. /* ===== ENCODING ===== */
  379. static void json_encode_exception(lua_State *l, json_config_t *cfg, strbuf_t *json, int lindex,
  380. const char *reason)
  381. {
  382. if (!cfg->encode_keep_buffer)
  383. strbuf_free(json);
  384. luaL_error(l, "Cannot serialise %s: %s",
  385. lua_typename(l, lua_type(l, lindex)), reason);
  386. }
  387. /* json_append_string args:
  388. * - lua_State
  389. * - JSON strbuf
  390. * - String (Lua stack index)
  391. *
  392. * Returns nothing. Doesn't remove string from Lua stack */
  393. static void json_append_string(lua_State *l, strbuf_t *json, int lindex)
  394. {
  395. const char *escstr;
  396. int i;
  397. const char *str;
  398. size_t len;
  399. str = lua_tolstring(l, lindex, &len);
  400. /* Worst case is len * 6 (all unicode escapes).
  401. * This buffer is reused constantly for small strings
  402. * If there are any excess pages, they won't be hit anyway.
  403. * This gains ~5% speedup. */
  404. strbuf_ensure_empty_length(json, len * 6 + 2);
  405. strbuf_append_char_unsafe(json, '\"');
  406. for (i = 0; i < len; i++) {
  407. escstr = char2escape[(unsigned char)str[i]];
  408. if (escstr)
  409. strbuf_append_string(json, escstr);
  410. else
  411. strbuf_append_char_unsafe(json, str[i]);
  412. }
  413. strbuf_append_char_unsafe(json, '\"');
  414. }
  415. /* Find the size of the array on the top of the Lua stack
  416. * -1 object (not a pure array)
  417. * >=0 elements in array
  418. */
  419. static int lua_array_length(lua_State *l, json_config_t *cfg, strbuf_t *json)
  420. {
  421. double k;
  422. int max;
  423. int items;
  424. max = 0;
  425. items = 0;
  426. lua_pushnil(l);
  427. /* table, startkey */
  428. while (lua_next(l, -2) != 0) {
  429. /* table, key, value */
  430. if (lua_type(l, -2) == LUA_TNUMBER &&
  431. (k = lua_tonumber(l, -2))) {
  432. /* Integer >= 1 ? */
  433. if (floor(k) == k && k >= 1) {
  434. if (k > max)
  435. max = k;
  436. items++;
  437. lua_pop(l, 1);
  438. continue;
  439. }
  440. }
  441. /* Must not be an array (non integer key) */
  442. lua_pop(l, 2);
  443. return -1;
  444. }
  445. /* Encode excessively sparse arrays as objects (if enabled) */
  446. if (cfg->encode_sparse_ratio > 0 &&
  447. max > items * cfg->encode_sparse_ratio &&
  448. max > cfg->encode_sparse_safe) {
  449. if (!cfg->encode_sparse_convert)
  450. json_encode_exception(l, cfg, json, -1, "excessively sparse array");
  451. return -1;
  452. }
  453. return max;
  454. }
  455. static void json_check_encode_depth(lua_State *l, json_config_t *cfg,
  456. int current_depth, strbuf_t *json)
  457. {
  458. /* Ensure there are enough slots free to traverse a table (key,
  459. * value) and push a string for a potential error message.
  460. *
  461. * Unlike "decode", the key and value are still on the stack when
  462. * lua_checkstack() is called. Hence an extra slot for luaL_error()
  463. * below is required just in case the next check to lua_checkstack()
  464. * fails.
  465. *
  466. * While this won't cause a crash due to the EXTRA_STACK reserve
  467. * slots, it would still be an improper use of the API. */
  468. if (current_depth <= cfg->encode_max_depth && lua_checkstack(l, 3))
  469. return;
  470. if (!cfg->encode_keep_buffer)
  471. strbuf_free(json);
  472. luaL_error(l, "Cannot serialise, excessive nesting (%d)",
  473. current_depth);
  474. }
  475. static void json_append_data(lua_State *l, json_config_t *cfg,
  476. int current_depth, strbuf_t *json);
  477. /* json_append_array args:
  478. * - lua_State
  479. * - JSON strbuf
  480. * - Size of passwd Lua array (top of stack) */
  481. static void json_append_array(lua_State *l, json_config_t *cfg, int current_depth,
  482. strbuf_t *json, int array_length)
  483. {
  484. int comma, i;
  485. strbuf_append_char(json, '[');
  486. comma = 0;
  487. for (i = 1; i <= array_length; i++) {
  488. if (comma)
  489. strbuf_append_char(json, ',');
  490. else
  491. comma = 1;
  492. lua_rawgeti(l, -1, i);
  493. json_append_data(l, cfg, current_depth, json);
  494. lua_pop(l, 1);
  495. }
  496. strbuf_append_char(json, ']');
  497. }
  498. static void json_append_number(lua_State *l, json_config_t *cfg,
  499. strbuf_t *json, int lindex)
  500. {
  501. double num = lua_tonumber(l, lindex);
  502. int len;
  503. if (cfg->encode_invalid_numbers == 0) {
  504. /* Prevent encoding invalid numbers */
  505. if (isinf(num) || isnan(num))
  506. json_encode_exception(l, cfg, json, lindex, "must not be NaN or Inf");
  507. } else if (cfg->encode_invalid_numbers == 1) {
  508. /* Encode invalid numbers, but handle "nan" separately
  509. * since some platforms may encode as "-nan". */
  510. if (isnan(num)) {
  511. strbuf_append_mem(json, "nan", 3);
  512. return;
  513. }
  514. } else {
  515. /* Encode invalid numbers as "null" */
  516. if (isinf(num) || isnan(num)) {
  517. strbuf_append_mem(json, "null", 4);
  518. return;
  519. }
  520. }
  521. strbuf_ensure_empty_length(json, FPCONV_G_FMT_BUFSIZE);
  522. len = fpconv_g_fmt(strbuf_empty_ptr(json), num, cfg->encode_number_precision);
  523. strbuf_extend_length(json, len);
  524. }
  525. static void json_append_object(lua_State *l, json_config_t *cfg,
  526. int current_depth, strbuf_t *json)
  527. {
  528. int comma, keytype;
  529. /* Object */
  530. strbuf_append_char(json, '{');
  531. lua_pushnil(l);
  532. /* table, startkey */
  533. comma = 0;
  534. while (lua_next(l, -2) != 0) {
  535. if (comma)
  536. strbuf_append_char(json, ',');
  537. else
  538. comma = 1;
  539. /* table, key, value */
  540. keytype = lua_type(l, -2);
  541. if (keytype == LUA_TNUMBER) {
  542. strbuf_append_char(json, '"');
  543. json_append_number(l, cfg, json, -2);
  544. strbuf_append_mem(json, "\":", 2);
  545. } else if (keytype == LUA_TSTRING) {
  546. json_append_string(l, json, -2);
  547. strbuf_append_char(json, ':');
  548. } else {
  549. json_encode_exception(l, cfg, json, -2,
  550. "table key must be a number or string");
  551. /* never returns */
  552. }
  553. /* table, key, value */
  554. json_append_data(l, cfg, current_depth, json);
  555. lua_pop(l, 1);
  556. /* table, key */
  557. }
  558. strbuf_append_char(json, '}');
  559. }
  560. /* Serialise Lua data into JSON string. */
  561. static void json_append_data(lua_State *l, json_config_t *cfg,
  562. int current_depth, strbuf_t *json)
  563. {
  564. int len;
  565. switch (lua_type(l, -1)) {
  566. case LUA_TSTRING:
  567. json_append_string(l, json, -1);
  568. break;
  569. case LUA_TNUMBER:
  570. json_append_number(l, cfg, json, -1);
  571. break;
  572. case LUA_TBOOLEAN:
  573. if (lua_toboolean(l, -1))
  574. strbuf_append_mem(json, "true", 4);
  575. else
  576. strbuf_append_mem(json, "false", 5);
  577. break;
  578. case LUA_TTABLE:
  579. current_depth++;
  580. json_check_encode_depth(l, cfg, current_depth, json);
  581. len = lua_array_length(l, cfg, json);
  582. if (len > 0)
  583. json_append_array(l, cfg, current_depth, json, len);
  584. else
  585. json_append_object(l, cfg, current_depth, json);
  586. break;
  587. case LUA_TNIL:
  588. strbuf_append_mem(json, "null", 4);
  589. break;
  590. case LUA_TLIGHTUSERDATA:
  591. if (lua_touserdata(l, -1) == NULL) {
  592. strbuf_append_mem(json, "null", 4);
  593. break;
  594. }
  595. default:
  596. /* Remaining types (LUA_TFUNCTION, LUA_TUSERDATA, LUA_TTHREAD,
  597. * and LUA_TLIGHTUSERDATA) cannot be serialised */
  598. json_encode_exception(l, cfg, json, -1, "type not supported");
  599. /* never returns */
  600. }
  601. }
  602. static int json_encode(lua_State *l)
  603. {
  604. json_config_t *cfg = json_fetch_config(l);
  605. strbuf_t local_encode_buf;
  606. strbuf_t *encode_buf;
  607. char *json;
  608. int len;
  609. luaL_argcheck(l, lua_gettop(l) == 1, 1, "expected 1 argument");
  610. if (!cfg->encode_keep_buffer) {
  611. /* Use private buffer */
  612. encode_buf = &local_encode_buf;
  613. strbuf_init(encode_buf, 0);
  614. } else {
  615. /* Reuse existing buffer */
  616. encode_buf = &cfg->encode_buf;
  617. strbuf_reset(encode_buf);
  618. }
  619. json_append_data(l, cfg, 0, encode_buf);
  620. json = strbuf_string(encode_buf, &len);
  621. lua_pushlstring(l, json, len);
  622. if (!cfg->encode_keep_buffer)
  623. strbuf_free(encode_buf);
  624. return 1;
  625. }
  626. /* ===== DECODING ===== */
  627. static void json_process_value(lua_State *l, json_parse_t *json,
  628. json_token_t *token);
  629. static int hexdigit2int(char hex)
  630. {
  631. if ('0' <= hex && hex <= '9')
  632. return hex - '0';
  633. /* Force lowercase */
  634. hex |= 0x20;
  635. if ('a' <= hex && hex <= 'f')
  636. return 10 + hex - 'a';
  637. return -1;
  638. }
  639. static int decode_hex4(const char *hex)
  640. {
  641. int digit[4];
  642. int i;
  643. /* Convert ASCII hex digit to numeric digit
  644. * Note: this returns an error for invalid hex digits, including
  645. * NULL */
  646. for (i = 0; i < 4; i++) {
  647. digit[i] = hexdigit2int(hex[i]);
  648. if (digit[i] < 0) {
  649. return -1;
  650. }
  651. }
  652. return (digit[0] << 12) +
  653. (digit[1] << 8) +
  654. (digit[2] << 4) +
  655. digit[3];
  656. }
  657. /* Converts a Unicode codepoint to UTF-8.
  658. * Returns UTF-8 string length, and up to 4 bytes in *utf8 */
  659. static int codepoint_to_utf8(char *utf8, int codepoint)
  660. {
  661. /* 0xxxxxxx */
  662. if (codepoint <= 0x7F) {
  663. utf8[0] = codepoint;
  664. return 1;
  665. }
  666. /* 110xxxxx 10xxxxxx */
  667. if (codepoint <= 0x7FF) {
  668. utf8[0] = (codepoint >> 6) | 0xC0;
  669. utf8[1] = (codepoint & 0x3F) | 0x80;
  670. return 2;
  671. }
  672. /* 1110xxxx 10xxxxxx 10xxxxxx */
  673. if (codepoint <= 0xFFFF) {
  674. utf8[0] = (codepoint >> 12) | 0xE0;
  675. utf8[1] = ((codepoint >> 6) & 0x3F) | 0x80;
  676. utf8[2] = (codepoint & 0x3F) | 0x80;
  677. return 3;
  678. }
  679. /* 11110xxx 10xxxxxx 10xxxxxx 10xxxxxx */
  680. if (codepoint <= 0x1FFFFF) {
  681. utf8[0] = (codepoint >> 18) | 0xF0;
  682. utf8[1] = ((codepoint >> 12) & 0x3F) | 0x80;
  683. utf8[2] = ((codepoint >> 6) & 0x3F) | 0x80;
  684. utf8[3] = (codepoint & 0x3F) | 0x80;
  685. return 4;
  686. }
  687. return 0;
  688. }
  689. /* Called when index pointing to beginning of UTF-16 code escape: \uXXXX
  690. * \u is guaranteed to exist, but the remaining hex characters may be
  691. * missing.
  692. * Translate to UTF-8 and append to temporary token string.
  693. * Must advance index to the next character to be processed.
  694. * Returns: 0 success
  695. * -1 error
  696. */
  697. static int json_append_unicode_escape(json_parse_t *json)
  698. {
  699. char utf8[4]; /* Surrogate pairs require 4 UTF-8 bytes */
  700. int codepoint;
  701. int surrogate_low;
  702. int len;
  703. int escape_len = 6;
  704. /* Fetch UTF-16 code unit */
  705. codepoint = decode_hex4(json->ptr + 2);
  706. if (codepoint < 0)
  707. return -1;
  708. /* UTF-16 surrogate pairs take the following 2 byte form:
  709. * 11011 x yyyyyyyyyy
  710. * When x = 0: y is the high 10 bits of the codepoint
  711. * x = 1: y is the low 10 bits of the codepoint
  712. *
  713. * Check for a surrogate pair (high or low) */
  714. if ((codepoint & 0xF800) == 0xD800) {
  715. /* Error if the 1st surrogate is not high */
  716. if (codepoint & 0x400)
  717. return -1;
  718. /* Ensure the next code is a unicode escape */
  719. if (*(json->ptr + escape_len) != '\\' ||
  720. *(json->ptr + escape_len + 1) != 'u') {
  721. return -1;
  722. }
  723. /* Fetch the next codepoint */
  724. surrogate_low = decode_hex4(json->ptr + 2 + escape_len);
  725. if (surrogate_low < 0)
  726. return -1;
  727. /* Error if the 2nd code is not a low surrogate */
  728. if ((surrogate_low & 0xFC00) != 0xDC00)
  729. return -1;
  730. /* Calculate Unicode codepoint */
  731. codepoint = (codepoint & 0x3FF) << 10;
  732. surrogate_low &= 0x3FF;
  733. codepoint = (codepoint | surrogate_low) + 0x10000;
  734. escape_len = 12;
  735. }
  736. /* Convert codepoint to UTF-8 */
  737. len = codepoint_to_utf8(utf8, codepoint);
  738. if (!len)
  739. return -1;
  740. /* Append bytes and advance parse index */
  741. strbuf_append_mem_unsafe(json->tmp, utf8, len);
  742. json->ptr += escape_len;
  743. return 0;
  744. }
  745. static void json_set_token_error(json_token_t *token, json_parse_t *json,
  746. const char *errtype)
  747. {
  748. token->type = T_ERROR;
  749. token->index = json->ptr - json->data;
  750. token->value.string = errtype;
  751. }
  752. static void json_next_string_token(json_parse_t *json, json_token_t *token)
  753. {
  754. char *escape2char = json->cfg->escape2char;
  755. char ch;
  756. /* Caller must ensure a string is next */
  757. assert(*json->ptr == '"');
  758. /* Skip " */
  759. json->ptr++;
  760. /* json->tmp is the temporary strbuf used to accumulate the
  761. * decoded string value.
  762. * json->tmp is sized to handle JSON containing only a string value.
  763. */
  764. strbuf_reset(json->tmp);
  765. while ((ch = *json->ptr) != '"') {
  766. if (!ch) {
  767. /* Premature end of the string */
  768. json_set_token_error(token, json, "unexpected end of string");
  769. return;
  770. }
  771. /* Handle escapes */
  772. if (ch == '\\') {
  773. /* Fetch escape character */
  774. ch = *(json->ptr + 1);
  775. /* Translate escape code and append to tmp string */
  776. ch = escape2char[(unsigned char)ch];
  777. if (ch == 'u') {
  778. if (json_append_unicode_escape(json) == 0)
  779. continue;
  780. json_set_token_error(token, json,
  781. "invalid unicode escape code");
  782. return;
  783. }
  784. if (!ch) {
  785. json_set_token_error(token, json, "invalid escape code");
  786. return;
  787. }
  788. /* Skip '\' */
  789. json->ptr++;
  790. }
  791. /* Append normal character or translated single character
  792. * Unicode escapes are handled above */
  793. strbuf_append_char_unsafe(json->tmp, ch);
  794. json->ptr++;
  795. }
  796. json->ptr++; /* Eat final quote (") */
  797. strbuf_ensure_null(json->tmp);
  798. token->type = T_STRING;
  799. token->value.string = strbuf_string(json->tmp, &token->string_len);
  800. }
  801. /* JSON numbers should take the following form:
  802. * -?(0|[1-9]|[1-9][0-9]+)(.[0-9]+)?([eE][-+]?[0-9]+)?
  803. *
  804. * json_next_number_token() uses strtod() which allows other forms:
  805. * - numbers starting with '+'
  806. * - NaN, -NaN, infinity, -infinity
  807. * - hexadecimal numbers
  808. * - numbers with leading zeros
  809. *
  810. * json_is_invalid_number() detects "numbers" which may pass strtod()'s
  811. * error checking, but should not be allowed with strict JSON.
  812. *
  813. * json_is_invalid_number() may pass numbers which cause strtod()
  814. * to generate an error.
  815. */
  816. static int json_is_invalid_number(json_parse_t *json)
  817. {
  818. const char *p = json->ptr;
  819. /* Reject numbers starting with + */
  820. if (*p == '+')
  821. return 1;
  822. /* Skip minus sign if it exists */
  823. if (*p == '-')
  824. p++;
  825. /* Reject numbers starting with 0x, or leading zeros */
  826. if (*p == '0') {
  827. int ch2 = *(p + 1);
  828. if ((ch2 | 0x20) == 'x' || /* Hex */
  829. ('0' <= ch2 && ch2 <= '9')) /* Leading zero */
  830. return 1;
  831. return 0;
  832. } else if (*p <= '9') {
  833. return 0; /* Ordinary number */
  834. }
  835. /* Reject inf/nan */
  836. if (!strncasecmp(p, "inf", 3))
  837. return 1;
  838. if (!strncasecmp(p, "nan", 3))
  839. return 1;
  840. /* Pass all other numbers which may still be invalid, but
  841. * strtod() will catch them. */
  842. return 0;
  843. }
  844. static void json_next_number_token(json_parse_t *json, json_token_t *token)
  845. {
  846. char *endptr;
  847. double value = fpconv_strtod(json->ptr, &endptr);
  848. if (json->ptr == endptr)
  849. {
  850. token->type = T_NUMBER;
  851. token->value.number = value;
  852. json_set_token_error(token, json, "invalid number");
  853. }
  854. else
  855. {
  856. //scaning the str has dot-operation
  857. char *start = (char*)json->ptr;
  858. bool is_int = true;
  859. while (start != endptr)
  860. {
  861. if (*start == '.')
  862. {
  863. //this is int
  864. is_int = false;
  865. break;
  866. }
  867. ++start;
  868. }
  869. if (is_int)
  870. {
  871. token->type = T_INTEGER;
  872. token->value.integer = (long long)value;
  873. }
  874. else
  875. {
  876. token->type = T_NUMBER;
  877. token->value.number = value;
  878. }
  879. json->ptr = endptr; /* Skip the processed number */
  880. }
  881. return;
  882. }
  883. /* Fills in the token struct.
  884. * T_STRING will return a pointer to the json_parse_t temporary string
  885. * T_ERROR will leave the json->ptr pointer at the error.
  886. */
  887. static void json_next_token(json_parse_t *json, json_token_t *token)
  888. {
  889. const json_token_type_t *ch2token = json->cfg->ch2token;
  890. int ch;
  891. /* Eat whitespace. */
  892. while (1) {
  893. ch = (unsigned char)*(json->ptr);
  894. token->type = ch2token[ch];
  895. if (token->type != T_WHITESPACE)
  896. break;
  897. json->ptr++;
  898. }
  899. /* Store location of new token. Required when throwing errors
  900. * for unexpected tokens (syntax errors). */
  901. token->index = json->ptr - json->data;
  902. /* Don't advance the pointer for an error or the end */
  903. if (token->type == T_ERROR) {
  904. json_set_token_error(token, json, "invalid token");
  905. return;
  906. }
  907. if (token->type == T_END) {
  908. return;
  909. }
  910. /* Found a known single character token, advance index and return */
  911. if (token->type != T_UNKNOWN) {
  912. json->ptr++;
  913. return;
  914. }
  915. /* Process characters which triggered T_UNKNOWN
  916. *
  917. * Must use strncmp() to match the front of the JSON string.
  918. * JSON identifier must be lowercase.
  919. * When strict_numbers if disabled, either case is allowed for
  920. * Infinity/NaN (since we are no longer following the spec..) */
  921. if (ch == '"') {
  922. json_next_string_token(json, token);
  923. return;
  924. } else if (ch == '-' || ('0' <= ch && ch <= '9')) {
  925. if (!json->cfg->decode_invalid_numbers && json_is_invalid_number(json)) {
  926. json_set_token_error(token, json, "invalid number");
  927. return;
  928. }
  929. json_next_number_token(json, token);
  930. return;
  931. } else if (!strncmp(json->ptr, "true", 4)) {
  932. token->type = T_BOOLEAN;
  933. token->value.boolean = 1;
  934. json->ptr += 4;
  935. return;
  936. } else if (!strncmp(json->ptr, "false", 5)) {
  937. token->type = T_BOOLEAN;
  938. token->value.boolean = 0;
  939. json->ptr += 5;
  940. return;
  941. } else if (!strncmp(json->ptr, "null", 4)) {
  942. token->type = T_NULL;
  943. json->ptr += 4;
  944. return;
  945. } else if (json->cfg->decode_invalid_numbers &&
  946. json_is_invalid_number(json)) {
  947. /* When decode_invalid_numbers is enabled, only attempt to process
  948. * numbers we know are invalid JSON (Inf, NaN, hex)
  949. * This is required to generate an appropriate token error,
  950. * otherwise all bad tokens will register as "invalid number"
  951. */
  952. json_next_number_token(json, token);
  953. return;
  954. }
  955. /* Token starts with t/f/n but isn't recognised above. */
  956. json_set_token_error(token, json, "invalid token");
  957. }
  958. /* This function does not return.
  959. * DO NOT CALL WITH DYNAMIC MEMORY ALLOCATED.
  960. * The only supported exception is the temporary parser string
  961. * json->tmp struct.
  962. * json and token should exist on the stack somewhere.
  963. * luaL_error() will long_jmp and release the stack */
  964. static void json_throw_parse_error(lua_State *l, json_parse_t *json,
  965. const char *exp, json_token_t *token)
  966. {
  967. const char *found;
  968. strbuf_free(json->tmp);
  969. if (token->type == T_ERROR)
  970. found = token->value.string;
  971. else
  972. found = json_token_type_name[token->type];
  973. /* Note: token->index is 0 based, display starting from 1 */
  974. luaL_error(l, "Expected %s but found %s at character %d",
  975. exp, found, token->index + 1);
  976. }
  977. static inline void json_decode_ascend(json_parse_t *json)
  978. {
  979. json->current_depth--;
  980. }
  981. static void json_decode_descend(lua_State *l, json_parse_t *json, int slots)
  982. {
  983. json->current_depth++;
  984. if (json->current_depth <= json->cfg->decode_max_depth &&
  985. lua_checkstack(l, slots)) {
  986. return;
  987. }
  988. strbuf_free(json->tmp);
  989. luaL_error(l, "Found too many nested data structures (%d) at character %d",
  990. json->current_depth, json->ptr - json->data);
  991. }
  992. static void json_parse_object_context(lua_State *l, json_parse_t *json)
  993. {
  994. json_token_t token;
  995. /* 3 slots required:
  996. * .., table, key, value */
  997. json_decode_descend(l, json, 3);
  998. lua_newtable(l);
  999. json_next_token(json, &token);
  1000. /* Handle empty objects */
  1001. if (token.type == T_OBJ_END) {
  1002. json_decode_ascend(json);
  1003. return;
  1004. }
  1005. while (1) {
  1006. if (token.type != T_STRING)
  1007. json_throw_parse_error(l, json, "object key string", &token);
  1008. /* Push key */
  1009. lua_pushlstring(l, token.value.string, token.string_len);
  1010. json_next_token(json, &token);
  1011. if (token.type != T_COLON)
  1012. json_throw_parse_error(l, json, "colon", &token);
  1013. /* Fetch value */
  1014. json_next_token(json, &token);
  1015. json_process_value(l, json, &token);
  1016. /* Set key = value */
  1017. lua_rawset(l, -3);
  1018. json_next_token(json, &token);
  1019. if (token.type == T_OBJ_END) {
  1020. json_decode_ascend(json);
  1021. return;
  1022. }
  1023. if (token.type != T_COMMA)
  1024. json_throw_parse_error(l, json, "comma or object end", &token);
  1025. json_next_token(json, &token);
  1026. }
  1027. }
  1028. /* Handle the array context */
  1029. static void json_parse_array_context(lua_State *l, json_parse_t *json)
  1030. {
  1031. json_token_t token;
  1032. int i;
  1033. /* 2 slots required:
  1034. * .., table, value */
  1035. json_decode_descend(l, json, 2);
  1036. lua_newtable(l);
  1037. json_next_token(json, &token);
  1038. /* Handle empty arrays */
  1039. if (token.type == T_ARR_END) {
  1040. json_decode_ascend(json);
  1041. return;
  1042. }
  1043. for (i = 1; ; i++) {
  1044. json_process_value(l, json, &token);
  1045. lua_rawseti(l, -2, i); /* arr[i] = value */
  1046. json_next_token(json, &token);
  1047. if (token.type == T_ARR_END) {
  1048. json_decode_ascend(json);
  1049. return;
  1050. }
  1051. if (token.type != T_COMMA)
  1052. json_throw_parse_error(l, json, "comma or array end", &token);
  1053. json_next_token(json, &token);
  1054. }
  1055. }
  1056. /* Handle the "value" context */
  1057. static void json_process_value(lua_State *l, json_parse_t *json,
  1058. json_token_t *token)
  1059. {
  1060. switch (token->type) {
  1061. case T_STRING:
  1062. lua_pushlstring(l, token->value.string, token->string_len);
  1063. break;;
  1064. case T_NUMBER:
  1065. lua_pushnumber(l, token->value.number);
  1066. break;;
  1067. case T_INTEGER:
  1068. lua_pushinteger(l, token->value.integer);
  1069. break;;
  1070. case T_BOOLEAN:
  1071. lua_pushboolean(l, token->value.boolean);
  1072. break;;
  1073. case T_OBJ_BEGIN:
  1074. json_parse_object_context(l, json);
  1075. break;;
  1076. case T_ARR_BEGIN:
  1077. json_parse_array_context(l, json);
  1078. break;;
  1079. case T_NULL:
  1080. /* In Lua, setting "t[k] = nil" will delete k from the table.
  1081. * Hence a NULL pointer lightuserdata object is used instead */
  1082. lua_pushlightuserdata(l, NULL);
  1083. break;;
  1084. default:
  1085. json_throw_parse_error(l, json, "value", token);
  1086. }
  1087. }
  1088. static int json_decode(lua_State *l)
  1089. {
  1090. json_parse_t json;
  1091. json_token_t token;
  1092. size_t json_len;
  1093. luaL_argcheck(l, lua_gettop(l) == 1, 1, "expected 1 argument");
  1094. json.cfg = json_fetch_config(l);
  1095. json.data = luaL_checklstring(l, 1, &json_len);
  1096. json.current_depth = 0;
  1097. json.ptr = json.data;
  1098. /* Detect Unicode other than UTF-8 (see RFC 4627, Sec 3)
  1099. *
  1100. * CJSON can support any simple data type, hence only the first
  1101. * character is guaranteed to be ASCII (at worst: '"'). This is
  1102. * still enough to detect whether the wrong encoding is in use. */
  1103. if (json_len >= 2 && (!json.data[0] || !json.data[1]))
  1104. luaL_error(l, "JSON parser does not support UTF-16 or UTF-32");
  1105. /* Ensure the temporary buffer can hold the entire string.
  1106. * This means we no longer need to do length checks since the decoded
  1107. * string must be smaller than the entire json string */
  1108. json.tmp = strbuf_new(json_len);
  1109. json_next_token(&json, &token);
  1110. json_process_value(l, &json, &token);
  1111. /* Ensure there is no more input left */
  1112. json_next_token(&json, &token);
  1113. if (token.type != T_END)
  1114. json_throw_parse_error(l, &json, "the end", &token);
  1115. strbuf_free(json.tmp);
  1116. return 1;
  1117. }
  1118. /* ===== INITIALISATION ===== */
  1119. #if !defined(LUA_VERSION_NUM) || LUA_VERSION_NUM < 502
  1120. /* Compatibility for Lua 5.1.
  1121. *
  1122. * luaL_setfuncs() is used to create a module table where the functions have
  1123. * json_config_t as their first upvalue. Code borrowed from Lua 5.2 source. */
  1124. static void luaL_setfuncs (lua_State *l, const luaL_Reg *reg, int nup)
  1125. {
  1126. int i;
  1127. luaL_checkstack(l, nup, "too many upvalues");
  1128. for (; reg->name != NULL; reg++) { /* fill the table with given functions */
  1129. for (i = 0; i < nup; i++) /* copy upvalues to the top */
  1130. lua_pushvalue(l, -nup);
  1131. lua_pushcclosure(l, reg->func, nup); /* closure with those upvalues */
  1132. lua_setfield(l, -(nup + 2), reg->name);
  1133. }
  1134. lua_pop(l, nup); /* remove upvalues */
  1135. }
  1136. #endif
  1137. /* Call target function in protected mode with all supplied args.
  1138. * Assumes target function only returns a single non-nil value.
  1139. * Convert and return thrown errors as: nil, "error message" */
  1140. static int json_protect_conversion(lua_State *l)
  1141. {
  1142. int err;
  1143. /* Deliberately throw an error for invalid arguments */
  1144. luaL_argcheck(l, lua_gettop(l) == 1, 1, "expected 1 argument");
  1145. /* pcall() the function stored as upvalue(1) */
  1146. lua_pushvalue(l, lua_upvalueindex(1));
  1147. lua_insert(l, 1);
  1148. err = lua_pcall(l, 1, 1, 0);
  1149. if (!err)
  1150. return 1;
  1151. if (err == LUA_ERRRUN) {
  1152. lua_pushnil(l);
  1153. lua_insert(l, -2);
  1154. return 2;
  1155. }
  1156. /* Since we are not using a custom error handler, the only remaining
  1157. * errors are memory related */
  1158. return luaL_error(l, "Memory allocation error in CJSON protected call");
  1159. }
  1160. /* Return cjson module table */
  1161. static int lua_cjson_new(lua_State *l)
  1162. {
  1163. luaL_Reg reg[] = {
  1164. { "encode", json_encode },
  1165. { "decode", json_decode },
  1166. { "encode_sparse_array", json_cfg_encode_sparse_array },
  1167. { "encode_max_depth", json_cfg_encode_max_depth },
  1168. { "decode_max_depth", json_cfg_decode_max_depth },
  1169. { "encode_number_precision", json_cfg_encode_number_precision },
  1170. { "encode_keep_buffer", json_cfg_encode_keep_buffer },
  1171. { "encode_invalid_numbers", json_cfg_encode_invalid_numbers },
  1172. { "decode_invalid_numbers", json_cfg_decode_invalid_numbers },
  1173. { "new", lua_cjson_new },
  1174. { NULL, NULL }
  1175. };
  1176. /* Initialise number conversions */
  1177. fpconv_init();
  1178. /* cjson module table */
  1179. lua_newtable(l);
  1180. /* Register functions with config data as upvalue */
  1181. json_create_config(l);
  1182. luaL_setfuncs(l, reg, 1);
  1183. /* Set cjson.null */
  1184. lua_pushlightuserdata(l, NULL);
  1185. lua_setfield(l, -2, "null");
  1186. /* Set module name / version fields */
  1187. lua_pushliteral(l, CJSON_MODNAME);
  1188. lua_setfield(l, -2, "_NAME");
  1189. lua_pushliteral(l, CJSON_VERSION);
  1190. lua_setfield(l, -2, "_VERSION");
  1191. return 1;
  1192. }
  1193. /* Return cjson.safe module table */
  1194. static int lua_cjson_safe_new(lua_State *l)
  1195. {
  1196. const char *func[] = { "decode", "encode", NULL };
  1197. int i;
  1198. lua_cjson_new(l);
  1199. /* Fix new() method */
  1200. lua_pushcfunction(l, lua_cjson_safe_new);
  1201. lua_setfield(l, -2, "new");
  1202. for (i = 0; func[i]; i++) {
  1203. lua_getfield(l, -1, func[i]);
  1204. lua_pushcclosure(l, json_protect_conversion, 1);
  1205. lua_setfield(l, -2, func[i]);
  1206. }
  1207. return 1;
  1208. }
  1209. int luaopen_cjson(lua_State *l)
  1210. {
  1211. lua_cjson_new(l);
  1212. #ifdef ENABLE_CJSON_GLOBAL
  1213. /* Register a global "cjson" table. */
  1214. lua_pushvalue(l, -1);
  1215. lua_setglobal(l, CJSON_MODNAME);
  1216. #endif
  1217. /* Return cjson table */
  1218. return 1;
  1219. }
  1220. int luaopen_cjson_safe(lua_State *l)
  1221. {
  1222. lua_cjson_safe_new(l);
  1223. /* Return cjson.safe table */
  1224. return 1;
  1225. }
  1226. /* vi:ai et sw=4 ts=4:
  1227. */