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
20 #include <sys/types.h>
30 #define LINEBUF_MAX 4096
32 static void uci_parse_error(struct uci_context *ctx, char *pos, char *reason)
34 struct uci_parse_context *pctx = ctx->pctx;
36 pctx->reason = reason;
37 pctx->byte = pos - pctx->buf;
38 UCI_THROW(ctx, UCI_ERR_PARSE);
42 * Fetch a new line from the input stream and resize buffer if necessary
44 static void uci_getln(struct uci_context *ctx, int offset)
46 struct uci_parse_context *pctx = ctx->pctx;
50 if (pctx->buf == NULL) {
51 pctx->buf = uci_malloc(ctx, LINEBUF);
52 pctx->bufsz = LINEBUF;
60 p = fgets(p, pctx->bufsz - ofs, pctx->file);
65 if (pctx->buf[ofs - 1] == '\n') {
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);
80 * Clean up all extra memory used by the parser and exporter
82 static void uci_file_cleanup(struct uci_context *ctx)
84 struct uci_parse_context *pctx;
98 uci_free_package(&pctx->package);
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
111 static inline bool parse_backslash(struct uci_context *ctx, char **str)
116 /* undecoded backslash at the end of line, fetch the next line */
119 uci_getln(ctx, *str - ctx->pctx->buf);
123 /* FIXME: decode escaped char, necessary? */
128 * move the string pointer forward until a non-whitespace character or
131 static void skip_whitespace(struct uci_context *ctx, char **str)
134 while (**str && isspace(**str))
138 if (!parse_backslash(ctx, str))
143 static inline void addc(char **dest, char **src)
151 * parse a double quoted string argument from the command line
153 static void parse_double_quote(struct uci_context *ctx, char **str, char **target)
157 /* skip quote character */
160 while ((c = **str)) {
167 if (!parse_backslash(ctx, str))
175 uci_parse_error(ctx, *str, "unterminated \"");
179 * parse a single quoted string argument from the command line
181 static void parse_single_quote(struct uci_context *ctx, char **str, char **target)
184 /* skip quote character */
187 while ((c = **str)) {
197 uci_parse_error(ctx, *str, "unterminated '");
201 * parse a string from the command line and detect the quoting style
203 static void parse_str(struct uci_context *ctx, char **str, char **target)
208 parse_single_quote(ctx, str, target);
211 parse_double_quote(ctx, str, target);
216 if (!parse_backslash(ctx, str))
223 } while (**str && !isspace(**str));
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
234 /* terminate the parsed string */
239 * extract the next argument from the command line
241 static char *next_arg(struct uci_context *ctx, char **str, bool required, bool name)
247 skip_whitespace(ctx, str);
248 parse_str(ctx, str, &ptr);
251 uci_parse_error(ctx, *str, "insufficient arguments");
255 if (name && !uci_validate_name(val))
256 uci_parse_error(ctx, val, "invalid character in field");
263 * verify that the end of the line or command is reached.
264 * throw an error if extra arguments are given on the command line
266 static void assert_eol(struct uci_context *ctx, char **str)
270 tmp = next_arg(ctx, str, false, false);
272 uci_parse_error(ctx, *str, "too many arguments");
276 * switch to a different config, either triggered by uci_load, or by a
277 * 'package <...>' statement in the import file
279 static void uci_switch_config(struct uci_context *ctx)
281 struct uci_parse_context *pctx;
282 struct uci_element *e;
288 /* add the last config to main config file list */
290 uci_list_add(&ctx->root, &pctx->package->e.list);
292 pctx->package = NULL;
293 pctx->section = NULL;
300 * if an older config under the same name exists, unload it
301 * ignore errors here, e.g. if the config was not found
303 e = uci_lookup_list(ctx, &ctx->root, name);
305 UCI_THROW(ctx, UCI_ERR_DUPLICATE);
306 pctx->package = uci_alloc_package(ctx, name);
310 * parse the 'package' uci command (next config package)
312 static void uci_parse_package(struct uci_context *ctx, char **str, bool single)
316 /* command string null-terminated by strtok */
317 *str += strlen(*str) + 1;
319 name = next_arg(ctx, str, true, true);
320 assert_eol(ctx, str);
324 ctx->pctx->name = name;
325 uci_switch_config(ctx);
328 /* Based on an efficient hash function published by D. J. Bernstein */
329 static unsigned int djbhash(unsigned int hash, char *str)
331 int len = strlen(str);
338 for(i = 0; i < len; i++) {
339 hash = ((hash << 5) + hash) + str[i];
341 return (hash & 0x7FFFFFFF);
344 /* fix up an unnamed section */
345 static void uci_fixup_section(struct uci_context *ctx, struct uci_section *s)
347 unsigned int hash = ~0;
348 struct uci_element *e;
355 * Generate a name for unnamed sections. This is used as reference
356 * when locating or updating the section from apps/scripts.
357 * To make multiple concurrent versions somewhat safe for updating,
358 * the name is generated from a hash of its type and name/value
359 * pairs of its option, and it is prefixed by a counter value.
360 * If the order of the unnamed sections changes for some reason,
361 * updates to them will be rejected.
363 hash = djbhash(hash, s->type);
364 uci_foreach_element(&s->options, e) {
365 hash = djbhash(hash, e->name);
366 hash = djbhash(hash, uci_to_option(e)->value);
368 sprintf(buf, "cfg%02x%04x", ++s->package->n_section, hash % (1 << 16));
369 s->e.name = uci_strdup(ctx, buf);
373 * parse the 'config' uci command (open a section)
375 static void uci_parse_config(struct uci_context *ctx, char **str)
377 struct uci_parse_context *pctx = ctx->pctx;
381 uci_fixup_section(ctx, ctx->pctx->section);
382 if (!ctx->pctx->package) {
383 if (!ctx->pctx->name)
384 uci_parse_error(ctx, *str, "attempting to import a file without a package name");
386 uci_switch_config(ctx);
389 /* command string null-terminated by strtok */
390 *str += strlen(*str) + 1;
392 type = next_arg(ctx, str, true, true);
393 name = next_arg(ctx, str, false, true);
394 assert_eol(ctx, str);
397 UCI_TRAP_SAVE(ctx, error);
398 uci_set(ctx, pctx->package, name, NULL, type);
399 UCI_TRAP_RESTORE(ctx);
402 UCI_THROW(ctx, ctx->errno);
404 pctx->section = uci_alloc_section(pctx->package, type, name);
408 * parse the 'option' uci command (open a value)
410 static void uci_parse_option(struct uci_context *ctx, char **str)
412 struct uci_parse_context *pctx = ctx->pctx;
417 uci_parse_error(ctx, *str, "option command found before the first section");
419 /* command string null-terminated by strtok */
420 *str += strlen(*str) + 1;
422 name = next_arg(ctx, str, true, true);
423 value = next_arg(ctx, str, true, false);
424 assert_eol(ctx, str);
427 UCI_TRAP_SAVE(ctx, error);
428 uci_set(ctx, pctx->package, pctx->section->e.name, name, value);
429 UCI_TRAP_RESTORE(ctx);
432 UCI_THROW(ctx, ctx->errno);
434 uci_alloc_option(pctx->section, name, value);
439 * parse a complete input line, split up combined commands by ';'
441 static void uci_parse_line(struct uci_context *ctx, bool single)
443 struct uci_parse_context *pctx = ctx->pctx;
444 char *word, *brk = NULL;
446 for (word = strtok_r(pctx->buf, ";", &brk);
448 word = strtok_r(NULL, ";", &brk)) {
451 word = strtok_r(word, " \t", &pbrk);
455 if ((word[1] == 0) || !strcmp(word + 1, "ackage"))
456 uci_parse_package(ctx, &word, single);
459 if ((word[1] == 0) || !strcmp(word + 1, "onfig"))
460 uci_parse_config(ctx, &word);
463 if ((word[1] == 0) || !strcmp(word + 1, "ption"))
464 uci_parse_option(ctx, &word);
467 uci_parse_error(ctx, word, "unterminated command");
473 /* max number of characters that escaping adds to the string */
474 #define UCI_QUOTE_ESCAPE "'\\''"
477 * escape an uci string for export
479 static char *uci_escape(struct uci_context *ctx, char *str)
485 ctx->bufsz = LINEBUF;
486 ctx->buf = malloc(LINEBUF);
490 p = strchr(str, '\'');
497 if (p + sizeof(UCI_QUOTE_ESCAPE) - str >= ctx->bufsz) {
499 ctx->buf = realloc(ctx->buf, ctx->bufsz);
501 UCI_THROW(ctx, UCI_ERR_MEM);
503 memcpy(&ctx->buf[pos], s, len);
506 strcpy(&ctx->buf[pos], UCI_QUOTE_ESCAPE);
507 pos += sizeof(UCI_QUOTE_ESCAPE);
509 } while ((p = strchr(s, '\'')));
516 * export a single config package to a file stream
518 static void uci_export_package(struct uci_package *p, FILE *stream, bool header)
520 struct uci_context *ctx = p->ctx;
521 struct uci_element *s, *o;
524 fprintf(stream, "package '%s'\n", uci_escape(ctx, p->e.name));
525 uci_foreach_element(&p->sections, s) {
526 struct uci_section *sec = uci_to_section(s);
527 fprintf(stream, "\nconfig '%s'", uci_escape(ctx, sec->type));
528 if (!sec->anonymous || (ctx->flags & UCI_FLAG_EXPORT_NAME))
529 fprintf(stream, " '%s'", uci_escape(ctx, sec->e.name));
530 fprintf(stream, "\n");
531 uci_foreach_element(&sec->options, o) {
532 struct uci_option *opt = uci_to_option(o);
533 fprintf(stream, "\toption '%s'", uci_escape(ctx, opt->e.name));
534 fprintf(stream, " '%s'\n", uci_escape(ctx, opt->value));
537 fprintf(stream, "\n");
540 int uci_export(struct uci_context *ctx, FILE *stream, struct uci_package *package, bool header)
542 struct uci_element *e;
545 UCI_ASSERT(ctx, stream != NULL);
548 uci_export_package(package, stream, header);
550 uci_foreach_element(&ctx->root, e) {
551 uci_export_package(uci_to_package(e), stream, header);
558 int uci_import(struct uci_context *ctx, FILE *stream, const char *name, struct uci_package **package, bool single)
560 struct uci_parse_context *pctx;
563 /* make sure no memory from previous parse attempts is leaked */
564 uci_file_cleanup(ctx);
566 pctx = (struct uci_parse_context *) uci_malloc(ctx, sizeof(struct uci_parse_context));
569 if (*package && single) {
570 pctx->package = *package;
575 * If 'name' was supplied, assume that the supplied stream does not contain
576 * the appropriate 'package <name>' string to specify the config name
577 * NB: the config file can still override the package name
582 while (!feof(pctx->file)) {
584 UCI_TRAP_SAVE(ctx, error);
586 uci_parse_line(ctx, single);
587 UCI_TRAP_RESTORE(ctx);
590 if (ctx->flags & UCI_FLAG_PERROR)
591 uci_perror(ctx, NULL);
592 if ((ctx->errno != UCI_ERR_PARSE) ||
593 (ctx->flags & UCI_FLAG_STRICT))
594 UCI_THROW(ctx, ctx->errno);
597 uci_fixup_section(ctx, ctx->pctx->section);
599 *package = pctx->package;
601 pctx->package = NULL;
604 uci_switch_config(ctx);
606 /* no error happened, we can get rid of the parser context now */
607 uci_file_cleanup(ctx);
613 * open a stream and go to the right position
615 * note: when opening for write and seeking to the beginning of
616 * the stream, truncate the file
618 static FILE *uci_open_stream(struct uci_context *ctx, const char *filename, int pos, bool write, bool create)
623 int mode = (write ? O_RDWR : O_RDONLY);
628 if (!write && ((stat(filename, &statbuf) < 0) ||
629 ((statbuf.st_mode & S_IFMT) != S_IFREG))) {
630 UCI_THROW(ctx, UCI_ERR_NOTFOUND);
633 fd = open(filename, mode, UCI_FILEMODE);
637 if (flock(fd, (write ? LOCK_EX : LOCK_SH)) < 0)
640 ret = lseek(fd, 0, pos);
645 file = fdopen(fd, (write ? "w+" : "r"));
650 UCI_THROW(ctx, UCI_ERR_IO);
655 static void uci_close_stream(FILE *stream)
667 static void uci_parse_history_line(struct uci_context *ctx, struct uci_package *p, char *buf)
671 char *package = NULL;
672 char *section = NULL;
679 } else if (buf[0] == '@') {
684 UCI_INTERNAL(uci_parse_tuple, ctx, buf, &package, §ion, &option, &value);
685 if (!package || !section || (!delete && !value))
687 if (strcmp(package, p->e.name) != 0)
689 if (!uci_validate_name(section))
691 if (option && !uci_validate_name(option))
695 UCI_INTERNAL(uci_rename, ctx, p, section, option, value);
697 UCI_INTERNAL(uci_delete, ctx, p, section, option);
699 UCI_INTERNAL(uci_set, ctx, p, section, option, value);
703 UCI_THROW(ctx, UCI_ERR_PARSE);
706 static void uci_parse_history(struct uci_context *ctx, FILE *stream, struct uci_package *p)
708 struct uci_parse_context *pctx;
710 /* make sure no memory from previous parse attempts is leaked */
711 uci_file_cleanup(ctx);
713 pctx = (struct uci_parse_context *) uci_malloc(ctx, sizeof(struct uci_parse_context));
717 while (!feof(pctx->file)) {
723 * ignore parse errors in single lines, we want to preserve as much
724 * history as possible
726 UCI_TRAP_SAVE(ctx, error);
727 uci_parse_history_line(ctx, p, pctx->buf);
728 UCI_TRAP_RESTORE(ctx);
733 /* no error happened, we can get rid of the parser context now */
734 uci_file_cleanup(ctx);
737 static void uci_load_history(struct uci_context *ctx, struct uci_package *p, bool flush)
739 char *filename = NULL;
744 if ((asprintf(&filename, "%s/%s", UCI_SAVEDIR, p->e.name) < 0) || !filename)
745 UCI_THROW(ctx, UCI_ERR_MEM);
747 UCI_TRAP_SAVE(ctx, done);
748 f = uci_open_stream(ctx, filename, SEEK_SET, flush, false);
750 uci_parse_history(ctx, f, p);
751 UCI_TRAP_RESTORE(ctx);
756 ftruncate(fileno(f), 0);
765 static char *uci_config_path(struct uci_context *ctx, const char *name)
769 if (strchr(name, '/'))
770 UCI_THROW(ctx, UCI_ERR_INVAL);
771 filename = uci_malloc(ctx, strlen(name) + sizeof(UCI_CONFDIR) + 2);
772 sprintf(filename, UCI_CONFDIR "/%s", name);
777 int uci_load(struct uci_context *ctx, const char *name, struct uci_package **package)
784 UCI_ASSERT(ctx, uci_validate_name(name));
788 /* relative path outside of /etc/config */
790 UCI_THROW(ctx, UCI_ERR_NOTFOUND);
793 /* absolute path outside of /etc/config */
794 filename = uci_strdup(ctx, name);
795 name = strrchr(name, '/') + 1;
799 /* config in /etc/config */
800 filename = uci_config_path(ctx, name);
805 file = uci_open_stream(ctx, filename, SEEK_SET, false, false);
807 UCI_TRAP_SAVE(ctx, done);
808 UCI_INTERNAL(uci_import, ctx, file, name, package, true);
809 UCI_TRAP_RESTORE(ctx);
812 (*package)->path = filename;
813 (*package)->confdir = confdir;
814 uci_load_history(ctx, *package, false);
818 uci_close_stream(file);
822 int uci_save(struct uci_context *ctx, struct uci_package *p)
825 char *filename = NULL;
826 struct uci_element *e, *tmp;
829 UCI_ASSERT(ctx, p != NULL);
832 * if the config file was outside of the /etc/config path,
833 * don't save the history to a file, update the real file
835 * does not modify the uci_package pointer
838 return uci_commit(ctx, &p, false);
840 if (uci_list_empty(&p->history))
843 if ((asprintf(&filename, "%s/%s", UCI_SAVEDIR, p->e.name) < 0) || !filename)
844 UCI_THROW(ctx, UCI_ERR_MEM);
847 UCI_TRAP_SAVE(ctx, done);
848 f = uci_open_stream(ctx, filename, SEEK_END, true, true);
849 UCI_TRAP_RESTORE(ctx);
851 uci_foreach_element_safe(&p->history, tmp, e) {
852 struct uci_history *h = uci_to_history(e);
854 if (h->cmd == UCI_CMD_REMOVE)
856 else if (h->cmd == UCI_CMD_RENAME)
859 fprintf(f, "%s.%s", p->e.name, h->section);
861 fprintf(f, ".%s", e->name);
863 if (h->cmd == UCI_CMD_REMOVE)
866 fprintf(f, "=%s\n", h->value);
875 UCI_THROW(ctx, ctx->errno);
880 int uci_commit(struct uci_context *ctx, struct uci_package **package, bool overwrite)
882 struct uci_package *p;
888 UCI_ASSERT(ctx, package != NULL);
891 UCI_ASSERT(ctx, p != NULL);
894 p->path = uci_config_path(ctx, p->e.name);
896 UCI_THROW(ctx, UCI_ERR_INVAL);
900 /* open the config file for writing now, so that it is locked */
901 f = uci_open_stream(ctx, p->path, SEEK_SET, true, true);
903 /* flush unsaved changes and reload from history file */
904 UCI_TRAP_SAVE(ctx, done);
907 name = uci_strdup(ctx, p->e.name);
908 path = uci_strdup(ctx, p->path);
909 if (!uci_list_empty(&p->history))
910 UCI_INTERNAL(uci_save, ctx, p);
911 uci_free_package(&p);
912 uci_file_cleanup(ctx);
913 UCI_INTERNAL(uci_import, ctx, f, name, &p, true);
919 /* freed together with the uci_package */
922 /* check for updated history, just in case */
923 uci_load_history(ctx, p, true);
926 uci_load_history(ctx, NULL, true);
931 ftruncate(fileno(f), 0);
933 uci_export(ctx, f, p, false);
934 UCI_TRAP_RESTORE(ctx);
943 UCI_THROW(ctx, ctx->errno);
950 * This function returns the filename by returning the string
951 * after the last '/' character. By checking for a non-'\0'
952 * character afterwards, directories are ignored (glob marks
953 * those with a trailing '/'
955 static inline char *get_filename(char *path)
959 p = strrchr(path, '/');
966 int uci_list_configs(struct uci_context *ctx, char ***list)
975 if (glob(UCI_CONFDIR "/*", GLOB_MARK, NULL, &globbuf) != 0)
976 UCI_THROW(ctx, UCI_ERR_NOTFOUND);
978 size = sizeof(char *) * (globbuf.gl_pathc + 1);
979 for(i = 0; i < globbuf.gl_pathc; i++) {
982 p = get_filename(globbuf.gl_pathv[i]);
986 size += strlen(p) + 1;
989 configs = uci_malloc(ctx, size);
990 buf = (char *) &configs[globbuf.gl_pathc + 1];
991 for(i = 0; i < globbuf.gl_pathc; i++) {
994 p = get_filename(globbuf.gl_pathv[i]);
1000 buf += strlen(buf) + 1;