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