2 * libuci - Library for the Unified Configuration Interface
3 * Copyright (C) 2008 Felix Fietkau <nbd@openwrt.org>
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
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.
16 * This file contains some common code for the uci library
20 #include <sys/types.h>
28 static const char *uci_confdir = UCI_CONFDIR;
29 static const char *uci_savedir = UCI_SAVEDIR;
31 static const char *uci_errstr[] = {
33 [UCI_ERR_MEM] = "Out of memory",
34 [UCI_ERR_INVAL] = "Invalid argument",
35 [UCI_ERR_NOTFOUND] = "Entry not found",
36 [UCI_ERR_IO] = "I/O error",
37 [UCI_ERR_PARSE] = "Parse error",
38 [UCI_ERR_DUPLICATE] = "Duplicate entry",
39 [UCI_ERR_UNKNOWN] = "Unknown error",
46 /* exported functions */
47 struct uci_context *uci_alloc_context(void)
49 struct uci_context *ctx;
51 ctx = (struct uci_context *) malloc(sizeof(struct uci_context));
52 memset(ctx, 0, sizeof(struct uci_context));
53 uci_list_init(&ctx->root);
54 ctx->flags = UCI_FLAG_STRICT;
56 ctx->confdir = (char *) uci_confdir;
57 ctx->savedir = (char *) uci_savedir;
62 void uci_free_context(struct uci_context *ctx)
64 struct uci_element *e, *tmp;
66 if (ctx->confdir != uci_confdir)
68 if (ctx->savedir != uci_savedir)
71 UCI_TRAP_SAVE(ctx, ignore);
73 uci_foreach_element_safe(&ctx->root, tmp, e) {
74 struct uci_package *p = uci_to_package(e);
78 UCI_TRAP_RESTORE(ctx);
84 int uci_set_confdir(struct uci_context *ctx, char *dir)
86 dir = uci_strdup(ctx, dir);
87 if (ctx->confdir != uci_confdir)
93 int uci_set_savedir(struct uci_context *ctx, char *dir)
95 dir = uci_strdup(ctx, dir);
96 if (ctx->savedir != uci_savedir)
102 int uci_cleanup(struct uci_context *ctx)
105 uci_file_cleanup(ctx);
109 void uci_perror(struct uci_context *ctx, const char *prefix)
118 if ((err < 0) || (err >= UCI_ERR_LAST))
119 err = UCI_ERR_UNKNOWN;
122 fprintf(stderr, "%s: ", prefix);
124 fprintf(stderr, "%s: ", ctx->func);
129 fprintf(stderr, "%s (%s) at line %d, byte %d\n", uci_errstr[err], (ctx->pctx->reason ? ctx->pctx->reason : "unknown"), ctx->pctx->line, ctx->pctx->byte);
134 fprintf(stderr, "%s\n", uci_errstr[err]);