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