add initial work for option datatype abstraction
[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/file.h>
22 #include <stdbool.h>
23 #include <unistd.h>
24 #include <fcntl.h>
25 #include <stdio.h>
26 #include <ctype.h>
27
28 static struct uci_backend uci_file_backend;
29
30 /*
31  * verify that the end of the line or command is reached.
32  * throw an error if extra arguments are given on the command line
33  */
34 static void assert_eol(struct uci_context *ctx, char **str)
35 {
36         char *tmp;
37
38         skip_whitespace(ctx, str);
39         tmp = next_arg(ctx, str, false, false);
40         if (*tmp && (ctx->flags & UCI_FLAG_STRICT))
41                 uci_parse_error(ctx, *str, "too many arguments");
42 }
43
44 /* 
45  * switch to a different config, either triggered by uci_load, or by a
46  * 'package <...>' statement in the import file
47  */
48 static void uci_switch_config(struct uci_context *ctx)
49 {
50         struct uci_parse_context *pctx;
51         struct uci_element *e;
52         const char *name;
53
54         pctx = ctx->pctx;
55         name = pctx->name;
56
57         /* add the last config to main config file list */
58         if (pctx->package) {
59                 pctx->package->backend = ctx->backend;
60                 uci_list_add(&ctx->root, &pctx->package->e.list);
61
62                 pctx->package = NULL;
63                 pctx->section = NULL;
64         }
65
66         if (!name)
67                 return;
68
69         /* 
70          * if an older config under the same name exists, unload it
71          * ignore errors here, e.g. if the config was not found
72          */
73         e = uci_lookup_list(&ctx->root, name);
74         if (e)
75                 UCI_THROW(ctx, UCI_ERR_DUPLICATE);
76         pctx->package = uci_alloc_package(ctx, name);
77 }
78
79 /*
80  * parse the 'package' uci command (next config package)
81  */
82 static void uci_parse_package(struct uci_context *ctx, char **str, bool single)
83 {
84         char *name = NULL;
85
86         /* command string null-terminated by strtok */
87         *str += strlen(*str) + 1;
88
89         name = next_arg(ctx, str, true, true);
90         assert_eol(ctx, str);
91         if (single)
92                 return;
93
94         ctx->pctx->name = name;
95         uci_switch_config(ctx);
96 }
97
98 /*
99  * parse the 'config' uci command (open a section)
100  */
101 static void uci_parse_config(struct uci_context *ctx, char **str)
102 {
103         struct uci_parse_context *pctx = ctx->pctx;
104         char *name = NULL;
105         char *type = NULL;
106
107         uci_fixup_section(ctx, ctx->pctx->section);
108         if (!ctx->pctx->package) {
109                 if (!ctx->pctx->name)
110                         uci_parse_error(ctx, *str, "attempting to import a file without a package name");
111
112                 uci_switch_config(ctx);
113         }
114
115         /* command string null-terminated by strtok */
116         *str += strlen(*str) + 1;
117
118         type = next_arg(ctx, str, true, false);
119         if (!uci_validate_str(type, false))
120                 uci_parse_error(ctx, type, "invalid character in field");
121         name = next_arg(ctx, str, false, true);
122         assert_eol(ctx, str);
123
124         if (pctx->merge) {
125                 UCI_TRAP_SAVE(ctx, error);
126                 if (uci_set(ctx, pctx->package, name, NULL, type, NULL) != UCI_OK)
127                         goto error;
128                 UCI_TRAP_RESTORE(ctx);
129                 return;
130 error:
131                 UCI_THROW(ctx, ctx->err);
132         } else
133                 pctx->section = uci_alloc_section(pctx->package, type, name);
134 }
135
136 /*
137  * parse the 'option' uci command (open a value)
138  */
139 static void uci_parse_option(struct uci_context *ctx, char **str)
140 {
141         struct uci_parse_context *pctx = ctx->pctx;
142         char *name = NULL;
143         char *value = NULL;
144
145         if (!pctx->section)
146                 uci_parse_error(ctx, *str, "option command found before the first section");
147
148         /* command string null-terminated by strtok */
149         *str += strlen(*str) + 1;
150
151         name = next_arg(ctx, str, true, true);
152         value = next_arg(ctx, str, false, false);
153         assert_eol(ctx, str);
154
155         if (pctx->merge) {
156                 UCI_TRAP_SAVE(ctx, error);
157                 uci_set(ctx, pctx->package, pctx->section->e.name, name, value, NULL);
158                 UCI_TRAP_RESTORE(ctx);
159                 return;
160 error:
161                 UCI_THROW(ctx, ctx->err);
162         } else
163                 uci_alloc_option(pctx->section, name, value);
164 }
165
166
167 /*
168  * parse a complete input line, split up combined commands by ';'
169  */
170 static void uci_parse_line(struct uci_context *ctx, bool single)
171 {
172         struct uci_parse_context *pctx = ctx->pctx;
173         char *word, *brk;
174
175         word = pctx->buf;
176         do {
177                 brk = NULL;
178                 word = strtok_r(word, " \t", &brk);
179                 if (!word)
180                         return;
181
182                 switch(word[0]) {
183                         case 0:
184                         case '#':
185                                 return;
186                         case 'p':
187                                 if ((word[1] == 0) || !strcmp(word + 1, "ackage"))
188                                         uci_parse_package(ctx, &word, single);
189                                 else
190                                         goto invalid;
191                                 break;
192                         case 'c':
193                                 if ((word[1] == 0) || !strcmp(word + 1, "onfig"))
194                                         uci_parse_config(ctx, &word);
195                                 else
196                                         goto invalid;
197                                 break;
198                         case 'o':
199                                 if ((word[1] == 0) || !strcmp(word + 1, "ption"))
200                                         uci_parse_option(ctx, &word);
201                                 else
202                                         goto invalid;
203                                 break;
204                         default:
205                                 goto invalid;
206                 }
207                 continue;
208 invalid:
209                 uci_parse_error(ctx, word, "invalid command");
210         } while (1);
211 }
212
213 /* max number of characters that escaping adds to the string */
214 #define UCI_QUOTE_ESCAPE        "'\\''"
215
216 /*
217  * escape an uci string for export
218  */
219 static char *uci_escape(struct uci_context *ctx, const char *str)
220 {
221         const char *end;
222         int ofs = 0;
223
224         if (!ctx->buf) {
225                 ctx->bufsz = LINEBUF;
226                 ctx->buf = malloc(LINEBUF);
227         }
228
229         while (1) {
230                 int len;
231
232                 end = strchr(str, '\'');
233                 if (!end)
234                         end = str + strlen(str);
235                 len = end - str;
236
237                 /* make sure that we have enough room in the buffer */
238                 while (ofs + len + sizeof(UCI_QUOTE_ESCAPE) + 1 > ctx->bufsz) {
239                         ctx->bufsz *= 2;
240                         ctx->buf = uci_realloc(ctx, ctx->buf, ctx->bufsz);
241                 }
242
243                 /* copy the string until the character before the quote */
244                 memcpy(&ctx->buf[ofs], str, len);
245                 ofs += len;
246
247                 /* end of string? return the buffer */
248                 if (*end == 0)
249                         break;
250
251                 memcpy(&ctx->buf[ofs], UCI_QUOTE_ESCAPE, sizeof(UCI_QUOTE_ESCAPE));
252                 ofs += strlen(&ctx->buf[ofs]);
253                 str = end + 1;
254         }
255
256         ctx->buf[ofs] = 0;
257         return ctx->buf;
258 }
259
260 /*
261  * export a single config package to a file stream
262  */
263 static void uci_export_package(struct uci_package *p, FILE *stream, bool header)
264 {
265         struct uci_context *ctx = p->ctx;
266         struct uci_element *s, *o;
267
268         if (header)
269                 fprintf(stream, "package '%s'\n", uci_escape(ctx, p->e.name));
270         uci_foreach_element(&p->sections, s) {
271                 struct uci_section *sec = uci_to_section(s);
272                 fprintf(stream, "\nconfig '%s'", uci_escape(ctx, sec->type));
273                 if (!sec->anonymous || (ctx->flags & UCI_FLAG_EXPORT_NAME))
274                         fprintf(stream, " '%s'", uci_escape(ctx, sec->e.name));
275                 fprintf(stream, "\n");
276                 uci_foreach_element(&sec->options, o) {
277                         struct uci_option *opt = uci_to_option(o);
278                         switch(o->type) {
279                         case UCI_TYPE_STRING:
280                                 fprintf(stream, "\toption '%s'", uci_escape(ctx, opt->e.name));
281                                 fprintf(stream, " '%s'\n", uci_escape(ctx, opt->v.string));
282                                 break;
283                         default:
284                                 fprintf(stream, "\t# unknown type for option '%s'\n", uci_escape(ctx, opt->e.name));
285                                 break;
286                         }
287                 }
288         }
289         fprintf(stream, "\n");
290 }
291
292 int uci_export(struct uci_context *ctx, FILE *stream, struct uci_package *package, bool header)
293 {
294         struct uci_element *e;
295
296         UCI_HANDLE_ERR(ctx);
297         UCI_ASSERT(ctx, stream != NULL);
298
299         if (package)
300                 uci_export_package(package, stream, header);
301         else {
302                 uci_foreach_element(&ctx->root, e) {
303                         uci_export_package(uci_to_package(e), stream, header);
304                 }
305         }
306
307         return 0;
308 }
309
310 int uci_import(struct uci_context *ctx, FILE *stream, const char *name, struct uci_package **package, bool single)
311 {
312         struct uci_parse_context *pctx;
313         UCI_HANDLE_ERR(ctx);
314
315         /* make sure no memory from previous parse attempts is leaked */
316         uci_cleanup(ctx);
317
318         uci_alloc_parse_context(ctx);
319         pctx = ctx->pctx;
320         pctx->file = stream;
321         if (*package && single) {
322                 pctx->package = *package;
323                 pctx->merge = true;
324         }
325
326         /*
327          * If 'name' was supplied, assume that the supplied stream does not contain
328          * the appropriate 'package <name>' string to specify the config name
329          * NB: the config file can still override the package name
330          */
331         if (name) {
332                 UCI_ASSERT(ctx, uci_validate_str(name, false));
333                 pctx->name = name;
334         }
335
336         while (!feof(pctx->file)) {
337                 uci_getln(ctx, 0);
338                 UCI_TRAP_SAVE(ctx, error);
339                 if (pctx->buf[0])
340                         uci_parse_line(ctx, single);
341                 UCI_TRAP_RESTORE(ctx);
342                 continue;
343 error:
344                 if (ctx->flags & UCI_FLAG_PERROR)
345                         uci_perror(ctx, NULL);
346                 if ((ctx->err != UCI_ERR_PARSE) ||
347                         (ctx->flags & UCI_FLAG_STRICT))
348                         UCI_THROW(ctx, ctx->err);
349         }
350
351         uci_fixup_section(ctx, ctx->pctx->section);
352         if (!pctx->package && name)
353                 uci_switch_config(ctx);
354         if (package)
355                 *package = pctx->package;
356         if (pctx->merge)
357                 pctx->package = NULL;
358
359         pctx->name = NULL;
360         uci_switch_config(ctx);
361
362         /* no error happened, we can get rid of the parser context now */
363         uci_cleanup(ctx);
364
365         return 0;
366 }
367
368
369 static char *uci_config_path(struct uci_context *ctx, const char *name)
370 {
371         char *filename;
372
373         UCI_ASSERT(ctx, uci_validate_str(name, false));
374         filename = uci_malloc(ctx, strlen(name) + strlen(ctx->confdir) + 2);
375         sprintf(filename, "%s/%s", ctx->confdir, name);
376
377         return filename;
378 }
379
380 void uci_file_commit(struct uci_context *ctx, struct uci_package **package, bool overwrite)
381 {
382         struct uci_package *p = *package;
383         FILE *f = NULL;
384         char *name = NULL;
385         char *path = NULL;
386
387         if (!p->path) {
388                 if (overwrite)
389                         p->path = uci_config_path(ctx, p->e.name);
390                 else
391                         UCI_THROW(ctx, UCI_ERR_INVAL);
392         }
393
394         /* open the config file for writing now, so that it is locked */
395         f = uci_open_stream(ctx, p->path, SEEK_SET, true, true);
396
397         /* flush unsaved changes and reload from history file */
398         UCI_TRAP_SAVE(ctx, done);
399         if (p->has_history) {
400                 if (!overwrite) {
401                         name = uci_strdup(ctx, p->e.name);
402                         path = uci_strdup(ctx, p->path);
403                         /* dump our own changes to the history file */
404                         if (!uci_list_empty(&p->history))
405                                 UCI_INTERNAL(uci_save, ctx, p);
406
407                         /* 
408                          * other processes might have modified the config 
409                          * as well. dump and reload 
410                          */
411                         uci_free_package(&p);
412                         uci_cleanup(ctx);
413                         UCI_INTERNAL(uci_import, ctx, f, name, &p, true);
414
415                         p->path = path;
416                         p->has_history = true;
417                         *package = p;
418
419                         /* freed together with the uci_package */
420                         path = NULL;
421
422                         /* check for updated history, flush */
423                         if (!uci_load_history(ctx, p, true))
424                                 goto done;
425                 } else {
426                         /* flush history */
427                         if (!uci_load_history(ctx, NULL, true))
428                                 goto done;
429                 }
430         }
431
432         rewind(f);
433         ftruncate(fileno(f), 0);
434
435         uci_export(ctx, f, p, false);
436         UCI_TRAP_RESTORE(ctx);
437
438 done:
439         if (name)
440                 free(name);
441         if (path)
442                 free(path);
443         uci_close_stream(f);
444         if (ctx->err)
445                 UCI_THROW(ctx, ctx->err);
446 }
447
448
449 /* 
450  * This function returns the filename by returning the string
451  * after the last '/' character. By checking for a non-'\0'
452  * character afterwards, directories are ignored (glob marks
453  * those with a trailing '/'
454  */
455 static inline char *get_filename(char *path)
456 {
457         char *p;
458
459         p = strrchr(path, '/');
460         p++;
461         if (!*p)
462                 return NULL;
463         return p;
464 }
465
466 static char **uci_list_config_files(struct uci_context *ctx)
467 {
468         char **configs;
469         glob_t globbuf;
470         int size, i;
471         char *buf;
472         char *dir;
473
474         dir = uci_malloc(ctx, strlen(ctx->confdir) + 1 + sizeof("/*"));
475         sprintf(dir, "%s/*", ctx->confdir);
476         if (glob(dir, GLOB_MARK, NULL, &globbuf) != 0)
477                 UCI_THROW(ctx, UCI_ERR_NOTFOUND);
478
479         size = sizeof(char *) * (globbuf.gl_pathc + 1);
480         for(i = 0; i < globbuf.gl_pathc; i++) {
481                 char *p;
482
483                 p = get_filename(globbuf.gl_pathv[i]);
484                 if (!p)
485                         continue;
486
487                 size += strlen(p) + 1;
488         }
489
490         configs = uci_malloc(ctx, size);
491         buf = (char *) &configs[globbuf.gl_pathc + 1];
492         for(i = 0; i < globbuf.gl_pathc; i++) {
493                 char *p;
494
495                 p = get_filename(globbuf.gl_pathv[i]);
496                 if (!p)
497                         continue;
498
499                 if (!uci_validate_name(p))
500                         continue;
501
502                 configs[i] = buf;
503                 strcpy(buf, p);
504                 buf += strlen(buf) + 1;
505         }
506         free(dir);
507         return configs;
508 }
509
510 static struct uci_package *uci_file_load(struct uci_context *ctx, const char *name)
511 {
512         struct uci_package *package = NULL;
513         char *filename;
514         bool confdir;
515         FILE *file = NULL;
516
517         switch (name[0]) {
518         case '.':
519                 /* relative path outside of /etc/config */
520                 if (name[1] != '/')
521                         UCI_THROW(ctx, UCI_ERR_NOTFOUND);
522                 /* fall through */
523         case '/':
524                 /* absolute path outside of /etc/config */
525                 filename = uci_strdup(ctx, name);
526                 name = strrchr(name, '/') + 1;
527                 confdir = false;
528                 break;
529         default:
530                 /* config in /etc/config */
531                 filename = uci_config_path(ctx, name);
532                 confdir = true;
533                 break;
534         }
535
536         file = uci_open_stream(ctx, filename, SEEK_SET, false, false);
537         ctx->err = 0;
538         UCI_TRAP_SAVE(ctx, done);
539         UCI_INTERNAL(uci_import, ctx, file, name, &package, true);
540         UCI_TRAP_RESTORE(ctx);
541
542         if (package) {
543                 package->path = filename;
544                 package->has_history = confdir;
545                 uci_load_history(ctx, package, false);
546         }
547
548 done:
549         uci_close_stream(file);
550         if (ctx->err)
551                 UCI_THROW(ctx, ctx->err);
552         return package;
553 }
554
555 static UCI_BACKEND(uci_file_backend, "file",
556         .load = uci_file_load,
557         .commit = uci_file_commit,
558         .list_configs = uci_list_config_files,
559 );