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