some more input validation
[project/uci.git] / util.c
1 /*
2 * libuci - Library for the Unified Configuration Interface
3 * Copyright (C) 2008 Felix Fietkau <nbd@openwrt.org>
4 *
5 * This program is free software; you can redistribute it and/or modify
6 * it under the terms of the GNU Lesser General Public License version 2.1
7 * as published by the Free Software Foundation
8 *
9 * This program is distributed in the hope that it will be useful,
10 * but WITHOUT ANY WARRANTY; without even the implied warranty of
11 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 * GNU General Public License for more details.
13 */
14
15 /*
16 * This file contains misc utility functions and wrappers to standard
17 * functions, which throw exceptions upon failure.
18 */
19 #include <sys/types.h>
20 #include <sys/stat.h>
21 #include <sys/file.h>
22 #include <stdbool.h>
23 #include <unistd.h>
24 #include <ctype.h>
25 #include <fcntl.h>
26
27 #define LINEBUF 32
28 #define LINEBUF_MAX 4096
29
30 __plugin void *uci_malloc(struct uci_context *ctx, size_t size)
31 {
32 void *ptr;
33
34 ptr = malloc(size);
35 if (!ptr)
36 UCI_THROW(ctx, UCI_ERR_MEM);
37 memset(ptr, 0, size);
38
39 return ptr;
40 }
41
42 __plugin void *uci_realloc(struct uci_context *ctx, void *ptr, size_t size)
43 {
44 ptr = realloc(ptr, size);
45 if (!ptr)
46 UCI_THROW(ctx, UCI_ERR_MEM);
47
48 return ptr;
49 }
50
51 __plugin char *uci_strdup(struct uci_context *ctx, const char *str)
52 {
53 char *ptr;
54
55 ptr = strdup(str);
56 if (!ptr)
57 UCI_THROW(ctx, UCI_ERR_MEM);
58
59 return ptr;
60 }
61
62 /* Based on an efficient hash function published by D. J. Bernstein */
63 static unsigned int djbhash(unsigned int hash, char *str)
64 {
65 int len = strlen(str);
66 int i;
67
68 /* initial value */
69 if (hash == ~0)
70 hash = 5381;
71
72 for(i = 0; i < len; i++) {
73 hash = ((hash << 5) + hash) + str[i];
74 }
75 return (hash & 0x7FFFFFFF);
76 }
77
78 /*
79 * validate strings for names and types, reject special characters
80 * for names, only alphanum and _ is allowed (shell compatibility)
81 * for types, we allow more characters
82 */
83 __plugin bool uci_validate_str(const char *str, bool name)
84 {
85 if (!*str)
86 return false;
87
88 while (*str) {
89 char c = *str;
90 if (!isalnum(c) && c != '_') {
91 if (name || (c < 33) || (c > 126))
92 return false;
93 }
94 str++;
95 }
96 return true;
97 }
98
99 static inline bool uci_validate_name(const char *str)
100 {
101 return uci_validate_str(str, true);
102 }
103
104 static inline bool uci_validate_text(const char *str)
105 {
106 while (*str) {
107 if ((*str == '\r') || (*str == '\n') ||
108 ((*str < 32) && (*str != '\t')))
109 return false;
110 }
111 return true;
112 }
113
114 static void uci_alloc_parse_context(struct uci_context *ctx)
115 {
116 ctx->pctx = (struct uci_parse_context *) uci_malloc(ctx, sizeof(struct uci_parse_context));
117 }
118
119 int uci_parse_tuple(struct uci_context *ctx, char *str, char **package, char **section, char **option, char **value)
120 {
121 char *last = NULL;
122
123 UCI_HANDLE_ERR(ctx);
124 UCI_ASSERT(ctx, str && package && section && option);
125
126 last = strchr(str, '=');
127 if (last) {
128 *last = 0;
129 last++;
130 }
131
132 *package = strsep(&str, ".");
133 if (!*package || !uci_validate_str(*package, false))
134 goto error;
135
136 *section = strsep(&str, ".");
137 *option = NULL;
138 *value = NULL;
139 if (!*section)
140 goto lastval;
141
142 *option = strsep(&str, ".");
143 if (!*option)
144 goto lastval;
145
146 lastval:
147 if (last) {
148 if (!value)
149 goto error;
150
151 if (!*last)
152 goto error;
153 *value = last;
154 }
155
156 if (*section && *section[0] && !uci_validate_name(*section))
157 goto error;
158 if (*option && !uci_validate_name(*option))
159 goto error;
160 if (*value && !uci_validate_text(*value))
161 goto error;
162
163 goto done;
164
165 error:
166 UCI_THROW(ctx, UCI_ERR_PARSE);
167
168 done:
169 return 0;
170 }
171
172
173 static void uci_parse_error(struct uci_context *ctx, char *pos, char *reason)
174 {
175 struct uci_parse_context *pctx = ctx->pctx;
176
177 pctx->reason = reason;
178 pctx->byte = pos - pctx->buf;
179 UCI_THROW(ctx, UCI_ERR_PARSE);
180 }
181
182
183 /*
184 * Fetch a new line from the input stream and resize buffer if necessary
185 */
186 static void uci_getln(struct uci_context *ctx, int offset)
187 {
188 struct uci_parse_context *pctx = ctx->pctx;
189 char *p;
190 int ofs;
191
192 if (pctx->buf == NULL) {
193 pctx->buf = uci_malloc(ctx, LINEBUF);
194 pctx->bufsz = LINEBUF;
195 }
196
197 ofs = offset;
198 do {
199 p = &pctx->buf[ofs];
200 p[ofs] = 0;
201
202 p = fgets(p, pctx->bufsz - ofs, pctx->file);
203 if (!p || !*p)
204 return;
205
206 ofs += strlen(p);
207 if (pctx->buf[ofs - 1] == '\n') {
208 pctx->line++;
209 pctx->buf[ofs - 1] = 0;
210 return;
211 }
212
213 if (pctx->bufsz > LINEBUF_MAX/2)
214 uci_parse_error(ctx, p, "line too long");
215
216 pctx->bufsz *= 2;
217 pctx->buf = uci_realloc(ctx, pctx->buf, pctx->bufsz);
218 } while (1);
219 }
220
221 /*
222 * parse a character escaped by '\'
223 * returns true if the escaped character is to be parsed
224 * returns false if the escaped character is to be ignored
225 */
226 static inline bool parse_backslash(struct uci_context *ctx, char **str)
227 {
228 /* skip backslash */
229 *str += 1;
230
231 /* undecoded backslash at the end of line, fetch the next line */
232 if (!**str) {
233 *str += 1;
234 uci_getln(ctx, *str - ctx->pctx->buf);
235 return false;
236 }
237
238 /* FIXME: decode escaped char, necessary? */
239 return true;
240 }
241
242 /*
243 * move the string pointer forward until a non-whitespace character or
244 * EOL is reached
245 */
246 static void skip_whitespace(struct uci_context *ctx, char **str)
247 {
248 restart:
249 while (**str && isspace(**str))
250 *str += 1;
251
252 if (**str == '\\') {
253 if (!parse_backslash(ctx, str))
254 goto restart;
255 }
256 }
257
258 static inline void addc(char **dest, char **src)
259 {
260 **dest = **src;
261 *dest += 1;
262 *src += 1;
263 }
264
265 /*
266 * parse a double quoted string argument from the command line
267 */
268 static void parse_double_quote(struct uci_context *ctx, char **str, char **target)
269 {
270 char c;
271
272 /* skip quote character */
273 *str += 1;
274
275 while ((c = **str)) {
276 switch(c) {
277 case '"':
278 **target = 0;
279 *str += 1;
280 return;
281 case '\\':
282 if (!parse_backslash(ctx, str))
283 continue;
284 /* fall through */
285 default:
286 addc(target, str);
287 break;
288 }
289 }
290 uci_parse_error(ctx, *str, "unterminated \"");
291 }
292
293 /*
294 * parse a single quoted string argument from the command line
295 */
296 static void parse_single_quote(struct uci_context *ctx, char **str, char **target)
297 {
298 char c;
299 /* skip quote character */
300 *str += 1;
301
302 while ((c = **str)) {
303 switch(c) {
304 case '\'':
305 **target = 0;
306 *str += 1;
307 return;
308 default:
309 addc(target, str);
310 }
311 }
312 uci_parse_error(ctx, *str, "unterminated '");
313 }
314
315 /*
316 * parse a string from the command line and detect the quoting style
317 */
318 static void parse_str(struct uci_context *ctx, char **str, char **target)
319 {
320 bool next = true;
321 do {
322 switch(**str) {
323 case '\'':
324 parse_single_quote(ctx, str, target);
325 break;
326 case '"':
327 parse_double_quote(ctx, str, target);
328 break;
329 case '#':
330 **str = 0;
331 /* fall through */
332 case 0:
333 goto done;
334 case ';':
335 next = false;
336 goto done;
337 case '\\':
338 if (!parse_backslash(ctx, str))
339 continue;
340 /* fall through */
341 default:
342 addc(target, str);
343 break;
344 }
345 } while (**str && !isspace(**str));
346 done:
347
348 /*
349 * if the string was unquoted and we've stopped at a whitespace
350 * character, skip to the next one, because the whitespace will
351 * be overwritten by a null byte here
352 */
353 if (**str && next)
354 *str += 1;
355
356 /* terminate the parsed string */
357 **target = 0;
358 }
359
360 /*
361 * extract the next argument from the command line
362 */
363 static char *next_arg(struct uci_context *ctx, char **str, bool required, bool name)
364 {
365 char *val;
366 char *ptr;
367
368 val = ptr = *str;
369 skip_whitespace(ctx, str);
370 if(*str[0] == ';') {
371 *str[0] = 0;
372 *str += 1;
373 } else {
374 parse_str(ctx, str, &ptr);
375 }
376 if (!*val) {
377 if (required)
378 uci_parse_error(ctx, *str, "insufficient arguments");
379 goto done;
380 }
381
382 if (name && !uci_validate_name(val))
383 uci_parse_error(ctx, val, "invalid character in field");
384
385 done:
386 return val;
387 }
388
389 int uci_parse_argument(struct uci_context *ctx, FILE *stream, char **str, char **result)
390 {
391 UCI_HANDLE_ERR(ctx);
392 UCI_ASSERT(ctx, str != NULL);
393 UCI_ASSERT(ctx, result != NULL);
394
395 if (ctx->pctx) {
396 if (ctx->pctx->file != stream) {
397 uci_cleanup(ctx);
398 }
399 } else {
400 uci_alloc_parse_context(ctx);
401 ctx->pctx->file = stream;
402 }
403 if (!*str) {
404 uci_getln(ctx, 0);
405 *str = ctx->pctx->buf;
406 }
407
408 *result = next_arg(ctx, str, false, false);
409
410 return 0;
411 }
412
413
414 /*
415 * open a stream and go to the right position
416 *
417 * note: when opening for write and seeking to the beginning of
418 * the stream, truncate the file
419 */
420 static FILE *uci_open_stream(struct uci_context *ctx, const char *filename, int pos, bool write, bool create)
421 {
422 struct stat statbuf;
423 FILE *file = NULL;
424 int fd, ret;
425 int mode = (write ? O_RDWR : O_RDONLY);
426
427 if (create)
428 mode |= O_CREAT;
429
430 if (!write && ((stat(filename, &statbuf) < 0) ||
431 ((statbuf.st_mode & S_IFMT) != S_IFREG))) {
432 UCI_THROW(ctx, UCI_ERR_NOTFOUND);
433 }
434
435 fd = open(filename, mode, UCI_FILEMODE);
436 if (fd < 0)
437 goto error;
438
439 if (flock(fd, (write ? LOCK_EX : LOCK_SH)) < 0)
440 goto error;
441
442 ret = lseek(fd, 0, pos);
443
444 if (ret < 0)
445 goto error;
446
447 file = fdopen(fd, (write ? "w+" : "r"));
448 if (file)
449 goto done;
450
451 error:
452 UCI_THROW(ctx, UCI_ERR_IO);
453 done:
454 return file;
455 }
456
457 static void uci_close_stream(FILE *stream)
458 {
459 int fd;
460
461 if (!stream)
462 return;
463
464 fd = fileno(stream);
465 flock(fd, LOCK_UN);
466 fclose(stream);
467 }
468
469