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