1 /*
2  * Copyright (c) 2004, 2005 Metaparadigm Pte. Ltd.
3  * Michael Clark <michael@metaparadigm.com>
4  * Copyright (c) 2016 Adiscon GmbH
5  * Rainer Gerhards <rgerhards@adiscon.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 
12 #include "config.h"
13 #undef realloc
14 
15 #include <stdio.h>
16 #include <stdlib.h>
17 #include <stddef.h>
18 #include <limits.h>
19 #include <string.h>
20 #include <errno.h>
21 #include <ctype.h>
22 #include <stdint.h>
23 
24 #ifdef HAVE_SYS_TYPES_H
25 #include <sys/types.h>
26 #endif /* HAVE_SYS_TYPES_H */
27 
28 #ifdef HAVE_SYS_STAT_H
29 #include <sys/stat.h>
30 #endif /* HAVE_SYS_STAT_H */
31 
32 #ifdef HAVE_FCNTL_H
33 #include <fcntl.h>
34 #endif /* HAVE_FCNTL_H */
35 
36 #ifdef HAVE_UNISTD_H
37 # include <unistd.h>
38 #endif /* HAVE_UNISTD_H */
39 
40 #if !defined(HAVE_SNPRINTF)
41 # error You do not have snprintf on your system.
42 #endif /* HAVE_SNPRINTF */
43 
44 #include "debug.h"
45 #include "printbuf.h"
46 #include "json_object.h"
47 #include "json_tokener.h"
48 #include "json_util.h"
49 
50 static int sscanf_is_broken = 0;
51 static int sscanf_is_broken_testdone = 0;
52 static void sscanf_is_broken_test(void);
53 
54 /*
55  * Create a JSON object from already opened file descriptor.
56  *
57  * This function can be helpful, when you opened the file already,
58  * e.g. when you have a temp file.
59  * Note, that the fd must be readable at the actual position, i.e.
60  * use lseek(fd, 0, SEEK_SET) before.
61  */
fjson_object_from_fd(int fd)62 struct fjson_object* fjson_object_from_fd(int fd)
63 {
64 	struct printbuf *pb;
65 	struct fjson_object *obj;
66 	char buf[FJSON_FILE_BUF_SIZE];
67 	int ret;
68 
69 	if(!(pb = printbuf_new())) {
70 		MC_ERROR("fjson_object_from_file: printbuf_new failed\n");
71 		return NULL;
72 	}
73 	while((ret = read(fd, buf, FJSON_FILE_BUF_SIZE)) > 0) {
74 		printbuf_memappend(pb, buf, ret);
75 	}
76 	if(ret < 0) {
77 		MC_ERROR("fjson_object_from_fd: error reading fd %d: %s\n", fd, strerror(errno));
78 		printbuf_free(pb);
79 		return NULL;
80 	}
81 	obj = fjson_tokener_parse(pb->buf);
82 	printbuf_free(pb);
83 	return obj;
84 }
85 
fjson_object_from_file(const char * filename)86 struct fjson_object* fjson_object_from_file(const char *filename)
87 {
88 	struct fjson_object *obj;
89 	int fd;
90 
91 	if((fd = open(filename, O_RDONLY)) < 0) {
92 		MC_ERROR("fjson_object_from_file: error opening file %s: %s\n",
93 		     filename, strerror(errno));
94 		return NULL;
95 	}
96 	obj = fjson_object_from_fd(fd);
97 	close(fd);
98 	return obj;
99 }
100 
101 /* extended "format and write to file" function */
102 
fjson_object_to_file_ext(const char * filename,struct fjson_object * obj,int flags)103 int fjson_object_to_file_ext(const char *filename, struct fjson_object *obj, int flags)
104 {
105 	const char *fjson_str;
106 	int fd, ret;
107 	unsigned int wpos, wsize;
108 
109 	if(!obj) {
110 		MC_ERROR("fjson_object_to_file: object is null\n");
111 		return -1;
112 	}
113 
114 	if((fd = open(filename, O_WRONLY | O_TRUNC | O_CREAT, 0644)) < 0) {
115 		MC_ERROR("fjson_object_to_file: error opening file %s: %s\n",
116 		     filename, strerror(errno));
117 		return -1;
118 	}
119 
120 	if(!(fjson_str = fjson_object_to_json_string_ext(obj,flags))) {
121 		close(fd);
122 		return -1;
123 	}
124 
125 	wsize = (unsigned int)(strlen(fjson_str) & UINT_MAX); /* CAW: probably unnecessary, but the most 64bit safe */
126 	wpos = 0;
127 	while(wpos < wsize) {
128 		if((ret = write(fd, fjson_str + wpos, wsize-wpos)) < 0) {
129 			close(fd);
130 			MC_ERROR("fjson_object_to_file: error writing file %s: %s\n",
131 			     filename, strerror(errno));
132 			return -1;
133 		}
134 
135 		/* because of the above check for ret < 0, we can safely cast and add */
136 		wpos += (unsigned int)ret;
137 	}
138 
139 	close(fd);
140 	return 0;
141 }
142 
143 // backwards compatible "format and write to file" function
144 
fjson_object_to_file(const char * filename,struct fjson_object * obj)145 int fjson_object_to_file(const char *filename, struct fjson_object *obj)
146 {
147 	return fjson_object_to_file_ext(filename, obj, FJSON_TO_STRING_PLAIN);
148 }
149 
fjson_parse_double(const char * buf,double * retval)150 int fjson_parse_double(const char *buf, double *retval)
151 {
152 	return (sscanf(buf, "%lf", retval)==1 ? 0 : 1);
153 }
154 
155 /*
156  * Not all implementations of sscanf actually work properly.
157  * Check whether the one we're currently using does, and if
158  * it's broken, enable the workaround code.
159  */
sscanf_is_broken_test(void)160 static void sscanf_is_broken_test(void)
161 {
162 	int64_t num64;
163 	int ret_errno, is_int64_min, ret_errno2, is_int64_max;
164 
165 	(void)sscanf(" -01234567890123456789012345", "%" SCNd64, &num64);
166 	ret_errno = errno;
167 	is_int64_min = (num64 == INT64_MIN);
168 
169 	(void)sscanf(" 01234567890123456789012345", "%" SCNd64, &num64);
170 	ret_errno2 = errno;
171 	is_int64_max = (num64 == INT64_MAX);
172 
173 	if (ret_errno != ERANGE || !is_int64_min ||
174 	    ret_errno2 != ERANGE || !is_int64_max)
175 	{
176 		MC_DEBUG("sscanf_is_broken_test failed, enabling workaround code\n");
177 		sscanf_is_broken = 1;
178 	}
179 }
180 
fjson_parse_int64(const char * buf,int64_t * retval)181 int fjson_parse_int64(const char *buf, int64_t *retval)
182 {
183 	int64_t num64;
184 	const char *buf_sig_digits;
185 	int orig_has_neg;
186 	int saved_errno;
187 
188 	if (!sscanf_is_broken_testdone)
189 	{
190 		sscanf_is_broken_test();
191 		sscanf_is_broken_testdone = 1;
192 	}
193 
194 	// Skip leading spaces
195 	while (isspace((int)*buf) && *buf)
196 		buf++;
197 
198 	errno = 0; // sscanf won't always set errno, so initialize
199 	if (sscanf(buf, "%" SCNd64, &num64) != 1)
200 	{
201 		MC_DEBUG("Failed to parse, sscanf != 1\n");
202 		return 1;
203 	}
204 
205 	saved_errno = errno;
206 	buf_sig_digits = buf;
207 	orig_has_neg = 0;
208 	if (*buf_sig_digits == '-')
209 	{
210 		buf_sig_digits++;
211 		orig_has_neg = 1;
212 	}
213 
214 	// Not all sscanf implementations actually work
215 	if (sscanf_is_broken && saved_errno != ERANGE)
216 	{
217 		char buf_cmp[100];
218 		char *buf_cmp_start = buf_cmp;
219 		int recheck_has_neg = 0;
220 		int buf_cmp_len;
221 
222 		// Skip leading zeros, but keep at least one digit
223 		while (buf_sig_digits[0] == '0' && buf_sig_digits[1] != '\0')
224 			buf_sig_digits++;
225 		if (num64 == 0) // assume all sscanf impl's will parse -0 to 0
226 			orig_has_neg = 0; // "-0" is the same as just plain "0"
227 
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 
236 		buf_cmp_len = strlen(buf_cmp_start);
237 		/**
238 		 * If the sign is different, or
239 		 * some of the digits are different, or
240 		 * there is another digit present in the original string
241 		 * then we have NOT successfully parsed the value.
242 		 */
243 		if (orig_has_neg != recheck_has_neg ||
244 		    strncmp(buf_sig_digits, buf_cmp_start, strlen(buf_cmp_start)) != 0 ||
245 			((int)strlen(buf_sig_digits) != buf_cmp_len &&
246 			 isdigit((int)buf_sig_digits[buf_cmp_len])
247 		    )
248 		   )
249 		{
250 			saved_errno = ERANGE;
251 		}
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 
268 #define NELEM(a)        (sizeof(a) / sizeof(a[0]))
269 static const char* fjson_type_name[] = {
270 	/* If you change this, be sure to update the enum fjson_type definition too */
271 	"null",
272 	"boolean",
273 	"double",
274 	"int",
275 	"object",
276 	"array",
277 	"string",
278 };
279 
fjson_type_to_name(enum fjson_type o_type)280 const char *fjson_type_to_name(enum fjson_type o_type)
281 {
282 	int o_type_int = (int)o_type;
283 	if (o_type_int < 0 || o_type_int >= (int)NELEM(fjson_type_name))
284 	{
285 		MC_ERROR("fjson_type_to_name: type %d is out of range [0,%zu]\n", o_type, NELEM(fjson_type_name));
286 		return NULL;
287 	}
288 	return fjson_type_name[o_type];
289 }
290 
291