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