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