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