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