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>
29 * Clean up all extra memory used by the parser and exporter
31 static void uci_file_cleanup(struct uci_context *ctx)
33 struct uci_parse_context *pctx;
47 uci_free_package(&pctx->package);
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
61 static inline bool parse_backslash(struct uci_context *ctx, char **str)
66 /* undecoded backslash at the end of line, fetch the next line */
69 uci_getln(ctx, *str - ctx->pctx->buf);
73 /* FIXME: decode escaped char, necessary? */
78 * move the string pointer forward until a non-whitespace character or
81 static void skip_whitespace(struct uci_context *ctx, char **str)
84 while (**str && isspace(**str))
88 if (!parse_backslash(ctx, str))
93 static inline void addc(char **dest, char **src)
101 * parse a double quoted string argument from the command line
103 static void parse_double_quote(struct uci_context *ctx, char **str, char **target)
107 /* skip quote character */
110 while ((c = **str)) {
117 if (!parse_backslash(ctx, str))
125 uci_parse_error(ctx, *str, "unterminated \"");
129 * parse a single quoted string argument from the command line
131 static void parse_single_quote(struct uci_context *ctx, char **str, char **target)
134 /* skip quote character */
137 while ((c = **str)) {
147 uci_parse_error(ctx, *str, "unterminated '");
151 * parse a string from the command line and detect the quoting style
153 static void parse_str(struct uci_context *ctx, char **str, char **target)
158 parse_single_quote(ctx, str, target);
161 parse_double_quote(ctx, str, target);
169 if (!parse_backslash(ctx, str))
176 } while (**str && !isspace(**str));
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
187 /* terminate the parsed string */
192 * extract the next argument from the command line
194 static char *next_arg(struct uci_context *ctx, char **str, bool required, bool name)
200 skip_whitespace(ctx, str);
201 parse_str(ctx, str, &ptr);
204 uci_parse_error(ctx, *str, "insufficient arguments");
208 if (name && !uci_validate_name(val))
209 uci_parse_error(ctx, val, "invalid character in field");
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
219 static void assert_eol(struct uci_context *ctx, char **str)
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");
229 * switch to a different config, either triggered by uci_load, or by a
230 * 'package <...>' statement in the import file
232 static void uci_switch_config(struct uci_context *ctx)
234 struct uci_parse_context *pctx;
235 struct uci_element *e;
241 /* add the last config to main config file list */
243 uci_list_add(&ctx->root, &pctx->package->e.list);
245 pctx->package = NULL;
246 pctx->section = NULL;
253 * if an older config under the same name exists, unload it
254 * ignore errors here, e.g. if the config was not found
256 e = uci_lookup_list(ctx, &ctx->root, name);
258 UCI_THROW(ctx, UCI_ERR_DUPLICATE);
259 pctx->package = uci_alloc_package(ctx, name);
263 * parse the 'package' uci command (next config package)
265 static void uci_parse_package(struct uci_context *ctx, char **str, bool single)
269 /* command string null-terminated by strtok */
270 *str += strlen(*str) + 1;
272 name = next_arg(ctx, str, true, true);
273 assert_eol(ctx, str);
277 ctx->pctx->name = name;
278 uci_switch_config(ctx);
281 /* Based on an efficient hash function published by D. J. Bernstein */
282 static unsigned int djbhash(unsigned int hash, char *str)
284 int len = strlen(str);
291 for(i = 0; i < len; i++) {
292 hash = ((hash << 5) + hash) + str[i];
294 return (hash & 0x7FFFFFFF);
297 /* fix up an unnamed section */
298 static void uci_fixup_section(struct uci_context *ctx, struct uci_section *s)
300 unsigned int hash = ~0;
301 struct uci_element *e;
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.
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);
321 sprintf(buf, "cfg%02x%04x", ++s->package->n_section, hash % (1 << 16));
322 s->e.name = uci_strdup(ctx, buf);
326 * parse the 'config' uci command (open a section)
328 static void uci_parse_config(struct uci_context *ctx, char **str)
330 struct uci_parse_context *pctx = ctx->pctx;
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");
339 uci_switch_config(ctx);
342 /* command string null-terminated by strtok */
343 *str += strlen(*str) + 1;
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);
352 UCI_TRAP_SAVE(ctx, error);
353 uci_set(ctx, pctx->package, name, NULL, type);
354 UCI_TRAP_RESTORE(ctx);
357 UCI_THROW(ctx, ctx->errno);
359 pctx->section = uci_alloc_section(pctx->package, type, name);
363 * parse the 'option' uci command (open a value)
365 static void uci_parse_option(struct uci_context *ctx, char **str)
367 struct uci_parse_context *pctx = ctx->pctx;
372 uci_parse_error(ctx, *str, "option command found before the first section");
374 /* command string null-terminated by strtok */
375 *str += strlen(*str) + 1;
377 name = next_arg(ctx, str, true, true);
378 value = next_arg(ctx, str, false, false);
379 assert_eol(ctx, str);
382 UCI_TRAP_SAVE(ctx, error);
383 uci_set(ctx, pctx->package, pctx->section->e.name, name, value);
384 UCI_TRAP_RESTORE(ctx);
387 UCI_THROW(ctx, ctx->errno);
389 uci_alloc_option(pctx->section, name, value);
394 * parse a complete input line, split up combined commands by ';'
396 static void uci_parse_line(struct uci_context *ctx, bool single)
398 struct uci_parse_context *pctx = ctx->pctx;
399 char *word, *brk = NULL;
401 for (word = strtok_r(pctx->buf, ";", &brk);
403 word = strtok_r(NULL, ";", &brk)) {
406 word = strtok_r(word, " \t", &pbrk);
415 if ((word[1] == 0) || !strcmp(word + 1, "ackage"))
416 uci_parse_package(ctx, &word, single);
419 if ((word[1] == 0) || !strcmp(word + 1, "onfig"))
420 uci_parse_config(ctx, &word);
423 if ((word[1] == 0) || !strcmp(word + 1, "ption"))
424 uci_parse_option(ctx, &word);
427 uci_parse_error(ctx, word, "unterminated command");
433 /* max number of characters that escaping adds to the string */
434 #define UCI_QUOTE_ESCAPE "'\\''"
437 * escape an uci string for export
439 static char *uci_escape(struct uci_context *ctx, char *str)
445 ctx->bufsz = LINEBUF;
446 ctx->buf = malloc(LINEBUF);
450 p = strchr(str, '\'');
457 if (p + sizeof(UCI_QUOTE_ESCAPE) - str >= ctx->bufsz) {
459 ctx->buf = realloc(ctx->buf, ctx->bufsz);
461 UCI_THROW(ctx, UCI_ERR_MEM);
463 memcpy(&ctx->buf[pos], s, len);
466 strcpy(&ctx->buf[pos], UCI_QUOTE_ESCAPE);
467 pos += sizeof(UCI_QUOTE_ESCAPE);
469 } while ((p = strchr(s, '\'')));
476 * export a single config package to a file stream
478 static void uci_export_package(struct uci_package *p, FILE *stream, bool header)
480 struct uci_context *ctx = p->ctx;
481 struct uci_element *s, *o;
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));
497 fprintf(stream, "\n");
500 int uci_export(struct uci_context *ctx, FILE *stream, struct uci_package *package, bool header)
502 struct uci_element *e;
505 UCI_ASSERT(ctx, stream != NULL);
508 uci_export_package(package, stream, header);
510 uci_foreach_element(&ctx->root, e) {
511 uci_export_package(uci_to_package(e), stream, header);
518 int uci_import(struct uci_context *ctx, FILE *stream, const char *name, struct uci_package **package, bool single)
520 struct uci_parse_context *pctx;
523 /* make sure no memory from previous parse attempts is leaked */
524 uci_file_cleanup(ctx);
526 uci_alloc_parse_context(ctx);
529 if (*package && single) {
530 pctx->package = *package;
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
540 UCI_ASSERT(ctx, uci_validate_name(name));
544 while (!feof(pctx->file)) {
546 UCI_TRAP_SAVE(ctx, error);
548 uci_parse_line(ctx, single);
549 UCI_TRAP_RESTORE(ctx);
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);
559 uci_fixup_section(ctx, ctx->pctx->section);
561 *package = pctx->package;
563 pctx->package = NULL;
566 uci_switch_config(ctx);
568 /* no error happened, we can get rid of the parser context now */
569 uci_file_cleanup(ctx);
575 static char *uci_config_path(struct uci_context *ctx, const char *name)
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);
586 int uci_load(struct uci_context *ctx, const char *name, struct uci_package **package)
596 /* relative path outside of /etc/config */
598 UCI_THROW(ctx, UCI_ERR_NOTFOUND);
601 /* absolute path outside of /etc/config */
602 filename = uci_strdup(ctx, name);
603 name = strrchr(name, '/') + 1;
607 /* config in /etc/config */
608 filename = uci_config_path(ctx, name);
613 file = uci_open_stream(ctx, filename, SEEK_SET, false, false);
615 UCI_TRAP_SAVE(ctx, done);
616 UCI_INTERNAL(uci_import, ctx, file, name, package, true);
617 UCI_TRAP_RESTORE(ctx);
620 (*package)->path = filename;
621 (*package)->confdir = confdir;
622 uci_load_history(ctx, *package, false);
626 uci_close_stream(file);
630 int uci_commit(struct uci_context *ctx, struct uci_package **package, bool overwrite)
632 struct uci_package *p;
638 UCI_ASSERT(ctx, package != NULL);
641 UCI_ASSERT(ctx, p != NULL);
644 p->path = uci_config_path(ctx, p->e.name);
646 UCI_THROW(ctx, UCI_ERR_INVAL);
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);
653 /* flush unsaved changes and reload from history file */
654 UCI_TRAP_SAVE(ctx, done);
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);
664 * other processes might have modified the config
665 * as well. dump and reload
667 uci_free_package(&p);
668 uci_file_cleanup(ctx);
669 UCI_INTERNAL(uci_import, ctx, f, name, &p, true);
675 /* freed together with the uci_package */
678 /* check for updated history, flush */
679 uci_load_history(ctx, p, true);
682 uci_load_history(ctx, NULL, true);
687 ftruncate(fileno(f), 0);
689 uci_export(ctx, f, p, false);
690 UCI_TRAP_RESTORE(ctx);
699 UCI_THROW(ctx, ctx->errno);
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 '/'
711 static inline char *get_filename(char *path)
715 p = strrchr(path, '/');
722 int uci_list_configs(struct uci_context *ctx, char ***list)
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);
737 size = sizeof(char *) * (globbuf.gl_pathc + 1);
738 for(i = 0; i < globbuf.gl_pathc; i++) {
741 p = get_filename(globbuf.gl_pathv[i]);
745 size += strlen(p) + 1;
748 configs = uci_malloc(ctx, size);
749 buf = (char *) &configs[globbuf.gl_pathc + 1];
750 for(i = 0; i < globbuf.gl_pathc; i++) {
753 p = get_filename(globbuf.gl_pathv[i]);
759 buf += strlen(buf) + 1;