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