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