Update to dhcpcd-9.4.1 with the following changes:
[dragonfly.git] / contrib / dhcpcd / src / ipv6.c
1 /* SPDX-License-Identifier: BSD-2-Clause */
2 /*
3  * dhcpcd - DHCP client daemon
4  * Copyright (c) 2006-2021 Roy Marples <roy@marples.name>
5  * All rights reserved
6
7  * Redistribution and use in source and binary forms, with or without
8  * modification, are permitted provided that the following conditions
9  * are met:
10  * 1. Redistributions of source code must retain the above copyright
11  *    notice, this list of conditions and the following disclaimer.
12  * 2. Redistributions in binary form must reproduce the above copyright
13  *    notice, this list of conditions and the following disclaimer in the
14  *    documentation and/or other materials provided with the distribution.
15  *
16  * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND
17  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
18  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
19  * ARE DISCLAIMED.  IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
20  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
21  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
22  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
23  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
24  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
25  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
26  * SUCH DAMAGE.
27  */
28
29 #include <sys/param.h>
30 #include <sys/types.h>
31 #include <sys/socket.h>
32 #include <sys/stat.h>
33
34 #include <arpa/inet.h>
35 #include <net/if.h>
36 #include <net/route.h>
37 #include <netinet/in.h>
38 #include <netinet/if_ether.h>
39
40 #include "config.h"
41
42 #ifdef HAVE_SYS_BITOPS_H
43 #include <sys/bitops.h>
44 #else
45 #include "compat/bitops.h"
46 #endif
47
48 #ifdef BSD
49 /* Purely for the ND6_IFF_AUTO_LINKLOCAL #define which is solely used
50  * to generate our CAN_ADD_LLADDR #define. */
51 #  include <netinet6/in6_var.h>
52 #  include <netinet6/nd6.h>
53 #endif
54
55 #include <errno.h>
56 #include <ifaddrs.h>
57 #include <inttypes.h>
58 #include <stdlib.h>
59 #include <string.h>
60 #include <syslog.h>
61 #include <unistd.h>
62
63 #define ELOOP_QUEUE     ELOOP_IPV6
64 #include "common.h"
65 #include "if.h"
66 #include "dhcpcd.h"
67 #include "dhcp6.h"
68 #include "eloop.h"
69 #include "ipv6.h"
70 #include "ipv6nd.h"
71 #include "logerr.h"
72 #include "privsep.h"
73 #include "sa.h"
74 #include "script.h"
75
76 #ifdef HAVE_MD5_H
77 #  ifndef DEPGEN
78 #    include <md5.h>
79 #  endif
80 #endif
81
82 #ifdef SHA2_H
83 #  include SHA2_H
84 #endif
85
86 #ifndef SHA256_DIGEST_LENGTH
87 #  define SHA256_DIGEST_LENGTH          32
88 #endif
89
90 #ifdef IPV6_POLLADDRFLAG
91 #  warning kernel does not report IPv6 address flag changes
92 #  warning polling tentative address flags periodically
93 #endif
94
95 /* Hackery at it's finest. */
96 #ifndef s6_addr32
97 #  ifdef __sun
98 #    define s6_addr32   _S6_un._S6_u32
99 #  else
100 #    define s6_addr32   __u6_addr.__u6_addr32
101 #  endif
102 #endif
103
104 #if defined(HAVE_IN6_ADDR_GEN_MODE_NONE) || defined(ND6_IFF_AUTO_LINKLOCAL) || \
105     defined(IFF_NOLINKLOCAL)
106 /* Only add the LL address if we have a carrier, so DaD works. */
107 #define CAN_ADD_LLADDR(ifp) \
108     (!((ifp)->options->options & DHCPCD_LINK) || if_is_link_up((ifp)))
109 #ifdef __sun
110 /* Although we can add our own LL address, we cannot drop it
111  * without unplumbing the if which is a lot of code.
112  * So just keep it for the time being. */
113 #define CAN_DROP_LLADDR(ifp)    (0)
114 #else
115 #define CAN_DROP_LLADDR(ifp)    (1)
116 #endif
117 #else
118 /* We have no control over the OS adding the LLADDR, so just let it do it
119  * as we cannot force our own view on it. */
120 #define CAN_ADD_LLADDR(ifp)     (0)
121 #define CAN_DROP_LLADDR(ifp)    (0)
122 #endif
123
124 #ifdef IPV6_MANAGETEMPADDR
125 static void ipv6_regentempaddr(void *);
126 #endif
127
128 int
129 ipv6_init(struct dhcpcd_ctx *ctx)
130 {
131
132         if (ctx->ra_routers != NULL)
133                 return 0;
134
135         ctx->ra_routers = malloc(sizeof(*ctx->ra_routers));
136         if (ctx->ra_routers == NULL)
137                 return -1;
138         TAILQ_INIT(ctx->ra_routers);
139
140 #ifndef __sun
141         ctx->nd_fd = -1;
142 #endif
143 #ifdef DHCP6
144         ctx->dhcp6_rfd = -1;
145         ctx->dhcp6_wfd = -1;
146 #endif
147         return 0;
148 }
149
150 static ssize_t
151 ipv6_readsecret(struct dhcpcd_ctx *ctx)
152 {
153         char line[1024];
154         unsigned char *p;
155         size_t len;
156         uint32_t r;
157
158         ctx->secret_len = dhcp_read_hwaddr_aton(ctx, &ctx->secret, SECRET);
159         if (ctx->secret_len != 0)
160                 return (ssize_t)ctx->secret_len;
161
162         if (errno != ENOENT)
163                 logerr("%s: cannot read secret", __func__);
164
165         /* Chaining arc4random should be good enough.
166          * RFC7217 section 5.1 states the key SHOULD be at least 128 bits.
167          * To attempt and future proof ourselves, we'll generate a key of
168          * 512 bits (64 bytes). */
169         if (ctx->secret_len < 64) {
170                 if ((ctx->secret = malloc(64)) == NULL) {
171                         logerr(__func__);
172                         return -1;
173                 }
174                 ctx->secret_len = 64;
175         }
176         p = ctx->secret;
177         for (len = 0; len < 512 / NBBY; len += sizeof(r)) {
178                 r = arc4random();
179                 memcpy(p, &r, sizeof(r));
180                 p += sizeof(r);
181         }
182
183         hwaddr_ntoa(ctx->secret, ctx->secret_len, line, sizeof(line));
184         len = strlen(line);
185         if (len < sizeof(line) - 2) {
186                 line[len++] = '\n';
187                 line[len] = '\0';
188         }
189         if (dhcp_writefile(ctx, SECRET, S_IRUSR, line, len) == -1) {
190                 logerr("%s: cannot write secret", __func__);
191                 ctx->secret_len = 0;
192                 return -1;
193         }
194         return (ssize_t)ctx->secret_len;
195 }
196
197 /* http://www.iana.org/assignments/ipv6-interface-ids/ipv6-interface-ids.xhtml
198  * RFC5453 */
199 static const struct reslowhigh {
200         const uint8_t high[8];
201         const uint8_t low[8];
202 } reslowhigh[] = {
203         /* RFC4291 + RFC6543 */
204         { { 0x02, 0x00, 0x5e, 0xff, 0xfe, 0x00, 0x00, 0x00 },
205           { 0x02, 0x00, 0x5e, 0xff, 0xfe, 0xff, 0xff, 0xff } },
206         /* RFC2526 */
207         { { 0xfd, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0x80 },
208           { 0xfd, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff } }
209 };
210
211 static bool
212 ipv6_reserved(const struct in6_addr *addr)
213 {
214         uint64_t id, low, high;
215         size_t i;
216         const struct reslowhigh *r;
217
218         id = be64dec(addr->s6_addr + sizeof(id));
219         if (id == 0) /* RFC4291 */
220                 return 1;
221         for (i = 0; i < __arraycount(reslowhigh); i++) {
222                 r = &reslowhigh[i];
223                 low = be64dec(r->low);
224                 high = be64dec(r->high);
225                 if (id >= low && id <= high)
226                         return true;
227         }
228         return false;
229 }
230
231 /* RFC7217 */
232 static int
233 ipv6_makestableprivate1(struct dhcpcd_ctx *ctx,
234     struct in6_addr *addr, const struct in6_addr *prefix, int prefix_len,
235     const unsigned char *netiface, size_t netiface_len,
236     const unsigned char *netid, size_t netid_len,
237     unsigned short vlanid,
238     uint32_t *dad_counter)
239 {
240         unsigned char buf[2048], *p, digest[SHA256_DIGEST_LENGTH];
241         size_t len, l;
242         SHA256_CTX sha_ctx;
243
244         if (prefix_len < 0 || prefix_len > 120) {
245                 errno = EINVAL;
246                 return -1;
247         }
248
249         if (ctx->secret_len == 0) {
250                 if (ipv6_readsecret(ctx) == -1)
251                         return -1;
252         }
253
254         l = (size_t)(ROUNDUP8(prefix_len) / NBBY);
255         len = l + netiface_len + netid_len + sizeof(*dad_counter) +
256             ctx->secret_len;
257         if (vlanid != 0)
258                 len += sizeof(vlanid);
259         if (len > sizeof(buf)) {
260                 errno = ENOBUFS;
261                 return -1;
262         }
263
264         for (;; (*dad_counter)++) {
265                 /* Combine all parameters into one buffer */
266                 p = buf;
267                 memcpy(p, prefix, l);
268                 p += l;
269                 memcpy(p, netiface, netiface_len);
270                 p += netiface_len;
271                 memcpy(p, netid, netid_len);
272                 p += netid_len;
273                 /* Don't use a vlanid if not set.
274                  * This ensures prior versions have the same unique address. */
275                 if (vlanid != 0) {
276                         memcpy(p, &vlanid, sizeof(vlanid));
277                         p += sizeof(vlanid);
278                 }
279                 memcpy(p, dad_counter, sizeof(*dad_counter));
280                 p += sizeof(*dad_counter);
281                 memcpy(p, ctx->secret, ctx->secret_len);
282
283                 /* Make an address using the digest of the above.
284                  * RFC7217 Section 5.1 states that we shouldn't use MD5.
285                  * Pity as we use that for HMAC-MD5 which is still deemed OK.
286                  * SHA-256 is recommended */
287                 SHA256_Init(&sha_ctx);
288                 SHA256_Update(&sha_ctx, buf, len);
289                 SHA256_Final(digest, &sha_ctx);
290
291                 p = addr->s6_addr;
292                 memcpy(p, prefix, l);
293                 /* RFC7217 section 5.2 says we need to start taking the id from
294                  * the least significant bit */
295                 len = sizeof(addr->s6_addr) - l;
296                 memcpy(p + l, digest + (sizeof(digest) - len), len);
297
298                 /* Ensure that the Interface ID does not match a reserved one,
299                  * if it does then treat it as a DAD failure.
300                  * RFC7217 section 5.2 */
301                 if (prefix_len != 64)
302                         break;
303                 if (!ipv6_reserved(addr))
304                         break;
305         }
306
307         return 0;
308 }
309
310 int
311 ipv6_makestableprivate(struct in6_addr *addr,
312     const struct in6_addr *prefix, int prefix_len,
313     const struct interface *ifp,
314     int *dad_counter)
315 {
316         uint32_t dad;
317         int r;
318
319         dad = (uint32_t)*dad_counter;
320
321         /* For our implementation, we shall set the hardware address
322          * as the interface identifier */
323         r = ipv6_makestableprivate1(ifp->ctx, addr, prefix, prefix_len,
324             ifp->hwaddr, ifp->hwlen,
325             ifp->ssid, ifp->ssid_len,
326             ifp->vlanid, &dad);
327
328         if (r == 0)
329                 *dad_counter = (int)dad;
330         return r;
331 }
332
333 #ifdef IPV6_AF_TEMPORARY
334 static int
335 ipv6_maketemporaryaddress(struct in6_addr *addr,
336     const struct in6_addr *prefix, int prefix_len,
337     const struct interface *ifp)
338 {
339         struct in6_addr mask;
340         struct interface *ifpn;
341
342         if (ipv6_mask(&mask, prefix_len) == -1)
343                 return -1;
344         *addr = *prefix;
345
346 again:
347         addr->s6_addr32[2] |= (arc4random() & ~mask.s6_addr32[2]);
348         addr->s6_addr32[3] |= (arc4random() & ~mask.s6_addr32[3]);
349
350         TAILQ_FOREACH(ifpn, ifp->ctx->ifaces, next) {
351                 if (ipv6_iffindaddr(ifpn, addr, 0) != NULL)
352                         break;
353         }
354         if (ifpn != NULL)
355                 goto again;
356         if (ipv6_reserved(addr))
357                 goto again;
358         return 0;
359 }
360 #endif
361
362 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_MANAGER))
600                 ps_inet_closedhcp6(ia);
601 #elif defined(SMALL)
602         UNUSED(ia);
603 #else
604         /* NOREJECT is set if we delegated exactly the prefix to another
605          * address.
606          * This can only be one address, so just clear the flag.
607          * This should ensure the reject route will be restored. */
608         if (ia->delegating_prefix != NULL)
609                 ia->delegating_prefix->flags &= ~IPV6_AF_NOREJECT;
610 #endif
611 #else
612         UNUSED(ia);
613 #endif
614 }
615
616 void
617 ipv6_deleteaddr(struct ipv6_addr *ia)
618 {
619         struct ipv6_state *state;
620         struct ipv6_addr *ap;
621
622         loginfox("%s: deleting address %s", ia->iface->name, ia->saddr);
623         if (if_address6(RTM_DELADDR, ia) == -1 &&
624             errno != EADDRNOTAVAIL && errno != ESRCH &&
625             errno != ENXIO && errno != ENODEV)
626                 logerr(__func__);
627
628         ipv6_deletedaddr(ia);
629
630         state = IPV6_STATE(ia->iface);
631         TAILQ_FOREACH(ap, &state->addrs, next) {
632                 if (IN6_ARE_ADDR_EQUAL(&ap->addr, &ia->addr)) {
633                         TAILQ_REMOVE(&state->addrs, ap, next);
634                         ipv6_freeaddr(ap);
635                         break;
636                 }
637         }
638
639 #ifdef ND6_ADVERTISE
640         /* Advertise the address if it exists on another interface. */
641         ipv6nd_advertise(ia);
642 #endif
643 }
644
645 static int
646 ipv6_addaddr1(struct ipv6_addr *ia, const struct timespec *now)
647 {
648         struct interface *ifp;
649         uint32_t pltime, vltime;
650         int loglevel;
651 #ifdef ND6_ADVERTISE
652         bool vltime_was_zero = ia->prefix_vltime == 0;
653 #endif
654 #ifdef __sun
655         struct ipv6_state *state;
656         struct ipv6_addr *ia2;
657
658         /* If we re-add then address on Solaris then the prefix
659          * route will be scrubbed and re-added. Something might
660          * be using it, so let's avoid it. */
661         if (ia->flags & IPV6_AF_DADCOMPLETED) {
662                 logdebugx("%s: IP address %s already exists",
663                     ia->iface->name, ia->saddr);
664 #ifdef ND6_ADVERTISE
665                 goto advertise;
666 #else
667                 return 0;
668 #endif
669         }
670 #endif
671
672         /* Remember the interface of the address. */
673         ifp = ia->iface;
674
675         if (!(ia->flags & IPV6_AF_DADCOMPLETED) &&
676             ipv6_iffindaddr(ifp, &ia->addr, IN6_IFF_NOTUSEABLE))
677                 ia->flags |= IPV6_AF_DADCOMPLETED;
678
679         /* Adjust plftime and vltime based on acquired time */
680         pltime = ia->prefix_pltime;
681         vltime = ia->prefix_vltime;
682
683         if (ifp->options->options & DHCPCD_LASTLEASE_EXTEND) {
684                 /* We don't want the kernel to expire the address.
685                  * The saved times will be re-applied to the ia
686                  * before exiting this function. */
687                 ia->prefix_vltime = ia->prefix_pltime = ND6_INFINITE_LIFETIME;
688         }
689
690         if (timespecisset(&ia->acquired) &&
691             (ia->prefix_pltime != ND6_INFINITE_LIFETIME ||
692             ia->prefix_vltime != ND6_INFINITE_LIFETIME))
693         {
694                 uint32_t elapsed;
695                 struct timespec n;
696
697                 if (now == NULL) {
698                         clock_gettime(CLOCK_MONOTONIC, &n);
699                         now = &n;
700                 }
701                 elapsed = (uint32_t)eloop_timespec_diff(now, &ia->acquired,
702                     NULL);
703                 if (ia->prefix_pltime != ND6_INFINITE_LIFETIME) {
704                         if (elapsed > ia->prefix_pltime)
705                                 ia->prefix_pltime = 0;
706                         else
707                                 ia->prefix_pltime -= elapsed;
708                 }
709                 if (ia->prefix_vltime != ND6_INFINITE_LIFETIME) {
710                         if (elapsed > ia->prefix_vltime)
711                                 ia->prefix_vltime = 0;
712                         else
713                                 ia->prefix_vltime -= elapsed;
714                 }
715         }
716
717         loglevel = ia->flags & IPV6_AF_NEW ? LOG_INFO : LOG_DEBUG;
718         logmessage(loglevel, "%s: adding %saddress %s", ifp->name,
719 #ifdef IPV6_AF_TEMPORARY
720             ia->flags & IPV6_AF_TEMPORARY ? "temporary " : "",
721 #else
722             "",
723 #endif
724             ia->saddr);
725         if (ia->prefix_pltime == ND6_INFINITE_LIFETIME &&
726             ia->prefix_vltime == ND6_INFINITE_LIFETIME)
727                 logdebugx("%s: pltime infinity, vltime infinity",
728                     ifp->name);
729         else if (ia->prefix_pltime == ND6_INFINITE_LIFETIME)
730                 logdebugx("%s: pltime infinity, vltime %"PRIu32" seconds",
731                     ifp->name, ia->prefix_vltime);
732         else if (ia->prefix_vltime == ND6_INFINITE_LIFETIME)
733                 logdebugx("%s: pltime %"PRIu32"seconds, vltime infinity",
734                     ifp->name, ia->prefix_pltime);
735         else
736                 logdebugx("%s: pltime %"PRIu32" seconds, vltime %"PRIu32
737                     " seconds",
738                     ifp->name, ia->prefix_pltime, ia->prefix_vltime);
739
740         if (if_address6(RTM_NEWADDR, ia) == -1) {
741                 logerr(__func__);
742                 /* Restore real pltime and vltime */
743                 ia->prefix_pltime = pltime;
744                 ia->prefix_vltime = vltime;
745                 return -1;
746         }
747
748 #ifdef IPV6_MANAGETEMPADDR
749         /* RFC4941 Section 3.4 */
750         if (ia->flags & IPV6_AF_TEMPORARY &&
751             ia->prefix_pltime &&
752             ia->prefix_vltime &&
753             ifp->options->options & DHCPCD_SLAACTEMP)
754                 eloop_timeout_add_sec(ifp->ctx->eloop,
755                     ia->prefix_pltime - REGEN_ADVANCE,
756                     ipv6_regentempaddr, ia);
757 #endif
758
759         /* Restore real pltime and vltime */
760         ia->prefix_pltime = pltime;
761         ia->prefix_vltime = vltime;
762
763         ia->flags &= ~IPV6_AF_NEW;
764         ia->flags |= IPV6_AF_ADDED;
765 #ifndef SMALL
766         if (ia->delegating_prefix != NULL)
767                 ia->flags |= IPV6_AF_DELEGATED;
768 #endif
769
770 #ifdef IPV6_POLLADDRFLAG
771         eloop_timeout_delete(ifp->ctx->eloop,
772                 ipv6_checkaddrflags, ia);
773         if (!(ia->flags & IPV6_AF_DADCOMPLETED)) {
774                 eloop_timeout_add_msec(ifp->ctx->eloop,
775                     RETRANS_TIMER / 2, ipv6_checkaddrflags, ia);
776         }
777 #endif
778
779 #ifdef __sun
780         /* Solaris does not announce new addresses which need DaD
781          * so we need to take a copy and add it to our list.
782          * Otherwise aliasing gets confused if we add another
783          * address during DaD. */
784
785         state = IPV6_STATE(ifp);
786         TAILQ_FOREACH(ia2, &state->addrs, next) {
787                 if (IN6_ARE_ADDR_EQUAL(&ia2->addr, &ia->addr))
788                         break;
789         }
790         if (ia2 == NULL) {
791                 if ((ia2 = malloc(sizeof(*ia2))) == NULL) {
792                         logerr(__func__);
793                         return 0; /* Well, we did add the address */
794                 }
795                 memcpy(ia2, ia, sizeof(*ia2));
796                 TAILQ_INSERT_TAIL(&state->addrs, ia2, next);
797         }
798 #endif
799
800 #ifdef ND6_ADVERTISE
801 #ifdef __sun
802 advertise:
803 #endif
804         /* Re-advertise the preferred address to be safe. */
805         if (!vltime_was_zero)
806                 ipv6nd_advertise(ia);
807 #endif
808
809         return 0;
810 }
811
812 #ifdef ALIAS_ADDR
813 /* Find the next logical alias address we can use. */
814 static int
815 ipv6_aliasaddr(struct ipv6_addr *ia, struct ipv6_addr **repl)
816 {
817         struct ipv6_state *state;
818         struct ipv6_addr *iap;
819         unsigned int lun;
820         char alias[IF_NAMESIZE];
821
822         if (ia->alias[0] != '\0')
823                 return 0;
824         state = IPV6_STATE(ia->iface);
825
826         /* First find an existng address.
827          * This can happen when dhcpcd restarts as ND and DHCPv6
828          * maintain their own lists of addresses. */
829         TAILQ_FOREACH(iap, &state->addrs, next) {
830                 if (iap->alias[0] != '\0' &&
831                     IN6_ARE_ADDR_EQUAL(&iap->addr, &ia->addr))
832                 {
833                         strlcpy(ia->alias, iap->alias, sizeof(ia->alias));
834                         return 0;
835                 }
836         }
837
838         lun = 0;
839 find_unit:
840         if (if_makealias(alias, IF_NAMESIZE, ia->iface->name, lun) >=
841             IF_NAMESIZE)
842         {
843                 errno = ENOMEM;
844                 return -1;
845         }
846         TAILQ_FOREACH(iap, &state->addrs, next) {
847                 if (iap->alias[0] == '\0')
848                         continue;
849                 if (IN6_IS_ADDR_UNSPECIFIED(&iap->addr)) {
850                         /* No address assigned? Lets use it. */
851                         strlcpy(ia->alias, iap->alias, sizeof(ia->alias));
852                         if (repl)
853                                 *repl = iap;
854                         return 1;
855                 }
856                 if (strcmp(iap->alias, alias) == 0)
857                         break;
858         }
859
860         if (iap != NULL) {
861                 if (lun == UINT_MAX) {
862                         errno = ERANGE;
863                         return -1;
864                 }
865                 lun++;
866                 goto find_unit;
867         }
868
869         strlcpy(ia->alias, alias, sizeof(ia->alias));
870         return 0;
871 }
872 #endif
873
874 int
875 ipv6_addaddr(struct ipv6_addr *ia, const struct timespec *now)
876 {
877         int r;
878 #ifdef ALIAS_ADDR
879         int replaced, blank;
880         struct ipv6_addr *replaced_ia;
881
882         blank = (ia->alias[0] == '\0');
883         if ((replaced = ipv6_aliasaddr(ia, &replaced_ia)) == -1)
884                 return -1;
885         if (blank)
886                 logdebugx("%s: aliased %s", ia->alias, ia->saddr);
887 #endif
888
889         if ((r = ipv6_addaddr1(ia, now)) == 0) {
890 #ifdef ALIAS_ADDR
891                 if (replaced) {
892                         struct ipv6_state *state;
893
894                         state = IPV6_STATE(ia->iface);
895                         TAILQ_REMOVE(&state->addrs, replaced_ia, next);
896                         ipv6_freeaddr(replaced_ia);
897                 }
898 #endif
899         }
900         return r;
901 }
902
903 int
904 ipv6_findaddrmatch(const struct ipv6_addr *addr, const struct in6_addr *match,
905     unsigned int flags)
906 {
907
908         if (match == NULL) {
909                 if ((addr->flags &
910                     (IPV6_AF_ADDED | IPV6_AF_DADCOMPLETED)) ==
911                     (IPV6_AF_ADDED | IPV6_AF_DADCOMPLETED))
912                         return 1;
913         } else if (addr->prefix_vltime &&
914             IN6_ARE_ADDR_EQUAL(&addr->addr, match) &&
915             (!flags || addr->flags & flags))
916                 return 1;
917
918         return 0;
919 }
920
921 struct ipv6_addr *
922 ipv6_findaddr(struct dhcpcd_ctx *ctx, const struct in6_addr *addr, unsigned int flags)
923 {
924         struct ipv6_addr *nap;
925 #ifdef DHCP6
926         struct ipv6_addr *dap;
927 #endif
928
929         nap = ipv6nd_findaddr(ctx, addr, flags);
930 #ifdef DHCP6
931         dap = dhcp6_findaddr(ctx, addr, flags);
932         if (!dap && !nap)
933                 return NULL;
934         if (dap && !nap)
935                 return dap;
936         if (nap && !dap)
937                 return nap;
938         if (nap->iface->metric < dap->iface->metric)
939                 return nap;
940         return dap;
941 #else
942         return nap;
943 #endif
944 }
945
946 int
947 ipv6_doaddr(struct ipv6_addr *ia, struct timespec *now)
948 {
949
950         /* A delegated prefix is not an address. */
951         if (ia->flags & IPV6_AF_DELEGATEDPFX)
952                 return 0;
953
954         if (ia->prefix_vltime == 0) {
955                 if (ia->flags & IPV6_AF_ADDED)
956                         ipv6_deleteaddr(ia);
957                 eloop_q_timeout_delete(ia->iface->ctx->eloop,
958                     ELOOP_QUEUE_ALL, NULL, ia);
959                 if (ia->flags & IPV6_AF_REQUEST) {
960                         ia->flags &= ~IPV6_AF_ADDED;
961                         return 0;
962                 }
963                 return -1;
964         }
965
966         if (ia->flags & IPV6_AF_STALE ||
967             IN6_IS_ADDR_UNSPECIFIED(&ia->addr))
968                 return 0;
969
970         if (!timespecisset(now))
971                 clock_gettime(CLOCK_MONOTONIC, now);
972         ipv6_addaddr(ia, now);
973         return ia->flags & IPV6_AF_NEW ? 1 : 0;
974 }
975
976 ssize_t
977 ipv6_addaddrs(struct ipv6_addrhead *iaddrs)
978 {
979         struct timespec now;
980         struct ipv6_addr *ia, *ian;
981         ssize_t i, r;
982
983         i = 0;
984         timespecclear(&now);
985         TAILQ_FOREACH_SAFE(ia, iaddrs, next, ian) {
986                 r = ipv6_doaddr(ia, &now);
987                 if (r != 0)
988                         i++;
989                 if (r == -1) {
990                         TAILQ_REMOVE(iaddrs, ia, next);
991                         ipv6_freeaddr(ia);
992                 }
993         }
994         return i;
995 }
996
997 void
998 ipv6_freeaddr(struct ipv6_addr *ia)
999 {
1000         struct eloop *eloop = ia->iface->ctx->eloop;
1001 #ifndef SMALL
1002         struct ipv6_addr *iad;
1003
1004         /* Forget the reference */
1005         if (ia->flags & IPV6_AF_DELEGATEDPFX) {
1006                 TAILQ_FOREACH(iad, &ia->pd_pfxs, pd_next) {
1007                         iad->delegating_prefix = NULL;
1008                 }
1009         } else if (ia->delegating_prefix != NULL) {
1010                 TAILQ_REMOVE(&ia->delegating_prefix->pd_pfxs, ia, pd_next);
1011         }
1012 #endif
1013
1014         if (ia->dhcp6_fd != -1) {
1015                 close(ia->dhcp6_fd);
1016                 eloop_event_delete(eloop, ia->dhcp6_fd);
1017         }
1018
1019         eloop_q_timeout_delete(eloop, ELOOP_QUEUE_ALL, NULL, ia);
1020         free(ia->na);
1021         free(ia);
1022 }
1023
1024 void
1025 ipv6_freedrop_addrs(struct ipv6_addrhead *addrs, int drop,
1026     const struct interface *ifd)
1027 {
1028         struct ipv6_addr *ap, *apn, *apf;
1029         struct timespec now;
1030
1031 #ifdef SMALL
1032         UNUSED(ifd);
1033 #endif
1034         timespecclear(&now);
1035         TAILQ_FOREACH_SAFE(ap, addrs, next, apn) {
1036 #ifndef SMALL
1037                 if (ifd != NULL &&
1038                     (ap->delegating_prefix == NULL ||
1039                     ap->delegating_prefix->iface != ifd))
1040                         continue;
1041 #endif
1042                 if (drop != 2)
1043                         TAILQ_REMOVE(addrs, ap, next);
1044                 if (drop && ap->flags & IPV6_AF_ADDED &&
1045                     (ap->iface->options->options &
1046                     (DHCPCD_EXITING | DHCPCD_PERSISTENT)) !=
1047                     (DHCPCD_EXITING | DHCPCD_PERSISTENT))
1048                 {
1049                         /* Don't drop link-local addresses. */
1050                         if (!IN6_IS_ADDR_LINKLOCAL(&ap->addr) ||
1051                             CAN_DROP_LLADDR(ap->iface))
1052                         {
1053                                 if (drop == 2)
1054                                         TAILQ_REMOVE(addrs, ap, next);
1055                                 /* Find the same address somewhere else */
1056                                 apf = ipv6_findaddr(ap->iface->ctx, &ap->addr,
1057                                     0);
1058                                 if ((apf == NULL ||
1059                                     (apf->iface != ap->iface)))
1060                                         ipv6_deleteaddr(ap);
1061                                 if (!(ap->iface->options->options &
1062                                     DHCPCD_EXITING) && apf)
1063                                 {
1064                                         if (!timespecisset(&now))
1065                                                 clock_gettime(CLOCK_MONOTONIC,
1066                                                     &now);
1067                                         ipv6_addaddr(apf, &now);
1068                                 }
1069                                 if (drop == 2)
1070                                         ipv6_freeaddr(ap);
1071                         }
1072                 }
1073                 if (drop != 2)
1074                         ipv6_freeaddr(ap);
1075         }
1076 }
1077
1078 static struct ipv6_state *
1079 ipv6_getstate(struct interface *ifp)
1080 {
1081         struct ipv6_state *state;
1082
1083         state = IPV6_STATE(ifp);
1084         if (state == NULL) {
1085                 ifp->if_data[IF_DATA_IPV6] = calloc(1, sizeof(*state));
1086                 state = IPV6_STATE(ifp);
1087                 if (state == NULL) {
1088                         logerr(__func__);
1089                         return NULL;
1090                 }
1091                 TAILQ_INIT(&state->addrs);
1092                 TAILQ_INIT(&state->ll_callbacks);
1093         }
1094         return state;
1095 }
1096
1097 struct ipv6_addr *
1098 ipv6_anyglobal(struct interface *sifp)
1099 {
1100         struct interface *ifp;
1101         struct ipv6_state *state;
1102         struct ipv6_addr *ia;
1103         bool forwarding;
1104
1105         /* BSD forwarding is either on or off.
1106          * Linux forwarding is technically the same as it's
1107          * configured by the "all" interface.
1108          * Per interface only affects IsRouter of NA messages. */
1109 #if defined(PRIVSEP) && (defined(HAVE_PLEDGE) || defined(__linux__))
1110         if (IN_PRIVSEP(sifp->ctx))
1111                 forwarding = ps_root_ip6forwarding(sifp->ctx, NULL) != 0;
1112         else
1113 #endif
1114                 forwarding = ip6_forwarding(NULL) != 0;
1115
1116         TAILQ_FOREACH(ifp, sifp->ctx->ifaces, next) {
1117                 if (ifp != sifp && !forwarding)
1118                         continue;
1119
1120                 state = IPV6_STATE(ifp);
1121                 if (state == NULL)
1122                         continue;
1123
1124                 TAILQ_FOREACH(ia, &state->addrs, next) {
1125                         if (IN6_IS_ADDR_LINKLOCAL(&ia->addr))
1126                                 continue;
1127                         /* Let's be optimistic.
1128                          * Any decent OS won't forward or accept traffic
1129                          * from/to tentative or detached addresses. */
1130                         if (!(ia->addr_flags & IN6_IFF_DUPLICATED))
1131                                 return ia;
1132                 }
1133         }
1134         return NULL;
1135 }
1136
1137 void
1138 ipv6_handleifa(struct dhcpcd_ctx *ctx,
1139     int cmd, struct if_head *ifs, const char *ifname,
1140     const struct in6_addr *addr, uint8_t prefix_len, int addrflags, pid_t pid)
1141 {
1142         struct interface *ifp;
1143         struct ipv6_state *state;
1144         struct ipv6_addr *ia;
1145         struct ll_callback *cb;
1146         bool anyglobal;
1147
1148 #ifdef __sun
1149         struct sockaddr_in6 subnet;
1150
1151         /* Solaris on-link route is an unspecified address! */
1152         if (IN6_IS_ADDR_UNSPECIFIED(addr)) {
1153                 if (if_getsubnet(ctx, ifname, AF_INET6,
1154                     &subnet, sizeof(subnet)) == -1)
1155                 {
1156                         logerr(__func__);
1157                         return;
1158                 }
1159                 addr = &subnet.sin6_addr;
1160         }
1161 #endif
1162
1163 #if 0
1164         char dbuf[INET6_ADDRSTRLEN];
1165         const char *dbp;
1166
1167         dbp = inet_ntop(AF_INET6, &addr->s6_addr,
1168             dbuf, INET6_ADDRSTRLEN);
1169         loginfox("%s: cmd %d addr %s addrflags %d",
1170             ifname, cmd, dbp, addrflags);
1171 #endif
1172
1173         if (ifs == NULL)
1174                 ifs = ctx->ifaces;
1175         if (ifs == NULL)
1176                 return;
1177         if ((ifp = if_find(ifs, ifname)) == NULL)
1178                 return;
1179         if ((state = ipv6_getstate(ifp)) == NULL)
1180                 return;
1181         anyglobal = ipv6_anyglobal(ifp) != NULL;
1182
1183         TAILQ_FOREACH(ia, &state->addrs, next) {
1184                 if (IN6_ARE_ADDR_EQUAL(&ia->addr, addr))
1185                         break;
1186         }
1187
1188         switch (cmd) {
1189         case RTM_DELADDR:
1190                 if (ia != NULL) {
1191                         TAILQ_REMOVE(&state->addrs, ia, next);
1192 #ifdef ND6_ADVERTISE
1193                         /* Advertise the address if it exists on
1194                          * another interface. */
1195                         ipv6nd_advertise(ia);
1196 #endif
1197                         /* We'll free it at the end of the function. */
1198                 }
1199                 break;
1200         case RTM_NEWADDR:
1201                 if (ia == NULL) {
1202                         ia = ipv6_newaddr(ifp, addr, prefix_len, 0);
1203 #ifdef ALIAS_ADDR
1204                         strlcpy(ia->alias, ifname, sizeof(ia->alias));
1205 #endif
1206                         if (if_getlifetime6(ia) == -1) {
1207                                 /* No support or address vanished.
1208                                  * Either way, just set a deprecated
1209                                  * infinite time lifetime and continue.
1210                                  * This is fine because we only want
1211                                  * to know this when trying to extend
1212                                  * temporary addresses.
1213                                  * As we can't extend infinite, we'll
1214                                  * create a new temporary address. */
1215                                 ia->prefix_pltime = 0;
1216                                 ia->prefix_vltime =
1217                                     ND6_INFINITE_LIFETIME;
1218                         }
1219                         /* This is a minor regression against RFC 4941
1220                          * because the kernel only knows when the
1221                          * lifetimes were last updated, not when the
1222                          * address was initially created.
1223                          * Provided dhcpcd is not restarted, this
1224                          * won't be a problem.
1225                          * If we don't like it, we can always
1226                          * pretend lifetimes are infinite and always
1227                          * generate a new temporary address on
1228                          * restart. */
1229                         ia->acquired = ia->created;
1230                         TAILQ_INSERT_TAIL(&state->addrs, ia, next);
1231                 }
1232                 ia->addr_flags = addrflags;
1233                 ia->flags &= ~IPV6_AF_STALE;
1234 #ifdef IPV6_MANAGETEMPADDR
1235                 if (ia->addr_flags & IN6_IFF_TEMPORARY)
1236                         ia->flags |= IPV6_AF_TEMPORARY;
1237 #endif
1238                 if (IN6_IS_ADDR_LINKLOCAL(&ia->addr) || ia->dadcallback) {
1239 #ifdef IPV6_POLLADDRFLAG
1240                         if (ia->addr_flags & IN6_IFF_TENTATIVE) {
1241                                 eloop_timeout_add_msec(
1242                                     ia->iface->ctx->eloop,
1243                                     RETRANS_TIMER / 2, ipv6_checkaddrflags, ia);
1244                                 break;
1245                         }
1246 #endif
1247
1248                         if (ia->dadcallback)
1249                                 ia->dadcallback(ia);
1250
1251                         if (IN6_IS_ADDR_LINKLOCAL(&ia->addr) &&
1252                             !(ia->addr_flags & IN6_IFF_NOTUSEABLE))
1253                         {
1254                                 /* Now run any callbacks.
1255                                  * Typically IPv6RS or DHCPv6 */
1256                                 while ((cb =
1257                                     TAILQ_FIRST(&state->ll_callbacks)))
1258                                 {
1259                                         TAILQ_REMOVE(
1260                                             &state->ll_callbacks,
1261                                             cb, next);
1262                                         cb->callback(cb->arg);
1263                                         free(cb);
1264                                 }
1265                         }
1266                 }
1267                 break;
1268         }
1269
1270         if (ia == NULL)
1271                 return;
1272
1273         ctx->options &= ~DHCPCD_RTBUILD;
1274         ipv6nd_handleifa(cmd, ia, pid);
1275 #ifdef DHCP6
1276         dhcp6_handleifa(cmd, ia, pid);
1277 #endif
1278
1279         /* Done with the ia now, so free it. */
1280         if (cmd == RTM_DELADDR)
1281                 ipv6_freeaddr(ia);
1282         else if (!(ia->addr_flags & IN6_IFF_NOTUSEABLE))
1283                 ia->flags |= IPV6_AF_DADCOMPLETED;
1284
1285         /* If we've not already called rt_build via the IPv6ND
1286          * or DHCP6 handlers and the existance of any useable
1287          * global address on the interface has changed,
1288          * call rt_build to add/remove the default route. */
1289         if (ifp->active &&
1290             ((ifp->options != NULL && ifp->options->options & DHCPCD_IPV6) ||
1291              (ifp->options == NULL && ctx->options & DHCPCD_IPV6)) &&
1292             !(ctx->options & DHCPCD_RTBUILD) &&
1293             (ipv6_anyglobal(ifp) != NULL) != anyglobal)
1294                 rt_build(ctx, AF_INET6);
1295 }
1296
1297 int
1298 ipv6_hasaddr(const struct interface *ifp)
1299 {
1300
1301         if (ipv6nd_iffindaddr(ifp, NULL, 0) != NULL)
1302                 return 1;
1303 #ifdef DHCP6
1304         if (dhcp6_iffindaddr(ifp, NULL, 0) != NULL)
1305                 return 1;
1306 #endif
1307         return 0;
1308 }
1309
1310 struct ipv6_addr *
1311 ipv6_iffindaddr(struct interface *ifp, const struct in6_addr *addr,
1312     int revflags)
1313 {
1314         struct ipv6_state *state;
1315         struct ipv6_addr *ap;
1316
1317         state = IPV6_STATE(ifp);
1318         if (state) {
1319                 TAILQ_FOREACH(ap, &state->addrs, next) {
1320                         if (addr == NULL) {
1321                                 if (IN6_IS_ADDR_LINKLOCAL(&ap->addr) &&
1322                                     (!revflags || !(ap->addr_flags & revflags)))
1323                                         return ap;
1324                         } else {
1325                                 if (IN6_ARE_ADDR_EQUAL(&ap->addr, addr) &&
1326                                     (!revflags || !(ap->addr_flags & revflags)))
1327                                         return ap;
1328                         }
1329                 }
1330         }
1331         return NULL;
1332 }
1333
1334 static struct ipv6_addr *
1335 ipv6_iffindmaskaddr(const struct interface *ifp, const struct in6_addr *addr)
1336 {
1337         struct ipv6_state *state;
1338         struct ipv6_addr *ap;
1339         struct in6_addr mask;
1340
1341         state = IPV6_STATE(ifp);
1342         if (state) {
1343                 TAILQ_FOREACH(ap, &state->addrs, next) {
1344                         if (ipv6_mask(&mask, ap->prefix_len) == -1)
1345                                 continue;
1346                         if (IN6_ARE_MASKED_ADDR_EQUAL(&ap->addr, addr, &mask))
1347                                 return ap;
1348                 }
1349         }
1350         return NULL;
1351 }
1352
1353 struct ipv6_addr *
1354 ipv6_findmaskaddr(struct dhcpcd_ctx *ctx, const struct in6_addr *addr)
1355 {
1356         struct interface *ifp;
1357         struct ipv6_addr *ap;
1358
1359         TAILQ_FOREACH(ifp, ctx->ifaces, next) {
1360                 ap = ipv6_iffindmaskaddr(ifp, addr);
1361                 if (ap != NULL)
1362                         return ap;
1363         }
1364         return NULL;
1365 }
1366
1367 int
1368 ipv6_addlinklocalcallback(struct interface *ifp,
1369     void (*callback)(void *), void *arg)
1370 {
1371         struct ipv6_state *state;
1372         struct ll_callback *cb;
1373
1374         state = ipv6_getstate(ifp);
1375         TAILQ_FOREACH(cb, &state->ll_callbacks, next) {
1376                 if (cb->callback == callback && cb->arg == arg)
1377                         break;
1378         }
1379         if (cb == NULL) {
1380                 cb = malloc(sizeof(*cb));
1381                 if (cb == NULL) {
1382                         logerr(__func__);
1383                         return -1;
1384                 }
1385                 cb->callback = callback;
1386                 cb->arg = arg;
1387                 TAILQ_INSERT_TAIL(&state->ll_callbacks, cb, next);
1388         }
1389         return 0;
1390 }
1391
1392 static struct ipv6_addr *
1393 ipv6_newlinklocal(struct interface *ifp)
1394 {
1395         struct ipv6_addr *ia;
1396         struct in6_addr in6;
1397
1398         memset(&in6, 0, sizeof(in6));
1399         in6.s6_addr32[0] = htonl(0xfe800000);
1400         ia = ipv6_newaddr(ifp, &in6, 64, 0);
1401         if (ia != NULL) {
1402                 ia->prefix_pltime = ND6_INFINITE_LIFETIME;
1403                 ia->prefix_vltime = ND6_INFINITE_LIFETIME;
1404         }
1405         return ia;
1406 }
1407
1408 static const uint8_t allzero[8] = { 0, 0, 0, 0, 0, 0, 0, 0 };
1409 static const uint8_t allone[8] =
1410     { 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff };
1411
1412 static int
1413 ipv6_addlinklocal(struct interface *ifp)
1414 {
1415         struct ipv6_state *state;
1416         struct ipv6_addr *ap, *ap2;
1417         int dadcounter;
1418
1419         if (!(ifp->options->options & DHCPCD_CONFIGURE))
1420                 return 0;
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_ADDED &&
2134                     !(ia->flags & IPV6_AF_STALE))
2135                         ia->flags |= IPV6_AF_REGEN;
2136                 else
2137                         ia->flags &= ~IPV6_AF_REGEN;
2138         }
2139
2140         /* Now regen temp addrs */
2141         TAILQ_FOREACH(ia, &state->addrs, next) {
2142                 if (ia->flags & IPV6_AF_REGEN) {
2143                         ipv6_regentempaddr0(ia, &tv);
2144                         ia->flags &= ~IPV6_AF_REGEN;
2145                 }
2146         }
2147 }
2148 #endif /* IPV6_MANAGETEMPADDR */
2149
2150 void
2151 ipv6_markaddrsstale(struct interface *ifp, unsigned int flags)
2152 {
2153         struct ipv6_state *state;
2154         struct ipv6_addr *ia;
2155
2156         state = IPV6_STATE(ifp);
2157         if (state == NULL)
2158                 return;
2159
2160         TAILQ_FOREACH(ia, &state->addrs, next) {
2161                 if (flags == 0 || ia->flags & flags)
2162                         ia->flags |= IPV6_AF_STALE;
2163         }
2164 }
2165
2166 void
2167 ipv6_deletestaleaddrs(struct interface *ifp)
2168 {
2169         struct ipv6_state *state;
2170         struct ipv6_addr *ia, *ia1;
2171
2172         state = IPV6_STATE(ifp);
2173         if (state == NULL)
2174                 return;
2175
2176         TAILQ_FOREACH_SAFE(ia, &state->addrs, next, ia1) {
2177                 if (ia->flags & IPV6_AF_STALE)
2178                         ipv6_handleifa(ifp->ctx, RTM_DELADDR,
2179                             ifp->ctx->ifaces, ifp->name,
2180                             &ia->addr, ia->prefix_len, 0, getpid());
2181         }
2182 }
2183
2184
2185 static struct rt *
2186 inet6_makeroute(struct interface *ifp, const struct ra *rap)
2187 {
2188         struct rt *rt;
2189
2190         if ((rt = rt_new(ifp)) == NULL)
2191                 return NULL;
2192
2193 #ifdef HAVE_ROUTE_METRIC
2194         rt->rt_metric = ifp->metric;
2195 #endif
2196         if (rap != NULL)
2197                 rt->rt_mtu = rap->mtu;
2198         return rt;
2199 }
2200
2201 static struct rt *
2202 inet6_makeprefix(struct interface *ifp, const struct ra *rap,
2203     const struct ipv6_addr *addr)
2204 {
2205         struct rt *rt;
2206         struct in6_addr netmask;
2207
2208         if (addr == NULL || addr->prefix_len > 128) {
2209                 errno = EINVAL;
2210                 return NULL;
2211         }
2212
2213         /* There is no point in trying to manage a /128 prefix,
2214          * ones without a lifetime.  */
2215         if (addr->prefix_len == 128 || addr->prefix_vltime == 0)
2216                 return NULL;
2217
2218         /* Don't install a reject route when not creating bigger prefixes. */
2219         if (addr->flags & IPV6_AF_NOREJECT)
2220                 return NULL;
2221
2222         /* This address is the delegated prefix, so add a reject route for
2223          * it via the loopback interface. */
2224         if (addr->flags & IPV6_AF_DELEGATEDPFX) {
2225                 struct interface *lo0;
2226
2227                 TAILQ_FOREACH(lo0, ifp->ctx->ifaces, next) {
2228                         if (lo0->flags & IFF_LOOPBACK)
2229                                 break;
2230                 }
2231                 if (lo0 == NULL)
2232                         logwarnx("cannot find a loopback interface "
2233                             "to reject via");
2234                 else
2235                         ifp = lo0;
2236         }
2237
2238         if ((rt = inet6_makeroute(ifp, rap)) == NULL)
2239                 return NULL;
2240
2241         sa_in6_init(&rt->rt_dest, &addr->prefix);
2242         ipv6_mask(&netmask, addr->prefix_len);
2243         sa_in6_init(&rt->rt_netmask, &netmask);
2244         if (addr->flags & IPV6_AF_DELEGATEDPFX) {
2245                 rt->rt_flags |= RTF_REJECT;
2246                 /* Linux does not like a gateway for a reject route. */
2247 #ifndef __linux__
2248                 sa_in6_init(&rt->rt_gateway, &in6addr_loopback);
2249 #endif
2250         } else if (!(addr->flags & IPV6_AF_ONLINK))
2251                 sa_in6_init(&rt->rt_gateway, &rap->from);
2252         else
2253                 rt->rt_gateway.sa_family = AF_UNSPEC;
2254         sa_in6_init(&rt->rt_ifa, &addr->addr);
2255         return rt;
2256 }
2257
2258 static struct rt *
2259 inet6_makerouter(struct ra *rap)
2260 {
2261         struct rt *rt;
2262
2263         if ((rt = inet6_makeroute(rap->iface, rap)) == NULL)
2264                 return NULL;
2265         sa_in6_init(&rt->rt_dest, &in6addr_any);
2266         sa_in6_init(&rt->rt_netmask, &in6addr_any);
2267         sa_in6_init(&rt->rt_gateway, &rap->from);
2268         return rt;
2269 }
2270
2271 #define RT_IS_DEFAULT(rtp) \
2272         (IN6_ARE_ADDR_EQUAL(&((rtp)->dest), &in6addr_any) &&                  \
2273             IN6_ARE_ADDR_EQUAL(&((rtp)->mask), &in6addr_any))
2274
2275 static int
2276 inet6_staticroutes(rb_tree_t *routes, struct dhcpcd_ctx *ctx)
2277 {
2278         struct interface *ifp;
2279         struct ipv6_state *state;
2280         struct ipv6_addr *ia;
2281         struct rt *rt;
2282
2283         TAILQ_FOREACH(ifp, ctx->ifaces, next) {
2284                 if ((state = IPV6_STATE(ifp)) == NULL)
2285                         continue;
2286                 TAILQ_FOREACH(ia, &state->addrs, next) {
2287                         if ((ia->flags & (IPV6_AF_ADDED | IPV6_AF_STATIC)) ==
2288                             (IPV6_AF_ADDED | IPV6_AF_STATIC))
2289                         {
2290                                 rt = inet6_makeprefix(ifp, NULL, ia);
2291                                 if (rt)
2292                                         rt_proto_add(routes, rt);
2293                         }
2294                 }
2295         }
2296         return 0;
2297 }
2298
2299 static int
2300 inet6_raroutes(rb_tree_t *routes, struct dhcpcd_ctx *ctx)
2301 {
2302         struct rt *rt;
2303         struct ra *rap;
2304         const struct ipv6_addr *addr;
2305
2306         if (ctx->ra_routers == NULL)
2307                 return 0;
2308
2309         TAILQ_FOREACH(rap, ctx->ra_routers, next) {
2310                 if (rap->expired)
2311                         continue;
2312                 TAILQ_FOREACH(addr, &rap->addrs, next) {
2313                         if (addr->prefix_vltime == 0)
2314                                 continue;
2315                         rt = inet6_makeprefix(rap->iface, rap, addr);
2316                         if (rt) {
2317                                 rt->rt_dflags |= RTDF_RA;
2318 #ifdef HAVE_ROUTE_PREF
2319                                 rt->rt_pref = ipv6nd_rtpref(rap);
2320 #endif
2321                                 rt_proto_add(routes, rt);
2322                         }
2323                 }
2324                 if (rap->lifetime == 0)
2325                         continue;
2326                 if (ipv6_anyglobal(rap->iface) == NULL)
2327                         continue;
2328                 rt = inet6_makerouter(rap);
2329                 if (rt == NULL)
2330                         continue;
2331                 rt->rt_dflags |= RTDF_RA;
2332 #ifdef HAVE_ROUTE_PREF
2333                 rt->rt_pref = ipv6nd_rtpref(rap);
2334 #endif
2335                 rt_proto_add(routes, rt);
2336         }
2337         return 0;
2338 }
2339
2340 #ifdef DHCP6
2341 static int
2342 inet6_dhcproutes(rb_tree_t *routes, struct dhcpcd_ctx *ctx,
2343     enum DH6S dstate)
2344 {
2345         struct interface *ifp;
2346         const struct dhcp6_state *d6_state;
2347         const struct ipv6_addr *addr;
2348         struct rt *rt;
2349
2350         TAILQ_FOREACH(ifp, ctx->ifaces, next) {
2351                 d6_state = D6_CSTATE(ifp);
2352                 if (d6_state && d6_state->state == dstate) {
2353                         TAILQ_FOREACH(addr, &d6_state->addrs, next) {
2354                                 rt = inet6_makeprefix(ifp, NULL, addr);
2355                                 if (rt == NULL)
2356                                         continue;
2357                                 rt->rt_dflags |= RTDF_DHCP;
2358                                 rt_proto_add(routes, rt);
2359                         }
2360                 }
2361         }
2362         return 0;
2363 }
2364 #endif
2365
2366 bool
2367 inet6_getroutes(struct dhcpcd_ctx *ctx, rb_tree_t *routes)
2368 {
2369
2370         /* Should static take priority? */
2371         if (inet6_staticroutes(routes, ctx) == -1)
2372                 return false;
2373
2374         /* First add reachable routers and their prefixes */
2375         if (inet6_raroutes(routes, ctx) == -1)
2376                 return false;
2377
2378 #ifdef DHCP6
2379         /* We have no way of knowing if prefixes added by DHCP are reachable
2380          * or not, so we have to assume they are.
2381          * Add bound before delegated so we can prefer interfaces better. */
2382         if (inet6_dhcproutes(routes, ctx, DH6S_BOUND) == -1)
2383                 return false;
2384         if (inet6_dhcproutes(routes, ctx, DH6S_DELEGATED) == -1)
2385                 return false;
2386 #endif
2387
2388         return true;
2389 }