Add bitfield_set function from libubox.
[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         uci_fixup_section(ctx, ctx->pctx->section);
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 + 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         uci_fixup_section(ctx, ctx->pctx->section);
693         if (!pctx->package && name)
694                 uci_switch_config(ctx);
695         if (package)
696                 *package = pctx->package;
697         if (pctx->merge)
698                 pctx->package = NULL;
699
700         pctx->name = NULL;
701         uci_switch_config(ctx);
702
703         /* no error happened, we can get rid of the parser context now */
704         uci_cleanup(ctx);
705
706         return 0;
707 }
708
709
710 static char *uci_config_path(struct uci_context *ctx, const char *name)
711 {
712         char *filename;
713
714         UCI_ASSERT(ctx, uci_validate_package(name));
715         filename = uci_malloc(ctx, strlen(name) + strlen(ctx->confdir) + 2);
716         sprintf(filename, "%s/%s", ctx->confdir, name);
717
718         return filename;
719 }
720
721 static void uci_file_commit(struct uci_context *ctx, struct uci_package **package, bool overwrite)
722 {
723         struct uci_package *p = *package;
724         FILE *f1, *f2 = NULL;
725         char *name = NULL;
726         char *path = NULL;
727         char *filename = NULL;
728         struct stat statbuf;
729         bool do_rename = false;
730
731         if (!p->path) {
732                 if (overwrite)
733                         p->path = uci_config_path(ctx, p->e.name);
734                 else
735                         UCI_THROW(ctx, UCI_ERR_INVAL);
736         }
737
738         if ((asprintf(&filename, "%s/.%s.uci-XXXXXX", ctx->confdir, p->e.name) < 0) || !filename)
739                 UCI_THROW(ctx, UCI_ERR_MEM);
740
741         /* open the config file for writing now, so that it is locked */
742         f1 = uci_open_stream(ctx, p->path, NULL, SEEK_SET, true, true);
743
744         /* flush unsaved changes and reload from delta file */
745         UCI_TRAP_SAVE(ctx, done);
746         if (p->has_delta) {
747                 if (!overwrite) {
748                         name = uci_strdup(ctx, p->e.name);
749                         path = uci_strdup(ctx, p->path);
750                         /* dump our own changes to the delta file */
751                         if (!uci_list_empty(&p->delta))
752                                 UCI_INTERNAL(uci_save, ctx, p);
753
754                         /*
755                          * other processes might have modified the config
756                          * as well. dump and reload
757                          */
758                         uci_free_package(&p);
759                         uci_cleanup(ctx);
760                         UCI_INTERNAL(uci_import, ctx, f1, name, &p, true);
761
762                         p->path = path;
763                         p->has_delta = true;
764                         *package = p;
765
766                         /* freed together with the uci_package */
767                         path = NULL;
768                 }
769
770                 /* flush delta */
771                 if (!uci_load_delta(ctx, p, true))
772                         goto done;
773         }
774
775         if (!mktemp(filename))
776                 *filename = 0;
777
778         if (!*filename) {
779                 free(filename);
780                 UCI_THROW(ctx, UCI_ERR_IO);
781         }
782
783         if ((stat(filename, &statbuf) == 0) && ((statbuf.st_mode & S_IFMT) != S_IFREG))
784                 UCI_THROW(ctx, UCI_ERR_IO);
785
786         f2 = uci_open_stream(ctx, filename, p->path, SEEK_SET, true, true);
787         uci_export(ctx, f2, p, false);
788
789         fflush(f2);
790         fsync(fileno(f2));
791         uci_close_stream(f2);
792
793         do_rename = true;
794
795         UCI_TRAP_RESTORE(ctx);
796
797 done:
798         free(name);
799         free(path);
800         uci_close_stream(f1);
801         if (do_rename) {
802                 path = realpath(p->path, NULL);
803                 if (!path || rename(filename, path)) {
804                         unlink(filename);
805                         UCI_THROW(ctx, UCI_ERR_IO);
806                 }
807                 free(path);
808         }
809         free(filename);
810         if (ctx->err)
811                 UCI_THROW(ctx, ctx->err);
812 }
813
814
815 /*
816  * This function returns the filename by returning the string
817  * after the last '/' character. By checking for a non-'\0'
818  * character afterwards, directories are ignored (glob marks
819  * those with a trailing '/'
820  */
821 static inline char *get_filename(char *path)
822 {
823         char *p;
824
825         p = strrchr(path, '/');
826         p++;
827         if (!*p)
828                 return NULL;
829         return p;
830 }
831
832 static char **uci_list_config_files(struct uci_context *ctx)
833 {
834         char **configs;
835         glob_t globbuf;
836         int size, i, j, skipped;
837         char *buf;
838         char *dir;
839
840         dir = uci_malloc(ctx, strlen(ctx->confdir) + 1 + sizeof("/*"));
841         sprintf(dir, "%s/*", ctx->confdir);
842         if (glob(dir, GLOB_MARK, NULL, &globbuf) != 0) {
843                 free(dir);
844                 UCI_THROW(ctx, UCI_ERR_NOTFOUND);
845         }
846
847         size = sizeof(char *) * (globbuf.gl_pathc + 1);
848         skipped = 0;
849         for(i = 0; i < globbuf.gl_pathc; i++) {
850                 char *p;
851
852                 p = get_filename(globbuf.gl_pathv[i]);
853                 if (!p) {
854                         skipped++;
855                         continue;
856                 }
857
858                 size += strlen(p) + 1;
859         }
860
861         configs = uci_malloc(ctx, size - skipped);
862         buf = (char *) &configs[globbuf.gl_pathc + 1 - skipped];
863         j = 0;
864         for(i = 0; i < globbuf.gl_pathc; i++) {
865                 char *p;
866
867                 p = get_filename(globbuf.gl_pathv[i]);
868                 if (!p)
869                         continue;
870
871                 if (!uci_validate_package(p))
872                         continue;
873
874                 configs[j++] = buf;
875                 strcpy(buf, p);
876                 buf += strlen(buf) + 1;
877         }
878         free(dir);
879         globfree(&globbuf);
880         return configs;
881 }
882
883 static struct uci_package *uci_file_load(struct uci_context *ctx, const char *name)
884 {
885         struct uci_package *package = NULL;
886         char *filename;
887         bool confdir;
888         FILE *file = NULL;
889
890         switch (name[0]) {
891         case '.':
892                 /* relative path outside of /etc/config */
893                 if (name[1] != '/')
894                         UCI_THROW(ctx, UCI_ERR_NOTFOUND);
895                 /* fall through */
896         case '/':
897                 /* absolute path outside of /etc/config */
898                 filename = uci_strdup(ctx, name);
899                 name = strrchr(name, '/') + 1;
900                 confdir = false;
901                 break;
902         default:
903                 /* config in /etc/config */
904                 filename = uci_config_path(ctx, name);
905                 confdir = true;
906                 break;
907         }
908
909         UCI_TRAP_SAVE(ctx, done);
910         file = uci_open_stream(ctx, filename, NULL, SEEK_SET, false, false);
911         ctx->err = 0;
912         UCI_INTERNAL(uci_import, ctx, file, name, &package, true);
913         UCI_TRAP_RESTORE(ctx);
914
915         if (package) {
916                 package->path = filename;
917                 package->has_delta = confdir;
918                 uci_load_delta(ctx, package, false);
919         }
920
921 done:
922         uci_close_stream(file);
923         if (ctx->err) {
924                 free(filename);
925                 UCI_THROW(ctx, ctx->err);
926         }
927         return package;
928 }
929
930 __private UCI_BACKEND(uci_file_backend, "file",
931         .load = uci_file_load,
932         .commit = uci_file_commit,
933         .list_configs = uci_list_config_files,
934 );