add foreign key and list support for ucimap
[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_package(const char *str)
100 {
101 return uci_validate_str(str, false);
102 }
103
104 static inline bool uci_validate_type(const char *str)
105 {
106 return uci_validate_str(str, false);
107 }
108
109 static inline bool uci_validate_name(const char *str)
110 {
111 return uci_validate_str(str, true);
112 }
113
114 bool uci_validate_text(const char *str)
115 {
116 while (*str) {
117 if ((*str == '\r') || (*str == '\n') ||
118 ((*str < 32) && (*str != '\t')))
119 return false;
120 str++;
121 }
122 return true;
123 }
124
125 static void uci_alloc_parse_context(struct uci_context *ctx)
126 {
127 ctx->pctx = (struct uci_parse_context *) uci_malloc(ctx, sizeof(struct uci_parse_context));
128 }
129
130 int uci_parse_ptr(struct uci_context *ctx, struct uci_ptr *ptr, char *str)
131 {
132 char *last = NULL;
133 char *tmp;
134
135 UCI_HANDLE_ERR(ctx);
136 UCI_ASSERT(ctx, str);
137 UCI_ASSERT(ctx, ptr);
138
139 memset(ptr, 0, sizeof(struct uci_ptr));
140
141 /* value */
142 last = strchr(str, '=');
143 if (last) {
144 *last = 0;
145 last++;
146 ptr->value = last;
147 }
148
149 ptr->package = strsep(&str, ".");
150 if (!ptr->package)
151 goto error;
152
153 ptr->section = strsep(&str, ".");
154 if (!ptr->section) {
155 ptr->target = UCI_TYPE_PACKAGE;
156 goto lastval;
157 }
158
159 ptr->option = strsep(&str, ".");
160 if (!ptr->option) {
161 ptr->target = UCI_TYPE_SECTION;
162 goto lastval;
163 } else {
164 ptr->target = UCI_TYPE_OPTION;
165 }
166
167 tmp = strsep(&str, ".");
168 if (tmp)
169 goto error;
170
171 lastval:
172 if (ptr->package && !uci_validate_package(ptr->package))
173 goto error;
174 if (ptr->section && !uci_validate_name(ptr->section))
175 ptr->flags |= UCI_LOOKUP_EXTENDED;
176 if (ptr->option && !uci_validate_name(ptr->option))
177 goto error;
178 if (ptr->value && !uci_validate_text(ptr->value))
179 goto error;
180
181 return 0;
182
183 error:
184 memset(ptr, 0, sizeof(struct uci_ptr));
185 UCI_THROW(ctx, UCI_ERR_PARSE);
186 }
187
188
189 static void uci_parse_error(struct uci_context *ctx, char *pos, char *reason)
190 {
191 struct uci_parse_context *pctx = ctx->pctx;
192
193 pctx->reason = reason;
194 pctx->byte = pos - pctx->buf;
195 UCI_THROW(ctx, UCI_ERR_PARSE);
196 }
197
198
199 /*
200 * Fetch a new line from the input stream and resize buffer if necessary
201 */
202 static void uci_getln(struct uci_context *ctx, int offset)
203 {
204 struct uci_parse_context *pctx = ctx->pctx;
205 char *p;
206 int ofs;
207
208 if (pctx->buf == NULL) {
209 pctx->buf = uci_malloc(ctx, LINEBUF);
210 pctx->bufsz = LINEBUF;
211 }
212
213 ofs = offset;
214 do {
215 p = &pctx->buf[ofs];
216 p[ofs] = 0;
217
218 p = fgets(p, pctx->bufsz - ofs, pctx->file);
219 if (!p || !*p)
220 return;
221
222 ofs += strlen(p);
223 if (pctx->buf[ofs - 1] == '\n') {
224 pctx->line++;
225 pctx->buf[ofs - 1] = 0;
226 return;
227 }
228
229 if (pctx->bufsz > LINEBUF_MAX/2)
230 uci_parse_error(ctx, p, "line too long");
231
232 pctx->bufsz *= 2;
233 pctx->buf = uci_realloc(ctx, pctx->buf, pctx->bufsz);
234 } while (1);
235 }
236
237 /*
238 * parse a character escaped by '\'
239 * returns true if the escaped character is to be parsed
240 * returns false if the escaped character is to be ignored
241 */
242 static inline bool parse_backslash(struct uci_context *ctx, char **str)
243 {
244 /* skip backslash */
245 *str += 1;
246
247 /* undecoded backslash at the end of line, fetch the next line */
248 if (!**str) {
249 *str += 1;
250 uci_getln(ctx, *str - ctx->pctx->buf);
251 return false;
252 }
253
254 /* FIXME: decode escaped char, necessary? */
255 return true;
256 }
257
258 /*
259 * move the string pointer forward until a non-whitespace character or
260 * EOL is reached
261 */
262 static void skip_whitespace(struct uci_context *ctx, char **str)
263 {
264 restart:
265 while (**str && isspace(**str))
266 *str += 1;
267
268 if (**str == '\\') {
269 if (!parse_backslash(ctx, str))
270 goto restart;
271 }
272 }
273
274 static inline void addc(char **dest, char **src)
275 {
276 **dest = **src;
277 *dest += 1;
278 *src += 1;
279 }
280
281 /*
282 * parse a double quoted string argument from the command line
283 */
284 static void parse_double_quote(struct uci_context *ctx, char **str, char **target)
285 {
286 char c;
287
288 /* skip quote character */
289 *str += 1;
290
291 while ((c = **str)) {
292 switch(c) {
293 case '"':
294 **target = 0;
295 *str += 1;
296 return;
297 case '\\':
298 if (!parse_backslash(ctx, str))
299 continue;
300 /* fall through */
301 default:
302 addc(target, str);
303 break;
304 }
305 }
306 uci_parse_error(ctx, *str, "unterminated \"");
307 }
308
309 /*
310 * parse a single quoted string argument from the command line
311 */
312 static void parse_single_quote(struct uci_context *ctx, char **str, char **target)
313 {
314 char c;
315 /* skip quote character */
316 *str += 1;
317
318 while ((c = **str)) {
319 switch(c) {
320 case '\'':
321 **target = 0;
322 *str += 1;
323 return;
324 default:
325 addc(target, str);
326 }
327 }
328 uci_parse_error(ctx, *str, "unterminated '");
329 }
330
331 /*
332 * parse a string from the command line and detect the quoting style
333 */
334 static void parse_str(struct uci_context *ctx, char **str, char **target)
335 {
336 bool next = true;
337 do {
338 switch(**str) {
339 case '\'':
340 parse_single_quote(ctx, str, target);
341 break;
342 case '"':
343 parse_double_quote(ctx, str, target);
344 break;
345 case '#':
346 **str = 0;
347 /* fall through */
348 case 0:
349 goto done;
350 case ';':
351 next = false;
352 goto done;
353 case '\\':
354 if (!parse_backslash(ctx, str))
355 continue;
356 /* fall through */
357 default:
358 addc(target, str);
359 break;
360 }
361 } while (**str && !isspace(**str));
362 done:
363
364 /*
365 * if the string was unquoted and we've stopped at a whitespace
366 * character, skip to the next one, because the whitespace will
367 * be overwritten by a null byte here
368 */
369 if (**str && next)
370 *str += 1;
371
372 /* terminate the parsed string */
373 **target = 0;
374 }
375
376 /*
377 * extract the next argument from the command line
378 */
379 static char *next_arg(struct uci_context *ctx, char **str, bool required, bool name)
380 {
381 char *val;
382 char *ptr;
383
384 val = ptr = *str;
385 skip_whitespace(ctx, str);
386 if(*str[0] == ';') {
387 *str[0] = 0;
388 *str += 1;
389 } else {
390 parse_str(ctx, str, &ptr);
391 }
392 if (!*val) {
393 if (required)
394 uci_parse_error(ctx, *str, "insufficient arguments");
395 goto done;
396 }
397
398 if (name && !uci_validate_name(val))
399 uci_parse_error(ctx, val, "invalid character in field");
400
401 done:
402 return val;
403 }
404
405 int uci_parse_argument(struct uci_context *ctx, FILE *stream, char **str, char **result)
406 {
407 UCI_HANDLE_ERR(ctx);
408 UCI_ASSERT(ctx, str != NULL);
409 UCI_ASSERT(ctx, result != NULL);
410
411 if (ctx->pctx && (ctx->pctx->file != stream))
412 uci_cleanup(ctx);
413
414 if (!ctx->pctx)
415 uci_alloc_parse_context(ctx);
416
417 ctx->pctx->file = stream;
418
419 if (!*str) {
420 uci_getln(ctx, 0);
421 *str = ctx->pctx->buf;
422 }
423
424 *result = next_arg(ctx, str, false, false);
425
426 return 0;
427 }
428
429
430 /*
431 * open a stream and go to the right position
432 *
433 * note: when opening for write and seeking to the beginning of
434 * the stream, truncate the file
435 */
436 static FILE *uci_open_stream(struct uci_context *ctx, const char *filename, int pos, bool write, bool create)
437 {
438 struct stat statbuf;
439 FILE *file = NULL;
440 int fd, ret;
441 int mode = (write ? O_RDWR : O_RDONLY);
442
443 if (create)
444 mode |= O_CREAT;
445
446 if (!write && ((stat(filename, &statbuf) < 0) ||
447 ((statbuf.st_mode & S_IFMT) != S_IFREG))) {
448 UCI_THROW(ctx, UCI_ERR_NOTFOUND);
449 }
450
451 fd = open(filename, mode, UCI_FILEMODE);
452 if (fd < 0)
453 goto error;
454
455 if (flock(fd, (write ? LOCK_EX : LOCK_SH)) < 0)
456 goto error;
457
458 ret = lseek(fd, 0, pos);
459
460 if (ret < 0)
461 goto error;
462
463 file = fdopen(fd, (write ? "w+" : "r"));
464 if (file)
465 goto done;
466
467 error:
468 UCI_THROW(ctx, UCI_ERR_IO);
469 done:
470 return file;
471 }
472
473 static void uci_close_stream(FILE *stream)
474 {
475 int fd;
476
477 if (!stream)
478 return;
479
480 fd = fileno(stream);
481 flock(fd, LOCK_UN);
482 fclose(stream);
483 }
484
485