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