fix sanity checks for uci.set to be able to create new sections
[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 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                 str++;
111         }
112         return true;
113 }
114
115 static void uci_alloc_parse_context(struct uci_context *ctx)
116 {
117         ctx->pctx = (struct uci_parse_context *) uci_malloc(ctx, sizeof(struct uci_parse_context));
118 }
119
120 int uci_parse_ptr(struct uci_context *ctx, struct uci_ptr *ptr, char *str)
121 {
122         char *last = NULL;
123         char *tmp;
124
125         UCI_HANDLE_ERR(ctx);
126         UCI_ASSERT(ctx, str);
127         UCI_ASSERT(ctx, ptr);
128
129         memset(ptr, 0, sizeof(struct uci_ptr));
130
131         /* value */
132         last = strchr(str, '=');
133         if (last) {
134                 *last = 0;
135                 last++;
136                 ptr->value = last;
137         }
138
139         ptr->package = strsep(&str, ".");
140         if (!ptr->package)
141                 goto error;
142
143         ptr->section = strsep(&str, ".");
144         if (!ptr->section) {
145                 ptr->target = UCI_TYPE_PACKAGE;
146                 goto lastval;
147         }
148
149         ptr->option = strsep(&str, ".");
150         if (!ptr->option) {
151                 ptr->target = UCI_TYPE_SECTION;
152                 goto lastval;
153         } else {
154                 ptr->target = UCI_TYPE_OPTION;
155         }
156
157         tmp = strsep(&str, ".");
158         if (tmp)
159                 goto error;
160
161 lastval:
162         if (ptr->package && !uci_validate_str(ptr->package, false))
163                 goto error;
164         if (ptr->section && !uci_validate_name(ptr->section))
165                 ptr->flags |= UCI_LOOKUP_EXTENDED;
166         if (ptr->option && !uci_validate_name(ptr->option))
167                 goto error;
168         if (ptr->value && !uci_validate_text(ptr->value))
169                 goto error;
170
171         return 0;
172
173 error:
174         memset(ptr, 0, sizeof(struct uci_ptr));
175         UCI_THROW(ctx, UCI_ERR_PARSE);
176 }
177
178
179 static void uci_parse_error(struct uci_context *ctx, char *pos, char *reason)
180 {
181         struct uci_parse_context *pctx = ctx->pctx;
182
183         pctx->reason = reason;
184         pctx->byte = pos - pctx->buf;
185         UCI_THROW(ctx, UCI_ERR_PARSE);
186 }
187
188
189 /*
190  * Fetch a new line from the input stream and resize buffer if necessary
191  */
192 static void uci_getln(struct uci_context *ctx, int offset)
193 {
194         struct uci_parse_context *pctx = ctx->pctx;
195         char *p;
196         int ofs;
197
198         if (pctx->buf == NULL) {
199                 pctx->buf = uci_malloc(ctx, LINEBUF);
200                 pctx->bufsz = LINEBUF;
201         }
202
203         ofs = offset;
204         do {
205                 p = &pctx->buf[ofs];
206                 p[ofs] = 0;
207
208                 p = fgets(p, pctx->bufsz - ofs, pctx->file);
209                 if (!p || !*p)
210                         return;
211
212                 ofs += strlen(p);
213                 if (pctx->buf[ofs - 1] == '\n') {
214                         pctx->line++;
215                         pctx->buf[ofs - 1] = 0;
216                         return;
217                 }
218
219                 if (pctx->bufsz > LINEBUF_MAX/2)
220                         uci_parse_error(ctx, p, "line too long");
221
222                 pctx->bufsz *= 2;
223                 pctx->buf = uci_realloc(ctx, pctx->buf, pctx->bufsz);
224         } while (1);
225 }
226
227 /* 
228  * parse a character escaped by '\'
229  * returns true if the escaped character is to be parsed
230  * returns false if the escaped character is to be ignored
231  */
232 static inline bool parse_backslash(struct uci_context *ctx, char **str)
233 {
234         /* skip backslash */
235         *str += 1;
236
237         /* undecoded backslash at the end of line, fetch the next line */
238         if (!**str) {
239                 *str += 1;
240                 uci_getln(ctx, *str - ctx->pctx->buf);
241                 return false;
242         }
243
244         /* FIXME: decode escaped char, necessary? */
245         return true;
246 }
247
248 /*
249  * move the string pointer forward until a non-whitespace character or
250  * EOL is reached
251  */
252 static void skip_whitespace(struct uci_context *ctx, char **str)
253 {
254 restart:
255         while (**str && isspace(**str))
256                 *str += 1;
257
258         if (**str == '\\') {
259                 if (!parse_backslash(ctx, str))
260                         goto restart;
261         }
262 }
263
264 static inline void addc(char **dest, char **src)
265 {
266         **dest = **src;
267         *dest += 1;
268         *src += 1;
269 }
270
271 /*
272  * parse a double quoted string argument from the command line
273  */
274 static void parse_double_quote(struct uci_context *ctx, char **str, char **target)
275 {
276         char c;
277
278         /* skip quote character */
279         *str += 1;
280
281         while ((c = **str)) {
282                 switch(c) {
283                 case '"':
284                         **target = 0;
285                         *str += 1;
286                         return;
287                 case '\\':
288                         if (!parse_backslash(ctx, str))
289                                 continue;
290                         /* fall through */
291                 default:
292                         addc(target, str);
293                         break;
294                 }
295         }
296         uci_parse_error(ctx, *str, "unterminated \"");
297 }
298
299 /*
300  * parse a single quoted string argument from the command line
301  */
302 static void parse_single_quote(struct uci_context *ctx, char **str, char **target)
303 {
304         char c;
305         /* skip quote character */
306         *str += 1;
307
308         while ((c = **str)) {
309                 switch(c) {
310                 case '\'':
311                         **target = 0;
312                         *str += 1;
313                         return;
314                 default:
315                         addc(target, str);
316                 }
317         }
318         uci_parse_error(ctx, *str, "unterminated '");
319 }
320
321 /*
322  * parse a string from the command line and detect the quoting style
323  */
324 static void parse_str(struct uci_context *ctx, char **str, char **target)
325 {
326         bool next = true;
327         do {
328                 switch(**str) {
329                 case '\'':
330                         parse_single_quote(ctx, str, target);
331                         break;
332                 case '"':
333                         parse_double_quote(ctx, str, target);
334                         break;
335                 case '#':
336                         **str = 0;
337                         /* fall through */
338                 case 0:
339                         goto done;
340                 case ';':
341                         next = false;
342                         goto done;
343                 case '\\':
344                         if (!parse_backslash(ctx, str))
345                                 continue;
346                         /* fall through */
347                 default:
348                         addc(target, str);
349                         break;
350                 }
351         } while (**str && !isspace(**str));
352 done:
353
354         /* 
355          * if the string was unquoted and we've stopped at a whitespace
356          * character, skip to the next one, because the whitespace will
357          * be overwritten by a null byte here
358          */
359         if (**str && next)
360                 *str += 1;
361
362         /* terminate the parsed string */
363         **target = 0;
364 }
365
366 /*
367  * extract the next argument from the command line
368  */
369 static char *next_arg(struct uci_context *ctx, char **str, bool required, bool name)
370 {
371         char *val;
372         char *ptr;
373
374         val = ptr = *str;
375         skip_whitespace(ctx, str);
376         if(*str[0] == ';') {
377                 *str[0] = 0;
378                 *str += 1;
379         } else {
380                 parse_str(ctx, str, &ptr);
381         }
382         if (!*val) {
383                 if (required)
384                         uci_parse_error(ctx, *str, "insufficient arguments");
385                 goto done;
386         }
387
388         if (name && !uci_validate_name(val))
389                 uci_parse_error(ctx, val, "invalid character in field");
390
391 done:
392         return val;
393 }
394
395 int uci_parse_argument(struct uci_context *ctx, FILE *stream, char **str, char **result)
396 {
397         UCI_HANDLE_ERR(ctx);
398         UCI_ASSERT(ctx, str != NULL);
399         UCI_ASSERT(ctx, result != NULL);
400
401         if (ctx->pctx) {
402                 if (ctx->pctx->file != stream) {
403                         uci_cleanup(ctx);
404                 }
405         } else {
406                 uci_alloc_parse_context(ctx);
407                 ctx->pctx->file = stream;
408         }
409         if (!*str) {
410                 uci_getln(ctx, 0);
411                 *str = ctx->pctx->buf;
412         }
413
414         *result = next_arg(ctx, str, false, false);
415
416         return 0;
417 }
418
419
420 /*
421  * open a stream and go to the right position
422  *
423  * note: when opening for write and seeking to the beginning of
424  * the stream, truncate the file
425  */
426 static FILE *uci_open_stream(struct uci_context *ctx, const char *filename, int pos, bool write, bool create)
427 {
428         struct stat statbuf;
429         FILE *file = NULL;
430         int fd, ret;
431         int mode = (write ? O_RDWR : O_RDONLY);
432
433         if (create)
434                 mode |= O_CREAT;
435
436         if (!write && ((stat(filename, &statbuf) < 0) ||
437                 ((statbuf.st_mode &  S_IFMT) != S_IFREG))) {
438                 UCI_THROW(ctx, UCI_ERR_NOTFOUND);
439         }
440
441         fd = open(filename, mode, UCI_FILEMODE);
442         if (fd < 0)
443                 goto error;
444
445         if (flock(fd, (write ? LOCK_EX : LOCK_SH)) < 0)
446                 goto error;
447
448         ret = lseek(fd, 0, pos);
449
450         if (ret < 0)
451                 goto error;
452
453         file = fdopen(fd, (write ? "w+" : "r"));
454         if (file)
455                 goto done;
456
457 error:
458         UCI_THROW(ctx, UCI_ERR_IO);
459 done:
460         return file;
461 }
462
463 static void uci_close_stream(FILE *stream)
464 {
465         int fd;
466
467         if (!stream)
468                 return;
469
470         fd = fileno(stream);
471         flock(fd, LOCK_UN);
472         fclose(stream);
473 }
474
475