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