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