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