c92e60bb276d65048cf97af6b2c72bdfb38ab074
[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->bufsz = 0;
79         }
80
81         pctx = ctx->pctx;
82         if (!pctx)
83                 return;
84
85         ctx->pctx = NULL;
86         if (pctx->cfg) {
87                 uci_list_del(&pctx->cfg->list);
88                 uci_drop_config(pctx->cfg);
89         }
90         if (pctx->buf)
91                 free(pctx->buf);
92         if (pctx->file)
93                 fclose(pctx->file);
94
95         free(pctx);
96 }
97
98 /* 
99  * parse a character escaped by '\'
100  * returns true if the escaped character is to be parsed
101  * returns false if the escaped character is to be ignored
102  */
103 static inline bool parse_backslash(struct uci_context *ctx, char **str)
104 {
105         /* skip backslash */
106         *str += 1;
107
108         /* undecoded backslash at the end of line, fetch the next line */
109         if (!**str) {
110                 *str += 1;
111                 uci_getln(ctx, *str - ctx->pctx->buf);
112                 return false;
113         }
114
115         /* FIXME: decode escaped char, necessary? */
116         return true;
117 }
118
119 /*
120  * move the string pointer forward until a non-whitespace character or
121  * EOL is reached
122  */
123 static void skip_whitespace(struct uci_context *ctx, char **str)
124 {
125 restart:
126         while (**str && isspace(**str))
127                 *str += 1;
128
129         if (**str == '\\') {
130                 if (!parse_backslash(ctx, str))
131                         goto restart;
132         }
133 }
134
135 static inline void addc(char **dest, char **src)
136 {
137         **dest = **src;
138         *dest += 1;
139         *src += 1;
140 }
141
142 /*
143  * parse a double quoted string argument from the command line
144  */
145 static void parse_double_quote(struct uci_context *ctx, char **str, char **target)
146 {
147         char c;
148
149         /* skip quote character */
150         *str += 1;
151
152         while ((c = **str)) {
153                 switch(c) {
154                 case '"':
155                         **target = 0;
156                         *str += 1;
157                         return;
158                 case '\\':
159                         if (!parse_backslash(ctx, str))
160                                 continue;
161                         /* fall through */
162                 default:
163                         addc(target, str);
164                         break;
165                 }
166         }
167         ctx->pctx->reason = "unterminated \"";
168         ctx->pctx->byte = *str - ctx->pctx->buf;
169         UCI_THROW(ctx, UCI_ERR_PARSE);
170 }
171
172 /*
173  * parse a single quoted string argument from the command line
174  */
175 static void parse_single_quote(struct uci_context *ctx, char **str, char **target)
176 {
177         char c;
178         /* skip quote character */
179         *str += 1;
180
181         while ((c = **str)) {
182                 switch(c) {
183                 case '\'':
184                         **target = 0;
185                         *str += 1;
186                         return;
187                 default:
188                         addc(target, str);
189                 }
190         }
191         ctx->pctx->reason = "unterminated '";
192         ctx->pctx->byte = *str - ctx->pctx->buf;
193         UCI_THROW(ctx, UCI_ERR_PARSE);
194 }
195
196 /*
197  * parse a string from the command line and detect the quoting style
198  */
199 static void parse_str(struct uci_context *ctx, char **str, char **target)
200 {
201         do {
202                 switch(**str) {
203                 case '\'':
204                         parse_single_quote(ctx, str, target);
205                         break;
206                 case '"':
207                         parse_double_quote(ctx, str, target);
208                         break;
209                 case 0:
210                         goto done;
211                 case '\\':
212                         if (!parse_backslash(ctx, str))
213                                 continue;
214                         /* fall through */
215                 default:
216                         addc(target, str);
217                         break;
218                 }
219         } while (**str && !isspace(**str));
220 done:
221
222         /* 
223          * if the string was unquoted and we've stopped at a whitespace
224          * character, skip to the next one, because the whitespace will
225          * be overwritten by a null byte here
226          */
227         if (**str)
228                 *str += 1;
229
230         /* terminate the parsed string */
231         **target = 0;
232 }
233
234 /*
235  * extract the next argument from the command line
236  */
237 static char *next_arg(struct uci_context *ctx, char **str, bool required)
238 {
239         char *val;
240         char *ptr;
241
242         val = ptr = *str;
243         skip_whitespace(ctx, str);
244         parse_str(ctx, str, &ptr);
245         if (required && !*val) {
246                 ctx->pctx->reason = "insufficient arguments";
247                 ctx->pctx->byte = *str - ctx->pctx->buf;
248                 UCI_THROW(ctx, UCI_ERR_PARSE);
249         }
250
251         return uci_strdup(ctx, val);
252 }
253
254 /*
255  * verify that the end of the line or command is reached.
256  * throw an error if extra arguments are given on the command line
257  */
258 static void assert_eol(struct uci_context *ctx, char **str)
259 {
260         char *tmp;
261
262         tmp = next_arg(ctx, str, false);
263         if (tmp && *tmp) {
264                 ctx->pctx->reason = "too many arguments";
265                 ctx->pctx->byte = tmp - ctx->pctx->buf;
266                 UCI_THROW(ctx, UCI_ERR_PARSE);
267         }
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         const char *name;
278
279         pctx = ctx->pctx;
280         name = pctx->name;
281
282         /* add the last config to main config file list */
283         if (pctx->cfg) {
284                 uci_list_add(&ctx->root, &pctx->cfg->list);
285
286                 pctx->cfg = NULL;
287                 pctx->section = NULL;
288         }
289
290         if (!name)
291                 return;
292
293         /* 
294          * if an older config under the same name exists, unload it
295          * ignore errors here, e.g. if the config was not found
296          */
297         UCI_TRAP_SAVE(ctx, ignore);
298         uci_unload(ctx, name);
299         UCI_TRAP_RESTORE(ctx);
300 ignore:
301         ctx->errno = 0;
302
303         pctx->cfg = uci_alloc_config(ctx, name);
304 }
305
306 /*
307  * parse the 'package' uci command (next config package)
308  */
309 static void uci_parse_package(struct uci_context *ctx, char **str)
310 {
311         char *name = NULL;
312
313         /* command string null-terminated by strtok */
314         *str += strlen(*str) + 1;
315
316         UCI_TRAP_SAVE(ctx, error);
317         name = next_arg(ctx, str, true);
318         assert_eol(ctx, str);
319         ctx->pctx->name = name;
320         uci_switch_config(ctx);
321         UCI_TRAP_RESTORE(ctx);
322         return;
323
324 error:
325         if (name)
326                 free(name);
327         UCI_THROW(ctx, ctx->errno);
328 }
329
330 /*
331  * parse the 'config' uci command (open a section)
332  */
333 static void uci_parse_config(struct uci_context *ctx, char **str)
334 {
335         char *name = NULL;
336         char *type = NULL;
337
338         if (!ctx->pctx->cfg) {
339                 if (!ctx->pctx->name) {
340                         ctx->pctx->byte = *str - ctx->pctx->buf;
341                         ctx->pctx->reason = "attempting to import a file without a package name";
342                         UCI_THROW(ctx, UCI_ERR_PARSE);
343                 }
344                 uci_switch_config(ctx);
345         }
346
347         /* command string null-terminated by strtok */
348         *str += strlen(*str) + 1;
349
350         UCI_TRAP_SAVE(ctx, error);
351         type = next_arg(ctx, str, true);
352         name = next_arg(ctx, str, false);
353         assert_eol(ctx, str);
354         ctx->pctx->section = uci_add_section(ctx->pctx->cfg, type, name);
355         UCI_TRAP_RESTORE(ctx);
356         return;
357
358 error:
359         if (name)
360                 free(name);
361         if (type)
362                 free(type);
363         UCI_THROW(ctx, ctx->errno);
364 }
365
366 /*
367  * parse the 'option' uci command (open a value)
368  */
369 static void uci_parse_option(struct uci_context *ctx, char **str)
370 {
371         char *name = NULL;
372         char *value = NULL;
373
374         if (!ctx->pctx->section) {
375                 ctx->pctx->byte = *str - ctx->pctx->buf;
376                 ctx->pctx->reason = "option command found before the first section";
377                 UCI_THROW(ctx, UCI_ERR_PARSE);
378         }
379         /* command string null-terminated by strtok */
380         *str += strlen(*str) + 1;
381
382         UCI_TRAP_SAVE(ctx, error);
383         name = next_arg(ctx, str, true);
384         value = next_arg(ctx, str, true);
385         assert_eol(ctx, str);
386         uci_add_option(ctx->pctx->section, name, value);
387         UCI_TRAP_RESTORE(ctx);
388         return;
389
390 error:
391         if (name)
392                 free(name);
393         if (value)
394                 free(value);
395         UCI_THROW(ctx, ctx->errno);
396 }
397
398
399 /*
400  * parse a complete input line, split up combined commands by ';'
401  */
402 static void uci_parse_line(struct uci_context *ctx)
403 {
404         struct uci_parse_context *pctx = ctx->pctx;
405         char *word, *brk;
406
407         for (word = strtok_r(pctx->buf, ";", &brk);
408                  word;
409                  word = strtok_r(NULL, ";", &brk)) {
410
411                 char *pbrk;
412                 word = strtok_r(word, " \t", &pbrk);
413
414                 switch(word[0]) {
415                         case 'p':
416                                 if ((word[1] == 0) || !strcmp(word + 1, "ackage"))
417                                         uci_parse_package(ctx, &word);
418                                 break;
419                         case 'c':
420                                 if ((word[1] == 0) || !strcmp(word + 1, "onfig"))
421                                         uci_parse_config(ctx, &word);
422                                 break;
423                         case 'o':
424                                 if ((word[1] == 0) || !strcmp(word + 1, "ption"))
425                                         uci_parse_option(ctx, &word);
426                                 break;
427                         default:
428                                 pctx->reason = "unterminated command";
429                                 pctx->byte = word - pctx->buf;
430                                 UCI_THROW(ctx, UCI_ERR_PARSE);
431                                 break;
432                 }
433         }
434 }
435
436 /* max number of characters that escaping adds to the string */
437 #define UCI_QUOTE_ESCAPE        "'\\'"
438
439 /*
440  * escape an uci string for export
441  */
442 static char *uci_escape(struct uci_context *ctx, char *str)
443 {
444         char *s, *p, *t;
445         int pos = 0;
446
447         if (!ctx->buf) {
448                 ctx->bufsz = LINEBUF;
449                 ctx->buf = malloc(LINEBUF);
450         }
451
452         s = str;
453         p = strchr(str, '\'');
454         if (!p)
455                 return str;
456
457         do {
458                 int len = p - s;
459                 if (len > 0) {
460                         if (p + sizeof(UCI_QUOTE_ESCAPE) - str >= ctx->bufsz) {
461                                 ctx->bufsz *= 2;
462                                 ctx->buf = realloc(ctx->buf, ctx->bufsz);
463                                 if (!ctx->buf)
464                                         UCI_THROW(ctx, UCI_ERR_MEM);
465                         }
466                         memcpy(&ctx->buf[pos], s, len);
467                         pos += len;
468                 }
469                 strcpy(&ctx->buf[pos], UCI_QUOTE_ESCAPE);
470                 pos += sizeof(UCI_QUOTE_ESCAPE);
471                 s = p + 1;
472         } while ((p = strchr(s, '\'')));
473
474         return ctx->buf;
475 }
476
477
478 /*
479  * export a single config package to a file stream
480  */
481 static void uci_export_config(struct uci_config *cfg, FILE *stream)
482 {
483         struct uci_context *ctx = cfg->ctx;
484         struct uci_section *s;
485         struct uci_option *o;
486
487         fprintf(stream, "package '%s'\n", uci_escape(ctx, cfg->name));
488         uci_foreach_entry(section, &cfg->sections, s) {
489                 fprintf(stream, "\nconfig '%s'", uci_escape(ctx, s->type));
490                 fprintf(stream, " '%s'\n", uci_escape(ctx, s->name));
491                 uci_foreach_entry(option, &s->options, o) {
492                         fprintf(stream, "\toption '%s'", uci_escape(ctx, o->name));
493                         fprintf(stream, " '%s'\n", uci_escape(ctx, o->value));
494                 }
495         }
496         fprintf(stream, "\n");
497 }
498
499 int uci_export(struct uci_context *ctx, FILE *stream, struct uci_config *cfg)
500 {
501         UCI_HANDLE_ERR(ctx);
502         UCI_ASSERT(ctx, stream != NULL);
503
504         if (cfg) {
505                 uci_export_config(cfg, stream);
506                 goto done;
507         }
508
509         uci_foreach_entry(config, &ctx->root, cfg) {
510                 uci_export_config(cfg, stream);
511         }
512 done:
513         return 0;
514 }
515
516 int uci_import(struct uci_context *ctx, FILE *stream, const char *name, struct uci_config **cfg)
517 {
518         struct uci_parse_context *pctx;
519
520         /* make sure no memory from previous parse attempts is leaked */
521         uci_file_cleanup(ctx);
522
523         pctx = (struct uci_parse_context *) uci_malloc(ctx, sizeof(struct uci_parse_context));
524         ctx->pctx = pctx;
525         pctx->file = stream;
526
527         /*
528          * If 'name' was supplied, assume that the supplied stream does not contain
529          * the appropriate 'package <name>' string to specify the config name
530          * NB: the config file can still override the package name
531          */
532         if (name)
533                 pctx->name = name;
534
535         while (!feof(pctx->file)) {
536                 uci_getln(ctx, 0);
537                 if (pctx->buf[0])
538                         uci_parse_line(ctx);
539         }
540
541         if (cfg)
542                 *cfg = pctx->cfg;
543
544         pctx->name = NULL;
545         uci_switch_config(ctx);
546
547         /* no error happened, we can get rid of the parser context now */
548         uci_file_cleanup(ctx);
549
550         return 0;
551 }
552
553 int uci_load(struct uci_context *ctx, const char *name, struct uci_config **cfg)
554 {
555         struct stat statbuf;
556         char *filename;
557         bool confpath;
558         FILE *file;
559
560         UCI_HANDLE_ERR(ctx);
561         UCI_ASSERT(ctx, name != NULL);
562
563 ignore:
564         ctx->errno = 0;
565
566         switch (name[0]) {
567         case '.':
568         case '/':
569                 /* absolute/relative path outside of /etc/config */
570                 filename = (char *) name;
571                 confpath = false;
572                 break;
573         default:
574                 filename = uci_malloc(ctx, strlen(name) + sizeof(UCI_CONFDIR) + 2);
575                 sprintf(filename, UCI_CONFDIR "/%s", name);
576                 confpath = true;
577                 break;
578         }
579
580         if ((stat(filename, &statbuf) < 0) ||
581                 ((statbuf.st_mode &  S_IFMT) != S_IFREG)) {
582                 UCI_THROW(ctx, UCI_ERR_NOTFOUND);
583         }
584
585         file = fopen(filename, "r");
586         if (filename != name)
587                 free(filename);
588
589         if (!file)
590                 UCI_THROW(ctx, UCI_ERR_IO);
591
592         return uci_import(ctx, file, name, cfg);
593 }
594