parse comments properly
[project/uci.git] / file.c
1 /*
2  * libuci - Library for the Unified Configuration Interface
3  * Copyright (C) 2008 Felix Fietkau <nbd@openwrt.org>
4  *
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
8  *
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.
13  */
14
15 /*
16  * This file contains the code for parsing uci config files
17  */
18
19 #define _GNU_SOURCE
20 #include <sys/types.h>
21 #include <sys/stat.h>
22 #include <sys/file.h>
23 #include <stdbool.h>
24 #include <unistd.h>
25 #include <fcntl.h>
26 #include <stdio.h>
27 #include <ctype.h>
28
29 #define LINEBUF 32
30 #define LINEBUF_MAX     4096
31
32 static void uci_parse_error(struct uci_context *ctx, char *pos, char *reason)
33 {
34         struct uci_parse_context *pctx = ctx->pctx;
35
36         pctx->reason = reason;
37         pctx->byte = pos - pctx->buf;
38         UCI_THROW(ctx, UCI_ERR_PARSE);
39 }
40
41 /*
42  * Fetch a new line from the input stream and resize buffer if necessary
43  */
44 static void uci_getln(struct uci_context *ctx, int offset)
45 {
46         struct uci_parse_context *pctx = ctx->pctx;
47         char *p;
48         int ofs;
49
50         if (pctx->buf == NULL) {
51                 pctx->buf = uci_malloc(ctx, LINEBUF);
52                 pctx->bufsz = LINEBUF;
53         }
54
55         ofs = offset;
56         do {
57                 p = &pctx->buf[ofs];
58                 p[ofs] = 0;
59
60                 p = fgets(p, pctx->bufsz - ofs, pctx->file);
61                 if (!p || !*p)
62                         return;
63
64                 ofs += strlen(p);
65                 if (pctx->buf[ofs - 1] == '\n') {
66                         pctx->line++;
67                         pctx->buf[ofs - 1] = 0;
68                         return;
69                 }
70
71                 if (pctx->bufsz > LINEBUF_MAX/2)
72                         uci_parse_error(ctx, p, "line too long");
73
74                 pctx->bufsz *= 2;
75                 pctx->buf = uci_realloc(ctx, pctx->buf, pctx->bufsz);
76         } while (1);
77 }
78
79 /*
80  * Clean up all extra memory used by the parser and exporter
81  */
82 static void uci_file_cleanup(struct uci_context *ctx)
83 {
84         struct uci_parse_context *pctx;
85
86         if (ctx->buf) {
87                 free(ctx->buf);
88                 ctx->buf = NULL;
89                 ctx->bufsz = 0;
90         }
91
92         pctx = ctx->pctx;
93         if (!pctx)
94                 return;
95
96         ctx->pctx = NULL;
97         if (pctx->package)
98                 uci_free_package(&pctx->package);
99
100         if (pctx->buf)
101                 free(pctx->buf);
102
103         free(pctx);
104 }
105
106 /* 
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
110  */
111 static inline bool parse_backslash(struct uci_context *ctx, char **str)
112 {
113         /* skip backslash */
114         *str += 1;
115
116         /* undecoded backslash at the end of line, fetch the next line */
117         if (!**str) {
118                 *str += 1;
119                 uci_getln(ctx, *str - ctx->pctx->buf);
120                 return false;
121         }
122
123         /* FIXME: decode escaped char, necessary? */
124         return true;
125 }
126
127 /*
128  * move the string pointer forward until a non-whitespace character or
129  * EOL is reached
130  */
131 static void skip_whitespace(struct uci_context *ctx, char **str)
132 {
133 restart:
134         while (**str && isspace(**str))
135                 *str += 1;
136
137         if (**str == '\\') {
138                 if (!parse_backslash(ctx, str))
139                         goto restart;
140         }
141 }
142
143 static inline void addc(char **dest, char **src)
144 {
145         **dest = **src;
146         *dest += 1;
147         *src += 1;
148 }
149
150 /*
151  * parse a double quoted string argument from the command line
152  */
153 static void parse_double_quote(struct uci_context *ctx, char **str, char **target)
154 {
155         char c;
156
157         /* skip quote character */
158         *str += 1;
159
160         while ((c = **str)) {
161                 switch(c) {
162                 case '"':
163                         **target = 0;
164                         *str += 1;
165                         return;
166                 case '\\':
167                         if (!parse_backslash(ctx, str))
168                                 continue;
169                         /* fall through */
170                 default:
171                         addc(target, str);
172                         break;
173                 }
174         }
175         uci_parse_error(ctx, *str, "unterminated \"");
176 }
177
178 /*
179  * parse a single quoted string argument from the command line
180  */
181 static void parse_single_quote(struct uci_context *ctx, char **str, char **target)
182 {
183         char c;
184         /* skip quote character */
185         *str += 1;
186
187         while ((c = **str)) {
188                 switch(c) {
189                 case '\'':
190                         **target = 0;
191                         *str += 1;
192                         return;
193                 default:
194                         addc(target, str);
195                 }
196         }
197         uci_parse_error(ctx, *str, "unterminated '");
198 }
199
200 /*
201  * parse a string from the command line and detect the quoting style
202  */
203 static void parse_str(struct uci_context *ctx, char **str, char **target)
204 {
205         do {
206                 switch(**str) {
207                 case '\'':
208                         parse_single_quote(ctx, str, target);
209                         break;
210                 case '"':
211                         parse_double_quote(ctx, str, target);
212                         break;
213                 case '#':
214                         **str = 0;
215                         /* fall through */
216                 case 0:
217                         goto done;
218                 case '\\':
219                         if (!parse_backslash(ctx, str))
220                                 continue;
221                         /* fall through */
222                 default:
223                         addc(target, str);
224                         break;
225                 }
226         } while (**str && !isspace(**str));
227 done:
228
229         /* 
230          * if the string was unquoted and we've stopped at a whitespace
231          * character, skip to the next one, because the whitespace will
232          * be overwritten by a null byte here
233          */
234         if (**str)
235                 *str += 1;
236
237         /* terminate the parsed string */
238         **target = 0;
239 }
240
241 /*
242  * extract the next argument from the command line
243  */
244 static char *next_arg(struct uci_context *ctx, char **str, bool required, bool name)
245 {
246         char *val;
247         char *ptr;
248
249         val = ptr = *str;
250         skip_whitespace(ctx, str);
251         parse_str(ctx, str, &ptr);
252         if (!*val) {
253                 if (required)
254                         uci_parse_error(ctx, *str, "insufficient arguments");
255                 goto done;
256         }
257
258         if (name && !uci_validate_name(val))
259                 uci_parse_error(ctx, val, "invalid character in field");
260
261 done:
262         return val;
263 }
264
265 /*
266  * verify that the end of the line or command is reached.
267  * throw an error if extra arguments are given on the command line
268  */
269 static void assert_eol(struct uci_context *ctx, char **str)
270 {
271         char *tmp;
272
273         tmp = next_arg(ctx, str, false, false);
274         if (tmp && *tmp && (ctx->flags & UCI_FLAG_STRICT))
275                 uci_parse_error(ctx, *str, "too many arguments");
276 }
277
278 /* 
279  * switch to a different config, either triggered by uci_load, or by a
280  * 'package <...>' statement in the import file
281  */
282 static void uci_switch_config(struct uci_context *ctx)
283 {
284         struct uci_parse_context *pctx;
285         struct uci_element *e;
286         const char *name;
287
288         pctx = ctx->pctx;
289         name = pctx->name;
290
291         /* add the last config to main config file list */
292         if (pctx->package) {
293                 uci_list_add(&ctx->root, &pctx->package->e.list);
294
295                 pctx->package = NULL;
296                 pctx->section = NULL;
297         }
298
299         if (!name)
300                 return;
301
302         /* 
303          * if an older config under the same name exists, unload it
304          * ignore errors here, e.g. if the config was not found
305          */
306         e = uci_lookup_list(ctx, &ctx->root, name);
307         if (e)
308                 UCI_THROW(ctx, UCI_ERR_DUPLICATE);
309         pctx->package = uci_alloc_package(ctx, name);
310 }
311
312 /*
313  * parse the 'package' uci command (next config package)
314  */
315 static void uci_parse_package(struct uci_context *ctx, char **str, bool single)
316 {
317         char *name = NULL;
318
319         /* command string null-terminated by strtok */
320         *str += strlen(*str) + 1;
321
322         name = next_arg(ctx, str, true, true);
323         assert_eol(ctx, str);
324         if (single)
325                 return;
326
327         ctx->pctx->name = name;
328         uci_switch_config(ctx);
329 }
330
331 /* Based on an efficient hash function published by D. J. Bernstein */
332 static unsigned int djbhash(unsigned int hash, char *str)
333 {
334         int len = strlen(str);
335         int i;
336
337         /* initial value */
338         if (hash == ~0)
339                 hash = 5381;
340
341         for(i = 0; i < len; i++) {
342                 hash = ((hash << 5) + hash) + str[i];
343         }
344         return (hash & 0x7FFFFFFF);
345 }
346
347 /* fix up an unnamed section */
348 static void uci_fixup_section(struct uci_context *ctx, struct uci_section *s)
349 {
350         unsigned int hash = ~0;
351         struct uci_element *e;
352         char buf[16];
353
354         if (!s || s->e.name)
355                 return;
356
357         /*
358          * Generate a name for unnamed sections. This is used as reference
359          * when locating or updating the section from apps/scripts.
360          * To make multiple concurrent versions somewhat safe for updating,
361          * the name is generated from a hash of its type and name/value
362          * pairs of its option, and it is prefixed by a counter value.
363          * If the order of the unnamed sections changes for some reason,
364          * updates to them will be rejected.
365          */
366         hash = djbhash(hash, s->type);
367         uci_foreach_element(&s->options, e) {
368                 hash = djbhash(hash, e->name);
369                 hash = djbhash(hash, uci_to_option(e)->value);
370         }
371         sprintf(buf, "cfg%02x%04x", ++s->package->n_section, hash % (1 << 16));
372         s->e.name = uci_strdup(ctx, buf);
373 }
374
375 /*
376  * parse the 'config' uci command (open a section)
377  */
378 static void uci_parse_config(struct uci_context *ctx, char **str)
379 {
380         struct uci_parse_context *pctx = ctx->pctx;
381         char *name = NULL;
382         char *type = NULL;
383
384         uci_fixup_section(ctx, ctx->pctx->section);
385         if (!ctx->pctx->package) {
386                 if (!ctx->pctx->name)
387                         uci_parse_error(ctx, *str, "attempting to import a file without a package name");
388
389                 uci_switch_config(ctx);
390         }
391
392         /* command string null-terminated by strtok */
393         *str += strlen(*str) + 1;
394
395         type = next_arg(ctx, str, true, true);
396         name = next_arg(ctx, str, false, true);
397         assert_eol(ctx, str);
398
399         if (pctx->merge) {
400                 UCI_TRAP_SAVE(ctx, error);
401                 uci_set(ctx, pctx->package, name, NULL, type);
402                 UCI_TRAP_RESTORE(ctx);
403                 return;
404 error:
405                 UCI_THROW(ctx, ctx->errno);
406         } else
407                 pctx->section = uci_alloc_section(pctx->package, type, name);
408 }
409
410 /*
411  * parse the 'option' uci command (open a value)
412  */
413 static void uci_parse_option(struct uci_context *ctx, char **str)
414 {
415         struct uci_parse_context *pctx = ctx->pctx;
416         char *name = NULL;
417         char *value = NULL;
418
419         if (!pctx->section)
420                 uci_parse_error(ctx, *str, "option command found before the first section");
421
422         /* command string null-terminated by strtok */
423         *str += strlen(*str) + 1;
424
425         name = next_arg(ctx, str, true, true);
426         value = next_arg(ctx, str, true, false);
427         assert_eol(ctx, str);
428
429         if (pctx->merge) {
430                 UCI_TRAP_SAVE(ctx, error);
431                 uci_set(ctx, pctx->package, pctx->section->e.name, name, value);
432                 UCI_TRAP_RESTORE(ctx);
433                 return;
434 error:
435                 UCI_THROW(ctx, ctx->errno);
436         } else
437                 uci_alloc_option(pctx->section, name, value);
438 }
439
440
441 /*
442  * parse a complete input line, split up combined commands by ';'
443  */
444 static void uci_parse_line(struct uci_context *ctx, bool single)
445 {
446         struct uci_parse_context *pctx = ctx->pctx;
447         char *word, *brk = NULL;
448
449         for (word = strtok_r(pctx->buf, ";", &brk);
450                  word;
451                  word = strtok_r(NULL, ";", &brk)) {
452
453                 char *pbrk = NULL;
454                 word = strtok_r(word, " \t", &pbrk);
455
456                 switch(word[0]) {
457                         case '#':
458                                 return;
459                         case 'p':
460                                 if ((word[1] == 0) || !strcmp(word + 1, "ackage"))
461                                         uci_parse_package(ctx, &word, single);
462                                 break;
463                         case 'c':
464                                 if ((word[1] == 0) || !strcmp(word + 1, "onfig"))
465                                         uci_parse_config(ctx, &word);
466                                 break;
467                         case 'o':
468                                 if ((word[1] == 0) || !strcmp(word + 1, "ption"))
469                                         uci_parse_option(ctx, &word);
470                                 break;
471                         default:
472                                 uci_parse_error(ctx, word, "unterminated command");
473                                 break;
474                 }
475         }
476 }
477
478 /* max number of characters that escaping adds to the string */
479 #define UCI_QUOTE_ESCAPE        "'\\''"
480
481 /*
482  * escape an uci string for export
483  */
484 static char *uci_escape(struct uci_context *ctx, char *str)
485 {
486         char *s, *p;
487         int pos = 0;
488
489         if (!ctx->buf) {
490                 ctx->bufsz = LINEBUF;
491                 ctx->buf = malloc(LINEBUF);
492         }
493
494         s = str;
495         p = strchr(str, '\'');
496         if (!p)
497                 return str;
498
499         do {
500                 int len = p - s;
501                 if (len > 0) {
502                         if (p + sizeof(UCI_QUOTE_ESCAPE) - str >= ctx->bufsz) {
503                                 ctx->bufsz *= 2;
504                                 ctx->buf = realloc(ctx->buf, ctx->bufsz);
505                                 if (!ctx->buf)
506                                         UCI_THROW(ctx, UCI_ERR_MEM);
507                         }
508                         memcpy(&ctx->buf[pos], s, len);
509                         pos += len;
510                 }
511                 strcpy(&ctx->buf[pos], UCI_QUOTE_ESCAPE);
512                 pos += sizeof(UCI_QUOTE_ESCAPE);
513                 s = p + 1;
514         } while ((p = strchr(s, '\'')));
515
516         return ctx->buf;
517 }
518
519
520 /*
521  * export a single config package to a file stream
522  */
523 static void uci_export_package(struct uci_package *p, FILE *stream, bool header)
524 {
525         struct uci_context *ctx = p->ctx;
526         struct uci_element *s, *o;
527
528         if (header)
529                 fprintf(stream, "package '%s'\n", uci_escape(ctx, p->e.name));
530         uci_foreach_element(&p->sections, s) {
531                 struct uci_section *sec = uci_to_section(s);
532                 fprintf(stream, "\nconfig '%s'", uci_escape(ctx, sec->type));
533                 if (!sec->anonymous || (ctx->flags & UCI_FLAG_EXPORT_NAME))
534                         fprintf(stream, " '%s'", uci_escape(ctx, sec->e.name));
535                 fprintf(stream, "\n");
536                 uci_foreach_element(&sec->options, o) {
537                         struct uci_option *opt = uci_to_option(o);
538                         fprintf(stream, "\toption '%s'", uci_escape(ctx, opt->e.name));
539                         fprintf(stream, " '%s'\n", uci_escape(ctx, opt->value));
540                 }
541         }
542         fprintf(stream, "\n");
543 }
544
545 int uci_export(struct uci_context *ctx, FILE *stream, struct uci_package *package, bool header)
546 {
547         struct uci_element *e;
548
549         UCI_HANDLE_ERR(ctx);
550         UCI_ASSERT(ctx, stream != NULL);
551
552         if (package)
553                 uci_export_package(package, stream, header);
554         else {
555                 uci_foreach_element(&ctx->root, e) {
556                         uci_export_package(uci_to_package(e), stream, header);
557                 }
558         }
559
560         return 0;
561 }
562
563 int uci_import(struct uci_context *ctx, FILE *stream, const char *name, struct uci_package **package, bool single)
564 {
565         struct uci_parse_context *pctx;
566         UCI_HANDLE_ERR(ctx);
567
568         /* make sure no memory from previous parse attempts is leaked */
569         uci_file_cleanup(ctx);
570
571         pctx = (struct uci_parse_context *) uci_malloc(ctx, sizeof(struct uci_parse_context));
572         ctx->pctx = pctx;
573         pctx->file = stream;
574         if (*package && single) {
575                 pctx->package = *package;
576                 pctx->merge = true;
577         }
578
579         /*
580          * If 'name' was supplied, assume that the supplied stream does not contain
581          * the appropriate 'package <name>' string to specify the config name
582          * NB: the config file can still override the package name
583          */
584         if (name) {
585                 UCI_ASSERT(ctx, uci_validate_name(name));
586                 pctx->name = name;
587         }
588
589         while (!feof(pctx->file)) {
590                 uci_getln(ctx, 0);
591                 UCI_TRAP_SAVE(ctx, error);
592                 if (pctx->buf[0])
593                         uci_parse_line(ctx, single);
594                 UCI_TRAP_RESTORE(ctx);
595                 continue;
596 error:
597                 if (ctx->flags & UCI_FLAG_PERROR)
598                         uci_perror(ctx, NULL);
599                 if ((ctx->errno != UCI_ERR_PARSE) ||
600                         (ctx->flags & UCI_FLAG_STRICT))
601                         UCI_THROW(ctx, ctx->errno);
602         }
603
604         uci_fixup_section(ctx, ctx->pctx->section);
605         if (package)
606                 *package = pctx->package;
607         if (pctx->merge)
608                 pctx->package = NULL;
609
610         pctx->name = NULL;
611         uci_switch_config(ctx);
612
613         /* no error happened, we can get rid of the parser context now */
614         uci_file_cleanup(ctx);
615
616         return 0;
617 }
618
619 /*
620  * open a stream and go to the right position
621  *
622  * note: when opening for write and seeking to the beginning of
623  * the stream, truncate the file
624  */
625 static FILE *uci_open_stream(struct uci_context *ctx, const char *filename, int pos, bool write, bool create)
626 {
627         struct stat statbuf;
628         FILE *file = NULL;
629         int fd, ret;
630         int mode = (write ? O_RDWR : O_RDONLY);
631
632         if (create)
633                 mode |= O_CREAT;
634
635         if (!write && ((stat(filename, &statbuf) < 0) ||
636                 ((statbuf.st_mode &  S_IFMT) != S_IFREG))) {
637                 UCI_THROW(ctx, UCI_ERR_NOTFOUND);
638         }
639
640         fd = open(filename, mode, UCI_FILEMODE);
641         if (fd <= 0)
642                 goto error;
643
644         if (flock(fd, (write ? LOCK_EX : LOCK_SH)) < 0)
645                 goto error;
646
647         ret = lseek(fd, 0, pos);
648
649         if (ret < 0)
650                 goto error;
651
652         file = fdopen(fd, (write ? "w+" : "r"));
653         if (file)
654                 goto done;
655
656 error:
657         UCI_THROW(ctx, UCI_ERR_IO);
658 done:
659         return file;
660 }
661
662 static void uci_close_stream(FILE *stream)
663 {
664         int fd;
665
666         if (!stream)
667                 return;
668
669         fd = fileno(stream);
670         flock(fd, LOCK_UN);
671         fclose(stream);
672 }
673
674 static void uci_parse_history_line(struct uci_context *ctx, struct uci_package *p, char *buf)
675 {
676         bool delete = false;
677         bool rename = false;
678         char *package = NULL;
679         char *section = NULL;
680         char *option = NULL;
681         char *value = NULL;
682
683         if (buf[0] == '-') {
684                 delete = true;
685                 buf++;
686         } else if (buf[0] == '@') {
687                 rename = true;
688                 buf++;
689         }
690
691         UCI_INTERNAL(uci_parse_tuple, ctx, buf, &package, &section, &option, &value);
692         if (!package || (strcmp(package, p->e.name) != 0))
693                 goto error;
694         if (!uci_validate_name(section))
695                 goto error;
696         if (option && !uci_validate_name(option))
697                 goto error;
698         if ((rename || !delete) && !uci_validate_name(value))
699                 goto error;
700
701         if (rename)
702                 UCI_INTERNAL(uci_rename, ctx, p, section, option, value);
703         else if (delete)
704                 UCI_INTERNAL(uci_delete, ctx, p, section, option);
705         else
706                 UCI_INTERNAL(uci_set, ctx, p, section, option, value);
707
708         return;
709 error:
710         UCI_THROW(ctx, UCI_ERR_PARSE);
711 }
712
713 static void uci_parse_history(struct uci_context *ctx, FILE *stream, struct uci_package *p)
714 {
715         struct uci_parse_context *pctx;
716
717         /* make sure no memory from previous parse attempts is leaked */
718         uci_file_cleanup(ctx);
719
720         pctx = (struct uci_parse_context *) uci_malloc(ctx, sizeof(struct uci_parse_context));
721         ctx->pctx = pctx;
722         pctx->file = stream;
723
724         while (!feof(pctx->file)) {
725                 uci_getln(ctx, 0);
726                 if (!pctx->buf[0])
727                         continue;
728
729                 /*
730                  * ignore parse errors in single lines, we want to preserve as much
731                  * history as possible
732                  */
733                 UCI_TRAP_SAVE(ctx, error);
734                 uci_parse_history_line(ctx, p, pctx->buf);
735                 UCI_TRAP_RESTORE(ctx);
736 error:
737                 continue;
738         }
739
740         /* no error happened, we can get rid of the parser context now */
741         uci_file_cleanup(ctx);
742 }
743
744 static void uci_load_history(struct uci_context *ctx, struct uci_package *p, bool flush)
745 {
746         char *filename = NULL;
747         FILE *f = NULL;
748
749         if (!p->confdir)
750                 return;
751
752         if ((asprintf(&filename, "%s/%s", UCI_SAVEDIR, p->e.name) < 0) || !filename)
753                 UCI_THROW(ctx, UCI_ERR_MEM);
754
755         UCI_TRAP_SAVE(ctx, done);
756         f = uci_open_stream(ctx, filename, SEEK_SET, flush, false);
757         if (p)
758                 uci_parse_history(ctx, f, p);
759         UCI_TRAP_RESTORE(ctx);
760
761 done:
762         if (flush && f) {
763                 rewind(f);
764                 ftruncate(fileno(f), 0);
765         }
766         if (filename)
767                 free(filename);
768         uci_close_stream(f);
769         ctx->errno = 0;
770 }
771
772
773 static char *uci_config_path(struct uci_context *ctx, const char *name)
774 {
775         char *filename;
776
777         UCI_ASSERT(ctx, uci_validate_name(name));
778         filename = uci_malloc(ctx, strlen(name) + sizeof(UCI_CONFDIR) + 2);
779         sprintf(filename, UCI_CONFDIR "/%s", name);
780
781         return filename;
782 }
783
784 int uci_load(struct uci_context *ctx, const char *name, struct uci_package **package)
785 {
786         char *filename;
787         bool confdir;
788         FILE *file = NULL;
789
790         UCI_HANDLE_ERR(ctx);
791
792         switch (name[0]) {
793         case '.':
794                 /* relative path outside of /etc/config */
795                 if (name[1] != '/')
796                         UCI_THROW(ctx, UCI_ERR_NOTFOUND);
797                 /* fall through */
798         case '/':
799                 /* absolute path outside of /etc/config */
800                 filename = uci_strdup(ctx, name);
801                 name = strrchr(name, '/') + 1;
802                 confdir = false;
803                 break;
804         default:
805                 /* config in /etc/config */
806                 filename = uci_config_path(ctx, name);
807                 confdir = true;
808                 break;
809         }
810
811         file = uci_open_stream(ctx, filename, SEEK_SET, false, false);
812         ctx->errno = 0;
813         UCI_TRAP_SAVE(ctx, done);
814         UCI_INTERNAL(uci_import, ctx, file, name, package, true);
815         UCI_TRAP_RESTORE(ctx);
816
817         if (*package) {
818                 (*package)->path = filename;
819                 (*package)->confdir = confdir;
820                 uci_load_history(ctx, *package, false);
821         }
822
823 done:
824         uci_close_stream(file);
825         return ctx->errno;
826 }
827
828 int uci_save(struct uci_context *ctx, struct uci_package *p)
829 {
830         FILE *f = NULL;
831         char *filename = NULL;
832         struct uci_element *e, *tmp;
833
834         UCI_HANDLE_ERR(ctx);
835         UCI_ASSERT(ctx, p != NULL);
836
837         /* 
838          * if the config file was outside of the /etc/config path,
839          * don't save the history to a file, update the real file
840          * directly.
841          * does not modify the uci_package pointer
842          */
843         if (!p->confdir)
844                 return uci_commit(ctx, &p, false);
845
846         if (uci_list_empty(&p->history))
847                 return 0;
848
849         if ((asprintf(&filename, "%s/%s", UCI_SAVEDIR, p->e.name) < 0) || !filename)
850                 UCI_THROW(ctx, UCI_ERR_MEM);
851
852         ctx->errno = 0;
853         UCI_TRAP_SAVE(ctx, done);
854         f = uci_open_stream(ctx, filename, SEEK_END, true, true);
855         UCI_TRAP_RESTORE(ctx);
856
857         uci_foreach_element_safe(&p->history, tmp, e) {
858                 struct uci_history *h = uci_to_history(e);
859
860                 if (h->cmd == UCI_CMD_REMOVE)
861                         fprintf(f, "-");
862                 else if (h->cmd == UCI_CMD_RENAME)
863                         fprintf(f, "@");
864
865                 fprintf(f, "%s.%s", p->e.name, h->section);
866                 if (e->name)
867                         fprintf(f, ".%s", e->name);
868
869                 if (h->cmd == UCI_CMD_REMOVE)
870                         fprintf(f, "\n");
871                 else
872                         fprintf(f, "=%s\n", h->value);
873                 uci_free_history(h);
874         }
875
876 done:
877         uci_close_stream(f);
878         if (filename)
879                 free(filename);
880         if (ctx->errno)
881                 UCI_THROW(ctx, ctx->errno);
882
883         return 0;
884 }
885
886 int uci_commit(struct uci_context *ctx, struct uci_package **package, bool overwrite)
887 {
888         struct uci_package *p;
889         FILE *f = NULL;
890         char *name = NULL;
891         char *path = NULL;
892
893         UCI_HANDLE_ERR(ctx);
894         UCI_ASSERT(ctx, package != NULL);
895         p = *package;
896
897         UCI_ASSERT(ctx, p != NULL);
898         if (!p->path) {
899                 if (overwrite)
900                         p->path = uci_config_path(ctx, p->e.name);
901                 else
902                         UCI_THROW(ctx, UCI_ERR_INVAL);
903         }
904
905
906         /* open the config file for writing now, so that it is locked */
907         f = uci_open_stream(ctx, p->path, SEEK_SET, true, true);
908
909         /* flush unsaved changes and reload from history file */
910         UCI_TRAP_SAVE(ctx, done);
911         if (p->confdir) {
912                 if (!overwrite) {
913                         name = uci_strdup(ctx, p->e.name);
914                         path = uci_strdup(ctx, p->path);
915                         /* dump our own changes to the history file */
916                         if (!uci_list_empty(&p->history))
917                                 UCI_INTERNAL(uci_save, ctx, p);
918
919                         /* 
920                          * other processes might have modified the config 
921                          * as well. dump and reload 
922                          */
923                         uci_free_package(&p);
924                         uci_file_cleanup(ctx);
925                         UCI_INTERNAL(uci_import, ctx, f, name, &p, true);
926
927                         p->path = path;
928                         p->confdir = true;
929                         *package = p;
930
931                         /* freed together with the uci_package */
932                         path = NULL;
933
934                         /* check for updated history, just in case */
935                         uci_load_history(ctx, p, true);
936                 } else {
937                         /* flush history */
938                         uci_load_history(ctx, NULL, true);
939                 }
940         }
941
942         rewind(f);
943         ftruncate(fileno(f), 0);
944
945         uci_export(ctx, f, p, false);
946         UCI_TRAP_RESTORE(ctx);
947
948 done:
949         if (name)
950                 free(name);
951         if (path)
952                 free(path);
953         uci_close_stream(f);
954         if (ctx->errno)
955                 UCI_THROW(ctx, ctx->errno);
956
957         return 0;
958 }
959
960
961 /* 
962  * This function returns the filename by returning the string
963  * after the last '/' character. By checking for a non-'\0'
964  * character afterwards, directories are ignored (glob marks
965  * those with a trailing '/'
966  */
967 static inline char *get_filename(char *path)
968 {
969         char *p;
970
971         p = strrchr(path, '/');
972         p++;
973         if (!*p)
974                 return NULL;
975         return p;
976 }
977
978 int uci_list_configs(struct uci_context *ctx, char ***list)
979 {
980         char **configs;
981         glob_t globbuf;
982         int size, i;
983         char *buf;
984
985         UCI_HANDLE_ERR(ctx);
986
987         if (glob(UCI_CONFDIR "/*", GLOB_MARK, NULL, &globbuf) != 0)
988                 UCI_THROW(ctx, UCI_ERR_NOTFOUND);
989
990         size = sizeof(char *) * (globbuf.gl_pathc + 1);
991         for(i = 0; i < globbuf.gl_pathc; i++) {
992                 char *p;
993
994                 p = get_filename(globbuf.gl_pathv[i]);
995                 if (!p)
996                         continue;
997
998                 size += strlen(p) + 1;
999         }
1000
1001         configs = uci_malloc(ctx, size);
1002         buf = (char *) &configs[globbuf.gl_pathc + 1];
1003         for(i = 0; i < globbuf.gl_pathc; i++) {
1004                 char *p;
1005
1006                 p = get_filename(globbuf.gl_pathv[i]);
1007                 if (!p)
1008                         continue;
1009
1010                 configs[i] = buf;
1011                 strcpy(buf, p);
1012                 buf += strlen(buf) + 1;
1013         }
1014         *list = configs;
1015
1016         return 0;
1017 }
1018