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