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