lua_cjson.c 42 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454
  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. /* Workaround for Solaris platforms missing isinf() */
  52. #if !defined(isinf) && (defined(USE_INTERNAL_ISINF) || defined(MISSING_ISINF))
  53. #define isinf(x) (!isnan(x) && isnan((x) - (x)))
  54. #endif
  55. #define DEFAULT_SPARSE_CONVERT 0
  56. #define DEFAULT_SPARSE_RATIO 2
  57. #define DEFAULT_SPARSE_SAFE 10
  58. #define DEFAULT_ENCODE_MAX_DEPTH 1000
  59. #define DEFAULT_DECODE_MAX_DEPTH 1000
  60. #define DEFAULT_ENCODE_INVALID_NUMBERS 0
  61. #define DEFAULT_DECODE_INVALID_NUMBERS 1
  62. #define DEFAULT_ENCODE_KEEP_BUFFER 1
  63. #define DEFAULT_ENCODE_NUMBER_PRECISION 14
  64. #ifdef DISABLE_INVALID_NUMBERS
  65. #undef DEFAULT_DECODE_INVALID_NUMBERS
  66. #define DEFAULT_DECODE_INVALID_NUMBERS 0
  67. #endif
  68. typedef enum {
  69. T_OBJ_BEGIN,
  70. T_OBJ_END,
  71. T_ARR_BEGIN,
  72. T_ARR_END,
  73. T_STRING,
  74. T_NUMBER,
  75. T_INTEGER,
  76. T_BOOLEAN,
  77. T_NULL,
  78. T_COLON,
  79. T_COMMA,
  80. T_END,
  81. T_WHITESPACE,
  82. T_ERROR,
  83. T_UNKNOWN
  84. } json_token_type_t;
  85. static const char *json_token_type_name[] = {
  86. "T_OBJ_BEGIN",
  87. "T_OBJ_END",
  88. "T_ARR_BEGIN",
  89. "T_ARR_END",
  90. "T_STRING",
  91. "T_NUMBER",
  92. "T_INTEGER",
  93. "T_BOOLEAN",
  94. "T_NULL",
  95. "T_COLON",
  96. "T_COMMA",
  97. "T_END",
  98. "T_WHITESPACE",
  99. "T_ERROR",
  100. "T_UNKNOWN",
  101. NULL
  102. };
  103. typedef struct {
  104. json_token_type_t ch2token[256];
  105. char escape2char[256]; /* Decoding */
  106. /* encode_buf is only allocated and used when
  107. * encode_keep_buffer is set */
  108. strbuf_t encode_buf;
  109. int encode_sparse_convert;
  110. int encode_sparse_ratio;
  111. int encode_sparse_safe;
  112. int encode_max_depth;
  113. int encode_invalid_numbers; /* 2 => Encode as "null" */
  114. int encode_number_precision;
  115. int encode_keep_buffer;
  116. int decode_invalid_numbers;
  117. int decode_max_depth;
  118. } json_config_t;
  119. typedef struct {
  120. const char *data;
  121. const char *ptr;
  122. strbuf_t *tmp; /* Temporary storage for strings */
  123. json_config_t *cfg;
  124. int current_depth;
  125. } json_parse_t;
  126. typedef struct {
  127. json_token_type_t type;
  128. int index;
  129. union {
  130. const char *string;
  131. double number;
  132. lua_Integer integer;
  133. int boolean;
  134. } value;
  135. int string_len;
  136. } json_token_t;
  137. static const char *char2escape[256] = {
  138. "\\u0000", "\\u0001", "\\u0002", "\\u0003",
  139. "\\u0004", "\\u0005", "\\u0006", "\\u0007",
  140. "\\b", "\\t", "\\n", "\\u000b",
  141. "\\f", "\\r", "\\u000e", "\\u000f",
  142. "\\u0010", "\\u0011", "\\u0012", "\\u0013",
  143. "\\u0014", "\\u0015", "\\u0016", "\\u0017",
  144. "\\u0018", "\\u0019", "\\u001a", "\\u001b",
  145. "\\u001c", "\\u001d", "\\u001e", "\\u001f",
  146. NULL, NULL, "\\\"", NULL, NULL, NULL, NULL, NULL,
  147. NULL, NULL, NULL, NULL, NULL, NULL, NULL, "\\/",
  148. NULL, 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,
  154. NULL, 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, "\\u007f",
  158. NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL,
  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. };
  175. /* ===== CONFIGURATION ===== */
  176. static json_config_t *json_fetch_config(lua_State *l)
  177. {
  178. json_config_t *cfg;
  179. cfg = lua_touserdata(l, lua_upvalueindex(1));
  180. if (!cfg)
  181. luaL_error(l, "BUG: Unable to fetch CJSON configuration");
  182. return cfg;
  183. }
  184. /* Ensure the correct number of arguments have been provided.
  185. * Pad with nil to allow other functions to simply check arg[i]
  186. * to find whether an argument was provided */
  187. static json_config_t *json_arg_init(lua_State *l, int args)
  188. {
  189. luaL_argcheck(l, lua_gettop(l) <= args, args + 1,
  190. "found too many arguments");
  191. while (lua_gettop(l) < args)
  192. lua_pushnil(l);
  193. return json_fetch_config(l);
  194. }
  195. /* Process integer options for configuration functions */
  196. static int json_integer_option(lua_State *l, int optindex, int *setting,
  197. int min, int max)
  198. {
  199. char errmsg[64];
  200. int value;
  201. if (!lua_isnil(l, optindex)) {
  202. value = luaL_checkinteger(l, optindex);
  203. snprintf(errmsg, sizeof(errmsg), "expected integer between %d and %d", min, max);
  204. luaL_argcheck(l, min <= value && value <= max, 1, errmsg);
  205. *setting = value;
  206. }
  207. lua_pushinteger(l, *setting);
  208. return 1;
  209. }
  210. /* Process enumerated arguments for a configuration function */
  211. static int json_enum_option(lua_State *l, int optindex, int *setting,
  212. const char **options, int bool_true)
  213. {
  214. static const char *bool_options[] = { "off", "on", NULL };
  215. if (!options) {
  216. options = bool_options;
  217. bool_true = 1;
  218. }
  219. if (!lua_isnil(l, optindex)) {
  220. if (bool_true && lua_isboolean(l, optindex))
  221. *setting = lua_toboolean(l, optindex) * bool_true;
  222. else
  223. *setting = luaL_checkoption(l, optindex, NULL, options);
  224. }
  225. if (bool_true && (*setting == 0 || *setting == bool_true))
  226. lua_pushboolean(l, *setting);
  227. else
  228. lua_pushstring(l, options[*setting]);
  229. return 1;
  230. }
  231. /* Configures handling of extremely sparse arrays:
  232. * convert: Convert extremely sparse arrays into objects? Otherwise error.
  233. * ratio: 0: always allow sparse; 1: never allow sparse; >1: use ratio
  234. * safe: Always use an array when the max index <= safe */
  235. static int json_cfg_encode_sparse_array(lua_State *l)
  236. {
  237. json_config_t *cfg = json_arg_init(l, 3);
  238. json_enum_option(l, 1, &cfg->encode_sparse_convert, NULL, 1);
  239. json_integer_option(l, 2, &cfg->encode_sparse_ratio, 0, INT_MAX);
  240. json_integer_option(l, 3, &cfg->encode_sparse_safe, 0, INT_MAX);
  241. return 3;
  242. }
  243. /* Configures the maximum number of nested arrays/objects allowed when
  244. * encoding */
  245. static int json_cfg_encode_max_depth(lua_State *l)
  246. {
  247. json_config_t *cfg = json_arg_init(l, 1);
  248. return json_integer_option(l, 1, &cfg->encode_max_depth, 1, INT_MAX);
  249. }
  250. /* Configures the maximum number of nested arrays/objects allowed when
  251. * encoding */
  252. static int json_cfg_decode_max_depth(lua_State *l)
  253. {
  254. json_config_t *cfg = json_arg_init(l, 1);
  255. return json_integer_option(l, 1, &cfg->decode_max_depth, 1, INT_MAX);
  256. }
  257. /* Configures number precision when converting doubles to text */
  258. static int json_cfg_encode_number_precision(lua_State *l)
  259. {
  260. json_config_t *cfg = json_arg_init(l, 1);
  261. return json_integer_option(l, 1, &cfg->encode_number_precision, 1, 14);
  262. }
  263. /* Configures JSON encoding buffer persistence */
  264. static int json_cfg_encode_keep_buffer(lua_State *l)
  265. {
  266. json_config_t *cfg = json_arg_init(l, 1);
  267. int old_value;
  268. old_value = cfg->encode_keep_buffer;
  269. json_enum_option(l, 1, &cfg->encode_keep_buffer, NULL, 1);
  270. /* Init / free the buffer if the setting has changed */
  271. if (old_value ^ cfg->encode_keep_buffer) {
  272. if (cfg->encode_keep_buffer)
  273. strbuf_init(&cfg->encode_buf, 0);
  274. else
  275. strbuf_free(&cfg->encode_buf);
  276. }
  277. return 1;
  278. }
  279. #if defined(DISABLE_INVALID_NUMBERS) && !defined(USE_INTERNAL_FPCONV)
  280. void json_verify_invalid_number_setting(lua_State *l, int *setting)
  281. {
  282. if (*setting == 1) {
  283. *setting = 0;
  284. luaL_error(l, "Infinity, NaN, and/or hexadecimal numbers are not supported.");
  285. }
  286. }
  287. #else
  288. #define json_verify_invalid_number_setting(l, s) do { } while(0)
  289. #endif
  290. static int json_cfg_encode_invalid_numbers(lua_State *l)
  291. {
  292. static const char *options[] = { "off", "on", "null", NULL };
  293. json_config_t *cfg = json_arg_init(l, 1);
  294. json_enum_option(l, 1, &cfg->encode_invalid_numbers, options, 1);
  295. json_verify_invalid_number_setting(l, &cfg->encode_invalid_numbers);
  296. return 1;
  297. }
  298. static int json_cfg_decode_invalid_numbers(lua_State *l)
  299. {
  300. json_config_t *cfg = json_arg_init(l, 1);
  301. json_enum_option(l, 1, &cfg->decode_invalid_numbers, NULL, 1);
  302. json_verify_invalid_number_setting(l, &cfg->encode_invalid_numbers);
  303. return 1;
  304. }
  305. static int json_destroy_config(lua_State *l)
  306. {
  307. json_config_t *cfg;
  308. cfg = lua_touserdata(l, 1);
  309. if (cfg)
  310. strbuf_free(&cfg->encode_buf);
  311. cfg = NULL;
  312. return 0;
  313. }
  314. static void json_create_config(lua_State *l)
  315. {
  316. json_config_t *cfg;
  317. int i;
  318. cfg = lua_newuserdata(l, sizeof(*cfg));
  319. /* Create GC method to clean up strbuf */
  320. lua_newtable(l);
  321. lua_pushcfunction(l, json_destroy_config);
  322. lua_setfield(l, -2, "__gc");
  323. lua_setmetatable(l, -2);
  324. cfg->encode_sparse_convert = DEFAULT_SPARSE_CONVERT;
  325. cfg->encode_sparse_ratio = DEFAULT_SPARSE_RATIO;
  326. cfg->encode_sparse_safe = DEFAULT_SPARSE_SAFE;
  327. cfg->encode_max_depth = DEFAULT_ENCODE_MAX_DEPTH;
  328. cfg->decode_max_depth = DEFAULT_DECODE_MAX_DEPTH;
  329. cfg->encode_invalid_numbers = DEFAULT_ENCODE_INVALID_NUMBERS;
  330. cfg->decode_invalid_numbers = DEFAULT_DECODE_INVALID_NUMBERS;
  331. cfg->encode_keep_buffer = DEFAULT_ENCODE_KEEP_BUFFER;
  332. cfg->encode_number_precision = DEFAULT_ENCODE_NUMBER_PRECISION;
  333. #if DEFAULT_ENCODE_KEEP_BUFFER > 0
  334. strbuf_init(&cfg->encode_buf, 0);
  335. #endif
  336. /* Decoding init */
  337. /* Tag all characters as an error */
  338. for (i = 0; i < 256; i++)
  339. cfg->ch2token[i] = T_ERROR;
  340. /* Set tokens that require no further processing */
  341. cfg->ch2token['{'] = T_OBJ_BEGIN;
  342. cfg->ch2token['}'] = T_OBJ_END;
  343. cfg->ch2token['['] = T_ARR_BEGIN;
  344. cfg->ch2token[']'] = T_ARR_END;
  345. cfg->ch2token[','] = T_COMMA;
  346. cfg->ch2token[':'] = T_COLON;
  347. cfg->ch2token['\0'] = T_END;
  348. cfg->ch2token[' '] = T_WHITESPACE;
  349. cfg->ch2token['\t'] = T_WHITESPACE;
  350. cfg->ch2token['\n'] = T_WHITESPACE;
  351. cfg->ch2token['\r'] = T_WHITESPACE;
  352. /* Update characters that require further processing */
  353. cfg->ch2token['f'] = T_UNKNOWN; /* false? */
  354. cfg->ch2token['i'] = T_UNKNOWN; /* inf, ininity? */
  355. cfg->ch2token['I'] = T_UNKNOWN;
  356. cfg->ch2token['n'] = T_UNKNOWN; /* null, nan? */
  357. cfg->ch2token['N'] = T_UNKNOWN;
  358. cfg->ch2token['t'] = T_UNKNOWN; /* true? */
  359. cfg->ch2token['"'] = T_UNKNOWN; /* string? */
  360. cfg->ch2token['+'] = T_UNKNOWN; /* number? */
  361. cfg->ch2token['-'] = T_UNKNOWN;
  362. for (i = 0; i < 10; i++)
  363. cfg->ch2token['0' + i] = T_UNKNOWN;
  364. /* Lookup table for parsing escape characters */
  365. for (i = 0; i < 256; i++)
  366. cfg->escape2char[i] = 0; /* String error */
  367. cfg->escape2char['"'] = '"';
  368. cfg->escape2char['\\'] = '\\';
  369. cfg->escape2char['/'] = '/';
  370. cfg->escape2char['b'] = '\b';
  371. cfg->escape2char['t'] = '\t';
  372. cfg->escape2char['n'] = '\n';
  373. cfg->escape2char['f'] = '\f';
  374. cfg->escape2char['r'] = '\r';
  375. cfg->escape2char['u'] = 'u'; /* Unicode parsing required */
  376. }
  377. /* ===== ENCODING ===== */
  378. static void json_encode_exception(lua_State *l, json_config_t *cfg, strbuf_t *json, int lindex,
  379. const char *reason)
  380. {
  381. if (!cfg->encode_keep_buffer)
  382. strbuf_free(json);
  383. luaL_error(l, "Cannot serialise %s: %s",
  384. lua_typename(l, lua_type(l, lindex)), reason);
  385. }
  386. /* json_append_string args:
  387. * - lua_State
  388. * - JSON strbuf
  389. * - String (Lua stack index)
  390. *
  391. * Returns nothing. Doesn't remove string from Lua stack */
  392. static void json_append_string(lua_State *l, strbuf_t *json, int lindex)
  393. {
  394. const char *escstr;
  395. int i;
  396. const char *str;
  397. size_t len;
  398. str = lua_tolstring(l, lindex, &len);
  399. /* Worst case is len * 6 (all unicode escapes).
  400. * This buffer is reused constantly for small strings
  401. * If there are any excess pages, they won't be hit anyway.
  402. * This gains ~5% speedup. */
  403. strbuf_ensure_empty_length(json, len * 6 + 2);
  404. strbuf_append_char_unsafe(json, '\"');
  405. for (i = 0; i < len; i++) {
  406. escstr = char2escape[(unsigned char)str[i]];
  407. if (escstr)
  408. strbuf_append_string(json, escstr);
  409. else
  410. strbuf_append_char_unsafe(json, str[i]);
  411. }
  412. strbuf_append_char_unsafe(json, '\"');
  413. }
  414. /* Find the size of the array on the top of the Lua stack
  415. * -1 object (not a pure array)
  416. * >=0 elements in array
  417. */
  418. static int lua_array_length(lua_State *l, json_config_t *cfg, strbuf_t *json)
  419. {
  420. double k;
  421. int max;
  422. int items;
  423. max = 0;
  424. items = 0;
  425. lua_pushnil(l);
  426. /* table, startkey */
  427. while (lua_next(l, -2) != 0) {
  428. /* table, key, value */
  429. if (lua_type(l, -2) == LUA_TNUMBER &&
  430. (k = lua_tonumber(l, -2))) {
  431. /* Integer >= 1 ? */
  432. if (floor(k) == k && k >= 1) {
  433. if (k > max)
  434. max = k;
  435. items++;
  436. lua_pop(l, 1);
  437. continue;
  438. }
  439. }
  440. /* Must not be an array (non integer key) */
  441. lua_pop(l, 2);
  442. return -1;
  443. }
  444. /* Encode excessively sparse arrays as objects (if enabled) */
  445. if (cfg->encode_sparse_ratio > 0 &&
  446. max > items * cfg->encode_sparse_ratio &&
  447. max > cfg->encode_sparse_safe) {
  448. if (!cfg->encode_sparse_convert)
  449. json_encode_exception(l, cfg, json, -1, "excessively sparse array");
  450. return -1;
  451. }
  452. return max;
  453. }
  454. static void json_check_encode_depth(lua_State *l, json_config_t *cfg,
  455. int current_depth, strbuf_t *json)
  456. {
  457. /* Ensure there are enough slots free to traverse a table (key,
  458. * value) and push a string for a potential error message.
  459. *
  460. * Unlike "decode", the key and value are still on the stack when
  461. * lua_checkstack() is called. Hence an extra slot for luaL_error()
  462. * below is required just in case the next check to lua_checkstack()
  463. * fails.
  464. *
  465. * While this won't cause a crash due to the EXTRA_STACK reserve
  466. * slots, it would still be an improper use of the API. */
  467. if (current_depth <= cfg->encode_max_depth && lua_checkstack(l, 3))
  468. return;
  469. if (!cfg->encode_keep_buffer)
  470. strbuf_free(json);
  471. luaL_error(l, "Cannot serialise, excessive nesting (%d)",
  472. current_depth);
  473. }
  474. static void json_append_data(lua_State *l, json_config_t *cfg,
  475. int current_depth, strbuf_t *json);
  476. /* json_append_array args:
  477. * - lua_State
  478. * - JSON strbuf
  479. * - Size of passwd Lua array (top of stack) */
  480. static void json_append_array(lua_State *l, json_config_t *cfg, int current_depth,
  481. strbuf_t *json, int array_length)
  482. {
  483. int comma, i;
  484. strbuf_append_char(json, '[');
  485. comma = 0;
  486. for (i = 1; i <= array_length; i++) {
  487. if (comma)
  488. strbuf_append_char(json, ',');
  489. else
  490. comma = 1;
  491. lua_rawgeti(l, -1, i);
  492. json_append_data(l, cfg, current_depth, json);
  493. lua_pop(l, 1);
  494. }
  495. strbuf_append_char(json, ']');
  496. }
  497. static void json_append_number(lua_State *l, json_config_t *cfg,
  498. strbuf_t *json, int lindex)
  499. {
  500. int len;
  501. #if LUA_VERSION_NUM >= 503
  502. if (lua_isinteger(l, lindex)) {
  503. lua_Integer num = lua_tointeger(l, lindex);
  504. strbuf_ensure_empty_length(json, FPCONV_G_FMT_BUFSIZE); /* max length of int64 is 19 */
  505. len = sprintf(strbuf_empty_ptr(json), LUA_INTEGER_FMT, num);
  506. strbuf_extend_length(json, len);
  507. return;
  508. }
  509. #endif
  510. double num = lua_tonumber(l, lindex);
  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 = 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->value.integer = strtoll(json->ptr, &endptr, 0);
  864. if (json->ptr == endptr) {
  865. json_set_token_error(token, json, "invalid number");
  866. return;
  867. }
  868. if (*endptr == '.' || *endptr == 'e' || *endptr == 'E') {
  869. token->type = T_NUMBER;
  870. token->value.number = fpconv_strtod(json->ptr, &endptr);
  871. } else {
  872. token->type = T_INTEGER;
  873. }
  874. json->ptr = endptr; /* Skip the processed number */
  875. return;
  876. }
  877. /* Fills in the token struct.
  878. * T_STRING will return a pointer to the json_parse_t temporary string
  879. * T_ERROR will leave the json->ptr pointer at the error.
  880. */
  881. static void json_next_token(json_parse_t *json, json_token_t *token)
  882. {
  883. const json_token_type_t *ch2token = json->cfg->ch2token;
  884. int ch;
  885. /* Eat whitespace. */
  886. while (1) {
  887. ch = (unsigned char)*(json->ptr);
  888. token->type = ch2token[ch];
  889. if (token->type != T_WHITESPACE)
  890. break;
  891. json->ptr++;
  892. }
  893. /* Store location of new token. Required when throwing errors
  894. * for unexpected tokens (syntax errors). */
  895. token->index = json->ptr - json->data;
  896. /* Don't advance the pointer for an error or the end */
  897. if (token->type == T_ERROR) {
  898. json_set_token_error(token, json, "invalid token");
  899. return;
  900. }
  901. if (token->type == T_END) {
  902. return;
  903. }
  904. /* Found a known single character token, advance index and return */
  905. if (token->type != T_UNKNOWN) {
  906. json->ptr++;
  907. return;
  908. }
  909. /* Process characters which triggered T_UNKNOWN
  910. *
  911. * Must use strncmp() to match the front of the JSON string.
  912. * JSON identifier must be lowercase.
  913. * When strict_numbers if disabled, either case is allowed for
  914. * Infinity/NaN (since we are no longer following the spec..) */
  915. if (ch == '"') {
  916. json_next_string_token(json, token);
  917. return;
  918. } else if (ch == '-' || ('0' <= ch && ch <= '9')) {
  919. if (!json->cfg->decode_invalid_numbers && json_is_invalid_number(json)) {
  920. json_set_token_error(token, json, "invalid number");
  921. return;
  922. }
  923. json_next_number_token(json, token);
  924. return;
  925. } else if (!strncmp(json->ptr, "true", 4)) {
  926. token->type = T_BOOLEAN;
  927. token->value.boolean = 1;
  928. json->ptr += 4;
  929. return;
  930. } else if (!strncmp(json->ptr, "false", 5)) {
  931. token->type = T_BOOLEAN;
  932. token->value.boolean = 0;
  933. json->ptr += 5;
  934. return;
  935. } else if (!strncmp(json->ptr, "null", 4)) {
  936. token->type = T_NULL;
  937. json->ptr += 4;
  938. return;
  939. } else if (json->cfg->decode_invalid_numbers &&
  940. json_is_invalid_number(json)) {
  941. /* When decode_invalid_numbers is enabled, only attempt to process
  942. * numbers we know are invalid JSON (Inf, NaN, hex)
  943. * This is required to generate an appropriate token error,
  944. * otherwise all bad tokens will register as "invalid number"
  945. */
  946. json_next_number_token(json, token);
  947. return;
  948. }
  949. /* Token starts with t/f/n but isn't recognised above. */
  950. json_set_token_error(token, json, "invalid token");
  951. }
  952. /* This function does not return.
  953. * DO NOT CALL WITH DYNAMIC MEMORY ALLOCATED.
  954. * The only supported exception is the temporary parser string
  955. * json->tmp struct.
  956. * json and token should exist on the stack somewhere.
  957. * luaL_error() will long_jmp and release the stack */
  958. static void json_throw_parse_error(lua_State *l, json_parse_t *json,
  959. const char *exp, json_token_t *token)
  960. {
  961. const char *found;
  962. strbuf_free(json->tmp);
  963. if (token->type == T_ERROR)
  964. found = token->value.string;
  965. else
  966. found = json_token_type_name[token->type];
  967. /* Note: token->index is 0 based, display starting from 1 */
  968. luaL_error(l, "Expected %s but found %s at character %d",
  969. exp, found, token->index + 1);
  970. }
  971. static inline void json_decode_ascend(json_parse_t *json)
  972. {
  973. json->current_depth--;
  974. }
  975. static void json_decode_descend(lua_State *l, json_parse_t *json, int slots)
  976. {
  977. json->current_depth++;
  978. if (json->current_depth <= json->cfg->decode_max_depth &&
  979. lua_checkstack(l, slots)) {
  980. return;
  981. }
  982. strbuf_free(json->tmp);
  983. luaL_error(l, "Found too many nested data structures (%d) at character %d",
  984. json->current_depth, json->ptr - json->data);
  985. }
  986. static void json_parse_object_context(lua_State *l, json_parse_t *json)
  987. {
  988. json_token_t token;
  989. /* 3 slots required:
  990. * .., table, key, value */
  991. json_decode_descend(l, json, 3);
  992. lua_newtable(l);
  993. json_next_token(json, &token);
  994. /* Handle empty objects */
  995. if (token.type == T_OBJ_END) {
  996. json_decode_ascend(json);
  997. return;
  998. }
  999. while (1) {
  1000. if (token.type != T_STRING)
  1001. json_throw_parse_error(l, json, "object key string", &token);
  1002. /* Push key */
  1003. lua_pushlstring(l, token.value.string, token.string_len);
  1004. json_next_token(json, &token);
  1005. if (token.type != T_COLON)
  1006. json_throw_parse_error(l, json, "colon", &token);
  1007. /* Fetch value */
  1008. json_next_token(json, &token);
  1009. json_process_value(l, json, &token);
  1010. /* Set key = value */
  1011. lua_rawset(l, -3);
  1012. json_next_token(json, &token);
  1013. if (token.type == T_OBJ_END) {
  1014. json_decode_ascend(json);
  1015. return;
  1016. }
  1017. if (token.type != T_COMMA)
  1018. json_throw_parse_error(l, json, "comma or object end", &token);
  1019. json_next_token(json, &token);
  1020. }
  1021. }
  1022. /* Handle the array context */
  1023. static void json_parse_array_context(lua_State *l, json_parse_t *json)
  1024. {
  1025. json_token_t token;
  1026. int i;
  1027. /* 2 slots required:
  1028. * .., table, value */
  1029. json_decode_descend(l, json, 2);
  1030. lua_newtable(l);
  1031. json_next_token(json, &token);
  1032. /* Handle empty arrays */
  1033. if (token.type == T_ARR_END) {
  1034. json_decode_ascend(json);
  1035. return;
  1036. }
  1037. for (i = 1; ; i++) {
  1038. json_process_value(l, json, &token);
  1039. lua_rawseti(l, -2, i); /* arr[i] = value */
  1040. json_next_token(json, &token);
  1041. if (token.type == T_ARR_END) {
  1042. json_decode_ascend(json);
  1043. return;
  1044. }
  1045. if (token.type != T_COMMA)
  1046. json_throw_parse_error(l, json, "comma or array end", &token);
  1047. json_next_token(json, &token);
  1048. }
  1049. }
  1050. /* Handle the "value" context */
  1051. static void json_process_value(lua_State *l, json_parse_t *json,
  1052. json_token_t *token)
  1053. {
  1054. switch (token->type) {
  1055. case T_STRING:
  1056. lua_pushlstring(l, token->value.string, token->string_len);
  1057. break;;
  1058. case T_NUMBER:
  1059. lua_pushnumber(l, token->value.number);
  1060. break;;
  1061. case T_INTEGER:
  1062. lua_pushinteger(l, token->value.integer);
  1063. break;;
  1064. case T_BOOLEAN:
  1065. lua_pushboolean(l, token->value.boolean);
  1066. break;;
  1067. case T_OBJ_BEGIN:
  1068. json_parse_object_context(l, json);
  1069. break;;
  1070. case T_ARR_BEGIN:
  1071. json_parse_array_context(l, json);
  1072. break;;
  1073. case T_NULL:
  1074. /* In Lua, setting "t[k] = nil" will delete k from the table.
  1075. * Hence a NULL pointer lightuserdata object is used instead */
  1076. lua_pushlightuserdata(l, NULL);
  1077. break;;
  1078. default:
  1079. json_throw_parse_error(l, json, "value", token);
  1080. }
  1081. }
  1082. static int json_decode(lua_State *l)
  1083. {
  1084. json_parse_t json;
  1085. json_token_t token;
  1086. size_t json_len;
  1087. luaL_argcheck(l, lua_gettop(l) == 1, 1, "expected 1 argument");
  1088. json.cfg = json_fetch_config(l);
  1089. json.data = luaL_checklstring(l, 1, &json_len);
  1090. json.current_depth = 0;
  1091. json.ptr = json.data;
  1092. /* Detect Unicode other than UTF-8 (see RFC 4627, Sec 3)
  1093. *
  1094. * CJSON can support any simple data type, hence only the first
  1095. * character is guaranteed to be ASCII (at worst: '"'). This is
  1096. * still enough to detect whether the wrong encoding is in use. */
  1097. if (json_len >= 2 && (!json.data[0] || !json.data[1]))
  1098. luaL_error(l, "JSON parser does not support UTF-16 or UTF-32");
  1099. /* Ensure the temporary buffer can hold the entire string.
  1100. * This means we no longer need to do length checks since the decoded
  1101. * string must be smaller than the entire json string */
  1102. json.tmp = strbuf_new(json_len);
  1103. json_next_token(&json, &token);
  1104. json_process_value(l, &json, &token);
  1105. /* Ensure there is no more input left */
  1106. json_next_token(&json, &token);
  1107. if (token.type != T_END)
  1108. json_throw_parse_error(l, &json, "the end", &token);
  1109. strbuf_free(json.tmp);
  1110. return 1;
  1111. }
  1112. /* ===== INITIALISATION ===== */
  1113. #if !defined(LUA_VERSION_NUM) || LUA_VERSION_NUM < 502
  1114. /* Compatibility for Lua 5.1.
  1115. *
  1116. * luaL_setfuncs() is used to create a module table where the functions have
  1117. * json_config_t as their first upvalue. Code borrowed from Lua 5.2 source. */
  1118. static void luaL_setfuncs (lua_State *l, const luaL_Reg *reg, int nup)
  1119. {
  1120. int i;
  1121. luaL_checkstack(l, nup, "too many upvalues");
  1122. for (; reg->name != NULL; reg++) { /* fill the table with given functions */
  1123. for (i = 0; i < nup; i++) /* copy upvalues to the top */
  1124. lua_pushvalue(l, -nup);
  1125. lua_pushcclosure(l, reg->func, nup); /* closure with those upvalues */
  1126. lua_setfield(l, -(nup + 2), reg->name);
  1127. }
  1128. lua_pop(l, nup); /* remove upvalues */
  1129. }
  1130. #endif
  1131. /* Call target function in protected mode with all supplied args.
  1132. * Assumes target function only returns a single non-nil value.
  1133. * Convert and return thrown errors as: nil, "error message" */
  1134. static int json_protect_conversion(lua_State *l)
  1135. {
  1136. int err;
  1137. /* Deliberately throw an error for invalid arguments */
  1138. luaL_argcheck(l, lua_gettop(l) == 1, 1, "expected 1 argument");
  1139. /* pcall() the function stored as upvalue(1) */
  1140. lua_pushvalue(l, lua_upvalueindex(1));
  1141. lua_insert(l, 1);
  1142. err = lua_pcall(l, 1, 1, 0);
  1143. if (!err)
  1144. return 1;
  1145. if (err == LUA_ERRRUN) {
  1146. lua_pushnil(l);
  1147. lua_insert(l, -2);
  1148. return 2;
  1149. }
  1150. /* Since we are not using a custom error handler, the only remaining
  1151. * errors are memory related */
  1152. return luaL_error(l, "Memory allocation error in CJSON protected call");
  1153. }
  1154. /* Return cjson module table */
  1155. static int lua_cjson_new(lua_State *l)
  1156. {
  1157. luaL_Reg reg[] = {
  1158. { "encode", json_encode },
  1159. { "decode", json_decode },
  1160. { "encode_sparse_array", json_cfg_encode_sparse_array },
  1161. { "encode_max_depth", json_cfg_encode_max_depth },
  1162. { "decode_max_depth", json_cfg_decode_max_depth },
  1163. { "encode_number_precision", json_cfg_encode_number_precision },
  1164. { "encode_keep_buffer", json_cfg_encode_keep_buffer },
  1165. { "encode_invalid_numbers", json_cfg_encode_invalid_numbers },
  1166. { "decode_invalid_numbers", json_cfg_decode_invalid_numbers },
  1167. { "new", lua_cjson_new },
  1168. { NULL, NULL }
  1169. };
  1170. /* Initialise number conversions */
  1171. fpconv_init();
  1172. /* cjson module table */
  1173. lua_newtable(l);
  1174. /* Register functions with config data as upvalue */
  1175. json_create_config(l);
  1176. luaL_setfuncs(l, reg, 1);
  1177. /* Set cjson.null */
  1178. lua_pushlightuserdata(l, NULL);
  1179. lua_setfield(l, -2, "null");
  1180. /* Set module name / version fields */
  1181. lua_pushliteral(l, CJSON_MODNAME);
  1182. lua_setfield(l, -2, "_NAME");
  1183. lua_pushliteral(l, CJSON_VERSION);
  1184. lua_setfield(l, -2, "_VERSION");
  1185. return 1;
  1186. }
  1187. /* Return cjson.safe module table */
  1188. static int lua_cjson_safe_new(lua_State *l)
  1189. {
  1190. const char *func[] = { "decode", "encode", NULL };
  1191. int i;
  1192. lua_cjson_new(l);
  1193. /* Fix new() method */
  1194. lua_pushcfunction(l, lua_cjson_safe_new);
  1195. lua_setfield(l, -2, "new");
  1196. for (i = 0; func[i]; i++) {
  1197. lua_getfield(l, -1, func[i]);
  1198. lua_pushcclosure(l, json_protect_conversion, 1);
  1199. lua_setfield(l, -2, func[i]);
  1200. }
  1201. return 1;
  1202. }
  1203. int luaopen_cjson(lua_State *l)
  1204. {
  1205. lua_cjson_new(l);
  1206. #ifdef ENABLE_CJSON_GLOBAL
  1207. /* Register a global "cjson" table. */
  1208. lua_pushvalue(l, -1);
  1209. lua_setglobal(l, CJSON_MODNAME);
  1210. #endif
  1211. /* Return cjson table */
  1212. return 1;
  1213. }
  1214. int luaopen_cjson_safe(lua_State *l)
  1215. {
  1216. lua_cjson_safe_new(l);
  1217. /* Return cjson.safe table */
  1218. return 1;
  1219. }
  1220. /* vi:ai et sw=4 ts=4:
  1221. */