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