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