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