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