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