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