8e6052c70c168eab23be093bde4174c91d1c3076
[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 static int
292 uci_fill_ptr(struct uci_context *ctx, struct uci_ptr *ptr, struct uci_element *e)
293 {
294         UCI_ASSERT(ctx, ptr != NULL);
295         UCI_ASSERT(ctx, e != NULL);
296
297         memset(ptr, 0, sizeof(struct uci_ptr));
298         switch(e->type) {
299         case UCI_TYPE_OPTION:
300                 ptr->o = uci_to_option(e);
301                 goto fill_option;
302         case UCI_TYPE_SECTION:
303                 ptr->s = uci_to_section(e);
304                 goto fill_section;
305         case UCI_TYPE_PACKAGE:
306                 ptr->p = uci_to_package(e);
307                 goto fill_package;
308         default:
309                 UCI_THROW(ctx, UCI_ERR_INVAL);
310         }
311
312 fill_option:
313         ptr->option = ptr->o->e.name;
314         ptr->s = ptr->o->section;
315 fill_section:
316         ptr->section = ptr->s->e.name;
317         ptr->p = ptr->s->package;
318 fill_package:
319         ptr->package = ptr->p->e.name;
320
321         ptr->flags |= UCI_LOOKUP_DONE;
322
323         return 0;
324 }
325
326
327
328 /*
329  * verify that the end of the line or command is reached.
330  * throw an error if extra arguments are given on the command line
331  */
332 static void assert_eol(struct uci_context *ctx)
333 {
334         char *tmp;
335         int ofs_tmp;
336
337         skip_whitespace(ctx);
338         ofs_tmp = next_arg(ctx, false, false, false);
339         tmp = pctx_str(ctx->pctx, ofs_tmp);
340         if (*tmp && (ctx->flags & UCI_FLAG_STRICT))
341                 uci_parse_error(ctx, "too many arguments");
342 }
343
344 /*
345  * switch to a different config, either triggered by uci_load, or by a
346  * 'package <...>' statement in the import file
347  */
348 static void uci_switch_config(struct uci_context *ctx)
349 {
350         struct uci_parse_context *pctx;
351         struct uci_element *e;
352         const char *name;
353
354         pctx = ctx->pctx;
355         name = pctx->name;
356
357         /* add the last config to main config file list */
358         if (pctx->package) {
359                 pctx->package->backend = ctx->backend;
360                 uci_list_add(&ctx->root, &pctx->package->e.list);
361
362                 pctx->package = NULL;
363                 pctx->section = NULL;
364         }
365
366         if (!name)
367                 return;
368
369         /*
370          * if an older config under the same name exists, unload it
371          * ignore errors here, e.g. if the config was not found
372          */
373         e = uci_lookup_list(&ctx->root, name);
374         if (e)
375                 UCI_THROW(ctx, UCI_ERR_DUPLICATE);
376         pctx->package = uci_alloc_package(ctx, name);
377 }
378
379 /*
380  * parse the 'package' uci command (next config package)
381  */
382 static void uci_parse_package(struct uci_context *ctx, bool single)
383 {
384         struct uci_parse_context *pctx = ctx->pctx;
385         int ofs_name;
386         char *name;
387
388         /* command string null-terminated by strtok */
389         pctx->pos += strlen(pctx_cur_str(pctx)) + 1;
390
391         ofs_name = next_arg(ctx, true, true, true);
392         name = pctx_str(pctx, ofs_name);
393         assert_eol(ctx);
394         if (single)
395                 return;
396
397         ctx->pctx->name = name;
398         uci_switch_config(ctx);
399 }
400
401 /*
402  * parse the 'config' uci command (open a section)
403  */
404 static void uci_parse_config(struct uci_context *ctx)
405 {
406         struct uci_parse_context *pctx = ctx->pctx;
407         struct uci_element *e;
408         struct uci_ptr ptr;
409         int ofs_name, ofs_type;
410         char *name;
411         char *type;
412
413         uci_fixup_section(ctx, ctx->pctx->section);
414         if (!ctx->pctx->package) {
415                 if (!ctx->pctx->name)
416                         uci_parse_error(ctx, "attempting to import a file without a package name");
417
418                 uci_switch_config(ctx);
419         }
420
421         /* command string null-terminated by strtok */
422         pctx->pos += strlen(pctx_cur_str(pctx)) + 1;
423
424         ofs_type = next_arg(ctx, true, false, false);
425         type = pctx_str(pctx, ofs_type);
426         if (!uci_validate_type(type))
427                 uci_parse_error(ctx, "invalid character in type field");
428
429         ofs_name = next_arg(ctx, false, true, false);
430         type = pctx_str(pctx, ofs_type);
431         name = pctx_str(pctx, ofs_name);
432         assert_eol(ctx);
433
434         if (!name || !name[0]) {
435                 ctx->internal = !pctx->merge;
436                 UCI_NESTED(uci_add_section, ctx, pctx->package, type, &pctx->section);
437         } else {
438                 uci_fill_ptr(ctx, &ptr, &pctx->package->e);
439                 e = uci_lookup_list(&pctx->package->sections, name);
440                 if (e)
441                         ptr.s = uci_to_section(e);
442                 ptr.section = name;
443                 ptr.value = type;
444
445                 ctx->internal = !pctx->merge;
446                 UCI_NESTED(uci_set, ctx, &ptr);
447                 pctx->section = uci_to_section(ptr.last);
448         }
449 }
450
451 /*
452  * parse the 'option' uci command (open a value)
453  */
454 static void uci_parse_option(struct uci_context *ctx, bool list)
455 {
456         struct uci_parse_context *pctx = ctx->pctx;
457         struct uci_element *e;
458         struct uci_ptr ptr;
459         int ofs_name, ofs_value;
460         char *name = NULL;
461         char *value = NULL;
462
463         if (!pctx->section)
464                 uci_parse_error(ctx, "option/list command found before the first section");
465
466         /* command string null-terminated by strtok */
467         pctx->pos += strlen(pctx_cur_str(pctx)) + 1;
468
469         ofs_name = next_arg(ctx, true, true, false);
470         ofs_value = next_arg(ctx, false, false, false);
471         name = pctx_str(pctx, ofs_name);
472         value = pctx_str(pctx, ofs_value);
473         assert_eol(ctx);
474
475         uci_fill_ptr(ctx, &ptr, &pctx->section->e);
476         e = uci_lookup_list(&pctx->section->options, name);
477         if (e)
478                 ptr.o = uci_to_option(e);
479         ptr.option = name;
480         ptr.value = value;
481
482         ctx->internal = !pctx->merge;
483         if (list)
484                 UCI_NESTED(uci_add_list, ctx, &ptr);
485         else
486                 UCI_NESTED(uci_set, ctx, &ptr);
487 }
488
489 /*
490  * parse a complete input line, split up combined commands by ';'
491  */
492 static void uci_parse_line(struct uci_context *ctx, bool single)
493 {
494         struct uci_parse_context *pctx = ctx->pctx;
495         char *word;
496
497         /* Skip whitespace characters at the start of line */
498         skip_whitespace(ctx);
499         do {
500                 word = strtok(pctx_cur_str(pctx), " \t");
501                 if (!word)
502                         return;
503
504                 switch(word[0]) {
505                         case 0:
506                         case '#':
507                                 return;
508                         case 'p':
509                                 if ((word[1] == 0) || !strcmp(word + 1, "ackage"))
510                                         uci_parse_package(ctx, single);
511                                 else
512                                         goto invalid;
513                                 break;
514                         case 'c':
515                                 if ((word[1] == 0) || !strcmp(word + 1, "onfig"))
516                                         uci_parse_config(ctx);
517                                 else
518                                         goto invalid;
519                                 break;
520                         case 'o':
521                                 if ((word[1] == 0) || !strcmp(word + 1, "ption"))
522                                         uci_parse_option(ctx, false);
523                                 else
524                                         goto invalid;
525                                 break;
526                         case 'l':
527                                 if ((word[1] == 0) || !strcmp(word + 1, "ist"))
528                                         uci_parse_option(ctx, true);
529                                 else
530                                         goto invalid;
531                                 break;
532                         default:
533                                 goto invalid;
534                 }
535                 continue;
536 invalid:
537                 uci_parse_error(ctx, "invalid command");
538         } while (1);
539 }
540
541 /* max number of characters that escaping adds to the string */
542 #define UCI_QUOTE_ESCAPE        "'\\''"
543
544 /*
545  * escape an uci string for export
546  */
547 static const char *uci_escape(struct uci_context *ctx, const char *str)
548 {
549         const char *end;
550         int ofs = 0;
551
552         if (!ctx->buf) {
553                 ctx->bufsz = LINEBUF;
554                 ctx->buf = malloc(LINEBUF);
555
556                 if (!ctx->buf)
557                         return str;
558         }
559
560         while (1) {
561                 int len;
562
563                 end = strchr(str, '\'');
564                 if (!end)
565                         end = str + strlen(str);
566                 len = end - str;
567
568                 /* make sure that we have enough room in the buffer */
569                 while (ofs + len + sizeof(UCI_QUOTE_ESCAPE) + 1 > ctx->bufsz) {
570                         ctx->bufsz *= 2;
571                         ctx->buf = uci_realloc(ctx, ctx->buf, ctx->bufsz);
572                 }
573
574                 /* copy the string until the character before the quote */
575                 memcpy(&ctx->buf[ofs], str, len);
576                 ofs += len;
577
578                 /* end of string? return the buffer */
579                 if (*end == 0)
580                         break;
581
582                 memcpy(&ctx->buf[ofs], UCI_QUOTE_ESCAPE, sizeof(UCI_QUOTE_ESCAPE));
583                 ofs += strlen(&ctx->buf[ofs]);
584                 str = end + 1;
585         }
586
587         ctx->buf[ofs] = 0;
588         return ctx->buf;
589 }
590
591 /*
592  * export a single config package to a file stream
593  */
594 static void uci_export_package(struct uci_package *p, FILE *stream, bool header)
595 {
596         struct uci_context *ctx = p->ctx;
597         struct uci_element *s, *o, *i;
598
599         if (header)
600                 fprintf(stream, "package %s\n", uci_escape(ctx, p->e.name));
601         uci_foreach_element(&p->sections, s) {
602                 struct uci_section *sec = uci_to_section(s);
603                 fprintf(stream, "\nconfig %s", uci_escape(ctx, sec->type));
604                 if (!sec->anonymous || (ctx->flags & UCI_FLAG_EXPORT_NAME))
605                         fprintf(stream, " '%s'", uci_escape(ctx, sec->e.name));
606                 fprintf(stream, "\n");
607                 uci_foreach_element(&sec->options, o) {
608                         struct uci_option *opt = uci_to_option(o);
609                         switch(opt->type) {
610                         case UCI_TYPE_STRING:
611                                 fprintf(stream, "\toption %s", uci_escape(ctx, opt->e.name));
612                                 fprintf(stream, " '%s'\n", uci_escape(ctx, opt->v.string));
613                                 break;
614                         case UCI_TYPE_LIST:
615                                 uci_foreach_element(&opt->v.list, i) {
616                                         fprintf(stream, "\tlist %s", uci_escape(ctx, opt->e.name));
617                                         fprintf(stream, " '%s'\n", uci_escape(ctx, i->name));
618                                 }
619                                 break;
620                         default:
621                                 fprintf(stream, "\t# unknown type for option '%s'\n", uci_escape(ctx, opt->e.name));
622                                 break;
623                         }
624                 }
625         }
626         fprintf(stream, "\n");
627 }
628
629 int uci_export(struct uci_context *ctx, FILE *stream, struct uci_package *package, bool header)
630 {
631         struct uci_element *e;
632
633         UCI_HANDLE_ERR(ctx);
634         UCI_ASSERT(ctx, stream != NULL);
635
636         if (package)
637                 uci_export_package(package, stream, header);
638         else {
639                 uci_foreach_element(&ctx->root, e) {
640                         uci_export_package(uci_to_package(e), stream, header);
641                 }
642         }
643
644         return 0;
645 }
646
647 int uci_import(struct uci_context *ctx, FILE *stream, const char *name, struct uci_package **package, bool single)
648 {
649         struct uci_parse_context *pctx;
650         UCI_HANDLE_ERR(ctx);
651
652         /* make sure no memory from previous parse attempts is leaked */
653         uci_cleanup(ctx);
654
655         uci_alloc_parse_context(ctx);
656         pctx = ctx->pctx;
657         pctx->file = stream;
658         if (package && *package && single) {
659                 pctx->package = *package;
660                 pctx->merge = true;
661         }
662
663         /*
664          * If 'name' was supplied, assume that the supplied stream does not contain
665          * the appropriate 'package <name>' string to specify the config name
666          * NB: the config file can still override the package name
667          */
668         if (name) {
669                 UCI_ASSERT(ctx, uci_validate_package(name));
670                 pctx->name = name;
671         }
672
673         while (!feof(pctx->file)) {
674                 pctx->pos = 0;
675                 uci_getln(ctx, 0);
676                 UCI_TRAP_SAVE(ctx, error);
677                 if (pctx->buf[0])
678                         uci_parse_line(ctx, single);
679                 UCI_TRAP_RESTORE(ctx);
680                 continue;
681 error:
682                 if (ctx->flags & UCI_FLAG_PERROR)
683                         uci_perror(ctx, NULL);
684                 if ((ctx->err != UCI_ERR_PARSE) ||
685                         (ctx->flags & UCI_FLAG_STRICT))
686                         UCI_THROW(ctx, ctx->err);
687         }
688
689         uci_fixup_section(ctx, ctx->pctx->section);
690         if (!pctx->package && name)
691                 uci_switch_config(ctx);
692         if (package)
693                 *package = pctx->package;
694         if (pctx->merge)
695                 pctx->package = NULL;
696
697         pctx->name = NULL;
698         uci_switch_config(ctx);
699
700         /* no error happened, we can get rid of the parser context now */
701         uci_cleanup(ctx);
702
703         return 0;
704 }
705
706
707 static char *uci_config_path(struct uci_context *ctx, const char *name)
708 {
709         char *filename;
710
711         UCI_ASSERT(ctx, uci_validate_package(name));
712         filename = uci_malloc(ctx, strlen(name) + strlen(ctx->confdir) + 2);
713         sprintf(filename, "%s/%s", ctx->confdir, name);
714
715         return filename;
716 }
717
718 static void uci_file_commit(struct uci_context *ctx, struct uci_package **package, bool overwrite)
719 {
720         struct uci_package *p = *package;
721         FILE *f1, *f2 = NULL;
722         char *name = NULL;
723         char *path = NULL;
724         char *filename = NULL;
725         struct stat statbuf;
726         bool do_rename = false;
727
728         if (!p->path) {
729                 if (overwrite)
730                         p->path = uci_config_path(ctx, p->e.name);
731                 else
732                         UCI_THROW(ctx, UCI_ERR_INVAL);
733         }
734
735         if ((asprintf(&filename, "%s/.%s.uci-XXXXXX", ctx->confdir, p->e.name) < 0) || !filename)
736                 UCI_THROW(ctx, UCI_ERR_MEM);
737
738         /* open the config file for writing now, so that it is locked */
739         f1 = uci_open_stream(ctx, p->path, NULL, SEEK_SET, true, true);
740
741         /* flush unsaved changes and reload from delta file */
742         UCI_TRAP_SAVE(ctx, done);
743         if (p->has_delta) {
744                 if (!overwrite) {
745                         name = uci_strdup(ctx, p->e.name);
746                         path = uci_strdup(ctx, p->path);
747                         /* dump our own changes to the delta file */
748                         if (!uci_list_empty(&p->delta))
749                                 UCI_INTERNAL(uci_save, ctx, p);
750
751                         /*
752                          * other processes might have modified the config
753                          * as well. dump and reload
754                          */
755                         uci_free_package(&p);
756                         uci_cleanup(ctx);
757                         UCI_INTERNAL(uci_import, ctx, f1, name, &p, true);
758
759                         p->path = path;
760                         p->has_delta = true;
761                         *package = p;
762
763                         /* freed together with the uci_package */
764                         path = NULL;
765                 }
766
767                 /* flush delta */
768                 if (!uci_load_delta(ctx, p, true))
769                         goto done;
770         }
771
772         if (!mktemp(filename))
773                 *filename = 0;
774
775         if (!*filename) {
776                 free(filename);
777                 UCI_THROW(ctx, UCI_ERR_IO);
778         }
779
780         if ((stat(filename, &statbuf) == 0) && ((statbuf.st_mode & S_IFMT) != S_IFREG))
781                 UCI_THROW(ctx, UCI_ERR_IO);
782
783         f2 = uci_open_stream(ctx, filename, p->path, SEEK_SET, true, true);
784         uci_export(ctx, f2, p, false);
785
786         fflush(f2);
787         fsync(fileno(f2));
788         uci_close_stream(f2);
789
790         do_rename = true;
791
792         UCI_TRAP_RESTORE(ctx);
793
794 done:
795         free(name);
796         free(path);
797         uci_close_stream(f1);
798         if (do_rename && rename(filename, p->path)) {
799                 unlink(filename);
800                 UCI_THROW(ctx, UCI_ERR_IO);
801         }
802         free(filename);
803         if (ctx->err)
804                 UCI_THROW(ctx, ctx->err);
805 }
806
807
808 /*
809  * This function returns the filename by returning the string
810  * after the last '/' character. By checking for a non-'\0'
811  * character afterwards, directories are ignored (glob marks
812  * those with a trailing '/'
813  */
814 static inline char *get_filename(char *path)
815 {
816         char *p;
817
818         p = strrchr(path, '/');
819         p++;
820         if (!*p)
821                 return NULL;
822         return p;
823 }
824
825 static char **uci_list_config_files(struct uci_context *ctx)
826 {
827         char **configs;
828         glob_t globbuf;
829         int size, i;
830         char *buf;
831         char *dir;
832
833         dir = uci_malloc(ctx, strlen(ctx->confdir) + 1 + sizeof("/*"));
834         sprintf(dir, "%s/*", ctx->confdir);
835         if (glob(dir, GLOB_MARK, NULL, &globbuf) != 0) {
836                 free(dir);
837                 UCI_THROW(ctx, UCI_ERR_NOTFOUND);
838         }
839
840         size = sizeof(char *) * (globbuf.gl_pathc + 1);
841         for(i = 0; i < globbuf.gl_pathc; i++) {
842                 char *p;
843
844                 p = get_filename(globbuf.gl_pathv[i]);
845                 if (!p)
846                         continue;
847
848                 size += strlen(p) + 1;
849         }
850
851         configs = uci_malloc(ctx, size);
852         buf = (char *) &configs[globbuf.gl_pathc + 1];
853         for(i = 0; i < globbuf.gl_pathc; i++) {
854                 char *p;
855
856                 p = get_filename(globbuf.gl_pathv[i]);
857                 if (!p)
858                         continue;
859
860                 if (!uci_validate_package(p))
861                         continue;
862
863                 configs[i] = buf;
864                 strcpy(buf, p);
865                 buf += strlen(buf) + 1;
866         }
867         free(dir);
868         globfree(&globbuf);
869         return configs;
870 }
871
872 static struct uci_package *uci_file_load(struct uci_context *ctx, const char *name)
873 {
874         struct uci_package *package = NULL;
875         char *filename;
876         bool confdir;
877         FILE *file = NULL;
878
879         switch (name[0]) {
880         case '.':
881                 /* relative path outside of /etc/config */
882                 if (name[1] != '/')
883                         UCI_THROW(ctx, UCI_ERR_NOTFOUND);
884                 /* fall through */
885         case '/':
886                 /* absolute path outside of /etc/config */
887                 filename = uci_strdup(ctx, name);
888                 name = strrchr(name, '/') + 1;
889                 confdir = false;
890                 break;
891         default:
892                 /* config in /etc/config */
893                 filename = uci_config_path(ctx, name);
894                 confdir = true;
895                 break;
896         }
897
898         UCI_TRAP_SAVE(ctx, done);
899         file = uci_open_stream(ctx, filename, NULL, SEEK_SET, false, false);
900         ctx->err = 0;
901         UCI_INTERNAL(uci_import, ctx, file, name, &package, true);
902         UCI_TRAP_RESTORE(ctx);
903
904         if (package) {
905                 package->path = filename;
906                 package->has_delta = confdir;
907                 uci_load_delta(ctx, package, false);
908         }
909
910 done:
911         uci_close_stream(file);
912         if (ctx->err) {
913                 free(filename);
914                 UCI_THROW(ctx, ctx->err);
915         }
916         return package;
917 }
918
919 __private UCI_BACKEND(uci_file_backend, "file",
920         .load = uci_file_load,
921         .commit = uci_file_commit,
922         .list_configs = uci_list_config_files,
923 );