2 * libuci - Library for the Unified Configuration Interface
3 * Copyright (C) 2008 Felix Fietkau <nbd@openwrt.org>
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
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 Lesser General Public License for more details.
16 * This file contains the code for parsing uci config files
20 #include <sys/types.h>
33 #include "uci_internal.h"
36 #define LINEBUF_MAX 4096
39 * Fetch a new line from the input stream and resize buffer if necessary
41 __private void uci_getln(struct uci_context *ctx, int offset)
43 struct uci_parse_context *pctx = ctx->pctx;
47 if (pctx->buf == NULL) {
48 pctx->buf = uci_malloc(ctx, LINEBUF);
49 pctx->bufsz = LINEBUF;
57 p = fgets(p, pctx->bufsz - ofs, pctx->file);
62 if (pctx->buf[ofs - 1] == '\n') {
64 if (ofs >= 2 && pctx->buf[ofs - 2] == '\r')
65 pctx->buf[ofs - 2] = 0;
67 pctx->buf[ofs - 1] = 0;
71 if (pctx->bufsz > LINEBUF_MAX/2)
72 uci_parse_error(ctx, p, "line too long");
75 pctx->buf = uci_realloc(ctx, pctx->buf, pctx->bufsz);
81 * parse a character escaped by '\'
82 * returns true if the escaped character is to be parsed
83 * returns false if the escaped character is to be ignored
85 static inline bool parse_backslash(struct uci_context *ctx, char **str)
90 /* undecoded backslash at the end of line, fetch the next line */
93 uci_getln(ctx, *str - ctx->pctx->buf);
97 /* FIXME: decode escaped char, necessary? */
102 * move the string pointer forward until a non-whitespace character or
105 static void skip_whitespace(struct uci_context *ctx, char **str)
108 while (**str && isspace(**str))
112 if (!parse_backslash(ctx, str))
117 static inline void addc(char **dest, char **src)
125 * parse a double quoted string argument from the command line
127 static void parse_double_quote(struct uci_context *ctx, char **str, char **target)
131 /* skip quote character */
134 while ((c = **str)) {
141 if (!parse_backslash(ctx, str))
149 uci_parse_error(ctx, *str, "unterminated \"");
153 * parse a single quoted string argument from the command line
155 static void parse_single_quote(struct uci_context *ctx, char **str, char **target)
158 /* skip quote character */
161 while ((c = **str)) {
171 uci_parse_error(ctx, *str, "unterminated '");
175 * parse a string from the command line and detect the quoting style
177 static void parse_str(struct uci_context *ctx, char **str, char **target)
183 parse_single_quote(ctx, str, target);
186 parse_double_quote(ctx, str, target);
197 if (!parse_backslash(ctx, str))
204 } while (**str && !isspace(**str));
208 * if the string was unquoted and we've stopped at a whitespace
209 * character, skip to the next one, because the whitespace will
210 * be overwritten by a null byte here
215 /* terminate the parsed string */
220 * extract the next argument from the command line
222 static char *next_arg(struct uci_context *ctx, char **str, bool required, bool name)
228 skip_whitespace(ctx, str);
233 parse_str(ctx, str, &ptr);
237 uci_parse_error(ctx, *str, "insufficient arguments");
241 if (name && !uci_validate_name(val))
242 uci_parse_error(ctx, val, "invalid character in field");
248 int uci_parse_argument(struct uci_context *ctx, FILE *stream, char **str, char **result)
251 UCI_ASSERT(ctx, str != NULL);
252 UCI_ASSERT(ctx, result != NULL);
254 if (ctx->pctx && (ctx->pctx->file != stream))
258 uci_alloc_parse_context(ctx);
260 ctx->pctx->file = stream;
264 *str = ctx->pctx->buf;
267 *result = next_arg(ctx, str, false, false);
273 uci_fill_ptr(struct uci_context *ctx, struct uci_ptr *ptr, struct uci_element *e)
275 UCI_ASSERT(ctx, ptr != NULL);
276 UCI_ASSERT(ctx, e != NULL);
278 memset(ptr, 0, sizeof(struct uci_ptr));
280 case UCI_TYPE_OPTION:
281 ptr->o = uci_to_option(e);
283 case UCI_TYPE_SECTION:
284 ptr->s = uci_to_section(e);
286 case UCI_TYPE_PACKAGE:
287 ptr->p = uci_to_package(e);
290 UCI_THROW(ctx, UCI_ERR_INVAL);
294 ptr->option = ptr->o->e.name;
295 ptr->s = ptr->o->section;
297 ptr->section = ptr->s->e.name;
298 ptr->p = ptr->s->package;
300 ptr->package = ptr->p->e.name;
302 ptr->flags |= UCI_LOOKUP_DONE;
310 * verify that the end of the line or command is reached.
311 * throw an error if extra arguments are given on the command line
313 static void assert_eol(struct uci_context *ctx, char **str)
317 skip_whitespace(ctx, str);
318 tmp = next_arg(ctx, str, false, false);
319 if (*tmp && (ctx->flags & UCI_FLAG_STRICT))
320 uci_parse_error(ctx, *str, "too many arguments");
324 * switch to a different config, either triggered by uci_load, or by a
325 * 'package <...>' statement in the import file
327 static void uci_switch_config(struct uci_context *ctx)
329 struct uci_parse_context *pctx;
330 struct uci_element *e;
336 /* add the last config to main config file list */
338 pctx->package->backend = ctx->backend;
339 uci_list_add(&ctx->root, &pctx->package->e.list);
341 pctx->package = NULL;
342 pctx->section = NULL;
349 * if an older config under the same name exists, unload it
350 * ignore errors here, e.g. if the config was not found
352 e = uci_lookup_list(&ctx->root, name);
354 UCI_THROW(ctx, UCI_ERR_DUPLICATE);
355 pctx->package = uci_alloc_package(ctx, name);
359 * parse the 'package' uci command (next config package)
361 static void uci_parse_package(struct uci_context *ctx, char **str, bool single)
365 /* command string null-terminated by strtok */
366 *str += strlen(*str) + 1;
368 name = next_arg(ctx, str, true, true);
369 assert_eol(ctx, str);
373 ctx->pctx->name = name;
374 uci_switch_config(ctx);
378 * parse the 'config' uci command (open a section)
380 static void uci_parse_config(struct uci_context *ctx, char **str)
382 struct uci_parse_context *pctx = ctx->pctx;
383 struct uci_element *e;
388 uci_fixup_section(ctx, ctx->pctx->section);
389 if (!ctx->pctx->package) {
390 if (!ctx->pctx->name)
391 uci_parse_error(ctx, *str, "attempting to import a file without a package name");
393 uci_switch_config(ctx);
396 /* command string null-terminated by strtok */
397 *str += strlen(*str) + 1;
399 type = next_arg(ctx, str, true, false);
400 if (!uci_validate_type(type))
401 uci_parse_error(ctx, type, "invalid character in field");
402 name = next_arg(ctx, str, false, true);
403 assert_eol(ctx, str);
405 if (!name || !name[0]) {
406 ctx->internal = !pctx->merge;
407 UCI_NESTED(uci_add_section, ctx, pctx->package, type, &pctx->section);
409 uci_fill_ptr(ctx, &ptr, &pctx->package->e);
410 e = uci_lookup_list(&pctx->package->sections, name);
412 ptr.s = uci_to_section(e);
416 ctx->internal = !pctx->merge;
417 UCI_NESTED(uci_set, ctx, &ptr);
418 pctx->section = uci_to_section(ptr.last);
423 * parse the 'option' uci command (open a value)
425 static void uci_parse_option(struct uci_context *ctx, char **str, bool list)
427 struct uci_parse_context *pctx = ctx->pctx;
428 struct uci_element *e;
434 uci_parse_error(ctx, *str, "option/list command found before the first section");
436 /* command string null-terminated by strtok */
437 *str += strlen(*str) + 1;
439 name = next_arg(ctx, str, true, true);
440 value = next_arg(ctx, str, false, false);
441 assert_eol(ctx, str);
443 uci_fill_ptr(ctx, &ptr, &pctx->section->e);
444 e = uci_lookup_list(&pctx->section->options, name);
446 ptr.o = uci_to_option(e);
450 ctx->internal = !pctx->merge;
452 UCI_NESTED(uci_add_list, ctx, &ptr);
454 UCI_NESTED(uci_set, ctx, &ptr);
458 * parse a complete input line, split up combined commands by ';'
460 static void uci_parse_line(struct uci_context *ctx, bool single)
462 struct uci_parse_context *pctx = ctx->pctx;
468 word = strtok_r(word, " \t", &brk);
477 if ((word[1] == 0) || !strcmp(word + 1, "ackage"))
478 uci_parse_package(ctx, &word, single);
483 if ((word[1] == 0) || !strcmp(word + 1, "onfig"))
484 uci_parse_config(ctx, &word);
489 if ((word[1] == 0) || !strcmp(word + 1, "ption"))
490 uci_parse_option(ctx, &word, false);
495 if ((word[1] == 0) || !strcmp(word + 1, "ist"))
496 uci_parse_option(ctx, &word, true);
505 uci_parse_error(ctx, word, "invalid command");
509 /* max number of characters that escaping adds to the string */
510 #define UCI_QUOTE_ESCAPE "'\\''"
513 * escape an uci string for export
515 static const char *uci_escape(struct uci_context *ctx, const char *str)
521 ctx->bufsz = LINEBUF;
522 ctx->buf = malloc(LINEBUF);
531 end = strchr(str, '\'');
533 end = str + strlen(str);
536 /* make sure that we have enough room in the buffer */
537 while (ofs + len + sizeof(UCI_QUOTE_ESCAPE) + 1 > ctx->bufsz) {
539 ctx->buf = uci_realloc(ctx, ctx->buf, ctx->bufsz);
542 /* copy the string until the character before the quote */
543 memcpy(&ctx->buf[ofs], str, len);
546 /* end of string? return the buffer */
550 memcpy(&ctx->buf[ofs], UCI_QUOTE_ESCAPE, sizeof(UCI_QUOTE_ESCAPE));
551 ofs += strlen(&ctx->buf[ofs]);
560 * export a single config package to a file stream
562 static void uci_export_package(struct uci_package *p, FILE *stream, bool header)
564 struct uci_context *ctx = p->ctx;
565 struct uci_element *s, *o, *i;
568 fprintf(stream, "package %s\n", uci_escape(ctx, p->e.name));
569 uci_foreach_element(&p->sections, s) {
570 struct uci_section *sec = uci_to_section(s);
571 fprintf(stream, "\nconfig %s", uci_escape(ctx, sec->type));
572 if (!sec->anonymous || (ctx->flags & UCI_FLAG_EXPORT_NAME))
573 fprintf(stream, " '%s'", uci_escape(ctx, sec->e.name));
574 fprintf(stream, "\n");
575 uci_foreach_element(&sec->options, o) {
576 struct uci_option *opt = uci_to_option(o);
578 case UCI_TYPE_STRING:
579 fprintf(stream, "\toption %s", uci_escape(ctx, opt->e.name));
580 fprintf(stream, " '%s'\n", uci_escape(ctx, opt->v.string));
583 uci_foreach_element(&opt->v.list, i) {
584 fprintf(stream, "\tlist %s", uci_escape(ctx, opt->e.name));
585 fprintf(stream, " '%s'\n", uci_escape(ctx, i->name));
589 fprintf(stream, "\t# unknown type for option '%s'\n", uci_escape(ctx, opt->e.name));
594 fprintf(stream, "\n");
597 int uci_export(struct uci_context *ctx, FILE *stream, struct uci_package *package, bool header)
599 struct uci_element *e;
602 UCI_ASSERT(ctx, stream != NULL);
605 uci_export_package(package, stream, header);
607 uci_foreach_element(&ctx->root, e) {
608 uci_export_package(uci_to_package(e), stream, header);
615 int uci_import(struct uci_context *ctx, FILE *stream, const char *name, struct uci_package **package, bool single)
617 struct uci_parse_context *pctx;
620 /* make sure no memory from previous parse attempts is leaked */
623 uci_alloc_parse_context(ctx);
626 if (package && *package && single) {
627 pctx->package = *package;
632 * If 'name' was supplied, assume that the supplied stream does not contain
633 * the appropriate 'package <name>' string to specify the config name
634 * NB: the config file can still override the package name
637 UCI_ASSERT(ctx, uci_validate_package(name));
641 while (!feof(pctx->file)) {
643 UCI_TRAP_SAVE(ctx, error);
645 uci_parse_line(ctx, single);
646 UCI_TRAP_RESTORE(ctx);
649 if (ctx->flags & UCI_FLAG_PERROR)
650 uci_perror(ctx, NULL);
651 if ((ctx->err != UCI_ERR_PARSE) ||
652 (ctx->flags & UCI_FLAG_STRICT))
653 UCI_THROW(ctx, ctx->err);
656 uci_fixup_section(ctx, ctx->pctx->section);
657 if (!pctx->package && name)
658 uci_switch_config(ctx);
660 *package = pctx->package;
662 pctx->package = NULL;
665 uci_switch_config(ctx);
667 /* no error happened, we can get rid of the parser context now */
674 static char *uci_config_path(struct uci_context *ctx, const char *name)
678 UCI_ASSERT(ctx, uci_validate_package(name));
679 filename = uci_malloc(ctx, strlen(name) + strlen(ctx->confdir) + 2);
680 sprintf(filename, "%s/%s", ctx->confdir, name);
685 static void uci_file_commit(struct uci_context *ctx, struct uci_package **package, bool overwrite)
687 struct uci_package *p = *package;
688 FILE *f1, *f2 = NULL;
691 char *filename = NULL;
693 bool do_rename = false;
697 p->path = uci_config_path(ctx, p->e.name);
699 UCI_THROW(ctx, UCI_ERR_INVAL);
702 if ((asprintf(&filename, "%s/.%s.uci-XXXXXX", ctx->confdir, p->e.name) < 0) || !filename)
703 UCI_THROW(ctx, UCI_ERR_MEM);
705 if (!mktemp(filename))
710 UCI_THROW(ctx, UCI_ERR_IO);
713 if ((stat(filename, &statbuf) == 0) && ((statbuf.st_mode & S_IFMT) != S_IFREG))
714 UCI_THROW(ctx, UCI_ERR_IO);
716 /* open the config file for writing now, so that it is locked */
717 f1 = uci_open_stream(ctx, p->path, SEEK_SET, false, false);
719 /* flush unsaved changes and reload from delta file */
720 UCI_TRAP_SAVE(ctx, done);
723 name = uci_strdup(ctx, p->e.name);
724 path = uci_strdup(ctx, p->path);
725 /* dump our own changes to the delta file */
726 if (!uci_list_empty(&p->delta))
727 UCI_INTERNAL(uci_save, ctx, p);
730 * other processes might have modified the config
731 * as well. dump and reload
733 uci_free_package(&p);
735 UCI_INTERNAL(uci_import, ctx, f1, name, &p, true);
741 /* freed together with the uci_package */
746 if (!uci_load_delta(ctx, p, true))
750 f2 = uci_open_stream(ctx, filename, SEEK_SET, true, true);
751 uci_export(ctx, f2, p, false);
755 uci_close_stream(f2);
759 UCI_TRAP_RESTORE(ctx);
764 uci_close_stream(f1);
765 if (do_rename && rename(filename, p->path)) {
767 UCI_THROW(ctx, UCI_ERR_IO);
772 UCI_THROW(ctx, ctx->err);
777 * This function returns the filename by returning the string
778 * after the last '/' character. By checking for a non-'\0'
779 * character afterwards, directories are ignored (glob marks
780 * those with a trailing '/'
782 static inline char *get_filename(char *path)
786 p = strrchr(path, '/');
793 static char **uci_list_config_files(struct uci_context *ctx)
801 dir = uci_malloc(ctx, strlen(ctx->confdir) + 1 + sizeof("/*"));
802 sprintf(dir, "%s/*", ctx->confdir);
803 if (glob(dir, GLOB_MARK, NULL, &globbuf) != 0) {
805 UCI_THROW(ctx, UCI_ERR_NOTFOUND);
808 size = sizeof(char *) * (globbuf.gl_pathc + 1);
809 for(i = 0; i < globbuf.gl_pathc; i++) {
812 p = get_filename(globbuf.gl_pathv[i]);
816 size += strlen(p) + 1;
819 configs = uci_malloc(ctx, size);
820 buf = (char *) &configs[globbuf.gl_pathc + 1];
821 for(i = 0; i < globbuf.gl_pathc; i++) {
824 p = get_filename(globbuf.gl_pathv[i]);
828 if (!uci_validate_package(p))
833 buf += strlen(buf) + 1;
840 static struct uci_package *uci_file_load(struct uci_context *ctx, const char *name)
842 struct uci_package *package = NULL;
849 /* relative path outside of /etc/config */
851 UCI_THROW(ctx, UCI_ERR_NOTFOUND);
854 /* absolute path outside of /etc/config */
855 filename = uci_strdup(ctx, name);
856 name = strrchr(name, '/') + 1;
860 /* config in /etc/config */
861 filename = uci_config_path(ctx, name);
866 UCI_TRAP_SAVE(ctx, done);
867 file = uci_open_stream(ctx, filename, SEEK_SET, false, false);
869 UCI_INTERNAL(uci_import, ctx, file, name, &package, true);
870 UCI_TRAP_RESTORE(ctx);
873 package->path = filename;
874 package->has_delta = confdir;
875 uci_load_delta(ctx, package, false);
879 uci_close_stream(file);
882 UCI_THROW(ctx, ctx->err);
887 __private UCI_BACKEND(uci_file_backend, "file",
888 .load = uci_file_load,
889 .commit = uci_file_commit,
890 .list_configs = uci_list_config_files,