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