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