lua_cjson.c 41 KB

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