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