another small comment
[project/uci.git] / file.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 the code for parsing uci config files
17  */
18
19 #include <sys/types.h>
20 #include <sys/stat.h>
21 #include <stdbool.h>
22 #include <fcntl.h>
23 #include <stdio.h>
24 #include <ctype.h>
25
26 #define LINEBUF 32
27 #define LINEBUF_MAX     4096
28
29 /*
30  * Fetch a new line from the input stream and resize buffer if necessary
31  */
32 static void uci_getln(struct uci_context *ctx, int offset)
33 {
34         struct uci_parse_context *pctx = ctx->pctx;
35         char *p;
36         int ofs;
37
38         if (pctx->buf == NULL) {
39                 pctx->buf = uci_malloc(ctx, LINEBUF);
40                 pctx->bufsz = LINEBUF;
41         }
42
43         ofs = offset;
44         do {
45                 p = &pctx->buf[ofs];
46                 p[ofs] = 0;
47
48                 p = fgets(p, pctx->bufsz - ofs, pctx->file);
49                 if (!p || !*p)
50                         return;
51
52                 ofs += strlen(p);
53                 if (pctx->buf[ofs - 1] == '\n') {
54                         pctx->line++;
55                         pctx->buf[ofs - 1] = 0;
56                         return;
57                 }
58
59                 if (pctx->bufsz > LINEBUF_MAX/2) {
60                         pctx->reason = "line too long";
61                         pctx->byte = LINEBUF_MAX;
62                         UCI_THROW(ctx, UCI_ERR_PARSE);
63                 }
64
65                 pctx->bufsz *= 2;
66                 pctx->buf = uci_realloc(ctx, pctx->buf, pctx->bufsz);
67         } while (1);
68 }
69
70 /*
71  * Clean up all extra memory used by the parser and exporter
72  */
73 static void uci_file_cleanup(struct uci_context *ctx)
74 {
75         struct uci_parse_context *pctx;
76
77         if (ctx->buf) {
78                 free(ctx->buf);
79                 ctx->buf = NULL;
80                 ctx->bufsz = 0;
81         }
82
83         pctx = ctx->pctx;
84         if (!pctx)
85                 return;
86
87         ctx->pctx = NULL;
88         if (pctx->package)
89                 uci_free_package(pctx->package);
90
91         if (pctx->buf)
92                 free(pctx->buf);
93         if (pctx->file)
94                 fclose(pctx->file);
95
96         free(pctx);
97 }
98
99 /* 
100  * parse a character escaped by '\'
101  * returns true if the escaped character is to be parsed
102  * returns false if the escaped character is to be ignored
103  */
104 static inline bool parse_backslash(struct uci_context *ctx, char **str)
105 {
106         /* skip backslash */
107         *str += 1;
108
109         /* undecoded backslash at the end of line, fetch the next line */
110         if (!**str) {
111                 *str += 1;
112                 uci_getln(ctx, *str - ctx->pctx->buf);
113                 return false;
114         }
115
116         /* FIXME: decode escaped char, necessary? */
117         return true;
118 }
119
120 /*
121  * move the string pointer forward until a non-whitespace character or
122  * EOL is reached
123  */
124 static void skip_whitespace(struct uci_context *ctx, char **str)
125 {
126 restart:
127         while (**str && isspace(**str))
128                 *str += 1;
129
130         if (**str == '\\') {
131                 if (!parse_backslash(ctx, str))
132                         goto restart;
133         }
134 }
135
136 static inline void addc(char **dest, char **src)
137 {
138         **dest = **src;
139         *dest += 1;
140         *src += 1;
141 }
142
143 /*
144  * parse a double quoted string argument from the command line
145  */
146 static void parse_double_quote(struct uci_context *ctx, char **str, char **target)
147 {
148         char c;
149
150         /* skip quote character */
151         *str += 1;
152
153         while ((c = **str)) {
154                 switch(c) {
155                 case '"':
156                         **target = 0;
157                         *str += 1;
158                         return;
159                 case '\\':
160                         if (!parse_backslash(ctx, str))
161                                 continue;
162                         /* fall through */
163                 default:
164                         addc(target, str);
165                         break;
166                 }
167         }
168         ctx->pctx->reason = "unterminated \"";
169         ctx->pctx->byte = *str - ctx->pctx->buf;
170         UCI_THROW(ctx, UCI_ERR_PARSE);
171 }
172
173 /*
174  * parse a single quoted string argument from the command line
175  */
176 static void parse_single_quote(struct uci_context *ctx, char **str, char **target)
177 {
178         char c;
179         /* skip quote character */
180         *str += 1;
181
182         while ((c = **str)) {
183                 switch(c) {
184                 case '\'':
185                         **target = 0;
186                         *str += 1;
187                         return;
188                 default:
189                         addc(target, str);
190                 }
191         }
192         ctx->pctx->reason = "unterminated '";
193         ctx->pctx->byte = *str - ctx->pctx->buf;
194         UCI_THROW(ctx, UCI_ERR_PARSE);
195 }
196
197 /*
198  * parse a string from the command line and detect the quoting style
199  */
200 static void parse_str(struct uci_context *ctx, char **str, char **target)
201 {
202         do {
203                 switch(**str) {
204                 case '\'':
205                         parse_single_quote(ctx, str, target);
206                         break;
207                 case '"':
208                         parse_double_quote(ctx, str, target);
209                         break;
210                 case 0:
211                         goto done;
212                 case '\\':
213                         if (!parse_backslash(ctx, str))
214                                 continue;
215                         /* fall through */
216                 default:
217                         addc(target, str);
218                         break;
219                 }
220         } while (**str && !isspace(**str));
221 done:
222
223         /* 
224          * if the string was unquoted and we've stopped at a whitespace
225          * character, skip to the next one, because the whitespace will
226          * be overwritten by a null byte here
227          */
228         if (**str)
229                 *str += 1;
230
231         /* terminate the parsed string */
232         **target = 0;
233 }
234
235 /*
236  * extract the next argument from the command line
237  */
238 static char *next_arg(struct uci_context *ctx, char **str, bool required)
239 {
240         char *val;
241         char *ptr;
242
243         val = ptr = *str;
244         skip_whitespace(ctx, str);
245         parse_str(ctx, str, &ptr);
246         if (required && !*val) {
247                 ctx->pctx->reason = "insufficient arguments";
248                 ctx->pctx->byte = *str - ctx->pctx->buf;
249                 UCI_THROW(ctx, UCI_ERR_PARSE);
250         }
251
252         return val;
253 }
254
255 /*
256  * verify that the end of the line or command is reached.
257  * throw an error if extra arguments are given on the command line
258  */
259 static void assert_eol(struct uci_context *ctx, char **str)
260 {
261         char *tmp;
262
263         tmp = next_arg(ctx, str, false);
264         if (tmp && *tmp) {
265                 ctx->pctx->reason = "too many arguments";
266                 ctx->pctx->byte = tmp - ctx->pctx->buf;
267                 UCI_THROW(ctx, UCI_ERR_PARSE);
268         }
269 }
270
271 /* 
272  * switch to a different config, either triggered by uci_load, or by a
273  * 'package <...>' statement in the import file
274  */
275 static void uci_switch_config(struct uci_context *ctx)
276 {
277         struct uci_parse_context *pctx;
278         const char *name;
279
280         pctx = ctx->pctx;
281         name = pctx->name;
282
283         /* add the last config to main config file list */
284         if (pctx->package) {
285                 uci_list_add(&ctx->root, &pctx->package->e.list);
286
287                 pctx->package = NULL;
288                 pctx->section = NULL;
289         }
290
291         if (!name)
292                 return;
293
294         /* 
295          * if an older config under the same name exists, unload it
296          * ignore errors here, e.g. if the config was not found
297          */
298         UCI_TRAP_SAVE(ctx, ignore);
299         uci_unload(ctx, name);
300         UCI_TRAP_RESTORE(ctx);
301 ignore:
302         ctx->errno = 0;
303
304         pctx->package = uci_alloc_package(ctx, name);
305 }
306
307 /*
308  * parse the 'package' uci command (next config package)
309  */
310 static void uci_parse_package(struct uci_context *ctx, char **str)
311 {
312         char *name = NULL;
313
314         /* command string null-terminated by strtok */
315         *str += strlen(*str) + 1;
316
317         name = next_arg(ctx, str, true);
318         assert_eol(ctx, str);
319         ctx->pctx->name = name;
320         uci_switch_config(ctx);
321 }
322
323 /*
324  * parse the 'config' uci command (open a section)
325  */
326 static void uci_parse_config(struct uci_context *ctx, char **str)
327 {
328         char *name = NULL;
329         char *type = NULL;
330
331         if (!ctx->pctx->package) {
332                 if (!ctx->pctx->name) {
333                         ctx->pctx->byte = *str - ctx->pctx->buf;
334                         ctx->pctx->reason = "attempting to import a file without a package name";
335                         UCI_THROW(ctx, UCI_ERR_PARSE);
336                 }
337                 uci_switch_config(ctx);
338         }
339
340         /* command string null-terminated by strtok */
341         *str += strlen(*str) + 1;
342
343         type = next_arg(ctx, str, true);
344         name = next_arg(ctx, str, false);
345         assert_eol(ctx, str);
346         ctx->pctx->section = uci_alloc_section(ctx->pctx->package, type, name);
347 }
348
349 /*
350  * parse the 'option' uci command (open a value)
351  */
352 static void uci_parse_option(struct uci_context *ctx, char **str)
353 {
354         char *name = NULL;
355         char *value = NULL;
356
357         if (!ctx->pctx->section) {
358                 ctx->pctx->byte = *str - ctx->pctx->buf;
359                 ctx->pctx->reason = "option command found before the first section";
360                 UCI_THROW(ctx, UCI_ERR_PARSE);
361         }
362         /* command string null-terminated by strtok */
363         *str += strlen(*str) + 1;
364
365         name = next_arg(ctx, str, true);
366         value = next_arg(ctx, str, true);
367         assert_eol(ctx, str);
368         uci_alloc_option(ctx->pctx->section, name, value);
369 }
370
371
372 /*
373  * parse a complete input line, split up combined commands by ';'
374  */
375 static void uci_parse_line(struct uci_context *ctx)
376 {
377         struct uci_parse_context *pctx = ctx->pctx;
378         char *word, *brk = NULL;
379
380         for (word = strtok_r(pctx->buf, ";", &brk);
381                  word;
382                  word = strtok_r(NULL, ";", &brk)) {
383
384                 char *pbrk = NULL;
385                 word = strtok_r(word, " \t", &pbrk);
386
387                 switch(word[0]) {
388                         case 'p':
389                                 if ((word[1] == 0) || !strcmp(word + 1, "ackage"))
390                                         uci_parse_package(ctx, &word);
391                                 break;
392                         case 'c':
393                                 if ((word[1] == 0) || !strcmp(word + 1, "onfig"))
394                                         uci_parse_config(ctx, &word);
395                                 break;
396                         case 'o':
397                                 if ((word[1] == 0) || !strcmp(word + 1, "ption"))
398                                         uci_parse_option(ctx, &word);
399                                 break;
400                         default:
401                                 pctx->reason = "unterminated command";
402                                 pctx->byte = word - pctx->buf;
403                                 UCI_THROW(ctx, UCI_ERR_PARSE);
404                                 break;
405                 }
406         }
407 }
408
409 /* max number of characters that escaping adds to the string */
410 #define UCI_QUOTE_ESCAPE        "'\\'"
411
412 /*
413  * escape an uci string for export
414  */
415 static char *uci_escape(struct uci_context *ctx, char *str)
416 {
417         char *s, *p;
418         int pos = 0;
419
420         if (!ctx->buf) {
421                 ctx->bufsz = LINEBUF;
422                 ctx->buf = malloc(LINEBUF);
423         }
424
425         s = str;
426         p = strchr(str, '\'');
427         if (!p)
428                 return str;
429
430         do {
431                 int len = p - s;
432                 if (len > 0) {
433                         if (p + sizeof(UCI_QUOTE_ESCAPE) - str >= ctx->bufsz) {
434                                 ctx->bufsz *= 2;
435                                 ctx->buf = realloc(ctx->buf, ctx->bufsz);
436                                 if (!ctx->buf)
437                                         UCI_THROW(ctx, UCI_ERR_MEM);
438                         }
439                         memcpy(&ctx->buf[pos], s, len);
440                         pos += len;
441                 }
442                 strcpy(&ctx->buf[pos], UCI_QUOTE_ESCAPE);
443                 pos += sizeof(UCI_QUOTE_ESCAPE);
444                 s = p + 1;
445         } while ((p = strchr(s, '\'')));
446
447         return ctx->buf;
448 }
449
450
451 /*
452  * export a single config package to a file stream
453  */
454 static void uci_export_package(struct uci_package *p, FILE *stream)
455 {
456         struct uci_context *ctx = p->ctx;
457         struct uci_element *s, *o;
458
459         fprintf(stream, "package '%s'\n", uci_escape(ctx, p->e.name));
460         uci_foreach_element(&p->sections, s) {
461                 struct uci_section *sec = uci_to_section(s);
462                 fprintf(stream, "\nconfig '%s'", uci_escape(ctx, sec->type));
463                 fprintf(stream, " '%s'\n", uci_escape(ctx, sec->e.name));
464                 uci_foreach_element(&sec->options, o) {
465                         struct uci_option *opt = uci_to_option(o);
466                         fprintf(stream, "\toption '%s'", uci_escape(ctx, opt->e.name));
467                         fprintf(stream, " '%s'\n", uci_escape(ctx, opt->value));
468                 }
469         }
470         fprintf(stream, "\n");
471 }
472
473 int uci_export(struct uci_context *ctx, FILE *stream, struct uci_package *package)
474 {
475         struct uci_element *e;
476
477         UCI_HANDLE_ERR(ctx);
478         UCI_ASSERT(ctx, stream != NULL);
479
480         if (package) {
481                 uci_export_package(package, stream);
482                 goto done;
483         }
484
485         uci_foreach_element(&ctx->root, e) {
486                 uci_export_package(uci_to_package(e), stream);
487         }
488 done:
489         return 0;
490 }
491
492 int uci_import(struct uci_context *ctx, FILE *stream, const char *name, struct uci_package **package)
493 {
494         struct uci_parse_context *pctx;
495
496         /* make sure no memory from previous parse attempts is leaked */
497         uci_file_cleanup(ctx);
498
499         pctx = (struct uci_parse_context *) uci_malloc(ctx, sizeof(struct uci_parse_context));
500         ctx->pctx = pctx;
501         pctx->file = stream;
502
503         /*
504          * If 'name' was supplied, assume that the supplied stream does not contain
505          * the appropriate 'package <name>' string to specify the config name
506          * NB: the config file can still override the package name
507          */
508         if (name)
509                 pctx->name = name;
510
511         while (!feof(pctx->file)) {
512                 uci_getln(ctx, 0);
513                 if (pctx->buf[0])
514                         uci_parse_line(ctx);
515         }
516
517         if (package)
518                 *package = pctx->package;
519
520         pctx->name = NULL;
521         uci_switch_config(ctx);
522
523         /* no error happened, we can get rid of the parser context now */
524         uci_file_cleanup(ctx);
525
526         return 0;
527 }
528
529 int uci_load(struct uci_context *ctx, const char *name, struct uci_package **package)
530 {
531         struct stat statbuf;
532         char *filename;
533         bool confpath;
534         FILE *file;
535         int fd;
536
537         UCI_HANDLE_ERR(ctx);
538         UCI_ASSERT(ctx, name != NULL);
539
540         switch (name[0]) {
541         case '.':
542         case '/':
543                 /* absolute/relative path outside of /etc/config */
544                 filename = (char *) name;
545                 confpath = false;
546                 break;
547         default:
548                 filename = uci_malloc(ctx, strlen(name) + sizeof(UCI_CONFDIR) + 2);
549                 sprintf(filename, UCI_CONFDIR "/%s", name);
550                 confpath = true;
551                 break;
552         }
553
554         if ((stat(filename, &statbuf) < 0) ||
555                 ((statbuf.st_mode &  S_IFMT) != S_IFREG)) {
556                 UCI_THROW(ctx, UCI_ERR_NOTFOUND);
557         }
558
559         fd = open(filename, O_RDONLY);
560         if (filename != name)
561                 free(filename);
562
563         flock(fd, LOCK_SH);
564         file = fdopen(fd, "r");
565         if (!file)
566                 UCI_THROW(ctx, UCI_ERR_IO);
567
568         ctx->errno = 0;
569         UCI_TRAP_SAVE(ctx, done);
570         uci_import(ctx, file, name, package);
571         UCI_TRAP_RESTORE(ctx);
572
573 done:
574         flock(fd, LOCK_UN);
575         fclose(file);
576         return ctx->errno;
577 }
578
579 /* 
580  * This function returns the filename by returning the string
581  * after the last '/' character. By checking for a non-'\0'
582  * character afterwards, directories are ignored (glob marks
583  * those with a trailing '/'
584  */
585 static inline char *get_filename(char *path)
586 {
587         char *p;
588
589         p = strrchr(path, '/');
590         p++;
591         if (!*p)
592                 return NULL;
593         return p;
594 }
595
596 char **uci_list_configs(struct uci_context *ctx)
597 {
598         char **configs;
599         glob_t globbuf;
600         int size, i;
601         char *buf;
602
603         if (glob(UCI_CONFDIR "/*", GLOB_MARK, NULL, &globbuf) != 0)
604                 return NULL;
605
606         size = sizeof(char *) * (globbuf.gl_pathc + 1);
607         for(i = 0; i < globbuf.gl_pathc; i++) {
608                 char *p;
609
610                 p = get_filename(globbuf.gl_pathv[i]);
611                 if (!p)
612                         continue;
613
614                 size += strlen(p) + 1;
615         }
616
617         configs = malloc(size);
618         if (!configs)
619                 return NULL;
620
621         memset(configs, 0, size);
622         buf = (char *) &configs[globbuf.gl_pathc + 1];
623         for(i = 0; i < globbuf.gl_pathc; i++) {
624                 char *p;
625
626                 p = get_filename(globbuf.gl_pathv[i]);
627                 if (!p)
628                         continue;
629
630                 configs[i] = buf;
631                 strcpy(buf, p);
632                 buf += strlen(buf) + 1;
633         }
634         return configs;
635 }
636
637