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