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