English Language flag
// Log In
// CVSweb
Project: FreeWRT
// Summary // Activity // Search // Tracker // Lists // News // SCM // Wiki

SCM Repository

ViewVC logotype

Contents of /branches/common-nfo/tools/nfotiser/parser.c

Parent Directory Parent Directory | Revision Log Revision Log


Revision 3461 - (show annotations) (download)
Thu Aug 9 14:53:21 2007 UTC (6 years, 6 months ago) by tg
File MIME type: text/plain
File size: 10124 byte(s)
• new keyword type MULTITOP = multi + optional iterator
• change a little in the data types to match spec and nfo draft
• fix a double free while here: str_[n]add() does realloc, no need to free

1 /* $FreeWRT: src/share/misc/licence.template,v 1.20 2006/12/11 21:04:56 tg Rel $ */
2
3 /*-
4 * Copyright (c) 2007
5 * Thorsten Glaser <tg@mirbsd.de>
6 *
7 * Provided that these terms and disclaimer and all copyright notices
8 * are retained or reproduced in an accompanying document, permission
9 * is granted to deal in this work without restriction, including un-
10 * limited rights to use, publicly perform, distribute, sell, modify,
11 * merge, give away, or sublicence.
12 *
13 * Advertising materials mentioning features or use of this work must
14 * display the following acknowledgement:
15 * This product includes material provided by Thorsten Glaser.
16 * This acknowledgement does not need to be reprinted if this work is
17 * linked into a bigger work whose licence does not allow such clause
18 * and the author of this work is given due credit in the bigger work
19 * or its accompanying documents, where such information is generally
20 * kept, provided that said credits are retained.
21 *
22 * This work is provided "AS IS" and WITHOUT WARRANTY of any kind, to
23 * the utmost extent permitted by applicable law, neither express nor
24 * implied; without malicious intent or gross negligence. In no event
25 * may a licensor, author or contributor be held liable for indirect,
26 * direct, other damage, loss, or other issues arising in any way out
27 * of dealing in the work, even if advised of the possibility of such
28 * damage or existence of a defect, except proven that it results out
29 * of said person's immediate fault when using the work as intended.
30 */
31
32 #include <sys/param.h>
33 #include <sys/mman.h>
34 #include <sys/stat.h>
35
36 #include <err.h>
37 #include <errno.h>
38 #include <stdarg.h>
39 #include <stdint.h>
40 #include <stdio.h>
41 #include <stdlib.h>
42 #include <string.h>
43
44 #include "nfotiser.h"
45
46 static void syntaxerr_(size_t, const char *, ...)
47 __attribute__((format (printf, 2, 3)))
48 __attribute__((noreturn));
49 #define syntaxerr(fmt, ...) syntaxerr_(lineno, (fmt), ##__VA_ARGS__)
50
51 /*
52 * Parsing works as follows:
53 *
54 * - strip completely empty line
55 * - strip line beginning with hash mark
56 * - if line ends with backslash, get next line that is not
57 * + empty
58 * + beginning with a hash mark
59 * and look if it begins with a tab (if not: syntax error)
60 * if so, strip backslash + newline + tab and repeat
61 * - if line begins with a tab, strip it and append line to
62 * the last line, including the newline separator
63 * - match line with '([A-Za-z_][A-Za-z0-9_]*)\t(.*)$' and
64 * call \1 the key and \2 the value (else: syntax error)
65 * - uppercase the key
66 * - enter the key/value pair in the system
67 *
68 * The following is also part of parsing, but left to the caller:
69 * - replace ${foo} with the value of key "foo"
70 * - undouble all backslashes
71 *
72 * We enter the key into the system up to three-fold:
73 * - KWT_NORMAL => ([A-Za-z_][A-Za-z0-9_]*)
74 * + \1 = keyword (toupper'd)
75 * - KWT_MULTI => ([A-Za-z_][A-Za-z0-9_]*)_([A-Za-z0-9_]*)
76 * + \1 = keyword (toupper'd)
77 * + \2 = kw_multi (case preserving)
78 * - KWT_ITERATED => ([A-Za-z_][A-Za-z0-9_]*)_([0-9]*)
79 * + \1 = keyword (toupper'd)
80 * + \2 = kw_iter (unsigned integer value)
81 * - KWT_MULTITER => ([A-Za-z_][A-Za-z0-9_]*)_([0-9]*)_([A-Za-z0-9_]*)
82 * + \1 = keyword (toupper'd)
83 * + \2 = kw_iter (unsigned integer value)
84 * + \3 = kw_multi (case preserving)
85 * - KWT_MULTITOP => ([A-Za-z_][A-Za-z0-9_]*)_(([0-9]*)_)?([A-Za-z0-9_]*)
86 * + \1 = keyword (toupper'd)
87 * + \2 = kw_iter (unsigned integer value), 0 if not set
88 * + \3 = kw_multi (case preserving)
89 *
90 * Cf. https://www.freewrt.org/trac/wiki/Documentation/Specs/Freewrt_info_files
91 * for more examples and a more human-readable version of this specification.
92 */
93
94 struct parser_result *
95 nfo_parse(int fd, const struct parser_keywords *kws)
96 {
97 struct parser_result *res;
98 struct parser_res *entry;
99 const struct parser_keywords *kwp;
100 char *cp, *t, *tp, *buf, *buf_base;
101 size_t len, n, lineno = 0;
102 struct stat sb;
103 char *entry_multi;
104 unsigned entry_iter;
105
106 res = xmalloc(sizeof (struct parser_result));
107 CIRCLEQ_INIT(res);
108
109 if (fstat(fd, &sb))
110 err(255, "cannot stat");
111
112 /* slurp whole file into mapped memory */
113 len = sb.st_size;
114 D(2, "trying to mmap %zu bytes...", len);
115 if ((cp = mmap(NULL, len, PROT_READ, MAP_FILE, fd, 0)) == MAP_FAILED)
116 err(255, "cannot mmap %zu bytes", len);
117 D(2, "ok\n");
118 /* make a nice NUL-terminated copy (malloc'd) */
119 D(2, "copying %zu bytes...", len);
120 buf = buf_base = str_nsave(cp, len);
121 D(2, " munmap...");
122 if (munmap(cp, len))
123 err(255, "cannot munmap");
124 D(2, "ok\n");
125 /* don't need the file any more */
126
127 /* now we can operate on the NUL-terminated R/W string “buf” */
128 if (buf[len - 1] != '\n')
129 syntaxerr("file does not end with a newline!");
130
131 D(2, "entire string: «%s» (%zu)\n", buf, strlen(buf));
132 lineno = 1;
133
134 loop_newline:
135 /* completely new line buffer */
136 cp = NULL;
137
138 loop_getline:
139 /* get a line and add it to line buffer */
140 if (*buf == '\0') {
141 D(2, "D: [%4zu] read EOF\n", lineno);
142 goto loop_eof;
143 }
144 if (*buf == '\n') {
145 D(2, "D: [%4zu] read newline\n", lineno);
146 ++buf;
147 ++lineno;
148 goto loop_getline;
149 }
150 if (*buf == '#') {
151 D(2, "D: [%4zu] read comment ", lineno);
152 t = buf;
153 while (*t != '\n')
154 ++t;
155 *t++ = '\0';
156 D(2, "'%s'\n", buf);
157 buf = t;
158 ++lineno;
159 goto loop_getline;
160 }
161 if (*buf == '\t') {
162 D(2, "D: [%4zu] read trail line\n", lineno);
163 if (cp == NULL)
164 syntaxerr("expected lead line, got trail line!");
165 t = ++buf;
166 goto loop_storeline;
167 } else {
168 D(2, "D: [%4zu] read head line (%02X)\n", lineno, *buf);
169 }
170 if (cp != NULL) {
171 --lineno;
172 goto process_line;
173 }
174 if ((*buf >= 'A' && *buf <= 'Z') ||
175 (*buf >= 'a' && *buf <= 'z') || *buf == '_')
176 t = buf;
177 else
178 syntaxerr("line must begin with a letter or an underscore!");
179 loop_storeline:
180 while (*t++ != '\n')
181 ;
182 t = str_nsave(buf, (tp = t) - buf);
183 buf = tp;
184 if (cp != NULL) {
185 if (*(tp = cp + strlen(cp) - 2) == '\\')
186 *tp = '\0';
187 }
188 tp = t + strlen(t) - 1;
189 *tp = '\0';
190 D(2, "D: [%4zu] storing string '%s'\n", lineno, t);
191 *tp = '\n';
192 tp = str_add(cp, t);
193 free(t);
194 cp = tp;
195 ++lineno;
196 goto loop_getline;
197 process_line:
198 /* cp points to <line>[<nl><line>…][\]<nl> */
199 /* buf points to first byte of next line */
200 if (*(tp = cp + strlen(cp) - 2) == '\\')
201 syntaxerr("expected trail line, got lead line!");
202 process_lastline:
203 /* cut off final newline */
204 *++tp = '\0';
205 D(2, "D: [%4zu] processing «%s»\n", lineno, cp);
206
207 /* parse the meat out of there */
208 if ((tp = strchr(cp, '\t')) == NULL)
209 syntaxerr("expected keyword + tab + value!");
210 *tp++ = '\0';
211 /* cp points to keyword, tp points to value */
212 entry_multi = NULL;
213 entry_iter = 0;
214 for (kwp = kws; kwp->kwprefix != NULL; ++kwp) {
215 char *np;
216
217 /* exact match? */
218 if (!strcasecmp(cp, kwp->kwprefix))
219 /* yepp */ break;
220 /* prefix match allowed? */
221 if (kwp->kwtype == KWT_NORMAL)
222 /* nope */ continue;
223 /* prefix match? */
224 if (strncasecmp(cp, kwp->kwprefix, n = strlen(kwp->kwprefix)))
225 /* nope */ continue;
226 if (cp[n] != '_')
227 /* same */ continue;
228 /* okay, we got a prefix match, get args */
229 np = cp + n + 1;
230 if (kwp->kwtype == KWT_ITERATED ||
231 (kwp->kwtype == KWT_MULTITOP &&
232 (*np >= '0' && *np <= '9')) ||
233 kwp->kwtype == KWT_MULTITER) {
234 char *zp = np;
235
236 if (zp[0] == '0' && (zp[1] == 'x' || zp[1] == 'X'))
237 zp += 2;
238 while (*zp >= '0' && *zp <= '9')
239 ++zp;
240 if (zp == np)
241 syntaxerr("iterator expected");
242 if (*zp != (char)(kwp->kwtype == KWT_ITERATED ?
243 '\0' : '_'))
244 syntaxerr("%s expected, got 0x%02X",
245 kwp->kwtype == KWT_ITERATED ?
246 "tab" : "underscore", *zp);
247 *zp++ = '\0';
248 entry_iter = (unsigned)strtoul(np, NULL, 0);
249 np = zp;
250 }
251 if (kwp->kwtype == KWT_MULTI ||
252 kwp->kwtype == KWT_MULTITOP ||
253 kwp->kwtype == KWT_MULTITER)
254 entry_multi = str_save(np);
255 /* values filled out */
256 break;
257 }
258 if (kwp->kwprefix == NULL)
259 errx(1, "unknown keyword '%s'", cp);
260 entry = xmalloc(sizeof (struct parser_res));
261 bzero(entry, sizeof (struct parser_res));
262 entry->keyword = kwp->kwnum;
263 entry->kw_multi = entry_multi;
264 entry->kw_iter = entry_iter;
265 entry->value = str_save(tp);
266 CIRCLEQ_INSERT_TAIL(res, entry, e);
267 free(cp);
268 ++lineno;
269 goto loop_newline;
270 loop_eof:
271 if (cp != NULL) {
272 if (*(tp = cp + strlen(cp) - 2) == '\\')
273 syntaxerr("expected trail line, read end of file!");
274 goto process_lastline;
275 }
276 free(buf_base);
277 return (res);
278 }
279
280 const struct parser_keywords *
281 parser_getkwbynum(parser_kwords num, const struct parser_keywords *kws)
282 {
283 const struct parser_keywords *kwp;
284
285 for (kwp = kws; kwp->kwprefix != NULL; ++kwp)
286 if (kwp->kwnum == num)
287 break;
288
289 return (kwp->kwprefix == NULL ? NULL : kwp);
290 }
291
292 void
293 parser_dump(struct parser_res *entry, const struct parser_keywords *kws)
294 {
295 const struct parser_keywords *kwp;
296
297 kwp = parser_getkwbynum(entry->keyword, kws);
298 printf("keyword %s (type %s)",
299 kwp == NULL ? "<unknown>" : kwp->kwprefix,
300 kwp == NULL ? "invalid" :
301 kwp->kwtype == KWT_NORMAL ? "normal" :
302 kwp->kwtype == KWT_MULTI ? "multi" :
303 kwp->kwtype == KWT_ITERATED ? "iterated" :
304 kwp->kwtype == KWT_MULTITER ? "multiter" :
305 kwp->kwtype == KWT_MULTITOP ? "multitop" : "unknown");
306 if (kwp) {
307 if (kwp->kwtype == KWT_ITERATED ||
308 kwp->kwtype == KWT_MULTITOP ||
309 kwp->kwtype == KWT_MULTITER)
310 printf(", iterator %u", entry->kw_iter);
311 if (kwp->kwtype == KWT_MULTI ||
312 kwp->kwtype == KWT_MULTITOP ||
313 kwp->kwtype == KWT_MULTITER)
314 printf(", multival '%s'", entry->kw_multi);
315 }
316 putchar('\n');
317 }
318
319 void
320 parser_free(struct parser_result *head)
321 {
322 struct parser_res *entry;
323
324 if (head == NULL)
325 return;
326
327 while (!CIRCLEQ_EMPTY(head)) {
328 entry = CIRCLEQ_FIRST(head);
329 CIRCLEQ_REMOVE(head, entry, e);
330 if (entry->kw_multi != NULL)
331 free(entry->kw_multi);
332 if (entry->value != NULL)
333 free(entry->value);
334 free(entry);
335 }
336
337 free(head);
338 }
339
340 static void
341 syntaxerr_(size_t lno, const char *fmt, ...)
342 {
343 va_list args;
344
345 va_start(args, fmt);
346 fflush(NULL);
347 fprintf(stderr, "syntax error [%4zu]: ", lno);
348 fflush(NULL);
349 verrx(1, fmt, args);
350 va_end(args);
351 }

root@freewrt.org:443
ViewVC Help
Powered by ViewVC 1.1.20