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