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 General Public License for more details.
16 * This file contains the code for parsing uci config files
19 #include <sys/types.h>
28 #define LINEBUF_MAX 4096
30 static void uci_parse_error(struct uci_context *ctx, char *pos, char *reason)
32 struct uci_parse_context *pctx = ctx->pctx;
34 pctx->reason = reason;
35 pctx->byte = pos - pctx->buf;
36 UCI_THROW(ctx, UCI_ERR_PARSE);
40 * Fetch a new line from the input stream and resize buffer if necessary
42 static void uci_getln(struct uci_context *ctx, int offset)
44 struct uci_parse_context *pctx = ctx->pctx;
48 if (pctx->buf == NULL) {
49 pctx->buf = uci_malloc(ctx, LINEBUF);
50 pctx->bufsz = LINEBUF;
58 p = fgets(p, pctx->bufsz - ofs, pctx->file);
63 if (pctx->buf[ofs - 1] == '\n') {
65 pctx->buf[ofs - 1] = 0;
69 if (pctx->bufsz > LINEBUF_MAX/2)
70 uci_parse_error(ctx, p, "line too long");
73 pctx->buf = uci_realloc(ctx, pctx->buf, pctx->bufsz);
78 * Clean up all extra memory used by the parser and exporter
80 static void uci_file_cleanup(struct uci_context *ctx)
82 struct uci_parse_context *pctx;
96 uci_free_package(&pctx->package);
105 * parse a character escaped by '\'
106 * returns true if the escaped character is to be parsed
107 * returns false if the escaped character is to be ignored
109 static inline bool parse_backslash(struct uci_context *ctx, char **str)
114 /* undecoded backslash at the end of line, fetch the next line */
117 uci_getln(ctx, *str - ctx->pctx->buf);
121 /* FIXME: decode escaped char, necessary? */
126 * move the string pointer forward until a non-whitespace character or
129 static void skip_whitespace(struct uci_context *ctx, char **str)
132 while (**str && isspace(**str))
136 if (!parse_backslash(ctx, str))
141 static inline void addc(char **dest, char **src)
149 * parse a double quoted string argument from the command line
151 static void parse_double_quote(struct uci_context *ctx, char **str, char **target)
155 /* skip quote character */
158 while ((c = **str)) {
165 if (!parse_backslash(ctx, str))
173 uci_parse_error(ctx, *str, "unterminated \"");
177 * parse a single quoted string argument from the command line
179 static void parse_single_quote(struct uci_context *ctx, char **str, char **target)
182 /* skip quote character */
185 while ((c = **str)) {
195 uci_parse_error(ctx, *str, "unterminated '");
199 * parse a string from the command line and detect the quoting style
201 static void parse_str(struct uci_context *ctx, char **str, char **target)
206 parse_single_quote(ctx, str, target);
209 parse_double_quote(ctx, str, target);
214 if (!parse_backslash(ctx, str))
221 } while (**str && !isspace(**str));
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
232 /* terminate the parsed string */
237 * extract the next argument from the command line
239 static char *next_arg(struct uci_context *ctx, char **str, bool required, bool name)
245 skip_whitespace(ctx, str);
246 parse_str(ctx, str, &ptr);
247 if (required && !*val)
248 uci_parse_error(ctx, *str, "insufficient arguments");
249 if (name && !uci_validate_name(val))
250 uci_parse_error(ctx, val, "invalid character in field");
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
259 static void assert_eol(struct uci_context *ctx, char **str)
263 tmp = next_arg(ctx, str, false, false);
265 uci_parse_error(ctx, *str, "too many arguments");
269 * switch to a different config, either triggered by uci_load, or by a
270 * 'package <...>' statement in the import file
272 static void uci_switch_config(struct uci_context *ctx)
274 struct uci_parse_context *pctx;
275 struct uci_element *e;
281 /* add the last config to main config file list */
283 uci_list_add(&ctx->root, &pctx->package->e.list);
285 pctx->package = NULL;
286 pctx->section = NULL;
293 * if an older config under the same name exists, unload it
294 * ignore errors here, e.g. if the config was not found
296 e = uci_lookup_list(ctx, &ctx->root, name);
298 UCI_THROW(ctx, UCI_ERR_DUPLICATE);
299 pctx->package = uci_alloc_package(ctx, name);
303 * parse the 'package' uci command (next config package)
305 static void uci_parse_package(struct uci_context *ctx, char **str, bool single)
309 /* command string null-terminated by strtok */
310 *str += strlen(*str) + 1;
312 name = next_arg(ctx, str, true, true);
313 assert_eol(ctx, str);
317 ctx->pctx->name = name;
318 uci_switch_config(ctx);
322 * parse the 'config' uci command (open a section)
324 static void uci_parse_config(struct uci_context *ctx, char **str)
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");
333 uci_switch_config(ctx);
336 /* command string null-terminated by strtok */
337 *str += strlen(*str) + 1;
339 type = next_arg(ctx, str, true, true);
340 name = next_arg(ctx, str, false, true);
341 assert_eol(ctx, str);
342 ctx->pctx->section = uci_alloc_section(ctx->pctx->package, type, name);
346 * parse the 'option' uci command (open a value)
348 static void uci_parse_option(struct uci_context *ctx, char **str)
353 if (!ctx->pctx->section)
354 uci_parse_error(ctx, *str, "option command found before the first section");
356 /* command string null-terminated by strtok */
357 *str += strlen(*str) + 1;
359 name = next_arg(ctx, str, true, true);
360 value = next_arg(ctx, str, true, false);
361 assert_eol(ctx, str);
362 uci_alloc_option(ctx->pctx->section, name, value);
367 * parse a complete input line, split up combined commands by ';'
369 static void uci_parse_line(struct uci_context *ctx, bool single)
371 struct uci_parse_context *pctx = ctx->pctx;
372 char *word, *brk = NULL;
374 for (word = strtok_r(pctx->buf, ";", &brk);
376 word = strtok_r(NULL, ";", &brk)) {
379 word = strtok_r(word, " \t", &pbrk);
383 if ((word[1] == 0) || !strcmp(word + 1, "ackage"))
384 uci_parse_package(ctx, &word, single);
387 if ((word[1] == 0) || !strcmp(word + 1, "onfig"))
388 uci_parse_config(ctx, &word);
391 if ((word[1] == 0) || !strcmp(word + 1, "ption"))
392 uci_parse_option(ctx, &word);
395 uci_parse_error(ctx, word, "unterminated command");
401 /* max number of characters that escaping adds to the string */
402 #define UCI_QUOTE_ESCAPE "'\\''"
405 * escape an uci string for export
407 static char *uci_escape(struct uci_context *ctx, char *str)
413 ctx->bufsz = LINEBUF;
414 ctx->buf = malloc(LINEBUF);
418 p = strchr(str, '\'');
425 if (p + sizeof(UCI_QUOTE_ESCAPE) - str >= ctx->bufsz) {
427 ctx->buf = realloc(ctx->buf, ctx->bufsz);
429 UCI_THROW(ctx, UCI_ERR_MEM);
431 memcpy(&ctx->buf[pos], s, len);
434 strcpy(&ctx->buf[pos], UCI_QUOTE_ESCAPE);
435 pos += sizeof(UCI_QUOTE_ESCAPE);
437 } while ((p = strchr(s, '\'')));
444 * export a single config package to a file stream
446 static void uci_export_package(struct uci_package *p, FILE *stream, bool header)
448 struct uci_context *ctx = p->ctx;
449 struct uci_element *s, *o;
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));
463 fprintf(stream, "\n");
466 int uci_export(struct uci_context *ctx, FILE *stream, struct uci_package *package, bool header)
468 struct uci_element *e;
471 UCI_ASSERT(ctx, stream != NULL);
474 uci_export_package(package, stream, header);
476 uci_foreach_element(&ctx->root, e) {
477 uci_export_package(uci_to_package(e), stream, header);
484 int uci_import(struct uci_context *ctx, FILE *stream, const char *name, struct uci_package **package, bool single)
486 struct uci_parse_context *pctx;
488 /* make sure no memory from previous parse attempts is leaked */
489 uci_file_cleanup(ctx);
491 pctx = (struct uci_parse_context *) uci_malloc(ctx, sizeof(struct uci_parse_context));
496 * If 'name' was supplied, assume that the supplied stream does not contain
497 * the appropriate 'package <name>' string to specify the config name
498 * NB: the config file can still override the package name
503 while (!feof(pctx->file)) {
505 UCI_TRAP_SAVE(ctx, error);
507 uci_parse_line(ctx, single);
508 UCI_TRAP_RESTORE(ctx);
511 if (ctx->flags & UCI_FLAG_PERROR)
512 uci_perror(ctx, NULL);
513 if ((ctx->errno != UCI_ERR_PARSE) ||
514 (ctx->flags & UCI_FLAG_STRICT))
515 UCI_THROW(ctx, ctx->errno);
519 *package = pctx->package;
522 uci_switch_config(ctx);
524 /* no error happened, we can get rid of the parser context now */
525 uci_file_cleanup(ctx);
531 * open a stream and go to the right position
533 * note: when opening for write and seeking to the beginning of
534 * the stream, truncate the file
536 static FILE *uci_open_stream(struct uci_context *ctx, const char *filename, int pos, bool write, bool create)
541 int mode = (write ? O_RDWR : O_RDONLY);
546 if (!write && ((stat(filename, &statbuf) < 0) ||
547 ((statbuf.st_mode & S_IFMT) != S_IFREG))) {
548 UCI_THROW(ctx, UCI_ERR_NOTFOUND);
551 fd = open(filename, mode, UCI_FILEMODE);
555 if (flock(fd, (write ? LOCK_EX : LOCK_SH)) < 0)
558 ret = lseek(fd, 0, pos);
563 file = fdopen(fd, (write ? "w+" : "r"));
568 UCI_THROW(ctx, UCI_ERR_IO);
573 static void uci_close_stream(FILE *stream)
585 static void uci_parse_history_line(struct uci_context *ctx, struct uci_package *p, char *buf)
588 char *package = NULL;
589 char *section = NULL;
598 UCI_INTERNAL(uci_parse_tuple, ctx, buf, &package, §ion, &option, &value);
599 if (!package || !section || (!delete && !value))
601 if (strcmp(package, p->e.name) != 0)
603 if (!uci_validate_name(section))
605 if (option && !uci_validate_name(option))
609 UCI_INTERNAL(uci_del, ctx, p, section, option);
611 UCI_INTERNAL(uci_set, ctx, p, section, option, value);
615 UCI_THROW(ctx, UCI_ERR_PARSE);
618 static void uci_parse_history(struct uci_context *ctx, FILE *stream, struct uci_package *p)
620 struct uci_parse_context *pctx;
622 /* make sure no memory from previous parse attempts is leaked */
623 uci_file_cleanup(ctx);
625 pctx = (struct uci_parse_context *) uci_malloc(ctx, sizeof(struct uci_parse_context));
629 while (!feof(pctx->file)) {
635 * ignore parse errors in single lines, we want to preserve as much
636 * history as possible
638 UCI_TRAP_SAVE(ctx, error);
639 uci_parse_history_line(ctx, p, pctx->buf);
640 UCI_TRAP_RESTORE(ctx);
645 /* no error happened, we can get rid of the parser context now */
646 uci_file_cleanup(ctx);
649 static void uci_load_history(struct uci_context *ctx, struct uci_package *p, bool flush)
651 char *filename = NULL;
656 if ((asprintf(&filename, "%s/%s", UCI_SAVEDIR, p->e.name) < 0) || !filename)
657 UCI_THROW(ctx, UCI_ERR_MEM);
659 UCI_TRAP_SAVE(ctx, done);
660 f = uci_open_stream(ctx, filename, SEEK_SET, flush, false);
661 uci_parse_history(ctx, f, p);
662 UCI_TRAP_RESTORE(ctx);
667 ftruncate(fileno(f), 0);
676 int uci_load(struct uci_context *ctx, const char *name, struct uci_package **package)
683 UCI_ASSERT(ctx, name != NULL);
687 /* relative path outside of /etc/config */
689 UCI_THROW(ctx, UCI_ERR_NOTFOUND);
692 /* absolute path outside of /etc/config */
693 filename = uci_strdup(ctx, name);
694 name = strrchr(name, '/') + 1;
698 /* config in /etc/config */
699 if (strchr(name, '/'))
700 UCI_THROW(ctx, UCI_ERR_INVAL);
701 filename = uci_malloc(ctx, strlen(name) + sizeof(UCI_CONFDIR) + 2);
702 sprintf(filename, UCI_CONFDIR "/%s", name);
707 file = uci_open_stream(ctx, filename, SEEK_SET, false, false);
709 UCI_TRAP_SAVE(ctx, done);
710 uci_import(ctx, file, name, package, true);
711 UCI_TRAP_RESTORE(ctx);
714 (*package)->path = filename;
715 (*package)->confdir = confdir;
716 uci_load_history(ctx, *package, false);
720 uci_close_stream(file);
724 int uci_save(struct uci_context *ctx, struct uci_package *p)
727 char *filename = NULL;
728 struct uci_element *e, *tmp;
731 UCI_ASSERT(ctx, p != NULL);
734 * if the config file was outside of the /etc/config path,
735 * don't save the history to a file, update the real file
737 * does not modify the uci_package pointer
740 return uci_commit(ctx, &p);
742 if (uci_list_empty(&p->history))
745 if ((asprintf(&filename, "%s/%s", UCI_SAVEDIR, p->e.name) < 0) || !filename)
746 UCI_THROW(ctx, UCI_ERR_MEM);
749 UCI_TRAP_SAVE(ctx, done);
750 f = uci_open_stream(ctx, filename, SEEK_END, true, true);
751 UCI_TRAP_RESTORE(ctx);
753 uci_foreach_element_safe(&p->history, tmp, e) {
754 struct uci_history *h = uci_to_history(e);
756 if (h->cmd == UCI_CMD_REMOVE)
759 fprintf(f, "%s.%s", p->e.name, h->section);
761 fprintf(f, ".%s", e->name);
763 if (h->cmd == UCI_CMD_REMOVE)
766 fprintf(f, "=%s\n", h->value);
775 UCI_THROW(ctx, ctx->errno);
780 int uci_commit(struct uci_context *ctx, struct uci_package **package)
782 struct uci_package *p;
788 UCI_ASSERT(ctx, package != NULL);
791 UCI_ASSERT(ctx, p != NULL);
792 UCI_ASSERT(ctx, p->path != NULL);
794 /* open the config file for writing now, so that it is locked */
795 f = uci_open_stream(ctx, p->path, SEEK_SET, true, true);
797 /* flush unsaved changes and reload from history file */
798 UCI_TRAP_SAVE(ctx, done);
800 name = uci_strdup(ctx, p->e.name);
801 path = uci_strdup(ctx, p->path);
802 if (!uci_list_empty(&p->history))
803 UCI_INTERNAL(uci_save, ctx, p);
804 uci_free_package(&p);
805 uci_file_cleanup(ctx);
806 UCI_INTERNAL(uci_import, ctx, f, name, &p, true);
812 /* freed together with the uci_package */
815 /* check for updated history, just in case */
816 uci_load_history(ctx, p, true);
820 ftruncate(fileno(f), 0);
822 uci_export(ctx, f, p, false);
823 UCI_TRAP_RESTORE(ctx);
832 UCI_THROW(ctx, ctx->errno);
839 * This function returns the filename by returning the string
840 * after the last '/' character. By checking for a non-'\0'
841 * character afterwards, directories are ignored (glob marks
842 * those with a trailing '/'
844 static inline char *get_filename(char *path)
848 p = strrchr(path, '/');
855 int uci_list_configs(struct uci_context *ctx, char ***list)
864 if (glob(UCI_CONFDIR "/*", GLOB_MARK, NULL, &globbuf) != 0)
865 UCI_THROW(ctx, UCI_ERR_NOTFOUND);
867 size = sizeof(char *) * (globbuf.gl_pathc + 1);
868 for(i = 0; i < globbuf.gl_pathc; i++) {
871 p = get_filename(globbuf.gl_pathv[i]);
875 size += strlen(p) + 1;
878 configs = uci_malloc(ctx, size);
879 buf = (char *) &configs[globbuf.gl_pathc + 1];
880 for(i = 0; i < globbuf.gl_pathc; i++) {
883 p = get_filename(globbuf.gl_pathv[i]);
889 buf += strlen(buf) + 1;