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