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