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