1 /*	$OpenBSD: dhclient.c,v 1.109 2007/02/13 21:54:22 stevesk Exp $	*/
2 
3 /*
4  * Copyright 2004 Henning Brauer <henning@openbsd.org>
5  * Copyright (c) 1995, 1996, 1997, 1998, 1999
6  * The Internet Software Consortium.    All rights reserved.
7  *
8  * Redistribution and use in source and binary forms, with or without
9  * modification, are permitted provided that the following conditions
10  * are met:
11  *
12  * 1. Redistributions of source code must retain the above copyright
13  *    notice, this list of conditions and the following disclaimer.
14  * 2. Redistributions in binary form must reproduce the above copyright
15  *    notice, this list of conditions and the following disclaimer in the
16  *    documentation and/or other materials provided with the distribution.
17  * 3. Neither the name of The Internet Software Consortium nor the names
18  *    of its contributors may be used to endorse or promote products derived
19  *    from this software without specific prior written permission.
20  *
21  * THIS SOFTWARE IS PROVIDED BY THE INTERNET SOFTWARE CONSORTIUM AND
22  * CONTRIBUTORS ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES,
23  * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
24  * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
25  * DISCLAIMED.  IN NO EVENT SHALL THE INTERNET SOFTWARE CONSORTIUM OR
26  * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
27  * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
28  * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF
29  * USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
30  * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
31  * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
32  * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
33  * SUCH DAMAGE.
34  *
35  * This software has been written for the Internet Software Consortium
36  * by Ted Lemon <mellon@fugue.com> in cooperation with Vixie
37  * Enterprises.  To learn more about the Internet Software Consortium,
38  * see ``http://www.vix.com/isc''.  To learn more about Vixie
39  * Enterprises, see ``http://www.vix.com''.
40  *
41  * This client was substantially modified and enhanced by Elliot Poger
42  * for use on Linux while he was working on the MosquitoNet project at
43  * Stanford.
44  *
45  * The current version owes much to Elliot's Linux enhancements, but
46  * was substantially reorganized and partially rewritten by Ted Lemon
47  * so as to use the same networking framework that the Internet Software
48  * Consortium DHCP server uses.   Much system-specific configuration code
49  * was moved into a shell script so that as support for more operating
50  * systems is added, it will not be necessary to port and maintain
51  * system-specific configuration code to these operating systems - instead,
52  * the shell script can invoke the native tools to accomplish the same
53  * purpose.
54  */
55 
56 #include <ctype.h>
57 #include <poll.h>
58 #include <pwd.h>
59 #include <stdbool.h>
60 
61 #include "dhcpd.h"
62 #include "privsep.h"
63 
64 __RCSID("$MirOS: src/sbin/dhclient/dhclient.c,v 1.9 2009/07/24 17:22:54 tg Exp $");
65 
66 #define	CLIENT_PATH "PATH=/usr/bin:/usr/sbin:/bin:/sbin"
67 
68 time_t cur_time;
69 time_t default_lease_time = 43200; /* 12 hours... */
70 
71 char *path_dhclient_conf = _PATH_DHCLIENT_CONF;
72 char *path_dhclient_db = NULL;
73 
74 int log_perror = 1;
75 int privfd;
76 int nullfd = -1;
77 int no_daemon;
78 int unknown_ok = 1;
79 int routefd = -1;
80 
81 struct iaddr iaddr_broadcast = { 4, { 255, 255, 255, 255 } };
82 struct in_addr inaddr_any;
83 struct sockaddr_in sockaddr_broadcast;
84 
85 #define TIME_MAX 2147483647
86 
87 struct interface_info *ifi;
88 struct client_state *client;
89 struct client_config *config;
90 
91 int		 findproto(char *, int);
92 struct sockaddr	*get_ifa(char *, int);
93 void		 usage(void);
94 int		 check_option(struct client_lease *l, int option);
95 int		 ipv4addrs(char * buf);
96 int		 res_hnok(const char *dn, bool wsp_ok);
97 char		*option_as_string(unsigned int code, unsigned char *data, int len);
98 int		 fork_privchld(int, int);
99 
100 #define	ROUNDUP(a) \
101 	    ((a) > 0 ? (1 + (((a) - 1) | (sizeof(long) - 1))) : sizeof(long))
102 #define	ADVANCE(x, n) (x += ROUNDUP((n)->sa_len))
103 
104 time_t	scripttime;
105 
106 int
findproto(char * cp,int n)107 findproto(char *cp, int n)
108 {
109 	struct sockaddr *sa;
110 	int i;
111 
112 	if (n == 0)
113 		return -1;
114 	for (i = 1; i; i <<= 1) {
115 		if (i & n) {
116 			sa = (struct sockaddr *)cp;
117 			switch (i) {
118 			case RTA_IFA:
119 			case RTA_DST:
120 			case RTA_GATEWAY:
121 			case RTA_NETMASK:
122 				if (sa->sa_family == AF_INET)
123 					return AF_INET;
124 				if (sa->sa_family == AF_INET6)
125 					return AF_INET6;
126 				break;
127 			case RTA_IFP:
128 				break;
129 			}
130 			ADVANCE(cp, sa);
131 		}
132 	}
133 	return (-1);
134 }
135 
136 struct sockaddr *
get_ifa(char * cp,int n)137 get_ifa(char *cp, int n)
138 {
139 	struct sockaddr *sa;
140 	int i;
141 
142 	if (n == 0)
143 		return (NULL);
144 	for (i = 1; i; i <<= 1)
145 		if (i & n) {
146 			sa = (struct sockaddr *)cp;
147 			if (i == RTA_IFA)
148 				return (sa);
149 			ADVANCE(cp, sa);
150 		}
151 
152 	return (NULL);
153 }
154 struct iaddr defaddr = { 4 };
155 
156 /* ARGSUSED */
157 void
routehandler(void)158 routehandler(void)
159 {
160 	char msg[2048];
161 	struct rt_msghdr *rtm;
162 	struct if_msghdr *ifm;
163 	struct ifa_msghdr *ifam;
164 	struct if_announcemsghdr *ifan;
165 	struct client_lease *l;
166 	time_t t = time(NULL);
167 	struct sockaddr *sa;
168 	struct iaddr a;
169 	ssize_t n;
170 
171 	do {
172 		n = read(routefd, &msg, sizeof(msg));
173 	} while (n == -1 && errno == EINTR);
174 
175 	rtm = (struct rt_msghdr *)msg;
176 	if (n < sizeof(rtm->rtm_msglen) || n < rtm->rtm_msglen ||
177 	    rtm->rtm_version != RTM_VERSION)
178 		return;
179 
180 	switch (rtm->rtm_type) {
181 	case RTM_NEWADDR:
182 		ifam = (struct ifa_msghdr *)rtm;
183 		if (ifam->ifam_index != ifi->index)
184 			break;
185 		if (findproto((char *)(ifam + 1), ifam->ifam_addrs) != AF_INET)
186 			break;
187 		sa = get_ifa((char *)(ifam + 1), ifam->ifam_addrs);
188 		if (sa == NULL)
189 			goto die;
190 
191 		if ((a.len = sizeof(struct in_addr)) > sizeof(a.iabuf))
192 			error("king bula sez: len mismatch");
193 		memcpy(a.iabuf, &((struct sockaddr_in *)sa)->sin_addr, a.len);
194 		if (addr_eq(a, defaddr))
195 			break;
196 
197 		for (l = client->active; l != NULL; l = l->next)
198 			if (addr_eq(a, l->address))
199 				break;
200 
201 		if (l != NULL || (client->alias &&
202 		    addr_eq(a, client->alias->address)))
203 			/* new addr is the one we set */
204 			break;
205 
206 		goto die;
207 	case RTM_DELADDR:
208 		ifam = (struct ifa_msghdr *)rtm;
209 		if (ifam->ifam_index != ifi->index)
210 			break;
211 		if (findproto((char *)(ifam + 1), ifam->ifam_addrs) != AF_INET)
212 			break;
213 		if (scripttime == 0 || t < scripttime + 10)
214 			break;
215 		goto die;
216 	case RTM_IFINFO:
217 		ifm = (struct if_msghdr *)rtm;
218 		if (ifm->ifm_index != ifi->index)
219 			break;
220 		if ((rtm->rtm_flags & RTF_UP) == 0)
221 			goto die;
222 		break;
223 	case RTM_IFANNOUNCE:
224 		ifan = (struct if_announcemsghdr *)rtm;
225 		if (ifan->ifan_what == IFAN_DEPARTURE &&
226 		    ifan->ifan_index == ifi->index)
227 			goto die;
228 		break;
229 	default:
230 		break;
231 	}
232 	return;
233 
234 die:
235 	script_init("FAIL", NULL);
236 	if (client->alias)
237 		script_write_params("alias_", client->alias);
238 	script_go();
239 	exit(1);
240 }
241 
242 int
main(int argc,char * argv[])243 main(int argc, char *argv[])
244 {
245 	int	 ch, fd, quiet = 0, i = 0, pipe_fd[2];
246 	extern char *__progname;
247 	struct passwd *pw;
248 
249 	/* Initially, log errors to stderr as well as to syslogd. */
250 	openlog(__progname, LOG_PID | LOG_NDELAY, DHCPD_LOG_FACILITY);
251 	setlogmask(LOG_UPTO(LOG_INFO));
252 
253 	while ((ch = getopt(argc, argv, "c:dl:qu")) != -1)
254 		switch (ch) {
255 		case 'c':
256 			path_dhclient_conf = optarg;
257 			break;
258 		case 'd':
259 			no_daemon = 1;
260 			break;
261 		case 'l':
262 			path_dhclient_db = optarg;
263 			break;
264 		case 'q':
265 			quiet = 1;
266 			break;
267 		case 'u':
268 			unknown_ok = 0;
269 			break;
270 		default:
271 			usage();
272 		}
273 
274 	argc -= optind;
275 	argv += optind;
276 
277 	if (argc != 1)
278 		usage();
279 
280 	ifi = calloc(1, sizeof(*ifi));
281 	if (ifi == NULL)
282 		error("ifi calloc");
283 	client = calloc(1, sizeof(*client));
284 	if (client == NULL)
285 		error("client calloc");
286 	config = calloc(1, sizeof(*config));
287 	if (config == NULL)
288 		error("config calloc");
289 
290 	if (strlcpy(ifi->name, argv[0], IFNAMSIZ) >= IFNAMSIZ)
291 		error("Interface name too long");
292 	if (path_dhclient_db == NULL && asprintf(&path_dhclient_db, "%s.%s",
293 	    _PATH_DHCLIENT_DB, ifi->name) == -1)
294 		error("asprintf");
295 
296 	if (quiet)
297 		log_perror = 0;
298 
299 	tzset();
300 	time(&cur_time);
301 
302 	memset(&sockaddr_broadcast, 0, sizeof(sockaddr_broadcast));
303 	sockaddr_broadcast.sin_family = AF_INET;
304 	sockaddr_broadcast.sin_port = htons(REMOTE_PORT);
305 	sockaddr_broadcast.sin_addr.s_addr = INADDR_BROADCAST;
306 	sockaddr_broadcast.sin_len = sizeof(sockaddr_broadcast);
307 	inaddr_any.s_addr = INADDR_ANY;
308 
309 	read_client_conf();
310 
311 	if (!interface_link_status(ifi->name)) {
312 		int linkstat = interface_link_forceup(ifi->name);
313 
314 		fprintf(stderr, "%s: no link ...", ifi->name);
315 		if (config->link_timeout == 0) {
316 			fprintf(stderr, " giving up\n");
317 			if (linkstat == 0)
318 				interface_link_forcedown(ifi->name);
319 			exit(1);
320 		}
321 		fflush(stderr);
322 		sleep(1);
323 		while (!interface_link_status(ifi->name)) {
324 			fprintf(stderr, ".");
325 			fflush(stderr);
326 			if (++i > config->link_timeout) {
327 				fprintf(stderr, " giving up\n");
328 				if (linkstat == 0)
329 					interface_link_forcedown(ifi->name);
330 				exit(1);
331 			}
332 			sleep(1);
333 		}
334 		fprintf(stderr, " got link\n");
335 	}
336 
337 	if ((nullfd = open(_PATH_DEVNULL, O_RDWR, 0)) == -1)
338 		error("cannot open %s: %m", _PATH_DEVNULL);
339 
340 	if ((pw = getpwnam("_dhcp")) == NULL) {
341 		warning("no such user: _dhcp, falling back to \"nobody\"");
342 		if ((pw = getpwnam("nobody")) == NULL)
343 			error("no such user: nobody");
344 	}
345 
346 	if (pipe(pipe_fd) == -1)
347 		error("pipe");
348 
349 	fork_privchld(pipe_fd[0], pipe_fd[1]);
350 
351 	close(pipe_fd[0]);
352 	privfd = pipe_fd[1];
353 
354 	if ((fd = open(path_dhclient_db, O_RDONLY|O_EXLOCK|O_CREAT, 0)) == -1)
355 		error("can't open and lock %s: %m", path_dhclient_db);
356 	read_client_leases();
357 	rewrite_client_leases();
358 	close(fd);
359 
360 	priv_script_init("PREINIT", NULL);
361 	if (client->alias)
362 		priv_script_write_params("alias_", client->alias);
363 	priv_script_go();
364 
365 	if ((routefd = socket(PF_ROUTE, SOCK_RAW, 0)) == -1)
366 		error("socket(PF_ROUTE, SOCK_RAW): %m");
367 
368 	/* set up the interface */
369 	discover_interface();
370 
371 	if (chroot(_PATH_VAREMPTY) == -1)
372 		error("chroot");
373 	if (chdir("/") == -1)
374 		error("chdir(\"/\")");
375 
376 	if (setresgid(pw->pw_gid, pw->pw_gid, pw->pw_gid) == -1)
377 		error("setresgid");
378 	if (setgroups(1, &pw->pw_gid) == -1)
379 		error("setgroups");
380 	if (setresuid(pw->pw_uid, pw->pw_uid, pw->pw_uid) == -1)
381 		error("setresuid");
382 
383 	endpwent();
384 
385 	setproctitle("%s", ifi->name);
386 
387 	client->state = S_INIT;
388 	state_reboot();
389 
390 	dispatch();
391 
392 	/* not reached */
393 	return (0);
394 }
395 
396 void
usage(void)397 usage(void)
398 {
399 	extern char	*__progname;
400 
401 	fprintf(stderr, "usage: %s [-dqu] ", __progname);
402 	fprintf(stderr, "[-c conffile] [-l leasefile] interface\n");
403 	exit(1);
404 }
405 
406 /*
407  * Individual States:
408  *
409  * Each routine is called from the dhclient_state_machine() in one of
410  * these conditions:
411  * -> entering INIT state
412  * -> recvpacket_flag == 0: timeout in this state
413  * -> otherwise: received a packet in this state
414  *
415  * Return conditions as handled by dhclient_state_machine():
416  * Returns 1, sendpacket_flag = 1: send packet, reset timer.
417  * Returns 1, sendpacket_flag = 0: just reset the timer (wait for a milestone).
418  * Returns 0: finish the nap which was interrupted for no good reason.
419  *
420  * Several per-interface variables are used to keep track of the process:
421  *   active_lease: the lease that is being used on the interface
422  *                 (null pointer if not configured yet).
423  *   offered_leases: leases corresponding to DHCPOFFER messages that have
424  *                   been sent to us by DHCP servers.
425  *   acked_leases: leases corresponding to DHCPACK messages that have been
426  *                 sent to us by DHCP servers.
427  *   sendpacket: DHCP packet we're trying to send.
428  *   destination: IP address to send sendpacket to
429  * In addition, there are several relevant per-lease variables.
430  *   T1_expiry, T2_expiry, lease_expiry: lease milestones
431  * In the active lease, these control the process of renewing the lease;
432  * In leases on the acked_leases list, this simply determines when we
433  * can no longer legitimately use the lease.
434  */
435 void
state_reboot(void)436 state_reboot(void)
437 {
438 	/* If we don't remember an active lease, go straight to INIT. */
439 	if (!client->active || client->active->is_bootp) {
440 		state_init();
441 		return;
442 	}
443 
444 	/* We are in the rebooting state. */
445 	client->state = S_REBOOTING;
446 
447 	/* make_request doesn't initialize xid because it normally comes
448 	   from the DHCPDISCOVER, but we haven't sent a DHCPDISCOVER,
449 	   so pick an xid now. */
450 	client->xid = arc4random();
451 
452 	/* Make a DHCPREQUEST packet, and set appropriate per-interface
453 	   flags. */
454 	make_request(client->active);
455 	client->destination = iaddr_broadcast;
456 	client->first_sending = cur_time;
457 	client->interval = config->initial_interval;
458 
459 	/* Zap the medium list... */
460 	client->medium = NULL;
461 
462 	/* Send out the first DHCPREQUEST packet. */
463 	send_request();
464 }
465 
466 /*
467  * Called when a lease has completely expired and we've
468  * been unable to renew it.
469  */
470 void
state_init(void)471 state_init(void)
472 {
473 	/* Make a DHCPDISCOVER packet, and set appropriate per-interface
474 	   flags. */
475 	make_discover(client->active);
476 	client->xid = client->packet.xid;
477 	client->destination = iaddr_broadcast;
478 	client->state = S_SELECTING;
479 	client->first_sending = cur_time;
480 	client->interval = config->initial_interval;
481 
482 	/* Add an immediate timeout to cause the first DHCPDISCOVER packet
483 	   to go out. */
484 	send_discover();
485 }
486 
487 /*
488  * state_selecting is called when one or more DHCPOFFER packets
489  * have been received and a configurable period of time has passed.
490  */
491 void
state_selecting(void)492 state_selecting(void)
493 {
494 	struct client_lease *lp, *next, *picked;
495 
496 	/* Cancel state_selecting and send_discover timeouts, since either
497 	   one could have got us here. */
498 	cancel_timeout(state_selecting);
499 	cancel_timeout(send_discover);
500 
501 	/* We have received one or more DHCPOFFER packets.   Currently,
502 	   the only criterion by which we judge leases is whether or
503 	   not we get a response when we arp for them. */
504 	picked = NULL;
505 	for (lp = client->offered_leases; lp; lp = next) {
506 		next = lp->next;
507 
508 		/* Check to see if we got an ARPREPLY for the address
509 		   in this particular lease. */
510 		if (!picked) {
511 			script_init("ARPCHECK", lp->medium);
512 			script_write_params("check_", lp);
513 
514 			/* If the ARPCHECK code detects another
515 			   machine using the offered address, it exits
516 			   nonzero.  We need to send a DHCPDECLINE and
517 			   toss the lease. */
518 			if (script_go()) {
519 				make_decline(lp);
520 				send_decline();
521 				goto freeit;
522 			}
523 			picked = lp;
524 			picked->next = NULL;
525 		} else {
526 freeit:
527 			free_client_lease(lp);
528 		}
529 	}
530 	client->offered_leases = NULL;
531 
532 	/* If we just tossed all the leases we were offered, go back
533 	   to square one. */
534 	if (!picked) {
535 		client->state = S_INIT;
536 		state_init();
537 		return;
538 	}
539 
540 	/* If it was a BOOTREPLY, we can just take the address right now. */
541 	if (!picked->options[DHO_DHCP_MESSAGE_TYPE].len) {
542 		client->new = picked;
543 
544 		/* Make up some lease expiry times
545 		   XXX these should be configurable. */
546 		client->new->expiry = cur_time + 12000;
547 		client->new->renewal += cur_time + 8000;
548 		client->new->rebind += cur_time + 10000;
549 
550 		client->state = S_REQUESTING;
551 
552 		/* Bind to the address we received. */
553 		bind_lease();
554 		return;
555 	}
556 
557 	/* Go to the REQUESTING state. */
558 	client->destination = iaddr_broadcast;
559 	client->state = S_REQUESTING;
560 	client->first_sending = cur_time;
561 	client->interval = config->initial_interval;
562 
563 	/* Make a DHCPREQUEST packet from the lease we picked. */
564 	make_request(picked);
565 	client->xid = client->packet.xid;
566 
567 	/* Toss the lease we picked - we'll get it back in a DHCPACK. */
568 	free_client_lease(picked);
569 
570 	/* Add an immediate timeout to send the first DHCPREQUEST packet. */
571 	send_request();
572 }
573 
574 /*
575  * state_requesting is called when we receive a DHCPACK message after
576  * having sent out one or more DHCPREQUEST packets.
577  */
578 void
dhcpack(struct iaddr client_addr,struct option_data * options)579 dhcpack(struct iaddr client_addr, struct option_data *options)
580 {
581 	struct client_lease *lease;
582 
583 	if (client->xid != client->packet.xid)
584 		return;
585 
586 	if (client->state != S_REBOOTING &&
587 	    client->state != S_REQUESTING &&
588 	    client->state != S_RENEWING &&
589 	    client->state != S_REBINDING)
590 		return;
591 
592 	note("DHCPACK from %s", piaddr(client_addr));
593 
594 	lease = packet_to_lease(client_addr, options);
595 	if (!lease) {
596 		note("packet_to_lease failed.");
597 		return;
598 	}
599 
600 	client->new = lease;
601 
602 	/* Stop resending DHCPREQUEST. */
603 	cancel_timeout(send_request);
604 
605 	/* Figure out the lease time. */
606 	if (client->new->options[DHO_DHCP_LEASE_TIME].data)
607 		client->new->expiry =
608 		    getULong(client->new->options[DHO_DHCP_LEASE_TIME].data);
609 	else
610 		client->new->expiry = default_lease_time;
611 	/* A number that looks negative here is really just very large,
612 	   because the lease expiry offset is unsigned. */
613 	if (client->new->expiry < 0)
614 		client->new->expiry = TIME_MAX;
615 	/* XXX should be fixed by resetting the client state */
616 	if (client->new->expiry < 60)
617 		client->new->expiry = 60;
618 
619 	/* Take the server-provided renewal time if there is one;
620 	   otherwise figure it out according to the spec. */
621 	if (client->new->options[DHO_DHCP_RENEWAL_TIME].len)
622 		client->new->renewal =
623 		    getULong(client->new->options[DHO_DHCP_RENEWAL_TIME].data);
624 	else
625 		client->new->renewal = client->new->expiry / 2;
626 
627 	/* Same deal with the rebind time. */
628 	if (client->new->options[DHO_DHCP_REBINDING_TIME].len)
629 		client->new->rebind =
630 		    getULong(client->new->options[DHO_DHCP_REBINDING_TIME].data);
631 	else
632 		client->new->rebind = client->new->renewal +
633 		    client->new->renewal / 2 + client->new->renewal / 4;
634 
635 	client->new->expiry += cur_time;
636 	/* Lease lengths can never be negative. */
637 	if (client->new->expiry < cur_time)
638 		client->new->expiry = TIME_MAX;
639 	client->new->renewal += cur_time;
640 	if (client->new->renewal < cur_time)
641 		client->new->renewal = TIME_MAX;
642 	client->new->rebind += cur_time;
643 	if (client->new->rebind < cur_time)
644 		client->new->rebind = TIME_MAX;
645 
646 	bind_lease();
647 }
648 
649 void
bind_lease(void)650 bind_lease(void)
651 {
652 	/* Remember the medium. */
653 	client->new->medium = client->medium;
654 
655 	/* Write out the new lease. */
656 	write_client_lease(client->new, 0);
657 
658 	/* Run the client script with the new parameters. */
659 	script_init((client->state == S_REQUESTING ? "BOUND" :
660 	    (client->state == S_RENEWING ? "RENEW" :
661 	    (client->state == S_REBOOTING ? "REBOOT" : "REBIND"))),
662 	    client->new->medium);
663 	if (client->active && client->state != S_REBOOTING)
664 		script_write_params("old_", client->active);
665 	script_write_params("new_", client->new);
666 	if (client->alias)
667 		script_write_params("alias_", client->alias);
668 	script_go();
669 
670 	/* Replace the old active lease with the new one. */
671 	if (client->active)
672 		free_client_lease(client->active);
673 	client->active = client->new;
674 	client->new = NULL;
675 
676 	/* Set up a timeout to start the renewal process. */
677 	add_timeout(client->active->renewal, state_bound);
678 
679 	note("bound to %s -- renewal in %ld seconds.",
680 	    piaddr(client->active->address),
681 	    (long)(client->active->renewal - cur_time));
682 	client->state = S_BOUND;
683 	reinitialize_interface();
684 	go_daemon();
685 }
686 
687 /*
688  * state_bound is called when we've successfully bound to a particular
689  * lease, but the renewal time on that lease has expired.   We are
690  * expected to unicast a DHCPREQUEST to the server that gave us our
691  * original lease.
692  */
693 void
state_bound(void)694 state_bound(void)
695 {
696 	/* T1 has expired. */
697 	make_request(client->active);
698 	client->xid = client->packet.xid;
699 
700 	if (client->active->options[DHO_DHCP_SERVER_IDENTIFIER].len == 4) {
701 		memcpy(client->destination.iabuf,
702 		    client->active->options[DHO_DHCP_SERVER_IDENTIFIER].data,
703 		    4);
704 		client->destination.len = 4;
705 	} else
706 		client->destination = iaddr_broadcast;
707 
708 	client->first_sending = cur_time;
709 	client->interval = config->initial_interval;
710 	client->state = S_RENEWING;
711 
712 	/* Send the first packet immediately. */
713 	send_request();
714 }
715 
716 void
dhcpoffer(struct iaddr client_addr,struct option_data * options)717 dhcpoffer(struct iaddr client_addr, struct option_data *options)
718 {
719 	struct client_lease *lease, *lp;
720 	int i;
721 	int arp_timeout_needed, stop_selecting;
722 	char *name = options[DHO_DHCP_MESSAGE_TYPE].len ? "DHCPOFFER" :
723 	    "BOOTREPLY";
724 
725 	if (client->xid != client->packet.xid)
726 		return;
727 
728 	if (client->state != S_SELECTING)
729 		return;
730 
731 	note("%s from %s", name, piaddr(client_addr));
732 
733 	/* If this lease doesn't supply the minimum required parameters,
734 	   blow it off. */
735 	for (i = 0; config->required_options[i]; i++) {
736 		if (!options[config->required_options[i]].len) {
737 			note("%s isn't satisfactory.", name);
738 			return;
739 		}
740 	}
741 
742 	/* If we've already seen this lease, don't record it again. */
743 	for (lease = client->offered_leases;
744 	    lease; lease = lease->next) {
745 		if (lease->address.len == sizeof(client->packet.yiaddr) &&
746 		    !memcmp(lease->address.iabuf,
747 		    &client->packet.yiaddr, lease->address.len)) {
748 			debug("%s already seen.", name);
749 			return;
750 		}
751 	}
752 
753 	lease = packet_to_lease(client_addr, options);
754 	if (!lease) {
755 		note("packet_to_lease failed.");
756 		return;
757 	}
758 
759 	/* If this lease was acquired through a BOOTREPLY, record that
760 	   fact. */
761 	if (!options[DHO_DHCP_MESSAGE_TYPE].len)
762 		lease->is_bootp = 1;
763 
764 	/* Record the medium under which this lease was offered. */
765 	lease->medium = client->medium;
766 
767 	/* Send out an ARP Request for the offered IP address. */
768 	script_init("ARPSEND", lease->medium);
769 	script_write_params("check_", lease);
770 	/* If the script can't send an ARP request without waiting,
771 	   we'll be waiting when we do the ARPCHECK, so don't wait now. */
772 	if (script_go())
773 		arp_timeout_needed = 0;
774 	else
775 		arp_timeout_needed = 2;
776 
777 	/* Figure out when we're supposed to stop selecting. */
778 	stop_selecting = client->first_sending + config->select_interval;
779 
780 	/* If this is the lease we asked for, put it at the head of the
781 	   list, and don't mess with the arp request timeout. */
782 	if (lease->address.len == client->requested_address.len &&
783 	    !memcmp(lease->address.iabuf,
784 	    client->requested_address.iabuf,
785 	    client->requested_address.len)) {
786 		lease->next = client->offered_leases;
787 		client->offered_leases = lease;
788 	} else {
789 		/* If we already have an offer, and arping for this
790 		   offer would take us past the selection timeout,
791 		   then don't extend the timeout - just hope for the
792 		   best. */
793 		if (client->offered_leases &&
794 		    (cur_time + arp_timeout_needed) > stop_selecting)
795 			arp_timeout_needed = 0;
796 
797 		/* Put the lease at the end of the list. */
798 		lease->next = NULL;
799 		if (!client->offered_leases)
800 			client->offered_leases = lease;
801 		else {
802 			for (lp = client->offered_leases; lp->next;
803 			    lp = lp->next)
804 				;	/* nothing */
805 			lp->next = lease;
806 		}
807 	}
808 
809 	/* If we're supposed to stop selecting before we've had time
810 	   to wait for the ARPREPLY, add some delay to wait for
811 	   the ARPREPLY. */
812 	if (stop_selecting - cur_time < arp_timeout_needed)
813 		stop_selecting = cur_time + arp_timeout_needed;
814 
815 	/* If the selecting interval has expired, go immediately to
816 	   state_selecting().  Otherwise, time out into
817 	   state_selecting at the select interval. */
818 	if (stop_selecting <= 0)
819 		state_selecting();
820 	else {
821 		add_timeout(stop_selecting, state_selecting);
822 		cancel_timeout(send_discover);
823 	}
824 }
825 
826 /*
827  * Allocate a client_lease structure and initialize it from the
828  * parameters in the specified packet.
829  */
830 struct client_lease *
packet_to_lease(struct iaddr client_addr,struct option_data * options)831 packet_to_lease(struct iaddr client_addr, struct option_data *options)
832 {
833 	struct client_lease *lease;
834 	int i;
835 
836 	lease = malloc(sizeof(struct client_lease));
837 
838 	if (!lease) {
839 		warning("dhcpoffer: no memory to record lease.");
840 		return (NULL);
841 	}
842 
843 	memset(lease, 0, sizeof(*lease));
844 
845 	/* Copy the lease options. */
846 	for (i = 0; i < 256; i++) {
847 		if (options[i].len) {
848 			lease->options[i] = options[i];
849 			options[i].data = NULL;
850 			options[i].len = 0;
851 			if (!check_option(lease, i)) {
852 				warning("Invalid lease option - ignoring offer");
853 				free_client_lease(lease);
854 				return (NULL);
855 			}
856 		}
857 	}
858 
859 	lease->address.len = sizeof(client->packet.yiaddr);
860 	memcpy(lease->address.iabuf, &client->packet.yiaddr,
861 	    lease->address.len);
862 
863 	/* If the server name was filled out, copy it. */
864 	if ((!options[DHO_DHCP_OPTION_OVERLOAD].len ||
865 	    !(options[DHO_DHCP_OPTION_OVERLOAD].data[0] & 2)) &&
866 	    client->packet.sname[0]) {
867 		lease->server_name = malloc(DHCP_SNAME_LEN + 1);
868 		if (!lease->server_name) {
869 			warning("dhcpoffer: no memory for server name.");
870 			free_client_lease(lease);
871 			return (NULL);
872 		}
873 		memcpy(lease->server_name, client->packet.sname,
874 		    DHCP_SNAME_LEN);
875 		lease->server_name[DHCP_SNAME_LEN] = '\0';
876 		if (!res_hnok(lease->server_name, false)) {
877 			warning("Bogus server name %s", lease->server_name);
878 			free(lease->server_name);
879 			lease->server_name = NULL;
880 		}
881 	}
882 
883 	/* Ditto for the filename. */
884 	if ((!options[DHO_DHCP_OPTION_OVERLOAD].len ||
885 	    !(options[DHO_DHCP_OPTION_OVERLOAD].data[0] & 1)) &&
886 	    client->packet.file[0]) {
887 		/* Don't count on the NUL terminator. */
888 		lease->filename = malloc(DHCP_FILE_LEN + 1);
889 		if (!lease->filename) {
890 			warning("dhcpoffer: no memory for filename.");
891 			free_client_lease(lease);
892 			return (NULL);
893 		}
894 		memcpy(lease->filename, client->packet.file, DHCP_FILE_LEN);
895 		lease->filename[DHCP_FILE_LEN] = '\0';
896 	}
897 	return lease;
898 }
899 
900 void
dhcpnak(struct iaddr client_addr,struct option_data * options)901 dhcpnak(struct iaddr client_addr, struct option_data *options)
902 {
903 	if (client->xid != client->packet.xid)
904 		return;
905 
906 	if (client->state != S_REBOOTING &&
907 	    client->state != S_REQUESTING &&
908 	    client->state != S_RENEWING &&
909 	    client->state != S_REBINDING)
910 		return;
911 
912 	note("DHCPNAK from %s", piaddr(client_addr));
913 
914 	if (!client->active) {
915 		note("DHCPNAK with no active lease.");
916 		return;
917 	}
918 
919 	free_client_lease(client->active);
920 	client->active = NULL;
921 
922 	/* Stop sending DHCPREQUEST packets... */
923 	cancel_timeout(send_request);
924 
925 	client->state = S_INIT;
926 	state_init();
927 }
928 
929 /*
930  * Send out a DHCPDISCOVER packet, and set a timeout to send out another
931  * one after the right interval has expired.  If we don't get an offer by
932  * the time we reach the panic interval, call the panic function.
933  */
934 void
send_discover(void)935 send_discover(void)
936 {
937 	int interval, increase = 1;
938 
939 	/* Figure out how long it's been since we started transmitting. */
940 	interval = cur_time - client->first_sending;
941 
942 	/* If we're past the panic timeout, call the script and tell it
943 	   we haven't found anything for this interface yet. */
944 	if (interval > config->timeout) {
945 		state_panic();
946 		return;
947 	}
948 
949 	/* If we're selecting media, try the whole list before doing
950 	   the exponential backoff, but if we've already received an
951 	   offer, stop looping, because we obviously have it right. */
952 	if (!client->offered_leases && config->media) {
953 		int fail = 0;
954 again:
955 		if (client->medium) {
956 			client->medium = client->medium->next;
957 			increase = 0;
958 		}
959 		if (!client->medium) {
960 			if (fail)
961 				error("No valid media types for %s!", ifi->name);
962 			client->medium = config->media;
963 			increase = 1;
964 		}
965 
966 		note("Trying medium \"%s\" %d", client->medium->string,
967 		    increase);
968 		script_init("MEDIUM", client->medium);
969 		if (script_go())
970 			goto again;
971 	}
972 
973 	/*
974 	 * If we're supposed to increase the interval, do so.  If it's
975 	 * currently zero (i.e., we haven't sent any packets yet), set
976 	 * it to initial_interval; otherwise, add to it a random
977 	 * number between zero and two times itself.  On average, this
978 	 * means that it will double with every transmission.
979 	 */
980 	if (increase) {
981 		if (!client->interval)
982 			client->interval = config->initial_interval;
983 		else {
984 			client->interval += (arc4random() >> 2) %
985 			    (2 * client->interval);
986 		}
987 
988 		/* Don't backoff past cutoff. */
989 		if (client->interval > config->backoff_cutoff)
990 			client->interval = ((config->backoff_cutoff / 2)
991 				 + ((arc4random() >> 2) %
992 				    config->backoff_cutoff));
993 	} else if (!client->interval)
994 		client->interval = config->initial_interval;
995 
996 	/* If the backoff would take us to the panic timeout, just use that
997 	   as the interval. */
998 	if (cur_time + client->interval >
999 	    client->first_sending + config->timeout)
1000 		client->interval = (client->first_sending +
1001 			 config->timeout) - cur_time + 1;
1002 
1003 	/* Record the number of seconds since we started sending. */
1004 	if (interval < 65536)
1005 		client->packet.secs = htons(interval);
1006 	else
1007 		client->packet.secs = htons(65535);
1008 	client->secs = client->packet.secs;
1009 
1010 	note("DHCPDISCOVER on %s to %s port %d interval %ld",
1011 	    ifi->name, inet_ntoa(sockaddr_broadcast.sin_addr),
1012 	    ntohs(sockaddr_broadcast.sin_port), (long)client->interval);
1013 
1014 	/* Send out a packet. */
1015 	send_packet(inaddr_any, &sockaddr_broadcast, NULL);
1016 
1017 	add_timeout(cur_time + client->interval, send_discover);
1018 }
1019 
1020 /*
1021  * state_panic gets called if we haven't received any offers in a preset
1022  * amount of time.   When this happens, we try to use existing leases
1023  * that haven't yet expired, and failing that, we call the client script
1024  * and hope it can do something.
1025  */
1026 void
state_panic(void)1027 state_panic(void)
1028 {
1029 	struct client_lease *loop = client->active;
1030 	struct client_lease *lp;
1031 
1032 	note("No DHCPOFFERS received.");
1033 
1034 	/* We may not have an active lease, but we may have some
1035 	   predefined leases that we can try. */
1036 	if (!client->active && client->leases)
1037 		goto activate_next;
1038 
1039 	/* Run through the list of leases and see if one can be used. */
1040 	while (client->active) {
1041 		if (client->active->expiry > cur_time) {
1042 			note("Trying recorded lease %s",
1043 			    piaddr(client->active->address));
1044 			/* Run the client script with the existing
1045 			   parameters. */
1046 			script_init("TIMEOUT",
1047 			    client->active->medium);
1048 			script_write_params("new_", client->active);
1049 			if (client->alias)
1050 				script_write_params("alias_",
1051 				    client->alias);
1052 
1053 			/* If the old lease is still good and doesn't
1054 			   yet need renewal, go into BOUND state and
1055 			   timeout at the renewal time. */
1056 			if (!script_go()) {
1057 				if (cur_time <
1058 				    client->active->renewal) {
1059 					client->state = S_BOUND;
1060 					note("bound: renewal in %ld seconds.",
1061 					    (long)(client->active->renewal -
1062 					    cur_time));
1063 					add_timeout(client->active->renewal,
1064 					    state_bound);
1065 				} else {
1066 					client->state = S_BOUND;
1067 					note("bound: immediate renewal.");
1068 					state_bound();
1069 				}
1070 				reinitialize_interface();
1071 				go_daemon();
1072 				return;
1073 			}
1074 		}
1075 
1076 		/* If there are no other leases, give up. */
1077 		if (!client->leases) {
1078 			client->leases = client->active;
1079 			client->active = NULL;
1080 			break;
1081 		}
1082 
1083 activate_next:
1084 		/* Otherwise, put the active lease at the end of the
1085 		   lease list, and try another lease.. */
1086 		for (lp = client->leases; lp->next; lp = lp->next)
1087 			;
1088 		lp->next = client->active;
1089 		if (lp->next)
1090 			lp->next->next = NULL;
1091 		client->active = client->leases;
1092 		client->leases = client->leases->next;
1093 
1094 		/* If we already tried this lease, we've exhausted the
1095 		   set of leases, so we might as well give up for
1096 		   now. */
1097 		if (client->active == loop)
1098 			break;
1099 		else if (!loop)
1100 			loop = client->active;
1101 	}
1102 
1103 	/* No leases were available, or what was available didn't work, so
1104 	   tell the shell script that we failed to allocate an address,
1105 	   and try again later. */
1106 	note("No working leases in persistent database - sleeping.");
1107 	script_init("FAIL", NULL);
1108 	if (client->alias)
1109 		script_write_params("alias_", client->alias);
1110 	script_go();
1111 	client->state = S_INIT;
1112 	add_timeout(cur_time + config->retry_interval, state_init);
1113 	go_daemon();
1114 }
1115 
1116 void
send_request(void)1117 send_request(void)
1118 {
1119 	struct sockaddr_in destination;
1120 	struct in_addr from;
1121 	int interval;
1122 
1123 	/* Figure out how long it's been since we started transmitting. */
1124 	interval = cur_time - client->first_sending;
1125 
1126 	/* If we're in the INIT-REBOOT or REQUESTING state and we're
1127 	   past the reboot timeout, go to INIT and see if we can
1128 	   DISCOVER an address... */
1129 	/* XXX In the INIT-REBOOT state, if we don't get an ACK, it
1130 	   means either that we're on a network with no DHCP server,
1131 	   or that our server is down.  In the latter case, assuming
1132 	   that there is a backup DHCP server, DHCPDISCOVER will get
1133 	   us a new address, but we could also have successfully
1134 	   reused our old address.  In the former case, we're hosed
1135 	   anyway.  This is not a win-prone situation. */
1136 	if ((client->state == S_REBOOTING ||
1137 	    client->state == S_REQUESTING) &&
1138 	    interval > config->reboot_timeout) {
1139 cancel:
1140 		client->state = S_INIT;
1141 		cancel_timeout(send_request);
1142 		state_init();
1143 		return;
1144 	}
1145 
1146 	/* If we're in the reboot state, make sure the media is set up
1147 	   correctly. */
1148 	if (client->state == S_REBOOTING &&
1149 	    !client->medium &&
1150 	    client->active->medium) {
1151 		script_init("MEDIUM", client->active->medium);
1152 
1153 		/* If the medium we chose won't fly, go to INIT state. */
1154 		if (script_go())
1155 			goto cancel;
1156 
1157 		/* Record the medium. */
1158 		client->medium = client->active->medium;
1159 	}
1160 
1161 	/* If the lease has expired, relinquish the address and go back
1162 	   to the INIT state. */
1163 	if (client->state != S_REQUESTING &&
1164 	    cur_time > client->active->expiry) {
1165 		/* Run the client script with the new parameters. */
1166 		script_init("EXPIRE", NULL);
1167 		script_write_params("old_", client->active);
1168 		if (client->alias)
1169 			script_write_params("alias_", client->alias);
1170 		script_go();
1171 
1172 		/* Now do a preinit on the interface so that we can
1173 		   discover a new address. */
1174 		script_init("PREINIT", NULL);
1175 		if (client->alias)
1176 			script_write_params("alias_", client->alias);
1177 		script_go();
1178 
1179 		client->state = S_INIT;
1180 		state_init();
1181 		return;
1182 	}
1183 
1184 	/* Do the exponential backoff... */
1185 	if (!client->interval)
1186 		client->interval = config->initial_interval;
1187 	else
1188 		client->interval += ((arc4random() >> 2) %
1189 		    (2 * client->interval));
1190 
1191 	/* Don't backoff past cutoff. */
1192 	if (client->interval > config->backoff_cutoff)
1193 		client->interval = ((config->backoff_cutoff / 2) +
1194 		    ((arc4random() >> 2) % client->interval));
1195 
1196 	/* If the backoff would take us to the expiry time, just set the
1197 	   timeout to the expiry time. */
1198 	if (client->state != S_REQUESTING && cur_time + client->interval >
1199 	    client->active->expiry)
1200 		client->interval = client->active->expiry - cur_time + 1;
1201 
1202 	/* If the lease T2 time has elapsed, or if we're not yet bound,
1203 	   broadcast the DHCPREQUEST rather than unicasting. */
1204 	memset(&destination, 0, sizeof(destination));
1205 	if (client->state == S_REQUESTING ||
1206 	    client->state == S_REBOOTING ||
1207 	    cur_time > client->active->rebind)
1208 		destination.sin_addr.s_addr = INADDR_BROADCAST;
1209 	else
1210 		memcpy(&destination.sin_addr.s_addr, client->destination.iabuf,
1211 		    sizeof(destination.sin_addr.s_addr));
1212 	destination.sin_port = htons(REMOTE_PORT);
1213 	destination.sin_family = AF_INET;
1214 	destination.sin_len = sizeof(destination);
1215 
1216 	if (client->state != S_REQUESTING)
1217 		memcpy(&from, client->active->address.iabuf, sizeof(from));
1218 	else
1219 		from.s_addr = INADDR_ANY;
1220 
1221 	/* Record the number of seconds since we started sending. */
1222 	if (client->state == S_REQUESTING)
1223 		client->packet.secs = client->secs;
1224 	else {
1225 		if (interval < 65536)
1226 			client->packet.secs = htons(interval);
1227 		else
1228 			client->packet.secs = htons(65535);
1229 	}
1230 
1231 	note("DHCPREQUEST on %s to %s port %d", ifi->name,
1232 	    inet_ntoa(destination.sin_addr), ntohs(destination.sin_port));
1233 
1234 	/* Send out a packet. */
1235 	send_packet(from, &destination, NULL);
1236 
1237 	add_timeout(cur_time + client->interval, send_request);
1238 }
1239 
1240 void
send_decline(void)1241 send_decline(void)
1242 {
1243 	note("DHCPDECLINE on %s to %s port %d", ifi->name,
1244 	    inet_ntoa(sockaddr_broadcast.sin_addr),
1245 	    ntohs(sockaddr_broadcast.sin_port));
1246 
1247 	/* Send out a packet. */
1248 	send_packet(inaddr_any, &sockaddr_broadcast, NULL);
1249 }
1250 
1251 void
make_discover(struct client_lease * lease)1252 make_discover(struct client_lease *lease)
1253 {
1254 	unsigned char discover = DHCPDISCOVER;
1255 	struct option_data options[256];
1256 	int i;
1257 
1258 	memset(options, 0, sizeof(options));
1259 	memset(&client->packet, 0, sizeof(client->packet));
1260 
1261 	/* Set DHCP_MESSAGE_TYPE to DHCPDISCOVER */
1262 	i = DHO_DHCP_MESSAGE_TYPE;
1263 	options[i].data = &discover;
1264 	options[i].len = sizeof(discover);
1265 
1266 	/* Request the options we want */
1267 	i  = DHO_DHCP_PARAMETER_REQUEST_LIST;
1268 	options[i].data = config->requested_options;
1269 	options[i].len = config->requested_option_count;
1270 
1271 	/* If we had an address, try to get it again. */
1272 	if (lease) {
1273 		client->requested_address = lease->address;
1274 		i = DHO_DHCP_REQUESTED_ADDRESS;
1275 		options[i].data = lease->address.iabuf;
1276 		options[i].len = lease->address.len;
1277 	} else
1278 		client->requested_address.len = 0;
1279 
1280 	/* Send any options requested in the config file. */
1281 	for (i = 0; i < 256; i++)
1282 		if (!options[i].data &&
1283 		    config->send_options[i].data) {
1284 			options[i].data = config->send_options[i].data;
1285 			options[i].len = config->send_options[i].len;
1286 		}
1287 
1288 	/* Set up the option buffer to fit in a minimal UDP packet. */
1289 	i = cons_options(client->packet.options, 576 - DHCP_FIXED_LEN,
1290 	    options);
1291 	if (i == -1 || client->packet.options[i] != DHO_END)
1292 		error("options do not fit in DHCPDISCOVER packet.");
1293 	client->packet_length = DHCP_FIXED_NON_UDP+i+1;
1294 	if (client->packet_length < BOOTP_MIN_LEN)
1295 		client->packet_length = BOOTP_MIN_LEN;
1296 
1297 	client->packet.op = BOOTREQUEST;
1298 	client->packet.htype = ifi->hw_address.htype;
1299 	client->packet.hlen = ifi->hw_address.hlen;
1300 	client->packet.hops = 0;
1301 	client->packet.xid = arc4random();
1302 	client->packet.secs = 0; /* filled in by send_discover. */
1303 	client->packet.flags = 0;
1304 
1305 	memset(&client->packet.ciaddr, 0, sizeof(client->packet.ciaddr));
1306 	memset(&client->packet.yiaddr, 0, sizeof(client->packet.yiaddr));
1307 	memset(&client->packet.siaddr, 0, sizeof(client->packet.siaddr));
1308 	memset(&client->packet.giaddr, 0, sizeof(client->packet.giaddr));
1309 	memcpy(client->packet.chaddr, ifi->hw_address.haddr,
1310 	    ifi->hw_address.hlen);
1311 }
1312 
1313 void
make_request(struct client_lease * lease)1314 make_request(struct client_lease * lease)
1315 {
1316 	unsigned char request = DHCPREQUEST;
1317 	struct option_data options[256];
1318 	int i;
1319 
1320 	memset(options, 0, sizeof(options));
1321 	memset(&client->packet, 0, sizeof(client->packet));
1322 
1323 	/* Set DHCP_MESSAGE_TYPE to DHCPREQUEST */
1324 	i = DHO_DHCP_MESSAGE_TYPE;
1325 	options[i].data = &request;
1326 	options[i].len = sizeof(request);
1327 
1328 	/* Request the options we want */
1329 	i = DHO_DHCP_PARAMETER_REQUEST_LIST;
1330 	options[i].data = config->requested_options;
1331 	options[i].len = config->requested_option_count;
1332 
1333 	/* If we are requesting an address that hasn't yet been assigned
1334 	   to us, use the DHCP Requested Address option. */
1335 	if (client->state == S_REQUESTING) {
1336 		/* Send back the server identifier... */
1337 		i = DHO_DHCP_SERVER_IDENTIFIER;
1338 		options[i].data = lease->options[i].data;
1339 		options[i].len = lease->options[i].len;
1340 	}
1341 	if (client->state == S_REQUESTING ||
1342 	    client->state == S_REBOOTING) {
1343 		client->requested_address = lease->address;
1344 		i = DHO_DHCP_REQUESTED_ADDRESS;
1345 		options[i].data = lease->address.iabuf;
1346 		options[i].len = lease->address.len;
1347 	} else
1348 		client->requested_address.len = 0;
1349 
1350 	/* Send any options requested in the config file. */
1351 	for (i = 0; i < 256; i++)
1352 		if (!options[i].data && config->send_options[i].data) {
1353 			options[i].data = config->send_options[i].data;
1354 			options[i].len = config->send_options[i].len;
1355 		}
1356 
1357 	/* Set up the option buffer to fit in a minimal UDP packet. */
1358 	i = cons_options(client->packet.options, 576 - DHCP_FIXED_LEN,
1359 	    options);
1360 	if (i == -1 || client->packet.options[i] != DHO_END)
1361 		error("options do not fit in DHCPREQUEST packet.");
1362 	client->packet_length = DHCP_FIXED_NON_UDP+i+1;
1363 	if (client->packet_length < BOOTP_MIN_LEN)
1364 		client->packet_length = BOOTP_MIN_LEN;
1365 
1366 	client->packet.op = BOOTREQUEST;
1367 	client->packet.htype = ifi->hw_address.htype;
1368 	client->packet.hlen = ifi->hw_address.hlen;
1369 	client->packet.hops = 0;
1370 	client->packet.xid = client->xid;
1371 	client->packet.secs = 0; /* Filled in by send_request. */
1372 	client->packet.flags = 0;
1373 
1374 	/* If we own the address we're requesting, put it in ciaddr;
1375 	   otherwise set ciaddr to zero. */
1376 	if (client->state == S_BOUND ||
1377 	    client->state == S_RENEWING ||
1378 	    client->state == S_REBINDING) {
1379 		memcpy(&client->packet.ciaddr,
1380 		    lease->address.iabuf, lease->address.len);
1381 	} else {
1382 		memset(&client->packet.ciaddr, 0,
1383 		    sizeof(client->packet.ciaddr));
1384 	}
1385 
1386 	memset(&client->packet.yiaddr, 0, sizeof(client->packet.yiaddr));
1387 	memset(&client->packet.siaddr, 0, sizeof(client->packet.siaddr));
1388 	memset(&client->packet.giaddr, 0, sizeof(client->packet.giaddr));
1389 	memcpy(client->packet.chaddr, ifi->hw_address.haddr,
1390 	    ifi->hw_address.hlen);
1391 }
1392 
1393 void
make_decline(struct client_lease * lease)1394 make_decline(struct client_lease *lease)
1395 {
1396 	struct option_data options[256];
1397 	unsigned char decline = DHCPDECLINE;
1398 	int i;
1399 
1400 	memset(options, 0, sizeof(options));
1401 	memset(&client->packet, 0, sizeof(client->packet));
1402 
1403 	/* Set DHCP_MESSAGE_TYPE to DHCPDECLINE */
1404 	i = DHO_DHCP_MESSAGE_TYPE;
1405 	options[i].data = &decline;
1406 	options[i].len = sizeof(decline);
1407 
1408 	/* Send back the server identifier... */
1409 	i = DHO_DHCP_SERVER_IDENTIFIER;
1410 	options[i].data = lease->options[i].data;
1411 	options[i].len = lease->options[i].len;
1412 
1413 	/* Send back the address we're declining. */
1414 	i = DHO_DHCP_REQUESTED_ADDRESS;
1415 	options[i].data = lease->address.iabuf;
1416 	options[i].len = lease->address.len;
1417 
1418 	/* Send the uid if the user supplied one. */
1419 	i = DHO_DHCP_CLIENT_IDENTIFIER;
1420 	if (config->send_options[i].len) {
1421 		options[i].data = config->send_options[i].data;
1422 		options[i].len = config->send_options[i].len;
1423 	}
1424 
1425 	/* Set up the option buffer to fit in a minimal UDP packet. */
1426 	i = cons_options(client->packet.options, 576 - DHCP_FIXED_LEN,
1427 	    options);
1428 	if (i == -1 || client->packet.options[i] != DHO_END)
1429 		error("options do not fit in DHCPDECLINE packet.");
1430 	client->packet_length = DHCP_FIXED_NON_UDP+i+1;
1431 	if (client->packet_length < BOOTP_MIN_LEN)
1432 		client->packet_length = BOOTP_MIN_LEN;
1433 
1434 	client->packet.op = BOOTREQUEST;
1435 	client->packet.htype = ifi->hw_address.htype;
1436 	client->packet.hlen = ifi->hw_address.hlen;
1437 	client->packet.hops = 0;
1438 	client->packet.xid = client->xid;
1439 	client->packet.secs = 0; /* Filled in by send_request. */
1440 	client->packet.flags = 0;
1441 
1442 	/* ciaddr must always be zero. */
1443 	memset(&client->packet.ciaddr, 0, sizeof(client->packet.ciaddr));
1444 	memset(&client->packet.yiaddr, 0, sizeof(client->packet.yiaddr));
1445 	memset(&client->packet.siaddr, 0, sizeof(client->packet.siaddr));
1446 	memset(&client->packet.giaddr, 0, sizeof(client->packet.giaddr));
1447 	memcpy(client->packet.chaddr, ifi->hw_address.haddr,
1448 	    ifi->hw_address.hlen);
1449 }
1450 
1451 void
free_client_lease(struct client_lease * lease)1452 free_client_lease(struct client_lease *lease)
1453 {
1454 	int i;
1455 
1456 	if (lease->server_name)
1457 		free(lease->server_name);
1458 	if (lease->filename)
1459 		free(lease->filename);
1460 	for (i = 0; i < 256; i++) {
1461 		if (lease->options[i].len)
1462 			free(lease->options[i].data);
1463 	}
1464 	free(lease);
1465 }
1466 
1467 FILE *leaseFile;
1468 
1469 void
rewrite_client_leases(void)1470 rewrite_client_leases(void)
1471 {
1472 	struct client_lease *lp;
1473 
1474 	if (!leaseFile) {
1475 		leaseFile = fopen(path_dhclient_db, "w");
1476 		if (!leaseFile)
1477 			error("can't create %s: %m", path_dhclient_db);
1478 	} else {
1479 		fflush(leaseFile);
1480 		rewind(leaseFile);
1481 	}
1482 
1483 	for (lp = client->leases; lp; lp = lp->next)
1484 		write_client_lease(lp, 1);
1485 	if (client->active)
1486 		write_client_lease(client->active, 1);
1487 
1488 	fflush(leaseFile);
1489 	ftruncate(fileno(leaseFile), ftello(leaseFile));
1490 	fsync(fileno(leaseFile));
1491 }
1492 
1493 void
write_client_lease(struct client_lease * lease,int rewrite)1494 write_client_lease(struct client_lease *lease, int rewrite)
1495 {
1496 	static int leases_written;
1497 	struct tm *t;
1498 	int i;
1499 
1500 	if (!rewrite) {
1501 		if (leases_written++ > 20) {
1502 			rewrite_client_leases();
1503 			leases_written = 0;
1504 		}
1505 	}
1506 
1507 	/* If the lease came from the config file, we don't need to stash
1508 	   a copy in the lease database. */
1509 	if (lease->is_static)
1510 		return;
1511 
1512 	if (!leaseFile) {	/* XXX */
1513 		leaseFile = fopen(path_dhclient_db, "w");
1514 		if (!leaseFile)
1515 			error("can't create %s: %m", path_dhclient_db);
1516 	}
1517 
1518 	fprintf(leaseFile, "lease {\n");
1519 	if (lease->is_bootp)
1520 		fprintf(leaseFile, "  bootp;\n");
1521 	fprintf(leaseFile, "  interface \"%s\";\n", ifi->name);
1522 	fprintf(leaseFile, "  fixed-address %s;\n", piaddr(lease->address));
1523 	if (lease->filename)
1524 		fprintf(leaseFile, "  filename \"%s\";\n", lease->filename);
1525 	if (lease->server_name)
1526 		fprintf(leaseFile, "  server-name \"%s\";\n",
1527 		    lease->server_name);
1528 	if (lease->medium)
1529 		fprintf(leaseFile, "  medium \"%s\";\n", lease->medium->string);
1530 	for (i = 0; i < 256; i++)
1531 		if (lease->options[i].len)
1532 			fprintf(leaseFile, "  option %s %s;\n",
1533 			    dhcp_options[i].name,
1534 			    pretty_print_option(i, lease->options[i].data,
1535 			    lease->options[i].len, 1, 1));
1536 
1537 	t = gmtime(&lease->renewal);
1538 	fprintf(leaseFile, "  renew %d %d/%d/%d %02d:%02d:%02d;\n",
1539 	    t->tm_wday, (int)t->tm_year + 1900, t->tm_mon + 1, t->tm_mday,
1540 	    t->tm_hour, t->tm_min, t->tm_sec);
1541 	t = gmtime(&lease->rebind);
1542 	fprintf(leaseFile, "  rebind %d %d/%d/%d %02d:%02d:%02d;\n",
1543 	    t->tm_wday, (int)t->tm_year + 1900, t->tm_mon + 1, t->tm_mday,
1544 	    t->tm_hour, t->tm_min, t->tm_sec);
1545 	t = gmtime(&lease->expiry);
1546 	fprintf(leaseFile, "  expire %d %d/%d/%d %02d:%02d:%02d;\n",
1547 	    t->tm_wday, (int)t->tm_year + 1900, t->tm_mon + 1, t->tm_mday,
1548 	    t->tm_hour, t->tm_min, t->tm_sec);
1549 	fprintf(leaseFile, "}\n");
1550 	fflush(leaseFile);
1551 }
1552 
1553 void
script_init(char * reason,struct string_list * medium)1554 script_init(char *reason, struct string_list *medium)
1555 {
1556 	size_t		 len, mediumlen = 0;
1557 	struct imsg_hdr	 hdr;
1558 	struct buf	*buf;
1559 
1560 	if (medium != NULL && medium->string != NULL)
1561 		mediumlen = strlen(medium->string);
1562 
1563 	hdr.code = IMSG_SCRIPT_INIT;
1564 	hdr.len = sizeof(struct imsg_hdr) +
1565 	    sizeof(size_t) + mediumlen +
1566 	    sizeof(size_t) + strlen(reason);
1567 
1568 	buf = buf_open(hdr.len);
1569 
1570 	buf_add(buf, &hdr, sizeof(hdr));
1571 	buf_add(buf, &mediumlen, sizeof(mediumlen));
1572 	if (mediumlen > 0)
1573 		buf_add(buf, medium->string, mediumlen);
1574 	len = strlen(reason);
1575 	buf_add(buf, &len, sizeof(len));
1576 	buf_add(buf, reason, len);
1577 
1578 	buf_close(privfd, buf);
1579 }
1580 
1581 void
priv_script_init(char * reason,char * medium)1582 priv_script_init(char *reason, char *medium)
1583 {
1584 	client->scriptEnvsize = 100;
1585 	if (client->scriptEnv == NULL)
1586 		client->scriptEnv =
1587 		    malloc(client->scriptEnvsize * sizeof(char *));
1588 	if (client->scriptEnv == NULL)
1589 		error("script_init: no memory for environment");
1590 
1591 	client->scriptEnv[0] = strdup(CLIENT_PATH);
1592 	if (client->scriptEnv[0] == NULL)
1593 		error("script_init: no memory for environment");
1594 
1595 	client->scriptEnv[1] = NULL;
1596 
1597 	script_set_env("", "interface", ifi->name);
1598 
1599 	if (medium)
1600 		script_set_env("", "medium", medium);
1601 
1602 	script_set_env("", "reason", reason);
1603 }
1604 
1605 void
priv_script_write_params(char * prefix,struct client_lease * lease)1606 priv_script_write_params(char *prefix, struct client_lease *lease)
1607 {
1608 	u_int8_t dbuf[1500];
1609 	int i, len = 0;
1610 	char tbuf[128];
1611 
1612 	script_set_env(prefix, "ip_address", piaddr(lease->address));
1613 
1614 	if (lease->options[DHO_SUBNET_MASK].len &&
1615 	    (lease->options[DHO_SUBNET_MASK].len <
1616 	    sizeof(lease->address.iabuf))) {
1617 		struct iaddr netmask, subnet, broadcast;
1618 
1619 		memcpy(netmask.iabuf, lease->options[DHO_SUBNET_MASK].data,
1620 		    lease->options[DHO_SUBNET_MASK].len);
1621 		netmask.len = lease->options[DHO_SUBNET_MASK].len;
1622 
1623 		subnet = subnet_number(lease->address, netmask);
1624 		if (subnet.len) {
1625 			script_set_env(prefix, "network_number",
1626 			    piaddr(subnet));
1627 			if (!lease->options[DHO_BROADCAST_ADDRESS].len) {
1628 				broadcast = broadcast_addr(subnet, netmask);
1629 				if (broadcast.len)
1630 					script_set_env(prefix,
1631 					    "broadcast_address",
1632 					    piaddr(broadcast));
1633 			}
1634 		}
1635 	}
1636 
1637 	if (lease->filename)
1638 		script_set_env(prefix, "filename", lease->filename);
1639 	if (lease->server_name)
1640 		script_set_env(prefix, "server_name",
1641 		    lease->server_name);
1642 	for (i = 0; i < 256; i++) {
1643 		u_int8_t *dp = NULL;
1644 
1645 		if (config->defaults[i].len) {
1646 			if (lease->options[i].len) {
1647 				switch (config->default_actions[i]) {
1648 				case ACTION_DEFAULT:
1649 					dp = lease->options[i].data;
1650 					len = lease->options[i].len;
1651 					break;
1652 				case ACTION_SUPERSEDE:
1653 supersede:
1654 					dp = config->defaults[i].data;
1655 					len = config->defaults[i].len;
1656 					break;
1657 				case ACTION_PREPEND:
1658 					len = config->defaults[i].len +
1659 					    lease->options[i].len;
1660 					if (len > sizeof(dbuf)) {
1661 						warning("no space to %s %s",
1662 						    "prepend option",
1663 						    dhcp_options[i].name);
1664 						goto supersede;
1665 					}
1666 					dp = dbuf;
1667 					memcpy(dp,
1668 					    config->defaults[i].data,
1669 					    config->defaults[i].len);
1670 					memcpy(dp +
1671 					    config->defaults[i].len,
1672 					    lease->options[i].data,
1673 					    lease->options[i].len);
1674 					dp[len] = '\0';
1675 					break;
1676 				case ACTION_APPEND:
1677 					len = config->defaults[i].len +
1678 					    lease->options[i].len;
1679 					if (len > sizeof(dbuf)) {
1680 						warning("no space to %s %s",
1681 						    "append option",
1682 						    dhcp_options[i].name);
1683 						goto supersede;
1684 					}
1685 					dp = dbuf;
1686 					memcpy(dp, lease->options[i].data,
1687 					    lease->options[i].len);
1688 					memcpy(dp + lease->options[i].len,
1689 					    config->defaults[i].data,
1690 					    config->defaults[i].len);
1691 					dp[len] = '\0';
1692 				}
1693 			} else {
1694 				dp = config->defaults[i].data;
1695 				len = config->defaults[i].len;
1696 			}
1697 		} else if (lease->options[i].len) {
1698 			len = lease->options[i].len;
1699 			dp = lease->options[i].data;
1700 		} else {
1701 			len = 0;
1702 		}
1703 		if (len) {
1704 			char name[256];
1705 
1706 			if (dhcp_option_ev_name(name, sizeof(name),
1707 			    &dhcp_options[i]))
1708 				script_set_env(prefix, name,
1709 				    pretty_print_option(i, dp, len, 0, 0));
1710 		}
1711 	}
1712 	snprintf(tbuf, sizeof(tbuf), "%d", (int)lease->expiry);
1713 	script_set_env(prefix, "expiry", tbuf);
1714 }
1715 
1716 void
script_write_params(char * prefix,struct client_lease * lease)1717 script_write_params(char *prefix, struct client_lease *lease)
1718 {
1719 	size_t		 fn_len = 0, sn_len = 0, pr_len = 0;
1720 	struct imsg_hdr	 hdr;
1721 	struct buf	*buf;
1722 	int		 i;
1723 
1724 	if (lease->filename != NULL)
1725 		fn_len = strlen(lease->filename);
1726 	if (lease->server_name != NULL)
1727 		sn_len = strlen(lease->server_name);
1728 	if (prefix != NULL)
1729 		pr_len = strlen(prefix);
1730 
1731 	hdr.code = IMSG_SCRIPT_WRITE_PARAMS;
1732 	hdr.len = sizeof(hdr) + sizeof(struct client_lease) +
1733 	    sizeof(size_t) + fn_len + sizeof(size_t) + sn_len +
1734 	    sizeof(size_t) + pr_len;
1735 
1736 	for (i = 0; i < 256; i++)
1737 		hdr.len += sizeof(int) + lease->options[i].len;
1738 
1739 	scripttime = time(NULL);
1740 
1741 	buf = buf_open(hdr.len);
1742 
1743 	buf_add(buf, &hdr, sizeof(hdr));
1744 	buf_add(buf, lease, sizeof(struct client_lease));
1745 	buf_add(buf, &fn_len, sizeof(fn_len));
1746 	buf_add(buf, lease->filename, fn_len);
1747 	buf_add(buf, &sn_len, sizeof(sn_len));
1748 	buf_add(buf, lease->server_name, sn_len);
1749 	buf_add(buf, &pr_len, sizeof(pr_len));
1750 	buf_add(buf, prefix, pr_len);
1751 
1752 	for (i = 0; i < 256; i++) {
1753 		buf_add(buf, &lease->options[i].len,
1754 		    sizeof(lease->options[i].len));
1755 		buf_add(buf, lease->options[i].data,
1756 		    lease->options[i].len);
1757 	}
1758 
1759 	buf_close(privfd, buf);
1760 }
1761 
1762 int
script_go(void)1763 script_go(void)
1764 {
1765 	struct imsg_hdr	 hdr;
1766 	struct buf	*buf;
1767 	int		 ret;
1768 
1769 	scripttime = time(NULL);
1770 
1771 	hdr.code = IMSG_SCRIPT_GO;
1772 	hdr.len = sizeof(struct imsg_hdr);
1773 
1774 	buf = buf_open(hdr.len);
1775 
1776 	buf_add(buf, &hdr, sizeof(hdr));
1777 	buf_close(privfd, buf);
1778 
1779 	bzero(&hdr, sizeof(hdr));
1780 	buf_read(privfd, &hdr, sizeof(hdr));
1781 	if (hdr.code != IMSG_SCRIPT_GO_RET)
1782 		error("unexpected msg type %u", hdr.code);
1783 	if (hdr.len != sizeof(hdr) + sizeof(int))
1784 		error("received corrupted message");
1785 	buf_read(privfd, &ret, sizeof(ret));
1786 
1787 	return (ret);
1788 }
1789 
1790 int
priv_script_go(void)1791 priv_script_go(void)
1792 {
1793 	char *scriptName, *argv[2], **envp;
1794 	int pid, wpid, wstatus;
1795 
1796 	scripttime = time(NULL);
1797 
1798 	scriptName = config->script_name;
1799 	envp = client->scriptEnv;
1800 
1801 	argv[0] = scriptName;
1802 	argv[1] = NULL;
1803 
1804 	pid = fork();
1805 	if (pid < 0) {
1806 		error("fork: %m");
1807 		wstatus = 0;
1808 	} else if (pid) {
1809 		do {
1810 			wpid = wait(&wstatus);
1811 		} while (wpid != pid && wpid > 0);
1812 		if (wpid < 0) {
1813 			error("wait: %m");
1814 			wstatus = 0;
1815 		}
1816 	} else {
1817 		execve(scriptName, argv, envp);
1818 		error("execve (%s, ...): %m", scriptName);
1819 	}
1820 
1821 	script_flush_env();
1822 
1823 	return (wstatus & 0xff);
1824 }
1825 
1826 void
script_set_env(const char * prefix,const char * name,const char * value)1827 script_set_env(const char *prefix, const char *name, const char *value)
1828 {
1829 	int i, j, namelen;
1830 
1831 	namelen = strlen(name);
1832 
1833 	for (i = 0; client->scriptEnv[i]; i++)
1834 		if (strncmp(client->scriptEnv[i], name, namelen) == 0 &&
1835 		    client->scriptEnv[i][namelen] == '=')
1836 			break;
1837 
1838 	if (client->scriptEnv[i])
1839 		/* Reuse the slot. */
1840 		free(client->scriptEnv[i]);
1841 	else {
1842 		/* New variable.  Expand if necessary. */
1843 		if (i >= client->scriptEnvsize - 1) {
1844 			char **newscriptEnv;
1845 			int newscriptEnvsize = client->scriptEnvsize + 50;
1846 
1847 			newscriptEnv = realloc(client->scriptEnv,
1848 			    newscriptEnvsize);
1849 			if (newscriptEnv == NULL) {
1850 				free(client->scriptEnv);
1851 				client->scriptEnv = NULL;
1852 				client->scriptEnvsize = 0;
1853 				error("script_set_env: no memory for variable");
1854 			}
1855 			client->scriptEnv = newscriptEnv;
1856 			client->scriptEnvsize = newscriptEnvsize;
1857 		}
1858 		/* need to set the NULL pointer at end of array beyond
1859 		   the new slot. */
1860 		client->scriptEnv[i + 1] = NULL;
1861 	}
1862 	/* Allocate space and format the variable in the appropriate slot. */
1863 	client->scriptEnv[i] = malloc(strlen(prefix) + strlen(name) + 1 +
1864 	    strlen(value) + 1);
1865 	if (client->scriptEnv[i] == NULL)
1866 		error("script_set_env: no memory for variable assignment");
1867 
1868 	/* No `` or $() command substitution allowed in environment values! */
1869 	for (j = 0; j < strlen(value); j++)
1870 		switch (value[j]) {
1871 		case '`':
1872 		case '$':
1873 			error("illegal character (%c) in value '%s'", value[j],
1874 			    value);
1875 			/* not reached */
1876 		}
1877 	snprintf(client->scriptEnv[i], strlen(prefix) + strlen(name) +
1878 	    1 + strlen(value) + 1, "%s%s=%s", prefix, name, value);
1879 }
1880 
1881 void
script_flush_env(void)1882 script_flush_env(void)
1883 {
1884 	int i;
1885 
1886 	for (i = 0; client->scriptEnv[i]; i++) {
1887 		free(client->scriptEnv[i]);
1888 		client->scriptEnv[i] = NULL;
1889 	}
1890 	client->scriptEnvsize = 0;
1891 }
1892 
1893 int
dhcp_option_ev_name(char * buf,size_t buflen,const struct option * option)1894 dhcp_option_ev_name(char *buf, size_t buflen, const struct option *option)
1895 {
1896 	int i;
1897 
1898 	for (i = 0; option->name[i]; i++) {
1899 		if (i + 1 == buflen)
1900 			return 0;
1901 		if (option->name[i] == '-')
1902 			buf[i] = '_';
1903 		else
1904 			buf[i] = option->name[i];
1905 	}
1906 
1907 	buf[i] = 0;
1908 	return 1;
1909 }
1910 
1911 void
go_daemon(void)1912 go_daemon(void)
1913 {
1914 	static int state = 0;
1915 
1916 	if (no_daemon || state)
1917 		return;
1918 
1919 	state = 1;
1920 
1921 	/* Stop logging to stderr... */
1922 	log_perror = 0;
1923 
1924 	if (daemon(1, 0) == -1)
1925 		error("daemon");
1926 
1927 	/* we are chrooted, daemon(3) fails to open /dev/null */
1928 	if (nullfd != -1) {
1929 		dup2(nullfd, STDIN_FILENO);
1930 		dup2(nullfd, STDOUT_FILENO);
1931 		dup2(nullfd, STDERR_FILENO);
1932 		close(nullfd);
1933 		nullfd = -1;
1934 	}
1935 }
1936 
1937 int
check_option(struct client_lease * l,int option)1938 check_option(struct client_lease *l, int option)
1939 {
1940 	char *opbuf;
1941 	char *sbuf;
1942 
1943 	/* we use this, since this is what gets passed to dhclient-script */
1944 
1945 	opbuf = pretty_print_option(option, l->options[option].data,
1946 	    l->options[option].len, 0, 0);
1947 
1948 	sbuf = option_as_string(option, l->options[option].data,
1949 	    l->options[option].len);
1950 
1951 	switch (option) {
1952 	case DHO_SUBNET_MASK:
1953 	case DHO_TIME_SERVERS:
1954 	case DHO_NAME_SERVERS:
1955 	case DHO_ROUTERS:
1956 	case DHO_DOMAIN_NAME_SERVERS:
1957 	case DHO_LOG_SERVERS:
1958 	case DHO_COOKIE_SERVERS:
1959 	case DHO_LPR_SERVERS:
1960 	case DHO_IMPRESS_SERVERS:
1961 	case DHO_RESOURCE_LOCATION_SERVERS:
1962 	case DHO_SWAP_SERVER:
1963 	case DHO_BROADCAST_ADDRESS:
1964 	case DHO_NIS_SERVERS:
1965 	case DHO_NTP_SERVERS:
1966 	case DHO_NETBIOS_NAME_SERVERS:
1967 	case DHO_NETBIOS_DD_SERVER:
1968 	case DHO_FONT_SERVERS:
1969 	case DHO_DHCP_SERVER_IDENTIFIER:
1970 		if (!ipv4addrs(opbuf)) {
1971 			warning("Invalid IP address in option: %s", opbuf);
1972 			return (0);
1973 		}
1974 		return (1);
1975 	case DHO_HOST_NAME:
1976 	case DHO_DOMAIN_NAME:
1977 	case DHO_NIS_DOMAIN:
1978 		if (!res_hnok(sbuf, option == DHO_DOMAIN_NAME)) {
1979 			warning("Bogus Host Name option %d: %s (%s)", option,
1980 			    sbuf, opbuf);
1981 			l->options[option].len = 0;
1982 			free(l->options[option].data);
1983 		}
1984 		return (1);
1985 	case DHO_PAD:
1986 	case DHO_TIME_OFFSET:
1987 	case DHO_BOOT_SIZE:
1988 	case DHO_MERIT_DUMP:
1989 	case DHO_ROOT_PATH:
1990 	case DHO_EXTENSIONS_PATH:
1991 	case DHO_IP_FORWARDING:
1992 	case DHO_NON_LOCAL_SOURCE_ROUTING:
1993 	case DHO_POLICY_FILTER:
1994 	case DHO_MAX_DGRAM_REASSEMBLY:
1995 	case DHO_DEFAULT_IP_TTL:
1996 	case DHO_PATH_MTU_AGING_TIMEOUT:
1997 	case DHO_PATH_MTU_PLATEAU_TABLE:
1998 	case DHO_INTERFACE_MTU:
1999 	case DHO_ALL_SUBNETS_LOCAL:
2000 	case DHO_PERFORM_MASK_DISCOVERY:
2001 	case DHO_MASK_SUPPLIER:
2002 	case DHO_ROUTER_DISCOVERY:
2003 	case DHO_ROUTER_SOLICITATION_ADDRESS:
2004 	case DHO_STATIC_ROUTES:
2005 	case DHO_TRAILER_ENCAPSULATION:
2006 	case DHO_ARP_CACHE_TIMEOUT:
2007 	case DHO_IEEE802_3_ENCAPSULATION:
2008 	case DHO_DEFAULT_TCP_TTL:
2009 	case DHO_TCP_KEEPALIVE_INTERVAL:
2010 	case DHO_TCP_KEEPALIVE_GARBAGE:
2011 	case DHO_VENDOR_ENCAPSULATED_OPTIONS:
2012 	case DHO_NETBIOS_NODE_TYPE:
2013 	case DHO_NETBIOS_SCOPE:
2014 	case DHO_X_DISPLAY_MANAGER:
2015 	case DHO_DHCP_REQUESTED_ADDRESS:
2016 	case DHO_DHCP_LEASE_TIME:
2017 	case DHO_DHCP_OPTION_OVERLOAD:
2018 	case DHO_DHCP_MESSAGE_TYPE:
2019 	case DHO_DHCP_PARAMETER_REQUEST_LIST:
2020 	case DHO_DHCP_MESSAGE:
2021 	case DHO_DHCP_MAX_MESSAGE_SIZE:
2022 	case DHO_DHCP_RENEWAL_TIME:
2023 	case DHO_DHCP_REBINDING_TIME:
2024 	case DHO_DHCP_CLASS_IDENTIFIER:
2025 	case DHO_DHCP_CLIENT_IDENTIFIER:
2026 	case DHO_DHCP_USER_CLASS_ID:
2027 	case DHO_END:
2028 		return (1);
2029 	default:
2030 		warning("unknown dhcp option value 0x%x", option);
2031 		return (unknown_ok);
2032 	}
2033 }
2034 
2035 int
res_hnok(const char * name,bool wsp_ok)2036 res_hnok(const char *name, bool wsp_ok)
2037 {
2038 	const char *dn = name;
2039 	int pch = '.', ch = *dn++;
2040 	bool warn_us = false, warn_sp = false;
2041 	const char *warntext = NULL;
2042 
2043 	while (ch != '\0') {
2044 		int nch = *dn++;
2045 
2046 		if (ch == ' ' || ch == '\t') {
2047 			ch = '.';	/* reset to initial state */
2048 			if (!warn_sp) {
2049 				warntext = "whitespace";
2050 				warn_sp = true;
2051 			}
2052 		} else if (ch == '.') {
2053 			;
2054 		} else if (pch == '.' || nch == '.' || nch == '\0') {
2055 			if (!isalnum(ch))
2056 				return (0);
2057 		} else if (!isalnum(ch) && ch != '-' && ch != '_')
2058 				return (0);
2059 		else if (ch == '_' && !warn_us) {
2060 			warn_us = true;
2061 			warntext = "an underscore";
2062 		}
2063 		if (warntext) {
2064 			warning("warning: hostname %s contains %s "
2065 			    "which violates RFC 952", name, warntext);
2066 			warntext = NULL;
2067 		}
2068 		pch = ch, ch = nch;
2069 	}
2070 	return (1);
2071 }
2072 
2073 /* Does buf consist only of dotted decimal ipv4 addrs?
2074  * return how many if so,
2075  * otherwise, return 0
2076  */
2077 int
ipv4addrs(char * buf)2078 ipv4addrs(char * buf)
2079 {
2080 	struct in_addr jnk;
2081 	int count = 0;
2082 
2083 	while (inet_aton(buf, &jnk) == 1){
2084 		count++;
2085 		while (*buf == '.' || isdigit(*buf))
2086 			buf++;
2087 		if (*buf == '\0')
2088 			return (count);
2089 		while (*buf ==  ' ')
2090 			buf++;
2091 	}
2092 	return (0);
2093 }
2094 
2095 char *
option_as_string(unsigned int code,unsigned char * data,int len)2096 option_as_string(unsigned int code, unsigned char *data, int len)
2097 {
2098 	static char optbuf[32768]; /* XXX */
2099 	char *op = optbuf;
2100 	int opleft = sizeof(optbuf);
2101 	unsigned char *dp = data;
2102 
2103 	if (code > 255)
2104 		error("option_as_string: bad code %d", code);
2105 
2106 	for (; dp < data + len; dp++) {
2107 		if (!isascii(*dp) || !isprint(*dp)) {
2108 			if (dp + 1 != data + len || *dp != 0) {
2109 				snprintf(op, opleft, "\\%03o", *dp);
2110 				op += 4;
2111 				opleft -= 4;
2112 			}
2113 		} else if (*dp == '"' || *dp == '\'' || *dp == '$' ||
2114 		    *dp == '`' || *dp == '\\') {
2115 			*op++ = '\\';
2116 			*op++ = *dp;
2117 			opleft -= 2;
2118 		} else {
2119 			*op++ = *dp;
2120 			opleft--;
2121 		}
2122 	}
2123 	if (opleft < 1)
2124 		goto toobig;
2125 	*op = 0;
2126 	return optbuf;
2127 toobig:
2128 	warning("dhcp option too large");
2129 	return "<error>";
2130 }
2131 
2132 int
fork_privchld(int fd,int fd2)2133 fork_privchld(int fd, int fd2)
2134 {
2135 	struct pollfd pfd[1];
2136 	int nfds;
2137 
2138 	switch (fork()) {
2139 	case -1:
2140 		error("cannot fork");
2141 		break;
2142 	case 0:
2143 		break;
2144 	default:
2145 		return (0);
2146 	}
2147 
2148 	if (chdir("/") == -1)
2149 		error("chdir(\"/\")");
2150 
2151 	setproctitle("%s [priv]", ifi->name);
2152 
2153 	dup2(nullfd, STDIN_FILENO);
2154 	dup2(nullfd, STDOUT_FILENO);
2155 	dup2(nullfd, STDERR_FILENO);
2156 	close(nullfd);
2157 	close(fd2);
2158 
2159 	for (;;) {
2160 		pfd[0].fd = fd;
2161 		pfd[0].events = POLLIN;
2162 		if ((nfds = poll(pfd, 1, INFTIM)) == -1)
2163 			if (errno != EINTR)
2164 				error("poll error");
2165 
2166 		if (nfds == 0 || !(pfd[0].revents & POLLIN))
2167 			continue;
2168 
2169 		dispatch_imsg(fd);
2170 	}
2171 }
2172