delta: catch error when parsing delta line.
[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 #define LINEBUF_MAX     4096
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                 if (pctx->bufsz > LINEBUF_MAX/2)
73                         uci_parse_error(ctx, "line too long");
74
75                 pctx->bufsz *= 2;
76                 pctx->buf = uci_realloc(ctx, pctx->buf, pctx->bufsz);
77         } while (1);
78 }
79
80 /*
81  * parse a character escaped by '\'
82  * returns true if the escaped character is to be parsed
83  * returns false if the escaped character is to be ignored
84  */
85 static bool parse_backslash(struct uci_context *ctx)
86 {
87         struct uci_parse_context *pctx = ctx->pctx;
88
89         /* skip backslash */
90         pctx->pos += 1;
91
92         /* undecoded backslash at the end of line, fetch the next line */
93         if (!pctx_cur_char(pctx) ||
94             pctx_cur_char(pctx) == '\n' ||
95             (pctx_cur_char(pctx) == '\r' &&
96              pctx_char(pctx, pctx_pos(pctx) + 1) == '\n' &&
97              !pctx_char(pctx, pctx_pos(pctx) + 2))) {
98                 uci_getln(ctx, pctx->pos);
99                 return false;
100         }
101
102         /* FIXME: decode escaped char, necessary? */
103         return true;
104 }
105
106 /*
107  * move the string pointer forward until a non-whitespace character or
108  * EOL is reached
109  */
110 static void skip_whitespace(struct uci_context *ctx)
111 {
112         struct uci_parse_context *pctx = ctx->pctx;
113
114         while (pctx_cur_char(pctx) && isspace(pctx_cur_char(pctx)))
115                 pctx->pos += 1;
116 }
117
118 static inline void addc(struct uci_context *ctx, int *pos_dest, int *pos_src)
119 {
120         struct uci_parse_context *pctx = ctx->pctx;
121
122         pctx_char(pctx, *pos_dest) = pctx_char(pctx, *pos_src);
123         *pos_dest += 1;
124         *pos_src += 1;
125 }
126
127 /*
128  * parse a double quoted string argument from the command line
129  */
130 static void parse_double_quote(struct uci_context *ctx, int *target)
131 {
132         struct uci_parse_context *pctx = ctx->pctx;
133         char c;
134
135         /* skip quote character */
136         pctx->pos += 1;
137
138         while (1) {
139                 c = pctx_cur_char(pctx);
140                 switch(c) {
141                 case '"':
142                         pctx->pos += 1;
143                         return;
144                 case 0:
145                         /* Multi-line str value */
146                         uci_getln(ctx, pctx->pos);
147                         if (!pctx_cur_char(pctx)) {
148                                 uci_parse_error(ctx, "EOF with unterminated \"");
149                         }
150                         break;
151                 case '\\':
152                         if (!parse_backslash(ctx))
153                                 continue;
154                         /* fall through */
155                 default:
156                         addc(ctx, target, &pctx->pos);
157                         break;
158                 }
159         }
160 }
161
162 /*
163  * parse a single quoted string argument from the command line
164  */
165 static void parse_single_quote(struct uci_context *ctx, int *target)
166 {
167         struct uci_parse_context *pctx = ctx->pctx;
168         char c;
169         /* skip quote character */
170         pctx->pos += 1;
171
172         while (1) {
173                 c = pctx_cur_char(pctx);
174                 switch(c) {
175                 case '\'':
176                         pctx->pos += 1;
177                         return;
178                 case 0:
179                         /* Multi-line str value */
180                         uci_getln(ctx, pctx->pos);
181                         if (!pctx_cur_char(pctx))
182                                 uci_parse_error(ctx, "EOF with unterminated '");
183
184                         break;
185                 default:
186                         addc(ctx, target, &pctx->pos);
187                 }
188         }
189 }
190
191 /*
192  * parse a string from the command line and detect the quoting style
193  */
194 static void parse_str(struct uci_context *ctx, int *target)
195 {
196         struct uci_parse_context *pctx = ctx->pctx;
197         bool next = true;
198         do {
199                 switch(pctx_cur_char(pctx)) {
200                 case '\'':
201                         parse_single_quote(ctx, target);
202                         break;
203                 case '"':
204                         parse_double_quote(ctx, target);
205                         break;
206                 case '#':
207                         pctx_cur_char(pctx) = 0;
208                         /* fall through */
209                 case 0:
210                         goto done;
211                 case ';':
212                         next = false;
213                         goto done;
214                 case '\\':
215                         if (!parse_backslash(ctx))
216                                 continue;
217                         /* fall through */
218                 default:
219                         addc(ctx, target, &pctx->pos);
220                         break;
221                 }
222         } while (pctx_cur_char(pctx) && !isspace(pctx_cur_char(pctx)));
223 done:
224
225         /*
226          * if the string was unquoted and we've stopped at a whitespace
227          * character, skip to the next one, because the whitespace will
228          * be overwritten by a null byte here
229          */
230         if (pctx_cur_char(pctx) && next)
231                 pctx->pos += 1;
232
233         /* terminate the parsed string */
234         pctx_char(pctx, *target) = 0;
235 }
236
237 /*
238  * extract the next argument from the command line
239  */
240 static int next_arg(struct uci_context *ctx, bool required, bool name, bool package)
241 {
242         struct uci_parse_context *pctx = ctx->pctx;
243         int val, ptr;
244
245         skip_whitespace(ctx);
246         val = ptr = pctx_pos(pctx);
247         if (pctx_cur_char(pctx) == ';') {
248                 pctx_cur_char(pctx) = 0;
249                 pctx->pos += 1;
250         } else {
251                 parse_str(ctx, &ptr);
252         }
253         if (!pctx_char(pctx, val)) {
254                 if (required)
255                         uci_parse_error(ctx, "insufficient arguments");
256                 goto done;
257         }
258
259         if (name && !uci_validate_str(pctx_str(pctx, val), name, package))
260                 uci_parse_error(ctx, "invalid character in name field");
261
262 done:
263         return val;
264 }
265
266 int uci_parse_argument(struct uci_context *ctx, FILE *stream, char **str, char **result)
267 {
268         int ofs_result;
269
270         UCI_HANDLE_ERR(ctx);
271         UCI_ASSERT(ctx, str != NULL);
272         UCI_ASSERT(ctx, result != NULL);
273
274         if (ctx->pctx && (ctx->pctx->file != stream))
275                 uci_cleanup(ctx);
276
277         if (!ctx->pctx)
278                 uci_alloc_parse_context(ctx);
279
280         ctx->pctx->file = stream;
281         if (!*str) {
282                 ctx->pctx->pos = 0;
283                 uci_getln(ctx, 0);
284         }
285
286         ofs_result = next_arg(ctx, false, false, false);
287         *result = pctx_str(ctx->pctx, ofs_result);
288         *str = pctx_cur_str(ctx->pctx);
289
290         return 0;
291 }
292
293 static int
294 uci_fill_ptr(struct uci_context *ctx, struct uci_ptr *ptr, struct uci_element *e)
295 {
296         UCI_ASSERT(ctx, ptr != NULL);
297         UCI_ASSERT(ctx, e != NULL);
298
299         memset(ptr, 0, sizeof(struct uci_ptr));
300         switch(e->type) {
301         case UCI_TYPE_OPTION:
302                 ptr->o = uci_to_option(e);
303                 goto fill_option;
304         case UCI_TYPE_SECTION:
305                 ptr->s = uci_to_section(e);
306                 goto fill_section;
307         case UCI_TYPE_PACKAGE:
308                 ptr->p = uci_to_package(e);
309                 goto fill_package;
310         default:
311                 UCI_THROW(ctx, UCI_ERR_INVAL);
312         }
313
314 fill_option:
315         ptr->option = ptr->o->e.name;
316         ptr->s = ptr->o->section;
317 fill_section:
318         ptr->section = ptr->s->e.name;
319         ptr->p = ptr->s->package;
320 fill_package:
321         ptr->package = ptr->p->e.name;
322
323         ptr->flags |= UCI_LOOKUP_DONE;
324
325         return 0;
326 }
327
328
329
330 /*
331  * verify that the end of the line or command is reached.
332  * throw an error if extra arguments are given on the command line
333  */
334 static void assert_eol(struct uci_context *ctx)
335 {
336         char *tmp;
337         int ofs_tmp;
338
339         skip_whitespace(ctx);
340         ofs_tmp = next_arg(ctx, false, false, false);
341         tmp = pctx_str(ctx->pctx, ofs_tmp);
342         if (*tmp && (ctx->flags & UCI_FLAG_STRICT))
343                 uci_parse_error(ctx, "too many arguments");
344 }
345
346 /*
347  * switch to a different config, either triggered by uci_load, or by a
348  * 'package <...>' statement in the import file
349  */
350 static void uci_switch_config(struct uci_context *ctx)
351 {
352         struct uci_parse_context *pctx;
353         struct uci_element *e;
354         const char *name;
355
356         pctx = ctx->pctx;
357         name = pctx->name;
358
359         /* add the last config to main config file list */
360         if (pctx->package) {
361                 pctx->package->backend = ctx->backend;
362                 uci_list_add(&ctx->root, &pctx->package->e.list);
363
364                 pctx->package = NULL;
365                 pctx->section = NULL;
366         }
367
368         if (!name)
369                 return;
370
371         /*
372          * if an older config under the same name exists, unload it
373          * ignore errors here, e.g. if the config was not found
374          */
375         e = uci_lookup_list(&ctx->root, name);
376         if (e)
377                 UCI_THROW(ctx, UCI_ERR_DUPLICATE);
378         pctx->package = uci_alloc_package(ctx, name);
379 }
380
381 /*
382  * parse the 'package' uci command (next config package)
383  */
384 static void uci_parse_package(struct uci_context *ctx, bool single)
385 {
386         struct uci_parse_context *pctx = ctx->pctx;
387         int ofs_name;
388         char *name;
389
390         /* command string null-terminated by strtok */
391         pctx->pos += strlen(pctx_cur_str(pctx)) + 1;
392
393         ofs_name = next_arg(ctx, true, true, true);
394         name = pctx_str(pctx, ofs_name);
395         assert_eol(ctx);
396         if (single)
397                 return;
398
399         ctx->pctx->name = name;
400         uci_switch_config(ctx);
401 }
402
403 /*
404  * parse the 'config' uci command (open a section)
405  */
406 static void uci_parse_config(struct uci_context *ctx)
407 {
408         struct uci_parse_context *pctx = ctx->pctx;
409         struct uci_element *e;
410         struct uci_ptr ptr;
411         int ofs_name, ofs_type;
412         char *name;
413         char *type;
414
415         uci_fixup_section(ctx, ctx->pctx->section);
416         if (!ctx->pctx->package) {
417                 if (!ctx->pctx->name)
418                         uci_parse_error(ctx, "attempting to import a file without a package name");
419
420                 uci_switch_config(ctx);
421         }
422
423         /* command string null-terminated by strtok */
424         pctx->pos += strlen(pctx_cur_str(pctx)) + 1;
425
426         ofs_type = next_arg(ctx, true, false, false);
427         type = pctx_str(pctx, ofs_type);
428         if (!uci_validate_type(type))
429                 uci_parse_error(ctx, "invalid character in type field");
430
431         ofs_name = next_arg(ctx, false, true, false);
432         type = pctx_str(pctx, ofs_type);
433         name = pctx_str(pctx, ofs_name);
434         assert_eol(ctx);
435
436         if (!name || !name[0]) {
437                 ctx->internal = !pctx->merge;
438                 UCI_NESTED(uci_add_section, ctx, pctx->package, type, &pctx->section);
439         } else {
440                 uci_fill_ptr(ctx, &ptr, &pctx->package->e);
441                 e = uci_lookup_list(&pctx->package->sections, name);
442                 if (e)
443                         ptr.s = uci_to_section(e);
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         uci_fixup_section(ctx, ctx->pctx->section);
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 *name = NULL;
725         char *path = NULL;
726         char *filename = NULL;
727         struct stat statbuf;
728         bool do_rename = false;
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         if (!mktemp(filename))
741                 *filename = 0;
742
743         if (!*filename) {
744                 free(filename);
745                 UCI_THROW(ctx, UCI_ERR_IO);
746         }
747
748         if ((stat(filename, &statbuf) == 0) && ((statbuf.st_mode & S_IFMT) != S_IFREG))
749                 UCI_THROW(ctx, UCI_ERR_IO);
750
751         /* open the config file for writing now, so that it is locked */
752         f1 = uci_open_stream(ctx, p->path, NULL, SEEK_SET, true, true);
753
754         /* flush unsaved changes and reload from delta file */
755         UCI_TRAP_SAVE(ctx, done);
756         if (p->has_delta) {
757                 if (!overwrite) {
758                         name = uci_strdup(ctx, p->e.name);
759                         path = uci_strdup(ctx, p->path);
760                         /* dump our own changes to the delta file */
761                         if (!uci_list_empty(&p->delta))
762                                 UCI_INTERNAL(uci_save, ctx, p);
763
764                         /*
765                          * other processes might have modified the config
766                          * as well. dump and reload
767                          */
768                         uci_free_package(&p);
769                         uci_cleanup(ctx);
770                         UCI_INTERNAL(uci_import, ctx, f1, name, &p, true);
771
772                         p->path = path;
773                         p->has_delta = true;
774                         *package = p;
775
776                         /* freed together with the uci_package */
777                         path = NULL;
778                 }
779
780                 /* flush delta */
781                 if (!uci_load_delta(ctx, p, true))
782                         goto done;
783         }
784
785         f2 = uci_open_stream(ctx, filename, p->path, SEEK_SET, true, true);
786         uci_export(ctx, f2, p, false);
787
788         fflush(f2);
789         fsync(fileno(f2));
790         uci_close_stream(f2);
791
792         do_rename = true;
793
794         UCI_TRAP_RESTORE(ctx);
795
796 done:
797         free(name);
798         free(path);
799         uci_close_stream(f1);
800         if (do_rename && rename(filename, p->path)) {
801                 unlink(filename);
802                 UCI_THROW(ctx, UCI_ERR_IO);
803         }
804         free(filename);
805         sync();
806         if (ctx->err)
807                 UCI_THROW(ctx, ctx->err);
808 }
809
810
811 /*
812  * This function returns the filename by returning the string
813  * after the last '/' character. By checking for a non-'\0'
814  * character afterwards, directories are ignored (glob marks
815  * those with a trailing '/'
816  */
817 static inline char *get_filename(char *path)
818 {
819         char *p;
820
821         p = strrchr(path, '/');
822         p++;
823         if (!*p)
824                 return NULL;
825         return p;
826 }
827
828 static char **uci_list_config_files(struct uci_context *ctx)
829 {
830         char **configs;
831         glob_t globbuf;
832         int size, i;
833         char *buf;
834         char *dir;
835
836         dir = uci_malloc(ctx, strlen(ctx->confdir) + 1 + sizeof("/*"));
837         sprintf(dir, "%s/*", ctx->confdir);
838         if (glob(dir, GLOB_MARK, NULL, &globbuf) != 0) {
839                 free(dir);
840                 UCI_THROW(ctx, UCI_ERR_NOTFOUND);
841         }
842
843         size = sizeof(char *) * (globbuf.gl_pathc + 1);
844         for(i = 0; i < globbuf.gl_pathc; i++) {
845                 char *p;
846
847                 p = get_filename(globbuf.gl_pathv[i]);
848                 if (!p)
849                         continue;
850
851                 size += strlen(p) + 1;
852         }
853
854         configs = uci_malloc(ctx, size);
855         buf = (char *) &configs[globbuf.gl_pathc + 1];
856         for(i = 0; i < globbuf.gl_pathc; i++) {
857                 char *p;
858
859                 p = get_filename(globbuf.gl_pathv[i]);
860                 if (!p)
861                         continue;
862
863                 if (!uci_validate_package(p))
864                         continue;
865
866                 configs[i] = buf;
867                 strcpy(buf, p);
868                 buf += strlen(buf) + 1;
869         }
870         free(dir);
871         globfree(&globbuf);
872         return configs;
873 }
874
875 static struct uci_package *uci_file_load(struct uci_context *ctx, const char *name)
876 {
877         struct uci_package *package = NULL;
878         char *filename;
879         bool confdir;
880         FILE *file = NULL;
881
882         switch (name[0]) {
883         case '.':
884                 /* relative path outside of /etc/config */
885                 if (name[1] != '/')
886                         UCI_THROW(ctx, UCI_ERR_NOTFOUND);
887                 /* fall through */
888         case '/':
889                 /* absolute path outside of /etc/config */
890                 filename = uci_strdup(ctx, name);
891                 name = strrchr(name, '/') + 1;
892                 confdir = false;
893                 break;
894         default:
895                 /* config in /etc/config */
896                 filename = uci_config_path(ctx, name);
897                 confdir = true;
898                 break;
899         }
900
901         UCI_TRAP_SAVE(ctx, done);
902         file = uci_open_stream(ctx, filename, NULL, SEEK_SET, false, false);
903         ctx->err = 0;
904         UCI_INTERNAL(uci_import, ctx, file, name, &package, true);
905         UCI_TRAP_RESTORE(ctx);
906
907         if (package) {
908                 package->path = filename;
909                 package->has_delta = confdir;
910                 uci_load_delta(ctx, package, false);
911         }
912
913 done:
914         uci_close_stream(file);
915         if (ctx->err) {
916                 free(filename);
917                 UCI_THROW(ctx, ctx->err);
918         }
919         return package;
920 }
921
922 __private UCI_BACKEND(uci_file_backend, "file",
923         .load = uci_file_load,
924         .commit = uci_file_commit,
925         .list_configs = uci_list_config_files,
926 );