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