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