1/*
2 * dhcpcd - DHCP client daemon
3 * Copyright (c) 2006-2015 Roy Marples <roy@marples.name>
4 * All rights reserved
5
6 * Redistribution and use in source and binary forms, with or without
7 * modification, are permitted provided that the following conditions
8 * are met:
9 * 1. Redistributions of source code must retain the above copyright
10 *    notice, this list of conditions and the following disclaimer.
11 * 2. Redistributions in binary form must reproduce the above copyright
12 *    notice, this list of conditions and the following disclaimer in the
13 *    documentation and/or other materials provided with the distribution.
14 *
15 * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND
16 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
17 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
18 * ARE DISCLAIMED.  IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
19 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
20 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
21 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
22 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
23 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
24 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
25 * SUCH DAMAGE.
26 */
27
28#include <sys/param.h>
29#include <sys/types.h>
30#include <sys/socket.h>
31#include <sys/stat.h>
32
33#include <net/if.h>
34#include <net/route.h>
35#include <netinet/in.h>
36#include <netinet/if_ether.h>
37
38#ifndef __linux__
39#  ifndef __QNX__
40#    include <sys/endian.h>
41#  endif
42#  include <net/if.h>
43#  ifdef __FreeBSD__ /* Needed so that including netinet6/in6_var.h works */
44#    include <net/if_var.h>
45#  endif
46#  ifndef __sun
47#    include <netinet6/in6_var.h>
48#  endif
49#endif
50
51#include <errno.h>
52#include <ifaddrs.h>
53#include <inttypes.h>
54#include <stdlib.h>
55#include <string.h>
56#include <unistd.h>
57
58#define ELOOP_QUEUE 7
59#include "common.h"
60#include "if.h"
61#include "dhcpcd.h"
62#include "dhcp6.h"
63#include "eloop.h"
64#include "ipv6.h"
65#include "ipv6nd.h"
66
67#ifdef HAVE_MD5_H
68#  ifndef DEPGEN
69#    include <md5.h>
70#  endif
71#else
72#  include "md5.h"
73#endif
74
75#ifdef SHA2_H
76#  include SHA2_H
77#else
78#  include "sha256.h"
79#endif
80
81#ifndef SHA256_DIGEST_LENGTH
82#  define SHA256_DIGEST_LENGTH		32
83#endif
84
85#ifdef IPV6_POLLADDRFLAG
86#  warning kernel does not report IPv6 address flag changes
87#  warning polling tentative address flags periodically
88#endif
89
90#ifdef __linux__
91   /* Match Linux defines to BSD */
92#  define IN6_IFF_TEMPORARY IFA_F_TEMPORARY
93#  ifdef IFA_F_OPTIMISTIC
94#    define IN6_IFF_TENTATIVE	(IFA_F_TENTATIVE | IFA_F_OPTIMISTIC)
95#  else
96#    define IN6_IFF_TENTATIVE   (IFA_F_TENTATIVE | 0x04)
97#  endif
98#  ifdef IF_F_DADFAILED
99#    define IN6_IFF_DUPLICATED	IFA_F_DADFAILED
100#  else
101#    define IN6_IFF_DUPLICATED	0x08
102#  endif
103#  define IN6_IFF_DETACHED	0
104#endif
105
106#define IN6_IFF_NOTUSEABLE \
107	(IN6_IFF_TENTATIVE | IN6_IFF_DUPLICATED | IN6_IFF_DETACHED)
108
109/* Hackery at it's finest. */
110#ifndef s6_addr32
111#  ifdef __sun
112#    define s6_addr32	_S6_un._S6_u32
113#  else
114#    define s6_addr32	__u6_addr.__u6_addr32
115#  endif
116#endif
117
118
119#ifdef IPV6_MANAGETEMPADDR
120static void ipv6_regentempifid(void *);
121static void ipv6_regentempaddr(void *);
122#else
123#define ipv6_regentempifid(a) {}
124#endif
125
126struct ipv6_ctx *
127ipv6_init(struct dhcpcd_ctx *dhcpcd_ctx)
128{
129	struct ipv6_ctx *ctx;
130
131	if (dhcpcd_ctx->ipv6)
132		return dhcpcd_ctx->ipv6;
133
134	ctx = calloc(1, sizeof(*ctx));
135	if (ctx == NULL)
136		return NULL;
137
138	ctx->routes = malloc(sizeof(*ctx->routes));
139	if (ctx->routes == NULL) {
140		free(ctx);
141		return NULL;
142	}
143	TAILQ_INIT(ctx->routes);
144
145	ctx->ra_routers = malloc(sizeof(*ctx->ra_routers));
146	if (ctx->ra_routers == NULL) {
147		free(ctx->routes);
148		free(ctx);
149		return NULL;
150	}
151	TAILQ_INIT(ctx->ra_routers);
152
153	TAILQ_INIT(&ctx->kroutes);
154
155	ctx->sndhdr.msg_namelen = sizeof(struct sockaddr_in6);
156	ctx->sndhdr.msg_iov = ctx->sndiov;
157	ctx->sndhdr.msg_iovlen = 1;
158	ctx->sndhdr.msg_control = ctx->sndbuf;
159	ctx->sndhdr.msg_controllen = sizeof(ctx->sndbuf);
160	ctx->rcvhdr.msg_name = &ctx->from;
161	ctx->rcvhdr.msg_namelen = sizeof(ctx->from);
162	ctx->rcvhdr.msg_iov = ctx->rcviov;
163	ctx->rcvhdr.msg_iovlen = 1;
164	ctx->rcvhdr.msg_control = ctx->rcvbuf;
165	// controllen is set at recieve
166	//ctx->rcvhdr.msg_controllen = sizeof(ctx->rcvbuf);
167	ctx->rcviov[0].iov_base = ctx->ansbuf;
168	ctx->rcviov[0].iov_len = sizeof(ctx->ansbuf);
169
170	ctx->nd_fd = -1;
171	ctx->dhcp_fd = -1;
172
173	dhcpcd_ctx->ipv6 = ctx;
174
175	return ctx;
176}
177
178ssize_t
179ipv6_printaddr(char *s, size_t sl, const uint8_t *d, const char *ifname)
180{
181	char buf[INET6_ADDRSTRLEN];
182	const char *p;
183	size_t l;
184
185	p = inet_ntop(AF_INET6, d, buf, sizeof(buf));
186	if (p == NULL)
187		return -1;
188
189	l = strlen(p);
190	if (d[0] == 0xfe && (d[1] & 0xc0) == 0x80)
191		l += 1 + strlen(ifname);
192
193	if (s == NULL)
194		return (ssize_t)l;
195
196	if (sl < l) {
197		errno = ENOMEM;
198		return -1;
199	}
200
201	s += strlcpy(s, p, sl);
202	if (d[0] == 0xfe && (d[1] & 0xc0) == 0x80) {
203		*s++ = '%';
204		s += strlcpy(s, ifname, sl);
205	}
206	*s = '\0';
207	return (ssize_t)l;
208}
209
210static ssize_t
211ipv6_readsecret(struct dhcpcd_ctx *ctx)
212{
213	FILE *fp;
214	char line[1024];
215	unsigned char *p;
216	size_t len;
217	uint32_t r;
218	int x;
219
220	if ((fp = fopen(SECRET, "r"))) {
221		len = 0;
222		while (fgets(line, sizeof(line), fp)) {
223			len = strlen(line);
224			if (len) {
225				if (line[len - 1] == '\n')
226					line[len - 1] = '\0';
227			}
228			len = hwaddr_aton(NULL, line);
229			if (len) {
230				ctx->secret_len = hwaddr_aton(ctx->secret,
231				    line);
232				break;
233			}
234			len = 0;
235		}
236		fclose(fp);
237		if (len)
238			return (ssize_t)len;
239	} else {
240		if (errno != ENOENT)
241			logger(ctx, LOG_ERR,
242			    "error reading secret: %s: %m", SECRET);
243	}
244
245	/* Chaining arc4random should be good enough.
246	 * RFC7217 section 5.1 states the key SHOULD be at least 128 bits.
247	 * To attempt and future proof ourselves, we'll generate a key of
248	 * 512 bits (64 bytes). */
249	p = ctx->secret;
250	ctx->secret_len = 0;
251	for (len = 0; len < 512 / NBBY; len += sizeof(r)) {
252		r = arc4random();
253		memcpy(p, &r, sizeof(r));
254		p += sizeof(r);
255		ctx->secret_len += sizeof(r);
256
257	}
258
259	/* Ensure that only the dhcpcd user can read the secret.
260	 * Write permission is also denied as chaning it would remove
261	 * it's stability. */
262	if ((fp = fopen(SECRET, "w")) == NULL ||
263	    chmod(SECRET, S_IRUSR) == -1)
264		goto eexit;
265	x = fprintf(fp, "%s\n",
266	    hwaddr_ntoa(ctx->secret, ctx->secret_len, line, sizeof(line)));
267	fclose(fp);
268	if (x > 0)
269		return (ssize_t)ctx->secret_len;
270
271eexit:
272	logger(ctx, LOG_ERR, "error writing secret: %s: %m", SECRET);
273	unlink(SECRET);
274	ctx->secret_len = 0;
275	return -1;
276}
277
278/* http://www.iana.org/assignments/ipv6-interface-ids/ipv6-interface-ids.xhtml
279 * RFC5453 */
280static const struct reslowhigh {
281	const uint8_t high[8];
282	const uint8_t low[8];
283} reslowhigh[] = {
284	/* RFC4291 + RFC6543 */
285	{ { 0x02, 0x00, 0x5e, 0xff, 0xfe, 0x00, 0x00, 0x00 },
286	  { 0x02, 0x00, 0x5e, 0xff, 0xfe, 0xff, 0xff, 0xff } },
287	/* RFC2526 */
288	{ { 0xfd, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0x80 },
289	  { 0xfd, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff } }
290};
291
292static int
293ipv6_reserved(const struct in6_addr *addr)
294{
295	uint64_t id, low, high;
296	size_t i;
297	const struct reslowhigh *r;
298
299	id = be64dec(addr->s6_addr + sizeof(id));
300	if (id == 0) /* RFC4291 */
301		return 1;
302	for (i = 0; i < sizeof(reslowhigh) / sizeof(reslowhigh[0]); i++) {
303		r = &reslowhigh[i];
304		low = be64dec(r->low);
305		high = be64dec(r->high);
306		if (id >= low && id <= high)
307			return 1;
308	}
309	return 0;
310}
311
312/* RFC7217 */
313static int
314ipv6_makestableprivate1(struct in6_addr *addr,
315    const struct in6_addr *prefix, int prefix_len,
316    const unsigned char *netiface, size_t netiface_len,
317    const unsigned char *netid, size_t netid_len,
318    uint32_t *dad_counter,
319    const unsigned char *secret, size_t secret_len)
320{
321	unsigned char buf[2048], *p, digest[SHA256_DIGEST_LENGTH];
322	size_t len, l;
323	SHA256_CTX ctx;
324
325	if (prefix_len < 0 || prefix_len > 120) {
326		errno = EINVAL;
327		return -1;
328	}
329
330	l = (size_t)(ROUNDUP8(prefix_len) / NBBY);
331	len = l + netiface_len + netid_len + sizeof(*dad_counter) + secret_len;
332	if (len > sizeof(buf)) {
333		errno = ENOBUFS;
334		return -1;
335	}
336
337	for (;; (*dad_counter)++) {
338		/* Combine all parameters into one buffer */
339		p = buf;
340		memcpy(p, prefix, l);
341		p += l;
342		memcpy(p, netiface, netiface_len);
343		p += netiface_len;
344		memcpy(p, netid, netid_len);
345		p += netid_len;
346		memcpy(p, dad_counter, sizeof(*dad_counter));
347		p += sizeof(*dad_counter);
348		memcpy(p, secret, secret_len);
349
350		/* Make an address using the digest of the above.
351		 * RFC7217 Section 5.1 states that we shouldn't use MD5.
352		 * Pity as we use that for HMAC-MD5 which is still deemed OK.
353		 * SHA-256 is recommended */
354		SHA256_Init(&ctx);
355		SHA256_Update(&ctx, buf, len);
356		SHA256_Final(digest, &ctx);
357
358		p = addr->s6_addr;
359		memcpy(p, prefix, l);
360		/* RFC7217 section 5.2 says we need to start taking the id from
361		 * the least significant bit */
362		len = sizeof(addr->s6_addr) - l;
363		memcpy(p + l, digest + (sizeof(digest) - len), len);
364
365		/* Ensure that the Interface ID does not match a reserved one,
366		 * if it does then treat it as a DAD failure.
367		 * RFC7217 section 5.2 */
368		if (prefix_len != 64)
369			break;
370		if (!ipv6_reserved(addr))
371			break;
372	}
373
374	return 0;
375}
376
377int
378ipv6_makestableprivate(struct in6_addr *addr,
379    const struct in6_addr *prefix, int prefix_len,
380    const struct interface *ifp,
381    int *dad_counter)
382{
383	uint32_t dad;
384	int r;
385
386	dad = (uint32_t)*dad_counter;
387
388	/* For our implementation, we shall set the hardware address
389	 * as the interface identifier */
390	r = ipv6_makestableprivate1(addr, prefix, prefix_len,
391	    ifp->hwaddr, ifp->hwlen,
392	    ifp->ssid, ifp->ssid_len,
393	    &dad,
394	    ifp->ctx->secret, ifp->ctx->secret_len);
395
396	if (r == 0)
397		*dad_counter = (int)dad;
398	return r;
399}
400
401int
402ipv6_makeaddr(struct in6_addr *addr, const struct interface *ifp,
403    const struct in6_addr *prefix, int prefix_len)
404{
405	const struct ipv6_addr *ap;
406	int dad;
407
408	if (prefix_len < 0 || prefix_len > 120) {
409		errno = EINVAL;
410		return -1;
411	}
412
413	if (ifp->options->options & DHCPCD_SLAACPRIVATE) {
414		if (ifp->ctx->secret_len == 0) {
415			if (ipv6_readsecret(ifp->ctx) == -1)
416				return -1;
417		}
418		dad = 0;
419		if (ipv6_makestableprivate(addr,
420		    prefix, prefix_len, ifp, &dad) == -1)
421			return -1;
422		return dad;
423	}
424
425	if (prefix_len > 64) {
426		errno = EINVAL;
427		return -1;
428	}
429	if ((ap = ipv6_linklocal(ifp)) == NULL) {
430		/* We delay a few functions until we get a local-link address
431		 * so this should never be hit. */
432		errno = ENOENT;
433		return -1;
434	}
435
436	/* Make the address from the first local-link address */
437	memcpy(addr, prefix, sizeof(*prefix));
438	addr->s6_addr32[2] = ap->addr.s6_addr32[2];
439	addr->s6_addr32[3] = ap->addr.s6_addr32[3];
440	return 0;
441}
442
443int
444ipv6_makeprefix(struct in6_addr *prefix, const struct in6_addr *addr, int len)
445{
446	int bytelen, bitlen;
447
448	if (len < 0 || len > 128) {
449		errno = EINVAL;
450		return -1;
451	}
452
453	bytelen = len / NBBY;
454	bitlen = len % NBBY;
455	memcpy(&prefix->s6_addr, &addr->s6_addr, (size_t)bytelen);
456	if (bitlen != 0)
457		prefix->s6_addr[bytelen] =
458		    (uint8_t)(prefix->s6_addr[bytelen] >> (NBBY - bitlen));
459	memset((char *)prefix->s6_addr + bytelen, 0,
460	    sizeof(prefix->s6_addr) - (size_t)bytelen);
461	return 0;
462}
463
464int
465ipv6_mask(struct in6_addr *mask, int len)
466{
467	static const unsigned char masks[NBBY] =
468	    { 0x80, 0xc0, 0xe0, 0xf0, 0xf8, 0xfc, 0xfe, 0xff };
469	int bytes, bits, i;
470
471	if (len < 0 || len > 128) {
472		errno = EINVAL;
473		return -1;
474	}
475
476	memset(mask, 0, sizeof(*mask));
477	bytes = len / NBBY;
478	bits = len % NBBY;
479	for (i = 0; i < bytes; i++)
480		mask->s6_addr[i] = 0xff;
481	if (bits)
482		mask->s6_addr[bytes] = masks[bits - 1];
483	return 0;
484}
485
486uint8_t
487ipv6_prefixlen(const struct in6_addr *mask)
488{
489	int x = 0, y;
490	const unsigned char *lim, *p;
491
492	lim = (const unsigned char *)mask + sizeof(*mask);
493	for (p = (const unsigned char *)mask; p < lim; x++, p++) {
494		if (*p != 0xff)
495			break;
496	}
497	y = 0;
498	if (p < lim) {
499		for (y = 0; y < NBBY; y++) {
500			if ((*p & (0x80 >> y)) == 0)
501				break;
502		}
503	}
504
505	/*
506	 * when the limit pointer is given, do a stricter check on the
507	 * remaining bits.
508	 */
509	if (p < lim) {
510		if (y != 0 && (*p & (0x00ff >> y)) != 0)
511			return 0;
512		for (p = p + 1; p < lim; p++)
513			if (*p != 0)
514				return 0;
515	}
516
517	return (uint8_t)(x * NBBY + y);
518}
519
520static void
521in6_to_h64(uint64_t *vhigh, uint64_t *vlow, const struct in6_addr *addr)
522{
523
524	*vhigh = be64dec(addr->s6_addr);
525	*vlow = be64dec(addr->s6_addr + 8);
526}
527
528static void
529h64_to_in6(struct in6_addr *addr, uint64_t vhigh, uint64_t vlow)
530{
531
532	be64enc(addr->s6_addr, vhigh);
533	be64enc(addr->s6_addr + 8, vlow);
534}
535
536int
537ipv6_userprefix(
538	const struct in6_addr *prefix,	// prefix from router
539	short prefix_len,		// length of prefix received
540	uint64_t user_number,		// "random" number from user
541	struct in6_addr *result,	// resultant prefix
542	short result_len)		// desired prefix length
543{
544	uint64_t vh, vl, user_low, user_high;
545
546	if (prefix_len < 0 || prefix_len > 120 ||
547	    result_len < 0 || result_len > 120)
548	{
549		errno = EINVAL;
550		return -1;
551	}
552
553	/* Check that the user_number fits inside result_len less prefix_len */
554	if (result_len < prefix_len || user_number > INT_MAX ||
555	    ffs((int)user_number) > result_len - prefix_len)
556	{
557	       errno = ERANGE;
558	       return -1;
559	}
560
561	/* virtually shift user number by dest_len, then split at 64 */
562	if (result_len >= 64) {
563		user_high = user_number << (result_len - 64);
564		user_low = 0;
565	} else {
566		user_high = user_number >> (64 - result_len);
567		user_low = user_number << result_len;
568	}
569
570	/* convert to two 64bit host order values */
571	in6_to_h64(&vh, &vl, prefix);
572
573	vh |= user_high;
574	vl |= user_low;
575
576	/* copy back result */
577	h64_to_in6(result, vh, vl);
578
579	return 0;
580}
581
582#ifdef IPV6_POLLADDRFLAG
583void
584ipv6_checkaddrflags(void *arg)
585{
586	struct ipv6_addr *ap;
587	int ifa_flags;
588
589	ap = arg;
590	ifa_flags = if_addrflags6(&ap->addr, ap->iface);
591	if (ifa_flags == -1)
592		logger(ap->iface->ctx, LOG_ERR,
593		    "%s: if_addrflags6: %m", ap->iface->name);
594	else if (!(ifa_flags & IN6_IFF_TENTATIVE)) {
595		ipv6_handleifa(ap->iface->ctx, RTM_NEWADDR,
596		    ap->iface->ctx->ifaces, ap->iface->name,
597		    &ap->addr, ap->prefix_len, ifa_flags);
598	} else {
599		struct timespec tv;
600
601		ms_to_ts(&tv, RETRANS_TIMER / 2);
602		eloop_timeout_add_tv(ap->iface->ctx->eloop, &tv,
603		    ipv6_checkaddrflags, ap);
604	}
605}
606#endif
607
608
609static void
610ipv6_deleteaddr(struct ipv6_addr *ia)
611{
612#ifndef PASSIVE_MODE
613	struct ipv6_state *state;
614	struct ipv6_addr *ap;
615
616	logger(ia->iface->ctx, LOG_INFO, "%s: deleting address %s",
617	    ia->iface->name, ia->saddr);
618	if (if_deladdress6(ia) == -1 &&
619	    errno != EADDRNOTAVAIL && errno != ENXIO && errno != ENODEV)
620		logger(ia->iface->ctx, LOG_ERR, "if_deladdress6: :%m");
621
622	state = IPV6_STATE(ia->iface);
623	TAILQ_FOREACH(ap, &state->addrs, next) {
624		if (IN6_ARE_ADDR_EQUAL(&ap->addr, &ia->addr)) {
625			TAILQ_REMOVE(&state->addrs, ap, next);
626			ipv6_freeaddr(ap);
627			break;
628		}
629	}
630#endif
631}
632
633int
634ipv6_addaddr(struct ipv6_addr *ap, const struct timespec *now)
635{
636#ifndef PASSIVE_MODE
637	struct interface *ifp;
638	struct ipv6_state *state;
639	struct ipv6_addr *nap;
640	uint32_t pltime, vltime;
641
642	/* Ensure no other interface has this address */
643	TAILQ_FOREACH(ifp, ap->iface->ctx->ifaces, next) {
644		if (ifp == ap->iface || strcmp(ifp->name, ap->iface->name) == 0)
645			continue;
646		state = IPV6_STATE(ifp);
647		if (state == NULL)
648			continue;
649		TAILQ_FOREACH(nap, &state->addrs, next) {
650			if (IN6_ARE_ADDR_EQUAL(&nap->addr, &ap->addr)) {
651				ipv6_deleteaddr(nap);
652				break;
653			}
654		}
655	}
656
657	if (!(ap->flags & IPV6_AF_DADCOMPLETED) &&
658	    ipv6_iffindaddr(ap->iface, &ap->addr))
659		ap->flags |= IPV6_AF_DADCOMPLETED;
660
661	logger(ap->iface->ctx, ap->flags & IPV6_AF_NEW ? LOG_INFO : LOG_DEBUG,
662	    "%s: adding address %s", ap->iface->name, ap->saddr);
663	if (ap->prefix_pltime == ND6_INFINITE_LIFETIME &&
664	    ap->prefix_vltime == ND6_INFINITE_LIFETIME)
665		logger(ap->iface->ctx, LOG_DEBUG,
666		    "%s: pltime infinity, vltime infinity",
667		    ap->iface->name);
668	else if (ap->prefix_pltime == ND6_INFINITE_LIFETIME)
669		logger(ap->iface->ctx, LOG_DEBUG,
670		    "%s: pltime infinity, vltime %"PRIu32" seconds",
671		    ap->iface->name, ap->prefix_vltime);
672	else if (ap->prefix_vltime == ND6_INFINITE_LIFETIME)
673		logger(ap->iface->ctx, LOG_DEBUG,
674		    "%s: pltime %"PRIu32"seconds, vltime infinity",
675		    ap->iface->name, ap->prefix_pltime);
676	else
677		logger(ap->iface->ctx, LOG_DEBUG,
678		    "%s: pltime %"PRIu32" seconds, vltime %"PRIu32" seconds",
679		    ap->iface->name, ap->prefix_pltime, ap->prefix_vltime);
680
681	/* Adjust plftime and vltime based on acquired time */
682	pltime = ap->prefix_pltime;
683	vltime = ap->prefix_vltime;
684	if (timespecisset(&ap->acquired) &&
685	    (ap->prefix_pltime != ND6_INFINITE_LIFETIME ||
686	    ap->prefix_vltime != ND6_INFINITE_LIFETIME))
687	{
688		struct timespec n;
689
690		if (now == NULL) {
691			get_monotonic(&n);
692			now = &n;
693		}
694		timespecsub(now, &ap->acquired, &n);
695		if (ap->prefix_pltime != ND6_INFINITE_LIFETIME)
696			ap->prefix_pltime -= (uint32_t)n.tv_sec;
697		if (ap->prefix_vltime != ND6_INFINITE_LIFETIME)
698			ap->prefix_vltime -= (uint32_t)n.tv_sec;
699	}
700
701	if (if_addaddress6(ap) == -1) {
702		logger(ap->iface->ctx, LOG_ERR, "if_addaddress6: %m");
703#if 0
704		logger(ap->iface->ctx, LOG_DEBUG,
705		    "%s: adj pltime %"PRIu32" seconds, "
706		    "vltime %"PRIu32" seconds",
707		    ap->iface->name, ap->prefix_pltime, ap->prefix_vltime);
708#endif
709		/* Restore real pltime and vltime */
710		ap->prefix_pltime = pltime;
711		ap->prefix_vltime = vltime;
712		return -1;
713	}
714
715#ifdef IPV6_MANAGETEMPADDR
716	/* RFC4941 Section 3.4 */
717	if (ap->flags & IPV6_AF_TEMPORARY &&
718	    ap->prefix_pltime &&
719	    ap->prefix_vltime &&
720	    ap->iface->options->options & DHCPCD_IPV6RA_OWN &&
721	    ip6_use_tempaddr(ap->iface->name))
722		eloop_timeout_add_sec(ap->iface->ctx->eloop,
723		    (time_t)ap->prefix_pltime - REGEN_ADVANCE,
724		    ipv6_regentempaddr, ap);
725#endif
726
727	/* Restore real pltime and vltime */
728	ap->prefix_pltime = pltime;
729	ap->prefix_vltime = vltime;
730
731	ap->flags &= ~IPV6_AF_NEW;
732	ap->flags |= IPV6_AF_ADDED;
733	if (ap->delegating_iface)
734		ap->flags |= IPV6_AF_DELEGATED;
735
736#ifdef IPV6_POLLADDRFLAG
737	eloop_timeout_delete(ap->iface->ctx->eloop,
738		ipv6_checkaddrflags, ap);
739	if (!(ap->flags & IPV6_AF_DADCOMPLETED)) {
740		struct timespec tv;
741
742		ms_to_ts(&tv, RETRANS_TIMER / 2);
743		eloop_timeout_add_tv(ap->iface->ctx->eloop,
744		    &tv, ipv6_checkaddrflags, ap);
745	}
746#endif
747#endif
748
749	return 0;
750}
751
752int
753ipv6_publicaddr(const struct ipv6_addr *ia)
754{
755	return (ia->prefix_pltime &&
756	    (ia->addr.s6_addr[0] & 0xfe) != 0xc &&
757	    !(ia->addr_flags & IN6_IFF_NOTUSEABLE));
758}
759
760struct ipv6_addr *
761ipv6_findaddr(struct dhcpcd_ctx *ctx, const struct in6_addr *addr, short flags)
762{
763	struct ipv6_addr *dap, *nap;
764
765	dap = dhcp6_findaddr(ctx, addr, flags);
766	nap = ipv6nd_findaddr(ctx, addr, flags);
767	if (!dap && !nap)
768		return NULL;
769	if (dap && !nap)
770		return dap;
771	if (nap && !dap)
772		return nap;
773	if (nap->iface->metric < dap->iface->metric)
774		return nap;
775	return dap;
776}
777
778ssize_t
779ipv6_addaddrs(struct ipv6_addrhead *addrs)
780{
781	struct ipv6_addr *ap, *apn, *apf;
782	ssize_t i;
783	struct timespec now;
784
785	i = 0;
786	timespecclear(&now);
787	TAILQ_FOREACH_SAFE(ap, addrs, next, apn) {
788		if (ap->prefix_vltime == 0) {
789			if (ap->flags & IPV6_AF_ADDED) {
790				ipv6_deleteaddr(ap);
791				i++;
792			}
793			eloop_q_timeout_delete(ap->iface->ctx->eloop,
794			    0, NULL, ap);
795			if (ap->flags & IPV6_AF_REQUEST) {
796				ap->flags &= ~IPV6_AF_ADDED;
797			} else {
798				TAILQ_REMOVE(addrs, ap, next);
799				ipv6_freeaddr(ap);
800			}
801		} else if (!(ap->flags & IPV6_AF_STALE) &&
802		    !IN6_IS_ADDR_UNSPECIFIED(&ap->addr))
803		{
804			apf = ipv6_findaddr(ap->iface->ctx,
805			    &ap->addr, IPV6_AF_ADDED);
806			if (apf && apf->iface != ap->iface &&
807			    strcmp(apf->iface->name, ap->iface->name))
808			{
809				if (apf->iface->metric <= ap->iface->metric) {
810					logger(apf->iface->ctx, LOG_INFO,
811					    "%s: preferring %s on %s",
812					    ap->iface->name,
813					    ap->saddr,
814					    apf->iface->name);
815					continue;
816				}
817				logger(apf->iface->ctx, LOG_INFO,
818				    "%s: preferring %s on %s",
819				    apf->iface->name,
820				    ap->saddr,
821				    ap->iface->name);
822				if (if_deladdress6(apf) == -1 &&
823				    errno != EADDRNOTAVAIL && errno != ENXIO)
824					logger(apf->iface->ctx, LOG_ERR,
825					    "if_deladdress6: %m");
826				apf->flags &=
827				    ~(IPV6_AF_ADDED | IPV6_AF_DADCOMPLETED);
828			} else if (apf)
829				apf->flags &= ~IPV6_AF_ADDED;
830			if (ap->flags & IPV6_AF_NEW)
831				i++;
832			if (!timespecisset(&now))
833				get_monotonic(&now);
834			ipv6_addaddr(ap, &now);
835		}
836	}
837
838	return i;
839}
840
841void
842ipv6_freeaddr(struct ipv6_addr *ap)
843{
844
845	eloop_q_timeout_delete(ap->iface->ctx->eloop, 0, NULL, ap);
846	free(ap);
847}
848
849void
850ipv6_freedrop_addrs(struct ipv6_addrhead *addrs, int drop,
851    const struct interface *ifd)
852{
853	struct ipv6_addr *ap, *apn, *apf;
854	struct timespec now;
855
856	timespecclear(&now);
857	TAILQ_FOREACH_SAFE(ap, addrs, next, apn) {
858		if (ifd && ap->delegating_iface != ifd)
859			continue;
860		if (drop != 2)
861			TAILQ_REMOVE(addrs, ap, next);
862		if (drop && ap->flags & IPV6_AF_ADDED &&
863		    (ap->iface->options->options &
864		    (DHCPCD_EXITING | DHCPCD_PERSISTENT)) !=
865		    (DHCPCD_EXITING | DHCPCD_PERSISTENT))
866		{
867			if (drop == 2)
868				TAILQ_REMOVE(addrs, ap, next);
869			/* Find the same address somewhere else */
870			apf = ipv6_findaddr(ap->iface->ctx, &ap->addr, 0);
871			if (apf == NULL ||
872			    (apf->iface != ap->iface &&
873			    strcmp(apf->iface->name, ap->iface->name)))
874				ipv6_deleteaddr(ap);
875			if (!(ap->iface->options->options &
876			    DHCPCD_EXITING) && apf)
877			{
878				if (!timespecisset(&now))
879					get_monotonic(&now);
880				ipv6_addaddr(apf, &now);
881			}
882			if (drop == 2)
883				ipv6_freeaddr(ap);
884		}
885		if (drop != 2)
886			ipv6_freeaddr(ap);
887	}
888}
889
890static struct ipv6_state *
891ipv6_getstate(struct interface *ifp)
892{
893	struct ipv6_state *state;
894
895	state = IPV6_STATE(ifp);
896	if (state == NULL) {
897	        ifp->if_data[IF_DATA_IPV6] = calloc(1, sizeof(*state));
898		state = IPV6_STATE(ifp);
899		if (state == NULL) {
900			logger(ifp->ctx, LOG_ERR, "%s: %m", __func__);
901			return NULL;
902		}
903		TAILQ_INIT(&state->addrs);
904		TAILQ_INIT(&state->ll_callbacks);
905
906		/* Regenerate new ids */
907		if (ifp->options &&
908		    ifp->options->options & DHCPCD_IPV6RA_OWN &&
909		    ip6_use_tempaddr(ifp->name))
910			ipv6_regentempifid(ifp);
911	}
912	return state;
913}
914
915void
916ipv6_handleifa(struct dhcpcd_ctx *ctx,
917    int cmd, struct if_head *ifs, const char *ifname,
918    const struct in6_addr *addr, uint8_t prefix_len, int flags)
919{
920	struct interface *ifp;
921	struct ipv6_state *state;
922	struct ipv6_addr *ap;
923	struct ll_callback *cb;
924
925#if 0
926	char buf[INET6_ADDRSTRLEN];
927	inet_ntop(AF_INET6, &addr->s6_addr,
928	    buf, INET6_ADDRSTRLEN);
929	logger(ctx, LOG_DEBUG, "%s: cmd %d addr %s flags %d",
930	    ifname, cmd, buf, flags);
931#endif
932
933	if (ifs == NULL)
934		ifs = ctx->ifaces;
935	if (ifs == NULL) {
936		errno = ESRCH;
937		return;
938	}
939	TAILQ_FOREACH(ifp, ifs, next) {
940		/* Each psuedo interface also stores addresses */
941		if (strcmp(ifp->name, ifname))
942			continue;
943		state = ipv6_getstate(ifp);
944		if (state == NULL)
945			continue;
946
947		if (!IN6_IS_ADDR_LINKLOCAL(addr)) {
948			ipv6nd_handleifa(ctx, cmd, ifname, addr, flags);
949			dhcp6_handleifa(ctx, cmd, ifname, addr, flags);
950		}
951
952		TAILQ_FOREACH(ap, &state->addrs, next) {
953			if (IN6_ARE_ADDR_EQUAL(&ap->addr, addr))
954				break;
955		}
956
957		switch (cmd) {
958		case RTM_DELADDR:
959			if (ap) {
960				TAILQ_REMOVE(&state->addrs, ap, next);
961				ipv6_freeaddr(ap);
962			}
963			break;
964		case RTM_NEWADDR:
965			if (ap == NULL) {
966				char buf[INET6_ADDRSTRLEN];
967				const char *cbp;
968
969				ap = calloc(1, sizeof(*ap));
970				ap->iface = ifp;
971				ap->addr = *addr;
972				ap->prefix_len = prefix_len;
973				ipv6_makeprefix(&ap->prefix, &ap->addr,
974				    ap->prefix_len);
975				cbp = inet_ntop(AF_INET6, &addr->s6_addr,
976				    buf, sizeof(buf));
977				if (cbp)
978					snprintf(ap->saddr, sizeof(ap->saddr),
979					    "%s/%d", cbp, prefix_len);
980				if (if_getlifetime6(ap) == -1) {
981					/* No support or address vanished.
982					 * Either way, just set a deprecated
983					 * infinite time lifetime and continue.
984					 * This is fine because we only want
985					 * to know this when trying to extend
986					 * temporary addresses.
987					 * As we can't extend infinite, we'll
988					 * create a new temporary address. */
989					ap->prefix_pltime = 0;
990					ap->prefix_vltime =
991					    ND6_INFINITE_LIFETIME;
992				}
993				/* This is a minor regression against RFC 4941
994				 * because the kernel only knows when the
995				 * lifetimes were last updated, not when the
996				 * address was initially created.
997				 * Provided dhcpcd is not restarted, this
998				 * won't be a problem.
999				 * If we don't like it, we can always
1000				 * pretend lifetimes are infinite and always
1001				 * generate a new temporary address on
1002				 * restart. */
1003				ap->acquired = ap->created;
1004				TAILQ_INSERT_TAIL(&state->addrs,
1005				    ap, next);
1006			}
1007			ap->addr_flags = flags;
1008#ifdef IPV6_MANAGETEMPADDR
1009			if (ap->addr_flags & IN6_IFF_TEMPORARY)
1010				ap->flags |= IPV6_AF_TEMPORARY;
1011#endif
1012			if (IN6_IS_ADDR_LINKLOCAL(&ap->addr)) {
1013#ifdef IPV6_POLLADDRFLAG
1014				if (ap->addr_flags & IN6_IFF_TENTATIVE) {
1015					struct timespec tv;
1016
1017					ms_to_ts(&tv, RETRANS_TIMER / 2);
1018					eloop_timeout_add_tv(
1019					    ap->iface->ctx->eloop,
1020					    &tv, ipv6_checkaddrflags, ap);
1021					break;
1022				}
1023#endif
1024
1025				if (!(ap->addr_flags & IN6_IFF_NOTUSEABLE)) {
1026					/* Now run any callbacks.
1027					 * Typically IPv6RS or DHCPv6 */
1028					while ((cb =
1029					    TAILQ_FIRST(&state->ll_callbacks)))
1030					{
1031						TAILQ_REMOVE(
1032						    &state->ll_callbacks,
1033						    cb, next);
1034						cb->callback(cb->arg);
1035						free(cb);
1036					}
1037				}
1038			}
1039			break;
1040		}
1041	}
1042}
1043
1044const struct ipv6_addr *
1045ipv6_iffindaddr(const struct interface *ifp, const struct in6_addr *addr)
1046{
1047	const struct ipv6_state *state;
1048	const struct ipv6_addr *ap;
1049
1050	state = IPV6_CSTATE(ifp);
1051	if (state) {
1052		TAILQ_FOREACH(ap, &state->addrs, next) {
1053			if (addr == NULL) {
1054				if (IN6_IS_ADDR_LINKLOCAL(&ap->addr) &&
1055				    !(ap->addr_flags & IN6_IFF_NOTUSEABLE))
1056					return ap;
1057			} else {
1058				if (IN6_ARE_ADDR_EQUAL(&ap->addr, addr) &&
1059				    !(ap->addr_flags & IN6_IFF_TENTATIVE))
1060					return ap;
1061			}
1062		}
1063	}
1064	return NULL;
1065}
1066
1067int
1068ipv6_addlinklocalcallback(struct interface *ifp,
1069    void (*callback)(void *), void *arg)
1070{
1071	struct ipv6_state *state;
1072	struct ll_callback *cb;
1073
1074	state = ipv6_getstate(ifp);
1075	TAILQ_FOREACH(cb, &state->ll_callbacks, next) {
1076		if (cb->callback == callback && cb->arg == arg)
1077			break;
1078	}
1079	if (cb == NULL) {
1080		cb = malloc(sizeof(*cb));
1081		if (cb == NULL) {
1082			logger(ifp->ctx, LOG_ERR, "%s: %m", __func__);
1083			return -1;
1084		}
1085		cb->callback = callback;
1086		cb->arg = arg;
1087		TAILQ_INSERT_TAIL(&state->ll_callbacks, cb, next);
1088	}
1089	return 0;
1090}
1091
1092static struct ipv6_addr *
1093ipv6_newlinklocal(struct interface *ifp)
1094{
1095	struct ipv6_addr *ap;
1096
1097	ap = calloc(1, sizeof(*ap));
1098	if (ap != NULL) {
1099		ap->iface = ifp;
1100		ap->prefix.s6_addr32[0] = htonl(0xfe800000);
1101		ap->prefix.s6_addr32[1] = 0;
1102		ap->prefix_len = 64;
1103		ap->dadcounter = 0;
1104		ap->prefix_pltime = ND6_INFINITE_LIFETIME;
1105		ap->prefix_vltime = ND6_INFINITE_LIFETIME;
1106		ap->flags = IPV6_AF_NEW;
1107		ap->addr_flags = IN6_IFF_TENTATIVE;
1108	}
1109	return ap;
1110}
1111
1112static const uint8_t allzero[8] = { 0, 0, 0, 0, 0, 0, 0, 0 };
1113static const uint8_t allone[8] =
1114    { 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff };
1115
1116static int
1117ipv6_addlinklocal(struct interface *ifp)
1118{
1119	struct ipv6_state *state;
1120	struct ipv6_addr *ap, *ap2;
1121	int dadcounter;
1122
1123	/* Check sanity before malloc */
1124	if (!(ifp->options->options & DHCPCD_SLAACPRIVATE)) {
1125		switch (ifp->family) {
1126		case ARPHRD_ETHER:
1127			/* Check for a valid hardware address */
1128			if (ifp->hwlen != 6 && ifp->hwlen != 8) {
1129				errno = ENOTSUP;
1130				return -1;
1131			}
1132			if (memcmp(ifp->hwaddr, allzero, ifp->hwlen) == 0 ||
1133			    memcmp(ifp->hwaddr, allone, ifp->hwlen) == 0)
1134			{
1135				errno = EINVAL;
1136				return -1;
1137			}
1138			break;
1139		default:
1140			errno = ENOTSUP;
1141			return -1;
1142		}
1143	}
1144
1145	state = ipv6_getstate(ifp);
1146	if (state == NULL)
1147		return -1;
1148
1149	ap = ipv6_newlinklocal(ifp);
1150	if (ap == NULL)
1151		return -1;
1152
1153	if (ifp->options->options & DHCPCD_SLAACPRIVATE) {
1154		dadcounter = 0;
1155nextslaacprivate:
1156		if (ipv6_makestableprivate(&ap->addr,
1157			&ap->prefix, ap->prefix_len, ifp, &dadcounter) == -1)
1158		{
1159			free(ap);
1160			return -1;
1161		}
1162		ap->dadcounter = dadcounter;
1163	} else {
1164		memcpy(ap->addr.s6_addr, ap->prefix.s6_addr, 8);
1165		switch (ifp->family) {
1166		case ARPHRD_ETHER:
1167			if (ifp->hwlen == 6) {
1168				ap->addr.s6_addr[ 8] = ifp->hwaddr[0];
1169				ap->addr.s6_addr[ 9] = ifp->hwaddr[1];
1170				ap->addr.s6_addr[10] = ifp->hwaddr[2];
1171				ap->addr.s6_addr[11] = 0xff;
1172				ap->addr.s6_addr[12] = 0xfe;
1173				ap->addr.s6_addr[13] = ifp->hwaddr[3];
1174				ap->addr.s6_addr[14] = ifp->hwaddr[4];
1175				ap->addr.s6_addr[15] = ifp->hwaddr[5];
1176			} else if (ifp->hwlen == 8)
1177				memcpy(&ap->addr.s6_addr[8], ifp->hwaddr, 8);
1178			else {
1179				free(ap);
1180				errno = ENOTSUP;
1181				return -1;
1182			}
1183			break;
1184		}
1185
1186		/* Sanity check: g bit must not indciate "group" */
1187		if (EUI64_GROUP(&ap->addr)) {
1188			free(ap);
1189			errno = EINVAL;
1190			return -1;
1191		}
1192		EUI64_TO_IFID(&ap->addr);
1193	}
1194
1195	/* Do we already have this address? */
1196	TAILQ_FOREACH(ap2, &state->addrs, next) {
1197		if (IN6_ARE_ADDR_EQUAL(&ap->addr, &ap2->addr)) {
1198			if (ap2->addr_flags & IN6_IFF_DUPLICATED) {
1199				if (ifp->options->options &
1200				    DHCPCD_SLAACPRIVATE)
1201				{
1202					dadcounter++;
1203					goto nextslaacprivate;
1204				}
1205				free(ap);
1206				errno = EADDRNOTAVAIL;
1207				return -1;
1208			}
1209
1210			logger(ap2->iface->ctx, LOG_WARNING,
1211			    "%s: waiting for %s to complete",
1212			    ap2->iface->name, ap2->saddr);
1213			free(ap);
1214			errno =	EEXIST;
1215			return 0;
1216		}
1217	}
1218
1219	inet_ntop(AF_INET6, &ap->addr, ap->saddr, sizeof(ap->saddr));
1220	TAILQ_INSERT_TAIL(&state->addrs, ap, next);
1221	ipv6_addaddr(ap, NULL);
1222	return 1;
1223}
1224
1225/* Ensure the interface has a link-local address */
1226int
1227ipv6_start(struct interface *ifp)
1228{
1229	const struct ipv6_state *state;
1230	const struct ipv6_addr *ap;
1231
1232	/* We can't assign a link-locak address to this,
1233	 * the ppp process has to. */
1234	if (ifp->flags & IFF_POINTOPOINT)
1235		return 0;
1236
1237	state = IPV6_CSTATE(ifp);
1238	if (state) {
1239		TAILQ_FOREACH(ap, &state->addrs, next) {
1240			if (IN6_IS_ADDR_LINKLOCAL(&ap->addr) &&
1241			    !(ap->addr_flags & IN6_IFF_DUPLICATED))
1242				break;
1243		}
1244		/* Regenerate new ids */
1245		if (ifp->options->options & DHCPCD_IPV6RA_OWN &&
1246		    ip6_use_tempaddr(ifp->name))
1247			ipv6_regentempifid(ifp);
1248	} else
1249		ap = NULL;
1250
1251	if (ap == NULL && ipv6_addlinklocal(ifp) == -1)
1252		return -1;
1253
1254	/* Load existing routes */
1255	if_initrt6(ifp);
1256	return 0;
1257}
1258
1259void
1260ipv6_freedrop(struct interface *ifp, int drop)
1261{
1262	struct ipv6_state *state;
1263	struct ll_callback *cb;
1264
1265	if (ifp == NULL)
1266		return;
1267
1268	if ((state = IPV6_STATE(ifp)) == NULL)
1269		return;
1270
1271	ipv6_freedrop_addrs(&state->addrs, drop ? 2 : 0, NULL);
1272
1273	/* Becuase we need to cache the addresses we don't control,
1274	 * we only free the state on when NOT dropping addresses. */
1275	if (drop == 0) {
1276		while ((cb = TAILQ_FIRST(&state->ll_callbacks))) {
1277			TAILQ_REMOVE(&state->ll_callbacks, cb, next);
1278			free(cb);
1279		}
1280		free(state);
1281		ifp->if_data[IF_DATA_IPV6] = NULL;
1282		eloop_timeout_delete(ifp->ctx->eloop, NULL, ifp);
1283	}
1284}
1285
1286void
1287ipv6_ctxfree(struct dhcpcd_ctx *ctx)
1288{
1289
1290	if (ctx->ipv6 == NULL)
1291		return;
1292
1293	ipv6_freerts(ctx->ipv6->routes);
1294	free(ctx->ipv6->routes);
1295	free(ctx->ipv6->ra_routers);
1296	ipv6_freerts(&ctx->ipv6->kroutes);
1297	free(ctx->ipv6);
1298}
1299
1300int
1301ipv6_handleifa_addrs(int cmd,
1302    struct ipv6_addrhead *addrs, const struct in6_addr *addr, int flags)
1303{
1304	struct ipv6_addr *ap, *apn;
1305	uint8_t found, alldadcompleted;
1306
1307	alldadcompleted = 1;
1308	found = 0;
1309	TAILQ_FOREACH_SAFE(ap, addrs, next, apn) {
1310		if (!IN6_ARE_ADDR_EQUAL(addr, &ap->addr)) {
1311			if (ap->flags & IPV6_AF_ADDED &&
1312			    !(ap->flags & IPV6_AF_DADCOMPLETED))
1313				alldadcompleted = 0;
1314			continue;
1315		}
1316		switch (cmd) {
1317		case RTM_DELADDR:
1318			if (ap->flags & IPV6_AF_ADDED) {
1319				logger(ap->iface->ctx, LOG_INFO,
1320				    "%s: deleted address %s",
1321				    ap->iface->name, ap->saddr);
1322				ap->flags &= ~IPV6_AF_ADDED;
1323			}
1324			break;
1325		case RTM_NEWADDR:
1326			/* Safety - ignore tentative announcements */
1327			if (flags & (IN6_IFF_DETACHED |IN6_IFF_TENTATIVE))
1328				break;
1329			if ((ap->flags & IPV6_AF_DADCOMPLETED) == 0) {
1330				found++;
1331				if (flags & IN6_IFF_DUPLICATED)
1332					ap->flags |= IPV6_AF_DUPLICATED;
1333				else
1334					ap->flags &= ~IPV6_AF_DUPLICATED;
1335				if (ap->dadcallback)
1336					ap->dadcallback(ap);
1337				/* We need to set this here in-case the
1338				 * dadcallback function checks it */
1339				ap->flags |= IPV6_AF_DADCOMPLETED;
1340			}
1341			break;
1342		}
1343	}
1344
1345	return alldadcompleted ? found : 0;
1346}
1347
1348#ifdef IPV6_MANAGETEMPADDR
1349static const struct ipv6_addr *
1350ipv6_findaddrid(struct dhcpcd_ctx *ctx, uint8_t *addr)
1351{
1352	const struct interface *ifp;
1353	const struct ipv6_state *state;
1354	const struct ipv6_addr *ia;
1355
1356	TAILQ_FOREACH(ifp, ctx->ifaces, next) {
1357		if ((state = IPV6_CSTATE(ifp))) {
1358			TAILQ_FOREACH(ia, &state->addrs, next) {
1359				if (memcmp(&ia->addr.s6_addr[8], addr, 8) == 0)
1360					return ia;
1361			}
1362		}
1363	}
1364	return NULL;
1365}
1366
1367static const uint8_t nullid[8];
1368static const uint8_t anycastid[8] = {
1369    0xfd, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0x80 };
1370static const uint8_t isatapid[4] = { 0x00, 0x00, 0x5e, 0xfe };
1371
1372static void
1373ipv6_regen_desync(struct interface *ifp, int force)
1374{
1375	struct ipv6_state *state;
1376	time_t max;
1377
1378	state = IPV6_STATE(ifp);
1379
1380	/* RFC4941 Section 5 states that DESYNC_FACTOR must never be
1381	 * greater than TEMP_VALID_LIFETIME - REGEN_ADVANCE.
1382	 * I believe this is an error and it should be never be greateter than
1383	 * TEMP_PREFERRED_LIFETIME - REGEN_ADVANCE. */
1384	max = ip6_temp_preferred_lifetime(ifp->name) - REGEN_ADVANCE;
1385	if (state->desync_factor && !force && state->desync_factor < max)
1386		return;
1387	if (state->desync_factor == 0)
1388		state->desync_factor =
1389		    (time_t)arc4random_uniform(MIN(MAX_DESYNC_FACTOR,
1390		    (uint32_t)max));
1391	max = ip6_temp_preferred_lifetime(ifp->name) -
1392	    state->desync_factor - REGEN_ADVANCE;
1393	eloop_timeout_add_sec(ifp->ctx->eloop, max, ipv6_regentempifid, ifp);
1394}
1395
1396void
1397ipv6_gentempifid(struct interface *ifp)
1398{
1399	struct ipv6_state *state;
1400	MD5_CTX md5;
1401	uint8_t seed[16], digest[16];
1402	int retry;
1403
1404	if ((state = IPV6_STATE(ifp)) == NULL)
1405		return;
1406
1407	retry = 0;
1408	if (memcmp(nullid, state->randomseed0, sizeof(nullid)) == 0) {
1409		uint32_t r;
1410
1411		r = arc4random();
1412		memcpy(seed, &r, sizeof(r));
1413		r = arc4random();
1414		memcpy(seed + sizeof(r), &r, sizeof(r));
1415	} else
1416		memcpy(seed, state->randomseed0, sizeof(state->randomseed0));
1417
1418	memcpy(seed + sizeof(state->randomseed0),
1419	    state->randomseed1, sizeof(state->randomseed1));
1420
1421again:
1422	/* RFC4941 Section 3.2.1.1
1423	 * Take the left-most 64bits and set bit 6 to zero */
1424	MD5Init(&md5);
1425	MD5Update(&md5, seed, sizeof(seed));
1426	MD5Final(digest, &md5);
1427
1428	/* RFC4941 Section 3.2.1.1
1429	 * Take the left-most 64bits and set bit 6 to zero */
1430	memcpy(state->randomid, digest, sizeof(state->randomid));
1431	state->randomid[0] = (uint8_t)(state->randomid[0] & ~EUI64_UBIT);
1432
1433	/* RFC4941 Section 3.2.1.4
1434	 * Reject reserved or existing id's */
1435	if (memcmp(nullid, state->randomid, sizeof(nullid)) == 0 ||
1436	    (memcmp(anycastid, state->randomid, 7) == 0 &&
1437	    (anycastid[7] & state->randomid[7]) == anycastid[7]) ||
1438	    memcmp(isatapid, state->randomid, sizeof(isatapid)) == 0 ||
1439	    ipv6_findaddrid(ifp->ctx, state->randomid))
1440	{
1441		if (++retry < GEN_TEMPID_RETRY_MAX) {
1442			memcpy(seed, digest + 8, 8);
1443			goto again;
1444		}
1445		memset(state->randomid, 0, sizeof(state->randomid));
1446	}
1447
1448	/* RFC4941 Section 3.2.1.6
1449	 * Save the right-most 64bits of the digest */
1450	memcpy(state->randomseed0, digest + 8,
1451	    sizeof(state->randomseed0));
1452}
1453
1454/* RFC4941 Section 3.3.7 */
1455static void
1456ipv6_tempdadcallback(void *arg)
1457{
1458	struct ipv6_addr *ia = arg;
1459
1460	if (ia->flags & IPV6_AF_DUPLICATED) {
1461		struct ipv6_addr *ia1;
1462		struct timespec tv;
1463
1464		if (++ia->dadcounter == TEMP_IDGEN_RETRIES) {
1465			logger(ia->iface->ctx, LOG_ERR,
1466			    "%s: too many duplicate temporary addresses",
1467			    ia->iface->name);
1468			return;
1469		}
1470		get_monotonic(&tv);
1471		if ((ia1 = ipv6_createtempaddr(ia, &tv)) == NULL)
1472			logger(ia->iface->ctx, LOG_ERR,
1473			    "ipv6_createtempaddr: %m");
1474		else
1475			ia1->dadcounter = ia->dadcounter;
1476		ipv6_deleteaddr(ia);
1477		if (ia1)
1478			ipv6_addaddr(ia1, &ia1->acquired);
1479	}
1480}
1481
1482struct ipv6_addr *
1483ipv6_createtempaddr(struct ipv6_addr *ia0, const struct timespec *now)
1484{
1485	struct ipv6_state *state;
1486	const struct ipv6_state *cstate;
1487	int genid;
1488	struct in6_addr addr, mask;
1489	uint32_t randid[2];
1490	const struct interface *ifp;
1491	const struct ipv6_addr *ap;
1492	struct ipv6_addr *ia;
1493	uint32_t i, trylimit;
1494	char buf[INET6_ADDRSTRLEN];
1495	const char *cbp;
1496
1497	trylimit = TEMP_IDGEN_RETRIES;
1498	state = IPV6_STATE(ia0->iface);
1499	genid = 0;
1500
1501	addr = ia0->addr;
1502	ipv6_mask(&mask, ia0->prefix_len);
1503	/* clear the old ifid */
1504	for (i = 0; i < 4; i++)
1505		addr.s6_addr32[i] &= mask.s6_addr32[i];
1506
1507again:
1508	if (memcmp(state->randomid, nullid, sizeof(nullid)) == 0)
1509		genid = 1;
1510	if (genid) {
1511		memcpy(state->randomseed1, &ia0->addr.s6_addr[8],
1512		    sizeof(state->randomseed1));
1513		ipv6_gentempifid(ia0->iface);
1514		if (memcmp(state->randomid, nullid, sizeof(nullid)) == 0) {
1515			errno = EFAULT;
1516			return NULL;
1517		}
1518	}
1519	memcpy(&randid[0], state->randomid, sizeof(randid[0]));
1520	memcpy(&randid[1], state->randomid + sizeof(randid[1]),
1521	    sizeof(randid[2]));
1522	addr.s6_addr32[2] |= randid[0] & ~mask.s6_addr32[2];
1523	addr.s6_addr32[3] |= randid[1] & ~mask.s6_addr32[3];
1524
1525	/* Ensure we don't already have it */
1526	TAILQ_FOREACH(ifp, ia0->iface->ctx->ifaces, next) {
1527		cstate = IPV6_CSTATE(ifp);
1528		if (cstate) {
1529			TAILQ_FOREACH(ap, &cstate->addrs, next) {
1530				if (IN6_ARE_ADDR_EQUAL(&ap->addr, &addr)) {
1531					if (--trylimit == 0) {
1532						errno = EEXIST;
1533						return NULL;
1534					}
1535					genid = 1;
1536					goto again;
1537				}
1538			}
1539		}
1540	}
1541
1542	if ((ia = calloc(1, sizeof(*ia))) == NULL)
1543		return NULL;
1544
1545	ia->iface = ia0->iface;
1546	ia->addr = addr;
1547	/* Must be made tentative, for our DaD to work */
1548	ia->addr_flags = IN6_IFF_TENTATIVE;
1549	ia->dadcallback = ipv6_tempdadcallback;
1550	ia->flags = IPV6_AF_NEW | IPV6_AF_AUTOCONF | IPV6_AF_TEMPORARY;
1551	ia->prefix = ia0->prefix;
1552	ia->prefix_len = ia0->prefix_len;
1553	ia->created = ia->acquired = now ? *now : ia0->acquired;
1554
1555	/* Ensure desync is still valid */
1556	ipv6_regen_desync(ia->iface, 0);
1557
1558	/* RFC4941 Section 3.3.4 */
1559	i = (uint32_t)(ip6_temp_preferred_lifetime(ia0->iface->name) -
1560	    state->desync_factor);
1561	ia->prefix_pltime = MIN(ia0->prefix_pltime, i);
1562	i = (uint32_t)ip6_temp_valid_lifetime(ia0->iface->name);
1563	ia->prefix_vltime = MIN(ia0->prefix_vltime, i);
1564	if (ia->prefix_pltime <= REGEN_ADVANCE ||
1565	    ia->prefix_pltime > ia0->prefix_vltime)
1566	{
1567		errno =	EINVAL;
1568		free(ia);
1569		return NULL;
1570	}
1571
1572	cbp = inet_ntop(AF_INET6, &ia->addr, buf, sizeof(buf));
1573	if (cbp)
1574		snprintf(ia->saddr, sizeof(ia->saddr), "%s/%d",
1575		    cbp, ia->prefix_len);
1576	else
1577		ia->saddr[0] = '\0';
1578
1579	TAILQ_INSERT_TAIL(&state->addrs, ia, next);
1580	return ia;
1581}
1582
1583void
1584ipv6_settempstale(struct interface *ifp)
1585{
1586	struct ipv6_state *state;
1587	struct ipv6_addr *ia;
1588
1589	state = IPV6_STATE(ifp);
1590	TAILQ_FOREACH(ia, &state->addrs, next) {
1591		if (ia->flags & IPV6_AF_TEMPORARY)
1592			ia->flags |= IPV6_AF_STALE;
1593	}
1594}
1595
1596struct ipv6_addr *
1597ipv6_settemptime(struct ipv6_addr *ia, int flags)
1598{
1599	struct ipv6_state *state;
1600	struct ipv6_addr *ap, *first;
1601
1602	state = IPV6_STATE(ia->iface);
1603	first = NULL;
1604	TAILQ_FOREACH_REVERSE(ap, &state->addrs, ipv6_addrhead, next) {
1605		if (ap->flags & IPV6_AF_TEMPORARY &&
1606		    ap->prefix_pltime &&
1607		    IN6_ARE_ADDR_EQUAL(&ia->prefix, &ap->prefix))
1608		{
1609			time_t max, ext;
1610
1611			if (flags == 0) {
1612				if (ap->prefix_pltime -
1613				    (uint32_t)(ia->acquired.tv_sec -
1614				    ap->acquired.tv_sec)
1615				    < REGEN_ADVANCE)
1616					continue;
1617
1618				return ap;
1619			}
1620
1621			if (!(ap->flags & IPV6_AF_ADDED))
1622				ap->flags |= IPV6_AF_NEW | IPV6_AF_AUTOCONF;
1623			ap->flags &= ~IPV6_AF_STALE;
1624
1625			/* RFC4941 Section 3.4
1626			 * Deprecated prefix, deprecate the temporary address */
1627			if (ia->prefix_pltime == 0) {
1628				ap->prefix_pltime = 0;
1629				goto valid;
1630			}
1631
1632			/* Ensure desync is still valid */
1633			ipv6_regen_desync(ap->iface, 0);
1634
1635			/* RFC4941 Section 3.3.2
1636			 * Extend temporary times, but ensure that they
1637			 * never last beyond the system limit. */
1638			ext = ia->acquired.tv_sec + (time_t)ia->prefix_pltime;
1639			max = ap->created.tv_sec +
1640			    ip6_temp_preferred_lifetime(ap->iface->name) -
1641			    state->desync_factor;
1642			if (ext < max)
1643				ap->prefix_pltime = ia->prefix_pltime;
1644			else
1645				ap->prefix_pltime =
1646				    (uint32_t)(max - ia->acquired.tv_sec);
1647
1648valid:
1649			ext = ia->acquired.tv_sec + (time_t)ia->prefix_vltime;
1650			max = ap->created.tv_sec +
1651			    ip6_temp_valid_lifetime(ap->iface->name);
1652			if (ext < max)
1653				ap->prefix_vltime = ia->prefix_vltime;
1654			else
1655				ap->prefix_vltime =
1656				    (uint32_t)(max - ia->acquired.tv_sec);
1657
1658			/* Just extend the latest matching prefix */
1659			ap->acquired = ia->acquired;
1660
1661			/* If extending return the last match as
1662			 * it's the most current.
1663			 * If deprecating, deprecate any other addresses we
1664			 * may have, although this should not be needed */
1665			if (ia->prefix_pltime)
1666				return ap;
1667			if (first == NULL)
1668				first = ap;
1669		}
1670	}
1671	return first;
1672}
1673
1674void
1675ipv6_addtempaddrs(struct interface *ifp, const struct timespec *now)
1676{
1677	struct ipv6_state *state;
1678	struct ipv6_addr *ia;
1679
1680	state = IPV6_STATE(ifp);
1681	TAILQ_FOREACH(ia, &state->addrs, next) {
1682		if (ia->flags & IPV6_AF_TEMPORARY &&
1683		    !(ia->flags & IPV6_AF_STALE))
1684			ipv6_addaddr(ia, now);
1685	}
1686}
1687
1688static void
1689ipv6_regentempaddr(void *arg)
1690{
1691	struct ipv6_addr *ia = arg, *ia1;
1692	struct timespec tv;
1693
1694	logger(ia->iface->ctx, LOG_DEBUG, "%s: regen temp addr %s",
1695	    ia->iface->name, ia->saddr);
1696	get_monotonic(&tv);
1697	ia1 = ipv6_createtempaddr(ia, &tv);
1698	if (ia1)
1699		ipv6_addaddr(ia1, &tv);
1700	else
1701		logger(ia->iface->ctx, LOG_ERR, "ipv6_createtempaddr: %m");
1702}
1703
1704static void
1705ipv6_regentempifid(void *arg)
1706{
1707	struct interface *ifp = arg;
1708	struct ipv6_state *state;
1709
1710	state = IPV6_STATE(ifp);
1711	if (memcmp(state->randomid, nullid, sizeof(state->randomid)))
1712		ipv6_gentempifid(ifp);
1713
1714	ipv6_regen_desync(ifp, 1);
1715}
1716#endif /* IPV6_MANAGETEMPADDR */
1717
1718static struct rt6 *
1719find_route6(struct rt6_head *rts, const struct rt6 *r)
1720{
1721	struct rt6 *rt;
1722
1723	TAILQ_FOREACH(rt, rts, next) {
1724		if (IN6_ARE_ADDR_EQUAL(&rt->dest, &r->dest) &&
1725#ifdef HAVE_ROUTE_METRIC
1726		    (r->iface == NULL || rt->iface == NULL ||
1727		    rt->iface->metric == r->iface->metric) &&
1728#endif
1729		    IN6_ARE_ADDR_EQUAL(&rt->net, &r->net))
1730			return rt;
1731	}
1732	return NULL;
1733}
1734
1735static void
1736desc_route(const char *cmd, const struct rt6 *rt)
1737{
1738	char destbuf[INET6_ADDRSTRLEN];
1739	char gatebuf[INET6_ADDRSTRLEN];
1740	const char *ifname, *dest, *gate;
1741	struct dhcpcd_ctx *ctx;
1742
1743	ctx = rt->iface ? rt->iface->ctx : NULL;
1744	ifname = rt->iface ? rt->iface->name : "(no iface)";
1745	dest = inet_ntop(AF_INET6, &rt->dest, destbuf, INET6_ADDRSTRLEN);
1746	gate = inet_ntop(AF_INET6, &rt->gate, gatebuf, INET6_ADDRSTRLEN);
1747	if (IN6_ARE_ADDR_EQUAL(&rt->gate, &in6addr_any))
1748		logger(ctx, LOG_INFO, "%s: %s route to %s/%d",
1749		    ifname, cmd, dest, ipv6_prefixlen(&rt->net));
1750	else if (IN6_ARE_ADDR_EQUAL(&rt->dest, &in6addr_any) &&
1751	    IN6_ARE_ADDR_EQUAL(&rt->net, &in6addr_any))
1752		logger(ctx, LOG_INFO, "%s: %s default route via %s",
1753		    ifname, cmd, gate);
1754	else
1755		logger(ctx, LOG_INFO, "%s: %s%s route to %s/%d via %s",
1756		    ifname, cmd,
1757		    rt->flags & RTF_REJECT ? " reject" : "",
1758		    dest, ipv6_prefixlen(&rt->net), gate);
1759}
1760
1761static struct rt6*
1762ipv6_findrt(struct dhcpcd_ctx *ctx, const struct rt6 *rt, int flags)
1763{
1764	struct rt6 *r;
1765
1766	TAILQ_FOREACH(r, &ctx->ipv6->kroutes, next) {
1767		if (IN6_ARE_ADDR_EQUAL(&rt->dest, &r->dest) &&
1768#ifdef HAVE_ROUTE_METRIC
1769		    (rt->iface == r->iface ||
1770		    (rt->flags & RTF_REJECT && r->flags & RTF_REJECT)) &&
1771		    (!flags || rt->metric == r->metric) &&
1772#else
1773		    (!flags || rt->iface == r->iface ||
1774		    (rt->flags & RTF_REJECT && r->flags & RTF_REJECT)) &&
1775#endif
1776		    IN6_ARE_ADDR_EQUAL(&rt->net, &r->net))
1777			return r;
1778	}
1779	return NULL;
1780}
1781
1782void
1783ipv6_freerts(struct rt6_head *routes)
1784{
1785	struct rt6 *rt;
1786
1787	while ((rt = TAILQ_FIRST(routes))) {
1788		TAILQ_REMOVE(routes, rt, next);
1789		free(rt);
1790	}
1791}
1792
1793/* If something other than dhcpcd removes a route,
1794 * we need to remove it from our internal table. */
1795int
1796ipv6_handlert(struct dhcpcd_ctx *ctx, int cmd, struct rt6 *rt)
1797{
1798	struct rt6 *f;
1799
1800	if (ctx->ipv6 == NULL)
1801		return 0;
1802
1803	f = ipv6_findrt(ctx, rt, 1);
1804	switch(cmd) {
1805	case RTM_ADD:
1806		if (f == NULL) {
1807			if ((f = malloc(sizeof(*f))) == NULL)
1808				return -1;
1809			*f = *rt;
1810			TAILQ_INSERT_TAIL(&ctx->ipv6->kroutes, f, next);
1811		}
1812		break;
1813	case RTM_DELETE:
1814		if (f) {
1815			TAILQ_REMOVE(&ctx->ipv6->kroutes, f, next);
1816			free(f);
1817		}
1818		/* If we manage the route, remove it */
1819		if ((f = find_route6(ctx->ipv6->routes, rt))) {
1820			desc_route("removing", f);
1821			TAILQ_REMOVE(ctx->ipv6->routes, f, next);
1822			free(f);
1823		}
1824		break;
1825	}
1826	return 0;
1827}
1828
1829#define n_route(a)	 nc_route(NULL, a)
1830#define c_route(a, b)	 nc_route(a, b)
1831static int
1832nc_route(struct rt6 *ort, struct rt6 *nrt)
1833{
1834
1835	/* Don't set default routes if not asked to */
1836	if (IN6_IS_ADDR_UNSPECIFIED(&nrt->dest) &&
1837	    IN6_IS_ADDR_UNSPECIFIED(&nrt->net) &&
1838	    !(nrt->iface->options->options & DHCPCD_GATEWAY))
1839		return -1;
1840
1841	desc_route(ort == NULL ? "adding" : "changing", nrt);
1842
1843	if (ort == NULL) {
1844		ort = ipv6_findrt(nrt->iface->ctx, nrt, 0);
1845		if (ort &&
1846		    ((ort->flags & RTF_REJECT && nrt->flags & RTF_REJECT) ||
1847		     (ort->iface == nrt->iface &&
1848#ifdef HAVE_ROUTE_METRIC
1849		    ort->metric == nrt->metric &&
1850#endif
1851		    IN6_ARE_ADDR_EQUAL(&ort->gate, &nrt->gate))))
1852			return 0;
1853	}
1854
1855#ifdef HAVE_ROUTE_METRIC
1856	/* With route metrics, we can safely add the new route before
1857	 * deleting the old route. */
1858	if (if_route6(RTM_ADD, nrt) == 0) {
1859		if (ort && if_route6(RTM_DELETE, ort) == -1 &&
1860		    errno != ESRCH)
1861			logger(nrt->iface->ctx, LOG_ERR, "if_route6 (DEL): %m");
1862		return 0;
1863	}
1864
1865	/* If the kernel claims the route exists we need to rip out the
1866	 * old one first. */
1867	if (errno != EEXIST || ort == NULL)
1868		goto logerr;
1869#endif
1870
1871	/* No route metrics, we need to delete the old route before
1872	 * adding the new one. */
1873	if (ort && if_route6(RTM_DELETE, ort) == -1 && errno != ESRCH)
1874		logger(nrt->iface->ctx, LOG_ERR, "if_route6: %m");
1875	if (if_route6(RTM_ADD, nrt) == 0)
1876		return 0;
1877#ifdef HAVE_ROUTE_METRIC
1878logerr:
1879#endif
1880	logger(nrt->iface->ctx, LOG_ERR, "if_route6 (ADD): %m");
1881	return -1;
1882}
1883
1884static int
1885d_route(struct rt6 *rt)
1886{
1887	int retval;
1888
1889	desc_route("deleting", rt);
1890	retval = if_route6(RTM_DELETE, rt);
1891	if (retval != 0 && errno != ENOENT && errno != ESRCH)
1892		logger(rt->iface->ctx, LOG_ERR,
1893		    "%s: if_delroute6: %m", rt->iface->name);
1894	return retval;
1895}
1896
1897static struct rt6 *
1898make_route(const struct interface *ifp, const struct ra *rap)
1899{
1900	struct rt6 *r;
1901
1902	r = calloc(1, sizeof(*r));
1903	if (r == NULL) {
1904		logger(ifp->ctx, LOG_ERR, "%s: %m", __func__);
1905		return NULL;
1906	}
1907	r->iface = ifp;
1908#ifdef HAVE_ROUTE_METRIC
1909	r->metric = ifp->metric;
1910#endif
1911	if (rap)
1912		r->mtu = rap->mtu;
1913	else
1914		r->mtu = 0;
1915	return r;
1916}
1917
1918static struct rt6 *
1919make_prefix(const struct interface *ifp, const struct ra *rap,
1920    const struct ipv6_addr *addr)
1921{
1922	struct rt6 *r;
1923
1924	if (addr == NULL || addr->prefix_len > 128) {
1925		errno = EINVAL;
1926		return NULL;
1927	}
1928
1929	/* There is no point in trying to manage a /128 prefix,
1930	 * ones without a lifetime or ones not on link or delegated */
1931	if (addr->prefix_len == 128 ||
1932	    addr->prefix_vltime == 0 ||
1933	    !(addr->flags & (IPV6_AF_ONLINK | IPV6_AF_DELEGATEDPFX)))
1934		return NULL;
1935
1936	/* Don't install a blackhole route when not creating bigger prefixes */
1937	if (addr->flags & IPV6_AF_DELEGATEDZERO)
1938		return NULL;
1939
1940	r = make_route(ifp, rap);
1941	if (r == NULL)
1942		return NULL;
1943	r->dest = addr->prefix;
1944	ipv6_mask(&r->net, addr->prefix_len);
1945	if (addr->flags & IPV6_AF_DELEGATEDPFX) {
1946		r->flags |= RTF_REJECT;
1947		r->gate = in6addr_loopback;
1948	} else
1949		r->gate = in6addr_any;
1950	return r;
1951}
1952
1953static struct rt6 *
1954make_router(const struct ra *rap)
1955{
1956	struct rt6 *r;
1957
1958	r = make_route(rap->iface, rap);
1959	if (r == NULL)
1960		return NULL;
1961	r->dest = in6addr_any;
1962	r->net = in6addr_any;
1963	r->gate = rap->from;
1964	return r;
1965}
1966
1967#define RT_IS_DEFAULT(rtp) \
1968	(IN6_ARE_ADDR_EQUAL(&((rtp)->dest), &in6addr_any) &&		      \
1969	    IN6_ARE_ADDR_EQUAL(&((rtp)->net), &in6addr_any))
1970
1971static void
1972ipv6_build_ra_routes(struct ipv6_ctx *ctx, struct rt6_head *dnr, int expired)
1973{
1974	struct rt6 *rt;
1975	struct ra *rap;
1976	const struct ipv6_addr *addr;
1977
1978	TAILQ_FOREACH(rap, ctx->ra_routers, next) {
1979		if (rap->expired != expired)
1980			continue;
1981		if (rap->iface->options->options & DHCPCD_IPV6RA_OWN) {
1982			TAILQ_FOREACH(addr, &rap->addrs, next) {
1983				rt = make_prefix(rap->iface, rap, addr);
1984				if (rt)
1985					TAILQ_INSERT_TAIL(dnr, rt, next);
1986			}
1987		}
1988		if (rap->lifetime && rap->iface->options->options &
1989		    (DHCPCD_IPV6RA_OWN | DHCPCD_IPV6RA_OWN_DEFAULT) &&
1990		    !rap->no_public_warned)
1991		{
1992			rt = make_router(rap);
1993			if (rt)
1994				TAILQ_INSERT_TAIL(dnr, rt, next);
1995		}
1996	}
1997}
1998
1999static void
2000ipv6_build_dhcp_routes(struct dhcpcd_ctx *ctx,
2001    struct rt6_head *dnr, enum DH6S dstate)
2002{
2003	const struct interface *ifp;
2004	const struct dhcp6_state *d6_state;
2005	const struct ipv6_addr *addr;
2006	struct rt6 *rt;
2007
2008	TAILQ_FOREACH(ifp, ctx->ifaces, next) {
2009		d6_state = D6_CSTATE(ifp);
2010		if (d6_state && d6_state->state == dstate) {
2011			TAILQ_FOREACH(addr, &d6_state->addrs, next) {
2012				rt = make_prefix(ifp, NULL, addr);
2013				if (rt)
2014					TAILQ_INSERT_TAIL(dnr, rt, next);
2015			}
2016		}
2017	}
2018}
2019
2020void
2021ipv6_buildroutes(struct dhcpcd_ctx *ctx)
2022{
2023#ifndef PASSIVE_MODE
2024	struct rt6_head dnr, *nrs;
2025	struct rt6 *rt, *rtn, *or;
2026	uint8_t have_default;
2027	unsigned long long o;
2028
2029	/* We need to have the interfaces in the correct order to ensure
2030	 * our routes are managed correctly. */
2031	if_sortinterfaces(ctx);
2032
2033	TAILQ_INIT(&dnr);
2034
2035	/* First add reachable routers and their prefixes */
2036	ipv6_build_ra_routes(ctx->ipv6, &dnr, 0);
2037#ifdef HAVE_ROUTE_METRIC
2038	have_default = (TAILQ_FIRST(&dnr) != NULL);
2039#endif
2040
2041	/* We have no way of knowing if prefixes added by DHCP are reachable
2042	 * or not, so we have to assume they are.
2043	 * Add bound before delegated so we can prefer interfaces better */
2044	ipv6_build_dhcp_routes(ctx, &dnr, DH6S_BOUND);
2045	ipv6_build_dhcp_routes(ctx, &dnr, DH6S_DELEGATED);
2046
2047#ifdef HAVE_ROUTE_METRIC
2048	/* If we have an unreachable router, we really do need to remove the
2049	 * route to it beause it could be a lower metric than a reachable
2050	 * router. Of course, we should at least have some routers if all
2051	 * are unreachable. */
2052	if (!have_default)
2053#endif
2054	/* Add our non-reachable routers and prefixes
2055	 * Unsure if this is needed, but it's a close match to kernel
2056	 * behaviour */
2057	ipv6_build_ra_routes(ctx->ipv6, &dnr, 1);
2058
2059	nrs = malloc(sizeof(*nrs));
2060	if (nrs == NULL) {
2061		logger(ctx, LOG_ERR, "%s: %m", __func__);
2062		return;
2063	}
2064	TAILQ_INIT(nrs);
2065	have_default = 0;
2066
2067	TAILQ_FOREACH_SAFE(rt, &dnr, next, rtn) {
2068		/* Is this route already in our table? */
2069		if (find_route6(nrs, rt) != NULL)
2070			continue;
2071		//rt->src.s_addr = ifp->addr.s_addr;
2072		/* Do we already manage it? */
2073		if ((or = find_route6(ctx->ipv6->routes, rt))) {
2074			if (or->iface != rt->iface ||
2075#ifdef HAVE_ROUTE_METRIC
2076			    rt->metric != or->metric ||
2077#endif
2078		//	    or->src.s_addr != ifp->addr.s_addr ||
2079			    !IN6_ARE_ADDR_EQUAL(&rt->gate, &or->gate))
2080			{
2081				if (c_route(or, rt) != 0)
2082					continue;
2083			}
2084			TAILQ_REMOVE(ctx->ipv6->routes, or, next);
2085			free(or);
2086		} else {
2087			if (n_route(rt) != 0)
2088				continue;
2089		}
2090		if (RT_IS_DEFAULT(rt))
2091			have_default = 1;
2092		TAILQ_REMOVE(&dnr, rt, next);
2093		TAILQ_INSERT_TAIL(nrs, rt, next);
2094	}
2095
2096	/* Free any routes we failed to add/change */
2097	while ((rt = TAILQ_FIRST(&dnr))) {
2098		TAILQ_REMOVE(&dnr, rt, next);
2099		free(rt);
2100	}
2101
2102	/* Remove old routes we used to manage
2103	 * If we own the default route, but not RA management itself
2104	 * then we need to preserve the last best default route we had */
2105	while ((rt = TAILQ_LAST(ctx->ipv6->routes, rt6_head))) {
2106		TAILQ_REMOVE(ctx->ipv6->routes, rt, next);
2107		if (find_route6(nrs, rt) == NULL) {
2108			o = rt->iface->options->options;
2109			if (!have_default &&
2110			    (o & DHCPCD_IPV6RA_OWN_DEFAULT) &&
2111			    !(o & DHCPCD_IPV6RA_OWN) &&
2112			    RT_IS_DEFAULT(rt))
2113				have_default = 1;
2114				/* no need to add it back to our routing table
2115				 * as we delete an exiting route when we add
2116				 * a new one */
2117			else if ((rt->iface->options->options &
2118				(DHCPCD_EXITING | DHCPCD_PERSISTENT)) !=
2119				(DHCPCD_EXITING | DHCPCD_PERSISTENT))
2120				d_route(rt);
2121		}
2122		free(rt);
2123	}
2124
2125	free(ctx->ipv6->routes);
2126	ctx->ipv6->routes = nrs;
2127#endif
2128}
2129