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