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