allow the cli to override the confdir
[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 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 } while (1);
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, const char *str)
212 {
213 const char *end;
214 int ofs = 0;
215
216 if (!ctx->buf) {
217 ctx->bufsz = LINEBUF;
218 ctx->buf = malloc(LINEBUF);
219 }
220
221 while (1) {
222 int len;
223
224 end = strchr(str, '\'');
225 if (!end)
226 end = str + strlen(str);
227 len = end - str;
228
229 /* make sure that we have enough room in the buffer */
230 while (ofs + len + sizeof(UCI_QUOTE_ESCAPE) + 1 > ctx->bufsz) {
231 ctx->bufsz *= 2;
232 ctx->buf = uci_realloc(ctx, ctx->buf, ctx->bufsz);
233 }
234
235 /* copy the string until the character before the quote */
236 memcpy(&ctx->buf[ofs], str, len);
237 ofs += len;
238
239 /* end of string? return the buffer */
240 if (*end == 0)
241 break;
242
243 memcpy(&ctx->buf[ofs], UCI_QUOTE_ESCAPE, sizeof(UCI_QUOTE_ESCAPE));
244 ofs += strlen(&ctx->buf[ofs]);
245 str = end + 1;
246 }
247
248 ctx->buf[ofs] = 0;
249 return ctx->buf;
250 }
251
252 /*
253 * export a single config package to a file stream
254 */
255 static void uci_export_package(struct uci_package *p, FILE *stream, bool header)
256 {
257 struct uci_context *ctx = p->ctx;
258 struct uci_element *s, *o;
259
260 if (header)
261 fprintf(stream, "package '%s'\n", uci_escape(ctx, p->e.name));
262 uci_foreach_element(&p->sections, s) {
263 struct uci_section *sec = uci_to_section(s);
264 fprintf(stream, "\nconfig '%s'", uci_escape(ctx, sec->type));
265 if (!sec->anonymous || (ctx->flags & UCI_FLAG_EXPORT_NAME))
266 fprintf(stream, " '%s'", uci_escape(ctx, sec->e.name));
267 fprintf(stream, "\n");
268 uci_foreach_element(&sec->options, o) {
269 struct uci_option *opt = uci_to_option(o);
270 fprintf(stream, "\toption '%s'", uci_escape(ctx, opt->e.name));
271 fprintf(stream, " '%s'\n", uci_escape(ctx, opt->value));
272 }
273 }
274 fprintf(stream, "\n");
275 }
276
277 int uci_export(struct uci_context *ctx, FILE *stream, struct uci_package *package, bool header)
278 {
279 struct uci_element *e;
280
281 UCI_HANDLE_ERR(ctx);
282 UCI_ASSERT(ctx, stream != NULL);
283
284 if (package)
285 uci_export_package(package, stream, header);
286 else {
287 uci_foreach_element(&ctx->root, e) {
288 uci_export_package(uci_to_package(e), stream, header);
289 }
290 }
291
292 return 0;
293 }
294
295 int uci_import(struct uci_context *ctx, FILE *stream, const char *name, struct uci_package **package, bool single)
296 {
297 struct uci_parse_context *pctx;
298 UCI_HANDLE_ERR(ctx);
299
300 /* make sure no memory from previous parse attempts is leaked */
301 uci_cleanup(ctx);
302
303 uci_alloc_parse_context(ctx);
304 pctx = ctx->pctx;
305 pctx->file = stream;
306 if (*package && single) {
307 pctx->package = *package;
308 pctx->merge = true;
309 }
310
311 /*
312 * If 'name' was supplied, assume that the supplied stream does not contain
313 * the appropriate 'package <name>' string to specify the config name
314 * NB: the config file can still override the package name
315 */
316 if (name) {
317 UCI_ASSERT(ctx, uci_validate_str(name, false));
318 pctx->name = name;
319 }
320
321 while (!feof(pctx->file)) {
322 uci_getln(ctx, 0);
323 UCI_TRAP_SAVE(ctx, error);
324 if (pctx->buf[0])
325 uci_parse_line(ctx, single);
326 UCI_TRAP_RESTORE(ctx);
327 continue;
328 error:
329 if (ctx->flags & UCI_FLAG_PERROR)
330 uci_perror(ctx, NULL);
331 if ((ctx->err != UCI_ERR_PARSE) ||
332 (ctx->flags & UCI_FLAG_STRICT))
333 UCI_THROW(ctx, ctx->err);
334 }
335
336 uci_fixup_section(ctx, ctx->pctx->section);
337 if (!pctx->package && name)
338 uci_switch_config(ctx);
339 if (package)
340 *package = pctx->package;
341 if (pctx->merge)
342 pctx->package = NULL;
343
344 pctx->name = NULL;
345 uci_switch_config(ctx);
346
347 /* no error happened, we can get rid of the parser context now */
348 uci_cleanup(ctx);
349
350 return 0;
351 }
352
353
354 static char *uci_config_path(struct uci_context *ctx, const char *name)
355 {
356 char *filename;
357
358 UCI_ASSERT(ctx, uci_validate_str(name, false));
359 filename = uci_malloc(ctx, strlen(name) + strlen(ctx->confdir) + 2);
360 sprintf(filename, "%s/%s", ctx->confdir, name);
361
362 return filename;
363 }
364
365 void uci_file_commit(struct uci_context *ctx, struct uci_package **package, bool overwrite)
366 {
367 struct uci_package *p = *package;
368 FILE *f = NULL;
369 char *name = NULL;
370 char *path = NULL;
371
372 if (!p->path) {
373 if (overwrite)
374 p->path = uci_config_path(ctx, p->e.name);
375 else
376 UCI_THROW(ctx, UCI_ERR_INVAL);
377 }
378
379 /* open the config file for writing now, so that it is locked */
380 f = uci_open_stream(ctx, p->path, SEEK_SET, true, true);
381
382 /* flush unsaved changes and reload from history file */
383 UCI_TRAP_SAVE(ctx, done);
384 if (p->has_history) {
385 if (!overwrite) {
386 name = uci_strdup(ctx, p->e.name);
387 path = uci_strdup(ctx, p->path);
388 /* dump our own changes to the history file */
389 if (!uci_list_empty(&p->history))
390 UCI_INTERNAL(uci_save, ctx, p);
391
392 /*
393 * other processes might have modified the config
394 * as well. dump and reload
395 */
396 uci_free_package(&p);
397 uci_cleanup(ctx);
398 UCI_INTERNAL(uci_import, ctx, f, name, &p, true);
399
400 p->path = path;
401 p->has_history = true;
402 *package = p;
403
404 /* freed together with the uci_package */
405 path = NULL;
406
407 /* check for updated history, flush */
408 if (!uci_load_history(ctx, p, true))
409 goto done;
410 } else {
411 /* flush history */
412 if (!uci_load_history(ctx, NULL, true))
413 goto done;
414 }
415 }
416
417 rewind(f);
418 ftruncate(fileno(f), 0);
419
420 uci_export(ctx, f, p, false);
421 UCI_TRAP_RESTORE(ctx);
422
423 done:
424 if (name)
425 free(name);
426 if (path)
427 free(path);
428 uci_close_stream(f);
429 if (ctx->err)
430 UCI_THROW(ctx, ctx->err);
431 }
432
433
434 /*
435 * This function returns the filename by returning the string
436 * after the last '/' character. By checking for a non-'\0'
437 * character afterwards, directories are ignored (glob marks
438 * those with a trailing '/'
439 */
440 static inline char *get_filename(char *path)
441 {
442 char *p;
443
444 p = strrchr(path, '/');
445 p++;
446 if (!*p)
447 return NULL;
448 return p;
449 }
450
451 static char **uci_list_config_files(struct uci_context *ctx)
452 {
453 char **configs;
454 glob_t globbuf;
455 int size, i;
456 char *buf;
457 char *dir;
458
459 dir = uci_malloc(ctx, strlen(ctx->confdir) + 1 + sizeof("/*"));
460 sprintf(dir, "%s/*", ctx->confdir);
461 if (glob(dir, GLOB_MARK, NULL, &globbuf) != 0)
462 UCI_THROW(ctx, UCI_ERR_NOTFOUND);
463
464 size = sizeof(char *) * (globbuf.gl_pathc + 1);
465 for(i = 0; i < globbuf.gl_pathc; i++) {
466 char *p;
467
468 p = get_filename(globbuf.gl_pathv[i]);
469 if (!p)
470 continue;
471
472 size += strlen(p) + 1;
473 }
474
475 configs = uci_malloc(ctx, size);
476 buf = (char *) &configs[globbuf.gl_pathc + 1];
477 for(i = 0; i < globbuf.gl_pathc; i++) {
478 char *p;
479
480 p = get_filename(globbuf.gl_pathv[i]);
481 if (!p)
482 continue;
483
484 configs[i] = buf;
485 strcpy(buf, p);
486 buf += strlen(buf) + 1;
487 }
488 free(dir);
489 return configs;
490 }
491
492 static struct uci_package *uci_file_load(struct uci_context *ctx, const char *name)
493 {
494 struct uci_package *package = NULL;
495 char *filename;
496 bool confdir;
497 FILE *file = NULL;
498
499 switch (name[0]) {
500 case '.':
501 /* relative path outside of /etc/config */
502 if (name[1] != '/')
503 UCI_THROW(ctx, UCI_ERR_NOTFOUND);
504 /* fall through */
505 case '/':
506 /* absolute path outside of /etc/config */
507 filename = uci_strdup(ctx, name);
508 name = strrchr(name, '/') + 1;
509 confdir = false;
510 break;
511 default:
512 /* config in /etc/config */
513 filename = uci_config_path(ctx, name);
514 confdir = true;
515 break;
516 }
517
518 file = uci_open_stream(ctx, filename, SEEK_SET, false, false);
519 ctx->err = 0;
520 UCI_TRAP_SAVE(ctx, done);
521 UCI_INTERNAL(uci_import, ctx, file, name, &package, true);
522 UCI_TRAP_RESTORE(ctx);
523
524 if (package) {
525 package->path = filename;
526 package->has_history = confdir;
527 uci_load_history(ctx, package, false);
528 }
529
530 done:
531 uci_close_stream(file);
532 if (ctx->err)
533 UCI_THROW(ctx, ctx->err);
534 return package;
535 }
536
537 static UCI_BACKEND(uci_file_backend, "file",
538 .load = uci_file_load,
539 .commit = uci_file_commit,
540 .list_configs = uci_list_config_files,
541 );