xref: /openbsd-src/usr.sbin/dhcpd/parse.c (revision f0a65fa006efdee0b470b840e2c3a4c4d3282eb0)
1 /*	$OpenBSD: parse.c,v 1.22 2017/02/11 16:12:36 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 <sys/types.h>
44 #include <sys/socket.h>
45 
46 #include <net/if.h>
47 
48 #include <netinet/in.h>
49 
50 #include <ctype.h>
51 #include <stdarg.h>
52 #include <stdint.h>
53 #include <stdio.h>
54 #include <stdlib.h>
55 #include <string.h>
56 #include <syslog.h>
57 #include <time.h>
58 #include <unistd.h>
59 
60 #include "dhcp.h"
61 #include "tree.h"
62 #include "dhcpd.h"
63 #include "dhctoken.h"
64 
65 /*
66  * Skip to the semicolon ending the current statement.   If we encounter
67  * braces, the matching closing brace terminates the statement.   If we
68  * encounter a right brace but haven't encountered a left brace, return
69  * leaving the brace in the token buffer for the caller.   If we see a
70  * semicolon and haven't seen a left brace, return.   This lets us skip
71  * over:
72  *
73  *	statement;
74  *	statement foo bar { }
75  *	statement foo bar { statement { } }
76  *	statement}
77  *
78  *	...et cetera.
79  */
80 void
81 skip_to_semi(FILE *cfile)
82 {
83 	int		 token;
84 	char		*val;
85 	int		 brace_count = 0;
86 
87 	do {
88 		token = peek_token(&val, cfile);
89 		if (token == '}') {
90 			if (brace_count) {
91 				token = next_token(&val, cfile);
92 				if (!--brace_count)
93 					return;
94 			} else
95 				return;
96 		} else if (token == '{') {
97 			brace_count++;
98 		} else if (token == ';' && !brace_count) {
99 			token = next_token(&val, cfile);
100 			return;
101 		} else if (token == '\n') {
102 			/*
103 			 * EOL only happens when parsing
104 			 * /etc/resolv.conf, and we treat it like a
105 			 * semicolon because the resolv.conf file is
106 			 * line-oriented.
107 			 */
108 			token = next_token(&val, cfile);
109 			return;
110 		}
111 		token = next_token(&val, cfile);
112 	} while (token != EOF);
113 }
114 
115 int
116 parse_semi(FILE *cfile)
117 {
118 	int token;
119 	char *val;
120 
121 	token = next_token(&val, cfile);
122 	if (token != ';') {
123 		parse_warn("semicolon expected.");
124 		skip_to_semi(cfile);
125 		return (0);
126 	}
127 	return (1);
128 }
129 
130 /*
131  * string-parameter :== STRING SEMI
132  */
133 char *
134 parse_string(FILE *cfile)
135 {
136 	char *val, *s;
137 	int token;
138 
139 	token = next_token(&val, cfile);
140 	if (token != TOK_STRING) {
141 		parse_warn("filename must be a string");
142 		skip_to_semi(cfile);
143 		return (NULL);
144 	}
145 	s = strdup(val);
146 	if (s == NULL)
147 		error("no memory for string %s.", val);
148 
149 	if (!parse_semi(cfile)) {
150 		free(s);
151 		return (NULL);
152 	}
153 	return (s);
154 }
155 
156 /*
157  * hostname :== identifier | hostname DOT identifier
158  */
159 char *
160 parse_host_name(FILE *cfile)
161 {
162 	char *val, *s, *t;
163 	int token, len = 0;
164 	pair c = NULL;
165 
166 	/* Read a dotted hostname... */
167 	do {
168 		/* Read a token, which should be an identifier. */
169 		token = next_token(&val, cfile);
170 		if (!is_identifier(token)) {
171 			parse_warn("expecting an identifier in hostname");
172 			skip_to_semi(cfile);
173 			return (NULL);
174 		}
175 		/* Store this identifier... */
176 		s = strdup(val);
177 		if (s == NULL)
178 			error("can't allocate temp space for hostname.");
179 		c = cons((caddr_t) s, c);
180 		len += strlen(s) + 1;
181 		/*
182 		 * Look for a dot; if it's there, keep going, otherwise
183 		 * we're done.
184 		 */
185 		token = peek_token(&val, cfile);
186 		if (token == '.')
187 			token = next_token(&val, cfile);
188 	} while (token == '.');
189 
190 	/* Assemble the hostname together into a string. */
191 	if (!(s = malloc(len)))
192 		error("can't allocate space for hostname.");
193 	t = s + len;
194 	*--t = '\0';
195 	while (c) {
196 		pair cdr = c->cdr;
197 		int l = strlen((char *)c->car);
198 
199 		t -= l;
200 		memcpy(t, (char *)c->car, l);
201 		/* Free up temp space. */
202 		free(c->car);
203 		free(c);
204 		c = cdr;
205 		if (t != s)
206 			*--t = '.';
207 	}
208 	return (s);
209 }
210 
211 /*
212  * hardware-parameter :== HARDWARE ETHERNET csns SEMI
213  * csns :== NUMBER | csns COLON NUMBER
214  */
215 void
216 parse_hardware_param(FILE *cfile, struct hardware *hardware)
217 {
218 	char *val;
219 	int token, hlen;
220 	unsigned char *t;
221 
222 	token = next_token(&val, cfile);
223 	switch (token) {
224 	case TOK_ETHERNET:
225 		hardware->htype = HTYPE_ETHER;
226 		break;
227 	case TOK_IPSEC_TUNNEL:
228 		hardware->htype = HTYPE_IPSEC_TUNNEL;
229 		break;
230 	default:
231 		parse_warn("expecting a network hardware type");
232 		skip_to_semi(cfile);
233 		return;
234 	}
235 
236 	/*
237 	 * Parse the hardware address information.   Technically, it
238 	 * would make a lot of sense to restrict the length of the data
239 	 * we'll accept here to the length of a particular hardware
240 	 * address type.   Unfortunately, there are some broken clients
241 	 * out there that put bogus data in the chaddr buffer, and we
242 	 * accept that data in the lease file rather than simply failing
243 	 * on such clients.   Yuck.
244 	 */
245 	hlen = 0;
246 	t = parse_numeric_aggregate(cfile, NULL, &hlen, ':', 16, 8);
247 	if (!t)
248 		return;
249 	if (hlen > sizeof(hardware->haddr)) {
250 		free(t);
251 		parse_warn("hardware address too long");
252 	} else {
253 		hardware->hlen = hlen;
254 		memcpy((unsigned char *)&hardware->haddr[0], t, hardware->hlen);
255 		if (hlen < sizeof(hardware->haddr))
256 			memset(&hardware->haddr[hlen], 0,
257 			    sizeof(hardware->haddr) - hlen);
258 		free(t);
259 	}
260 
261 	token = next_token(&val, cfile);
262 	if (token != ';') {
263 		parse_warn("expecting semicolon.");
264 		skip_to_semi(cfile);
265 	}
266 }
267 
268 /*
269  * lease-time :== NUMBER SEMI
270  */
271 void
272 parse_lease_time(FILE *cfile, time_t *timep)
273 {
274 	const char *errstr;
275 	char *val;
276 	uint32_t value;
277 	int token;
278 
279 	token = next_token(&val, cfile);
280 
281 	value = strtonum(val, 0, UINT32_MAX, &errstr);
282 	if (errstr) {
283 		parse_warn("lease time is %s: %s", errstr, val);
284 		skip_to_semi(cfile);
285 		return;
286 	}
287 
288 	*timep = value;
289 
290 	parse_semi(cfile);
291 }
292 
293 /*
294  * No BNF for numeric aggregates - that's defined by the caller.  What
295  * this function does is to parse a sequence of numbers separated by the
296  * token specified in separator.  If max is zero, any number of numbers
297  * will be parsed; otherwise, exactly max numbers are expected.  Base
298  * and size tell us how to internalize the numbers once they've been
299  * tokenized.
300  */
301 unsigned char *
302 parse_numeric_aggregate(FILE *cfile, unsigned char *buf, int *max,
303     int separator, int base, int size)
304 {
305 	char *val, *t;
306 	int token, count = 0;
307 	unsigned char *bufp = buf, *s = NULL;
308 	pair c = NULL;
309 
310 	if (!bufp && *max) {
311 		bufp = malloc(*max * size / 8);
312 		if (!bufp)
313 			error("can't allocate space for numeric aggregate");
314 	} else
315 		s = bufp;
316 
317 	do {
318 		if (count) {
319 			token = peek_token(&val, cfile);
320 			if (token != separator) {
321 				if (!*max)
322 					break;
323 				if (token != '{' && token != '}')
324 					token = next_token(&val, cfile);
325 				parse_warn("too few numbers.");
326 				if (token != ';')
327 					skip_to_semi(cfile);
328 				return (NULL);
329 			}
330 			token = next_token(&val, cfile);
331 		}
332 		token = next_token(&val, cfile);
333 
334 		if (token == EOF) {
335 			parse_warn("unexpected end of file");
336 			break;
337 		}
338 		if (token != TOK_NUMBER && token != TOK_NUMBER_OR_NAME) {
339 			parse_warn("expecting numeric value.");
340 			skip_to_semi(cfile);
341 			return (NULL);
342 		}
343 		/*
344 		 * If we can, convert the number now; otherwise, build a
345 		 * linked list of all the numbers.
346 		 */
347 		if (s) {
348 			convert_num(s, val, base, size);
349 			s += size / 8;
350 		} else {
351 			t = strdup(val);
352 			if (t == NULL)
353 				error("no temp space for number.");
354 			c = cons(t, c);
355 		}
356 	} while (++count != *max);
357 
358 	/* If we had to cons up a list, convert it now. */
359 	if (c) {
360 		bufp = malloc(count * size / 8);
361 		if (!bufp)
362 			error("can't allocate space for numeric aggregate.");
363 		s = bufp + count - size / 8;
364 		*max = count;
365 	}
366 	while (c) {
367 		pair		cdr = c->cdr;
368 		convert_num(s, (char *)c->car, base, size);
369 		s -= size / 8;
370 		/* Free up temp space. */
371 		free(c->car);
372 		free(c);
373 		c = cdr;
374 	}
375 	return (bufp);
376 }
377 
378 void
379 convert_num(unsigned char *buf, char *str, int base, int size)
380 {
381 	int negative = 0, tval, max;
382 	u_int32_t val = 0;
383 	char *ptr = str;
384 
385 	if (*ptr == '-') {
386 		negative = 1;
387 		ptr++;
388 	}
389 
390 	/* If base wasn't specified, figure it out from the data. */
391 	if (!base) {
392 		if (ptr[0] == '0') {
393 			if (ptr[1] == 'x') {
394 				base = 16;
395 				ptr += 2;
396 			} else if (isascii((unsigned char)ptr[1]) &&
397 			    isdigit((unsigned char)ptr[1])) {
398 				base = 8;
399 				ptr += 1;
400 			} else
401 				base = 10;
402 		} else
403 			base = 10;
404 	}
405 
406 	do {
407 		tval = *ptr++;
408 		/* XXX assumes ASCII... */
409 		if (tval >= 'a')
410 			tval = tval - 'a' + 10;
411 		else if (tval >= 'A')
412 			tval = tval - 'A' + 10;
413 		else if (tval >= '0')
414 			tval -= '0';
415 		else {
416 			warning("Bogus number: %s.", str);
417 			break;
418 		}
419 		if (tval >= base) {
420 			warning("Bogus number: %s: digit %d not in base %d",
421 			    str, tval, base);
422 			break;
423 		}
424 		val = val * base + tval;
425 	} while (*ptr);
426 
427 	if (negative)
428 		max = (1 << (size - 1));
429 	else
430 		max = (1 << (size - 1)) + ((1 << (size - 1)) - 1);
431 	if (val > max) {
432 		switch (base) {
433 		case 8:
434 			warning("value %s%o exceeds max (%d) for precision.",
435 			    negative ? "-" : "", val, max);
436 			break;
437 		case 16:
438 			warning("value %s%x exceeds max (%d) for precision.",
439 			    negative ? "-" : "", val, max);
440 			break;
441 		default:
442 			warning("value %s%u exceeds max (%d) for precision.",
443 			    negative ? "-" : "", val, max);
444 			break;
445 		}
446 	}
447 
448 	if (negative) {
449 		switch (size) {
450 		case 8:
451 			*buf = -(unsigned long)val;
452 			break;
453 		case 16:
454 			putShort(buf, -(unsigned long)val);
455 			break;
456 		case 32:
457 			putLong(buf, -(unsigned long)val);
458 			break;
459 		default:
460 			warning("Unexpected integer size: %d", size);
461 			break;
462 		}
463 	} else {
464 		switch (size) {
465 		case 8:
466 			*buf = (u_int8_t)val;
467 			break;
468 		case 16:
469 			putUShort(buf, (u_int16_t)val);
470 			break;
471 		case 32:
472 			putULong(buf, val);
473 			break;
474 		default:
475 			warning("Unexpected integer size: %d", size);
476 			break;
477 		}
478 	}
479 }
480 
481 /*
482  * date :== NUMBER NUMBER SLASH NUMBER SLASH NUMBER
483  *		NUMBER COLON NUMBER COLON NUMBER UTC SEMI
484  *
485  * Dates are always in UTC; first number is day of week; next is
486  * year/month/day; next is hours:minutes:seconds on a 24-hour
487  * clock.
488  */
489 time_t
490 parse_date(FILE *cfile)
491 {
492 	struct tm tm;
493 	char timestr[26]; /* "w yyyy/mm/dd hh:mm:ss UTC" */
494 	char *val, *p;
495 	size_t n;
496 	time_t guess;
497 	int token;
498 
499 	memset(timestr, 0, sizeof(timestr));
500 
501 	do {
502 		token = peek_token(NULL, cfile);
503 		switch (token) {
504 		case TOK_NAME:
505 		case TOK_NUMBER:
506 		case TOK_NUMBER_OR_NAME:
507 		case '/':
508 		case ':':
509 			token = next_token(&val, cfile);
510 			n = strlcat(timestr, val, sizeof(timestr));
511 			if (n >= sizeof(timestr)) {
512 				/* XXX Will break after year 9999! */
513 				parse_warn("time string too long");
514 				skip_to_semi(cfile);
515 				return (0);
516 			}
517 			break;
518 		case';':
519 			break;
520 		default:
521 			parse_warn("invalid time string");
522 			skip_to_semi(cfile);
523 			return (0);
524 		}
525 	} while (token != ';');
526 
527 	parse_semi(cfile);
528 
529 	memset(&tm, 0, sizeof(tm));	/* 'cuz strptime ignores tm_isdt. */
530 	p = strptime(timestr, DB_TIMEFMT, &tm);
531 	if (p == NULL || *p != '\0') {
532 		p = strptime(timestr, OLD_DB_TIMEFMT, &tm);
533 		if (p == NULL || *p != '\0') {
534 			parse_warn("unparseable time string");
535 			return (0);
536 		}
537 	}
538 
539 	guess = timegm(&tm);
540 	if (guess == -1) {
541 		parse_warn("time could not be represented");
542 		return (0);
543 	}
544 
545 	return (guess);
546 }
547 
548 int
549 parse_warn(char *fmt, ...)
550 {
551 	extern char mbuf[1024];
552 	extern char fbuf[1024];
553 	va_list list;
554 	static char spaces[] =
555 	    "                                        "
556 	    "                                        "; /* 80 spaces */
557 	struct iovec iov[6];
558 	size_t iovcnt;
559 
560 	do_percentm(mbuf, sizeof(mbuf), fmt);
561 	snprintf(fbuf, sizeof(fbuf), "%s line %d: %s", tlname, lexline, mbuf);
562 	va_start(list, fmt);
563 	vsnprintf(mbuf, sizeof(mbuf), fbuf, list);
564 	va_end(list);
565 
566 	if (log_perror) {
567 		iov[0].iov_base = mbuf;
568 		iov[0].iov_len = strlen(mbuf);
569 		iov[1].iov_base = "\n";
570 		iov[1].iov_len = 1;
571 		iov[2].iov_base = token_line;
572 		iov[2].iov_len = strlen(token_line);
573 		iov[3].iov_base = "\n";
574 		iov[3].iov_len = 1;
575 		iovcnt = 4;
576 		if (lexchar < 81) {
577 			iov[4].iov_base = spaces;
578 			iov[4].iov_len = lexchar - 1;
579 			iov[5].iov_base = "^\n";
580 			iov[5].iov_len = 2;
581 			iovcnt += 2;
582 		}
583 		writev(STDERR_FILENO, iov, iovcnt);
584 	} else {
585 		syslog_r(log_priority | LOG_ERR, &sdata, "%s", mbuf);
586 		syslog_r(log_priority | LOG_ERR, &sdata, "%s", token_line);
587 		if (lexchar < 81)
588 			syslog_r(log_priority | LOG_ERR, &sdata, "%*c", lexchar,
589 			    '^');
590 	}
591 
592 	warnings_occurred = 1;
593 
594 	return (0);
595 }
596