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