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

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