6052c4010a4c74c1e7f1151b209ebf9e77e531f5
[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_file(struct uci_context *ctx, struct uci_package *p, char *filename, FILE **f, bool flush)
748 {
749 FILE *stream = NULL;
750
751 UCI_TRAP_SAVE(ctx, done);
752 stream = uci_open_stream(ctx, filename, SEEK_SET, flush, false);
753 if (p)
754 uci_parse_history(ctx, stream, p);
755 UCI_TRAP_RESTORE(ctx);
756 done:
757 if (f)
758 *f = stream;
759 else if (stream)
760 uci_close_stream(stream);
761 }
762
763 static void uci_load_history(struct uci_context *ctx, struct uci_package *p, bool flush)
764 {
765 struct uci_element *e;
766 char *filename = NULL;
767 FILE *f = NULL;
768
769 if (!p->confdir)
770 return;
771
772 uci_foreach_element(&ctx->history_path, e) {
773 if ((asprintf(&filename, "%s/%s", e->name, p->e.name) < 0) || !filename)
774 UCI_THROW(ctx, UCI_ERR_MEM);
775
776 uci_load_history_file(ctx, p, filename, NULL, false);
777 free(filename);
778 }
779
780 if ((asprintf(&filename, "%s/%s", ctx->savedir, p->e.name) < 0) || !filename)
781 UCI_THROW(ctx, UCI_ERR_MEM);
782
783 uci_load_history_file(ctx, p, filename, &f, flush);
784 if (flush && f) {
785 rewind(f);
786 ftruncate(fileno(f), 0);
787 }
788 if (filename)
789 free(filename);
790 uci_close_stream(f);
791 ctx->errno = 0;
792 }
793
794
795 static char *uci_config_path(struct uci_context *ctx, const char *name)
796 {
797 char *filename;
798
799 UCI_ASSERT(ctx, uci_validate_name(name));
800 filename = uci_malloc(ctx, strlen(name) + strlen(ctx->confdir) + 2);
801 sprintf(filename, "%s/%s", ctx->confdir, name);
802
803 return filename;
804 }
805
806 int uci_load(struct uci_context *ctx, const char *name, struct uci_package **package)
807 {
808 char *filename;
809 bool confdir;
810 FILE *file = NULL;
811
812 UCI_HANDLE_ERR(ctx);
813
814 switch (name[0]) {
815 case '.':
816 /* relative path outside of /etc/config */
817 if (name[1] != '/')
818 UCI_THROW(ctx, UCI_ERR_NOTFOUND);
819 /* fall through */
820 case '/':
821 /* absolute path outside of /etc/config */
822 filename = uci_strdup(ctx, name);
823 name = strrchr(name, '/') + 1;
824 confdir = false;
825 break;
826 default:
827 /* config in /etc/config */
828 filename = uci_config_path(ctx, name);
829 confdir = true;
830 break;
831 }
832
833 file = uci_open_stream(ctx, filename, SEEK_SET, false, false);
834 ctx->errno = 0;
835 UCI_TRAP_SAVE(ctx, done);
836 UCI_INTERNAL(uci_import, ctx, file, name, package, true);
837 UCI_TRAP_RESTORE(ctx);
838
839 if (*package) {
840 (*package)->path = filename;
841 (*package)->confdir = confdir;
842 uci_load_history(ctx, *package, false);
843 }
844
845 done:
846 uci_close_stream(file);
847 return ctx->errno;
848 }
849
850 int uci_save(struct uci_context *ctx, struct uci_package *p)
851 {
852 FILE *f = NULL;
853 char *filename = NULL;
854 struct uci_element *e, *tmp;
855
856 UCI_HANDLE_ERR(ctx);
857 UCI_ASSERT(ctx, p != NULL);
858
859 /*
860 * if the config file was outside of the /etc/config path,
861 * don't save the history to a file, update the real file
862 * directly.
863 * does not modify the uci_package pointer
864 */
865 if (!p->confdir)
866 return uci_commit(ctx, &p, false);
867
868 if (uci_list_empty(&p->history))
869 return 0;
870
871 if ((asprintf(&filename, "%s/%s", ctx->savedir, p->e.name) < 0) || !filename)
872 UCI_THROW(ctx, UCI_ERR_MEM);
873
874 ctx->errno = 0;
875 UCI_TRAP_SAVE(ctx, done);
876 f = uci_open_stream(ctx, filename, SEEK_END, true, true);
877 UCI_TRAP_RESTORE(ctx);
878
879 uci_foreach_element_safe(&p->history, tmp, e) {
880 struct uci_history *h = uci_to_history(e);
881
882 if (h->cmd == UCI_CMD_REMOVE)
883 fprintf(f, "-");
884 else if (h->cmd == UCI_CMD_RENAME)
885 fprintf(f, "@");
886
887 fprintf(f, "%s.%s", p->e.name, h->section);
888 if (e->name)
889 fprintf(f, ".%s", e->name);
890
891 if (h->cmd == UCI_CMD_REMOVE)
892 fprintf(f, "\n");
893 else
894 fprintf(f, "=%s\n", h->value);
895 uci_free_history(h);
896 }
897
898 done:
899 uci_close_stream(f);
900 if (filename)
901 free(filename);
902 if (ctx->errno)
903 UCI_THROW(ctx, ctx->errno);
904
905 return 0;
906 }
907
908 int uci_commit(struct uci_context *ctx, struct uci_package **package, bool overwrite)
909 {
910 struct uci_package *p;
911 FILE *f = NULL;
912 char *name = NULL;
913 char *path = NULL;
914
915 UCI_HANDLE_ERR(ctx);
916 UCI_ASSERT(ctx, package != NULL);
917 p = *package;
918
919 UCI_ASSERT(ctx, p != NULL);
920 if (!p->path) {
921 if (overwrite)
922 p->path = uci_config_path(ctx, p->e.name);
923 else
924 UCI_THROW(ctx, UCI_ERR_INVAL);
925 }
926
927
928 /* open the config file for writing now, so that it is locked */
929 f = uci_open_stream(ctx, p->path, SEEK_SET, true, true);
930
931 /* flush unsaved changes and reload from history file */
932 UCI_TRAP_SAVE(ctx, done);
933 if (p->confdir) {
934 if (!overwrite) {
935 name = uci_strdup(ctx, p->e.name);
936 path = uci_strdup(ctx, p->path);
937 /* dump our own changes to the history file */
938 if (!uci_list_empty(&p->history))
939 UCI_INTERNAL(uci_save, ctx, p);
940
941 /*
942 * other processes might have modified the config
943 * as well. dump and reload
944 */
945 uci_free_package(&p);
946 uci_file_cleanup(ctx);
947 UCI_INTERNAL(uci_import, ctx, f, name, &p, true);
948
949 p->path = path;
950 p->confdir = true;
951 *package = p;
952
953 /* freed together with the uci_package */
954 path = NULL;
955
956 /* check for updated history, just in case */
957 uci_load_history(ctx, p, true);
958 } else {
959 /* flush history */
960 uci_load_history(ctx, NULL, true);
961 }
962 }
963
964 rewind(f);
965 ftruncate(fileno(f), 0);
966
967 uci_export(ctx, f, p, false);
968 UCI_TRAP_RESTORE(ctx);
969
970 done:
971 if (name)
972 free(name);
973 if (path)
974 free(path);
975 uci_close_stream(f);
976 if (ctx->errno)
977 UCI_THROW(ctx, ctx->errno);
978
979 return 0;
980 }
981
982
983 /*
984 * This function returns the filename by returning the string
985 * after the last '/' character. By checking for a non-'\0'
986 * character afterwards, directories are ignored (glob marks
987 * those with a trailing '/'
988 */
989 static inline char *get_filename(char *path)
990 {
991 char *p;
992
993 p = strrchr(path, '/');
994 p++;
995 if (!*p)
996 return NULL;
997 return p;
998 }
999
1000 int uci_list_configs(struct uci_context *ctx, char ***list)
1001 {
1002 char **configs;
1003 glob_t globbuf;
1004 int size, i;
1005 char *buf;
1006 char *dir;
1007
1008 UCI_HANDLE_ERR(ctx);
1009
1010 dir = uci_malloc(ctx, strlen(ctx->confdir) + 1 + sizeof("/*"));
1011 sprintf(dir, "%s/*", ctx->confdir);
1012 if (glob(dir, GLOB_MARK, NULL, &globbuf) != 0)
1013 UCI_THROW(ctx, UCI_ERR_NOTFOUND);
1014
1015 size = sizeof(char *) * (globbuf.gl_pathc + 1);
1016 for(i = 0; i < globbuf.gl_pathc; i++) {
1017 char *p;
1018
1019 p = get_filename(globbuf.gl_pathv[i]);
1020 if (!p)
1021 continue;
1022
1023 size += strlen(p) + 1;
1024 }
1025
1026 configs = uci_malloc(ctx, size);
1027 buf = (char *) &configs[globbuf.gl_pathc + 1];
1028 for(i = 0; i < globbuf.gl_pathc; i++) {
1029 char *p;
1030
1031 p = get_filename(globbuf.gl_pathv[i]);
1032 if (!p)
1033 continue;
1034
1035 configs[i] = buf;
1036 strcpy(buf, p);
1037 buf += strlen(buf) + 1;
1038 }
1039 *list = configs;
1040 free(dir);
1041
1042 return 0;
1043 }
1044