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