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