lua_cjson.c 41 KB

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