You can not select more than 25 topics Topics must start with a chinese character,a letter or number, can include dashes ('-') and can be up to 35 characters long.

json_util.c 8.0 kB

12 years ago
12 years ago
12 years ago
12 years ago
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344
  1. /*
  2. * $Id: json_util.c,v 1.4 2006/01/30 23:07:57 mclark Exp $
  3. *
  4. * Copyright (c) 2004, 2005 Metaparadigm Pte. Ltd.
  5. * Michael Clark <michael@metaparadigm.com>
  6. *
  7. * This library is free software; you can redistribute it and/or modify
  8. * it under the terms of the MIT license. See COPYING for details.
  9. *
  10. */
  11. #include "config.h"
  12. #undef realloc
  13. #include "strerror_override.h"
  14. #include <stdarg.h>
  15. #include <stdio.h>
  16. #include <stdlib.h>
  17. #include <stddef.h>
  18. #include <limits.h>
  19. #include <string.h>
  20. #include <ctype.h>
  21. #ifdef HAVE_SYS_TYPES_H
  22. #include <sys/types.h>
  23. #endif /* HAVE_SYS_TYPES_H */
  24. #ifdef HAVE_SYS_STAT_H
  25. #include <sys/stat.h>
  26. #endif /* HAVE_SYS_STAT_H */
  27. #ifdef HAVE_FCNTL_H
  28. #include <fcntl.h>
  29. #endif /* HAVE_FCNTL_H */
  30. #ifdef HAVE_UNISTD_H
  31. # include <unistd.h>
  32. #endif /* HAVE_UNISTD_H */
  33. #ifdef WIN32
  34. # define WIN32_LEAN_AND_MEAN
  35. # include <windows.h>
  36. # include <io.h>
  37. #endif /* defined(WIN32) */
  38. #if !defined(HAVE_OPEN) && defined(WIN32)
  39. # define open _open
  40. #endif
  41. #include "snprintf_compat.h"
  42. #include "debug.h"
  43. #include "printbuf.h"
  44. #include "json_inttypes.h"
  45. #include "json_object.h"
  46. #include "json_tokener.h"
  47. #include "json_util.h"
  48. static int sscanf_is_broken = 0;
  49. static int sscanf_is_broken_testdone = 0;
  50. static void sscanf_is_broken_test(void);
  51. static int _json_object_to_fd(int fd, struct json_object *obj, int flags, const char *filename);
  52. static char _last_err[256] = "";
  53. const char *json_util_get_last_err()
  54. {
  55. if (_last_err[0] == '\0')
  56. return NULL;
  57. return _last_err;
  58. }
  59. void _set_last_err(const char *err_fmt, ...)
  60. {
  61. va_list ap;
  62. va_start(ap, err_fmt);
  63. // Ignore (attempted) overruns from snprintf
  64. (void)vsnprintf(_last_err, sizeof(_last_err), err_fmt, ap);
  65. va_end(ap);
  66. }
  67. struct json_object* json_object_from_fd(int fd)
  68. {
  69. struct printbuf *pb;
  70. struct json_object *obj;
  71. char buf[JSON_FILE_BUF_SIZE];
  72. int ret;
  73. if(!(pb = printbuf_new())) {
  74. _set_last_err("json_object_from_file: printbuf_new failed\n");
  75. return NULL;
  76. }
  77. while((ret = read(fd, buf, JSON_FILE_BUF_SIZE)) > 0) {
  78. printbuf_memappend(pb, buf, ret);
  79. }
  80. if(ret < 0) {
  81. _set_last_err("json_object_from_fd: error reading fd %d: %s\n", fd, strerror(errno));
  82. printbuf_free(pb);
  83. return NULL;
  84. }
  85. obj = json_tokener_parse(pb->buf);
  86. printbuf_free(pb);
  87. return obj;
  88. }
  89. struct json_object* json_object_from_file(const char *filename)
  90. {
  91. struct json_object *obj;
  92. int fd;
  93. if((fd = open(filename, O_RDONLY)) < 0) {
  94. _set_last_err("json_object_from_file: error opening file %s: %s\n",
  95. filename, strerror(errno));
  96. return NULL;
  97. }
  98. obj = json_object_from_fd(fd);
  99. close(fd);
  100. return obj;
  101. }
  102. /* extended "format and write to file" function */
  103. int json_object_to_file_ext(const char *filename, struct json_object *obj, int flags)
  104. {
  105. int fd, ret;
  106. int saved_errno;
  107. if (!obj) {
  108. _set_last_err("json_object_to_file: object is null\n");
  109. return -1;
  110. }
  111. if ((fd = open(filename, O_WRONLY | O_TRUNC | O_CREAT, 0644)) < 0) {
  112. _set_last_err("json_object_to_file: error opening file %s: %s\n",
  113. filename, strerror(errno));
  114. return -1;
  115. }
  116. ret = _json_object_to_fd(fd, obj, flags, filename);
  117. saved_errno = errno;
  118. close(fd);
  119. errno = saved_errno;
  120. return ret;
  121. }
  122. int json_object_to_fd(int fd, struct json_object *obj, int flags)
  123. {
  124. if (!obj) {
  125. _set_last_err("json_object_to_fd: object is null\n");
  126. return -1;
  127. }
  128. return _json_object_to_fd(fd, obj, flags, NULL);
  129. }
  130. static int _json_object_to_fd(int fd, struct json_object *obj, int flags, const char *filename)
  131. {
  132. int ret;
  133. const char *json_str;
  134. unsigned int wpos, wsize;
  135. filename = filename ? filename : "(fd)";
  136. if (!(json_str = json_object_to_json_string_ext(obj,flags))) {
  137. return -1;
  138. }
  139. wsize = (unsigned int)(strlen(json_str) & UINT_MAX); /* CAW: probably unnecessary, but the most 64bit safe */
  140. wpos = 0;
  141. while(wpos < wsize) {
  142. if((ret = write(fd, json_str + wpos, wsize-wpos)) < 0) {
  143. _set_last_err("json_object_to_file: error writing file %s: %s\n",
  144. filename, strerror(errno));
  145. return -1;
  146. }
  147. /* because of the above check for ret < 0, we can safely cast and add */
  148. wpos += (unsigned int)ret;
  149. }
  150. return 0;
  151. }
  152. // backwards compatible "format and write to file" function
  153. int json_object_to_file(const char *filename, struct json_object *obj)
  154. {
  155. return json_object_to_file_ext(filename, obj, JSON_C_TO_STRING_PLAIN);
  156. }
  157. int json_parse_double(const char *buf, double *retval)
  158. {
  159. char *end;
  160. *retval = strtod(buf, &end);
  161. return end == buf ? 1 : 0;
  162. }
  163. /*
  164. * Not all implementations of sscanf actually work properly.
  165. * Check whether the one we're currently using does, and if
  166. * it's broken, enable the workaround code.
  167. */
  168. static void sscanf_is_broken_test()
  169. {
  170. int64_t num64;
  171. int ret_errno, is_int64_min, ret_errno2, is_int64_max;
  172. (void)sscanf(" -01234567890123456789012345", "%" SCNd64, &num64);
  173. ret_errno = errno;
  174. is_int64_min = (num64 == INT64_MIN);
  175. (void)sscanf(" 01234567890123456789012345", "%" SCNd64, &num64);
  176. ret_errno2 = errno;
  177. is_int64_max = (num64 == INT64_MAX);
  178. if (ret_errno != ERANGE || !is_int64_min ||
  179. ret_errno2 != ERANGE || !is_int64_max)
  180. {
  181. MC_DEBUG("sscanf_is_broken_test failed, enabling workaround code\n");
  182. sscanf_is_broken = 1;
  183. }
  184. }
  185. int json_parse_int64(const char *buf, int64_t *retval)
  186. {
  187. int64_t num64;
  188. const char *buf_sig_digits;
  189. int orig_has_neg;
  190. int saved_errno;
  191. if (!sscanf_is_broken_testdone)
  192. {
  193. sscanf_is_broken_test();
  194. sscanf_is_broken_testdone = 1;
  195. }
  196. // Skip leading spaces
  197. while (isspace((int)*buf) && *buf)
  198. buf++;
  199. errno = 0; // sscanf won't always set errno, so initialize
  200. if (sscanf(buf, "%" SCNd64, &num64) != 1)
  201. {
  202. MC_DEBUG("Failed to parse, sscanf != 1\n");
  203. return 1;
  204. }
  205. saved_errno = errno;
  206. buf_sig_digits = buf;
  207. orig_has_neg = 0;
  208. if (*buf_sig_digits == '-')
  209. {
  210. buf_sig_digits++;
  211. orig_has_neg = 1;
  212. }
  213. // Not all sscanf implementations actually work
  214. if (sscanf_is_broken && saved_errno != ERANGE)
  215. {
  216. char buf_cmp[100];
  217. char *buf_cmp_start = buf_cmp;
  218. int recheck_has_neg = 0;
  219. int buf_cmp_len;
  220. // Skip leading zeros, but keep at least one digit
  221. while (buf_sig_digits[0] == '0' && buf_sig_digits[1] != '\0')
  222. buf_sig_digits++;
  223. if (num64 == 0) // assume all sscanf impl's will parse -0 to 0
  224. orig_has_neg = 0; // "-0" is the same as just plain "0"
  225. snprintf(buf_cmp_start, sizeof(buf_cmp), "%" PRId64, num64);
  226. if (*buf_cmp_start == '-')
  227. {
  228. recheck_has_neg = 1;
  229. buf_cmp_start++;
  230. }
  231. // No need to skip leading spaces or zeros here.
  232. buf_cmp_len = strlen(buf_cmp_start);
  233. /**
  234. * If the sign is different, or
  235. * some of the digits are different, or
  236. * there is another digit present in the original string
  237. * then we have NOT successfully parsed the value.
  238. */
  239. if (orig_has_neg != recheck_has_neg ||
  240. strncmp(buf_sig_digits, buf_cmp_start, strlen(buf_cmp_start)) != 0 ||
  241. ((int)strlen(buf_sig_digits) != buf_cmp_len &&
  242. isdigit((int)buf_sig_digits[buf_cmp_len])
  243. )
  244. )
  245. {
  246. saved_errno = ERANGE;
  247. }
  248. }
  249. // Not all sscanf impl's set the value properly when out of range.
  250. // Always do this, even for properly functioning implementations,
  251. // since it shouldn't slow things down much.
  252. if (saved_errno == ERANGE)
  253. {
  254. if (orig_has_neg)
  255. num64 = INT64_MIN;
  256. else
  257. num64 = INT64_MAX;
  258. }
  259. *retval = num64;
  260. return 0;
  261. }
  262. #ifndef HAVE_REALLOC
  263. void* rpl_realloc(void* p, size_t n)
  264. {
  265. if (n == 0)
  266. n = 1;
  267. if (p == 0)
  268. return malloc(n);
  269. return realloc(p, n);
  270. }
  271. #endif
  272. #define NELEM(a) (sizeof(a) / sizeof(a[0]))
  273. static const char* json_type_name[] = {
  274. /* If you change this, be sure to update the enum json_type definition too */
  275. "null",
  276. "boolean",
  277. "double",
  278. "int",
  279. "object",
  280. "array",
  281. "string",
  282. };
  283. const char *json_type_to_name(enum json_type o_type)
  284. {
  285. int o_type_int = (int)o_type;
  286. if (o_type_int < 0 || o_type_int >= (int)NELEM(json_type_name))
  287. {
  288. _set_last_err("json_type_to_name: type %d is out of range [0,%d]\n", o_type, NELEM(json_type_name));
  289. return NULL;
  290. }
  291. return json_type_name[o_type];
  292. }