xref: /dragonfly/contrib/dhcpcd/src/dhcp6.c (revision f984587a)
1 /* SPDX-License-Identifier: BSD-2-Clause */
2 /*
3  * dhcpcd - DHCP client daemon
4  * Copyright (c) 2006-2023 Roy Marples <roy@marples.name>
5  * All rights reserved
6 
7  * Redistribution and use in source and binary forms, with or without
8  * modification, are permitted provided that the following conditions
9  * are met:
10  * 1. Redistributions of source code must retain the above copyright
11  *    notice, this list of conditions and the following disclaimer.
12  * 2. Redistributions in binary form must reproduce the above copyright
13  *    notice, this list of conditions and the following disclaimer in the
14  *    documentation and/or other materials provided with the distribution.
15  *
16  * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND
17  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
18  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
19  * ARE DISCLAIMED.  IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
20  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
21  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
22  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
23  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
24  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
25  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
26  * SUCH DAMAGE.
27  */
28 
29 #include <sys/utsname.h>
30 #include <sys/types.h>
31 
32 #include <netinet/in.h>
33 #include <netinet/ip6.h>
34 
35 #include <assert.h>
36 #include <ctype.h>
37 #include <errno.h>
38 #include <fcntl.h>
39 #include <inttypes.h>
40 #include <stdbool.h>
41 #include <stddef.h>
42 #include <stdlib.h>
43 #include <string.h>
44 #include <unistd.h>
45 #include <fcntl.h>
46 #include <syslog.h>
47 
48 #define ELOOP_QUEUE	ELOOP_DHCP6
49 #include "config.h"
50 #include "common.h"
51 #include "dhcp.h"
52 #include "dhcp6.h"
53 #include "duid.h"
54 #include "eloop.h"
55 #include "if.h"
56 #include "if-options.h"
57 #include "ipv6nd.h"
58 #include "logerr.h"
59 #include "privsep.h"
60 #include "script.h"
61 
62 #ifdef HAVE_SYS_BITOPS_H
63 #include <sys/bitops.h>
64 #else
65 #include "compat/bitops.h"
66 #endif
67 
68 /* DHCPCD Project has been assigned an IANA PEN of 40712 */
69 #define DHCPCD_IANA_PEN 40712
70 
71 /* Unsure if I want this */
72 //#define VENDOR_SPLIT
73 
74 /* Support older systems with different defines */
75 #if !defined(IPV6_RECVPKTINFO) && defined(IPV6_PKTINFO)
76 #define IPV6_RECVPKTINFO IPV6_PKTINFO
77 #endif
78 
79 #ifdef DHCP6
80 
81 /* Assert the correct structure size for on wire */
82 struct dhcp6_message {
83 	uint8_t type;
84 	uint8_t xid[3];
85 	/* followed by options */
86 };
87 __CTASSERT(sizeof(struct dhcp6_message) == 4);
88 
89 struct dhcp6_option {
90 	uint16_t code;
91 	uint16_t len;
92 	/* followed by data */
93 };
94 __CTASSERT(sizeof(struct dhcp6_option) == 4);
95 
96 struct dhcp6_ia_na {
97 	uint8_t iaid[4];
98 	uint32_t t1;
99 	uint32_t t2;
100 };
101 __CTASSERT(sizeof(struct dhcp6_ia_na) == 12);
102 
103 struct dhcp6_ia_ta {
104 	uint8_t iaid[4];
105 };
106 __CTASSERT(sizeof(struct dhcp6_ia_ta) == 4);
107 
108 struct dhcp6_ia_addr {
109 	struct in6_addr addr;
110 	uint32_t pltime;
111 	uint32_t vltime;
112 };
113 __CTASSERT(sizeof(struct dhcp6_ia_addr) == 16 + 8);
114 
115 /* XXX FIXME: This is the only packed structure and it does not align.
116  * Maybe manually decode it? */
117 struct dhcp6_pd_addr {
118 	uint32_t pltime;
119 	uint32_t vltime;
120 	uint8_t prefix_len;
121 	struct in6_addr prefix;
122 } __packed;
123 __CTASSERT(sizeof(struct dhcp6_pd_addr) == 8 + 1 + 16);
124 
125 struct dhcp6_op {
126 	uint16_t type;
127 	const char *name;
128 };
129 
130 static const struct dhcp6_op dhcp6_ops[] = {
131 	{ DHCP6_SOLICIT, "SOLICIT6" },
132 	{ DHCP6_ADVERTISE, "ADVERTISE6" },
133 	{ DHCP6_REQUEST, "REQUEST6" },
134 	{ DHCP6_REPLY, "REPLY6" },
135 	{ DHCP6_RENEW, "RENEW6" },
136 	{ DHCP6_REBIND, "REBIND6" },
137 	{ DHCP6_CONFIRM, "CONFIRM6" },
138 	{ DHCP6_INFORMATION_REQ, "INFORM6" },
139 	{ DHCP6_RELEASE, "RELEASE6" },
140 	{ DHCP6_RECONFIGURE, "RECONFIGURE6" },
141 	{ DHCP6_DECLINE, "DECLINE6" },
142 	{ 0, NULL }
143 };
144 
145 struct dhcp_compat {
146 	uint8_t dhcp_opt;
147 	uint16_t dhcp6_opt;
148 };
149 
150 /*
151  * RFC 5908 deprecates OPTION_SNTP_SERVERS.
152  * But we can support both as the hook scripts will uniqify the
153  * results if the server returns both options.
154  */
155 static const struct dhcp_compat dhcp_compats[] = {
156 	{ DHO_DNSSERVER,	D6_OPTION_DNS_SERVERS },
157 	{ DHO_HOSTNAME,		D6_OPTION_FQDN },
158 	{ DHO_DNSDOMAIN,	D6_OPTION_FQDN },
159 	{ DHO_NISSERVER,	D6_OPTION_NIS_SERVERS },
160 	{ DHO_NTPSERVER,	D6_OPTION_SNTP_SERVERS },
161 	{ DHO_NTPSERVER,	D6_OPTION_NTP_SERVER },
162 	{ DHO_RAPIDCOMMIT,	D6_OPTION_RAPID_COMMIT },
163 	{ DHO_FQDN,		D6_OPTION_FQDN },
164 	{ DHO_VIVCO,		D6_OPTION_VENDOR_CLASS },
165 	{ DHO_VIVSO,		D6_OPTION_VENDOR_OPTS },
166 	{ DHO_DNSSEARCH,	D6_OPTION_DOMAIN_LIST },
167 	{ 0, 0 }
168 };
169 
170 static const char * const dhcp6_statuses[] = {
171 	"Success",
172 	"Unspecified Failure",
173 	"No Addresses Available",
174 	"No Binding",
175 	"Not On Link",
176 	"Use Multicast",
177 	"No Prefix Available"
178 };
179 
180 static void dhcp6_bind(struct interface *, const char *, const char *);
181 static void dhcp6_failinform(void *);
182 static void dhcp6_recvaddr(void *, unsigned short);
183 static void dhcp6_startdecline(struct interface *);
184 
185 #ifdef SMALL
186 #define dhcp6_hasprefixdelegation(a)	(0)
187 #else
188 static int dhcp6_hasprefixdelegation(struct interface *);
189 #endif
190 
191 #define DECLINE_IA(ia) \
192 	((ia)->addr_flags & IN6_IFF_DUPLICATED && \
193 	(ia)->ia_type != 0 && (ia)->ia_type != D6_OPTION_IA_PD && \
194 	!((ia)->flags & IPV6_AF_STALE) && \
195 	(ia)->prefix_vltime != 0)
196 
197 void
198 dhcp6_printoptions(const struct dhcpcd_ctx *ctx,
199     const struct dhcp_opt *opts, size_t opts_len)
200 {
201 	size_t i, j;
202 	const struct dhcp_opt *opt, *opt2;
203 	int cols;
204 
205 	for (i = 0, opt = ctx->dhcp6_opts;
206 	    i < ctx->dhcp6_opts_len; i++, opt++)
207 	{
208 		for (j = 0, opt2 = opts; j < opts_len; j++, opt2++)
209 			if (opt2->option == opt->option)
210 				break;
211 		if (j == opts_len) {
212 			cols = printf("%05d %s", opt->option, opt->var);
213 			dhcp_print_option_encoding(opt, cols);
214 		}
215 	}
216 	for (i = 0, opt = opts; i < opts_len; i++, opt++) {
217 		cols = printf("%05d %s", opt->option, opt->var);
218 		dhcp_print_option_encoding(opt, cols);
219 	}
220 }
221 
222 static size_t
223 dhcp6_makeuser(void *data, const struct interface *ifp)
224 {
225 	const struct if_options *ifo = ifp->options;
226 	struct dhcp6_option o;
227 	uint8_t *p;
228 	const uint8_t *up, *ue;
229 	uint16_t ulen, unlen;
230 	size_t olen;
231 
232 	/* Convert the DHCPv4 user class option to DHCPv6 */
233 	up = ifo->userclass;
234 	ulen = *up++;
235 	if (ulen == 0)
236 		return 0;
237 
238 	p = data;
239 	olen = 0;
240 	if (p != NULL)
241 		p += sizeof(o);
242 
243 	ue = up + ulen;
244 	for (; up < ue; up += ulen) {
245 		ulen = *up++;
246 		olen += sizeof(ulen) + ulen;
247 		if (data == NULL)
248 			continue;
249 		unlen = htons(ulen);
250 		memcpy(p, &unlen, sizeof(unlen));
251 		p += sizeof(unlen);
252 		memcpy(p, up, ulen);
253 		p += ulen;
254 	}
255 	if (data != NULL) {
256 		o.code = htons(D6_OPTION_USER_CLASS);
257 		o.len = htons((uint16_t)olen);
258 		memcpy(data, &o, sizeof(o));
259 	}
260 
261 	return sizeof(o) + olen;
262 }
263 
264 static size_t
265 dhcp6_makevendor(void *data, const struct interface *ifp)
266 {
267 	const struct if_options *ifo;
268 	size_t len, vlen, i;
269 	uint8_t *p;
270 	const struct vivco *vivco;
271 	struct dhcp6_option o;
272 
273 	ifo = ifp->options;
274 	len = sizeof(uint32_t); /* IANA PEN */
275 	if (ifo->vivco_en) {
276 		vlen = 0;
277 		for (i = 0, vivco = ifo->vivco;
278 		    i < ifo->vivco_len;
279 		    i++, vivco++)
280 			vlen += sizeof(uint16_t) + vivco->len;
281 		len += vlen;
282 	} else if (ifo->vendorclassid[0] != '\0') {
283 		/* dhcpcd owns DHCPCD_IANA_PEN.
284 		 * If you need your own string, get your own IANA PEN. */
285 		vlen = strlen(ifp->ctx->vendor);
286 		len += sizeof(uint16_t) + vlen;
287 	} else
288 		return 0;
289 
290 	if (len > UINT16_MAX) {
291 		logerrx("%s: DHCPv6 Vendor Class too big", ifp->name);
292 		return 0;
293 	}
294 
295 	if (data != NULL) {
296 		uint32_t pen;
297 		uint16_t hvlen;
298 
299 		p = data;
300 		o.code = htons(D6_OPTION_VENDOR_CLASS);
301 		o.len = htons((uint16_t)len);
302 		memcpy(p, &o, sizeof(o));
303 		p += sizeof(o);
304 		pen = htonl(ifo->vivco_en ? ifo->vivco_en : DHCPCD_IANA_PEN);
305 		memcpy(p, &pen, sizeof(pen));
306 		p += sizeof(pen);
307 
308 		if (ifo->vivco_en) {
309 			for (i = 0, vivco = ifo->vivco;
310 			    i < ifo->vivco_len;
311 			    i++, vivco++)
312 			{
313 				hvlen = htons((uint16_t)vivco->len);
314 				memcpy(p, &hvlen, sizeof(hvlen));
315 				p += sizeof(hvlen);
316 				memcpy(p, vivco->data, vivco->len);
317 				p += vivco->len;
318 			}
319 		} else if (ifo->vendorclassid[0] != '\0') {
320 			hvlen = htons((uint16_t)vlen);
321 			memcpy(p, &hvlen, sizeof(hvlen));
322 			p += sizeof(hvlen);
323 			memcpy(p, ifp->ctx->vendor, vlen);
324 		}
325 	}
326 
327 	return sizeof(o) + len;
328 }
329 
330 static void *
331 dhcp6_findoption(void *data, size_t data_len, uint16_t code, uint16_t *len)
332 {
333 	uint8_t *d;
334 	struct dhcp6_option o;
335 
336 	code = htons(code);
337 	for (d = data; data_len != 0; d += o.len, data_len -= o.len) {
338 		if (data_len < sizeof(o)) {
339 			errno = EINVAL;
340 			return NULL;
341 		}
342 		memcpy(&o, d, sizeof(o));
343 		d += sizeof(o);
344 		data_len -= sizeof(o);
345 		o.len = htons(o.len);
346 		if (data_len < o.len) {
347 			errno = EINVAL;
348 			return NULL;
349 		}
350 		if (o.code == code) {
351 			if (len != NULL)
352 				*len = o.len;
353 			return d;
354 		}
355 	}
356 
357 	errno = ENOENT;
358 	return NULL;
359 }
360 
361 static void *
362 dhcp6_findmoption(void *data, size_t data_len, uint16_t code,
363     uint16_t *len)
364 {
365 	uint8_t *d;
366 
367 	if (data_len < sizeof(struct dhcp6_message)) {
368 		errno = EINVAL;
369 		return false;
370 	}
371 	d = data;
372 	d += sizeof(struct dhcp6_message);
373 	data_len -= sizeof(struct dhcp6_message);
374 	return dhcp6_findoption(d, data_len, code, len);
375 }
376 
377 static const uint8_t *
378 dhcp6_getoption(struct dhcpcd_ctx *ctx,
379     size_t *os, unsigned int *code, size_t *len,
380     const uint8_t *od, size_t ol, struct dhcp_opt **oopt)
381 {
382 	struct dhcp6_option o;
383 	size_t i;
384 	struct dhcp_opt *opt;
385 
386 	if (od != NULL) {
387 		*os = sizeof(o);
388 		if (ol < *os) {
389 			errno = EINVAL;
390 			return NULL;
391 		}
392 		memcpy(&o, od, sizeof(o));
393 		*len = ntohs(o.len);
394 		if (*len > ol - *os) {
395 			errno = ERANGE;
396 			return NULL;
397 		}
398 		*code = ntohs(o.code);
399 	}
400 
401 	*oopt = NULL;
402 	for (i = 0, opt = ctx->dhcp6_opts;
403 	    i < ctx->dhcp6_opts_len; i++, opt++)
404 	{
405 		if (opt->option == *code) {
406 			*oopt = opt;
407 			break;
408 		}
409 	}
410 
411 	if (od != NULL)
412 		return od + sizeof(o);
413 	return NULL;
414 }
415 
416 static bool
417 dhcp6_updateelapsed(struct interface *ifp, struct dhcp6_message *m, size_t len)
418 {
419 	uint8_t *opt;
420 	uint16_t opt_len;
421 	struct dhcp6_state *state;
422 	struct timespec tv;
423 	unsigned long long hsec;
424 	uint16_t sec;
425 
426 	opt = dhcp6_findmoption(m, len, D6_OPTION_ELAPSED, &opt_len);
427 	if (opt == NULL)
428 		return false;
429 	if (opt_len != sizeof(sec)) {
430 		errno = EINVAL;
431 		return false;
432 	}
433 
434 	state = D6_STATE(ifp);
435 	clock_gettime(CLOCK_MONOTONIC, &tv);
436 	if (state->RTC == 0) {
437 		/* An RTC of zero means we're the first message
438 		 * out of the door, so the elapsed time is zero. */
439 		state->started = tv;
440 		hsec = 0;
441 	} else {
442 		unsigned long long secs;
443 		unsigned int nsecs;
444 
445 		secs = eloop_timespec_diff(&tv, &state->started, &nsecs);
446 		/* Elapsed time is measured in centiseconds.
447 		 * We need to be sure it will not potentially overflow. */
448 		if (secs >= (UINT16_MAX / CSEC_PER_SEC) + 1)
449 			hsec = UINT16_MAX;
450 		else {
451 			hsec = (secs * CSEC_PER_SEC) +
452 			    (nsecs / NSEC_PER_CSEC);
453 			if (hsec > UINT16_MAX)
454 				hsec = UINT16_MAX;
455 		}
456 	}
457 	sec = htons((uint16_t)hsec);
458 	memcpy(opt, &sec, sizeof(sec));
459 	return true;
460 }
461 
462 static void
463 dhcp6_newxid(const struct interface *ifp, struct dhcp6_message *m)
464 {
465 	const struct interface *ifp1;
466 	const struct dhcp6_state *state1;
467 	uint32_t xid;
468 
469 	if (ifp->options->options & DHCPCD_XID_HWADDR &&
470 	    ifp->hwlen >= sizeof(xid))
471 		/* The lower bits are probably more unique on the network */
472 		memcpy(&xid, (ifp->hwaddr + ifp->hwlen) - sizeof(xid),
473 		    sizeof(xid));
474 	else {
475 again:
476 		xid = arc4random();
477 	}
478 
479 	m->xid[0] = (xid >> 16) & 0xff;
480 	m->xid[1] = (xid >> 8) & 0xff;
481 	m->xid[2] = xid & 0xff;
482 
483 	/* Ensure it's unique */
484 	TAILQ_FOREACH(ifp1, ifp->ctx->ifaces, next) {
485 		if (ifp == ifp1)
486 			continue;
487 		if ((state1 = D6_CSTATE(ifp1)) == NULL)
488 			continue;
489 		if (state1->send != NULL &&
490 		    state1->send->xid[0] == m->xid[0] &&
491 		    state1->send->xid[1] == m->xid[1] &&
492 		    state1->send->xid[2] == m->xid[2])
493 			break;
494 	}
495 
496 	if (ifp1 != NULL) {
497 		if (ifp->options->options & DHCPCD_XID_HWADDR &&
498 		    ifp->hwlen >= sizeof(xid))
499 		{
500 			logerrx("%s: duplicate xid on %s",
501 			    ifp->name, ifp1->name);
502 			    return;
503 		}
504 		goto again;
505 	}
506 }
507 
508 #ifndef SMALL
509 static const struct if_sla *
510 dhcp6_findselfsla(struct interface *ifp)
511 {
512 	size_t i, j;
513 	struct if_ia *ia;
514 
515 	for (i = 0; i < ifp->options->ia_len; i++) {
516 		ia = &ifp->options->ia[i];
517 		if (ia->ia_type != D6_OPTION_IA_PD)
518 			continue;
519 		for (j = 0; j < ia->sla_len; j++) {
520 			if (strcmp(ia->sla[j].ifname, ifp->name) == 0)
521 				return &ia->sla[j];
522 		}
523 	}
524 	return NULL;
525 }
526 
527 static int
528 dhcp6_delegateaddr(struct in6_addr *addr, struct interface *ifp,
529     const struct ipv6_addr *prefix, const struct if_sla *sla, struct if_ia *ia)
530 {
531 	struct dhcp6_state *state;
532 	struct if_sla asla;
533 	char sabuf[INET6_ADDRSTRLEN];
534 	const char *sa;
535 
536 	state = D6_STATE(ifp);
537 	if (state == NULL) {
538 		ifp->if_data[IF_DATA_DHCP6] = calloc(1, sizeof(*state));
539 		state = D6_STATE(ifp);
540 		if (state == NULL) {
541 			logerr(__func__);
542 			return -1;
543 		}
544 
545 		TAILQ_INIT(&state->addrs);
546 		state->state = DH6S_DELEGATED;
547 		state->reason = "DELEGATED6";
548 	}
549 
550 	if (sla == NULL || !sla->sla_set) {
551 		/* No SLA set, so make an assumption of
552 		 * desired SLA and prefix length. */
553 		asla.sla = ifp->index;
554 		asla.prefix_len = 0;
555 		asla.sla_set = false;
556 		sla = &asla;
557 	} else if (sla->prefix_len == 0) {
558 		/* An SLA was given, but prefix length was not.
559 		 * We need to work out a suitable prefix length for
560 		 * potentially more than one interface. */
561 		asla.sla = sla->sla;
562 		asla.prefix_len = 0;
563 		asla.sla_set = sla->sla_set;
564 		sla = &asla;
565 	}
566 
567 	if (sla->prefix_len == 0) {
568 		uint32_t sla_max;
569 		int bits;
570 
571 		sla_max = ia->sla_max;
572 		if (sla_max == 0 && (sla == NULL || !sla->sla_set)) {
573 			const struct interface *ifi;
574 
575 			TAILQ_FOREACH(ifi, ifp->ctx->ifaces, next) {
576 				if (ifi->index > sla_max)
577 					sla_max = ifi->index;
578 			}
579 		}
580 
581 		bits = fls32(sla_max);
582 
583 		if (prefix->prefix_len + bits > (int)UINT8_MAX)
584 			asla.prefix_len = UINT8_MAX;
585 		else {
586 			asla.prefix_len = (uint8_t)(prefix->prefix_len + bits);
587 
588 			/* Make a 64 prefix by default, as this makes SLAAC
589 			 * possible.
590 			 * Otherwise round up to the nearest 4 bits. */
591 			if (asla.prefix_len <= 64)
592 				asla.prefix_len = 64;
593 			else
594 				asla.prefix_len =
595 				    (uint8_t)ROUNDUP4(asla.prefix_len);
596 		}
597 
598 #define BIT(n) (1UL << (n))
599 #define BIT_MASK(len) (BIT(len) - 1)
600 		if (ia->sla_max == 0) {
601 			/* Work out the real sla_max from our bits used */
602 			bits = asla.prefix_len - prefix->prefix_len;
603 			/* Make static analysis happy.
604 			 * Bits cannot be bigger than 32 thanks to fls32. */
605 			assert(bits <= 32);
606 			ia->sla_max = (uint32_t)BIT_MASK(bits);
607 		}
608 	}
609 
610 	if (ipv6_userprefix(&prefix->prefix, prefix->prefix_len,
611 		sla->sla, addr, sla->prefix_len) == -1)
612 	{
613 		sa = inet_ntop(AF_INET6, &prefix->prefix,
614 		    sabuf, sizeof(sabuf));
615 		logerr("%s: invalid prefix %s/%d + %d/%d",
616 		    ifp->name, sa, prefix->prefix_len,
617 		    sla->sla, sla->prefix_len);
618 		return -1;
619 	}
620 
621 	if (prefix->prefix_exclude_len &&
622 	    IN6_ARE_ADDR_EQUAL(addr, &prefix->prefix_exclude))
623 	{
624 		sa = inet_ntop(AF_INET6, &prefix->prefix_exclude,
625 		    sabuf, sizeof(sabuf));
626 		logerrx("%s: cannot delegate excluded prefix %s/%d",
627 		    ifp->name, sa, prefix->prefix_exclude_len);
628 		return -1;
629 	}
630 
631 	return sla->prefix_len;
632 }
633 #endif
634 
635 static int
636 dhcp6_makemessage(struct interface *ifp)
637 {
638 	struct dhcp6_state *state;
639 	struct dhcp6_message *m;
640 	struct dhcp6_option o;
641 	uint8_t *p, *si, *unicast, IA;
642 	size_t n, l, len, ml, hl;
643 	uint8_t type;
644 	uint16_t si_len, uni_len, n_options;
645 	uint8_t *o_lenp;
646 	struct if_options *ifo = ifp->options;
647 	const struct dhcp_opt *opt, *opt2;
648 	const struct ipv6_addr *ap;
649 	char hbuf[HOSTNAME_MAX_LEN + 1];
650 	const char *hostname;
651 	int fqdn;
652 	struct dhcp6_ia_na ia_na;
653 	uint16_t ia_na_len;
654 	struct if_ia *ifia;
655 #ifdef AUTH
656 	uint16_t auth_len;
657 #endif
658 	uint8_t duid[DUID_LEN];
659 	size_t duid_len = 0;
660 
661 	state = D6_STATE(ifp);
662 	if (state->send) {
663 		free(state->send);
664 		state->send = NULL;
665 	}
666 
667 	switch(state->state) {
668 	case DH6S_INIT: /* FALLTHROUGH */
669 	case DH6S_DISCOVER:
670 		type = DHCP6_SOLICIT;
671 		break;
672 	case DH6S_REQUEST:
673 		type = DHCP6_REQUEST;
674 		break;
675 	case DH6S_CONFIRM:
676 		type = DHCP6_CONFIRM;
677 		break;
678 	case DH6S_REBIND:
679 		type = DHCP6_REBIND;
680 		break;
681 	case DH6S_RENEW:
682 		type = DHCP6_RENEW;
683 		break;
684 	case DH6S_INFORM:
685 		type = DHCP6_INFORMATION_REQ;
686 		break;
687 	case DH6S_RELEASE:
688 		type = DHCP6_RELEASE;
689 		break;
690 	case DH6S_DECLINE:
691 		type = DHCP6_DECLINE;
692 		break;
693 	default:
694 		errno = EINVAL;
695 		return -1;
696 	}
697 
698 	/* RFC 4704 Section 5 says we can only send FQDN for these
699 	 * message types. */
700 	switch(type) {
701 	case DHCP6_SOLICIT:
702 	case DHCP6_REQUEST:
703 	case DHCP6_RENEW:
704 	case DHCP6_REBIND:
705 		fqdn = ifo->fqdn;
706 		break;
707 	default:
708 		fqdn = FQDN_DISABLE;
709 		break;
710 	}
711 
712 	if (fqdn == FQDN_DISABLE && ifo->options & DHCPCD_HOSTNAME) {
713 		/* We're sending the DHCPv4 hostname option, so send FQDN as
714 		 * DHCPv6 has no FQDN option and DHCPv4 must not send
715 		 * hostname and FQDN according to RFC4702 */
716 		fqdn = FQDN_BOTH;
717 	}
718 	if (fqdn != FQDN_DISABLE)
719 		hostname = dhcp_get_hostname(hbuf, sizeof(hbuf), ifo);
720 	else
721 		hostname = NULL; /* appearse gcc */
722 
723 	/* Work out option size first */
724 	n_options = 0;
725 	len = 0;
726 	si = NULL;
727 	hl = 0; /* Appease gcc */
728 	if (state->state != DH6S_RELEASE && state->state != DH6S_DECLINE) {
729 		for (l = 0, opt = ifp->ctx->dhcp6_opts;
730 		    l < ifp->ctx->dhcp6_opts_len;
731 		    l++, opt++)
732 		{
733 			for (n = 0, opt2 = ifo->dhcp6_override;
734 			    n < ifo->dhcp6_override_len;
735 			    n++, opt2++)
736 			{
737 				if (opt->option == opt2->option)
738 					break;
739 			}
740 			if (n < ifo->dhcp6_override_len)
741 				continue;
742 			if (!DHC_REQOPT(opt, ifo->requestmask6, ifo->nomask6))
743 				continue;
744 			n_options++;
745 			len += sizeof(o.len);
746 		}
747 #ifndef SMALL
748 		for (l = 0, opt = ifo->dhcp6_override;
749 		    l < ifo->dhcp6_override_len;
750 		    l++, opt++)
751 		{
752 			if (!DHC_REQOPT(opt, ifo->requestmask6, ifo->nomask6))
753 				continue;
754 			n_options++;
755 			len += sizeof(o.len);
756 		}
757 		if (dhcp6_findselfsla(ifp)) {
758 			n_options++;
759 			len += sizeof(o.len);
760 		}
761 #endif
762 		if (len)
763 			len += sizeof(o);
764 
765 		if (fqdn != FQDN_DISABLE) {
766 			hl = encode_rfc1035(hostname, NULL);
767 			len += sizeof(o) + 1 + hl;
768 		}
769 
770 		if (!has_option_mask(ifo->nomask6, D6_OPTION_MUDURL) &&
771 		    ifo->mudurl[0])
772 			len += sizeof(o) + ifo->mudurl[0];
773 
774 #ifdef AUTH
775 		if ((ifo->auth.options & DHCPCD_AUTH_SENDREQUIRE) !=
776 		    DHCPCD_AUTH_SENDREQUIRE &&
777 		    DHC_REQ(ifo->requestmask6, ifo->nomask6,
778 		    D6_OPTION_RECONF_ACCEPT))
779 			len += sizeof(o); /* Reconfigure Accept */
780 #endif
781 	}
782 
783 	len += sizeof(*state->send);
784 	len += sizeof(o) + sizeof(uint16_t); /* elapsed */
785 
786 	if (ifo->options & DHCPCD_ANONYMOUS) {
787 		duid_len = duid_make(duid, ifp, DUID_LL);
788 		len += sizeof(o) + duid_len;
789 	} else {
790 		len += sizeof(o) + ifp->ctx->duid_len;
791 	}
792 
793 	if (!has_option_mask(ifo->nomask6, D6_OPTION_USER_CLASS))
794 		len += dhcp6_makeuser(NULL, ifp);
795 	if (!has_option_mask(ifo->nomask6, D6_OPTION_VENDOR_CLASS))
796 		len += dhcp6_makevendor(NULL, ifp);
797 
798 	/* IA */
799 	m = NULL;
800 	ml = 0;
801 	switch(state->state) {
802 	case DH6S_REQUEST:
803 		m = state->recv;
804 		ml = state->recv_len;
805 		/* FALLTHROUGH */
806 	case DH6S_DECLINE:
807 		/* FALLTHROUGH */
808 	case DH6S_RELEASE:
809 		/* FALLTHROUGH */
810 	case DH6S_RENEW:
811 		if (m == NULL) {
812 			m = state->new;
813 			ml = state->new_len;
814 		}
815 		si = dhcp6_findmoption(m, ml, D6_OPTION_SERVERID, &si_len);
816 		if (si == NULL)
817 			return -1;
818 		len += sizeof(o) + si_len;
819 		/* FALLTHROUGH */
820 	case DH6S_REBIND:
821 		/* FALLTHROUGH */
822 	case DH6S_CONFIRM:
823 		/* FALLTHROUGH */
824 	case DH6S_DISCOVER:
825 		if (m == NULL) {
826 			m = state->new;
827 			ml = state->new_len;
828 		}
829 		TAILQ_FOREACH(ap, &state->addrs, next) {
830 			if (ap->flags & IPV6_AF_STALE)
831 				continue;
832 			if (!(ap->flags & IPV6_AF_REQUEST) &&
833 			    (ap->prefix_vltime == 0 ||
834 			    state->state == DH6S_DISCOVER))
835 				continue;
836 			if (DECLINE_IA(ap) && state->state != DH6S_DECLINE)
837 				continue;
838 			if (ap->ia_type == D6_OPTION_IA_PD) {
839 #ifndef SMALL
840 				len += sizeof(o) + sizeof(struct dhcp6_pd_addr);
841 				if (ap->prefix_exclude_len)
842 					len += sizeof(o) + 1 +
843 					    (uint8_t)((ap->prefix_exclude_len -
844 					    ap->prefix_len - 1) / NBBY) + 1;
845 #endif
846 			} else
847 				len += sizeof(o) + sizeof(struct dhcp6_ia_addr);
848 		}
849 		/* FALLTHROUGH */
850 	case DH6S_INIT:
851 		for (l = 0; l < ifo->ia_len; l++) {
852 			len += sizeof(o) + sizeof(uint32_t); /* IAID */
853 			/* IA_TA does not have T1 or T2 timers */
854 			if (ifo->ia[l].ia_type != D6_OPTION_IA_TA)
855 				len += sizeof(uint32_t) + sizeof(uint32_t);
856 		}
857 		IA = 1;
858 		break;
859 	default:
860 		IA = 0;
861 	}
862 
863 	if (state->state == DH6S_DISCOVER &&
864 	    !(ifp->ctx->options & DHCPCD_TEST) &&
865 	    DHC_REQ(ifo->requestmask6, ifo->nomask6, D6_OPTION_RAPID_COMMIT))
866 		len += sizeof(o);
867 
868 	if (m == NULL) {
869 		m = state->new;
870 		ml = state->new_len;
871 	}
872 
873 	switch(state->state) {
874 	case DH6S_REQUEST: /* FALLTHROUGH */
875 	case DH6S_RENEW:   /* FALLTHROUGH */
876 	case DH6S_RELEASE:
877 		if (has_option_mask(ifo->nomask6, D6_OPTION_UNICAST)) {
878 			unicast = NULL;
879 			break;
880 		}
881 		unicast = dhcp6_findmoption(m, ml, D6_OPTION_UNICAST, &uni_len);
882 		break;
883 	default:
884 		unicast = NULL;
885 		break;
886 	}
887 
888 	/* In non manager mode we listen and send from fixed addresses.
889 	 * We should try and match an address we have to unicast to,
890 	 * but for now this is the safest policy. */
891 	if (unicast != NULL && !(ifp->ctx->options & DHCPCD_MANAGER)) {
892 		logdebugx("%s: ignoring unicast option as not manager",
893 		    ifp->name);
894 		unicast = NULL;
895 	}
896 
897 #ifdef AUTH
898 	auth_len = 0;
899 	if (ifo->auth.options & DHCPCD_AUTH_SEND) {
900 		ssize_t alen = dhcp_auth_encode(ifp->ctx, &ifo->auth,
901 		    state->auth.token, NULL, 0, 6, type, NULL, 0);
902 		if (alen != -1 && alen > UINT16_MAX) {
903 			errno = ERANGE;
904 			alen = -1;
905 		}
906 		if (alen == -1)
907 			logerr("%s: %s: dhcp_auth_encode", __func__, ifp->name);
908 		else if (alen != 0) {
909 			auth_len = (uint16_t)alen;
910 			len += sizeof(o) + auth_len;
911 		}
912 	}
913 #endif
914 
915 	state->send = malloc(len);
916 	if (state->send == NULL)
917 		return -1;
918 
919 	state->send_len = len;
920 	state->send->type = type;
921 
922 	/* If we found a unicast option, copy it to our state for sending */
923 	if (unicast && uni_len == sizeof(state->unicast))
924 		memcpy(&state->unicast, unicast, sizeof(state->unicast));
925 	else
926 		state->unicast = in6addr_any;
927 
928 	dhcp6_newxid(ifp, state->send);
929 
930 #define COPYIN1(_code, _len)		{	\
931 	o.code = htons((_code));		\
932 	o.len = htons((_len));			\
933 	memcpy(p, &o, sizeof(o));		\
934 	p += sizeof(o);				\
935 }
936 #define COPYIN(_code, _data, _len)	do {	\
937 	COPYIN1((_code), (_len));		\
938 	if ((_len) != 0) {			\
939 		memcpy(p, (_data), (_len));	\
940 		p += (_len);			\
941 	}					\
942 } while (0 /* CONSTCOND */)
943 #define NEXTLEN (p + offsetof(struct dhcp6_option, len))
944 
945 	/* Options are listed in numerical order as per RFC 7844 Section 4.1
946 	 * XXX: They should be randomised. */
947 
948 	p = (uint8_t *)state->send + sizeof(*state->send);
949 	if (ifo->options & DHCPCD_ANONYMOUS)
950 		COPYIN(D6_OPTION_CLIENTID, duid,
951 		    (uint16_t)duid_len);
952 	else
953 		COPYIN(D6_OPTION_CLIENTID, ifp->ctx->duid,
954 		    (uint16_t)ifp->ctx->duid_len);
955 
956 	if (si != NULL)
957 		COPYIN(D6_OPTION_SERVERID, si, si_len);
958 
959 	for (l = 0; IA && l < ifo->ia_len; l++) {
960 		ifia = &ifo->ia[l];
961 		o_lenp = NEXTLEN;
962 		/* TA structure is the same as the others,
963 		 * it just lacks the T1 and T2 timers.
964 		 * These happen to be at the end of the struct,
965 		 * so we just don't copy them in. */
966 		if (ifia->ia_type == D6_OPTION_IA_TA)
967 			ia_na_len = sizeof(struct dhcp6_ia_ta);
968 		else
969 			ia_na_len = sizeof(ia_na);
970 		memcpy(ia_na.iaid, ifia->iaid, sizeof(ia_na.iaid));
971 		/* RFC 8415 21.4 and 21.21 state that T1 and T2 should be zero.
972 		 * An RFC compliant server MUST ignore them anyway. */
973 		ia_na.t1 = 0;
974 		ia_na.t2 = 0;
975 		COPYIN(ifia->ia_type, &ia_na, ia_na_len);
976 		TAILQ_FOREACH(ap, &state->addrs, next) {
977 			if (ap->flags & IPV6_AF_STALE)
978 				continue;
979 			if (!(ap->flags & IPV6_AF_REQUEST) &&
980 			    (ap->prefix_vltime == 0 ||
981 			    state->state == DH6S_DISCOVER))
982 				continue;
983 			if (DECLINE_IA(ap) && state->state != DH6S_DECLINE)
984 				continue;
985 			if (ap->ia_type != ifia->ia_type)
986 				continue;
987 			if (memcmp(ap->iaid, ifia->iaid, sizeof(ap->iaid)))
988 				continue;
989 			if (ap->ia_type == D6_OPTION_IA_PD) {
990 #ifndef SMALL
991 				struct dhcp6_pd_addr pdp = {
992 				    .prefix_len = ap->prefix_len,
993 				    /*
994 				     * RFC 8415 21.22 states that the
995 				     * valid and preferred lifetimes sent by
996 				     * the client SHOULD be zero and MUST
997 				     * be ignored by the server.
998 				     */
999 				};
1000 
1001 				/* pdp.prefix is not aligned, so copy it in. */
1002 				memcpy(&pdp.prefix, &ap->prefix, sizeof(pdp.prefix));
1003 				COPYIN(D6_OPTION_IAPREFIX, &pdp, sizeof(pdp));
1004 				ia_na_len = (uint16_t)
1005 				    (ia_na_len + sizeof(o) + sizeof(pdp));
1006 
1007 				/* RFC6603 Section 4.2 */
1008 				if (ap->prefix_exclude_len) {
1009 					uint8_t exb[16], *ep, u8;
1010 					const uint8_t *pp;
1011 
1012 					n = (size_t)((ap->prefix_exclude_len -
1013 					    ap->prefix_len - 1) / NBBY) + 1;
1014 					ep = exb;
1015 					*ep++ = (uint8_t)ap->prefix_exclude_len;
1016 					pp = ap->prefix_exclude.s6_addr;
1017 					pp += (size_t)
1018 					    ((ap->prefix_len - 1) / NBBY) +
1019 					    (n - 1);
1020 					u8 = ap->prefix_len % NBBY;
1021 					if (u8)
1022 						n--;
1023 					while (n-- > 0)
1024 						*ep++ = *pp--;
1025 					if (u8)
1026 						*ep = (uint8_t)(*pp << u8);
1027 					n++;
1028 					COPYIN(D6_OPTION_PD_EXCLUDE, exb,
1029 					    (uint16_t)n);
1030 					ia_na_len = (uint16_t)
1031 					    (ia_na_len + sizeof(o) + n);
1032 				}
1033 #endif
1034 			} else {
1035 				struct dhcp6_ia_addr ia = {
1036 				    .addr = ap->addr,
1037 				    /*
1038 				     * RFC 8415 21.6 states that the
1039 				     * valid and preferred lifetimes sent by
1040 				     * the client SHOULD be zero and MUST
1041 				     * be ignored by the server.
1042 				     */
1043 				};
1044 
1045 				COPYIN(D6_OPTION_IA_ADDR, &ia, sizeof(ia));
1046 				ia_na_len = (uint16_t)
1047 				    (ia_na_len + sizeof(o) + sizeof(ia));
1048 			}
1049 		}
1050 
1051 		/* Update the total option lenth. */
1052 		ia_na_len = htons(ia_na_len);
1053 		memcpy(o_lenp, &ia_na_len, sizeof(ia_na_len));
1054 	}
1055 
1056 	if (state->send->type != DHCP6_RELEASE &&
1057 	    state->send->type != DHCP6_DECLINE &&
1058 	    n_options)
1059 	{
1060 		o_lenp = NEXTLEN;
1061 		o.len = 0;
1062 		COPYIN1(D6_OPTION_ORO, 0);
1063 		for (l = 0, opt = ifp->ctx->dhcp6_opts;
1064 		    l < ifp->ctx->dhcp6_opts_len;
1065 		    l++, opt++)
1066 		{
1067 #ifndef SMALL
1068 			for (n = 0, opt2 = ifo->dhcp6_override;
1069 			    n < ifo->dhcp6_override_len;
1070 			    n++, opt2++)
1071 			{
1072 				if (opt->option == opt2->option)
1073 					break;
1074 			}
1075 			if (n < ifo->dhcp6_override_len)
1076 			    continue;
1077 #endif
1078 			if (!DHC_REQOPT(opt, ifo->requestmask6, ifo->nomask6))
1079 				continue;
1080 			o.code = htons((uint16_t)opt->option);
1081 			memcpy(p, &o.code, sizeof(o.code));
1082 			p += sizeof(o.code);
1083 			o.len = (uint16_t)(o.len + sizeof(o.code));
1084 		}
1085 #ifndef SMALL
1086 		for (l = 0, opt = ifo->dhcp6_override;
1087 		    l < ifo->dhcp6_override_len;
1088 		    l++, opt++)
1089 		{
1090 			if (!DHC_REQOPT(opt, ifo->requestmask6, ifo->nomask6))
1091 				continue;
1092 			o.code = htons((uint16_t)opt->option);
1093 			memcpy(p, &o.code, sizeof(o.code));
1094 			p += sizeof(o.code);
1095 			o.len = (uint16_t)(o.len + sizeof(o.code));
1096 		}
1097 		if (dhcp6_findselfsla(ifp)) {
1098 			o.code = htons(D6_OPTION_PD_EXCLUDE);
1099 			memcpy(p, &o.code, sizeof(o.code));
1100 			p += sizeof(o.code);
1101 			o.len = (uint16_t)(o.len + sizeof(o.code));
1102 		}
1103 #endif
1104 		o.len = htons(o.len);
1105 		memcpy(o_lenp, &o.len, sizeof(o.len));
1106 	}
1107 
1108 	si_len = 0;
1109 	COPYIN(D6_OPTION_ELAPSED, &si_len, sizeof(si_len));
1110 
1111 	if (state->state == DH6S_DISCOVER &&
1112 	    !(ifp->ctx->options & DHCPCD_TEST) &&
1113 	    DHC_REQ(ifo->requestmask6, ifo->nomask6, D6_OPTION_RAPID_COMMIT))
1114 		COPYIN1(D6_OPTION_RAPID_COMMIT, 0);
1115 
1116 	if (!has_option_mask(ifo->nomask6, D6_OPTION_USER_CLASS))
1117 		p += dhcp6_makeuser(p, ifp);
1118 	if (!has_option_mask(ifo->nomask6, D6_OPTION_VENDOR_CLASS))
1119 		p += dhcp6_makevendor(p, ifp);
1120 
1121 	if (state->send->type != DHCP6_RELEASE &&
1122 	    state->send->type != DHCP6_DECLINE)
1123 	{
1124 		if (fqdn != FQDN_DISABLE) {
1125 			o_lenp = NEXTLEN;
1126 			COPYIN1(D6_OPTION_FQDN, 0);
1127 			if (hl == 0)
1128 				*p = D6_FQDN_NONE;
1129 			else {
1130 				switch (fqdn) {
1131 				case FQDN_BOTH:
1132 					*p = D6_FQDN_BOTH;
1133 					break;
1134 				case FQDN_PTR:
1135 					*p = D6_FQDN_PTR;
1136 					break;
1137 				default:
1138 					*p = D6_FQDN_NONE;
1139 					break;
1140 				}
1141 			}
1142 			p++;
1143 			encode_rfc1035(hostname, p);
1144 			p += hl;
1145 			o.len = htons((uint16_t)(hl + 1));
1146 			memcpy(o_lenp, &o.len, sizeof(o.len));
1147 		}
1148 
1149 		if (!has_option_mask(ifo->nomask6, D6_OPTION_MUDURL) &&
1150 		    ifo->mudurl[0])
1151 			COPYIN(D6_OPTION_MUDURL,
1152 			    ifo->mudurl + 1, ifo->mudurl[0]);
1153 
1154 #ifdef AUTH
1155 		if ((ifo->auth.options & DHCPCD_AUTH_SENDREQUIRE) !=
1156 		    DHCPCD_AUTH_SENDREQUIRE &&
1157 		    DHC_REQ(ifo->requestmask6, ifo->nomask6,
1158 		    D6_OPTION_RECONF_ACCEPT))
1159 			COPYIN1(D6_OPTION_RECONF_ACCEPT, 0);
1160 #endif
1161 
1162 	}
1163 
1164 #ifdef AUTH
1165 	/* This has to be the last option */
1166 	if (ifo->auth.options & DHCPCD_AUTH_SEND && auth_len != 0) {
1167 		COPYIN1(D6_OPTION_AUTH, auth_len);
1168 		/* data will be filled at send message time */
1169 	}
1170 #endif
1171 
1172 	return 0;
1173 }
1174 
1175 static const char *
1176 dhcp6_get_op(uint16_t type)
1177 {
1178 	const struct dhcp6_op *d;
1179 
1180 	for (d = dhcp6_ops; d->name; d++)
1181 		if (d->type == type)
1182 			return d->name;
1183 	return NULL;
1184 }
1185 
1186 static void
1187 dhcp6_freedrop_addrs(struct interface *ifp, int drop,
1188     const struct interface *ifd)
1189 {
1190 	struct dhcp6_state *state;
1191 
1192 	state = D6_STATE(ifp);
1193 	if (state) {
1194 		ipv6_freedrop_addrs(&state->addrs, drop, ifd);
1195 		if (drop)
1196 			rt_build(ifp->ctx, AF_INET6);
1197 	}
1198 }
1199 
1200 #ifndef SMALL
1201 static void dhcp6_delete_delegates(struct interface *ifp)
1202 {
1203 	struct interface *ifp0;
1204 
1205 	if (ifp->ctx->ifaces) {
1206 		TAILQ_FOREACH(ifp0, ifp->ctx->ifaces, next) {
1207 			if (ifp0 != ifp)
1208 				dhcp6_freedrop_addrs(ifp0, 1, ifp);
1209 		}
1210 	}
1211 }
1212 #endif
1213 
1214 #ifdef AUTH
1215 static ssize_t
1216 dhcp6_update_auth(struct interface *ifp, struct dhcp6_message *m, size_t len)
1217 {
1218 	struct dhcp6_state *state;
1219 	uint8_t *opt;
1220 	uint16_t opt_len;
1221 
1222 	opt = dhcp6_findmoption(m, len, D6_OPTION_AUTH, &opt_len);
1223 	if (opt == NULL)
1224 		return -1;
1225 
1226 	state = D6_STATE(ifp);
1227 	return dhcp_auth_encode(ifp->ctx, &ifp->options->auth,
1228 	    state->auth.token, (uint8_t *)state->send, state->send_len, 6,
1229 	    state->send->type, opt, opt_len);
1230 }
1231 #endif
1232 
1233 static const struct in6_addr alldhcp = IN6ADDR_LINKLOCAL_ALLDHCP_INIT;
1234 static int
1235 dhcp6_sendmessage(struct interface *ifp, void (*callback)(void *))
1236 {
1237 	struct dhcp6_state *state = D6_STATE(ifp);
1238 	struct dhcpcd_ctx *ctx = ifp->ctx;
1239 	unsigned int RT;
1240 	bool multicast = true;
1241 	struct sockaddr_in6 dst = {
1242 	    .sin6_family = AF_INET6,
1243 	    /* Setting the port on Linux gives EINVAL when sending.
1244 	     * This looks like a kernel bug as the equivalent works
1245 	     * fine with the DHCP counterpart. */
1246 #ifndef __linux__
1247 	    .sin6_port = htons(DHCP6_SERVER_PORT),
1248 #endif
1249 	};
1250 	struct udphdr udp = {
1251 	    .uh_sport = htons(DHCP6_CLIENT_PORT),
1252 	    .uh_dport = htons(DHCP6_SERVER_PORT),
1253 	    .uh_ulen = htons((uint16_t)(sizeof(udp) + state->send_len)),
1254 	};
1255 	struct iovec iov[] = {
1256 	    { .iov_base = &udp, .iov_len = sizeof(udp), },
1257 	    { .iov_base = state->send, .iov_len = state->send_len, },
1258 	};
1259 	union {
1260 		struct cmsghdr hdr;
1261 		uint8_t buf[CMSG_SPACE(sizeof(struct in6_pktinfo))];
1262 	} cmsgbuf = { .buf = { 0 } };
1263 	struct msghdr msg = {
1264 	    .msg_name = &dst, .msg_namelen = sizeof(dst),
1265 	    .msg_iov = iov, .msg_iovlen = __arraycount(iov),
1266 	};
1267 	char uaddr[INET6_ADDRSTRLEN];
1268 
1269 	if (!callback && !if_is_link_up(ifp))
1270 		return 0;
1271 
1272 	if (!IN6_IS_ADDR_UNSPECIFIED(&state->unicast)) {
1273 		switch (state->send->type) {
1274 		case DHCP6_SOLICIT:	/* FALLTHROUGH */
1275 		case DHCP6_CONFIRM:	/* FALLTHROUGH */
1276 		case DHCP6_REBIND:
1277 			/* Unicasting is denied for these types. */
1278 			break;
1279 		default:
1280 			multicast = false;
1281 			inet_ntop(AF_INET6, &state->unicast, uaddr,
1282 			    sizeof(uaddr));
1283 			break;
1284 		}
1285 	}
1286 	dst.sin6_addr = multicast ? alldhcp : state->unicast;
1287 
1288 	if (!callback) {
1289 		logdebugx("%s: %s %s with xid 0x%02x%02x%02x%s%s",
1290 		    ifp->name,
1291 		    multicast ? "multicasting" : "unicasting",
1292 		    dhcp6_get_op(state->send->type),
1293 		    state->send->xid[0],
1294 		    state->send->xid[1],
1295 		    state->send->xid[2],
1296 		    !multicast ? " " : "",
1297 		    !multicast ? uaddr : "");
1298 		RT = 0;
1299 	} else {
1300 		if (state->IMD &&
1301 		    !(ifp->options->options & DHCPCD_INITIAL_DELAY))
1302 			state->IMD = 0;
1303 		if (state->IMD) {
1304 			state->RT = state->IMD * MSEC_PER_SEC;
1305 			/* Some buggy PPP servers close the link too early
1306 			 * after sending an invalid status in their reply
1307 			 * which means this host won't see it.
1308 			 * 1 second grace seems to be the sweet spot. */
1309 			if (ifp->flags & IFF_POINTOPOINT)
1310 				state->RT += MSEC_PER_SEC;
1311 		} else if (state->RTC == 0)
1312 			state->RT = state->IRT * MSEC_PER_SEC;
1313 
1314 		if (state->MRT != 0) {
1315 			unsigned int mrt = state->MRT * MSEC_PER_SEC;
1316 
1317 			if (state->RT > mrt)
1318 				state->RT = mrt;
1319 		}
1320 
1321 		/* Add -.1 to .1 * RT randomness as per RFC8415 section 15 */
1322 		uint32_t lru = arc4random_uniform(
1323 		    state->RTC == 0 ? DHCP6_RAND_MAX
1324 		    : DHCP6_RAND_MAX - DHCP6_RAND_MIN);
1325 		int lr = (int)lru - (state->RTC == 0 ? 0 : DHCP6_RAND_MAX);
1326 		RT = state->RT
1327 		    + (unsigned int)((float)state->RT
1328 		    * ((float)lr / DHCP6_RAND_DIV));
1329 
1330 		if (if_is_link_up(ifp))
1331 			logdebugx("%s: %s %s (xid 0x%02x%02x%02x)%s%s,"
1332 			    " next in %0.1f seconds",
1333 			    ifp->name,
1334 			    state->IMD != 0 ? "delaying" :
1335 			    multicast ? "multicasting" : "unicasting",
1336 			    dhcp6_get_op(state->send->type),
1337 			    state->send->xid[0],
1338 			    state->send->xid[1],
1339 			    state->send->xid[2],
1340 			    state->IMD == 0 && !multicast ? " " : "",
1341 			    state->IMD == 0 && !multicast ? uaddr : "",
1342 			    (float)RT / MSEC_PER_SEC);
1343 
1344 		/* Wait the initial delay */
1345 		if (state->IMD != 0) {
1346 			state->IMD = 0;
1347 			eloop_timeout_add_msec(ctx->eloop, RT, callback, ifp);
1348 			return 0;
1349 		}
1350 	}
1351 
1352 	if (!if_is_link_up(ifp))
1353 		return 0;
1354 
1355 	/* Update the elapsed time */
1356 	dhcp6_updateelapsed(ifp, state->send, state->send_len);
1357 #ifdef AUTH
1358 	if (ifp->options->auth.options & DHCPCD_AUTH_SEND &&
1359 	    dhcp6_update_auth(ifp, state->send, state->send_len) == -1)
1360 	{
1361 		logerr("%s: %s: dhcp6_updateauth", __func__, ifp->name);
1362 		if (errno != ESRCH)
1363 			return -1;
1364 	}
1365 #endif
1366 
1367 	/* Set the outbound interface */
1368 	if (multicast) {
1369 		struct cmsghdr *cm;
1370 		struct in6_pktinfo pi = { .ipi6_ifindex = ifp->index };
1371 
1372 		dst.sin6_scope_id = ifp->index;
1373 		msg.msg_control = cmsgbuf.buf;
1374 		msg.msg_controllen = sizeof(cmsgbuf.buf);
1375 		cm = CMSG_FIRSTHDR(&msg);
1376 		if (cm == NULL) /* unlikely */
1377 			return -1;
1378 		cm->cmsg_level = IPPROTO_IPV6;
1379 		cm->cmsg_type = IPV6_PKTINFO;
1380 		cm->cmsg_len = CMSG_LEN(sizeof(pi));
1381 		memcpy(CMSG_DATA(cm), &pi, sizeof(pi));
1382 	}
1383 
1384 #ifdef PRIVSEP
1385 	if (IN_PRIVSEP(ifp->ctx)) {
1386 		if (ps_inet_senddhcp6(ifp, &msg) == -1)
1387 			logerr(__func__);
1388 		goto sent;
1389 	}
1390 #endif
1391 
1392 	if (sendmsg(ctx->dhcp6_wfd, &msg, 0) == -1) {
1393 		logerr("%s: %s: sendmsg", __func__, ifp->name);
1394 		/* Allow DHCPv6 to continue .... the errors
1395 		 * would be rate limited by the protocol.
1396 		 * Generally the error is ENOBUFS when struggling to
1397 		 * associate with an access point. */
1398 	}
1399 
1400 #ifdef PRIVSEP
1401 sent:
1402 #endif
1403 	state->RTC++;
1404 	if (callback) {
1405 		state->RT = RT * 2;
1406 		if (state->RT < RT) /* Check overflow */
1407 			state->RT = RT;
1408 		if (state->MRC == 0 || state->RTC < state->MRC)
1409 			eloop_timeout_add_msec(ctx->eloop,
1410 			    RT, callback, ifp);
1411 		else if (state->MRC != 0 && state->MRCcallback)
1412 			eloop_timeout_add_msec(ctx->eloop,
1413 			    RT, state->MRCcallback, ifp);
1414 		else
1415 			logwarnx("%s: sent %d times with no reply",
1416 			    ifp->name, state->RTC);
1417 	}
1418 	return 0;
1419 }
1420 
1421 static void
1422 dhcp6_sendinform(void *arg)
1423 {
1424 
1425 	dhcp6_sendmessage(arg, dhcp6_sendinform);
1426 }
1427 
1428 static void
1429 dhcp6_senddiscover(void *arg)
1430 {
1431 
1432 	dhcp6_sendmessage(arg, dhcp6_senddiscover);
1433 }
1434 
1435 static void
1436 dhcp6_sendrequest(void *arg)
1437 {
1438 
1439 	dhcp6_sendmessage(arg, dhcp6_sendrequest);
1440 }
1441 
1442 static void
1443 dhcp6_sendrebind(void *arg)
1444 {
1445 
1446 	dhcp6_sendmessage(arg, dhcp6_sendrebind);
1447 }
1448 
1449 static void
1450 dhcp6_sendrenew(void *arg)
1451 {
1452 
1453 	dhcp6_sendmessage(arg, dhcp6_sendrenew);
1454 }
1455 
1456 static void
1457 dhcp6_sendconfirm(void *arg)
1458 {
1459 
1460 	dhcp6_sendmessage(arg, dhcp6_sendconfirm);
1461 }
1462 
1463 static void
1464 dhcp6_senddecline(void *arg)
1465 {
1466 
1467 	dhcp6_sendmessage(arg, dhcp6_senddecline);
1468 }
1469 
1470 static void
1471 dhcp6_sendrelease(void *arg)
1472 {
1473 
1474 	dhcp6_sendmessage(arg, dhcp6_sendrelease);
1475 }
1476 
1477 static void
1478 dhcp6_startrenew(void *arg)
1479 {
1480 	struct interface *ifp;
1481 	struct dhcp6_state *state;
1482 
1483 	ifp = arg;
1484 	if ((state = D6_STATE(ifp)) == NULL)
1485 		return;
1486 
1487 	/* Only renew in the bound or renew states */
1488 	if (state->state != DH6S_BOUND &&
1489 	    state->state != DH6S_RENEW)
1490 		return;
1491 
1492 	/* Remove the timeout as the renew may have been forced. */
1493 	eloop_timeout_delete(ifp->ctx->eloop, dhcp6_startrenew, ifp);
1494 
1495 	state->state = DH6S_RENEW;
1496 	state->RTC = 0;
1497 	state->IMD = REN_MAX_DELAY;
1498 	state->IRT = REN_TIMEOUT;
1499 	state->MRT = REN_MAX_RT;
1500 	state->MRC = 0;
1501 
1502 	if (dhcp6_makemessage(ifp) == -1)
1503 		logerr("%s: %s", __func__, ifp->name);
1504 	else
1505 		dhcp6_sendrenew(ifp);
1506 }
1507 
1508 void dhcp6_renew(struct interface *ifp)
1509 {
1510 
1511 	dhcp6_startrenew(ifp);
1512 }
1513 
1514 bool
1515 dhcp6_dadcompleted(const struct interface *ifp)
1516 {
1517 	const struct dhcp6_state *state;
1518 	const struct ipv6_addr *ap;
1519 
1520 	state = D6_CSTATE(ifp);
1521 	TAILQ_FOREACH(ap, &state->addrs, next) {
1522 		if (ap->flags & IPV6_AF_ADDED &&
1523 		    !(ap->flags & IPV6_AF_DADCOMPLETED))
1524 			return false;
1525 	}
1526 	return true;
1527 }
1528 
1529 static void
1530 dhcp6_dadcallback(void *arg)
1531 {
1532 	struct ipv6_addr *ia = arg;
1533 	struct interface *ifp;
1534 	struct dhcp6_state *state;
1535 	struct ipv6_addr *ia2;
1536 	bool completed, valid, oneduplicated;
1537 
1538 	completed = (ia->flags & IPV6_AF_DADCOMPLETED);
1539 	ia->flags |= IPV6_AF_DADCOMPLETED;
1540 	if (ia->addr_flags & IN6_IFF_DUPLICATED)
1541 		logwarnx("%s: DAD detected %s", ia->iface->name, ia->saddr);
1542 
1543 #ifdef ND6_ADVERTISE
1544 	else
1545 		ipv6nd_advertise(ia);
1546 #endif
1547 	if (completed)
1548 		return;
1549 
1550 	ifp = ia->iface;
1551 	state = D6_STATE(ifp);
1552 	if (state->state != DH6S_BOUND && state->state != DH6S_DELEGATED)
1553 		return;
1554 
1555 #ifdef SMALL
1556 	valid = true;
1557 #else
1558 	valid = (ia->delegating_prefix == NULL);
1559 #endif
1560 	completed = true;
1561 	oneduplicated = false;
1562 	TAILQ_FOREACH(ia2, &state->addrs, next) {
1563 		if (ia2->flags & IPV6_AF_ADDED &&
1564 		    !(ia2->flags & IPV6_AF_DADCOMPLETED))
1565 		{
1566 			completed = false;
1567 			break;
1568 		}
1569 		if (DECLINE_IA(ia))
1570 			oneduplicated = true;
1571 	}
1572 	if (!completed)
1573 		return;
1574 
1575 	logdebugx("%s: DHCPv6 DAD completed", ifp->name);
1576 
1577 	if (oneduplicated && state->state == DH6S_BOUND) {
1578 		dhcp6_startdecline(ifp);
1579 		return;
1580 	}
1581 
1582 	script_runreason(ifp,
1583 #ifndef SMALL
1584 	    ia->delegating_prefix ? "DELEGATED6" :
1585 #endif
1586 	    state->reason);
1587 	if (valid)
1588 		dhcpcd_daemonise(ifp->ctx);
1589 }
1590 
1591 static void
1592 dhcp6_addrequestedaddrs(struct interface *ifp)
1593 {
1594 	struct dhcp6_state *state;
1595 	size_t i;
1596 	struct if_ia *ia;
1597 	struct ipv6_addr *a;
1598 
1599 	state = D6_STATE(ifp);
1600 	/* Add any requested prefixes / addresses */
1601 	for (i = 0; i < ifp->options->ia_len; i++) {
1602 		ia = &ifp->options->ia[i];
1603 		if (!((ia->ia_type == D6_OPTION_IA_PD && ia->prefix_len) ||
1604 		    !IN6_IS_ADDR_UNSPECIFIED(&ia->addr)))
1605 			continue;
1606 		a = ipv6_newaddr(ifp, &ia->addr,
1607 			/*
1608 			 * RFC 5942 Section 5
1609 			 * We cannot assume any prefix length, nor tie the
1610 			 * address to an existing one as it could expire
1611 			 * before the address.
1612 			 * As such we just give it a 128 prefix.
1613 			 */
1614 		    ia->ia_type == D6_OPTION_IA_PD ? ia->prefix_len : 128,
1615 		    IPV6_AF_REQUEST);
1616 		if (a == NULL)
1617 			continue;
1618 		a->dadcallback = dhcp6_dadcallback;
1619 		memcpy(&a->iaid, &ia->iaid, sizeof(a->iaid));
1620 		a->ia_type = ia->ia_type;
1621 		TAILQ_INSERT_TAIL(&state->addrs, a, next);
1622 	}
1623 }
1624 
1625 static void
1626 dhcp6_startdiscover(void *arg)
1627 {
1628 	struct interface *ifp;
1629 	struct dhcp6_state *state;
1630 	int llevel;
1631 
1632 	ifp = arg;
1633 	state = D6_STATE(ifp);
1634 #ifndef SMALL
1635 	if (state->reason == NULL || strcmp(state->reason, "TIMEOUT6") != 0)
1636 		dhcp6_delete_delegates(ifp);
1637 #endif
1638 	if (state->new == NULL && !state->failed)
1639 		llevel = LOG_INFO;
1640 	else
1641 		llevel = LOG_DEBUG;
1642 	logmessage(llevel, "%s: soliciting a DHCPv6 lease", ifp->name);
1643 	state->state = DH6S_DISCOVER;
1644 	state->RTC = 0;
1645 	state->IMD = SOL_MAX_DELAY;
1646 	state->IRT = SOL_TIMEOUT;
1647 	state->MRT = state->sol_max_rt;
1648 	state->MRC = SOL_MAX_RC;
1649 
1650 	eloop_timeout_delete(ifp->ctx->eloop, NULL, ifp);
1651 	free(state->new);
1652 	state->new = NULL;
1653 	state->new_len = 0;
1654 
1655 	if (dhcp6_makemessage(ifp) == -1)
1656 		logerr("%s: %s", __func__, ifp->name);
1657 	else
1658 		dhcp6_senddiscover(ifp);
1659 }
1660 
1661 static void
1662 dhcp6_startinform(void *arg)
1663 {
1664 	struct interface *ifp;
1665 	struct dhcp6_state *state;
1666 	int llevel;
1667 
1668 	ifp = arg;
1669 	state = D6_STATE(ifp);
1670 	if (state->new_start || (state->new == NULL && !state->failed))
1671 		llevel = LOG_INFO;
1672 	else
1673 		llevel = LOG_DEBUG;
1674 	logmessage(llevel, "%s: requesting DHCPv6 information", ifp->name);
1675 	state->state = DH6S_INFORM;
1676 	state->RTC = 0;
1677 	state->IMD = INF_MAX_DELAY;
1678 	state->IRT = INF_TIMEOUT;
1679 	state->MRT = state->inf_max_rt;
1680 	state->MRC = 0;
1681 
1682 	eloop_timeout_delete(ifp->ctx->eloop, NULL, ifp);
1683 	if (dhcp6_makemessage(ifp) == -1) {
1684 		logerr("%s: %s", __func__, ifp->name);
1685 		return;
1686 	}
1687 	dhcp6_sendinform(ifp);
1688 	/* RFC3315 18.1.2 says that if CONFIRM failed then the prior addresses
1689 	 * SHOULD be used. The wording here is poor, because the addresses are
1690 	 * merely one facet of the lease as a whole.
1691 	 * This poor wording might explain the lack of similar text for INFORM
1692 	 * in 18.1.5 because there are no addresses in the INFORM message. */
1693 	eloop_timeout_add_sec(ifp->ctx->eloop,
1694 	    INF_MAX_RD, dhcp6_failinform, ifp);
1695 }
1696 
1697 static bool
1698 dhcp6_startdiscoinform(struct interface *ifp)
1699 {
1700 	unsigned long long opts = ifp->options->options;
1701 
1702 	if (opts & DHCPCD_IA_FORCED || ipv6nd_hasradhcp(ifp, true))
1703 		dhcp6_startdiscover(ifp);
1704 	else if (opts & DHCPCD_INFORM6 || ipv6nd_hasradhcp(ifp, false))
1705 		dhcp6_startinform(ifp);
1706 	else
1707 		return false;
1708 	return true;
1709 }
1710 
1711 static void
1712 dhcp6_leaseextend(struct interface *ifp)
1713 {
1714 	struct dhcp6_state *state = D6_STATE(ifp);
1715 	struct ipv6_addr *ia;
1716 
1717 	logwarnx("%s: extending DHCPv6 lease", ifp->name);
1718 	TAILQ_FOREACH(ia, &state->addrs, next) {
1719 		ia->flags |= IPV6_AF_EXTENDED;
1720 		/* Set infinite lifetimes. */
1721 		ia->prefix_pltime = ND6_INFINITE_LIFETIME;
1722 		ia->prefix_vltime = ND6_INFINITE_LIFETIME;
1723 	}
1724 }
1725 
1726 static void
1727 dhcp6_fail(struct interface *ifp)
1728 {
1729 	struct dhcp6_state *state = D6_STATE(ifp);
1730 
1731 	state->failed = true;
1732 
1733 	/* RFC3315 18.1.2 says that prior addresses SHOULD be used on failure.
1734 	 * RFC2131 3.2.3 says that MAY chose to use the prior address.
1735 	 * Because dhcpcd was written first for RFC2131, we have the LASTLEASE
1736 	 * option which defaults to off as that makes the most sense for
1737 	 * mobile clients.
1738 	 * dhcpcd also has LASTLEASE_EXTEND to extend this lease past it's
1739 	 * expiry, but this is strictly not RFC compliant in any way or form. */
1740 	if (state->new != NULL &&
1741 	    ifp->options->options & DHCPCD_LASTLEASE_EXTEND)
1742 	{
1743 		dhcp6_leaseextend(ifp);
1744 		dhcp6_bind(ifp, NULL, NULL);
1745 	} else {
1746 		dhcp6_freedrop_addrs(ifp, 1, NULL);
1747 #ifndef SMALL
1748 		dhcp6_delete_delegates(ifp);
1749 #endif
1750 		free(state->old);
1751 		state->old = state->new;
1752 		state->old_len = state->new_len;
1753 		state->new = NULL;
1754 		state->new_len = 0;
1755 		if (state->old != NULL)
1756 			script_runreason(ifp, "EXPIRE6");
1757 		dhcp_unlink(ifp->ctx, state->leasefile);
1758 		dhcp6_addrequestedaddrs(ifp);
1759 	}
1760 
1761 	if (!dhcp6_startdiscoinform(ifp)) {
1762 		logwarnx("%s: no advertising IPv6 router wants DHCP",ifp->name);
1763 		state->state = DH6S_INIT;
1764 		eloop_timeout_delete(ifp->ctx->eloop, NULL, ifp);
1765 	}
1766 }
1767 
1768 static int
1769 dhcp6_failloglevel(struct interface *ifp)
1770 {
1771 	const struct dhcp6_state *state = D6_CSTATE(ifp);
1772 
1773 	return state->failed ? LOG_DEBUG : LOG_ERR;
1774 }
1775 
1776 static void
1777 dhcp6_failconfirm(void *arg)
1778 {
1779 	struct interface *ifp = arg;
1780 	int llevel = dhcp6_failloglevel(ifp);
1781 
1782 	logmessage(llevel, "%s: failed to confirm prior DHCPv6 address",
1783 	    ifp->name);
1784 	dhcp6_fail(ifp);
1785 }
1786 
1787 static void
1788 dhcp6_failrequest(void *arg)
1789 {
1790 	struct interface *ifp = arg;
1791 	int llevel = dhcp6_failloglevel(ifp);
1792 
1793 	logmessage(llevel, "%s: failed to request DHCPv6 address", ifp->name);
1794 	dhcp6_fail(ifp);
1795 }
1796 
1797 static void
1798 dhcp6_failinform(void *arg)
1799 {
1800 	struct interface *ifp = arg;
1801 	int llevel = dhcp6_failloglevel(ifp);
1802 
1803 	logmessage(llevel, "%s: failed to request DHCPv6 information",
1804 	    ifp->name);
1805 	dhcp6_fail(ifp);
1806 }
1807 
1808 #ifndef SMALL
1809 static void
1810 dhcp6_failrebind(void *arg)
1811 {
1812 	struct interface *ifp = arg;
1813 
1814 	logerrx("%s: failed to rebind prior DHCPv6 delegation", ifp->name);
1815 	dhcp6_fail(ifp);
1816 }
1817 
1818 static int
1819 dhcp6_hasprefixdelegation(struct interface *ifp)
1820 {
1821 	size_t i;
1822 	uint16_t t;
1823 
1824 	t = 0;
1825 	for (i = 0; i < ifp->options->ia_len; i++) {
1826 		if (t && t != ifp->options->ia[i].ia_type) {
1827 			if (t == D6_OPTION_IA_PD ||
1828 			    ifp->options->ia[i].ia_type == D6_OPTION_IA_PD)
1829 				return 2;
1830 		}
1831 		t = ifp->options->ia[i].ia_type;
1832 	}
1833 	return t == D6_OPTION_IA_PD ? 1 : 0;
1834 }
1835 #endif
1836 
1837 static void
1838 dhcp6_startrebind(void *arg)
1839 {
1840 	struct interface *ifp;
1841 	struct dhcp6_state *state;
1842 #ifndef SMALL
1843 	int pd;
1844 #endif
1845 
1846 	ifp = arg;
1847 	eloop_timeout_delete(ifp->ctx->eloop, dhcp6_sendrenew, ifp);
1848 	state = D6_STATE(ifp);
1849 	if (state->state == DH6S_RENEW)
1850 		logwarnx("%s: failed to renew DHCPv6, rebinding", ifp->name);
1851 	else
1852 		loginfox("%s: rebinding prior DHCPv6 lease", ifp->name);
1853 	state->state = DH6S_REBIND;
1854 	state->RTC = 0;
1855 	state->MRC = 0;
1856 
1857 #ifndef SMALL
1858 	/* RFC 3633 section 12.1 */
1859 	pd = dhcp6_hasprefixdelegation(ifp);
1860 	if (pd) {
1861 		state->IMD = CNF_MAX_DELAY;
1862 		state->IRT = CNF_TIMEOUT;
1863 		state->MRT = CNF_MAX_RT;
1864 	} else
1865 #endif
1866 	{
1867 		state->IMD = REB_MAX_DELAY;
1868 		state->IRT = REB_TIMEOUT;
1869 		state->MRT = REB_MAX_RT;
1870 	}
1871 
1872 	if (dhcp6_makemessage(ifp) == -1)
1873 		logerr("%s: %s", __func__, ifp->name);
1874 	else
1875 		dhcp6_sendrebind(ifp);
1876 
1877 #ifndef SMALL
1878 	/* RFC 3633 section 12.1 */
1879 	if (pd)
1880 		eloop_timeout_add_sec(ifp->ctx->eloop,
1881 		    CNF_MAX_RD, dhcp6_failrebind, ifp);
1882 #endif
1883 }
1884 
1885 
1886 static void
1887 dhcp6_startrequest(struct interface *ifp)
1888 {
1889 	struct dhcp6_state *state;
1890 
1891 	eloop_timeout_delete(ifp->ctx->eloop, dhcp6_senddiscover, ifp);
1892 	state = D6_STATE(ifp);
1893 	state->state = DH6S_REQUEST;
1894 	state->RTC = 0;
1895 	state->IMD = 0;
1896 	state->IRT = REQ_TIMEOUT;
1897 	state->MRT = REQ_MAX_RT;
1898 	state->MRC = REQ_MAX_RC;
1899 	state->MRCcallback = dhcp6_failrequest;
1900 
1901 	if (dhcp6_makemessage(ifp) == -1) {
1902 		logerr("%s: %s", __func__, ifp->name);
1903 		return;
1904 	}
1905 
1906 	dhcp6_sendrequest(ifp);
1907 }
1908 
1909 static void
1910 dhcp6_startconfirm(struct interface *ifp)
1911 {
1912 	struct dhcp6_state *state;
1913 	struct ipv6_addr *ia;
1914 
1915 	state = D6_STATE(ifp);
1916 
1917 	TAILQ_FOREACH(ia, &state->addrs, next) {
1918 		if (!DECLINE_IA(ia))
1919 			continue;
1920 		logerrx("%s: prior DHCPv6 has a duplicated address", ifp->name);
1921 		dhcp6_startdecline(ifp);
1922 		return;
1923 	}
1924 
1925 	state->state = DH6S_CONFIRM;
1926 	state->RTC = 0;
1927 	state->IMD = CNF_MAX_DELAY;
1928 	state->IRT = CNF_TIMEOUT;
1929 	state->MRT = CNF_MAX_RT;
1930 	state->MRC = CNF_MAX_RC;
1931 
1932 	loginfox("%s: confirming prior DHCPv6 lease", ifp->name);
1933 
1934 	if (dhcp6_makemessage(ifp) == -1) {
1935 		logerr("%s: %s", __func__, ifp->name);
1936 		return;
1937 	}
1938 	dhcp6_sendconfirm(ifp);
1939 	eloop_timeout_add_sec(ifp->ctx->eloop,
1940 	    CNF_MAX_RD, dhcp6_failconfirm, ifp);
1941 }
1942 
1943 static void
1944 dhcp6_startexpire(void *arg)
1945 {
1946 	struct interface *ifp;
1947 
1948 	ifp = arg;
1949 	eloop_timeout_delete(ifp->ctx->eloop, dhcp6_sendrebind, ifp);
1950 
1951 	logerrx("%s: DHCPv6 lease expired", ifp->name);
1952 	dhcp6_fail(ifp);
1953 }
1954 
1955 static void
1956 dhcp6_faildecline(void *arg)
1957 {
1958 	struct interface *ifp = arg;
1959 
1960 	logerrx("%s: failed to decline duplicated DHCPv6 addresses", ifp->name);
1961 	dhcp6_fail(ifp);
1962 }
1963 
1964 static void
1965 dhcp6_startdecline(struct interface *ifp)
1966 {
1967 	struct dhcp6_state *state;
1968 
1969 	state = D6_STATE(ifp);
1970 	loginfox("%s: declining failed DHCPv6 addresses", ifp->name);
1971 	state->state = DH6S_DECLINE;
1972 	state->RTC = 0;
1973 	state->IMD = 0;
1974 	state->IRT = DEC_TIMEOUT;
1975 	state->MRT = 0;
1976 	state->MRC = DEC_MAX_RC;
1977 	state->MRCcallback = dhcp6_faildecline;
1978 
1979 	if (dhcp6_makemessage(ifp) == -1)
1980 		logerr("%s: %s", __func__, ifp->name);
1981 	else
1982 		dhcp6_senddecline(ifp);
1983 }
1984 
1985 static void
1986 dhcp6_finishrelease(void *arg)
1987 {
1988 	struct interface *ifp;
1989 	struct dhcp6_state *state;
1990 
1991 	ifp = (struct interface *)arg;
1992 	if ((state = D6_STATE(ifp)) != NULL) {
1993 		state->state = DH6S_RELEASED;
1994 		dhcp6_drop(ifp, "RELEASE6");
1995 	}
1996 }
1997 
1998 static void
1999 dhcp6_startrelease(struct interface *ifp)
2000 {
2001 	struct dhcp6_state *state;
2002 
2003 	state = D6_STATE(ifp);
2004 	if (state->state != DH6S_BOUND)
2005 		return;
2006 
2007 	state->state = DH6S_RELEASE;
2008 	state->RTC = 0;
2009 	state->IMD = REL_MAX_DELAY;
2010 	state->IRT = REL_TIMEOUT;
2011 	state->MRT = REL_MAX_RT;
2012 	/* MRC of REL_MAX_RC is optional in RFC 3315 18.1.6 */
2013 #if 0
2014 	state->MRC = REL_MAX_RC;
2015 	state->MRCcallback = dhcp6_finishrelease;
2016 #else
2017 	state->MRC = 0;
2018 	state->MRCcallback = NULL;
2019 #endif
2020 
2021 	if (dhcp6_makemessage(ifp) == -1)
2022 		logerr("%s: %s", __func__, ifp->name);
2023 	else {
2024 		dhcp6_sendrelease(ifp);
2025 		dhcp6_finishrelease(ifp);
2026 	}
2027 }
2028 
2029 static int
2030 dhcp6_checkstatusok(const struct interface *ifp,
2031     struct dhcp6_message *m, uint8_t *p, size_t len)
2032 {
2033 	struct dhcp6_state *state;
2034 	uint8_t *opt;
2035 	uint16_t opt_len, code;
2036 	size_t mlen;
2037 	void * (*f)(void *, size_t, uint16_t, uint16_t *), *farg;
2038 	char buf[32], *sbuf;
2039 	const char *status;
2040 	int loglevel;
2041 
2042 	state = D6_STATE(ifp);
2043 	f = p ? dhcp6_findoption : dhcp6_findmoption;
2044 	if (p)
2045 		farg = p;
2046 	else
2047 		farg = m;
2048 	if ((opt = f(farg, len, D6_OPTION_STATUS_CODE, &opt_len)) == NULL) {
2049 		//logdebugx("%s: no status", ifp->name);
2050 		state->lerror = 0;
2051 		errno = ESRCH;
2052 		return 0;
2053 	}
2054 
2055 	if (opt_len < sizeof(code)) {
2056 		logerrx("%s: status truncated", ifp->name);
2057 		return -1;
2058 	}
2059 	memcpy(&code, opt, sizeof(code));
2060 	code = ntohs(code);
2061 	if (code == D6_STATUS_OK) {
2062 		state->lerror = 0;
2063 		errno = 0;
2064 		return 0;
2065 	}
2066 
2067 	/* Anything after the code is a message. */
2068 	opt += sizeof(code);
2069 	mlen = opt_len - sizeof(code);
2070 	if (mlen == 0) {
2071 		sbuf = NULL;
2072 		if (code < sizeof(dhcp6_statuses) / sizeof(char *))
2073 			status = dhcp6_statuses[code];
2074 		else {
2075 			snprintf(buf, sizeof(buf), "Unknown Status (%d)", code);
2076 			status = buf;
2077 		}
2078 	} else {
2079 		if ((sbuf = malloc(mlen + 1)) == NULL) {
2080 			logerr(__func__);
2081 			return -1;
2082 		}
2083 		memcpy(sbuf, opt, mlen);
2084 		sbuf[mlen] = '\0';
2085 		status = sbuf;
2086 	}
2087 
2088 	if (state->lerror == code || state->state == DH6S_INIT)
2089 		loglevel = LOG_DEBUG;
2090 	else
2091 		loglevel = LOG_ERR;
2092 	logmessage(loglevel, "%s: DHCPv6 REPLY: %s", ifp->name, status);
2093 	free(sbuf);
2094 	state->lerror = code;
2095 	errno = 0;
2096 
2097 	/* code cannot be D6_STATUS_OK, so there is a failure */
2098 	if (ifp->ctx->options & DHCPCD_TEST)
2099 		eloop_exit(ifp->ctx->eloop, EXIT_FAILURE);
2100 
2101 	return (int)code;
2102 }
2103 
2104 const struct ipv6_addr *
2105 dhcp6_iffindaddr(const struct interface *ifp, const struct in6_addr *addr,
2106     unsigned int flags)
2107 {
2108 	const struct dhcp6_state *state;
2109 	const struct ipv6_addr *ap;
2110 
2111 	if ((state = D6_STATE(ifp)) != NULL) {
2112 		TAILQ_FOREACH(ap, &state->addrs, next) {
2113 			if (ipv6_findaddrmatch(ap, addr, flags))
2114 				return ap;
2115 		}
2116 	}
2117 	return NULL;
2118 }
2119 
2120 struct ipv6_addr *
2121 dhcp6_findaddr(struct dhcpcd_ctx *ctx, const struct in6_addr *addr,
2122     unsigned int flags)
2123 {
2124 	struct interface *ifp;
2125 	struct ipv6_addr *ap;
2126 	struct dhcp6_state *state;
2127 
2128 	TAILQ_FOREACH(ifp, ctx->ifaces, next) {
2129 		if ((state = D6_STATE(ifp)) != NULL) {
2130 			TAILQ_FOREACH(ap, &state->addrs, next) {
2131 				if (ipv6_findaddrmatch(ap, addr, flags))
2132 					return ap;
2133 			}
2134 		}
2135 	}
2136 	return NULL;
2137 }
2138 
2139 static int
2140 dhcp6_findna(struct interface *ifp, uint16_t ot, const uint8_t *iaid,
2141     uint8_t *d, size_t l, const struct timespec *acquired)
2142 {
2143 	struct dhcp6_state *state;
2144 	uint8_t *o, *nd;
2145 	uint16_t ol;
2146 	struct ipv6_addr *a;
2147 	int i;
2148 	struct dhcp6_ia_addr ia;
2149 
2150 	i = 0;
2151 	state = D6_STATE(ifp);
2152 	while ((o = dhcp6_findoption(d, l, D6_OPTION_IA_ADDR, &ol))) {
2153 		/* Set d and l first to ensure we find the next option. */
2154 		nd = o + ol;
2155 		l -= (size_t)(nd - d);
2156 		d = nd;
2157 		if (ol < sizeof(ia)) {
2158 			errno = EINVAL;
2159 			logerrx("%s: IA Address option truncated", ifp->name);
2160 			continue;
2161 		}
2162 		memcpy(&ia, o, sizeof(ia));
2163 		ia.pltime = ntohl(ia.pltime);
2164 		ia.vltime = ntohl(ia.vltime);
2165 		/* RFC 3315 22.6 */
2166 		if (ia.pltime > ia.vltime) {
2167 			errno = EINVAL;
2168 			logerr("%s: IA Address pltime %"PRIu32
2169 			    " > vltime %"PRIu32,
2170 			    ifp->name, ia.pltime, ia.vltime);
2171 			continue;
2172 		}
2173 		TAILQ_FOREACH(a, &state->addrs, next) {
2174 			if (ipv6_findaddrmatch(a, &ia.addr, 0))
2175 				break;
2176 		}
2177 		if (a == NULL) {
2178 			/*
2179 			 * RFC 5942 Section 5
2180 			 * We cannot assume any prefix length, nor tie the
2181 			 * address to an existing one as it could expire
2182 			 * before the address.
2183 			 * As such we just give it a 128 prefix.
2184 			 */
2185 			a = ipv6_newaddr(ifp, &ia.addr, 128, IPV6_AF_ONLINK);
2186 			a->dadcallback = dhcp6_dadcallback;
2187 			a->ia_type = ot;
2188 			memcpy(a->iaid, iaid, sizeof(a->iaid));
2189 			a->created = *acquired;
2190 
2191 			TAILQ_INSERT_TAIL(&state->addrs, a, next);
2192 		} else {
2193 			if (!(a->flags & IPV6_AF_ONLINK))
2194 				a->flags |= IPV6_AF_ONLINK | IPV6_AF_NEW;
2195 			a->flags &= ~(IPV6_AF_STALE | IPV6_AF_EXTENDED);
2196 		}
2197 		a->acquired = *acquired;
2198 		a->prefix_pltime = ia.pltime;
2199 		if (a->prefix_vltime != ia.vltime) {
2200 			a->flags |= IPV6_AF_NEW;
2201 			a->prefix_vltime = ia.vltime;
2202 		}
2203 		if (a->prefix_pltime && a->prefix_pltime < state->lowpl)
2204 		    state->lowpl = a->prefix_pltime;
2205 		if (a->prefix_vltime && a->prefix_vltime > state->expire)
2206 		    state->expire = a->prefix_vltime;
2207 		i++;
2208 	}
2209 	return i;
2210 }
2211 
2212 #ifndef SMALL
2213 static int
2214 dhcp6_findpd(struct interface *ifp, const uint8_t *iaid,
2215     uint8_t *d, size_t l, const struct timespec *acquired)
2216 {
2217 	struct dhcp6_state *state;
2218 	uint8_t *o, *nd;
2219 	struct ipv6_addr *a;
2220 	int i;
2221 	uint8_t nb, *pw;
2222 	uint16_t ol;
2223 	struct dhcp6_pd_addr pdp;
2224 	struct in6_addr pdp_prefix;
2225 
2226 	i = 0;
2227 	state = D6_STATE(ifp);
2228 	while ((o = dhcp6_findoption(d, l, D6_OPTION_IAPREFIX, &ol))) {
2229 		/* Set d and l first to ensure we find the next option. */
2230 		nd = o + ol;
2231 		l -= (size_t)(nd - d);
2232 		d = nd;
2233 		if (ol < sizeof(pdp)) {
2234 			errno = EINVAL;
2235 			logerrx("%s: IA Prefix option truncated", ifp->name);
2236 			continue;
2237 		}
2238 
2239 		memcpy(&pdp, o, sizeof(pdp));
2240 		pdp.pltime = ntohl(pdp.pltime);
2241 		pdp.vltime = ntohl(pdp.vltime);
2242 		/* RFC 3315 22.6 */
2243 		if (pdp.pltime > pdp.vltime) {
2244 			errno = EINVAL;
2245 			logerrx("%s: IA Prefix pltime %"PRIu32
2246 			    " > vltime %"PRIu32,
2247 			    ifp->name, pdp.pltime, pdp.vltime);
2248 			continue;
2249 		}
2250 
2251 		o += sizeof(pdp);
2252 		ol = (uint16_t)(ol - sizeof(pdp));
2253 
2254 		/* pdp.prefix is not aligned so copy it out. */
2255 		memcpy(&pdp_prefix, &pdp.prefix, sizeof(pdp_prefix));
2256 		TAILQ_FOREACH(a, &state->addrs, next) {
2257 			if (IN6_ARE_ADDR_EQUAL(&a->prefix, &pdp_prefix))
2258 				break;
2259 		}
2260 
2261 		if (a == NULL) {
2262 			a = ipv6_newaddr(ifp, &pdp_prefix, pdp.prefix_len,
2263 			    IPV6_AF_DELEGATEDPFX);
2264 			if (a == NULL)
2265 				break;
2266 			a->created = *acquired;
2267 			a->dadcallback = dhcp6_dadcallback;
2268 			a->ia_type = D6_OPTION_IA_PD;
2269 			memcpy(a->iaid, iaid, sizeof(a->iaid));
2270 			TAILQ_INSERT_TAIL(&state->addrs, a, next);
2271 		} else {
2272 			if (!(a->flags & IPV6_AF_DELEGATEDPFX))
2273 				a->flags |= IPV6_AF_NEW | IPV6_AF_DELEGATEDPFX;
2274 			a->flags &= ~(IPV6_AF_STALE |
2275 				      IPV6_AF_EXTENDED |
2276 				      IPV6_AF_REQUEST);
2277 			if (a->prefix_vltime != pdp.vltime)
2278 				a->flags |= IPV6_AF_NEW;
2279 		}
2280 
2281 		a->acquired = *acquired;
2282 		a->prefix_pltime = pdp.pltime;
2283 		a->prefix_vltime = pdp.vltime;
2284 
2285 		if (a->prefix_pltime && a->prefix_pltime < state->lowpl)
2286 			state->lowpl = a->prefix_pltime;
2287 		if (a->prefix_vltime && a->prefix_vltime > state->expire)
2288 			state->expire = a->prefix_vltime;
2289 		i++;
2290 
2291 		a->prefix_exclude_len = 0;
2292 		memset(&a->prefix_exclude, 0, sizeof(a->prefix_exclude));
2293 		o = dhcp6_findoption(o, ol, D6_OPTION_PD_EXCLUDE, &ol);
2294 		if (o == NULL)
2295 			continue;
2296 
2297 		/* RFC 6603 4.2 says option length MUST be between 2 and 17.
2298 		 * This allows 1 octet for prefix length and 16 for the
2299 		 * subnet ID. */
2300 		if (ol < 2 || ol > 17) {
2301 			logerrx("%s: invalid PD Exclude option", ifp->name);
2302 			continue;
2303 		}
2304 
2305 		/* RFC 6603 4.2 says prefix length MUST be between the
2306 		 * length of the IAPREFIX prefix length + 1 and 128. */
2307 		if (*o < a->prefix_len + 1 || *o > 128) {
2308 			logerrx("%s: invalid PD Exclude length", ifp->name);
2309 			continue;
2310 		}
2311 
2312 		ol--;
2313 		/* Check option length matches prefix length. */
2314 		if (((*o - a->prefix_len - 1) / NBBY) + 1 != ol) {
2315 			logerrx("%s: PD Exclude length mismatch", ifp->name);
2316 			continue;
2317 		}
2318 		a->prefix_exclude_len = *o++;
2319 
2320 		memcpy(&a->prefix_exclude, &a->prefix,
2321 		    sizeof(a->prefix_exclude));
2322 		nb = a->prefix_len % NBBY;
2323 		if (nb)
2324 			ol--;
2325 		pw = a->prefix_exclude.s6_addr +
2326 		    (a->prefix_exclude_len / NBBY) - 1;
2327 		while (ol-- > 0)
2328 			*pw-- = *o++;
2329 		if (nb)
2330 			*pw = (uint8_t)(*pw | (*o >> nb));
2331 	}
2332 	return i;
2333 }
2334 #endif
2335 
2336 static int
2337 dhcp6_findia(struct interface *ifp, struct dhcp6_message *m, size_t l,
2338     const char *sfrom, const struct timespec *acquired)
2339 {
2340 	struct dhcp6_state *state;
2341 	const struct if_options *ifo;
2342 	struct dhcp6_option o;
2343 	uint8_t *d, *p;
2344 	struct dhcp6_ia_na ia;
2345 	int i, e, error;
2346 	size_t j;
2347 	uint16_t nl;
2348 	uint8_t iaid[4];
2349 	char buf[sizeof(iaid) * 3];
2350 	struct ipv6_addr *ap;
2351 	struct if_ia *ifia;
2352 
2353 	if (l < sizeof(*m)) {
2354 		/* Should be impossible with guards at packet in
2355 		 * and reading leases */
2356 		errno = EINVAL;
2357 		return -1;
2358 	}
2359 
2360 	ifo = ifp->options;
2361 	i = e = 0;
2362 	state = D6_STATE(ifp);
2363 	TAILQ_FOREACH(ap, &state->addrs, next) {
2364 		if (!(ap->flags & IPV6_AF_DELEGATED))
2365 			ap->flags |= IPV6_AF_STALE;
2366 	}
2367 
2368 	d = (uint8_t *)m + sizeof(*m);
2369 	l -= sizeof(*m);
2370 	while (l > sizeof(o)) {
2371 		memcpy(&o, d, sizeof(o));
2372 		o.len = ntohs(o.len);
2373 		if (o.len > l || sizeof(o) + o.len > l) {
2374 			errno = EINVAL;
2375 			logerrx("%s: option overflow", ifp->name);
2376 			break;
2377 		}
2378 		p = d + sizeof(o);
2379 		d = p + o.len;
2380 		l -= sizeof(o) + o.len;
2381 
2382 		o.code = ntohs(o.code);
2383 		switch(o.code) {
2384 		case D6_OPTION_IA_TA:
2385 			nl = 4;
2386 			break;
2387 		case D6_OPTION_IA_NA:
2388 		case D6_OPTION_IA_PD:
2389 			nl = 12;
2390 			break;
2391 		default:
2392 			continue;
2393 		}
2394 		if (o.len < nl) {
2395 			errno = EINVAL;
2396 			logerrx("%s: IA option truncated", ifp->name);
2397 			continue;
2398 		}
2399 
2400 		memcpy(&ia, p, nl);
2401 		p += nl;
2402 		o.len = (uint16_t)(o.len - nl);
2403 
2404 		for (j = 0; j < ifo->ia_len; j++) {
2405 			ifia = &ifo->ia[j];
2406 			if (ifia->ia_type == o.code &&
2407 			    memcmp(ifia->iaid, ia.iaid, sizeof(ia.iaid)) == 0)
2408 				break;
2409 		}
2410 		if (j == ifo->ia_len &&
2411 		    !(ifo->ia_len == 0 && ifp->ctx->options & DHCPCD_DUMPLEASE))
2412 		{
2413 			logdebugx("%s: ignoring unrequested IAID %s",
2414 			    ifp->name,
2415 			    hwaddr_ntoa(ia.iaid, sizeof(ia.iaid),
2416 			    buf, sizeof(buf)));
2417 			continue;
2418 		}
2419 
2420 		if (o.code != D6_OPTION_IA_TA) {
2421 			ia.t1 = ntohl(ia.t1);
2422 			ia.t2 = ntohl(ia.t2);
2423 			/* RFC 3315 22.4 */
2424 			if (ia.t2 > 0 && ia.t1 > ia.t2) {
2425 				logwarnx("%s: IAID %s T1(%d) > T2(%d) from %s",
2426 				    ifp->name,
2427 				    hwaddr_ntoa(iaid, sizeof(iaid), buf,
2428 						sizeof(buf)),
2429 				    ia.t1, ia.t2, sfrom);
2430 				continue;
2431 			}
2432 		} else
2433 			ia.t1 = ia.t2 = 0; /* appease gcc */
2434 		if ((error = dhcp6_checkstatusok(ifp, NULL, p, o.len)) != 0) {
2435 			if (error == D6_STATUS_NOBINDING)
2436 				state->has_no_binding = true;
2437 			e = 1;
2438 			continue;
2439 		}
2440 		if (o.code == D6_OPTION_IA_PD) {
2441 #ifndef SMALL
2442 			if (dhcp6_findpd(ifp, ia.iaid, p, o.len,
2443 					 acquired) == 0)
2444 			{
2445 				logwarnx("%s: %s: DHCPv6 REPLY missing Prefix",
2446 				    ifp->name, sfrom);
2447 				continue;
2448 			}
2449 #endif
2450 		} else {
2451 			if (dhcp6_findna(ifp, o.code, ia.iaid, p, o.len,
2452 					 acquired) == 0)
2453 			{
2454 				logwarnx("%s: %s: DHCPv6 REPLY missing "
2455 				    "IA Address",
2456 				    ifp->name, sfrom);
2457 				continue;
2458 			}
2459 		}
2460 		if (o.code != D6_OPTION_IA_TA) {
2461 			if (ia.t1 != 0 &&
2462 			    (ia.t1 < state->renew || state->renew == 0))
2463 				state->renew = ia.t1;
2464 			if (ia.t2 != 0 &&
2465 			    (ia.t2 < state->rebind || state->rebind == 0))
2466 				state->rebind = ia.t2;
2467 		}
2468 		i++;
2469 	}
2470 
2471 	if (i == 0 && e)
2472 		return -1;
2473 	return i;
2474 }
2475 
2476 #ifndef SMALL
2477 static void
2478 dhcp6_deprecatedele(struct ipv6_addr *ia)
2479 {
2480 	struct ipv6_addr *da, *dan, *dda;
2481 	struct timespec now;
2482 	struct dhcp6_state *state;
2483 
2484 	timespecclear(&now);
2485 	TAILQ_FOREACH_SAFE(da, &ia->pd_pfxs, pd_next, dan) {
2486 		if (ia->prefix_vltime == 0) {
2487 			if (da->prefix_vltime != 0)
2488 				da->prefix_vltime = 0;
2489 			else
2490 				continue;
2491 		} else if (da->prefix_pltime != 0)
2492 			da->prefix_pltime = 0;
2493 		else
2494 			continue;
2495 
2496 		if (ipv6_doaddr(da, &now) != -1)
2497 			continue;
2498 
2499 		/* Delegation deleted, forget it. */
2500 		TAILQ_REMOVE(&ia->pd_pfxs, da, pd_next);
2501 
2502 		/* Delete it from the interface. */
2503 		state = D6_STATE(da->iface);
2504 		TAILQ_FOREACH(dda, &state->addrs, next) {
2505 			if (IN6_ARE_ADDR_EQUAL(&dda->addr, &da->addr))
2506 				break;
2507 		}
2508 		if (dda != NULL) {
2509 			TAILQ_REMOVE(&state->addrs, dda, next);
2510 			ipv6_freeaddr(dda);
2511 		}
2512 	}
2513 }
2514 #endif
2515 
2516 static void
2517 dhcp6_deprecateaddrs(struct ipv6_addrhead *addrs)
2518 {
2519 	struct ipv6_addr *ia, *ian;
2520 
2521 	TAILQ_FOREACH_SAFE(ia, addrs, next, ian) {
2522 		if (ia->flags & IPV6_AF_EXTENDED)
2523 			;
2524 		else if (ia->flags & IPV6_AF_STALE) {
2525 			if (ia->prefix_vltime != 0)
2526 				logdebugx("%s: %s: became stale",
2527 				    ia->iface->name, ia->saddr);
2528 			/* Technically this violates RFC 8415 18.2.10.1,
2529 			 * but we need a mechanism to tell the kernel to
2530 			 * try and prefer other addresses. */
2531 			ia->prefix_pltime = 0;
2532 		} else if (ia->prefix_vltime == 0)
2533 			loginfox("%s: %s: no valid lifetime",
2534 			    ia->iface->name, ia->saddr);
2535 		else
2536 			continue;
2537 
2538 #ifndef SMALL
2539 		/* If we delegated from this prefix, deprecate or remove
2540 		 * the delegations. */
2541 		if (ia->flags & IPV6_AF_DELEGATEDPFX)
2542 			dhcp6_deprecatedele(ia);
2543 #endif
2544 
2545 		if (ia->flags & IPV6_AF_REQUEST) {
2546 			ia->prefix_vltime = ia->prefix_pltime = 0;
2547 			eloop_q_timeout_delete(ia->iface->ctx->eloop,
2548 			    ELOOP_QUEUE_ALL, NULL, ia);
2549 			continue;
2550 		}
2551 		TAILQ_REMOVE(addrs, ia, next);
2552 		if (ia->flags & IPV6_AF_EXTENDED)
2553 			ipv6_deleteaddr(ia);
2554 		ipv6_freeaddr(ia);
2555 	}
2556 }
2557 
2558 static int
2559 dhcp6_validatelease(struct interface *ifp,
2560     struct dhcp6_message *m, size_t len,
2561     const char *sfrom, const struct timespec *acquired)
2562 {
2563 	struct dhcp6_state *state;
2564 	int nia, ok_errno;
2565 	struct timespec aq;
2566 
2567 	if (len <= sizeof(*m)) {
2568 		logerrx("%s: DHCPv6 lease truncated", ifp->name);
2569 		return -1;
2570 	}
2571 
2572 	state = D6_STATE(ifp);
2573 	errno = 0;
2574 	if (dhcp6_checkstatusok(ifp, m, NULL, len) != 0)
2575 		return -1;
2576 	ok_errno = errno;
2577 
2578 	state->renew = state->rebind = state->expire = 0;
2579 	state->lowpl = ND6_INFINITE_LIFETIME;
2580 	if (!acquired) {
2581 		clock_gettime(CLOCK_MONOTONIC, &aq);
2582 		acquired = &aq;
2583 	}
2584 	state->has_no_binding = false;
2585 	nia = dhcp6_findia(ifp, m, len, sfrom, acquired);
2586 	if (nia == 0) {
2587 		if (state->state != DH6S_CONFIRM && ok_errno != 0) {
2588 			logerrx("%s: no useable IA found in lease", ifp->name);
2589 			return -1;
2590 		}
2591 
2592 		/* We are confirming and have an OK,
2593 		 * so look for ia's in our old lease.
2594 		 * IA's must have existed here otherwise we would
2595 		 * have rejected it earlier. */
2596 		assert(state->new != NULL && state->new_len != 0);
2597 		state->has_no_binding = false;
2598 		nia = dhcp6_findia(ifp, state->new, state->new_len,
2599 		    sfrom, acquired);
2600 	}
2601 	return nia;
2602 }
2603 
2604 static ssize_t
2605 dhcp6_readlease(struct interface *ifp, int validate)
2606 {
2607 	union {
2608 		struct dhcp6_message dhcp6;
2609 		uint8_t buf[UDPLEN_MAX];
2610 	} buf;
2611 	struct dhcp6_state *state;
2612 	ssize_t bytes;
2613 	int fd;
2614 	time_t mtime, now;
2615 #ifdef AUTH
2616 	uint8_t *o;
2617 	uint16_t ol;
2618 #endif
2619 
2620 	state = D6_STATE(ifp);
2621 	if (state->leasefile[0] == '\0') {
2622 		logdebugx("reading standard input");
2623 		bytes = read(fileno(stdin), buf.buf, sizeof(buf.buf));
2624 	} else {
2625 		logdebugx("%s: reading lease: %s",
2626 		    ifp->name, state->leasefile);
2627 		bytes = dhcp_readfile(ifp->ctx, state->leasefile,
2628 		    buf.buf, sizeof(buf.buf));
2629 	}
2630 	if (bytes == -1)
2631 		goto ex;
2632 
2633 	if (ifp->ctx->options & DHCPCD_DUMPLEASE || state->leasefile[0] == '\0')
2634 		goto out;
2635 
2636 	if (bytes == 0)
2637 		goto ex;
2638 
2639 	/* If not validating IA's and if they have expired,
2640 	 * skip to the auth check. */
2641 	if (!validate)
2642 		goto auth;
2643 
2644 	if (dhcp_filemtime(ifp->ctx, state->leasefile, &mtime) == -1)
2645 		goto ex;
2646 	clock_gettime(CLOCK_MONOTONIC, &state->acquired);
2647 	if ((now = time(NULL)) == -1)
2648 		goto ex;
2649 	state->acquired.tv_sec -= now - mtime;
2650 
2651 	/* Check to see if the lease is still valid */
2652 	fd = dhcp6_validatelease(ifp, &buf.dhcp6, (size_t)bytes, NULL,
2653 	    &state->acquired);
2654 	if (fd == -1)
2655 		goto ex;
2656 
2657 	if (state->expire != ND6_INFINITE_LIFETIME &&
2658 	    (time_t)state->expire < now - mtime &&
2659 	    !(ifp->options->options & DHCPCD_LASTLEASE_EXTEND))
2660 	{
2661 		logdebugx("%s: discarding expired lease", ifp->name);
2662 		bytes = 0;
2663 		goto ex;
2664 	}
2665 
2666 auth:
2667 #ifdef AUTH
2668 	/* Authenticate the message */
2669 	o = dhcp6_findmoption(&buf.dhcp6, (size_t)bytes, D6_OPTION_AUTH, &ol);
2670 	if (o) {
2671 		if (dhcp_auth_validate(&state->auth, &ifp->options->auth,
2672 		    buf.buf, (size_t)bytes, 6, buf.dhcp6.type, o, ol) == NULL)
2673 		{
2674 			logerr("%s: authentication failed", ifp->name);
2675 			bytes = 0;
2676 			goto ex;
2677 		}
2678 		if (state->auth.token)
2679 			logdebugx("%s: validated using 0x%08" PRIu32,
2680 			    ifp->name, state->auth.token->secretid);
2681 		else
2682 			loginfox("%s: accepted reconfigure key", ifp->name);
2683 	} else if ((ifp->options->auth.options & DHCPCD_AUTH_SENDREQUIRE) ==
2684 	    DHCPCD_AUTH_SENDREQUIRE)
2685 	{
2686 		logerrx("%s: authentication now required", ifp->name);
2687 		goto ex;
2688 	}
2689 #endif
2690 
2691 out:
2692 	free(state->new);
2693 	state->new = malloc((size_t)bytes);
2694 	if (state->new == NULL) {
2695 		logerr(__func__);
2696 		goto ex;
2697 	}
2698 
2699 	memcpy(state->new, buf.buf, (size_t)bytes);
2700 	state->new_len = (size_t)bytes;
2701 	return bytes;
2702 
2703 ex:
2704 	dhcp6_freedrop_addrs(ifp, 0, NULL);
2705 	dhcp_unlink(ifp->ctx, state->leasefile);
2706 	free(state->new);
2707 	state->new = NULL;
2708 	state->new_len = 0;
2709 	dhcp6_addrequestedaddrs(ifp);
2710 	return bytes == 0 ? 0 : -1;
2711 }
2712 
2713 static void
2714 dhcp6_startinit(struct interface *ifp)
2715 {
2716 	struct dhcp6_state *state;
2717 	ssize_t r;
2718 	uint8_t has_ta, has_non_ta;
2719 	size_t i;
2720 
2721 	state = D6_STATE(ifp);
2722 	state->state = DH6S_INIT;
2723 	state->expire = ND6_INFINITE_LIFETIME;
2724 	state->lowpl = ND6_INFINITE_LIFETIME;
2725 
2726 	dhcp6_addrequestedaddrs(ifp);
2727 	has_ta = has_non_ta = 0;
2728 	for (i = 0; i < ifp->options->ia_len; i++) {
2729 		switch (ifp->options->ia[i].ia_type) {
2730 		case D6_OPTION_IA_TA:
2731 			has_ta = 1;
2732 			break;
2733 		default:
2734 			has_non_ta = 1;
2735 		}
2736 	}
2737 
2738 	if (!(ifp->ctx->options & DHCPCD_TEST) &&
2739 	    !(has_ta && !has_non_ta) &&
2740 	    ifp->options->reboot != 0)
2741 	{
2742 		r = dhcp6_readlease(ifp, 1);
2743 		if (r == -1) {
2744 			if (errno != ENOENT && errno != ESRCH)
2745 				logerr("%s: %s", __func__, state->leasefile);
2746 		} else if (r != 0 &&
2747 		    !(ifp->options->options & DHCPCD_ANONYMOUS))
2748 		{
2749 			/* RFC 3633 section 12.1 */
2750 #ifndef SMALL
2751 			if (dhcp6_hasprefixdelegation(ifp))
2752 				dhcp6_startrebind(ifp);
2753 			else
2754 #endif
2755 				dhcp6_startconfirm(ifp);
2756 			return;
2757 		}
2758 	}
2759 	dhcp6_startdiscoinform(ifp);
2760 }
2761 
2762 #ifndef SMALL
2763 static struct ipv6_addr *
2764 dhcp6_ifdelegateaddr(struct interface *ifp, struct ipv6_addr *prefix,
2765     const struct if_sla *sla, struct if_ia *if_ia)
2766 {
2767 	struct dhcp6_state *state;
2768 	struct in6_addr addr, daddr;
2769 	struct ipv6_addr *ia;
2770 	int pfxlen, dadcounter;
2771 	uint64_t vl;
2772 
2773 	/* RFC6603 Section 4.2 */
2774 	if (strcmp(ifp->name, prefix->iface->name) == 0) {
2775 		if (prefix->prefix_exclude_len == 0) {
2776 			/* Don't spam the log automatically */
2777 			if (sla != NULL)
2778 				logwarnx("%s: DHCPv6 server does not support "
2779 				    "OPTION_PD_EXCLUDE",
2780 				    ifp->name);
2781 			return NULL;
2782 		}
2783 		pfxlen = prefix->prefix_exclude_len;
2784 		memcpy(&addr, &prefix->prefix_exclude, sizeof(addr));
2785 	} else if ((pfxlen = dhcp6_delegateaddr(&addr, ifp, prefix,
2786 	    sla, if_ia)) == -1)
2787 		return NULL;
2788 
2789 	if (sla != NULL && fls64(sla->suffix) > 128 - pfxlen) {
2790 		logerrx("%s: suffix %" PRIu64 " + prefix_len %d > 128",
2791 		    ifp->name, sla->suffix, pfxlen);
2792 		return NULL;
2793 	}
2794 
2795 	/* Add our suffix */
2796 	if (sla != NULL && sla->suffix != 0) {
2797 		daddr = addr;
2798 		vl = be64dec(addr.s6_addr + 8);
2799 		vl |= sla->suffix;
2800 		be64enc(daddr.s6_addr + 8, vl);
2801 	} else {
2802 		dadcounter = ipv6_makeaddr(&daddr, ifp, &addr, pfxlen, 0);
2803 		if (dadcounter == -1) {
2804 			logerrx("%s: error adding slaac to prefix_len %d",
2805 			    ifp->name, pfxlen);
2806 			return NULL;
2807 		}
2808 	}
2809 
2810 	/* Find an existing address */
2811 	state = D6_STATE(ifp);
2812 	TAILQ_FOREACH(ia, &state->addrs, next) {
2813 		if (IN6_ARE_ADDR_EQUAL(&ia->addr, &daddr))
2814 			break;
2815 	}
2816 	if (ia == NULL) {
2817 		ia = ipv6_newaddr(ifp, &daddr, (uint8_t)pfxlen, IPV6_AF_ONLINK);
2818 		if (ia == NULL)
2819 			return NULL;
2820 		ia->dadcallback = dhcp6_dadcallback;
2821 		memcpy(&ia->iaid, &prefix->iaid, sizeof(ia->iaid));
2822 		ia->created = prefix->acquired;
2823 
2824 		TAILQ_INSERT_TAIL(&state->addrs, ia, next);
2825 		TAILQ_INSERT_TAIL(&prefix->pd_pfxs, ia, pd_next);
2826 	}
2827 	ia->delegating_prefix = prefix;
2828 	ia->prefix = addr;
2829 	ia->prefix_len = (uint8_t)pfxlen;
2830 	ia->acquired = prefix->acquired;
2831 	ia->prefix_pltime = prefix->prefix_pltime;
2832 	ia->prefix_vltime = prefix->prefix_vltime;
2833 
2834 	/* If the prefix length hasn't changed,
2835 	 * don't install a reject route. */
2836 	if (prefix->prefix_len == pfxlen)
2837 		prefix->flags |= IPV6_AF_NOREJECT;
2838 	else
2839 		prefix->flags &= ~IPV6_AF_NOREJECT;
2840 
2841 	return ia;
2842 }
2843 #endif
2844 
2845 static void
2846 dhcp6_script_try_run(struct interface *ifp, int delegated)
2847 {
2848 	struct dhcp6_state *state;
2849 	struct ipv6_addr *ap;
2850 	int completed;
2851 
2852 	state = D6_STATE(ifp);
2853 	completed = 1;
2854 	/* If all addresses have completed DAD run the script */
2855 	TAILQ_FOREACH(ap, &state->addrs, next) {
2856 		if (!(ap->flags & IPV6_AF_ADDED))
2857 			continue;
2858 		if (ap->flags & IPV6_AF_ONLINK) {
2859 			if (!(ap->flags & IPV6_AF_DADCOMPLETED) &&
2860 			    ipv6_iffindaddr(ap->iface, &ap->addr,
2861 					    IN6_IFF_TENTATIVE))
2862 				ap->flags |= IPV6_AF_DADCOMPLETED;
2863 			if ((ap->flags & IPV6_AF_DADCOMPLETED) == 0
2864 #ifndef SMALL
2865 			    && ((delegated && ap->delegating_prefix) ||
2866 			    (!delegated && !ap->delegating_prefix))
2867 #endif
2868 			    )
2869 			{
2870 				completed = 0;
2871 				break;
2872 			}
2873 		}
2874 	}
2875 	if (completed) {
2876 		script_runreason(ifp, delegated ? "DELEGATED6" : state->reason);
2877 		if (!delegated)
2878 			dhcpcd_daemonise(ifp->ctx);
2879 	} else
2880 		logdebugx("%s: waiting for DHCPv6 DAD to complete", ifp->name);
2881 }
2882 
2883 #ifdef SMALL
2884 size_t
2885 dhcp6_find_delegates(__unused struct interface *ifp)
2886 {
2887 
2888 	return 0;
2889 }
2890 #else
2891 static void
2892 dhcp6_delegate_prefix(struct interface *ifp)
2893 {
2894 	struct if_options *ifo;
2895 	struct dhcp6_state *state;
2896 	struct ipv6_addr *ap;
2897 	size_t i, j, k;
2898 	struct if_ia *ia;
2899 	struct if_sla *sla;
2900 	struct interface *ifd;
2901 	bool carrier_warned;
2902 
2903 	ifo = ifp->options;
2904 	state = D6_STATE(ifp);
2905 
2906 	/* Clear the logged flag. */
2907 	TAILQ_FOREACH(ap, &state->addrs, next) {
2908 		ap->flags &= ~IPV6_AF_DELEGATEDLOG;
2909 	}
2910 
2911 	TAILQ_FOREACH(ifd, ifp->ctx->ifaces, next) {
2912 		if (!ifd->active)
2913 			continue;
2914 		if (!(ifd->options->options & DHCPCD_CONFIGURE))
2915 			continue;
2916 		k = 0;
2917 		carrier_warned = false;
2918 		TAILQ_FOREACH(ap, &state->addrs, next) {
2919 			if (!(ap->flags & IPV6_AF_DELEGATEDPFX))
2920 				continue;
2921 			if (!(ap->flags & IPV6_AF_DELEGATEDLOG)) {
2922 				int loglevel;
2923 
2924 				if (ap->flags & IPV6_AF_NEW)
2925 					loglevel = LOG_INFO;
2926 				else
2927 					loglevel = LOG_DEBUG;
2928 				/* We only want to log this the once as we loop
2929 				 * through many interfaces first. */
2930 				ap->flags |= IPV6_AF_DELEGATEDLOG;
2931 				logmessage(loglevel, "%s: delegated prefix %s",
2932 				    ifp->name, ap->saddr);
2933 				ap->flags &= ~IPV6_AF_NEW;
2934 			}
2935 			for (i = 0; i < ifo->ia_len; i++) {
2936 				ia = &ifo->ia[i];
2937 				if (ia->ia_type != D6_OPTION_IA_PD)
2938 					continue;
2939 				if (memcmp(ia->iaid, ap->iaid,
2940 				    sizeof(ia->iaid)))
2941 					continue;
2942 				if (ia->sla_len == 0) {
2943 					/* no SLA configured, so lets
2944 					 * automate it */
2945 					if (!if_is_link_up(ifd)) {
2946 						logdebugx(
2947 						    "%s: has no carrier, cannot"
2948 						    " delegate addresses",
2949 						    ifd->name);
2950 						carrier_warned = true;
2951 						break;
2952 					}
2953 					if (dhcp6_ifdelegateaddr(ifd, ap,
2954 					    NULL, ia))
2955 						k++;
2956 				}
2957 				for (j = 0; j < ia->sla_len; j++) {
2958 					sla = &ia->sla[j];
2959 					if (strcmp(ifd->name, sla->ifname))
2960 						continue;
2961 					if (!if_is_link_up(ifd)) {
2962 						logdebugx(
2963 						    "%s: has no carrier, cannot"
2964 						    " delegate addresses",
2965 						    ifd->name);
2966 						carrier_warned = true;
2967 						break;
2968 					}
2969 					if (dhcp6_ifdelegateaddr(ifd, ap,
2970 					    sla, ia))
2971 						k++;
2972 				}
2973 				if (carrier_warned)
2974 					break;
2975 			}
2976 			if (carrier_warned)
2977 				break;
2978 		}
2979 		if (k && !carrier_warned) {
2980 			struct dhcp6_state *s = D6_STATE(ifd);
2981 
2982 			ipv6_addaddrs(&s->addrs);
2983 			dhcp6_script_try_run(ifd, 1);
2984 		}
2985 	}
2986 
2987 	/* Now all addresses have been added, rebuild the routing table. */
2988 	rt_build(ifp->ctx, AF_INET6);
2989 }
2990 
2991 static void
2992 dhcp6_find_delegates1(void *arg)
2993 {
2994 
2995 	dhcp6_find_delegates(arg);
2996 }
2997 
2998 size_t
2999 dhcp6_find_delegates(struct interface *ifp)
3000 {
3001 	struct if_options *ifo;
3002 	struct dhcp6_state *state;
3003 	struct ipv6_addr *ap;
3004 	size_t i, j, k;
3005 	struct if_ia *ia;
3006 	struct if_sla *sla;
3007 	struct interface *ifd;
3008 
3009 	if (ifp->options != NULL &&
3010 	    !(ifp->options->options & DHCPCD_CONFIGURE))
3011 		return 0;
3012 
3013 	k = 0;
3014 	TAILQ_FOREACH(ifd, ifp->ctx->ifaces, next) {
3015 		ifo = ifd->options;
3016 		state = D6_STATE(ifd);
3017 		if (state == NULL || state->state != DH6S_BOUND)
3018 			continue;
3019 		TAILQ_FOREACH(ap, &state->addrs, next) {
3020 			if (!(ap->flags & IPV6_AF_DELEGATEDPFX))
3021 				continue;
3022 			for (i = 0; i < ifo->ia_len; i++) {
3023 				ia = &ifo->ia[i];
3024 				if (ia->ia_type != D6_OPTION_IA_PD)
3025 					continue;
3026 				if (memcmp(ia->iaid, ap->iaid,
3027 				    sizeof(ia->iaid)))
3028 					continue;
3029 				for (j = 0; j < ia->sla_len; j++) {
3030 					sla = &ia->sla[j];
3031 					if (strcmp(ifp->name, sla->ifname))
3032 						continue;
3033 					if (ipv6_linklocal(ifp) == NULL) {
3034 						logdebugx(
3035 						    "%s: delaying adding"
3036 						    " delegated addresses for"
3037 						    " LL address",
3038 						    ifp->name);
3039 						ipv6_addlinklocalcallback(ifp,
3040 						    dhcp6_find_delegates1, ifp);
3041 						return 1;
3042 					}
3043 					if (dhcp6_ifdelegateaddr(ifp, ap,
3044 					    sla, ia))
3045 					    k++;
3046 				}
3047 			}
3048 		}
3049 	}
3050 
3051 	if (k) {
3052 		loginfox("%s: adding delegated prefixes", ifp->name);
3053 		state = D6_STATE(ifp);
3054 		state->state = DH6S_DELEGATED;
3055 		ipv6_addaddrs(&state->addrs);
3056 		rt_build(ifp->ctx, AF_INET6);
3057 		dhcp6_script_try_run(ifp, 1);
3058 	}
3059 	return k;
3060 }
3061 #endif
3062 
3063 static void
3064 dhcp6_bind(struct interface *ifp, const char *op, const char *sfrom)
3065 {
3066 	struct dhcp6_state *state = D6_STATE(ifp);
3067 	bool timedout = (op == NULL), confirmed;
3068 	struct ipv6_addr *ia;
3069 	int loglevel;
3070 	struct timespec now;
3071 
3072 	if (state->state == DH6S_RENEW && !state->new_start) {
3073 		loglevel = LOG_DEBUG;
3074 		TAILQ_FOREACH(ia, &state->addrs, next) {
3075 			if (ia->flags & IPV6_AF_NEW) {
3076 				loglevel = LOG_INFO;
3077 				break;
3078 			}
3079 		}
3080 	} else if (state->state == DH6S_INFORM)
3081 		loglevel = state->new_start ? LOG_INFO : LOG_DEBUG;
3082 	else
3083 		loglevel = LOG_INFO;
3084 	state->new_start = false;
3085 
3086 	if (!timedout) {
3087 		logmessage(loglevel, "%s: %s received from %s",
3088 		    ifp->name, op, sfrom);
3089 #ifndef SMALL
3090 		/* If we delegated from an unconfirmed lease we MUST drop
3091 		 * them now. Hopefully we have new delegations. */
3092 		if (state->reason != NULL &&
3093 		    strcmp(state->reason, "TIMEOUT6") == 0)
3094 			dhcp6_delete_delegates(ifp);
3095 #endif
3096 		state->reason = NULL;
3097 	} else
3098 		state->reason = "TIMEOUT6";
3099 
3100 	eloop_timeout_delete(ifp->ctx->eloop, NULL, ifp);
3101 	clock_gettime(CLOCK_MONOTONIC, &now);
3102 
3103 	switch(state->state) {
3104 	case DH6S_INFORM:
3105 	{
3106 		struct dhcp6_option *o;
3107 		uint16_t ol;
3108 
3109 		if (state->reason == NULL)
3110 			state->reason = "INFORM6";
3111 		o = dhcp6_findmoption(state->new, state->new_len,
3112 				      D6_OPTION_INFO_REFRESH_TIME, &ol);
3113 		if (o == NULL || ol != sizeof(uint32_t))
3114 			state->renew = IRT_DEFAULT;
3115 		else {
3116 			memcpy(&state->renew, o, ol);
3117 			state->renew = ntohl(state->renew);
3118 			if (state->renew < IRT_MINIMUM)
3119 				state->renew = IRT_MINIMUM;
3120 		}
3121 		state->rebind = 0;
3122 		state->expire = ND6_INFINITE_LIFETIME;
3123 		state->lowpl = ND6_INFINITE_LIFETIME;
3124 	}
3125 		break;
3126 
3127 	case DH6S_REQUEST:
3128 		if (state->reason == NULL)
3129 			state->reason = "BOUND6";
3130 		/* FALLTHROUGH */
3131 	case DH6S_RENEW:
3132 		if (state->reason == NULL)
3133 			state->reason = "RENEW6";
3134 		/* FALLTHROUGH */
3135 	case DH6S_REBIND:
3136 		if (state->reason == NULL)
3137 			state->reason = "REBIND6";
3138 		/* FALLTHROUGH */
3139 	case DH6S_CONFIRM:
3140 		if (state->reason == NULL)
3141 			state->reason = "REBOOT6";
3142 		if (state->renew != 0) {
3143 			bool all_expired = true;
3144 
3145 			TAILQ_FOREACH(ia, &state->addrs, next) {
3146 				if (ia->flags & IPV6_AF_STALE)
3147 					continue;
3148 				if (!(state->renew == ND6_INFINITE_LIFETIME
3149 				    && ia->prefix_vltime == ND6_INFINITE_LIFETIME)
3150 				    && ia->prefix_vltime != 0
3151 				    && ia->prefix_vltime <= state->renew)
3152 					logwarnx(
3153 					    "%s: %s will expire before renewal",
3154 					    ifp->name, ia->saddr);
3155 				else
3156 					all_expired = false;
3157 			}
3158 			if (all_expired) {
3159 				/* All address's vltime happens at or before
3160 				 * the configured T1 in the IA.
3161 				 * This is a badly configured server and we
3162 				 * have to use our own notion of what
3163 				 * T1 and T2 should be as a result.
3164 				 *
3165 				 * Doing this violates RFC 3315 22.4:
3166 				 * In a message sent by a server to a client,
3167 				 * the client MUST use the values in the T1
3168 				 * and T2 fields for the T1 and T2 parameters,
3169 				 * unless those values in those fields are 0.
3170 				 */
3171 				logwarnx("%s: ignoring T1 %"PRIu32
3172 				    " due to address expiry",
3173 				    ifp->name, state->renew);
3174 				state->renew = state->rebind = 0;
3175 			}
3176 		}
3177 		if (state->renew == 0 && state->lowpl != ND6_INFINITE_LIFETIME)
3178 			state->renew = (uint32_t)(state->lowpl * 0.5);
3179 		if (state->rebind == 0 && state->lowpl != ND6_INFINITE_LIFETIME)
3180 			state->rebind = (uint32_t)(state->lowpl * 0.8);
3181 		break;
3182 	default:
3183 		state->reason = "UNKNOWN6";
3184 		break;
3185 	}
3186 
3187 	if (state->state != DH6S_CONFIRM && !timedout) {
3188 		state->acquired = now;
3189 		free(state->old);
3190 		state->old = state->new;
3191 		state->old_len = state->new_len;
3192 		state->new = state->recv;
3193 		state->new_len = state->recv_len;
3194 		state->recv = NULL;
3195 		state->recv_len = 0;
3196 		confirmed = false;
3197 	} else {
3198 		/* Reduce timers based on when we got the lease. */
3199 		uint32_t elapsed;
3200 
3201 		elapsed = (uint32_t)eloop_timespec_diff(&now,
3202 		    &state->acquired, NULL);
3203 		if (state->renew && state->renew != ND6_INFINITE_LIFETIME) {
3204 			if (state->renew > elapsed)
3205 				state->renew -= elapsed;
3206 			else
3207 				state->renew = 0;
3208 		}
3209 		if (state->rebind && state->rebind != ND6_INFINITE_LIFETIME) {
3210 			if (state->rebind > elapsed)
3211 				state->rebind -= elapsed;
3212 			else
3213 				state->rebind = 0;
3214 		}
3215 		if (state->expire && state->expire != ND6_INFINITE_LIFETIME) {
3216 			if (state->expire > elapsed)
3217 				state->expire -= elapsed;
3218 			else
3219 				state->expire = 0;
3220 		}
3221 		confirmed = true;
3222 	}
3223 
3224 	if (ifp->ctx->options & DHCPCD_TEST)
3225 		script_runreason(ifp, "TEST");
3226 	else {
3227 		if (state->state == DH6S_INFORM)
3228 			state->state = DH6S_INFORMED;
3229 		else
3230 			state->state = DH6S_BOUND;
3231 		state->failed = false;
3232 
3233 		if (state->renew && state->renew != ND6_INFINITE_LIFETIME)
3234 			eloop_timeout_add_sec(ifp->ctx->eloop,
3235 			    state->renew,
3236 			    state->state == DH6S_INFORMED ?
3237 			    dhcp6_startinform : dhcp6_startrenew, ifp);
3238 		if (state->rebind && state->rebind != ND6_INFINITE_LIFETIME)
3239 			eloop_timeout_add_sec(ifp->ctx->eloop,
3240 			    state->rebind, dhcp6_startrebind, ifp);
3241 		if (state->expire != ND6_INFINITE_LIFETIME)
3242 			eloop_timeout_add_sec(ifp->ctx->eloop,
3243 			    state->expire, dhcp6_startexpire, ifp);
3244 
3245 		if (ifp->options->options & DHCPCD_CONFIGURE) {
3246 			ipv6_addaddrs(&state->addrs);
3247 			if (!timedout)
3248 				dhcp6_deprecateaddrs(&state->addrs);
3249 		}
3250 
3251 		if (state->state == DH6S_INFORMED)
3252 			logmessage(loglevel, "%s: refresh in %"PRIu32" seconds",
3253 			    ifp->name, state->renew);
3254 		else if (state->renew == ND6_INFINITE_LIFETIME)
3255 			logmessage(loglevel, "%s: leased for infinity",
3256 			    ifp->name);
3257 		else if (state->renew || state->rebind)
3258 			logmessage(loglevel, "%s: renew in %"PRIu32", "
3259 			    "rebind in %"PRIu32", "
3260 			    "expire in %"PRIu32" seconds",
3261 			    ifp->name,
3262 			    state->renew, state->rebind, state->expire);
3263 		else if (state->expire == 0)
3264 			logmessage(loglevel, "%s: will expire", ifp->name);
3265 		else
3266 			logmessage(loglevel, "%s: expire in %"PRIu32" seconds",
3267 			    ifp->name, state->expire);
3268 		rt_build(ifp->ctx, AF_INET6);
3269 		if (!confirmed && !timedout) {
3270 			logdebugx("%s: writing lease: %s",
3271 			    ifp->name, state->leasefile);
3272 			if (dhcp_writefile(ifp->ctx, state->leasefile, 0640,
3273 			    state->new, state->new_len) == -1)
3274 				logerr("dhcp_writefile: %s",state->leasefile);
3275 		}
3276 #ifndef SMALL
3277 		dhcp6_delegate_prefix(ifp);
3278 #endif
3279 		dhcp6_script_try_run(ifp, 0);
3280 	}
3281 
3282 	if (ifp->ctx->options & DHCPCD_TEST ||
3283 	    (ifp->options->options & DHCPCD_INFORM &&
3284 	    !(ifp->ctx->options & DHCPCD_MANAGER)))
3285 	{
3286 		eloop_exit(ifp->ctx->eloop, EXIT_SUCCESS);
3287 	}
3288 }
3289 
3290 static void
3291 dhcp6_recvif(struct interface *ifp, const char *sfrom,
3292     struct dhcp6_message *r, size_t len)
3293 {
3294 	struct dhcpcd_ctx *ctx;
3295 	size_t i;
3296 	const char *op;
3297 	struct dhcp6_state *state;
3298 	uint8_t *o;
3299 	uint16_t ol;
3300 	const struct dhcp_opt *opt;
3301 	const struct if_options *ifo;
3302 	bool valid_op;
3303 #ifdef AUTH
3304 	uint8_t *auth;
3305 	uint16_t auth_len;
3306 #endif
3307 
3308 	ctx = ifp->ctx;
3309 	state = D6_STATE(ifp);
3310 	if (state == NULL || state->send == NULL) {
3311 		logdebugx("%s: DHCPv6 reply received but not running",
3312 		    ifp->name);
3313 		return;
3314 	}
3315 
3316 	/* We're already bound and this message is for another machine */
3317 	/* XXX DELEGATED? */
3318 	if (r->type != DHCP6_RECONFIGURE &&
3319 	    (state->state == DH6S_BOUND || state->state == DH6S_INFORMED))
3320 	{
3321 		logdebugx("%s: DHCPv6 reply received but already bound",
3322 		    ifp->name);
3323 		return;
3324 	}
3325 
3326 	if (dhcp6_findmoption(r, len, D6_OPTION_SERVERID, NULL) == NULL) {
3327 		logdebugx("%s: no DHCPv6 server ID from %s", ifp->name, sfrom);
3328 		return;
3329 	}
3330 
3331 	ifo = ifp->options;
3332 	for (i = 0, opt = ctx->dhcp6_opts;
3333 	    i < ctx->dhcp6_opts_len;
3334 	    i++, opt++)
3335 	{
3336 		if (has_option_mask(ifo->requiremask6, opt->option) &&
3337 		    !dhcp6_findmoption(r, len, (uint16_t)opt->option, NULL))
3338 		{
3339 			logwarnx("%s: reject DHCPv6 (no option %s) from %s",
3340 			    ifp->name, opt->var, sfrom);
3341 			return;
3342 		}
3343 		if (has_option_mask(ifo->rejectmask6, opt->option) &&
3344 		    dhcp6_findmoption(r, len, (uint16_t)opt->option, NULL))
3345 		{
3346 			logwarnx("%s: reject DHCPv6 (option %s) from %s",
3347 			    ifp->name, opt->var, sfrom);
3348 			return;
3349 		}
3350 	}
3351 
3352 #ifdef AUTH
3353 	/* Authenticate the message */
3354 	auth = dhcp6_findmoption(r, len, D6_OPTION_AUTH, &auth_len);
3355 	if (auth != NULL) {
3356 		if (dhcp_auth_validate(&state->auth, &ifo->auth,
3357 		    (uint8_t *)r, len, 6, r->type, auth, auth_len) == NULL)
3358 		{
3359 			logerr("%s: authentication failed from %s",
3360 			    ifp->name, sfrom);
3361 			return;
3362 		}
3363 		if (state->auth.token)
3364 			logdebugx("%s: validated using 0x%08" PRIu32,
3365 			    ifp->name, state->auth.token->secretid);
3366 		else
3367 			loginfox("%s: accepted reconfigure key", ifp->name);
3368 	} else if (ifo->auth.options & DHCPCD_AUTH_SEND) {
3369 		if (ifo->auth.options & DHCPCD_AUTH_REQUIRE) {
3370 			logerrx("%s: no authentication from %s",
3371 			    ifp->name, sfrom);
3372 			return;
3373 		}
3374 		logwarnx("%s: no authentication from %s", ifp->name, sfrom);
3375 	}
3376 #endif
3377 
3378 	op = dhcp6_get_op(r->type);
3379 	valid_op = op != NULL;
3380 	switch(r->type) {
3381 	case DHCP6_REPLY:
3382 		switch(state->state) {
3383 		case DH6S_INFORM:
3384 			if (dhcp6_checkstatusok(ifp, r, NULL, len) != 0)
3385 				return;
3386 			break;
3387 		case DH6S_CONFIRM:
3388 			if (dhcp6_validatelease(ifp, r, len, sfrom, NULL) == -1)
3389 			{
3390 				dhcp6_startdiscoinform(ifp);
3391 				return;
3392 			}
3393 			break;
3394 		case DH6S_DISCOVER:
3395 			/* Only accept REPLY in DISCOVER for RAPID_COMMIT.
3396 			 * Normally we get an ADVERTISE for a DISCOVER. */
3397 			if (!has_option_mask(ifo->requestmask6,
3398 			    D6_OPTION_RAPID_COMMIT) ||
3399 			    !dhcp6_findmoption(r, len, D6_OPTION_RAPID_COMMIT,
3400 					      NULL))
3401 			{
3402 				valid_op = false;
3403 				break;
3404 			}
3405 			/* Validate lease before setting state to REQUEST. */
3406 			/* FALLTHROUGH */
3407 		case DH6S_REQUEST: /* FALLTHROUGH */
3408 		case DH6S_RENEW: /* FALLTHROUGH */
3409 		case DH6S_REBIND:
3410 			if (dhcp6_validatelease(ifp, r, len, sfrom, NULL) == -1)
3411 			{
3412 				/*
3413 				 * If we can't use the lease, fallback to
3414 				 * DISCOVER and try and get a new one.
3415 				 *
3416 				 * This is needed become some servers
3417 				 * renumber the prefix or address
3418 				 * and deny the current one before it expires
3419 				 * rather than sending it back with a zero
3420 				 * lifetime along with the new prefix or
3421 				 * address to use.
3422 				 * This behavior is wrong, but moving to the
3423 				 * DISCOVER phase works around it.
3424 				 *
3425 				 * The currently held lease is still valid
3426 				 * until a new one is found.
3427 				 */
3428 				if (state->state != DH6S_DISCOVER)
3429 					dhcp6_startdiscoinform(ifp);
3430 				return;
3431 			}
3432 			/* RFC8415 18.2.10.1 */
3433 			if ((state->state == DH6S_RENEW ||
3434 			    state->state == DH6S_REBIND) &&
3435 			    state->has_no_binding)
3436 			{
3437 				dhcp6_startrequest(ifp);
3438 				return;
3439 			}
3440 			if (state->state == DH6S_DISCOVER)
3441 				state->state = DH6S_REQUEST;
3442 			break;
3443 		case DH6S_DECLINE:
3444 			/* This isnt really a failure, but an
3445 			 * acknowledgement of one. */
3446 			loginfox("%s: %s acknowledged DECLINE6",
3447 			    ifp->name, sfrom);
3448 			dhcp6_fail(ifp);
3449 			return;
3450 		default:
3451 			valid_op = false;
3452 			break;
3453 		}
3454 		break;
3455 	case DHCP6_ADVERTISE:
3456 		if (state->state != DH6S_DISCOVER) {
3457 			valid_op = false;
3458 			break;
3459 		}
3460 		/* RFC7083 */
3461 		o = dhcp6_findmoption(r, len, D6_OPTION_SOL_MAX_RT, &ol);
3462 		if (o && ol == sizeof(uint32_t)) {
3463 			uint32_t max_rt;
3464 
3465 			memcpy(&max_rt, o, sizeof(max_rt));
3466 			max_rt = ntohl(max_rt);
3467 			if (max_rt >= 60 && max_rt <= 86400) {
3468 				logdebugx("%s: SOL_MAX_RT %llu -> %u",
3469 				    ifp->name,
3470 				    (unsigned long long)state->sol_max_rt,
3471 				    max_rt);
3472 				state->sol_max_rt = max_rt;
3473 			} else
3474 				logerr("%s: invalid SOL_MAX_RT %u",
3475 				    ifp->name, max_rt);
3476 		}
3477 		o = dhcp6_findmoption(r, len, D6_OPTION_INF_MAX_RT, &ol);
3478 		if (o && ol == sizeof(uint32_t)) {
3479 			uint32_t max_rt;
3480 
3481 			memcpy(&max_rt, o, sizeof(max_rt));
3482 			max_rt = ntohl(max_rt);
3483 			if (max_rt >= 60 && max_rt <= 86400) {
3484 				logdebugx("%s: INF_MAX_RT %llu -> %u",
3485 				    ifp->name,
3486 				    (unsigned long long)state->inf_max_rt,
3487 				    max_rt);
3488 				state->inf_max_rt = max_rt;
3489 			} else
3490 				logerrx("%s: invalid INF_MAX_RT %u",
3491 				    ifp->name, max_rt);
3492 		}
3493 		if (dhcp6_validatelease(ifp, r, len, sfrom, NULL) == -1)
3494 			return;
3495 		break;
3496 	case DHCP6_RECONFIGURE:
3497 #ifdef AUTH
3498 		if (auth == NULL) {
3499 #endif
3500 			logerrx("%s: unauthenticated %s from %s",
3501 			    ifp->name, op, sfrom);
3502 			if (ifo->auth.options & DHCPCD_AUTH_REQUIRE)
3503 				return;
3504 #ifdef AUTH
3505 		}
3506 		loginfox("%s: %s from %s", ifp->name, op, sfrom);
3507 		o = dhcp6_findmoption(r, len, D6_OPTION_RECONF_MSG, &ol);
3508 		if (o == NULL) {
3509 			logerrx("%s: missing Reconfigure Message option",
3510 			    ifp->name);
3511 			return;
3512 		}
3513 		if (ol != 1) {
3514 			logerrx("%s: missing Reconfigure Message type",
3515 			    ifp->name);
3516 			return;
3517 		}
3518 		switch(*o) {
3519 		case DHCP6_RENEW:
3520 			if (state->state != DH6S_BOUND) {
3521 				logerrx("%s: not bound, ignoring %s",
3522 				    ifp->name, op);
3523 				return;
3524 			}
3525 			dhcp6_startrenew(ifp);
3526 			break;
3527 		case DHCP6_INFORMATION_REQ:
3528 			if (state->state != DH6S_INFORMED) {
3529 				logerrx("%s: not informed, ignoring %s",
3530 				    ifp->name, op);
3531 				return;
3532 			}
3533 			eloop_timeout_delete(ifp->ctx->eloop,
3534 			    dhcp6_sendinform, ifp);
3535 			dhcp6_startinform(ifp);
3536 			break;
3537 		default:
3538 			logerr("%s: unsupported %s type %d",
3539 			    ifp->name, op, *o);
3540 			break;
3541 		}
3542 		return;
3543 #else
3544 		break;
3545 #endif
3546 	default:
3547 		logerrx("%s: invalid DHCP6 type %s (%d)",
3548 		    ifp->name, op, r->type);
3549 		return;
3550 	}
3551 	if (!valid_op) {
3552 		logwarnx("%s: invalid state for DHCP6 type %s (%d)",
3553 		    ifp->name, op, r->type);
3554 		return;
3555 	}
3556 
3557 	if (state->recv_len < (size_t)len) {
3558 		free(state->recv);
3559 		state->recv = malloc(len);
3560 		if (state->recv == NULL) {
3561 			logerr(__func__);
3562 			return;
3563 		}
3564 	}
3565 	memcpy(state->recv, r, len);
3566 	state->recv_len = len;
3567 
3568 	if (r->type == DHCP6_ADVERTISE) {
3569 		struct ipv6_addr *ia;
3570 
3571 		if (state->state == DH6S_REQUEST) /* rapid commit */
3572 			goto bind;
3573 		TAILQ_FOREACH(ia, &state->addrs, next) {
3574 			if (!(ia->flags & (IPV6_AF_STALE | IPV6_AF_REQUEST)))
3575 				break;
3576 		}
3577 		if (ia == NULL)
3578 			ia = TAILQ_FIRST(&state->addrs);
3579 		if (ia == NULL)
3580 			loginfox("%s: ADV (no address) from %s",
3581 			    ifp->name, sfrom);
3582 		else
3583 			loginfox("%s: ADV %s from %s",
3584 			    ifp->name, ia->saddr, sfrom);
3585 		dhcp6_startrequest(ifp);
3586 		return;
3587 	}
3588 
3589 bind:
3590 	dhcp6_bind(ifp, op, sfrom);
3591 }
3592 
3593 void
3594 dhcp6_recvmsg(struct dhcpcd_ctx *ctx, struct msghdr *msg, struct ipv6_addr *ia)
3595 {
3596 	struct sockaddr_in6 *from = msg->msg_name;
3597 	size_t len = msg->msg_iov[0].iov_len;
3598 	char sfrom[INET6_ADDRSTRLEN];
3599 	struct interface *ifp;
3600 	struct dhcp6_message *r;
3601 	const struct dhcp6_state *state;
3602 	uint8_t *o;
3603 	uint16_t ol;
3604 
3605 	inet_ntop(AF_INET6, &from->sin6_addr, sfrom, sizeof(sfrom));
3606 	if (len < sizeof(struct dhcp6_message)) {
3607 		logerrx("DHCPv6 packet too short from %s", sfrom);
3608 		return;
3609 	}
3610 
3611 	if (ia != NULL)
3612 		ifp = ia->iface;
3613 	else {
3614 		ifp = if_findifpfromcmsg(ctx, msg, NULL);
3615 		if (ifp == NULL) {
3616 			logerr(__func__);
3617 			return;
3618 		}
3619 	}
3620 
3621 	r = (struct dhcp6_message *)msg->msg_iov[0].iov_base;
3622 
3623 	uint8_t duid[DUID_LEN], *dp;
3624 	size_t duid_len;
3625 	o = dhcp6_findmoption(r, len, D6_OPTION_CLIENTID, &ol);
3626 	if (ifp->options->options & DHCPCD_ANONYMOUS) {
3627 		duid_len = duid_make(duid, ifp, DUID_LL);
3628 		dp = duid;
3629 	} else {
3630 		duid_len = ctx->duid_len;
3631 		dp = ctx->duid;
3632 	}
3633 	if (o == NULL || ol != duid_len || memcmp(o, dp, ol) != 0) {
3634 		logdebugx("%s: incorrect client ID from %s",
3635 		    ifp->name, sfrom);
3636 		return;
3637 	}
3638 
3639 	if (dhcp6_findmoption(r, len, D6_OPTION_SERVERID, NULL) == NULL) {
3640 		logdebugx("%s: no DHCPv6 server ID from %s",
3641 		    ifp->name, sfrom);
3642 		return;
3643 	}
3644 
3645 	if (r->type == DHCP6_RECONFIGURE) {
3646 		if (!IN6_IS_ADDR_LINKLOCAL(&from->sin6_addr)) {
3647 			logerrx("%s: RECONFIGURE6 recv from %s, not LL",
3648 			    ifp->name, sfrom);
3649 			return;
3650 		}
3651 		goto recvif;
3652 	}
3653 
3654 	state = D6_CSTATE(ifp);
3655 	if (state == NULL ||
3656 	    r->xid[0] != state->send->xid[0] ||
3657 	    r->xid[1] != state->send->xid[1] ||
3658 	    r->xid[2] != state->send->xid[2])
3659 	{
3660 		struct interface *ifp1;
3661 		const struct dhcp6_state *state1;
3662 
3663 		/* Find an interface with a matching xid. */
3664 		TAILQ_FOREACH(ifp1, ctx->ifaces, next) {
3665 			state1 = D6_CSTATE(ifp1);
3666 			if (state1 == NULL || state1->send == NULL)
3667 				continue;
3668 			if (r->xid[0] == state1->send->xid[0] &&
3669 			    r->xid[1] == state1->send->xid[1] &&
3670 			    r->xid[2] == state1->send->xid[2])
3671 				break;
3672 		}
3673 
3674 		if (ifp1 == NULL) {
3675 			if (state != NULL)
3676 				logdebugx("%s: wrong xid 0x%02x%02x%02x"
3677 				    " (expecting 0x%02x%02x%02x) from %s",
3678 				    ifp->name,
3679 				    r->xid[0], r->xid[1], r->xid[2],
3680 				    state->send->xid[0],
3681 				    state->send->xid[1],
3682 				    state->send->xid[2],
3683 				    sfrom);
3684 			return;
3685 		}
3686 		logdebugx("%s: redirecting DHCP6 message to %s",
3687 		    ifp->name, ifp1->name);
3688 		ifp = ifp1;
3689 	}
3690 
3691 #if 0
3692 	/*
3693 	 * Handy code to inject raw DHCPv6 packets over responses
3694 	 * from our server.
3695 	 * This allows me to take a 3rd party wireshark trace and
3696 	 * replay it in my code.
3697 	 */
3698 	static int replyn = 0;
3699 	char fname[PATH_MAX], tbuf[UDPLEN_MAX];
3700 	int fd;
3701 	ssize_t tlen;
3702 	uint8_t *si1, *si2;
3703 	uint16_t si_len1, si_len2;
3704 
3705 	snprintf(fname, sizeof(fname),
3706 	    "/tmp/dhcp6.reply%d.raw", replyn++);
3707 	fd = open(fname, O_RDONLY, 0);
3708 	if (fd == -1) {
3709 		logerr("%s: open: %s", __func__, fname);
3710 		return;
3711 	}
3712 	tlen = read(fd, tbuf, sizeof(tbuf));
3713 	if (tlen == -1)
3714 		logerr("%s: read: %s", __func__, fname);
3715 	close(fd);
3716 
3717 	/* Copy across ServerID so we can work with our own server. */
3718 	si1 = dhcp6_findmoption(r, len, D6_OPTION_SERVERID, &si_len1);
3719 	si2 = dhcp6_findmoption(tbuf, (size_t)tlen,
3720 	    D6_OPTION_SERVERID, &si_len2);
3721 	if (si1 != NULL && si2 != NULL && si_len1 == si_len2)
3722 		memcpy(si2, si1, si_len2);
3723 	r = (struct dhcp6_message *)tbuf;
3724 	len = (size_t)tlen;
3725 #endif
3726 
3727 recvif:
3728 	dhcp6_recvif(ifp, sfrom, r, len);
3729 }
3730 
3731 static void
3732 dhcp6_recv(struct dhcpcd_ctx *ctx, struct ipv6_addr *ia, unsigned short events)
3733 {
3734 	struct sockaddr_in6 from;
3735 	union {
3736 		struct dhcp6_message dhcp6;
3737 		uint8_t buf[UDPLEN_MAX]; /* Maximum UDP message size */
3738 	} iovbuf;
3739 	struct iovec iov = {
3740 		.iov_base = iovbuf.buf, .iov_len = sizeof(iovbuf.buf),
3741 	};
3742 	union {
3743 		struct cmsghdr hdr;
3744 		uint8_t buf[CMSG_SPACE(sizeof(struct in6_pktinfo))];
3745 	} cmsgbuf = { .buf = { 0 } };
3746 	struct msghdr msg = {
3747 	    .msg_name = &from, .msg_namelen = sizeof(from),
3748 	    .msg_iov = &iov, .msg_iovlen = 1,
3749 	    .msg_control = cmsgbuf.buf, .msg_controllen = sizeof(cmsgbuf.buf),
3750 	};
3751 	int s;
3752 	ssize_t bytes;
3753 
3754 	if (events != ELE_READ)
3755 		logerrx("%s: unexpected event 0x%04x", __func__, events);
3756 
3757 	s = ia != NULL ? ia->dhcp6_fd : ctx->dhcp6_rfd;
3758 	bytes = recvmsg(s, &msg, 0);
3759 	if (bytes == -1) {
3760 		logerr(__func__);
3761 		return;
3762 	}
3763 
3764 	iov.iov_len = (size_t)bytes;
3765 	dhcp6_recvmsg(ctx, &msg, ia);
3766 }
3767 
3768 static void
3769 
3770 dhcp6_recvaddr(void *arg, unsigned short events)
3771 {
3772 	struct ipv6_addr *ia = arg;
3773 
3774 	dhcp6_recv(ia->iface->ctx, ia, events);
3775 }
3776 
3777 static void
3778 dhcp6_recvctx(void *arg, unsigned short events)
3779 {
3780 	struct dhcpcd_ctx *ctx = arg;
3781 
3782 	dhcp6_recv(ctx, NULL, events);
3783 }
3784 
3785 int
3786 dhcp6_openraw(void)
3787 {
3788 	int fd, v;
3789 
3790 	fd = socket(PF_INET6, SOCK_RAW | SOCK_CXNB, IPPROTO_UDP);
3791 	if (fd == -1)
3792 		return -1;
3793 
3794 	v = 1;
3795 	if (setsockopt(fd, SOL_SOCKET, SO_BROADCAST, &v, sizeof(v)) == -1)
3796 		goto errexit;
3797 
3798 	v = offsetof(struct udphdr, uh_sum);
3799 	if (setsockopt(fd, IPPROTO_IPV6, IPV6_CHECKSUM, &v, sizeof(v)) == -1)
3800 		goto errexit;
3801 
3802 	return fd;
3803 
3804 errexit:
3805 	close(fd);
3806 	return -1;
3807 }
3808 
3809 int
3810 dhcp6_openudp(unsigned int ifindex, struct in6_addr *ia)
3811 {
3812 	struct sockaddr_in6 sa;
3813 	int n, s;
3814 
3815 	s = xsocket(PF_INET6, SOCK_DGRAM | SOCK_CXNB, IPPROTO_UDP);
3816 	if (s == -1)
3817 		goto errexit;
3818 
3819 	memset(&sa, 0, sizeof(sa));
3820 	sa.sin6_family = AF_INET6;
3821 	sa.sin6_port = htons(DHCP6_CLIENT_PORT);
3822 #ifdef BSD
3823 	sa.sin6_len = sizeof(sa);
3824 #endif
3825 
3826 	if (ia != NULL) {
3827 		memcpy(&sa.sin6_addr, ia, sizeof(sa.sin6_addr));
3828 		ipv6_setscope(&sa, ifindex);
3829 	}
3830 
3831 	if (bind(s, (struct sockaddr *)&sa, sizeof(sa)) == -1)
3832 		goto errexit;
3833 
3834 	n = 1;
3835 	if (setsockopt(s, IPPROTO_IPV6, IPV6_RECVPKTINFO, &n, sizeof(n)) == -1)
3836 		goto errexit;
3837 
3838 #ifdef SO_RERROR
3839 	n = 1;
3840 	if (setsockopt(s, SOL_SOCKET, SO_RERROR, &n, sizeof(n)) == -1)
3841 		goto errexit;
3842 #endif
3843 
3844 	return s;
3845 
3846 errexit:
3847 	logerr(__func__);
3848 	if (s != -1)
3849 		close(s);
3850 	return -1;
3851 }
3852 
3853 #ifndef SMALL
3854 static void
3855 dhcp6_activateinterfaces(struct interface *ifp)
3856 {
3857 	struct interface *ifd;
3858 	size_t i, j;
3859 	struct if_ia *ia;
3860 	struct if_sla *sla;
3861 
3862 	for (i = 0; i < ifp->options->ia_len; i++) {
3863 		ia = &ifp->options->ia[i];
3864 		if (ia->ia_type != D6_OPTION_IA_PD)
3865 			continue;
3866 		for (j = 0; j < ia->sla_len; j++) {
3867 			sla = &ia->sla[j];
3868 			ifd = if_find(ifp->ctx->ifaces, sla->ifname);
3869 			if (ifd == NULL) {
3870 				logwarn("%s: cannot delegate to %s",
3871 				    ifp->name, sla->ifname);
3872 				continue;
3873 			}
3874 			if (!ifd->active) {
3875 				loginfox("%s: activating for delegation",
3876 				    sla->ifname);
3877 				dhcpcd_activateinterface(ifd,
3878 				    DHCPCD_IPV6 | DHCPCD_DHCP6);
3879 			}
3880 		}
3881 	}
3882 }
3883 #endif
3884 
3885 static void
3886 dhcp6_start1(void *arg)
3887 {
3888 	struct interface *ifp = arg;
3889 	struct dhcpcd_ctx *ctx = ifp->ctx;
3890 	struct if_options *ifo = ifp->options;
3891 	struct dhcp6_state *state;
3892 	size_t i;
3893 	const struct dhcp_compat *dhc;
3894 
3895 	if ((ctx->options & (DHCPCD_MANAGER|DHCPCD_PRIVSEP)) == DHCPCD_MANAGER &&
3896 	    ctx->dhcp6_rfd == -1)
3897 	{
3898 		ctx->dhcp6_rfd = dhcp6_openudp(0, NULL);
3899 		if (ctx->dhcp6_rfd == -1) {
3900 			logerr(__func__);
3901 			return;
3902 		}
3903 		if (eloop_event_add(ctx->eloop, ctx->dhcp6_rfd, ELE_READ,
3904 		    dhcp6_recvctx, ctx) == -1)
3905 			logerr("%s: eloop_event_add", __func__);
3906 	}
3907 
3908 	if (!IN_PRIVSEP(ctx) && ctx->dhcp6_wfd == -1) {
3909 		ctx->dhcp6_wfd = dhcp6_openraw();
3910 		if (ctx->dhcp6_wfd == -1) {
3911 			logerr(__func__);
3912 			return;
3913 		}
3914 	}
3915 
3916 	state = D6_STATE(ifp);
3917 	/* If no DHCPv6 options are configured,
3918 	   match configured DHCPv4 options to DHCPv6 equivalents. */
3919 	for (i = 0; i < sizeof(ifo->requestmask6); i++) {
3920 		if (ifo->requestmask6[i] != '\0')
3921 			break;
3922 	}
3923 	if (i == sizeof(ifo->requestmask6)) {
3924 		for (dhc = dhcp_compats; dhc->dhcp_opt; dhc++) {
3925 			if (DHC_REQ(ifo->requestmask, ifo->nomask, dhc->dhcp_opt))
3926 				add_option_mask(ifo->requestmask6,
3927 				    dhc->dhcp6_opt);
3928 		}
3929 		if (ifo->fqdn != FQDN_DISABLE || ifo->options & DHCPCD_HOSTNAME)
3930 			add_option_mask(ifo->requestmask6, D6_OPTION_FQDN);
3931 	}
3932 
3933 #ifndef SMALL
3934 	/* Rapid commit won't work with Prefix Delegation Exclusion */
3935 	if (dhcp6_findselfsla(ifp))
3936 		del_option_mask(ifo->requestmask6, D6_OPTION_RAPID_COMMIT);
3937 #endif
3938 
3939 	if (state->state == DH6S_INFORM) {
3940 		add_option_mask(ifo->requestmask6, D6_OPTION_INFO_REFRESH_TIME);
3941 		dhcp6_startinform(ifp);
3942 	} else {
3943 		del_option_mask(ifo->requestmask6, D6_OPTION_INFO_REFRESH_TIME);
3944 		dhcp6_startinit(ifp);
3945 	}
3946 
3947 #ifndef SMALL
3948 	dhcp6_activateinterfaces(ifp);
3949 #endif
3950 }
3951 
3952 int
3953 dhcp6_start(struct interface *ifp, enum DH6S init_state)
3954 {
3955 	struct dhcp6_state *state;
3956 
3957 	state = D6_STATE(ifp);
3958 	if (state != NULL) {
3959 		switch (init_state) {
3960 		case DH6S_INIT:
3961 			goto gogogo;
3962 		case DH6S_INFORM:
3963 			if (state->state == DH6S_INIT ||
3964 			    state->state == DH6S_INFORMED ||
3965 			    (state->state == DH6S_DISCOVER &&
3966 			    !(ifp->options->options & DHCPCD_IA_FORCED) &&
3967 			    !ipv6nd_hasradhcp(ifp, true)))
3968 			{
3969 				/* We don't want log spam when the RA
3970 				 * has just adjusted it's prefix times. */
3971 				if (state->state != DH6S_INFORMED)
3972 					state->new_start = true;
3973 				dhcp6_startinform(ifp);
3974 			}
3975 			break;
3976 		case DH6S_REQUEST:
3977 			if (ifp->options->options & DHCPCD_DHCP6 &&
3978 			    (state->state == DH6S_INIT ||
3979 			     state->state == DH6S_INFORM ||
3980 			     state->state == DH6S_INFORMED ||
3981 			     state->state == DH6S_DELEGATED))
3982 			{
3983 				/* Change from stateless to stateful */
3984 				init_state = DH6S_INIT;
3985 				goto gogogo;
3986 			}
3987 			break;
3988 		case DH6S_CONFIRM:
3989 			init_state = DH6S_INIT;
3990 			goto gogogo;
3991 		default:
3992 			/* Not possible, but sushes some compiler warnings. */
3993 			break;
3994 		}
3995 		return 0;
3996 	} else {
3997 		switch (init_state) {
3998 		case DH6S_CONFIRM:
3999 			/* No DHCPv6 config, no existing state
4000 			 * so nothing to do. */
4001 			return 0;
4002 		case DH6S_INFORM:
4003 			break;
4004 		default:
4005 			init_state = DH6S_INIT;
4006 			break;
4007 		}
4008 	}
4009 
4010 	if (!(ifp->options->options & DHCPCD_DHCP6))
4011 		return 0;
4012 
4013 	ifp->if_data[IF_DATA_DHCP6] = calloc(1, sizeof(*state));
4014 	state = D6_STATE(ifp);
4015 	if (state == NULL)
4016 		return -1;
4017 
4018 	state->sol_max_rt = SOL_MAX_RT;
4019 	state->inf_max_rt = INF_MAX_RT;
4020 	TAILQ_INIT(&state->addrs);
4021 
4022 gogogo:
4023 	state->new_start = true;
4024 	state->state = init_state;
4025 	state->lerror = 0;
4026 	state->failed = false;
4027 	dhcp_set_leasefile(state->leasefile, sizeof(state->leasefile),
4028 	    AF_INET6, ifp);
4029 	if (ipv6_linklocal(ifp) == NULL) {
4030 		logdebugx("%s: delaying DHCPv6 for LL address", ifp->name);
4031 		ipv6_addlinklocalcallback(ifp, dhcp6_start1, ifp);
4032 		return 0;
4033 	}
4034 
4035 	dhcp6_start1(ifp);
4036 	return 0;
4037 }
4038 
4039 void
4040 dhcp6_reboot(struct interface *ifp)
4041 {
4042 	struct dhcp6_state *state;
4043 
4044 	state = D6_STATE(ifp);
4045 	if (state == NULL)
4046 		return;
4047 
4048 	state->lerror = 0;
4049 	switch (state->state) {
4050 	case DH6S_BOUND:
4051 		dhcp6_startrebind(ifp);
4052 		break;
4053 	default:
4054 		dhcp6_startdiscoinform(ifp);
4055 		break;
4056 	}
4057 }
4058 
4059 static void
4060 dhcp6_freedrop(struct interface *ifp, int drop, const char *reason)
4061 {
4062 	struct dhcp6_state *state;
4063 	struct dhcpcd_ctx *ctx;
4064 	unsigned long long options;
4065 
4066 	if (ifp->options)
4067 		options = ifp->options->options;
4068 	else
4069 		options = ifp->ctx->options;
4070 
4071 	if (ifp->ctx->eloop)
4072 		eloop_timeout_delete(ifp->ctx->eloop, NULL, ifp);
4073 
4074 #ifndef SMALL
4075 	/* If we're dropping the lease, drop delegated addresses.
4076 	 * If, for whatever reason, we don't drop them in the future
4077 	 * then they should at least be marked as deprecated (pltime 0). */
4078 	if (drop && (options & DHCPCD_NODROP) != DHCPCD_NODROP)
4079 		dhcp6_delete_delegates(ifp);
4080 #endif
4081 
4082 	state = D6_STATE(ifp);
4083 	if (state) {
4084 		/* Failure to send the release may cause this function to
4085 		 * re-enter */
4086 		if (state->state == DH6S_RELEASE) {
4087 			dhcp6_finishrelease(ifp);
4088 			return;
4089 		}
4090 
4091 		if (drop && options & DHCPCD_RELEASE &&
4092 		    state->state != DH6S_DELEGATED)
4093 		{
4094 			if (if_is_link_up(ifp) &&
4095 			    state->state != DH6S_RELEASED &&
4096 			    state->state != DH6S_INFORMED)
4097 			{
4098 				dhcp6_startrelease(ifp);
4099 				return;
4100 			}
4101 			dhcp_unlink(ifp->ctx, state->leasefile);
4102 		}
4103 #ifdef AUTH
4104 		else if (state->auth.reconf != NULL) {
4105 			/*
4106 			 * Drop the lease as the token may only be present
4107 			 * in the initial reply message and not subsequent
4108 			 * renewals.
4109 			 * If dhcpcd is restarted, the token is lost.
4110 			 * XXX persist this in another file?
4111 			 */
4112 			dhcp_unlink(ifp->ctx, state->leasefile);
4113 		}
4114 #endif
4115 
4116 		dhcp6_freedrop_addrs(ifp, drop, NULL);
4117 		free(state->old);
4118 		state->old = state->new;
4119 		state->old_len = state->new_len;
4120 		state->new = NULL;
4121 		state->new_len = 0;
4122 		if (drop && state->old &&
4123 		    (options & DHCPCD_NODROP) != DHCPCD_NODROP)
4124 		{
4125 			if (reason == NULL)
4126 				reason = "STOP6";
4127 			script_runreason(ifp, reason);
4128 		}
4129 		free(state->old);
4130 		free(state->send);
4131 		free(state->recv);
4132 		free(state);
4133 		ifp->if_data[IF_DATA_DHCP6] = NULL;
4134 	}
4135 
4136 	/* If we don't have any more DHCP6 enabled interfaces,
4137 	 * close the global socket and release resources */
4138 	ctx = ifp->ctx;
4139 	if (ctx->ifaces) {
4140 		TAILQ_FOREACH(ifp, ctx->ifaces, next) {
4141 			if (D6_STATE(ifp))
4142 				break;
4143 		}
4144 	}
4145 	if (ifp == NULL && ctx->dhcp6_rfd != -1) {
4146 		eloop_event_delete(ctx->eloop, ctx->dhcp6_rfd);
4147 		close(ctx->dhcp6_rfd);
4148 		ctx->dhcp6_rfd = -1;
4149 	}
4150 }
4151 
4152 void
4153 dhcp6_drop(struct interface *ifp, const char *reason)
4154 {
4155 
4156 	dhcp6_freedrop(ifp, 1, reason);
4157 }
4158 
4159 void
4160 dhcp6_free(struct interface *ifp)
4161 {
4162 
4163 	dhcp6_freedrop(ifp, 0, NULL);
4164 }
4165 
4166 void
4167 dhcp6_abort(struct interface *ifp)
4168 {
4169 	struct dhcp6_state *state;
4170 #ifdef ND6_ADVERTISE
4171 	struct ipv6_addr *ia;
4172 #endif
4173 
4174 	eloop_timeout_delete(ifp->ctx->eloop, dhcp6_start1, ifp);
4175 	state = D6_STATE(ifp);
4176 	if (state == NULL)
4177 		return;
4178 
4179 #ifdef ND6_ADVERTISE
4180 	TAILQ_FOREACH(ia, &state->addrs, next) {
4181 		ipv6nd_advertise(ia);
4182 	}
4183 #endif
4184 
4185 	eloop_timeout_delete(ifp->ctx->eloop, dhcp6_startdiscover, ifp);
4186 	eloop_timeout_delete(ifp->ctx->eloop, dhcp6_senddiscover, ifp);
4187 	eloop_timeout_delete(ifp->ctx->eloop, dhcp6_startinform, ifp);
4188 	eloop_timeout_delete(ifp->ctx->eloop, dhcp6_sendinform, ifp);
4189 
4190 	switch (state->state) {
4191 	case DH6S_DISCOVER:	/* FALLTHROUGH */
4192 	case DH6S_REQUEST:	/* FALLTHROUGH */
4193 	case DH6S_INFORM:
4194 		state->state = DH6S_INIT;
4195 		break;
4196 	default:
4197 		break;
4198 	}
4199 }
4200 
4201 void
4202 dhcp6_handleifa(int cmd, struct ipv6_addr *ia, pid_t pid)
4203 {
4204 	struct dhcp6_state *state;
4205 	struct interface *ifp = ia->iface;
4206 
4207 	/* If not running in manager mode, listen to this address */
4208 	if (cmd == RTM_NEWADDR &&
4209 	    !(ia->addr_flags & IN6_IFF_NOTUSEABLE) &&
4210 	    ifp->active == IF_ACTIVE_USER &&
4211 	    !(ifp->ctx->options & DHCPCD_MANAGER) &&
4212 	    ifp->options->options & DHCPCD_DHCP6)
4213 	{
4214 #ifdef PRIVSEP
4215 		if (IN_PRIVSEP_SE(ifp->ctx)) {
4216 			if (ps_inet_opendhcp6(ia) == -1)
4217 				logerr(__func__);
4218 		} else
4219 #endif
4220 		{
4221 			if (ia->dhcp6_fd == -1)
4222 				ia->dhcp6_fd = dhcp6_openudp(ia->iface->index,
4223 				    &ia->addr);
4224 			if (ia->dhcp6_fd != -1 &&
4225 			    eloop_event_add(ia->iface->ctx->eloop,
4226 			    ia->dhcp6_fd, ELE_READ, dhcp6_recvaddr, ia) == -1)
4227 				logerr("%s: eloop_event_add", __func__);
4228 		}
4229 	}
4230 
4231 	if ((state = D6_STATE(ifp)) != NULL)
4232 		ipv6_handleifa_addrs(cmd, &state->addrs, ia, pid);
4233 }
4234 
4235 ssize_t
4236 dhcp6_env(FILE *fp, const char *prefix, const struct interface *ifp,
4237     const struct dhcp6_message *m, size_t len)
4238 {
4239 	const struct if_options *ifo;
4240 	struct dhcp_opt *opt, *vo;
4241 	const uint8_t *p;
4242 	struct dhcp6_option o;
4243 	size_t i;
4244 	char *pfx;
4245 	uint32_t en;
4246 	const struct dhcpcd_ctx *ctx;
4247 #ifndef SMALL
4248 	const struct dhcp6_state *state;
4249 	const struct ipv6_addr *ap;
4250 #endif
4251 
4252 	if (m == NULL)
4253 		goto delegated;
4254 
4255 	if (len < sizeof(*m)) {
4256 		/* Should be impossible with guards at packet in
4257 		 * and reading leases */
4258 		errno = EINVAL;
4259 		return -1;
4260 	}
4261 
4262 	ifo = ifp->options;
4263 	ctx = ifp->ctx;
4264 
4265 	/* Zero our indexes */
4266 	for (i = 0, opt = ctx->dhcp6_opts;
4267 	    i < ctx->dhcp6_opts_len;
4268 	    i++, opt++)
4269 		dhcp_zero_index(opt);
4270 	for (i = 0, opt = ifp->options->dhcp6_override;
4271 	    i < ifp->options->dhcp6_override_len;
4272 	    i++, opt++)
4273 		dhcp_zero_index(opt);
4274 	for (i = 0, opt = ctx->vivso;
4275 	    i < ctx->vivso_len;
4276 	    i++, opt++)
4277 		dhcp_zero_index(opt);
4278 	if (asprintf(&pfx, "%s_dhcp6", prefix) == -1)
4279 		return -1;
4280 
4281 	/* Unlike DHCP, DHCPv6 options *may* occur more than once.
4282 	 * There is also no provision for option concatenation unlike DHCP. */
4283 	p = (const uint8_t *)m + sizeof(*m);
4284 	len -= sizeof(*m);
4285 	for (; len != 0; p += o.len, len -= o.len) {
4286 		if (len < sizeof(o)) {
4287 			errno = EINVAL;
4288 			break;
4289 		}
4290 		memcpy(&o, p, sizeof(o));
4291 		p += sizeof(o);
4292 		len -= sizeof(o);
4293 		o.len = ntohs(o.len);
4294 		if (len < o.len) {
4295 			errno =	EINVAL;
4296 			break;
4297 		}
4298 		o.code = ntohs(o.code);
4299 		if (has_option_mask(ifo->nomask6, o.code))
4300 			continue;
4301 		for (i = 0, opt = ifo->dhcp6_override;
4302 		    i < ifo->dhcp6_override_len;
4303 		    i++, opt++)
4304 			if (opt->option == o.code)
4305 				break;
4306 		if (i == ifo->dhcp6_override_len &&
4307 		    o.code == D6_OPTION_VENDOR_OPTS &&
4308 		    o.len > sizeof(en))
4309 		{
4310 			memcpy(&en, p, sizeof(en));
4311 			en = ntohl(en);
4312 			vo = vivso_find(en, ifp);
4313 		} else
4314 			vo = NULL;
4315 		if (i == ifo->dhcp6_override_len) {
4316 			for (i = 0, opt = ctx->dhcp6_opts;
4317 			    i < ctx->dhcp6_opts_len;
4318 			    i++, opt++)
4319 				if (opt->option == o.code)
4320 					break;
4321 			if (i == ctx->dhcp6_opts_len)
4322 				opt = NULL;
4323 		}
4324 		if (opt) {
4325 			dhcp_envoption(ifp->ctx,
4326 			    fp, pfx, ifp->name,
4327 			    opt, dhcp6_getoption, p, o.len);
4328 		}
4329 		if (vo) {
4330 			dhcp_envoption(ifp->ctx,
4331 			    fp, pfx, ifp->name,
4332 			    vo, dhcp6_getoption,
4333 			    p + sizeof(en),
4334 			    o.len - sizeof(en));
4335 		}
4336 	}
4337 	free(pfx);
4338 
4339 delegated:
4340 #ifndef SMALL
4341 	/* Needed for Delegated Prefixes */
4342 	state = D6_CSTATE(ifp);
4343 	TAILQ_FOREACH(ap, &state->addrs, next) {
4344 		if (ap->delegating_prefix)
4345 			break;
4346 	}
4347 	if (ap == NULL)
4348 		return 1;
4349 	if (fprintf(fp, "%s_delegated_dhcp6_prefix=", prefix) == -1)
4350 		return -1;
4351 	TAILQ_FOREACH(ap, &state->addrs, next) {
4352 		if (ap->delegating_prefix == NULL)
4353 			continue;
4354 		if (ap != TAILQ_FIRST(&state->addrs)) {
4355 			if (fputc(' ', fp) == EOF)
4356 				return -1;
4357 		}
4358 		if (fprintf(fp, "%s", ap->saddr) == -1)
4359 			return -1;
4360 	}
4361 	if (fputc('\0', fp) == EOF)
4362 		return -1;
4363 #endif
4364 
4365 	return 1;
4366 }
4367 #endif
4368 
4369 #ifndef SMALL
4370 int
4371 dhcp6_dump(struct interface *ifp)
4372 {
4373 	struct dhcp6_state *state;
4374 
4375 	ifp->if_data[IF_DATA_DHCP6] = state = calloc(1, sizeof(*state));
4376 	if (state == NULL) {
4377 		logerr(__func__);
4378 		return -1;
4379 	}
4380 	TAILQ_INIT(&state->addrs);
4381 	if (dhcp6_readlease(ifp, 0) == -1) {
4382 		logerr("dhcp6_readlease");
4383 		return -1;
4384 	}
4385 	state->reason = "DUMP6";
4386 	return script_runreason(ifp, state->reason);
4387 }
4388 #endif
4389