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