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