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