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