lua_cjson.c 34 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214
  1. /* CJSON - JSON support for Lua
  2. *
  3. * Copyright (c) 2010-2011 Mark Pulford <[email protected]>
  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.
  29. * - Javascript comments are not part of the JSON spec, and are not
  30. * supported.
  31. *
  32. * Note: Decoding is slower than encoding. Lua spends significant
  33. * time (30%) managing tables when parsing JSON since it is
  34. * difficult to know object/array sizes ahead of time.
  35. */
  36. #include <assert.h>
  37. #include <string.h>
  38. #include <math.h>
  39. #include <lua.h>
  40. #include <lauxlib.h>
  41. #include "strbuf.h"
  42. #define DEFAULT_SPARSE_CONVERT 0
  43. #define DEFAULT_SPARSE_RATIO 2
  44. #define DEFAULT_SPARSE_SAFE 10
  45. #define DEFAULT_MAX_DEPTH 20
  46. #define DEFAULT_ENCODE_REFUSE_BADNUM 1
  47. #define DEFAULT_DECODE_REFUSE_BADNUM 0
  48. typedef enum {
  49. T_OBJ_BEGIN,
  50. T_OBJ_END,
  51. T_ARR_BEGIN,
  52. T_ARR_END,
  53. T_STRING,
  54. T_NUMBER,
  55. T_BOOLEAN,
  56. T_NULL,
  57. T_COLON,
  58. T_COMMA,
  59. T_END,
  60. T_WHITESPACE,
  61. T_ERROR,
  62. T_UNKNOWN
  63. } json_token_type_t;
  64. static const char *json_token_type_name[] = {
  65. "T_OBJ_BEGIN",
  66. "T_OBJ_END",
  67. "T_ARR_BEGIN",
  68. "T_ARR_END",
  69. "T_STRING",
  70. "T_NUMBER",
  71. "T_BOOLEAN",
  72. "T_NULL",
  73. "T_COLON",
  74. "T_COMMA",
  75. "T_END",
  76. "T_WHITESPACE",
  77. "T_ERROR",
  78. "T_UNKNOWN",
  79. NULL
  80. };
  81. typedef struct {
  82. json_token_type_t ch2token[256];
  83. char escape2char[256]; /* Decoding */
  84. #if 0
  85. char escapes[35][8]; /* Pre-generated escape string buffer */
  86. char *char2escape[256]; /* Encoding */
  87. #endif
  88. strbuf_t encode_buf;
  89. int current_depth;
  90. int encode_sparse_convert;
  91. int encode_sparse_ratio;
  92. int encode_sparse_safe;
  93. int encode_max_depth;
  94. int encode_refuse_badnum;
  95. int decode_refuse_badnum;
  96. } json_config_t;
  97. typedef struct {
  98. const char *data;
  99. int index;
  100. strbuf_t *tmp; /* Temporary storage for strings */
  101. json_config_t *cfg;
  102. } json_parse_t;
  103. typedef struct {
  104. json_token_type_t type;
  105. int index;
  106. union {
  107. const char *string;
  108. double number;
  109. int boolean;
  110. } value;
  111. int string_len;
  112. } json_token_t;
  113. static const char *char2escape[256] = {
  114. "\\u0000", "\\u0001", "\\u0002", "\\u0003",
  115. "\\u0004", "\\u0005", "\\u0006", "\\u0007",
  116. "\\b", "\\t", "\\n", "\\u000b",
  117. "\\f", "\\r", "\\u000e", "\\u000f",
  118. "\\u0010", "\\u0011", "\\u0012", "\\u0013",
  119. "\\u0014", "\\u0015", "\\u0016", "\\u0017",
  120. "\\u0018", "\\u0019", "\\u001a", "\\u001b",
  121. "\\u001c", "\\u001d", "\\u001e", "\\u001f",
  122. NULL, NULL, "\\\"", NULL, NULL, NULL, NULL, NULL,
  123. NULL, NULL, NULL, NULL, NULL, NULL, NULL, "\\/",
  124. NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL,
  125. NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL,
  126. NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL,
  127. NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL,
  128. NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL,
  129. NULL, NULL, NULL, NULL, "\\\\", NULL, NULL, NULL,
  130. NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL,
  131. NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL,
  132. NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL,
  133. NULL, NULL, NULL, NULL, NULL, NULL, NULL, "\\u007f",
  134. NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL,
  135. NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL,
  136. NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL,
  137. NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL,
  138. NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL,
  139. NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL,
  140. NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL,
  141. NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL,
  142. NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL,
  143. NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL,
  144. NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL,
  145. NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL,
  146. NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL,
  147. NULL, 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. };
  151. static int json_config_key;
  152. /* ===== CONFIGURATION ===== */
  153. static json_config_t *json_fetch_config(lua_State *l)
  154. {
  155. json_config_t *cfg;
  156. lua_pushlightuserdata(l, &json_config_key);
  157. lua_gettable(l, LUA_REGISTRYINDEX);
  158. cfg = lua_touserdata(l, -1);
  159. if (!cfg)
  160. luaL_error(l, "BUG: Unable to fetch cjson configuration");
  161. lua_pop(l, 1);
  162. return cfg;
  163. }
  164. static void json_verify_arg_count(lua_State *l, int args)
  165. {
  166. luaL_argcheck(l, lua_gettop(l) <= args, args + 1,
  167. "found too many arguments");
  168. }
  169. /* Configures handling of extremely sparse arrays:
  170. * convert: Convert extremely sparse arrays into objects? Otherwise error.
  171. * ratio: 0: always allow sparse; 1: never allow sparse; >1: use ratio
  172. * safe: Always use an array when the max index <= safe */
  173. static int json_cfg_encode_sparse_array(lua_State *l)
  174. {
  175. json_config_t *cfg;
  176. int val;
  177. json_verify_arg_count(l, 3);
  178. cfg = json_fetch_config(l);
  179. switch (lua_gettop(l)) {
  180. case 3:
  181. val = luaL_checkinteger(l, 3);
  182. luaL_argcheck(l, val >= 0, 3, "expected integer >= 0");
  183. cfg->encode_sparse_safe = val;
  184. case 2:
  185. val = luaL_checkinteger(l, 2);
  186. luaL_argcheck(l, val >= 0, 2, "expected integer >= 0");
  187. cfg->encode_sparse_ratio = val;
  188. case 1:
  189. luaL_argcheck(l, lua_isboolean(l, 1), 1, "expected boolean");
  190. cfg->encode_sparse_convert = lua_toboolean(l, 1);
  191. }
  192. lua_pushboolean(l, cfg->encode_sparse_convert);
  193. lua_pushinteger(l, cfg->encode_sparse_ratio);
  194. lua_pushinteger(l, cfg->encode_sparse_safe);
  195. return 3;
  196. }
  197. /* Configures the maximum number of nested arrays/objects allowed when
  198. * encoding */
  199. static int json_cfg_encode_max_depth(lua_State *l)
  200. {
  201. json_config_t *cfg;
  202. int depth;
  203. json_verify_arg_count(l, 1);
  204. cfg = json_fetch_config(l);
  205. if (lua_gettop(l)) {
  206. depth = luaL_checkinteger(l, 1);
  207. luaL_argcheck(l, depth > 0, 1, "expected positive integer");
  208. cfg->encode_max_depth = depth;
  209. }
  210. lua_pushinteger(l, cfg->encode_max_depth);
  211. return 1;
  212. }
  213. /* On argument: decode enum and set config variables
  214. * **options must point to a NULL terminated array of 4 enums
  215. * Returns: current enum value */
  216. static void json_enum_option(lua_State *l, const char **options,
  217. int *opt1, int *opt2)
  218. {
  219. int setting;
  220. if (lua_gettop(l)) {
  221. if (lua_isboolean(l, 1))
  222. setting = lua_toboolean(l, 1) * 3;
  223. else
  224. setting = luaL_checkoption(l, 1, NULL, options);
  225. *opt1 = setting & 1 ? 1 : 0;
  226. *opt2 = setting & 2 ? 1 : 0;
  227. } else {
  228. setting = *opt1 | (*opt2 << 1);
  229. }
  230. if (setting)
  231. lua_pushstring(l, options[setting]);
  232. else
  233. lua_pushboolean(l, 0);
  234. }
  235. /* When enabled, rejects: NaN, Infinity, hexidecimal numbers */
  236. static int json_cfg_refuse_invalid_numbers(lua_State *l)
  237. {
  238. static const char *options_enc_dec[] = { "none", "encode", "decode",
  239. "both", NULL };
  240. json_config_t *cfg;
  241. json_verify_arg_count(l, 1);
  242. cfg = json_fetch_config(l);
  243. json_enum_option(l, options_enc_dec,
  244. &cfg->encode_refuse_badnum,
  245. &cfg->decode_refuse_badnum);
  246. return 1;
  247. }
  248. static int json_destroy_config(lua_State *l)
  249. {
  250. json_config_t *cfg;
  251. cfg = lua_touserdata(l, 1);
  252. if (cfg)
  253. strbuf_free(&cfg->encode_buf);
  254. cfg = NULL;
  255. return 0;
  256. }
  257. static void json_create_config(lua_State *l)
  258. {
  259. json_config_t *cfg;
  260. int i;
  261. cfg = lua_newuserdata(l, sizeof(*cfg));
  262. /* Create GC method to clean up strbuf */
  263. lua_newtable(l);
  264. lua_pushcfunction(l, json_destroy_config);
  265. lua_setfield(l, -2, "__gc");
  266. lua_setmetatable(l, -2);
  267. strbuf_init(&cfg->encode_buf, 0);
  268. cfg->encode_sparse_convert = DEFAULT_SPARSE_CONVERT;
  269. cfg->encode_sparse_ratio = DEFAULT_SPARSE_RATIO;
  270. cfg->encode_sparse_safe = DEFAULT_SPARSE_SAFE;
  271. cfg->encode_max_depth = DEFAULT_MAX_DEPTH;
  272. cfg->encode_refuse_badnum = DEFAULT_ENCODE_REFUSE_BADNUM;
  273. cfg->decode_refuse_badnum = DEFAULT_DECODE_REFUSE_BADNUM;
  274. /* Decoding init */
  275. /* Tag all characters as an error */
  276. for (i = 0; i < 256; i++)
  277. cfg->ch2token[i] = T_ERROR;
  278. /* Set tokens that require no further processing */
  279. cfg->ch2token['{'] = T_OBJ_BEGIN;
  280. cfg->ch2token['}'] = T_OBJ_END;
  281. cfg->ch2token['['] = T_ARR_BEGIN;
  282. cfg->ch2token[']'] = T_ARR_END;
  283. cfg->ch2token[','] = T_COMMA;
  284. cfg->ch2token[':'] = T_COLON;
  285. cfg->ch2token['\0'] = T_END;
  286. cfg->ch2token[' '] = T_WHITESPACE;
  287. cfg->ch2token['\t'] = T_WHITESPACE;
  288. cfg->ch2token['\n'] = T_WHITESPACE;
  289. cfg->ch2token['\r'] = T_WHITESPACE;
  290. /* Update characters that require further processing */
  291. cfg->ch2token['f'] = T_UNKNOWN; /* false? */
  292. cfg->ch2token['i'] = T_UNKNOWN; /* inf, ininity? */
  293. cfg->ch2token['I'] = T_UNKNOWN;
  294. cfg->ch2token['n'] = T_UNKNOWN; /* null, nan? */
  295. cfg->ch2token['N'] = T_UNKNOWN;
  296. cfg->ch2token['t'] = T_UNKNOWN; /* true? */
  297. cfg->ch2token['"'] = T_UNKNOWN; /* string? */
  298. cfg->ch2token['+'] = T_UNKNOWN; /* number? */
  299. cfg->ch2token['-'] = T_UNKNOWN;
  300. for (i = 0; i < 10; i++)
  301. cfg->ch2token['0' + i] = T_UNKNOWN;
  302. /* Lookup table for parsing escape characters */
  303. for (i = 0; i < 256; i++)
  304. cfg->escape2char[i] = 0; /* String error */
  305. cfg->escape2char['"'] = '"';
  306. cfg->escape2char['\\'] = '\\';
  307. cfg->escape2char['/'] = '/';
  308. cfg->escape2char['b'] = '\b';
  309. cfg->escape2char['t'] = '\t';
  310. cfg->escape2char['n'] = '\n';
  311. cfg->escape2char['f'] = '\f';
  312. cfg->escape2char['r'] = '\r';
  313. cfg->escape2char['u'] = 'u'; /* Unicode parsing required */
  314. #if 0
  315. /* Initialise separate storage for pre-generated escape codes.
  316. * Escapes 0-31 map directly, 34, 92, 127 follow afterwards to
  317. * save memory. */
  318. for (i = 0 ; i < 32; i++)
  319. sprintf(cfg->escapes[i], "\\u%04x", i);
  320. strcpy(cfg->escapes[8], "\b"); /* Override simpler escapes */
  321. strcpy(cfg->escapes[9], "\t");
  322. strcpy(cfg->escapes[10], "\n");
  323. strcpy(cfg->escapes[12], "\f");
  324. strcpy(cfg->escapes[13], "\r");
  325. strcpy(cfg->escapes[32], "\\\""); /* chr(34) */
  326. strcpy(cfg->escapes[33], "\\\\"); /* chr(92) */
  327. sprintf(cfg->escapes[34], "\\u%04x", 127); /* char(127) */
  328. /* Initialise encoding escape lookup table */
  329. for (i = 0; i < 32; i++)
  330. cfg->char2escape[i] = cfg->escapes[i];
  331. for (i = 32; i < 256; i++)
  332. cfg->char2escape[i] = NULL;
  333. cfg->char2escape[34] = cfg->escapes[32];
  334. cfg->char2escape[92] = cfg->escapes[33];
  335. cfg->char2escape[127] = cfg->escapes[34];
  336. #endif
  337. }
  338. /* ===== ENCODING ===== */
  339. static void json_encode_exception(lua_State *l, int lindex, const char *reason)
  340. {
  341. luaL_error(l, "Cannot serialise %s: %s",
  342. lua_typename(l, lua_type(l, lindex)), reason);
  343. }
  344. /* json_append_string args:
  345. * - lua_State
  346. * - JSON strbuf
  347. * - String (Lua stack index)
  348. *
  349. * Returns nothing. Doesn't remove string from Lua stack */
  350. static void json_append_string(lua_State *l, strbuf_t *json, int lindex)
  351. {
  352. const char *escstr;
  353. int i;
  354. const char *str;
  355. size_t len;
  356. str = lua_tolstring(l, lindex, &len);
  357. /* Worst case is len * 6 (all unicode escapes).
  358. * This buffer is reused constantly for small strings
  359. * If there are any excess pages, they won't be hit anyway.
  360. * This gains ~5% speedup. */
  361. strbuf_ensure_empty_length(json, len * 6 + 2);
  362. strbuf_append_char_unsafe(json, '\"');
  363. for (i = 0; i < len; i++) {
  364. escstr = char2escape[(unsigned char)str[i]];
  365. if (escstr)
  366. strbuf_append_string(json, escstr);
  367. else
  368. strbuf_append_char_unsafe(json, str[i]);
  369. }
  370. strbuf_append_char_unsafe(json, '\"');
  371. }
  372. /* Find the size of the array on the top of the Lua stack
  373. * -1 object (not a pure array)
  374. * >=0 elements in array
  375. */
  376. static int lua_array_length(lua_State *l, json_config_t *cfg)
  377. {
  378. double k;
  379. int max;
  380. int items;
  381. max = 0;
  382. items = 0;
  383. lua_pushnil(l);
  384. /* table, startkey */
  385. while (lua_next(l, -2) != 0) {
  386. /* table, key, value */
  387. if (lua_isnumber(l, -2) &&
  388. (k = lua_tonumber(l, -2))) {
  389. /* Integer >= 1 ? */
  390. if (floor(k) == k && k >= 1) {
  391. if (k > max)
  392. max = k;
  393. items++;
  394. lua_pop(l, 1);
  395. continue;
  396. }
  397. }
  398. /* Must not be an array (non integer key) */
  399. lua_pop(l, 2);
  400. return -1;
  401. }
  402. /* Encode very sparse arrays as objects (if enabled) */
  403. if (cfg->encode_sparse_ratio > 0 &&
  404. max > items * cfg->encode_sparse_ratio &&
  405. max > cfg->encode_sparse_safe) {
  406. if (!cfg->encode_sparse_convert)
  407. json_encode_exception(l, -1, "excessively sparse array");
  408. return -1;
  409. }
  410. return max;
  411. }
  412. static void json_encode_descend(lua_State *l, json_config_t *cfg)
  413. {
  414. cfg->current_depth++;
  415. if (cfg->current_depth > cfg->encode_max_depth) {
  416. luaL_error(l, "Cannot serialise, excessive nesting (%d)",
  417. cfg->current_depth);
  418. }
  419. }
  420. static void json_append_data(lua_State *l, json_config_t *cfg, strbuf_t *json);
  421. /* json_append_array args:
  422. * - lua_State
  423. * - JSON strbuf
  424. * - Size of passwd Lua array (top of stack) */
  425. static void json_append_array(lua_State *l, json_config_t *cfg, strbuf_t *json,
  426. int array_length)
  427. {
  428. int comma, i;
  429. json_encode_descend(l, cfg);
  430. strbuf_append_mem(json, "[ ", 2);
  431. comma = 0;
  432. for (i = 1; i <= array_length; i++) {
  433. if (comma)
  434. strbuf_append_mem(json, ", ", 2);
  435. else
  436. comma = 1;
  437. lua_rawgeti(l, -1, i);
  438. json_append_data(l, cfg, json);
  439. lua_pop(l, 1);
  440. }
  441. strbuf_append_mem(json, " ]", 2);
  442. cfg->current_depth--;
  443. }
  444. static void json_append_number(lua_State *l, strbuf_t *json, int index,
  445. int refuse_badnum)
  446. {
  447. double num = lua_tonumber(l, index);
  448. if (refuse_badnum && (isinf(num) || isnan(num)))
  449. json_encode_exception(l, index, "must not be NaN or Inf");
  450. strbuf_append_number(json, num);
  451. }
  452. static void json_append_object(lua_State *l, json_config_t *cfg,
  453. strbuf_t *json)
  454. {
  455. int comma, keytype;
  456. json_encode_descend(l, cfg);
  457. /* Object */
  458. strbuf_append_mem(json, "{ ", 2);
  459. lua_pushnil(l);
  460. /* table, startkey */
  461. comma = 0;
  462. while (lua_next(l, -2) != 0) {
  463. if (comma)
  464. strbuf_append_mem(json, ", ", 2);
  465. else
  466. comma = 1;
  467. /* table, key, value */
  468. keytype = lua_type(l, -2);
  469. if (keytype == LUA_TNUMBER) {
  470. strbuf_append_char(json, '"');
  471. json_append_number(l, json, -2, cfg->encode_refuse_badnum);
  472. strbuf_append_mem(json, "\": ", 3);
  473. } else if (keytype == LUA_TSTRING) {
  474. json_append_string(l, json, -2);
  475. strbuf_append_mem(json, ": ", 2);
  476. } else {
  477. json_encode_exception(l, -2,
  478. "table key must be a number or string");
  479. /* never returns */
  480. }
  481. /* table, key, value */
  482. json_append_data(l, cfg, json);
  483. lua_pop(l, 1);
  484. /* table, key */
  485. }
  486. strbuf_append_mem(json, " }", 2);
  487. cfg->current_depth--;
  488. }
  489. /* Serialise Lua data into JSON string. */
  490. static void json_append_data(lua_State *l, json_config_t *cfg, strbuf_t *json)
  491. {
  492. int len;
  493. switch (lua_type(l, -1)) {
  494. case LUA_TSTRING:
  495. json_append_string(l, json, -1);
  496. break;
  497. case LUA_TNUMBER:
  498. json_append_number(l, json, -1, cfg->encode_refuse_badnum);
  499. break;
  500. case LUA_TBOOLEAN:
  501. if (lua_toboolean(l, -1))
  502. strbuf_append_mem(json, "true", 4);
  503. else
  504. strbuf_append_mem(json, "false", 5);
  505. break;
  506. case LUA_TTABLE:
  507. len = lua_array_length(l, cfg);
  508. if (len > 0)
  509. json_append_array(l, cfg, json, len);
  510. else
  511. json_append_object(l, cfg, json);
  512. break;
  513. case LUA_TNIL:
  514. strbuf_append_mem(json, "null", 4);
  515. break;
  516. case LUA_TLIGHTUSERDATA:
  517. if (lua_touserdata(l, -1) == NULL) {
  518. strbuf_append_mem(json, "null", 4);
  519. break;
  520. }
  521. default:
  522. /* Remaining types (LUA_TFUNCTION, LUA_TUSERDATA, LUA_TTHREAD,
  523. * and LUA_TLIGHTUSERDATA) cannot be serialised */
  524. json_encode_exception(l, -1, "type not supported");
  525. /* never returns */
  526. }
  527. }
  528. static int json_encode(lua_State *l)
  529. {
  530. json_config_t *cfg;
  531. char *json;
  532. int len;
  533. /* Can't use json_verify_arg_count() since we need to ensure
  534. * there is only 1 argument */
  535. luaL_argcheck(l, lua_gettop(l) == 1, 1, "expected 1 argument");
  536. cfg = json_fetch_config(l);
  537. cfg->current_depth = 0;
  538. /* Reset persistent encode_buf. Avoids temporary allocation
  539. * for a single call. */
  540. strbuf_reset(&cfg->encode_buf);
  541. json_append_data(l, cfg, &cfg->encode_buf);
  542. json = strbuf_string(&cfg->encode_buf, &len);
  543. lua_pushlstring(l, json, len);
  544. return 1;
  545. }
  546. /* ===== DECODING ===== */
  547. static void json_process_value(lua_State *l, json_parse_t *json,
  548. json_token_t *token);
  549. static int hexdigit2int(char hex)
  550. {
  551. if ('0' <= hex && hex <= '9')
  552. return hex - '0';
  553. /* Force lowercase */
  554. hex |= 0x20;
  555. if ('a' <= hex && hex <= 'f')
  556. return 10 + hex - 'a';
  557. return -1;
  558. }
  559. static int decode_hex4(const char *hex)
  560. {
  561. int digit[4];
  562. int i;
  563. /* Convert ASCII hex digit to numeric digit
  564. * Note: this returns an error for invalid hex digits, including
  565. * NULL */
  566. for (i = 0; i < 4; i++) {
  567. digit[i] = hexdigit2int(hex[i]);
  568. if (digit[i] < 0) {
  569. return -1;
  570. }
  571. }
  572. return (digit[0] << 12) +
  573. (digit[1] << 8) +
  574. (digit[2] << 4) +
  575. digit[3];
  576. }
  577. /* Converts a Unicode codepoint to UTF-8.
  578. * Returns UTF-8 string length, and up to 4 bytes in *utf8 */
  579. static int codepoint_to_utf8(char *utf8, int codepoint)
  580. {
  581. /* 0xxxxxxx */
  582. if (codepoint <= 0x7F) {
  583. utf8[0] = codepoint;
  584. return 1;
  585. }
  586. /* 110xxxxx 10xxxxxx */
  587. if (codepoint <= 0x7FF) {
  588. utf8[0] = (codepoint >> 6) | 0xC0;
  589. utf8[1] = (codepoint & 0x3F) | 0x80;
  590. return 2;
  591. }
  592. /* 1110xxxx 10xxxxxx 10xxxxxx */
  593. if (codepoint <= 0xFFFF) {
  594. utf8[0] = (codepoint >> 12) | 0xE0;
  595. utf8[1] = ((codepoint >> 6) & 0x3F) | 0x80;
  596. utf8[2] = (codepoint & 0x3F) | 0x80;
  597. return 3;
  598. }
  599. /* 11110xxx 10xxxxxx 10xxxxxx 10xxxxxx */
  600. if (codepoint <= 0x1FFFFF) {
  601. utf8[0] = (codepoint >> 18) | 0xF0;
  602. utf8[1] = ((codepoint >> 12) & 0x3F) | 0x80;
  603. utf8[2] = ((codepoint >> 6) & 0x3F) | 0x80;
  604. utf8[3] = (codepoint & 0x3F) | 0x80;
  605. return 4;
  606. }
  607. return 0;
  608. }
  609. /* Called when index pointing to beginning of UTF-16 code escape: \uXXXX
  610. * \u is guaranteed to exist, but the remaining hex characters may be
  611. * missing.
  612. * Translate to UTF-8 and append to temporary token string.
  613. * Must advance index to the next character to be processed.
  614. * Returns: 0 success
  615. * -1 error
  616. */
  617. static int json_append_unicode_escape(json_parse_t *json)
  618. {
  619. char utf8[4]; /* Surrogate pairs require 4 UTF-8 bytes */
  620. int codepoint;
  621. int surrogate_low;
  622. int len;
  623. int escape_len = 6;
  624. /* Fetch UTF-16 code unit */
  625. codepoint = decode_hex4(&json->data[json->index + 2]);
  626. if (codepoint < 0)
  627. return -1;
  628. /* UTF-16 surrogate pairs take the following 2 byte form:
  629. * 11011 x yyyyyyyyyy
  630. * When x = 0: y is the high 10 bits of the codepoint
  631. * x = 1: y is the low 10 bits of the codepoint
  632. *
  633. * Check for a surrogate pair (high or low) */
  634. if ((codepoint & 0xF800) == 0xD800) {
  635. /* Error if the 1st surrogate is not high */
  636. if (codepoint & 0x400)
  637. return -1;
  638. /* Ensure the next code is a unicode escape */
  639. if (json->data[json->index + escape_len] != '\\' ||
  640. json->data[json->index + escape_len + 1] != 'u') {
  641. return -1;
  642. }
  643. /* Fetch the next codepoint */
  644. surrogate_low = decode_hex4(&json->data[json->index + 2 + escape_len]);
  645. if (surrogate_low < 0)
  646. return -1;
  647. /* Error if the 2nd code is not a low surrogate */
  648. if ((surrogate_low & 0xFC00) != 0xDC00)
  649. return -1;
  650. /* Calculate Unicode codepoint */
  651. codepoint = (codepoint & 0x3FF) << 10;
  652. surrogate_low &= 0x3FF;
  653. codepoint = (codepoint | surrogate_low) + 0x10000;
  654. escape_len = 12;
  655. }
  656. /* Convert codepoint to UTF-8 */
  657. len = codepoint_to_utf8(utf8, codepoint);
  658. if (!len)
  659. return -1;
  660. /* Append bytes and advance parse index */
  661. strbuf_append_mem_unsafe(json->tmp, utf8, len);
  662. json->index += escape_len;
  663. return 0;
  664. }
  665. static void json_set_token_error(json_token_t *token, json_parse_t *json,
  666. const char *errtype)
  667. {
  668. token->type = T_ERROR;
  669. token->index = json->index;
  670. token->value.string = errtype;
  671. }
  672. static void json_next_string_token(json_parse_t *json, json_token_t *token)
  673. {
  674. char *escape2char = json->cfg->escape2char;
  675. char ch;
  676. /* Caller must ensure a string is next */
  677. assert(json->data[json->index] == '"');
  678. /* Skip " */
  679. json->index++;
  680. /* json->tmp is the temporary strbuf used to accumulate the
  681. * decoded string value. */
  682. strbuf_reset(json->tmp);
  683. while ((ch = json->data[json->index]) != '"') {
  684. if (!ch) {
  685. /* Premature end of the string */
  686. json_set_token_error(token, json, "unexpected end of string");
  687. return;
  688. }
  689. /* Handle escapes */
  690. if (ch == '\\') {
  691. /* Fetch escape character */
  692. ch = json->data[json->index + 1];
  693. /* Translate escape code and append to tmp string */
  694. ch = escape2char[(unsigned char)ch];
  695. if (ch == 'u') {
  696. if (json_append_unicode_escape(json) == 0)
  697. continue;
  698. json_set_token_error(token, json,
  699. "invalid unicode escape code");
  700. return;
  701. }
  702. if (!ch) {
  703. json_set_token_error(token, json, "invalid escape code");
  704. return;
  705. }
  706. /* Skip '\' */
  707. json->index++;
  708. }
  709. /* Append normal character or translated single character
  710. * Unicode escapes are handled above */
  711. strbuf_append_char_unsafe(json->tmp, ch);
  712. json->index++;
  713. }
  714. json->index++; /* Eat final quote (") */
  715. strbuf_ensure_null(json->tmp);
  716. token->type = T_STRING;
  717. token->value.string = strbuf_string(json->tmp, &token->string_len);
  718. }
  719. /* JSON numbers should take the following form:
  720. * -?(0|[1-9]|[1-9][0-9]+)(.[0-9]+)?([eE][-+]?[0-9]+)?
  721. *
  722. * json_next_number_token() uses strtod() which allows other forms:
  723. * - numbers starting with '+'
  724. * - NaN, -NaN, infinity, -infinity
  725. * - hexidecimal numbers
  726. * - numbers with leading zeros
  727. *
  728. * json_is_invalid_number() detects "numbers" which may pass strtod()'s
  729. * error checking, but should not be allowed with strict JSON.
  730. *
  731. * json_is_invalid_number() may pass numbers which cause strtod()
  732. * to generate an error.
  733. */
  734. static int json_is_invalid_number(json_parse_t *json)
  735. {
  736. int i = json->index;
  737. /* Reject numbers starting with + */
  738. if (json->data[i] == '+')
  739. return 1;
  740. /* Skip minus sign if it exists */
  741. if (json->data[i] == '-')
  742. i++;
  743. /* Reject numbers starting with 0x, or leading zeros */
  744. if (json->data[i] == '0') {
  745. int ch2 = json->data[i + 1];
  746. if ((ch2 | 0x20) == 'x' || /* Hex */
  747. ('0' <= ch2 && ch2 <= '9')) /* Leading zero */
  748. return 1;
  749. return 0;
  750. } else if (json->data[i] <= '9') {
  751. return 0; /* Ordinary number */
  752. }
  753. /* Reject inf/nan */
  754. if (!strncasecmp(&json->data[i], "inf", 3))
  755. return 1;
  756. if (!strncasecmp(&json->data[i], "nan", 3))
  757. return 1;
  758. /* Pass all other numbers which may still be invalid, but
  759. * strtod() will catch them. */
  760. return 0;
  761. }
  762. static void json_next_number_token(json_parse_t *json, json_token_t *token)
  763. {
  764. const char *startptr;
  765. char *endptr;
  766. token->type = T_NUMBER;
  767. startptr = &json->data[json->index];
  768. token->value.number = strtod(&json->data[json->index], &endptr);
  769. if (startptr == endptr)
  770. json_set_token_error(token, json, "invalid number");
  771. else
  772. json->index += endptr - startptr; /* Skip the processed number */
  773. return;
  774. }
  775. /* Fills in the token struct.
  776. * T_STRING will return a pointer to the json_parse_t temporary string
  777. * T_ERROR will leave the json->index pointer at the error.
  778. */
  779. static void json_next_token(json_parse_t *json, json_token_t *token)
  780. {
  781. json_token_type_t *ch2token = json->cfg->ch2token;
  782. int ch;
  783. /* Eat whitespace. FIXME: UGLY */
  784. token->type = ch2token[(unsigned char)json->data[json->index]];
  785. while (token->type == T_WHITESPACE)
  786. token->type = ch2token[(unsigned char)json->data[++json->index]];
  787. token->index = json->index;
  788. /* Don't advance the pointer for an error or the end */
  789. if (token->type == T_ERROR) {
  790. json_set_token_error(token, json, "invalid token");
  791. return;
  792. }
  793. if (token->type == T_END) {
  794. return;
  795. }
  796. /* Found a known single character token, advance index and return */
  797. if (token->type != T_UNKNOWN) {
  798. json->index++;
  799. return;
  800. }
  801. /* Process characters which triggered T_UNKNOWN */
  802. ch = json->data[json->index];
  803. /* Must use strncmp() to match the front of the JSON string.
  804. * JSON identifier must be lowercase.
  805. * When strict_numbers if disabled, either case is allowed for
  806. * Infinity/NaN (since we are no longer following the spec..) */
  807. if (ch == '"') {
  808. json_next_string_token(json, token);
  809. return;
  810. } else if (ch == '-' || ('0' <= ch && ch <= '9')) {
  811. if (json->cfg->decode_refuse_badnum && json_is_invalid_number(json)) {
  812. json_set_token_error(token, json, "invalid number");
  813. return;
  814. }
  815. json_next_number_token(json, token);
  816. return;
  817. } else if (!strncmp(&json->data[json->index], "true", 4)) {
  818. token->type = T_BOOLEAN;
  819. token->value.boolean = 1;
  820. json->index += 4;
  821. return;
  822. } else if (!strncmp(&json->data[json->index], "false", 5)) {
  823. token->type = T_BOOLEAN;
  824. token->value.boolean = 0;
  825. json->index += 5;
  826. return;
  827. } else if (!strncmp(&json->data[json->index], "null", 4)) {
  828. token->type = T_NULL;
  829. json->index += 4;
  830. return;
  831. } else if (!json->cfg->decode_refuse_badnum &&
  832. json_is_invalid_number(json)) {
  833. /* When refuse_badnum is disabled, only attempt to process
  834. * numbers we know are invalid JSON (Inf, NaN, hex)
  835. * This is required to generate an appropriate token error,
  836. * otherwise all bad tokens will register as "invalid number"
  837. */
  838. json_next_number_token(json, token);
  839. return;
  840. }
  841. /* Token starts with t/f/n but isn't recognised above. */
  842. json_set_token_error(token, json, "invalid token");
  843. }
  844. /* This function does not return.
  845. * DO NOT CALL WITH DYNAMIC MEMORY ALLOCATED.
  846. * The only supported exception is the temporary parser string
  847. * json->tmp struct.
  848. * json and token should exist on the stack somewhere.
  849. * luaL_error() will long_jmp and release the stack */
  850. static void json_throw_parse_error(lua_State *l, json_parse_t *json,
  851. const char *exp, json_token_t *token)
  852. {
  853. const char *found;
  854. strbuf_free(json->tmp);
  855. if (token->type == T_ERROR)
  856. found = token->value.string;
  857. else
  858. found = json_token_type_name[token->type];
  859. /* Note: token->index is 0 based, display starting from 1 */
  860. luaL_error(l, "Expected %s but found %s at character %d",
  861. exp, found, token->index + 1);
  862. }
  863. static void json_parse_object_context(lua_State *l, json_parse_t *json)
  864. {
  865. json_token_t token;
  866. /* 3 slots required:
  867. * .., table, key, value */
  868. luaL_checkstack(l, 3, "too many nested data structures");
  869. lua_newtable(l);
  870. json_next_token(json, &token);
  871. /* Handle empty objects */
  872. if (token.type == T_OBJ_END) {
  873. return;
  874. }
  875. while (1) {
  876. if (token.type != T_STRING)
  877. json_throw_parse_error(l, json, "object key string", &token);
  878. /* Push key */
  879. lua_pushlstring(l, token.value.string, token.string_len);
  880. json_next_token(json, &token);
  881. if (token.type != T_COLON)
  882. json_throw_parse_error(l, json, "colon", &token);
  883. /* Fetch value */
  884. json_next_token(json, &token);
  885. json_process_value(l, json, &token);
  886. /* Set key = value */
  887. lua_rawset(l, -3);
  888. json_next_token(json, &token);
  889. if (token.type == T_OBJ_END)
  890. return;
  891. if (token.type != T_COMMA)
  892. json_throw_parse_error(l, json, "comma or object end", &token);
  893. json_next_token(json, &token);
  894. }
  895. }
  896. /* Handle the array context */
  897. static void json_parse_array_context(lua_State *l, json_parse_t *json)
  898. {
  899. json_token_t token;
  900. int i;
  901. /* 2 slots required:
  902. * .., table, value */
  903. luaL_checkstack(l, 2, "too many nested data structures");
  904. lua_newtable(l);
  905. json_next_token(json, &token);
  906. /* Handle empty arrays */
  907. if (token.type == T_ARR_END)
  908. return;
  909. for (i = 1; ; i++) {
  910. json_process_value(l, json, &token);
  911. lua_rawseti(l, -2, i); /* arr[i] = value */
  912. json_next_token(json, &token);
  913. if (token.type == T_ARR_END)
  914. return;
  915. if (token.type != T_COMMA)
  916. json_throw_parse_error(l, json, "comma or array end", &token);
  917. json_next_token(json, &token);
  918. }
  919. }
  920. /* Handle the "value" context */
  921. static void json_process_value(lua_State *l, json_parse_t *json,
  922. json_token_t *token)
  923. {
  924. switch (token->type) {
  925. case T_STRING:
  926. lua_pushlstring(l, token->value.string, token->string_len);
  927. break;;
  928. case T_NUMBER:
  929. lua_pushnumber(l, token->value.number);
  930. break;;
  931. case T_BOOLEAN:
  932. lua_pushboolean(l, token->value.boolean);
  933. break;;
  934. case T_OBJ_BEGIN:
  935. json_parse_object_context(l, json);
  936. break;;
  937. case T_ARR_BEGIN:
  938. json_parse_array_context(l, json);
  939. break;;
  940. case T_NULL:
  941. /* In Lua, setting "t[k] = nil" will delete k from the table.
  942. * Hence a NULL pointer lightuserdata object is used instead */
  943. lua_pushlightuserdata(l, NULL);
  944. break;;
  945. default:
  946. json_throw_parse_error(l, json, "value", token);
  947. }
  948. }
  949. /* json_text must be null terminated string */
  950. static void lua_json_decode(lua_State *l, const char *json_text, int json_len)
  951. {
  952. json_parse_t json;
  953. json_token_t token;
  954. json.cfg = json_fetch_config(l);
  955. json.data = json_text;
  956. json.index = 0;
  957. /* Ensure the temporary buffer can hold the entire string.
  958. * This means we no longer need to do length checks since the decoded
  959. * string must be smaller than the entire json string */
  960. json.tmp = strbuf_new(json_len);
  961. json_next_token(&json, &token);
  962. json_process_value(l, &json, &token);
  963. /* Ensure there is no more input left */
  964. json_next_token(&json, &token);
  965. if (token.type != T_END)
  966. json_throw_parse_error(l, &json, "the end", &token);
  967. strbuf_free(json.tmp);
  968. }
  969. static int json_decode(lua_State *l)
  970. {
  971. const char *json;
  972. size_t len;
  973. json_verify_arg_count(l, 1);
  974. json = luaL_checklstring(l, 1, &len);
  975. /* Detect Unicode other than UTF-8 (see RFC 4627, Sec 3)
  976. *
  977. * CJSON can support any simple data type, hence only the first
  978. * character is guaranteed to be ASCII (at worst: "). This is
  979. * still enough to detect whether the wrong encoding is in use. */
  980. if (len >= 2 && (!json[0] || !json[1]))
  981. luaL_error(l, "JSON parser does not support UTF-16 or UTF-32");
  982. lua_json_decode(l, json, len);
  983. return 1;
  984. }
  985. /* ===== INITIALISATION ===== */
  986. int luaopen_cjson(lua_State *l)
  987. {
  988. luaL_Reg reg[] = {
  989. { "encode", json_encode },
  990. { "decode", json_decode },
  991. { "encode_sparse_array", json_cfg_encode_sparse_array },
  992. { "encode_max_depth", json_cfg_encode_max_depth },
  993. { "refuse_invalid_numbers", json_cfg_refuse_invalid_numbers },
  994. { NULL, NULL }
  995. };
  996. /* Use json_fetch_config as a pointer.
  997. * It's faster than using a config string, and more unique */
  998. lua_pushlightuserdata(l, &json_config_key);
  999. json_create_config(l);
  1000. lua_settable(l, LUA_REGISTRYINDEX);
  1001. luaL_register(l, "cjson", reg);
  1002. /* Set cjson.null */
  1003. lua_pushlightuserdata(l, NULL);
  1004. lua_setfield(l, -2, "null");
  1005. /* Set cjson.version */
  1006. lua_pushliteral(l, VERSION);
  1007. lua_setfield(l, -2, "version");
  1008. /* Return cjson table */
  1009. return 1;
  1010. }
  1011. /* vi:ai et sw=4 ts=4:
  1012. */