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