1 /*-*- Mode: C; c-basic-offset: 8; indent-tabs-mode: nil -*-*/
6 * Copyright (c) 2014 Samsung Electronics Co., Ltd.
8 * Licensed under the Apache License, Version 2.0 (the License);
9 * you may not use this file except in compliance with the License.
10 * You may obtain a copy of the License at
12 * http://www.apache.org/licenses/LICENSE-2.0
14 * Unless required by applicable law or agreed to in writing, software
15 * distributed under the License is distributed on an "AS IS" BASIS,
16 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
17 * See the License for the specific language governing permissions and
18 * limitations under the License.
28 #include "libsystem.h"
29 #include "config-parser.h"
31 #define MAX_SECTION 64
33 static int config_table_lookup(
37 ConfigParserCallback *func,
49 for (t = table; t->lvalue; t++) {
51 if (!streq(lvalue, t->lvalue))
54 if (!streq_ptr(section, t->section))
66 /* Run the user supplied parser for an assignment */
67 static int config_parse_table(
75 ConfigParserCallback cb = NULL;
85 r = config_table_lookup(table,
107 const char *filename,
110 _cleanup_fclose_ FILE *f = NULL;
111 char *sections[MAX_SECTION] = { 0 };
112 char *section = NULL, *n, *e, l[LINE_MAX];
114 int i, r, num_section = 0;
120 f = fopen(filename, "r");
125 _cleanup_free_ char *lvalue = NULL, *rvalue = NULL;
127 if (fgets(l, LINE_MAX, f) == NULL) {
138 if (strchr(COMMENTS NEWLINE, *l))
143 if (l[len-1] != ']') {
148 n = strndup(l+1, len-2);
155 for (i = 0; i < num_section; i++) {
156 if (streq(n, sections[i])) {
157 section = sections[i];
168 sections[num_section] = n;
170 if (num_section > MAX_SECTION) {
185 r = strndup_strip(l, e - l, &lvalue);
189 r = strdup_strip(e + 1, &rvalue);
193 r = config_parse_table(filename,
206 for (i=0; i<num_section; i++)
213 int config_parse_dir(const char *dir, ConfigParseFunc fp, void *data) {
214 _cleanup_closedir_ DIR *d = NULL;
221 FOREACH_DIRENT(de, d, return -errno) {
222 _cleanup_free_ char *path = NULL;
225 if (de->d_type != DT_REG)
228 r = asprintf(&path, "%s/%s", dir, de->d_name);
232 /* Do not just break loop until parse all file of
233 * dir. ignore return */
234 (void) fp(path, data);
240 int config_parse_int(
241 const char *filename,
256 if (!is_number(rvalue, strlen(rvalue)))
264 int config_parse_bool(
265 const char *filename,
281 k = parse_boolean(rvalue);
289 int config_parse_string(
290 const char *filename,
319 int config_parse_bytes(
320 const char *filename,
328 size_t *ss = data, s = 0;
339 r = parse_bytes(rvalue, &s);