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