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.2 kB

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