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