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