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