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