set -O0 for debug builds
[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 #include <sys/types.h>
20 #include <sys/stat.h>
21 #include <stdbool.h>
22 #include <unistd.h>
23 #include <fcntl.h>
24 #include <stdio.h>
25 #include <ctype.h>
26
27 #define LINEBUF 32
28 #define LINEBUF_MAX 4096
29
30 static void uci_parse_error(struct uci_context *ctx, char *pos, char *reason)
31 {
32 struct uci_parse_context *pctx = ctx->pctx;
33
34 pctx->reason = reason;
35 pctx->byte = pos - pctx->buf;
36 UCI_THROW(ctx, UCI_ERR_PARSE);
37 }
38
39 /*
40 * Fetch a new line from the input stream and resize buffer if necessary
41 */
42 static void uci_getln(struct uci_context *ctx, int offset)
43 {
44 struct uci_parse_context *pctx = ctx->pctx;
45 char *p;
46 int ofs;
47
48 if (pctx->buf == NULL) {
49 pctx->buf = uci_malloc(ctx, LINEBUF);
50 pctx->bufsz = LINEBUF;
51 }
52
53 ofs = offset;
54 do {
55 p = &pctx->buf[ofs];
56 p[ofs] = 0;
57
58 p = fgets(p, pctx->bufsz - ofs, pctx->file);
59 if (!p || !*p)
60 return;
61
62 ofs += strlen(p);
63 if (pctx->buf[ofs - 1] == '\n') {
64 pctx->line++;
65 pctx->buf[ofs - 1] = 0;
66 return;
67 }
68
69 if (pctx->bufsz > LINEBUF_MAX/2)
70 uci_parse_error(ctx, p, "line too long");
71
72 pctx->bufsz *= 2;
73 pctx->buf = uci_realloc(ctx, pctx->buf, pctx->bufsz);
74 } while (1);
75 }
76
77 /*
78 * Clean up all extra memory used by the parser and exporter
79 */
80 static void uci_file_cleanup(struct uci_context *ctx)
81 {
82 struct uci_parse_context *pctx;
83
84 if (ctx->buf) {
85 free(ctx->buf);
86 ctx->buf = NULL;
87 ctx->bufsz = 0;
88 }
89
90 pctx = ctx->pctx;
91 if (!pctx)
92 return;
93
94 ctx->pctx = NULL;
95 if (pctx->package)
96 uci_free_package(pctx->package);
97
98 if (pctx->buf)
99 free(pctx->buf);
100 if (pctx->file)
101 fclose(pctx->file);
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 (required && !*val)
250 uci_parse_error(ctx, *str, "insufficient arguments");
251 if (name && !uci_validate_name(val))
252 uci_parse_error(ctx, val, "invalid character in field");
253
254 return val;
255 }
256
257 /*
258 * verify that the end of the line or command is reached.
259 * throw an error if extra arguments are given on the command line
260 */
261 static void assert_eol(struct uci_context *ctx, char **str)
262 {
263 char *tmp;
264
265 tmp = next_arg(ctx, str, false, false);
266 if (tmp && *tmp)
267 uci_parse_error(ctx, *str, "too many arguments");
268 }
269
270 /*
271 * switch to a different config, either triggered by uci_load, or by a
272 * 'package <...>' statement in the import file
273 */
274 static void uci_switch_config(struct uci_context *ctx)
275 {
276 struct uci_parse_context *pctx;
277 struct uci_element *e;
278 const char *name;
279
280 pctx = ctx->pctx;
281 name = pctx->name;
282
283 /* add the last config to main config file list */
284 if (pctx->package) {
285 uci_list_add(&ctx->root, &pctx->package->e.list);
286
287 pctx->package = NULL;
288 pctx->section = NULL;
289 }
290
291 if (!name)
292 return;
293
294 /*
295 * if an older config under the same name exists, unload it
296 * ignore errors here, e.g. if the config was not found
297 */
298 e = uci_lookup_list(ctx, &ctx->root, name);
299 if (e)
300 UCI_THROW(ctx, UCI_ERR_DUPLICATE);
301 pctx->package = uci_alloc_package(ctx, name);
302 }
303
304 /*
305 * parse the 'package' uci command (next config package)
306 */
307 static void uci_parse_package(struct uci_context *ctx, char **str, bool single)
308 {
309 char *name = NULL;
310
311 /* command string null-terminated by strtok */
312 *str += strlen(*str) + 1;
313
314 name = next_arg(ctx, str, true, true);
315 assert_eol(ctx, str);
316 if (single)
317 return;
318
319 ctx->pctx->name = name;
320 uci_switch_config(ctx);
321 }
322
323 /*
324 * parse the 'config' uci command (open a section)
325 */
326 static void uci_parse_config(struct uci_context *ctx, char **str)
327 {
328 char *name = NULL;
329 char *type = NULL;
330
331 if (!ctx->pctx->package) {
332 if (!ctx->pctx->name)
333 uci_parse_error(ctx, *str, "attempting to import a file without a package name");
334
335 uci_switch_config(ctx);
336 }
337
338 /* command string null-terminated by strtok */
339 *str += strlen(*str) + 1;
340
341 type = next_arg(ctx, str, true, true);
342 name = next_arg(ctx, str, false, true);
343 assert_eol(ctx, str);
344 ctx->pctx->section = uci_alloc_section(ctx->pctx->package, type, name);
345 }
346
347 /*
348 * parse the 'option' uci command (open a value)
349 */
350 static void uci_parse_option(struct uci_context *ctx, char **str)
351 {
352 char *name = NULL;
353 char *value = NULL;
354
355 if (!ctx->pctx->section)
356 uci_parse_error(ctx, *str, "option command found before the first section");
357
358 /* command string null-terminated by strtok */
359 *str += strlen(*str) + 1;
360
361 name = next_arg(ctx, str, true, true);
362 value = next_arg(ctx, str, true, false);
363 assert_eol(ctx, str);
364 uci_alloc_option(ctx->pctx->section, name, value);
365 }
366
367
368 /*
369 * parse a complete input line, split up combined commands by ';'
370 */
371 static void uci_parse_line(struct uci_context *ctx, bool single)
372 {
373 struct uci_parse_context *pctx = ctx->pctx;
374 char *word, *brk = NULL;
375
376 for (word = strtok_r(pctx->buf, ";", &brk);
377 word;
378 word = strtok_r(NULL, ";", &brk)) {
379
380 char *pbrk = NULL;
381 word = strtok_r(word, " \t", &pbrk);
382
383 switch(word[0]) {
384 case 'p':
385 if ((word[1] == 0) || !strcmp(word + 1, "ackage"))
386 uci_parse_package(ctx, &word, single);
387 break;
388 case 'c':
389 if ((word[1] == 0) || !strcmp(word + 1, "onfig"))
390 uci_parse_config(ctx, &word);
391 break;
392 case 'o':
393 if ((word[1] == 0) || !strcmp(word + 1, "ption"))
394 uci_parse_option(ctx, &word);
395 break;
396 default:
397 uci_parse_error(ctx, word, "unterminated command");
398 break;
399 }
400 }
401 }
402
403 /* max number of characters that escaping adds to the string */
404 #define UCI_QUOTE_ESCAPE "'\\''"
405
406 /*
407 * escape an uci string for export
408 */
409 static char *uci_escape(struct uci_context *ctx, char *str)
410 {
411 char *s, *p;
412 int pos = 0;
413
414 if (!ctx->buf) {
415 ctx->bufsz = LINEBUF;
416 ctx->buf = malloc(LINEBUF);
417 }
418
419 s = str;
420 p = strchr(str, '\'');
421 if (!p)
422 return str;
423
424 do {
425 int len = p - s;
426 if (len > 0) {
427 if (p + sizeof(UCI_QUOTE_ESCAPE) - str >= ctx->bufsz) {
428 ctx->bufsz *= 2;
429 ctx->buf = realloc(ctx->buf, ctx->bufsz);
430 if (!ctx->buf)
431 UCI_THROW(ctx, UCI_ERR_MEM);
432 }
433 memcpy(&ctx->buf[pos], s, len);
434 pos += len;
435 }
436 strcpy(&ctx->buf[pos], UCI_QUOTE_ESCAPE);
437 pos += sizeof(UCI_QUOTE_ESCAPE);
438 s = p + 1;
439 } while ((p = strchr(s, '\'')));
440
441 return ctx->buf;
442 }
443
444
445 /*
446 * export a single config package to a file stream
447 */
448 static void uci_export_package(struct uci_package *p, FILE *stream, bool header)
449 {
450 struct uci_context *ctx = p->ctx;
451 struct uci_element *s, *o;
452
453 if (header)
454 fprintf(stream, "package '%s'\n", uci_escape(ctx, p->e.name));
455 uci_foreach_element(&p->sections, s) {
456 struct uci_section *sec = uci_to_section(s);
457 fprintf(stream, "\nconfig '%s'", uci_escape(ctx, sec->type));
458 fprintf(stream, " '%s'\n", uci_escape(ctx, sec->e.name));
459 uci_foreach_element(&sec->options, o) {
460 struct uci_option *opt = uci_to_option(o);
461 fprintf(stream, "\toption '%s'", uci_escape(ctx, opt->e.name));
462 fprintf(stream, " '%s'\n", uci_escape(ctx, opt->value));
463 }
464 }
465 fprintf(stream, "\n");
466 }
467
468 int uci_export(struct uci_context *ctx, FILE *stream, struct uci_package *package, bool header)
469 {
470 struct uci_element *e;
471
472 UCI_HANDLE_ERR(ctx);
473 UCI_ASSERT(ctx, stream != NULL);
474
475 if (package)
476 uci_export_package(package, stream, header);
477 else {
478 uci_foreach_element(&ctx->root, e) {
479 uci_export_package(uci_to_package(e), stream, header);
480 }
481 }
482
483 return 0;
484 }
485
486 int uci_import(struct uci_context *ctx, FILE *stream, const char *name, struct uci_package **package, bool single)
487 {
488 struct uci_parse_context *pctx;
489
490 /* make sure no memory from previous parse attempts is leaked */
491 uci_file_cleanup(ctx);
492
493 pctx = (struct uci_parse_context *) uci_malloc(ctx, sizeof(struct uci_parse_context));
494 ctx->pctx = pctx;
495 pctx->file = stream;
496
497 /*
498 * If 'name' was supplied, assume that the supplied stream does not contain
499 * the appropriate 'package <name>' string to specify the config name
500 * NB: the config file can still override the package name
501 */
502 if (name)
503 pctx->name = name;
504
505 while (!feof(pctx->file)) {
506 uci_getln(ctx, 0);
507 if (pctx->buf[0])
508 uci_parse_line(ctx, single);
509 }
510
511 if (package)
512 *package = pctx->package;
513
514 pctx->name = NULL;
515 uci_switch_config(ctx);
516
517 /* no error happened, we can get rid of the parser context now */
518 uci_file_cleanup(ctx);
519
520 return 0;
521 }
522
523 int uci_load(struct uci_context *ctx, const char *name, struct uci_package **package)
524 {
525 struct stat statbuf;
526 char *filename;
527 bool confdir;
528 FILE *file;
529 int fd;
530
531 UCI_HANDLE_ERR(ctx);
532 UCI_ASSERT(ctx, name != NULL);
533
534 switch (name[0]) {
535 case '.':
536 if (name[1] != '/')
537 UCI_THROW(ctx, UCI_ERR_NOTFOUND);
538 /* fall through */
539 case '/':
540 /* absolute/relative path outside of /etc/config */
541 filename = uci_strdup(ctx, name);
542 name = strrchr(name, '/') + 1;
543 confdir = false;
544 break;
545 default:
546 filename = uci_malloc(ctx, strlen(name) + sizeof(UCI_CONFDIR) + 2);
547 sprintf(filename, UCI_CONFDIR "/%s", name);
548 confdir = true;
549 break;
550 }
551
552 if ((stat(filename, &statbuf) < 0) ||
553 ((statbuf.st_mode & S_IFMT) != S_IFREG)) {
554 UCI_THROW(ctx, UCI_ERR_NOTFOUND);
555 }
556
557 fd = open(filename, O_RDONLY);
558 if (fd <= 0)
559 UCI_THROW(ctx, UCI_ERR_IO);
560
561 if (flock(fd, LOCK_SH) < 0)
562 UCI_THROW(ctx, UCI_ERR_IO);
563
564 file = fdopen(fd, "r");
565 if (!file)
566 UCI_THROW(ctx, UCI_ERR_IO);
567
568 ctx->errno = 0;
569 UCI_TRAP_SAVE(ctx, done);
570 uci_import(ctx, file, name, package, true);
571 UCI_TRAP_RESTORE(ctx);
572
573 if (*package) {
574 (*package)->path = filename;
575 (*package)->confdir = confdir;
576 }
577
578 done:
579 flock(fd, LOCK_UN);
580 fclose(file);
581 return ctx->errno;
582 }
583
584 int uci_commit(struct uci_context *ctx, struct uci_package *p)
585 {
586 FILE *f = NULL;
587 int fd = 0;
588 int err = UCI_ERR_IO;
589
590 UCI_HANDLE_ERR(ctx);
591 UCI_ASSERT(ctx, p != NULL);
592 UCI_ASSERT(ctx, p->path != NULL);
593
594 fd = open(p->path, O_RDWR);
595 if (fd < 0)
596 goto done;
597
598 if (flock(fd, LOCK_EX) < 0)
599 goto done;
600
601 ftruncate(fd, 0);
602 f = fdopen(fd, "w");
603 if (!f)
604 goto done;
605
606 UCI_TRAP_SAVE(ctx, done);
607 uci_export(ctx, f, p, false);
608 UCI_TRAP_RESTORE(ctx);
609
610 done:
611 if (f)
612 fclose(f);
613 else if (fd > 0)
614 close(fd);
615
616 if (ctx->errno)
617 UCI_THROW(ctx, ctx->errno);
618 if (err)
619 UCI_THROW(ctx, UCI_ERR_IO);
620 return 0;
621 }
622
623
624 /*
625 * This function returns the filename by returning the string
626 * after the last '/' character. By checking for a non-'\0'
627 * character afterwards, directories are ignored (glob marks
628 * those with a trailing '/'
629 */
630 static inline char *get_filename(char *path)
631 {
632 char *p;
633
634 p = strrchr(path, '/');
635 p++;
636 if (!*p)
637 return NULL;
638 return p;
639 }
640
641 char **uci_list_configs(struct uci_context *ctx)
642 {
643 char **configs;
644 glob_t globbuf;
645 int size, i;
646 char *buf;
647
648 if (glob(UCI_CONFDIR "/*", GLOB_MARK, NULL, &globbuf) != 0)
649 return NULL;
650
651 size = sizeof(char *) * (globbuf.gl_pathc + 1);
652 for(i = 0; i < globbuf.gl_pathc; i++) {
653 char *p;
654
655 p = get_filename(globbuf.gl_pathv[i]);
656 if (!p)
657 continue;
658
659 size += strlen(p) + 1;
660 }
661
662 configs = malloc(size);
663 if (!configs)
664 return NULL;
665
666 memset(configs, 0, size);
667 buf = (char *) &configs[globbuf.gl_pathc + 1];
668 for(i = 0; i < globbuf.gl_pathc; i++) {
669 char *p;
670
671 p = get_filename(globbuf.gl_pathv[i]);
672 if (!p)
673 continue;
674
675 configs[i] = buf;
676 strcpy(buf, p);
677 buf += strlen(buf) + 1;
678 }
679 return configs;
680 }
681
682