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