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