xref: /freebsd/sys/netinet6/nd6_rtr.c (revision 1f4bcc459a76b7aa664f3fd557684cd0ba6da352)
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.flags  = 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 	return;
507 }
508 
509 struct nd_defrouter *
510 defrouter_lookup(struct in6_addr *addr, struct ifnet *ifp)
511 {
512 	struct nd_defrouter *dr;
513 
514 	TAILQ_FOREACH(dr, &V_nd_defrouter, dr_entry) {
515 		if (dr->ifp == ifp && IN6_ARE_ADDR_EQUAL(addr, &dr->rtaddr))
516 			return (dr);
517 	}
518 
519 	return (NULL);		/* search failed */
520 }
521 
522 /*
523  * Remove the default route for a given router.
524  * This is just a subroutine function for defrouter_select(), and should
525  * not be called from anywhere else.
526  */
527 static void
528 defrouter_delreq(struct nd_defrouter *dr)
529 {
530 	struct sockaddr_in6 def, mask, gate;
531 	struct rtentry *oldrt = NULL;
532 
533 	bzero(&def, sizeof(def));
534 	bzero(&mask, sizeof(mask));
535 	bzero(&gate, sizeof(gate));
536 
537 	def.sin6_len = mask.sin6_len = gate.sin6_len =
538 	    sizeof(struct sockaddr_in6);
539 	def.sin6_family = gate.sin6_family = AF_INET6;
540 	gate.sin6_addr = dr->rtaddr;
541 
542 	in6_rtrequest(RTM_DELETE, (struct sockaddr *)&def,
543 	    (struct sockaddr *)&gate,
544 	    (struct sockaddr *)&mask, RTF_GATEWAY, &oldrt, RT_DEFAULT_FIB);
545 	if (oldrt) {
546 		nd6_rtmsg(RTM_DELETE, oldrt);
547 		RTFREE(oldrt);
548 	}
549 
550 	dr->installed = 0;
551 }
552 
553 /*
554  * remove all default routes from default router list
555  */
556 void
557 defrouter_reset(void)
558 {
559 	struct nd_defrouter *dr;
560 
561 	TAILQ_FOREACH(dr, &V_nd_defrouter, dr_entry)
562 		defrouter_delreq(dr);
563 
564 	/*
565 	 * XXX should we also nuke any default routers in the kernel, by
566 	 * going through them by rtalloc1()?
567 	 */
568 }
569 
570 void
571 defrtrlist_del(struct nd_defrouter *dr)
572 {
573 	struct nd_defrouter *deldr = NULL;
574 	struct nd_prefix *pr;
575 
576 	/*
577 	 * Flush all the routing table entries that use the router
578 	 * as a next hop.
579 	 */
580 	if (ND_IFINFO(dr->ifp)->flags & ND6_IFF_ACCEPT_RTADV)
581 		rt6_flush(&dr->rtaddr, dr->ifp);
582 
583 	if (dr->installed) {
584 		deldr = dr;
585 		defrouter_delreq(dr);
586 	}
587 	TAILQ_REMOVE(&V_nd_defrouter, dr, dr_entry);
588 
589 	/*
590 	 * Also delete all the pointers to the router in each prefix lists.
591 	 */
592 	LIST_FOREACH(pr, &V_nd_prefix, ndpr_entry) {
593 		struct nd_pfxrouter *pfxrtr;
594 		if ((pfxrtr = pfxrtr_lookup(pr, dr)) != NULL)
595 			pfxrtr_del(pfxrtr);
596 	}
597 	pfxlist_onlink_check();
598 
599 	/*
600 	 * If the router is the primary one, choose a new one.
601 	 * Note that defrouter_select() will remove the current gateway
602 	 * from the routing table.
603 	 */
604 	if (deldr)
605 		defrouter_select();
606 
607 	free(dr, M_IP6NDP);
608 }
609 
610 /*
611  * Default Router Selection according to Section 6.3.6 of RFC 2461 and
612  * draft-ietf-ipngwg-router-selection:
613  * 1) Routers that are reachable or probably reachable should be preferred.
614  *    If we have more than one (probably) reachable router, prefer ones
615  *    with the highest router preference.
616  * 2) When no routers on the list are known to be reachable or
617  *    probably reachable, routers SHOULD be selected in a round-robin
618  *    fashion, regardless of router preference values.
619  * 3) If the Default Router List is empty, assume that all
620  *    destinations are on-link.
621  *
622  * We assume nd_defrouter is sorted by router preference value.
623  * Since the code below covers both with and without router preference cases,
624  * we do not need to classify the cases by ifdef.
625  *
626  * At this moment, we do not try to install more than one default router,
627  * even when the multipath routing is available, because we're not sure about
628  * the benefits for stub hosts comparing to the risk of making the code
629  * complicated and the possibility of introducing bugs.
630  */
631 void
632 defrouter_select(void)
633 {
634 	struct nd_defrouter *dr, *selected_dr = NULL, *installed_dr = NULL;
635 	struct llentry *ln = NULL;
636 
637 	/*
638 	 * Let's handle easy case (3) first:
639 	 * If default router list is empty, there's nothing to be done.
640 	 */
641 	if (TAILQ_EMPTY(&V_nd_defrouter))
642 		return;
643 
644 	/*
645 	 * Search for a (probably) reachable router from the list.
646 	 * We just pick up the first reachable one (if any), assuming that
647 	 * the ordering rule of the list described in defrtrlist_update().
648 	 */
649 	TAILQ_FOREACH(dr, &V_nd_defrouter, dr_entry) {
650 		IF_AFDATA_RLOCK(dr->ifp);
651 		if (selected_dr == NULL &&
652 		    (ln = nd6_lookup(&dr->rtaddr, 0, dr->ifp)) &&
653 		    ND6_IS_LLINFO_PROBREACH(ln)) {
654 			selected_dr = dr;
655 		}
656 		IF_AFDATA_RUNLOCK(dr->ifp);
657 		if (ln != NULL) {
658 			LLE_RUNLOCK(ln);
659 			ln = NULL;
660 		}
661 
662 		if (dr->installed && installed_dr == NULL)
663 			installed_dr = dr;
664 		else if (dr->installed && installed_dr) {
665 			/* this should not happen.  warn for diagnosis. */
666 			log(LOG_ERR, "defrouter_select: more than one router"
667 			    " is installed\n");
668 		}
669 	}
670 	/*
671 	 * If none of the default routers was found to be reachable,
672 	 * round-robin the list regardless of preference.
673 	 * Otherwise, if we have an installed router, check if the selected
674 	 * (reachable) router should really be preferred to the installed one.
675 	 * We only prefer the new router when the old one is not reachable
676 	 * or when the new one has a really higher preference value.
677 	 */
678 	if (selected_dr == NULL) {
679 		if (installed_dr == NULL || !TAILQ_NEXT(installed_dr, dr_entry))
680 			selected_dr = TAILQ_FIRST(&V_nd_defrouter);
681 		else
682 			selected_dr = TAILQ_NEXT(installed_dr, dr_entry);
683 	} else if (installed_dr) {
684 		IF_AFDATA_RLOCK(installed_dr->ifp);
685 		if ((ln = nd6_lookup(&installed_dr->rtaddr, 0, installed_dr->ifp)) &&
686 		    ND6_IS_LLINFO_PROBREACH(ln) &&
687 		    rtpref(selected_dr) <= rtpref(installed_dr)) {
688 			selected_dr = installed_dr;
689 		}
690 		IF_AFDATA_RUNLOCK(installed_dr->ifp);
691 		if (ln != NULL)
692 			LLE_RUNLOCK(ln);
693 	}
694 
695 	/*
696 	 * If the selected router is different than the installed one,
697 	 * remove the installed router and install the selected one.
698 	 * Note that the selected router is never NULL here.
699 	 */
700 	if (installed_dr != selected_dr) {
701 		if (installed_dr)
702 			defrouter_delreq(installed_dr);
703 		defrouter_addreq(selected_dr);
704 	}
705 
706 	return;
707 }
708 
709 /*
710  * for default router selection
711  * regards router-preference field as a 2-bit signed integer
712  */
713 static int
714 rtpref(struct nd_defrouter *dr)
715 {
716 	switch (dr->flags & ND_RA_FLAG_RTPREF_MASK) {
717 	case ND_RA_FLAG_RTPREF_HIGH:
718 		return (RTPREF_HIGH);
719 	case ND_RA_FLAG_RTPREF_MEDIUM:
720 	case ND_RA_FLAG_RTPREF_RSV:
721 		return (RTPREF_MEDIUM);
722 	case ND_RA_FLAG_RTPREF_LOW:
723 		return (RTPREF_LOW);
724 	default:
725 		/*
726 		 * This case should never happen.  If it did, it would mean a
727 		 * serious bug of kernel internal.  We thus always bark here.
728 		 * Or, can we even panic?
729 		 */
730 		log(LOG_ERR, "rtpref: impossible RA flag %x\n", dr->flags);
731 		return (RTPREF_INVALID);
732 	}
733 	/* NOTREACHED */
734 }
735 
736 static struct nd_defrouter *
737 defrtrlist_update(struct nd_defrouter *new)
738 {
739 	struct nd_defrouter *dr, *n;
740 
741 	if ((dr = defrouter_lookup(&new->rtaddr, new->ifp)) != NULL) {
742 		/* entry exists */
743 		if (new->rtlifetime == 0) {
744 			defrtrlist_del(dr);
745 			dr = NULL;
746 		} else {
747 			int oldpref = rtpref(dr);
748 
749 			/* override */
750 			dr->flags = new->flags; /* xxx flag check */
751 			dr->rtlifetime = new->rtlifetime;
752 			dr->expire = new->expire;
753 
754 			/*
755 			 * If the preference does not change, there's no need
756 			 * to sort the entries. Also make sure the selected
757 			 * router is still installed in the kernel.
758 			 */
759 			if (dr->installed && rtpref(new) == oldpref)
760 				return (dr);
761 
762 			/*
763 			 * preferred router may be changed, so relocate
764 			 * this router.
765 			 * XXX: calling TAILQ_REMOVE directly is a bad manner.
766 			 * However, since defrtrlist_del() has many side
767 			 * effects, we intentionally do so here.
768 			 * defrouter_select() below will handle routing
769 			 * changes later.
770 			 */
771 			TAILQ_REMOVE(&V_nd_defrouter, dr, dr_entry);
772 			n = dr;
773 			goto insert;
774 		}
775 		return (dr);
776 	}
777 
778 	/* entry does not exist */
779 	if (new->rtlifetime == 0)
780 		return (NULL);
781 
782 	n = (struct nd_defrouter *)malloc(sizeof(*n), M_IP6NDP, M_NOWAIT);
783 	if (n == NULL)
784 		return (NULL);
785 	bzero(n, sizeof(*n));
786 	*n = *new;
787 
788 insert:
789 	/*
790 	 * Insert the new router in the Default Router List;
791 	 * The Default Router List should be in the descending order
792 	 * of router-preferece.  Routers with the same preference are
793 	 * sorted in the arriving time order.
794 	 */
795 
796 	/* insert at the end of the group */
797 	TAILQ_FOREACH(dr, &V_nd_defrouter, dr_entry) {
798 		if (rtpref(n) > rtpref(dr))
799 			break;
800 	}
801 	if (dr)
802 		TAILQ_INSERT_BEFORE(dr, n, dr_entry);
803 	else
804 		TAILQ_INSERT_TAIL(&V_nd_defrouter, n, dr_entry);
805 
806 	defrouter_select();
807 
808 	return (n);
809 }
810 
811 static struct nd_pfxrouter *
812 pfxrtr_lookup(struct nd_prefix *pr, struct nd_defrouter *dr)
813 {
814 	struct nd_pfxrouter *search;
815 
816 	LIST_FOREACH(search, &pr->ndpr_advrtrs, pfr_entry) {
817 		if (search->router == dr)
818 			break;
819 	}
820 
821 	return (search);
822 }
823 
824 static void
825 pfxrtr_add(struct nd_prefix *pr, struct nd_defrouter *dr)
826 {
827 	struct nd_pfxrouter *new;
828 
829 	new = (struct nd_pfxrouter *)malloc(sizeof(*new), M_IP6NDP, M_NOWAIT);
830 	if (new == NULL)
831 		return;
832 	bzero(new, sizeof(*new));
833 	new->router = dr;
834 
835 	LIST_INSERT_HEAD(&pr->ndpr_advrtrs, new, pfr_entry);
836 
837 	pfxlist_onlink_check();
838 }
839 
840 static void
841 pfxrtr_del(struct nd_pfxrouter *pfr)
842 {
843 	LIST_REMOVE(pfr, pfr_entry);
844 	free(pfr, M_IP6NDP);
845 }
846 
847 struct nd_prefix *
848 nd6_prefix_lookup(struct nd_prefixctl *key)
849 {
850 	struct nd_prefix *search;
851 
852 	LIST_FOREACH(search, &V_nd_prefix, ndpr_entry) {
853 		if (key->ndpr_ifp == search->ndpr_ifp &&
854 		    key->ndpr_plen == search->ndpr_plen &&
855 		    in6_are_prefix_equal(&key->ndpr_prefix.sin6_addr,
856 		    &search->ndpr_prefix.sin6_addr, key->ndpr_plen)) {
857 			break;
858 		}
859 	}
860 
861 	return (search);
862 }
863 
864 int
865 nd6_prelist_add(struct nd_prefixctl *pr, struct nd_defrouter *dr,
866     struct nd_prefix **newp)
867 {
868 	struct nd_prefix *new = NULL;
869 	int error = 0;
870 	char ip6buf[INET6_ADDRSTRLEN];
871 
872 	new = (struct nd_prefix *)malloc(sizeof(*new), M_IP6NDP, M_NOWAIT);
873 	if (new == NULL)
874 		return(ENOMEM);
875 	bzero(new, sizeof(*new));
876 	new->ndpr_ifp = pr->ndpr_ifp;
877 	new->ndpr_prefix = pr->ndpr_prefix;
878 	new->ndpr_plen = pr->ndpr_plen;
879 	new->ndpr_vltime = pr->ndpr_vltime;
880 	new->ndpr_pltime = pr->ndpr_pltime;
881 	new->ndpr_flags = pr->ndpr_flags;
882 	if ((error = in6_init_prefix_ltimes(new)) != 0) {
883 		free(new, M_IP6NDP);
884 		return(error);
885 	}
886 	new->ndpr_lastupdate = time_uptime;
887 	if (newp != NULL)
888 		*newp = new;
889 
890 	/* initialization */
891 	LIST_INIT(&new->ndpr_advrtrs);
892 	in6_prefixlen2mask(&new->ndpr_mask, new->ndpr_plen);
893 	/* make prefix in the canonical form */
894 	IN6_MASK_ADDR(&new->ndpr_prefix.sin6_addr, &new->ndpr_mask);
895 
896 	/* link ndpr_entry to nd_prefix list */
897 	LIST_INSERT_HEAD(&V_nd_prefix, new, ndpr_entry);
898 
899 	/* ND_OPT_PI_FLAG_ONLINK processing */
900 	if (new->ndpr_raf_onlink) {
901 		int e;
902 
903 		if ((e = nd6_prefix_onlink(new)) != 0) {
904 			nd6log((LOG_ERR, "nd6_prelist_add: failed to make "
905 			    "the prefix %s/%d on-link on %s (errno=%d)\n",
906 			    ip6_sprintf(ip6buf, &pr->ndpr_prefix.sin6_addr),
907 			    pr->ndpr_plen, if_name(pr->ndpr_ifp), e));
908 			/* proceed anyway. XXX: is it correct? */
909 		}
910 	}
911 
912 	if (dr)
913 		pfxrtr_add(new, dr);
914 
915 	return 0;
916 }
917 
918 void
919 prelist_remove(struct nd_prefix *pr)
920 {
921 	struct nd_pfxrouter *pfr, *next;
922 	int e;
923 	char ip6buf[INET6_ADDRSTRLEN];
924 
925 	/* make sure to invalidate the prefix until it is really freed. */
926 	pr->ndpr_vltime = 0;
927 	pr->ndpr_pltime = 0;
928 
929 	/*
930 	 * Though these flags are now meaningless, we'd rather keep the value
931 	 * of pr->ndpr_raf_onlink and pr->ndpr_raf_auto not to confuse users
932 	 * when executing "ndp -p".
933 	 */
934 
935 	if ((pr->ndpr_stateflags & NDPRF_ONLINK) != 0 &&
936 	    (e = nd6_prefix_offlink(pr)) != 0) {
937 		nd6log((LOG_ERR, "prelist_remove: failed to make %s/%d offlink "
938 		    "on %s, errno=%d\n",
939 		    ip6_sprintf(ip6buf, &pr->ndpr_prefix.sin6_addr),
940 		    pr->ndpr_plen, if_name(pr->ndpr_ifp), e));
941 		/* what should we do? */
942 	}
943 
944 	if (pr->ndpr_refcnt > 0)
945 		return;		/* notice here? */
946 
947 	/* unlink ndpr_entry from nd_prefix list */
948 	LIST_REMOVE(pr, ndpr_entry);
949 
950 	/* free list of routers that adversed the prefix */
951 	LIST_FOREACH_SAFE(pfr, &pr->ndpr_advrtrs, pfr_entry, next) {
952 		free(pfr, M_IP6NDP);
953 	}
954 	free(pr, M_IP6NDP);
955 
956 	pfxlist_onlink_check();
957 }
958 
959 /*
960  * dr - may be NULL
961  */
962 
963 static int
964 prelist_update(struct nd_prefixctl *new, struct nd_defrouter *dr,
965     struct mbuf *m, int mcast)
966 {
967 	struct in6_ifaddr *ia6 = NULL, *ia6_match = NULL;
968 	struct ifaddr *ifa;
969 	struct ifnet *ifp = new->ndpr_ifp;
970 	struct nd_prefix *pr;
971 	int error = 0;
972 	int newprefix = 0;
973 	int auth;
974 	struct in6_addrlifetime lt6_tmp;
975 	char ip6buf[INET6_ADDRSTRLEN];
976 
977 	auth = 0;
978 	if (m) {
979 		/*
980 		 * Authenticity for NA consists authentication for
981 		 * both IP header and IP datagrams, doesn't it ?
982 		 */
983 #if defined(M_AUTHIPHDR) && defined(M_AUTHIPDGM)
984 		auth = ((m->m_flags & M_AUTHIPHDR) &&
985 		    (m->m_flags & M_AUTHIPDGM));
986 #endif
987 	}
988 
989 	if ((pr = nd6_prefix_lookup(new)) != NULL) {
990 		/*
991 		 * nd6_prefix_lookup() ensures that pr and new have the same
992 		 * prefix on a same interface.
993 		 */
994 
995 		/*
996 		 * Update prefix information.  Note that the on-link (L) bit
997 		 * and the autonomous (A) bit should NOT be changed from 1
998 		 * to 0.
999 		 */
1000 		if (new->ndpr_raf_onlink == 1)
1001 			pr->ndpr_raf_onlink = 1;
1002 		if (new->ndpr_raf_auto == 1)
1003 			pr->ndpr_raf_auto = 1;
1004 		if (new->ndpr_raf_onlink) {
1005 			pr->ndpr_vltime = new->ndpr_vltime;
1006 			pr->ndpr_pltime = new->ndpr_pltime;
1007 			(void)in6_init_prefix_ltimes(pr); /* XXX error case? */
1008 			pr->ndpr_lastupdate = time_uptime;
1009 		}
1010 
1011 		if (new->ndpr_raf_onlink &&
1012 		    (pr->ndpr_stateflags & NDPRF_ONLINK) == 0) {
1013 			int e;
1014 
1015 			if ((e = nd6_prefix_onlink(pr)) != 0) {
1016 				nd6log((LOG_ERR,
1017 				    "prelist_update: failed to make "
1018 				    "the prefix %s/%d on-link on %s "
1019 				    "(errno=%d)\n",
1020 				    ip6_sprintf(ip6buf,
1021 					    &pr->ndpr_prefix.sin6_addr),
1022 				    pr->ndpr_plen, if_name(pr->ndpr_ifp), e));
1023 				/* proceed anyway. XXX: is it correct? */
1024 			}
1025 		}
1026 
1027 		if (dr && pfxrtr_lookup(pr, dr) == NULL)
1028 			pfxrtr_add(pr, dr);
1029 	} else {
1030 		struct nd_prefix *newpr = NULL;
1031 
1032 		newprefix = 1;
1033 
1034 		if (new->ndpr_vltime == 0)
1035 			goto end;
1036 		if (new->ndpr_raf_onlink == 0 && new->ndpr_raf_auto == 0)
1037 			goto end;
1038 
1039 		error = nd6_prelist_add(new, dr, &newpr);
1040 		if (error != 0 || newpr == NULL) {
1041 			nd6log((LOG_NOTICE, "prelist_update: "
1042 			    "nd6_prelist_add failed for %s/%d on %s "
1043 			    "errno=%d, returnpr=%p\n",
1044 			    ip6_sprintf(ip6buf, &new->ndpr_prefix.sin6_addr),
1045 			    new->ndpr_plen, if_name(new->ndpr_ifp),
1046 			    error, newpr));
1047 			goto end; /* we should just give up in this case. */
1048 		}
1049 
1050 		/*
1051 		 * XXX: from the ND point of view, we can ignore a prefix
1052 		 * with the on-link bit being zero.  However, we need a
1053 		 * prefix structure for references from autoconfigured
1054 		 * addresses.  Thus, we explicitly make sure that the prefix
1055 		 * itself expires now.
1056 		 */
1057 		if (newpr->ndpr_raf_onlink == 0) {
1058 			newpr->ndpr_vltime = 0;
1059 			newpr->ndpr_pltime = 0;
1060 			in6_init_prefix_ltimes(newpr);
1061 		}
1062 
1063 		pr = newpr;
1064 	}
1065 
1066 	/*
1067 	 * Address autoconfiguration based on Section 5.5.3 of RFC 2462.
1068 	 * Note that pr must be non NULL at this point.
1069 	 */
1070 
1071 	/* 5.5.3 (a). Ignore the prefix without the A bit set. */
1072 	if (!new->ndpr_raf_auto)
1073 		goto end;
1074 
1075 	/*
1076 	 * 5.5.3 (b). the link-local prefix should have been ignored in
1077 	 * nd6_ra_input.
1078 	 */
1079 
1080 	/* 5.5.3 (c). Consistency check on lifetimes: pltime <= vltime. */
1081 	if (new->ndpr_pltime > new->ndpr_vltime) {
1082 		error = EINVAL;	/* XXX: won't be used */
1083 		goto end;
1084 	}
1085 
1086 	/*
1087 	 * 5.5.3 (d).  If the prefix advertised is not equal to the prefix of
1088 	 * an address configured by stateless autoconfiguration already in the
1089 	 * list of addresses associated with the interface, and the Valid
1090 	 * Lifetime is not 0, form an address.  We first check if we have
1091 	 * a matching prefix.
1092 	 * Note: we apply a clarification in rfc2462bis-02 here.  We only
1093 	 * consider autoconfigured addresses while RFC2462 simply said
1094 	 * "address".
1095 	 */
1096 	IF_ADDR_RLOCK(ifp);
1097 	TAILQ_FOREACH(ifa, &ifp->if_addrhead, ifa_link) {
1098 		struct in6_ifaddr *ifa6;
1099 		u_int32_t remaininglifetime;
1100 
1101 		if (ifa->ifa_addr->sa_family != AF_INET6)
1102 			continue;
1103 
1104 		ifa6 = (struct in6_ifaddr *)ifa;
1105 
1106 		/*
1107 		 * We only consider autoconfigured addresses as per rfc2462bis.
1108 		 */
1109 		if (!(ifa6->ia6_flags & IN6_IFF_AUTOCONF))
1110 			continue;
1111 
1112 		/*
1113 		 * Spec is not clear here, but I believe we should concentrate
1114 		 * on unicast (i.e. not anycast) addresses.
1115 		 * XXX: other ia6_flags? detached or duplicated?
1116 		 */
1117 		if ((ifa6->ia6_flags & IN6_IFF_ANYCAST) != 0)
1118 			continue;
1119 
1120 		/*
1121 		 * Ignore the address if it is not associated with a prefix
1122 		 * or is associated with a prefix that is different from this
1123 		 * one.  (pr is never NULL here)
1124 		 */
1125 		if (ifa6->ia6_ndpr != pr)
1126 			continue;
1127 
1128 		if (ia6_match == NULL) /* remember the first one */
1129 			ia6_match = ifa6;
1130 
1131 		/*
1132 		 * An already autoconfigured address matched.  Now that we
1133 		 * are sure there is at least one matched address, we can
1134 		 * proceed to 5.5.3. (e): update the lifetimes according to the
1135 		 * "two hours" rule and the privacy extension.
1136 		 * We apply some clarifications in rfc2462bis:
1137 		 * - use remaininglifetime instead of storedlifetime as a
1138 		 *   variable name
1139 		 * - remove the dead code in the "two-hour" rule
1140 		 */
1141 #define TWOHOUR		(120*60)
1142 		lt6_tmp = ifa6->ia6_lifetime;
1143 
1144 		if (lt6_tmp.ia6t_vltime == ND6_INFINITE_LIFETIME)
1145 			remaininglifetime = ND6_INFINITE_LIFETIME;
1146 		else if (time_uptime - ifa6->ia6_updatetime >
1147 			 lt6_tmp.ia6t_vltime) {
1148 			/*
1149 			 * The case of "invalid" address.  We should usually
1150 			 * not see this case.
1151 			 */
1152 			remaininglifetime = 0;
1153 		} else
1154 			remaininglifetime = lt6_tmp.ia6t_vltime -
1155 			    (time_uptime - ifa6->ia6_updatetime);
1156 
1157 		/* when not updating, keep the current stored lifetime. */
1158 		lt6_tmp.ia6t_vltime = remaininglifetime;
1159 
1160 		if (TWOHOUR < new->ndpr_vltime ||
1161 		    remaininglifetime < new->ndpr_vltime) {
1162 			lt6_tmp.ia6t_vltime = new->ndpr_vltime;
1163 		} else if (remaininglifetime <= TWOHOUR) {
1164 			if (auth) {
1165 				lt6_tmp.ia6t_vltime = new->ndpr_vltime;
1166 			}
1167 		} else {
1168 			/*
1169 			 * new->ndpr_vltime <= TWOHOUR &&
1170 			 * TWOHOUR < remaininglifetime
1171 			 */
1172 			lt6_tmp.ia6t_vltime = TWOHOUR;
1173 		}
1174 
1175 		/* The 2 hour rule is not imposed for preferred lifetime. */
1176 		lt6_tmp.ia6t_pltime = new->ndpr_pltime;
1177 
1178 		in6_init_address_ltimes(pr, &lt6_tmp);
1179 
1180 		/*
1181 		 * We need to treat lifetimes for temporary addresses
1182 		 * differently, according to
1183 		 * draft-ietf-ipv6-privacy-addrs-v2-01.txt 3.3 (1);
1184 		 * we only update the lifetimes when they are in the maximum
1185 		 * intervals.
1186 		 */
1187 		if ((ifa6->ia6_flags & IN6_IFF_TEMPORARY) != 0) {
1188 			u_int32_t maxvltime, maxpltime;
1189 
1190 			if (V_ip6_temp_valid_lifetime >
1191 			    (u_int32_t)((time_uptime - ifa6->ia6_createtime) +
1192 			    V_ip6_desync_factor)) {
1193 				maxvltime = V_ip6_temp_valid_lifetime -
1194 				    (time_uptime - ifa6->ia6_createtime) -
1195 				    V_ip6_desync_factor;
1196 			} else
1197 				maxvltime = 0;
1198 			if (V_ip6_temp_preferred_lifetime >
1199 			    (u_int32_t)((time_uptime - ifa6->ia6_createtime) +
1200 			    V_ip6_desync_factor)) {
1201 				maxpltime = V_ip6_temp_preferred_lifetime -
1202 				    (time_uptime - ifa6->ia6_createtime) -
1203 				    V_ip6_desync_factor;
1204 			} else
1205 				maxpltime = 0;
1206 
1207 			if (lt6_tmp.ia6t_vltime == ND6_INFINITE_LIFETIME ||
1208 			    lt6_tmp.ia6t_vltime > maxvltime) {
1209 				lt6_tmp.ia6t_vltime = maxvltime;
1210 			}
1211 			if (lt6_tmp.ia6t_pltime == ND6_INFINITE_LIFETIME ||
1212 			    lt6_tmp.ia6t_pltime > maxpltime) {
1213 				lt6_tmp.ia6t_pltime = maxpltime;
1214 			}
1215 		}
1216 		ifa6->ia6_lifetime = lt6_tmp;
1217 		ifa6->ia6_updatetime = time_uptime;
1218 	}
1219 	IF_ADDR_RUNLOCK(ifp);
1220 	if (ia6_match == NULL && new->ndpr_vltime) {
1221 		int ifidlen;
1222 
1223 		/*
1224 		 * 5.5.3 (d) (continued)
1225 		 * No address matched and the valid lifetime is non-zero.
1226 		 * Create a new address.
1227 		 */
1228 
1229 		/*
1230 		 * Prefix Length check:
1231 		 * If the sum of the prefix length and interface identifier
1232 		 * length does not equal 128 bits, the Prefix Information
1233 		 * option MUST be ignored.  The length of the interface
1234 		 * identifier is defined in a separate link-type specific
1235 		 * document.
1236 		 */
1237 		ifidlen = in6_if2idlen(ifp);
1238 		if (ifidlen < 0) {
1239 			/* this should not happen, so we always log it. */
1240 			log(LOG_ERR, "prelist_update: IFID undefined (%s)\n",
1241 			    if_name(ifp));
1242 			goto end;
1243 		}
1244 		if (ifidlen + pr->ndpr_plen != 128) {
1245 			nd6log((LOG_INFO,
1246 			    "prelist_update: invalid prefixlen "
1247 			    "%d for %s, ignored\n",
1248 			    pr->ndpr_plen, if_name(ifp)));
1249 			goto end;
1250 		}
1251 
1252 		if ((ia6 = in6_ifadd(new, mcast)) != NULL) {
1253 			/*
1254 			 * note that we should use pr (not new) for reference.
1255 			 */
1256 			pr->ndpr_refcnt++;
1257 			ia6->ia6_ndpr = pr;
1258 
1259 			/*
1260 			 * RFC 3041 3.3 (2).
1261 			 * When a new public address is created as described
1262 			 * in RFC2462, also create a new temporary address.
1263 			 *
1264 			 * RFC 3041 3.5.
1265 			 * When an interface connects to a new link, a new
1266 			 * randomized interface identifier should be generated
1267 			 * immediately together with a new set of temporary
1268 			 * addresses.  Thus, we specifiy 1 as the 2nd arg of
1269 			 * in6_tmpifadd().
1270 			 */
1271 			if (V_ip6_use_tempaddr) {
1272 				int e;
1273 				if ((e = in6_tmpifadd(ia6, 1, 1)) != 0) {
1274 					nd6log((LOG_NOTICE, "prelist_update: "
1275 					    "failed to create a temporary "
1276 					    "address, errno=%d\n",
1277 					    e));
1278 				}
1279 			}
1280 			ifa_free(&ia6->ia_ifa);
1281 
1282 			/*
1283 			 * A newly added address might affect the status
1284 			 * of other addresses, so we check and update it.
1285 			 * XXX: what if address duplication happens?
1286 			 */
1287 			pfxlist_onlink_check();
1288 		} else {
1289 			/* just set an error. do not bark here. */
1290 			error = EADDRNOTAVAIL; /* XXX: might be unused. */
1291 		}
1292 	}
1293 
1294  end:
1295 	return error;
1296 }
1297 
1298 /*
1299  * A supplement function used in the on-link detection below;
1300  * detect if a given prefix has a (probably) reachable advertising router.
1301  * XXX: lengthy function name...
1302  */
1303 static struct nd_pfxrouter *
1304 find_pfxlist_reachable_router(struct nd_prefix *pr)
1305 {
1306 	struct nd_pfxrouter *pfxrtr;
1307 	struct llentry *ln;
1308 	int canreach;
1309 
1310 	LIST_FOREACH(pfxrtr, &pr->ndpr_advrtrs, pfr_entry) {
1311 		IF_AFDATA_RLOCK(pfxrtr->router->ifp);
1312 		ln = nd6_lookup(&pfxrtr->router->rtaddr, 0, pfxrtr->router->ifp);
1313 		IF_AFDATA_RUNLOCK(pfxrtr->router->ifp);
1314 		if (ln == NULL)
1315 			continue;
1316 		canreach = ND6_IS_LLINFO_PROBREACH(ln);
1317 		LLE_RUNLOCK(ln);
1318 		if (canreach)
1319 			break;
1320 	}
1321 	return (pfxrtr);
1322 }
1323 
1324 /*
1325  * Check if each prefix in the prefix list has at least one available router
1326  * that advertised the prefix (a router is "available" if its neighbor cache
1327  * entry is reachable or probably reachable).
1328  * If the check fails, the prefix may be off-link, because, for example,
1329  * we have moved from the network but the lifetime of the prefix has not
1330  * expired yet.  So we should not use the prefix if there is another prefix
1331  * that has an available router.
1332  * But, if there is no prefix that has an available router, we still regards
1333  * all the prefixes as on-link.  This is because we can't tell if all the
1334  * routers are simply dead or if we really moved from the network and there
1335  * is no router around us.
1336  */
1337 void
1338 pfxlist_onlink_check()
1339 {
1340 	struct nd_prefix *pr;
1341 	struct in6_ifaddr *ifa;
1342 	struct nd_defrouter *dr;
1343 	struct nd_pfxrouter *pfxrtr = NULL;
1344 
1345 	/*
1346 	 * Check if there is a prefix that has a reachable advertising
1347 	 * router.
1348 	 */
1349 	LIST_FOREACH(pr, &V_nd_prefix, ndpr_entry) {
1350 		if (pr->ndpr_raf_onlink && find_pfxlist_reachable_router(pr))
1351 			break;
1352 	}
1353 
1354 	/*
1355 	 * If we have no such prefix, check whether we still have a router
1356 	 * that does not advertise any prefixes.
1357 	 */
1358 	if (pr == NULL) {
1359 		TAILQ_FOREACH(dr, &V_nd_defrouter, dr_entry) {
1360 			struct nd_prefix *pr0;
1361 
1362 			LIST_FOREACH(pr0, &V_nd_prefix, ndpr_entry) {
1363 				if ((pfxrtr = pfxrtr_lookup(pr0, dr)) != NULL)
1364 					break;
1365 			}
1366 			if (pfxrtr != NULL)
1367 				break;
1368 		}
1369 	}
1370 	if (pr != NULL || (!TAILQ_EMPTY(&V_nd_defrouter) && pfxrtr == NULL)) {
1371 		/*
1372 		 * There is at least one prefix that has a reachable router,
1373 		 * or at least a router which probably does not advertise
1374 		 * any prefixes.  The latter would be the case when we move
1375 		 * to a new link where we have a router that does not provide
1376 		 * prefixes and we configure an address by hand.
1377 		 * Detach prefixes which have no reachable advertising
1378 		 * router, and attach other prefixes.
1379 		 */
1380 		LIST_FOREACH(pr, &V_nd_prefix, ndpr_entry) {
1381 			/* XXX: a link-local prefix should never be detached */
1382 			if (IN6_IS_ADDR_LINKLOCAL(&pr->ndpr_prefix.sin6_addr))
1383 				continue;
1384 
1385 			/*
1386 			 * we aren't interested in prefixes without the L bit
1387 			 * set.
1388 			 */
1389 			if (pr->ndpr_raf_onlink == 0)
1390 				continue;
1391 
1392 			if (pr->ndpr_raf_auto == 0)
1393 				continue;
1394 
1395 			if ((pr->ndpr_stateflags & NDPRF_DETACHED) == 0 &&
1396 			    find_pfxlist_reachable_router(pr) == NULL)
1397 				pr->ndpr_stateflags |= NDPRF_DETACHED;
1398 			if ((pr->ndpr_stateflags & NDPRF_DETACHED) != 0 &&
1399 			    find_pfxlist_reachable_router(pr) != 0)
1400 				pr->ndpr_stateflags &= ~NDPRF_DETACHED;
1401 		}
1402 	} else {
1403 		/* there is no prefix that has a reachable router */
1404 		LIST_FOREACH(pr, &V_nd_prefix, ndpr_entry) {
1405 			if (IN6_IS_ADDR_LINKLOCAL(&pr->ndpr_prefix.sin6_addr))
1406 				continue;
1407 
1408 			if (pr->ndpr_raf_onlink == 0)
1409 				continue;
1410 
1411 			if (pr->ndpr_raf_auto == 0)
1412 				continue;
1413 
1414 			if ((pr->ndpr_stateflags & NDPRF_DETACHED) != 0)
1415 				pr->ndpr_stateflags &= ~NDPRF_DETACHED;
1416 		}
1417 	}
1418 
1419 	/*
1420 	 * Remove each interface route associated with a (just) detached
1421 	 * prefix, and reinstall the interface route for a (just) attached
1422 	 * prefix.  Note that all attempt of reinstallation does not
1423 	 * necessarily success, when a same prefix is shared among multiple
1424 	 * interfaces.  Such cases will be handled in nd6_prefix_onlink,
1425 	 * so we don't have to care about them.
1426 	 */
1427 	LIST_FOREACH(pr, &V_nd_prefix, ndpr_entry) {
1428 		int e;
1429 		char ip6buf[INET6_ADDRSTRLEN];
1430 
1431 		if (IN6_IS_ADDR_LINKLOCAL(&pr->ndpr_prefix.sin6_addr))
1432 			continue;
1433 
1434 		if (pr->ndpr_raf_onlink == 0)
1435 			continue;
1436 
1437 		if (pr->ndpr_raf_auto == 0)
1438 			continue;
1439 
1440 		if ((pr->ndpr_stateflags & NDPRF_DETACHED) != 0 &&
1441 		    (pr->ndpr_stateflags & NDPRF_ONLINK) != 0) {
1442 			if ((e = nd6_prefix_offlink(pr)) != 0) {
1443 				nd6log((LOG_ERR,
1444 				    "pfxlist_onlink_check: failed to "
1445 				    "make %s/%d offlink, errno=%d\n",
1446 				    ip6_sprintf(ip6buf,
1447 					    &pr->ndpr_prefix.sin6_addr),
1448 					    pr->ndpr_plen, e));
1449 			}
1450 		}
1451 		if ((pr->ndpr_stateflags & NDPRF_DETACHED) == 0 &&
1452 		    (pr->ndpr_stateflags & NDPRF_ONLINK) == 0 &&
1453 		    pr->ndpr_raf_onlink) {
1454 			if ((e = nd6_prefix_onlink(pr)) != 0) {
1455 				nd6log((LOG_ERR,
1456 				    "pfxlist_onlink_check: failed to "
1457 				    "make %s/%d onlink, errno=%d\n",
1458 				    ip6_sprintf(ip6buf,
1459 					    &pr->ndpr_prefix.sin6_addr),
1460 					    pr->ndpr_plen, e));
1461 			}
1462 		}
1463 	}
1464 
1465 	/*
1466 	 * Changes on the prefix status might affect address status as well.
1467 	 * Make sure that all addresses derived from an attached prefix are
1468 	 * attached, and that all addresses derived from a detached prefix are
1469 	 * detached.  Note, however, that a manually configured address should
1470 	 * always be attached.
1471 	 * The precise detection logic is same as the one for prefixes.
1472 	 *
1473 	 * XXXRW: in6_ifaddrhead locking.
1474 	 */
1475 	TAILQ_FOREACH(ifa, &V_in6_ifaddrhead, ia_link) {
1476 		if (!(ifa->ia6_flags & IN6_IFF_AUTOCONF))
1477 			continue;
1478 
1479 		if (ifa->ia6_ndpr == NULL) {
1480 			/*
1481 			 * This can happen when we first configure the address
1482 			 * (i.e. the address exists, but the prefix does not).
1483 			 * XXX: complicated relationships...
1484 			 */
1485 			continue;
1486 		}
1487 
1488 		if (find_pfxlist_reachable_router(ifa->ia6_ndpr))
1489 			break;
1490 	}
1491 	if (ifa) {
1492 		TAILQ_FOREACH(ifa, &V_in6_ifaddrhead, ia_link) {
1493 			if ((ifa->ia6_flags & IN6_IFF_AUTOCONF) == 0)
1494 				continue;
1495 
1496 			if (ifa->ia6_ndpr == NULL) /* XXX: see above. */
1497 				continue;
1498 
1499 			if (find_pfxlist_reachable_router(ifa->ia6_ndpr)) {
1500 				if (ifa->ia6_flags & IN6_IFF_DETACHED) {
1501 					ifa->ia6_flags &= ~IN6_IFF_DETACHED;
1502 					ifa->ia6_flags |= IN6_IFF_TENTATIVE;
1503 					nd6_dad_start((struct ifaddr *)ifa, 0);
1504 				}
1505 			} else {
1506 				ifa->ia6_flags |= IN6_IFF_DETACHED;
1507 			}
1508 		}
1509 	}
1510 	else {
1511 		TAILQ_FOREACH(ifa, &V_in6_ifaddrhead, ia_link) {
1512 			if ((ifa->ia6_flags & IN6_IFF_AUTOCONF) == 0)
1513 				continue;
1514 
1515 			if (ifa->ia6_flags & IN6_IFF_DETACHED) {
1516 				ifa->ia6_flags &= ~IN6_IFF_DETACHED;
1517 				ifa->ia6_flags |= IN6_IFF_TENTATIVE;
1518 				/* Do we need a delay in this case? */
1519 				nd6_dad_start((struct ifaddr *)ifa, 0);
1520 			}
1521 		}
1522 	}
1523 }
1524 
1525 static int
1526 nd6_prefix_onlink_rtrequest(struct nd_prefix *pr, struct ifaddr *ifa)
1527 {
1528 	static struct sockaddr_dl null_sdl = {sizeof(null_sdl), AF_LINK};
1529 	struct rib_head *rnh;
1530 	struct rtentry *rt;
1531 	struct sockaddr_in6 mask6;
1532 	u_long rtflags;
1533 	int error, a_failure, fibnum;
1534 
1535 	/*
1536 	 * in6_ifinit() sets nd6_rtrequest to ifa_rtrequest for all ifaddrs.
1537 	 * ifa->ifa_rtrequest = nd6_rtrequest;
1538 	 */
1539 	bzero(&mask6, sizeof(mask6));
1540 	mask6.sin6_len = sizeof(mask6);
1541 	mask6.sin6_addr = pr->ndpr_mask;
1542 	rtflags = (ifa->ifa_flags & ~IFA_RTSELF) | RTF_UP;
1543 
1544 	a_failure = 0;
1545 	for (fibnum = 0; fibnum < rt_numfibs; fibnum++) {
1546 
1547 		rt = NULL;
1548 		error = in6_rtrequest(RTM_ADD,
1549 		    (struct sockaddr *)&pr->ndpr_prefix, ifa->ifa_addr,
1550 		    (struct sockaddr *)&mask6, rtflags, &rt, fibnum);
1551 		if (error == 0) {
1552 			KASSERT(rt != NULL, ("%s: in6_rtrequest return no "
1553 			    "error(%d) but rt is NULL, pr=%p, ifa=%p", __func__,
1554 			    error, pr, ifa));
1555 
1556 			rnh = rt_tables_get_rnh(rt->rt_fibnum, AF_INET6);
1557 			/* XXX what if rhn == NULL? */
1558 			RIB_WLOCK(rnh);
1559 			RT_LOCK(rt);
1560 			if (rt_setgate(rt, rt_key(rt),
1561 			    (struct sockaddr *)&null_sdl) == 0) {
1562 				struct sockaddr_dl *dl;
1563 
1564 				dl = (struct sockaddr_dl *)rt->rt_gateway;
1565 				dl->sdl_type = rt->rt_ifp->if_type;
1566 				dl->sdl_index = rt->rt_ifp->if_index;
1567 			}
1568 			RIB_WUNLOCK(rnh);
1569 			nd6_rtmsg(RTM_ADD, rt);
1570 			RT_UNLOCK(rt);
1571 			pr->ndpr_stateflags |= NDPRF_ONLINK;
1572 		} else {
1573 			char ip6buf[INET6_ADDRSTRLEN];
1574 			char ip6bufg[INET6_ADDRSTRLEN];
1575 			char ip6bufm[INET6_ADDRSTRLEN];
1576 			struct sockaddr_in6 *sin6;
1577 
1578 			sin6 = (struct sockaddr_in6 *)ifa->ifa_addr;
1579 			nd6log((LOG_ERR, "nd6_prefix_onlink: failed to add "
1580 			    "route for a prefix (%s/%d) on %s, gw=%s, mask=%s, "
1581 			    "flags=%lx errno = %d\n",
1582 			    ip6_sprintf(ip6buf, &pr->ndpr_prefix.sin6_addr),
1583 			    pr->ndpr_plen, if_name(pr->ndpr_ifp),
1584 			    ip6_sprintf(ip6bufg, &sin6->sin6_addr),
1585 			    ip6_sprintf(ip6bufm, &mask6.sin6_addr),
1586 			    rtflags, error));
1587 
1588 			/* Save last error to return, see rtinit(). */
1589 			a_failure = error;
1590 		}
1591 
1592 		if (rt != NULL) {
1593 			RT_LOCK(rt);
1594 			RT_REMREF(rt);
1595 			RT_UNLOCK(rt);
1596 		}
1597 	}
1598 
1599 	/* Return the last error we got. */
1600 	return (a_failure);
1601 }
1602 
1603 static int
1604 nd6_prefix_onlink(struct nd_prefix *pr)
1605 {
1606 	struct ifaddr *ifa;
1607 	struct ifnet *ifp = pr->ndpr_ifp;
1608 	struct nd_prefix *opr;
1609 	int error = 0;
1610 	char ip6buf[INET6_ADDRSTRLEN];
1611 
1612 	/* sanity check */
1613 	if ((pr->ndpr_stateflags & NDPRF_ONLINK) != 0) {
1614 		nd6log((LOG_ERR,
1615 		    "nd6_prefix_onlink: %s/%d is already on-link\n",
1616 		    ip6_sprintf(ip6buf, &pr->ndpr_prefix.sin6_addr),
1617 		    pr->ndpr_plen));
1618 		return (EEXIST);
1619 	}
1620 
1621 	/*
1622 	 * Add the interface route associated with the prefix.  Before
1623 	 * installing the route, check if there's the same prefix on another
1624 	 * interface, and the prefix has already installed the interface route.
1625 	 * Although such a configuration is expected to be rare, we explicitly
1626 	 * allow it.
1627 	 */
1628 	LIST_FOREACH(opr, &V_nd_prefix, ndpr_entry) {
1629 		if (opr == pr)
1630 			continue;
1631 
1632 		if ((opr->ndpr_stateflags & NDPRF_ONLINK) == 0)
1633 			continue;
1634 
1635 		if (opr->ndpr_plen == pr->ndpr_plen &&
1636 		    in6_are_prefix_equal(&pr->ndpr_prefix.sin6_addr,
1637 		    &opr->ndpr_prefix.sin6_addr, pr->ndpr_plen))
1638 			return (0);
1639 	}
1640 
1641 	/*
1642 	 * We prefer link-local addresses as the associated interface address.
1643 	 */
1644 	/* search for a link-local addr */
1645 	ifa = (struct ifaddr *)in6ifa_ifpforlinklocal(ifp,
1646 	    IN6_IFF_NOTREADY | IN6_IFF_ANYCAST);
1647 	if (ifa == NULL) {
1648 		/* XXX: freebsd does not have ifa_ifwithaf */
1649 		IF_ADDR_RLOCK(ifp);
1650 		TAILQ_FOREACH(ifa, &ifp->if_addrhead, ifa_link) {
1651 			if (ifa->ifa_addr->sa_family == AF_INET6)
1652 				break;
1653 		}
1654 		if (ifa != NULL)
1655 			ifa_ref(ifa);
1656 		IF_ADDR_RUNLOCK(ifp);
1657 		/* should we care about ia6_flags? */
1658 	}
1659 	if (ifa == NULL) {
1660 		/*
1661 		 * This can still happen, when, for example, we receive an RA
1662 		 * containing a prefix with the L bit set and the A bit clear,
1663 		 * after removing all IPv6 addresses on the receiving
1664 		 * interface.  This should, of course, be rare though.
1665 		 */
1666 		nd6log((LOG_NOTICE,
1667 		    "nd6_prefix_onlink: failed to find any ifaddr"
1668 		    " to add route for a prefix(%s/%d) on %s\n",
1669 		    ip6_sprintf(ip6buf, &pr->ndpr_prefix.sin6_addr),
1670 		    pr->ndpr_plen, if_name(ifp)));
1671 		return (0);
1672 	}
1673 
1674 	error = nd6_prefix_onlink_rtrequest(pr, ifa);
1675 
1676 	if (ifa != NULL)
1677 		ifa_free(ifa);
1678 
1679 	return (error);
1680 }
1681 
1682 static int
1683 nd6_prefix_offlink(struct nd_prefix *pr)
1684 {
1685 	int error = 0;
1686 	struct ifnet *ifp = pr->ndpr_ifp;
1687 	struct nd_prefix *opr;
1688 	struct sockaddr_in6 sa6, mask6;
1689 	struct rtentry *rt;
1690 	char ip6buf[INET6_ADDRSTRLEN];
1691 	int fibnum, a_failure;
1692 
1693 	/* sanity check */
1694 	if ((pr->ndpr_stateflags & NDPRF_ONLINK) == 0) {
1695 		nd6log((LOG_ERR,
1696 		    "nd6_prefix_offlink: %s/%d is already off-link\n",
1697 		    ip6_sprintf(ip6buf, &pr->ndpr_prefix.sin6_addr),
1698 		    pr->ndpr_plen));
1699 		return (EEXIST);
1700 	}
1701 
1702 	bzero(&sa6, sizeof(sa6));
1703 	sa6.sin6_family = AF_INET6;
1704 	sa6.sin6_len = sizeof(sa6);
1705 	bcopy(&pr->ndpr_prefix.sin6_addr, &sa6.sin6_addr,
1706 	    sizeof(struct in6_addr));
1707 	bzero(&mask6, sizeof(mask6));
1708 	mask6.sin6_family = AF_INET6;
1709 	mask6.sin6_len = sizeof(sa6);
1710 	bcopy(&pr->ndpr_mask, &mask6.sin6_addr, sizeof(struct in6_addr));
1711 
1712 	a_failure = 0;
1713 	for (fibnum = 0; fibnum < rt_numfibs; fibnum++) {
1714 		rt = NULL;
1715 		error = in6_rtrequest(RTM_DELETE, (struct sockaddr *)&sa6, NULL,
1716 		    (struct sockaddr *)&mask6, 0, &rt, fibnum);
1717 		if (error == 0) {
1718 			/* report the route deletion to the routing socket. */
1719 			if (rt != NULL)
1720 				nd6_rtmsg(RTM_DELETE, rt);
1721 		} else {
1722 			/* Save last error to return, see rtinit(). */
1723 			a_failure = error;
1724 		}
1725 		if (rt != NULL) {
1726 			RTFREE(rt);
1727 		}
1728 	}
1729 	error = a_failure;
1730 	a_failure = 1;
1731 	if (error == 0) {
1732 		pr->ndpr_stateflags &= ~NDPRF_ONLINK;
1733 
1734 		/*
1735 		 * There might be the same prefix on another interface,
1736 		 * the prefix which could not be on-link just because we have
1737 		 * the interface route (see comments in nd6_prefix_onlink).
1738 		 * If there's one, try to make the prefix on-link on the
1739 		 * interface.
1740 		 */
1741 		LIST_FOREACH(opr, &V_nd_prefix, ndpr_entry) {
1742 			if (opr == pr)
1743 				continue;
1744 
1745 			if ((opr->ndpr_stateflags & NDPRF_ONLINK) != 0)
1746 				continue;
1747 
1748 			/*
1749 			 * KAME specific: detached prefixes should not be
1750 			 * on-link.
1751 			 */
1752 			if ((opr->ndpr_stateflags & NDPRF_DETACHED) != 0)
1753 				continue;
1754 
1755 			if (opr->ndpr_plen == pr->ndpr_plen &&
1756 			    in6_are_prefix_equal(&pr->ndpr_prefix.sin6_addr,
1757 			    &opr->ndpr_prefix.sin6_addr, pr->ndpr_plen)) {
1758 				int e;
1759 
1760 				if ((e = nd6_prefix_onlink(opr)) != 0) {
1761 					nd6log((LOG_ERR,
1762 					    "nd6_prefix_offlink: failed to "
1763 					    "recover a prefix %s/%d from %s "
1764 					    "to %s (errno = %d)\n",
1765 					    ip6_sprintf(ip6buf,
1766 						&opr->ndpr_prefix.sin6_addr),
1767 					    opr->ndpr_plen, if_name(ifp),
1768 					    if_name(opr->ndpr_ifp), e));
1769 				} else
1770 					a_failure = 0;
1771 			}
1772 		}
1773 	} else {
1774 		/* XXX: can we still set the NDPRF_ONLINK flag? */
1775 		nd6log((LOG_ERR,
1776 		    "nd6_prefix_offlink: failed to delete route: "
1777 		    "%s/%d on %s (errno = %d)\n",
1778 		    ip6_sprintf(ip6buf, &sa6.sin6_addr), pr->ndpr_plen,
1779 		    if_name(ifp), error));
1780 	}
1781 
1782 	if (a_failure)
1783 		lltable_prefix_free(AF_INET6, (struct sockaddr *)&sa6,
1784 		    (struct sockaddr *)&mask6, LLE_STATIC);
1785 
1786 	return (error);
1787 }
1788 
1789 static struct in6_ifaddr *
1790 in6_ifadd(struct nd_prefixctl *pr, int mcast)
1791 {
1792 	struct ifnet *ifp = pr->ndpr_ifp;
1793 	struct ifaddr *ifa;
1794 	struct in6_aliasreq ifra;
1795 	struct in6_ifaddr *ia, *ib;
1796 	int error, plen0;
1797 	struct in6_addr mask;
1798 	int prefixlen = pr->ndpr_plen;
1799 	int updateflags;
1800 	char ip6buf[INET6_ADDRSTRLEN];
1801 
1802 	in6_prefixlen2mask(&mask, prefixlen);
1803 
1804 	/*
1805 	 * find a link-local address (will be interface ID).
1806 	 * Is it really mandatory? Theoretically, a global or a site-local
1807 	 * address can be configured without a link-local address, if we
1808 	 * have a unique interface identifier...
1809 	 *
1810 	 * it is not mandatory to have a link-local address, we can generate
1811 	 * interface identifier on the fly.  we do this because:
1812 	 * (1) it should be the easiest way to find interface identifier.
1813 	 * (2) RFC2462 5.4 suggesting the use of the same interface identifier
1814 	 * for multiple addresses on a single interface, and possible shortcut
1815 	 * of DAD.  we omitted DAD for this reason in the past.
1816 	 * (3) a user can prevent autoconfiguration of global address
1817 	 * by removing link-local address by hand (this is partly because we
1818 	 * don't have other way to control the use of IPv6 on an interface.
1819 	 * this has been our design choice - cf. NRL's "ifconfig auto").
1820 	 * (4) it is easier to manage when an interface has addresses
1821 	 * with the same interface identifier, than to have multiple addresses
1822 	 * with different interface identifiers.
1823 	 */
1824 	ifa = (struct ifaddr *)in6ifa_ifpforlinklocal(ifp, 0); /* 0 is OK? */
1825 	if (ifa)
1826 		ib = (struct in6_ifaddr *)ifa;
1827 	else
1828 		return NULL;
1829 
1830 	/* prefixlen + ifidlen must be equal to 128 */
1831 	plen0 = in6_mask2len(&ib->ia_prefixmask.sin6_addr, NULL);
1832 	if (prefixlen != plen0) {
1833 		ifa_free(ifa);
1834 		nd6log((LOG_INFO, "in6_ifadd: wrong prefixlen for %s "
1835 		    "(prefix=%d ifid=%d)\n",
1836 		    if_name(ifp), prefixlen, 128 - plen0));
1837 		return NULL;
1838 	}
1839 
1840 	/* make ifaddr */
1841 	in6_prepare_ifra(&ifra, &pr->ndpr_prefix.sin6_addr, &mask);
1842 
1843 	IN6_MASK_ADDR(&ifra.ifra_addr.sin6_addr, &mask);
1844 	/* interface ID */
1845 	ifra.ifra_addr.sin6_addr.s6_addr32[0] |=
1846 	    (ib->ia_addr.sin6_addr.s6_addr32[0] & ~mask.s6_addr32[0]);
1847 	ifra.ifra_addr.sin6_addr.s6_addr32[1] |=
1848 	    (ib->ia_addr.sin6_addr.s6_addr32[1] & ~mask.s6_addr32[1]);
1849 	ifra.ifra_addr.sin6_addr.s6_addr32[2] |=
1850 	    (ib->ia_addr.sin6_addr.s6_addr32[2] & ~mask.s6_addr32[2]);
1851 	ifra.ifra_addr.sin6_addr.s6_addr32[3] |=
1852 	    (ib->ia_addr.sin6_addr.s6_addr32[3] & ~mask.s6_addr32[3]);
1853 	ifa_free(ifa);
1854 
1855 	/* lifetimes. */
1856 	ifra.ifra_lifetime.ia6t_vltime = pr->ndpr_vltime;
1857 	ifra.ifra_lifetime.ia6t_pltime = pr->ndpr_pltime;
1858 
1859 	/* XXX: scope zone ID? */
1860 
1861 	ifra.ifra_flags |= IN6_IFF_AUTOCONF; /* obey autoconf */
1862 
1863 	/*
1864 	 * Make sure that we do not have this address already.  This should
1865 	 * usually not happen, but we can still see this case, e.g., if we
1866 	 * have manually configured the exact address to be configured.
1867 	 */
1868 	ifa = (struct ifaddr *)in6ifa_ifpwithaddr(ifp,
1869 	    &ifra.ifra_addr.sin6_addr);
1870 	if (ifa != NULL) {
1871 		ifa_free(ifa);
1872 		/* this should be rare enough to make an explicit log */
1873 		log(LOG_INFO, "in6_ifadd: %s is already configured\n",
1874 		    ip6_sprintf(ip6buf, &ifra.ifra_addr.sin6_addr));
1875 		return (NULL);
1876 	}
1877 
1878 	/*
1879 	 * Allocate ifaddr structure, link into chain, etc.
1880 	 * If we are going to create a new address upon receiving a multicasted
1881 	 * RA, we need to impose a random delay before starting DAD.
1882 	 * [draft-ietf-ipv6-rfc2462bis-02.txt, Section 5.4.2]
1883 	 */
1884 	updateflags = 0;
1885 	if (mcast)
1886 		updateflags |= IN6_IFAUPDATE_DADDELAY;
1887 	if ((error = in6_update_ifa(ifp, &ifra, NULL, updateflags)) != 0) {
1888 		nd6log((LOG_ERR,
1889 		    "in6_ifadd: failed to make ifaddr %s on %s (errno=%d)\n",
1890 		    ip6_sprintf(ip6buf, &ifra.ifra_addr.sin6_addr),
1891 		    if_name(ifp), error));
1892 		return (NULL);	/* ifaddr must not have been allocated. */
1893 	}
1894 
1895 	ia = in6ifa_ifpwithaddr(ifp, &ifra.ifra_addr.sin6_addr);
1896 	/*
1897 	 * XXXRW: Assumption of non-NULLness here might not be true with
1898 	 * fine-grained locking -- should we validate it?  Or just return
1899 	 * earlier ifa rather than looking it up again?
1900 	 */
1901 	return (ia);		/* this is always non-NULL  and referenced. */
1902 }
1903 
1904 /*
1905  * ia0 - corresponding public address
1906  */
1907 int
1908 in6_tmpifadd(const struct in6_ifaddr *ia0, int forcegen, int delay)
1909 {
1910 	struct ifnet *ifp = ia0->ia_ifa.ifa_ifp;
1911 	struct in6_ifaddr *newia;
1912 	struct in6_aliasreq ifra;
1913 	int error;
1914 	int trylimit = 3;	/* XXX: adhoc value */
1915 	int updateflags;
1916 	u_int32_t randid[2];
1917 	time_t vltime0, pltime0;
1918 
1919 	in6_prepare_ifra(&ifra, &ia0->ia_addr.sin6_addr,
1920 	    &ia0->ia_prefixmask.sin6_addr);
1921 
1922 	ifra.ifra_addr = ia0->ia_addr;	/* XXX: do we need this ? */
1923 	/* clear the old IFID */
1924 	IN6_MASK_ADDR(&ifra.ifra_addr.sin6_addr,
1925 	    &ifra.ifra_prefixmask.sin6_addr);
1926 
1927   again:
1928 	if (in6_get_tmpifid(ifp, (u_int8_t *)randid,
1929 	    (const u_int8_t *)&ia0->ia_addr.sin6_addr.s6_addr[8], forcegen)) {
1930 		nd6log((LOG_NOTICE, "in6_tmpifadd: failed to find a good "
1931 		    "random IFID\n"));
1932 		return (EINVAL);
1933 	}
1934 	ifra.ifra_addr.sin6_addr.s6_addr32[2] |=
1935 	    (randid[0] & ~(ifra.ifra_prefixmask.sin6_addr.s6_addr32[2]));
1936 	ifra.ifra_addr.sin6_addr.s6_addr32[3] |=
1937 	    (randid[1] & ~(ifra.ifra_prefixmask.sin6_addr.s6_addr32[3]));
1938 
1939 	/*
1940 	 * in6_get_tmpifid() quite likely provided a unique interface ID.
1941 	 * However, we may still have a chance to see collision, because
1942 	 * there may be a time lag between generation of the ID and generation
1943 	 * of the address.  So, we'll do one more sanity check.
1944 	 */
1945 
1946 	if (in6_localip(&ifra.ifra_addr.sin6_addr) != 0) {
1947 		if (trylimit-- > 0) {
1948 			forcegen = 1;
1949 			goto again;
1950 		}
1951 
1952 		/* Give up.  Something strange should have happened.  */
1953 		nd6log((LOG_NOTICE, "in6_tmpifadd: failed to "
1954 		    "find a unique random IFID\n"));
1955 		return (EEXIST);
1956 	}
1957 
1958 	/*
1959 	 * The Valid Lifetime is the lower of the Valid Lifetime of the
1960          * public address or TEMP_VALID_LIFETIME.
1961 	 * The Preferred Lifetime is the lower of the Preferred Lifetime
1962          * of the public address or TEMP_PREFERRED_LIFETIME -
1963          * DESYNC_FACTOR.
1964 	 */
1965 	if (ia0->ia6_lifetime.ia6t_vltime != ND6_INFINITE_LIFETIME) {
1966 		vltime0 = IFA6_IS_INVALID(ia0) ? 0 :
1967 		    (ia0->ia6_lifetime.ia6t_vltime -
1968 		    (time_uptime - ia0->ia6_updatetime));
1969 		if (vltime0 > V_ip6_temp_valid_lifetime)
1970 			vltime0 = V_ip6_temp_valid_lifetime;
1971 	} else
1972 		vltime0 = V_ip6_temp_valid_lifetime;
1973 	if (ia0->ia6_lifetime.ia6t_pltime != ND6_INFINITE_LIFETIME) {
1974 		pltime0 = IFA6_IS_DEPRECATED(ia0) ? 0 :
1975 		    (ia0->ia6_lifetime.ia6t_pltime -
1976 		    (time_uptime - ia0->ia6_updatetime));
1977 		if (pltime0 > V_ip6_temp_preferred_lifetime - V_ip6_desync_factor){
1978 			pltime0 = V_ip6_temp_preferred_lifetime -
1979 			    V_ip6_desync_factor;
1980 		}
1981 	} else
1982 		pltime0 = V_ip6_temp_preferred_lifetime - V_ip6_desync_factor;
1983 	ifra.ifra_lifetime.ia6t_vltime = vltime0;
1984 	ifra.ifra_lifetime.ia6t_pltime = pltime0;
1985 
1986 	/*
1987 	 * A temporary address is created only if this calculated Preferred
1988 	 * Lifetime is greater than REGEN_ADVANCE time units.
1989 	 */
1990 	if (ifra.ifra_lifetime.ia6t_pltime <= V_ip6_temp_regen_advance)
1991 		return (0);
1992 
1993 	/* XXX: scope zone ID? */
1994 
1995 	ifra.ifra_flags |= (IN6_IFF_AUTOCONF|IN6_IFF_TEMPORARY);
1996 
1997 	/* allocate ifaddr structure, link into chain, etc. */
1998 	updateflags = 0;
1999 	if (delay)
2000 		updateflags |= IN6_IFAUPDATE_DADDELAY;
2001 	if ((error = in6_update_ifa(ifp, &ifra, NULL, updateflags)) != 0)
2002 		return (error);
2003 
2004 	newia = in6ifa_ifpwithaddr(ifp, &ifra.ifra_addr.sin6_addr);
2005 	if (newia == NULL) {	/* XXX: can it happen? */
2006 		nd6log((LOG_ERR,
2007 		    "in6_tmpifadd: ifa update succeeded, but we got "
2008 		    "no ifaddr\n"));
2009 		return (EINVAL); /* XXX */
2010 	}
2011 	newia->ia6_ndpr = ia0->ia6_ndpr;
2012 	newia->ia6_ndpr->ndpr_refcnt++;
2013 	ifa_free(&newia->ia_ifa);
2014 
2015 	/*
2016 	 * A newly added address might affect the status of other addresses.
2017 	 * XXX: when the temporary address is generated with a new public
2018 	 * address, the onlink check is redundant.  However, it would be safe
2019 	 * to do the check explicitly everywhere a new address is generated,
2020 	 * and, in fact, we surely need the check when we create a new
2021 	 * temporary address due to deprecation of an old temporary address.
2022 	 */
2023 	pfxlist_onlink_check();
2024 
2025 	return (0);
2026 }
2027 
2028 static int
2029 in6_init_prefix_ltimes(struct nd_prefix *ndpr)
2030 {
2031 	if (ndpr->ndpr_pltime == ND6_INFINITE_LIFETIME)
2032 		ndpr->ndpr_preferred = 0;
2033 	else
2034 		ndpr->ndpr_preferred = time_uptime + ndpr->ndpr_pltime;
2035 	if (ndpr->ndpr_vltime == ND6_INFINITE_LIFETIME)
2036 		ndpr->ndpr_expire = 0;
2037 	else
2038 		ndpr->ndpr_expire = time_uptime + ndpr->ndpr_vltime;
2039 
2040 	return 0;
2041 }
2042 
2043 static void
2044 in6_init_address_ltimes(struct nd_prefix *new, struct in6_addrlifetime *lt6)
2045 {
2046 	/* init ia6t_expire */
2047 	if (lt6->ia6t_vltime == ND6_INFINITE_LIFETIME)
2048 		lt6->ia6t_expire = 0;
2049 	else {
2050 		lt6->ia6t_expire = time_uptime;
2051 		lt6->ia6t_expire += lt6->ia6t_vltime;
2052 	}
2053 
2054 	/* init ia6t_preferred */
2055 	if (lt6->ia6t_pltime == ND6_INFINITE_LIFETIME)
2056 		lt6->ia6t_preferred = 0;
2057 	else {
2058 		lt6->ia6t_preferred = time_uptime;
2059 		lt6->ia6t_preferred += lt6->ia6t_pltime;
2060 	}
2061 }
2062 
2063 /*
2064  * Delete all the routing table entries that use the specified gateway.
2065  * XXX: this function causes search through all entries of routing table, so
2066  * it shouldn't be called when acting as a router.
2067  */
2068 void
2069 rt6_flush(struct in6_addr *gateway, struct ifnet *ifp)
2070 {
2071 
2072 	/* We'll care only link-local addresses */
2073 	if (!IN6_IS_ADDR_LINKLOCAL(gateway))
2074 		return;
2075 
2076 	/* XXX Do we really need to walk any but the default FIB? */
2077 	rt_foreach_fib_walk_del(AF_INET6, rt6_deleteroute, (void *)gateway);
2078 }
2079 
2080 static int
2081 rt6_deleteroute(const struct rtentry *rt, void *arg)
2082 {
2083 #define SIN6(s)	((struct sockaddr_in6 *)s)
2084 	struct in6_addr *gate = (struct in6_addr *)arg;
2085 
2086 	if (rt->rt_gateway == NULL || rt->rt_gateway->sa_family != AF_INET6)
2087 		return (0);
2088 
2089 	if (!IN6_ARE_ADDR_EQUAL(gate, &SIN6(rt->rt_gateway)->sin6_addr)) {
2090 		return (0);
2091 	}
2092 
2093 	/*
2094 	 * Do not delete a static route.
2095 	 * XXX: this seems to be a bit ad-hoc. Should we consider the
2096 	 * 'cloned' bit instead?
2097 	 */
2098 	if ((rt->rt_flags & RTF_STATIC) != 0)
2099 		return (0);
2100 
2101 	/*
2102 	 * We delete only host route. This means, in particular, we don't
2103 	 * delete default route.
2104 	 */
2105 	if ((rt->rt_flags & RTF_HOST) == 0)
2106 		return (0);
2107 
2108 	return (1);
2109 #undef SIN6
2110 }
2111 
2112 int
2113 nd6_setdefaultiface(int ifindex)
2114 {
2115 	int error = 0;
2116 
2117 	if (ifindex < 0 || V_if_index < ifindex)
2118 		return (EINVAL);
2119 	if (ifindex != 0 && !ifnet_byindex(ifindex))
2120 		return (EINVAL);
2121 
2122 	if (V_nd6_defifindex != ifindex) {
2123 		V_nd6_defifindex = ifindex;
2124 		if (V_nd6_defifindex > 0)
2125 			V_nd6_defifp = ifnet_byindex(V_nd6_defifindex);
2126 		else
2127 			V_nd6_defifp = NULL;
2128 
2129 		/*
2130 		 * Our current implementation assumes one-to-one maping between
2131 		 * interfaces and links, so it would be natural to use the
2132 		 * default interface as the default link.
2133 		 */
2134 		scope6_setdefault(V_nd6_defifp);
2135 	}
2136 
2137 	return (error);
2138 }
2139