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 7.7 kB

12 years ago
12 years ago
12 years ago
12 years ago
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326
  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 <stdarg.h>
  14. #include <stdio.h>
  15. #include <stdlib.h>
  16. #include <stddef.h>
  17. #include <limits.h>
  18. #include <string.h>
  19. #include <errno.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 void _set_last_err(const char *err_fmt, ...);
  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. static 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. const char *json_str;
  111. int fd, ret;
  112. unsigned int wpos, wsize;
  113. if(!obj) {
  114. _set_last_err("json_object_to_file: object is null\n");
  115. return -1;
  116. }
  117. if((fd = open(filename, O_WRONLY | O_TRUNC | O_CREAT, 0644)) < 0) {
  118. _set_last_err("json_object_to_file: error opening file %s: %s\n",
  119. filename, strerror(errno));
  120. return -1;
  121. }
  122. if(!(json_str = json_object_to_json_string_ext(obj,flags))) {
  123. close(fd);
  124. return -1;
  125. }
  126. wsize = (unsigned int)(strlen(json_str) & UINT_MAX); /* CAW: probably unnecessary, but the most 64bit safe */
  127. wpos = 0;
  128. while(wpos < wsize) {
  129. if((ret = write(fd, json_str + wpos, wsize-wpos)) < 0) {
  130. close(fd);
  131. _set_last_err("json_object_to_file: error writing file %s: %s\n",
  132. filename, strerror(errno));
  133. return -1;
  134. }
  135. /* because of the above check for ret < 0, we can safely cast and add */
  136. wpos += (unsigned int)ret;
  137. }
  138. close(fd);
  139. return 0;
  140. }
  141. // backwards compatible "format and write to file" function
  142. int json_object_to_file(const char *filename, struct json_object *obj)
  143. {
  144. return json_object_to_file_ext(filename, obj, JSON_C_TO_STRING_PLAIN);
  145. }
  146. int json_parse_double(const char *buf, double *retval)
  147. {
  148. return (sscanf(buf, "%lf", retval)==1 ? 0 : 1);
  149. }
  150. /*
  151. * Not all implementations of sscanf actually work properly.
  152. * Check whether the one we're currently using does, and if
  153. * it's broken, enable the workaround code.
  154. */
  155. static void sscanf_is_broken_test()
  156. {
  157. int64_t num64;
  158. int ret_errno, is_int64_min, ret_errno2, is_int64_max;
  159. (void)sscanf(" -01234567890123456789012345", "%" SCNd64, &num64);
  160. ret_errno = errno;
  161. is_int64_min = (num64 == INT64_MIN);
  162. (void)sscanf(" 01234567890123456789012345", "%" SCNd64, &num64);
  163. ret_errno2 = errno;
  164. is_int64_max = (num64 == INT64_MAX);
  165. if (ret_errno != ERANGE || !is_int64_min ||
  166. ret_errno2 != ERANGE || !is_int64_max)
  167. {
  168. MC_DEBUG("sscanf_is_broken_test failed, enabling workaround code\n");
  169. sscanf_is_broken = 1;
  170. }
  171. }
  172. int json_parse_int64(const char *buf, int64_t *retval)
  173. {
  174. int64_t num64;
  175. const char *buf_sig_digits;
  176. int orig_has_neg;
  177. int saved_errno;
  178. if (!sscanf_is_broken_testdone)
  179. {
  180. sscanf_is_broken_test();
  181. sscanf_is_broken_testdone = 1;
  182. }
  183. // Skip leading spaces
  184. while (isspace((int)*buf) && *buf)
  185. buf++;
  186. errno = 0; // sscanf won't always set errno, so initialize
  187. if (sscanf(buf, "%" SCNd64, &num64) != 1)
  188. {
  189. MC_DEBUG("Failed to parse, sscanf != 1\n");
  190. return 1;
  191. }
  192. saved_errno = errno;
  193. buf_sig_digits = buf;
  194. orig_has_neg = 0;
  195. if (*buf_sig_digits == '-')
  196. {
  197. buf_sig_digits++;
  198. orig_has_neg = 1;
  199. }
  200. // Not all sscanf implementations actually work
  201. if (sscanf_is_broken && saved_errno != ERANGE)
  202. {
  203. char buf_cmp[100];
  204. char *buf_cmp_start = buf_cmp;
  205. int recheck_has_neg = 0;
  206. int buf_cmp_len;
  207. // Skip leading zeros, but keep at least one digit
  208. while (buf_sig_digits[0] == '0' && buf_sig_digits[1] != '\0')
  209. buf_sig_digits++;
  210. if (num64 == 0) // assume all sscanf impl's will parse -0 to 0
  211. orig_has_neg = 0; // "-0" is the same as just plain "0"
  212. snprintf(buf_cmp_start, sizeof(buf_cmp), "%" PRId64, num64);
  213. if (*buf_cmp_start == '-')
  214. {
  215. recheck_has_neg = 1;
  216. buf_cmp_start++;
  217. }
  218. // No need to skip leading spaces or zeros here.
  219. buf_cmp_len = strlen(buf_cmp_start);
  220. /**
  221. * If the sign is different, or
  222. * some of the digits are different, or
  223. * there is another digit present in the original string
  224. * then we have NOT successfully parsed the value.
  225. */
  226. if (orig_has_neg != recheck_has_neg ||
  227. strncmp(buf_sig_digits, buf_cmp_start, strlen(buf_cmp_start)) != 0 ||
  228. ((int)strlen(buf_sig_digits) != buf_cmp_len &&
  229. isdigit((int)buf_sig_digits[buf_cmp_len])
  230. )
  231. )
  232. {
  233. saved_errno = ERANGE;
  234. }
  235. }
  236. // Not all sscanf impl's set the value properly when out of range.
  237. // Always do this, even for properly functioning implementations,
  238. // since it shouldn't slow things down much.
  239. if (saved_errno == ERANGE)
  240. {
  241. if (orig_has_neg)
  242. num64 = INT64_MIN;
  243. else
  244. num64 = INT64_MAX;
  245. }
  246. *retval = num64;
  247. return 0;
  248. }
  249. #ifndef HAVE_REALLOC
  250. void* rpl_realloc(void* p, size_t n)
  251. {
  252. if (n == 0)
  253. n = 1;
  254. if (p == 0)
  255. return malloc(n);
  256. return realloc(p, n);
  257. }
  258. #endif
  259. #define NELEM(a) (sizeof(a) / sizeof(a[0]))
  260. static const char* json_type_name[] = {
  261. /* If you change this, be sure to update the enum json_type definition too */
  262. "null",
  263. "boolean",
  264. "double",
  265. "int",
  266. "object",
  267. "array",
  268. "string",
  269. };
  270. const char *json_type_to_name(enum json_type o_type)
  271. {
  272. int o_type_int = (int)o_type;
  273. if (o_type_int < 0 || o_type_int >= (int)NELEM(json_type_name))
  274. {
  275. _set_last_err("json_type_to_name: type %d is out of range [0,%d]\n", o_type, NELEM(json_type_name));
  276. return NULL;
  277. }
  278. return json_type_name[o_type];
  279. }