Fix uci show for sections and options.
[project/uci.git] / util.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 misc utility functions and wrappers to standard
17 * functions, which throw exceptions upon failure.
18 */
19 #include <sys/types.h>
20 #include <sys/stat.h>
21 #include <sys/file.h>
22 #include <stdbool.h>
23 #include <unistd.h>
24 #include <ctype.h>
25 #include <fcntl.h>
26
27 #define LINEBUF 32
28 #define LINEBUF_MAX 4096
29
30 __plugin void *uci_malloc(struct uci_context *ctx, size_t size)
31 {
32 void *ptr;
33
34 ptr = malloc(size);
35 if (!ptr)
36 UCI_THROW(ctx, UCI_ERR_MEM);
37 memset(ptr, 0, size);
38
39 return ptr;
40 }
41
42 __plugin void *uci_realloc(struct uci_context *ctx, void *ptr, size_t size)
43 {
44 ptr = realloc(ptr, size);
45 if (!ptr)
46 UCI_THROW(ctx, UCI_ERR_MEM);
47
48 return ptr;
49 }
50
51 __plugin char *uci_strdup(struct uci_context *ctx, const char *str)
52 {
53 char *ptr;
54
55 ptr = strdup(str);
56 if (!ptr)
57 UCI_THROW(ctx, UCI_ERR_MEM);
58
59 return ptr;
60 }
61
62 /* Based on an efficient hash function published by D. J. Bernstein */
63 static unsigned int djbhash(unsigned int hash, char *str)
64 {
65 int len = strlen(str);
66 int i;
67
68 /* initial value */
69 if (hash == ~0)
70 hash = 5381;
71
72 for(i = 0; i < len; i++) {
73 hash = ((hash << 5) + hash) + str[i];
74 }
75 return (hash & 0x7FFFFFFF);
76 }
77
78 /*
79 * validate strings for names and types, reject special characters
80 * for names, only alphanum and _ is allowed (shell compatibility)
81 * for types, we allow more characters
82 */
83 __plugin bool uci_validate_str(const char *str, bool name)
84 {
85 if (!*str)
86 return false;
87
88 while (*str) {
89 char c = *str;
90 if (!isalnum(c) && c != '_') {
91 if (name || (c < 33) || (c > 126))
92 return false;
93 }
94 str++;
95 }
96 return true;
97 }
98
99 static inline bool uci_validate_name(const char *str)
100 {
101 return uci_validate_str(str, true);
102 }
103
104 static inline bool uci_validate_text(const char *str)
105 {
106 while (*str) {
107 if ((*str == '\r') || (*str == '\n') ||
108 ((*str < 32) && (*str != '\t')))
109 return false;
110 str++;
111 }
112 return true;
113 }
114
115 static void uci_alloc_parse_context(struct uci_context *ctx)
116 {
117 ctx->pctx = (struct uci_parse_context *) uci_malloc(ctx, sizeof(struct uci_parse_context));
118 }
119
120 int uci_parse_tuple(struct uci_context *ctx, char *str, char **package, char **section, char **option, char **value)
121 {
122 char *last = NULL;
123
124 UCI_HANDLE_ERR(ctx);
125 UCI_ASSERT(ctx, str && package && section && option);
126
127 last = strchr(str, '=');
128 if (last) {
129 *last = 0;
130 last++;
131 }
132
133 *package = strsep(&str, ".");
134 if (!*package || !uci_validate_str(*package, false))
135 goto error;
136
137 *section = strsep(&str, ".");
138 *option = NULL;
139 if (value)
140 *value = NULL;
141 if (!*section)
142 goto lastval;
143
144 *option = strsep(&str, ".");
145 if (!*option)
146 goto lastval;
147
148 lastval:
149 if (last) {
150 if (!value)
151 goto error;
152
153 if (!*last)
154 goto error;
155 *value = last;
156 }
157
158 if (*section && *section[0] && !uci_validate_name(*section))
159 goto error;
160 if (*option && !uci_validate_name(*option))
161 goto error;
162 if (value && *value && !uci_validate_text(*value))
163 goto error;
164
165 goto done;
166
167 error:
168 UCI_THROW(ctx, UCI_ERR_PARSE);
169
170 done:
171 return 0;
172 }
173
174
175 static void uci_parse_error(struct uci_context *ctx, char *pos, char *reason)
176 {
177 struct uci_parse_context *pctx = ctx->pctx;
178
179 pctx->reason = reason;
180 pctx->byte = pos - pctx->buf;
181 UCI_THROW(ctx, UCI_ERR_PARSE);
182 }
183
184
185 /*
186 * Fetch a new line from the input stream and resize buffer if necessary
187 */
188 static void uci_getln(struct uci_context *ctx, int offset)
189 {
190 struct uci_parse_context *pctx = ctx->pctx;
191 char *p;
192 int ofs;
193
194 if (pctx->buf == NULL) {
195 pctx->buf = uci_malloc(ctx, LINEBUF);
196 pctx->bufsz = LINEBUF;
197 }
198
199 ofs = offset;
200 do {
201 p = &pctx->buf[ofs];
202 p[ofs] = 0;
203
204 p = fgets(p, pctx->bufsz - ofs, pctx->file);
205 if (!p || !*p)
206 return;
207
208 ofs += strlen(p);
209 if (pctx->buf[ofs - 1] == '\n') {
210 pctx->line++;
211 pctx->buf[ofs - 1] = 0;
212 return;
213 }
214
215 if (pctx->bufsz > LINEBUF_MAX/2)
216 uci_parse_error(ctx, p, "line too long");
217
218 pctx->bufsz *= 2;
219 pctx->buf = uci_realloc(ctx, pctx->buf, pctx->bufsz);
220 } while (1);
221 }
222
223 /*
224 * parse a character escaped by '\'
225 * returns true if the escaped character is to be parsed
226 * returns false if the escaped character is to be ignored
227 */
228 static inline bool parse_backslash(struct uci_context *ctx, char **str)
229 {
230 /* skip backslash */
231 *str += 1;
232
233 /* undecoded backslash at the end of line, fetch the next line */
234 if (!**str) {
235 *str += 1;
236 uci_getln(ctx, *str - ctx->pctx->buf);
237 return false;
238 }
239
240 /* FIXME: decode escaped char, necessary? */
241 return true;
242 }
243
244 /*
245 * move the string pointer forward until a non-whitespace character or
246 * EOL is reached
247 */
248 static void skip_whitespace(struct uci_context *ctx, char **str)
249 {
250 restart:
251 while (**str && isspace(**str))
252 *str += 1;
253
254 if (**str == '\\') {
255 if (!parse_backslash(ctx, str))
256 goto restart;
257 }
258 }
259
260 static inline void addc(char **dest, char **src)
261 {
262 **dest = **src;
263 *dest += 1;
264 *src += 1;
265 }
266
267 /*
268 * parse a double quoted string argument from the command line
269 */
270 static void parse_double_quote(struct uci_context *ctx, char **str, char **target)
271 {
272 char c;
273
274 /* skip quote character */
275 *str += 1;
276
277 while ((c = **str)) {
278 switch(c) {
279 case '"':
280 **target = 0;
281 *str += 1;
282 return;
283 case '\\':
284 if (!parse_backslash(ctx, str))
285 continue;
286 /* fall through */
287 default:
288 addc(target, str);
289 break;
290 }
291 }
292 uci_parse_error(ctx, *str, "unterminated \"");
293 }
294
295 /*
296 * parse a single quoted string argument from the command line
297 */
298 static void parse_single_quote(struct uci_context *ctx, char **str, char **target)
299 {
300 char c;
301 /* skip quote character */
302 *str += 1;
303
304 while ((c = **str)) {
305 switch(c) {
306 case '\'':
307 **target = 0;
308 *str += 1;
309 return;
310 default:
311 addc(target, str);
312 }
313 }
314 uci_parse_error(ctx, *str, "unterminated '");
315 }
316
317 /*
318 * parse a string from the command line and detect the quoting style
319 */
320 static void parse_str(struct uci_context *ctx, char **str, char **target)
321 {
322 bool next = true;
323 do {
324 switch(**str) {
325 case '\'':
326 parse_single_quote(ctx, str, target);
327 break;
328 case '"':
329 parse_double_quote(ctx, str, target);
330 break;
331 case '#':
332 **str = 0;
333 /* fall through */
334 case 0:
335 goto done;
336 case ';':
337 next = false;
338 goto done;
339 case '\\':
340 if (!parse_backslash(ctx, str))
341 continue;
342 /* fall through */
343 default:
344 addc(target, str);
345 break;
346 }
347 } while (**str && !isspace(**str));
348 done:
349
350 /*
351 * if the string was unquoted and we've stopped at a whitespace
352 * character, skip to the next one, because the whitespace will
353 * be overwritten by a null byte here
354 */
355 if (**str && next)
356 *str += 1;
357
358 /* terminate the parsed string */
359 **target = 0;
360 }
361
362 /*
363 * extract the next argument from the command line
364 */
365 static char *next_arg(struct uci_context *ctx, char **str, bool required, bool name)
366 {
367 char *val;
368 char *ptr;
369
370 val = ptr = *str;
371 skip_whitespace(ctx, str);
372 if(*str[0] == ';') {
373 *str[0] = 0;
374 *str += 1;
375 } else {
376 parse_str(ctx, str, &ptr);
377 }
378 if (!*val) {
379 if (required)
380 uci_parse_error(ctx, *str, "insufficient arguments");
381 goto done;
382 }
383
384 if (name && !uci_validate_name(val))
385 uci_parse_error(ctx, val, "invalid character in field");
386
387 done:
388 return val;
389 }
390
391 int uci_parse_argument(struct uci_context *ctx, FILE *stream, char **str, char **result)
392 {
393 UCI_HANDLE_ERR(ctx);
394 UCI_ASSERT(ctx, str != NULL);
395 UCI_ASSERT(ctx, result != NULL);
396
397 if (ctx->pctx) {
398 if (ctx->pctx->file != stream) {
399 uci_cleanup(ctx);
400 }
401 } else {
402 uci_alloc_parse_context(ctx);
403 ctx->pctx->file = stream;
404 }
405 if (!*str) {
406 uci_getln(ctx, 0);
407 *str = ctx->pctx->buf;
408 }
409
410 *result = next_arg(ctx, str, false, false);
411
412 return 0;
413 }
414
415
416 /*
417 * open a stream and go to the right position
418 *
419 * note: when opening for write and seeking to the beginning of
420 * the stream, truncate the file
421 */
422 static FILE *uci_open_stream(struct uci_context *ctx, const char *filename, int pos, bool write, bool create)
423 {
424 struct stat statbuf;
425 FILE *file = NULL;
426 int fd, ret;
427 int mode = (write ? O_RDWR : O_RDONLY);
428
429 if (create)
430 mode |= O_CREAT;
431
432 if (!write && ((stat(filename, &statbuf) < 0) ||
433 ((statbuf.st_mode & S_IFMT) != S_IFREG))) {
434 UCI_THROW(ctx, UCI_ERR_NOTFOUND);
435 }
436
437 fd = open(filename, mode, UCI_FILEMODE);
438 if (fd < 0)
439 goto error;
440
441 if (flock(fd, (write ? LOCK_EX : LOCK_SH)) < 0)
442 goto error;
443
444 ret = lseek(fd, 0, pos);
445
446 if (ret < 0)
447 goto error;
448
449 file = fdopen(fd, (write ? "w+" : "r"));
450 if (file)
451 goto done;
452
453 error:
454 UCI_THROW(ctx, UCI_ERR_IO);
455 done:
456 return file;
457 }
458
459 static void uci_close_stream(FILE *stream)
460 {
461 int fd;
462
463 if (!stream)
464 return;
465
466 fd = fileno(stream);
467 flock(fd, LOCK_UN);
468 fclose(stream);
469 }
470
471