xref: /dragonfly/contrib/dhcpcd/src/ipv6.c (revision f984587a)
1 /* SPDX-License-Identifier: BSD-2-Clause */
2 /*
3  * dhcpcd - DHCP client daemon
4  * Copyright (c) 2006-2023 Roy Marples <roy@marples.name>
5  * All rights reserved
6 
7  * Redistribution and use in source and binary forms, with or without
8  * modification, are permitted provided that the following conditions
9  * are met:
10  * 1. Redistributions of source code must retain the above copyright
11  *    notice, this list of conditions and the following disclaimer.
12  * 2. Redistributions in binary form must reproduce the above copyright
13  *    notice, this list of conditions and the following disclaimer in the
14  *    documentation and/or other materials provided with the distribution.
15  *
16  * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND
17  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
18  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
19  * ARE DISCLAIMED.  IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
20  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
21  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
22  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
23  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
24  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
25  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
26  * SUCH DAMAGE.
27  */
28 
29 #include <sys/param.h>
30 #include <sys/types.h>
31 #include <sys/socket.h>
32 #include <sys/stat.h>
33 
34 #include <arpa/inet.h>
35 #include <net/if.h>
36 #include <net/route.h>
37 #include <netinet/in.h>
38 #include <netinet/if_ether.h>
39 
40 #include "config.h"
41 
42 #ifdef HAVE_SYS_BITOPS_H
43 #include <sys/bitops.h>
44 #else
45 #include "compat/bitops.h"
46 #endif
47 
48 #ifdef BSD
49 /* Purely for the ND6_IFF_AUTO_LINKLOCAL #define which is solely used
50  * to generate our CAN_ADD_LLADDR #define. */
51 #  include <netinet6/in6_var.h>
52 #  include <netinet6/nd6.h>
53 #endif
54 
55 #include <errno.h>
56 #include <ifaddrs.h>
57 #include <inttypes.h>
58 #include <stdlib.h>
59 #include <string.h>
60 #include <syslog.h>
61 #include <unistd.h>
62 
63 #define ELOOP_QUEUE	ELOOP_IPV6
64 #include "common.h"
65 #include "if.h"
66 #include "dhcpcd.h"
67 #include "dhcp6.h"
68 #include "eloop.h"
69 #include "ipv6.h"
70 #include "ipv6nd.h"
71 #include "logerr.h"
72 #include "privsep.h"
73 #include "sa.h"
74 #include "script.h"
75 
76 #ifdef HAVE_MD5_H
77 #  ifndef DEPGEN
78 #    include <md5.h>
79 #  endif
80 #endif
81 
82 #ifdef SHA2_H
83 #  include SHA2_H
84 #endif
85 
86 #ifndef SHA256_DIGEST_LENGTH
87 #  define SHA256_DIGEST_LENGTH		32
88 #endif
89 
90 #ifdef IPV6_POLLADDRFLAG
91 #  warning kernel does not report IPv6 address flag changes
92 #  warning polling tentative address flags periodically
93 #endif
94 
95 /* Hackery at it's finest. */
96 #ifndef s6_addr32
97 #  ifdef __sun
98 #    define s6_addr32	_S6_un._S6_u32
99 #  else
100 #    define s6_addr32	__u6_addr.__u6_addr32
101 #  endif
102 #endif
103 
104 #if defined(HAVE_IN6_ADDR_GEN_MODE_NONE) || defined(ND6_IFF_AUTO_LINKLOCAL) || \
105     defined(IFF_NOLINKLOCAL)
106 /* Only add the LL address if we have a carrier, so DaD works. */
107 #define	CAN_ADD_LLADDR(ifp) \
108     (!((ifp)->options->options & DHCPCD_LINK) || if_is_link_up((ifp)))
109 #ifdef __sun
110 /* Although we can add our own LL address, we cannot drop it
111  * without unplumbing the if which is a lot of code.
112  * So just keep it for the time being. */
113 #define	CAN_DROP_LLADDR(ifp)	(0)
114 #else
115 #define	CAN_DROP_LLADDR(ifp)	(1)
116 #endif
117 #else
118 /* We have no control over the OS adding the LLADDR, so just let it do it
119  * as we cannot force our own view on it. */
120 #define	CAN_ADD_LLADDR(ifp)	(0)
121 #define	CAN_DROP_LLADDR(ifp)	(0)
122 #endif
123 
124 #ifdef IPV6_MANAGETEMPADDR
125 static void ipv6_regentempaddr(void *);
126 #endif
127 
128 int
129 ipv6_init(struct dhcpcd_ctx *ctx)
130 {
131 
132 	if (ctx->ra_routers != NULL)
133 		return 0;
134 
135 	ctx->ra_routers = malloc(sizeof(*ctx->ra_routers));
136 	if (ctx->ra_routers == NULL)
137 		return -1;
138 	TAILQ_INIT(ctx->ra_routers);
139 
140 #ifndef __sun
141 	ctx->nd_fd = -1;
142 #endif
143 #ifdef DHCP6
144 	ctx->dhcp6_rfd = -1;
145 	ctx->dhcp6_wfd = -1;
146 #endif
147 	return 0;
148 }
149 
150 static ssize_t
151 ipv6_readsecret(struct dhcpcd_ctx *ctx)
152 {
153 	char line[1024];
154 	unsigned char *p;
155 	size_t len;
156 	uint32_t r;
157 
158 	ctx->secret_len = dhcp_read_hwaddr_aton(ctx, &ctx->secret, SECRET);
159 	if (ctx->secret_len != 0)
160 		return (ssize_t)ctx->secret_len;
161 
162 	if (errno != ENOENT)
163 		logerr("%s: cannot read secret", __func__);
164 
165 	/* Chaining arc4random should be good enough.
166 	 * RFC7217 section 5.1 states the key SHOULD be at least 128 bits.
167 	 * To attempt and future proof ourselves, we'll generate a key of
168 	 * 512 bits (64 bytes). */
169 	if (ctx->secret_len < 64) {
170 		if ((ctx->secret = malloc(64)) == NULL) {
171 			logerr(__func__);
172 			return -1;
173 		}
174 		ctx->secret_len = 64;
175 	}
176 	p = ctx->secret;
177 	for (len = 0; len < 512 / NBBY; len += sizeof(r)) {
178 		r = arc4random();
179 		memcpy(p, &r, sizeof(r));
180 		p += sizeof(r);
181 	}
182 
183 	hwaddr_ntoa(ctx->secret, ctx->secret_len, line, sizeof(line));
184 	len = strlen(line);
185 	if (len < sizeof(line) - 2) {
186 		line[len++] = '\n';
187 		line[len] = '\0';
188 	}
189 	if (dhcp_writefile(ctx, SECRET, S_IRUSR, line, len) == -1) {
190 		logerr("%s: cannot write secret", __func__);
191 		ctx->secret_len = 0;
192 		return -1;
193 	}
194 	return (ssize_t)ctx->secret_len;
195 }
196 
197 /* http://www.iana.org/assignments/ipv6-interface-ids/ipv6-interface-ids.xhtml
198  * RFC5453 */
199 static const struct reslowhigh {
200 	const uint8_t high[8];
201 	const uint8_t low[8];
202 } reslowhigh[] = {
203 	/* RFC4291 + RFC6543 */
204 	{ { 0x02, 0x00, 0x5e, 0xff, 0xfe, 0x00, 0x00, 0x00 },
205 	  { 0x02, 0x00, 0x5e, 0xff, 0xfe, 0xff, 0xff, 0xff } },
206 	/* RFC2526 */
207 	{ { 0xfd, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0x80 },
208 	  { 0xfd, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff } }
209 };
210 
211 static bool
212 ipv6_reserved(const struct in6_addr *addr)
213 {
214 	uint64_t id, low, high;
215 	size_t i;
216 	const struct reslowhigh *r;
217 
218 	id = be64dec(addr->s6_addr + sizeof(id));
219 	if (id == 0) /* RFC4291 */
220 		return 1;
221 	for (i = 0; i < __arraycount(reslowhigh); i++) {
222 		r = &reslowhigh[i];
223 		low = be64dec(r->low);
224 		high = be64dec(r->high);
225 		if (id >= low && id <= high)
226 			return true;
227 	}
228 	return false;
229 }
230 
231 /* RFC7217 */
232 static int
233 ipv6_makestableprivate1(struct dhcpcd_ctx *ctx,
234     struct in6_addr *addr, const struct in6_addr *prefix, int prefix_len,
235     const unsigned char *netiface, size_t netiface_len,
236     const unsigned char *netid, size_t netid_len,
237     unsigned short vlanid,
238     uint32_t *dad_counter)
239 {
240 	unsigned char buf[2048], *p, digest[SHA256_DIGEST_LENGTH];
241 	size_t len, l;
242 	SHA256_CTX sha_ctx;
243 
244 	if (prefix_len < 0 || prefix_len > 120) {
245 		errno = EINVAL;
246 		return -1;
247 	}
248 
249 	if (ctx->secret_len == 0) {
250 		if (ipv6_readsecret(ctx) == -1)
251 			return -1;
252 	}
253 
254 	l = (size_t)(ROUNDUP8(prefix_len) / NBBY);
255 	len = l + netiface_len + netid_len + sizeof(*dad_counter) +
256 	    ctx->secret_len;
257 	if (vlanid != 0)
258 		len += sizeof(vlanid);
259 	if (len > sizeof(buf)) {
260 		errno = ENOBUFS;
261 		return -1;
262 	}
263 
264 	for (;; (*dad_counter)++) {
265 		/* Combine all parameters into one buffer */
266 		p = buf;
267 		memcpy(p, prefix, l);
268 		p += l;
269 		memcpy(p, netiface, netiface_len);
270 		p += netiface_len;
271 		memcpy(p, netid, netid_len);
272 		p += netid_len;
273 		/* Don't use a vlanid if not set.
274 		 * This ensures prior versions have the same unique address. */
275 		if (vlanid != 0) {
276 			memcpy(p, &vlanid, sizeof(vlanid));
277 			p += sizeof(vlanid);
278 		}
279 		memcpy(p, dad_counter, sizeof(*dad_counter));
280 		p += sizeof(*dad_counter);
281 		memcpy(p, ctx->secret, ctx->secret_len);
282 
283 		/* Make an address using the digest of the above.
284 		 * RFC7217 Section 5.1 states that we shouldn't use MD5.
285 		 * Pity as we use that for HMAC-MD5 which is still deemed OK.
286 		 * SHA-256 is recommended */
287 		SHA256_Init(&sha_ctx);
288 		SHA256_Update(&sha_ctx, buf, len);
289 		SHA256_Final(digest, &sha_ctx);
290 
291 		p = addr->s6_addr;
292 		memcpy(p, prefix, l);
293 		/* RFC7217 section 5.2 says we need to start taking the id from
294 		 * the least significant bit */
295 		len = sizeof(addr->s6_addr) - l;
296 		memcpy(p + l, digest + (sizeof(digest) - len), len);
297 
298 		/* Ensure that the Interface ID does not match a reserved one,
299 		 * if it does then treat it as a DAD failure.
300 		 * RFC7217 section 5.2 */
301 		if (prefix_len != 64)
302 			break;
303 		if (!ipv6_reserved(addr))
304 			break;
305 	}
306 
307 	return 0;
308 }
309 
310 int
311 ipv6_makestableprivate(struct in6_addr *addr,
312     const struct in6_addr *prefix, int prefix_len,
313     const struct interface *ifp,
314     int *dad_counter)
315 {
316 	uint32_t dad;
317 	int r;
318 
319 	dad = (uint32_t)*dad_counter;
320 
321 	/* For our implementation, we shall set the hardware address
322 	 * as the interface identifier */
323 	r = ipv6_makestableprivate1(ifp->ctx, addr, prefix, prefix_len,
324 	    ifp->hwaddr, ifp->hwlen,
325 	    ifp->ssid, ifp->ssid_len,
326 	    ifp->vlanid, &dad);
327 
328 	if (r == 0)
329 		*dad_counter = (int)dad;
330 	return r;
331 }
332 
333 #ifdef IPV6_AF_TEMPORARY
334 static int
335 ipv6_maketemporaryaddress(struct in6_addr *addr,
336     const struct in6_addr *prefix, int prefix_len,
337     const struct interface *ifp)
338 {
339 	struct in6_addr mask;
340 	struct interface *ifpn;
341 
342 	if (ipv6_mask(&mask, prefix_len) == -1)
343 		return -1;
344 	*addr = *prefix;
345 
346 again:
347 	addr->s6_addr32[2] |= (arc4random() & ~mask.s6_addr32[2]);
348 	addr->s6_addr32[3] |= (arc4random() & ~mask.s6_addr32[3]);
349 
350 	TAILQ_FOREACH(ifpn, ifp->ctx->ifaces, next) {
351 		if (ipv6_iffindaddr(ifpn, addr, 0) != NULL)
352 			break;
353 	}
354 	if (ifpn != NULL)
355 		goto again;
356 	if (ipv6_reserved(addr))
357 		goto again;
358 	return 0;
359 }
360 #endif
361 
362 static int
363 ipv6_makeprefix(struct in6_addr *prefix, const struct in6_addr *addr, int len)
364 {
365 	struct in6_addr mask;
366 	size_t i;
367 
368 	if (ipv6_mask(&mask, len) == -1)
369 		return -1;
370 	*prefix = *addr;
371 	for (i = 0; i < sizeof(prefix->s6_addr); i++)
372 		prefix->s6_addr[i] &= mask.s6_addr[i];
373 	return 0;
374 }
375 
376 int
377 ipv6_mask(struct in6_addr *mask, int len)
378 {
379 	static const unsigned char masks[NBBY] =
380 	    { 0x80, 0xc0, 0xe0, 0xf0, 0xf8, 0xfc, 0xfe, 0xff };
381 	int bytes, bits, i;
382 
383 	if (len < 0 || len > 128) {
384 		errno = EINVAL;
385 		return -1;
386 	}
387 
388 	memset(mask, 0, sizeof(*mask));
389 	bytes = len / NBBY;
390 	bits = len % NBBY;
391 	for (i = 0; i < bytes; i++)
392 		mask->s6_addr[i] = 0xff;
393 	if (bits != 0) {
394 		/* Coverify false positive.
395 		 * bytelen cannot be 16 if bitlen is non zero */
396 		/* coverity[overrun-local] */
397 		mask->s6_addr[bytes] = masks[bits - 1];
398 	}
399 	return 0;
400 }
401 
402 uint8_t
403 ipv6_prefixlen(const struct in6_addr *mask)
404 {
405 	int x = 0, y;
406 	const unsigned char *lim, *p;
407 
408 	lim = (const unsigned char *)mask + sizeof(*mask);
409 	for (p = (const unsigned char *)mask; p < lim; x++, p++) {
410 		if (*p != 0xff)
411 			break;
412 	}
413 	y = 0;
414 	if (p < lim) {
415 		for (y = 0; y < NBBY; y++) {
416 			if ((*p & (0x80 >> y)) == 0)
417 				break;
418 		}
419 	}
420 
421 	/*
422 	 * when the limit pointer is given, do a stricter check on the
423 	 * remaining bits.
424 	 */
425 	if (p < lim) {
426 		if (y != 0 && (*p & (0x00ff >> y)) != 0)
427 			return 0;
428 		for (p = p + 1; p < lim; p++)
429 			if (*p != 0)
430 				return 0;
431 	}
432 
433 	return (uint8_t)(x * NBBY + y);
434 }
435 
436 int
437 ipv6_makeaddr(struct in6_addr *addr, struct interface *ifp,
438     const struct in6_addr *prefix, int prefix_len, unsigned int flags)
439 {
440 	const struct ipv6_addr *ap;
441 	const struct if_options *ifo = ifp->options;
442 	int dad;
443 
444 	if (prefix_len < 0 || prefix_len > 120) {
445 		errno = EINVAL;
446 		return -1;
447 	}
448 
449 #ifdef IPV6_AF_TEMPORARY
450 	if (flags & IPV6_AF_TEMPORARY)
451 		return ipv6_maketemporaryaddress(addr, prefix, prefix_len, ifp);
452 #else
453 	UNUSED(flags);
454 #endif
455 
456 	if (ifo->options & DHCPCD_SLAACPRIVATE) {
457 		dad = 0;
458 		if (ipv6_makestableprivate(addr,
459 		    prefix, prefix_len, ifp, &dad) == -1)
460 			return -1;
461 		return dad;
462 	} else if (!IN6_IS_ADDR_UNSPECIFIED(&ifo->token)) {
463 		int bytes = prefix_len / NBBY;
464 		int bits = prefix_len % NBBY;
465 
466 		// Copy the token into the address.
467 		*addr = ifo->token;
468 
469 		// If we have any dangling bits, just copy that in also.
470 		// XXX Can we preserve part of the token still?
471 		if (bits != 0)
472 			bytes++;
473 
474 		// Copy the prefix in.
475 		if (bytes > 0)
476 			memcpy(addr->s6_addr, prefix->s6_addr, (size_t)bytes);
477 		return 0;
478 	}
479 
480 	if (prefix_len > 64) {
481 		errno = EINVAL;
482 		return -1;
483 	}
484 	if ((ap = ipv6_linklocal(ifp)) == NULL) {
485 		/* We delay a few functions until we get a local-link address
486 		 * so this should never be hit. */
487 		errno = ENOENT;
488 		return -1;
489 	}
490 
491 	/* Make the address from the first local-link address */
492 	memcpy(addr, prefix, sizeof(*prefix));
493 	addr->s6_addr32[2] = ap->addr.s6_addr32[2];
494 	addr->s6_addr32[3] = ap->addr.s6_addr32[3];
495 	return 0;
496 }
497 
498 static void
499 in6_to_h64(uint64_t *vhigh, uint64_t *vlow, const struct in6_addr *addr)
500 {
501 
502 	*vhigh = be64dec(addr->s6_addr);
503 	*vlow = be64dec(addr->s6_addr + 8);
504 }
505 
506 static void
507 h64_to_in6(struct in6_addr *addr, uint64_t vhigh, uint64_t vlow)
508 {
509 
510 	be64enc(addr->s6_addr, vhigh);
511 	be64enc(addr->s6_addr + 8, vlow);
512 }
513 
514 int
515 ipv6_userprefix(
516 	const struct in6_addr *prefix,	// prefix from router
517 	short prefix_len,		// length of prefix received
518 	uint64_t user_number,		// "random" number from user
519 	struct in6_addr *result,	// resultant prefix
520 	short result_len)		// desired prefix length
521 {
522 	uint64_t vh, vl, user_low, user_high;
523 
524 	if (prefix_len < 1 || prefix_len > 128 ||
525 	    result_len < 1 || result_len > 128)
526 	{
527 		errno = EINVAL;
528 		return -1;
529 	}
530 
531 	/* Check that the user_number fits inside result_len less prefix_len */
532 	if (result_len < prefix_len ||
533 	    fls64(user_number) > result_len - prefix_len)
534 	{
535 	       errno = ERANGE;
536 	       return -1;
537 	}
538 
539 	/* If user_number is zero, just copy the prefix into the result. */
540 	if (user_number == 0) {
541 		*result = *prefix;
542 		return 0;
543 	}
544 
545 	/* Shift user_number so it fit's just inside result_len.
546 	 * Shifting by 0 or sizeof(user_number) is undefined,
547 	 * so we cater for that. */
548 	if (result_len == 128) {
549 		user_high = 0;
550 		user_low = user_number;
551 	} else if (result_len > 64) {
552 		if (prefix_len >= 64)
553 			user_high = 0;
554 		else
555 			user_high = user_number >> (result_len - prefix_len);
556 		user_low = user_number << (128 - result_len);
557 	} else if (result_len == 64) {
558 		user_high = user_number;
559 		user_low = 0;
560 	} else {
561 		user_high = user_number << (64 - result_len);
562 		user_low = 0;
563 	}
564 
565 	/* convert to two 64bit host order values */
566 	in6_to_h64(&vh, &vl, prefix);
567 
568 	vh |= user_high;
569 	vl |= user_low;
570 
571 	/* copy back result */
572 	h64_to_in6(result, vh, vl);
573 
574 	return 0;
575 }
576 
577 #ifdef IPV6_POLLADDRFLAG
578 void
579 ipv6_checkaddrflags(void *arg)
580 {
581 	struct ipv6_addr *ia;
582 	int flags;
583 	const char *alias;
584 
585 	ia = arg;
586 #ifdef ALIAS_ADDR
587 	alias = ia->alias;
588 #else
589 	alias = NULL;
590 #endif
591 	if ((flags = if_addrflags6(ia->iface, &ia->addr, alias)) == -1) {
592 		if (errno != EEXIST && errno != EADDRNOTAVAIL)
593 			logerr("%s: if_addrflags6", __func__);
594 		return;
595 	}
596 
597 	if (!(flags & IN6_IFF_TENTATIVE)) {
598 		/* Simulate the kernel announcing the new address. */
599 		ipv6_handleifa(ia->iface->ctx, RTM_NEWADDR,
600 		    ia->iface->ctx->ifaces, ia->iface->name,
601 		    &ia->addr, ia->prefix_len, flags, 0);
602 	} else {
603 		/* Still tentative? Check again in a bit. */
604 		eloop_timeout_add_msec(ia->iface->ctx->eloop,
605 		    RETRANS_TIMER / 2, ipv6_checkaddrflags, ia);
606 	}
607 }
608 #endif
609 
610 static void
611 ipv6_deletedaddr(struct ipv6_addr *ia)
612 {
613 
614 #ifdef DHCP6
615 #ifdef PRIVSEP
616 	if (!(ia->iface->ctx->options & DHCPCD_MANAGER))
617 		ps_inet_closedhcp6(ia);
618 #elif defined(SMALL)
619 	UNUSED(ia);
620 #else
621 	/* NOREJECT is set if we delegated exactly the prefix to another
622 	 * address.
623 	 * This can only be one address, so just clear the flag.
624 	 * This should ensure the reject route will be restored. */
625 	if (ia->delegating_prefix != NULL)
626 		ia->delegating_prefix->flags &= ~IPV6_AF_NOREJECT;
627 #endif
628 #else
629 	UNUSED(ia);
630 #endif
631 }
632 
633 void
634 ipv6_deleteaddr(struct ipv6_addr *ia)
635 {
636 	struct ipv6_state *state;
637 	struct ipv6_addr *ap;
638 
639 	loginfox("%s: deleting address %s", ia->iface->name, ia->saddr);
640 	if (if_address6(RTM_DELADDR, ia) == -1 &&
641 	    errno != EADDRNOTAVAIL && errno != ESRCH &&
642 	    errno != ENXIO && errno != ENODEV)
643 		logerr(__func__);
644 
645 	ipv6_deletedaddr(ia);
646 
647 	state = IPV6_STATE(ia->iface);
648 	TAILQ_FOREACH(ap, &state->addrs, next) {
649 		if (IN6_ARE_ADDR_EQUAL(&ap->addr, &ia->addr)) {
650 			TAILQ_REMOVE(&state->addrs, ap, next);
651 			ipv6_freeaddr(ap);
652 			break;
653 		}
654 	}
655 
656 #ifdef ND6_ADVERTISE
657 	/* Advertise the address if it exists on another interface. */
658 	ipv6nd_advertise(ia);
659 #endif
660 }
661 
662 static int
663 ipv6_addaddr1(struct ipv6_addr *ia, const struct timespec *now)
664 {
665 	struct interface *ifp;
666 	uint32_t pltime, vltime;
667 	int loglevel;
668 #ifdef ND6_ADVERTISE
669 	bool vltime_was_zero = ia->prefix_vltime == 0;
670 #endif
671 #ifdef __sun
672 	struct ipv6_state *state;
673 	struct ipv6_addr *ia2;
674 
675 	/* If we re-add then address on Solaris then the prefix
676 	 * route will be scrubbed and re-added. Something might
677 	 * be using it, so let's avoid it. */
678 	if (ia->flags & IPV6_AF_DADCOMPLETED) {
679 		logdebugx("%s: IP address %s already exists",
680 		    ia->iface->name, ia->saddr);
681 #ifdef ND6_ADVERTISE
682 		goto advertise;
683 #else
684 		return 0;
685 #endif
686 	}
687 #endif
688 
689 	/* Remember the interface of the address. */
690 	ifp = ia->iface;
691 
692 	if (!(ia->flags & IPV6_AF_DADCOMPLETED) &&
693 	    ipv6_iffindaddr(ifp, &ia->addr, IN6_IFF_NOTUSEABLE))
694 		ia->flags |= IPV6_AF_DADCOMPLETED;
695 
696 	/* Adjust plftime and vltime based on acquired time */
697 	pltime = ia->prefix_pltime;
698 	vltime = ia->prefix_vltime;
699 
700 	if (ifp->options->options & DHCPCD_LASTLEASE_EXTEND) {
701 		/* We don't want the kernel to expire the address.
702 		 * The saved times will be re-applied to the ia
703 		 * before exiting this function. */
704 		ia->prefix_vltime = ia->prefix_pltime = ND6_INFINITE_LIFETIME;
705 	}
706 
707 	if (timespecisset(&ia->acquired) &&
708 	    (ia->prefix_pltime != ND6_INFINITE_LIFETIME ||
709 	    ia->prefix_vltime != ND6_INFINITE_LIFETIME))
710 	{
711 		uint32_t elapsed;
712 		struct timespec n;
713 
714 		if (now == NULL) {
715 			clock_gettime(CLOCK_MONOTONIC, &n);
716 			now = &n;
717 		}
718 		elapsed = (uint32_t)eloop_timespec_diff(now, &ia->acquired,
719 		    NULL);
720 		if (ia->prefix_pltime != ND6_INFINITE_LIFETIME) {
721 			if (elapsed > ia->prefix_pltime)
722 				ia->prefix_pltime = 0;
723 			else
724 				ia->prefix_pltime -= elapsed;
725 		}
726 		if (ia->prefix_vltime != ND6_INFINITE_LIFETIME) {
727 			if (elapsed > ia->prefix_vltime)
728 				ia->prefix_vltime = 0;
729 			else
730 				ia->prefix_vltime -= elapsed;
731 		}
732 	}
733 
734 	loglevel = ia->flags & IPV6_AF_NEW ? LOG_INFO : LOG_DEBUG;
735 	logmessage(loglevel, "%s: adding %saddress %s", ifp->name,
736 #ifdef IPV6_AF_TEMPORARY
737 	    ia->flags & IPV6_AF_TEMPORARY ? "temporary " : "",
738 #else
739 	    "",
740 #endif
741 	    ia->saddr);
742 	if (ia->prefix_pltime == ND6_INFINITE_LIFETIME &&
743 	    ia->prefix_vltime == ND6_INFINITE_LIFETIME)
744 		logdebugx("%s: pltime infinity, vltime infinity",
745 		    ifp->name);
746 	else if (ia->prefix_pltime == ND6_INFINITE_LIFETIME)
747 		logdebugx("%s: pltime infinity, vltime %"PRIu32" seconds",
748 		    ifp->name, ia->prefix_vltime);
749 	else if (ia->prefix_vltime == ND6_INFINITE_LIFETIME)
750 		logdebugx("%s: pltime %"PRIu32"seconds, vltime infinity",
751 		    ifp->name, ia->prefix_pltime);
752 	else
753 		logdebugx("%s: pltime %"PRIu32" seconds, vltime %"PRIu32
754 		    " seconds",
755 		    ifp->name, ia->prefix_pltime, ia->prefix_vltime);
756 
757 	if (if_address6(RTM_NEWADDR, ia) == -1) {
758 		logerr(__func__);
759 		/* Restore real pltime and vltime */
760 		ia->prefix_pltime = pltime;
761 		ia->prefix_vltime = vltime;
762 		return -1;
763 	}
764 
765 #ifdef IPV6_MANAGETEMPADDR
766 	/* RFC4941 Section 3.4 */
767 	if (ia->flags & IPV6_AF_TEMPORARY &&
768 	    ia->prefix_pltime &&
769 	    ia->prefix_vltime &&
770 	    ifp->options->options & DHCPCD_SLAACTEMP)
771 		eloop_timeout_add_sec(ifp->ctx->eloop,
772 		    ia->prefix_pltime - REGEN_ADVANCE,
773 		    ipv6_regentempaddr, ia);
774 #endif
775 
776 	/* Restore real pltime and vltime */
777 	ia->prefix_pltime = pltime;
778 	ia->prefix_vltime = vltime;
779 
780 	ia->flags &= ~IPV6_AF_NEW;
781 	ia->flags |= IPV6_AF_ADDED;
782 #ifndef SMALL
783 	if (ia->delegating_prefix != NULL)
784 		ia->flags |= IPV6_AF_DELEGATED;
785 #endif
786 
787 #ifdef IPV6_POLLADDRFLAG
788 	eloop_timeout_delete(ifp->ctx->eloop,
789 		ipv6_checkaddrflags, ia);
790 	if (!(ia->flags & IPV6_AF_DADCOMPLETED)) {
791 		eloop_timeout_add_msec(ifp->ctx->eloop,
792 		    RETRANS_TIMER / 2, ipv6_checkaddrflags, ia);
793 	}
794 #endif
795 
796 #ifdef __sun
797 	/* Solaris does not announce new addresses which need DaD
798 	 * so we need to take a copy and add it to our list.
799 	 * Otherwise aliasing gets confused if we add another
800 	 * address during DaD. */
801 
802 	state = IPV6_STATE(ifp);
803 	TAILQ_FOREACH(ia2, &state->addrs, next) {
804 		if (IN6_ARE_ADDR_EQUAL(&ia2->addr, &ia->addr))
805 			break;
806 	}
807 	if (ia2 == NULL) {
808 		if ((ia2 = malloc(sizeof(*ia2))) == NULL) {
809 			logerr(__func__);
810 			return 0; /* Well, we did add the address */
811 		}
812 		memcpy(ia2, ia, sizeof(*ia2));
813 		TAILQ_INSERT_TAIL(&state->addrs, ia2, next);
814 	}
815 #endif
816 
817 #ifdef ND6_ADVERTISE
818 #ifdef __sun
819 advertise:
820 #endif
821 	/* Re-advertise the preferred address to be safe. */
822 	if (!vltime_was_zero)
823 		ipv6nd_advertise(ia);
824 #endif
825 
826 	return 0;
827 }
828 
829 #ifdef ALIAS_ADDR
830 /* Find the next logical alias address we can use. */
831 static int
832 ipv6_aliasaddr(struct ipv6_addr *ia, struct ipv6_addr **repl)
833 {
834 	struct ipv6_state *state;
835 	struct ipv6_addr *iap;
836 	unsigned int lun;
837 	char alias[IF_NAMESIZE];
838 
839 	if (ia->alias[0] != '\0')
840 		return 0;
841 	state = IPV6_STATE(ia->iface);
842 
843 	/* First find an existng address.
844 	 * This can happen when dhcpcd restarts as ND and DHCPv6
845 	 * maintain their own lists of addresses. */
846 	TAILQ_FOREACH(iap, &state->addrs, next) {
847 		if (iap->alias[0] != '\0' &&
848 		    IN6_ARE_ADDR_EQUAL(&iap->addr, &ia->addr))
849 		{
850 			strlcpy(ia->alias, iap->alias, sizeof(ia->alias));
851 			return 0;
852 		}
853 	}
854 
855 	lun = 0;
856 find_unit:
857 	if (if_makealias(alias, IF_NAMESIZE, ia->iface->name, lun) >=
858 	    IF_NAMESIZE)
859 	{
860 		errno = ENOMEM;
861 		return -1;
862 	}
863 	TAILQ_FOREACH(iap, &state->addrs, next) {
864 		if (iap->alias[0] == '\0')
865 			continue;
866 		if (IN6_IS_ADDR_UNSPECIFIED(&iap->addr)) {
867 			/* No address assigned? Lets use it. */
868 			strlcpy(ia->alias, iap->alias, sizeof(ia->alias));
869 			if (repl)
870 				*repl = iap;
871 			return 1;
872 		}
873 		if (strcmp(iap->alias, alias) == 0)
874 			break;
875 	}
876 
877 	if (iap != NULL) {
878 		if (lun == UINT_MAX) {
879 			errno = ERANGE;
880 			return -1;
881 		}
882 		lun++;
883 		goto find_unit;
884 	}
885 
886 	strlcpy(ia->alias, alias, sizeof(ia->alias));
887 	return 0;
888 }
889 #endif
890 
891 int
892 ipv6_addaddr(struct ipv6_addr *ia, const struct timespec *now)
893 {
894 	int r;
895 #ifdef ALIAS_ADDR
896 	int replaced, blank;
897 	struct ipv6_addr *replaced_ia;
898 
899 	blank = (ia->alias[0] == '\0');
900 	if ((replaced = ipv6_aliasaddr(ia, &replaced_ia)) == -1)
901 		return -1;
902 	if (blank)
903 		logdebugx("%s: aliased %s", ia->alias, ia->saddr);
904 #endif
905 
906 	if ((r = ipv6_addaddr1(ia, now)) == 0) {
907 #ifdef ALIAS_ADDR
908 		if (replaced) {
909 			struct ipv6_state *state;
910 
911 			state = IPV6_STATE(ia->iface);
912 			TAILQ_REMOVE(&state->addrs, replaced_ia, next);
913 			ipv6_freeaddr(replaced_ia);
914 		}
915 #endif
916 	}
917 	return r;
918 }
919 
920 int
921 ipv6_findaddrmatch(const struct ipv6_addr *addr, const struct in6_addr *match,
922     unsigned int flags)
923 {
924 
925 	if (match == NULL) {
926 		if ((addr->flags &
927 		    (IPV6_AF_ADDED | IPV6_AF_DADCOMPLETED)) ==
928 		    (IPV6_AF_ADDED | IPV6_AF_DADCOMPLETED))
929 			return 1;
930 	} else if (addr->prefix_vltime &&
931 	    IN6_ARE_ADDR_EQUAL(&addr->addr, match) &&
932 	    (!flags || addr->flags & flags))
933 		return 1;
934 
935 	return 0;
936 }
937 
938 struct ipv6_addr *
939 ipv6_findaddr(struct dhcpcd_ctx *ctx, const struct in6_addr *addr, unsigned int flags)
940 {
941 	struct ipv6_addr *nap;
942 #ifdef DHCP6
943 	struct ipv6_addr *dap;
944 #endif
945 
946 	nap = ipv6nd_findaddr(ctx, addr, flags);
947 #ifdef DHCP6
948 	dap = dhcp6_findaddr(ctx, addr, flags);
949 	if (!dap && !nap)
950 		return NULL;
951 	if (dap && !nap)
952 		return dap;
953 	if (nap && !dap)
954 		return nap;
955 	if (nap->iface->metric < dap->iface->metric)
956 		return nap;
957 	return dap;
958 #else
959 	return nap;
960 #endif
961 }
962 
963 int
964 ipv6_doaddr(struct ipv6_addr *ia, struct timespec *now)
965 {
966 
967 	/* A delegated prefix is not an address. */
968 	if (ia->flags & IPV6_AF_DELEGATEDPFX)
969 		return 0;
970 
971 	if (ia->prefix_vltime == 0) {
972 		if (ia->flags & IPV6_AF_ADDED)
973 			ipv6_deleteaddr(ia);
974 		eloop_q_timeout_delete(ia->iface->ctx->eloop,
975 		    ELOOP_QUEUE_ALL, NULL, ia);
976 		if (ia->flags & IPV6_AF_REQUEST) {
977 			ia->flags &= ~IPV6_AF_ADDED;
978 			return 0;
979 		}
980 		return -1;
981 	}
982 
983 	if (ia->flags & IPV6_AF_STALE ||
984 	    IN6_IS_ADDR_UNSPECIFIED(&ia->addr))
985 		return 0;
986 
987 	if (!timespecisset(now))
988 		clock_gettime(CLOCK_MONOTONIC, now);
989 	ipv6_addaddr(ia, now);
990 	return ia->flags & IPV6_AF_NEW ? 1 : 0;
991 }
992 
993 ssize_t
994 ipv6_addaddrs(struct ipv6_addrhead *iaddrs)
995 {
996 	struct timespec now;
997 	struct ipv6_addr *ia, *ian;
998 	ssize_t i, r;
999 
1000 	i = 0;
1001 	timespecclear(&now);
1002 	TAILQ_FOREACH_SAFE(ia, iaddrs, next, ian) {
1003 		r = ipv6_doaddr(ia, &now);
1004 		if (r != 0)
1005 			i++;
1006 		if (r == -1) {
1007 			TAILQ_REMOVE(iaddrs, ia, next);
1008 			ipv6_freeaddr(ia);
1009 		}
1010 	}
1011 	return i;
1012 }
1013 
1014 void
1015 ipv6_freeaddr(struct ipv6_addr *ia)
1016 {
1017 	struct eloop *eloop = ia->iface->ctx->eloop;
1018 #ifndef SMALL
1019 	struct ipv6_addr *iad;
1020 
1021 	/* Forget the reference */
1022 	if (ia->flags & IPV6_AF_DELEGATEDPFX) {
1023 		TAILQ_FOREACH(iad, &ia->pd_pfxs, pd_next) {
1024 			iad->delegating_prefix = NULL;
1025 		}
1026 	} else if (ia->delegating_prefix != NULL) {
1027 		TAILQ_REMOVE(&ia->delegating_prefix->pd_pfxs, ia, pd_next);
1028 	}
1029 #endif
1030 
1031 	if (ia->dhcp6_fd != -1) {
1032 		close(ia->dhcp6_fd);
1033 		eloop_event_delete(eloop, ia->dhcp6_fd);
1034 	}
1035 
1036 	eloop_q_timeout_delete(eloop, ELOOP_QUEUE_ALL, NULL, ia);
1037 	free(ia->na);
1038 	free(ia);
1039 }
1040 
1041 void
1042 ipv6_freedrop_addrs(struct ipv6_addrhead *addrs, int drop,
1043     const struct interface *ifd)
1044 {
1045 	struct ipv6_addr *ap, *apn, *apf;
1046 	struct timespec now;
1047 
1048 #ifdef SMALL
1049 	UNUSED(ifd);
1050 #endif
1051 	timespecclear(&now);
1052 	TAILQ_FOREACH_SAFE(ap, addrs, next, apn) {
1053 #ifndef SMALL
1054 		if (ifd != NULL &&
1055 		    (ap->delegating_prefix == NULL ||
1056 		    ap->delegating_prefix->iface != ifd))
1057 			continue;
1058 #endif
1059 		if (drop != 2)
1060 			TAILQ_REMOVE(addrs, ap, next);
1061 		if (drop && ap->flags & IPV6_AF_ADDED &&
1062 		    (ap->iface->options->options &
1063 		    (DHCPCD_EXITING | DHCPCD_PERSISTENT)) !=
1064 		    (DHCPCD_EXITING | DHCPCD_PERSISTENT))
1065 		{
1066 			/* Don't drop link-local addresses. */
1067 			if (!IN6_IS_ADDR_LINKLOCAL(&ap->addr) ||
1068 			    CAN_DROP_LLADDR(ap->iface))
1069 			{
1070 				if (drop == 2)
1071 					TAILQ_REMOVE(addrs, ap, next);
1072 				/* Find the same address somewhere else */
1073 				apf = ipv6_findaddr(ap->iface->ctx, &ap->addr,
1074 				    0);
1075 				if ((apf == NULL ||
1076 				    (apf->iface != ap->iface)))
1077 					ipv6_deleteaddr(ap);
1078 				if (!(ap->iface->options->options &
1079 				    DHCPCD_EXITING) && apf)
1080 				{
1081 					if (!timespecisset(&now))
1082 						clock_gettime(CLOCK_MONOTONIC,
1083 						    &now);
1084 					ipv6_addaddr(apf, &now);
1085 				}
1086 				if (drop == 2)
1087 					ipv6_freeaddr(ap);
1088 			}
1089 		}
1090 		if (drop != 2)
1091 			ipv6_freeaddr(ap);
1092 	}
1093 }
1094 
1095 static struct ipv6_state *
1096 ipv6_getstate(struct interface *ifp)
1097 {
1098 	struct ipv6_state *state;
1099 
1100 	state = IPV6_STATE(ifp);
1101 	if (state == NULL) {
1102 	        ifp->if_data[IF_DATA_IPV6] = calloc(1, sizeof(*state));
1103 		state = IPV6_STATE(ifp);
1104 		if (state == NULL) {
1105 			logerr(__func__);
1106 			return NULL;
1107 		}
1108 		TAILQ_INIT(&state->addrs);
1109 		TAILQ_INIT(&state->ll_callbacks);
1110 	}
1111 	return state;
1112 }
1113 
1114 struct ipv6_addr *
1115 ipv6_anyglobal(struct interface *sifp)
1116 {
1117 	struct interface *ifp;
1118 	struct ipv6_state *state;
1119 	struct ipv6_addr *ia;
1120 	bool forwarding;
1121 
1122 	/* BSD forwarding is either on or off.
1123 	 * Linux forwarding is technically the same as it's
1124 	 * configured by the "all" interface.
1125 	 * Per interface only affects IsRouter of NA messages. */
1126 #if defined(PRIVSEP) && (defined(HAVE_PLEDGE) || defined(__linux__))
1127 	if (IN_PRIVSEP(sifp->ctx))
1128 		forwarding = ps_root_ip6forwarding(sifp->ctx, NULL) != 0;
1129 	else
1130 #endif
1131 		forwarding = ip6_forwarding(NULL) != 0;
1132 
1133 	TAILQ_FOREACH(ifp, sifp->ctx->ifaces, next) {
1134 		if (ifp != sifp && !forwarding)
1135 			continue;
1136 
1137 		state = IPV6_STATE(ifp);
1138 		if (state == NULL)
1139 			continue;
1140 
1141 		TAILQ_FOREACH(ia, &state->addrs, next) {
1142 			if (IN6_IS_ADDR_LINKLOCAL(&ia->addr))
1143 				continue;
1144 			/* Let's be optimistic.
1145 			 * Any decent OS won't forward or accept traffic
1146 			 * from/to tentative or detached addresses. */
1147 			if (!(ia->addr_flags & IN6_IFF_DUPLICATED))
1148 				return ia;
1149 		}
1150 	}
1151 	return NULL;
1152 }
1153 
1154 void
1155 ipv6_handleifa(struct dhcpcd_ctx *ctx,
1156     int cmd, struct if_head *ifs, const char *ifname,
1157     const struct in6_addr *addr, uint8_t prefix_len, int addrflags, pid_t pid)
1158 {
1159 	struct interface *ifp;
1160 	struct ipv6_state *state;
1161 	struct ipv6_addr *ia;
1162 	struct ll_callback *cb;
1163 	bool anyglobal;
1164 
1165 #ifdef __sun
1166 	struct sockaddr_in6 subnet;
1167 
1168 	/* Solaris on-link route is an unspecified address! */
1169 	if (IN6_IS_ADDR_UNSPECIFIED(addr)) {
1170 		if (if_getsubnet(ctx, ifname, AF_INET6,
1171 		    &subnet, sizeof(subnet)) == -1)
1172 		{
1173 			logerr(__func__);
1174 			return;
1175 		}
1176 		addr = &subnet.sin6_addr;
1177 	}
1178 #endif
1179 
1180 #if 0
1181 	char dbuf[INET6_ADDRSTRLEN];
1182 	const char *dbp;
1183 
1184 	dbp = inet_ntop(AF_INET6, &addr->s6_addr,
1185 	    dbuf, INET6_ADDRSTRLEN);
1186 	loginfox("%s: cmd %d addr %s addrflags %d",
1187 	    ifname, cmd, dbp, addrflags);
1188 #endif
1189 
1190 	if (ifs == NULL)
1191 		ifs = ctx->ifaces;
1192 	if (ifs == NULL)
1193 		return;
1194 	if ((ifp = if_find(ifs, ifname)) == NULL)
1195 		return;
1196 	if ((state = ipv6_getstate(ifp)) == NULL)
1197 		return;
1198 	anyglobal = ipv6_anyglobal(ifp) != NULL;
1199 
1200 	TAILQ_FOREACH(ia, &state->addrs, next) {
1201 		if (IN6_ARE_ADDR_EQUAL(&ia->addr, addr))
1202 			break;
1203 	}
1204 
1205 	switch (cmd) {
1206 	case RTM_DELADDR:
1207 		if (ia != NULL) {
1208 			TAILQ_REMOVE(&state->addrs, ia, next);
1209 #ifdef ND6_ADVERTISE
1210 			/* Advertise the address if it exists on
1211 			 * another interface. */
1212 			ipv6nd_advertise(ia);
1213 #endif
1214 			/* We'll free it at the end of the function. */
1215 		}
1216 		break;
1217 	case RTM_NEWADDR:
1218 		if (ia == NULL) {
1219 			ia = ipv6_newaddr(ifp, addr, prefix_len, 0);
1220 #ifdef ALIAS_ADDR
1221 			strlcpy(ia->alias, ifname, sizeof(ia->alias));
1222 #endif
1223 			if (if_getlifetime6(ia) == -1) {
1224 				/* No support or address vanished.
1225 				 * Either way, just set a deprecated
1226 				 * infinite time lifetime and continue.
1227 				 * This is fine because we only want
1228 				 * to know this when trying to extend
1229 				 * temporary addresses.
1230 				 * As we can't extend infinite, we'll
1231 				 * create a new temporary address. */
1232 				ia->prefix_pltime = 0;
1233 				ia->prefix_vltime =
1234 				    ND6_INFINITE_LIFETIME;
1235 			}
1236 			/* This is a minor regression against RFC 4941
1237 			 * because the kernel only knows when the
1238 			 * lifetimes were last updated, not when the
1239 			 * address was initially created.
1240 			 * Provided dhcpcd is not restarted, this
1241 			 * won't be a problem.
1242 			 * If we don't like it, we can always
1243 			 * pretend lifetimes are infinite and always
1244 			 * generate a new temporary address on
1245 			 * restart. */
1246 			ia->acquired = ia->created;
1247 			TAILQ_INSERT_TAIL(&state->addrs, ia, next);
1248 		}
1249 		ia->addr_flags = addrflags;
1250 		ia->flags &= ~IPV6_AF_STALE;
1251 #ifdef IPV6_MANAGETEMPADDR
1252 		if (ia->addr_flags & IN6_IFF_TEMPORARY)
1253 			ia->flags |= IPV6_AF_TEMPORARY;
1254 #endif
1255 		if (IN6_IS_ADDR_LINKLOCAL(&ia->addr) || ia->dadcallback) {
1256 #ifdef IPV6_POLLADDRFLAG
1257 			if (ia->addr_flags & IN6_IFF_TENTATIVE) {
1258 				eloop_timeout_add_msec(
1259 				    ia->iface->ctx->eloop,
1260 				    RETRANS_TIMER / 2, ipv6_checkaddrflags, ia);
1261 				break;
1262 			}
1263 #endif
1264 
1265 			if (ia->dadcallback)
1266 				ia->dadcallback(ia);
1267 
1268 			if (IN6_IS_ADDR_LINKLOCAL(&ia->addr) &&
1269 			    !(ia->addr_flags & IN6_IFF_NOTUSEABLE))
1270 			{
1271 				/* Now run any callbacks.
1272 				 * Typically IPv6RS or DHCPv6 */
1273 				while ((cb =
1274 				    TAILQ_FIRST(&state->ll_callbacks)))
1275 				{
1276 					TAILQ_REMOVE(
1277 					    &state->ll_callbacks,
1278 					    cb, next);
1279 					cb->callback(cb->arg);
1280 					free(cb);
1281 				}
1282 			}
1283 		}
1284 		break;
1285 	}
1286 
1287 	if (ia == NULL)
1288 		return;
1289 
1290 	ctx->options &= ~DHCPCD_RTBUILD;
1291 	ipv6nd_handleifa(cmd, ia, pid);
1292 #ifdef DHCP6
1293 	dhcp6_handleifa(cmd, ia, pid);
1294 #endif
1295 
1296 	/* Done with the ia now, so free it. */
1297 	if (cmd == RTM_DELADDR)
1298 		ipv6_freeaddr(ia);
1299 	else if (!(ia->addr_flags & IN6_IFF_NOTUSEABLE))
1300 		ia->flags |= IPV6_AF_DADCOMPLETED;
1301 
1302 	/* If we've not already called rt_build via the IPv6ND
1303 	 * or DHCP6 handlers and the existance of any useable
1304 	 * global address on the interface has changed,
1305 	 * call rt_build to add/remove the default route. */
1306 	if (ifp->active &&
1307 	    ((ifp->options != NULL && ifp->options->options & DHCPCD_IPV6) ||
1308 	     (ifp->options == NULL && ctx->options & DHCPCD_IPV6)) &&
1309 	    !(ctx->options & DHCPCD_RTBUILD) &&
1310 	    (ipv6_anyglobal(ifp) != NULL) != anyglobal)
1311 		rt_build(ctx, AF_INET6);
1312 }
1313 
1314 int
1315 ipv6_hasaddr(const struct interface *ifp)
1316 {
1317 
1318 	if (ipv6nd_iffindaddr(ifp, NULL, 0) != NULL)
1319 		return 1;
1320 #ifdef DHCP6
1321 	if (dhcp6_iffindaddr(ifp, NULL, 0) != NULL)
1322 		return 1;
1323 #endif
1324 	return 0;
1325 }
1326 
1327 struct ipv6_addr *
1328 ipv6_iffindaddr(struct interface *ifp, const struct in6_addr *addr,
1329     int revflags)
1330 {
1331 	struct ipv6_state *state;
1332 	struct ipv6_addr *ap;
1333 
1334 	state = IPV6_STATE(ifp);
1335 	if (state) {
1336 		TAILQ_FOREACH(ap, &state->addrs, next) {
1337 			if (addr == NULL) {
1338 				if (IN6_IS_ADDR_LINKLOCAL(&ap->addr) &&
1339 				    (!revflags || !(ap->addr_flags & revflags)))
1340 					return ap;
1341 			} else {
1342 				if (IN6_ARE_ADDR_EQUAL(&ap->addr, addr) &&
1343 				    (!revflags || !(ap->addr_flags & revflags)))
1344 					return ap;
1345 			}
1346 		}
1347 	}
1348 	return NULL;
1349 }
1350 
1351 static struct ipv6_addr *
1352 ipv6_iffindmaskaddr(const struct interface *ifp, const struct in6_addr *addr)
1353 {
1354 	struct ipv6_state *state;
1355 	struct ipv6_addr *ap;
1356 	struct in6_addr mask;
1357 
1358 	state = IPV6_STATE(ifp);
1359 	if (state) {
1360 		TAILQ_FOREACH(ap, &state->addrs, next) {
1361 			if (ipv6_mask(&mask, ap->prefix_len) == -1)
1362 				continue;
1363 			if (IN6_ARE_MASKED_ADDR_EQUAL(&ap->addr, addr, &mask))
1364 				return ap;
1365 		}
1366 	}
1367 	return NULL;
1368 }
1369 
1370 struct ipv6_addr *
1371 ipv6_findmaskaddr(struct dhcpcd_ctx *ctx, const struct in6_addr *addr)
1372 {
1373 	struct interface *ifp;
1374 	struct ipv6_addr *ap;
1375 
1376 	TAILQ_FOREACH(ifp, ctx->ifaces, next) {
1377 		ap = ipv6_iffindmaskaddr(ifp, addr);
1378 		if (ap != NULL)
1379 			return ap;
1380 	}
1381 	return NULL;
1382 }
1383 
1384 int
1385 ipv6_addlinklocalcallback(struct interface *ifp,
1386     void (*callback)(void *), void *arg)
1387 {
1388 	struct ipv6_state *state;
1389 	struct ll_callback *cb;
1390 
1391 	state = ipv6_getstate(ifp);
1392 	TAILQ_FOREACH(cb, &state->ll_callbacks, next) {
1393 		if (cb->callback == callback && cb->arg == arg)
1394 			break;
1395 	}
1396 	if (cb == NULL) {
1397 		cb = malloc(sizeof(*cb));
1398 		if (cb == NULL) {
1399 			logerr(__func__);
1400 			return -1;
1401 		}
1402 		cb->callback = callback;
1403 		cb->arg = arg;
1404 		TAILQ_INSERT_TAIL(&state->ll_callbacks, cb, next);
1405 	}
1406 	return 0;
1407 }
1408 
1409 static struct ipv6_addr *
1410 ipv6_newlinklocal(struct interface *ifp)
1411 {
1412 	struct ipv6_addr *ia;
1413 	struct in6_addr in6;
1414 
1415 	memset(&in6, 0, sizeof(in6));
1416 	in6.s6_addr32[0] = htonl(0xfe800000);
1417 	ia = ipv6_newaddr(ifp, &in6, 64, 0);
1418 	if (ia != NULL) {
1419 		ia->prefix_pltime = ND6_INFINITE_LIFETIME;
1420 		ia->prefix_vltime = ND6_INFINITE_LIFETIME;
1421 	}
1422 	return ia;
1423 }
1424 
1425 static const uint8_t allzero[8] = { 0, 0, 0, 0, 0, 0, 0, 0 };
1426 static const uint8_t allone[8] =
1427     { 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff };
1428 
1429 static int
1430 ipv6_addlinklocal(struct interface *ifp)
1431 {
1432 	struct ipv6_state *state;
1433 	struct ipv6_addr *ap, *ap2;
1434 	int dadcounter;
1435 
1436 	if (!(ifp->options->options & DHCPCD_CONFIGURE))
1437 		return 0;
1438 
1439 	/* Check sanity before malloc */
1440 	if (!(ifp->options->options & DHCPCD_SLAACPRIVATE)) {
1441 		switch (ifp->hwtype) {
1442 		case ARPHRD_ETHER:
1443 			/* Check for a valid hardware address */
1444 			if (ifp->hwlen != 6 && ifp->hwlen != 8) {
1445 				errno = ENOTSUP;
1446 				return -1;
1447 			}
1448 			if (memcmp(ifp->hwaddr, allzero, ifp->hwlen) == 0 ||
1449 			    memcmp(ifp->hwaddr, allone, ifp->hwlen) == 0)
1450 			{
1451 				errno = EINVAL;
1452 				return -1;
1453 			}
1454 			break;
1455 		default:
1456 			errno = ENOTSUP;
1457 			return -1;
1458 		}
1459 	}
1460 
1461 	state = ipv6_getstate(ifp);
1462 	if (state == NULL)
1463 		return -1;
1464 
1465 	ap = ipv6_newlinklocal(ifp);
1466 	if (ap == NULL)
1467 		return -1;
1468 
1469 	dadcounter = 0;
1470 	if (ifp->options->options & DHCPCD_SLAACPRIVATE) {
1471 nextslaacprivate:
1472 		if (ipv6_makestableprivate(&ap->addr,
1473 			&ap->prefix, ap->prefix_len, ifp, &dadcounter) == -1)
1474 		{
1475 			free(ap);
1476 			return -1;
1477 		}
1478 		ap->dadcounter = dadcounter;
1479 	} else {
1480 		memcpy(ap->addr.s6_addr, ap->prefix.s6_addr, 8);
1481 		switch (ifp->hwtype) {
1482 		case ARPHRD_ETHER:
1483 			if (ifp->hwlen == 6) {
1484 				ap->addr.s6_addr[ 8] = ifp->hwaddr[0];
1485 				ap->addr.s6_addr[ 9] = ifp->hwaddr[1];
1486 				ap->addr.s6_addr[10] = ifp->hwaddr[2];
1487 				ap->addr.s6_addr[11] = 0xff;
1488 				ap->addr.s6_addr[12] = 0xfe;
1489 				ap->addr.s6_addr[13] = ifp->hwaddr[3];
1490 				ap->addr.s6_addr[14] = ifp->hwaddr[4];
1491 				ap->addr.s6_addr[15] = ifp->hwaddr[5];
1492 			} else if (ifp->hwlen == 8)
1493 				memcpy(&ap->addr.s6_addr[8], ifp->hwaddr, 8);
1494 			else {
1495 				free(ap);
1496 				errno = ENOTSUP;
1497 				return -1;
1498 			}
1499 			break;
1500 		}
1501 
1502 		/* Sanity check: g bit must not indciate "group" */
1503 		if (EUI64_GROUP(&ap->addr)) {
1504 			free(ap);
1505 			errno = EINVAL;
1506 			return -1;
1507 		}
1508 		EUI64_TO_IFID(&ap->addr);
1509 	}
1510 
1511 	/* Do we already have this address? */
1512 	TAILQ_FOREACH(ap2, &state->addrs, next) {
1513 		if (IN6_ARE_ADDR_EQUAL(&ap->addr, &ap2->addr)) {
1514 			if (ap2->addr_flags & IN6_IFF_DUPLICATED) {
1515 				if (ifp->options->options &
1516 				    DHCPCD_SLAACPRIVATE)
1517 				{
1518 					dadcounter++;
1519 					goto nextslaacprivate;
1520 				}
1521 				free(ap);
1522 				errno = EADDRNOTAVAIL;
1523 				return -1;
1524 			}
1525 
1526 			logwarnx("%s: waiting for %s to complete",
1527 			    ap2->iface->name, ap2->saddr);
1528 			free(ap);
1529 			errno =	EEXIST;
1530 			return 0;
1531 		}
1532 	}
1533 
1534 	inet_ntop(AF_INET6, &ap->addr, ap->saddr, sizeof(ap->saddr));
1535 	TAILQ_INSERT_TAIL(&state->addrs, ap, next);
1536 	ipv6_addaddr(ap, NULL);
1537 	return 1;
1538 }
1539 
1540 static int
1541 ipv6_tryaddlinklocal(struct interface *ifp)
1542 {
1543 	struct ipv6_addr *ia;
1544 
1545 	/* We can't assign a link-locak address to this,
1546 	 * the ppp process has to. */
1547 	if (ifp->flags & IFF_POINTOPOINT)
1548 		return 0;
1549 
1550 	ia = ipv6_iffindaddr(ifp, NULL, IN6_IFF_DUPLICATED);
1551 	if (ia != NULL) {
1552 #ifdef IPV6_POLLADDRFLAG
1553 		if (ia->addr_flags & IN6_IFF_TENTATIVE) {
1554 			eloop_timeout_add_msec(
1555 			    ia->iface->ctx->eloop,
1556 			    RETRANS_TIMER / 2, ipv6_checkaddrflags, ia);
1557 		}
1558 #endif
1559 		return 0;
1560 	}
1561 	if (!CAN_ADD_LLADDR(ifp))
1562 		return 0;
1563 
1564 	return ipv6_addlinklocal(ifp);
1565 }
1566 
1567 void
1568 ipv6_setscope(struct sockaddr_in6 *sin, unsigned int ifindex)
1569 {
1570 
1571 #ifdef __KAME__
1572 	/* KAME based systems want to store the scope inside the sin6_addr
1573 	 * for link local addresses */
1574 	if (IN6_IS_ADDR_LINKLOCAL(&sin->sin6_addr)) {
1575 		uint16_t scope = htons((uint16_t)ifindex);
1576 		memcpy(&sin->sin6_addr.s6_addr[2], &scope,
1577 		    sizeof(scope));
1578 	}
1579 	sin->sin6_scope_id = 0;
1580 #else
1581 	if (IN6_IS_ADDR_LINKLOCAL(&sin->sin6_addr))
1582 		sin->sin6_scope_id = ifindex;
1583 	else
1584 		sin->sin6_scope_id = 0;
1585 #endif
1586 }
1587 
1588 unsigned int
1589 ipv6_getscope(const struct sockaddr_in6 *sin)
1590 {
1591 #ifdef __KAME__
1592 	uint16_t scope;
1593 #endif
1594 
1595 	if (!IN6_IS_ADDR_LINKLOCAL(&sin->sin6_addr))
1596 		return 0;
1597 #ifdef __KAME__
1598 	memcpy(&scope, &sin->sin6_addr.s6_addr[2], sizeof(scope));
1599 	return (unsigned int)ntohs(scope);
1600 #else
1601 	return (unsigned int)sin->sin6_scope_id;
1602 #endif
1603 }
1604 
1605 struct ipv6_addr *
1606 ipv6_newaddr(struct interface *ifp, const struct in6_addr *addr,
1607     uint8_t prefix_len, unsigned int flags)
1608 {
1609 	struct ipv6_addr *ia, *iaf;
1610 	char buf[INET6_ADDRSTRLEN];
1611 	const char *cbp;
1612 	bool tempaddr;
1613 	int addr_flags;
1614 
1615 #ifdef IPV6_AF_TEMPORARY
1616 	tempaddr = flags & IPV6_AF_TEMPORARY;
1617 #else
1618 	tempaddr = false;
1619 #endif
1620 
1621 	/* If adding a new DHCP / RA derived address, check current flags
1622 	 * from an existing address. */
1623 	if (tempaddr)
1624 		iaf = NULL;
1625 	else if (flags & IPV6_AF_AUTOCONF)
1626 		iaf = ipv6nd_iffindprefix(ifp, addr, prefix_len);
1627 	else
1628 		iaf = ipv6_iffindaddr(ifp, addr, 0);
1629 	if (iaf != NULL) {
1630 		addr_flags = iaf->addr_flags;
1631 		flags |= IPV6_AF_ADDED;
1632 	} else
1633 		addr_flags = IN6_IFF_TENTATIVE;
1634 
1635 	ia = calloc(1, sizeof(*ia));
1636 	if (ia == NULL)
1637 		goto err;
1638 
1639 	ia->iface = ifp;
1640 	ia->addr_flags = addr_flags;
1641 	ia->flags = IPV6_AF_NEW | flags;
1642 	if (!(ia->addr_flags & IN6_IFF_NOTUSEABLE))
1643 		ia->flags |= IPV6_AF_DADCOMPLETED;
1644 	ia->prefix_len = prefix_len;
1645 	ia->dhcp6_fd = -1;
1646 
1647 #ifndef SMALL
1648 	TAILQ_INIT(&ia->pd_pfxs);
1649 #endif
1650 
1651 	if (prefix_len == 128)
1652 		goto makepfx;
1653 	else if (ia->flags & IPV6_AF_AUTOCONF) {
1654 		ia->prefix = *addr;
1655 		if (iaf != NULL)
1656 			memcpy(&ia->addr, &iaf->addr, sizeof(ia->addr));
1657 		else {
1658 			ia->dadcounter = ipv6_makeaddr(&ia->addr, ifp,
1659 			                               &ia->prefix,
1660 						       ia->prefix_len,
1661 						       ia->flags);
1662 			if (ia->dadcounter == -1)
1663 				goto err;
1664 		}
1665 	} else if (ia->flags & IPV6_AF_RAPFX) {
1666 		ia->prefix = *addr;
1667 #ifdef __sun
1668 		ia->addr = *addr;
1669 		cbp = inet_ntop(AF_INET6, &ia->addr, buf, sizeof(buf));
1670 		goto paddr;
1671 #else
1672 		return ia;
1673 #endif
1674 	} else if (ia->flags & (IPV6_AF_REQUEST | IPV6_AF_DELEGATEDPFX)) {
1675 		ia->prefix = *addr;
1676 		cbp = inet_ntop(AF_INET6, &ia->prefix, buf, sizeof(buf));
1677 		goto paddr;
1678 	} else {
1679 makepfx:
1680 		ia->addr = *addr;
1681 		if (ipv6_makeprefix(&ia->prefix,
1682 		                    &ia->addr, ia->prefix_len) == -1)
1683 			goto err;
1684 	}
1685 
1686 	cbp = inet_ntop(AF_INET6, &ia->addr, buf, sizeof(buf));
1687 paddr:
1688 	if (cbp == NULL)
1689 		goto err;
1690 	snprintf(ia->saddr, sizeof(ia->saddr), "%s/%d", cbp, ia->prefix_len);
1691 
1692 	return ia;
1693 
1694 err:
1695 	logerr(__func__);
1696 	free(ia);
1697 	return NULL;
1698 }
1699 
1700 static void
1701 ipv6_staticdadcallback(void *arg)
1702 {
1703 	struct ipv6_addr *ia = arg;
1704 	int wascompleted;
1705 
1706 	wascompleted = (ia->flags & IPV6_AF_DADCOMPLETED);
1707 	ia->flags |= IPV6_AF_DADCOMPLETED;
1708 	if (ia->addr_flags & IN6_IFF_DUPLICATED)
1709 		logwarnx("%s: DAD detected %s", ia->iface->name,
1710 		    ia->saddr);
1711 	else if (!wascompleted) {
1712 		logdebugx("%s: IPv6 static DAD completed",
1713 		    ia->iface->name);
1714 	}
1715 
1716 #define FINISHED (IPV6_AF_ADDED | IPV6_AF_DADCOMPLETED)
1717 	if (!wascompleted) {
1718 		struct interface *ifp;
1719 		struct ipv6_state *state;
1720 
1721 		ifp = ia->iface;
1722 		state = IPV6_STATE(ifp);
1723 		TAILQ_FOREACH(ia, &state->addrs, next) {
1724 			if (ia->flags & IPV6_AF_STATIC &&
1725 			    (ia->flags & FINISHED) != FINISHED)
1726 			{
1727 				wascompleted = 1;
1728 				break;
1729 			}
1730 		}
1731 		if (!wascompleted)
1732 			script_runreason(ifp, "STATIC6");
1733 	}
1734 #undef FINISHED
1735 }
1736 
1737 ssize_t
1738 ipv6_env(FILE *fp, const char *prefix, const struct interface *ifp)
1739 {
1740 	struct ipv6_addr *ia;
1741 
1742 	ia = ipv6_iffindaddr(UNCONST(ifp), &ifp->options->req_addr6,
1743 	    IN6_IFF_NOTUSEABLE);
1744 	if (ia == NULL)
1745 		return 0;
1746 	if (efprintf(fp, "%s_ip6_address=%s", prefix, ia->saddr) == -1)
1747 		return -1;
1748 	return 1;
1749 }
1750 
1751 int
1752 ipv6_staticdadcompleted(const struct interface *ifp)
1753 {
1754 	const struct ipv6_state *state;
1755 	const struct ipv6_addr *ia;
1756 	int n;
1757 
1758 	if ((state = IPV6_CSTATE(ifp)) == NULL)
1759 		return 0;
1760 	n = 0;
1761 #define COMPLETED (IPV6_AF_STATIC | IPV6_AF_ADDED | IPV6_AF_DADCOMPLETED)
1762 	TAILQ_FOREACH(ia, &state->addrs, next) {
1763 		if ((ia->flags & COMPLETED) == COMPLETED &&
1764 		    !(ia->addr_flags & IN6_IFF_NOTUSEABLE))
1765 			n++;
1766 	}
1767 	return n;
1768 }
1769 
1770 int
1771 ipv6_startstatic(struct interface *ifp)
1772 {
1773 	struct ipv6_addr *ia;
1774 	int run_script;
1775 
1776 	if (IN6_IS_ADDR_UNSPECIFIED(&ifp->options->req_addr6))
1777 		return 0;
1778 
1779 	ia = ipv6_iffindaddr(ifp, &ifp->options->req_addr6, 0);
1780 	if (ia != NULL &&
1781 	    (ia->prefix_len != ifp->options->req_prefix_len ||
1782 	    ia->addr_flags & IN6_IFF_NOTUSEABLE))
1783 	{
1784 		ipv6_deleteaddr(ia);
1785 		ia = NULL;
1786 	}
1787 	if (ia == NULL) {
1788 		struct ipv6_state *state;
1789 
1790 		ia = ipv6_newaddr(ifp, &ifp->options->req_addr6,
1791 		    ifp->options->req_prefix_len, 0);
1792 		if (ia == NULL)
1793 			return -1;
1794 		state = IPV6_STATE(ifp);
1795 		TAILQ_INSERT_TAIL(&state->addrs, ia, next);
1796 		run_script = 0;
1797 	} else
1798 		run_script = 1;
1799 	ia->flags |= IPV6_AF_STATIC | IPV6_AF_ONLINK;
1800 	ia->prefix_vltime = ND6_INFINITE_LIFETIME;
1801 	ia->prefix_pltime = ND6_INFINITE_LIFETIME;
1802 	ia->dadcallback = ipv6_staticdadcallback;
1803 	ipv6_addaddr(ia, NULL);
1804 	rt_build(ifp->ctx, AF_INET6);
1805 	if (run_script)
1806 		script_runreason(ifp, "STATIC6");
1807 	return 1;
1808 }
1809 
1810 /* Ensure the interface has a link-local address */
1811 int
1812 ipv6_start(struct interface *ifp)
1813 {
1814 #ifdef IPV6_POLLADDRFLAG
1815 	struct ipv6_state *state;
1816 
1817 	/* We need to update the address flags. */
1818 	if ((state = IPV6_STATE(ifp)) != NULL) {
1819 		struct ipv6_addr *ia;
1820 		const char *alias;
1821 		int flags;
1822 
1823 		TAILQ_FOREACH(ia, &state->addrs, next) {
1824 #ifdef ALIAS_ADDR
1825 			alias = ia->alias;
1826 #else
1827 			alias = NULL;
1828 #endif
1829 			flags = if_addrflags6(ia->iface, &ia->addr, alias);
1830 			if (flags != -1)
1831 				ia->addr_flags = flags;
1832 		}
1833 	}
1834 #endif
1835 
1836 	if (ipv6_tryaddlinklocal(ifp) == -1)
1837 		return -1;
1838 
1839 	return 0;
1840 }
1841 
1842 void
1843 ipv6_freedrop(struct interface *ifp, int drop)
1844 {
1845 	struct ipv6_state *state;
1846 	struct ll_callback *cb;
1847 
1848 	if (ifp == NULL)
1849 		return;
1850 
1851 	if ((state = IPV6_STATE(ifp)) == NULL)
1852 		return;
1853 
1854 	/* If we got here, we can get rid of any LL callbacks. */
1855 	while ((cb = TAILQ_FIRST(&state->ll_callbacks))) {
1856 		TAILQ_REMOVE(&state->ll_callbacks, cb, next);
1857 		free(cb);
1858 	}
1859 
1860 	ipv6_freedrop_addrs(&state->addrs, drop ? 2 : 0, NULL);
1861 	if (drop) {
1862 		if (ifp->ctx->ra_routers != NULL)
1863 			rt_build(ifp->ctx, AF_INET6);
1864 	} else {
1865 		/* Because we need to cache the addresses we don't control,
1866 		 * we only free the state on when NOT dropping addresses. */
1867 		free(state);
1868 		ifp->if_data[IF_DATA_IPV6] = NULL;
1869 		eloop_timeout_delete(ifp->ctx->eloop, NULL, ifp);
1870 	}
1871 }
1872 
1873 void
1874 ipv6_ctxfree(struct dhcpcd_ctx *ctx)
1875 {
1876 
1877 	free(ctx->ra_routers);
1878 	free(ctx->secret);
1879 }
1880 
1881 int
1882 ipv6_handleifa_addrs(int cmd,
1883     struct ipv6_addrhead *addrs, const struct ipv6_addr *addr, pid_t pid)
1884 {
1885 	struct ipv6_addr *ia, *ian;
1886 	uint8_t found, alldadcompleted;
1887 
1888 	alldadcompleted = 1;
1889 	found = 0;
1890 	TAILQ_FOREACH_SAFE(ia, addrs, next, ian) {
1891 		if (!IN6_ARE_ADDR_EQUAL(&addr->addr, &ia->addr)) {
1892 			if (ia->flags & IPV6_AF_ADDED &&
1893 			    !(ia->flags & IPV6_AF_DADCOMPLETED))
1894 				alldadcompleted = 0;
1895 			continue;
1896 		}
1897 		switch (cmd) {
1898 		case RTM_DELADDR:
1899 			if (ia->flags & IPV6_AF_ADDED) {
1900 				logwarnx("%s: pid %d deleted address %s",
1901 				    ia->iface->name, pid, ia->saddr);
1902 				ia->flags &= ~IPV6_AF_ADDED;
1903 			}
1904 			ipv6_deletedaddr(ia);
1905 			if (ia->flags & IPV6_AF_DELEGATED) {
1906 				TAILQ_REMOVE(addrs, ia, next);
1907 				ipv6_freeaddr(ia);
1908 			}
1909 			break;
1910 		case RTM_NEWADDR:
1911 			ia->addr_flags = addr->addr_flags;
1912 			/* Safety - ignore tentative announcements */
1913 			if (ia->addr_flags &
1914 			    (IN6_IFF_DETACHED | IN6_IFF_TENTATIVE))
1915 				break;
1916 			if ((ia->flags & IPV6_AF_DADCOMPLETED) == 0) {
1917 				found++;
1918 				if (ia->dadcallback)
1919 					ia->dadcallback(ia);
1920 				/* We need to set this here in-case the
1921 				 * dadcallback function checks it */
1922 				ia->flags |= IPV6_AF_DADCOMPLETED;
1923 			}
1924 			break;
1925 		}
1926 	}
1927 
1928 	return alldadcompleted ? found : 0;
1929 }
1930 
1931 #ifdef IPV6_MANAGETEMPADDR
1932 static void
1933 ipv6_regen_desync(struct interface *ifp, bool force)
1934 {
1935 	struct ipv6_state *state;
1936 	unsigned int max;
1937 
1938 	state = IPV6_STATE(ifp);
1939 
1940 	/* RFC4941 Section 5 states that DESYNC_FACTOR must never be
1941 	 * greater than TEMP_VALID_LIFETIME - REGEN_ADVANCE.
1942 	 * I believe this is an error and it should be never be greater than
1943 	 * TEMP_PREFERRED_LIFETIME - REGEN_ADVANCE. */
1944 	max = TEMP_PREFERRED_LIFETIME - REGEN_ADVANCE;
1945 	if (state->desync_factor && !force && state->desync_factor < max)
1946 		return;
1947 	if (state->desync_factor == 0)
1948 		state->desync_factor =
1949 		    arc4random_uniform(MIN(MAX_DESYNC_FACTOR, max));
1950 	max = TEMP_PREFERRED_LIFETIME - state->desync_factor - REGEN_ADVANCE;
1951 	eloop_timeout_add_sec(ifp->ctx->eloop, max, ipv6_regentempaddrs, ifp);
1952 }
1953 
1954 /* RFC4941 Section 3.3.7 */
1955 static void
1956 ipv6_tempdadcallback(void *arg)
1957 {
1958 	struct ipv6_addr *ia = arg;
1959 
1960 	if (ia->addr_flags & IN6_IFF_DUPLICATED) {
1961 		struct ipv6_addr *ia1;
1962 		struct timespec tv;
1963 
1964 		if (++ia->dadcounter == TEMP_IDGEN_RETRIES) {
1965 			logerrx("%s: too many duplicate temporary addresses",
1966 			    ia->iface->name);
1967 			return;
1968 		}
1969 		clock_gettime(CLOCK_MONOTONIC, &tv);
1970 		if ((ia1 = ipv6_createtempaddr(ia, &tv)) == NULL)
1971 			logerr(__func__);
1972 		else
1973 			ia1->dadcounter = ia->dadcounter;
1974 		ipv6_deleteaddr(ia);
1975 		if (ia1)
1976 			ipv6_addaddr(ia1, &ia1->acquired);
1977 	}
1978 }
1979 
1980 struct ipv6_addr *
1981 ipv6_createtempaddr(struct ipv6_addr *ia0, const struct timespec *now)
1982 {
1983 	struct ipv6_state *state;
1984 	struct interface *ifp = ia0->iface;
1985 	struct ipv6_addr *ia;
1986 
1987 	ia = ipv6_newaddr(ifp, &ia0->prefix, ia0->prefix_len,
1988 	    IPV6_AF_AUTOCONF | IPV6_AF_TEMPORARY);
1989 	if (ia == NULL)
1990 		return NULL;
1991 
1992 	ia->dadcallback = ipv6_tempdadcallback;
1993 	ia->created = ia->acquired = now ? *now : ia0->acquired;
1994 
1995 	/* Ensure desync is still valid */
1996 	ipv6_regen_desync(ifp, false);
1997 
1998 	/* RFC4941 Section 3.3.4 */
1999 	state = IPV6_STATE(ia->iface);
2000 	ia->prefix_pltime = MIN(ia0->prefix_pltime,
2001 	    TEMP_PREFERRED_LIFETIME - state->desync_factor);
2002 	ia->prefix_vltime = MIN(ia0->prefix_vltime, TEMP_VALID_LIFETIME);
2003 	if (ia->prefix_pltime <= REGEN_ADVANCE ||
2004 	    ia->prefix_pltime > ia0->prefix_vltime)
2005 	{
2006 		errno =	EINVAL;
2007 		free(ia);
2008 		return NULL;
2009 	}
2010 
2011 	TAILQ_INSERT_TAIL(&state->addrs, ia, next);
2012 	return ia;
2013 }
2014 
2015 struct ipv6_addr *
2016 ipv6_settemptime(struct ipv6_addr *ia, int flags)
2017 {
2018 	struct ipv6_state *state;
2019 	struct ipv6_addr *ap, *first;
2020 
2021 	state = IPV6_STATE(ia->iface);
2022 	first = NULL;
2023 	TAILQ_FOREACH_REVERSE(ap, &state->addrs, ipv6_addrhead, next) {
2024 		if (ap->flags & IPV6_AF_TEMPORARY &&
2025 		    ap->prefix_pltime &&
2026 		    IN6_ARE_ADDR_EQUAL(&ia->prefix, &ap->prefix))
2027 		{
2028 			unsigned int max, ext;
2029 
2030 			if (flags == 0) {
2031 				if (ap->prefix_pltime -
2032 				    (uint32_t)(ia->acquired.tv_sec -
2033 				    ap->acquired.tv_sec)
2034 				    < REGEN_ADVANCE)
2035 					continue;
2036 
2037 				return ap;
2038 			}
2039 
2040 			if (!(ap->flags & IPV6_AF_ADDED))
2041 				ap->flags |= IPV6_AF_NEW | IPV6_AF_AUTOCONF;
2042 			ap->flags &= ~IPV6_AF_STALE;
2043 
2044 			/* RFC4941 Section 3.4
2045 			 * Deprecated prefix, deprecate the temporary address */
2046 			if (ia->prefix_pltime == 0) {
2047 				ap->prefix_pltime = 0;
2048 				goto valid;
2049 			}
2050 
2051 			/* Ensure desync is still valid */
2052 			ipv6_regen_desync(ap->iface, false);
2053 
2054 			/* RFC4941 Section 3.3.2
2055 			 * Extend temporary times, but ensure that they
2056 			 * never last beyond the system limit. */
2057 			ext = (unsigned int)ia->acquired.tv_sec
2058 			    + ia->prefix_pltime;
2059 			max = (unsigned int)(ap->created.tv_sec +
2060 			    TEMP_PREFERRED_LIFETIME -
2061 			    state->desync_factor);
2062 			if (ext < max)
2063 				ap->prefix_pltime = ia->prefix_pltime;
2064 			else
2065 				ap->prefix_pltime =
2066 				    (uint32_t)(max - ia->acquired.tv_sec);
2067 
2068 valid:
2069 			ext = (unsigned int)ia->acquired.tv_sec +
2070 			    ia->prefix_vltime;
2071 			max = (unsigned int)(ap->created.tv_sec +
2072 			    TEMP_VALID_LIFETIME);
2073 			if (ext < max)
2074 				ap->prefix_vltime = ia->prefix_vltime;
2075 			else
2076 				ap->prefix_vltime =
2077 				    (uint32_t)(max - ia->acquired.tv_sec);
2078 
2079 			/* Just extend the latest matching prefix */
2080 			ap->acquired = ia->acquired;
2081 
2082 			/* If extending return the last match as
2083 			 * it's the most current.
2084 			 * If deprecating, deprecate any other addresses we
2085 			 * may have, although this should not be needed */
2086 			if (ia->prefix_pltime)
2087 				return ap;
2088 			if (first == NULL)
2089 				first = ap;
2090 		}
2091 	}
2092 	return first;
2093 }
2094 
2095 void
2096 ipv6_addtempaddrs(struct interface *ifp, const struct timespec *now)
2097 {
2098 	struct ipv6_state *state;
2099 	struct ipv6_addr *ia;
2100 
2101 	state = IPV6_STATE(ifp);
2102 	TAILQ_FOREACH(ia, &state->addrs, next) {
2103 		if (ia->flags & IPV6_AF_TEMPORARY &&
2104 		    !(ia->flags & IPV6_AF_STALE))
2105 			ipv6_addaddr(ia, now);
2106 	}
2107 }
2108 
2109 static void
2110 ipv6_regentempaddr0(struct ipv6_addr *ia, struct timespec *tv)
2111 {
2112 	struct ipv6_addr *ia1;
2113 
2114 	logdebugx("%s: regen temp addr %s", ia->iface->name, ia->saddr);
2115 	ia1 = ipv6_createtempaddr(ia, tv);
2116 	if (ia1)
2117 		ipv6_addaddr(ia1, tv);
2118 	else
2119 		logerr(__func__);
2120 }
2121 
2122 static void
2123 ipv6_regentempaddr(void *arg)
2124 {
2125 	struct timespec tv;
2126 
2127 	clock_gettime(CLOCK_MONOTONIC, &tv);
2128 	ipv6_regentempaddr0(arg, &tv);
2129 }
2130 
2131 void
2132 ipv6_regentempaddrs(void *arg)
2133 {
2134 	struct interface *ifp = arg;
2135 	struct timespec tv;
2136 	struct ipv6_state *state;
2137 	struct ipv6_addr *ia;
2138 
2139 	state = IPV6_STATE(ifp);
2140 	if (state == NULL)
2141 		return;
2142 
2143 	ipv6_regen_desync(ifp, true);
2144 
2145 	clock_gettime(CLOCK_MONOTONIC, &tv);
2146 
2147 	/* Mark addresses for regen so we don't infinite loop. */
2148 	TAILQ_FOREACH(ia, &state->addrs, next) {
2149 		if (ia->flags & IPV6_AF_TEMPORARY &&
2150 		    ia->flags & IPV6_AF_ADDED &&
2151 		    !(ia->flags & IPV6_AF_STALE))
2152 			ia->flags |= IPV6_AF_REGEN;
2153 		else
2154 			ia->flags &= ~IPV6_AF_REGEN;
2155 	}
2156 
2157 	/* Now regen temp addrs */
2158 	TAILQ_FOREACH(ia, &state->addrs, next) {
2159 		if (ia->flags & IPV6_AF_REGEN) {
2160 			ipv6_regentempaddr0(ia, &tv);
2161 			ia->flags &= ~IPV6_AF_REGEN;
2162 		}
2163 	}
2164 }
2165 #endif /* IPV6_MANAGETEMPADDR */
2166 
2167 void
2168 ipv6_markaddrsstale(struct interface *ifp, unsigned int flags)
2169 {
2170 	struct ipv6_state *state;
2171 	struct ipv6_addr *ia;
2172 
2173 	state = IPV6_STATE(ifp);
2174 	if (state == NULL)
2175 		return;
2176 
2177 	TAILQ_FOREACH(ia, &state->addrs, next) {
2178 		if (flags == 0 || ia->flags & flags)
2179 			ia->flags |= IPV6_AF_STALE;
2180 	}
2181 }
2182 
2183 void
2184 ipv6_deletestaleaddrs(struct interface *ifp)
2185 {
2186 	struct ipv6_state *state;
2187 	struct ipv6_addr *ia, *ia1;
2188 
2189 	state = IPV6_STATE(ifp);
2190 	if (state == NULL)
2191 		return;
2192 
2193 	TAILQ_FOREACH_SAFE(ia, &state->addrs, next, ia1) {
2194 		if (ia->flags & IPV6_AF_STALE)
2195 			ipv6_handleifa(ifp->ctx, RTM_DELADDR,
2196 			    ifp->ctx->ifaces, ifp->name,
2197 			    &ia->addr, ia->prefix_len, 0, getpid());
2198 	}
2199 }
2200 
2201 
2202 static struct rt *
2203 inet6_makeroute(struct interface *ifp, const struct ra *rap)
2204 {
2205 	struct rt *rt;
2206 
2207 	if ((rt = rt_new(ifp)) == NULL)
2208 		return NULL;
2209 
2210 #ifdef HAVE_ROUTE_METRIC
2211 	rt->rt_metric = ifp->metric;
2212 #endif
2213 	if (rap != NULL)
2214 		rt->rt_mtu = rap->mtu;
2215 	return rt;
2216 }
2217 
2218 static struct rt *
2219 inet6_makeprefix(struct interface *ifp, const struct ra *rap,
2220     const struct ipv6_addr *addr)
2221 {
2222 	struct rt *rt;
2223 	struct in6_addr netmask;
2224 
2225 	if (addr == NULL || addr->prefix_len > 128) {
2226 		errno = EINVAL;
2227 		return NULL;
2228 	}
2229 
2230 	/* There is no point in trying to manage a /128 prefix,
2231 	 * ones without a lifetime.  */
2232 	if (addr->prefix_len == 128 || addr->prefix_vltime == 0)
2233 		return NULL;
2234 
2235 	/* Don't install a reject route when not creating bigger prefixes. */
2236 	if (addr->flags & IPV6_AF_NOREJECT)
2237 		return NULL;
2238 
2239 	/* This address is the delegated prefix, so add a reject route for
2240 	 * it via the loopback interface. */
2241 	if (addr->flags & IPV6_AF_DELEGATEDPFX) {
2242 		struct interface *lo0;
2243 
2244 		TAILQ_FOREACH(lo0, ifp->ctx->ifaces, next) {
2245 			if (lo0->flags & IFF_LOOPBACK)
2246 				break;
2247 		}
2248 		if (lo0 == NULL)
2249 			logwarnx("cannot find a loopback interface "
2250 			    "to reject via");
2251 		else
2252 			ifp = lo0;
2253 	}
2254 
2255 	if ((rt = inet6_makeroute(ifp, rap)) == NULL)
2256 		return NULL;
2257 
2258 	sa_in6_init(&rt->rt_dest, &addr->prefix);
2259 	ipv6_mask(&netmask, addr->prefix_len);
2260 	sa_in6_init(&rt->rt_netmask, &netmask);
2261 	if (addr->flags & IPV6_AF_DELEGATEDPFX) {
2262 		rt->rt_flags |= RTF_REJECT;
2263 		/* Linux does not like a gateway for a reject route. */
2264 #ifndef __linux__
2265 		sa_in6_init(&rt->rt_gateway, &in6addr_loopback);
2266 #endif
2267 	} else if (!(addr->flags & IPV6_AF_ONLINK))
2268 		sa_in6_init(&rt->rt_gateway, &rap->from);
2269 	else
2270 		rt->rt_gateway.sa_family = AF_UNSPEC;
2271 	sa_in6_init(&rt->rt_ifa, &addr->addr);
2272 	return rt;
2273 }
2274 
2275 static struct rt *
2276 inet6_makerouter(struct ra *rap)
2277 {
2278 	struct rt *rt;
2279 
2280 	if ((rt = inet6_makeroute(rap->iface, rap)) == NULL)
2281 		return NULL;
2282 	sa_in6_init(&rt->rt_dest, &in6addr_any);
2283 	sa_in6_init(&rt->rt_netmask, &in6addr_any);
2284 	sa_in6_init(&rt->rt_gateway, &rap->from);
2285 	return rt;
2286 }
2287 
2288 #define RT_IS_DEFAULT(rtp) \
2289 	(IN6_ARE_ADDR_EQUAL(&((rtp)->dest), &in6addr_any) &&		      \
2290 	    IN6_ARE_ADDR_EQUAL(&((rtp)->mask), &in6addr_any))
2291 
2292 static int
2293 inet6_staticroutes(rb_tree_t *routes, struct dhcpcd_ctx *ctx)
2294 {
2295 	struct interface *ifp;
2296 	struct ipv6_state *state;
2297 	struct ipv6_addr *ia;
2298 	struct rt *rt;
2299 
2300 	TAILQ_FOREACH(ifp, ctx->ifaces, next) {
2301 		if ((state = IPV6_STATE(ifp)) == NULL)
2302 			continue;
2303 		TAILQ_FOREACH(ia, &state->addrs, next) {
2304 			if ((ia->flags & (IPV6_AF_ADDED | IPV6_AF_STATIC)) ==
2305 			    (IPV6_AF_ADDED | IPV6_AF_STATIC))
2306 			{
2307 				rt = inet6_makeprefix(ifp, NULL, ia);
2308 				if (rt)
2309 					rt_proto_add(routes, rt);
2310 			}
2311 		}
2312 	}
2313 	return 0;
2314 }
2315 
2316 static int
2317 inet6_raroutes(rb_tree_t *routes, struct dhcpcd_ctx *ctx)
2318 {
2319 	struct rt *rt;
2320 	struct ra *rap;
2321 	const struct ipv6_addr *addr;
2322 
2323 	if (ctx->ra_routers == NULL)
2324 		return 0;
2325 
2326 	TAILQ_FOREACH(rap, ctx->ra_routers, next) {
2327 		if (rap->expired)
2328 			continue;
2329 		TAILQ_FOREACH(addr, &rap->addrs, next) {
2330 			if (addr->prefix_vltime == 0)
2331 				continue;
2332 			rt = inet6_makeprefix(rap->iface, rap, addr);
2333 			if (rt) {
2334 				rt->rt_dflags |= RTDF_RA;
2335 #ifdef HAVE_ROUTE_PREF
2336 				rt->rt_pref = ipv6nd_rtpref(rap);
2337 #endif
2338 				rt_proto_add(routes, rt);
2339 			}
2340 		}
2341 		if (rap->lifetime == 0)
2342 			continue;
2343 		if (ipv6_anyglobal(rap->iface) == NULL)
2344 			continue;
2345 		rt = inet6_makerouter(rap);
2346 		if (rt == NULL)
2347 			continue;
2348 		rt->rt_dflags |= RTDF_RA;
2349 #ifdef HAVE_ROUTE_PREF
2350 		rt->rt_pref = ipv6nd_rtpref(rap);
2351 #endif
2352 		rt_proto_add(routes, rt);
2353 	}
2354 	return 0;
2355 }
2356 
2357 #ifdef DHCP6
2358 static int
2359 inet6_dhcproutes(rb_tree_t *routes, struct dhcpcd_ctx *ctx,
2360     enum DH6S dstate)
2361 {
2362 	struct interface *ifp;
2363 	const struct dhcp6_state *d6_state;
2364 	const struct ipv6_addr *addr;
2365 	struct rt *rt;
2366 
2367 	TAILQ_FOREACH(ifp, ctx->ifaces, next) {
2368 		d6_state = D6_CSTATE(ifp);
2369 		if (d6_state && d6_state->state == dstate) {
2370 			TAILQ_FOREACH(addr, &d6_state->addrs, next) {
2371 				rt = inet6_makeprefix(ifp, NULL, addr);
2372 				if (rt == NULL)
2373 					continue;
2374 				rt->rt_dflags |= RTDF_DHCP;
2375 				rt_proto_add(routes, rt);
2376 			}
2377 		}
2378 	}
2379 	return 0;
2380 }
2381 #endif
2382 
2383 bool
2384 inet6_getroutes(struct dhcpcd_ctx *ctx, rb_tree_t *routes)
2385 {
2386 
2387 	/* Should static take priority? */
2388 	if (inet6_staticroutes(routes, ctx) == -1)
2389 		return false;
2390 
2391 	/* First add reachable routers and their prefixes */
2392 	if (inet6_raroutes(routes, ctx) == -1)
2393 		return false;
2394 
2395 #ifdef DHCP6
2396 	/* We have no way of knowing if prefixes added by DHCP are reachable
2397 	 * or not, so we have to assume they are.
2398 	 * Add bound before delegated so we can prefer interfaces better. */
2399 	if (inet6_dhcproutes(routes, ctx, DH6S_BOUND) == -1)
2400 		return false;
2401 	if (inet6_dhcproutes(routes, ctx, DH6S_DELEGATED) == -1)
2402 		return false;
2403 #endif
2404 
2405 	return true;
2406 }
2407