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