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