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