xref: /minix/external/bsd/dhcpcd/dist/dhcp6.c (revision fb9c64b2)
1 #include <sys/cdefs.h>
2  __RCSID("$NetBSD: dhcp6.c,v 1.15 2015/08/21 10:39:00 roy Exp $");
3 
4 /*
5  * dhcpcd - DHCP client daemon
6  * Copyright (c) 2006-2015 Roy Marples <roy@marples.name>
7  * All rights reserved
8 
9  * Redistribution and use in source and binary forms, with or without
10  * modification, are permitted provided that the following conditions
11  * are met:
12  * 1. Redistributions of source code must retain the above copyright
13  *    notice, this list of conditions and the following disclaimer.
14  * 2. Redistributions in binary form must reproduce the above copyright
15  *    notice, this list of conditions and the following disclaimer in the
16  *    documentation and/or other materials provided with the distribution.
17  *
18  * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND
19  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
20  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
21  * ARE DISCLAIMED.  IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
22  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
23  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
24  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
25  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
26  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
27  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
28  * SUCH DAMAGE.
29  */
30 
31 /* TODO: We should decline dupliate addresses detected */
32 
33 #include <sys/stat.h>
34 #include <sys/utsname.h>
35 
36 #include <netinet/in.h>
37 
38 #include <assert.h>
39 #include <ctype.h>
40 #include <errno.h>
41 #include <fcntl.h>
42 #include <inttypes.h>
43 #include <stdlib.h>
44 #include <string.h>
45 #include <unistd.h>
46 #include <fcntl.h>
47 
48 #define ELOOP_QUEUE 4
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 "script.h"
59 
60 #ifndef __UNCONST
61 #define __UNCONST(a) ((void *)(unsigned long)(const void *)(a))
62 #endif
63 
64 /* DHCPCD Project has been assigned an IANA PEN of 40712 */
65 #define DHCPCD_IANA_PEN 40712
66 
67 /* Unsure if I want this */
68 //#define VENDOR_SPLIT
69 
70 /* Support older systems with different defines */
71 #if !defined(IPV6_RECVPKTINFO) && defined(IPV6_PKTINFO)
72 #define IPV6_RECVPKTINFO IPV6_PKTINFO
73 #endif
74 
75 struct dhcp6_op {
76 	uint16_t type;
77 	const char *name;
78 };
79 
80 static const struct dhcp6_op dhcp6_ops[] = {
81 	{ DHCP6_SOLICIT, "SOLICIT6" },
82 	{ DHCP6_ADVERTISE, "ADVERTISE6" },
83 	{ DHCP6_REQUEST, "REQUEST6" },
84 	{ DHCP6_REPLY, "REPLY6" },
85 	{ DHCP6_RENEW, "RENEW6" },
86 	{ DHCP6_REBIND, "REBIND6" },
87 	{ DHCP6_CONFIRM, "CONFIRM6" },
88 	{ DHCP6_INFORMATION_REQ, "INFORM6" },
89 	{ DHCP6_RELEASE, "RELEASE6" },
90 	{ DHCP6_RECONFIGURE, "RECONFIURE6" },
91 	{ 0, NULL }
92 };
93 
94 struct dhcp_compat {
95 	uint8_t dhcp_opt;
96 	uint16_t dhcp6_opt;
97 };
98 
99 const struct dhcp_compat dhcp_compats[] = {
100 	{ DHO_DNSSERVER,	D6_OPTION_DNS_SERVERS },
101 	{ DHO_HOSTNAME,		D6_OPTION_FQDN },
102 	{ DHO_DNSDOMAIN,	D6_OPTION_FQDN },
103 	{ DHO_NISSERVER,	D6_OPTION_NIS_SERVERS },
104 	{ DHO_NTPSERVER,	D6_OPTION_SNTP_SERVERS },
105 	{ DHO_RAPIDCOMMIT,	D6_OPTION_RAPID_COMMIT },
106 	{ DHO_FQDN,		D6_OPTION_FQDN },
107 	{ DHO_VIVCO,		D6_OPTION_VENDOR_CLASS },
108 	{ DHO_VIVSO,		D6_OPTION_VENDOR_OPTS },
109 	{ DHO_DNSSEARCH,	D6_OPTION_DOMAIN_LIST },
110 	{ 0, 0 }
111 };
112 
113 static const char * const dhcp6_statuses[] = {
114 	"Success",
115 	"Unspecified Failure",
116 	"No Addresses Available",
117 	"No Binding",
118 	"Not On Link",
119 	"Use Multicast"
120 };
121 
122 struct dhcp6_ia_addr {
123 	struct in6_addr addr;
124 	uint32_t pltime;
125 	uint32_t vltime;
126 } __packed;
127 
128 struct dhcp6_pd_addr {
129 	uint32_t pltime;
130 	uint32_t vltime;
131 	uint8_t prefix_len;
132 	struct in6_addr prefix;
133 } __packed;
134 
135 void
136 dhcp6_printoptions(const struct dhcpcd_ctx *ctx,
137     const struct dhcp_opt *opts, size_t opts_len)
138 {
139 	size_t i, j;
140 	const struct dhcp_opt *opt, *opt2;
141 	int cols;
142 
143 	for (i = 0, opt = ctx->dhcp6_opts;
144 	    i < ctx->dhcp6_opts_len; i++, opt++)
145 	{
146 		for (j = 0, opt2 = opts; j < opts_len; j++, opt2++)
147 			if (opt2->option == opt->option)
148 				break;
149 		if (j == opts_len) {
150 			cols = printf("%05d %s", opt->option, opt->var);
151 			dhcp_print_option_encoding(opt, cols);
152 		}
153 	}
154 	for (i = 0, opt = opts; i < opts_len; i++, opt++) {
155 		cols = printf("%05d %s", opt->option, opt->var);
156 		dhcp_print_option_encoding(opt, cols);
157 	}
158 }
159 
160 static size_t
161 dhcp6_makevendor(struct dhcp6_option *o, const struct interface *ifp)
162 {
163 	const struct if_options *ifo;
164 	size_t len, i;
165 	uint8_t *p;
166 	uint16_t u16;
167 	uint32_t u32;
168 	ssize_t vlen;
169 	const struct vivco *vivco;
170 	char vendor[VENDORCLASSID_MAX_LEN];
171 
172 	ifo = ifp->options;
173 	len = sizeof(uint32_t); /* IANA PEN */
174 	if (ifo->vivco_en) {
175 		for (i = 0, vivco = ifo->vivco;
176 		    i < ifo->vivco_len;
177 		    i++, vivco++)
178 			len += sizeof(uint16_t) + vivco->len;
179 		vlen = 0; /* silence bogus gcc warning */
180 	} else {
181 		vlen = dhcp_vendor(vendor, sizeof(vendor));
182 		if (vlen == -1)
183 			vlen = 0;
184 		else
185 			len += sizeof(uint16_t) + (size_t)vlen;
186 	}
187 
188 	if (len > UINT16_MAX) {
189 		logger(ifp->ctx, LOG_ERR,
190 		    "%s: DHCPv6 Vendor Class too big", ifp->name);
191 		return 0;
192 	}
193 
194 	if (o) {
195 		o->code = htons(D6_OPTION_VENDOR_CLASS);
196 		o->len = htons((uint16_t)len);
197 		p = D6_OPTION_DATA(o);
198 		u32 = htonl(ifo->vivco_en ? ifo->vivco_en : DHCPCD_IANA_PEN);
199 		memcpy(p, &u32, sizeof(u32));
200 		p += sizeof(u32);
201 		if (ifo->vivco_en) {
202 			for (i = 0, vivco = ifo->vivco;
203 			    i < ifo->vivco_len;
204 			    i++, vivco++)
205 			{
206 				u16 = htons((uint16_t)vivco->len);
207 				memcpy(p, &u16, sizeof(u16));
208 				p += sizeof(u16);
209 				memcpy(p, vivco->data, vivco->len);
210 				p += vivco->len;
211 			}
212 		} else if (vlen) {
213 			u16 = htons((uint16_t)vlen);
214 			memcpy(p, &u16, sizeof(u16));
215 			p += sizeof(u16);
216 			memcpy(p, vendor, (size_t)vlen);
217 		}
218 	}
219 
220 	return len;
221 }
222 
223 static const struct dhcp6_option *
224 dhcp6_findoption(uint16_t code, const uint8_t *d, size_t len)
225 {
226 	const struct dhcp6_option *o;
227 	size_t ol;
228 
229 	code = htons(code);
230 	for (o = (const struct dhcp6_option *)d;
231 	    len >= sizeof(*o);
232 	    o = D6_CNEXT_OPTION(o))
233 	{
234 		ol = sizeof(*o) + ntohs(o->len);
235 		if (ol > len) {
236 			errno = EINVAL;
237 			return NULL;
238 		}
239 		if (o->code == code)
240 			return o;
241 		len -= ol;
242 	}
243 
244 	errno = ESRCH;
245 	return NULL;
246 }
247 
248 static const uint8_t *
249 dhcp6_getoption(struct dhcpcd_ctx *ctx,
250     size_t *os, unsigned int *code, size_t *len,
251     const uint8_t *od, size_t ol, struct dhcp_opt **oopt)
252 {
253 	const struct dhcp6_option *o;
254 	size_t i;
255 	struct dhcp_opt *opt;
256 
257 	if (od) {
258 		*os = sizeof(*o);
259 		if (ol < *os) {
260 			errno = EINVAL;
261 			return NULL;
262 		}
263 		o = (const struct dhcp6_option *)od;
264 		*len = ntohs(o->len);
265 		if (*len > ol) {
266 			errno = EINVAL;
267 			return NULL;
268 		}
269 		*code = ntohs(o->code);
270 	} else
271 		o = NULL;
272 
273 	for (i = 0, opt = ctx->dhcp6_opts;
274 	    i < ctx->dhcp6_opts_len; i++, opt++)
275 	{
276 		if (opt->option == *code) {
277 			*oopt = opt;
278 			break;
279 		}
280 	}
281 
282 	if (o)
283 		return D6_COPTION_DATA(o);
284 	return NULL;
285 }
286 
287 static const struct dhcp6_option *
288 dhcp6_getmoption(uint16_t code, const struct dhcp6_message *m, size_t len)
289 {
290 
291 	if (len < sizeof(*m)) {
292 		errno = EINVAL;
293 		return NULL;
294 	}
295 	len -= sizeof(*m);
296 	return dhcp6_findoption(code,
297 	    (const uint8_t *)D6_CFIRST_OPTION(m), len);
298 }
299 
300 static int
301 dhcp6_updateelapsed(struct interface *ifp, struct dhcp6_message *m, size_t len)
302 {
303 	struct dhcp6_state *state;
304 	const struct dhcp6_option *co;
305 	struct dhcp6_option *o;
306 	struct timespec tv;
307 	time_t hsec;
308 	uint16_t u16;
309 
310 	co = dhcp6_getmoption(D6_OPTION_ELAPSED, m, len);
311 	if (co == NULL)
312 		return -1;
313 
314 	o = __UNCONST(co);
315 	state = D6_STATE(ifp);
316 	clock_gettime(CLOCK_MONOTONIC, &tv);
317 	if (state->RTC == 0) {
318 		/* An RTC of zero means we're the first message
319 		 * out of the door, so the elapsed time is zero. */
320 		state->started = tv;
321 		hsec = 0;
322 	} else {
323 		timespecsub(&tv, &state->started, &tv);
324 		/* Elapsed time is measured in centiseconds.
325 		 * We need to be sure it will not potentially overflow. */
326 		if (tv.tv_sec >= (UINT16_MAX / CSEC_PER_SEC) + 1)
327 			hsec = UINT16_MAX;
328 		else {
329 			hsec = (tv.tv_sec * CSEC_PER_SEC) +
330 			    (tv.tv_nsec / NSEC_PER_CSEC);
331 			if (hsec > UINT16_MAX)
332 				hsec = UINT16_MAX;
333 		}
334 	}
335 	u16 = htons((uint16_t)hsec);
336 	memcpy(D6_OPTION_DATA(o), &u16, sizeof(u16));
337 	return 0;
338 }
339 
340 static void
341 dhcp6_newxid(const struct interface *ifp, struct dhcp6_message *m)
342 {
343 	uint32_t xid;
344 
345 	if (ifp->options->options & DHCPCD_XID_HWADDR &&
346 	    ifp->hwlen >= sizeof(xid))
347 		/* The lower bits are probably more unique on the network */
348 		memcpy(&xid, (ifp->hwaddr + ifp->hwlen) - sizeof(xid),
349 		    sizeof(xid));
350 	else
351 		xid = arc4random();
352 
353 	m->xid[0] = (xid >> 16) & 0xff;
354 	m->xid[1] = (xid >> 8) & 0xff;
355 	m->xid[2] = xid & 0xff;
356 }
357 
358 static const struct if_sla *
359 dhcp6_findselfsla(struct interface *ifp, const uint8_t *iaid)
360 {
361 	size_t i, j;
362 
363 	for (i = 0; i < ifp->options->ia_len; i++) {
364 		if (iaid == NULL ||
365 		    memcmp(&ifp->options->ia[i].iaid, iaid,
366 		    sizeof(ifp->options->ia[i].iaid)) == 0)
367 		{
368 			for (j = 0; j < ifp->options->ia[i].sla_len; j++) {
369 				if (strcmp(ifp->options->ia[i].sla[j].ifname,
370 				    ifp->name) == 0)
371 					return &ifp->options->ia[i].sla[j];
372 			}
373 		}
374 	}
375 	return NULL;
376 }
377 
378 
379 #ifndef ffs32
380 static int
381 ffs32(uint32_t n)
382 {
383 	int v;
384 
385 	if (!n)
386 		return 0;
387 
388 	v = 1;
389 	if ((n & 0x0000FFFFU) == 0) {
390 		n >>= 16;
391 		v += 16;
392 	}
393 	if ((n & 0x000000FFU) == 0) {
394 		n >>= 8;
395 		v += 8;
396 	}
397 	if ((n & 0x0000000FU) == 0) {
398 		n >>= 4;
399 		v += 4;
400 	}
401 	if ((n & 0x00000003U) == 0) {
402 		n >>= 2;
403 		v += 2;
404 	}
405 	if ((n & 0x00000001U) == 0)
406 		v += 1;
407 
408 	return v;
409 }
410 #endif
411 
412 static int
413 dhcp6_delegateaddr(struct in6_addr *addr, struct interface *ifp,
414     const struct ipv6_addr *prefix, const struct if_sla *sla, struct if_ia *ia)
415 {
416 	struct dhcp6_state *state;
417 	struct if_sla asla;
418 	char sabuf[INET6_ADDRSTRLEN];
419 	const char *sa;
420 
421 	state = D6_STATE(ifp);
422 	if (state == NULL) {
423 		ifp->if_data[IF_DATA_DHCP6] = calloc(1, sizeof(*state));
424 		state = D6_STATE(ifp);
425 		if (state == NULL) {
426 			logger(ifp->ctx, LOG_ERR, "%s: %m", __func__);
427 			return -1;
428 		}
429 
430 		TAILQ_INIT(&state->addrs);
431 		state->state = DH6S_DELEGATED;
432 		state->reason = "DELEGATED6";
433 	}
434 
435 	if (sla == NULL || sla->sla_set == 0) {
436 		asla.sla = ifp->index;
437 		asla.prefix_len = 0;
438 		sla = &asla;
439 	} else if (sla->prefix_len == 0) {
440 		asla.sla = sla->sla;
441 		if (asla.sla == 0)
442 			asla.prefix_len = prefix->prefix_len;
443 		else
444 			asla.prefix_len = 0;
445 		sla = &asla;
446 	}
447 	if (sla->prefix_len == 0) {
448 		uint32_t sla_max;
449 		int bits;
450 
451 		if (ia->sla_max == 0) {
452 			const struct interface *ifi;
453 
454 			sla_max = 0;
455 			TAILQ_FOREACH(ifi, ifp->ctx->ifaces, next) {
456 				if (ifi != ifp && ifi->index > sla_max)
457 					sla_max = ifi->index;
458 			}
459 		} else
460 			sla_max = ia->sla_max;
461 
462 		bits = ffs32(sla_max);
463 
464 		if (prefix->prefix_len + bits > UINT8_MAX)
465 			asla.prefix_len = UINT8_MAX;
466 		else {
467 			asla.prefix_len = (uint8_t)(prefix->prefix_len + bits);
468 
469 			/* Make a 64 prefix by default, as this maks SLAAC
470 			 * possible. Otherwise round up to the nearest octet. */
471 			if (asla.prefix_len <= 64)
472 				asla.prefix_len = 64;
473 			else
474 				asla.prefix_len = (uint8_t)ROUNDUP8(asla.prefix_len);
475 
476 		}
477 
478 #define BIT(n) (1l << (n))
479 #define BIT_MASK(len) (BIT(len) - 1)
480 		if (ia->sla_max == 0)
481 			/* Work out the real sla_max from our bits used */
482 			ia->sla_max = (uint32_t)BIT_MASK(asla.prefix_len -
483 			    prefix->prefix_len);
484 	}
485 
486 	if (ipv6_userprefix(&prefix->prefix, prefix->prefix_len,
487 		sla->sla, addr, sla->prefix_len) == -1)
488 	{
489 		sa = inet_ntop(AF_INET6, &prefix->prefix,
490 		    sabuf, sizeof(sabuf));
491 		logger(ifp->ctx, LOG_ERR,
492 		    "%s: invalid prefix %s/%d + %d/%d: %m",
493 		    ifp->name, sa, prefix->prefix_len,
494 		    sla->sla, sla->prefix_len);
495 		return -1;
496 	}
497 
498 	if (prefix->prefix_exclude_len &&
499 	    IN6_ARE_ADDR_EQUAL(addr, &prefix->prefix_exclude))
500 	{
501 		sa = inet_ntop(AF_INET6, &prefix->prefix_exclude,
502 		    sabuf, sizeof(sabuf));
503 		logger(ifp->ctx, LOG_ERR,
504 		    "%s: cannot delegate excluded prefix %s/%d",
505 		    ifp->name, sa, prefix->prefix_exclude_len);
506 		return -1;
507 	}
508 
509 	return sla->prefix_len;
510 }
511 
512 int
513 dhcp6_has_public_addr(const struct interface *ifp)
514 {
515 	const struct dhcp6_state *state = D6_CSTATE(ifp);
516 	const struct ipv6_addr *ia;
517 
518 	if (state == NULL)
519 		return 0;
520 	TAILQ_FOREACH(ia, &state->addrs, next) {
521 		if (ipv6_publicaddr(ia))
522 			return 1;
523 	}
524 	return 0;
525 }
526 
527 static int
528 dhcp6_makemessage(struct interface *ifp)
529 {
530 	struct dhcp6_state *state;
531 	struct dhcp6_message *m;
532 	struct dhcp6_option *o, *so, *eo;
533 	const struct dhcp6_option *si, *unicast;
534 	size_t l, n, len, ml;
535 	uint8_t u8, type;
536 	uint16_t u16, n_options, auth_len;
537 	struct if_options *ifo;
538 	const struct dhcp_opt *opt, *opt2;
539 	uint8_t IA, *p;
540 	const uint8_t *pp;
541 	uint32_t u32;
542 	const struct ipv6_addr *ap;
543 	char hbuf[HOSTNAME_MAX_LEN + 1];
544 	const char *hostname;
545 	int fqdn;
546 	struct dhcp6_ia_addr *iap;
547 	struct dhcp6_pd_addr *pdp;
548 
549 	state = D6_STATE(ifp);
550 	if (state->send) {
551 		free(state->send);
552 		state->send = NULL;
553 	}
554 
555 	ifo = ifp->options;
556 	fqdn = ifo->fqdn;
557 
558 	if (fqdn == FQDN_DISABLE && ifo->options & DHCPCD_HOSTNAME) {
559 		/* We're sending the DHCPv4 hostname option, so send FQDN as
560 		 * DHCPv6 has no FQDN option and DHCPv4 must not send
561 		 * hostname and FQDN according to RFC4702 */
562 		fqdn = FQDN_BOTH;
563 	}
564 	if (fqdn != FQDN_DISABLE) {
565 		if (ifo->hostname[0] == '\0')
566 			hostname = get_hostname(hbuf, sizeof(hbuf),
567 			    ifo->options & DHCPCD_HOSTNAME_SHORT ? 1 : 0);
568 		else
569 			hostname = ifo->hostname;
570 	} else
571 		hostname = NULL; /* appearse gcc */
572 
573 	/* Work out option size first */
574 	n_options = 0;
575 	len = 0;
576 	si = NULL;
577 	if (state->state != DH6S_RELEASE) {
578 		for (l = 0, opt = ifp->ctx->dhcp6_opts;
579 		    l < ifp->ctx->dhcp6_opts_len;
580 		    l++, opt++)
581 		{
582 			for (n = 0, opt2 = ifo->dhcp6_override;
583 			    n < ifo->dhcp6_override_len;
584 			    n++, opt2++)
585 			{
586 				if (opt->option == opt2->option)
587 					break;
588 			}
589 			if (n < ifo->dhcp6_override_len)
590 			    continue;
591 			if (!(opt->type & NOREQ) &&
592 			    (opt->type & REQUEST ||
593 			    has_option_mask(ifo->requestmask6, opt->option)))
594 			{
595 				n_options++;
596 				len += sizeof(u16);
597 			}
598 		}
599 		for (l = 0, opt = ifo->dhcp6_override;
600 		    l < ifo->dhcp6_override_len;
601 		    l++, opt++)
602 		{
603 			if (!(opt->type & NOREQ) &&
604 			    (opt->type & REQUEST ||
605 			    has_option_mask(ifo->requestmask6, opt->option)))
606 			{
607 				n_options++;
608 				len += sizeof(u16);
609 			}
610 		}
611 		if (dhcp6_findselfsla(ifp, NULL)) {
612 			n_options++;
613 			len += sizeof(u16);
614 		}
615 		if (len)
616 			len += sizeof(*o);
617 
618 		if (fqdn != FQDN_DISABLE)
619 			len += sizeof(*o) + 1 + encode_rfc1035(hostname, NULL);
620 
621 		if ((ifo->auth.options & DHCPCD_AUTH_SENDREQUIRE) !=
622 		    DHCPCD_AUTH_SENDREQUIRE)
623 			len += sizeof(*o); /* Reconfigure Accept */
624 	}
625 
626 	len += sizeof(*state->send);
627 	len += sizeof(*o) + ifp->ctx->duid_len;
628 	len += sizeof(*o) + sizeof(uint16_t); /* elapsed */
629 	len += sizeof(*o) + dhcp6_makevendor(NULL, ifp);
630 
631 	/* IA */
632 	m = NULL;
633 	ml = 0;
634 	switch(state->state) {
635 	case DH6S_REQUEST:
636 		m = state->recv;
637 		ml = state->recv_len;
638 		/* FALLTHROUGH */
639 	case DH6S_RELEASE:
640 		/* FALLTHROUGH */
641 	case DH6S_RENEW:
642 		if (m == NULL) {
643 			m = state->new;
644 			ml = state->new_len;
645 		}
646 		si = dhcp6_getmoption(D6_OPTION_SERVERID, m, ml);
647 		if (si == NULL) {
648 			errno = ESRCH;
649 			return -1;
650 		}
651 		len += sizeof(*si) + ntohs(si->len);
652 		/* FALLTHROUGH */
653 	case DH6S_REBIND:
654 		/* FALLTHROUGH */
655 	case DH6S_CONFIRM:
656 		/* FALLTHROUGH */
657 	case DH6S_DISCOVER:
658 		if (m == NULL) {
659 			m = state->new;
660 			ml = state->new_len;
661 		}
662 		TAILQ_FOREACH(ap, &state->addrs, next) {
663 			if (ap->prefix_vltime == 0 &&
664 			    !(ap->flags & IPV6_AF_REQUEST))
665 				continue;
666 			if (ap->ia_type == D6_OPTION_IA_PD) {
667 				len += sizeof(*o) + sizeof(u8) +
668 				    sizeof(u32) + sizeof(u32) +
669 				    sizeof(ap->prefix);
670 				if (ap->prefix_exclude_len)
671 					len += sizeof(*o) + 1 +
672 					    (uint8_t)((ap->prefix_exclude_len -
673 					    ap->prefix_len - 1) / NBBY) + 1;
674 			} else
675 				len += sizeof(*o) + sizeof(ap->addr) +
676 				    sizeof(u32) + sizeof(u32);
677 		}
678 		/* FALLTHROUGH */
679 	case DH6S_INIT:
680 		len += ifo->ia_len * (sizeof(*o) + (sizeof(u32) * 3));
681 		IA = 1;
682 		break;
683 	default:
684 		IA = 0;
685 	}
686 
687 	if (state->state == DH6S_DISCOVER &&
688 	    !(ifp->ctx->options & DHCPCD_TEST) &&
689 	    has_option_mask(ifo->requestmask6, D6_OPTION_RAPID_COMMIT))
690 		len += sizeof(*o);
691 
692 	if (m == NULL) {
693 		m = state->new;
694 		ml = state->new_len;
695 	}
696 	unicast = NULL;
697 	/* Depending on state, get the unicast address */
698 	switch(state->state) {
699 		break;
700 	case DH6S_INIT: /* FALLTHROUGH */
701 	case DH6S_DISCOVER:
702 		type = DHCP6_SOLICIT;
703 		break;
704 	case DH6S_REQUEST:
705 		type = DHCP6_REQUEST;
706 		unicast = dhcp6_getmoption(D6_OPTION_UNICAST, m, ml);
707 		break;
708 	case DH6S_CONFIRM:
709 		type = DHCP6_CONFIRM;
710 		break;
711 	case DH6S_REBIND:
712 		type = DHCP6_REBIND;
713 		break;
714 	case DH6S_RENEW:
715 		type = DHCP6_RENEW;
716 		unicast = dhcp6_getmoption(D6_OPTION_UNICAST, m, ml);
717 		break;
718 	case DH6S_INFORM:
719 		type = DHCP6_INFORMATION_REQ;
720 		break;
721 	case DH6S_RELEASE:
722 		type = DHCP6_RELEASE;
723 		unicast = dhcp6_getmoption(D6_OPTION_UNICAST, m, ml);
724 		break;
725 	default:
726 		errno = EINVAL;
727 		return -1;
728 	}
729 
730 	auth_len = 0;
731 	if (ifo->auth.options & DHCPCD_AUTH_SEND) {
732 		ssize_t alen = dhcp_auth_encode(&ifo->auth,
733 		    state->auth.token, NULL, 0, 6, type, NULL, 0);
734 		if (alen != -1 && alen > UINT16_MAX) {
735 			errno = ERANGE;
736 			alen = -1;
737 		}
738 		if (alen == -1)
739 			logger(ifp->ctx, LOG_ERR,
740 			    "%s: dhcp_auth_encode: %m", ifp->name);
741 		else if (alen != 0) {
742 			auth_len = (uint16_t)alen;
743 			len += sizeof(*o) + auth_len;
744 		}
745 	}
746 
747 	state->send = malloc(len);
748 	if (state->send == NULL)
749 		return -1;
750 
751 	state->send_len = len;
752 	state->send->type = type;
753 
754 	/* If we found a unicast option, copy it to our state for sending */
755 	if (unicast && ntohs(unicast->len) == sizeof(state->unicast))
756 		memcpy(&state->unicast, D6_COPTION_DATA(unicast),
757 		    sizeof(state->unicast));
758 	else
759 		state->unicast = in6addr_any;
760 
761 	dhcp6_newxid(ifp, state->send);
762 
763 	o = D6_FIRST_OPTION(state->send);
764 	o->code = htons(D6_OPTION_CLIENTID);
765 	o->len = htons((uint16_t)ifp->ctx->duid_len);
766 	memcpy(D6_OPTION_DATA(o), ifp->ctx->duid, ifp->ctx->duid_len);
767 
768 	if (si) {
769 		o = D6_NEXT_OPTION(o);
770 		memcpy(o, si, sizeof(*si) + ntohs(si->len));
771 	}
772 
773 	o = D6_NEXT_OPTION(o);
774 	o->code = htons(D6_OPTION_ELAPSED);
775 	o->len = htons(sizeof(uint16_t));
776 	p = D6_OPTION_DATA(o);
777 	memset(p, 0, sizeof(uint16_t));
778 
779 	o = D6_NEXT_OPTION(o);
780 	dhcp6_makevendor(o, ifp);
781 
782 	if (state->state == DH6S_DISCOVER &&
783 	    !(ifp->ctx->options & DHCPCD_TEST) &&
784 	    has_option_mask(ifo->requestmask6, D6_OPTION_RAPID_COMMIT))
785 	{
786 		o = D6_NEXT_OPTION(o);
787 		o->code = htons(D6_OPTION_RAPID_COMMIT);
788 		o->len = 0;
789 	}
790 
791 	for (l = 0; IA && l < ifo->ia_len; l++) {
792 		o = D6_NEXT_OPTION(o);
793 		o->code = htons(ifo->ia[l].ia_type);
794 		o->len = htons(sizeof(u32) + sizeof(u32) + sizeof(u32));
795 		p = D6_OPTION_DATA(o);
796 		memcpy(p, ifo->ia[l].iaid, sizeof(u32));
797 		p += sizeof(u32);
798 		memset(p, 0, sizeof(u32) + sizeof(u32));
799 		TAILQ_FOREACH(ap, &state->addrs, next) {
800 			if (ap->prefix_vltime == 0 &&
801 			    !(ap->flags & IPV6_AF_REQUEST))
802 				continue;
803 			if (memcmp(ifo->ia[l].iaid, ap->iaid, sizeof(u32)))
804 				continue;
805 			so = D6_NEXT_OPTION(o);
806 			if (ap->ia_type == D6_OPTION_IA_PD) {
807 				so->code = htons(D6_OPTION_IAPREFIX);
808 				so->len = htons(sizeof(ap->prefix) +
809 				    sizeof(u32) + sizeof(u32) + sizeof(u8));
810 				pdp = (struct dhcp6_pd_addr *)
811 				    D6_OPTION_DATA(so);
812 				pdp->pltime = htonl(ap->prefix_pltime);
813 				pdp->vltime = htonl(ap->prefix_vltime);
814 				pdp->prefix_len = ap->prefix_len;
815 				pdp->prefix = ap->prefix;
816 
817 				/* RFC6603 Section 4.2 */
818 				if (ap->prefix_exclude_len) {
819 					n = (size_t)((ap->prefix_exclude_len -
820 					    ap->prefix_len - 1) / NBBY) + 1;
821 					eo = D6_NEXT_OPTION(so);
822 					eo->code = htons(D6_OPTION_PD_EXCLUDE);
823 					eo->len = (uint16_t)(n + 1);
824 					p = D6_OPTION_DATA(eo);
825 					*p++ = (uint8_t)ap->prefix_exclude_len;
826 					pp = ap->prefix_exclude.s6_addr;
827 					pp += (size_t)((ap->prefix_len - 1) / NBBY)
828 					    + (n - 1);
829 					u8 = ap->prefix_len % NBBY;
830 					if (u8)
831 						n--;
832 					while (n-- > 0)
833 						*p++ = *pp--;
834 					if (u8)
835 						*p = (uint8_t)(*pp << u8);
836 					u16 = (uint16_t)(ntohs(so->len) +
837 					    sizeof(*eo) + eo->len);
838 					so->len = htons(u16);
839 					eo->len = htons(eo->len);
840 				}
841 
842 				u16 = (uint16_t)(ntohs(o->len) + sizeof(*so)
843 				    + ntohs(so->len));
844 				o->len = htons(u16);
845 			} else {
846 				so->code = htons(D6_OPTION_IA_ADDR);
847 				so->len = sizeof(ap->addr) +
848 				    sizeof(u32) + sizeof(u32);
849 				iap = (struct dhcp6_ia_addr *)
850 				    D6_OPTION_DATA(so);
851 				iap->addr = ap->addr;
852 				iap->pltime = htonl(ap->prefix_pltime);
853 				iap->vltime = htonl(ap->prefix_vltime);
854 				u16 = (uint16_t)(ntohs(o->len) + sizeof(*so)
855 				    + so->len);
856 				so->len = htons(so->len);
857 				o->len = htons(u16);
858 			}
859 		}
860 	}
861 
862 	if (state->send->type != DHCP6_RELEASE) {
863 		if (fqdn != FQDN_DISABLE) {
864 			o = D6_NEXT_OPTION(o);
865 			o->code = htons(D6_OPTION_FQDN);
866 			p = D6_OPTION_DATA(o);
867 			switch (fqdn) {
868 			case FQDN_BOTH:
869 				*p = D6_FQDN_BOTH;
870 				break;
871 			case FQDN_PTR:
872 				*p = D6_FQDN_PTR;
873 				break;
874 			default:
875 				*p = D6_FQDN_NONE;
876 				break;
877 			}
878 			l = encode_rfc1035(hostname, p + 1);
879 			if (l == 0)
880 				*p = D6_FQDN_NONE;
881 			o->len = htons((uint16_t)(l + 1));
882 		}
883 
884 		if ((ifo->auth.options & DHCPCD_AUTH_SENDREQUIRE) !=
885 		    DHCPCD_AUTH_SENDREQUIRE)
886 		{
887 			o = D6_NEXT_OPTION(o);
888 			o->code = htons(D6_OPTION_RECONF_ACCEPT);
889 			o->len = 0;
890 		}
891 
892 		if (n_options) {
893 			o = D6_NEXT_OPTION(o);
894 			o->code = htons(D6_OPTION_ORO);
895 			o->len = 0;
896 			p = D6_OPTION_DATA(o);
897 			for (l = 0, opt = ifp->ctx->dhcp6_opts;
898 			    l < ifp->ctx->dhcp6_opts_len;
899 			    l++, opt++)
900 			{
901 				for (n = 0, opt2 = ifo->dhcp6_override;
902 				    n < ifo->dhcp6_override_len;
903 				    n++, opt2++)
904 				{
905 					if (opt->option == opt2->option)
906 						break;
907 				}
908 				if (n < ifo->dhcp6_override_len)
909 				    continue;
910 				if (!(opt->type & NOREQ) &&
911 				    (opt->type & REQUEST ||
912 				    has_option_mask(ifo->requestmask6,
913 				        opt->option)))
914 				{
915 					u16 = htons((uint16_t)opt->option);
916 					memcpy(p, &u16, sizeof(u16));
917 					p += sizeof(u16);
918 					o->len = (uint16_t)(o->len + sizeof(u16));
919 				}
920 			}
921 			for (l = 0, opt = ifo->dhcp6_override;
922 			    l < ifo->dhcp6_override_len;
923 			    l++, opt++)
924 			{
925 				if (!(opt->type & NOREQ) &&
926 				    (opt->type & REQUEST ||
927 				    has_option_mask(ifo->requestmask6,
928 				        opt->option)))
929 				{
930 					u16 = htons((uint16_t)opt->option);
931 					memcpy(p, &u16, sizeof(u16));
932 					p += sizeof(u16);
933 					o->len = (uint16_t)(o->len + sizeof(u16));
934 				}
935 			}
936 			if (dhcp6_findselfsla(ifp, NULL)) {
937 				u16 = htons(D6_OPTION_PD_EXCLUDE);
938 				memcpy(p, &u16, sizeof(u16));
939 				o->len = (uint16_t)(o->len + sizeof(u16));
940 			}
941 			o->len = htons(o->len);
942 		}
943 	}
944 
945 	/* This has to be the last option */
946 	if (ifo->auth.options & DHCPCD_AUTH_SEND && auth_len != 0) {
947 		o = D6_NEXT_OPTION(o);
948 		o->code = htons(D6_OPTION_AUTH);
949 		o->len = htons((uint16_t)auth_len);
950 		/* data will be filled at send message time */
951 	}
952 
953 	return 0;
954 }
955 
956 static const char *
957 dhcp6_get_op(uint16_t type)
958 {
959 	const struct dhcp6_op *d;
960 
961 	for (d = dhcp6_ops; d->name; d++)
962 		if (d->type == type)
963 			return d->name;
964 	return NULL;
965 }
966 
967 static void
968 dhcp6_freedrop_addrs(struct interface *ifp, int drop,
969     const struct interface *ifd)
970 {
971 	struct dhcp6_state *state;
972 
973 	state = D6_STATE(ifp);
974 	if (state) {
975 		ipv6_freedrop_addrs(&state->addrs, drop, ifd);
976 		if (drop)
977 			ipv6_buildroutes(ifp->ctx);
978 	}
979 }
980 
981 static void dhcp6_delete_delegates(struct interface *ifp)
982 {
983 	struct interface *ifp0;
984 
985 	if (ifp->ctx->ifaces) {
986 		TAILQ_FOREACH(ifp0, ifp->ctx->ifaces, next) {
987 			if (ifp0 != ifp)
988 				dhcp6_freedrop_addrs(ifp0, 1, ifp);
989 		}
990 	}
991 }
992 
993 static ssize_t
994 dhcp6_update_auth(struct interface *ifp, struct dhcp6_message *m, size_t len)
995 {
996 	struct dhcp6_state *state;
997 	const struct dhcp6_option *co;
998 	struct dhcp6_option *o;
999 
1000 	co = dhcp6_getmoption(D6_OPTION_AUTH, m, len);
1001 	if (co == NULL)
1002 		return -1;
1003 
1004 	o = __UNCONST(co);
1005 	state = D6_STATE(ifp);
1006 
1007 	return dhcp_auth_encode(&ifp->options->auth, state->auth.token,
1008 	    (uint8_t *)state->send, state->send_len,
1009 	    6, state->send->type,
1010 	    D6_OPTION_DATA(o), ntohs(o->len));
1011 }
1012 
1013 static int
1014 dhcp6_sendmessage(struct interface *ifp, void (*callback)(void *))
1015 {
1016 	struct dhcp6_state *state;
1017 	struct ipv6_ctx *ctx;
1018 	struct sockaddr_in6 dst;
1019 	struct cmsghdr *cm;
1020 	struct in6_pktinfo pi;
1021 	struct timespec RTprev;
1022 	double rnd;
1023 	time_t ms;
1024 	uint8_t neg;
1025 	const char *broad_uni;
1026 	const struct in6_addr alldhcp = IN6ADDR_LINKLOCAL_ALLDHCP_INIT;
1027 
1028 	if (!callback && ifp->carrier == LINK_DOWN)
1029 		return 0;
1030 
1031 	memset(&dst, 0, sizeof(dst));
1032 	dst.sin6_family = AF_INET6;
1033 	dst.sin6_port = htons(DHCP6_SERVER_PORT);
1034 #ifdef SIN6_LEN
1035 	dst.sin6_len = sizeof(dst);
1036 #endif
1037 
1038 	state = D6_STATE(ifp);
1039 	/* We need to ensure we have sufficient scope to unicast the address */
1040 	/* XXX FIXME: We should check any added addresses we have like from
1041 	 * a Router Advertisement */
1042 	if (IN6_IS_ADDR_UNSPECIFIED(&state->unicast) ||
1043 	    (state->state == DH6S_REQUEST &&
1044 	    (!IN6_IS_ADDR_LINKLOCAL(&state->unicast) || !ipv6_linklocal(ifp))))
1045 	{
1046 		dst.sin6_addr = alldhcp;
1047 		broad_uni = "broadcasting";
1048 	} else {
1049 		dst.sin6_addr = state->unicast;
1050 		broad_uni = "unicasting";
1051 	}
1052 
1053 	if (!callback)
1054 		logger(ifp->ctx, LOG_DEBUG,
1055 		    "%s: %s %s with xid 0x%02x%02x%02x",
1056 		    ifp->name,
1057 		    broad_uni,
1058 		    dhcp6_get_op(state->send->type),
1059 		    state->send->xid[0],
1060 		    state->send->xid[1],
1061 		    state->send->xid[2]);
1062 	else {
1063 		if (state->IMD &&
1064 		    !(ifp->options->options & DHCPCD_INITIAL_DELAY))
1065 			state->IMD = 0;
1066 		if (state->IMD) {
1067 			/* Some buggy PPP servers close the link too early
1068 			 * after sending an invalid status in their reply
1069 			 * which means this host won't see it.
1070 			 * 1 second grace seems to be the sweet spot. */
1071 			if (ifp->flags & IFF_POINTOPOINT)
1072 				state->RT.tv_sec = 1;
1073 			else
1074 				state->RT.tv_sec = 0;
1075 			state->RT.tv_nsec = (suseconds_t)arc4random_uniform(
1076 			    (uint32_t)(state->IMD * NSEC_PER_SEC));
1077 			timespecnorm(&state->RT);
1078 			broad_uni = "delaying";
1079 			goto logsend;
1080 		}
1081 		if (state->RTC == 0) {
1082 			RTprev.tv_sec = state->IRT;
1083 			RTprev.tv_nsec = 0;
1084 			state->RT.tv_sec = RTprev.tv_sec;
1085 			state->RT.tv_nsec = 0;
1086 		} else {
1087 			RTprev = state->RT;
1088 			timespecadd(&state->RT, &state->RT, &state->RT);
1089 		}
1090 
1091 		rnd = DHCP6_RAND_MIN;
1092 		rnd += (suseconds_t)arc4random_uniform(
1093 		    DHCP6_RAND_MAX - DHCP6_RAND_MIN);
1094 		rnd /= MSEC_PER_SEC;
1095 		neg = (rnd < 0.0);
1096 		if (neg)
1097 			rnd = -rnd;
1098 		ts_to_ms(ms, &RTprev);
1099 		ms = (time_t)((double)ms * rnd);
1100 		ms_to_ts(&RTprev, ms);
1101 		if (neg)
1102 			timespecsub(&state->RT, &RTprev, &state->RT);
1103 		else
1104 			timespecadd(&state->RT, &RTprev, &state->RT);
1105 
1106 		if (state->MRT != 0 && state->RT.tv_sec > state->MRT) {
1107 			RTprev.tv_sec = state->MRT;
1108 			RTprev.tv_nsec = 0;
1109 			state->RT.tv_sec = state->MRT;
1110 			state->RT.tv_nsec = 0;
1111 			ts_to_ms(ms, &RTprev);
1112 			ms = (time_t)((double)ms * rnd);
1113 			ms_to_ts(&RTprev, ms);
1114 			if (neg)
1115 				timespecsub(&state->RT, &RTprev, &state->RT);
1116 			else
1117 				timespecadd(&state->RT, &RTprev, &state->RT);
1118 		}
1119 
1120 logsend:
1121 		if (ifp->carrier != LINK_DOWN)
1122 			logger(ifp->ctx, LOG_DEBUG,
1123 			    "%s: %s %s (xid 0x%02x%02x%02x),"
1124 			    " next in %0.1f seconds",
1125 			    ifp->name,
1126 			    broad_uni,
1127 			    dhcp6_get_op(state->send->type),
1128 			    state->send->xid[0],
1129 			    state->send->xid[1],
1130 			    state->send->xid[2],
1131 			    timespec_to_double(&state->RT));
1132 
1133 		/* This sometimes happens when we delegate to this interface
1134 		 * AND run DHCPv6 on it normally. */
1135 		assert(timespec_to_double(&state->RT) != 0);
1136 
1137 		/* Wait the initial delay */
1138 		if (state->IMD != 0) {
1139 			state->IMD = 0;
1140 			eloop_timeout_add_tv(ifp->ctx->eloop,
1141 			    &state->RT, callback, ifp);
1142 			return 0;
1143 		}
1144 	}
1145 
1146 	if (ifp->carrier == LINK_DOWN)
1147 		return 0;
1148 
1149 	/* Update the elapsed time */
1150 	dhcp6_updateelapsed(ifp, state->send, state->send_len);
1151 	if (ifp->options->auth.options & DHCPCD_AUTH_SEND &&
1152 	    dhcp6_update_auth(ifp, state->send, state->send_len) == -1)
1153 	{
1154 		logger(ifp->ctx, LOG_ERR,
1155 		    "%s: dhcp6_updateauth: %m", ifp->name);
1156 		if (errno != ESRCH)
1157 			return -1;
1158 	}
1159 
1160 	ctx = ifp->ctx->ipv6;
1161 	dst.sin6_scope_id = ifp->index;
1162 	ctx->sndhdr.msg_name = (void *)&dst;
1163 	ctx->sndhdr.msg_iov[0].iov_base = state->send;
1164 	ctx->sndhdr.msg_iov[0].iov_len = state->send_len;
1165 
1166 	/* Set the outbound interface */
1167 	cm = CMSG_FIRSTHDR(&ctx->sndhdr);
1168 	if (cm == NULL) /* unlikely */
1169 		return -1;
1170 	cm->cmsg_level = IPPROTO_IPV6;
1171 	cm->cmsg_type = IPV6_PKTINFO;
1172 	cm->cmsg_len = CMSG_LEN(sizeof(pi));
1173 	memset(&pi, 0, sizeof(pi));
1174 	pi.ipi6_ifindex = ifp->index;
1175 	memcpy(CMSG_DATA(cm), &pi, sizeof(pi));
1176 
1177 	if (sendmsg(ctx->dhcp_fd, &ctx->sndhdr, 0) == -1) {
1178 		logger(ifp->ctx, LOG_ERR,
1179 		    "%s: %s: sendmsg: %m", ifp->name, __func__);
1180 		ifp->options->options &= ~DHCPCD_IPV6;
1181 		dhcp6_drop(ifp, "EXPIRE6");
1182 		return -1;
1183 	}
1184 
1185 	state->RTC++;
1186 	if (callback) {
1187 		if (state->MRC == 0 || state->RTC < state->MRC)
1188 			eloop_timeout_add_tv(ifp->ctx->eloop,
1189 			    &state->RT, callback, ifp);
1190 		else if (state->MRC != 0 && state->MRCcallback)
1191 			eloop_timeout_add_tv(ifp->ctx->eloop,
1192 			    &state->RT, state->MRCcallback, ifp);
1193 		else
1194 			logger(ifp->ctx, LOG_WARNING,
1195 			    "%s: sent %d times with no reply",
1196 			    ifp->name, state->RTC);
1197 	}
1198 	return 0;
1199 }
1200 
1201 static void
1202 dhcp6_sendinform(void *arg)
1203 {
1204 
1205 	dhcp6_sendmessage(arg, dhcp6_sendinform);
1206 }
1207 
1208 static void
1209 dhcp6_senddiscover(void *arg)
1210 {
1211 
1212 	dhcp6_sendmessage(arg, dhcp6_senddiscover);
1213 }
1214 
1215 static void
1216 dhcp6_sendrequest(void *arg)
1217 {
1218 
1219 	dhcp6_sendmessage(arg, dhcp6_sendrequest);
1220 }
1221 
1222 static void
1223 dhcp6_sendrebind(void *arg)
1224 {
1225 
1226 	dhcp6_sendmessage(arg, dhcp6_sendrebind);
1227 }
1228 
1229 static void
1230 dhcp6_sendrenew(void *arg)
1231 {
1232 
1233 	dhcp6_sendmessage(arg, dhcp6_sendrenew);
1234 }
1235 
1236 static void
1237 dhcp6_sendconfirm(void *arg)
1238 {
1239 
1240 	dhcp6_sendmessage(arg, dhcp6_sendconfirm);
1241 }
1242 
1243 static void
1244 dhcp6_sendrelease(void *arg)
1245 {
1246 
1247 	dhcp6_sendmessage(arg, dhcp6_sendrelease);
1248 }
1249 
1250 static void
1251 dhcp6_startrenew(void *arg)
1252 {
1253 	struct interface *ifp;
1254 	struct dhcp6_state *state;
1255 
1256 	ifp = arg;
1257 	state = D6_STATE(ifp);
1258 	state->state = DH6S_RENEW;
1259 	state->RTC = 0;
1260 	state->IRT = REN_TIMEOUT;
1261 	state->MRT = REN_MAX_RT;
1262 	state->MRC = 0;
1263 
1264 	if (dhcp6_makemessage(ifp) == -1)
1265 		logger(ifp->ctx, LOG_ERR,
1266 		    "%s: dhcp6_makemessage: %m", ifp->name);
1267 	else
1268 		dhcp6_sendrenew(ifp);
1269 }
1270 
1271 int
1272 dhcp6_dadcompleted(const struct interface *ifp)
1273 {
1274 	const struct dhcp6_state *state;
1275 	const struct ipv6_addr *ap;
1276 
1277 	state = D6_CSTATE(ifp);
1278 	TAILQ_FOREACH(ap, &state->addrs, next) {
1279 		if (ap->flags & IPV6_AF_ADDED &&
1280 		    !(ap->flags & IPV6_AF_DADCOMPLETED))
1281 			return 0;
1282 	}
1283 	return 1;
1284 }
1285 
1286 static void
1287 dhcp6_dadcallback(void *arg)
1288 {
1289 	struct ipv6_addr *ap = arg;
1290 	struct interface *ifp;
1291 	struct dhcp6_state *state;
1292 	int wascompleted, valid;
1293 
1294 	wascompleted = (ap->flags & IPV6_AF_DADCOMPLETED);
1295 	ap->flags |= IPV6_AF_DADCOMPLETED;
1296 	if (ap->flags & IPV6_AF_DUPLICATED)
1297 		/* XXX FIXME
1298 		 * We should decline the address */
1299 		logger(ap->iface->ctx, LOG_WARNING, "%s: DAD detected %s",
1300 		    ap->iface->name, ap->saddr);
1301 
1302 	if (!wascompleted) {
1303 		ifp = ap->iface;
1304 		state = D6_STATE(ifp);
1305 		if (state->state == DH6S_BOUND ||
1306 		    state->state == DH6S_DELEGATED)
1307 		{
1308 			struct ipv6_addr *ap2;
1309 
1310 			valid = (ap->delegating_iface == NULL);
1311 			TAILQ_FOREACH(ap2, &state->addrs, next) {
1312 				if (ap2->flags & IPV6_AF_ADDED &&
1313 				    !(ap2->flags & IPV6_AF_DADCOMPLETED))
1314 				{
1315 					wascompleted = 1;
1316 					break;
1317 				}
1318 			}
1319 			if (!wascompleted) {
1320 				logger(ap->iface->ctx, LOG_DEBUG,
1321 				    "%s: DHCPv6 DAD completed", ifp->name);
1322 				script_runreason(ifp,
1323 				    ap->delegating_iface ?
1324 				    "DELEGATED6" : state->reason);
1325 				if (valid)
1326 					dhcpcd_daemonise(ifp->ctx);
1327 			}
1328 		}
1329 	}
1330 }
1331 
1332 static void
1333 dhcp6_addrequestedaddrs(struct interface *ifp)
1334 {
1335 	struct dhcp6_state *state;
1336 	size_t i;
1337 	struct if_ia *ia;
1338 	struct ipv6_addr *a;
1339 	char iabuf[INET6_ADDRSTRLEN];
1340 	const char *iap;
1341 
1342 	state = D6_STATE(ifp);
1343 	/* Add any requested prefixes / addresses */
1344 	for (i = 0; i < ifp->options->ia_len; i++) {
1345 		ia = &ifp->options->ia[i];
1346 		if (!((ia->ia_type == D6_OPTION_IA_PD && ia->prefix_len) ||
1347 		    !IN6_IS_ADDR_UNSPECIFIED(&ia->addr)))
1348 			continue;
1349 		a = calloc(1, sizeof(*a));
1350 		if (a == NULL) {
1351 			logger(ifp->ctx, LOG_ERR, "%s: %m", __func__);
1352 			return;
1353 		}
1354 		a->flags = IPV6_AF_REQUEST;
1355 		a->iface = ifp;
1356 		a->dadcallback = dhcp6_dadcallback;
1357 		memcpy(&a->iaid, &ia->iaid, sizeof(a->iaid));
1358 		a->ia_type = ia->ia_type;
1359 		//a->prefix_pltime = 0;
1360 		//a->prefix_vltime = 0;
1361 
1362 		if (ia->ia_type == D6_OPTION_IA_PD) {
1363 			memcpy(&a->prefix, &ia->addr, sizeof(a->addr));
1364 			a->prefix_len = ia->prefix_len;
1365 			iap = inet_ntop(AF_INET6, &a->prefix,
1366 			    iabuf, sizeof(iabuf));
1367 		} else {
1368 			memcpy(&a->addr, &ia->addr, sizeof(a->addr));
1369 			/*
1370 			 * RFC 5942 Section 5
1371 			 * We cannot assume any prefix length, nor tie the
1372 			 * address to an existing one as it could expire
1373 			 * before the address.
1374 			 * As such we just give it a 128 prefix.
1375 			 */
1376 			a->prefix_len = 128;
1377 			ipv6_makeprefix(&a->prefix, &a->addr, a->prefix_len);
1378 			iap = inet_ntop(AF_INET6, &a->addr,
1379 			    iabuf, sizeof(iabuf));
1380 		}
1381 		snprintf(a->saddr, sizeof(a->saddr),
1382 		    "%s/%d", iap, a->prefix_len);
1383 		TAILQ_INSERT_TAIL(&state->addrs, a, next);
1384 	}
1385 }
1386 
1387 static void
1388 dhcp6_startdiscover(void *arg)
1389 {
1390 	struct interface *ifp;
1391 	struct dhcp6_state *state;
1392 
1393 	ifp = arg;
1394 	dhcp6_delete_delegates(ifp);
1395 	logger(ifp->ctx, LOG_INFO, "%s: soliciting a DHCPv6 lease", ifp->name);
1396 	state = D6_STATE(ifp);
1397 	state->state = DH6S_DISCOVER;
1398 	state->RTC = 0;
1399 	state->IMD = SOL_MAX_DELAY;
1400 	state->IRT = SOL_TIMEOUT;
1401 	state->MRT = state->sol_max_rt;
1402 	state->MRC = 0;
1403 
1404 	eloop_timeout_delete(ifp->ctx->eloop, NULL, ifp);
1405 	free(state->new);
1406 	state->new = NULL;
1407 	state->new_len = 0;
1408 
1409 	dhcp6_freedrop_addrs(ifp, 0, NULL);
1410 	unlink(state->leasefile);
1411 
1412 	dhcp6_addrequestedaddrs(ifp);
1413 
1414 	if (dhcp6_makemessage(ifp) == -1)
1415 		logger(ifp->ctx, LOG_ERR,
1416 		    "%s: dhcp6_makemessage: %m", ifp->name);
1417 	else
1418 		dhcp6_senddiscover(ifp);
1419 }
1420 
1421 static void
1422 dhcp6_failconfirm(void *arg)
1423 {
1424 	struct interface *ifp;
1425 
1426 	ifp = arg;
1427 	logger(ifp->ctx, LOG_ERR,
1428 	    "%s: failed to confirm prior address", ifp->name);
1429 	/* Section 18.1.2 says that we SHOULD use the last known
1430 	 * IP address(s) and lifetimes if we didn't get a reply.
1431 	 * I disagree with this. */
1432 	dhcp6_startdiscover(ifp);
1433 }
1434 
1435 static void
1436 dhcp6_failrequest(void *arg)
1437 {
1438 	struct interface *ifp;
1439 
1440 	ifp = arg;
1441 	logger(ifp->ctx, LOG_ERR, "%s: failed to request address", ifp->name);
1442 	/* Section 18.1.1 says that client local policy dictates
1443 	 * what happens if a REQUEST fails.
1444 	 * Of the possible scenarios listed, moving back to the
1445 	 * DISCOVER phase makes more sense for us. */
1446 	dhcp6_startdiscover(ifp);
1447 }
1448 
1449 static void
1450 dhcp6_failrebind(void *arg)
1451 {
1452 	struct interface *ifp;
1453 
1454 	ifp = arg;
1455 	logger(ifp->ctx, LOG_ERR,
1456 	    "%s: failed to rebind prior delegation", ifp->name);
1457 	dhcp6_delete_delegates(ifp);
1458 	/* Section 18.1.2 says that we SHOULD use the last known
1459 	 * IP address(s) and lifetimes if we didn't get a reply.
1460 	 * I disagree with this. */
1461 	dhcp6_startdiscover(ifp);
1462 }
1463 
1464 
1465 static int
1466 dhcp6_hasprefixdelegation(struct interface *ifp)
1467 {
1468 	size_t i;
1469 	uint16_t t;
1470 
1471 	t = 0;
1472 	for (i = 0; i < ifp->options->ia_len; i++) {
1473 		if (t && t != ifp->options->ia[i].ia_type) {
1474 			if (t == D6_OPTION_IA_PD ||
1475 			    ifp->options->ia[i].ia_type == D6_OPTION_IA_PD)
1476 				return 2;
1477 		}
1478 		t = ifp->options->ia[i].ia_type;
1479 	}
1480 	return t == D6_OPTION_IA_PD ? 1 : 0;
1481 }
1482 
1483 static void
1484 dhcp6_startrebind(void *arg)
1485 {
1486 	struct interface *ifp;
1487 	struct dhcp6_state *state;
1488 	int pd;
1489 
1490 	ifp = arg;
1491 	eloop_timeout_delete(ifp->ctx->eloop, dhcp6_sendrenew, ifp);
1492 	state = D6_STATE(ifp);
1493 	if (state->state == DH6S_RENEW)
1494 		logger(ifp->ctx, LOG_WARNING,
1495 		    "%s: failed to renew DHCPv6, rebinding", ifp->name);
1496 	else
1497 		logger(ifp->ctx, LOG_INFO,
1498 		    "%s: rebinding prior DHCPv6 lease", ifp->name);
1499 	state->state = DH6S_REBIND;
1500 	state->RTC = 0;
1501 	state->MRC = 0;
1502 
1503 	/* RFC 3633 section 12.1 */
1504 	pd = dhcp6_hasprefixdelegation(ifp);
1505 	if (pd) {
1506 		state->IMD = CNF_MAX_DELAY;
1507 		state->IRT = CNF_TIMEOUT;
1508 		state->MRT = CNF_MAX_RT;
1509 	} else {
1510 		state->IRT = REB_TIMEOUT;
1511 		state->MRT = REB_MAX_RT;
1512 	}
1513 
1514 	if (dhcp6_makemessage(ifp) == -1)
1515 		logger(ifp->ctx, LOG_ERR,
1516 		    "%s: dhcp6_makemessage: %m", ifp->name);
1517 	else
1518 		dhcp6_sendrebind(ifp);
1519 
1520 	/* RFC 3633 section 12.1 */
1521 	if (pd)
1522 		eloop_timeout_add_sec(ifp->ctx->eloop,
1523 		    CNF_MAX_RD, dhcp6_failrebind, ifp);
1524 }
1525 
1526 
1527 static void
1528 dhcp6_startrequest(struct interface *ifp)
1529 {
1530 	struct dhcp6_state *state;
1531 
1532 	eloop_timeout_delete(ifp->ctx->eloop, dhcp6_senddiscover, ifp);
1533 	state = D6_STATE(ifp);
1534 	state->state = DH6S_REQUEST;
1535 	state->RTC = 0;
1536 	state->IRT = REQ_TIMEOUT;
1537 	state->MRT = REQ_MAX_RT;
1538 	state->MRC = REQ_MAX_RC;
1539 	state->MRCcallback = dhcp6_failrequest;
1540 
1541 	if (dhcp6_makemessage(ifp) == -1) {
1542 		logger(ifp->ctx, LOG_ERR,
1543 		    "%s: dhcp6_makemessage: %m", ifp->name);
1544 		return;
1545 	}
1546 
1547 	dhcp6_sendrequest(ifp);
1548 }
1549 
1550 static void
1551 dhcp6_startconfirm(struct interface *ifp)
1552 {
1553 	struct dhcp6_state *state;
1554 
1555 	state = D6_STATE(ifp);
1556 	state->state = DH6S_CONFIRM;
1557 	state->RTC = 0;
1558 	state->IMD = CNF_MAX_DELAY;
1559 	state->IRT = CNF_TIMEOUT;
1560 	state->MRT = CNF_MAX_RT;
1561 	state->MRC = 0;
1562 
1563 	logger(ifp->ctx, LOG_INFO,
1564 	    "%s: confirming prior DHCPv6 lease", ifp->name);
1565 	if (dhcp6_makemessage(ifp) == -1) {
1566 		logger(ifp->ctx, LOG_ERR,
1567 		    "%s: dhcp6_makemessage: %m", ifp->name);
1568 		return;
1569 	}
1570 	dhcp6_sendconfirm(ifp);
1571 	eloop_timeout_add_sec(ifp->ctx->eloop,
1572 	    CNF_MAX_RD, dhcp6_failconfirm, ifp);
1573 }
1574 
1575 static void
1576 dhcp6_startinform(void *arg)
1577 {
1578 	struct interface *ifp;
1579 	struct dhcp6_state *state;
1580 
1581 	ifp = arg;
1582 	state = D6_STATE(ifp);
1583 	if (state->new == NULL || ifp->options->options & DHCPCD_DEBUG)
1584 		logger(ifp->ctx, LOG_INFO,
1585 		    "%s: requesting DHCPv6 information", ifp->name);
1586 	state->state = DH6S_INFORM;
1587 	state->RTC = 0;
1588 	state->IMD = INF_MAX_DELAY;
1589 	state->IRT = INF_TIMEOUT;
1590 	state->MRT = state->inf_max_rt;
1591 	state->MRC = 0;
1592 
1593 	if (dhcp6_makemessage(ifp) == -1)
1594 		logger(ifp->ctx, LOG_ERR,
1595 		    "%s: dhcp6_makemessage: %m", ifp->name);
1596 	else
1597 		dhcp6_sendinform(ifp);
1598 }
1599 
1600 static void
1601 dhcp6_startexpire(void *arg)
1602 {
1603 	struct interface *ifp;
1604 
1605 	ifp = arg;
1606 	eloop_timeout_delete(ifp->ctx->eloop, dhcp6_sendrebind, ifp);
1607 
1608 	logger(ifp->ctx, LOG_ERR, "%s: DHCPv6 lease expired", ifp->name);
1609 	dhcp6_freedrop_addrs(ifp, 1, NULL);
1610 	dhcp6_delete_delegates(ifp);
1611 	script_runreason(ifp, "EXPIRE6");
1612 	if (ipv6nd_hasradhcp(ifp) || dhcp6_hasprefixdelegation(ifp))
1613 		dhcp6_startdiscover(ifp);
1614 	else
1615 		logger(ifp->ctx, LOG_WARNING,
1616 		    "%s: no advertising IPv6 router wants DHCP", ifp->name);
1617 }
1618 
1619 static void
1620 dhcp6_finishrelease(void *arg)
1621 {
1622 	struct interface *ifp;
1623 	struct dhcp6_state *state;
1624 
1625 	ifp = (struct interface *)arg;
1626 	state = D6_STATE(ifp);
1627 	state->state = DH6S_RELEASED;
1628 	dhcp6_drop(ifp, "RELEASE6");
1629 }
1630 
1631 static void
1632 dhcp6_startrelease(struct interface *ifp)
1633 {
1634 	struct dhcp6_state *state;
1635 
1636 	state = D6_STATE(ifp);
1637 	if (state->state != DH6S_BOUND)
1638 		return;
1639 
1640 	state->state = DH6S_RELEASE;
1641 	state->RTC = 0;
1642 	state->IRT = REL_TIMEOUT;
1643 	state->MRT = 0;
1644 	/* MRC of REL_MAX_RC is optional in RFC 3315 18.1.6 */
1645 #if 0
1646 	state->MRC = REL_MAX_RC;
1647 	state->MRCcallback = dhcp6_finishrelease;
1648 #else
1649 	state->MRC = 0;
1650 	state->MRCcallback = NULL;
1651 #endif
1652 
1653 	if (dhcp6_makemessage(ifp) == -1)
1654 		logger(ifp->ctx, LOG_ERR,
1655 		    "%s: dhcp6_makemessage: %m", ifp->name);
1656 	else {
1657 		dhcp6_sendrelease(ifp);
1658 		dhcp6_finishrelease(ifp);
1659 	}
1660 }
1661 
1662 static int
1663 dhcp6_checkstatusok(const struct interface *ifp,
1664     const struct dhcp6_message *m, const uint8_t *p, size_t len)
1665 {
1666 	const struct dhcp6_option *o;
1667 	uint16_t code;
1668 	char *status;
1669 
1670 	if (p)
1671 		o = dhcp6_findoption(D6_OPTION_STATUS_CODE, p, len);
1672 	else
1673 		o = dhcp6_getmoption(D6_OPTION_STATUS_CODE, m, len);
1674 	if (o == NULL) {
1675 		//logger(ifp->ctx, LOG_DEBUG, "%s: no status", ifp->name);
1676 		return 0;
1677 	}
1678 
1679 	len = ntohs(o->len);
1680 	if (len < sizeof(code)) {
1681 		logger(ifp->ctx, LOG_ERR, "%s: status truncated", ifp->name);
1682 		return -1;
1683 	}
1684 
1685 	p = D6_COPTION_DATA(o);
1686 	memcpy(&code, p, sizeof(code));
1687 	code = ntohs(code);
1688 	if (code == D6_STATUS_OK)
1689 		return 1;
1690 
1691 	len -= sizeof(code);
1692 
1693 	if (len == 0) {
1694 		if (code < sizeof(dhcp6_statuses) / sizeof(char *)) {
1695 			p = (const uint8_t *)dhcp6_statuses[code];
1696 			len = strlen((const char *)p);
1697 		} else
1698 			p = NULL;
1699 	} else
1700 		p += sizeof(code);
1701 
1702 	status = malloc(len + 1);
1703 	if (status == NULL) {
1704 		logger(ifp->ctx, LOG_ERR, "%s: %m", __func__);
1705 		return -1;
1706 	}
1707 	if (p)
1708 		memcpy(status, p, len);
1709 	status[len] = '\0';
1710 	logger(ifp->ctx, LOG_ERR, "%s: DHCPv6 REPLY: %s", ifp->name, status);
1711 	free(status);
1712 	return -1;
1713 }
1714 
1715 const struct ipv6_addr *
1716 dhcp6_iffindaddr(const struct interface *ifp, const struct in6_addr *addr,
1717     short flags)
1718 {
1719 	const struct dhcp6_state *state;
1720 	const struct ipv6_addr *ap;
1721 
1722 	if ((state = D6_STATE(ifp)) != NULL) {
1723 		TAILQ_FOREACH(ap, &state->addrs, next) {
1724 			if (ipv6_findaddrmatch(ap, addr, flags))
1725 				return ap;
1726 		}
1727 	}
1728 	return NULL;
1729 }
1730 
1731 struct ipv6_addr *
1732 dhcp6_findaddr(struct dhcpcd_ctx *ctx, const struct in6_addr *addr,
1733     short flags)
1734 {
1735 	struct interface *ifp;
1736 	struct ipv6_addr *ap;
1737 	struct dhcp6_state *state;
1738 
1739 	TAILQ_FOREACH(ifp, ctx->ifaces, next) {
1740 		if ((state = D6_STATE(ifp)) != NULL) {
1741 			TAILQ_FOREACH(ap, &state->addrs, next) {
1742 				if (ipv6_findaddrmatch(ap, addr, flags))
1743 					return ap;
1744 			}
1745 		}
1746 	}
1747 	return NULL;
1748 }
1749 
1750 static int
1751 dhcp6_findna(struct interface *ifp, uint16_t ot, const uint8_t *iaid,
1752     const uint8_t *d, size_t l, const struct timespec *acquired)
1753 {
1754 	struct dhcp6_state *state;
1755 	const struct dhcp6_option *o;
1756 	struct ipv6_addr *a;
1757 	char iabuf[INET6_ADDRSTRLEN];
1758 	const char *ia;
1759 	int i;
1760 	uint32_t u32;
1761 	size_t off;
1762 	const struct dhcp6_ia_addr *iap;
1763 
1764 	i = 0;
1765 	state = D6_STATE(ifp);
1766 	while ((o = dhcp6_findoption(D6_OPTION_IA_ADDR, d, l))) {
1767 		off = (size_t)((const uint8_t *)o - d);
1768 		l -= off;
1769 		d += off;
1770 		u32 = ntohs(o->len);
1771 		l -= sizeof(*o) + u32;
1772 		d += sizeof(*o) + u32;
1773 		if (u32 < 24) {
1774 			errno = EINVAL;
1775 			logger(ifp->ctx, LOG_ERR,
1776 			    "%s: IA Address option truncated", ifp->name);
1777 			continue;
1778 		}
1779 		iap = (const struct dhcp6_ia_addr *)D6_COPTION_DATA(o);
1780 		TAILQ_FOREACH(a, &state->addrs, next) {
1781 			if (ipv6_findaddrmatch(a, &iap->addr, 0))
1782 				break;
1783 		}
1784 		if (a == NULL) {
1785 			a = calloc(1, sizeof(*a));
1786 			if (a == NULL) {
1787 				logger(ifp->ctx, LOG_ERR, "%s: %m", __func__);
1788 				break;
1789 			}
1790 			a->iface = ifp;
1791 			a->flags = IPV6_AF_NEW | IPV6_AF_ONLINK;
1792 			a->dadcallback = dhcp6_dadcallback;
1793 			a->ia_type = ot;
1794 			memcpy(a->iaid, iaid, sizeof(a->iaid));
1795 			a->addr = iap->addr;
1796 			a->created = *acquired;
1797 
1798 			/*
1799 			 * RFC 5942 Section 5
1800 			 * We cannot assume any prefix length, nor tie the
1801 			 * address to an existing one as it could expire
1802 			 * before the address.
1803 			 * As such we just give it a 128 prefix.
1804 			 */
1805 			a->prefix_len = 128;
1806 			ipv6_makeprefix(&a->prefix, &a->addr, a->prefix_len);
1807 			ia = inet_ntop(AF_INET6, &a->addr,
1808 			    iabuf, sizeof(iabuf));
1809 			snprintf(a->saddr, sizeof(a->saddr),
1810 			    "%s/%d", ia, a->prefix_len);
1811 
1812 			TAILQ_INSERT_TAIL(&state->addrs, a, next);
1813 		} else {
1814 			if (!(a->flags & IPV6_AF_ONLINK))
1815 				a->flags |= IPV6_AF_ONLINK | IPV6_AF_NEW;
1816 			a->flags &= ~IPV6_AF_STALE;
1817 		}
1818 		a->acquired = *acquired;
1819 		a->prefix_pltime = ntohl(iap->pltime);
1820 		u32 = ntohl(iap->vltime);
1821 		if (a->prefix_vltime != u32) {
1822 			a->flags |= IPV6_AF_NEW;
1823 			a->prefix_vltime = u32;
1824 		}
1825 		if (a->prefix_pltime && a->prefix_pltime < state->lowpl)
1826 		    state->lowpl = a->prefix_pltime;
1827 		if (a->prefix_vltime && a->prefix_vltime > state->expire)
1828 		    state->expire = a->prefix_vltime;
1829 		i++;
1830 	}
1831 	return i;
1832 }
1833 
1834 static int
1835 dhcp6_findpd(struct interface *ifp, const uint8_t *iaid,
1836     const uint8_t *d, size_t l, const struct timespec *acquired)
1837 {
1838 	struct dhcp6_state *state;
1839 	const struct dhcp6_option *o, *ex;
1840 	const uint8_t *p, *op;
1841 	struct ipv6_addr *a;
1842 	char iabuf[INET6_ADDRSTRLEN];
1843 	const char *ia;
1844 	int i;
1845 	uint8_t u8, *pw;
1846 	size_t off;
1847 	uint16_t ol;
1848 	const struct dhcp6_pd_addr *pdp;
1849 
1850 	i = 0;
1851 	state = D6_STATE(ifp);
1852 	while ((o = dhcp6_findoption(D6_OPTION_IAPREFIX, d, l))) {
1853 		off = (size_t)((const uint8_t *)o - d);
1854 		l -= off;
1855 		d += off;
1856 		ol = ntohs(o->len);
1857 		l -= sizeof(*o) + ol;
1858 		d += sizeof(*o) + ol;
1859 		if (ol < sizeof(*pdp)) {
1860 			errno = EINVAL;
1861 			logger(ifp->ctx, LOG_ERR,
1862 			    "%s: IA Prefix option truncated", ifp->name);
1863 			continue;
1864 		}
1865 
1866 		pdp = (const struct dhcp6_pd_addr *)D6_COPTION_DATA(o);
1867 		TAILQ_FOREACH(a, &state->addrs, next) {
1868 			if (IN6_ARE_ADDR_EQUAL(&a->prefix, &pdp->prefix))
1869 				break;
1870 		}
1871 		if (a == NULL) {
1872 			a = calloc(1, sizeof(*a));
1873 			if (a == NULL) {
1874 				logger(ifp->ctx, LOG_ERR, "%s: %m", __func__);
1875 				break;
1876 			}
1877 			a->iface = ifp;
1878 			a->flags = IPV6_AF_NEW | IPV6_AF_DELEGATEDPFX;
1879 			a->created = *acquired;
1880 			a->dadcallback = dhcp6_dadcallback;
1881 			a->ia_type = D6_OPTION_IA_PD;
1882 			memcpy(a->iaid, iaid, sizeof(a->iaid));
1883 			a->prefix = pdp->prefix;
1884 			a->prefix_len = pdp->prefix_len;
1885 			ia = inet_ntop(AF_INET6, &a->prefix,
1886 			    iabuf, sizeof(iabuf));
1887 			snprintf(a->saddr, sizeof(a->saddr),
1888 			    "%s/%d", ia, a->prefix_len);
1889 			TAILQ_INSERT_TAIL(&state->addrs, a, next);
1890 		} else {
1891 			if (!(a->flags & IPV6_AF_DELEGATEDPFX))
1892 				a->flags |= IPV6_AF_NEW | IPV6_AF_DELEGATEDPFX;
1893 			a->flags &= ~(IPV6_AF_STALE | IPV6_AF_REQUEST);
1894 			if (a->prefix_vltime != ntohl(pdp->vltime))
1895 				a->flags |= IPV6_AF_NEW;
1896 		}
1897 
1898 		a->acquired = *acquired;
1899 		a->prefix_pltime = ntohl(pdp->pltime);
1900 		a->prefix_vltime = ntohl(pdp->vltime);
1901 
1902 		if (a->prefix_pltime && a->prefix_pltime < state->lowpl)
1903 			state->lowpl = a->prefix_pltime;
1904 		if (a->prefix_vltime && a->prefix_vltime > state->expire)
1905 			state->expire = a->prefix_vltime;
1906 		i++;
1907 
1908 		p = D6_COPTION_DATA(o) + sizeof(pdp);
1909 		ol = (uint16_t)(ol - sizeof(pdp));
1910 		ex = dhcp6_findoption(D6_OPTION_PD_EXCLUDE, p, ol);
1911 		a->prefix_exclude_len = 0;
1912 		memset(&a->prefix_exclude, 0, sizeof(a->prefix_exclude));
1913 #if 0
1914 		if (ex == NULL) {
1915 			struct dhcp6_option *w;
1916 			uint8_t *wp;
1917 
1918 			w = calloc(1, 128);
1919 			w->len = htons(2);
1920 			wp = D6_OPTION_DATA(w);
1921 			*wp++ = 64;
1922 			*wp++ = 0x78;
1923 			ex = w;
1924 		}
1925 #endif
1926 		if (ex == NULL)
1927 			continue;
1928 		ol = ntohs(ex->len);
1929 		if (ol < 2) {
1930 			logger(ifp->ctx, LOG_ERR,
1931 			    "%s: truncated PD Exclude", ifp->name);
1932 			continue;
1933 		}
1934 		op = D6_COPTION_DATA(ex);
1935 		a->prefix_exclude_len = *op++;
1936 		ol--;
1937 		if (((a->prefix_exclude_len - a->prefix_len - 1) / NBBY) + 1
1938 		    != ol)
1939 		{
1940 			logger(ifp->ctx, LOG_ERR,
1941 			    "%s: PD Exclude length mismatch", ifp->name);
1942 			a->prefix_exclude_len = 0;
1943 			continue;
1944 		}
1945 		u8 = a->prefix_len % NBBY;
1946 		memcpy(&a->prefix_exclude, &a->prefix,
1947 		    sizeof(a->prefix_exclude));
1948 		if (u8)
1949 			ol--;
1950 		pw = a->prefix_exclude.s6_addr +
1951 		    (a->prefix_exclude_len / NBBY) - 1;
1952 		while (ol-- > 0)
1953 			*pw-- = *op++;
1954 		if (u8)
1955 			*pw = (uint8_t)(*pw | (*op >> u8));
1956 	}
1957 	return i;
1958 }
1959 
1960 static int
1961 dhcp6_findia(struct interface *ifp, const struct dhcp6_message *m, size_t l,
1962     const char *sfrom, const struct timespec *acquired)
1963 {
1964 	struct dhcp6_state *state;
1965 	const struct if_options *ifo;
1966 	const struct dhcp6_option *o;
1967 	const uint8_t *p;
1968 	int i, e;
1969 	size_t j;
1970 	uint32_t u32, renew, rebind;
1971 	uint16_t code, ol;
1972 	uint8_t iaid[4];
1973 	char buf[sizeof(iaid) * 3];
1974 	struct ipv6_addr *ap, *nap;
1975 
1976 	if (l < sizeof(*m)) {
1977 		/* Should be impossible with guards at packet in
1978 		 * and reading leases */
1979 		errno = EINVAL;
1980 		return -1;
1981 	}
1982 
1983 	ifo = ifp->options;
1984 	i = e = 0;
1985 	state = D6_STATE(ifp);
1986 	TAILQ_FOREACH(ap, &state->addrs, next) {
1987 		ap->flags |= IPV6_AF_STALE;
1988 	}
1989 	l -= sizeof(*m);
1990 	for (o = D6_CFIRST_OPTION(m); l > sizeof(*o); o = D6_CNEXT_OPTION(o)) {
1991 		ol = ntohs(o->len);
1992 		if (sizeof(*o) + ol > l) {
1993 			errno = EINVAL;
1994 			logger(ifp->ctx, LOG_ERR,
1995 			    "%s: option overflow", ifp->name);
1996 			break;
1997 		}
1998 		l -= sizeof(*o) + ol;
1999 
2000 		code = ntohs(o->code);
2001 		switch(code) {
2002 		case D6_OPTION_IA_TA:
2003 			u32 = 4;
2004 			break;
2005 		case D6_OPTION_IA_NA:
2006 		case D6_OPTION_IA_PD:
2007 			u32 = 12;
2008 			break;
2009 		default:
2010 			continue;
2011 		}
2012 		if (ol < u32) {
2013 			errno = EINVAL;
2014 			logger(ifp->ctx, LOG_ERR,
2015 			    "%s: IA option truncated", ifp->name);
2016 			continue;
2017 		}
2018 
2019 		p = D6_COPTION_DATA(o);
2020 		memcpy(iaid, p, sizeof(iaid));
2021 		p += sizeof(iaid);
2022 		ol = (uint16_t)(ol - sizeof(iaid));
2023 
2024 		for (j = 0; j < ifo->ia_len; j++) {
2025 			if (memcmp(&ifo->ia[j].iaid, iaid, sizeof(iaid)) == 0)
2026 				break;
2027 		}
2028 		if (j == ifo->ia_len &&
2029 		    !(ifo->ia_len == 0 && ifp->ctx->options & DHCPCD_DUMPLEASE))
2030 		{
2031 			logger(ifp->ctx, LOG_DEBUG,
2032 			    "%s: ignoring unrequested IAID %s",
2033 			    ifp->name,
2034 			    hwaddr_ntoa(iaid, sizeof(iaid), buf, sizeof(buf)));
2035 			continue;
2036 		}
2037 		if ( j < ifo->ia_len && ifo->ia[j].ia_type != code) {
2038 			logger(ifp->ctx, LOG_ERR,
2039 			    "%s: IAID %s: option type mismatch",
2040 			    ifp->name,
2041 			    hwaddr_ntoa(iaid, sizeof(iaid), buf, sizeof(buf)));
2042 			continue;
2043 		}
2044 
2045 		if (code != D6_OPTION_IA_TA) {
2046 			memcpy(&u32, p, sizeof(u32));
2047 			renew = ntohl(u32);
2048 			p += sizeof(u32);
2049 			ol = (uint16_t)(ol - sizeof(u32));
2050 			memcpy(&u32, p, sizeof(u32));
2051 			rebind = ntohl(u32);
2052 			p += sizeof(u32);
2053 			ol = (uint16_t)(ol - sizeof(u32));
2054 		} else
2055 			renew = rebind = 0; /* appease gcc */
2056 		if (dhcp6_checkstatusok(ifp, NULL, p, ol) == -1) {
2057 			e = 1;
2058 			continue;
2059 		}
2060 		if (code == D6_OPTION_IA_PD) {
2061 			if (dhcp6_findpd(ifp, iaid, p, ol, acquired) == 0) {
2062 				logger(ifp->ctx, LOG_WARNING,
2063 				    "%s: %s: DHCPv6 REPLY missing Prefix",
2064 				    ifp->name, sfrom);
2065 				continue;
2066 			}
2067 		} else {
2068 			if (dhcp6_findna(ifp, code, iaid, p, ol, acquired) == 0)
2069 			{
2070 				logger(ifp->ctx, LOG_WARNING,
2071 				    "%s: %s: DHCPv6 REPLY missing IA Address",
2072 				    ifp->name, sfrom);
2073 				continue;
2074 			}
2075 		}
2076 		if (code != D6_OPTION_IA_TA) {
2077 			if (renew > rebind && rebind > 0) {
2078 				if (sfrom)
2079 				    logger(ifp->ctx, LOG_WARNING,
2080 					"%s: T1 (%d) > T2 (%d) from %s",
2081 					ifp->name, renew, rebind, sfrom);
2082 				renew = 0;
2083 				rebind = 0;
2084 			}
2085 			if (renew != 0 &&
2086 			    (renew < state->renew || state->renew == 0))
2087 				state->renew = renew;
2088 			if (rebind != 0 &&
2089 			    (rebind < state->rebind || state->rebind == 0))
2090 				state->rebind = rebind;
2091 		}
2092 		i++;
2093 	}
2094 	TAILQ_FOREACH_SAFE(ap, &state->addrs, next, nap) {
2095 		if (ap->flags & IPV6_AF_STALE) {
2096 			eloop_q_timeout_delete(ifp->ctx->eloop, 0, NULL, ap);
2097 			if (ap->flags & IPV6_AF_REQUEST) {
2098 				ap->prefix_vltime = ap->prefix_pltime = 0;
2099 			} else {
2100 				TAILQ_REMOVE(&state->addrs, ap, next);
2101 				free(ap);
2102 			}
2103 		}
2104 	}
2105 	if (i == 0 && e)
2106 		return -1;
2107 	return i;
2108 }
2109 
2110 static int
2111 dhcp6_validatelease(struct interface *ifp,
2112     const struct dhcp6_message *m, size_t len,
2113     const char *sfrom, const struct timespec *acquired)
2114 {
2115 	struct dhcp6_state *state;
2116 	int nia;
2117 	struct timespec aq;
2118 
2119 	if (len <= sizeof(*m)) {
2120 		logger(ifp->ctx, LOG_ERR,
2121 		    "%s: DHCPv6 lease truncated", ifp->name);
2122 		return -1;
2123 	}
2124 
2125 	state = D6_STATE(ifp);
2126 	if (dhcp6_checkstatusok(ifp, m, NULL, len) == -1)
2127 		return -1;
2128 
2129 	state->renew = state->rebind = state->expire = 0;
2130 	state->lowpl = ND6_INFINITE_LIFETIME;
2131 	if (!acquired) {
2132 		clock_gettime(CLOCK_MONOTONIC, &aq);
2133 		acquired = &aq;
2134 	}
2135 	nia = dhcp6_findia(ifp, m, len, sfrom, acquired);
2136 	if (nia == 0) {
2137 		logger(ifp->ctx, LOG_ERR,
2138 		    "%s: no useable IA found in lease", ifp->name);
2139 		return -1;
2140 	}
2141 	return nia;
2142 }
2143 
2144 static ssize_t
2145 dhcp6_writelease(const struct interface *ifp)
2146 {
2147 	const struct dhcp6_state *state;
2148 	int fd;
2149 	ssize_t bytes;
2150 
2151 	state = D6_CSTATE(ifp);
2152 	logger(ifp->ctx, LOG_DEBUG,
2153 	    "%s: writing lease `%s'", ifp->name, state->leasefile);
2154 
2155 	fd = open(state->leasefile, O_WRONLY | O_CREAT | O_TRUNC, 0644);
2156 	if (fd == -1) {
2157 		logger(ifp->ctx, LOG_ERR, "%s: dhcp6_writelease: %m", ifp->name);
2158 		return -1;
2159 	}
2160 	bytes = write(fd, state->new, state->new_len);
2161 	close(fd);
2162 	return bytes;
2163 }
2164 
2165 static int
2166 dhcp6_readlease(struct interface *ifp, int validate)
2167 {
2168 	struct dhcp6_state *state;
2169 	struct stat st;
2170 	int fd;
2171 	ssize_t bytes;
2172 	const struct dhcp6_option *o;
2173 	struct timespec acquired;
2174 	time_t now;
2175 	int retval;
2176 
2177 	state = D6_STATE(ifp);
2178 	if (stat(state->leasefile, &st) == -1)
2179 		return -1;
2180 	logger(ifp->ctx, LOG_DEBUG, "%s: reading lease `%s'",
2181 	    ifp->name, state->leasefile);
2182 	if (st.st_size > UINT32_MAX) {
2183 		errno = E2BIG;
2184 		return -1;
2185 	}
2186 	if ((fd = open(state->leasefile, O_RDONLY)) == -1)
2187 		return -1;
2188 	if ((state->new = malloc((size_t)st.st_size)) == NULL)
2189 		return -1;
2190 	retval = -1;
2191 	state->new_len = (size_t)st.st_size;
2192 	bytes = read(fd, state->new, state->new_len);
2193 	close(fd);
2194 	if (bytes != (ssize_t)state->new_len)
2195 		goto ex;
2196 
2197 	/* If not validating IA's and if they have expired,
2198 	 * skip to the auth check. */
2199 	if (!validate) {
2200 		fd = 0;
2201 		goto auth;
2202 	}
2203 
2204 	if ((now = time(NULL)) == -1)
2205 		goto ex;
2206 
2207 	clock_gettime(CLOCK_MONOTONIC, &acquired);
2208 	acquired.tv_sec -= now - st.st_mtime;
2209 
2210 	/* Check to see if the lease is still valid */
2211 	fd = dhcp6_validatelease(ifp, state->new, state->new_len, NULL,
2212 	    &acquired);
2213 	if (fd == -1)
2214 		goto ex;
2215 
2216 	if (!(ifp->ctx->options & DHCPCD_DUMPLEASE) &&
2217 	    state->expire != ND6_INFINITE_LIFETIME)
2218 	{
2219 		if ((time_t)state->expire < now - st.st_mtime) {
2220 			logger(ifp->ctx,
2221 			    LOG_DEBUG,"%s: discarding expired lease",
2222 			    ifp->name);
2223 			retval = 0;
2224 			goto ex;
2225 		}
2226 	}
2227 
2228 auth:
2229 
2230 	retval = 0;
2231 	/* Authenticate the message */
2232 	o = dhcp6_getmoption(D6_OPTION_AUTH, state->new, state->new_len);
2233 	if (o) {
2234 		if (dhcp_auth_validate(&state->auth, &ifp->options->auth,
2235 		    (uint8_t *)state->new, state->new_len, 6, state->new->type,
2236 		    D6_COPTION_DATA(o), ntohs(o->len)) == NULL)
2237 		{
2238 			logger(ifp->ctx, LOG_DEBUG,
2239 			    "%s: dhcp_auth_validate: %m", ifp->name);
2240 			logger(ifp->ctx, LOG_ERR,
2241 			    "%s: authentication failed", ifp->name);
2242 			goto ex;
2243 		}
2244 		if (state->auth.token)
2245 			logger(ifp->ctx, LOG_DEBUG,
2246 			    "%s: validated using 0x%08" PRIu32,
2247 			    ifp->name, state->auth.token->secretid);
2248 		else
2249 			logger(ifp->ctx, LOG_DEBUG,
2250 			    "%s: accepted reconfigure key", ifp->name);
2251 	} else if ((ifp->options->auth.options & DHCPCD_AUTH_SENDREQUIRE) ==
2252 	    DHCPCD_AUTH_SENDREQUIRE)
2253 	{
2254 		logger(ifp->ctx, LOG_ERR,
2255 		    "%s: authentication now required", ifp->name);
2256 		goto ex;
2257 	}
2258 
2259 	return fd;
2260 
2261 ex:
2262 	dhcp6_freedrop_addrs(ifp, 0, NULL);
2263 	free(state->new);
2264 	state->new = NULL;
2265 	state->new_len = 0;
2266 	if (!(ifp->ctx->options & DHCPCD_DUMPLEASE))
2267 		unlink(state->leasefile);
2268 	return retval;
2269 }
2270 
2271 static void
2272 dhcp6_startinit(struct interface *ifp)
2273 {
2274 	struct dhcp6_state *state;
2275 	int r;
2276 	uint8_t has_ta, has_non_ta;
2277 	size_t i;
2278 
2279 	state = D6_STATE(ifp);
2280 	state->state = DH6S_INIT;
2281 	state->expire = ND6_INFINITE_LIFETIME;
2282 	state->lowpl = ND6_INFINITE_LIFETIME;
2283 
2284 	dhcp6_addrequestedaddrs(ifp);
2285 	has_ta = has_non_ta = 0;
2286 	for (i = 0; i < ifp->options->ia_len; i++) {
2287 		switch (ifp->options->ia[i].ia_type) {
2288 		case D6_OPTION_IA_TA:
2289 			has_ta = 1;
2290 			break;
2291 		default:
2292 			has_non_ta = 1;
2293 		}
2294 	}
2295 
2296 	if (!(ifp->ctx->options & DHCPCD_TEST) &&
2297 	    !(has_ta && !has_non_ta) &&
2298 	    ifp->options->reboot != 0)
2299 	{
2300 		r = dhcp6_readlease(ifp, 1);
2301 		if (r == -1) {
2302 			if (errno != ENOENT)
2303 				logger(ifp->ctx, LOG_ERR,
2304 				    "%s: dhcp6_readlease: %s: %m",
2305 				    ifp->name, state->leasefile);
2306 		} else if (r != 0) {
2307 			/* RFC 3633 section 12.1 */
2308 			if (dhcp6_hasprefixdelegation(ifp))
2309 				dhcp6_startrebind(ifp);
2310 			else
2311 				dhcp6_startconfirm(ifp);
2312 			return;
2313 		}
2314 	}
2315 	dhcp6_startdiscover(ifp);
2316 }
2317 
2318 static struct ipv6_addr *
2319 dhcp6_ifdelegateaddr(struct interface *ifp, struct ipv6_addr *prefix,
2320     const struct if_sla *sla, struct if_ia *ia, struct interface *ifs)
2321 {
2322 	struct dhcp6_state *state;
2323 	struct in6_addr addr;
2324 	struct ipv6_addr *a, *ap, *apn;
2325 	char sabuf[INET6_ADDRSTRLEN];
2326 	const char *sa;
2327 	int pfxlen;
2328 
2329 	/* RFC6603 Section 4.2 */
2330 	if (strcmp(ifp->name, ifs->name) == 0) {
2331 		if (prefix->prefix_exclude_len == 0) {
2332 			/* Don't spam the log automatically */
2333 			if (sla)
2334 				logger(ifp->ctx, LOG_WARNING,
2335 				    "%s: DHCPv6 server does not support "
2336 				    "OPTION_PD_EXCLUDE",
2337 				    ifp->name);
2338 			return NULL;
2339 		}
2340 		pfxlen = prefix->prefix_exclude_len;
2341 		memcpy(&addr, &prefix->prefix_exclude, sizeof(addr));
2342 	} else if ((pfxlen = dhcp6_delegateaddr(&addr, ifp, prefix,
2343 	    sla, ia)) == -1)
2344 		return NULL;
2345 
2346 
2347 	a = calloc(1, sizeof(*a));
2348 	if (a == NULL) {
2349 		logger(ifp->ctx, LOG_ERR, "%s: %m", __func__);
2350 		return NULL;
2351 	}
2352 	a->iface = ifp;
2353 	a->flags = IPV6_AF_NEW | IPV6_AF_ONLINK;
2354 	a->dadcallback = dhcp6_dadcallback;
2355 	a->delegating_iface = ifs;
2356 	memcpy(&a->iaid, &prefix->iaid, sizeof(a->iaid));
2357 	a->created = a->acquired = prefix->acquired;
2358 	a->prefix_pltime = prefix->prefix_pltime;
2359 	a->prefix_vltime = prefix->prefix_vltime;
2360 	a->prefix = addr;
2361 	a->prefix_len = (uint8_t)pfxlen;
2362 
2363 	/* Wang a 1 at the end as the prefix could be >64
2364 	 * making SLAAC impossible. */
2365 	a->addr = a->prefix;
2366 	a->addr.s6_addr[sizeof(a->addr.s6_addr) - 1] =
2367 	    (uint8_t)(a->addr.s6_addr[sizeof(a->addr.s6_addr) - 1] + 1);
2368 
2369 	state = D6_STATE(ifp);
2370 	/* Remove any exiting address */
2371 	TAILQ_FOREACH_SAFE(ap, &state->addrs, next, apn) {
2372 		if (IN6_ARE_ADDR_EQUAL(&ap->addr, &a->addr)) {
2373 			TAILQ_REMOVE(&state->addrs, ap, next);
2374 			/* Keep our flags */
2375 			a->flags |= ap->flags;
2376 			a->flags &= ~IPV6_AF_NEW;
2377 			a->created = ap->created;
2378 			ipv6_freeaddr(ap);
2379 		}
2380 	}
2381 
2382 	sa = inet_ntop(AF_INET6, &a->addr, sabuf, sizeof(sabuf));
2383 	snprintf(a->saddr, sizeof(a->saddr), "%s/%d", sa, a->prefix_len);
2384 	TAILQ_INSERT_TAIL(&state->addrs, a, next);
2385 	return a;
2386 }
2387 
2388 static void
2389 dhcp6_script_try_run(struct interface *ifp, int delegated)
2390 {
2391 	struct dhcp6_state *state;
2392 	struct ipv6_addr *ap;
2393 	int completed;
2394 
2395 	state = D6_STATE(ifp);
2396 	completed = 1;
2397 	/* If all addresses have completed DAD run the script */
2398 	TAILQ_FOREACH(ap, &state->addrs, next) {
2399 		if (!(ap->flags & IPV6_AF_ADDED))
2400 			continue;
2401 		if (ap->flags & IPV6_AF_ONLINK) {
2402 			if (!(ap->flags & IPV6_AF_DADCOMPLETED) &&
2403 			    ipv6_iffindaddr(ap->iface, &ap->addr))
2404 				ap->flags |= IPV6_AF_DADCOMPLETED;
2405 			if ((ap->flags & IPV6_AF_DADCOMPLETED) == 0 &&
2406 			    ((delegated && ap->delegating_iface) ||
2407 			    (!delegated && !ap->delegating_iface)))
2408 			{
2409 				completed = 0;
2410 				break;
2411 			}
2412 		}
2413 	}
2414 	if (completed) {
2415 		script_runreason(ifp, delegated ? "DELEGATED6" : state->reason);
2416 		if (!delegated)
2417 			dhcpcd_daemonise(ifp->ctx);
2418 	} else
2419 		logger(ifp->ctx, LOG_DEBUG,
2420 		    "%s: waiting for DHCPv6 DAD to complete", ifp->name);
2421 }
2422 
2423 static void
2424 dhcp6_delegate_prefix(struct interface *ifp)
2425 {
2426 	struct if_options *ifo;
2427 	struct dhcp6_state *state, *ifd_state;
2428 	struct ipv6_addr *ap;
2429 	size_t i, j, k;
2430 	struct if_ia *ia;
2431 	struct if_sla *sla;
2432 	struct interface *ifd;
2433 	uint8_t carrier_warned, abrt;
2434 
2435 	ifo = ifp->options;
2436 	state = D6_STATE(ifp);
2437 
2438 	/* Try to load configured interfaces for delegation that do not exist */
2439 	for (i = 0; i < ifo->ia_len; i++) {
2440 		ia = &ifo->ia[i];
2441 		for (j = 0; j < ia->sla_len; j++) {
2442 			sla = &ia->sla[j];
2443 			for (k = 0; k < i; j++)
2444 				if (strcmp(sla->ifname, ia->sla[j].ifname) == 0)
2445 					break;
2446 			if (j >= i &&
2447 			    if_find(ifp->ctx->ifaces, sla->ifname) == NULL)
2448 			{
2449 				logger(ifp->ctx, LOG_INFO,
2450 				    "%s: loading for delegation", sla->ifname);
2451 				if (dhcpcd_handleinterface(ifp->ctx, 2,
2452 				    sla->ifname) == -1)
2453 					logger(ifp->ctx, LOG_ERR,
2454 					    "%s: interface does not exist"
2455 					    " for delegation",
2456 					    sla->ifname);
2457 			}
2458 		}
2459 	}
2460 
2461 	TAILQ_FOREACH(ifd, ifp->ctx->ifaces, next) {
2462 		k = 0;
2463 		carrier_warned = abrt = 0;
2464 		TAILQ_FOREACH(ap, &state->addrs, next) {
2465 			if (!(ap->flags & IPV6_AF_DELEGATEDPFX))
2466 				continue;
2467 			if (ap->flags & IPV6_AF_NEW) {
2468 				ap->flags &= ~IPV6_AF_NEW;
2469 				logger(ifp->ctx, LOG_DEBUG,
2470 				    "%s: delegated prefix %s",
2471 				    ifp->name, ap->saddr);
2472 			}
2473 			for (i = 0; i < ifo->ia_len; i++) {
2474 				ia = &ifo->ia[i];
2475 				if (memcmp(ia->iaid, ap->iaid,
2476 				    sizeof(ia->iaid)))
2477 					continue;
2478 				if (ia->sla_len == 0) {
2479 					/* no SLA configured, so lets
2480 					 * automate it */
2481 					if (ifd->carrier != LINK_UP) {
2482 						logger(ifp->ctx, LOG_DEBUG,
2483 						    "%s: has no carrier, cannot"
2484 						    " delegate addresses",
2485 						    ifd->name);
2486 						carrier_warned = 1;
2487 						break;
2488 					}
2489 					if (dhcp6_ifdelegateaddr(ifd, ap,
2490 					    NULL, ia, ifp))
2491 						k++;
2492 				}
2493 				for (j = 0; j < ia->sla_len; j++) {
2494 					sla = &ia->sla[j];
2495 					if (sla->sla_set && sla->sla == 0)
2496 						ap->flags |=
2497 						    IPV6_AF_DELEGATEDZERO;
2498 					if (strcmp(ifd->name, sla->ifname))
2499 						continue;
2500 					if (ifd->carrier != LINK_UP) {
2501 						logger(ifp->ctx, LOG_DEBUG,
2502 						    "%s: has no carrier, cannot"
2503 						    " delegate addresses",
2504 						    ifd->name);
2505 						carrier_warned = 1;
2506 						break;
2507 					}
2508 					if (dhcp6_ifdelegateaddr(ifd, ap,
2509 					    sla, ia, ifp))
2510 						k++;
2511 				}
2512 				if (carrier_warned ||abrt)
2513 					break;
2514 			}
2515 			if (carrier_warned || abrt)
2516 				break;
2517 		}
2518 		if (k && !carrier_warned) {
2519 			ifd_state = D6_STATE(ifd);
2520 			ipv6_addaddrs(&ifd_state->addrs);
2521 			if_initrt6(ifd);
2522 			dhcp6_script_try_run(ifd, 1);
2523 		}
2524 	}
2525 }
2526 
2527 static void
2528 dhcp6_find_delegates1(void *arg)
2529 {
2530 
2531 	dhcp6_find_delegates(arg);
2532 }
2533 
2534 size_t
2535 dhcp6_find_delegates(struct interface *ifp)
2536 {
2537 	struct if_options *ifo;
2538 	struct dhcp6_state *state;
2539 	struct ipv6_addr *ap;
2540 	size_t i, j, k;
2541 	struct if_ia *ia;
2542 	struct if_sla *sla;
2543 	struct interface *ifd;
2544 
2545 	k = 0;
2546 	TAILQ_FOREACH(ifd, ifp->ctx->ifaces, next) {
2547 		ifo = ifd->options;
2548 		state = D6_STATE(ifd);
2549 		if (state == NULL || state->state != DH6S_BOUND)
2550 			continue;
2551 		TAILQ_FOREACH(ap, &state->addrs, next) {
2552 			if (!(ap->flags & IPV6_AF_DELEGATEDPFX))
2553 				continue;
2554 			for (i = 0; i < ifo->ia_len; i++) {
2555 				ia = &ifo->ia[i];
2556 				if (memcmp(ia->iaid, ap->iaid,
2557 				    sizeof(ia->iaid)))
2558 					continue;
2559 				for (j = 0; j < ia->sla_len; j++) {
2560 					sla = &ia->sla[j];
2561 					if (strcmp(ifp->name, sla->ifname))
2562 						continue;
2563 					if (ipv6_linklocal(ifp) == NULL) {
2564 						logger(ifp->ctx, LOG_DEBUG,
2565 						    "%s: delaying adding"
2566 						    " delegated addresses for"
2567 						    " LL address",
2568 						    ifp->name);
2569 						ipv6_addlinklocalcallback(ifp,
2570 						    dhcp6_find_delegates1, ifp);
2571 						return 1;
2572 					}
2573 					if (dhcp6_ifdelegateaddr(ifp, ap,
2574 					    sla, ia, ifd))
2575 					    k++;
2576 				}
2577 			}
2578 		}
2579 	}
2580 
2581 	if (k) {
2582 		logger(ifp->ctx, LOG_INFO,
2583 		    "%s: adding delegated prefixes", ifp->name);
2584 		state = D6_STATE(ifp);
2585 		state->state = DH6S_DELEGATED;
2586 		ipv6_addaddrs(&state->addrs);
2587 		if_initrt6(ifp);
2588 		ipv6_buildroutes(ifp->ctx);
2589 		dhcp6_script_try_run(ifp, 1);
2590 	}
2591 	return k;
2592 }
2593 
2594 /* ARGSUSED */
2595 static void
2596 dhcp6_handledata(void *arg)
2597 {
2598 	struct dhcpcd_ctx *dctx;
2599 	struct ipv6_ctx *ctx;
2600 	size_t i, len;
2601 	ssize_t bytes;
2602 	struct cmsghdr *cm;
2603 	struct in6_pktinfo pkt;
2604 	struct interface *ifp;
2605 	const char *op;
2606 	struct dhcp6_message *r;
2607 	struct dhcp6_state *state;
2608 	const struct dhcp6_option *o, *auth;
2609 	const struct dhcp_opt *opt;
2610 	const struct if_options *ifo;
2611 	struct ipv6_addr *ap;
2612 	uint8_t has_new;
2613 	int error;
2614 	uint32_t u32;
2615 
2616 	dctx = arg;
2617 	ctx = dctx->ipv6;
2618 	ctx->rcvhdr.msg_controllen = CMSG_SPACE(sizeof(struct in6_pktinfo));
2619 	bytes = recvmsg(ctx->dhcp_fd, &ctx->rcvhdr, 0);
2620 	if (bytes == -1) {
2621 		logger(dctx, LOG_ERR, "%s: recvmsg: %m", __func__);
2622 		close(ctx->dhcp_fd);
2623 		eloop_event_delete(dctx->eloop, ctx->dhcp_fd);
2624 		ctx->dhcp_fd = -1;
2625 		return;
2626 	}
2627 	len = (size_t)bytes;
2628 	ctx->sfrom = inet_ntop(AF_INET6, &ctx->from.sin6_addr,
2629 	    ctx->ntopbuf, sizeof(ctx->ntopbuf));
2630 	if (len < sizeof(struct dhcp6_message)) {
2631 		logger(dctx, LOG_ERR,
2632 		    "DHCPv6 packet too short from %s", ctx->sfrom);
2633 		return;
2634 	}
2635 
2636 	pkt.ipi6_ifindex = 0;
2637 	for (cm = (struct cmsghdr *)CMSG_FIRSTHDR(&ctx->rcvhdr);
2638 	     cm;
2639 	     cm = (struct cmsghdr *)CMSG_NXTHDR(&ctx->rcvhdr, cm))
2640 	{
2641 		if (cm->cmsg_level != IPPROTO_IPV6)
2642 			continue;
2643 		switch(cm->cmsg_type) {
2644 		case IPV6_PKTINFO:
2645 			if (cm->cmsg_len == CMSG_LEN(sizeof(pkt)))
2646 				memcpy(&pkt, CMSG_DATA(cm), sizeof(pkt));
2647 			break;
2648 		}
2649 	}
2650 	if (pkt.ipi6_ifindex == 0) {
2651 		logger(dctx, LOG_ERR,
2652 		    "DHCPv6 reply did not contain index from %s", ctx->sfrom);
2653 		return;
2654 	}
2655 
2656 	TAILQ_FOREACH(ifp, dctx->ifaces, next) {
2657 		if (ifp->index == (unsigned int)pkt.ipi6_ifindex)
2658 			break;
2659 	}
2660 	if (ifp == NULL) {
2661 		logger(dctx, LOG_DEBUG,
2662 		    "DHCPv6 reply for unexpected interface from %s",
2663 		    ctx->sfrom);
2664 		return;
2665 	}
2666 
2667 	state = D6_STATE(ifp);
2668 	if (state == NULL || state->send == NULL) {
2669 		logger(ifp->ctx, LOG_DEBUG,
2670 		    "%s: DHCPv6 reply received but not running", ifp->name);
2671 		return;
2672 	}
2673 
2674 	r = (struct dhcp6_message *)ctx->rcvhdr.msg_iov[0].iov_base;
2675 	/* We're already bound and this message is for another machine */
2676 	/* XXX DELEGATED? */
2677 	if (r->type != DHCP6_RECONFIGURE &&
2678 	    (state->state == DH6S_BOUND || state->state == DH6S_INFORMED))
2679 	{
2680 		logger(ifp->ctx, LOG_DEBUG,
2681 		    "%s: DHCPv6 reply received but already bound", ifp->name);
2682 		return;
2683 	}
2684 
2685 	if (r->type != DHCP6_RECONFIGURE &&
2686 	    (r->xid[0] != state->send->xid[0] ||
2687 	    r->xid[1] != state->send->xid[1] ||
2688 	    r->xid[2] != state->send->xid[2]))
2689 	{
2690 		logger(dctx, LOG_DEBUG,
2691 		    "%s: wrong xid 0x%02x%02x%02x"
2692 		    " (expecting 0x%02x%02x%02x) from %s",
2693 		    ifp->name,
2694 		    r->xid[0], r->xid[1], r->xid[2],
2695 		    state->send->xid[0], state->send->xid[1],
2696 		    state->send->xid[2],
2697 		    ctx->sfrom);
2698 		return;
2699 	}
2700 
2701 	if (dhcp6_getmoption(D6_OPTION_SERVERID, r, len) == NULL) {
2702 		logger(ifp->ctx, LOG_DEBUG, "%s: no DHCPv6 server ID from %s",
2703 		    ifp->name, ctx->sfrom);
2704 		return;
2705 	}
2706 
2707 	o = dhcp6_getmoption(D6_OPTION_CLIENTID, r, len);
2708 	if (o == NULL || ntohs(o->len) != dctx->duid_len ||
2709 	    memcmp(D6_COPTION_DATA(o), dctx->duid, dctx->duid_len) != 0)
2710 	{
2711 		logger(ifp->ctx, LOG_DEBUG, "%s: incorrect client ID from %s",
2712 		    ifp->name, ctx->sfrom);
2713 		return;
2714 	}
2715 
2716 	ifo = ifp->options;
2717 	for (i = 0, opt = dctx->dhcp6_opts;
2718 	    i < dctx->dhcp6_opts_len;
2719 	    i++, opt++)
2720 	{
2721 		if (has_option_mask(ifo->requiremask6, opt->option) &&
2722 		    dhcp6_getmoption((uint16_t)opt->option, r, len) == NULL)
2723 		{
2724 			logger(ifp->ctx, LOG_WARNING,
2725 			    "%s: reject DHCPv6 (no option %s) from %s",
2726 			    ifp->name, opt->var, ctx->sfrom);
2727 			return;
2728 		}
2729 		if (has_option_mask(ifo->rejectmask6, opt->option) &&
2730 		    dhcp6_getmoption((uint16_t)opt->option, r, len))
2731 		{
2732 			logger(ifp->ctx, LOG_WARNING,
2733 			    "%s: reject DHCPv6 (option %s) from %s",
2734 			    ifp->name, opt->var, ctx->sfrom);
2735 			return;
2736 		}
2737 	}
2738 
2739 	/* Authenticate the message */
2740 	auth = dhcp6_getmoption(D6_OPTION_AUTH, r, len);
2741 	if (auth) {
2742 		if (dhcp_auth_validate(&state->auth, &ifo->auth,
2743 		    (uint8_t *)r, len, 6, r->type,
2744 		    D6_COPTION_DATA(auth), ntohs(auth->len)) == NULL)
2745 		{
2746 			logger(ifp->ctx, LOG_DEBUG, "dhcp_auth_validate: %m");
2747 			logger(ifp->ctx, LOG_ERR,
2748 			    "%s: authentication failed from %s",
2749 			    ifp->name, ctx->sfrom);
2750 			return;
2751 		}
2752 		if (state->auth.token)
2753 			logger(ifp->ctx, LOG_DEBUG,
2754 			    "%s: validated using 0x%08" PRIu32,
2755 			    ifp->name, state->auth.token->secretid);
2756 		else
2757 			logger(ifp->ctx, LOG_DEBUG,
2758 			    "%s: accepted reconfigure key", ifp->name);
2759 	} else if (ifo->auth.options & DHCPCD_AUTH_SEND) {
2760 		if (ifo->auth.options & DHCPCD_AUTH_REQUIRE) {
2761 			logger(ifp->ctx, LOG_ERR,
2762 			    "%s: no authentication from %s",
2763 			    ifp->name, ctx->sfrom);
2764 			return;
2765 		}
2766 		logger(ifp->ctx, LOG_WARNING,
2767 		    "%s: no authentication from %s", ifp->name, ctx->sfrom);
2768 	}
2769 
2770 	op = dhcp6_get_op(r->type);
2771 	switch(r->type) {
2772 	case DHCP6_REPLY:
2773 		switch(state->state) {
2774 		case DH6S_INFORM:
2775 			if (dhcp6_checkstatusok(ifp, r, NULL, len) == -1)
2776 				return;
2777 			/* RFC4242 */
2778 			o = dhcp6_getmoption(D6_OPTION_INFO_REFRESH_TIME,
2779 			    r, len);
2780 			if (o == NULL || ntohs(o->len) != sizeof(u32))
2781 				state->renew = IRT_DEFAULT;
2782 			else {
2783 				memcpy(&u32, D6_COPTION_DATA(o), sizeof(u32));
2784 				state->renew = ntohl(u32);
2785 				if (state->renew < IRT_MINIMUM)
2786 					state->renew = IRT_MINIMUM;
2787 			}
2788 			break;
2789 		case DH6S_CONFIRM:
2790 			error = dhcp6_checkstatusok(ifp, r, NULL, len);
2791 			/* If we got an OK status the chances are that we
2792 			 * didn't get the IA's returned, so preserve them
2793 			 * from our saved response */
2794 			if (error == 1)
2795 				goto recv;
2796 			if (error == -1 ||
2797 			    dhcp6_validatelease(ifp, r, len,
2798 			    ctx->sfrom, NULL) == -1)
2799 			{
2800 				dhcp6_startdiscover(ifp);
2801 				return;
2802 			}
2803 			break;
2804 		case DH6S_DISCOVER:
2805 			if (has_option_mask(ifo->requestmask6,
2806 			    D6_OPTION_RAPID_COMMIT) &&
2807 			    dhcp6_getmoption(D6_OPTION_RAPID_COMMIT, r, len))
2808 				state->state = DH6S_REQUEST;
2809 			else
2810 				op = NULL;
2811 		case DH6S_REQUEST: /* FALLTHROUGH */
2812 		case DH6S_RENEW: /* FALLTHROUGH */
2813 		case DH6S_REBIND:
2814 			if (dhcp6_validatelease(ifp, r, len,
2815 			    ctx->sfrom, NULL) == -1)
2816 			{
2817 				/* PD doesn't use CONFIRM, so REBIND could
2818 				 * throw up an invalid prefix if we
2819 				 * changed link */
2820 				if (dhcp6_hasprefixdelegation(ifp))
2821 					dhcp6_startdiscover(ifp);
2822 				return;
2823 			}
2824 			break;
2825 		default:
2826 			op = NULL;
2827 		}
2828 		break;
2829 	case DHCP6_ADVERTISE:
2830 		if (state->state != DH6S_DISCOVER) {
2831 			op = NULL;
2832 			break;
2833 		}
2834 		/* RFC7083 */
2835 		o = dhcp6_getmoption(D6_OPTION_SOL_MAX_RT, r, len);
2836 		if (o && ntohs(o->len) >= sizeof(u32)) {
2837 			memcpy(&u32, D6_COPTION_DATA(o), sizeof(u32));
2838 			u32 = ntohl(u32);
2839 			if (u32 >= 60 && u32 <= 86400) {
2840 				logger(ifp->ctx, LOG_DEBUG,
2841 				    "%s: SOL_MAX_RT %llu -> %d", ifp->name,
2842 				    (unsigned long long)state->sol_max_rt, u32);
2843 				state->sol_max_rt = (time_t)u32;
2844 			} else
2845 				logger(ifp->ctx, LOG_ERR,
2846 				    "%s: invalid SOL_MAX_RT %d",
2847 				    ifp->name, u32);
2848 		}
2849 		o = dhcp6_getmoption(D6_OPTION_INF_MAX_RT, r, len);
2850 		if (o && ntohs(o->len) >= sizeof(u32)) {
2851 			memcpy(&u32, D6_COPTION_DATA(o), sizeof(u32));
2852 			u32 = ntohl(u32);
2853 			if (u32 >= 60 && u32 <= 86400) {
2854 				logger(ifp->ctx, LOG_DEBUG,
2855 				    "%s: INF_MAX_RT %llu -> %d",
2856 				    ifp->name,
2857 				    (unsigned long long)state->inf_max_rt, u32);
2858 				state->inf_max_rt = (time_t)u32;
2859 			} else
2860 				logger(ifp->ctx, LOG_ERR,
2861 				    "%s: invalid INF_MAX_RT %d",
2862 				    ifp->name, u32);
2863 		}
2864 		if (dhcp6_validatelease(ifp, r, len, ctx->sfrom, NULL) == -1)
2865 			return;
2866 		break;
2867 	case DHCP6_RECONFIGURE:
2868 		if (auth == NULL) {
2869 			logger(ifp->ctx, LOG_ERR,
2870 			    "%s: unauthenticated %s from %s",
2871 			    ifp->name, op, ctx->sfrom);
2872 			if (ifo->auth.options & DHCPCD_AUTH_REQUIRE)
2873 				return;
2874 		}
2875 		logger(ifp->ctx, LOG_INFO, "%s: %s from %s",
2876 		    ifp->name, op, ctx->sfrom);
2877 		o = dhcp6_getmoption(D6_OPTION_RECONF_MSG, r, len);
2878 		if (o == NULL) {
2879 			logger(ifp->ctx, LOG_ERR,
2880 			    "%s: missing Reconfigure Message option",
2881 			    ifp->name);
2882 			return;
2883 		}
2884 		if (ntohs(o->len) != 1) {
2885 			logger(ifp->ctx, LOG_ERR,
2886 			    "%s: missing Reconfigure Message type", ifp->name);
2887 			return;
2888 		}
2889 		switch(*D6_COPTION_DATA(o)) {
2890 		case DHCP6_RENEW:
2891 			if (state->state != DH6S_BOUND) {
2892 				logger(ifp->ctx, LOG_ERR,
2893 				    "%s: not bound, ignoring %s",
2894 				    ifp->name, op);
2895 				return;
2896 			}
2897 			eloop_timeout_delete(ifp->ctx->eloop,
2898 			    dhcp6_startrenew, ifp);
2899 			dhcp6_startrenew(ifp);
2900 			break;
2901 		case DHCP6_INFORMATION_REQ:
2902 			if (state->state != DH6S_INFORMED) {
2903 				logger(ifp->ctx, LOG_ERR,
2904 				    "%s: not informed, ignoring %s",
2905 				    ifp->name, op);
2906 				return;
2907 			}
2908 			eloop_timeout_delete(ifp->ctx->eloop,
2909 			    dhcp6_sendinform, ifp);
2910 			dhcp6_startinform(ifp);
2911 			break;
2912 		default:
2913 			logger(ifp->ctx, LOG_ERR,
2914 			    "%s: unsupported %s type %d",
2915 			    ifp->name, op, *D6_COPTION_DATA(o));
2916 			break;
2917 		}
2918 		return;
2919 	default:
2920 		logger(ifp->ctx, LOG_ERR, "%s: invalid DHCP6 type %s (%d)",
2921 		    ifp->name, op, r->type);
2922 		return;
2923 	}
2924 	if (op == NULL) {
2925 		logger(ifp->ctx, LOG_WARNING,
2926 		    "%s: invalid state for DHCP6 type %s (%d)",
2927 		    ifp->name, op, r->type);
2928 		return;
2929 	}
2930 
2931 	if (state->recv_len < (size_t)len) {
2932 		free(state->recv);
2933 		state->recv = malloc(len);
2934 		if (state->recv == NULL) {
2935 			logger(ifp->ctx, LOG_ERR,
2936 			    "%s: malloc recv: %m", ifp->name);
2937 			return;
2938 		}
2939 	}
2940 	memcpy(state->recv, r, len);
2941 	state->recv_len = len;
2942 
2943 	switch(r->type) {
2944 	case DHCP6_ADVERTISE:
2945 		if (state->state == DH6S_REQUEST) /* rapid commit */
2946 			break;
2947 		ap = TAILQ_FIRST(&state->addrs);
2948 		logger(ifp->ctx, LOG_INFO, "%s: ADV %s from %s",
2949 		    ifp->name, ap->saddr, ctx->sfrom);
2950 		if (ifp->ctx->options & DHCPCD_TEST)
2951 			break;
2952 		dhcp6_startrequest(ifp);
2953 		return;
2954 	}
2955 
2956 recv:
2957 	has_new = 0;
2958 	TAILQ_FOREACH(ap, &state->addrs, next) {
2959 		if (ap->flags & IPV6_AF_NEW) {
2960 			has_new = 1;
2961 			break;
2962 		}
2963 	}
2964 	logger(ifp->ctx, has_new ? LOG_INFO : LOG_DEBUG,
2965 	    "%s: %s received from %s", ifp->name, op, ctx->sfrom);
2966 
2967 	state->reason = NULL;
2968 	eloop_timeout_delete(ifp->ctx->eloop, NULL, ifp);
2969 	switch(state->state) {
2970 	case DH6S_INFORM:
2971 		state->rebind = 0;
2972 		state->expire = ND6_INFINITE_LIFETIME;
2973 		state->lowpl = ND6_INFINITE_LIFETIME;
2974 		state->reason = "INFORM6";
2975 		break;
2976 	case DH6S_REQUEST:
2977 		if (state->reason == NULL)
2978 			state->reason = "BOUND6";
2979 		/* FALLTHROUGH */
2980 	case DH6S_RENEW:
2981 		if (state->reason == NULL)
2982 			state->reason = "RENEW6";
2983 		/* FALLTHROUGH */
2984 	case DH6S_REBIND:
2985 		if (state->reason == NULL)
2986 			state->reason = "REBIND6";
2987 		/* FALLTHROUGH */
2988 	case DH6S_CONFIRM:
2989 		if (state->reason == NULL)
2990 			state->reason = "REBOOT6";
2991 		if (state->renew == 0) {
2992 			if (state->expire == ND6_INFINITE_LIFETIME)
2993 				state->renew = ND6_INFINITE_LIFETIME;
2994 			else if (state->lowpl != ND6_INFINITE_LIFETIME)
2995 				state->renew = (uint32_t)(state->lowpl * 0.5);
2996 		}
2997 		if (state->rebind == 0) {
2998 			if (state->expire == ND6_INFINITE_LIFETIME)
2999 				state->rebind = ND6_INFINITE_LIFETIME;
3000 			else if (state->lowpl != ND6_INFINITE_LIFETIME)
3001 				state->rebind = (uint32_t)(state->lowpl * 0.8);
3002 		}
3003 		break;
3004 	default:
3005 		state->reason = "UNKNOWN6";
3006 		break;
3007 	}
3008 
3009 	if (state->state != DH6S_CONFIRM) {
3010 		free(state->old);
3011 		state->old = state->new;
3012 		state->old_len = state->new_len;
3013 		state->new = state->recv;
3014 		state->new_len = state->recv_len;
3015 		state->recv = NULL;
3016 		state->recv_len = 0;
3017 	}
3018 
3019 	if (ifp->ctx->options & DHCPCD_TEST)
3020 		script_runreason(ifp, "TEST");
3021 	else {
3022 		if (state->state == DH6S_INFORM)
3023 			state->state = DH6S_INFORMED;
3024 		else
3025 			state->state = DH6S_BOUND;
3026 		if (state->renew && state->renew != ND6_INFINITE_LIFETIME)
3027 			eloop_timeout_add_sec(ifp->ctx->eloop,
3028 			    (time_t)state->renew,
3029 			    state->state == DH6S_INFORMED ?
3030 			    dhcp6_startinform : dhcp6_startrenew, ifp);
3031 		if (state->rebind && state->rebind != ND6_INFINITE_LIFETIME)
3032 			eloop_timeout_add_sec(ifp->ctx->eloop,
3033 			    (time_t)state->rebind, dhcp6_startrebind, ifp);
3034 		if (state->expire != ND6_INFINITE_LIFETIME)
3035 			eloop_timeout_add_sec(ifp->ctx->eloop,
3036 			    (time_t)state->expire, dhcp6_startexpire, ifp);
3037 
3038 		ipv6nd_runignoredra(ifp);
3039 		ipv6_addaddrs(&state->addrs);
3040 		dhcp6_delegate_prefix(ifp);
3041 
3042 		if (state->state == DH6S_INFORMED)
3043 			logger(ifp->ctx, has_new ? LOG_INFO : LOG_DEBUG,
3044 			    "%s: refresh in %"PRIu32" seconds",
3045 			    ifp->name, state->renew);
3046 		else if (state->renew || state->rebind)
3047 			logger(ifp->ctx, has_new ? LOG_INFO : LOG_DEBUG,
3048 			    "%s: renew in %"PRIu32" seconds,"
3049 			    " rebind in %"PRIu32" seconds",
3050 			    ifp->name, state->renew, state->rebind);
3051 		else if (state->expire == 0)
3052 			logger(ifp->ctx, has_new ? LOG_INFO : LOG_DEBUG,
3053 			    "%s: will expire", ifp->name);
3054 		if_initrt6(ifp);
3055 		ipv6_buildroutes(ifp->ctx);
3056 		dhcp6_writelease(ifp);
3057 		dhcp6_script_try_run(ifp, 0);
3058 	}
3059 
3060 	if (ifp->ctx->options & DHCPCD_TEST ||
3061 	    (ifp->options->options & DHCPCD_INFORM &&
3062 	    !(ifp->ctx->options & DHCPCD_MASTER)))
3063 	{
3064 		eloop_exit(ifp->ctx->eloop, EXIT_SUCCESS);
3065 	}
3066 }
3067 
3068 static int
3069 dhcp6_open(struct dhcpcd_ctx *dctx)
3070 {
3071 	struct ipv6_ctx *ctx;
3072 	struct sockaddr_in6 sa;
3073 	int n;
3074 
3075 	memset(&sa, 0, sizeof(sa));
3076 	sa.sin6_family = AF_INET6;
3077 	sa.sin6_port = htons(DHCP6_CLIENT_PORT);
3078 #ifdef BSD
3079 	sa.sin6_len = sizeof(sa);
3080 #endif
3081 
3082 	ctx = dctx->ipv6;
3083 	ctx->dhcp_fd = xsocket(PF_INET6, SOCK_DGRAM, IPPROTO_UDP,
3084 	    O_NONBLOCK|O_CLOEXEC);
3085 	if (ctx->dhcp_fd == -1)
3086 		return -1;
3087 
3088 	n = 1;
3089 	if (setsockopt(ctx->dhcp_fd, SOL_SOCKET, SO_REUSEADDR,
3090 	    &n, sizeof(n)) == -1)
3091 		goto errexit;
3092 
3093 	n = 1;
3094 	if (setsockopt(ctx->dhcp_fd, SOL_SOCKET, SO_BROADCAST,
3095 	    &n, sizeof(n)) == -1)
3096 		goto errexit;
3097 
3098 #ifdef SO_REUSEPORT
3099 	n = 1;
3100 	if (setsockopt(ctx->dhcp_fd, SOL_SOCKET, SO_REUSEPORT,
3101 	    &n, sizeof(n)) == -1)
3102 		logger(dctx, LOG_WARNING, "setsockopt: SO_REUSEPORT: %m");
3103 #endif
3104 
3105 	if (bind(ctx->dhcp_fd, (struct sockaddr *)&sa, sizeof(sa)) == -1)
3106 		goto errexit;
3107 
3108 	n = 1;
3109 	if (setsockopt(ctx->dhcp_fd, IPPROTO_IPV6, IPV6_RECVPKTINFO,
3110 	    &n, sizeof(n)) == -1)
3111 		goto errexit;
3112 
3113 	eloop_event_add(dctx->eloop, ctx->dhcp_fd,
3114 	    dhcp6_handledata, dctx, NULL, NULL);
3115 	return 0;
3116 
3117 errexit:
3118 	close(ctx->dhcp_fd);
3119 	ctx->dhcp_fd = -1;
3120 	return -1;
3121 }
3122 
3123 static void
3124 dhcp6_start1(void *arg)
3125 {
3126 	struct interface *ifp = arg;
3127 	struct if_options *ifo = ifp->options;
3128 	struct dhcp6_state *state;
3129 	size_t i;
3130 	const struct dhcp_compat *dhc;
3131 
3132 	state = D6_STATE(ifp);
3133 	/* If no DHCPv6 options are configured,
3134 	   match configured DHCPv4 options to DHCPv6 equivalents. */
3135 	for (i = 0; i < sizeof(ifo->requestmask6); i++) {
3136 		if (ifo->requestmask6[i] != '\0')
3137 			break;
3138 	}
3139 	if (i == sizeof(ifo->requestmask6)) {
3140 		for (dhc = dhcp_compats; dhc->dhcp_opt; dhc++) {
3141 			if (has_option_mask(ifo->requestmask, dhc->dhcp_opt))
3142 				add_option_mask(ifo->requestmask6,
3143 				    dhc->dhcp6_opt);
3144 		}
3145 		if (ifo->fqdn != FQDN_DISABLE ||
3146 		    ifo->options & DHCPCD_HOSTNAME)
3147 			add_option_mask(ifo->requestmask6, D6_OPTION_FQDN);
3148 	}
3149 
3150 	/* Rapid commit won't work with Prefix Delegation Exclusion */
3151 	if (dhcp6_findselfsla(ifp, NULL))
3152 		del_option_mask(ifo->requestmask6, D6_OPTION_RAPID_COMMIT);
3153 
3154 	if (state->state == DH6S_INFORM) {
3155 		add_option_mask(ifo->requestmask6, D6_OPTION_INFO_REFRESH_TIME);
3156 		dhcp6_startinform(ifp);
3157 	} else {
3158 		del_option_mask(ifo->requestmask6, D6_OPTION_INFO_REFRESH_TIME);
3159 		dhcp6_startinit(ifp);
3160 	}
3161 }
3162 
3163 int
3164 dhcp6_start(struct interface *ifp, enum DH6S init_state)
3165 {
3166 	struct dhcp6_state *state;
3167 
3168 	state = D6_STATE(ifp);
3169 	if (state) {
3170 		if (state->state == DH6S_INFORMED &&
3171 		    init_state == DH6S_INFORM)
3172 		{
3173 			dhcp6_startinform(ifp);
3174 			return 0;
3175 		}
3176 		if (init_state == DH6S_INIT &&
3177 		    ifp->options->options & DHCPCD_DHCP6 &&
3178 		    (state->state == DH6S_INFORM ||
3179 		    state->state == DH6S_INFORMED ||
3180 		    state->state == DH6S_DELEGATED))
3181 		{
3182 			/* Change from stateless to stateful */
3183 			goto gogogo;
3184 		}
3185 		/* We're already running DHCP6 */
3186 		/* XXX: What if the managed flag vanishes from all RA? */
3187 		return 0;
3188 	}
3189 
3190 	if (!(ifp->options->options & DHCPCD_DHCP6))
3191 		return 0;
3192 
3193 	if (ifp->ctx->ipv6->dhcp_fd == -1 && dhcp6_open(ifp->ctx) == -1)
3194 		return -1;
3195 
3196 	ifp->if_data[IF_DATA_DHCP6] = calloc(1, sizeof(*state));
3197 	state = D6_STATE(ifp);
3198 	if (state == NULL)
3199 		return -1;
3200 
3201 	state->sol_max_rt = SOL_MAX_RT;
3202 	state->inf_max_rt = INF_MAX_RT;
3203 	TAILQ_INIT(&state->addrs);
3204 
3205 gogogo:
3206 	state->state = init_state;
3207 	dhcp_set_leasefile(state->leasefile, sizeof(state->leasefile),
3208 	    AF_INET6, ifp);
3209 	if (ipv6_linklocal(ifp) == NULL) {
3210 		logger(ifp->ctx, LOG_DEBUG,
3211 		    "%s: delaying DHCPv6 soliciation for LL address",
3212 		    ifp->name);
3213 		ipv6_addlinklocalcallback(ifp, dhcp6_start1, ifp);
3214 		return 0;
3215 	}
3216 
3217 	dhcp6_start1(ifp);
3218 	return 0;
3219 }
3220 
3221 void
3222 dhcp6_reboot(struct interface *ifp)
3223 {
3224 	struct dhcp6_state *state;
3225 
3226 	state = D6_STATE(ifp);
3227 	if (state) {
3228 		switch (state->state) {
3229 		case DH6S_BOUND:
3230 			dhcp6_startrebind(ifp);
3231 			break;
3232 		case DH6S_INFORMED:
3233 			dhcp6_startinform(ifp);
3234 			break;
3235 		default:
3236 			dhcp6_startdiscover(ifp);
3237 			break;
3238 		}
3239 	}
3240 }
3241 
3242 static void
3243 dhcp6_freedrop(struct interface *ifp, int drop, const char *reason)
3244 {
3245 	struct dhcp6_state *state;
3246 	struct dhcpcd_ctx *ctx;
3247 	unsigned long long options;
3248 	int dropdele;
3249 
3250 	/*
3251 	 * As the interface is going away from dhcpcd we need to
3252 	 * remove the delegated addresses, otherwise we lose track
3253 	 * of which interface is delegating as we remeber it by pointer.
3254 	 * So if we need to change this behaviour, we need to change
3255 	 * how we remember which interface delegated.
3256 	 *
3257 	 * XXX The below is no longer true due to the change of the
3258 	 * default IAID, but do PPP links have stable ethernet
3259 	 * addresses?
3260 	 *
3261 	 * To make it more interesting, on some OS's with PPP links
3262 	 * there is no guarantee the delegating interface will have
3263 	 * the same name or index so think very hard before changing
3264 	 * this.
3265 	 */
3266 	if (ifp->options)
3267 		options = ifp->options->options;
3268 	else
3269 		options = 0;
3270 	dropdele = (options & (DHCPCD_STOPPING | DHCPCD_RELEASE) &&
3271 	    (options & DHCPCD_NODROP) != DHCPCD_NODROP);
3272 
3273 	if (ifp->ctx->eloop)
3274 		eloop_timeout_delete(ifp->ctx->eloop, NULL, ifp);
3275 
3276 	if (dropdele)
3277 		dhcp6_delete_delegates(ifp);
3278 
3279 	state = D6_STATE(ifp);
3280 	if (state) {
3281 		/* Failure to send the release may cause this function to
3282 		 * re-enter */
3283 		if (state->state == DH6S_RELEASE) {
3284 			dhcp6_finishrelease(ifp);
3285 			return;
3286 		}
3287 
3288 		if (drop && options & DHCPCD_RELEASE) {
3289 			if (ifp->carrier == LINK_UP &&
3290 			    state->state != DH6S_RELEASED)
3291 			{
3292 				dhcp6_startrelease(ifp);
3293 				return;
3294 			}
3295 			unlink(state->leasefile);
3296 		}
3297 		dhcp6_freedrop_addrs(ifp, drop, NULL);
3298 		free(state->old);
3299 		state->old = state->new;
3300 		state->old_len = state->new_len;
3301 		state->new = NULL;
3302 		state->new_len = 0;
3303 		if (drop && state->old &&
3304 		    (options & DHCPCD_NODROP) != DHCPCD_NODROP)
3305 		{
3306 			if (reason == NULL)
3307 				reason = "STOP6";
3308 			script_runreason(ifp, reason);
3309 		}
3310 		free(state->old);
3311 		free(state->send);
3312 		free(state->recv);
3313 		free(state);
3314 		ifp->if_data[IF_DATA_DHCP6] = NULL;
3315 	}
3316 
3317 	/* If we don't have any more DHCP6 enabled interfaces,
3318 	 * close the global socket and release resources */
3319 	ctx = ifp->ctx;
3320 	if (ctx->ifaces) {
3321 		TAILQ_FOREACH(ifp, ctx->ifaces, next) {
3322 			if (D6_STATE(ifp))
3323 				break;
3324 		}
3325 	}
3326 	if (ifp == NULL && ctx->ipv6) {
3327 		if (ctx->ipv6->dhcp_fd != -1) {
3328 			eloop_event_delete(ctx->eloop, ctx->ipv6->dhcp_fd);
3329 			close(ctx->ipv6->dhcp_fd);
3330 			ctx->ipv6->dhcp_fd = -1;
3331 		}
3332 	}
3333 }
3334 
3335 void
3336 dhcp6_drop(struct interface *ifp, const char *reason)
3337 {
3338 
3339 	dhcp6_freedrop(ifp, 1, reason);
3340 }
3341 
3342 void
3343 dhcp6_free(struct interface *ifp)
3344 {
3345 
3346 	dhcp6_freedrop(ifp, 0, NULL);
3347 }
3348 
3349 void
3350 dhcp6_handleifa(struct dhcpcd_ctx *ctx, int cmd, const char *ifname,
3351     const struct in6_addr *addr, int flags)
3352 {
3353 	struct interface *ifp;
3354 	struct dhcp6_state *state;
3355 
3356 	if (ctx->ifaces == NULL)
3357 		return;
3358 
3359 	TAILQ_FOREACH(ifp, ctx->ifaces, next) {
3360 		state = D6_STATE(ifp);
3361 		if (state == NULL || strcmp(ifp->name, ifname))
3362 			continue;
3363 		ipv6_handleifa_addrs(cmd, &state->addrs, addr, flags);
3364 	}
3365 
3366 }
3367 
3368 ssize_t
3369 dhcp6_env(char **env, const char *prefix, const struct interface *ifp,
3370     const struct dhcp6_message *m, size_t len)
3371 {
3372 	const struct if_options *ifo;
3373 	struct dhcp_opt *opt, *vo;
3374 	const struct dhcp6_option *o;
3375 	size_t i, n;
3376 	uint16_t ol, oc;
3377 	char *pfx;
3378 	uint32_t en;
3379 	const struct dhcpcd_ctx *ctx;
3380 	const struct dhcp6_state *state;
3381 	const struct ipv6_addr *ap;
3382 	char *v, *val;
3383 
3384 	n = 0;
3385 	if (m == NULL)
3386 		goto delegated;
3387 
3388 	if (len < sizeof(*m)) {
3389 		/* Should be impossible with guards at packet in
3390 		 * and reading leases */
3391 		errno = EINVAL;
3392 		return -1;
3393 	}
3394 
3395 	ifo = ifp->options;
3396 	ctx = ifp->ctx;
3397 
3398 	/* Zero our indexes */
3399 	if (env) {
3400 		for (i = 0, opt = ctx->dhcp6_opts;
3401 		    i < ctx->dhcp6_opts_len;
3402 		    i++, opt++)
3403 			dhcp_zero_index(opt);
3404 		for (i = 0, opt = ifp->options->dhcp6_override;
3405 		    i < ifp->options->dhcp6_override_len;
3406 		    i++, opt++)
3407 			dhcp_zero_index(opt);
3408 		for (i = 0, opt = ctx->vivso;
3409 		    i < ctx->vivso_len;
3410 		    i++, opt++)
3411 			dhcp_zero_index(opt);
3412 		i = strlen(prefix) + strlen("_dhcp6") + 1;
3413 		pfx = malloc(i);
3414 		if (pfx == NULL) {
3415 			logger(ifp->ctx, LOG_ERR, "%s: %m", __func__);
3416 			return -1;
3417 		}
3418 		snprintf(pfx, i, "%s_dhcp6", prefix);
3419 	} else
3420 		pfx = NULL;
3421 
3422 	/* Unlike DHCP, DHCPv6 options *may* occur more than once.
3423 	 * There is also no provision for option concatenation unlike DHCP. */
3424 	for (o = D6_CFIRST_OPTION(m);
3425 	    len > (ssize_t)sizeof(*o);
3426 	    o = D6_CNEXT_OPTION(o))
3427 	{
3428 		ol = ntohs(o->len);
3429 		if (sizeof(*o) + ol > len) {
3430 			errno =	EINVAL;
3431 			break;
3432 		}
3433 		len -= sizeof(*o) + ol;
3434 		oc = ntohs(o->code);
3435 		if (has_option_mask(ifo->nomask6, oc))
3436 			continue;
3437 		for (i = 0, opt = ifo->dhcp6_override;
3438 		    i < ifo->dhcp6_override_len;
3439 		    i++, opt++)
3440 			if (opt->option == oc)
3441 				break;
3442 		if (i == ifo->dhcp6_override_len &&
3443 		    oc == D6_OPTION_VENDOR_OPTS &&
3444 		    ol > sizeof(en))
3445 		{
3446 			memcpy(&en, D6_COPTION_DATA(o), sizeof(en));
3447 			en = ntohl(en);
3448 			vo = vivso_find(en, ifp);
3449 		} else
3450 			vo = NULL;
3451 		if (i == ifo->dhcp6_override_len) {
3452 			for (i = 0, opt = ctx->dhcp6_opts;
3453 			    i < ctx->dhcp6_opts_len;
3454 			    i++, opt++)
3455 				if (opt->option == oc)
3456 					break;
3457 			if (i == ctx->dhcp6_opts_len)
3458 				opt = NULL;
3459 		}
3460 		if (opt) {
3461 			n += dhcp_envoption(ifp->ctx,
3462 			    env == NULL ? NULL : &env[n],
3463 			    pfx, ifp->name,
3464 			    opt, dhcp6_getoption, D6_COPTION_DATA(o), ol);
3465 		}
3466 		if (vo) {
3467 			n += dhcp_envoption(ifp->ctx,
3468 			    env == NULL ? NULL : &env[n],
3469 			    pfx, ifp->name,
3470 			    vo, dhcp6_getoption,
3471 			    D6_COPTION_DATA(o) + sizeof(en),
3472 			    ol - sizeof(en));
3473 		}
3474 	}
3475 	free(pfx);
3476 
3477 delegated:
3478         /* Needed for Delegated Prefixes */
3479 	state = D6_CSTATE(ifp);
3480 	i = 0;
3481 	TAILQ_FOREACH(ap, &state->addrs, next) {
3482 		if (ap->delegating_iface) {
3483 			i += strlen(ap->saddr) + 1;
3484 		}
3485 	}
3486 	if (env && i) {
3487 		i += strlen(prefix) + strlen("_delegated_dhcp6_prefix=");
3488                 v = val = env[n] = malloc(i);
3489 		if (v == NULL) {
3490 			logger(ifp->ctx, LOG_ERR, "%s: %m", __func__);
3491 			return -1;
3492 		}
3493 		v += snprintf(val, i, "%s_delegated_dhcp6_prefix=", prefix);
3494 		TAILQ_FOREACH(ap, &state->addrs, next) {
3495 			if (ap->delegating_iface) {
3496 				/* Can't use stpcpy(3) due to "security" */
3497 				const char *sap = ap->saddr;
3498 
3499 				do
3500 					*v++ = *sap;
3501 				while (*++sap != '\0');
3502 				*v++ = ' ';
3503 			}
3504 		}
3505 		*--v = '\0';
3506         }
3507 	if (i)
3508 		n++;
3509 
3510 	return (ssize_t)n;
3511 }
3512 
3513 int
3514 dhcp6_dump(struct interface *ifp)
3515 {
3516 	struct dhcp6_state *state;
3517 
3518 	ifp->if_data[IF_DATA_DHCP6] = state = calloc(1, sizeof(*state));
3519 	if (state == NULL) {
3520 		logger(ifp->ctx, LOG_ERR, "%s: %m", __func__);
3521 		return -1;
3522 	}
3523 	TAILQ_INIT(&state->addrs);
3524 	dhcp_set_leasefile(state->leasefile, sizeof(state->leasefile),
3525 	    AF_INET6, ifp);
3526 	if (dhcp6_readlease(ifp, 0) == -1) {
3527 		logger(ifp->ctx, LOG_ERR, "%s: %s: %m",
3528 		    *ifp->name ? ifp->name : state->leasefile, __func__);
3529 		return -1;
3530 	}
3531 	state->reason = "DUMP6";
3532 	return script_runreason(ifp, state->reason);
3533 }
3534