xref: /dragonfly/contrib/dhcpcd/src/dhcp.c (revision b608d1d3)
1 /*
2  * dhcpcd - DHCP client daemon
3  * Copyright (c) 2006-2018 Roy Marples <roy@marples.name>
4  * All rights reserved
5 
6  * Redistribution and use in source and binary forms, with or without
7  * modification, are permitted provided that the following conditions
8  * are met:
9  * 1. Redistributions of source code must retain the above copyright
10  *    notice, this list of conditions and the following disclaimer.
11  * 2. Redistributions in binary form must reproduce the above copyright
12  *    notice, this list of conditions and the following disclaimer in the
13  *    documentation and/or other materials provided with the distribution.
14  *
15  * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND
16  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
17  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
18  * ARE DISCLAIMED.  IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
19  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
20  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
21  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
22  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
23  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
24  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
25  * SUCH DAMAGE.
26  */
27 
28 #include <sys/param.h>
29 #include <sys/socket.h>
30 #include <sys/stat.h>
31 
32 #include <arpa/inet.h>
33 #include <net/if.h>
34 #include <net/route.h>
35 #include <netinet/if_ether.h>
36 #include <netinet/in_systm.h>
37 #include <netinet/in.h>
38 #include <netinet/ip.h>
39 #define __FAVOR_BSD /* Nasty glibc hack so we can use BSD semantics for UDP */
40 #include <netinet/udp.h>
41 #undef __FAVOR_BSD
42 
43 #include <assert.h>
44 #include <ctype.h>
45 #include <errno.h>
46 #include <fcntl.h>
47 #include <inttypes.h>
48 #include <stdbool.h>
49 #include <stddef.h>
50 #include <stdlib.h>
51 #include <string.h>
52 #include <unistd.h>
53 
54 #define ELOOP_QUEUE 2
55 #include "config.h"
56 #include "arp.h"
57 #include "bpf.h"
58 #include "common.h"
59 #include "dhcp.h"
60 #include "dhcpcd.h"
61 #include "dhcp-common.h"
62 #include "duid.h"
63 #include "eloop.h"
64 #include "if.h"
65 #include "ipv4.h"
66 #include "ipv4ll.h"
67 #include "logerr.h"
68 #include "sa.h"
69 #include "script.h"
70 
71 #define DAD		"Duplicate address detected"
72 #define DHCP_MIN_LEASE	20
73 
74 #define IPV4A		ADDRIPV4 | ARRAY
75 #define IPV4R		ADDRIPV4 | REQUEST
76 
77 /* We should define a maximum for the NAK exponential backoff */
78 #define NAKOFF_MAX              60
79 
80 /* Wait N nanoseconds between sending a RELEASE and dropping the address.
81  * This gives the kernel enough time to actually send it. */
82 #define RELEASE_DELAY_S		0
83 #define RELEASE_DELAY_NS	10000000
84 
85 #ifndef IPDEFTTL
86 #define IPDEFTTL 64 /* RFC1340 */
87 #endif
88 
89 /* NetBSD-7 has an incomplete IP_PKTINFO implementation. */
90 #if defined(__NetBSD_Version__) && __NetBSD_Version__ < 800000000
91 #undef IP_PKTINFO
92 #endif
93 
94 /* Assert the correct structure size for on wire */
95 __CTASSERT(sizeof(struct ip)		== 20);
96 __CTASSERT(sizeof(struct udphdr)	== 8);
97 __CTASSERT(sizeof(struct bootp)		== 300);
98 
99 struct dhcp_op {
100 	uint8_t value;
101 	const char *name;
102 };
103 
104 static const struct dhcp_op dhcp_ops[] = {
105 	{ DHCP_DISCOVER,   "DISCOVER" },
106 	{ DHCP_OFFER,      "OFFER" },
107 	{ DHCP_REQUEST,    "REQUEST" },
108 	{ DHCP_DECLINE,    "DECLINE" },
109 	{ DHCP_ACK,        "ACK" },
110 	{ DHCP_NAK,        "NAK" },
111 	{ DHCP_RELEASE,    "RELEASE" },
112 	{ DHCP_INFORM,     "INFORM" },
113 	{ DHCP_FORCERENEW, "FORCERENEW"},
114 	{ 0, NULL }
115 };
116 
117 static const char * const dhcp_params[] = {
118 	"ip_address",
119 	"subnet_cidr",
120 	"network_number",
121 	"filename",
122 	"server_name",
123 	NULL
124 };
125 
126 static int dhcp_openbpf(struct interface *);
127 #ifdef ARP
128 static void dhcp_arp_conflicted(struct arp_state *, const struct arp_msg *);
129 #endif
130 static void dhcp_handledhcp(struct interface *, struct bootp *, size_t,
131     const struct in_addr *);
132 static int dhcp_initstate(struct interface *);
133 
134 void
135 dhcp_printoptions(const struct dhcpcd_ctx *ctx,
136     const struct dhcp_opt *opts, size_t opts_len)
137 {
138 	const char * const *p;
139 	size_t i, j;
140 	const struct dhcp_opt *opt, *opt2;
141 	int cols;
142 
143 	for (p = dhcp_params; *p; p++)
144 		printf("    %s\n", *p);
145 
146 	for (i = 0, opt = ctx->dhcp_opts; i < ctx->dhcp_opts_len; i++, opt++) {
147 		for (j = 0, opt2 = opts; j < opts_len; j++, opt2++)
148 			if (opt->option == opt2->option)
149 				break;
150 		if (j == opts_len) {
151 			cols = printf("%03d %s", opt->option, opt->var);
152 			dhcp_print_option_encoding(opt, cols);
153 		}
154 	}
155 	for (i = 0, opt = opts; i < opts_len; i++, opt++) {
156 		cols = printf("%03d %s", opt->option, opt->var);
157 		dhcp_print_option_encoding(opt, cols);
158 	}
159 }
160 
161 #define get_option_raw(ctx, bootp, bootp_len, opt)	\
162 	get_option((ctx), (bootp), (bootp_len), NULL)
163 static const uint8_t *
164 get_option(struct dhcpcd_ctx *ctx,
165     const struct bootp *bootp, size_t bootp_len,
166     unsigned int opt, size_t *opt_len)
167 {
168 	const uint8_t *p, *e;
169 	uint8_t l, o, ol, overl, *bp;
170 	const uint8_t *op;
171 	size_t bl;
172 
173 	/* Check we have the magic cookie */
174 	if (!IS_DHCP(bootp)) {
175 		errno = ENOTSUP;
176 		return NULL;
177 	}
178 
179 	p = bootp->vend + 4; /* options after the 4 byte cookie */
180 	e = (const uint8_t *)bootp + bootp_len;
181 	ol = o = overl = 0;
182 	bp = NULL;
183 	op = NULL;
184 	bl = 0;
185 	while (p < e) {
186 		o = *p++;
187 		switch (o) {
188 		case DHO_PAD:
189 			/* No length to read */
190 			continue;
191 		case DHO_END:
192 			if (overl & 1) {
193 				/* bit 1 set means parse boot file */
194 				overl = (uint8_t)(overl & ~1);
195 				p = bootp->file;
196 				e = p + sizeof(bootp->file);
197 			} else if (overl & 2) {
198 				/* bit 2 set means parse server name */
199 				overl = (uint8_t)(overl & ~2);
200 				p = bootp->sname;
201 				e = p + sizeof(bootp->sname);
202 			} else
203 				goto exit;
204 			/* No length to read */
205 			continue;
206 		}
207 
208 		/* Check we can read the length */
209 		if (p == e) {
210 			errno = EINVAL;
211 			return NULL;
212 		}
213 		l = *p++;
214 
215 		if (o == DHO_OPTSOVERLOADED) {
216 			/* Ensure we only get this option once by setting
217 			 * the last bit as well as the value.
218 			 * This is valid because only the first two bits
219 			 * actually mean anything in RFC2132 Section 9.3 */
220 			if (l == 1 && !overl)
221 				overl = 0x80 | p[0];
222 		}
223 
224 		if (o == opt) {
225 			if (op) {
226 				/* We must concatonate the options. */
227 				if (bl + l > ctx->opt_buffer_len) {
228 					size_t pos;
229 					uint8_t *nb;
230 
231 					if (bp)
232 						pos = (size_t)
233 						    (bp - ctx->opt_buffer);
234 					else
235 						pos = 0;
236 					nb = realloc(ctx->opt_buffer, bl + l);
237 					if (nb == NULL)
238 						return NULL;
239 					ctx->opt_buffer = nb;
240 					ctx->opt_buffer_len = bl + l;
241 					bp = ctx->opt_buffer + pos;
242 				}
243 				if (bp == NULL)
244 					bp = ctx->opt_buffer;
245 				memcpy(bp, op, ol);
246 				bp += ol;
247 			}
248 			ol = l;
249 			if (p + ol >= e) {
250 				errno = EINVAL;
251 				return NULL;
252 			}
253 			op = p;
254 			bl += ol;
255 		}
256 		p += l;
257 	}
258 
259 exit:
260 	if (opt_len)
261 		*opt_len = bl;
262 	if (bp) {
263 		memcpy(bp, op, ol);
264 		return (const uint8_t *)ctx->opt_buffer;
265 	}
266 	if (op)
267 		return op;
268 	errno = ENOENT;
269 	return NULL;
270 }
271 
272 static int
273 get_option_addr(struct dhcpcd_ctx *ctx,
274     struct in_addr *a, const struct bootp *bootp, size_t bootp_len,
275     uint8_t option)
276 {
277 	const uint8_t *p;
278 	size_t len;
279 
280 	p = get_option(ctx, bootp, bootp_len, option, &len);
281 	if (!p || len < (ssize_t)sizeof(a->s_addr))
282 		return -1;
283 	memcpy(&a->s_addr, p, sizeof(a->s_addr));
284 	return 0;
285 }
286 
287 static int
288 get_option_uint32(struct dhcpcd_ctx *ctx,
289     uint32_t *i, const struct bootp *bootp, size_t bootp_len, uint8_t option)
290 {
291 	const uint8_t *p;
292 	size_t len;
293 	uint32_t d;
294 
295 	p = get_option(ctx, bootp, bootp_len, option, &len);
296 	if (!p || len < (ssize_t)sizeof(d))
297 		return -1;
298 	memcpy(&d, p, sizeof(d));
299 	if (i)
300 		*i = ntohl(d);
301 	return 0;
302 }
303 
304 static int
305 get_option_uint16(struct dhcpcd_ctx *ctx,
306     uint16_t *i, const struct bootp *bootp, size_t bootp_len, uint8_t option)
307 {
308 	const uint8_t *p;
309 	size_t len;
310 	uint16_t d;
311 
312 	p = get_option(ctx, bootp, bootp_len, option, &len);
313 	if (!p || len < (ssize_t)sizeof(d))
314 		return -1;
315 	memcpy(&d, p, sizeof(d));
316 	if (i)
317 		*i = ntohs(d);
318 	return 0;
319 }
320 
321 static int
322 get_option_uint8(struct dhcpcd_ctx *ctx,
323     uint8_t *i, const struct bootp *bootp, size_t bootp_len, uint8_t option)
324 {
325 	const uint8_t *p;
326 	size_t len;
327 
328 	p = get_option(ctx, bootp, bootp_len, option, &len);
329 	if (!p || len < (ssize_t)sizeof(*p))
330 		return -1;
331 	if (i)
332 		*i = *(p);
333 	return 0;
334 }
335 
336 ssize_t
337 decode_rfc3442(char *out, size_t len, const uint8_t *p, size_t pl)
338 {
339 	const uint8_t *e;
340 	size_t bytes = 0, ocets;
341 	int b;
342 	uint8_t cidr;
343 	struct in_addr addr;
344 	char *o = out;
345 
346 	/* Minimum is 5 -first is CIDR and a router length of 4 */
347 	if (pl < 5) {
348 		errno = EINVAL;
349 		return -1;
350 	}
351 
352 	e = p + pl;
353 	while (p < e) {
354 		cidr = *p++;
355 		if (cidr > 32) {
356 			errno = EINVAL;
357 			return -1;
358 		}
359 		ocets = (size_t)(cidr + 7) / NBBY;
360 		if (p + 4 + ocets > e) {
361 			errno = ERANGE;
362 			return -1;
363 		}
364 		if (!out) {
365 			p += 4 + ocets;
366 			bytes += ((4 * 4) * 2) + 4;
367 			continue;
368 		}
369 		if ((((4 * 4) * 2) + 4) > len) {
370 			errno = ENOBUFS;
371 			return -1;
372 		}
373 		if (o != out) {
374 			*o++ = ' ';
375 			len--;
376 		}
377 		/* If we have ocets then we have a destination and netmask */
378 		if (ocets > 0) {
379 			addr.s_addr = 0;
380 			memcpy(&addr.s_addr, p, ocets);
381 			b = snprintf(o, len, "%s/%d", inet_ntoa(addr), cidr);
382 			p += ocets;
383 		} else
384 			b = snprintf(o, len, "0.0.0.0/0");
385 		o += b;
386 		len -= (size_t)b;
387 
388 		/* Finally, snag the router */
389 		memcpy(&addr.s_addr, p, 4);
390 		p += 4;
391 		b = snprintf(o, len, " %s", inet_ntoa(addr));
392 		o += b;
393 		len -= (size_t)b;
394 	}
395 
396 	if (out)
397 		return o - out;
398 	return (ssize_t)bytes;
399 }
400 
401 static int
402 decode_rfc3442_rt(struct rt_head *routes, struct interface *ifp,
403     const uint8_t *data, size_t dl, const struct bootp *bootp)
404 {
405 	const uint8_t *p = data;
406 	const uint8_t *e;
407 	uint8_t cidr;
408 	size_t ocets;
409 	struct rt *rt = NULL;
410 	struct in_addr dest, netmask, gateway;
411 	int n;
412 
413 	/* Minimum is 5 -first is CIDR and a router length of 4 */
414 	if (dl < 5) {
415 		errno = EINVAL;
416 		return -1;
417 	}
418 
419 	n = 0;
420 	e = p + dl;
421 	while (p < e) {
422 		cidr = *p++;
423 		if (cidr > 32) {
424 			errno = EINVAL;
425 			return -1;
426 		}
427 
428 		ocets = (size_t)(cidr + 7) / NBBY;
429 		if (p + 4 + ocets > e) {
430 			errno = ERANGE;
431 			return -1;
432 		}
433 
434 		if ((rt = rt_new(ifp)) == NULL)
435 			return -1;
436 
437 		/* If we have ocets then we have a destination and netmask */
438 		dest.s_addr = 0;
439 		if (ocets > 0) {
440 			memcpy(&dest.s_addr, p, ocets);
441 			p += ocets;
442 			netmask.s_addr = htonl(~0U << (32 - cidr));
443 		} else
444 			netmask.s_addr = 0;
445 
446 		/* Finally, snag the router */
447 		memcpy(&gateway.s_addr, p, 4);
448 		p += 4;
449 
450 		/* A host route is normally set by having the
451 		 * gateway match the destination or assigned address */
452 		if (gateway.s_addr == dest.s_addr ||
453 		    (gateway.s_addr == bootp->yiaddr ||
454 		    gateway.s_addr == bootp->ciaddr))
455 		{
456 			gateway.s_addr = INADDR_ANY;
457 			netmask.s_addr = INADDR_BROADCAST;
458 			rt->rt_flags = RTF_HOST;
459 		}
460 
461 		sa_in_init(&rt->rt_dest, &dest);
462 		sa_in_init(&rt->rt_netmask, &netmask);
463 		sa_in_init(&rt->rt_gateway, &gateway);
464 
465 		/* If CIDR is 32 then it's a host route. */
466 		if (cidr == 32)
467 			rt->rt_flags = RTF_HOST;
468 
469 		TAILQ_INSERT_TAIL(routes, rt, rt_next);
470 		n++;
471 	}
472 	return n;
473 }
474 
475 char *
476 decode_rfc3361(const uint8_t *data, size_t dl)
477 {
478 	uint8_t enc;
479 	size_t l;
480 	ssize_t r;
481 	char *sip = NULL;
482 	struct in_addr addr;
483 	char *p;
484 
485 	if (dl < 2) {
486 		errno = EINVAL;
487 		return 0;
488 	}
489 
490 	enc = *data++;
491 	dl--;
492 	switch (enc) {
493 	case 0:
494 		if ((r = decode_rfc1035(NULL, 0, data, dl)) > 0) {
495 			l = (size_t)r + 1;
496 			sip = malloc(l);
497 			if (sip == NULL)
498 				return 0;
499 			decode_rfc1035(sip, l, data, dl);
500 		}
501 		break;
502 	case 1:
503 		if (dl == 0 || dl % 4 != 0) {
504 			errno = EINVAL;
505 			break;
506 		}
507 		addr.s_addr = INADDR_BROADCAST;
508 		l = ((dl / sizeof(addr.s_addr)) * ((4 * 4) + 1)) + 1;
509 		sip = p = malloc(l);
510 		if (sip == NULL)
511 			return 0;
512 		while (dl != 0) {
513 			memcpy(&addr.s_addr, data, sizeof(addr.s_addr));
514 			data += sizeof(addr.s_addr);
515 			p += snprintf(p, l - (size_t)(p - sip),
516 			    "%s ", inet_ntoa(addr));
517 			dl -= sizeof(addr.s_addr);
518 		}
519 		*--p = '\0';
520 		break;
521 	default:
522 		errno = EINVAL;
523 		return 0;
524 	}
525 
526 	return sip;
527 }
528 
529 static char *
530 get_option_string(struct dhcpcd_ctx *ctx,
531     const struct bootp *bootp, size_t bootp_len, uint8_t option)
532 {
533 	size_t len;
534 	const uint8_t *p;
535 	char *s;
536 
537 	p = get_option(ctx, bootp, bootp_len, option, &len);
538 	if (!p || len == 0 || *p == '\0')
539 		return NULL;
540 
541 	s = malloc(sizeof(char) * (len + 1));
542 	if (s) {
543 		memcpy(s, p, len);
544 		s[len] = '\0';
545 	}
546 	return s;
547 }
548 
549 /* This calculates the netmask that we should use for static routes.
550  * This IS different from the calculation used to calculate the netmask
551  * for an interface address. */
552 static uint32_t
553 route_netmask(uint32_t ip_in)
554 {
555 	/* used to be unsigned long - check if error */
556 	uint32_t p = ntohl(ip_in);
557 	uint32_t t;
558 
559 	if (IN_CLASSA(p))
560 		t = ~IN_CLASSA_NET;
561 	else {
562 		if (IN_CLASSB(p))
563 			t = ~IN_CLASSB_NET;
564 		else {
565 			if (IN_CLASSC(p))
566 				t = ~IN_CLASSC_NET;
567 			else
568 				t = 0;
569 		}
570 	}
571 
572 	while (t & p)
573 		t >>= 1;
574 
575 	return (htonl(~t));
576 }
577 
578 /* We need to obey routing options.
579  * If we have a CSR then we only use that.
580  * Otherwise we add static routes and then routers. */
581 static int
582 get_option_routes(struct rt_head *routes, struct interface *ifp,
583     const struct bootp *bootp, size_t bootp_len)
584 {
585 	struct if_options *ifo = ifp->options;
586 	const uint8_t *p;
587 	const uint8_t *e;
588 	struct rt *rt = NULL;
589 	struct in_addr dest, netmask, gateway;
590 	size_t len;
591 	const char *csr = "";
592 	int n;
593 
594 	/* If we have CSR's then we MUST use these only */
595 	if (!has_option_mask(ifo->nomask, DHO_CSR))
596 		p = get_option(ifp->ctx, bootp, bootp_len, DHO_CSR, &len);
597 	else
598 		p = NULL;
599 	/* Check for crappy MS option */
600 	if (!p && !has_option_mask(ifo->nomask, DHO_MSCSR)) {
601 		p = get_option(ifp->ctx, bootp, bootp_len, DHO_MSCSR, &len);
602 		if (p)
603 			csr = "MS ";
604 	}
605 	if (p && (n = decode_rfc3442_rt(routes, ifp, p, len, bootp)) != -1) {
606 		const struct dhcp_state *state;
607 
608 		state = D_CSTATE(ifp);
609 		if (!(ifo->options & DHCPCD_CSR_WARNED) &&
610 		    !(state->added & STATE_FAKE))
611 		{
612 			logdebugx("%s: using %sClassless Static Routes",
613 			    ifp->name, csr);
614 			ifo->options |= DHCPCD_CSR_WARNED;
615 		}
616 		return n;
617 	}
618 
619 	n = 0;
620 	/* OK, get our static routes first. */
621 	if (!has_option_mask(ifo->nomask, DHO_STATICROUTE))
622 		p = get_option(ifp->ctx, bootp, bootp_len,
623 		    DHO_STATICROUTE, &len);
624 	else
625 		p = NULL;
626 	/* RFC 2131 Section 5.8 states length MUST be in multiples of 8 */
627 	if (p && len % 8 == 0) {
628 		e = p + len;
629 		while (p < e) {
630 			memcpy(&dest.s_addr, p, sizeof(dest.s_addr));
631 			p += 4;
632 			memcpy(&gateway.s_addr, p, sizeof(gateway.s_addr));
633 			p += 4;
634 			/* RFC 2131 Section 5.8 states default route is
635 			 * illegal */
636 			if (gateway.s_addr == INADDR_ANY)
637 				continue;
638 			if ((rt = rt_new(ifp)) == NULL)
639 				return -1;
640 
641 			/* A host route is normally set by having the
642 			 * gateway match the destination or assigned address */
643 			if (gateway.s_addr == dest.s_addr ||
644 			     (gateway.s_addr == bootp->yiaddr ||
645 			      gateway.s_addr == bootp->ciaddr))
646 			{
647 				gateway.s_addr = INADDR_ANY;
648 				netmask.s_addr = INADDR_BROADCAST;
649 				rt->rt_flags = RTF_HOST;
650 			} else
651 				netmask.s_addr = route_netmask(dest.s_addr);
652 			sa_in_init(&rt->rt_dest, &dest);
653 			sa_in_init(&rt->rt_netmask, &netmask);
654 			sa_in_init(&rt->rt_gateway, &gateway);
655 			TAILQ_INSERT_TAIL(routes, rt, rt_next);
656 			n++;
657 		}
658 	}
659 
660 	/* Now grab our routers */
661 	if (!has_option_mask(ifo->nomask, DHO_ROUTER))
662 		p = get_option(ifp->ctx, bootp, bootp_len, DHO_ROUTER, &len);
663 	else
664 		p = NULL;
665 	if (p) {
666 		e = p + len;
667 		dest.s_addr = INADDR_ANY;
668 		netmask.s_addr = INADDR_ANY;
669 		while (p < e) {
670 			if ((rt = rt_new(ifp)) == NULL)
671 				return -1;
672 			memcpy(&gateway.s_addr, p, sizeof(gateway.s_addr));
673 			p += 4;
674 			sa_in_init(&rt->rt_dest, &dest);
675 			sa_in_init(&rt->rt_netmask, &netmask);
676 			sa_in_init(&rt->rt_gateway, &gateway);
677 			TAILQ_INSERT_TAIL(routes, rt, rt_next);
678 			n++;
679 		}
680 	}
681 
682 	return n;
683 }
684 
685 uint16_t
686 dhcp_get_mtu(const struct interface *ifp)
687 {
688 	const struct dhcp_state *state;
689 	uint16_t mtu;
690 
691 	if (ifp->options->mtu)
692 		return (uint16_t)ifp->options->mtu;
693 	mtu = 0; /* bogus gcc warning */
694 	if ((state = D_CSTATE(ifp)) == NULL ||
695 	    has_option_mask(ifp->options->nomask, DHO_MTU) ||
696 	    get_option_uint16(ifp->ctx, &mtu,
697 			      state->new, state->new_len, DHO_MTU) == -1)
698 		return 0;
699 	return mtu;
700 }
701 
702 /* Grab our routers from the DHCP message and apply any MTU value
703  * the message contains */
704 int
705 dhcp_get_routes(struct rt_head *routes, struct interface *ifp)
706 {
707 	const struct dhcp_state *state;
708 
709 	if ((state = D_CSTATE(ifp)) == NULL || !(state->added & STATE_ADDED))
710 		return 0;
711 	return get_option_routes(routes, ifp, state->new, state->new_len);
712 }
713 
714 /* Assumes DHCP options */
715 static int
716 dhcp_message_add_addr(struct bootp *bootp,
717     uint8_t type, struct in_addr addr)
718 {
719 	uint8_t *p;
720 	size_t len;
721 
722 	p = bootp->vend;
723 	while (*p != DHO_END) {
724 		p++;
725 		p += *p + 1;
726 	}
727 
728 	len = (size_t)(p - bootp->vend);
729 	if (len + 6 > sizeof(bootp->vend)) {
730 		errno = ENOMEM;
731 		return -1;
732 	}
733 
734 	*p++ = type;
735 	*p++ = 4;
736 	memcpy(p, &addr.s_addr, 4);
737 	p += 4;
738 	*p = DHO_END;
739 	return 0;
740 }
741 
742 static ssize_t
743 make_message(struct bootp **bootpm, const struct interface *ifp, uint8_t type)
744 {
745 	struct bootp *bootp;
746 	uint8_t *lp, *p, *e;
747 	uint8_t *n_params = NULL;
748 	uint32_t ul;
749 	uint16_t sz;
750 	size_t len, i;
751 	const struct dhcp_opt *opt;
752 	struct if_options *ifo = ifp->options;
753 	const struct dhcp_state *state = D_CSTATE(ifp);
754 	const struct dhcp_lease *lease = &state->lease;
755 	char hbuf[HOSTNAME_MAX_LEN + 1];
756 	const char *hostname;
757 	const struct vivco *vivco;
758 	int mtu;
759 #ifdef AUTH
760 	uint8_t *auth, auth_len;
761 #endif
762 
763 	if ((mtu = if_getmtu(ifp)) == -1)
764 		logerr("%s: if_getmtu", ifp->name);
765 	else if (mtu < MTU_MIN) {
766 		if (if_setmtu(ifp, MTU_MIN) == -1)
767 			logerr("%s: if_setmtu", ifp->name);
768 		mtu = MTU_MIN;
769 	}
770 
771 	if (ifo->options & DHCPCD_BOOTP)
772 		bootp = calloc(1, sizeof (*bootp));
773 	else
774 		/* Make the maximal message we could send */
775 		bootp = calloc(1, (size_t)(mtu - IP_UDP_SIZE));
776 
777 	if (bootp == NULL)
778 		return -1;
779 	*bootpm = bootp;
780 
781 	if (state->addr != NULL &&
782 	    (type == DHCP_INFORM || type == DHCP_RELEASE ||
783 	    (type == DHCP_REQUEST &&
784 	    state->addr->mask.s_addr == lease->mask.s_addr &&
785 	    (state->new == NULL || IS_DHCP(state->new)) &&
786 	    !(state->added & STATE_FAKE))))
787 		bootp->ciaddr = state->addr->addr.s_addr;
788 
789 	bootp->op = BOOTREQUEST;
790 	bootp->htype = (uint8_t)ifp->family;
791 	switch (ifp->family) {
792 	case ARPHRD_ETHER:
793 	case ARPHRD_IEEE802:
794 		bootp->hlen = (uint8_t)ifp->hwlen;
795 		memcpy(&bootp->chaddr, &ifp->hwaddr, ifp->hwlen);
796 		break;
797 	}
798 
799 	if (ifo->options & DHCPCD_BROADCAST &&
800 	    bootp->ciaddr == 0 &&
801 	    type != DHCP_DECLINE &&
802 	    type != DHCP_RELEASE)
803 		bootp->flags = htons(BROADCAST_FLAG);
804 
805 	if (type != DHCP_DECLINE && type != DHCP_RELEASE) {
806 		struct timespec tv;
807 
808 		clock_gettime(CLOCK_MONOTONIC, &tv);
809 		timespecsub(&tv, &state->started, &tv);
810 		if (tv.tv_sec < 0 || tv.tv_sec > (time_t)UINT16_MAX)
811 			bootp->secs = htons((uint16_t)UINT16_MAX);
812 		else
813 			bootp->secs = htons((uint16_t)tv.tv_sec);
814 	}
815 
816 	bootp->xid = htonl(state->xid);
817 
818 	if (ifo->options & DHCPCD_BOOTP)
819 		return sizeof(*bootp);
820 
821 	p = bootp->vend;
822 	e = (uint8_t *)bootp + (mtu - IP_UDP_SIZE) - 1; /* -1 for DHO_END */
823 
824 	ul = htonl(MAGIC_COOKIE);
825 	memcpy(p, &ul, sizeof(ul));
826 	p += sizeof(ul);
827 
828 	*p++ = DHO_MESSAGETYPE;
829 	*p++ = 1;
830 	*p++ = type;
831 
832 #define AREA_LEFT	(size_t)(e - p)
833 #define AREA_FIT(s)	if ((s) > AREA_LEFT) goto toobig
834 #define AREA_CHECK(s)	if ((s) + 2UL > AREA_LEFT) goto toobig
835 #define PUT_ADDR(o, a)	do {		\
836 	AREA_CHECK(4);			\
837 	*p++ = (o);			\
838 	*p++ = 4;			\
839 	memcpy(p, &(a)->s_addr, 4);	\
840 	p += 4;				\
841 } while (0 /* CONSTCOND */)
842 
843 	if (state->clientid) {
844 		AREA_CHECK(state->clientid[0]);
845 		*p++ = DHO_CLIENTID;
846 		memcpy(p, state->clientid, (size_t)state->clientid[0] + 1);
847 		p += state->clientid[0] + 1;
848 	}
849 
850 	if (lease->addr.s_addr && lease->cookie == htonl(MAGIC_COOKIE)) {
851 		if (type == DHCP_DECLINE ||
852 		    (type == DHCP_REQUEST &&
853 		    (state->addr == NULL ||
854 		    state->added & STATE_FAKE ||
855 		    lease->addr.s_addr != state->addr->addr.s_addr)))
856 		{
857 			PUT_ADDR(DHO_IPADDRESS, &lease->addr);
858 			if (lease->server.s_addr)
859 				PUT_ADDR(DHO_SERVERID, &lease->server);
860 		}
861 
862 		if (type == DHCP_RELEASE) {
863 			if (lease->server.s_addr)
864 				PUT_ADDR(DHO_SERVERID, &lease->server);
865 		}
866 	}
867 
868 	if (type == DHCP_DECLINE) {
869 		len = strlen(DAD);
870 		if (len > AREA_LEFT) {
871 			*p++ = DHO_MESSAGE;
872 			*p++ = (uint8_t)len;
873 			memcpy(p, DAD, len);
874 			p += len;
875 		}
876 	}
877 
878 	if (type == DHCP_DISCOVER &&
879 	    !(ifp->ctx->options & DHCPCD_TEST) &&
880 	    has_option_mask(ifo->requestmask, DHO_RAPIDCOMMIT))
881 	{
882 		/* RFC 4039 Section 3 */
883 		AREA_CHECK(0);
884 		*p++ = DHO_RAPIDCOMMIT;
885 		*p++ = 0;
886 	}
887 
888 	if (type == DHCP_DISCOVER && ifo->options & DHCPCD_REQUEST)
889 		PUT_ADDR(DHO_IPADDRESS, &ifo->req_addr);
890 
891 	/* RFC 2563 Auto Configure */
892 	if (type == DHCP_DISCOVER && ifo->options & DHCPCD_IPV4LL) {
893 		AREA_CHECK(1);
894 		*p++ = DHO_AUTOCONFIGURE;
895 		*p++ = 1;
896 		*p++ = 1;
897 	}
898 
899 	if (type == DHCP_DISCOVER ||
900 	    type == DHCP_INFORM ||
901 	    type == DHCP_REQUEST)
902 	{
903 		if (mtu != -1) {
904 			AREA_CHECK(2);
905 			*p++ = DHO_MAXMESSAGESIZE;
906 			*p++ = 2;
907 			sz = htons((uint16_t)(mtu - IP_UDP_SIZE));
908 			memcpy(p, &sz, 2);
909 			p += 2;
910 		}
911 
912 		if (ifo->userclass[0]) {
913 			AREA_CHECK(ifo->userclass[0]);
914 			*p++ = DHO_USERCLASS;
915 			memcpy(p, ifo->userclass,
916 			    (size_t)ifo->userclass[0] + 1);
917 			p += ifo->userclass[0] + 1;
918 		}
919 
920 		if (ifo->vendorclassid[0]) {
921 			AREA_CHECK(ifo->vendorclassid[0]);
922 			*p++ = DHO_VENDORCLASSID;
923 			memcpy(p, ifo->vendorclassid,
924 			    (size_t)ifo->vendorclassid[0] + 1);
925 			p += ifo->vendorclassid[0] + 1;
926 		}
927 
928 		if (ifo->mudurl[0]) {
929 		       AREA_CHECK(ifo->mudurl[0]);
930 		       *p++ = DHO_MUDURL;
931 		       memcpy(p, ifo->mudurl, (size_t)ifo->mudurl[0] + 1);
932 		       p += ifo->mudurl[0] + 1;
933 		}
934 
935 		if (type != DHCP_INFORM) {
936 			if (ifo->leasetime != 0) {
937 				AREA_CHECK(4);
938 				*p++ = DHO_LEASETIME;
939 				*p++ = 4;
940 				ul = htonl(ifo->leasetime);
941 				memcpy(p, &ul, 4);
942 				p += 4;
943 			}
944 		}
945 
946 		hostname = dhcp_get_hostname(hbuf, sizeof(hbuf), ifo);
947 
948 		/*
949 		 * RFC4702 3.1 States that if we send the Client FQDN option
950 		 * then we MUST NOT also send the Host Name option.
951 		 * Technically we could, but that is not RFC conformant and
952 		 * also seems to break some DHCP server implemetations such as
953 		 * Windows. On the other hand, ISC dhcpd is just as non RFC
954 		 * conformant by not accepting a partially qualified FQDN.
955 		 */
956 		if (ifo->fqdn != FQDN_DISABLE) {
957 			/* IETF DHC-FQDN option (81), RFC4702 */
958 			i = 3;
959 			if (hostname)
960 				i += encode_rfc1035(hostname, NULL);
961 			AREA_CHECK(i);
962 			*p++ = DHO_FQDN;
963 			*p++ = (uint8_t)i;
964 			/*
965 			 * Flags: 0000NEOS
966 			 * S: 1 => Client requests Server to update
967 			 *         a RR in DNS as well as PTR
968 			 * O: 1 => Server indicates to client that
969 			 *         DNS has been updated
970 			 * E: 1 => Name data is DNS format
971 			 * N: 1 => Client requests Server to not
972 			 *         update DNS
973 			 */
974 			if (hostname)
975 				*p++ = (uint8_t)((ifo->fqdn & 0x09) | 0x04);
976 			else
977 				*p++ = (FQDN_NONE & 0x09) | 0x04;
978 			*p++ = 0; /* from server for PTR RR */
979 			*p++ = 0; /* from server for A RR if S=1 */
980 			if (hostname) {
981 				i = encode_rfc1035(hostname, p);
982 				p += i;
983 			}
984 		} else if (ifo->options & DHCPCD_HOSTNAME && hostname) {
985 			len = strlen(hostname);
986 			AREA_CHECK(len);
987 			*p++ = DHO_HOSTNAME;
988 			*p++ = (uint8_t)len;
989 			memcpy(p, hostname, len);
990 			p += len;
991 		}
992 
993 		/* vendor is already encoded correctly, so just add it */
994 		if (ifo->vendor[0]) {
995 			AREA_CHECK(ifo->vendor[0]);
996 			*p++ = DHO_VENDOR;
997 			memcpy(p, ifo->vendor, (size_t)ifo->vendor[0] + 1);
998 			p += ifo->vendor[0] + 1;
999 		}
1000 
1001 #ifdef AUTH
1002 		if ((ifo->auth.options & DHCPCD_AUTH_SENDREQUIRE) !=
1003 		    DHCPCD_AUTH_SENDREQUIRE)
1004 		{
1005 			/* We support HMAC-MD5 */
1006 			AREA_CHECK(1);
1007 			*p++ = DHO_FORCERENEW_NONCE;
1008 			*p++ = 1;
1009 			*p++ = AUTH_ALG_HMAC_MD5;
1010 		}
1011 #endif
1012 
1013 		if (ifo->vivco_len) {
1014 			AREA_CHECK(sizeof(ul));
1015 			*p++ = DHO_VIVCO;
1016 			lp = p++;
1017 			*lp = sizeof(ul);
1018 			ul = htonl(ifo->vivco_en);
1019 			memcpy(p, &ul, sizeof(ul));
1020 			p += sizeof(ul);
1021 			for (i = 0, vivco = ifo->vivco;
1022 			    i < ifo->vivco_len;
1023 			    i++, vivco++)
1024 			{
1025 				AREA_FIT(vivco->len);
1026 				if (vivco->len + 2 + *lp > 255) {
1027 					logerrx("%s: VIVCO option too big",
1028 					    ifp->name);
1029 					free(bootp);
1030 					return -1;
1031 				}
1032 				*p++ = (uint8_t)vivco->len;
1033 				memcpy(p, vivco->data, vivco->len);
1034 				p += vivco->len;
1035 				*lp = (uint8_t)(*lp + vivco->len + 1);
1036 			}
1037 		}
1038 
1039 		AREA_CHECK(0);
1040 		*p++ = DHO_PARAMETERREQUESTLIST;
1041 		n_params = p;
1042 		*p++ = 0;
1043 		for (i = 0, opt = ifp->ctx->dhcp_opts;
1044 		    i < ifp->ctx->dhcp_opts_len;
1045 		    i++, opt++)
1046 		{
1047 			if (!(opt->type & OT_REQUEST ||
1048 			    has_option_mask(ifo->requestmask, opt->option)))
1049 				continue;
1050 			if (opt->type & OT_NOREQ)
1051 				continue;
1052 			if (type == DHCP_INFORM &&
1053 			    (opt->option == DHO_RENEWALTIME ||
1054 				opt->option == DHO_REBINDTIME))
1055 				continue;
1056 			AREA_FIT(1);
1057 			*p++ = (uint8_t)opt->option;
1058 		}
1059 		for (i = 0, opt = ifo->dhcp_override;
1060 		    i < ifo->dhcp_override_len;
1061 		    i++, opt++)
1062 		{
1063 			/* Check if added above */
1064 			for (lp = n_params + 1; lp < p; lp++)
1065 				if (*lp == (uint8_t)opt->option)
1066 					break;
1067 			if (lp < p)
1068 				continue;
1069 			if (!(opt->type & OT_REQUEST ||
1070 			    has_option_mask(ifo->requestmask, opt->option)))
1071 				continue;
1072 			if (opt->type & OT_NOREQ)
1073 				continue;
1074 			if (type == DHCP_INFORM &&
1075 			    (opt->option == DHO_RENEWALTIME ||
1076 				opt->option == DHO_REBINDTIME))
1077 				continue;
1078 			AREA_FIT(1);
1079 			*p++ = (uint8_t)opt->option;
1080 		}
1081 		*n_params = (uint8_t)(p - n_params - 1);
1082 	}
1083 
1084 #ifdef AUTH
1085 	auth = NULL;	/* appease GCC */
1086 	auth_len = 0;
1087 	if (ifo->auth.options & DHCPCD_AUTH_SEND) {
1088 		ssize_t alen = dhcp_auth_encode(&ifo->auth,
1089 		    state->auth.token,
1090 		    NULL, 0, 4, type, NULL, 0);
1091 		if (alen != -1 && alen > UINT8_MAX) {
1092 			errno = ERANGE;
1093 			alen = -1;
1094 		}
1095 		if (alen == -1)
1096 			logerr("%s: dhcp_auth_encode", ifp->name);
1097 		else if (alen != 0) {
1098 			auth_len = (uint8_t)alen;
1099 			AREA_CHECK(auth_len);
1100 			*p++ = DHO_AUTHENTICATION;
1101 			*p++ = auth_len;
1102 			auth = p;
1103 			p += auth_len;
1104 		}
1105 	}
1106 #endif
1107 
1108 	*p++ = DHO_END;
1109 	len = (size_t)(p - (uint8_t *)bootp);
1110 
1111 	/* Pad out to the BOOTP message length.
1112 	 * Even if we send a DHCP packet with a variable length vendor area,
1113 	 * some servers / relay agents don't like packets smaller than
1114 	 * a BOOTP message which is fine because that's stipulated
1115 	 * in RFC1542 section 2.1. */
1116 	while (len < sizeof(*bootp)) {
1117 		*p++ = DHO_PAD;
1118 		len++;
1119 	}
1120 
1121 #ifdef AUTH
1122 	if (ifo->auth.options & DHCPCD_AUTH_SEND && auth_len != 0)
1123 		dhcp_auth_encode(&ifo->auth, state->auth.token,
1124 		    (uint8_t *)bootp, len, 4, type, auth, auth_len);
1125 #endif
1126 
1127 	return (ssize_t)len;
1128 
1129 toobig:
1130 	logerrx("%s: DHCP message too big", ifp->name);
1131 	free(bootp);
1132 	return -1;
1133 }
1134 
1135 static ssize_t
1136 write_lease(const struct interface *ifp, const struct bootp *bootp, size_t len)
1137 {
1138 	int fd;
1139 	ssize_t bytes;
1140 	const struct dhcp_state *state = D_CSTATE(ifp);
1141 
1142 	logdebugx("%s: writing lease `%s'", ifp->name, state->leasefile);
1143 
1144 	fd = open(state->leasefile, O_WRONLY | O_CREAT | O_TRUNC, 0644);
1145 	if (fd == -1)
1146 		return -1;
1147 	bytes = write(fd, bootp, len);
1148 	close(fd);
1149 	return bytes;
1150 }
1151 
1152 static size_t
1153 read_lease(struct interface *ifp, struct bootp **bootp)
1154 {
1155 	int fd;
1156 	bool fd_opened;
1157 	struct dhcp_state *state = D_STATE(ifp);
1158 	struct bootp *lease;
1159 	size_t bytes;
1160 	uint8_t type;
1161 #ifdef AUTH
1162 	const uint8_t *auth;
1163 	size_t auth_len;
1164 #endif
1165 
1166 	/* Safety */
1167 	*bootp = NULL;
1168 
1169 	if (state->leasefile[0] == '\0') {
1170 		fd = fileno(stdin);
1171 		fd_opened = false;
1172 	} else {
1173 		fd = open(state->leasefile, O_RDONLY);
1174 		fd_opened = true;
1175 	}
1176 	if (fd == -1) {
1177 		if (errno != ENOENT)
1178 			logerr("%s: open `%s'",
1179 			    ifp->name, state->leasefile);
1180 		return 0;
1181 	}
1182 	if (state->leasefile[0] == '\0')
1183 		logdebugx("reading standard input");
1184 	else
1185 		logdebugx("%s: reading lease `%s'",
1186 		    ifp->name, state->leasefile);
1187 
1188 	bytes = dhcp_read_lease_fd(fd, (void **)&lease);
1189 	if (fd_opened)
1190 		close(fd);
1191 	if (bytes == 0) {
1192 		free(lease);
1193 		logerr("%s: dhcp_read_lease_fd", __func__);
1194 		return 0;
1195 	}
1196 
1197 	/* Ensure the packet is at lease BOOTP sized
1198 	 * with a vendor area of 4 octets
1199 	 * (it should be more, and our read packet enforces this so this
1200 	 * code should not be needed, but of course people could
1201 	 * scribble whatever in the stored lease file. */
1202 	if (bytes < offsetof(struct bootp, vend) + 4) {
1203 		free(lease);
1204 		logerrx("%s: %s: truncated lease", ifp->name, __func__);
1205 		return 0;
1206 	}
1207 
1208 	if (ifp->ctx->options & DHCPCD_DUMPLEASE)
1209 		goto out;
1210 
1211 	/* We may have found a BOOTP server */
1212 	if (get_option_uint8(ifp->ctx, &type, (struct bootp *)lease, bytes,
1213 	    DHO_MESSAGETYPE) == -1)
1214 		type = 0;
1215 
1216 #ifdef AUTH
1217 	/* Authenticate the message */
1218 	auth = get_option(ifp->ctx, (struct bootp *)lease, bytes,
1219 	    DHO_AUTHENTICATION, &auth_len);
1220 	if (auth) {
1221 		if (dhcp_auth_validate(&state->auth, &ifp->options->auth,
1222 		    lease, bytes, 4, type, auth, auth_len) == NULL)
1223 		{
1224 			logerr("%s: authentication failed", ifp->name);
1225 			free(lease);
1226 			return 0;
1227 		}
1228 		if (state->auth.token)
1229 			logdebugx("%s: validated using 0x%08" PRIu32,
1230 			    ifp->name, state->auth.token->secretid);
1231 		else
1232 			logdebugx("%s: accepted reconfigure key", ifp->name);
1233 	} else if ((ifp->options->auth.options & DHCPCD_AUTH_SENDREQUIRE) ==
1234 	    DHCPCD_AUTH_SENDREQUIRE)
1235 	{
1236 		logerrx("%s: authentication now required", ifp->name);
1237 		free(lease);
1238 		return 0;
1239 	}
1240 #endif
1241 
1242 out:
1243 	*bootp = (struct bootp *)lease;
1244 	return bytes;
1245 }
1246 
1247 static const struct dhcp_opt *
1248 dhcp_getoverride(const struct if_options *ifo, unsigned int o)
1249 {
1250 	size_t i;
1251 	const struct dhcp_opt *opt;
1252 
1253 	for (i = 0, opt = ifo->dhcp_override;
1254 	    i < ifo->dhcp_override_len;
1255 	    i++, opt++)
1256 	{
1257 		if (opt->option == o)
1258 			return opt;
1259 	}
1260 	return NULL;
1261 }
1262 
1263 static const uint8_t *
1264 dhcp_getoption(struct dhcpcd_ctx *ctx,
1265     size_t *os, unsigned int *code, size_t *len,
1266     const uint8_t *od, size_t ol, struct dhcp_opt **oopt)
1267 {
1268 	size_t i;
1269 	struct dhcp_opt *opt;
1270 
1271 	if (od) {
1272 		if (ol < 2) {
1273 			errno = EINVAL;
1274 			return NULL;
1275 		}
1276 		*os = 2; /* code + len */
1277 		*code = (unsigned int)*od++;
1278 		*len = (size_t)*od++;
1279 		if (*len > ol - *os) {
1280 			errno = ERANGE;
1281 			return NULL;
1282 		}
1283 	}
1284 
1285 	*oopt = NULL;
1286 	for (i = 0, opt = ctx->dhcp_opts; i < ctx->dhcp_opts_len; i++, opt++) {
1287 		if (opt->option == *code) {
1288 			*oopt = opt;
1289 			break;
1290 		}
1291 	}
1292 
1293 	return od;
1294 }
1295 
1296 ssize_t
1297 dhcp_env(char **env, const char *prefix,
1298     const struct bootp *bootp, size_t bootp_len,
1299     const struct interface *ifp)
1300 {
1301 	const struct if_options *ifo;
1302 	const uint8_t *p;
1303 	struct in_addr addr;
1304 	struct in_addr net;
1305 	struct in_addr brd;
1306 	struct dhcp_opt *opt, *vo;
1307 	size_t e, i, pl;
1308 	char **ep;
1309 	char cidr[4], safe[(BOOTP_FILE_LEN * 4) + 1];
1310 	uint8_t overl = 0;
1311 	uint32_t en;
1312 
1313 	e = 0;
1314 	ifo = ifp->options;
1315 	if (get_option_uint8(ifp->ctx, &overl, bootp, bootp_len,
1316 	    DHO_OPTSOVERLOADED) == -1)
1317 		overl = 0;
1318 
1319 	if (env == NULL) {
1320 		if (bootp->yiaddr || bootp->ciaddr)
1321 			e += 5;
1322 		if (*bootp->file && !(overl & 1))
1323 			e++;
1324 		if (*bootp->sname && !(overl & 2))
1325 			e++;
1326 		for (i = 0, opt = ifp->ctx->dhcp_opts;
1327 		    i < ifp->ctx->dhcp_opts_len;
1328 		    i++, opt++)
1329 		{
1330 			if (has_option_mask(ifo->nomask, opt->option))
1331 				continue;
1332 			if (dhcp_getoverride(ifo, opt->option))
1333 				continue;
1334 			p = get_option(ifp->ctx, bootp, bootp_len,
1335 			    opt->option, &pl);
1336 			if (!p)
1337 				continue;
1338 			e += dhcp_envoption(ifp->ctx, NULL, NULL, ifp->name,
1339 			    opt, dhcp_getoption, p, pl);
1340 		}
1341 		for (i = 0, opt = ifo->dhcp_override;
1342 		    i < ifo->dhcp_override_len;
1343 		    i++, opt++)
1344 		{
1345 			if (has_option_mask(ifo->nomask, opt->option))
1346 				continue;
1347 			p = get_option(ifp->ctx, bootp, bootp_len,
1348 			    opt->option, &pl);
1349 			if (!p)
1350 				continue;
1351 			e += dhcp_envoption(ifp->ctx, NULL, NULL, ifp->name,
1352 			    opt, dhcp_getoption, p, pl);
1353 		}
1354 		return (ssize_t)e;
1355 	}
1356 
1357 	ep = env;
1358 	if (bootp->yiaddr || bootp->ciaddr) {
1359 		/* Set some useful variables that we derive from the DHCP
1360 		 * message but are not necessarily in the options */
1361 		addr.s_addr = bootp->yiaddr ? bootp->yiaddr : bootp->ciaddr;
1362 		addvar(&ep, prefix, "ip_address", inet_ntoa(addr));
1363 		if (get_option_addr(ifp->ctx, &net,
1364 		    bootp, bootp_len, DHO_SUBNETMASK) == -1)
1365 		{
1366 			net.s_addr = ipv4_getnetmask(addr.s_addr);
1367 			addvar(&ep, prefix,
1368 			    "subnet_mask", inet_ntoa(net));
1369 		}
1370 		snprintf(cidr, sizeof(cidr), "%d", inet_ntocidr(net));
1371 		addvar(&ep, prefix, "subnet_cidr", cidr);
1372 		if (get_option_addr(ifp->ctx, &brd,
1373 		    bootp, bootp_len, DHO_BROADCAST) == -1)
1374 		{
1375 			brd.s_addr = addr.s_addr | ~net.s_addr;
1376 			addvar(&ep, prefix,
1377 			    "broadcast_address", inet_ntoa(brd));
1378 		}
1379 		addr.s_addr = bootp->yiaddr & net.s_addr;
1380 		addvar(&ep, prefix,
1381 		    "network_number", inet_ntoa(addr));
1382 	}
1383 
1384 	if (*bootp->file && !(overl & 1)) {
1385 		print_string(safe, sizeof(safe), OT_STRING,
1386 		    bootp->file, sizeof(bootp->file));
1387 		addvar(&ep, prefix, "filename", safe);
1388 	}
1389 	if (*bootp->sname && !(overl & 2)) {
1390 		print_string(safe, sizeof(safe), OT_STRING | OT_DOMAIN,
1391 		    bootp->sname, sizeof(bootp->sname));
1392 		addvar(&ep, prefix, "server_name", safe);
1393 	}
1394 
1395 	/* Zero our indexes */
1396 	if (env) {
1397 		for (i = 0, opt = ifp->ctx->dhcp_opts;
1398 		    i < ifp->ctx->dhcp_opts_len;
1399 		    i++, opt++)
1400 			dhcp_zero_index(opt);
1401 		for (i = 0, opt = ifp->options->dhcp_override;
1402 		    i < ifp->options->dhcp_override_len;
1403 		    i++, opt++)
1404 			dhcp_zero_index(opt);
1405 		for (i = 0, opt = ifp->ctx->vivso;
1406 		    i < ifp->ctx->vivso_len;
1407 		    i++, opt++)
1408 			dhcp_zero_index(opt);
1409 	}
1410 
1411 	for (i = 0, opt = ifp->ctx->dhcp_opts;
1412 	    i < ifp->ctx->dhcp_opts_len;
1413 	    i++, opt++)
1414 	{
1415 		if (has_option_mask(ifo->nomask, opt->option))
1416 			continue;
1417 		if (dhcp_getoverride(ifo, opt->option))
1418 			continue;
1419 		p = get_option(ifp->ctx, bootp, bootp_len, opt->option, &pl);
1420 		if (p == NULL)
1421 			continue;
1422 		ep += dhcp_envoption(ifp->ctx, ep, prefix, ifp->name,
1423 		    opt, dhcp_getoption, p, pl);
1424 
1425 		if (opt->option != DHO_VIVSO || pl <= (int)sizeof(uint32_t))
1426 			continue;
1427 		memcpy(&en, p, sizeof(en));
1428 		en = ntohl(en);
1429 		vo = vivso_find(en, ifp);
1430 		if (vo == NULL)
1431 			continue;
1432 		/* Skip over en + total size */
1433 		p += sizeof(en) + 1;
1434 		pl -= sizeof(en) + 1;
1435 		ep += dhcp_envoption(ifp->ctx, ep, prefix, ifp->name,
1436 		    vo, dhcp_getoption, p, pl);
1437 	}
1438 
1439 	for (i = 0, opt = ifo->dhcp_override;
1440 	    i < ifo->dhcp_override_len;
1441 	    i++, opt++)
1442 	{
1443 		if (has_option_mask(ifo->nomask, opt->option))
1444 			continue;
1445 		p = get_option(ifp->ctx, bootp, bootp_len, opt->option, &pl);
1446 		if (p == NULL)
1447 			continue;
1448 		ep += dhcp_envoption(ifp->ctx, ep, prefix, ifp->name,
1449 		    opt, dhcp_getoption, p, pl);
1450 	}
1451 
1452 	return ep - env;
1453 }
1454 
1455 static void
1456 get_lease(struct interface *ifp,
1457     struct dhcp_lease *lease, const struct bootp *bootp, size_t len)
1458 {
1459 	struct dhcpcd_ctx *ctx;
1460 
1461 	assert(bootp != NULL);
1462 
1463 	memcpy(&lease->cookie, bootp->vend, sizeof(lease->cookie));
1464 	/* BOOTP does not set yiaddr for replies when ciaddr is set. */
1465 	lease->addr.s_addr = bootp->yiaddr ? bootp->yiaddr : bootp->ciaddr;
1466 	ctx = ifp->ctx;
1467 	if (ifp->options->options & (DHCPCD_STATIC | DHCPCD_INFORM)) {
1468 		if (ifp->options->req_addr.s_addr != INADDR_ANY) {
1469 			lease->mask = ifp->options->req_mask;
1470 			if (ifp->options->req_brd.s_addr != INADDR_ANY)
1471 				lease->brd = ifp->options->req_brd;
1472 			else
1473 				lease->brd.s_addr =
1474 				    lease->addr.s_addr | ~lease->mask.s_addr;
1475 		} else {
1476 			const struct ipv4_addr *ia;
1477 
1478 			ia = ipv4_iffindaddr(ifp, &lease->addr, NULL);
1479 			assert(ia != NULL);
1480 			lease->mask = ia->mask;
1481 			lease->brd = ia->brd;
1482 		}
1483 	} else {
1484 		if (get_option_addr(ctx, &lease->mask, bootp, len,
1485 		    DHO_SUBNETMASK) == -1)
1486 			lease->mask.s_addr =
1487 			    ipv4_getnetmask(lease->addr.s_addr);
1488 		if (get_option_addr(ctx, &lease->brd, bootp, len,
1489 		    DHO_BROADCAST) == -1)
1490 			lease->brd.s_addr =
1491 			    lease->addr.s_addr | ~lease->mask.s_addr;
1492 	}
1493 	if (get_option_uint32(ctx, &lease->leasetime,
1494 	    bootp, len, DHO_LEASETIME) != 0)
1495 		lease->leasetime = ~0U; /* Default to infinite lease */
1496 	if (get_option_uint32(ctx, &lease->renewaltime,
1497 	    bootp, len, DHO_RENEWALTIME) != 0)
1498 		lease->renewaltime = 0;
1499 	if (get_option_uint32(ctx, &lease->rebindtime,
1500 	    bootp, len, DHO_REBINDTIME) != 0)
1501 		lease->rebindtime = 0;
1502 	if (get_option_addr(ctx, &lease->server, bootp, len, DHO_SERVERID) != 0)
1503 		lease->server.s_addr = INADDR_ANY;
1504 }
1505 
1506 static const char *
1507 get_dhcp_op(uint8_t type)
1508 {
1509 	const struct dhcp_op *d;
1510 
1511 	for (d = dhcp_ops; d->name; d++)
1512 		if (d->value == type)
1513 			return d->name;
1514 	return NULL;
1515 }
1516 
1517 static void
1518 dhcp_fallback(void *arg)
1519 {
1520 	struct interface *iface;
1521 
1522 	iface = (struct interface *)arg;
1523 	dhcpcd_selectprofile(iface, iface->options->fallback);
1524 	dhcpcd_startinterface(iface);
1525 }
1526 
1527 static void
1528 dhcp_new_xid(struct interface *ifp)
1529 {
1530 	struct dhcp_state *state;
1531 	const struct interface *ifp1;
1532 	const struct dhcp_state *state1;
1533 
1534 	state = D_STATE(ifp);
1535 	if (ifp->options->options & DHCPCD_XID_HWADDR &&
1536 	    ifp->hwlen >= sizeof(state->xid))
1537 		/* The lower bits are probably more unique on the network */
1538 		memcpy(&state->xid,
1539 		    (ifp->hwaddr + ifp->hwlen) - sizeof(state->xid),
1540 		    sizeof(state->xid));
1541 	else {
1542 again:
1543 		state->xid = arc4random();
1544 	}
1545 
1546 	/* Ensure it's unique */
1547 	TAILQ_FOREACH(ifp1, ifp->ctx->ifaces, next) {
1548 		if (ifp == ifp1)
1549 			continue;
1550 		if ((state1 = D_CSTATE(ifp1)) == NULL)
1551 			continue;
1552 		if (state1->xid == state->xid)
1553 			break;
1554 	}
1555 	if (ifp1 != NULL) {
1556 		if (ifp->options->options & DHCPCD_XID_HWADDR &&
1557 		    ifp->hwlen >= sizeof(state->xid))
1558 		{
1559 			logerrx("%s: duplicate xid on %s",
1560 			    ifp->name, ifp1->name);
1561 			    return;
1562 		}
1563 		goto again;
1564 	}
1565 
1566 	/* We can't do this when sharing leases across interfaes */
1567 #if 0
1568 	/* As the XID changes, re-apply the filter. */
1569 	if (state->bpf_fd != -1) {
1570 		if (bpf_bootp(ifp, state->bpf_fd) == -1)
1571 			logerr(__func__); /* try to continue */
1572 	}
1573 #endif
1574 }
1575 
1576 void
1577 dhcp_close(struct interface *ifp)
1578 {
1579 	struct dhcp_state *state = D_STATE(ifp);
1580 
1581 	if (state == NULL)
1582 		return;
1583 
1584 	if (state->bpf_fd != -1) {
1585 		eloop_event_delete(ifp->ctx->eloop, state->bpf_fd);
1586 		bpf_close(ifp, state->bpf_fd);
1587 		state->bpf_fd = -1;
1588 		state->bpf_flags |= BPF_EOF;
1589 	}
1590 
1591 	state->interval = 0;
1592 }
1593 
1594 static int
1595 dhcp_openudp(struct interface *ifp)
1596 {
1597 	int s;
1598 	struct sockaddr_in sin;
1599 	int n;
1600 
1601 	if ((s = xsocket(PF_INET, SOCK_DGRAM|SOCK_CLOEXEC, IPPROTO_UDP)) == -1)
1602 		return -1;
1603 
1604 	n = 1;
1605 	if (setsockopt(s, SOL_SOCKET, SO_REUSEADDR, &n, sizeof(n)) == -1)
1606 		goto eexit;
1607 	memset(&sin, 0, sizeof(sin));
1608 	sin.sin_family = AF_INET;
1609 	sin.sin_port = htons(BOOTPC);
1610 	if (ifp) {
1611 		struct dhcp_state *state = D_STATE(ifp);
1612 
1613 		if (state->addr)
1614 			sin.sin_addr.s_addr = state->addr->addr.s_addr;
1615 	}
1616 	if (bind(s, (struct sockaddr *)&sin, sizeof(sin)) == -1)
1617 		goto eexit;
1618 
1619 	return s;
1620 
1621 eexit:
1622 	close(s);
1623 	return -1;
1624 }
1625 
1626 static uint16_t
1627 checksum(const void *data, size_t len)
1628 {
1629 	const uint8_t *addr = data;
1630 	uint32_t sum = 0;
1631 
1632 	while (len > 1) {
1633 		sum += (uint32_t)(addr[0] * 256 + addr[1]);
1634 		addr += 2;
1635 		len -= 2;
1636 	}
1637 
1638 	if (len == 1)
1639 		sum += (uint32_t)(*addr * 256);
1640 
1641 	sum = (sum >> 16) + (sum & 0xffff);
1642 	sum += (sum >> 16);
1643 
1644 	return (uint16_t)~htons((uint16_t)sum);
1645 }
1646 
1647 static struct bootp_pkt *
1648 dhcp_makeudppacket(size_t *sz, const uint8_t *data, size_t length,
1649 	struct in_addr source, struct in_addr dest)
1650 {
1651 	struct bootp_pkt *udpp;
1652 	struct ip *ip;
1653 	struct udphdr *udp;
1654 
1655 	if ((udpp = calloc(1, sizeof(*ip) + sizeof(*udp) + length)) == NULL)
1656 		return NULL;
1657 	ip = &udpp->ip;
1658 	udp = &udpp->udp;
1659 
1660 	/* OK, this is important :)
1661 	 * We copy the data to our packet and then create a small part of the
1662 	 * ip structure and an invalid ip_len (basically udp length).
1663 	 * We then fill the udp structure and put the checksum
1664 	 * of the whole packet into the udp checksum.
1665 	 * Finally we complete the ip structure and ip checksum.
1666 	 * If we don't do the ordering like so then the udp checksum will be
1667 	 * broken, so find another way of doing it! */
1668 
1669 	memcpy(&udpp->bootp, data, length);
1670 
1671 	ip->ip_p = IPPROTO_UDP;
1672 	ip->ip_src.s_addr = source.s_addr;
1673 	if (dest.s_addr == 0)
1674 		ip->ip_dst.s_addr = INADDR_BROADCAST;
1675 	else
1676 		ip->ip_dst.s_addr = dest.s_addr;
1677 
1678 	udp->uh_sport = htons(BOOTPC);
1679 	udp->uh_dport = htons(BOOTPS);
1680 	udp->uh_ulen = htons((uint16_t)(sizeof(*udp) + length));
1681 	ip->ip_len = udp->uh_ulen;
1682 	udp->uh_sum = checksum(udpp, sizeof(*ip) +  sizeof(*udp) + length);
1683 
1684 	ip->ip_v = IPVERSION;
1685 	ip->ip_hl = sizeof(*ip) >> 2;
1686 	ip->ip_id = (uint16_t)arc4random_uniform(UINT16_MAX);
1687 	ip->ip_ttl = IPDEFTTL;
1688 	ip->ip_len = htons((uint16_t)(sizeof(*ip) + sizeof(*udp) + length));
1689 	ip->ip_sum = checksum(ip, sizeof(*ip));
1690 
1691 	*sz = sizeof(*ip) + sizeof(*udp) + length;
1692 	return udpp;
1693 }
1694 
1695 static ssize_t
1696 dhcp_sendudp(struct interface *ifp, struct in_addr *to, void *data, size_t len)
1697 {
1698 	int s;
1699 	struct msghdr msg;
1700 	struct sockaddr_in sin;
1701 	struct iovec iov[1];
1702 	ssize_t r;
1703 #ifdef IP_PKTINFO
1704 	uint8_t cmsg[CMSG_SPACE(sizeof(struct in_pktinfo))];
1705 	struct cmsghdr *cm;
1706 	struct in_pktinfo ipi;
1707 #endif
1708 
1709 	iov[0].iov_base = data;
1710 	iov[0].iov_len = len;
1711 
1712 	memset(&sin, 0, sizeof(sin));
1713 	sin.sin_family = AF_INET;
1714 	sin.sin_addr = *to;
1715 	sin.sin_port = htons(BOOTPS);
1716 #ifdef HAVE_SA_LEN
1717 	sin.sin_len = sizeof(sin);
1718 #endif
1719 
1720 	memset(&msg, 0, sizeof(msg));
1721 	msg.msg_name = (void *)&sin;
1722 	msg.msg_namelen = sizeof(sin);
1723 	msg.msg_iov = iov;
1724 	msg.msg_iovlen = 1;
1725 
1726 #ifdef IP_PKTINFO
1727 	/* Set the outbound interface */
1728 	msg.msg_control = cmsg;
1729 	msg.msg_controllen = sizeof(cmsg);
1730 
1731 	memset(&ipi, 0, sizeof(ipi));
1732 	ipi.ipi_ifindex = ifp->index;
1733 	cm = CMSG_FIRSTHDR(&msg);
1734 	if (cm == NULL) {
1735 		errno = ESRCH;
1736 		return -1;
1737 	}
1738 	cm->cmsg_level = IPPROTO_IP;
1739 	cm->cmsg_type = IP_PKTINFO;
1740 	cm->cmsg_len = CMSG_LEN(sizeof(ipi));
1741 	memcpy(CMSG_DATA(cm), &ipi, sizeof(ipi));
1742 #endif
1743 
1744 	s = dhcp_openudp(ifp);
1745 	if (s == -1)
1746 		return -1;
1747 	r = sendmsg(s, &msg, 0);
1748 	close(s);
1749 	return r;
1750 }
1751 
1752 static void
1753 send_message(struct interface *ifp, uint8_t type,
1754     void (*callback)(void *))
1755 {
1756 	struct dhcp_state *state = D_STATE(ifp);
1757 	struct if_options *ifo = ifp->options;
1758 	struct bootp *bootp;
1759 	struct bootp_pkt *udp;
1760 	size_t len, ulen;
1761 	ssize_t r;
1762 	struct in_addr from, to;
1763 	struct timespec tv;
1764 
1765 	if (!callback) {
1766 		/* No carrier? Don't bother sending the packet. */
1767 		if (ifp->carrier == LINK_DOWN)
1768 			return;
1769 		logdebugx("%s: sending %s with xid 0x%x",
1770 		    ifp->name,
1771 		    ifo->options & DHCPCD_BOOTP ? "BOOTP" : get_dhcp_op(type),
1772 		    state->xid);
1773 	} else {
1774 		if (state->interval == 0)
1775 			state->interval = 4;
1776 		else {
1777 			state->interval *= 2;
1778 			if (state->interval > 64)
1779 				state->interval = 64;
1780 		}
1781 		tv.tv_sec = state->interval + DHCP_RAND_MIN;
1782 		tv.tv_nsec = (suseconds_t)arc4random_uniform(
1783 		    (DHCP_RAND_MAX - DHCP_RAND_MIN) * NSEC_PER_SEC);
1784 		timespecnorm(&tv);
1785 		/* No carrier? Don't bother sending the packet.
1786 		 * However, we do need to advance the timeout. */
1787 		if (ifp->carrier == LINK_DOWN)
1788 			goto fail;
1789 		logdebugx("%s: sending %s (xid 0x%x), next in %0.1f seconds",
1790 		    ifp->name,
1791 		    ifo->options & DHCPCD_BOOTP ? "BOOTP" : get_dhcp_op(type),
1792 		    state->xid,
1793 		    timespec_to_double(&tv));
1794 	}
1795 
1796 	r = make_message(&bootp, ifp, type);
1797 	if (r == -1)
1798 		goto fail;
1799 	len = (size_t)r;
1800 	from.s_addr = bootp->ciaddr;
1801 	if (from.s_addr != INADDR_ANY)
1802 		to.s_addr = state->lease.server.s_addr;
1803 	else
1804 		to.s_addr = INADDR_ANY;
1805 
1806 	/* If unicasting, try and void sending by BPF so we don't
1807 	 * use a L2 broadcast. */
1808 	if (to.s_addr != INADDR_ANY && to.s_addr != INADDR_BROADCAST) {
1809 		if (dhcp_sendudp(ifp, &to, bootp, len) != -1)
1810 			goto out;
1811 		logerr("%s: dhcp_sendudp", ifp->name);
1812 	}
1813 
1814 	if (dhcp_openbpf(ifp) == -1)
1815 		goto out;
1816 
1817 	udp = dhcp_makeudppacket(&ulen, (uint8_t *)bootp, len, from, to);
1818 	if (udp == NULL) {
1819 		logerr("%s: dhcp_makeudppacket", ifp->name);
1820 		r = 0;
1821 	} else {
1822 		r = bpf_send(ifp, state->bpf_fd,
1823 		    ETHERTYPE_IP, (uint8_t *)udp, ulen);
1824 		free(udp);
1825 	}
1826 	/* If we failed to send a raw packet this normally means
1827 	 * we don't have the ability to work beneath the IP layer
1828 	 * for this interface.
1829 	 * As such we remove it from consideration without actually
1830 	 * stopping the interface. */
1831 	if (r == -1) {
1832 		logerr("%s: if_sendraw", ifp->name);
1833 		switch(errno) {
1834 		case ENETDOWN:
1835 		case ENETRESET:
1836 		case ENETUNREACH:
1837 		case ENOBUFS:
1838 			break;
1839 		default:
1840 			if (!(ifp->ctx->options & DHCPCD_TEST))
1841 				dhcp_drop(ifp, "FAIL");
1842 			eloop_timeout_delete(ifp->ctx->eloop,
1843 			    NULL, ifp);
1844 			callback = NULL;
1845 		}
1846 	}
1847 
1848 out:
1849 	free(bootp);
1850 
1851 fail:
1852 	/* Even if we fail to send a packet we should continue as we are
1853 	 * as our failure timeouts will change out codepath when needed. */
1854 	if (callback)
1855 		eloop_timeout_add_tv(ifp->ctx->eloop, &tv, callback, ifp);
1856 }
1857 
1858 static void
1859 send_inform(void *arg)
1860 {
1861 
1862 	send_message((struct interface *)arg, DHCP_INFORM, send_inform);
1863 }
1864 
1865 static void
1866 send_discover(void *arg)
1867 {
1868 
1869 	send_message((struct interface *)arg, DHCP_DISCOVER, send_discover);
1870 }
1871 
1872 static void
1873 send_request(void *arg)
1874 {
1875 
1876 	send_message((struct interface *)arg, DHCP_REQUEST, send_request);
1877 }
1878 
1879 static void
1880 send_renew(void *arg)
1881 {
1882 
1883 	send_message((struct interface *)arg, DHCP_REQUEST, send_renew);
1884 }
1885 
1886 static void
1887 send_rebind(void *arg)
1888 {
1889 
1890 	send_message((struct interface *)arg, DHCP_REQUEST, send_rebind);
1891 }
1892 
1893 void
1894 dhcp_discover(void *arg)
1895 {
1896 	struct interface *ifp = arg;
1897 	struct dhcp_state *state = D_STATE(ifp);
1898 	struct if_options *ifo = ifp->options;
1899 
1900 	state->state = DHS_DISCOVER;
1901 	dhcp_new_xid(ifp);
1902 	eloop_timeout_delete(ifp->ctx->eloop, NULL, ifp);
1903 	if (ifo->fallback)
1904 		eloop_timeout_add_sec(ifp->ctx->eloop,
1905 		    ifo->reboot, dhcp_fallback, ifp);
1906 #ifdef IPV4LL
1907 	else if (ifo->options & DHCPCD_IPV4LL)
1908 		eloop_timeout_add_sec(ifp->ctx->eloop,
1909 		    ifo->reboot, ipv4ll_start, ifp);
1910 #endif
1911 	if (ifo->options & DHCPCD_REQUEST)
1912 		loginfox("%s: soliciting a DHCP lease (requesting %s)",
1913 		    ifp->name, inet_ntoa(ifo->req_addr));
1914 	else
1915 		loginfox("%s: soliciting a %s lease",
1916 		    ifp->name, ifo->options & DHCPCD_BOOTP ? "BOOTP" : "DHCP");
1917 	send_discover(ifp);
1918 }
1919 
1920 static void
1921 dhcp_request(void *arg)
1922 {
1923 	struct interface *ifp = arg;
1924 	struct dhcp_state *state = D_STATE(ifp);
1925 
1926 	state->state = DHS_REQUEST;
1927 	send_request(ifp);
1928 }
1929 
1930 static int
1931 dhcp_leaseextend(struct interface *ifp)
1932 {
1933 
1934 #ifdef ARP
1935 	if (ifp->options->options & DHCPCD_ARP) {
1936 		const struct dhcp_state *state;
1937 		struct arp_state *astate;
1938 
1939 		state = D_CSTATE(ifp);
1940 		if ((astate = arp_new(ifp, &state->lease.addr)) == NULL)
1941 			return -1;
1942 		astate->conflicted_cb = dhcp_arp_conflicted;
1943 
1944 #ifndef KERNEL_RFC5227
1945 		if (arp_open(ifp) == -1)
1946 			return -1;
1947 #endif
1948 
1949 		logwarnx("%s: extending lease until DaD failure or DHCP",
1950 		    ifp->name);
1951 		return 0;
1952 	}
1953 #endif
1954 
1955 	logwarnx("%s: extending lease", ifp->name);
1956 	return 0;
1957 }
1958 
1959 static void
1960 dhcp_expire1(struct interface *ifp)
1961 {
1962 	struct dhcp_state *state = D_STATE(ifp);
1963 
1964 	eloop_timeout_delete(ifp->ctx->eloop, NULL, ifp);
1965 	dhcp_drop(ifp, "EXPIRE");
1966 	unlink(state->leasefile);
1967 	state->interval = 0;
1968 	if (!(ifp->options->options & DHCPCD_LINK) || ifp->carrier != LINK_DOWN)
1969 		dhcp_discover(ifp);
1970 }
1971 
1972 static void
1973 dhcp_expire(void *arg)
1974 {
1975 	struct interface *ifp = arg;
1976 
1977 	logerrx("%s: DHCP lease expired", ifp->name);
1978 	if (ifp->options->options & DHCPCD_LASTLEASE_EXTEND) {
1979 		if (dhcp_leaseextend(ifp) == 0)
1980 			return;
1981 		logerr(__func__);
1982 	}
1983 	dhcp_expire1(ifp);
1984 }
1985 
1986 #if defined(ARP) || defined(IN_IFF_DUPLICATED)
1987 static void
1988 dhcp_decline(struct interface *ifp)
1989 {
1990 
1991 	send_message(ifp, DHCP_DECLINE, NULL);
1992 }
1993 #endif
1994 
1995 static void
1996 dhcp_startrenew(void *arg)
1997 {
1998 	struct interface *ifp = arg;
1999 	struct dhcp_state *state;
2000 	struct dhcp_lease *lease;
2001 
2002 	if ((state = D_STATE(ifp)) == NULL)
2003 		return;
2004 
2005 	/* Only renew in the bound or renew states */
2006 	if (state->state != DHS_BOUND &&
2007 	    state->state != DHS_RENEW)
2008 		return;
2009 
2010 	/* Remove the timeout as the renew may have been forced. */
2011 	eloop_timeout_delete(ifp->ctx->eloop, dhcp_startrenew, ifp);
2012 
2013 	lease = &state->lease;
2014 	logdebugx("%s: renewing lease of %s", ifp->name,
2015 	    inet_ntoa(lease->addr));
2016 	state->state = DHS_RENEW;
2017 	dhcp_new_xid(ifp);
2018 	state->interval = 0;
2019 	send_renew(ifp);
2020 }
2021 
2022 void
2023 dhcp_renew(struct interface *ifp)
2024 {
2025 
2026 	dhcp_startrenew(ifp);
2027 }
2028 
2029 static void
2030 dhcp_rebind(void *arg)
2031 {
2032 	struct interface *ifp = arg;
2033 	struct dhcp_state *state = D_STATE(ifp);
2034 	struct dhcp_lease *lease = &state->lease;
2035 
2036 	logwarnx("%s: failed to renew DHCP, rebinding", ifp->name);
2037 	logdebugx("%s: expire in %"PRIu32" seconds",
2038 	    ifp->name, lease->leasetime - lease->rebindtime);
2039 	state->state = DHS_REBIND;
2040 	eloop_timeout_delete(ifp->ctx->eloop, send_renew, ifp);
2041 	state->lease.server.s_addr = INADDR_ANY;
2042 	state->interval = 0;
2043 	ifp->options->options &= ~(DHCPCD_CSR_WARNED |
2044 	    DHCPCD_ROUTER_HOST_ROUTE_WARNED);
2045 	send_rebind(ifp);
2046 }
2047 
2048 #ifdef ARP
2049 static void
2050 dhcp_arp_probed(struct arp_state *astate)
2051 {
2052 	struct interface *ifp;
2053 	struct dhcp_state *state;
2054 	struct if_options *ifo;
2055 
2056 	ifp = astate->iface;
2057 	state = D_STATE(ifp);
2058 	ifo = ifp->options;
2059 #ifdef ARPING
2060 	if (ifo->arping_len && state->arping_index < ifo->arping_len) {
2061 		/* We didn't find a profile for this
2062 		 * address or hwaddr, so move to the next
2063 		 * arping profile */
2064 		if (++state->arping_index < ifo->arping_len) {
2065 			astate->addr.s_addr =
2066 			    ifo->arping[state->arping_index];
2067 			arp_probe(astate);
2068 			return;
2069 		}
2070 		arp_free(astate);
2071 #ifdef KERNEL_RFC5227
2072 		/* As arping is finished, close the ARP socket.
2073 		 * The kernel will handle ACD from here. */
2074 		arp_close(ifp);
2075 #endif
2076 		dhcpcd_startinterface(ifp);
2077 		return;
2078 	}
2079 #endif
2080 
2081 	/* Already bound so DAD has worked */
2082 	if (state->state == DHS_BOUND)
2083 		return;
2084 
2085 	logdebugx("%s: DAD completed for %s",
2086 	    ifp->name, inet_ntoa(astate->addr));
2087 	if (!(ifo->options & DHCPCD_INFORM))
2088 		dhcp_bind(ifp);
2089 #ifndef IN_IFF_TENTATIVE
2090 	else {
2091 		struct bootp *bootp;
2092 		size_t len;
2093 
2094 		bootp = state->new;
2095 		len = state->new_len;
2096 		state->new = state->offer;
2097 		state->new_len = state->offer_len;
2098 		get_lease(ifp, &state->lease, state->new, state->new_len);
2099 		ipv4_applyaddr(astate->iface);
2100 		state->new = bootp;
2101 		state->new_len = len;
2102 	}
2103 #endif
2104 
2105 	/* If we forked, stop here. */
2106 	if (ifp->ctx->options & DHCPCD_FORKED)
2107 		return;
2108 
2109 #ifdef IPV4LL
2110 	/* Stop IPv4LL now we have a working DHCP address */
2111 	ipv4ll_drop(ifp);
2112 #endif
2113 
2114 	if (ifo->options & DHCPCD_INFORM)
2115 		dhcp_inform(ifp);
2116 }
2117 
2118 static void
2119 dhcp_arp_conflicted(struct arp_state *astate, const struct arp_msg *amsg)
2120 {
2121 	struct interface *ifp;
2122 	struct dhcp_state *state;
2123 #ifdef ARPING
2124 	struct if_options *ifo;
2125 #endif
2126 
2127 	ifp = astate->iface;
2128 	state = D_STATE(ifp);
2129 
2130 #ifdef ARPING
2131 	ifo = ifp->options;
2132 	if (state->arping_index != -1 &&
2133 	    state->arping_index < ifo->arping_len &&
2134 	    amsg &&
2135 	    amsg->sip.s_addr == ifo->arping[state->arping_index])
2136 	{
2137 		char buf[HWADDR_LEN * 3];
2138 
2139 		astate->failed.s_addr = ifo->arping[state->arping_index];
2140 		arp_report_conflicted(astate, amsg);
2141 		hwaddr_ntoa(amsg->sha, ifp->hwlen, buf, sizeof(buf));
2142 		if (dhcpcd_selectprofile(ifp, buf) == -1 &&
2143 		    dhcpcd_selectprofile(ifp,
2144 		        inet_ntoa(astate->failed)) == -1)
2145 		{
2146 			/* We didn't find a profile for this
2147 			 * address or hwaddr, so move to the next
2148 			 * arping profile */
2149 			dhcp_arp_probed(astate);
2150 			return;
2151 		}
2152 		arp_free(astate);
2153 #ifdef KERNEL_RFC5227
2154 		/* As arping is finished, close the ARP socket.
2155 		 * The kernel will handle ACD from here. */
2156 		arp_close(ifp);
2157 #endif
2158 		eloop_timeout_delete(ifp->ctx->eloop, NULL, ifp);
2159 		dhcpcd_startinterface(ifp);
2160 		return;
2161 	}
2162 #endif
2163 
2164 	/* RFC 2131 3.1.5, Client-server interaction
2165 	 * NULL amsg means IN_IFF_DUPLICATED */
2166 	if (amsg == NULL || (state->offer &&
2167 	    (amsg->sip.s_addr == state->offer->yiaddr ||
2168 	    (amsg->sip.s_addr == 0 &&
2169 	    amsg->tip.s_addr == state->offer->yiaddr))))
2170 	{
2171 #ifdef IN_IFF_DUPLICATED
2172 		struct ipv4_addr *ia;
2173 #endif
2174 
2175 		if (amsg)
2176 			astate->failed.s_addr = state->offer->yiaddr;
2177 		else
2178 			astate->failed = astate->addr;
2179 		arp_report_conflicted(astate, amsg);
2180 		unlink(state->leasefile);
2181 #ifdef ARP
2182 		if (!(ifp->options->options & DHCPCD_STATIC) &&
2183 		    !state->lease.frominfo)
2184 			dhcp_decline(ifp);
2185 #endif
2186 #ifdef IN_IFF_DUPLICATED
2187 		if ((ia = ipv4_iffindaddr(ifp, &astate->addr, NULL)) != NULL)
2188 			ipv4_deladdr(ia, 1);
2189 #endif
2190 		arp_free(astate);
2191 		eloop_timeout_delete(ifp->ctx->eloop, NULL, ifp);
2192 		eloop_timeout_add_sec(ifp->ctx->eloop,
2193 		    DHCP_RAND_MAX, dhcp_discover, ifp);
2194 		return;
2195 	}
2196 
2197 	/* Bound address */
2198 	if (amsg && state->addr &&
2199 	    amsg->sip.s_addr == state->addr->addr.s_addr)
2200 	{
2201 		astate->failed = state->addr->addr;
2202 		arp_report_conflicted(astate, amsg);
2203 		if (state->state == DHS_BOUND) {
2204 			/* For now, just report the duplicated address */
2205 		} else {
2206 			arp_free(astate);
2207 			dhcp_expire1(ifp);
2208 		}
2209 		return;
2210 	}
2211 }
2212 #endif
2213 
2214 void
2215 dhcp_bind(struct interface *ifp)
2216 {
2217 	struct dhcp_state *state = D_STATE(ifp);
2218 	struct if_options *ifo = ifp->options;
2219 	struct dhcp_lease *lease = &state->lease;
2220 
2221 	state->reason = NULL;
2222 	/* If we don't have an offer, we are re-binding a lease on preference,
2223 	 * normally when two interfaces have a lease matching IP addresses. */
2224 	if (state->offer) {
2225 		free(state->old);
2226 		state->old = state->new;
2227 		state->old_len = state->new_len;
2228 		state->new = state->offer;
2229 		state->new_len = state->offer_len;
2230 		state->offer = NULL;
2231 		state->offer_len = 0;
2232 	}
2233 	get_lease(ifp, lease, state->new, state->new_len);
2234 	if (ifo->options & DHCPCD_STATIC) {
2235 		loginfox("%s: using static address %s/%d",
2236 		    ifp->name, inet_ntoa(lease->addr),
2237 		    inet_ntocidr(lease->mask));
2238 		lease->leasetime = ~0U;
2239 		state->reason = "STATIC";
2240 	} else if (ifo->options & DHCPCD_INFORM) {
2241 		loginfox("%s: received approval for %s",
2242 		    ifp->name, inet_ntoa(lease->addr));
2243 		lease->leasetime = ~0U;
2244 		state->reason = "INFORM";
2245 	} else {
2246 		if (lease->frominfo)
2247 			state->reason = "TIMEOUT";
2248 		if (lease->leasetime == ~0U) {
2249 			lease->renewaltime =
2250 			    lease->rebindtime =
2251 			    lease->leasetime;
2252 			loginfox("%s: leased %s for infinity",
2253 			   ifp->name, inet_ntoa(lease->addr));
2254 		} else {
2255 			if (lease->leasetime < DHCP_MIN_LEASE) {
2256 				logwarnx("%s: minimum lease is %d seconds",
2257 				    ifp->name, DHCP_MIN_LEASE);
2258 				lease->leasetime = DHCP_MIN_LEASE;
2259 			}
2260 			if (lease->rebindtime == 0)
2261 				lease->rebindtime =
2262 				    (uint32_t)(lease->leasetime * T2);
2263 			else if (lease->rebindtime >= lease->leasetime) {
2264 				lease->rebindtime =
2265 				    (uint32_t)(lease->leasetime * T2);
2266 				logwarnx("%s: rebind time greater than lease "
2267 				    "time, forcing to %"PRIu32" seconds",
2268 				    ifp->name, lease->rebindtime);
2269 			}
2270 			if (lease->renewaltime == 0)
2271 				lease->renewaltime =
2272 				    (uint32_t)(lease->leasetime * T1);
2273 			else if (lease->renewaltime > lease->rebindtime) {
2274 				lease->renewaltime =
2275 				    (uint32_t)(lease->leasetime * T1);
2276 				logwarnx("%s: renewal time greater than "
2277 				    "rebind time, forcing to %"PRIu32" seconds",
2278 				    ifp->name, lease->renewaltime);
2279 			}
2280 			if (state->addr &&
2281 			    lease->addr.s_addr == state->addr->addr.s_addr &&
2282 			    !(state->added & STATE_FAKE))
2283 				logdebugx("%s: leased %s for %"PRIu32" seconds",
2284 				    ifp->name, inet_ntoa(lease->addr),
2285 				    lease->leasetime);
2286 			else
2287 				loginfox("%s: leased %s for %"PRIu32" seconds",
2288 				    ifp->name, inet_ntoa(lease->addr),
2289 				    lease->leasetime);
2290 		}
2291 	}
2292 	if (ifp->ctx->options & DHCPCD_TEST) {
2293 		state->reason = "TEST";
2294 		script_runreason(ifp, state->reason);
2295 		eloop_exit(ifp->ctx->eloop, EXIT_SUCCESS);
2296 		return;
2297 	}
2298 	if (state->reason == NULL) {
2299 		if (state->old && !(state->added & STATE_FAKE)) {
2300 			if (state->old->yiaddr == state->new->yiaddr &&
2301 			    lease->server.s_addr &&
2302 			    state->state != DHS_REBIND)
2303 				state->reason = "RENEW";
2304 			else
2305 				state->reason = "REBIND";
2306 		} else if (state->state == DHS_REBOOT)
2307 			state->reason = "REBOOT";
2308 		else
2309 			state->reason = "BOUND";
2310 	}
2311 	if (lease->leasetime == ~0U)
2312 		lease->renewaltime = lease->rebindtime = lease->leasetime;
2313 	else {
2314 		eloop_timeout_add_sec(ifp->ctx->eloop,
2315 		    (time_t)lease->renewaltime, dhcp_startrenew, ifp);
2316 		eloop_timeout_add_sec(ifp->ctx->eloop,
2317 		    (time_t)lease->rebindtime, dhcp_rebind, ifp);
2318 		eloop_timeout_add_sec(ifp->ctx->eloop,
2319 		    (time_t)lease->leasetime, dhcp_expire, ifp);
2320 		logdebugx("%s: renew in %"PRIu32" seconds, rebind in %"PRIu32
2321 		    " seconds",
2322 		    ifp->name, lease->renewaltime, lease->rebindtime);
2323 	}
2324 	state->state = DHS_BOUND;
2325 	/* Re-apply the filter because we need to accept any XID anymore. */
2326 	if (bpf_bootp(ifp, state->bpf_fd) == -1)
2327 		logerr(__func__); /* try to continue */
2328 	if (!state->lease.frominfo &&
2329 	    !(ifo->options & (DHCPCD_INFORM | DHCPCD_STATIC)))
2330 		if (write_lease(ifp, state->new, state->new_len) == -1)
2331 			logerr(__func__);
2332 
2333 	ipv4_applyaddr(ifp);
2334 }
2335 
2336 static void
2337 dhcp_lastlease(void *arg)
2338 {
2339 	struct interface *ifp = arg;
2340 	struct dhcp_state *state = D_STATE(ifp);
2341 
2342 	loginfox("%s: timed out contacting a DHCP server, using last lease",
2343 	    ifp->name);
2344 	dhcp_bind(ifp);
2345 	/* If we forked, stop here. */
2346 	if (ifp->ctx->options & DHCPCD_FORKED)
2347 		return;
2348 	state->interval = 0;
2349 	if (ifp->options->options & DHCPCD_LASTLEASE_EXTEND &&
2350 	    dhcp_leaseextend(ifp) == -1)
2351 	{
2352 		logerr("%s: %s", ifp->name, __func__);
2353 		dhcp_expire(ifp);
2354 	}
2355 	dhcp_discover(ifp);
2356 }
2357 
2358 static size_t
2359 dhcp_message_new(struct bootp **bootp,
2360     const struct in_addr *addr, const struct in_addr *mask)
2361 {
2362 	uint8_t *p;
2363 	uint32_t cookie;
2364 
2365 	if ((*bootp = calloc(1, sizeof(**bootp))) == NULL)
2366 		return 0;
2367 
2368 	(*bootp)->yiaddr = addr->s_addr;
2369 	p = (*bootp)->vend;
2370 
2371 	cookie = htonl(MAGIC_COOKIE);
2372 	memcpy(p, &cookie, sizeof(cookie));
2373 	p += sizeof(cookie);
2374 
2375 	if (mask->s_addr != INADDR_ANY) {
2376 		*p++ = DHO_SUBNETMASK;
2377 		*p++ = sizeof(mask->s_addr);
2378 		memcpy(p, &mask->s_addr, sizeof(mask->s_addr));
2379 		p+= sizeof(mask->s_addr);
2380 	}
2381 
2382 	*p = DHO_END;
2383 	return sizeof(**bootp);
2384 }
2385 
2386 #ifdef ARP
2387 static int
2388 dhcp_arp_address(struct interface *ifp)
2389 {
2390 	struct dhcp_state *state;
2391 	struct in_addr addr;
2392 	struct ipv4_addr *ia;
2393 	struct arp_state *astate;
2394 
2395 	eloop_timeout_delete(ifp->ctx->eloop, NULL, ifp);
2396 
2397 	state = D_STATE(ifp);
2398 	addr.s_addr = state->offer->yiaddr == INADDR_ANY ?
2399 	    state->offer->ciaddr : state->offer->yiaddr;
2400 	/* If the interface already has the address configured
2401 	 * then we can't ARP for duplicate detection. */
2402 	ia = ipv4_iffindaddr(ifp, &addr, NULL);
2403 	if ((astate = arp_new(ifp, &addr)) == NULL)
2404 		return -1;
2405 	astate->probed_cb = dhcp_arp_probed;
2406 	astate->conflicted_cb = dhcp_arp_conflicted;
2407 
2408 #ifdef IN_IFF_TENTATIVE
2409 	if (ia == NULL || ia->addr_flags & IN_IFF_NOTUSEABLE) {
2410 		state->state = DHS_PROBE;
2411 		if (ia == NULL) {
2412 			struct dhcp_lease l;
2413 
2414 			get_lease(ifp, &l, state->offer, state->offer_len);
2415 			/* Add the address now, let the kernel handle DAD. */
2416 			ipv4_addaddr(ifp, &l.addr, &l.mask, &l.brd);
2417 		} else
2418 			loginfox("%s: waiting for DAD on %s",
2419 			    ifp->name, inet_ntoa(addr));
2420 		return 0;
2421 	}
2422 #else
2423 	if (ifp->options->options & DHCPCD_ARP && ia == NULL) {
2424 		struct dhcp_lease l;
2425 
2426 		state->state = DHS_PROBE;
2427 		get_lease(ifp, &l, state->offer, state->offer_len);
2428 		loginfox("%s: probing address %s/%d",
2429 		    ifp->name, inet_ntoa(l.addr), inet_ntocidr(l.mask));
2430 		/* We need to handle DAD. */
2431 		arp_probe(astate);
2432 		return 0;
2433 	}
2434 #endif
2435 
2436 	return 1;
2437 }
2438 
2439 static void
2440 dhcp_arp_bind(struct interface *ifp)
2441 {
2442 
2443 	if (dhcp_arp_address(ifp) == 1)
2444 		dhcp_bind(ifp);
2445 }
2446 #endif
2447 
2448 static void
2449 dhcp_static(struct interface *ifp)
2450 {
2451 	struct if_options *ifo;
2452 	struct dhcp_state *state;
2453 	struct ipv4_addr *ia;
2454 
2455 	state = D_STATE(ifp);
2456 	ifo = ifp->options;
2457 
2458 	ia = NULL;
2459 	if (ifo->req_addr.s_addr == INADDR_ANY &&
2460 	    (ia = ipv4_iffindaddr(ifp, NULL, NULL)) == NULL)
2461 	{
2462 		loginfox("%s: waiting for 3rd party to "
2463 		    "configure IP address", ifp->name);
2464 		state->reason = "3RDPARTY";
2465 		script_runreason(ifp, state->reason);
2466 		return;
2467 	}
2468 
2469 	state->offer_len = dhcp_message_new(&state->offer,
2470 	    ia ? &ia->addr : &ifo->req_addr,
2471 	    ia ? &ia->mask : &ifo->req_mask);
2472 	if (state->offer_len)
2473 #ifdef ARP
2474 		dhcp_arp_bind(ifp);
2475 #else
2476 		dhcp_bind(ifp);
2477 #endif
2478 }
2479 
2480 void
2481 dhcp_inform(struct interface *ifp)
2482 {
2483 	struct dhcp_state *state;
2484 	struct if_options *ifo;
2485 	struct ipv4_addr *ia;
2486 
2487 	state = D_STATE(ifp);
2488 	ifo = ifp->options;
2489 
2490 	state->state = DHS_INFORM;
2491 	free(state->offer);
2492 	state->offer = NULL;
2493 	state->offer_len = 0;
2494 
2495 	if (ifo->req_addr.s_addr == INADDR_ANY) {
2496 		ia = ipv4_iffindaddr(ifp, NULL, NULL);
2497 		if (ia == NULL) {
2498 			loginfox("%s: waiting for 3rd party to "
2499 			    "configure IP address",
2500 			    ifp->name);
2501 			if (!(ifp->ctx->options & DHCPCD_TEST)) {
2502 				state->reason = "3RDPARTY";
2503 				script_runreason(ifp, state->reason);
2504 			}
2505 			return;
2506 		}
2507 	} else {
2508 		ia = ipv4_iffindaddr(ifp, &ifo->req_addr, &ifo->req_mask);
2509 		if (ia == NULL) {
2510 			if (ifp->ctx->options & DHCPCD_TEST) {
2511 				logerrx("%s: cannot add IP address in test mode",
2512 				    ifp->name);
2513 				return;
2514 			}
2515 			ia = ipv4_iffindaddr(ifp, &ifo->req_addr, NULL);
2516 			if (ia != NULL)
2517 				/* Netmask must be different, delete it. */
2518 				ipv4_deladdr(ia, 1);
2519 			state->offer_len = dhcp_message_new(&state->offer,
2520 			    &ifo->req_addr, &ifo->req_mask);
2521 #ifdef ARP
2522 			if (dhcp_arp_address(ifp) == 0)
2523 				return;
2524 #endif
2525 			ia = ipv4_iffindaddr(ifp,
2526 			    &ifo->req_addr, &ifo->req_mask);
2527 			assert(ia != NULL);
2528 		}
2529 	}
2530 
2531 	state->addr = ia;
2532 	state->offer_len = dhcp_message_new(&state->offer,
2533 	    &ia->addr, &ia->mask);
2534 	if (state->offer_len) {
2535 		dhcp_new_xid(ifp);
2536 		get_lease(ifp, &state->lease, state->offer, state->offer_len);
2537 		send_inform(ifp);
2538 	}
2539 }
2540 
2541 void
2542 dhcp_reboot_newopts(struct interface *ifp, unsigned long long oldopts)
2543 {
2544 	struct if_options *ifo;
2545 	struct dhcp_state *state = D_STATE(ifp);
2546 
2547 	if (state == NULL || state->state == DHS_NONE)
2548 		return;
2549 	ifo = ifp->options;
2550 	if ((ifo->options & (DHCPCD_INFORM | DHCPCD_STATIC) &&
2551 		(state->addr == NULL ||
2552 		state->addr->addr.s_addr != ifo->req_addr.s_addr)) ||
2553 	    (oldopts & (DHCPCD_INFORM | DHCPCD_STATIC) &&
2554 		!(ifo->options & (DHCPCD_INFORM | DHCPCD_STATIC))))
2555 	{
2556 		dhcp_drop(ifp, "EXPIRE");
2557 	}
2558 }
2559 
2560 #ifdef ARP
2561 static int
2562 dhcp_activeaddr(const struct interface *ifp, const struct in_addr *addr)
2563 {
2564 	const struct interface *ifp1;
2565 	const struct dhcp_state *state;
2566 
2567 	TAILQ_FOREACH(ifp1, ifp->ctx->ifaces, next) {
2568 		if (ifp1 == ifp)
2569 			continue;
2570 		if ((state = D_CSTATE(ifp1)) == NULL)
2571 			continue;
2572 		switch(state->state) {
2573 		case DHS_REBOOT:
2574 		case DHS_RENEW:
2575 		case DHS_REBIND:
2576 		case DHS_BOUND:
2577 		case DHS_INFORM:
2578 			break;
2579 		default:
2580 			continue;
2581 		}
2582 		if (state->lease.addr.s_addr == addr->s_addr)
2583 			return 1;
2584 	}
2585 	return 0;
2586 }
2587 #endif
2588 
2589 static void
2590 dhcp_reboot(struct interface *ifp)
2591 {
2592 	struct if_options *ifo;
2593 	struct dhcp_state *state = D_STATE(ifp);
2594 #ifdef ARP
2595 	struct ipv4_addr *ia;
2596 #endif
2597 
2598 	if (state == NULL || state->state == DHS_NONE)
2599 		return;
2600 	ifo = ifp->options;
2601 	state->state = DHS_REBOOT;
2602 	state->interval = 0;
2603 
2604 	if (ifo->options & DHCPCD_LINK && ifp->carrier == LINK_DOWN) {
2605 		loginfox("%s: waiting for carrier", ifp->name);
2606 		return;
2607 	}
2608 	if (ifo->options & DHCPCD_STATIC) {
2609 		dhcp_static(ifp);
2610 		return;
2611 	}
2612 	if (ifo->options & DHCPCD_INFORM) {
2613 		loginfox("%s: informing address of %s",
2614 		    ifp->name, inet_ntoa(state->lease.addr));
2615 		dhcp_inform(ifp);
2616 		return;
2617 	}
2618 	if (ifo->reboot == 0 || state->offer == NULL) {
2619 		dhcp_discover(ifp);
2620 		return;
2621 	}
2622 	if (!IS_DHCP(state->offer))
2623 		return;
2624 
2625 	loginfox("%s: rebinding lease of %s",
2626 	    ifp->name, inet_ntoa(state->lease.addr));
2627 
2628 #ifdef ARP
2629 	/* If the address exists on the interface and no other interface
2630 	 * is currently using it then announce it to ensure this
2631 	 * interface gets the reply. */
2632 	ia = ipv4_iffindaddr(ifp, &state->lease.addr, NULL);
2633 	if (ia != NULL &&
2634 #ifdef IN_IFF_NOTUSEABLE
2635 	    !(ia->addr_flags & IN_IFF_NOTUSEABLE) &&
2636 #endif
2637 	    dhcp_activeaddr(ifp, &state->lease.addr) == 0)
2638 		arp_ifannounceaddr(ifp, &state->lease.addr);
2639 #endif
2640 
2641 	dhcp_new_xid(ifp);
2642 	state->lease.server.s_addr = INADDR_ANY;
2643 	eloop_timeout_delete(ifp->ctx->eloop, NULL, ifp);
2644 
2645 #ifdef IPV4LL
2646 	/* Need to add this before dhcp_expire and friends. */
2647 	if (!ifo->fallback && ifo->options & DHCPCD_IPV4LL)
2648 		eloop_timeout_add_sec(ifp->ctx->eloop,
2649 		    ifo->reboot, ipv4ll_start, ifp);
2650 #endif
2651 
2652 	if (ifo->options & DHCPCD_LASTLEASE && state->lease.frominfo)
2653 		eloop_timeout_add_sec(ifp->ctx->eloop,
2654 		    ifo->reboot, dhcp_lastlease, ifp);
2655 	else if (!(ifo->options & DHCPCD_INFORM))
2656 		eloop_timeout_add_sec(ifp->ctx->eloop,
2657 		    ifo->reboot, dhcp_expire, ifp);
2658 
2659 	/* Don't bother ARP checking as the server could NAK us first.
2660 	 * Don't call dhcp_request as that would change the state */
2661 	send_request(ifp);
2662 }
2663 
2664 void
2665 dhcp_drop(struct interface *ifp, const char *reason)
2666 {
2667 	struct dhcp_state *state;
2668 #ifdef RELEASE_SLOW
2669 	struct timespec ts;
2670 #endif
2671 
2672 	state = D_STATE(ifp);
2673 	/* dhcp_start may just have been called and we don't yet have a state
2674 	 * but we do have a timeout, so punt it. */
2675 	if (state == NULL || state->state == DHS_NONE) {
2676 		eloop_timeout_delete(ifp->ctx->eloop, NULL, ifp);
2677 		return;
2678 	}
2679 
2680 #ifdef ARPING
2681 	state->arping_index = -1;
2682 #endif
2683 	if (ifp->options->options & DHCPCD_RELEASE &&
2684 	    !(ifp->options->options & DHCPCD_INFORM))
2685 	{
2686 		/* Failure to send the release may cause this function to
2687 		 * re-enter so guard by setting the state. */
2688 		if (state->state == DHS_RELEASE)
2689 			return;
2690 		state->state = DHS_RELEASE;
2691 
2692 		unlink(state->leasefile);
2693 		if (ifp->carrier != LINK_DOWN &&
2694 		    state->new != NULL &&
2695 		    state->lease.server.s_addr != INADDR_ANY)
2696 		{
2697 			loginfox("%s: releasing lease of %s",
2698 			    ifp->name, inet_ntoa(state->lease.addr));
2699 			dhcp_new_xid(ifp);
2700 			send_message(ifp, DHCP_RELEASE, NULL);
2701 #ifdef RELEASE_SLOW
2702 			/* Give the packet a chance to go */
2703 			ts.tv_sec = RELEASE_DELAY_S;
2704 			ts.tv_nsec = RELEASE_DELAY_NS;
2705 			nanosleep(&ts, NULL);
2706 #endif
2707 		}
2708 	}
2709 
2710 	eloop_timeout_delete(ifp->ctx->eloop, NULL, ifp);
2711 #ifdef AUTH
2712 	dhcp_auth_reset(&state->auth);
2713 #endif
2714 
2715 	state->state = DHS_NONE;
2716 	free(state->offer);
2717 	state->offer = NULL;
2718 	state->offer_len = 0;
2719 	free(state->old);
2720 	state->old = state->new;
2721 	state->old_len = state->new_len;
2722 	state->new = NULL;
2723 	state->new_len = 0;
2724 	state->reason = reason;
2725 	ipv4_applyaddr(ifp);
2726 	free(state->old);
2727 	state->old = NULL;
2728 	state->old_len = 0;
2729 	state->lease.addr.s_addr = 0;
2730 	ifp->options->options &= ~(DHCPCD_CSR_WARNED |
2731 	    DHCPCD_ROUTER_HOST_ROUTE_WARNED);
2732 }
2733 
2734 static int
2735 blacklisted_ip(const struct if_options *ifo, in_addr_t addr)
2736 {
2737 	size_t i;
2738 
2739 	for (i = 0; i < ifo->blacklist_len; i += 2)
2740 		if (ifo->blacklist[i] == (addr & ifo->blacklist[i + 1]))
2741 			return 1;
2742 	return 0;
2743 }
2744 
2745 #define	WHTLST_NONE	0
2746 #define	WHTLST_MATCH	1
2747 #define WHTLST_NOMATCH	2
2748 static unsigned int
2749 whitelisted_ip(const struct if_options *ifo, in_addr_t addr)
2750 {
2751 	size_t i;
2752 
2753 	if (ifo->whitelist_len == 0)
2754 		return WHTLST_NONE;
2755 	for (i = 0; i < ifo->whitelist_len; i += 2)
2756 		if (ifo->whitelist[i] == (addr & ifo->whitelist[i + 1]))
2757 			return WHTLST_MATCH;
2758 	return WHTLST_NOMATCH;
2759 }
2760 
2761 static void
2762 log_dhcp(logfunc_t *logfunc, const char *msg,
2763     const struct interface *ifp, const struct bootp *bootp, size_t bootp_len,
2764     const struct in_addr *from, int ad)
2765 {
2766 	const char *tfrom;
2767 	char *a, sname[sizeof(bootp->sname) * 4];
2768 	struct in_addr addr;
2769 	int r;
2770 	uint8_t overl;
2771 
2772 	if (strcmp(msg, "NAK:") == 0) {
2773 		a = get_option_string(ifp->ctx, bootp, bootp_len, DHO_MESSAGE);
2774 		if (a) {
2775 			char *tmp;
2776 			size_t al, tmpl;
2777 
2778 			al = strlen(a);
2779 			tmpl = (al * 4) + 1;
2780 			tmp = malloc(tmpl);
2781 			if (tmp == NULL) {
2782 				logerr(__func__);
2783 				free(a);
2784 				return;
2785 			}
2786 			print_string(tmp, tmpl, OT_STRING, (uint8_t *)a, al);
2787 			free(a);
2788 			a = tmp;
2789 		}
2790 	} else if (ad && bootp->yiaddr != 0) {
2791 		addr.s_addr = bootp->yiaddr;
2792 		a = strdup(inet_ntoa(addr));
2793 		if (a == NULL) {
2794 			logerr(__func__);
2795 			return;
2796 		}
2797 	} else
2798 		a = NULL;
2799 
2800 	tfrom = "from";
2801 	r = get_option_addr(ifp->ctx, &addr, bootp, bootp_len, DHO_SERVERID);
2802 	if (get_option_uint8(ifp->ctx, &overl, bootp, bootp_len,
2803 	    DHO_OPTSOVERLOADED) == -1)
2804 		overl = 0;
2805 	if (bootp->sname[0] && r == 0 && !(overl & 2)) {
2806 		print_string(sname, sizeof(sname), OT_STRING | OT_DOMAIN,
2807 		    bootp->sname, sizeof(bootp->sname));
2808 		if (a == NULL)
2809 			logfunc("%s: %s %s %s `%s'",
2810 			    ifp->name, msg, tfrom, inet_ntoa(addr), sname);
2811 		else
2812 			logfunc("%s: %s %s %s %s `%s'",
2813 			    ifp->name, msg, a, tfrom, inet_ntoa(addr), sname);
2814 	} else {
2815 		if (r != 0) {
2816 			tfrom = "via";
2817 			addr = *from;
2818 		}
2819 		if (a == NULL)
2820 			logfunc("%s: %s %s %s",
2821 			    ifp->name, msg, tfrom, inet_ntoa(addr));
2822 		else
2823 			logfunc("%s: %s %s %s %s",
2824 			    ifp->name, msg, a, tfrom, inet_ntoa(addr));
2825 	}
2826 	free(a);
2827 }
2828 
2829 /* If we're sharing the same IP address with another interface on the
2830  * same network, we may receive the DHCP reply on the wrong interface.
2831  * Try and re-direct it here. */
2832 static void
2833 dhcp_redirect_dhcp(struct interface *ifp, struct bootp *bootp, size_t bootp_len,
2834     const struct in_addr *from)
2835 {
2836 	struct interface *ifn;
2837 	const struct dhcp_state *state;
2838 	uint32_t xid;
2839 
2840 	xid = ntohl(bootp->xid);
2841 	TAILQ_FOREACH(ifn, ifp->ctx->ifaces, next) {
2842 		state = D_CSTATE(ifn);
2843 		if (state == NULL || state->state == DHS_NONE)
2844 			continue;
2845 		if (state->xid != xid)
2846 			continue;
2847 		if (ifn->hwlen <= sizeof(bootp->chaddr) &&
2848 		    memcmp(bootp->chaddr, ifn->hwaddr, ifn->hwlen))
2849 			continue;
2850 		logdebugx("%s: redirecting DHCP message to %s",
2851 		    ifp->name, ifn->name);
2852 		dhcp_handledhcp(ifn, bootp, bootp_len, from);
2853 	}
2854 }
2855 
2856 static void
2857 dhcp_handledhcp(struct interface *ifp, struct bootp *bootp, size_t bootp_len,
2858     const struct in_addr *from)
2859 {
2860 	struct dhcp_state *state = D_STATE(ifp);
2861 	struct if_options *ifo = ifp->options;
2862 	struct dhcp_lease *lease = &state->lease;
2863 	uint8_t type, tmp;
2864 	struct in_addr addr;
2865 	unsigned int i;
2866 	char *msg;
2867 	bool bootp_copied;
2868 #ifdef AUTH
2869 	const uint8_t *auth;
2870 	size_t auth_len;
2871 #endif
2872 #ifdef IN_IFF_DUPLICATED
2873 	struct ipv4_addr *ia;
2874 #endif
2875 
2876 #define LOGDHCP0(l, m) \
2877 	log_dhcp((l), (m), ifp, bootp, bootp_len, from, 0)
2878 #define LOGDHCP(l, m) \
2879 	log_dhcp((l), (m), ifp, bootp, bootp_len, from, 1)
2880 
2881 	/* Handled in our BPF filter. */
2882 #if 0
2883 	if (bootp->op != BOOTREPLY) {
2884 		logdebugx("%s: op (%d) is not BOOTREPLY",
2885 		    ifp->name, bootp->op);
2886 		return;
2887 	}
2888 #endif
2889 
2890 	if (state->xid != ntohl(bootp->xid)) {
2891 		if (state->state != DHS_BOUND && state->state != DHS_NONE)
2892 			logdebugx("%s: wrong xid 0x%x (expecting 0x%x) from %s",
2893 			    ifp->name, ntohl(bootp->xid), state->xid,
2894 			    inet_ntoa(*from));
2895 		dhcp_redirect_dhcp(ifp, bootp, bootp_len, from);
2896 		return;
2897 	}
2898 
2899 	if (ifp->hwlen <= sizeof(bootp->chaddr) &&
2900 	    memcmp(bootp->chaddr, ifp->hwaddr, ifp->hwlen))
2901 	{
2902 		char buf[sizeof(bootp->chaddr) * 3];
2903 
2904 		logdebugx("%s: xid 0x%x is for hwaddr %s",
2905 		    ifp->name, ntohl(bootp->xid),
2906 		    hwaddr_ntoa(bootp->chaddr, sizeof(bootp->chaddr),
2907 		    buf, sizeof(buf)));
2908 		dhcp_redirect_dhcp(ifp, bootp, bootp_len, from);
2909 		return;
2910 	}
2911 
2912 	if (!ifp->active)
2913 		return;
2914 
2915 	i = whitelisted_ip(ifp->options, from->s_addr);
2916 	switch (i) {
2917 	case WHTLST_NOMATCH:
2918 		logwarnx("%s: non whitelisted DHCP packet from %s",
2919 		    ifp->name, inet_ntoa(*from));
2920 		return;
2921 	case WHTLST_MATCH:
2922 		break;
2923 	case WHTLST_NONE:
2924 		if (blacklisted_ip(ifp->options, from->s_addr) == 1) {
2925 			logwarnx("%s: blacklisted DHCP packet from %s",
2926 			    ifp->name, inet_ntoa(*from));
2927 			return;
2928 		}
2929 	}
2930 
2931 	/* We may have found a BOOTP server */
2932 	if (get_option_uint8(ifp->ctx, &type,
2933 	    bootp, bootp_len, DHO_MESSAGETYPE) == -1)
2934 		type = 0;
2935 	else if (ifo->options & DHCPCD_BOOTP) {
2936 		logdebugx("%s: ignoring DHCP reply (expecting BOOTP)",
2937 		    ifp->name);
2938 		return;
2939 	}
2940 
2941 #ifdef AUTH
2942 	/* Authenticate the message */
2943 	auth = get_option(ifp->ctx, bootp, bootp_len,
2944 	    DHO_AUTHENTICATION, &auth_len);
2945 	if (auth) {
2946 		if (dhcp_auth_validate(&state->auth, &ifo->auth,
2947 		    (uint8_t *)bootp, bootp_len, 4, type,
2948 		    auth, auth_len) == NULL)
2949 		{
2950 			LOGDHCP0(logerrx, "authentication failed");
2951 			return;
2952 		}
2953 		if (state->auth.token)
2954 			logdebugx("%s: validated using 0x%08" PRIu32,
2955 			    ifp->name, state->auth.token->secretid);
2956 		else
2957 			loginfox("%s: accepted reconfigure key", ifp->name);
2958 	} else if (ifo->auth.options & DHCPCD_AUTH_SEND) {
2959 		if (ifo->auth.options & DHCPCD_AUTH_REQUIRE) {
2960 			LOGDHCP0(logerrx, "no authentication");
2961 			return;
2962 		}
2963 		LOGDHCP0(logwarnx, "no authentication");
2964 	}
2965 #endif
2966 
2967 	/* RFC 3203 */
2968 	if (type == DHCP_FORCERENEW) {
2969 		if (from->s_addr == INADDR_ANY ||
2970 		    from->s_addr == INADDR_BROADCAST)
2971 		{
2972 			LOGDHCP(logerrx, "discarding Force Renew");
2973 			return;
2974 		}
2975 #ifdef AUTH
2976 		if (auth == NULL) {
2977 			LOGDHCP(logerrx, "unauthenticated Force Renew");
2978 			if (ifo->auth.options & DHCPCD_AUTH_REQUIRE)
2979 				return;
2980 		}
2981 		if (state->state != DHS_BOUND && state->state != DHS_INFORM) {
2982 			LOGDHCP(logdebugx, "not bound, ignoring Force Renew");
2983 			return;
2984 		}
2985 		LOGDHCP(loginfox, "Force Renew from");
2986 		/* The rebind and expire timings are still the same, we just
2987 		 * enter the renew state early */
2988 		if (state->state == DHS_BOUND)
2989 			dhcp_renew(ifp);
2990 		else {
2991 			eloop_timeout_delete(ifp->ctx->eloop,
2992 			    send_inform, ifp);
2993 			dhcp_inform(ifp);
2994 		}
2995 #else
2996 		LOGDHCP(logerrx, "unauthenticated Force Renew");
2997 #endif
2998 		return;
2999 	}
3000 
3001 	if (state->state == DHS_BOUND) {
3002 		/* Before we supported FORCERENEW we closed off the raw
3003 		 * port so we effectively ignored all messages.
3004 		 * As such we'll not log by default here. */
3005 		//LOGDHCP(logdebugx, "bound, ignoring");
3006 		return;
3007 	}
3008 
3009 	if (state->state == DHS_PROBE) {
3010 		/* Ignore any DHCP messages whilst probing a lease to bind. */
3011 		LOGDHCP(logdebugx, "probing, ignoring");
3012 		return;
3013 	}
3014 
3015 	/* reset the message counter */
3016 	state->interval = 0;
3017 
3018 	/* Ensure that no reject options are present */
3019 	for (i = 1; i < 255; i++) {
3020 		if (has_option_mask(ifo->rejectmask, i) &&
3021 		    get_option_uint8(ifp->ctx, &tmp,
3022 		    bootp, bootp_len, (uint8_t)i) == 0)
3023 		{
3024 			LOGDHCP(logwarnx, "reject DHCP");
3025 			return;
3026 		}
3027 	}
3028 
3029 	if (type == DHCP_NAK) {
3030 		/* For NAK, only check if we require the ServerID */
3031 		if (has_option_mask(ifo->requiremask, DHO_SERVERID) &&
3032 		    get_option_addr(ifp->ctx, &addr,
3033 		    bootp, bootp_len, DHO_SERVERID) == -1)
3034 		{
3035 			LOGDHCP(logwarnx, "reject NAK");
3036 			return;
3037 		}
3038 
3039 		/* We should restart on a NAK */
3040 		LOGDHCP(logwarnx, "NAK:");
3041 		if ((msg = get_option_string(ifp->ctx,
3042 		    bootp, bootp_len, DHO_MESSAGE)))
3043 		{
3044 			logwarnx("%s: message: %s", ifp->name, msg);
3045 			free(msg);
3046 		}
3047 		if (state->state == DHS_INFORM) /* INFORM should not be NAKed */
3048 			return;
3049 		if (!(ifp->ctx->options & DHCPCD_TEST)) {
3050 			dhcp_drop(ifp, "NAK");
3051 			unlink(state->leasefile);
3052 		}
3053 
3054 		/* If we constantly get NAKS then we should slowly back off */
3055 		eloop_timeout_add_sec(ifp->ctx->eloop,
3056 		    state->nakoff, dhcp_discover, ifp);
3057 		if (state->nakoff == 0)
3058 			state->nakoff = 1;
3059 		else {
3060 			state->nakoff *= 2;
3061 			if (state->nakoff > NAKOFF_MAX)
3062 				state->nakoff = NAKOFF_MAX;
3063 		}
3064 		return;
3065 	}
3066 
3067 	/* Ensure that all required options are present */
3068 	for (i = 1; i < 255; i++) {
3069 		if (has_option_mask(ifo->requiremask, i) &&
3070 		    get_option_uint8(ifp->ctx, &tmp,
3071 		    bootp, bootp_len, (uint8_t)i) != 0)
3072 		{
3073 			/* If we are BOOTP, then ignore the need for serverid.
3074 			 * To ignore BOOTP, require dhcp_message_type.
3075 			 * However, nothing really stops BOOTP from providing
3076 			 * DHCP style options as well so the above isn't
3077 			 * always true. */
3078 			if (type == 0 && i == DHO_SERVERID)
3079 				continue;
3080 			LOGDHCP(logwarnx, "reject DHCP");
3081 			return;
3082 		}
3083 	}
3084 
3085 	/* DHCP Auto-Configure, RFC 2563 */
3086 	if (type == DHCP_OFFER && bootp->yiaddr == 0) {
3087 		LOGDHCP(logwarnx, "no address given");
3088 		if ((msg = get_option_string(ifp->ctx,
3089 		    bootp, bootp_len, DHO_MESSAGE)))
3090 		{
3091 			logwarnx("%s: message: %s", ifp->name, msg);
3092 			free(msg);
3093 		}
3094 #ifdef IPV4LL
3095 		if (state->state == DHS_DISCOVER &&
3096 		    get_option_uint8(ifp->ctx, &tmp, bootp, bootp_len,
3097 		    DHO_AUTOCONFIGURE) == 0)
3098 		{
3099 			switch (tmp) {
3100 			case 0:
3101 				LOGDHCP(logwarnx, "IPv4LL disabled from");
3102 				ipv4ll_drop(ifp);
3103 #ifdef ARP
3104 				arp_drop(ifp);
3105 #endif
3106 				break;
3107 			case 1:
3108 				LOGDHCP(logwarnx, "IPv4LL enabled from");
3109 				ipv4ll_start(ifp);
3110 				break;
3111 			default:
3112 				logerrx("%s: unknown auto configuration "
3113 				    "option %d",
3114 				    ifp->name, tmp);
3115 				break;
3116 			}
3117 			eloop_timeout_delete(ifp->ctx->eloop, NULL, ifp);
3118 			eloop_timeout_add_sec(ifp->ctx->eloop,
3119 			    DHCP_MAX, dhcp_discover, ifp);
3120 		}
3121 #endif
3122 		return;
3123 	}
3124 
3125 	/* Ensure that the address offered is valid */
3126 	if ((type == 0 || type == DHCP_OFFER || type == DHCP_ACK) &&
3127 	    (bootp->ciaddr == INADDR_ANY || bootp->ciaddr == INADDR_BROADCAST)
3128 	    &&
3129 	    (bootp->yiaddr == INADDR_ANY || bootp->yiaddr == INADDR_BROADCAST))
3130 	{
3131 		LOGDHCP(logwarnx, "reject invalid address");
3132 		return;
3133 	}
3134 
3135 #ifdef IN_IFF_DUPLICATED
3136 	ia = ipv4_iffindaddr(ifp, &lease->addr, NULL);
3137 	if (ia && ia->addr_flags & IN_IFF_DUPLICATED) {
3138 		LOGDHCP(logwarnx, "declined duplicate address");
3139 		if (type)
3140 			dhcp_decline(ifp);
3141 		ipv4_deladdr(ia, 0);
3142 		eloop_timeout_delete(ifp->ctx->eloop, NULL, ifp);
3143 		eloop_timeout_add_sec(ifp->ctx->eloop,
3144 		    DHCP_RAND_MAX, dhcp_discover, ifp);
3145 		return;
3146 	}
3147 #endif
3148 
3149 	bootp_copied = false;
3150 	if ((type == 0 || type == DHCP_OFFER) && state->state == DHS_DISCOVER) {
3151 		lease->frominfo = 0;
3152 		lease->addr.s_addr = bootp->yiaddr;
3153 		memcpy(&lease->cookie, bootp->vend, sizeof(lease->cookie));
3154 		if (type == 0 ||
3155 		    get_option_addr(ifp->ctx,
3156 		    &lease->server, bootp, bootp_len, DHO_SERVERID) != 0)
3157 			lease->server.s_addr = INADDR_ANY;
3158 
3159 		/* Test for rapid commit in the OFFER */
3160 		if (!(ifp->ctx->options & DHCPCD_TEST) &&
3161 		    has_option_mask(ifo->requestmask, DHO_RAPIDCOMMIT) &&
3162 		    get_option(ifp->ctx, bootp, bootp_len,
3163 		    DHO_RAPIDCOMMIT, NULL))
3164 		{
3165 			state->state = DHS_REQUEST;
3166 			goto rapidcommit;
3167 		}
3168 
3169 		LOGDHCP(loginfox, "offered");
3170 		if (state->offer_len < bootp_len) {
3171 			free(state->offer);
3172 			if ((state->offer = malloc(bootp_len)) == NULL) {
3173 				logerr(__func__);
3174 				state->offer_len = 0;
3175 				return;
3176 			}
3177 		}
3178 		state->offer_len = bootp_len;
3179 		memcpy(state->offer, bootp, bootp_len);
3180 		bootp_copied = true;
3181 		if (ifp->ctx->options & DHCPCD_TEST) {
3182 			free(state->old);
3183 			state->old = state->new;
3184 			state->old_len = state->new_len;
3185 			state->new = state->offer;
3186 			state->new_len = state->offer_len;
3187 			state->offer = NULL;
3188 			state->offer_len = 0;
3189 			state->reason = "TEST";
3190 			script_runreason(ifp, state->reason);
3191 			eloop_exit(ifp->ctx->eloop, EXIT_SUCCESS);
3192 			return;
3193 		}
3194 		eloop_timeout_delete(ifp->ctx->eloop, send_discover, ifp);
3195 		/* We don't request BOOTP addresses */
3196 		if (type) {
3197 			/* We used to ARP check here, but that seems to be in
3198 			 * violation of RFC2131 where it only describes
3199 			 * DECLINE after REQUEST.
3200 			 * It also seems that some MS DHCP servers actually
3201 			 * ignore DECLINE if no REQUEST, ie we decline a
3202 			 * DISCOVER. */
3203 			dhcp_request(ifp);
3204 			return;
3205 		}
3206 	}
3207 
3208 	if (type) {
3209 		if (type == DHCP_OFFER) {
3210 			LOGDHCP(logwarnx, "ignoring offer of");
3211 			return;
3212 		}
3213 
3214 		/* We should only be dealing with acks */
3215 		if (type != DHCP_ACK) {
3216 			LOGDHCP(logerr, "not ACK or OFFER");
3217 			return;
3218 		}
3219 
3220 		if (state->state == DHS_DISCOVER) {
3221 			/* We only allow ACK of rapid commit DISCOVER. */
3222 			if (has_option_mask(ifo->requestmask,
3223 			    DHO_RAPIDCOMMIT) &&
3224 			    get_option(ifp->ctx, bootp, bootp_len,
3225 			    DHO_RAPIDCOMMIT, NULL))
3226 				state->state = DHS_REQUEST;
3227 			else {
3228 				LOGDHCP(logdebugx, "ignoring ack of");
3229 				return;
3230 			}
3231 		}
3232 
3233 rapidcommit:
3234 		if (!(ifo->options & DHCPCD_INFORM))
3235 			LOGDHCP(logdebugx, "acknowledged");
3236 		else
3237 		    ifo->options &= ~DHCPCD_STATIC;
3238 	}
3239 
3240 	/* No NAK, so reset the backoff
3241 	 * We don't reset on an OFFER message because the server could
3242 	 * potentially NAK the REQUEST. */
3243 	state->nakoff = 0;
3244 
3245 	/* BOOTP could have already assigned this above. */
3246 	if (!bootp_copied) {
3247 		if (state->offer_len < bootp_len) {
3248 			free(state->offer);
3249 			if ((state->offer = malloc(bootp_len)) == NULL) {
3250 				logerr(__func__);
3251 				state->offer_len = 0;
3252 				return;
3253 			}
3254 		}
3255 		state->offer_len = bootp_len;
3256 		memcpy(state->offer, bootp, bootp_len);
3257 	}
3258 
3259 	lease->frominfo = 0;
3260 	eloop_timeout_delete(ifp->ctx->eloop, NULL, ifp);
3261 
3262 #ifdef ARP
3263 	dhcp_arp_bind(ifp);
3264 #else
3265 	dhcp_bind(ifp);
3266 #endif
3267 }
3268 
3269 static void *
3270 get_udp_data(void *udp, size_t *len)
3271 {
3272 	struct bootp_pkt *p;
3273 
3274 	p = (struct bootp_pkt *)udp;
3275 	*len = (size_t)ntohs(p->ip.ip_len) - sizeof(p->ip) - sizeof(p->udp);
3276 	return (char *)udp + offsetof(struct bootp_pkt, bootp);
3277 }
3278 
3279 static int
3280 valid_udp_packet(void *data, size_t data_len, struct in_addr *from,
3281     int noudpcsum)
3282 {
3283 	struct bootp_pkt *p;
3284 	uint16_t bytes;
3285 
3286 	if (data_len < sizeof(p->ip)) {
3287 		if (from)
3288 			from->s_addr = INADDR_ANY;
3289 		errno = ERANGE;
3290 		return -1;
3291 	}
3292 	p = (struct bootp_pkt *)data;
3293 	if (from)
3294 		from->s_addr = p->ip.ip_src.s_addr;
3295 	if (checksum(&p->ip, sizeof(p->ip)) != 0) {
3296 		errno = EINVAL;
3297 		return -1;
3298 	}
3299 
3300 	bytes = ntohs(p->ip.ip_len);
3301 	/* Check we have a payload */
3302 	if (bytes <= sizeof(p->ip) + sizeof(p->udp)) {
3303 		errno = ERANGE;
3304 		return -1;
3305 	}
3306 	/* Check we don't go beyond the payload */
3307 	if (bytes > data_len) {
3308 		errno = ENOBUFS;
3309 		return -1;
3310 	}
3311 
3312 	if (noudpcsum == 0) {
3313 		uint16_t udpsum, iplen;
3314 
3315 		/* This does scribble on the packet, but at this point
3316 		 * we don't care to keep it. */
3317 		iplen = p->ip.ip_len;
3318 		udpsum = p->udp.uh_sum;
3319 		p->udp.uh_sum = 0;
3320 		p->ip.ip_hl = 0;
3321 		p->ip.ip_v = 0;
3322 		p->ip.ip_tos = 0;
3323 		p->ip.ip_len = p->udp.uh_ulen;
3324 		p->ip.ip_id = 0;
3325 		p->ip.ip_off = 0;
3326 		p->ip.ip_ttl = 0;
3327 		p->ip.ip_sum = 0;
3328 		if (udpsum && checksum(p, bytes) != udpsum) {
3329 			errno = EINVAL;
3330 			return -1;
3331 		}
3332 		p->ip.ip_len = iplen;
3333 	}
3334 
3335 	return 0;
3336 }
3337 
3338 static void
3339 dhcp_handlepacket(struct interface *ifp, uint8_t *data, size_t len)
3340 {
3341 	struct bootp *bootp;
3342 	struct in_addr from;
3343 	size_t udp_len;
3344 	const struct dhcp_state *state = D_CSTATE(ifp);
3345 
3346 	if (valid_udp_packet(data, len, &from,
3347 			     state->bpf_flags & RAW_PARTIALCSUM) == -1)
3348 	{
3349 		if (errno == EINVAL)
3350 			logerrx("%s: checksum failure from %s",
3351 			  ifp->name, inet_ntoa(from));
3352 		else
3353 			logerr("%s: invalid UDP packet from %s",
3354 			  ifp->name, inet_ntoa(from));
3355 		return;
3356 	}
3357 	if (ifp->flags & IFF_POINTOPOINT &&
3358 	    (state->addr == NULL || state->addr->brd.s_addr != from.s_addr))
3359 	{
3360 		logwarnx("%s: server %s is not destination",
3361 		    ifp->name, inet_ntoa(from));
3362 	}
3363 
3364 	/*
3365 	 * DHCP has a variable option area rather than a fixed vendor area.
3366 	 * Because DHCP uses the BOOTP protocol it should still send BOOTP
3367 	 * sized packets to be RFC compliant.
3368 	 * However some servers send a truncated vendor area.
3369 	 * dhcpcd can work fine without the vendor area being sent.
3370 	 */
3371 	bootp = get_udp_data(data, &udp_len);
3372 	/* udp_len must be correct because the values are checked in
3373 	 * valid_udp_packet(). */
3374 	if (udp_len < offsetof(struct bootp, vend)) {
3375 		logerrx("%s: truncated packet (%zu) from %s",
3376 		    ifp->name, udp_len, inet_ntoa(from));
3377 		return;
3378 	}
3379 	/* To make our IS_DHCP macro easy, ensure the vendor
3380 	 * area has at least 4 octets. */
3381 	len = udp_len - offsetof(struct bootp, vend);
3382 	while (len < 4) {
3383 		bootp->vend[len++] = '\0';
3384 		udp_len++;
3385 	}
3386 
3387 	dhcp_handledhcp(ifp, bootp, udp_len, &from);
3388 }
3389 
3390 static void
3391 dhcp_readpacket(void *arg)
3392 {
3393 	struct interface *ifp = arg;
3394 	uint8_t buf[MTU_MAX];
3395 	ssize_t bytes;
3396 	struct dhcp_state *state = D_STATE(ifp);
3397 
3398 	/* Some RAW mechanisms are generic file descriptors, not sockets.
3399 	 * This means we have no kernel call to just get one packet,
3400 	 * so we have to process the entire buffer. */
3401 	state->bpf_flags &= ~BPF_EOF;
3402 	state->bpf_flags |= BPF_READING;
3403 	while (!(state->bpf_flags & BPF_EOF)) {
3404 		bytes = bpf_read(ifp, state->bpf_fd, buf, sizeof(buf),
3405 				 &state->bpf_flags);
3406 		if (bytes == -1) {
3407 			if (state->state != DHS_NONE) {
3408 				logerr("%s: %s", __func__, ifp->name);
3409 				dhcp_close(ifp);
3410 			}
3411 			break;
3412 		}
3413 		dhcp_handlepacket(ifp, buf, (size_t)bytes);
3414 		/* Check we still have a state after processing. */
3415 		if ((state = D_STATE(ifp)) == NULL)
3416 			break;
3417 	}
3418 	if (state != NULL)
3419 		state->bpf_flags &= ~BPF_READING;
3420 }
3421 
3422 static void
3423 dhcp_handleudp(void *arg)
3424 {
3425 	struct dhcpcd_ctx *ctx;
3426 	uint8_t buffer[MTU_MAX];
3427 
3428 	ctx = arg;
3429 
3430 	/* Just read what's in the UDP fd and discard it as we always read
3431 	 * from the raw fd */
3432 	if (read(ctx->udp_fd, buffer, sizeof(buffer)) == -1) {
3433 		logerr(__func__);
3434 		eloop_event_delete(ctx->eloop, ctx->udp_fd);
3435 		close(ctx->udp_fd);
3436 		ctx->udp_fd = -1;
3437 	}
3438 }
3439 
3440 static int
3441 dhcp_openbpf(struct interface *ifp)
3442 {
3443 	struct dhcp_state *state;
3444 
3445 	state = D_STATE(ifp);
3446 	if (state->bpf_fd != -1)
3447 		return 0;
3448 
3449 	state->bpf_fd = bpf_open(ifp, bpf_bootp);
3450 	if (state->bpf_fd == -1) {
3451 		if (errno == ENOENT) {
3452 			logerrx("%s not found", bpf_name);
3453 			/* May as well disable IPv4 entirely at
3454 			 * this point as we really need it. */
3455 			ifp->options->options &= ~DHCPCD_IPV4;
3456 		} else
3457 			logerr("%s: %s", __func__, ifp->name);
3458 		return -1;
3459 	}
3460 
3461 	eloop_event_add(ifp->ctx->eloop,
3462 	    state->bpf_fd, dhcp_readpacket, ifp);
3463 	return 0;
3464 }
3465 
3466 int
3467 dhcp_dump(struct interface *ifp)
3468 {
3469 	struct dhcp_state *state;
3470 
3471 	ifp->if_data[IF_DATA_DHCP] = state = calloc(1, sizeof(*state));
3472 	if (state == NULL)
3473 		goto eexit;
3474 	state->bpf_fd = -1;
3475 	dhcp_set_leasefile(state->leasefile, sizeof(state->leasefile),
3476 	    AF_INET, ifp);
3477 	state->new_len = read_lease(ifp, &state->new);
3478 	if (state->new == NULL) {
3479 		logerr("%s: %s",
3480 		    *ifp->name ? ifp->name : state->leasefile, __func__);
3481 		return -1;
3482 	}
3483 	state->reason = "DUMP";
3484 	return script_runreason(ifp, state->reason);
3485 
3486 eexit:
3487 	logerr(__func__);
3488 	return -1;
3489 }
3490 
3491 void
3492 dhcp_free(struct interface *ifp)
3493 {
3494 	struct dhcp_state *state = D_STATE(ifp);
3495 	struct dhcpcd_ctx *ctx;
3496 
3497 	dhcp_close(ifp);
3498 #ifdef ARP
3499 	arp_drop(ifp);
3500 #endif
3501 	if (state) {
3502 		state->state = DHS_NONE;
3503 		free(state->old);
3504 		free(state->new);
3505 		free(state->offer);
3506 		free(state->clientid);
3507 		free(state);
3508 	}
3509 
3510 	ctx = ifp->ctx;
3511 	/* If we don't have any more DHCP enabled interfaces,
3512 	 * close the global socket and release resources */
3513 	if (ctx->ifaces) {
3514 		TAILQ_FOREACH(ifp, ctx->ifaces, next) {
3515 			state = D_STATE(ifp);
3516 			if (state != NULL && state->state != DHS_NONE)
3517 				break;
3518 		}
3519 	}
3520 	if (ifp == NULL) {
3521 		if (ctx->udp_fd != -1) {
3522 			eloop_event_delete(ctx->eloop, ctx->udp_fd);
3523 			close(ctx->udp_fd);
3524 			ctx->udp_fd = -1;
3525 		}
3526 
3527 		free(ctx->opt_buffer);
3528 		ctx->opt_buffer = NULL;
3529 	}
3530 }
3531 
3532 static int
3533 dhcp_initstate(struct interface *ifp)
3534 {
3535 	struct dhcp_state *state;
3536 
3537 	state = D_STATE(ifp);
3538 	if (state != NULL)
3539 		return 0;
3540 
3541 	ifp->if_data[IF_DATA_DHCP] = calloc(1, sizeof(*state));
3542 	state = D_STATE(ifp);
3543 	if (state == NULL)
3544 		return -1;
3545 
3546 	state->state = DHS_NONE;
3547 	/* 0 is a valid fd, so init to -1 */
3548 	state->bpf_fd = -1;
3549 #ifdef ARPING
3550 	state->arping_index = -1;
3551 #endif
3552 	return 1;
3553 }
3554 
3555 static int
3556 dhcp_init(struct interface *ifp)
3557 {
3558 	struct dhcp_state *state;
3559 	const struct if_options *ifo;
3560 	uint8_t len;
3561 	char buf[(sizeof(ifo->clientid) - 1) * 3];
3562 	int r;
3563 
3564 	r = dhcp_initstate(ifp);
3565 	if (r == -1)
3566 		return -1;
3567 	else if (r == 1) {
3568 		/* Now is a good time to find IPv4 routes */
3569 		if_initrt(ifp->ctx, AF_INET);
3570 	}
3571 
3572 	state = D_STATE(ifp);
3573 	state->state = DHS_INIT;
3574 	state->reason = "PREINIT";
3575 	state->nakoff = 0;
3576 	dhcp_set_leasefile(state->leasefile, sizeof(state->leasefile),
3577 	    AF_INET, ifp);
3578 
3579 	ifo = ifp->options;
3580 	/* We need to drop the leasefile so that dhcp_start
3581 	 * doesn't load it. */
3582 	if (ifo->options & DHCPCD_REQUEST)
3583 		unlink(state->leasefile);
3584 
3585 	free(state->clientid);
3586 	state->clientid = NULL;
3587 
3588 	if (*ifo->clientid) {
3589 		state->clientid = malloc((size_t)(ifo->clientid[0] + 1));
3590 		if (state->clientid == NULL)
3591 			goto eexit;
3592 		memcpy(state->clientid, ifo->clientid,
3593 		    (size_t)(ifo->clientid[0]) + 1);
3594 	} else if (ifo->options & DHCPCD_CLIENTID) {
3595 		if (ifo->options & DHCPCD_DUID) {
3596 			state->clientid = malloc(ifp->ctx->duid_len + 6);
3597 			if (state->clientid == NULL)
3598 				goto eexit;
3599 			state->clientid[0] =(uint8_t)(ifp->ctx->duid_len + 5);
3600 			state->clientid[1] = 255; /* RFC 4361 */
3601 			memcpy(state->clientid + 2, ifo->iaid, 4);
3602 			memcpy(state->clientid + 6, ifp->ctx->duid,
3603 			    ifp->ctx->duid_len);
3604 		} else {
3605 			len = (uint8_t)(ifp->hwlen + 1);
3606 			state->clientid = malloc((size_t)len + 1);
3607 			if (state->clientid == NULL)
3608 				goto eexit;
3609 			state->clientid[0] = len;
3610 			state->clientid[1] = (uint8_t)ifp->family;
3611 			memcpy(state->clientid + 2, ifp->hwaddr,
3612 			    ifp->hwlen);
3613 		}
3614 	}
3615 
3616 	if (ifo->options & DHCPCD_DUID)
3617 		/* Don't bother logging as DUID and IAID are reported
3618 		 * at device start. */
3619 		return 0;
3620 
3621 	if (ifo->options & DHCPCD_CLIENTID)
3622 		logdebugx("%s: using ClientID %s", ifp->name,
3623 		    hwaddr_ntoa(state->clientid + 1, state->clientid[0],
3624 			buf, sizeof(buf)));
3625 	else if (ifp->hwlen)
3626 		logdebugx("%s: using hwaddr %s", ifp->name,
3627 		    hwaddr_ntoa(ifp->hwaddr, ifp->hwlen, buf, sizeof(buf)));
3628 	return 0;
3629 
3630 eexit:
3631 	logerr(__func__);
3632 	return -1;
3633 }
3634 
3635 static void
3636 dhcp_start1(void *arg)
3637 {
3638 	struct interface *ifp = arg;
3639 	struct if_options *ifo = ifp->options;
3640 	struct dhcp_state *state;
3641 	struct stat st;
3642 	uint32_t l;
3643 	int nolease;
3644 
3645 	if (!(ifo->options & DHCPCD_IPV4))
3646 		return;
3647 
3648 	/* Listen on *.*.*.*:bootpc so that the kernel never sends an
3649 	 * ICMP port unreachable message back to the DHCP server */
3650 	if (ifp->ctx->udp_fd == -1) {
3651 		ifp->ctx->udp_fd = dhcp_openudp(NULL);
3652 		if (ifp->ctx->udp_fd == -1) {
3653 			/* Don't log an error if some other process
3654 			 * is handling this. */
3655 			if (errno != EADDRINUSE)
3656 				logerr("%s: dhcp_openudp", __func__);
3657 		} else
3658 			eloop_event_add(ifp->ctx->eloop,
3659 			    ifp->ctx->udp_fd, dhcp_handleudp, ifp->ctx);
3660 	}
3661 
3662 	if (dhcp_init(ifp) == -1) {
3663 		logerr("%s: dhcp_init", ifp->name);
3664 		return;
3665 	}
3666 
3667 	state = D_STATE(ifp);
3668 	clock_gettime(CLOCK_MONOTONIC, &state->started);
3669 	state->interval = 0;
3670 	free(state->offer);
3671 	state->offer = NULL;
3672 	state->offer_len = 0;
3673 
3674 #ifdef ARPING
3675 	if (ifo->arping_len && state->arping_index < ifo->arping_len) {
3676 		struct arp_state *astate;
3677 
3678 		astate = arp_new(ifp, NULL);
3679 		if (astate) {
3680 			astate->probed_cb = dhcp_arp_probed;
3681 			astate->conflicted_cb = dhcp_arp_conflicted;
3682 			dhcp_arp_probed(astate);
3683 		}
3684 		return;
3685 	}
3686 #endif
3687 
3688 	if (ifo->options & DHCPCD_STATIC) {
3689 		dhcp_static(ifp);
3690 		return;
3691 	}
3692 
3693 	if (ifo->options & DHCPCD_DHCP && dhcp_openbpf(ifp) == -1)
3694 		return;
3695 
3696 	if (ifo->options & DHCPCD_INFORM) {
3697 		dhcp_inform(ifp);
3698 		return;
3699 	}
3700 	if (ifp->hwlen == 0 && ifo->clientid[0] == '\0') {
3701 		logwarnx("%s: needs a clientid to configure", ifp->name);
3702 		dhcp_drop(ifp, "FAIL");
3703 		eloop_timeout_delete(ifp->ctx->eloop, NULL, ifp);
3704 		return;
3705 	}
3706 	/* We don't want to read the old lease if we NAK an old test */
3707 	nolease = state->offer && ifp->ctx->options & DHCPCD_TEST;
3708 	if (!nolease && ifo->options & DHCPCD_DHCP) {
3709 		state->offer_len = read_lease(ifp, &state->offer);
3710 		/* Check the saved lease matches the type we want */
3711 		if (state->offer) {
3712 #ifdef IN_IFF_DUPLICATED
3713 			struct in_addr addr;
3714 			struct ipv4_addr *ia;
3715 
3716 			addr.s_addr = state->offer->yiaddr;
3717 			ia = ipv4_iffindaddr(ifp, &addr, NULL);
3718 #endif
3719 
3720 			if ((!IS_DHCP(state->offer) &&
3721 			    !(ifo->options & DHCPCD_BOOTP)) ||
3722 #ifdef IN_IFF_DUPLICATED
3723 			    (ia && ia->addr_flags & IN_IFF_DUPLICATED) ||
3724 #endif
3725 			    (IS_DHCP(state->offer) &&
3726 			    ifo->options & DHCPCD_BOOTP))
3727 			{
3728 				free(state->offer);
3729 				state->offer = NULL;
3730 				state->offer_len = 0;
3731 			}
3732 		}
3733 	}
3734 	if (state->offer) {
3735 		struct ipv4_addr *ia;
3736 
3737 		get_lease(ifp, &state->lease, state->offer, state->offer_len);
3738 		state->lease.frominfo = 1;
3739 		if (state->new == NULL &&
3740 		    (ia = ipv4_iffindaddr(ifp,
3741 		    &state->lease.addr, &state->lease.mask)) != NULL)
3742 		{
3743 			/* We still have the IP address from the last lease.
3744 			 * Fake add the address and routes from it so the lease
3745 			 * can be cleaned up. */
3746 			state->new = malloc(state->offer_len);
3747 			if (state->new) {
3748 				memcpy(state->new,
3749 				    state->offer, state->offer_len);
3750 				state->new_len = state->offer_len;
3751 				state->addr = ia;
3752 				state->added |= STATE_ADDED | STATE_FAKE;
3753 				rt_build(ifp->ctx, AF_INET);
3754 			} else
3755 				logerr(__func__);
3756 		}
3757 		if (!IS_DHCP(state->offer)) {
3758 			free(state->offer);
3759 			state->offer = NULL;
3760 			state->offer_len = 0;
3761 		} else if (!(ifo->options & DHCPCD_LASTLEASE_EXTEND) &&
3762 		    state->lease.leasetime != ~0U &&
3763 		    stat(state->leasefile, &st) == 0)
3764 		{
3765 			time_t now;
3766 
3767 			/* Offset lease times and check expiry */
3768 			now = time(NULL);
3769 			if (now == -1 ||
3770 			    (time_t)state->lease.leasetime < now - st.st_mtime)
3771 			{
3772 				logdebugx("%s: discarding expired lease",
3773 				    ifp->name);
3774 				free(state->offer);
3775 				state->offer = NULL;
3776 				state->offer_len = 0;
3777 				state->lease.addr.s_addr = 0;
3778 				/* Technically we should discard the lease
3779 				 * as it's expired, just as DHCPv6 addresses
3780 				 * would be by the kernel.
3781 				 * However, this may violate POLA so
3782 				 * we currently leave it be.
3783 				 * If we get a totally different lease from
3784 				 * the DHCP server we'll drop it anyway, as
3785 				 * we will on any other event which would
3786 				 * trigger a lease drop.
3787 				 * This should only happen if dhcpcd stops
3788 				 * running and the lease expires before
3789 				 * dhcpcd starts again. */
3790 #if 0
3791 				if (state->new)
3792 					dhcp_drop(ifp, "EXPIRE");
3793 #endif
3794 			} else {
3795 				l = (uint32_t)(now - st.st_mtime);
3796 				state->lease.leasetime -= l;
3797 				state->lease.renewaltime -= l;
3798 				state->lease.rebindtime -= l;
3799 			}
3800 		}
3801 	}
3802 
3803 #ifdef IPV4LL
3804 	if (!(ifo->options & DHCPCD_DHCP)) {
3805 		if (ifo->options & DHCPCD_IPV4LL)
3806 			ipv4ll_start(ifp);
3807 		return;
3808 	}
3809 #endif
3810 
3811 	if (state->offer == NULL || !IS_DHCP(state->offer))
3812 		dhcp_discover(ifp);
3813 	else
3814 		dhcp_reboot(ifp);
3815 }
3816 
3817 void
3818 dhcp_start(struct interface *ifp)
3819 {
3820 	struct timespec tv;
3821 #ifdef ARPING
3822 	const struct dhcp_state *state;
3823 #endif
3824 
3825 	if (!(ifp->options->options & DHCPCD_IPV4))
3826 		return;
3827 
3828 	/* If we haven't been given a netmask for our requested address,
3829 	 * set it now. */
3830 	if (ifp->options->req_addr.s_addr != INADDR_ANY &&
3831 	    ifp->options->req_mask.s_addr == INADDR_ANY)
3832 		ifp->options->req_mask.s_addr =
3833 		    ipv4_getnetmask(ifp->options->req_addr.s_addr);
3834 
3835 	/* If we haven't specified a ClientID and our hardware address
3836 	 * length is greater than BOOTP CHADDR then we enforce a ClientID
3837 	 * of the hardware address family and the hardware address.
3838 	 * If there is no hardware address and no ClientID set,
3839 	 * force a DUID based ClientID. */
3840 	if (ifp->hwlen > 16)
3841 		ifp->options->options |= DHCPCD_CLIENTID;
3842 	else if (ifp->hwlen == 0 && !(ifp->options->options & DHCPCD_CLIENTID))
3843 		ifp->options->options |= DHCPCD_CLIENTID | DHCPCD_DUID;
3844 
3845 	/* Firewire and InfiniBand interfaces require ClientID and
3846 	 * the broadcast option being set. */
3847 	switch (ifp->family) {
3848 	case ARPHRD_IEEE1394:	/* FALLTHROUGH */
3849 	case ARPHRD_INFINIBAND:
3850 		ifp->options->options |= DHCPCD_CLIENTID | DHCPCD_BROADCAST;
3851 		break;
3852 	}
3853 
3854 	/* If we violate RFC2131 section 3.7 then require ARP
3855 	 * to detect if any other client wants our address. */
3856 	if (ifp->options->options & DHCPCD_LASTLEASE_EXTEND)
3857 		ifp->options->options |= DHCPCD_ARP;
3858 
3859 	/* No point in delaying a static configuration */
3860 	if (ifp->options->options & DHCPCD_STATIC ||
3861 	    !(ifp->options->options & DHCPCD_INITIAL_DELAY))
3862 	{
3863 		dhcp_start1(ifp);
3864 		return;
3865 	}
3866 
3867 #ifdef ARPING
3868 	/* If we have arpinged then we have already delayed. */
3869 	state = D_CSTATE(ifp);
3870 	if (state != NULL && state->arping_index != -1) {
3871 		dhcp_start1(ifp);
3872 		return;
3873 	}
3874 #endif
3875 
3876 	tv.tv_sec = DHCP_MIN_DELAY;
3877 	tv.tv_nsec = (suseconds_t)arc4random_uniform(
3878 	    (DHCP_MAX_DELAY - DHCP_MIN_DELAY) * NSEC_PER_SEC);
3879 	timespecnorm(&tv);
3880 	logdebugx("%s: delaying IPv4 for %0.1f seconds",
3881 	    ifp->name, timespec_to_double(&tv));
3882 
3883 	eloop_timeout_add_tv(ifp->ctx->eloop, &tv, dhcp_start1, ifp);
3884 }
3885 
3886 void
3887 dhcp_abort(struct interface *ifp)
3888 {
3889 	struct dhcp_state *state;
3890 
3891 	state = D_STATE(ifp);
3892 #ifdef ARPING
3893 	if (state != NULL)
3894 		state->arping_index = -1;
3895 #endif
3896 
3897 	eloop_timeout_delete(ifp->ctx->eloop, dhcp_start1, ifp);
3898 
3899 	if (state != NULL && state->added) {
3900 		rt_build(ifp->ctx, AF_INET);
3901 #ifdef ARP
3902 		arp_announceaddr(ifp->ctx, &state->addr->addr);
3903 #endif
3904 	}
3905 }
3906 
3907 void
3908 dhcp_handleifa(int cmd, struct ipv4_addr *ia, pid_t pid)
3909 {
3910 	struct interface *ifp;
3911 	struct dhcp_state *state;
3912 	struct if_options *ifo;
3913 	uint8_t i;
3914 
3915 	ifp = ia->iface;
3916 	state = D_STATE(ifp);
3917 	if (state == NULL || state->state == DHS_NONE)
3918 		return;
3919 
3920 	if (cmd == RTM_DELADDR) {
3921 		if (state->addr == ia) {
3922 			loginfox("%s: pid %d deleted IP address %s",
3923 			    ifp->name, pid, ia->saddr);
3924 			state->addr = NULL;
3925 			/* Don't clear the added state as we need
3926 			 * to drop the lease. */
3927 			dhcp_drop(ifp, "EXPIRE");
3928 			dhcp_start1(ifp);
3929 		}
3930 		return;
3931 	}
3932 
3933 	if (cmd != RTM_NEWADDR)
3934 		return;
3935 
3936 #ifdef IN_IFF_NOTUSEABLE
3937 	if (ia->addr_flags & IN_IFF_NOTUSEABLE)
3938 		return;
3939 #endif
3940 
3941 	ifo = ifp->options;
3942 	if (ifo->options & DHCPCD_INFORM) {
3943 		if (state->state != DHS_INFORM)
3944 			dhcp_inform(ifp);
3945 		return;
3946 	}
3947 
3948 	if (!(ifo->options & DHCPCD_STATIC))
3949 		return;
3950 	if (ifo->req_addr.s_addr != INADDR_ANY)
3951 		return;
3952 
3953 	free(state->old);
3954 	state->old = state->new;
3955 	state->new_len = dhcp_message_new(&state->new, &ia->addr, &ia->mask);
3956 	if (state->new == NULL)
3957 		return;
3958 	if (ifp->flags & IFF_POINTOPOINT) {
3959 		for (i = 1; i < 255; i++)
3960 			if (i != DHO_ROUTER && has_option_mask(ifo->dstmask,i))
3961 				dhcp_message_add_addr(state->new, i, ia->brd);
3962 	}
3963 	state->reason = "STATIC";
3964 	rt_build(ifp->ctx, AF_INET);
3965 	script_runreason(ifp, state->reason);
3966 	if (ifo->options & DHCPCD_INFORM) {
3967 		state->state = DHS_INFORM;
3968 		dhcp_new_xid(ifp);
3969 		state->lease.server.s_addr = INADDR_ANY;
3970 		state->addr = ia;
3971 		dhcp_inform(ifp);
3972 	}
3973 }
3974