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