xref: /openbsd-src/usr.sbin/dhcpd/parse.c (revision ca61718500ebd5b13a6bcb2b27c9b4a777be8857)
1 /*	$OpenBSD: parse.c,v 1.14 2013/04/17 19:26:10 krw Exp $	*/
2 
3 /* Common parser code for dhcpd and dhclient. */
4 
5 /*
6  * Copyright (c) 1995, 1996, 1997, 1998 The Internet Software Consortium.
7  * All rights reserved.
8  *
9  * Redistribution and use in source and binary forms, with or without
10  * modification, are permitted provided that the following conditions
11  * are met:
12  *
13  * 1. Redistributions of source code must retain the above copyright
14  *    notice, this list of conditions and the following disclaimer.
15  * 2. Redistributions in binary form must reproduce the above copyright
16  *    notice, this list of conditions and the following disclaimer in the
17  *    documentation and/or other materials provided with the distribution.
18  * 3. Neither the name of The Internet Software Consortium nor the names
19  *    of its contributors may be used to endorse or promote products derived
20  *    from this software without specific prior written permission.
21  *
22  * THIS SOFTWARE IS PROVIDED BY THE INTERNET SOFTWARE CONSORTIUM AND
23  * CONTRIBUTORS ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES,
24  * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
25  * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
26  * DISCLAIMED.  IN NO EVENT SHALL THE INTERNET SOFTWARE CONSORTIUM OR
27  * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
28  * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
29  * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF
30  * USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
31  * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
32  * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
33  * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
34  * SUCH DAMAGE.
35  *
36  * This software has been written for the Internet Software Consortium
37  * by Ted Lemon <mellon@fugue.com> in cooperation with Vixie
38  * Enterprises.  To learn more about the Internet Software Consortium,
39  * see ``http://www.vix.com/isc''.  To learn more about Vixie
40  * Enterprises, see ``http://www.vix.com''.
41  */
42 
43 #include "dhcpd.h"
44 #include "dhctoken.h"
45 
46 /*
47  * Skip to the semicolon ending the current statement.   If we encounter
48  * braces, the matching closing brace terminates the statement.   If we
49  * encounter a right brace but haven't encountered a left brace, return
50  * leaving the brace in the token buffer for the caller.   If we see a
51  * semicolon and haven't seen a left brace, return.   This lets us skip
52  * over:
53  *
54  *	statement;
55  *	statement foo bar { }
56  *	statement foo bar { statement { } }
57  *	statement}
58  *
59  *	...et cetera.
60  */
61 void
62 skip_to_semi(FILE *cfile)
63 {
64 	int		 token;
65 	char		*val;
66 	int		 brace_count = 0;
67 
68 	do {
69 		token = peek_token(&val, cfile);
70 		if (token == '}') {
71 			if (brace_count) {
72 				token = next_token(&val, cfile);
73 				if (!--brace_count)
74 					return;
75 			} else
76 				return;
77 		} else if (token == '{') {
78 			brace_count++;
79 		} else if (token == ';' && !brace_count) {
80 			token = next_token(&val, cfile);
81 			return;
82 		} else if (token == '\n') {
83 			/*
84 			 * EOL only happens when parsing
85 			 * /etc/resolv.conf, and we treat it like a
86 			 * semicolon because the resolv.conf file is
87 			 * line-oriented.
88 			 */
89 			token = next_token(&val, cfile);
90 			return;
91 		}
92 		token = next_token(&val, cfile);
93 	} while (token != EOF);
94 }
95 
96 int
97 parse_semi(FILE *cfile)
98 {
99 	int token;
100 	char *val;
101 
102 	token = next_token(&val, cfile);
103 	if (token != ';') {
104 		parse_warn("semicolon expected.");
105 		skip_to_semi(cfile);
106 		return (0);
107 	}
108 	return (1);
109 }
110 
111 /*
112  * string-parameter :== STRING SEMI
113  */
114 char *
115 parse_string(FILE *cfile)
116 {
117 	char *val, *s;
118 	int token;
119 
120 	token = next_token(&val, cfile);
121 	if (token != TOK_STRING) {
122 		parse_warn("filename must be a string");
123 		skip_to_semi(cfile);
124 		return (NULL);
125 	}
126 	s = strdup(val);
127 	if (s == NULL)
128 		error("no memory for string %s.", val);
129 
130 	if (!parse_semi(cfile)) {
131 		free(s);
132 		return (NULL);
133 	}
134 	return (s);
135 }
136 
137 /*
138  * hostname :== identifier | hostname DOT identifier
139  */
140 char *
141 parse_host_name(FILE *cfile)
142 {
143 	char *val, *s, *t;
144 	int token, len = 0;
145 	pair c = NULL;
146 
147 	/* Read a dotted hostname... */
148 	do {
149 		/* Read a token, which should be an identifier. */
150 		token = next_token(&val, cfile);
151 		if (!is_identifier(token) && token != TOK_NUMBER) {
152 			parse_warn("expecting an identifier in hostname");
153 			skip_to_semi(cfile);
154 			return (NULL);
155 		}
156 		/* Store this identifier... */
157 		s = strdup(val);
158 		if (s == NULL)
159 			error("can't allocate temp space for hostname.");
160 		c = cons((caddr_t) s, c);
161 		len += strlen(s) + 1;
162 		/*
163 		 * Look for a dot; if it's there, keep going, otherwise
164 		 * we're done.
165 		 */
166 		token = peek_token(&val, cfile);
167 		if (token == '.')
168 			token = next_token(&val, cfile);
169 	} while (token == '.');
170 
171 	/* Assemble the hostname together into a string. */
172 	if (!(s = malloc(len)))
173 		error("can't allocate space for hostname.");
174 	t = s + len;
175 	*--t = '\0';
176 	while (c) {
177 		pair cdr = c->cdr;
178 		int l = strlen((char *)c->car);
179 
180 		t -= l;
181 		memcpy(t, (char *)c->car, l);
182 		/* Free up temp space. */
183 		free(c->car);
184 		free(c);
185 		c = cdr;
186 		if (t != s)
187 			*--t = '.';
188 	}
189 	return (s);
190 }
191 
192 /*
193  * hardware-parameter :== HARDWARE ETHERNET csns SEMI
194  * csns :== NUMBER | csns COLON NUMBER
195  */
196 void
197 parse_hardware_param(FILE *cfile, struct hardware *hardware)
198 {
199 	char *val;
200 	int token, hlen;
201 	unsigned char *t;
202 
203 	token = next_token(&val, cfile);
204 	switch (token) {
205 	case TOK_ETHERNET:
206 		hardware->htype = HTYPE_ETHER;
207 		break;
208 	case TOK_TOKEN_RING:
209 		hardware->htype = HTYPE_IEEE802;
210 		break;
211 	case TOK_FDDI:
212 		hardware->htype = HTYPE_FDDI;
213 		break;
214 	case TOK_IPSEC_TUNNEL:
215 		hardware->htype = HTYPE_IPSEC_TUNNEL;
216 		break;
217 	default:
218 		parse_warn("expecting a network hardware type");
219 		skip_to_semi(cfile);
220 		return;
221 	}
222 
223 	/*
224 	 * Parse the hardware address information.   Technically, it
225 	 * would make a lot of sense to restrict the length of the data
226 	 * we'll accept here to the length of a particular hardware
227 	 * address type.   Unfortunately, there are some broken clients
228 	 * out there that put bogus data in the chaddr buffer, and we
229 	 * accept that data in the lease file rather than simply failing
230 	 * on such clients.   Yuck.
231 	 */
232 	hlen = 0;
233 	t = parse_numeric_aggregate(cfile, NULL, &hlen, ':', 16, 8);
234 	if (!t)
235 		return;
236 	if (hlen > sizeof(hardware->haddr)) {
237 		free(t);
238 		parse_warn("hardware address too long");
239 	} else {
240 		hardware->hlen = hlen;
241 		memcpy((unsigned char *)&hardware->haddr[0], t, hardware->hlen);
242 		if (hlen < sizeof(hardware->haddr))
243 			memset(&hardware->haddr[hlen], 0,
244 			    sizeof(hardware->haddr) - hlen);
245 		free(t);
246 	}
247 
248 	token = next_token(&val, cfile);
249 	if (token != ';') {
250 		parse_warn("expecting semicolon.");
251 		skip_to_semi(cfile);
252 	}
253 }
254 
255 /*
256  * lease-time :== NUMBER SEMI
257  */
258 void
259 parse_lease_time(FILE *cfile, time_t *timep)
260 {
261 	char *val;
262 	uint32_t value;
263 	int token;
264 
265 	token = next_token(&val, cfile);
266 	if (token != TOK_NUMBER) {
267 		parse_warn("Expecting numeric lease time");
268 		skip_to_semi(cfile);
269 		return;
270 	}
271 	convert_num((unsigned char *)&value, val, 10, 32);
272 	/* Unswap the number - convert_num returns stuff in NBO. */
273 	*timep = ntohl(value);	/* XXX */
274 
275 	parse_semi(cfile);
276 }
277 
278 /*
279  * No BNF for numeric aggregates - that's defined by the caller.  What
280  * this function does is to parse a sequence of numbers separated by the
281  * token specified in separator.  If max is zero, any number of numbers
282  * will be parsed; otherwise, exactly max numbers are expected.  Base
283  * and size tell us how to internalize the numbers once they've been
284  * tokenized.
285  */
286 unsigned char *
287 parse_numeric_aggregate(FILE *cfile, unsigned char *buf, int *max,
288     int separator, int base, int size)
289 {
290 	char *val, *t;
291 	int token, count = 0;
292 	unsigned char *bufp = buf, *s = NULL;
293 	pair c = NULL;
294 
295 	if (!bufp && *max) {
296 		bufp = malloc(*max * size / 8);
297 		if (!bufp)
298 			error("can't allocate space for numeric aggregate");
299 	} else
300 		s = bufp;
301 
302 	do {
303 		if (count) {
304 			token = peek_token(&val, cfile);
305 			if (token != separator) {
306 				if (!*max)
307 					break;
308 				if (token != '{' && token != '}')
309 					token = next_token(&val, cfile);
310 				parse_warn("too few numbers.");
311 				if (token != ';')
312 					skip_to_semi(cfile);
313 				return (NULL);
314 			}
315 			token = next_token(&val, cfile);
316 		}
317 		token = next_token(&val, cfile);
318 
319 		if (token == EOF) {
320 			parse_warn("unexpected end of file");
321 			break;
322 		}
323 		/* Allow NUMBER_OR_NAME if base is 16. */
324 		if (token != TOK_NUMBER &&
325 		    (base != 16 || token != TOK_NUMBER_OR_NAME)) {
326 			parse_warn("expecting numeric value.");
327 			skip_to_semi(cfile);
328 			return (NULL);
329 		}
330 		/*
331 		 * If we can, convert the number now; otherwise, build a
332 		 * linked list of all the numbers.
333 		 */
334 		if (s) {
335 			convert_num(s, val, base, size);
336 			s += size / 8;
337 		} else {
338 			t = strdup(val);
339 			if (t == NULL)
340 				error("no temp space for number.");
341 			c = cons(t, c);
342 		}
343 	} while (++count != *max);
344 
345 	/* If we had to cons up a list, convert it now. */
346 	if (c) {
347 		bufp = malloc(count * size / 8);
348 		if (!bufp)
349 			error("can't allocate space for numeric aggregate.");
350 		s = bufp + count - size / 8;
351 		*max = count;
352 	}
353 	while (c) {
354 		pair		cdr = c->cdr;
355 		convert_num(s, (char *)c->car, base, size);
356 		s -= size / 8;
357 		/* Free up temp space. */
358 		free(c->car);
359 		free(c);
360 		c = cdr;
361 	}
362 	return (bufp);
363 }
364 
365 void
366 convert_num(unsigned char *buf, char *str, int base, int size)
367 {
368 	int negative = 0, tval, max;
369 	u_int32_t val = 0;
370 	char *ptr = str;
371 
372 	if (*ptr == '-') {
373 		negative = 1;
374 		ptr++;
375 	}
376 
377 	/* If base wasn't specified, figure it out from the data. */
378 	if (!base) {
379 		if (ptr[0] == '0') {
380 			if (ptr[1] == 'x') {
381 				base = 16;
382 				ptr += 2;
383 			} else if (isascii(ptr[1]) && isdigit(ptr[1])) {
384 				base = 8;
385 				ptr += 1;
386 			} else
387 				base = 10;
388 		} else
389 			base = 10;
390 	}
391 
392 	do {
393 		tval = *ptr++;
394 		/* XXX assumes ASCII... */
395 		if (tval >= 'a')
396 			tval = tval - 'a' + 10;
397 		else if (tval >= 'A')
398 			tval = tval - 'A' + 10;
399 		else if (tval >= '0')
400 			tval -= '0';
401 		else {
402 			warning("Bogus number: %s.", str);
403 			break;
404 		}
405 		if (tval >= base) {
406 			warning("Bogus number: %s: digit %d not in base %d",
407 			    str, tval, base);
408 			break;
409 		}
410 		val = val * base + tval;
411 	} while (*ptr);
412 
413 	if (negative)
414 		max = (1 << (size - 1));
415 	else
416 		max = (1 << (size - 1)) + ((1 << (size - 1)) - 1);
417 	if (val > max) {
418 		switch (base) {
419 		case 8:
420 			warning("value %s%o exceeds max (%d) for precision.",
421 			    negative ? "-" : "", val, max);
422 			break;
423 		case 16:
424 			warning("value %s%x exceeds max (%d) for precision.",
425 			    negative ? "-" : "", val, max);
426 			break;
427 		default:
428 			warning("value %s%u exceeds max (%d) for precision.",
429 			    negative ? "-" : "", val, max);
430 			break;
431 		}
432 	}
433 
434 	if (negative) {
435 		switch (size) {
436 		case 8:
437 			*buf = -(unsigned long)val;
438 			break;
439 		case 16:
440 			putShort(buf, -(unsigned long)val);
441 			break;
442 		case 32:
443 			putLong(buf, -(unsigned long)val);
444 			break;
445 		default:
446 			warning("Unexpected integer size: %d", size);
447 			break;
448 		}
449 	} else {
450 		switch (size) {
451 		case 8:
452 			*buf = (u_int8_t)val;
453 			break;
454 		case 16:
455 			putUShort(buf, (u_int16_t)val);
456 			break;
457 		case 32:
458 			putULong(buf, val);
459 			break;
460 		default:
461 			warning("Unexpected integer size: %d", size);
462 			break;
463 		}
464 	}
465 }
466 
467 /*
468  * date :== NUMBER NUMBER SLASH NUMBER SLASH NUMBER
469  *		NUMBER COLON NUMBER COLON NUMBER UTC SEMI
470  *
471  * Dates are always in UTC; first number is day of week; next is
472  * year/month/day; next is hours:minutes:seconds on a 24-hour
473  * clock.
474  */
475 time_t
476 parse_date(FILE *cfile)
477 {
478 	struct tm tm;
479 	char timestr[26]; /* "w yyyy/mm/dd hh:mm:ss UTC" */
480 	char *val, *p;
481 	size_t n;
482 	time_t guess;
483 	int token;
484 
485 	memset(timestr, 0, sizeof(timestr));
486 
487 	do {
488 		token = peek_token(NULL, cfile);
489 		switch (token) {
490 		case TOK_NAME:
491 		case TOK_NUMBER:
492 		case '/':
493 		case ':':
494 			token = next_token(&val, cfile);
495 			n = strlcat(timestr, val, sizeof(timestr));
496 			if (n >= sizeof(timestr)) {
497 				/* XXX Will break after year 9999! */
498 				parse_warn("time string too long");
499 				skip_to_semi(cfile);
500 				return (0);
501 			}
502 			break;
503 		case';':
504 			break;
505 		default:
506 			parse_warn("invalid time string");
507 			skip_to_semi(cfile);
508 			return (0);
509 		}
510 	} while (token != ';');
511 
512 	parse_semi(cfile);
513 
514 	memset(&tm, 0, sizeof(tm));	/* 'cuz strptime ignores tm_isdt. */
515 	p = strptime(timestr, DB_TIMEFMT, &tm);
516 	if (p == NULL || *p != '\0') {
517 		p = strptime(timestr, OLD_DB_TIMEFMT, &tm);
518 		if (p == NULL || *p != '\0') {
519 			parse_warn("unparseable time string");
520 			return (0);
521 		}
522 	}
523 
524 	guess = timegm(&tm);
525 	if (guess == -1) {
526 		parse_warn("time could not be represented");
527 		return (0);
528 	}
529 
530 	return (guess);
531 }
532