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