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