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