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