]> CyberLeo.Net >> Repos - FreeBSD/FreeBSD.git/blob - sys/netinet6/nd6_rtr.c
Update OpenZFS to 2.0.0-rc3-gfc5966
[FreeBSD/FreeBSD.git] / sys / netinet6 / nd6_rtr.c
1 /*-
2  * SPDX-License-Identifier: BSD-3-Clause
3  *
4  * Copyright (C) 1995, 1996, 1997, and 1998 WIDE Project.
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  * 3. Neither the name of the project nor the names of its contributors
16  *    may be used to endorse or promote products derived from this software
17  *    without specific prior written permission.
18  *
19  * THIS SOFTWARE IS PROVIDED BY THE PROJECT AND CONTRIBUTORS ``AS IS'' AND
20  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
21  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
22  * ARE DISCLAIMED.  IN NO EVENT SHALL THE PROJECT OR CONTRIBUTORS BE LIABLE
23  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
24  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
25  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
26  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
27  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
28  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
29  * SUCH DAMAGE.
30  *
31  *      $KAME: nd6_rtr.c,v 1.111 2001/04/27 01:37:15 jinmei Exp $
32  */
33
34 #include <sys/cdefs.h>
35 __FBSDID("$FreeBSD$");
36
37 #include "opt_inet.h"
38 #include "opt_inet6.h"
39
40 #include <sys/param.h>
41 #include <sys/systm.h>
42 #include <sys/malloc.h>
43 #include <sys/mbuf.h>
44 #include <sys/refcount.h>
45 #include <sys/socket.h>
46 #include <sys/sockio.h>
47 #include <sys/time.h>
48 #include <sys/kernel.h>
49 #include <sys/lock.h>
50 #include <sys/errno.h>
51 #include <sys/rmlock.h>
52 #include <sys/rwlock.h>
53 #include <sys/sysctl.h>
54 #include <sys/syslog.h>
55 #include <sys/queue.h>
56
57 #include <net/if.h>
58 #include <net/if_var.h>
59 #include <net/if_types.h>
60 #include <net/if_dl.h>
61 #include <net/route.h>
62 #include <net/route/nhop.h>
63 #include <net/route/route_ctl.h>
64 #include <net/route/route_var.h>
65 #include <net/radix.h>
66 #include <net/vnet.h>
67
68 #include <netinet/in.h>
69 #include <net/if_llatbl.h>
70 #include <netinet6/in6_var.h>
71 #include <netinet6/in6_ifattach.h>
72 #include <netinet/ip6.h>
73 #include <netinet6/ip6_var.h>
74 #include <netinet6/nd6.h>
75 #include <netinet/icmp6.h>
76 #include <netinet6/scope6_var.h>
77
78 static struct nd_defrouter *defrtrlist_update(struct nd_defrouter *);
79 static int prelist_update(struct nd_prefixctl *, struct nd_defrouter *,
80     struct mbuf *, int);
81 static int nd6_prefix_onlink(struct nd_prefix *);
82
83 TAILQ_HEAD(nd6_drhead, nd_defrouter);
84 VNET_DEFINE_STATIC(struct nd6_drhead, nd6_defrouter);
85 #define V_nd6_defrouter                 VNET(nd6_defrouter)
86
87 VNET_DECLARE(int, nd6_recalc_reachtm_interval);
88 #define V_nd6_recalc_reachtm_interval   VNET(nd6_recalc_reachtm_interval)
89
90 VNET_DEFINE_STATIC(struct ifnet *, nd6_defifp);
91 VNET_DEFINE(int, nd6_defifindex);
92 #define V_nd6_defifp                    VNET(nd6_defifp)
93
94 VNET_DEFINE(int, ip6_use_tempaddr) = 0;
95
96 VNET_DEFINE(int, ip6_desync_factor);
97 VNET_DEFINE(u_int32_t, ip6_temp_preferred_lifetime) = DEF_TEMP_PREFERRED_LIFETIME;
98 VNET_DEFINE(u_int32_t, ip6_temp_valid_lifetime) = DEF_TEMP_VALID_LIFETIME;
99
100 VNET_DEFINE(int, ip6_temp_regen_advance) = TEMPADDR_REGEN_ADVANCE;
101
102 #ifdef EXPERIMENTAL
103 VNET_DEFINE(int, nd6_ignore_ipv6_only_ra) = 1;
104 #endif
105
106 SYSCTL_DECL(_net_inet6_icmp6);
107
108 /* RTPREF_MEDIUM has to be 0! */
109 #define RTPREF_HIGH     1
110 #define RTPREF_MEDIUM   0
111 #define RTPREF_LOW      (-1)
112 #define RTPREF_RESERVED (-2)
113 #define RTPREF_INVALID  (-3)    /* internal */
114
115 static void
116 defrouter_ref(struct nd_defrouter *dr)
117 {
118
119         refcount_acquire(&dr->refcnt);
120 }
121
122 void
123 defrouter_rele(struct nd_defrouter *dr)
124 {
125
126         if (refcount_release(&dr->refcnt))
127                 free(dr, M_IP6NDP);
128 }
129
130 /*
131  * Remove a router from the global list and optionally stash it in a
132  * caller-supplied queue.
133  */
134 static void
135 defrouter_unlink(struct nd_defrouter *dr, struct nd6_drhead *drq)
136 {
137
138         ND6_WLOCK_ASSERT();
139
140         TAILQ_REMOVE(&V_nd6_defrouter, dr, dr_entry);
141         V_nd6_list_genid++;
142         if (drq != NULL)
143                 TAILQ_INSERT_TAIL(drq, dr, dr_entry);
144 }
145
146 /*
147  * Receive Router Solicitation Message - just for routers.
148  * Router solicitation/advertisement is mostly managed by userland program
149  * (rtadvd) so here we have no function like nd6_ra_output().
150  *
151  * Based on RFC 2461
152  */
153 void
154 nd6_rs_input(struct mbuf *m, int off, int icmp6len)
155 {
156         struct ifnet *ifp;
157         struct ip6_hdr *ip6;
158         struct nd_router_solicit *nd_rs;
159         struct in6_addr saddr6;
160         union nd_opts ndopts;
161         char ip6bufs[INET6_ADDRSTRLEN], ip6bufd[INET6_ADDRSTRLEN];
162         char *lladdr;
163         int lladdrlen;
164
165         ifp = m->m_pkthdr.rcvif;
166
167         /*
168          * Accept RS only when V_ip6_forwarding=1 and the interface has
169          * no ND6_IFF_ACCEPT_RTADV.
170          */
171         if (!V_ip6_forwarding || ND_IFINFO(ifp)->flags & ND6_IFF_ACCEPT_RTADV)
172                 goto freeit;
173
174         /* RFC 6980: Nodes MUST silently ignore fragments */   
175         if(m->m_flags & M_FRAGMENTED)
176                 goto freeit;
177
178         /* Sanity checks */
179         ip6 = mtod(m, struct ip6_hdr *);
180         if (ip6->ip6_hlim != 255) {
181                 nd6log((LOG_ERR,
182                     "%s: invalid hlim (%d) from %s to %s on %s\n", __func__,
183                     ip6->ip6_hlim, ip6_sprintf(ip6bufs, &ip6->ip6_src),
184                     ip6_sprintf(ip6bufd, &ip6->ip6_dst), if_name(ifp)));
185                 goto bad;
186         }
187
188         /*
189          * Don't update the neighbor cache, if src = ::.
190          * This indicates that the src has no IP address assigned yet.
191          */
192         saddr6 = ip6->ip6_src;
193         if (IN6_IS_ADDR_UNSPECIFIED(&saddr6))
194                 goto freeit;
195
196         if (m->m_len < off + icmp6len) {
197                 m = m_pullup(m, off + icmp6len);
198                 if (m == NULL) {
199                         IP6STAT_INC(ip6s_exthdrtoolong);
200                         return;
201                 }
202         }
203         ip6 = mtod(m, struct ip6_hdr *);
204         nd_rs = (struct nd_router_solicit *)((caddr_t)ip6 + off);
205
206         icmp6len -= sizeof(*nd_rs);
207         nd6_option_init(nd_rs + 1, icmp6len, &ndopts);
208         if (nd6_options(&ndopts) < 0) {
209                 nd6log((LOG_INFO,
210                     "%s: invalid ND option, ignored\n", __func__));
211                 /* nd6_options have incremented stats */
212                 goto freeit;
213         }
214
215         lladdr = NULL;
216         lladdrlen = 0;
217         if (ndopts.nd_opts_src_lladdr) {
218                 lladdr = (char *)(ndopts.nd_opts_src_lladdr + 1);
219                 lladdrlen = ndopts.nd_opts_src_lladdr->nd_opt_len << 3;
220         }
221
222         if (lladdr && ((ifp->if_addrlen + 2 + 7) & ~7) != lladdrlen) {
223                 nd6log((LOG_INFO,
224                     "%s: lladdrlen mismatch for %s (if %d, RS packet %d)\n",
225                     __func__, ip6_sprintf(ip6bufs, &saddr6),
226                     ifp->if_addrlen, lladdrlen - 2));
227                 goto bad;
228         }
229
230         nd6_cache_lladdr(ifp, &saddr6, lladdr, lladdrlen, ND_ROUTER_SOLICIT, 0);
231
232  freeit:
233         m_freem(m);
234         return;
235
236  bad:
237         ICMP6STAT_INC(icp6s_badrs);
238         m_freem(m);
239 }
240
241 #ifdef EXPERIMENTAL
242 /*
243  * An initial update routine for draft-ietf-6man-ipv6only-flag.
244  * We need to iterate over all default routers for the given
245  * interface to see whether they are all advertising the "S"
246  * (IPv6-Only) flag.  If they do set, otherwise unset, the
247  * interface flag we later use to filter on.
248  */
249 static void
250 defrtr_ipv6_only_ifp(struct ifnet *ifp)
251 {
252         struct nd_defrouter *dr;
253         bool ipv6_only, ipv6_only_old;
254 #ifdef INET
255         struct epoch_tracker et;
256         struct ifaddr *ifa;
257         bool has_ipv4_addr;
258 #endif
259
260         if (V_nd6_ignore_ipv6_only_ra != 0)
261                 return;
262
263         ipv6_only = true;
264         ND6_RLOCK();
265         TAILQ_FOREACH(dr, &V_nd6_defrouter, dr_entry)
266                 if (dr->ifp == ifp &&
267                     (dr->raflags & ND_RA_FLAG_IPV6_ONLY) == 0)
268                         ipv6_only = false;
269         ND6_RUNLOCK();
270
271         IF_AFDATA_WLOCK(ifp);
272         ipv6_only_old = ND_IFINFO(ifp)->flags & ND6_IFF_IPV6_ONLY;
273         IF_AFDATA_WUNLOCK(ifp);
274
275         /* If nothing changed, we have an early exit. */
276         if (ipv6_only == ipv6_only_old)
277                 return;
278
279 #ifdef INET
280         /*
281          * Should we want to set the IPV6-ONLY flag, check if the
282          * interface has a non-0/0 and non-link-local IPv4 address
283          * configured on it.  If it has we will assume working
284          * IPv4 operations and will clear the interface flag.
285          */
286         has_ipv4_addr = false;
287         if (ipv6_only) {
288                 NET_EPOCH_ENTER(et);
289                 CK_STAILQ_FOREACH(ifa, &ifp->if_addrhead, ifa_link) {
290                         if (ifa->ifa_addr->sa_family != AF_INET)
291                                 continue;
292                         if (in_canforward(
293                             satosin(ifa->ifa_addr)->sin_addr)) {
294                                 has_ipv4_addr = true;
295                                 break;
296                         }
297                 }
298                 NET_EPOCH_EXIT(et);
299         }
300         if (ipv6_only && has_ipv4_addr) {
301                 log(LOG_NOTICE, "%s rcvd RA w/ IPv6-Only flag set but has IPv4 "
302                     "configured, ignoring IPv6-Only flag.\n", ifp->if_xname);
303                 ipv6_only = false;
304         }
305 #endif
306
307         IF_AFDATA_WLOCK(ifp);
308         if (ipv6_only)
309                 ND_IFINFO(ifp)->flags |= ND6_IFF_IPV6_ONLY;
310         else
311                 ND_IFINFO(ifp)->flags &= ~ND6_IFF_IPV6_ONLY;
312         IF_AFDATA_WUNLOCK(ifp);
313
314 #ifdef notyet
315         /* Send notification of flag change. */
316 #endif
317 }
318
319 static void
320 defrtr_ipv6_only_ipf_down(struct ifnet *ifp)
321 {
322
323         IF_AFDATA_WLOCK(ifp);
324         ND_IFINFO(ifp)->flags &= ~ND6_IFF_IPV6_ONLY;
325         IF_AFDATA_WUNLOCK(ifp);
326 }
327 #endif  /* EXPERIMENTAL */
328
329 void
330 nd6_ifnet_link_event(void *arg __unused, struct ifnet *ifp, int linkstate)
331 {
332
333         /*
334          * XXX-BZ we might want to trigger re-evaluation of our default router
335          * availability. E.g., on link down the default router might be
336          * unreachable but a different interface might still have connectivity.
337          */
338
339 #ifdef EXPERIMENTAL
340         if (linkstate == LINK_STATE_DOWN)
341                 defrtr_ipv6_only_ipf_down(ifp);
342 #endif
343 }
344
345 /*
346  * Receive Router Advertisement Message.
347  *
348  * Based on RFC 2461
349  * TODO: on-link bit on prefix information
350  * TODO: ND_RA_FLAG_{OTHER,MANAGED} processing
351  */
352 void
353 nd6_ra_input(struct mbuf *m, int off, int icmp6len)
354 {
355         struct ifnet *ifp;
356         struct nd_ifinfo *ndi;
357         struct ip6_hdr *ip6;
358         struct nd_router_advert *nd_ra;
359         struct in6_addr saddr6;
360         struct nd_defrouter *dr;
361         union nd_opts ndopts;
362         char ip6bufs[INET6_ADDRSTRLEN], ip6bufd[INET6_ADDRSTRLEN];
363         int mcast;
364
365         /*
366          * We only accept RAs only when the per-interface flag
367          * ND6_IFF_ACCEPT_RTADV is on the receiving interface.
368          */
369         ifp = m->m_pkthdr.rcvif;
370         ndi = ND_IFINFO(ifp);
371         if (!(ndi->flags & ND6_IFF_ACCEPT_RTADV))
372                 goto freeit;
373
374         /* RFC 6980: Nodes MUST silently ignore fragments */
375         if(m->m_flags & M_FRAGMENTED)
376                 goto freeit;
377
378         ip6 = mtod(m, struct ip6_hdr *);
379         if (ip6->ip6_hlim != 255) {
380                 nd6log((LOG_ERR,
381                     "%s: invalid hlim (%d) from %s to %s on %s\n", __func__,
382                     ip6->ip6_hlim, ip6_sprintf(ip6bufs, &ip6->ip6_src),
383                     ip6_sprintf(ip6bufd, &ip6->ip6_dst), if_name(ifp)));
384                 goto bad;
385         }
386
387         saddr6 = ip6->ip6_src;
388         if (!IN6_IS_ADDR_LINKLOCAL(&saddr6)) {
389                 nd6log((LOG_ERR,
390                     "%s: src %s is not link-local\n", __func__,
391                     ip6_sprintf(ip6bufs, &saddr6)));
392                 goto bad;
393         }
394
395         if (m->m_len < off + icmp6len) {
396                 m = m_pullup(m, off + icmp6len);
397                 if (m == NULL) {
398                         IP6STAT_INC(ip6s_exthdrtoolong);
399                         return;
400                 }
401         }
402         ip6 = mtod(m, struct ip6_hdr *);
403         nd_ra = (struct nd_router_advert *)((caddr_t)ip6 + off);
404
405         icmp6len -= sizeof(*nd_ra);
406         nd6_option_init(nd_ra + 1, icmp6len, &ndopts);
407         if (nd6_options(&ndopts) < 0) {
408                 nd6log((LOG_INFO,
409                     "%s: invalid ND option, ignored\n", __func__));
410                 /* nd6_options have incremented stats */
411                 goto freeit;
412         }
413
414         mcast = 0;
415         dr = NULL;
416     {
417         struct nd_defrouter dr0;
418         u_int32_t advreachable = nd_ra->nd_ra_reachable;
419
420         /* remember if this is a multicasted advertisement */
421         if (IN6_IS_ADDR_MULTICAST(&ip6->ip6_dst))
422                 mcast = 1;
423
424         bzero(&dr0, sizeof(dr0));
425         dr0.rtaddr = saddr6;
426         dr0.raflags = nd_ra->nd_ra_flags_reserved;
427         /*
428          * Effectively-disable routes from RA messages when
429          * ND6_IFF_NO_RADR enabled on the receiving interface or
430          * (ip6.forwarding == 1 && ip6.rfc6204w3 != 1).
431          */
432         if (ndi->flags & ND6_IFF_NO_RADR)
433                 dr0.rtlifetime = 0;
434         else if (V_ip6_forwarding && !V_ip6_rfc6204w3)
435                 dr0.rtlifetime = 0;
436         else
437                 dr0.rtlifetime = ntohs(nd_ra->nd_ra_router_lifetime);
438         dr0.expire = time_uptime + dr0.rtlifetime;
439         dr0.ifp = ifp;
440         /* unspecified or not? (RFC 2461 6.3.4) */
441         if (advreachable) {
442                 advreachable = ntohl(advreachable);
443                 if (advreachable <= MAX_REACHABLE_TIME &&
444                     ndi->basereachable != advreachable) {
445                         ndi->basereachable = advreachable;
446                         ndi->reachable = ND_COMPUTE_RTIME(ndi->basereachable);
447                         ndi->recalctm = V_nd6_recalc_reachtm_interval; /* reset */
448                 }
449         }
450         if (nd_ra->nd_ra_retransmit)
451                 ndi->retrans = ntohl(nd_ra->nd_ra_retransmit);
452         if (nd_ra->nd_ra_curhoplimit) {
453                 if (ndi->chlim < nd_ra->nd_ra_curhoplimit)
454                         ndi->chlim = nd_ra->nd_ra_curhoplimit;
455                 else if (ndi->chlim != nd_ra->nd_ra_curhoplimit) {
456                         log(LOG_ERR, "RA with a lower CurHopLimit sent from "
457                             "%s on %s (current = %d, received = %d). "
458                             "Ignored.\n", ip6_sprintf(ip6bufs, &ip6->ip6_src),
459                             if_name(ifp), ndi->chlim, nd_ra->nd_ra_curhoplimit);
460                 }
461         }
462         dr = defrtrlist_update(&dr0);
463 #ifdef EXPERIMENTAL
464         defrtr_ipv6_only_ifp(ifp);
465 #endif
466     }
467
468         /*
469          * prefix
470          */
471         if (ndopts.nd_opts_pi) {
472                 struct nd_opt_hdr *pt;
473                 struct nd_opt_prefix_info *pi = NULL;
474                 struct nd_prefixctl pr;
475
476                 for (pt = (struct nd_opt_hdr *)ndopts.nd_opts_pi;
477                      pt <= (struct nd_opt_hdr *)ndopts.nd_opts_pi_end;
478                      pt = (struct nd_opt_hdr *)((caddr_t)pt +
479                                                 (pt->nd_opt_len << 3))) {
480                         if (pt->nd_opt_type != ND_OPT_PREFIX_INFORMATION)
481                                 continue;
482                         pi = (struct nd_opt_prefix_info *)pt;
483
484                         if (pi->nd_opt_pi_len != 4) {
485                                 nd6log((LOG_INFO,
486                                     "%s: invalid option len %d for prefix "
487                                     "information option, ignored\n", __func__,
488                                     pi->nd_opt_pi_len));
489                                 continue;
490                         }
491
492                         if (128 < pi->nd_opt_pi_prefix_len) {
493                                 nd6log((LOG_INFO,
494                                     "%s: invalid prefix len %d for prefix "
495                                     "information option, ignored\n", __func__,
496                                     pi->nd_opt_pi_prefix_len));
497                                 continue;
498                         }
499
500                         if (IN6_IS_ADDR_MULTICAST(&pi->nd_opt_pi_prefix)
501                          || IN6_IS_ADDR_LINKLOCAL(&pi->nd_opt_pi_prefix)) {
502                                 nd6log((LOG_INFO,
503                                     "%s: invalid prefix %s, ignored\n",
504                                     __func__, ip6_sprintf(ip6bufs,
505                                         &pi->nd_opt_pi_prefix)));
506                                 continue;
507                         }
508
509                         bzero(&pr, sizeof(pr));
510                         pr.ndpr_prefix.sin6_family = AF_INET6;
511                         pr.ndpr_prefix.sin6_len = sizeof(pr.ndpr_prefix);
512                         pr.ndpr_prefix.sin6_addr = pi->nd_opt_pi_prefix;
513                         pr.ndpr_ifp = (struct ifnet *)m->m_pkthdr.rcvif;
514
515                         pr.ndpr_raf_onlink = (pi->nd_opt_pi_flags_reserved &
516                             ND_OPT_PI_FLAG_ONLINK) ? 1 : 0;
517                         pr.ndpr_raf_auto = (pi->nd_opt_pi_flags_reserved &
518                             ND_OPT_PI_FLAG_AUTO) ? 1 : 0;
519                         pr.ndpr_plen = pi->nd_opt_pi_prefix_len;
520                         pr.ndpr_vltime = ntohl(pi->nd_opt_pi_valid_time);
521                         pr.ndpr_pltime = ntohl(pi->nd_opt_pi_preferred_time);
522                         (void)prelist_update(&pr, dr, m, mcast);
523                 }
524         }
525         if (dr != NULL) {
526                 defrouter_rele(dr);
527                 dr = NULL;
528         }
529
530         /*
531          * MTU
532          */
533         if (ndopts.nd_opts_mtu && ndopts.nd_opts_mtu->nd_opt_mtu_len == 1) {
534                 u_long mtu;
535                 u_long maxmtu;
536
537                 mtu = (u_long)ntohl(ndopts.nd_opts_mtu->nd_opt_mtu_mtu);
538
539                 /* lower bound */
540                 if (mtu < IPV6_MMTU) {
541                         nd6log((LOG_INFO, "%s: bogus mtu option mtu=%lu sent "
542                             "from %s, ignoring\n", __func__,
543                             mtu, ip6_sprintf(ip6bufs, &ip6->ip6_src)));
544                         goto skip;
545                 }
546
547                 /* upper bound */
548                 maxmtu = (ndi->maxmtu && ndi->maxmtu < ifp->if_mtu)
549                     ? ndi->maxmtu : ifp->if_mtu;
550                 if (mtu <= maxmtu) {
551                         int change = (ndi->linkmtu != mtu);
552
553                         ndi->linkmtu = mtu;
554                         if (change) {
555                                 /* in6_maxmtu may change */
556                                 in6_setmaxmtu();
557                                 rt_updatemtu(ifp);
558                         }
559                 } else {
560                         nd6log((LOG_INFO, "%s: bogus mtu=%lu sent from %s; "
561                             "exceeds maxmtu %lu, ignoring\n", __func__,
562                             mtu, ip6_sprintf(ip6bufs, &ip6->ip6_src), maxmtu));
563                 }
564         }
565
566  skip:
567
568         /*
569          * Source link layer address
570          */
571     {
572         char *lladdr = NULL;
573         int lladdrlen = 0;
574
575         if (ndopts.nd_opts_src_lladdr) {
576                 lladdr = (char *)(ndopts.nd_opts_src_lladdr + 1);
577                 lladdrlen = ndopts.nd_opts_src_lladdr->nd_opt_len << 3;
578         }
579
580         if (lladdr && ((ifp->if_addrlen + 2 + 7) & ~7) != lladdrlen) {
581                 nd6log((LOG_INFO,
582                     "%s: lladdrlen mismatch for %s (if %d, RA packet %d)\n",
583                     __func__, ip6_sprintf(ip6bufs, &saddr6),
584                     ifp->if_addrlen, lladdrlen - 2));
585                 goto bad;
586         }
587
588         nd6_cache_lladdr(ifp, &saddr6, lladdr,
589             lladdrlen, ND_ROUTER_ADVERT, 0);
590
591         /*
592          * Installing a link-layer address might change the state of the
593          * router's neighbor cache, which might also affect our on-link
594          * detection of adveritsed prefixes.
595          */
596         pfxlist_onlink_check();
597     }
598
599  freeit:
600         m_freem(m);
601         return;
602
603  bad:
604         ICMP6STAT_INC(icp6s_badra);
605         m_freem(m);
606 }
607
608 /* PFXRTR */
609 static struct nd_pfxrouter *
610 pfxrtr_lookup(struct nd_prefix *pr, struct nd_defrouter *dr)
611 {
612         struct nd_pfxrouter *search;
613
614         ND6_LOCK_ASSERT();
615
616         LIST_FOREACH(search, &pr->ndpr_advrtrs, pfr_entry) {
617                 if (search->router == dr)
618                         break;
619         }
620         return (search);
621 }
622
623 static void
624 pfxrtr_add(struct nd_prefix *pr, struct nd_defrouter *dr)
625 {
626         struct nd_pfxrouter *new;
627         bool update;
628
629         ND6_UNLOCK_ASSERT();
630
631         ND6_RLOCK();
632         if (pfxrtr_lookup(pr, dr) != NULL) {
633                 ND6_RUNLOCK();
634                 return;
635         }
636         ND6_RUNLOCK();
637
638         new = malloc(sizeof(*new), M_IP6NDP, M_NOWAIT | M_ZERO);
639         if (new == NULL)
640                 return;
641         defrouter_ref(dr);
642         new->router = dr;
643
644         ND6_WLOCK();
645         if (pfxrtr_lookup(pr, dr) == NULL) {
646                 LIST_INSERT_HEAD(&pr->ndpr_advrtrs, new, pfr_entry);
647                 update = true;
648         } else {
649                 /* We lost a race to add the reference. */
650                 defrouter_rele(dr);
651                 free(new, M_IP6NDP);
652                 update = false;
653         }
654         ND6_WUNLOCK();
655
656         if (update)
657                 pfxlist_onlink_check();
658 }
659
660 static void
661 pfxrtr_del(struct nd_pfxrouter *pfr)
662 {
663
664         ND6_WLOCK_ASSERT();
665
666         LIST_REMOVE(pfr, pfr_entry);
667         defrouter_rele(pfr->router);
668         free(pfr, M_IP6NDP);
669 }
670
671 /* Default router list processing sub routines. */
672 static void
673 defrouter_addreq(struct nd_defrouter *new)
674 {
675         struct sockaddr_in6 def, mask, gate;
676         struct rt_addrinfo info;
677         struct rib_cmd_info rc;
678         unsigned int fibnum;
679         int error;
680
681         bzero(&def, sizeof(def));
682         bzero(&mask, sizeof(mask));
683         bzero(&gate, sizeof(gate));
684
685         def.sin6_len = mask.sin6_len = gate.sin6_len =
686             sizeof(struct sockaddr_in6);
687         def.sin6_family = gate.sin6_family = AF_INET6;
688         gate.sin6_addr = new->rtaddr;
689         fibnum = new->ifp->if_fib;
690
691         bzero((caddr_t)&info, sizeof(info));
692         info.rti_flags = RTF_GATEWAY;
693         info.rti_info[RTAX_DST] = (struct sockaddr *)&def;
694         info.rti_info[RTAX_GATEWAY] = (struct sockaddr *)&gate;
695         info.rti_info[RTAX_NETMASK] = (struct sockaddr *)&mask;
696
697         NET_EPOCH_ASSERT();
698         error = rib_action(fibnum, RTM_ADD, &info, &rc);
699         if (rc.rc_rt != NULL)
700                 rt_routemsg(RTM_ADD, rc.rc_rt, new->ifp, 0, fibnum);
701         if (error == 0)
702                 new->installed = 1;
703 }
704
705 /*
706  * Remove the default route for a given router.
707  * This is just a subroutine function for defrouter_select_fib(), and
708  * should not be called from anywhere else.
709  */
710 static void
711 defrouter_delreq(struct nd_defrouter *dr)
712 {
713         struct sockaddr_in6 def, mask, gate;
714         struct rt_addrinfo info;
715         struct rib_cmd_info rc;
716         struct epoch_tracker et;
717         unsigned int fibnum;
718
719         bzero(&def, sizeof(def));
720         bzero(&mask, sizeof(mask));
721         bzero(&gate, sizeof(gate));
722
723         def.sin6_len = mask.sin6_len = gate.sin6_len =
724             sizeof(struct sockaddr_in6);
725         def.sin6_family = gate.sin6_family = AF_INET6;
726         gate.sin6_addr = dr->rtaddr;
727         fibnum = dr->ifp->if_fib;
728
729         bzero((caddr_t)&info, sizeof(info));
730         info.rti_flags = RTF_GATEWAY;
731         info.rti_info[RTAX_DST] = (struct sockaddr *)&def;
732         info.rti_info[RTAX_GATEWAY] = (struct sockaddr *)&gate;
733         info.rti_info[RTAX_NETMASK] = (struct sockaddr *)&mask;
734
735         NET_EPOCH_ENTER(et);
736         rib_action(fibnum, RTM_DELETE, &info, &rc);
737         if (rc.rc_rt != NULL)
738                 rt_routemsg(RTM_DELETE, rc.rc_rt, dr->ifp, 0, fibnum);
739         NET_EPOCH_EXIT(et);
740
741         dr->installed = 0;
742 }
743
744 static void
745 defrouter_del(struct nd_defrouter *dr)
746 {
747         struct nd_defrouter *deldr = NULL;
748         struct nd_prefix *pr;
749         struct nd_pfxrouter *pfxrtr;
750
751         ND6_UNLOCK_ASSERT();
752
753         /*
754          * Flush all the routing table entries that use the router
755          * as a next hop.
756          */
757         if (ND_IFINFO(dr->ifp)->flags & ND6_IFF_ACCEPT_RTADV)
758                 rt6_flush(&dr->rtaddr, dr->ifp);
759
760 #ifdef EXPERIMENTAL
761         defrtr_ipv6_only_ifp(dr->ifp);
762 #endif
763
764         if (dr->installed) {
765                 deldr = dr;
766                 defrouter_delreq(dr);
767         }
768
769         /*
770          * Also delete all the pointers to the router in each prefix lists.
771          */
772         ND6_WLOCK();
773         LIST_FOREACH(pr, &V_nd_prefix, ndpr_entry) {
774                 if ((pfxrtr = pfxrtr_lookup(pr, dr)) != NULL)
775                         pfxrtr_del(pfxrtr);
776         }
777         ND6_WUNLOCK();
778
779         pfxlist_onlink_check();
780
781         /*
782          * If the router is the primary one, choose a new one.
783          * Note that defrouter_select_fib() will remove the current
784          * gateway from the routing table.
785          */
786         if (deldr)
787                 defrouter_select_fib(deldr->ifp->if_fib);
788
789         /*
790          * Release the list reference.
791          */
792         defrouter_rele(dr);
793 }
794
795 struct nd_defrouter *
796 defrouter_lookup_locked(const struct in6_addr *addr, struct ifnet *ifp)
797 {
798         struct nd_defrouter *dr;
799
800         ND6_LOCK_ASSERT();
801         TAILQ_FOREACH(dr, &V_nd6_defrouter, dr_entry)
802                 if (dr->ifp == ifp && IN6_ARE_ADDR_EQUAL(addr, &dr->rtaddr)) {
803                         defrouter_ref(dr);
804                         return (dr);
805                 }
806         return (NULL);
807 }
808
809 struct nd_defrouter *
810 defrouter_lookup(const struct in6_addr *addr, struct ifnet *ifp)
811 {
812         struct nd_defrouter *dr;
813
814         ND6_RLOCK();
815         dr = defrouter_lookup_locked(addr, ifp);
816         ND6_RUNLOCK();
817         return (dr);
818 }
819
820 /*
821  * Remove all default routes from default router list.
822  */
823 void
824 defrouter_reset(void)
825 {
826         struct nd_defrouter *dr, **dra;
827         int count, i;
828
829         count = i = 0;
830
831         /*
832          * We can't delete routes with the ND lock held, so make a copy of the
833          * current default router list and use that when deleting routes.
834          */
835         ND6_RLOCK();
836         TAILQ_FOREACH(dr, &V_nd6_defrouter, dr_entry)
837                 count++;
838         ND6_RUNLOCK();
839
840         dra = malloc(count * sizeof(*dra), M_TEMP, M_WAITOK | M_ZERO);
841
842         ND6_RLOCK();
843         TAILQ_FOREACH(dr, &V_nd6_defrouter, dr_entry) {
844                 if (i == count)
845                         break;
846                 defrouter_ref(dr);
847                 dra[i++] = dr;
848         }
849         ND6_RUNLOCK();
850
851         for (i = 0; i < count && dra[i] != NULL; i++) {
852                 defrouter_delreq(dra[i]);
853                 defrouter_rele(dra[i]);
854         }
855         free(dra, M_TEMP);
856
857         /*
858          * XXX should we also nuke any default routers in the kernel, by
859          * going through them by rtalloc1()?
860          */
861 }
862
863 /*
864  * Look up a matching default router list entry and remove it. Returns true if a
865  * matching entry was found, false otherwise.
866  */
867 bool
868 defrouter_remove(struct in6_addr *addr, struct ifnet *ifp)
869 {
870         struct nd_defrouter *dr;
871
872         ND6_WLOCK();
873         dr = defrouter_lookup_locked(addr, ifp);
874         if (dr == NULL) {
875                 ND6_WUNLOCK();
876                 return (false);
877         }
878
879         defrouter_unlink(dr, NULL);
880         ND6_WUNLOCK();
881         defrouter_del(dr);
882         defrouter_rele(dr);
883         return (true);
884 }
885
886 /*
887  * for default router selection
888  * regards router-preference field as a 2-bit signed integer
889  */
890 static int
891 rtpref(struct nd_defrouter *dr)
892 {
893         switch (dr->raflags & ND_RA_FLAG_RTPREF_MASK) {
894         case ND_RA_FLAG_RTPREF_HIGH:
895                 return (RTPREF_HIGH);
896         case ND_RA_FLAG_RTPREF_MEDIUM:
897         case ND_RA_FLAG_RTPREF_RSV:
898                 return (RTPREF_MEDIUM);
899         case ND_RA_FLAG_RTPREF_LOW:
900                 return (RTPREF_LOW);
901         default:
902                 /*
903                  * This case should never happen.  If it did, it would mean a
904                  * serious bug of kernel internal.  We thus always bark here.
905                  * Or, can we even panic?
906                  */
907                 log(LOG_ERR, "rtpref: impossible RA flag %x\n", dr->raflags);
908                 return (RTPREF_INVALID);
909         }
910         /* NOTREACHED */
911 }
912
913 /*
914  * Default Router Selection according to Section 6.3.6 of RFC 2461 and
915  * draft-ietf-ipngwg-router-selection:
916  * 1) Routers that are reachable or probably reachable should be preferred.
917  *    If we have more than one (probably) reachable router, prefer ones
918  *    with the highest router preference.
919  * 2) When no routers on the list are known to be reachable or
920  *    probably reachable, routers SHOULD be selected in a round-robin
921  *    fashion, regardless of router preference values.
922  * 3) If the Default Router List is empty, assume that all
923  *    destinations are on-link.
924  *
925  * We assume nd_defrouter is sorted by router preference value.
926  * Since the code below covers both with and without router preference cases,
927  * we do not need to classify the cases by ifdef.
928  *
929  * At this moment, we do not try to install more than one default router,
930  * even when the multipath routing is available, because we're not sure about
931  * the benefits for stub hosts comparing to the risk of making the code
932  * complicated and the possibility of introducing bugs.
933  *
934  * We maintain a single list of routers for multiple FIBs, only considering one
935  * at a time based on the receiving interface's FIB. If @fibnum is RT_ALL_FIBS,
936  * we do the whole thing multiple times.
937  */
938 void
939 defrouter_select_fib(int fibnum)
940 {
941         struct epoch_tracker et;
942         struct nd_defrouter *dr, *selected_dr, *installed_dr;
943         struct llentry *ln = NULL;
944
945         if (fibnum == RT_ALL_FIBS) {
946                 for (fibnum = 0; fibnum < rt_numfibs; fibnum++) {
947                         defrouter_select_fib(fibnum);
948                 }
949         }
950
951         ND6_RLOCK();
952         /*
953          * Let's handle easy case (3) first:
954          * If default router list is empty, there's nothing to be done.
955          */
956         if (TAILQ_EMPTY(&V_nd6_defrouter)) {
957                 ND6_RUNLOCK();
958                 return;
959         }
960
961         /*
962          * Search for a (probably) reachable router from the list.
963          * We just pick up the first reachable one (if any), assuming that
964          * the ordering rule of the list described in defrtrlist_update().
965          */
966         selected_dr = installed_dr = NULL;
967         TAILQ_FOREACH(dr, &V_nd6_defrouter, dr_entry) {
968                 NET_EPOCH_ENTER(et);
969                 if (selected_dr == NULL && dr->ifp->if_fib == fibnum &&
970                     (ln = nd6_lookup(&dr->rtaddr, 0, dr->ifp)) &&
971                     ND6_IS_LLINFO_PROBREACH(ln)) {
972                         selected_dr = dr;
973                         defrouter_ref(selected_dr);
974                 }
975                 NET_EPOCH_EXIT(et);
976                 if (ln != NULL) {
977                         LLE_RUNLOCK(ln);
978                         ln = NULL;
979                 }
980
981                 if (dr->installed && dr->ifp->if_fib == fibnum) {
982                         if (installed_dr == NULL) {
983                                 installed_dr = dr;
984                                 defrouter_ref(installed_dr);
985                         } else {
986                                 /*
987                                  * this should not happen.
988                                  * warn for diagnosis.
989                                  */
990                                 log(LOG_ERR, "defrouter_select_fib: more than "
991                                              "one router is installed\n");
992                         }
993                 }
994         }
995         /*
996          * If none of the default routers was found to be reachable,
997          * round-robin the list regardless of preference.
998          * Otherwise, if we have an installed router, check if the selected
999          * (reachable) router should really be preferred to the installed one.
1000          * We only prefer the new router when the old one is not reachable
1001          * or when the new one has a really higher preference value.
1002          */
1003         if (selected_dr == NULL) {
1004                 if (installed_dr == NULL ||
1005                     TAILQ_NEXT(installed_dr, dr_entry) == NULL)
1006                         dr = TAILQ_FIRST(&V_nd6_defrouter);
1007                 else
1008                         dr = TAILQ_NEXT(installed_dr, dr_entry);
1009
1010                 /* Ensure we select a router for this FIB. */
1011                 TAILQ_FOREACH_FROM(dr, &V_nd6_defrouter, dr_entry) {
1012                         if (dr->ifp->if_fib == fibnum) {
1013                                 selected_dr = dr;
1014                                 defrouter_ref(selected_dr);
1015                                 break;
1016                         }
1017                 }
1018         } else if (installed_dr != NULL) {
1019                 NET_EPOCH_ENTER(et);
1020                 if ((ln = nd6_lookup(&installed_dr->rtaddr, 0,
1021                                      installed_dr->ifp)) &&
1022                     ND6_IS_LLINFO_PROBREACH(ln) &&
1023                     installed_dr->ifp->if_fib == fibnum &&
1024                     rtpref(selected_dr) <= rtpref(installed_dr)) {
1025                         defrouter_rele(selected_dr);
1026                         selected_dr = installed_dr;
1027                 }
1028                 NET_EPOCH_EXIT(et);
1029                 if (ln != NULL)
1030                         LLE_RUNLOCK(ln);
1031         }
1032         ND6_RUNLOCK();
1033
1034         NET_EPOCH_ENTER(et);
1035         /*
1036          * If we selected a router for this FIB and it's different
1037          * than the installed one, remove the installed router and
1038          * install the selected one in its place.
1039          */
1040         if (installed_dr != selected_dr) {
1041                 if (installed_dr != NULL) {
1042                         defrouter_delreq(installed_dr);
1043                         defrouter_rele(installed_dr);
1044                 }
1045                 if (selected_dr != NULL)
1046                         defrouter_addreq(selected_dr);
1047         }
1048         if (selected_dr != NULL)
1049                 defrouter_rele(selected_dr);
1050         NET_EPOCH_EXIT(et);
1051 }
1052
1053 static struct nd_defrouter *
1054 defrtrlist_update(struct nd_defrouter *new)
1055 {
1056         struct nd_defrouter *dr, *n;
1057         uint64_t genid;
1058         int oldpref;
1059         bool writelocked;
1060
1061         if (new->rtlifetime == 0) {
1062                 defrouter_remove(&new->rtaddr, new->ifp);
1063                 return (NULL);
1064         }
1065
1066         ND6_RLOCK();
1067         writelocked = false;
1068 restart:
1069         dr = defrouter_lookup_locked(&new->rtaddr, new->ifp);
1070         if (dr != NULL) {
1071                 oldpref = rtpref(dr);
1072
1073                 /* override */
1074                 dr->raflags = new->raflags; /* XXX flag check */
1075                 dr->rtlifetime = new->rtlifetime;
1076                 dr->expire = new->expire;
1077
1078                 /*
1079                  * If the preference does not change, there's no need
1080                  * to sort the entries. Also make sure the selected
1081                  * router is still installed in the kernel.
1082                  */
1083                 if (dr->installed && rtpref(new) == oldpref) {
1084                         if (writelocked)
1085                                 ND6_WUNLOCK();
1086                         else
1087                                 ND6_RUNLOCK();
1088                         return (dr);
1089                 }
1090         }
1091
1092         /*
1093          * The router needs to be reinserted into the default router
1094          * list, so upgrade to a write lock. If that fails and the list
1095          * has potentially changed while the lock was dropped, we'll
1096          * redo the lookup with the write lock held.
1097          */
1098         if (!writelocked) {
1099                 writelocked = true;
1100                 if (!ND6_TRY_UPGRADE()) {
1101                         genid = V_nd6_list_genid;
1102                         ND6_RUNLOCK();
1103                         ND6_WLOCK();
1104                         if (genid != V_nd6_list_genid)
1105                                 goto restart;
1106                 }
1107         }
1108
1109         if (dr != NULL) {
1110                 /*
1111                  * The preferred router may have changed, so relocate this
1112                  * router.
1113                  */
1114                 TAILQ_REMOVE(&V_nd6_defrouter, dr, dr_entry);
1115                 n = dr;
1116         } else {
1117                 n = malloc(sizeof(*n), M_IP6NDP, M_NOWAIT | M_ZERO);
1118                 if (n == NULL) {
1119                         ND6_WUNLOCK();
1120                         return (NULL);
1121                 }
1122                 memcpy(n, new, sizeof(*n));
1123                 /* Initialize with an extra reference for the caller. */
1124                 refcount_init(&n->refcnt, 2);
1125         }
1126
1127         /*
1128          * Insert the new router in the Default Router List;
1129          * The Default Router List should be in the descending order
1130          * of router-preferece.  Routers with the same preference are
1131          * sorted in the arriving time order.
1132          */
1133
1134         /* insert at the end of the group */
1135         TAILQ_FOREACH(dr, &V_nd6_defrouter, dr_entry) {
1136                 if (rtpref(n) > rtpref(dr))
1137                         break;
1138         }
1139         if (dr != NULL)
1140                 TAILQ_INSERT_BEFORE(dr, n, dr_entry);
1141         else
1142                 TAILQ_INSERT_TAIL(&V_nd6_defrouter, n, dr_entry);
1143         V_nd6_list_genid++;
1144         ND6_WUNLOCK();
1145
1146         defrouter_select_fib(new->ifp->if_fib);
1147
1148         return (n);
1149 }
1150
1151 static int
1152 in6_init_prefix_ltimes(struct nd_prefix *ndpr)
1153 {
1154         if (ndpr->ndpr_pltime == ND6_INFINITE_LIFETIME)
1155                 ndpr->ndpr_preferred = 0;
1156         else
1157                 ndpr->ndpr_preferred = time_uptime + ndpr->ndpr_pltime;
1158         if (ndpr->ndpr_vltime == ND6_INFINITE_LIFETIME)
1159                 ndpr->ndpr_expire = 0;
1160         else
1161                 ndpr->ndpr_expire = time_uptime + ndpr->ndpr_vltime;
1162
1163         return 0;
1164 }
1165
1166 static void
1167 in6_init_address_ltimes(struct nd_prefix *new, struct in6_addrlifetime *lt6)
1168 {
1169         /* init ia6t_expire */
1170         if (lt6->ia6t_vltime == ND6_INFINITE_LIFETIME)
1171                 lt6->ia6t_expire = 0;
1172         else {
1173                 lt6->ia6t_expire = time_uptime;
1174                 lt6->ia6t_expire += lt6->ia6t_vltime;
1175         }
1176
1177         /* init ia6t_preferred */
1178         if (lt6->ia6t_pltime == ND6_INFINITE_LIFETIME)
1179                 lt6->ia6t_preferred = 0;
1180         else {
1181                 lt6->ia6t_preferred = time_uptime;
1182                 lt6->ia6t_preferred += lt6->ia6t_pltime;
1183         }
1184 }
1185
1186 static struct in6_ifaddr *
1187 in6_ifadd(struct nd_prefixctl *pr, int mcast)
1188 {
1189         struct ifnet *ifp = pr->ndpr_ifp;
1190         struct ifaddr *ifa;
1191         struct in6_aliasreq ifra;
1192         struct in6_ifaddr *ia, *ib;
1193         int error, plen0;
1194         struct in6_addr mask;
1195         int prefixlen = pr->ndpr_plen;
1196         int updateflags;
1197         char ip6buf[INET6_ADDRSTRLEN];
1198
1199         in6_prefixlen2mask(&mask, prefixlen);
1200
1201         /*
1202          * find a link-local address (will be interface ID).
1203          * Is it really mandatory? Theoretically, a global or a site-local
1204          * address can be configured without a link-local address, if we
1205          * have a unique interface identifier...
1206          *
1207          * it is not mandatory to have a link-local address, we can generate
1208          * interface identifier on the fly.  we do this because:
1209          * (1) it should be the easiest way to find interface identifier.
1210          * (2) RFC2462 5.4 suggesting the use of the same interface identifier
1211          * for multiple addresses on a single interface, and possible shortcut
1212          * of DAD.  we omitted DAD for this reason in the past.
1213          * (3) a user can prevent autoconfiguration of global address
1214          * by removing link-local address by hand (this is partly because we
1215          * don't have other way to control the use of IPv6 on an interface.
1216          * this has been our design choice - cf. NRL's "ifconfig auto").
1217          * (4) it is easier to manage when an interface has addresses
1218          * with the same interface identifier, than to have multiple addresses
1219          * with different interface identifiers.
1220          */
1221         ifa = (struct ifaddr *)in6ifa_ifpforlinklocal(ifp, 0); /* 0 is OK? */
1222         if (ifa)
1223                 ib = (struct in6_ifaddr *)ifa;
1224         else
1225                 return NULL;
1226
1227         /* prefixlen + ifidlen must be equal to 128 */
1228         plen0 = in6_mask2len(&ib->ia_prefixmask.sin6_addr, NULL);
1229         if (prefixlen != plen0) {
1230                 ifa_free(ifa);
1231                 nd6log((LOG_INFO,
1232                     "%s: wrong prefixlen for %s (prefix=%d ifid=%d)\n",
1233                     __func__, if_name(ifp), prefixlen, 128 - plen0));
1234                 return NULL;
1235         }
1236
1237         /* make ifaddr */
1238         in6_prepare_ifra(&ifra, &pr->ndpr_prefix.sin6_addr, &mask);
1239
1240         IN6_MASK_ADDR(&ifra.ifra_addr.sin6_addr, &mask);
1241         /* interface ID */
1242         ifra.ifra_addr.sin6_addr.s6_addr32[0] |=
1243             (ib->ia_addr.sin6_addr.s6_addr32[0] & ~mask.s6_addr32[0]);
1244         ifra.ifra_addr.sin6_addr.s6_addr32[1] |=
1245             (ib->ia_addr.sin6_addr.s6_addr32[1] & ~mask.s6_addr32[1]);
1246         ifra.ifra_addr.sin6_addr.s6_addr32[2] |=
1247             (ib->ia_addr.sin6_addr.s6_addr32[2] & ~mask.s6_addr32[2]);
1248         ifra.ifra_addr.sin6_addr.s6_addr32[3] |=
1249             (ib->ia_addr.sin6_addr.s6_addr32[3] & ~mask.s6_addr32[3]);
1250         ifa_free(ifa);
1251
1252         /* lifetimes. */
1253         ifra.ifra_lifetime.ia6t_vltime = pr->ndpr_vltime;
1254         ifra.ifra_lifetime.ia6t_pltime = pr->ndpr_pltime;
1255
1256         /* XXX: scope zone ID? */
1257
1258         ifra.ifra_flags |= IN6_IFF_AUTOCONF; /* obey autoconf */
1259
1260         /*
1261          * Make sure that we do not have this address already.  This should
1262          * usually not happen, but we can still see this case, e.g., if we
1263          * have manually configured the exact address to be configured.
1264          */
1265         ifa = (struct ifaddr *)in6ifa_ifpwithaddr(ifp,
1266             &ifra.ifra_addr.sin6_addr);
1267         if (ifa != NULL) {
1268                 ifa_free(ifa);
1269                 /* this should be rare enough to make an explicit log */
1270                 log(LOG_INFO, "in6_ifadd: %s is already configured\n",
1271                     ip6_sprintf(ip6buf, &ifra.ifra_addr.sin6_addr));
1272                 return (NULL);
1273         }
1274
1275         /*
1276          * Allocate ifaddr structure, link into chain, etc.
1277          * If we are going to create a new address upon receiving a multicasted
1278          * RA, we need to impose a random delay before starting DAD.
1279          * [draft-ietf-ipv6-rfc2462bis-02.txt, Section 5.4.2]
1280          */
1281         updateflags = 0;
1282         if (mcast)
1283                 updateflags |= IN6_IFAUPDATE_DADDELAY;
1284         if ((error = in6_update_ifa(ifp, &ifra, NULL, updateflags)) != 0) {
1285                 nd6log((LOG_ERR,
1286                     "%s: failed to make ifaddr %s on %s (errno=%d)\n", __func__,
1287                     ip6_sprintf(ip6buf, &ifra.ifra_addr.sin6_addr),
1288                     if_name(ifp), error));
1289                 return (NULL);  /* ifaddr must not have been allocated. */
1290         }
1291
1292         ia = in6ifa_ifpwithaddr(ifp, &ifra.ifra_addr.sin6_addr);
1293         /*
1294          * XXXRW: Assumption of non-NULLness here might not be true with
1295          * fine-grained locking -- should we validate it?  Or just return
1296          * earlier ifa rather than looking it up again?
1297          */
1298         return (ia);            /* this is always non-NULL  and referenced. */
1299 }
1300
1301 static struct nd_prefix *
1302 nd6_prefix_lookup_locked(struct nd_prefixctl *key)
1303 {
1304         struct nd_prefix *search;
1305
1306         ND6_LOCK_ASSERT();
1307
1308         LIST_FOREACH(search, &V_nd_prefix, ndpr_entry) {
1309                 if (key->ndpr_ifp == search->ndpr_ifp &&
1310                     key->ndpr_plen == search->ndpr_plen &&
1311                     in6_are_prefix_equal(&key->ndpr_prefix.sin6_addr,
1312                     &search->ndpr_prefix.sin6_addr, key->ndpr_plen)) {
1313                         nd6_prefix_ref(search);
1314                         break;
1315                 }
1316         }
1317         return (search);
1318 }
1319
1320 struct nd_prefix *
1321 nd6_prefix_lookup(struct nd_prefixctl *key)
1322 {
1323         struct nd_prefix *search;
1324
1325         ND6_RLOCK();
1326         search = nd6_prefix_lookup_locked(key);
1327         ND6_RUNLOCK();
1328         return (search);
1329 }
1330
1331 void
1332 nd6_prefix_ref(struct nd_prefix *pr)
1333 {
1334
1335         refcount_acquire(&pr->ndpr_refcnt);
1336 }
1337
1338 void
1339 nd6_prefix_rele(struct nd_prefix *pr)
1340 {
1341
1342         if (refcount_release(&pr->ndpr_refcnt)) {
1343                 KASSERT(LIST_EMPTY(&pr->ndpr_advrtrs),
1344                     ("prefix %p has advertising routers", pr));
1345                 free(pr, M_IP6NDP);
1346         }
1347 }
1348
1349 int
1350 nd6_prelist_add(struct nd_prefixctl *pr, struct nd_defrouter *dr,
1351     struct nd_prefix **newp)
1352 {
1353         struct nd_prefix *new;
1354         char ip6buf[INET6_ADDRSTRLEN];
1355         int error;
1356
1357         new = malloc(sizeof(*new), M_IP6NDP, M_NOWAIT | M_ZERO);
1358         if (new == NULL)
1359                 return (ENOMEM);
1360         refcount_init(&new->ndpr_refcnt, newp != NULL ? 2 : 1);
1361         new->ndpr_ifp = pr->ndpr_ifp;
1362         new->ndpr_prefix = pr->ndpr_prefix;
1363         new->ndpr_plen = pr->ndpr_plen;
1364         new->ndpr_vltime = pr->ndpr_vltime;
1365         new->ndpr_pltime = pr->ndpr_pltime;
1366         new->ndpr_flags = pr->ndpr_flags;
1367         if ((error = in6_init_prefix_ltimes(new)) != 0) {
1368                 free(new, M_IP6NDP);
1369                 return (error);
1370         }
1371         new->ndpr_lastupdate = time_uptime;
1372
1373         /* initialization */
1374         LIST_INIT(&new->ndpr_advrtrs);
1375         in6_prefixlen2mask(&new->ndpr_mask, new->ndpr_plen);
1376         /* make prefix in the canonical form */
1377         IN6_MASK_ADDR(&new->ndpr_prefix.sin6_addr, &new->ndpr_mask);
1378
1379         ND6_WLOCK();
1380         LIST_INSERT_HEAD(&V_nd_prefix, new, ndpr_entry);
1381         V_nd6_list_genid++;
1382         ND6_WUNLOCK();
1383
1384         /* ND_OPT_PI_FLAG_ONLINK processing */
1385         if (new->ndpr_raf_onlink) {
1386                 struct epoch_tracker et;
1387
1388                 ND6_ONLINK_LOCK();
1389                 NET_EPOCH_ENTER(et);
1390                 if ((error = nd6_prefix_onlink(new)) != 0) {
1391                         nd6log((LOG_ERR, "%s: failed to make the prefix %s/%d "
1392                             "on-link on %s (errno=%d)\n", __func__,
1393                             ip6_sprintf(ip6buf, &pr->ndpr_prefix.sin6_addr),
1394                             pr->ndpr_plen, if_name(pr->ndpr_ifp), error));
1395                         /* proceed anyway. XXX: is it correct? */
1396                 }
1397                 NET_EPOCH_EXIT(et);
1398                 ND6_ONLINK_UNLOCK();
1399         }
1400
1401         if (dr != NULL)
1402                 pfxrtr_add(new, dr);
1403         if (newp != NULL)
1404                 *newp = new;
1405         return (0);
1406 }
1407
1408 /*
1409  * Remove a prefix from the prefix list and optionally stash it in a
1410  * caller-provided list.
1411  *
1412  * The ND6 lock must be held.
1413  */
1414 void
1415 nd6_prefix_unlink(struct nd_prefix *pr, struct nd_prhead *list)
1416 {
1417
1418         ND6_WLOCK_ASSERT();
1419
1420         LIST_REMOVE(pr, ndpr_entry);
1421         V_nd6_list_genid++;
1422         if (list != NULL)
1423                 LIST_INSERT_HEAD(list, pr, ndpr_entry);
1424 }
1425
1426 /*
1427  * Free an unlinked prefix, first marking it off-link if necessary.
1428  */
1429 void
1430 nd6_prefix_del(struct nd_prefix *pr)
1431 {
1432         struct nd_pfxrouter *pfr, *next;
1433         int e;
1434         char ip6buf[INET6_ADDRSTRLEN];
1435
1436         KASSERT(pr->ndpr_addrcnt == 0,
1437             ("prefix %p has referencing addresses", pr));
1438         ND6_UNLOCK_ASSERT();
1439
1440         /*
1441          * Though these flags are now meaningless, we'd rather keep the value
1442          * of pr->ndpr_raf_onlink and pr->ndpr_raf_auto not to confuse users
1443          * when executing "ndp -p".
1444          */
1445         if ((pr->ndpr_stateflags & NDPRF_ONLINK) != 0) {
1446                 ND6_ONLINK_LOCK();
1447                 if ((e = nd6_prefix_offlink(pr)) != 0) {
1448                         nd6log((LOG_ERR,
1449                             "%s: failed to make the prefix %s/%d offlink on %s "
1450                             "(errno=%d)\n", __func__,
1451                             ip6_sprintf(ip6buf, &pr->ndpr_prefix.sin6_addr),
1452                             pr->ndpr_plen, if_name(pr->ndpr_ifp), e));
1453                         /* what should we do? */
1454                 }
1455                 ND6_ONLINK_UNLOCK();
1456         }
1457
1458         /* Release references to routers that have advertised this prefix. */
1459         ND6_WLOCK();
1460         LIST_FOREACH_SAFE(pfr, &pr->ndpr_advrtrs, pfr_entry, next)
1461                 pfxrtr_del(pfr);
1462         ND6_WUNLOCK();
1463
1464         nd6_prefix_rele(pr);
1465
1466         pfxlist_onlink_check();
1467 }
1468
1469 static int
1470 prelist_update(struct nd_prefixctl *new, struct nd_defrouter *dr,
1471     struct mbuf *m, int mcast)
1472 {
1473         struct in6_ifaddr *ia6 = NULL, *ia6_match = NULL;
1474         struct ifaddr *ifa;
1475         struct ifnet *ifp = new->ndpr_ifp;
1476         struct nd_prefix *pr;
1477         int error = 0;
1478         int auth;
1479         struct in6_addrlifetime lt6_tmp;
1480         char ip6buf[INET6_ADDRSTRLEN];
1481
1482         NET_EPOCH_ASSERT();
1483
1484         auth = 0;
1485         if (m) {
1486                 /*
1487                  * Authenticity for NA consists authentication for
1488                  * both IP header and IP datagrams, doesn't it ?
1489                  */
1490 #if defined(M_AUTHIPHDR) && defined(M_AUTHIPDGM)
1491                 auth = ((m->m_flags & M_AUTHIPHDR) &&
1492                     (m->m_flags & M_AUTHIPDGM));
1493 #endif
1494         }
1495
1496         if ((pr = nd6_prefix_lookup(new)) != NULL) {
1497                 /*
1498                  * nd6_prefix_lookup() ensures that pr and new have the same
1499                  * prefix on a same interface.
1500                  */
1501
1502                 /*
1503                  * Update prefix information.  Note that the on-link (L) bit
1504                  * and the autonomous (A) bit should NOT be changed from 1
1505                  * to 0.
1506                  */
1507                 if (new->ndpr_raf_onlink == 1)
1508                         pr->ndpr_raf_onlink = 1;
1509                 if (new->ndpr_raf_auto == 1)
1510                         pr->ndpr_raf_auto = 1;
1511                 if (new->ndpr_raf_onlink) {
1512                         pr->ndpr_vltime = new->ndpr_vltime;
1513                         pr->ndpr_pltime = new->ndpr_pltime;
1514                         (void)in6_init_prefix_ltimes(pr); /* XXX error case? */
1515                         pr->ndpr_lastupdate = time_uptime;
1516                 }
1517
1518                 if (new->ndpr_raf_onlink &&
1519                     (pr->ndpr_stateflags & NDPRF_ONLINK) == 0) {
1520                         ND6_ONLINK_LOCK();
1521                         if ((error = nd6_prefix_onlink(pr)) != 0) {
1522                                 nd6log((LOG_ERR,
1523                                     "%s: failed to make the prefix %s/%d "
1524                                     "on-link on %s (errno=%d)\n", __func__,
1525                                     ip6_sprintf(ip6buf,
1526                                         &pr->ndpr_prefix.sin6_addr),
1527                                     pr->ndpr_plen, if_name(pr->ndpr_ifp),
1528                                     error));
1529                                 /* proceed anyway. XXX: is it correct? */
1530                         }
1531                         ND6_ONLINK_UNLOCK();
1532                 }
1533
1534                 if (dr != NULL)
1535                         pfxrtr_add(pr, dr);
1536         } else {
1537                 if (new->ndpr_vltime == 0)
1538                         goto end;
1539                 if (new->ndpr_raf_onlink == 0 && new->ndpr_raf_auto == 0)
1540                         goto end;
1541
1542                 error = nd6_prelist_add(new, dr, &pr);
1543                 if (error != 0) {
1544                         nd6log((LOG_NOTICE, "%s: nd6_prelist_add() failed for "
1545                             "the prefix %s/%d on %s (errno=%d)\n", __func__,
1546                             ip6_sprintf(ip6buf, &new->ndpr_prefix.sin6_addr),
1547                             new->ndpr_plen, if_name(new->ndpr_ifp), error));
1548                         goto end; /* we should just give up in this case. */
1549                 }
1550
1551                 /*
1552                  * XXX: from the ND point of view, we can ignore a prefix
1553                  * with the on-link bit being zero.  However, we need a
1554                  * prefix structure for references from autoconfigured
1555                  * addresses.  Thus, we explicitly make sure that the prefix
1556                  * itself expires now.
1557                  */
1558                 if (pr->ndpr_raf_onlink == 0) {
1559                         pr->ndpr_vltime = 0;
1560                         pr->ndpr_pltime = 0;
1561                         in6_init_prefix_ltimes(pr);
1562                 }
1563         }
1564
1565         /*
1566          * Address autoconfiguration based on Section 5.5.3 of RFC 2462.
1567          * Note that pr must be non NULL at this point.
1568          */
1569
1570         /* 5.5.3 (a). Ignore the prefix without the A bit set. */
1571         if (!new->ndpr_raf_auto)
1572                 goto end;
1573
1574         /*
1575          * 5.5.3 (b). the link-local prefix should have been ignored in
1576          * nd6_ra_input.
1577          */
1578
1579         /* 5.5.3 (c). Consistency check on lifetimes: pltime <= vltime. */
1580         if (new->ndpr_pltime > new->ndpr_vltime) {
1581                 error = EINVAL; /* XXX: won't be used */
1582                 goto end;
1583         }
1584
1585         /*
1586          * 5.5.3 (d).  If the prefix advertised is not equal to the prefix of
1587          * an address configured by stateless autoconfiguration already in the
1588          * list of addresses associated with the interface, and the Valid
1589          * Lifetime is not 0, form an address.  We first check if we have
1590          * a matching prefix.
1591          * Note: we apply a clarification in rfc2462bis-02 here.  We only
1592          * consider autoconfigured addresses while RFC2462 simply said
1593          * "address".
1594          */
1595         CK_STAILQ_FOREACH(ifa, &ifp->if_addrhead, ifa_link) {
1596                 struct in6_ifaddr *ifa6;
1597                 u_int32_t remaininglifetime;
1598
1599                 if (ifa->ifa_addr->sa_family != AF_INET6)
1600                         continue;
1601
1602                 ifa6 = (struct in6_ifaddr *)ifa;
1603
1604                 /*
1605                  * We only consider autoconfigured addresses as per rfc2462bis.
1606                  */
1607                 if (!(ifa6->ia6_flags & IN6_IFF_AUTOCONF))
1608                         continue;
1609
1610                 /*
1611                  * Spec is not clear here, but I believe we should concentrate
1612                  * on unicast (i.e. not anycast) addresses.
1613                  * XXX: other ia6_flags? detached or duplicated?
1614                  */
1615                 if ((ifa6->ia6_flags & IN6_IFF_ANYCAST) != 0)
1616                         continue;
1617
1618                 /*
1619                  * Ignore the address if it is not associated with a prefix
1620                  * or is associated with a prefix that is different from this
1621                  * one.  (pr is never NULL here)
1622                  */
1623                 if (ifa6->ia6_ndpr != pr)
1624                         continue;
1625
1626                 if (ia6_match == NULL) /* remember the first one */
1627                         ia6_match = ifa6;
1628
1629                 /*
1630                  * An already autoconfigured address matched.  Now that we
1631                  * are sure there is at least one matched address, we can
1632                  * proceed to 5.5.3. (e): update the lifetimes according to the
1633                  * "two hours" rule and the privacy extension.
1634                  * We apply some clarifications in rfc2462bis:
1635                  * - use remaininglifetime instead of storedlifetime as a
1636                  *   variable name
1637                  * - remove the dead code in the "two-hour" rule
1638                  */
1639 #define TWOHOUR         (120*60)
1640                 lt6_tmp = ifa6->ia6_lifetime;
1641
1642                 if (lt6_tmp.ia6t_vltime == ND6_INFINITE_LIFETIME)
1643                         remaininglifetime = ND6_INFINITE_LIFETIME;
1644                 else if (time_uptime - ifa6->ia6_updatetime >
1645                          lt6_tmp.ia6t_vltime) {
1646                         /*
1647                          * The case of "invalid" address.  We should usually
1648                          * not see this case.
1649                          */
1650                         remaininglifetime = 0;
1651                 } else
1652                         remaininglifetime = lt6_tmp.ia6t_vltime -
1653                             (time_uptime - ifa6->ia6_updatetime);
1654
1655                 /* when not updating, keep the current stored lifetime. */
1656                 lt6_tmp.ia6t_vltime = remaininglifetime;
1657
1658                 if (TWOHOUR < new->ndpr_vltime ||
1659                     remaininglifetime < new->ndpr_vltime) {
1660                         lt6_tmp.ia6t_vltime = new->ndpr_vltime;
1661                 } else if (remaininglifetime <= TWOHOUR) {
1662                         if (auth) {
1663                                 lt6_tmp.ia6t_vltime = new->ndpr_vltime;
1664                         }
1665                 } else {
1666                         /*
1667                          * new->ndpr_vltime <= TWOHOUR &&
1668                          * TWOHOUR < remaininglifetime
1669                          */
1670                         lt6_tmp.ia6t_vltime = TWOHOUR;
1671                 }
1672
1673                 /* The 2 hour rule is not imposed for preferred lifetime. */
1674                 lt6_tmp.ia6t_pltime = new->ndpr_pltime;
1675
1676                 in6_init_address_ltimes(pr, &lt6_tmp);
1677
1678                 /*
1679                  * We need to treat lifetimes for temporary addresses
1680                  * differently, according to
1681                  * draft-ietf-ipv6-privacy-addrs-v2-01.txt 3.3 (1);
1682                  * we only update the lifetimes when they are in the maximum
1683                  * intervals.
1684                  */
1685                 if ((ifa6->ia6_flags & IN6_IFF_TEMPORARY) != 0) {
1686                         u_int32_t maxvltime, maxpltime;
1687
1688                         if (V_ip6_temp_valid_lifetime >
1689                             (u_int32_t)((time_uptime - ifa6->ia6_createtime) +
1690                             V_ip6_desync_factor)) {
1691                                 maxvltime = V_ip6_temp_valid_lifetime -
1692                                     (time_uptime - ifa6->ia6_createtime) -
1693                                     V_ip6_desync_factor;
1694                         } else
1695                                 maxvltime = 0;
1696                         if (V_ip6_temp_preferred_lifetime >
1697                             (u_int32_t)((time_uptime - ifa6->ia6_createtime) +
1698                             V_ip6_desync_factor)) {
1699                                 maxpltime = V_ip6_temp_preferred_lifetime -
1700                                     (time_uptime - ifa6->ia6_createtime) -
1701                                     V_ip6_desync_factor;
1702                         } else
1703                                 maxpltime = 0;
1704
1705                         if (lt6_tmp.ia6t_vltime == ND6_INFINITE_LIFETIME ||
1706                             lt6_tmp.ia6t_vltime > maxvltime) {
1707                                 lt6_tmp.ia6t_vltime = maxvltime;
1708                         }
1709                         if (lt6_tmp.ia6t_pltime == ND6_INFINITE_LIFETIME ||
1710                             lt6_tmp.ia6t_pltime > maxpltime) {
1711                                 lt6_tmp.ia6t_pltime = maxpltime;
1712                         }
1713                 }
1714                 ifa6->ia6_lifetime = lt6_tmp;
1715                 ifa6->ia6_updatetime = time_uptime;
1716         }
1717         if (ia6_match == NULL && new->ndpr_vltime) {
1718                 int ifidlen;
1719
1720                 /*
1721                  * 5.5.3 (d) (continued)
1722                  * No address matched and the valid lifetime is non-zero.
1723                  * Create a new address.
1724                  */
1725
1726                 /*
1727                  * Prefix Length check:
1728                  * If the sum of the prefix length and interface identifier
1729                  * length does not equal 128 bits, the Prefix Information
1730                  * option MUST be ignored.  The length of the interface
1731                  * identifier is defined in a separate link-type specific
1732                  * document.
1733                  */
1734                 ifidlen = in6_if2idlen(ifp);
1735                 if (ifidlen < 0) {
1736                         /* this should not happen, so we always log it. */
1737                         log(LOG_ERR, "prelist_update: IFID undefined (%s)\n",
1738                             if_name(ifp));
1739                         goto end;
1740                 }
1741                 if (ifidlen + pr->ndpr_plen != 128) {
1742                         nd6log((LOG_INFO,
1743                             "%s: invalid prefixlen %d for %s, ignored\n",
1744                             __func__, pr->ndpr_plen, if_name(ifp)));
1745                         goto end;
1746                 }
1747
1748                 if ((ia6 = in6_ifadd(new, mcast)) != NULL) {
1749                         /*
1750                          * note that we should use pr (not new) for reference.
1751                          */
1752                         pr->ndpr_addrcnt++;
1753                         ia6->ia6_ndpr = pr;
1754
1755                         /*
1756                          * RFC 3041 3.3 (2).
1757                          * When a new public address is created as described
1758                          * in RFC2462, also create a new temporary address.
1759                          *
1760                          * RFC 3041 3.5.
1761                          * When an interface connects to a new link, a new
1762                          * randomized interface identifier should be generated
1763                          * immediately together with a new set of temporary
1764                          * addresses.  Thus, we specifiy 1 as the 2nd arg of
1765                          * in6_tmpifadd().
1766                          */
1767                         if (V_ip6_use_tempaddr) {
1768                                 int e;
1769                                 if ((e = in6_tmpifadd(ia6, 1, 1)) != 0) {
1770                                         nd6log((LOG_NOTICE, "%s: failed to "
1771                                             "create a temporary address "
1772                                             "(errno=%d)\n", __func__, e));
1773                                 }
1774                         }
1775                         ifa_free(&ia6->ia_ifa);
1776
1777                         /*
1778                          * A newly added address might affect the status
1779                          * of other addresses, so we check and update it.
1780                          * XXX: what if address duplication happens?
1781                          */
1782                         pfxlist_onlink_check();
1783                 } else {
1784                         /* just set an error. do not bark here. */
1785                         error = EADDRNOTAVAIL; /* XXX: might be unused. */
1786                 }
1787         }
1788
1789 end:
1790         if (pr != NULL)
1791                 nd6_prefix_rele(pr);
1792         return (error);
1793 }
1794
1795 /*
1796  * A supplement function used in the on-link detection below;
1797  * detect if a given prefix has a (probably) reachable advertising router.
1798  * XXX: lengthy function name...
1799  */
1800 static struct nd_pfxrouter *
1801 find_pfxlist_reachable_router(struct nd_prefix *pr)
1802 {
1803         struct epoch_tracker et;
1804         struct nd_pfxrouter *pfxrtr;
1805         struct llentry *ln;
1806         int canreach;
1807
1808         ND6_LOCK_ASSERT();
1809
1810         NET_EPOCH_ENTER(et);
1811         LIST_FOREACH(pfxrtr, &pr->ndpr_advrtrs, pfr_entry) {
1812                 ln = nd6_lookup(&pfxrtr->router->rtaddr, 0, pfxrtr->router->ifp);
1813                 if (ln == NULL)
1814                         continue;
1815                 canreach = ND6_IS_LLINFO_PROBREACH(ln);
1816                 LLE_RUNLOCK(ln);
1817                 if (canreach)
1818                         break;
1819         }
1820         NET_EPOCH_EXIT(et);
1821         return (pfxrtr);
1822 }
1823
1824 /*
1825  * Check if each prefix in the prefix list has at least one available router
1826  * that advertised the prefix (a router is "available" if its neighbor cache
1827  * entry is reachable or probably reachable).
1828  * If the check fails, the prefix may be off-link, because, for example,
1829  * we have moved from the network but the lifetime of the prefix has not
1830  * expired yet.  So we should not use the prefix if there is another prefix
1831  * that has an available router.
1832  * But, if there is no prefix that has an available router, we still regard
1833  * all the prefixes as on-link.  This is because we can't tell if all the
1834  * routers are simply dead or if we really moved from the network and there
1835  * is no router around us.
1836  */
1837 void
1838 pfxlist_onlink_check(void)
1839 {
1840         struct nd_prefix *pr;
1841         struct in6_ifaddr *ifa;
1842         struct nd_defrouter *dr;
1843         struct nd_pfxrouter *pfxrtr = NULL;
1844         struct rm_priotracker in6_ifa_tracker;
1845         uint64_t genid;
1846         uint32_t flags;
1847
1848         ND6_ONLINK_LOCK();
1849         ND6_RLOCK();
1850
1851         /*
1852          * Check if there is a prefix that has a reachable advertising
1853          * router.
1854          */
1855         LIST_FOREACH(pr, &V_nd_prefix, ndpr_entry) {
1856                 if (pr->ndpr_raf_onlink && find_pfxlist_reachable_router(pr))
1857                         break;
1858         }
1859
1860         /*
1861          * If we have no such prefix, check whether we still have a router
1862          * that does not advertise any prefixes.
1863          */
1864         if (pr == NULL) {
1865                 TAILQ_FOREACH(dr, &V_nd6_defrouter, dr_entry) {
1866                         struct nd_prefix *pr0;
1867
1868                         LIST_FOREACH(pr0, &V_nd_prefix, ndpr_entry) {
1869                                 if ((pfxrtr = pfxrtr_lookup(pr0, dr)) != NULL)
1870                                         break;
1871                         }
1872                         if (pfxrtr != NULL)
1873                                 break;
1874                 }
1875         }
1876         if (pr != NULL || (!TAILQ_EMPTY(&V_nd6_defrouter) && pfxrtr == NULL)) {
1877                 /*
1878                  * There is at least one prefix that has a reachable router,
1879                  * or at least a router which probably does not advertise
1880                  * any prefixes.  The latter would be the case when we move
1881                  * to a new link where we have a router that does not provide
1882                  * prefixes and we configure an address by hand.
1883                  * Detach prefixes which have no reachable advertising
1884                  * router, and attach other prefixes.
1885                  */
1886                 LIST_FOREACH(pr, &V_nd_prefix, ndpr_entry) {
1887                         /* XXX: a link-local prefix should never be detached */
1888                         if (IN6_IS_ADDR_LINKLOCAL(&pr->ndpr_prefix.sin6_addr) ||
1889                             pr->ndpr_raf_onlink == 0 ||
1890                             pr->ndpr_raf_auto == 0)
1891                                 continue;
1892
1893                         if ((pr->ndpr_stateflags & NDPRF_DETACHED) == 0 &&
1894                             find_pfxlist_reachable_router(pr) == NULL)
1895                                 pr->ndpr_stateflags |= NDPRF_DETACHED;
1896                         else if ((pr->ndpr_stateflags & NDPRF_DETACHED) != 0 &&
1897                             find_pfxlist_reachable_router(pr) != NULL)
1898                                 pr->ndpr_stateflags &= ~NDPRF_DETACHED;
1899                 }
1900         } else {
1901                 /* there is no prefix that has a reachable router */
1902                 LIST_FOREACH(pr, &V_nd_prefix, ndpr_entry) {
1903                         if (IN6_IS_ADDR_LINKLOCAL(&pr->ndpr_prefix.sin6_addr) ||
1904                             pr->ndpr_raf_onlink == 0 ||
1905                             pr->ndpr_raf_auto == 0)
1906                                 continue;
1907                         pr->ndpr_stateflags &= ~NDPRF_DETACHED;
1908                 }
1909         }
1910
1911         /*
1912          * Remove each interface route associated with a (just) detached
1913          * prefix, and reinstall the interface route for a (just) attached
1914          * prefix.  Note that all attempt of reinstallation does not
1915          * necessarily success, when a same prefix is shared among multiple
1916          * interfaces.  Such cases will be handled in nd6_prefix_onlink,
1917          * so we don't have to care about them.
1918          */
1919 restart:
1920         LIST_FOREACH(pr, &V_nd_prefix, ndpr_entry) {
1921                 char ip6buf[INET6_ADDRSTRLEN];
1922                 int e;
1923
1924                 if (IN6_IS_ADDR_LINKLOCAL(&pr->ndpr_prefix.sin6_addr) ||
1925                     pr->ndpr_raf_onlink == 0 ||
1926                     pr->ndpr_raf_auto == 0)
1927                         continue;
1928
1929                 flags = pr->ndpr_stateflags & (NDPRF_DETACHED | NDPRF_ONLINK);
1930                 if (flags == 0 || flags == (NDPRF_DETACHED | NDPRF_ONLINK)) {
1931                         genid = V_nd6_list_genid;
1932                         ND6_RUNLOCK();
1933                         if ((flags & NDPRF_ONLINK) != 0 &&
1934                             (e = nd6_prefix_offlink(pr)) != 0) {
1935                                 nd6log((LOG_ERR,
1936                                     "%s: failed to make %s/%d offlink "
1937                                     "(errno=%d)\n", __func__, 
1938                                     ip6_sprintf(ip6buf,
1939                                             &pr->ndpr_prefix.sin6_addr),
1940                                             pr->ndpr_plen, e));
1941                         } else if ((flags & NDPRF_ONLINK) == 0 &&
1942                             (e = nd6_prefix_onlink(pr)) != 0) {
1943                                 nd6log((LOG_ERR,
1944                                     "%s: failed to make %s/%d onlink "
1945                                     "(errno=%d)\n", __func__,
1946                                     ip6_sprintf(ip6buf,
1947                                             &pr->ndpr_prefix.sin6_addr),
1948                                             pr->ndpr_plen, e));
1949                         }
1950                         ND6_RLOCK();
1951                         if (genid != V_nd6_list_genid)
1952                                 goto restart;
1953                 }
1954         }
1955
1956         /*
1957          * Changes on the prefix status might affect address status as well.
1958          * Make sure that all addresses derived from an attached prefix are
1959          * attached, and that all addresses derived from a detached prefix are
1960          * detached.  Note, however, that a manually configured address should
1961          * always be attached.
1962          * The precise detection logic is same as the one for prefixes.
1963          */
1964         IN6_IFADDR_RLOCK(&in6_ifa_tracker);
1965         CK_STAILQ_FOREACH(ifa, &V_in6_ifaddrhead, ia_link) {
1966                 if (!(ifa->ia6_flags & IN6_IFF_AUTOCONF))
1967                         continue;
1968
1969                 if (ifa->ia6_ndpr == NULL) {
1970                         /*
1971                          * This can happen when we first configure the address
1972                          * (i.e. the address exists, but the prefix does not).
1973                          * XXX: complicated relationships...
1974                          */
1975                         continue;
1976                 }
1977
1978                 if (find_pfxlist_reachable_router(ifa->ia6_ndpr))
1979                         break;
1980         }
1981         if (ifa) {
1982                 CK_STAILQ_FOREACH(ifa, &V_in6_ifaddrhead, ia_link) {
1983                         if ((ifa->ia6_flags & IN6_IFF_AUTOCONF) == 0)
1984                                 continue;
1985
1986                         if (ifa->ia6_ndpr == NULL) /* XXX: see above. */
1987                                 continue;
1988
1989                         if (find_pfxlist_reachable_router(ifa->ia6_ndpr)) {
1990                                 if (ifa->ia6_flags & IN6_IFF_DETACHED) {
1991                                         ifa->ia6_flags &= ~IN6_IFF_DETACHED;
1992                                         ifa->ia6_flags |= IN6_IFF_TENTATIVE;
1993                                         nd6_dad_start((struct ifaddr *)ifa, 0);
1994                                 }
1995                         } else {
1996                                 ifa->ia6_flags |= IN6_IFF_DETACHED;
1997                         }
1998                 }
1999         } else {
2000                 CK_STAILQ_FOREACH(ifa, &V_in6_ifaddrhead, ia_link) {
2001                         if ((ifa->ia6_flags & IN6_IFF_AUTOCONF) == 0)
2002                                 continue;
2003
2004                         if (ifa->ia6_flags & IN6_IFF_DETACHED) {
2005                                 ifa->ia6_flags &= ~IN6_IFF_DETACHED;
2006                                 ifa->ia6_flags |= IN6_IFF_TENTATIVE;
2007                                 /* Do we need a delay in this case? */
2008                                 nd6_dad_start((struct ifaddr *)ifa, 0);
2009                         }
2010                 }
2011         }
2012         IN6_IFADDR_RUNLOCK(&in6_ifa_tracker);
2013         ND6_RUNLOCK();
2014         ND6_ONLINK_UNLOCK();
2015 }
2016
2017 static int
2018 nd6_prefix_onlink_rtrequest(struct nd_prefix *pr, struct ifaddr *ifa)
2019 {
2020         struct sockaddr_dl_short sdl;
2021         struct sockaddr_in6 mask6;
2022         u_long rtflags;
2023         int error, a_failure, fibnum, maxfib;
2024
2025         bzero(&mask6, sizeof(mask6));
2026         mask6.sin6_len = sizeof(mask6);
2027         mask6.sin6_addr = pr->ndpr_mask;
2028         rtflags = (ifa->ifa_flags & ~IFA_RTSELF) | RTF_UP;
2029
2030         bzero(&sdl, sizeof(struct sockaddr_dl_short));
2031         sdl.sdl_len = sizeof(struct sockaddr_dl_short);
2032         sdl.sdl_family = AF_LINK;
2033         sdl.sdl_type = ifa->ifa_ifp->if_type;
2034         sdl.sdl_index = ifa->ifa_ifp->if_index;
2035
2036         if(V_rt_add_addr_allfibs) {
2037                 fibnum = 0;
2038                 maxfib = rt_numfibs;
2039         } else {
2040                 fibnum = ifa->ifa_ifp->if_fib;
2041                 maxfib = fibnum + 1;
2042         }
2043         a_failure = 0;
2044         for (; fibnum < maxfib; fibnum++) {
2045                 struct rt_addrinfo info;
2046                 struct rib_cmd_info rc;
2047
2048                 bzero((caddr_t)&info, sizeof(info));
2049                 info.rti_flags = rtflags;
2050                 info.rti_info[RTAX_DST] = (struct sockaddr *)&pr->ndpr_prefix;
2051                 info.rti_info[RTAX_GATEWAY] = (struct sockaddr *)&sdl;
2052                 info.rti_info[RTAX_NETMASK] = (struct sockaddr *)&mask6;
2053
2054                 NET_EPOCH_ASSERT();
2055                 error = rib_action(fibnum, RTM_ADD, &info, &rc);
2056                 if (error != 0) {
2057                         char ip6buf[INET6_ADDRSTRLEN];
2058                         char ip6bufg[INET6_ADDRSTRLEN];
2059                         char ip6bufm[INET6_ADDRSTRLEN];
2060                         struct sockaddr_in6 *sin6;
2061
2062                         sin6 = (struct sockaddr_in6 *)ifa->ifa_addr;
2063                         nd6log((LOG_ERR, "%s: failed to add "
2064                             "route for a prefix (%s/%d) on %s, gw=%s, mask=%s, "
2065                             "flags=%lx errno = %d\n", __func__,
2066                             ip6_sprintf(ip6buf, &pr->ndpr_prefix.sin6_addr),
2067                             pr->ndpr_plen, if_name(pr->ndpr_ifp),
2068                             ip6_sprintf(ip6bufg, &sin6->sin6_addr),
2069                             ip6_sprintf(ip6bufm, &mask6.sin6_addr),
2070                             rtflags, error));
2071
2072                         /* Save last error to return, see rtinit(). */
2073                         a_failure = error;
2074                         continue;
2075                 }
2076
2077                 pr->ndpr_stateflags |= NDPRF_ONLINK;
2078                 rt_routemsg(RTM_ADD, rc.rc_rt, pr->ndpr_ifp, 0, fibnum);
2079         }
2080
2081         /* Return the last error we got. */
2082         return (a_failure);
2083 }
2084
2085 static int
2086 nd6_prefix_onlink(struct nd_prefix *pr)
2087 {
2088         struct epoch_tracker et;
2089         struct ifaddr *ifa;
2090         struct ifnet *ifp = pr->ndpr_ifp;
2091         struct nd_prefix *opr;
2092         char ip6buf[INET6_ADDRSTRLEN];
2093         int error;
2094
2095         ND6_ONLINK_LOCK_ASSERT();
2096         ND6_UNLOCK_ASSERT();
2097
2098         if ((pr->ndpr_stateflags & NDPRF_ONLINK) != 0)
2099                 return (EEXIST);
2100
2101         /*
2102          * Add the interface route associated with the prefix.  Before
2103          * installing the route, check if there's the same prefix on another
2104          * interface, and the prefix has already installed the interface route.
2105          * Although such a configuration is expected to be rare, we explicitly
2106          * allow it.
2107          */
2108         ND6_RLOCK();
2109         LIST_FOREACH(opr, &V_nd_prefix, ndpr_entry) {
2110                 if (opr == pr)
2111                         continue;
2112
2113                 if ((opr->ndpr_stateflags & NDPRF_ONLINK) == 0)
2114                         continue;
2115
2116                 if (!V_rt_add_addr_allfibs &&
2117                     opr->ndpr_ifp->if_fib != pr->ndpr_ifp->if_fib)
2118                         continue;
2119
2120                 if (opr->ndpr_plen == pr->ndpr_plen &&
2121                     in6_are_prefix_equal(&pr->ndpr_prefix.sin6_addr,
2122                     &opr->ndpr_prefix.sin6_addr, pr->ndpr_plen)) {
2123                         ND6_RUNLOCK();
2124                         return (0);
2125                 }
2126         }
2127         ND6_RUNLOCK();
2128
2129         /*
2130          * We prefer link-local addresses as the associated interface address.
2131          */
2132         /* search for a link-local addr */
2133         NET_EPOCH_ENTER(et);
2134         ifa = (struct ifaddr *)in6ifa_ifpforlinklocal(ifp,
2135             IN6_IFF_NOTREADY | IN6_IFF_ANYCAST);
2136         if (ifa == NULL) {
2137                 /* XXX: freebsd does not have ifa_ifwithaf */
2138                 CK_STAILQ_FOREACH(ifa, &ifp->if_addrhead, ifa_link) {
2139                         if (ifa->ifa_addr->sa_family == AF_INET6) {
2140                                 ifa_ref(ifa);
2141                                 break;
2142                         }
2143                 }
2144                 /* should we care about ia6_flags? */
2145         }
2146         if (ifa == NULL) {
2147                 /*
2148                  * This can still happen, when, for example, we receive an RA
2149                  * containing a prefix with the L bit set and the A bit clear,
2150                  * after removing all IPv6 addresses on the receiving
2151                  * interface.  This should, of course, be rare though.
2152                  */
2153                 nd6log((LOG_NOTICE,
2154                     "%s: failed to find any ifaddr to add route for a "
2155                     "prefix(%s/%d) on %s\n", __func__,
2156                     ip6_sprintf(ip6buf, &pr->ndpr_prefix.sin6_addr),
2157                     pr->ndpr_plen, if_name(ifp)));
2158                 error = 0;
2159         } else {
2160                 error = nd6_prefix_onlink_rtrequest(pr, ifa);
2161                 ifa_free(ifa);
2162         }
2163         NET_EPOCH_EXIT(et);
2164
2165         return (error);
2166 }
2167
2168 int
2169 nd6_prefix_offlink(struct nd_prefix *pr)
2170 {
2171         int error = 0;
2172         struct ifnet *ifp = pr->ndpr_ifp;
2173         struct nd_prefix *opr;
2174         struct sockaddr_in6 sa6, mask6;
2175         char ip6buf[INET6_ADDRSTRLEN];
2176         uint64_t genid;
2177         int fibnum, maxfib, a_failure;
2178         struct epoch_tracker et;
2179
2180         ND6_ONLINK_LOCK_ASSERT();
2181         ND6_UNLOCK_ASSERT();
2182
2183         if ((pr->ndpr_stateflags & NDPRF_ONLINK) == 0)
2184                 return (EEXIST);
2185
2186         bzero(&sa6, sizeof(sa6));
2187         sa6.sin6_family = AF_INET6;
2188         sa6.sin6_len = sizeof(sa6);
2189         bcopy(&pr->ndpr_prefix.sin6_addr, &sa6.sin6_addr,
2190             sizeof(struct in6_addr));
2191         bzero(&mask6, sizeof(mask6));
2192         mask6.sin6_family = AF_INET6;
2193         mask6.sin6_len = sizeof(sa6);
2194         bcopy(&pr->ndpr_mask, &mask6.sin6_addr, sizeof(struct in6_addr));
2195
2196         if (V_rt_add_addr_allfibs) {
2197                 fibnum = 0;
2198                 maxfib = rt_numfibs;
2199         } else {
2200                 fibnum = ifp->if_fib;
2201                 maxfib = fibnum + 1;
2202         }
2203
2204         a_failure = 0;
2205         NET_EPOCH_ENTER(et);
2206         for (; fibnum < maxfib; fibnum++) {
2207                 struct rt_addrinfo info;
2208                 struct rib_cmd_info rc;
2209
2210                 bzero((caddr_t)&info, sizeof(info));
2211                 info.rti_flags = RTF_GATEWAY;
2212                 info.rti_info[RTAX_DST] = (struct sockaddr *)&sa6;
2213                 info.rti_info[RTAX_GATEWAY] = NULL;
2214                 info.rti_info[RTAX_NETMASK] = (struct sockaddr *)&mask6;
2215
2216                 NET_EPOCH_ASSERT();
2217                 error = rib_action(fibnum, RTM_DELETE, &info, &rc);
2218                 if (error != 0) {
2219                         /* Save last error to return, see rtinit(). */
2220                         a_failure = error;
2221                         continue;
2222                 }
2223
2224                 /* report route deletion to the routing socket. */
2225                 rt_routemsg(RTM_DELETE, rc.rc_rt, ifp, 0, fibnum);
2226         }
2227         NET_EPOCH_EXIT(et);
2228         error = a_failure;
2229         a_failure = 1;
2230         if (error == 0) {
2231                 pr->ndpr_stateflags &= ~NDPRF_ONLINK;
2232
2233                 /*
2234                  * There might be the same prefix on another interface,
2235                  * the prefix which could not be on-link just because we have
2236                  * the interface route (see comments in nd6_prefix_onlink).
2237                  * If there's one, try to make the prefix on-link on the
2238                  * interface.
2239                  */
2240                 ND6_RLOCK();
2241 restart:
2242                 LIST_FOREACH(opr, &V_nd_prefix, ndpr_entry) {
2243                         /*
2244                          * KAME specific: detached prefixes should not be
2245                          * on-link.
2246                          */
2247                         if (opr == pr || (opr->ndpr_stateflags &
2248                             (NDPRF_ONLINK | NDPRF_DETACHED)) != 0)
2249                                 continue;
2250
2251                         if (opr->ndpr_plen == pr->ndpr_plen &&
2252                             in6_are_prefix_equal(&pr->ndpr_prefix.sin6_addr,
2253                             &opr->ndpr_prefix.sin6_addr, pr->ndpr_plen)) {
2254                                 int e;
2255
2256                                 genid = V_nd6_list_genid;
2257                                 ND6_RUNLOCK();
2258                                 if ((e = nd6_prefix_onlink(opr)) != 0) {
2259                                         nd6log((LOG_ERR,
2260                                             "%s: failed to recover a prefix "
2261                                             "%s/%d from %s to %s (errno=%d)\n",
2262                                             __func__, ip6_sprintf(ip6buf,
2263                                                 &opr->ndpr_prefix.sin6_addr),
2264                                             opr->ndpr_plen, if_name(ifp),
2265                                             if_name(opr->ndpr_ifp), e));
2266                                 } else
2267                                         a_failure = 0;
2268                                 ND6_RLOCK();
2269                                 if (genid != V_nd6_list_genid)
2270                                         goto restart;
2271                         }
2272                 }
2273                 ND6_RUNLOCK();
2274         } else {
2275                 /* XXX: can we still set the NDPRF_ONLINK flag? */
2276                 nd6log((LOG_ERR,
2277                     "%s: failed to delete route: %s/%d on %s (errno=%d)\n",
2278                     __func__, ip6_sprintf(ip6buf, &sa6.sin6_addr),
2279                     pr->ndpr_plen, if_name(ifp), error));
2280         }
2281
2282         if (a_failure)
2283                 lltable_prefix_free(AF_INET6, (struct sockaddr *)&sa6,
2284                     (struct sockaddr *)&mask6, LLE_STATIC);
2285
2286         return (error);
2287 }
2288
2289 /*
2290  * ia0 - corresponding public address
2291  */
2292 int
2293 in6_tmpifadd(const struct in6_ifaddr *ia0, int forcegen, int delay)
2294 {
2295         struct ifnet *ifp = ia0->ia_ifa.ifa_ifp;
2296         struct in6_ifaddr *newia;
2297         struct in6_aliasreq ifra;
2298         int error;
2299         int trylimit = 3;       /* XXX: adhoc value */
2300         int updateflags;
2301         u_int32_t randid[2];
2302         time_t vltime0, pltime0;
2303
2304         in6_prepare_ifra(&ifra, &ia0->ia_addr.sin6_addr,
2305             &ia0->ia_prefixmask.sin6_addr);
2306
2307         ifra.ifra_addr = ia0->ia_addr;  /* XXX: do we need this ? */
2308         /* clear the old IFID */
2309         IN6_MASK_ADDR(&ifra.ifra_addr.sin6_addr,
2310             &ifra.ifra_prefixmask.sin6_addr);
2311
2312   again:
2313         if (in6_get_tmpifid(ifp, (u_int8_t *)randid,
2314             (const u_int8_t *)&ia0->ia_addr.sin6_addr.s6_addr[8], forcegen)) {
2315                 nd6log((LOG_NOTICE, "%s: failed to find a good random IFID\n",
2316                     __func__));
2317                 return (EINVAL);
2318         }
2319         ifra.ifra_addr.sin6_addr.s6_addr32[2] |=
2320             (randid[0] & ~(ifra.ifra_prefixmask.sin6_addr.s6_addr32[2]));
2321         ifra.ifra_addr.sin6_addr.s6_addr32[3] |=
2322             (randid[1] & ~(ifra.ifra_prefixmask.sin6_addr.s6_addr32[3]));
2323
2324         /*
2325          * in6_get_tmpifid() quite likely provided a unique interface ID.
2326          * However, we may still have a chance to see collision, because
2327          * there may be a time lag between generation of the ID and generation
2328          * of the address.  So, we'll do one more sanity check.
2329          */
2330
2331         if (in6_localip(&ifra.ifra_addr.sin6_addr) != 0) {
2332                 if (trylimit-- > 0) {
2333                         forcegen = 1;
2334                         goto again;
2335                 }
2336
2337                 /* Give up.  Something strange should have happened.  */
2338                 nd6log((LOG_NOTICE, "%s: failed to find a unique random IFID\n",
2339                     __func__));
2340                 return (EEXIST);
2341         }
2342
2343         /*
2344          * The Valid Lifetime is the lower of the Valid Lifetime of the
2345          * public address or TEMP_VALID_LIFETIME.
2346          * The Preferred Lifetime is the lower of the Preferred Lifetime
2347          * of the public address or TEMP_PREFERRED_LIFETIME -
2348          * DESYNC_FACTOR.
2349          */
2350         if (ia0->ia6_lifetime.ia6t_vltime != ND6_INFINITE_LIFETIME) {
2351                 vltime0 = IFA6_IS_INVALID(ia0) ? 0 :
2352                     (ia0->ia6_lifetime.ia6t_vltime -
2353                     (time_uptime - ia0->ia6_updatetime));
2354                 if (vltime0 > V_ip6_temp_valid_lifetime)
2355                         vltime0 = V_ip6_temp_valid_lifetime;
2356         } else
2357                 vltime0 = V_ip6_temp_valid_lifetime;
2358         if (ia0->ia6_lifetime.ia6t_pltime != ND6_INFINITE_LIFETIME) {
2359                 pltime0 = IFA6_IS_DEPRECATED(ia0) ? 0 :
2360                     (ia0->ia6_lifetime.ia6t_pltime -
2361                     (time_uptime - ia0->ia6_updatetime));
2362                 if (pltime0 > V_ip6_temp_preferred_lifetime - V_ip6_desync_factor){
2363                         pltime0 = V_ip6_temp_preferred_lifetime -
2364                             V_ip6_desync_factor;
2365                 }
2366         } else
2367                 pltime0 = V_ip6_temp_preferred_lifetime - V_ip6_desync_factor;
2368         ifra.ifra_lifetime.ia6t_vltime = vltime0;
2369         ifra.ifra_lifetime.ia6t_pltime = pltime0;
2370
2371         /*
2372          * A temporary address is created only if this calculated Preferred
2373          * Lifetime is greater than REGEN_ADVANCE time units.
2374          */
2375         if (ifra.ifra_lifetime.ia6t_pltime <= V_ip6_temp_regen_advance)
2376                 return (0);
2377
2378         /* XXX: scope zone ID? */
2379
2380         ifra.ifra_flags |= (IN6_IFF_AUTOCONF|IN6_IFF_TEMPORARY);
2381
2382         /* allocate ifaddr structure, link into chain, etc. */
2383         updateflags = 0;
2384         if (delay)
2385                 updateflags |= IN6_IFAUPDATE_DADDELAY;
2386         if ((error = in6_update_ifa(ifp, &ifra, NULL, updateflags)) != 0)
2387                 return (error);
2388
2389         newia = in6ifa_ifpwithaddr(ifp, &ifra.ifra_addr.sin6_addr);
2390         if (newia == NULL) {    /* XXX: can it happen? */
2391                 nd6log((LOG_ERR,
2392                     "%s: ifa update succeeded, but we got no ifaddr\n",
2393                     __func__));
2394                 return (EINVAL); /* XXX */
2395         }
2396         newia->ia6_ndpr = ia0->ia6_ndpr;
2397         newia->ia6_ndpr->ndpr_addrcnt++;
2398         ifa_free(&newia->ia_ifa);
2399
2400         /*
2401          * A newly added address might affect the status of other addresses.
2402          * XXX: when the temporary address is generated with a new public
2403          * address, the onlink check is redundant.  However, it would be safe
2404          * to do the check explicitly everywhere a new address is generated,
2405          * and, in fact, we surely need the check when we create a new
2406          * temporary address due to deprecation of an old temporary address.
2407          */
2408         pfxlist_onlink_check();
2409
2410         return (0);
2411 }
2412
2413 static int
2414 rt6_deleteroute(const struct rtentry *rt, const struct nhop_object *nh,
2415     void *arg)
2416 {
2417         struct in6_addr *gate = (struct in6_addr *)arg;
2418         int nh_rt_flags;
2419
2420         if (nh->gw_sa.sa_family != AF_INET6)
2421                 return (0);
2422
2423         if (!IN6_ARE_ADDR_EQUAL(gate, &nh->gw6_sa.sin6_addr)) {
2424                 return (0);
2425         }
2426
2427         /*
2428          * Do not delete a static route.
2429          * XXX: this seems to be a bit ad-hoc. Should we consider the
2430          * 'cloned' bit instead?
2431          */
2432         nh_rt_flags = nhop_get_rtflags(nh);
2433         if ((nh_rt_flags & RTF_STATIC) != 0)
2434                 return (0);
2435
2436         /*
2437          * We delete only host route. This means, in particular, we don't
2438          * delete default route.
2439          */
2440         if ((nh_rt_flags & RTF_HOST) == 0)
2441                 return (0);
2442
2443         return (1);
2444 #undef SIN6
2445 }
2446
2447 /*
2448  * Delete all the routing table entries that use the specified gateway.
2449  * XXX: this function causes search through all entries of routing table, so
2450  * it shouldn't be called when acting as a router.
2451  */
2452 void
2453 rt6_flush(struct in6_addr *gateway, struct ifnet *ifp)
2454 {
2455
2456         /* We'll care only link-local addresses */
2457         if (!IN6_IS_ADDR_LINKLOCAL(gateway))
2458                 return;
2459
2460         /* XXX Do we really need to walk any but the default FIB? */
2461         rt_foreach_fib_walk_del(AF_INET6, rt6_deleteroute, (void *)gateway);
2462 }
2463
2464 int
2465 nd6_setdefaultiface(int ifindex)
2466 {
2467         int error = 0;
2468
2469         if (ifindex < 0 || V_if_index < ifindex)
2470                 return (EINVAL);
2471         if (ifindex != 0 && !ifnet_byindex(ifindex))
2472                 return (EINVAL);
2473
2474         if (V_nd6_defifindex != ifindex) {
2475                 V_nd6_defifindex = ifindex;
2476                 if (V_nd6_defifindex > 0)
2477                         V_nd6_defifp = ifnet_byindex(V_nd6_defifindex);
2478                 else
2479                         V_nd6_defifp = NULL;
2480
2481                 /*
2482                  * Our current implementation assumes one-to-one maping between
2483                  * interfaces and links, so it would be natural to use the
2484                  * default interface as the default link.
2485                  */
2486                 scope6_setdefault(V_nd6_defifp);
2487         }
2488
2489         return (error);
2490 }
2491
2492 bool
2493 nd6_defrouter_list_empty(void)
2494 {
2495
2496         return (TAILQ_EMPTY(&V_nd6_defrouter));
2497 }
2498
2499 void
2500 nd6_defrouter_timer(void)
2501 {
2502         struct nd_defrouter *dr, *ndr;
2503         struct nd6_drhead drq;
2504
2505         TAILQ_INIT(&drq);
2506
2507         ND6_WLOCK();
2508         TAILQ_FOREACH_SAFE(dr, &V_nd6_defrouter, dr_entry, ndr)
2509                 if (dr->expire && dr->expire < time_uptime)
2510                         defrouter_unlink(dr, &drq);
2511         ND6_WUNLOCK();
2512
2513         while ((dr = TAILQ_FIRST(&drq)) != NULL) {
2514                 TAILQ_REMOVE(&drq, dr, dr_entry);
2515                 defrouter_del(dr);
2516         }
2517 }
2518
2519 /*
2520  * Nuke default router list entries toward ifp.
2521  * We defer removal of default router list entries that is installed in the
2522  * routing table, in order to keep additional side effects as small as possible.
2523  */
2524 void
2525 nd6_defrouter_purge(struct ifnet *ifp)
2526 {
2527         struct nd_defrouter *dr, *ndr;
2528         struct nd6_drhead drq;
2529
2530         TAILQ_INIT(&drq);
2531
2532         ND6_WLOCK();
2533         TAILQ_FOREACH_SAFE(dr, &V_nd6_defrouter, dr_entry, ndr) {
2534                 if (dr->installed)
2535                         continue;
2536                 if (dr->ifp == ifp)
2537                         defrouter_unlink(dr, &drq);
2538         }
2539         TAILQ_FOREACH_SAFE(dr, &V_nd6_defrouter, dr_entry, ndr) {
2540                 if (!dr->installed)
2541                         continue;
2542                 if (dr->ifp == ifp)
2543                         defrouter_unlink(dr, &drq);
2544         }
2545         ND6_WUNLOCK();
2546
2547         /* Delete the unlinked router objects. */
2548         while ((dr = TAILQ_FIRST(&drq)) != NULL) {
2549                 TAILQ_REMOVE(&drq, dr, dr_entry);
2550                 defrouter_del(dr);
2551         }
2552 }
2553
2554 void
2555 nd6_defrouter_flush_all(void)
2556 {
2557         struct nd_defrouter *dr;
2558         struct nd6_drhead drq;
2559
2560         TAILQ_INIT(&drq);
2561
2562         ND6_WLOCK();
2563         while ((dr = TAILQ_FIRST(&V_nd6_defrouter)) != NULL)
2564                 defrouter_unlink(dr, &drq);
2565         ND6_WUNLOCK();
2566
2567         while ((dr = TAILQ_FIRST(&drq)) != NULL) {
2568                 TAILQ_REMOVE(&drq, dr, dr_entry);
2569                 defrouter_del(dr);
2570         }
2571 }
2572
2573 void
2574 nd6_defrouter_init(void)
2575 {
2576
2577         TAILQ_INIT(&V_nd6_defrouter);
2578 }
2579
2580 static int
2581 nd6_sysctl_drlist(SYSCTL_HANDLER_ARGS)
2582 {
2583         struct in6_defrouter d;
2584         struct nd_defrouter *dr;
2585         int error;
2586
2587         if (req->newptr != NULL)
2588                 return (EPERM);
2589
2590         error = sysctl_wire_old_buffer(req, 0);
2591         if (error != 0)
2592                 return (error);
2593
2594         bzero(&d, sizeof(d));
2595         d.rtaddr.sin6_family = AF_INET6;
2596         d.rtaddr.sin6_len = sizeof(d.rtaddr);
2597
2598         ND6_RLOCK();
2599         TAILQ_FOREACH(dr, &V_nd6_defrouter, dr_entry) {
2600                 d.rtaddr.sin6_addr = dr->rtaddr;
2601                 error = sa6_recoverscope(&d.rtaddr);
2602                 if (error != 0)
2603                         break;
2604                 d.flags = dr->raflags;
2605                 d.rtlifetime = dr->rtlifetime;
2606                 d.expire = dr->expire + (time_second - time_uptime);
2607                 d.if_index = dr->ifp->if_index;
2608                 error = SYSCTL_OUT(req, &d, sizeof(d));
2609                 if (error != 0)
2610                         break;
2611         }
2612         ND6_RUNLOCK();
2613         return (error);
2614 }
2615 SYSCTL_PROC(_net_inet6_icmp6, ICMPV6CTL_ND6_DRLIST, nd6_drlist,
2616         CTLTYPE_OPAQUE | CTLFLAG_RD | CTLFLAG_MPSAFE,
2617         NULL, 0, nd6_sysctl_drlist, "S,in6_defrouter",
2618         "NDP default router list");