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