3ccffb766b1b934293d1f169a4e7fe838eddcc64
[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 <stdio.h>
23 #include <ctype.h>
24
25 #define LINEBUF 32
26 #define LINEBUF_MAX     4096
27
28 /*
29  * Fetch a new line from the input stream and resize buffer if necessary
30  */
31 static void uci_getln(struct uci_context *ctx, int offset)
32 {
33         struct uci_parse_context *pctx = ctx->pctx;
34         char *p;
35         int ofs;
36
37         if (pctx->buf == NULL) {
38                 pctx->buf = uci_malloc(ctx, LINEBUF);
39                 pctx->bufsz = LINEBUF;
40         }
41
42         ofs = offset;
43         do {
44                 p = &pctx->buf[ofs];
45                 p[ofs] = 0;
46
47                 p = fgets(p, pctx->bufsz - ofs, pctx->file);
48                 if (!p || !*p)
49                         return;
50
51                 ofs += strlen(p);
52                 if (pctx->buf[ofs - 1] == '\n') {
53                         pctx->line++;
54                         pctx->buf[ofs - 1] = 0;
55                         return;
56                 }
57
58                 if (pctx->bufsz > LINEBUF_MAX/2) {
59                         pctx->reason = "line too long";
60                         pctx->byte = LINEBUF_MAX;
61                         UCI_THROW(ctx, UCI_ERR_PARSE);
62                 }
63
64                 pctx->bufsz *= 2;
65                 pctx->buf = uci_realloc(ctx, pctx->buf, pctx->bufsz);
66         } while (1);
67 }
68
69 /*
70  * Clean up all extra memory used by the parser and exporter
71  */
72 static void uci_file_cleanup(struct uci_context *ctx)
73 {
74         struct uci_parse_context *pctx;
75
76         if (ctx->buf) {
77                 free(ctx->buf);
78                 ctx->buf = NULL;
79                 ctx->bufsz = 0;
80         }
81
82         pctx = ctx->pctx;
83         if (!pctx)
84                 return;
85
86         ctx->pctx = NULL;
87         if (pctx->package) {
88                 uci_list_del(&pctx->package->list);
89                 uci_drop_config(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 uci_strdup(ctx, 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         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->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         UCI_TRAP_SAVE(ctx, ignore);
299         uci_unload(ctx, name);
300         UCI_TRAP_RESTORE(ctx);
301 ignore:
302         ctx->errno = 0;
303
304         pctx->package = uci_alloc_config(ctx, name);
305 }
306
307 /*
308  * parse the 'package' uci command (next config package)
309  */
310 static void uci_parse_package(struct uci_context *ctx, char **str)
311 {
312         char *name = NULL;
313
314         /* command string null-terminated by strtok */
315         *str += strlen(*str) + 1;
316
317         UCI_TRAP_SAVE(ctx, error);
318         name = next_arg(ctx, str, true);
319         assert_eol(ctx, str);
320         ctx->pctx->name = name;
321         uci_switch_config(ctx);
322         UCI_TRAP_RESTORE(ctx);
323         return;
324
325 error:
326         if (name)
327                 free(name);
328         UCI_THROW(ctx, ctx->errno);
329 }
330
331 /*
332  * parse the 'config' uci command (open a section)
333  */
334 static void uci_parse_config(struct uci_context *ctx, char **str)
335 {
336         char *name = NULL;
337         char *type = NULL;
338
339         if (!ctx->pctx->package) {
340                 if (!ctx->pctx->name) {
341                         ctx->pctx->byte = *str - ctx->pctx->buf;
342                         ctx->pctx->reason = "attempting to import a file without a package name";
343                         UCI_THROW(ctx, UCI_ERR_PARSE);
344                 }
345                 uci_switch_config(ctx);
346         }
347
348         /* command string null-terminated by strtok */
349         *str += strlen(*str) + 1;
350
351         UCI_TRAP_SAVE(ctx, error);
352         type = next_arg(ctx, str, true);
353         name = next_arg(ctx, str, false);
354         assert_eol(ctx, str);
355         ctx->pctx->section = uci_add_section(ctx->pctx->package, type, name);
356         UCI_TRAP_RESTORE(ctx);
357         return;
358
359 error:
360         if (name)
361                 free(name);
362         if (type)
363                 free(type);
364         UCI_THROW(ctx, ctx->errno);
365 }
366
367 /*
368  * parse the 'option' uci command (open a value)
369  */
370 static void uci_parse_option(struct uci_context *ctx, char **str)
371 {
372         char *name = NULL;
373         char *value = NULL;
374
375         if (!ctx->pctx->section) {
376                 ctx->pctx->byte = *str - ctx->pctx->buf;
377                 ctx->pctx->reason = "option command found before the first section";
378                 UCI_THROW(ctx, UCI_ERR_PARSE);
379         }
380         /* command string null-terminated by strtok */
381         *str += strlen(*str) + 1;
382
383         UCI_TRAP_SAVE(ctx, error);
384         name = next_arg(ctx, str, true);
385         value = next_arg(ctx, str, true);
386         assert_eol(ctx, str);
387         uci_add_option(ctx->pctx->section, name, value);
388         UCI_TRAP_RESTORE(ctx);
389         return;
390
391 error:
392         if (name)
393                 free(name);
394         if (value)
395                 free(value);
396         UCI_THROW(ctx, ctx->errno);
397 }
398
399
400 /*
401  * parse a complete input line, split up combined commands by ';'
402  */
403 static void uci_parse_line(struct uci_context *ctx)
404 {
405         struct uci_parse_context *pctx = ctx->pctx;
406         char *word, *brk;
407
408         for (word = strtok_r(pctx->buf, ";", &brk);
409                  word;
410                  word = strtok_r(NULL, ";", &brk)) {
411
412                 char *pbrk;
413                 word = strtok_r(word, " \t", &pbrk);
414
415                 switch(word[0]) {
416                         case 'p':
417                                 if ((word[1] == 0) || !strcmp(word + 1, "ackage"))
418                                         uci_parse_package(ctx, &word);
419                                 break;
420                         case 'c':
421                                 if ((word[1] == 0) || !strcmp(word + 1, "onfig"))
422                                         uci_parse_config(ctx, &word);
423                                 break;
424                         case 'o':
425                                 if ((word[1] == 0) || !strcmp(word + 1, "ption"))
426                                         uci_parse_option(ctx, &word);
427                                 break;
428                         default:
429                                 pctx->reason = "unterminated command";
430                                 pctx->byte = word - pctx->buf;
431                                 UCI_THROW(ctx, UCI_ERR_PARSE);
432                                 break;
433                 }
434         }
435 }
436
437 /* max number of characters that escaping adds to the string */
438 #define UCI_QUOTE_ESCAPE        "'\\'"
439
440 /*
441  * escape an uci string for export
442  */
443 static char *uci_escape(struct uci_context *ctx, char *str)
444 {
445         char *s, *p, *t;
446         int pos = 0;
447
448         if (!ctx->buf) {
449                 ctx->bufsz = LINEBUF;
450                 ctx->buf = malloc(LINEBUF);
451         }
452
453         s = str;
454         p = strchr(str, '\'');
455         if (!p)
456                 return str;
457
458         do {
459                 int len = p - s;
460                 if (len > 0) {
461                         if (p + sizeof(UCI_QUOTE_ESCAPE) - str >= ctx->bufsz) {
462                                 ctx->bufsz *= 2;
463                                 ctx->buf = realloc(ctx->buf, ctx->bufsz);
464                                 if (!ctx->buf)
465                                         UCI_THROW(ctx, UCI_ERR_MEM);
466                         }
467                         memcpy(&ctx->buf[pos], s, len);
468                         pos += len;
469                 }
470                 strcpy(&ctx->buf[pos], UCI_QUOTE_ESCAPE);
471                 pos += sizeof(UCI_QUOTE_ESCAPE);
472                 s = p + 1;
473         } while ((p = strchr(s, '\'')));
474
475         return ctx->buf;
476 }
477
478
479 /*
480  * export a single config package to a file stream
481  */
482 static void uci_export_config(struct uci_package *package, FILE *stream)
483 {
484         struct uci_context *ctx = package->ctx;
485         struct uci_section *s;
486         struct uci_option *o;
487
488         fprintf(stream, "package '%s'\n", uci_escape(ctx, package->name));
489         uci_foreach_entry(section, &package->sections, s) {
490                 fprintf(stream, "\nconfig '%s'", uci_escape(ctx, s->type));
491                 fprintf(stream, " '%s'\n", uci_escape(ctx, s->name));
492                 uci_foreach_entry(option, &s->options, o) {
493                         fprintf(stream, "\toption '%s'", uci_escape(ctx, o->name));
494                         fprintf(stream, " '%s'\n", uci_escape(ctx, o->value));
495                 }
496         }
497         fprintf(stream, "\n");
498 }
499
500 int uci_export(struct uci_context *ctx, FILE *stream, struct uci_package *package)
501 {
502         UCI_HANDLE_ERR(ctx);
503         UCI_ASSERT(ctx, stream != NULL);
504
505         if (package) {
506                 uci_export_config(package, stream);
507                 goto done;
508         }
509
510         uci_foreach_entry(package, &ctx->root, package) {
511                 uci_export_config(package, stream);
512         }
513 done:
514         return 0;
515 }
516
517 int uci_import(struct uci_context *ctx, FILE *stream, const char *name, struct uci_package **package)
518 {
519         struct uci_parse_context *pctx;
520
521         /* make sure no memory from previous parse attempts is leaked */
522         uci_file_cleanup(ctx);
523
524         pctx = (struct uci_parse_context *) uci_malloc(ctx, sizeof(struct uci_parse_context));
525         ctx->pctx = pctx;
526         pctx->file = stream;
527
528         /*
529          * If 'name' was supplied, assume that the supplied stream does not contain
530          * the appropriate 'package <name>' string to specify the config name
531          * NB: the config file can still override the package name
532          */
533         if (name)
534                 pctx->name = name;
535
536         while (!feof(pctx->file)) {
537                 uci_getln(ctx, 0);
538                 if (pctx->buf[0])
539                         uci_parse_line(ctx);
540         }
541
542         if (package)
543                 *package = pctx->package;
544
545         pctx->name = NULL;
546         uci_switch_config(ctx);
547
548         /* no error happened, we can get rid of the parser context now */
549         uci_file_cleanup(ctx);
550
551         return 0;
552 }
553
554 int uci_load(struct uci_context *ctx, const char *name, struct uci_package **package)
555 {
556         struct stat statbuf;
557         char *filename;
558         bool confpath;
559         FILE *file;
560
561         UCI_HANDLE_ERR(ctx);
562         UCI_ASSERT(ctx, name != NULL);
563
564 ignore:
565         ctx->errno = 0;
566
567         switch (name[0]) {
568         case '.':
569         case '/':
570                 /* absolute/relative path outside of /etc/config */
571                 filename = (char *) name;
572                 confpath = false;
573                 break;
574         default:
575                 filename = uci_malloc(ctx, strlen(name) + sizeof(UCI_CONFDIR) + 2);
576                 sprintf(filename, UCI_CONFDIR "/%s", name);
577                 confpath = true;
578                 break;
579         }
580
581         if ((stat(filename, &statbuf) < 0) ||
582                 ((statbuf.st_mode &  S_IFMT) != S_IFREG)) {
583                 UCI_THROW(ctx, UCI_ERR_NOTFOUND);
584         }
585
586         file = fopen(filename, "r");
587         if (filename != name)
588                 free(filename);
589
590         if (!file)
591                 UCI_THROW(ctx, UCI_ERR_IO);
592
593         return uci_import(ctx, file, name, package);
594 }
595