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