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
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347
  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. return (sscanf(buf, "%lf", retval)==1 ? 0 : 1);
  165. }
  166. /*
  167. * Not all implementations of sscanf actually work properly.
  168. * Check whether the one we're currently using does, and if
  169. * it's broken, enable the workaround code.
  170. */
  171. static void sscanf_is_broken_test()
  172. {
  173. int64_t num64;
  174. int ret_errno, is_int64_min, ret_errno2, is_int64_max;
  175. (void)sscanf(" -01234567890123456789012345", "%" SCNd64, &num64);
  176. ret_errno = errno;
  177. is_int64_min = (num64 == INT64_MIN);
  178. (void)sscanf(" 01234567890123456789012345", "%" SCNd64, &num64);
  179. ret_errno2 = errno;
  180. is_int64_max = (num64 == INT64_MAX);
  181. if (ret_errno != ERANGE || !is_int64_min ||
  182. ret_errno2 != ERANGE || !is_int64_max)
  183. {
  184. MC_DEBUG("sscanf_is_broken_test failed, enabling workaround code\n");
  185. sscanf_is_broken = 1;
  186. }
  187. }
  188. int json_parse_int64(const char *buf, int64_t *retval)
  189. {
  190. int64_t num64;
  191. const char *buf_sig_digits;
  192. int orig_has_neg;
  193. int saved_errno;
  194. if (!sscanf_is_broken_testdone)
  195. {
  196. sscanf_is_broken_test();
  197. sscanf_is_broken_testdone = 1;
  198. }
  199. // Skip leading spaces
  200. while (isspace((int)*buf) && *buf)
  201. buf++;
  202. errno = 0; // sscanf won't always set errno, so initialize
  203. if (sscanf(buf, "%" SCNd64, &num64) != 1)
  204. {
  205. MC_DEBUG("Failed to parse, sscanf != 1\n");
  206. return 1;
  207. }
  208. saved_errno = errno;
  209. buf_sig_digits = buf;
  210. orig_has_neg = 0;
  211. if (*buf_sig_digits == '-')
  212. {
  213. buf_sig_digits++;
  214. orig_has_neg = 1;
  215. }
  216. // Not all sscanf implementations actually work
  217. if (sscanf_is_broken && saved_errno != ERANGE)
  218. {
  219. char buf_cmp[100];
  220. char *buf_cmp_start = buf_cmp;
  221. int recheck_has_neg = 0;
  222. int buf_cmp_len;
  223. // Skip leading zeros, but keep at least one digit
  224. while (buf_sig_digits[0] == '0' && buf_sig_digits[1] != '\0')
  225. buf_sig_digits++;
  226. if (num64 == 0) // assume all sscanf impl's will parse -0 to 0
  227. orig_has_neg = 0; // "-0" is the same as just plain "0"
  228. snprintf(buf_cmp_start, sizeof(buf_cmp), "%" PRId64, num64);
  229. if (*buf_cmp_start == '-')
  230. {
  231. recheck_has_neg = 1;
  232. buf_cmp_start++;
  233. }
  234. // No need to skip leading spaces or zeros here.
  235. buf_cmp_len = strlen(buf_cmp_start);
  236. /**
  237. * If the sign is different, or
  238. * some of the digits are different, or
  239. * there is another digit present in the original string
  240. * then we have NOT successfully parsed the value.
  241. */
  242. if (orig_has_neg != recheck_has_neg ||
  243. strncmp(buf_sig_digits, buf_cmp_start, strlen(buf_cmp_start)) != 0 ||
  244. ((int)strlen(buf_sig_digits) != buf_cmp_len &&
  245. isdigit((int)buf_sig_digits[buf_cmp_len])
  246. )
  247. )
  248. {
  249. saved_errno = ERANGE;
  250. }
  251. }
  252. // Not all sscanf impl's set the value properly when out of range.
  253. // Always do this, even for properly functioning implementations,
  254. // since it shouldn't slow things down much.
  255. if (saved_errno == ERANGE)
  256. {
  257. if (orig_has_neg)
  258. num64 = INT64_MIN;
  259. else
  260. num64 = INT64_MAX;
  261. }
  262. *retval = num64;
  263. return 0;
  264. }
  265. #ifndef HAVE_REALLOC
  266. void* rpl_realloc(void* p, size_t n)
  267. {
  268. if (n == 0)
  269. n = 1;
  270. if (p == 0)
  271. return malloc(n);
  272. return realloc(p, n);
  273. }
  274. #endif
  275. #define NELEM(a) (sizeof(a) / sizeof(a[0]))
  276. static const char* json_type_name[] = {
  277. /* If you change this, be sure to update the enum json_type definition too */
  278. "null",
  279. "boolean",
  280. "double",
  281. "int",
  282. "object",
  283. "array",
  284. "string",
  285. };
  286. const char *json_type_to_name(enum json_type o_type)
  287. {
  288. int o_type_int = (int)o_type;
  289. if (o_type_int < 0 || o_type_int >= (int)NELEM(json_type_name))
  290. {
  291. _set_last_err("json_type_to_name: type %d is out of range [0,%d]\n", o_type, NELEM(json_type_name));
  292. return NULL;
  293. }
  294. return json_type_name[o_type];
  295. }