lua_cjson.c 38 KB

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