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