allow accessing files outside of /etc/config
[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 <fcntl.h>
23 #include <stdio.h>
24 #include <ctype.h>
25
26 #define LINEBUF 32
27 #define LINEBUF_MAX 4096
28
29 /*
30 * Fetch a new line from the input stream and resize buffer if necessary
31 */
32 static void uci_getln(struct uci_context *ctx, int offset)
33 {
34 struct uci_parse_context *pctx = ctx->pctx;
35 char *p;
36 int ofs;
37
38 if (pctx->buf == NULL) {
39 pctx->buf = uci_malloc(ctx, LINEBUF);
40 pctx->bufsz = LINEBUF;
41 }
42
43 ofs = offset;
44 do {
45 p = &pctx->buf[ofs];
46 p[ofs] = 0;
47
48 p = fgets(p, pctx->bufsz - ofs, pctx->file);
49 if (!p || !*p)
50 return;
51
52 ofs += strlen(p);
53 if (pctx->buf[ofs - 1] == '\n') {
54 pctx->line++;
55 pctx->buf[ofs - 1] = 0;
56 return;
57 }
58
59 if (pctx->bufsz > LINEBUF_MAX/2) {
60 pctx->reason = "line too long";
61 pctx->byte = LINEBUF_MAX;
62 UCI_THROW(ctx, UCI_ERR_PARSE);
63 }
64
65 pctx->bufsz *= 2;
66 pctx->buf = uci_realloc(ctx, pctx->buf, pctx->bufsz);
67 } while (1);
68 }
69
70 /*
71 * Clean up all extra memory used by the parser and exporter
72 */
73 static void uci_file_cleanup(struct uci_context *ctx)
74 {
75 struct uci_parse_context *pctx;
76
77 if (ctx->buf) {
78 free(ctx->buf);
79 ctx->buf = NULL;
80 ctx->bufsz = 0;
81 }
82
83 pctx = ctx->pctx;
84 if (!pctx)
85 return;
86
87 ctx->pctx = NULL;
88 if (pctx->package)
89 uci_free_package(pctx->package);
90
91 if (pctx->buf)
92 free(pctx->buf);
93 if (pctx->file)
94 fclose(pctx->file);
95
96 free(pctx);
97 }
98
99 /*
100 * parse a character escaped by '\'
101 * returns true if the escaped character is to be parsed
102 * returns false if the escaped character is to be ignored
103 */
104 static inline bool parse_backslash(struct uci_context *ctx, char **str)
105 {
106 /* skip backslash */
107 *str += 1;
108
109 /* undecoded backslash at the end of line, fetch the next line */
110 if (!**str) {
111 *str += 1;
112 uci_getln(ctx, *str - ctx->pctx->buf);
113 return false;
114 }
115
116 /* FIXME: decode escaped char, necessary? */
117 return true;
118 }
119
120 /*
121 * move the string pointer forward until a non-whitespace character or
122 * EOL is reached
123 */
124 static void skip_whitespace(struct uci_context *ctx, char **str)
125 {
126 restart:
127 while (**str && isspace(**str))
128 *str += 1;
129
130 if (**str == '\\') {
131 if (!parse_backslash(ctx, str))
132 goto restart;
133 }
134 }
135
136 static inline void addc(char **dest, char **src)
137 {
138 **dest = **src;
139 *dest += 1;
140 *src += 1;
141 }
142
143 /*
144 * parse a double quoted string argument from the command line
145 */
146 static void parse_double_quote(struct uci_context *ctx, char **str, char **target)
147 {
148 char c;
149
150 /* skip quote character */
151 *str += 1;
152
153 while ((c = **str)) {
154 switch(c) {
155 case '"':
156 **target = 0;
157 *str += 1;
158 return;
159 case '\\':
160 if (!parse_backslash(ctx, str))
161 continue;
162 /* fall through */
163 default:
164 addc(target, str);
165 break;
166 }
167 }
168 ctx->pctx->reason = "unterminated \"";
169 ctx->pctx->byte = *str - ctx->pctx->buf;
170 UCI_THROW(ctx, UCI_ERR_PARSE);
171 }
172
173 /*
174 * parse a single quoted string argument from the command line
175 */
176 static void parse_single_quote(struct uci_context *ctx, char **str, char **target)
177 {
178 char c;
179 /* skip quote character */
180 *str += 1;
181
182 while ((c = **str)) {
183 switch(c) {
184 case '\'':
185 **target = 0;
186 *str += 1;
187 return;
188 default:
189 addc(target, str);
190 }
191 }
192 ctx->pctx->reason = "unterminated '";
193 ctx->pctx->byte = *str - ctx->pctx->buf;
194 UCI_THROW(ctx, UCI_ERR_PARSE);
195 }
196
197 /*
198 * parse a string from the command line and detect the quoting style
199 */
200 static void parse_str(struct uci_context *ctx, char **str, char **target)
201 {
202 do {
203 switch(**str) {
204 case '\'':
205 parse_single_quote(ctx, str, target);
206 break;
207 case '"':
208 parse_double_quote(ctx, str, target);
209 break;
210 case 0:
211 goto done;
212 case '\\':
213 if (!parse_backslash(ctx, str))
214 continue;
215 /* fall through */
216 default:
217 addc(target, str);
218 break;
219 }
220 } while (**str && !isspace(**str));
221 done:
222
223 /*
224 * if the string was unquoted and we've stopped at a whitespace
225 * character, skip to the next one, because the whitespace will
226 * be overwritten by a null byte here
227 */
228 if (**str)
229 *str += 1;
230
231 /* terminate the parsed string */
232 **target = 0;
233 }
234
235 /*
236 * extract the next argument from the command line
237 */
238 static char *next_arg(struct uci_context *ctx, char **str, bool required)
239 {
240 char *val;
241 char *ptr;
242
243 val = ptr = *str;
244 skip_whitespace(ctx, str);
245 parse_str(ctx, str, &ptr);
246 if (required && !*val) {
247 ctx->pctx->reason = "insufficient arguments";
248 ctx->pctx->byte = *str - ctx->pctx->buf;
249 UCI_THROW(ctx, UCI_ERR_PARSE);
250 }
251
252 return val;
253 }
254
255 /*
256 * verify that the end of the line or command is reached.
257 * throw an error if extra arguments are given on the command line
258 */
259 static void assert_eol(struct uci_context *ctx, char **str)
260 {
261 char *tmp;
262
263 tmp = next_arg(ctx, str, false);
264 if (tmp && *tmp) {
265 ctx->pctx->reason = "too many arguments";
266 ctx->pctx->byte = tmp - ctx->pctx->buf;
267 UCI_THROW(ctx, UCI_ERR_PARSE);
268 }
269 }
270
271 /*
272 * switch to a different config, either triggered by uci_load, or by a
273 * 'package <...>' statement in the import file
274 */
275 static void uci_switch_config(struct uci_context *ctx)
276 {
277 struct uci_parse_context *pctx;
278 struct uci_element *e;
279 const char *name;
280
281 pctx = ctx->pctx;
282 name = pctx->name;
283
284 /* add the last config to main config file list */
285 if (pctx->package) {
286 uci_list_add(&ctx->root, &pctx->package->e.list);
287
288 pctx->package = NULL;
289 pctx->section = NULL;
290 }
291
292 if (!name)
293 return;
294
295 /*
296 * if an older config under the same name exists, unload it
297 * ignore errors here, e.g. if the config was not found
298 */
299 UCI_TRAP_SAVE(ctx, ignore);
300 e = uci_lookup_list(ctx, &ctx->root, name);
301 if (e)
302 uci_unload(ctx, uci_to_package(e));
303 UCI_TRAP_RESTORE(ctx);
304 ignore:
305 ctx->errno = 0;
306
307 pctx->package = uci_alloc_package(ctx, name);
308 }
309
310 /*
311 * parse the 'package' uci command (next config package)
312 */
313 static void uci_parse_package(struct uci_context *ctx, char **str)
314 {
315 char *name = NULL;
316
317 /* command string null-terminated by strtok */
318 *str += strlen(*str) + 1;
319
320 name = next_arg(ctx, str, true);
321 assert_eol(ctx, str);
322 ctx->pctx->name = name;
323 uci_switch_config(ctx);
324 }
325
326 /*
327 * parse the 'config' uci command (open a section)
328 */
329 static void uci_parse_config(struct uci_context *ctx, char **str)
330 {
331 char *name = NULL;
332 char *type = NULL;
333
334 if (!ctx->pctx->package) {
335 if (!ctx->pctx->name) {
336 ctx->pctx->byte = *str - ctx->pctx->buf;
337 ctx->pctx->reason = "attempting to import a file without a package name";
338 UCI_THROW(ctx, UCI_ERR_PARSE);
339 }
340 uci_switch_config(ctx);
341 }
342
343 /* command string null-terminated by strtok */
344 *str += strlen(*str) + 1;
345
346 type = next_arg(ctx, str, true);
347 name = next_arg(ctx, str, false);
348 assert_eol(ctx, str);
349 ctx->pctx->section = uci_alloc_section(ctx->pctx->package, type, name);
350 }
351
352 /*
353 * parse the 'option' uci command (open a value)
354 */
355 static void uci_parse_option(struct uci_context *ctx, char **str)
356 {
357 char *name = NULL;
358 char *value = NULL;
359
360 if (!ctx->pctx->section) {
361 ctx->pctx->byte = *str - ctx->pctx->buf;
362 ctx->pctx->reason = "option command found before the first section";
363 UCI_THROW(ctx, UCI_ERR_PARSE);
364 }
365 /* command string null-terminated by strtok */
366 *str += strlen(*str) + 1;
367
368 name = next_arg(ctx, str, true);
369 value = next_arg(ctx, str, true);
370 assert_eol(ctx, str);
371 uci_alloc_option(ctx->pctx->section, name, value);
372 }
373
374
375 /*
376 * parse a complete input line, split up combined commands by ';'
377 */
378 static void uci_parse_line(struct uci_context *ctx)
379 {
380 struct uci_parse_context *pctx = ctx->pctx;
381 char *word, *brk = NULL;
382
383 for (word = strtok_r(pctx->buf, ";", &brk);
384 word;
385 word = strtok_r(NULL, ";", &brk)) {
386
387 char *pbrk = NULL;
388 word = strtok_r(word, " \t", &pbrk);
389
390 switch(word[0]) {
391 case 'p':
392 if ((word[1] == 0) || !strcmp(word + 1, "ackage"))
393 uci_parse_package(ctx, &word);
394 break;
395 case 'c':
396 if ((word[1] == 0) || !strcmp(word + 1, "onfig"))
397 uci_parse_config(ctx, &word);
398 break;
399 case 'o':
400 if ((word[1] == 0) || !strcmp(word + 1, "ption"))
401 uci_parse_option(ctx, &word);
402 break;
403 default:
404 pctx->reason = "unterminated command";
405 pctx->byte = word - pctx->buf;
406 UCI_THROW(ctx, UCI_ERR_PARSE);
407 break;
408 }
409 }
410 }
411
412 /* max number of characters that escaping adds to the string */
413 #define UCI_QUOTE_ESCAPE "'\\'"
414
415 /*
416 * escape an uci string for export
417 */
418 static char *uci_escape(struct uci_context *ctx, char *str)
419 {
420 char *s, *p;
421 int pos = 0;
422
423 if (!ctx->buf) {
424 ctx->bufsz = LINEBUF;
425 ctx->buf = malloc(LINEBUF);
426 }
427
428 s = str;
429 p = strchr(str, '\'');
430 if (!p)
431 return str;
432
433 do {
434 int len = p - s;
435 if (len > 0) {
436 if (p + sizeof(UCI_QUOTE_ESCAPE) - str >= ctx->bufsz) {
437 ctx->bufsz *= 2;
438 ctx->buf = realloc(ctx->buf, ctx->bufsz);
439 if (!ctx->buf)
440 UCI_THROW(ctx, UCI_ERR_MEM);
441 }
442 memcpy(&ctx->buf[pos], s, len);
443 pos += len;
444 }
445 strcpy(&ctx->buf[pos], UCI_QUOTE_ESCAPE);
446 pos += sizeof(UCI_QUOTE_ESCAPE);
447 s = p + 1;
448 } while ((p = strchr(s, '\'')));
449
450 return ctx->buf;
451 }
452
453
454 /*
455 * export a single config package to a file stream
456 */
457 static void uci_export_package(struct uci_package *p, FILE *stream)
458 {
459 struct uci_context *ctx = p->ctx;
460 struct uci_element *s, *o;
461
462 fprintf(stream, "package '%s'\n", uci_escape(ctx, p->e.name));
463 uci_foreach_element(&p->sections, s) {
464 struct uci_section *sec = uci_to_section(s);
465 fprintf(stream, "\nconfig '%s'", uci_escape(ctx, sec->type));
466 fprintf(stream, " '%s'\n", uci_escape(ctx, sec->e.name));
467 uci_foreach_element(&sec->options, o) {
468 struct uci_option *opt = uci_to_option(o);
469 fprintf(stream, "\toption '%s'", uci_escape(ctx, opt->e.name));
470 fprintf(stream, " '%s'\n", uci_escape(ctx, opt->value));
471 }
472 }
473 fprintf(stream, "\n");
474 }
475
476 int uci_export(struct uci_context *ctx, FILE *stream, struct uci_package *package)
477 {
478 struct uci_element *e;
479
480 UCI_HANDLE_ERR(ctx);
481 UCI_ASSERT(ctx, stream != NULL);
482
483 if (package) {
484 uci_export_package(package, stream);
485 goto done;
486 }
487
488 uci_foreach_element(&ctx->root, e) {
489 uci_export_package(uci_to_package(e), stream);
490 }
491 done:
492 return 0;
493 }
494
495 int uci_import(struct uci_context *ctx, FILE *stream, const char *name, struct uci_package **package)
496 {
497 struct uci_parse_context *pctx;
498
499 /* make sure no memory from previous parse attempts is leaked */
500 uci_file_cleanup(ctx);
501
502 pctx = (struct uci_parse_context *) uci_malloc(ctx, sizeof(struct uci_parse_context));
503 ctx->pctx = pctx;
504 pctx->file = stream;
505
506 /*
507 * If 'name' was supplied, assume that the supplied stream does not contain
508 * the appropriate 'package <name>' string to specify the config name
509 * NB: the config file can still override the package name
510 */
511 if (name)
512 pctx->name = name;
513
514 while (!feof(pctx->file)) {
515 uci_getln(ctx, 0);
516 if (pctx->buf[0])
517 uci_parse_line(ctx);
518 }
519
520 if (package)
521 *package = pctx->package;
522
523 pctx->name = NULL;
524 uci_switch_config(ctx);
525
526 /* no error happened, we can get rid of the parser context now */
527 uci_file_cleanup(ctx);
528
529 return 0;
530 }
531
532 int uci_load(struct uci_context *ctx, const char *name, struct uci_package **package)
533 {
534 struct stat statbuf;
535 char *filename;
536 bool confdir;
537 FILE *file;
538 int fd;
539
540 UCI_HANDLE_ERR(ctx);
541 UCI_ASSERT(ctx, name != NULL);
542
543 switch (name[0]) {
544 case '.':
545 if (name[1] != '/')
546 UCI_THROW(ctx, UCI_ERR_NOTFOUND);
547 /* fall through */
548 case '/':
549 /* absolute/relative path outside of /etc/config */
550 filename = uci_strdup(ctx, name);
551 name = strrchr(name, '/') + 1;
552 confdir = false;
553 break;
554 default:
555 filename = uci_malloc(ctx, strlen(name) + sizeof(UCI_CONFDIR) + 2);
556 sprintf(filename, UCI_CONFDIR "/%s", name);
557 confdir = true;
558 break;
559 }
560
561 if ((stat(filename, &statbuf) < 0) ||
562 ((statbuf.st_mode & S_IFMT) != S_IFREG)) {
563 UCI_THROW(ctx, UCI_ERR_NOTFOUND);
564 }
565
566 fd = open(filename, O_RDONLY);
567 if (fd <= 0)
568 UCI_THROW(ctx, UCI_ERR_IO);
569
570 flock(fd, LOCK_SH);
571 file = fdopen(fd, "r");
572 if (!file)
573 UCI_THROW(ctx, UCI_ERR_IO);
574
575 ctx->errno = 0;
576 UCI_TRAP_SAVE(ctx, done);
577 uci_import(ctx, file, name, package);
578 UCI_TRAP_RESTORE(ctx);
579
580 if (*package) {
581 (*package)->path = filename;
582 (*package)->confdir = confdir;
583 }
584
585 done:
586 flock(fd, LOCK_UN);
587 fclose(file);
588 return ctx->errno;
589 }
590
591 /*
592 * This function returns the filename by returning the string
593 * after the last '/' character. By checking for a non-'\0'
594 * character afterwards, directories are ignored (glob marks
595 * those with a trailing '/'
596 */
597 static inline char *get_filename(char *path)
598 {
599 char *p;
600
601 p = strrchr(path, '/');
602 p++;
603 if (!*p)
604 return NULL;
605 return p;
606 }
607
608 char **uci_list_configs(struct uci_context *ctx)
609 {
610 char **configs;
611 glob_t globbuf;
612 int size, i;
613 char *buf;
614
615 if (glob(UCI_CONFDIR "/*", GLOB_MARK, NULL, &globbuf) != 0)
616 return NULL;
617
618 size = sizeof(char *) * (globbuf.gl_pathc + 1);
619 for(i = 0; i < globbuf.gl_pathc; i++) {
620 char *p;
621
622 p = get_filename(globbuf.gl_pathv[i]);
623 if (!p)
624 continue;
625
626 size += strlen(p) + 1;
627 }
628
629 configs = malloc(size);
630 if (!configs)
631 return NULL;
632
633 memset(configs, 0, size);
634 buf = (char *) &configs[globbuf.gl_pathc + 1];
635 for(i = 0; i < globbuf.gl_pathc; i++) {
636 char *p;
637
638 p = get_filename(globbuf.gl_pathv[i]);
639 if (!p)
640 continue;
641
642 configs[i] = buf;
643 strcpy(buf, p);
644 buf += strlen(buf) + 1;
645 }
646 return configs;
647 }
648
649