f5aad020da387d5a19aee69faf63608a31aff4b2
[project/mountd.git] / uci.c
1 /*
2 * This program is free software; you can redistribute it and/or modify
3 * it under the terms of the GNU General Public License as published by
4 * the Free Software Foundation; either version 2 of the License, or
5 * (at your option) any later version.
6 *
7 * This program is distributed in the hope that it will be useful,
8 * but WITHOUT ANY WARRANTY; without even the implied warranty of
9 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
10 * GNU General Public License for more details.
11 *
12 * You should have received a copy of the GNU General Public License
13 * along with this program; if not, write to the Free Software
14 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307, USA.
15 *
16 * Provided by fon.com
17 * Copyright (C) 2008 John Crispin <blogic@openwrt.org>
18 */
19
20 #include <string.h>
21 #include <stdlib.h>
22
23 #include "include/log.h"
24 #include <uci.h>
25
26 struct uci_package *p = NULL;
27
28 struct uci_context* uci_init(char *config_file)
29 {
30 struct uci_context *ctx = uci_alloc_context();
31 uci_add_delta_path(ctx, "/var/state");
32 if(uci_load(ctx, config_file, &p) != UCI_OK)
33 {
34 log_printf("/etc/config/%s is missing or corrupt\n", config_file);
35 exit(-1);
36 }
37 return ctx;
38 }
39
40 void uci_cleanup(struct uci_context *ctx)
41 {
42 uci_unload(ctx, p);
43 uci_free_context(ctx);
44 }
45
46 void uci_save_state(struct uci_context *ctx)
47 {
48 uci_save(ctx, p);
49 }
50
51 char* uci_get_option(struct uci_context *ctx, char *section, char *option)
52 {
53 struct uci_element *e = NULL;
54 char *value = NULL;
55 struct uci_ptr ptr;
56
57 memset(&ptr, 0, sizeof(ptr));
58 ptr.package = p->e.name;
59 ptr.section = section;
60 ptr.option = option;
61 if (uci_lookup_ptr(ctx, &ptr, NULL, true) != UCI_OK)
62 return NULL;
63
64 if (!(ptr.flags & UCI_LOOKUP_COMPLETE))
65 return NULL;
66
67 e = ptr.last;
68 switch (e->type)
69 {
70 case UCI_TYPE_SECTION:
71 value = uci_to_section(e)->type;
72 break;
73 case UCI_TYPE_OPTION:
74 switch(ptr.o->type) {
75 case UCI_TYPE_STRING:
76 value = ptr.o->v.string;
77 break;
78 default:
79 value = NULL;
80 break;
81 }
82 break;
83 default:
84 return 0;
85 }
86
87 return value;
88 }
89
90 int uci_get_option_int(struct uci_context *ctx, char *section, char *option, int def)
91 {
92 char *tmp = uci_get_option(ctx, section, option);
93 int ret = def;
94
95 if (tmp)
96 ret = atoi(tmp);
97 return ret;
98 }
99
100 void uci_for_each_section_type(char *type, void (*cb)(char*, void*), void *priv)
101 {
102 struct uci_element *e;
103
104 uci_foreach_element(&p->sections, e)
105 if (!strcmp(type, uci_to_section(e)->type))
106 cb(e->name, priv);
107 }