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