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