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