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