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
);
249 uci_parse_error(ctx
, *str
, "insufficient arguments");
253 if (name
&& !uci_validate_name(val
))
254 uci_parse_error(ctx
, val
, "invalid character in field");
261 * verify that the end of the line or command is reached.
262 * throw an error if extra arguments are given on the command line
264 static void assert_eol(struct uci_context
*ctx
, char **str
)
268 tmp
= next_arg(ctx
, str
, false, false);
270 uci_parse_error(ctx
, *str
, "too many arguments");
274 * switch to a different config, either triggered by uci_load, or by a
275 * 'package <...>' statement in the import file
277 static void uci_switch_config(struct uci_context
*ctx
)
279 struct uci_parse_context
*pctx
;
280 struct uci_element
*e
;
286 /* add the last config to main config file list */
288 uci_list_add(&ctx
->root
, &pctx
->package
->e
.list
);
290 pctx
->package
= NULL
;
291 pctx
->section
= NULL
;
298 * if an older config under the same name exists, unload it
299 * ignore errors here, e.g. if the config was not found
301 e
= uci_lookup_list(ctx
, &ctx
->root
, name
);
303 UCI_THROW(ctx
, UCI_ERR_DUPLICATE
);
304 pctx
->package
= uci_alloc_package(ctx
, name
);
308 * parse the 'package' uci command (next config package)
310 static void uci_parse_package(struct uci_context
*ctx
, char **str
, bool single
)
314 /* command string null-terminated by strtok */
315 *str
+= strlen(*str
) + 1;
317 name
= next_arg(ctx
, str
, true, true);
318 assert_eol(ctx
, str
);
322 ctx
->pctx
->name
= name
;
323 uci_switch_config(ctx
);
326 /* Based on an efficient hash function published by D. J. Bernstein */
327 static unsigned int djbhash(unsigned int hash
, char *str
)
329 int len
= strlen(str
);
336 for(i
= 0; i
< len
; i
++) {
337 hash
= ((hash
<< 5) + hash
) + str
[i
];
339 return (hash
& 0x7FFFFFFF);
342 /* fix up an unnamed section */
343 static void uci_fixup_section(struct uci_context
*ctx
, struct uci_section
*s
)
345 unsigned int hash
= ~0;
346 struct uci_element
*e
;
353 * Generate a name for unnamed sections. This is used as reference
354 * when locating or updating the section from apps/scripts.
355 * To make multiple concurrent versions somewhat safe for updating,
356 * the name is generated from a hash of its type and name/value
357 * pairs of its option, and it is prefixed by a counter value.
358 * If the order of the unnamed sections changes for some reason,
359 * updates to them will be rejected.
361 hash
= djbhash(hash
, s
->type
);
362 uci_foreach_element(&s
->options
, e
) {
363 hash
= djbhash(hash
, e
->name
);
364 hash
= djbhash(hash
, uci_to_option(e
)->value
);
366 sprintf(buf
, "cfg%02x%04x", ++s
->package
->n_section
, hash
% (1 << 16));
367 s
->e
.name
= uci_strdup(ctx
, buf
);
371 * parse the 'config' uci command (open a section)
373 static void uci_parse_config(struct uci_context
*ctx
, char **str
)
375 struct uci_parse_context
*pctx
= ctx
->pctx
;
376 struct uci_section
*s
;
380 uci_fixup_section(ctx
, ctx
->pctx
->section
);
381 if (!ctx
->pctx
->package
) {
382 if (!ctx
->pctx
->name
)
383 uci_parse_error(ctx
, *str
, "attempting to import a file without a package name");
385 uci_switch_config(ctx
);
388 /* command string null-terminated by strtok */
389 *str
+= strlen(*str
) + 1;
391 type
= next_arg(ctx
, str
, true, true);
392 name
= next_arg(ctx
, str
, false, true);
393 assert_eol(ctx
, str
);
396 UCI_TRAP_SAVE(ctx
, error
);
397 uci_set(ctx
, pctx
->package
, name
, NULL
, type
);
398 UCI_TRAP_RESTORE(ctx
);
401 UCI_THROW(ctx
, ctx
->errno
);
403 pctx
->section
= uci_alloc_section(pctx
->package
, type
, name
);
407 * parse the 'option' uci command (open a value)
409 static void uci_parse_option(struct uci_context
*ctx
, char **str
)
411 struct uci_parse_context
*pctx
= ctx
->pctx
;
416 uci_parse_error(ctx
, *str
, "option command found before the first section");
418 /* command string null-terminated by strtok */
419 *str
+= strlen(*str
) + 1;
421 name
= next_arg(ctx
, str
, true, true);
422 value
= next_arg(ctx
, str
, true, false);
423 assert_eol(ctx
, str
);
426 UCI_TRAP_SAVE(ctx
, error
);
427 uci_set(ctx
, pctx
->package
, pctx
->section
->e
.name
, name
, value
);
428 UCI_TRAP_RESTORE(ctx
);
431 UCI_THROW(ctx
, ctx
->errno
);
433 uci_alloc_option(pctx
->section
, name
, value
);
438 * parse a complete input line, split up combined commands by ';'
440 static void uci_parse_line(struct uci_context
*ctx
, bool single
)
442 struct uci_parse_context
*pctx
= ctx
->pctx
;
443 char *word
, *brk
= NULL
;
445 for (word
= strtok_r(pctx
->buf
, ";", &brk
);
447 word
= strtok_r(NULL
, ";", &brk
)) {
450 word
= strtok_r(word
, " \t", &pbrk
);
454 if ((word
[1] == 0) || !strcmp(word
+ 1, "ackage"))
455 uci_parse_package(ctx
, &word
, single
);
458 if ((word
[1] == 0) || !strcmp(word
+ 1, "onfig"))
459 uci_parse_config(ctx
, &word
);
462 if ((word
[1] == 0) || !strcmp(word
+ 1, "ption"))
463 uci_parse_option(ctx
, &word
);
466 uci_parse_error(ctx
, word
, "unterminated command");
472 /* max number of characters that escaping adds to the string */
473 #define UCI_QUOTE_ESCAPE "'\\''"
476 * escape an uci string for export
478 static char *uci_escape(struct uci_context
*ctx
, char *str
)
484 ctx
->bufsz
= LINEBUF
;
485 ctx
->buf
= malloc(LINEBUF
);
489 p
= strchr(str
, '\'');
496 if (p
+ sizeof(UCI_QUOTE_ESCAPE
) - str
>= ctx
->bufsz
) {
498 ctx
->buf
= realloc(ctx
->buf
, ctx
->bufsz
);
500 UCI_THROW(ctx
, UCI_ERR_MEM
);
502 memcpy(&ctx
->buf
[pos
], s
, len
);
505 strcpy(&ctx
->buf
[pos
], UCI_QUOTE_ESCAPE
);
506 pos
+= sizeof(UCI_QUOTE_ESCAPE
);
508 } while ((p
= strchr(s
, '\'')));
515 * export a single config package to a file stream
517 static void uci_export_package(struct uci_package
*p
, FILE *stream
, bool header
)
519 struct uci_context
*ctx
= p
->ctx
;
520 struct uci_element
*s
, *o
;
523 fprintf(stream
, "package '%s'\n", uci_escape(ctx
, p
->e
.name
));
524 uci_foreach_element(&p
->sections
, s
) {
525 struct uci_section
*sec
= uci_to_section(s
);
526 fprintf(stream
, "\nconfig '%s'", uci_escape(ctx
, sec
->type
));
528 fprintf(stream
, " '%s'", uci_escape(ctx
, sec
->e
.name
));
529 fprintf(stream
, "\n");
530 uci_foreach_element(&sec
->options
, o
) {
531 struct uci_option
*opt
= uci_to_option(o
);
532 fprintf(stream
, "\toption '%s'", uci_escape(ctx
, opt
->e
.name
));
533 fprintf(stream
, " '%s'\n", uci_escape(ctx
, opt
->value
));
536 fprintf(stream
, "\n");
539 int uci_export(struct uci_context
*ctx
, FILE *stream
, struct uci_package
*package
, bool header
)
541 struct uci_element
*e
;
544 UCI_ASSERT(ctx
, stream
!= NULL
);
547 uci_export_package(package
, stream
, header
);
549 uci_foreach_element(&ctx
->root
, e
) {
550 uci_export_package(uci_to_package(e
), stream
, header
);
557 int uci_import(struct uci_context
*ctx
, FILE *stream
, const char *name
, struct uci_package
**package
, bool single
)
559 struct uci_parse_context
*pctx
;
562 /* make sure no memory from previous parse attempts is leaked */
563 uci_file_cleanup(ctx
);
565 pctx
= (struct uci_parse_context
*) uci_malloc(ctx
, sizeof(struct uci_parse_context
));
568 if (*package
&& single
) {
569 pctx
->package
= *package
;
574 * If 'name' was supplied, assume that the supplied stream does not contain
575 * the appropriate 'package <name>' string to specify the config name
576 * NB: the config file can still override the package name
581 while (!feof(pctx
->file
)) {
583 UCI_TRAP_SAVE(ctx
, error
);
585 uci_parse_line(ctx
, single
);
586 UCI_TRAP_RESTORE(ctx
);
589 if (ctx
->flags
& UCI_FLAG_PERROR
)
590 uci_perror(ctx
, NULL
);
591 if ((ctx
->errno
!= UCI_ERR_PARSE
) ||
592 (ctx
->flags
& UCI_FLAG_STRICT
))
593 UCI_THROW(ctx
, ctx
->errno
);
596 uci_fixup_section(ctx
, ctx
->pctx
->section
);
598 *package
= pctx
->package
;
600 pctx
->package
= NULL
;
603 uci_switch_config(ctx
);
605 /* no error happened, we can get rid of the parser context now */
606 uci_file_cleanup(ctx
);
612 * open a stream and go to the right position
614 * note: when opening for write and seeking to the beginning of
615 * the stream, truncate the file
617 static FILE *uci_open_stream(struct uci_context
*ctx
, const char *filename
, int pos
, bool write
, bool create
)
622 int mode
= (write
? O_RDWR
: O_RDONLY
);
627 if (!write
&& ((stat(filename
, &statbuf
) < 0) ||
628 ((statbuf
.st_mode
& S_IFMT
) != S_IFREG
))) {
629 UCI_THROW(ctx
, UCI_ERR_NOTFOUND
);
632 fd
= open(filename
, mode
, UCI_FILEMODE
);
636 if (flock(fd
, (write
? LOCK_EX
: LOCK_SH
)) < 0)
639 ret
= lseek(fd
, 0, pos
);
644 file
= fdopen(fd
, (write
? "w+" : "r"));
649 UCI_THROW(ctx
, UCI_ERR_IO
);
654 static void uci_close_stream(FILE *stream
)
666 static void uci_parse_history_line(struct uci_context
*ctx
, struct uci_package
*p
, char *buf
)
670 char *package
= NULL
;
671 char *section
= NULL
;
678 } else if (buf
[0] == '@') {
683 UCI_INTERNAL(uci_parse_tuple
, ctx
, buf
, &package
, §ion
, &option
, &value
);
684 if (!package
|| !section
|| (!delete && !value
))
686 if (strcmp(package
, p
->e
.name
) != 0)
688 if (!uci_validate_name(section
))
690 if (option
&& !uci_validate_name(option
))
694 UCI_INTERNAL(uci_rename
, ctx
, p
, section
, option
, value
);
696 UCI_INTERNAL(uci_delete
, ctx
, p
, section
, option
);
698 UCI_INTERNAL(uci_set
, ctx
, p
, section
, option
, value
);
702 UCI_THROW(ctx
, UCI_ERR_PARSE
);
705 static void uci_parse_history(struct uci_context
*ctx
, FILE *stream
, struct uci_package
*p
)
707 struct uci_parse_context
*pctx
;
709 /* make sure no memory from previous parse attempts is leaked */
710 uci_file_cleanup(ctx
);
712 pctx
= (struct uci_parse_context
*) uci_malloc(ctx
, sizeof(struct uci_parse_context
));
716 while (!feof(pctx
->file
)) {
722 * ignore parse errors in single lines, we want to preserve as much
723 * history as possible
725 UCI_TRAP_SAVE(ctx
, error
);
726 uci_parse_history_line(ctx
, p
, pctx
->buf
);
727 UCI_TRAP_RESTORE(ctx
);
732 /* no error happened, we can get rid of the parser context now */
733 uci_file_cleanup(ctx
);
736 static void uci_load_history(struct uci_context
*ctx
, struct uci_package
*p
, bool flush
)
738 char *filename
= NULL
;
743 if ((asprintf(&filename
, "%s/%s", UCI_SAVEDIR
, p
->e
.name
) < 0) || !filename
)
744 UCI_THROW(ctx
, UCI_ERR_MEM
);
746 UCI_TRAP_SAVE(ctx
, done
);
747 f
= uci_open_stream(ctx
, filename
, SEEK_SET
, flush
, false);
749 uci_parse_history(ctx
, f
, p
);
750 UCI_TRAP_RESTORE(ctx
);
755 ftruncate(fileno(f
), 0);
764 static char *uci_config_path(struct uci_context
*ctx
, const char *name
)
768 if (strchr(name
, '/'))
769 UCI_THROW(ctx
, UCI_ERR_INVAL
);
770 filename
= uci_malloc(ctx
, strlen(name
) + sizeof(UCI_CONFDIR
) + 2);
771 sprintf(filename
, UCI_CONFDIR
"/%s", name
);
776 int uci_load(struct uci_context
*ctx
, const char *name
, struct uci_package
**package
)
783 UCI_ASSERT(ctx
, uci_validate_name(name
));
787 /* relative path outside of /etc/config */
789 UCI_THROW(ctx
, UCI_ERR_NOTFOUND
);
792 /* absolute path outside of /etc/config */
793 filename
= uci_strdup(ctx
, name
);
794 name
= strrchr(name
, '/') + 1;
798 /* config in /etc/config */
799 filename
= uci_config_path(ctx
, name
);
804 file
= uci_open_stream(ctx
, filename
, SEEK_SET
, false, false);
806 UCI_TRAP_SAVE(ctx
, done
);
807 UCI_INTERNAL(uci_import
, ctx
, file
, name
, package
, true);
808 UCI_TRAP_RESTORE(ctx
);
811 (*package
)->path
= filename
;
812 (*package
)->confdir
= confdir
;
813 uci_load_history(ctx
, *package
, false);
817 uci_close_stream(file
);
821 int uci_save(struct uci_context
*ctx
, struct uci_package
*p
)
824 char *filename
= NULL
;
825 struct uci_element
*e
, *tmp
;
828 UCI_ASSERT(ctx
, p
!= NULL
);
831 * if the config file was outside of the /etc/config path,
832 * don't save the history to a file, update the real file
834 * does not modify the uci_package pointer
837 return uci_commit(ctx
, &p
, false);
839 if (uci_list_empty(&p
->history
))
842 if ((asprintf(&filename
, "%s/%s", UCI_SAVEDIR
, p
->e
.name
) < 0) || !filename
)
843 UCI_THROW(ctx
, UCI_ERR_MEM
);
846 UCI_TRAP_SAVE(ctx
, done
);
847 f
= uci_open_stream(ctx
, filename
, SEEK_END
, true, true);
848 UCI_TRAP_RESTORE(ctx
);
850 uci_foreach_element_safe(&p
->history
, tmp
, e
) {
851 struct uci_history
*h
= uci_to_history(e
);
853 if (h
->cmd
== UCI_CMD_REMOVE
)
855 else if (h
->cmd
== UCI_CMD_RENAME
)
858 fprintf(f
, "%s.%s", p
->e
.name
, h
->section
);
860 fprintf(f
, ".%s", e
->name
);
862 if (h
->cmd
== UCI_CMD_REMOVE
)
865 fprintf(f
, "=%s\n", h
->value
);
874 UCI_THROW(ctx
, ctx
->errno
);
879 int uci_commit(struct uci_context
*ctx
, struct uci_package
**package
, bool overwrite
)
881 struct uci_package
*p
;
887 UCI_ASSERT(ctx
, package
!= NULL
);
890 UCI_ASSERT(ctx
, p
!= NULL
);
893 p
->path
= uci_config_path(ctx
, p
->e
.name
);
895 UCI_THROW(ctx
, UCI_ERR_INVAL
);
899 /* open the config file for writing now, so that it is locked */
900 f
= uci_open_stream(ctx
, p
->path
, SEEK_SET
, true, true);
902 /* flush unsaved changes and reload from history file */
903 UCI_TRAP_SAVE(ctx
, done
);
906 name
= uci_strdup(ctx
, p
->e
.name
);
907 path
= uci_strdup(ctx
, p
->path
);
908 if (!uci_list_empty(&p
->history
))
909 UCI_INTERNAL(uci_save
, ctx
, p
);
910 uci_free_package(&p
);
911 uci_file_cleanup(ctx
);
912 UCI_INTERNAL(uci_import
, ctx
, f
, name
, &p
, true);
918 /* freed together with the uci_package */
921 /* check for updated history, just in case */
922 uci_load_history(ctx
, p
, true);
925 uci_load_history(ctx
, NULL
, true);
930 ftruncate(fileno(f
), 0);
932 uci_export(ctx
, f
, p
, false);
933 UCI_TRAP_RESTORE(ctx
);
942 UCI_THROW(ctx
, ctx
->errno
);
949 * This function returns the filename by returning the string
950 * after the last '/' character. By checking for a non-'\0'
951 * character afterwards, directories are ignored (glob marks
952 * those with a trailing '/'
954 static inline char *get_filename(char *path
)
958 p
= strrchr(path
, '/');
965 int uci_list_configs(struct uci_context
*ctx
, char ***list
)
974 if (glob(UCI_CONFDIR
"/*", GLOB_MARK
, NULL
, &globbuf
) != 0)
975 UCI_THROW(ctx
, UCI_ERR_NOTFOUND
);
977 size
= sizeof(char *) * (globbuf
.gl_pathc
+ 1);
978 for(i
= 0; i
< globbuf
.gl_pathc
; i
++) {
981 p
= get_filename(globbuf
.gl_pathv
[i
]);
985 size
+= strlen(p
) + 1;
988 configs
= uci_malloc(ctx
, size
);
989 buf
= (char *) &configs
[globbuf
.gl_pathc
+ 1];
990 for(i
= 0; i
< globbuf
.gl_pathc
; i
++) {
993 p
= get_filename(globbuf
.gl_pathv
[i
]);
999 buf
+= strlen(buf
) + 1;