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