nd6_rtr.c revision 188113
1158115Sume/*-
2158115Sume * Copyright (C) 1995, 1996, 1997, and 1998 WIDE Project.
3158115Sume * All rights reserved.
4158115Sume *
5158115Sume * Redistribution and use in source and binary forms, with or without
6158115Sume * modification, are permitted provided that the following conditions
7158115Sume * are met:
8158115Sume * 1. Redistributions of source code must retain the above copyright
9158115Sume *    notice, this list of conditions and the following disclaimer.
10158115Sume * 2. Redistributions in binary form must reproduce the above copyright
11158115Sume *    notice, this list of conditions and the following disclaimer in the
12158115Sume *    documentation and/or other materials provided with the distribution.
13158115Sume * 3. Neither the name of the project nor the names of its contributors
14158115Sume *    may be used to endorse or promote products derived from this software
15158115Sume *    without specific prior written permission.
16158115Sume *
17158115Sume * THIS SOFTWARE IS PROVIDED BY THE PROJECT AND CONTRIBUTORS ``AS IS'' AND
18158115Sume * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
19158115Sume * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
20158115Sume * ARE DISCLAIMED.  IN NO EVENT SHALL THE PROJECT OR CONTRIBUTORS BE LIABLE
21158115Sume * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
22158115Sume * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
23158115Sume * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
24158115Sume * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
25158115Sume * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
26158115Sume * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
27158115Sume * SUCH DAMAGE.
28158115Sume *
29158115Sume *	$KAME: nd6_rtr.c,v 1.111 2001/04/27 01:37:15 jinmei Exp $
30158115Sume */
31194089Sdes
32194089Sdes#include <sys/cdefs.h>
33158115Sume__FBSDID("$FreeBSD: head/sys/netinet6/nd6_rtr.c 188113 2009-02-04 10:35:27Z bz $");
34158115Sume
35194089Sdes#include "opt_inet.h"
36158115Sume#include "opt_inet6.h"
37158115Sume
38194089Sdes#include <sys/param.h>
39194089Sdes#include <sys/systm.h>
40158115Sume#include <sys/malloc.h>
41158115Sume#include <sys/mbuf.h>
42158115Sume#include <sys/socket.h>
43158115Sume#include <sys/sockio.h>
44158115Sume#include <sys/time.h>
45158115Sume#include <sys/kernel.h>
46158115Sume#include <sys/lock.h>
47158115Sume#include <sys/errno.h>
48158115Sume#include <sys/rwlock.h>
49158115Sume#include <sys/syslog.h>
50158115Sume#include <sys/queue.h>
51158115Sume#include <sys/vimage.h>
52158115Sume
53158115Sume#include <net/if.h>
54158115Sume#include <net/if_types.h>
55158115Sume#include <net/if_dl.h>
56158115Sume#include <net/route.h>
57158115Sume#include <net/radix.h>
58158115Sume#include <net/vnet.h>
59158115Sume
60158115Sume#include <netinet/in.h>
61158115Sume#include <net/if_llatbl.h>
62158115Sume#include <netinet6/in6_var.h>
63158115Sume#include <netinet6/in6_ifattach.h>
64158115Sume#include <netinet/ip6.h>
65158115Sume#include <netinet6/ip6_var.h>
66158115Sume#include <netinet6/nd6.h>
67158115Sume#include <netinet/icmp6.h>
68158115Sume#include <netinet6/scope6_var.h>
69158115Sume#include <netinet6/vinet6.h>
70158115Sume
71158115Sumestatic int rtpref(struct nd_defrouter *);
72158115Sumestatic struct nd_defrouter *defrtrlist_update(struct nd_defrouter *);
73158115Sumestatic int prelist_update __P((struct nd_prefixctl *, struct nd_defrouter *,
74158115Sume    struct mbuf *, int));
75158115Sumestatic struct in6_ifaddr *in6_ifadd(struct nd_prefixctl *,	int);
76158115Sumestatic struct nd_pfxrouter *pfxrtr_lookup __P((struct nd_prefix *,
77158115Sume	struct nd_defrouter *));
78158115Sumestatic void pfxrtr_add(struct nd_prefix *, struct nd_defrouter *);
79158115Sumestatic void pfxrtr_del(struct nd_pfxrouter *);
80158115Sumestatic struct nd_pfxrouter *find_pfxlist_reachable_router
81158115Sume(struct nd_prefix *);
82158115Sumestatic void defrouter_delreq(struct nd_defrouter *);
83158115Sumestatic void nd6_rtmsg(int, struct rtentry *);
84158115Sume
85158115Sumestatic int in6_init_prefix_ltimes(struct nd_prefix *);
86158115Sumestatic void in6_init_address_ltimes __P((struct nd_prefix *,
87158115Sume	struct in6_addrlifetime *));
88158115Sume
89158115Sumestatic int rt6_deleteroute(struct radix_node *, void *);
90158115Sume
91158115Sume#ifdef VIMAGE_GLOBALS
92158115Sumeextern int nd6_recalc_reachtm_interval;
93158115Sume
94158115Sumestatic struct ifnet *nd6_defifp;
95158115Sumeint nd6_defifindex;
96158115Sume
97158115Sumeint ip6_use_tempaddr;
98158115Sumeint ip6_desync_factor;
99158115Sumeu_int32_t ip6_temp_preferred_lifetime;
100158115Sumeu_int32_t ip6_temp_valid_lifetime;
101158115Sumeint ip6_temp_regen_advance;
102158115Sume#endif
103158115Sume
104158115Sume/* RTPREF_MEDIUM has to be 0! */
105158115Sume#define RTPREF_HIGH	1
106158115Sume#define RTPREF_MEDIUM	0
107158115Sume#define RTPREF_LOW	(-1)
108158115Sume#define RTPREF_RESERVED	(-2)
109158115Sume#define RTPREF_INVALID	(-3)	/* internal */
110158115Sume
111158115Sume/*
112158115Sume * Receive Router Solicitation Message - just for routers.
113158115Sume * Router solicitation/advertisement is mostly managed by userland program
114158115Sume * (rtadvd) so here we have no function like nd6_ra_output().
115158115Sume *
116158115Sume * Based on RFC 2461
117158115Sume */
118158115Sumevoid
119158115Sumend6_rs_input(struct mbuf *m, int off, int icmp6len)
120194104Sdes{
121158115Sume	INIT_VNET_INET6(curvnet);
122158115Sume	struct ifnet *ifp = m->m_pkthdr.rcvif;
123158115Sume	struct ip6_hdr *ip6 = mtod(m, struct ip6_hdr *);
124158115Sume	struct nd_router_solicit *nd_rs;
125158115Sume	struct in6_addr saddr6 = ip6->ip6_src;
126158115Sume	char *lladdr = NULL;
127158115Sume	int lladdrlen = 0;
128158115Sume	union nd_opts ndopts;
129158115Sume	char ip6bufs[INET6_ADDRSTRLEN], ip6bufd[INET6_ADDRSTRLEN];
130158115Sume
131158115Sume	/* If I'm not a router, ignore it. */
132158115Sume	if (V_ip6_accept_rtadv != 0 || V_ip6_forwarding != 1)
133158115Sume		goto freeit;
134158115Sume
135158115Sume	/* Sanity checks */
136158115Sume	if (ip6->ip6_hlim != 255) {
137158115Sume		nd6log((LOG_ERR,
138158115Sume		    "nd6_rs_input: invalid hlim (%d) from %s to %s on %s\n",
139158115Sume		    ip6->ip6_hlim, ip6_sprintf(ip6bufs, &ip6->ip6_src),
140158115Sume		    ip6_sprintf(ip6bufd, &ip6->ip6_dst), if_name(ifp)));
141158115Sume		goto bad;
142158115Sume	}
143194096Sdes
144158115Sume	/*
145158115Sume	 * Don't update the neighbor cache, if src = ::.
146158115Sume	 * This indicates that the src has no IP address assigned yet.
147158115Sume	 */
148158115Sume	if (IN6_IS_ADDR_UNSPECIFIED(&saddr6))
149158115Sume		goto freeit;
150158115Sume
151158115Sume#ifndef PULLDOWN_TEST
152158115Sume	IP6_EXTHDR_CHECK(m, off, icmp6len,);
153158115Sume	nd_rs = (struct nd_router_solicit *)((caddr_t)ip6 + off);
154158115Sume#else
155158115Sume	IP6_EXTHDR_GET(nd_rs, struct nd_router_solicit *, m, off, icmp6len);
156158115Sume	if (nd_rs == NULL) {
157158115Sume		V_icmp6stat.icp6s_tooshort++;
158158115Sume		return;
159158115Sume	}
160158115Sume#endif
161158115Sume
162158115Sume	icmp6len -= sizeof(*nd_rs);
163158115Sume	nd6_option_init(nd_rs + 1, icmp6len, &ndopts);
164158115Sume	if (nd6_options(&ndopts) < 0) {
165158115Sume		nd6log((LOG_INFO,
166158115Sume		    "nd6_rs_input: invalid ND option, ignored\n"));
167158115Sume		/* nd6_options have incremented stats */
168158115Sume		goto freeit;
169158115Sume	}
170158115Sume
171158115Sume	if (ndopts.nd_opts_src_lladdr) {
172158115Sume		lladdr = (char *)(ndopts.nd_opts_src_lladdr + 1);
173158115Sume		lladdrlen = ndopts.nd_opts_src_lladdr->nd_opt_len << 3;
174158115Sume	}
175158115Sume
176158115Sume	if (lladdr && ((ifp->if_addrlen + 2 + 7) & ~7) != lladdrlen) {
177158115Sume		nd6log((LOG_INFO,
178158115Sume		    "nd6_rs_input: lladdrlen mismatch for %s "
179158115Sume		    "(if %d, RS packet %d)\n",
180158115Sume		    ip6_sprintf(ip6bufs, &saddr6),
181158115Sume		    ifp->if_addrlen, lladdrlen - 2));
182158115Sume		goto bad;
183158115Sume	}
184158115Sume
185158115Sume	nd6_cache_lladdr(ifp, &saddr6, lladdr, lladdrlen, ND_ROUTER_SOLICIT, 0);
186158115Sume
187158115Sume freeit:
188158115Sume	m_freem(m);
189158115Sume	return;
190158115Sume
191158115Sume bad:
192158115Sume	V_icmp6stat.icp6s_badrs++;
193158115Sume	m_freem(m);
194158115Sume}
195158115Sume
196158115Sume/*
197158115Sume * Receive Router Advertisement Message.
198158115Sume *
199158115Sume * Based on RFC 2461
200158115Sume * TODO: on-link bit on prefix information
201194097Sdes * TODO: ND_RA_FLAG_{OTHER,MANAGED} processing
202158115Sume */
203171795Sbushmanvoid
204158115Sumend6_ra_input(struct mbuf *m, int off, int icmp6len)
205158115Sume{
206158115Sume	INIT_VNET_INET6(curvnet);
207158115Sume	struct ifnet *ifp = m->m_pkthdr.rcvif;
208158115Sume	struct nd_ifinfo *ndi = ND_IFINFO(ifp);
209158115Sume	struct ip6_hdr *ip6 = mtod(m, struct ip6_hdr *);
210158115Sume	struct nd_router_advert *nd_ra;
211194097Sdes	struct in6_addr saddr6 = ip6->ip6_src;
212158115Sume	int mcast = 0;
213158115Sume	union nd_opts ndopts;
214158115Sume	struct nd_defrouter *dr;
215158115Sume	char ip6bufs[INET6_ADDRSTRLEN], ip6bufd[INET6_ADDRSTRLEN];
216158115Sume
217158115Sume	/*
218158115Sume	 * We only accept RAs only when
219158115Sume	 * the system-wide variable allows the acceptance, and
220158115Sume	 * per-interface variable allows RAs on the receiving interface.
221158115Sume	 */
222158115Sume	if (V_ip6_accept_rtadv == 0)
223158115Sume		goto freeit;
224158115Sume	if (!(ndi->flags & ND6_IFF_ACCEPT_RTADV))
225158115Sume		goto freeit;
226158115Sume
227158115Sume	if (ip6->ip6_hlim != 255) {
228158115Sume		nd6log((LOG_ERR,
229158115Sume		    "nd6_ra_input: invalid hlim (%d) from %s to %s on %s\n",
230158115Sume		    ip6->ip6_hlim, ip6_sprintf(ip6bufs, &ip6->ip6_src),
231158115Sume		    ip6_sprintf(ip6bufd, &ip6->ip6_dst), if_name(ifp)));
232158115Sume		goto bad;
233158115Sume	}
234158115Sume
235158115Sume	if (!IN6_IS_ADDR_LINKLOCAL(&saddr6)) {
236158115Sume		nd6log((LOG_ERR,
237158115Sume		    "nd6_ra_input: src %s is not link-local\n",
238158115Sume		    ip6_sprintf(ip6bufs, &saddr6)));
239158115Sume		goto bad;
240158115Sume	}
241158115Sume
242158115Sume#ifndef PULLDOWN_TEST
243158115Sume	IP6_EXTHDR_CHECK(m, off, icmp6len,);
244158115Sume	nd_ra = (struct nd_router_advert *)((caddr_t)ip6 + off);
245158115Sume#else
246158115Sume	IP6_EXTHDR_GET(nd_ra, struct nd_router_advert *, m, off, icmp6len);
247158115Sume	if (nd_ra == NULL) {
248158115Sume		V_icmp6stat.icp6s_tooshort++;
249158115Sume		return;
250158115Sume	}
251158115Sume#endif
252158115Sume
253158115Sume	icmp6len -= sizeof(*nd_ra);
254158115Sume	nd6_option_init(nd_ra + 1, icmp6len, &ndopts);
255158115Sume	if (nd6_options(&ndopts) < 0) {
256158115Sume		nd6log((LOG_INFO,
257158115Sume		    "nd6_ra_input: invalid ND option, ignored\n"));
258158115Sume		/* nd6_options have incremented stats */
259158115Sume		goto freeit;
260158115Sume	}
261158115Sume
262158115Sume    {
263158115Sume	struct nd_defrouter dr0;
264158115Sume	u_int32_t advreachable = nd_ra->nd_ra_reachable;
265158115Sume
266158115Sume	/* remember if this is a multicasted advertisement */
267158115Sume	if (IN6_IS_ADDR_MULTICAST(&ip6->ip6_dst))
268158115Sume		mcast = 1;
269158115Sume
270158115Sume	bzero(&dr0, sizeof(dr0));
271158115Sume	dr0.rtaddr = saddr6;
272158115Sume	dr0.flags  = nd_ra->nd_ra_flags_reserved;
273158115Sume	dr0.rtlifetime = ntohs(nd_ra->nd_ra_router_lifetime);
274158115Sume	dr0.expire = time_second + dr0.rtlifetime;
275158115Sume	dr0.ifp = ifp;
276158115Sume	/* unspecified or not? (RFC 2461 6.3.4) */
277158115Sume	if (advreachable) {
278158115Sume		advreachable = ntohl(advreachable);
279158115Sume		if (advreachable <= MAX_REACHABLE_TIME &&
280158115Sume		    ndi->basereachable != advreachable) {
281158115Sume			ndi->basereachable = advreachable;
282158115Sume			ndi->reachable = ND_COMPUTE_RTIME(ndi->basereachable);
283158115Sume			ndi->recalctm = V_nd6_recalc_reachtm_interval; /* reset */
284158115Sume		}
285158115Sume	}
286158115Sume	if (nd_ra->nd_ra_retransmit)
287158115Sume		ndi->retrans = ntohl(nd_ra->nd_ra_retransmit);
288158115Sume	if (nd_ra->nd_ra_curhoplimit)
289158115Sume		ndi->chlim = nd_ra->nd_ra_curhoplimit;
290158115Sume	dr = defrtrlist_update(&dr0);
291158115Sume    }
292158115Sume
293158115Sume	/*
294158115Sume	 * prefix
295158115Sume	 */
296158115Sume	if (ndopts.nd_opts_pi) {
297158115Sume		struct nd_opt_hdr *pt;
298158115Sume		struct nd_opt_prefix_info *pi = NULL;
299158115Sume		struct nd_prefixctl pr;
300158115Sume
301158115Sume		for (pt = (struct nd_opt_hdr *)ndopts.nd_opts_pi;
302158115Sume		     pt <= (struct nd_opt_hdr *)ndopts.nd_opts_pi_end;
303158115Sume		     pt = (struct nd_opt_hdr *)((caddr_t)pt +
304158115Sume						(pt->nd_opt_len << 3))) {
305158115Sume			if (pt->nd_opt_type != ND_OPT_PREFIX_INFORMATION)
306158115Sume				continue;
307158115Sume			pi = (struct nd_opt_prefix_info *)pt;
308158115Sume
309158115Sume			if (pi->nd_opt_pi_len != 4) {
310158115Sume				nd6log((LOG_INFO,
311158115Sume				    "nd6_ra_input: invalid option "
312158115Sume				    "len %d for prefix information option, "
313158115Sume				    "ignored\n", pi->nd_opt_pi_len));
314158115Sume				continue;
315158115Sume			}
316158115Sume
317158115Sume			if (128 < pi->nd_opt_pi_prefix_len) {
318158115Sume				nd6log((LOG_INFO,
319158115Sume				    "nd6_ra_input: invalid prefix "
320158115Sume				    "len %d for prefix information option, "
321158115Sume				    "ignored\n", pi->nd_opt_pi_prefix_len));
322158115Sume				continue;
323158115Sume			}
324158115Sume
325158115Sume			if (IN6_IS_ADDR_MULTICAST(&pi->nd_opt_pi_prefix)
326158115Sume			 || IN6_IS_ADDR_LINKLOCAL(&pi->nd_opt_pi_prefix)) {
327158115Sume				nd6log((LOG_INFO,
328158115Sume				    "nd6_ra_input: invalid prefix "
329158115Sume				    "%s, ignored\n",
330158115Sume				    ip6_sprintf(ip6bufs,
331158115Sume					&pi->nd_opt_pi_prefix)));
332158115Sume				continue;
333158115Sume			}
334158115Sume
335158115Sume			bzero(&pr, sizeof(pr));
336158115Sume			pr.ndpr_prefix.sin6_family = AF_INET6;
337158115Sume			pr.ndpr_prefix.sin6_len = sizeof(pr.ndpr_prefix);
338158115Sume			pr.ndpr_prefix.sin6_addr = pi->nd_opt_pi_prefix;
339158115Sume			pr.ndpr_ifp = (struct ifnet *)m->m_pkthdr.rcvif;
340158115Sume
341158115Sume			pr.ndpr_raf_onlink = (pi->nd_opt_pi_flags_reserved &
342158115Sume			    ND_OPT_PI_FLAG_ONLINK) ? 1 : 0;
343158115Sume			pr.ndpr_raf_auto = (pi->nd_opt_pi_flags_reserved &
344158115Sume			    ND_OPT_PI_FLAG_AUTO) ? 1 : 0;
345158115Sume			pr.ndpr_plen = pi->nd_opt_pi_prefix_len;
346158115Sume			pr.ndpr_vltime = ntohl(pi->nd_opt_pi_valid_time);
347158115Sume			pr.ndpr_pltime = ntohl(pi->nd_opt_pi_preferred_time);
348158115Sume			(void)prelist_update(&pr, dr, m, mcast);
349158115Sume		}
350158115Sume	}
351158115Sume
352158115Sume	/*
353158115Sume	 * MTU
354158115Sume	 */
355158115Sume	if (ndopts.nd_opts_mtu && ndopts.nd_opts_mtu->nd_opt_mtu_len == 1) {
356158115Sume		u_long mtu;
357158115Sume		u_long maxmtu;
358158115Sume
359158115Sume		mtu = (u_long)ntohl(ndopts.nd_opts_mtu->nd_opt_mtu_mtu);
360158115Sume
361158115Sume		/* lower bound */
362158115Sume		if (mtu < IPV6_MMTU) {
363158115Sume			nd6log((LOG_INFO, "nd6_ra_input: bogus mtu option "
364158115Sume			    "mtu=%lu sent from %s, ignoring\n",
365158115Sume			    mtu, ip6_sprintf(ip6bufs, &ip6->ip6_src)));
366158115Sume			goto skip;
367158115Sume		}
368158115Sume
369158115Sume		/* upper bound */
370158115Sume		maxmtu = (ndi->maxmtu && ndi->maxmtu < ifp->if_mtu)
371158115Sume		    ? ndi->maxmtu : ifp->if_mtu;
372158115Sume		if (mtu <= maxmtu) {
373158115Sume			int change = (ndi->linkmtu != mtu);
374158115Sume
375158115Sume			ndi->linkmtu = mtu;
376158115Sume			if (change) /* in6_maxmtu may change */
377158115Sume				in6_setmaxmtu();
378158115Sume		} else {
379158115Sume			nd6log((LOG_INFO, "nd6_ra_input: bogus mtu "
380158115Sume			    "mtu=%lu sent from %s; "
381158115Sume			    "exceeds maxmtu %lu, ignoring\n",
382158115Sume			    mtu, ip6_sprintf(ip6bufs, &ip6->ip6_src), maxmtu));
383158115Sume		}
384158115Sume	}
385158115Sume
386158115Sume skip:
387158115Sume
388158115Sume	/*
389158115Sume	 * Source link layer address
390158115Sume	 */
391158115Sume    {
392158115Sume	char *lladdr = NULL;
393158115Sume	int lladdrlen = 0;
394158115Sume
395158115Sume	if (ndopts.nd_opts_src_lladdr) {
396158115Sume		lladdr = (char *)(ndopts.nd_opts_src_lladdr + 1);
397158115Sume		lladdrlen = ndopts.nd_opts_src_lladdr->nd_opt_len << 3;
398158115Sume	}
399158115Sume
400158115Sume	if (lladdr && ((ifp->if_addrlen + 2 + 7) & ~7) != lladdrlen) {
401158115Sume		nd6log((LOG_INFO,
402158115Sume		    "nd6_ra_input: lladdrlen mismatch for %s "
403158115Sume		    "(if %d, RA packet %d)\n", ip6_sprintf(ip6bufs, &saddr6),
404158115Sume		    ifp->if_addrlen, lladdrlen - 2));
405158115Sume		goto bad;
406158115Sume	}
407158115Sume
408158115Sume	nd6_cache_lladdr(ifp, &saddr6, lladdr,
409158115Sume	    lladdrlen, ND_ROUTER_ADVERT, 0);
410158115Sume
411158115Sume	/*
412158115Sume	 * Installing a link-layer address might change the state of the
413158115Sume	 * router's neighbor cache, which might also affect our on-link
414158115Sume	 * detection of adveritsed prefixes.
415158115Sume	 */
416158115Sume	pfxlist_onlink_check();
417158115Sume    }
418158115Sume
419158115Sume freeit:
420158115Sume	m_freem(m);
421158115Sume	return;
422158115Sume
423158115Sume bad:
424158115Sume	V_icmp6stat.icp6s_badra++;
425158115Sume	m_freem(m);
426158115Sume}
427158115Sume
428158115Sume/*
429158115Sume * default router list proccessing sub routines
430158115Sume */
431194104Sdes
432158115Sume/* tell the change to user processes watching the routing socket. */
433158115Sumestatic void
434158115Sumend6_rtmsg(int cmd, struct rtentry *rt)
435158115Sume{
436158115Sume	struct rt_addrinfo info;
437158115Sume
438158115Sume	bzero((caddr_t)&info, sizeof(info));
439158115Sume	info.rti_info[RTAX_DST] = rt_key(rt);
440158115Sume	info.rti_info[RTAX_GATEWAY] = rt->rt_gateway;
441158115Sume	info.rti_info[RTAX_NETMASK] = rt_mask(rt);
442158115Sume	if (rt->rt_ifp) {
443158115Sume		info.rti_info[RTAX_IFP] =
444158115Sume		    TAILQ_FIRST(&rt->rt_ifp->if_addrlist)->ifa_addr;
445158115Sume		info.rti_info[RTAX_IFA] = rt->rt_ifa->ifa_addr;
446158115Sume	}
447158115Sume
448158115Sume	rt_missmsg(cmd, &info, rt->rt_flags, 0);
449158115Sume}
450158115Sume
451158115Sumevoid
452158115Sumedefrouter_addreq(struct nd_defrouter *new)
453158115Sume{
454158115Sume	struct sockaddr_in6 def, mask, gate;
455158115Sume	struct rtentry *newrt = NULL;
456158115Sume	int s;
457158115Sume	int error;
458158115Sume
459158115Sume	bzero(&def, sizeof(def));
460158115Sume	bzero(&mask, sizeof(mask));
461158115Sume	bzero(&gate, sizeof(gate));
462158115Sume
463158115Sume	def.sin6_len = mask.sin6_len = gate.sin6_len =
464158115Sume	    sizeof(struct sockaddr_in6);
465158115Sume	def.sin6_family = gate.sin6_family = AF_INET6;
466194096Sdes	gate.sin6_addr = new->rtaddr;
467158115Sume
468158115Sume	s = splnet();
469158115Sume	error = rtrequest(RTM_ADD, (struct sockaddr *)&def,
470158115Sume	    (struct sockaddr *)&gate, (struct sockaddr *)&mask,
471158115Sume	    RTF_GATEWAY, &newrt);
472158115Sume	if (newrt) {
473158115Sume		nd6_rtmsg(RTM_ADD, newrt); /* tell user process */
474158115Sume		RTFREE(newrt);
475158115Sume	}
476194096Sdes	if (error == 0)
477158115Sume		new->installed = 1;
478158115Sume	splx(s);
479158115Sume	return;
480158115Sume}
481158115Sume
482158115Sumestruct nd_defrouter *
483158115Sumedefrouter_lookup(struct in6_addr *addr, struct ifnet *ifp)
484158115Sume{
485158115Sume	INIT_VNET_INET6(ifp->if_vnet);
486158115Sume	struct nd_defrouter *dr;
487158115Sume
488158115Sume	for (dr = TAILQ_FIRST(&V_nd_defrouter); dr;
489158115Sume	     dr = TAILQ_NEXT(dr, dr_entry)) {
490158115Sume		if (dr->ifp == ifp && IN6_ARE_ADDR_EQUAL(addr, &dr->rtaddr))
491158115Sume			return (dr);
492158115Sume	}
493158115Sume
494158115Sume	return (NULL);		/* search failed */
495158115Sume}
496158115Sume
497158115Sume/*
498158115Sume * Remove the default route for a given router.
499158115Sume * This is just a subroutine function for defrouter_select(), and should
500158115Sume * not be called from anywhere else.
501158115Sume */
502194096Sdesstatic void
503158115Sumedefrouter_delreq(struct nd_defrouter *dr)
504158115Sume{
505158115Sume	struct sockaddr_in6 def, mask, gate;
506158115Sume	struct rtentry *oldrt = NULL;
507158115Sume
508158115Sume	bzero(&def, sizeof(def));
509158115Sume	bzero(&mask, sizeof(mask));
510158115Sume	bzero(&gate, sizeof(gate));
511158115Sume
512158115Sume	def.sin6_len = mask.sin6_len = gate.sin6_len =
513158115Sume	    sizeof(struct sockaddr_in6);
514158115Sume	def.sin6_family = gate.sin6_family = AF_INET6;
515158115Sume	gate.sin6_addr = dr->rtaddr;
516158115Sume
517158115Sume	rtrequest(RTM_DELETE, (struct sockaddr *)&def,
518158115Sume	    (struct sockaddr *)&gate,
519158115Sume	    (struct sockaddr *)&mask, RTF_GATEWAY, &oldrt);
520158115Sume	if (oldrt) {
521158115Sume		nd6_rtmsg(RTM_DELETE, oldrt);
522158115Sume		RTFREE(oldrt);
523158115Sume	}
524158115Sume
525158115Sume	dr->installed = 0;
526158115Sume}
527158115Sume
528158115Sume/*
529158115Sume * remove all default routes from default router list
530158115Sume */
531158115Sumevoid
532158115Sumedefrouter_reset(void)
533158115Sume{
534158115Sume	INIT_VNET_INET6(curvnet);
535158115Sume	struct nd_defrouter *dr;
536158115Sume
537158115Sume	for (dr = TAILQ_FIRST(&V_nd_defrouter); dr;
538	     dr = TAILQ_NEXT(dr, dr_entry))
539		defrouter_delreq(dr);
540
541	/*
542	 * XXX should we also nuke any default routers in the kernel, by
543	 * going through them by rtalloc1()?
544	 */
545}
546
547void
548defrtrlist_del(struct nd_defrouter *dr)
549{
550	INIT_VNET_INET6(curvnet);
551	struct nd_defrouter *deldr = NULL;
552	struct nd_prefix *pr;
553
554	/*
555	 * Flush all the routing table entries that use the router
556	 * as a next hop.
557	 */
558	if (!V_ip6_forwarding && V_ip6_accept_rtadv) /* XXX: better condition? */
559		rt6_flush(&dr->rtaddr, dr->ifp);
560
561	if (dr->installed) {
562		deldr = dr;
563		defrouter_delreq(dr);
564	}
565	TAILQ_REMOVE(&V_nd_defrouter, dr, dr_entry);
566
567	/*
568	 * Also delete all the pointers to the router in each prefix lists.
569	 */
570	for (pr = V_nd_prefix.lh_first; pr; pr = pr->ndpr_next) {
571		struct nd_pfxrouter *pfxrtr;
572		if ((pfxrtr = pfxrtr_lookup(pr, dr)) != NULL)
573			pfxrtr_del(pfxrtr);
574	}
575	pfxlist_onlink_check();
576
577	/*
578	 * If the router is the primary one, choose a new one.
579	 * Note that defrouter_select() will remove the current gateway
580	 * from the routing table.
581	 */
582	if (deldr)
583		defrouter_select();
584
585	free(dr, M_IP6NDP);
586}
587
588/*
589 * Default Router Selection according to Section 6.3.6 of RFC 2461 and
590 * draft-ietf-ipngwg-router-selection:
591 * 1) Routers that are reachable or probably reachable should be preferred.
592 *    If we have more than one (probably) reachable router, prefer ones
593 *    with the highest router preference.
594 * 2) When no routers on the list are known to be reachable or
595 *    probably reachable, routers SHOULD be selected in a round-robin
596 *    fashion, regardless of router preference values.
597 * 3) If the Default Router List is empty, assume that all
598 *    destinations are on-link.
599 *
600 * We assume nd_defrouter is sorted by router preference value.
601 * Since the code below covers both with and without router preference cases,
602 * we do not need to classify the cases by ifdef.
603 *
604 * At this moment, we do not try to install more than one default router,
605 * even when the multipath routing is available, because we're not sure about
606 * the benefits for stub hosts comparing to the risk of making the code
607 * complicated and the possibility of introducing bugs.
608 */
609void
610defrouter_select(void)
611{
612	INIT_VNET_INET6(curvnet);
613	int s = splnet();
614	struct nd_defrouter *dr, *selected_dr = NULL, *installed_dr = NULL;
615	struct llentry *ln = NULL;
616
617	/*
618	 * This function should be called only when acting as an autoconfigured
619	 * host.  Although the remaining part of this function is not effective
620	 * if the node is not an autoconfigured host, we explicitly exclude
621	 * such cases here for safety.
622	 */
623	if (V_ip6_forwarding || !V_ip6_accept_rtadv) {
624		nd6log((LOG_WARNING,
625		    "defrouter_select: called unexpectedly (forwarding=%d, "
626		    "accept_rtadv=%d)\n", V_ip6_forwarding, V_ip6_accept_rtadv));
627		splx(s);
628		return;
629	}
630
631	/*
632	 * Let's handle easy case (3) first:
633	 * If default router list is empty, there's nothing to be done.
634	 */
635	if (!TAILQ_FIRST(&V_nd_defrouter)) {
636		splx(s);
637		return;
638	}
639
640	/*
641	 * Search for a (probably) reachable router from the list.
642	 * We just pick up the first reachable one (if any), assuming that
643	 * the ordering rule of the list described in defrtrlist_update().
644	 */
645	for (dr = TAILQ_FIRST(&V_nd_defrouter); dr;
646	     dr = TAILQ_NEXT(dr, dr_entry)) {
647		IF_AFDATA_LOCK(dr->ifp);
648		if (selected_dr == NULL &&
649		    (ln = nd6_lookup(&dr->rtaddr, 0, dr->ifp)) &&
650		    ND6_IS_LLINFO_PROBREACH(ln)) {
651			selected_dr = dr;
652		}
653		IF_AFDATA_UNLOCK(dr->ifp);
654		if (ln != NULL) {
655			LLE_RUNLOCK(ln);
656			ln = NULL;
657		}
658
659		if (dr->installed && installed_dr == NULL)
660			installed_dr = dr;
661		else if (dr->installed && installed_dr) {
662			/* this should not happen.  warn for diagnosis. */
663			log(LOG_ERR, "defrouter_select: more than one router"
664			    " is installed\n");
665		}
666	}
667	/*
668	 * If none of the default routers was found to be reachable,
669	 * round-robin the list regardless of preference.
670	 * Otherwise, if we have an installed router, check if the selected
671	 * (reachable) router should really be preferred to the installed one.
672	 * We only prefer the new router when the old one is not reachable
673	 * or when the new one has a really higher preference value.
674	 */
675	if (selected_dr == NULL) {
676		if (installed_dr == NULL || !TAILQ_NEXT(installed_dr, dr_entry))
677			selected_dr = TAILQ_FIRST(&V_nd_defrouter);
678		else
679			selected_dr = TAILQ_NEXT(installed_dr, dr_entry);
680	} else if (installed_dr) {
681		IF_AFDATA_LOCK(installed_dr->ifp);
682		if ((ln = nd6_lookup(&installed_dr->rtaddr, 0, installed_dr->ifp)) &&
683		    ND6_IS_LLINFO_PROBREACH(ln) &&
684		    rtpref(selected_dr) <= rtpref(installed_dr)) {
685			selected_dr = installed_dr;
686		}
687		IF_AFDATA_UNLOCK(installed_dr->ifp);
688		if (ln != NULL)
689			LLE_RUNLOCK(ln);
690	}
691
692	/*
693	 * If the selected router is different than the installed one,
694	 * remove the installed router and install the selected one.
695	 * Note that the selected router is never NULL here.
696	 */
697	if (installed_dr != selected_dr) {
698		if (installed_dr)
699			defrouter_delreq(installed_dr);
700		defrouter_addreq(selected_dr);
701	}
702
703	splx(s);
704	return;
705}
706
707/*
708 * for default router selection
709 * regards router-preference field as a 2-bit signed integer
710 */
711static int
712rtpref(struct nd_defrouter *dr)
713{
714	switch (dr->flags & ND_RA_FLAG_RTPREF_MASK) {
715	case ND_RA_FLAG_RTPREF_HIGH:
716		return (RTPREF_HIGH);
717	case ND_RA_FLAG_RTPREF_MEDIUM:
718	case ND_RA_FLAG_RTPREF_RSV:
719		return (RTPREF_MEDIUM);
720	case ND_RA_FLAG_RTPREF_LOW:
721		return (RTPREF_LOW);
722	default:
723		/*
724		 * This case should never happen.  If it did, it would mean a
725		 * serious bug of kernel internal.  We thus always bark here.
726		 * Or, can we even panic?
727		 */
728		log(LOG_ERR, "rtpref: impossible RA flag %x\n", dr->flags);
729		return (RTPREF_INVALID);
730	}
731	/* NOTREACHED */
732}
733
734static struct nd_defrouter *
735defrtrlist_update(struct nd_defrouter *new)
736{
737	INIT_VNET_INET6(curvnet);
738	struct nd_defrouter *dr, *n;
739	int s = splnet();
740
741	if ((dr = defrouter_lookup(&new->rtaddr, new->ifp)) != NULL) {
742		/* entry exists */
743		if (new->rtlifetime == 0) {
744			defrtrlist_del(dr);
745			dr = NULL;
746		} else {
747			int oldpref = rtpref(dr);
748
749			/* override */
750			dr->flags = new->flags; /* xxx flag check */
751			dr->rtlifetime = new->rtlifetime;
752			dr->expire = new->expire;
753
754			/*
755			 * If the preference does not change, there's no need
756			 * to sort the entries.
757			 */
758			if (rtpref(new) == oldpref) {
759				splx(s);
760				return (dr);
761			}
762
763			/*
764			 * preferred router may be changed, so relocate
765			 * this router.
766			 * XXX: calling TAILQ_REMOVE directly is a bad manner.
767			 * However, since defrtrlist_del() has many side
768			 * effects, we intentionally do so here.
769			 * defrouter_select() below will handle routing
770			 * changes later.
771			 */
772			TAILQ_REMOVE(&V_nd_defrouter, dr, dr_entry);
773			n = dr;
774			goto insert;
775		}
776		splx(s);
777		return (dr);
778	}
779
780	/* entry does not exist */
781	if (new->rtlifetime == 0) {
782		splx(s);
783		return (NULL);
784	}
785
786	n = (struct nd_defrouter *)malloc(sizeof(*n), M_IP6NDP, M_NOWAIT);
787	if (n == NULL) {
788		splx(s);
789		return (NULL);
790	}
791	bzero(n, sizeof(*n));
792	*n = *new;
793
794insert:
795	/*
796	 * Insert the new router in the Default Router List;
797	 * The Default Router List should be in the descending order
798	 * of router-preferece.  Routers with the same preference are
799	 * sorted in the arriving time order.
800	 */
801
802	/* insert at the end of the group */
803	for (dr = TAILQ_FIRST(&V_nd_defrouter); dr;
804	     dr = TAILQ_NEXT(dr, dr_entry)) {
805		if (rtpref(n) > rtpref(dr))
806			break;
807	}
808	if (dr)
809		TAILQ_INSERT_BEFORE(dr, n, dr_entry);
810	else
811		TAILQ_INSERT_TAIL(&V_nd_defrouter, n, dr_entry);
812
813	defrouter_select();
814
815	splx(s);
816
817	return (n);
818}
819
820static struct nd_pfxrouter *
821pfxrtr_lookup(struct nd_prefix *pr, struct nd_defrouter *dr)
822{
823	struct nd_pfxrouter *search;
824
825	for (search = pr->ndpr_advrtrs.lh_first; search; search = search->pfr_next) {
826		if (search->router == dr)
827			break;
828	}
829
830	return (search);
831}
832
833static void
834pfxrtr_add(struct nd_prefix *pr, struct nd_defrouter *dr)
835{
836	struct nd_pfxrouter *new;
837
838	new = (struct nd_pfxrouter *)malloc(sizeof(*new), M_IP6NDP, M_NOWAIT);
839	if (new == NULL)
840		return;
841	bzero(new, sizeof(*new));
842	new->router = dr;
843
844	LIST_INSERT_HEAD(&pr->ndpr_advrtrs, new, pfr_entry);
845
846	pfxlist_onlink_check();
847}
848
849static void
850pfxrtr_del(struct nd_pfxrouter *pfr)
851{
852	LIST_REMOVE(pfr, pfr_entry);
853	free(pfr, M_IP6NDP);
854}
855
856struct nd_prefix *
857nd6_prefix_lookup(struct nd_prefixctl *key)
858{
859	INIT_VNET_INET6(curvnet);
860	struct nd_prefix *search;
861
862	for (search = V_nd_prefix.lh_first;
863	    search; search = search->ndpr_next) {
864		if (key->ndpr_ifp == search->ndpr_ifp &&
865		    key->ndpr_plen == search->ndpr_plen &&
866		    in6_are_prefix_equal(&key->ndpr_prefix.sin6_addr,
867		    &search->ndpr_prefix.sin6_addr, key->ndpr_plen)) {
868			break;
869		}
870	}
871
872	return (search);
873}
874
875int
876nd6_prelist_add(struct nd_prefixctl *pr, struct nd_defrouter *dr,
877    struct nd_prefix **newp)
878{
879	INIT_VNET_INET6(curvnet);
880	struct nd_prefix *new = NULL;
881	int error = 0;
882	int i, s;
883	char ip6buf[INET6_ADDRSTRLEN];
884
885	new = (struct nd_prefix *)malloc(sizeof(*new), M_IP6NDP, M_NOWAIT);
886	if (new == NULL)
887		return(ENOMEM);
888	bzero(new, sizeof(*new));
889	new->ndpr_ifp = pr->ndpr_ifp;
890	new->ndpr_prefix = pr->ndpr_prefix;
891	new->ndpr_plen = pr->ndpr_plen;
892	new->ndpr_vltime = pr->ndpr_vltime;
893	new->ndpr_pltime = pr->ndpr_pltime;
894	new->ndpr_flags = pr->ndpr_flags;
895	if ((error = in6_init_prefix_ltimes(new)) != 0) {
896		free(new, M_IP6NDP);
897		return(error);
898	}
899	new->ndpr_lastupdate = time_second;
900	if (newp != NULL)
901		*newp = new;
902
903	/* initialization */
904	LIST_INIT(&new->ndpr_advrtrs);
905	in6_prefixlen2mask(&new->ndpr_mask, new->ndpr_plen);
906	/* make prefix in the canonical form */
907	for (i = 0; i < 4; i++)
908		new->ndpr_prefix.sin6_addr.s6_addr32[i] &=
909		    new->ndpr_mask.s6_addr32[i];
910
911	s = splnet();
912	/* link ndpr_entry to nd_prefix list */
913	LIST_INSERT_HEAD(&V_nd_prefix, new, ndpr_entry);
914	splx(s);
915
916	/* ND_OPT_PI_FLAG_ONLINK processing */
917	if (new->ndpr_raf_onlink) {
918		int e;
919
920		if ((e = nd6_prefix_onlink(new)) != 0) {
921			nd6log((LOG_ERR, "nd6_prelist_add: failed to make "
922			    "the prefix %s/%d on-link on %s (errno=%d)\n",
923			    ip6_sprintf(ip6buf, &pr->ndpr_prefix.sin6_addr),
924			    pr->ndpr_plen, if_name(pr->ndpr_ifp), e));
925			/* proceed anyway. XXX: is it correct? */
926		}
927	}
928
929	if (dr)
930		pfxrtr_add(new, dr);
931
932	return 0;
933}
934
935void
936prelist_remove(struct nd_prefix *pr)
937{
938	INIT_VNET_INET6(curvnet);
939	struct nd_pfxrouter *pfr, *next;
940	int e, s;
941	char ip6buf[INET6_ADDRSTRLEN];
942
943	/* make sure to invalidate the prefix until it is really freed. */
944	pr->ndpr_vltime = 0;
945	pr->ndpr_pltime = 0;
946
947	/*
948	 * Though these flags are now meaningless, we'd rather keep the value
949	 * of pr->ndpr_raf_onlink and pr->ndpr_raf_auto not to confuse users
950	 * when executing "ndp -p".
951	 */
952
953	if ((pr->ndpr_stateflags & NDPRF_ONLINK) != 0 &&
954	    (e = nd6_prefix_offlink(pr)) != 0) {
955		nd6log((LOG_ERR, "prelist_remove: failed to make %s/%d offlink "
956		    "on %s, errno=%d\n",
957		    ip6_sprintf(ip6buf, &pr->ndpr_prefix.sin6_addr),
958		    pr->ndpr_plen, if_name(pr->ndpr_ifp), e));
959		/* what should we do? */
960	}
961
962	if (pr->ndpr_refcnt > 0)
963		return;		/* notice here? */
964
965	s = splnet();
966
967	/* unlink ndpr_entry from nd_prefix list */
968	LIST_REMOVE(pr, ndpr_entry);
969
970	/* free list of routers that adversed the prefix */
971	for (pfr = pr->ndpr_advrtrs.lh_first; pfr; pfr = next) {
972		next = pfr->pfr_next;
973
974		free(pfr, M_IP6NDP);
975	}
976	splx(s);
977
978	free(pr, M_IP6NDP);
979
980	pfxlist_onlink_check();
981}
982
983/*
984 * dr - may be NULL
985 */
986
987static int
988prelist_update(struct nd_prefixctl *new, struct nd_defrouter *dr,
989    struct mbuf *m, int mcast)
990{
991	INIT_VNET_INET6(curvnet);
992	struct in6_ifaddr *ia6 = NULL, *ia6_match = NULL;
993	struct ifaddr *ifa;
994	struct ifnet *ifp = new->ndpr_ifp;
995	struct nd_prefix *pr;
996	int s = splnet();
997	int error = 0;
998	int newprefix = 0;
999	int auth;
1000	struct in6_addrlifetime lt6_tmp;
1001	char ip6buf[INET6_ADDRSTRLEN];
1002
1003	auth = 0;
1004	if (m) {
1005		/*
1006		 * Authenticity for NA consists authentication for
1007		 * both IP header and IP datagrams, doesn't it ?
1008		 */
1009#if defined(M_AUTHIPHDR) && defined(M_AUTHIPDGM)
1010		auth = ((m->m_flags & M_AUTHIPHDR) &&
1011		    (m->m_flags & M_AUTHIPDGM));
1012#endif
1013	}
1014
1015	if ((pr = nd6_prefix_lookup(new)) != NULL) {
1016		/*
1017		 * nd6_prefix_lookup() ensures that pr and new have the same
1018		 * prefix on a same interface.
1019		 */
1020
1021		/*
1022		 * Update prefix information.  Note that the on-link (L) bit
1023		 * and the autonomous (A) bit should NOT be changed from 1
1024		 * to 0.
1025		 */
1026		if (new->ndpr_raf_onlink == 1)
1027			pr->ndpr_raf_onlink = 1;
1028		if (new->ndpr_raf_auto == 1)
1029			pr->ndpr_raf_auto = 1;
1030		if (new->ndpr_raf_onlink) {
1031			pr->ndpr_vltime = new->ndpr_vltime;
1032			pr->ndpr_pltime = new->ndpr_pltime;
1033			(void)in6_init_prefix_ltimes(pr); /* XXX error case? */
1034			pr->ndpr_lastupdate = time_second;
1035		}
1036
1037		if (new->ndpr_raf_onlink &&
1038		    (pr->ndpr_stateflags & NDPRF_ONLINK) == 0) {
1039			int e;
1040
1041			if ((e = nd6_prefix_onlink(pr)) != 0) {
1042				nd6log((LOG_ERR,
1043				    "prelist_update: failed to make "
1044				    "the prefix %s/%d on-link on %s "
1045				    "(errno=%d)\n",
1046				    ip6_sprintf(ip6buf,
1047					    &pr->ndpr_prefix.sin6_addr),
1048				    pr->ndpr_plen, if_name(pr->ndpr_ifp), e));
1049				/* proceed anyway. XXX: is it correct? */
1050			}
1051		}
1052
1053		if (dr && pfxrtr_lookup(pr, dr) == NULL)
1054			pfxrtr_add(pr, dr);
1055	} else {
1056		struct nd_prefix *newpr = NULL;
1057
1058		newprefix = 1;
1059
1060		if (new->ndpr_vltime == 0)
1061			goto end;
1062		if (new->ndpr_raf_onlink == 0 && new->ndpr_raf_auto == 0)
1063			goto end;
1064
1065		error = nd6_prelist_add(new, dr, &newpr);
1066		if (error != 0 || newpr == NULL) {
1067			nd6log((LOG_NOTICE, "prelist_update: "
1068			    "nd6_prelist_add failed for %s/%d on %s "
1069			    "errno=%d, returnpr=%p\n",
1070			    ip6_sprintf(ip6buf, &new->ndpr_prefix.sin6_addr),
1071			    new->ndpr_plen, if_name(new->ndpr_ifp),
1072			    error, newpr));
1073			goto end; /* we should just give up in this case. */
1074		}
1075
1076		/*
1077		 * XXX: from the ND point of view, we can ignore a prefix
1078		 * with the on-link bit being zero.  However, we need a
1079		 * prefix structure for references from autoconfigured
1080		 * addresses.  Thus, we explicitly make sure that the prefix
1081		 * itself expires now.
1082		 */
1083		if (newpr->ndpr_raf_onlink == 0) {
1084			newpr->ndpr_vltime = 0;
1085			newpr->ndpr_pltime = 0;
1086			in6_init_prefix_ltimes(newpr);
1087		}
1088
1089		pr = newpr;
1090	}
1091
1092	/*
1093	 * Address autoconfiguration based on Section 5.5.3 of RFC 2462.
1094	 * Note that pr must be non NULL at this point.
1095	 */
1096
1097	/* 5.5.3 (a). Ignore the prefix without the A bit set. */
1098	if (!new->ndpr_raf_auto)
1099		goto end;
1100
1101	/*
1102	 * 5.5.3 (b). the link-local prefix should have been ignored in
1103	 * nd6_ra_input.
1104	 */
1105
1106	/* 5.5.3 (c). Consistency check on lifetimes: pltime <= vltime. */
1107	if (new->ndpr_pltime > new->ndpr_vltime) {
1108		error = EINVAL;	/* XXX: won't be used */
1109		goto end;
1110	}
1111
1112	/*
1113	 * 5.5.3 (d).  If the prefix advertised is not equal to the prefix of
1114	 * an address configured by stateless autoconfiguration already in the
1115	 * list of addresses associated with the interface, and the Valid
1116	 * Lifetime is not 0, form an address.  We first check if we have
1117	 * a matching prefix.
1118	 * Note: we apply a clarification in rfc2462bis-02 here.  We only
1119	 * consider autoconfigured addresses while RFC2462 simply said
1120	 * "address".
1121	 */
1122	TAILQ_FOREACH(ifa, &ifp->if_addrlist, ifa_list) {
1123		struct in6_ifaddr *ifa6;
1124		u_int32_t remaininglifetime;
1125
1126		if (ifa->ifa_addr->sa_family != AF_INET6)
1127			continue;
1128
1129		ifa6 = (struct in6_ifaddr *)ifa;
1130
1131		/*
1132		 * We only consider autoconfigured addresses as per rfc2462bis.
1133		 */
1134		if (!(ifa6->ia6_flags & IN6_IFF_AUTOCONF))
1135			continue;
1136
1137		/*
1138		 * Spec is not clear here, but I believe we should concentrate
1139		 * on unicast (i.e. not anycast) addresses.
1140		 * XXX: other ia6_flags? detached or duplicated?
1141		 */
1142		if ((ifa6->ia6_flags & IN6_IFF_ANYCAST) != 0)
1143			continue;
1144
1145		/*
1146		 * Ignore the address if it is not associated with a prefix
1147		 * or is associated with a prefix that is different from this
1148		 * one.  (pr is never NULL here)
1149		 */
1150		if (ifa6->ia6_ndpr != pr)
1151			continue;
1152
1153		if (ia6_match == NULL) /* remember the first one */
1154			ia6_match = ifa6;
1155
1156		/*
1157		 * An already autoconfigured address matched.  Now that we
1158		 * are sure there is at least one matched address, we can
1159		 * proceed to 5.5.3. (e): update the lifetimes according to the
1160		 * "two hours" rule and the privacy extension.
1161		 * We apply some clarifications in rfc2462bis:
1162		 * - use remaininglifetime instead of storedlifetime as a
1163		 *   variable name
1164		 * - remove the dead code in the "two-hour" rule
1165		 */
1166#define TWOHOUR		(120*60)
1167		lt6_tmp = ifa6->ia6_lifetime;
1168
1169		if (lt6_tmp.ia6t_vltime == ND6_INFINITE_LIFETIME)
1170			remaininglifetime = ND6_INFINITE_LIFETIME;
1171		else if (time_second - ifa6->ia6_updatetime >
1172			 lt6_tmp.ia6t_vltime) {
1173			/*
1174			 * The case of "invalid" address.  We should usually
1175			 * not see this case.
1176			 */
1177			remaininglifetime = 0;
1178		} else
1179			remaininglifetime = lt6_tmp.ia6t_vltime -
1180			    (time_second - ifa6->ia6_updatetime);
1181
1182		/* when not updating, keep the current stored lifetime. */
1183		lt6_tmp.ia6t_vltime = remaininglifetime;
1184
1185		if (TWOHOUR < new->ndpr_vltime ||
1186		    remaininglifetime < new->ndpr_vltime) {
1187			lt6_tmp.ia6t_vltime = new->ndpr_vltime;
1188		} else if (remaininglifetime <= TWOHOUR) {
1189			if (auth) {
1190				lt6_tmp.ia6t_vltime = new->ndpr_vltime;
1191			}
1192		} else {
1193			/*
1194			 * new->ndpr_vltime <= TWOHOUR &&
1195			 * TWOHOUR < remaininglifetime
1196			 */
1197			lt6_tmp.ia6t_vltime = TWOHOUR;
1198		}
1199
1200		/* The 2 hour rule is not imposed for preferred lifetime. */
1201		lt6_tmp.ia6t_pltime = new->ndpr_pltime;
1202
1203		in6_init_address_ltimes(pr, &lt6_tmp);
1204
1205		/*
1206		 * We need to treat lifetimes for temporary addresses
1207		 * differently, according to
1208		 * draft-ietf-ipv6-privacy-addrs-v2-01.txt 3.3 (1);
1209		 * we only update the lifetimes when they are in the maximum
1210		 * intervals.
1211		 */
1212		if ((ifa6->ia6_flags & IN6_IFF_TEMPORARY) != 0) {
1213			u_int32_t maxvltime, maxpltime;
1214
1215			if (V_ip6_temp_valid_lifetime >
1216			    (u_int32_t)((time_second - ifa6->ia6_createtime) +
1217			    V_ip6_desync_factor)) {
1218				maxvltime = V_ip6_temp_valid_lifetime -
1219				    (time_second - ifa6->ia6_createtime) -
1220				    V_ip6_desync_factor;
1221			} else
1222				maxvltime = 0;
1223			if (V_ip6_temp_preferred_lifetime >
1224			    (u_int32_t)((time_second - ifa6->ia6_createtime) +
1225			    V_ip6_desync_factor)) {
1226				maxpltime = V_ip6_temp_preferred_lifetime -
1227				    (time_second - ifa6->ia6_createtime) -
1228				    V_ip6_desync_factor;
1229			} else
1230				maxpltime = 0;
1231
1232			if (lt6_tmp.ia6t_vltime == ND6_INFINITE_LIFETIME ||
1233			    lt6_tmp.ia6t_vltime > maxvltime) {
1234				lt6_tmp.ia6t_vltime = maxvltime;
1235			}
1236			if (lt6_tmp.ia6t_pltime == ND6_INFINITE_LIFETIME ||
1237			    lt6_tmp.ia6t_pltime > maxpltime) {
1238				lt6_tmp.ia6t_pltime = maxpltime;
1239			}
1240		}
1241		ifa6->ia6_lifetime = lt6_tmp;
1242		ifa6->ia6_updatetime = time_second;
1243	}
1244	if (ia6_match == NULL && new->ndpr_vltime) {
1245		int ifidlen;
1246
1247		/*
1248		 * 5.5.3 (d) (continued)
1249		 * No address matched and the valid lifetime is non-zero.
1250		 * Create a new address.
1251		 */
1252
1253		/*
1254		 * Prefix Length check:
1255		 * If the sum of the prefix length and interface identifier
1256		 * length does not equal 128 bits, the Prefix Information
1257		 * option MUST be ignored.  The length of the interface
1258		 * identifier is defined in a separate link-type specific
1259		 * document.
1260		 */
1261		ifidlen = in6_if2idlen(ifp);
1262		if (ifidlen < 0) {
1263			/* this should not happen, so we always log it. */
1264			log(LOG_ERR, "prelist_update: IFID undefined (%s)\n",
1265			    if_name(ifp));
1266			goto end;
1267		}
1268		if (ifidlen + pr->ndpr_plen != 128) {
1269			nd6log((LOG_INFO,
1270			    "prelist_update: invalid prefixlen "
1271			    "%d for %s, ignored\n",
1272			    pr->ndpr_plen, if_name(ifp)));
1273			goto end;
1274		}
1275
1276		if ((ia6 = in6_ifadd(new, mcast)) != NULL) {
1277			/*
1278			 * note that we should use pr (not new) for reference.
1279			 */
1280			pr->ndpr_refcnt++;
1281			ia6->ia6_ndpr = pr;
1282
1283			/*
1284			 * RFC 3041 3.3 (2).
1285			 * When a new public address is created as described
1286			 * in RFC2462, also create a new temporary address.
1287			 *
1288			 * RFC 3041 3.5.
1289			 * When an interface connects to a new link, a new
1290			 * randomized interface identifier should be generated
1291			 * immediately together with a new set of temporary
1292			 * addresses.  Thus, we specifiy 1 as the 2nd arg of
1293			 * in6_tmpifadd().
1294			 */
1295			if (V_ip6_use_tempaddr) {
1296				int e;
1297				if ((e = in6_tmpifadd(ia6, 1, 1)) != 0) {
1298					nd6log((LOG_NOTICE, "prelist_update: "
1299					    "failed to create a temporary "
1300					    "address, errno=%d\n",
1301					    e));
1302				}
1303			}
1304
1305			/*
1306			 * A newly added address might affect the status
1307			 * of other addresses, so we check and update it.
1308			 * XXX: what if address duplication happens?
1309			 */
1310			pfxlist_onlink_check();
1311		} else {
1312			/* just set an error. do not bark here. */
1313			error = EADDRNOTAVAIL; /* XXX: might be unused. */
1314		}
1315	}
1316
1317 end:
1318	splx(s);
1319	return error;
1320}
1321
1322/*
1323 * A supplement function used in the on-link detection below;
1324 * detect if a given prefix has a (probably) reachable advertising router.
1325 * XXX: lengthy function name...
1326 */
1327static struct nd_pfxrouter *
1328find_pfxlist_reachable_router(struct nd_prefix *pr)
1329{
1330	struct nd_pfxrouter *pfxrtr;
1331	struct llentry *ln;
1332	int canreach;
1333
1334	for (pfxrtr = LIST_FIRST(&pr->ndpr_advrtrs); pfxrtr != NULL;
1335	     pfxrtr = LIST_NEXT(pfxrtr, pfr_entry)) {
1336		IF_AFDATA_LOCK(pfxrtr->router->ifp);
1337		ln = nd6_lookup(&pfxrtr->router->rtaddr, 0, pfxrtr->router->ifp);
1338		IF_AFDATA_UNLOCK(pfxrtr->router->ifp);
1339		if (ln == NULL)
1340			continue;
1341		canreach = ND6_IS_LLINFO_PROBREACH(ln);
1342		LLE_RUNLOCK(ln);
1343		if (canreach)
1344			break;
1345	}
1346	return (pfxrtr);
1347}
1348
1349/*
1350 * Check if each prefix in the prefix list has at least one available router
1351 * that advertised the prefix (a router is "available" if its neighbor cache
1352 * entry is reachable or probably reachable).
1353 * If the check fails, the prefix may be off-link, because, for example,
1354 * we have moved from the network but the lifetime of the prefix has not
1355 * expired yet.  So we should not use the prefix if there is another prefix
1356 * that has an available router.
1357 * But, if there is no prefix that has an available router, we still regards
1358 * all the prefixes as on-link.  This is because we can't tell if all the
1359 * routers are simply dead or if we really moved from the network and there
1360 * is no router around us.
1361 */
1362void
1363pfxlist_onlink_check()
1364{
1365	INIT_VNET_INET6(curvnet);
1366	struct nd_prefix *pr;
1367	struct in6_ifaddr *ifa;
1368	struct nd_defrouter *dr;
1369	struct nd_pfxrouter *pfxrtr = NULL;
1370
1371	/*
1372	 * Check if there is a prefix that has a reachable advertising
1373	 * router.
1374	 */
1375	for (pr = V_nd_prefix.lh_first; pr; pr = pr->ndpr_next) {
1376		if (pr->ndpr_raf_onlink && find_pfxlist_reachable_router(pr))
1377			break;
1378	}
1379
1380	/*
1381	 * If we have no such prefix, check whether we still have a router
1382	 * that does not advertise any prefixes.
1383	 */
1384	if (pr == NULL) {
1385		for (dr = TAILQ_FIRST(&V_nd_defrouter); dr;
1386		    dr = TAILQ_NEXT(dr, dr_entry)) {
1387			struct nd_prefix *pr0;
1388
1389			for (pr0 = V_nd_prefix.lh_first; pr0;
1390			    pr0 = pr0->ndpr_next) {
1391				if ((pfxrtr = pfxrtr_lookup(pr0, dr)) != NULL)
1392					break;
1393			}
1394			if (pfxrtr != NULL)
1395				break;
1396		}
1397	}
1398	if (pr != NULL || (TAILQ_FIRST(&V_nd_defrouter) && pfxrtr == NULL)) {
1399		/*
1400		 * There is at least one prefix that has a reachable router,
1401		 * or at least a router which probably does not advertise
1402		 * any prefixes.  The latter would be the case when we move
1403		 * to a new link where we have a router that does not provide
1404		 * prefixes and we configure an address by hand.
1405		 * Detach prefixes which have no reachable advertising
1406		 * router, and attach other prefixes.
1407		 */
1408		for (pr = V_nd_prefix.lh_first; pr; pr = pr->ndpr_next) {
1409			/* XXX: a link-local prefix should never be detached */
1410			if (IN6_IS_ADDR_LINKLOCAL(&pr->ndpr_prefix.sin6_addr))
1411				continue;
1412
1413			/*
1414			 * we aren't interested in prefixes without the L bit
1415			 * set.
1416			 */
1417			if (pr->ndpr_raf_onlink == 0)
1418				continue;
1419
1420			if ((pr->ndpr_stateflags & NDPRF_DETACHED) == 0 &&
1421			    find_pfxlist_reachable_router(pr) == NULL)
1422				pr->ndpr_stateflags |= NDPRF_DETACHED;
1423			if ((pr->ndpr_stateflags & NDPRF_DETACHED) != 0 &&
1424			    find_pfxlist_reachable_router(pr) != 0)
1425				pr->ndpr_stateflags &= ~NDPRF_DETACHED;
1426		}
1427	} else {
1428		/* there is no prefix that has a reachable router */
1429		for (pr = V_nd_prefix.lh_first; pr; pr = pr->ndpr_next) {
1430			if (IN6_IS_ADDR_LINKLOCAL(&pr->ndpr_prefix.sin6_addr))
1431				continue;
1432
1433			if (pr->ndpr_raf_onlink == 0)
1434				continue;
1435
1436			if ((pr->ndpr_stateflags & NDPRF_DETACHED) != 0)
1437				pr->ndpr_stateflags &= ~NDPRF_DETACHED;
1438		}
1439	}
1440
1441	/*
1442	 * Remove each interface route associated with a (just) detached
1443	 * prefix, and reinstall the interface route for a (just) attached
1444	 * prefix.  Note that all attempt of reinstallation does not
1445	 * necessarily success, when a same prefix is shared among multiple
1446	 * interfaces.  Such cases will be handled in nd6_prefix_onlink,
1447	 * so we don't have to care about them.
1448	 */
1449	for (pr = V_nd_prefix.lh_first; pr; pr = pr->ndpr_next) {
1450		int e;
1451		char ip6buf[INET6_ADDRSTRLEN];
1452
1453		if (IN6_IS_ADDR_LINKLOCAL(&pr->ndpr_prefix.sin6_addr))
1454			continue;
1455
1456		if (pr->ndpr_raf_onlink == 0)
1457			continue;
1458
1459		if ((pr->ndpr_stateflags & NDPRF_DETACHED) != 0 &&
1460		    (pr->ndpr_stateflags & NDPRF_ONLINK) != 0) {
1461			if ((e = nd6_prefix_offlink(pr)) != 0) {
1462				nd6log((LOG_ERR,
1463				    "pfxlist_onlink_check: failed to "
1464				    "make %s/%d offlink, errno=%d\n",
1465				    ip6_sprintf(ip6buf,
1466					    &pr->ndpr_prefix.sin6_addr),
1467					    pr->ndpr_plen, e));
1468			}
1469		}
1470		if ((pr->ndpr_stateflags & NDPRF_DETACHED) == 0 &&
1471		    (pr->ndpr_stateflags & NDPRF_ONLINK) == 0 &&
1472		    pr->ndpr_raf_onlink) {
1473			if ((e = nd6_prefix_onlink(pr)) != 0) {
1474				nd6log((LOG_ERR,
1475				    "pfxlist_onlink_check: failed to "
1476				    "make %s/%d onlink, errno=%d\n",
1477				    ip6_sprintf(ip6buf,
1478					    &pr->ndpr_prefix.sin6_addr),
1479					    pr->ndpr_plen, e));
1480			}
1481		}
1482	}
1483
1484	/*
1485	 * Changes on the prefix status might affect address status as well.
1486	 * Make sure that all addresses derived from an attached prefix are
1487	 * attached, and that all addresses derived from a detached prefix are
1488	 * detached.  Note, however, that a manually configured address should
1489	 * always be attached.
1490	 * The precise detection logic is same as the one for prefixes.
1491	 */
1492	for (ifa = V_in6_ifaddr; ifa; ifa = ifa->ia_next) {
1493		if (!(ifa->ia6_flags & IN6_IFF_AUTOCONF))
1494			continue;
1495
1496		if (ifa->ia6_ndpr == NULL) {
1497			/*
1498			 * This can happen when we first configure the address
1499			 * (i.e. the address exists, but the prefix does not).
1500			 * XXX: complicated relationships...
1501			 */
1502			continue;
1503		}
1504
1505		if (find_pfxlist_reachable_router(ifa->ia6_ndpr))
1506			break;
1507	}
1508	if (ifa) {
1509		for (ifa = V_in6_ifaddr; ifa; ifa = ifa->ia_next) {
1510			if ((ifa->ia6_flags & IN6_IFF_AUTOCONF) == 0)
1511				continue;
1512
1513			if (ifa->ia6_ndpr == NULL) /* XXX: see above. */
1514				continue;
1515
1516			if (find_pfxlist_reachable_router(ifa->ia6_ndpr)) {
1517				if (ifa->ia6_flags & IN6_IFF_DETACHED) {
1518					ifa->ia6_flags &= ~IN6_IFF_DETACHED;
1519					ifa->ia6_flags |= IN6_IFF_TENTATIVE;
1520					nd6_dad_start((struct ifaddr *)ifa, 0);
1521				}
1522			} else {
1523				ifa->ia6_flags |= IN6_IFF_DETACHED;
1524			}
1525		}
1526	}
1527	else {
1528		for (ifa = V_in6_ifaddr; ifa; ifa = ifa->ia_next) {
1529			if ((ifa->ia6_flags & IN6_IFF_AUTOCONF) == 0)
1530				continue;
1531
1532			if (ifa->ia6_flags & IN6_IFF_DETACHED) {
1533				ifa->ia6_flags &= ~IN6_IFF_DETACHED;
1534				ifa->ia6_flags |= IN6_IFF_TENTATIVE;
1535				/* Do we need a delay in this case? */
1536				nd6_dad_start((struct ifaddr *)ifa, 0);
1537			}
1538		}
1539	}
1540}
1541
1542int
1543nd6_prefix_onlink(struct nd_prefix *pr)
1544{
1545	INIT_VNET_INET6(curvnet);
1546	struct ifaddr *ifa;
1547	struct ifnet *ifp = pr->ndpr_ifp;
1548	struct sockaddr_in6 mask6;
1549	struct nd_prefix *opr;
1550	u_long rtflags;
1551	int error = 0;
1552	struct radix_node_head *rnh;
1553	struct rtentry *rt = NULL;
1554	char ip6buf[INET6_ADDRSTRLEN];
1555	struct sockaddr_dl null_sdl = {sizeof(null_sdl), AF_LINK};
1556
1557	/* sanity check */
1558	if ((pr->ndpr_stateflags & NDPRF_ONLINK) != 0) {
1559		nd6log((LOG_ERR,
1560		    "nd6_prefix_onlink: %s/%d is already on-link\n",
1561		    ip6_sprintf(ip6buf, &pr->ndpr_prefix.sin6_addr),
1562		    pr->ndpr_plen));
1563		return (EEXIST);
1564	}
1565
1566	/*
1567	 * Add the interface route associated with the prefix.  Before
1568	 * installing the route, check if there's the same prefix on another
1569	 * interface, and the prefix has already installed the interface route.
1570	 * Although such a configuration is expected to be rare, we explicitly
1571	 * allow it.
1572	 */
1573	for (opr = V_nd_prefix.lh_first; opr; opr = opr->ndpr_next) {
1574		if (opr == pr)
1575			continue;
1576
1577		if ((opr->ndpr_stateflags & NDPRF_ONLINK) == 0)
1578			continue;
1579
1580		if (opr->ndpr_plen == pr->ndpr_plen &&
1581		    in6_are_prefix_equal(&pr->ndpr_prefix.sin6_addr,
1582		    &opr->ndpr_prefix.sin6_addr, pr->ndpr_plen))
1583			return (0);
1584	}
1585
1586	/*
1587	 * We prefer link-local addresses as the associated interface address.
1588	 */
1589	/* search for a link-local addr */
1590	ifa = (struct ifaddr *)in6ifa_ifpforlinklocal(ifp,
1591	    IN6_IFF_NOTREADY | IN6_IFF_ANYCAST);
1592	if (ifa == NULL) {
1593		/* XXX: freebsd does not have ifa_ifwithaf */
1594		TAILQ_FOREACH(ifa, &ifp->if_addrlist, ifa_list) {
1595			if (ifa->ifa_addr->sa_family == AF_INET6)
1596				break;
1597		}
1598		/* should we care about ia6_flags? */
1599	}
1600	if (ifa == NULL) {
1601		/*
1602		 * This can still happen, when, for example, we receive an RA
1603		 * containing a prefix with the L bit set and the A bit clear,
1604		 * after removing all IPv6 addresses on the receiving
1605		 * interface.  This should, of course, be rare though.
1606		 */
1607		nd6log((LOG_NOTICE,
1608		    "nd6_prefix_onlink: failed to find any ifaddr"
1609		    " to add route for a prefix(%s/%d) on %s\n",
1610		    ip6_sprintf(ip6buf, &pr->ndpr_prefix.sin6_addr),
1611		    pr->ndpr_plen, if_name(ifp)));
1612		return (0);
1613	}
1614
1615	/*
1616	 * in6_ifinit() sets nd6_rtrequest to ifa_rtrequest for all ifaddrs.
1617	 * ifa->ifa_rtrequest = nd6_rtrequest;
1618	 */
1619	bzero(&mask6, sizeof(mask6));
1620	mask6.sin6_len = sizeof(mask6);
1621	mask6.sin6_addr = pr->ndpr_mask;
1622	rtflags = ifa->ifa_flags | RTF_UP;
1623	error = rtrequest(RTM_ADD, (struct sockaddr *)&pr->ndpr_prefix,
1624	    ifa->ifa_addr, (struct sockaddr *)&mask6, rtflags, &rt);
1625	if (error == 0) {
1626		if (rt != NULL) /* this should be non NULL, though */ {
1627			rnh = V_rt_tables[rt->rt_fibnum][AF_INET6];
1628			RADIX_NODE_HEAD_LOCK(rnh);
1629			RT_LOCK(rt);
1630			if (!rt_setgate(rt, rt_key(rt), (struct sockaddr *)&null_sdl)) {
1631				((struct sockaddr_dl *)rt->rt_gateway)->sdl_type =
1632					rt->rt_ifp->if_type;
1633				((struct sockaddr_dl *)rt->rt_gateway)->sdl_index =
1634					rt->rt_ifp->if_index;
1635			}
1636			RADIX_NODE_HEAD_UNLOCK(rnh);
1637			nd6_rtmsg(RTM_ADD, rt);
1638			RT_UNLOCK(rt);
1639		}
1640		pr->ndpr_stateflags |= NDPRF_ONLINK;
1641	} else {
1642		char ip6bufg[INET6_ADDRSTRLEN], ip6bufm[INET6_ADDRSTRLEN];
1643		nd6log((LOG_ERR, "nd6_prefix_onlink: failed to add route for a"
1644		    " prefix (%s/%d) on %s, gw=%s, mask=%s, flags=%lx "
1645		    "errno = %d\n",
1646		    ip6_sprintf(ip6buf, &pr->ndpr_prefix.sin6_addr),
1647		    pr->ndpr_plen, if_name(ifp),
1648		    ip6_sprintf(ip6bufg, &((struct sockaddr_in6 *)ifa->ifa_addr)->sin6_addr),
1649		    ip6_sprintf(ip6bufm, &mask6.sin6_addr), rtflags, error));
1650	}
1651
1652	if (rt != NULL) {
1653		RT_LOCK(rt);
1654		RT_REMREF(rt);
1655		RT_UNLOCK(rt);
1656	}
1657
1658	return (error);
1659}
1660
1661int
1662nd6_prefix_offlink(struct nd_prefix *pr)
1663{
1664	INIT_VNET_INET6(curvnet);
1665	int error = 0;
1666	struct ifnet *ifp = pr->ndpr_ifp;
1667	struct nd_prefix *opr;
1668	struct sockaddr_in6 sa6, mask6;
1669	struct rtentry *rt = NULL;
1670	char ip6buf[INET6_ADDRSTRLEN];
1671
1672	/* sanity check */
1673	if ((pr->ndpr_stateflags & NDPRF_ONLINK) == 0) {
1674		nd6log((LOG_ERR,
1675		    "nd6_prefix_offlink: %s/%d is already off-link\n",
1676		    ip6_sprintf(ip6buf, &pr->ndpr_prefix.sin6_addr),
1677		    pr->ndpr_plen));
1678		return (EEXIST);
1679	}
1680
1681	bzero(&sa6, sizeof(sa6));
1682	sa6.sin6_family = AF_INET6;
1683	sa6.sin6_len = sizeof(sa6);
1684	bcopy(&pr->ndpr_prefix.sin6_addr, &sa6.sin6_addr,
1685	    sizeof(struct in6_addr));
1686	bzero(&mask6, sizeof(mask6));
1687	mask6.sin6_family = AF_INET6;
1688	mask6.sin6_len = sizeof(sa6);
1689	bcopy(&pr->ndpr_mask, &mask6.sin6_addr, sizeof(struct in6_addr));
1690	error = rtrequest(RTM_DELETE, (struct sockaddr *)&sa6, NULL,
1691	    (struct sockaddr *)&mask6, 0, &rt);
1692	if (error == 0) {
1693		pr->ndpr_stateflags &= ~NDPRF_ONLINK;
1694
1695		/* report the route deletion to the routing socket. */
1696		if (rt != NULL)
1697			nd6_rtmsg(RTM_DELETE, rt);
1698
1699		/*
1700		 * There might be the same prefix on another interface,
1701		 * the prefix which could not be on-link just because we have
1702		 * the interface route (see comments in nd6_prefix_onlink).
1703		 * If there's one, try to make the prefix on-link on the
1704		 * interface.
1705		 */
1706		for (opr = V_nd_prefix.lh_first; opr; opr = opr->ndpr_next) {
1707			if (opr == pr)
1708				continue;
1709
1710			if ((opr->ndpr_stateflags & NDPRF_ONLINK) != 0)
1711				continue;
1712
1713			/*
1714			 * KAME specific: detached prefixes should not be
1715			 * on-link.
1716			 */
1717			if ((opr->ndpr_stateflags & NDPRF_DETACHED) != 0)
1718				continue;
1719
1720			if (opr->ndpr_plen == pr->ndpr_plen &&
1721			    in6_are_prefix_equal(&pr->ndpr_prefix.sin6_addr,
1722			    &opr->ndpr_prefix.sin6_addr, pr->ndpr_plen)) {
1723				int e;
1724
1725				if ((e = nd6_prefix_onlink(opr)) != 0) {
1726					nd6log((LOG_ERR,
1727					    "nd6_prefix_offlink: failed to "
1728					    "recover a prefix %s/%d from %s "
1729					    "to %s (errno = %d)\n",
1730					    ip6_sprintf(ip6buf,
1731						&opr->ndpr_prefix.sin6_addr),
1732					    opr->ndpr_plen, if_name(ifp),
1733					    if_name(opr->ndpr_ifp), e));
1734				}
1735			}
1736		}
1737	} else {
1738		/* XXX: can we still set the NDPRF_ONLINK flag? */
1739		nd6log((LOG_ERR,
1740		    "nd6_prefix_offlink: failed to delete route: "
1741		    "%s/%d on %s (errno = %d)\n",
1742		    ip6_sprintf(ip6buf, &sa6.sin6_addr), pr->ndpr_plen,
1743		    if_name(ifp), error));
1744	}
1745
1746	if (rt != NULL) {
1747		RTFREE(rt);
1748	}
1749
1750	return (error);
1751}
1752
1753static struct in6_ifaddr *
1754in6_ifadd(struct nd_prefixctl *pr, int mcast)
1755{
1756	INIT_VNET_INET6(curvnet);
1757	struct ifnet *ifp = pr->ndpr_ifp;
1758	struct ifaddr *ifa;
1759	struct in6_aliasreq ifra;
1760	struct in6_ifaddr *ia, *ib;
1761	int error, plen0;
1762	struct in6_addr mask;
1763	int prefixlen = pr->ndpr_plen;
1764	int updateflags;
1765	char ip6buf[INET6_ADDRSTRLEN];
1766
1767	in6_prefixlen2mask(&mask, prefixlen);
1768
1769	/*
1770	 * find a link-local address (will be interface ID).
1771	 * Is it really mandatory? Theoretically, a global or a site-local
1772	 * address can be configured without a link-local address, if we
1773	 * have a unique interface identifier...
1774	 *
1775	 * it is not mandatory to have a link-local address, we can generate
1776	 * interface identifier on the fly.  we do this because:
1777	 * (1) it should be the easiest way to find interface identifier.
1778	 * (2) RFC2462 5.4 suggesting the use of the same interface identifier
1779	 * for multiple addresses on a single interface, and possible shortcut
1780	 * of DAD.  we omitted DAD for this reason in the past.
1781	 * (3) a user can prevent autoconfiguration of global address
1782	 * by removing link-local address by hand (this is partly because we
1783	 * don't have other way to control the use of IPv6 on an interface.
1784	 * this has been our design choice - cf. NRL's "ifconfig auto").
1785	 * (4) it is easier to manage when an interface has addresses
1786	 * with the same interface identifier, than to have multiple addresses
1787	 * with different interface identifiers.
1788	 */
1789	ifa = (struct ifaddr *)in6ifa_ifpforlinklocal(ifp, 0); /* 0 is OK? */
1790	if (ifa)
1791		ib = (struct in6_ifaddr *)ifa;
1792	else
1793		return NULL;
1794
1795	/* prefixlen + ifidlen must be equal to 128 */
1796	plen0 = in6_mask2len(&ib->ia_prefixmask.sin6_addr, NULL);
1797	if (prefixlen != plen0) {
1798		nd6log((LOG_INFO, "in6_ifadd: wrong prefixlen for %s "
1799		    "(prefix=%d ifid=%d)\n",
1800		    if_name(ifp), prefixlen, 128 - plen0));
1801		return NULL;
1802	}
1803
1804	/* make ifaddr */
1805
1806	bzero(&ifra, sizeof(ifra));
1807	/*
1808	 * in6_update_ifa() does not use ifra_name, but we accurately set it
1809	 * for safety.
1810	 */
1811	strncpy(ifra.ifra_name, if_name(ifp), sizeof(ifra.ifra_name));
1812	ifra.ifra_addr.sin6_family = AF_INET6;
1813	ifra.ifra_addr.sin6_len = sizeof(struct sockaddr_in6);
1814	/* prefix */
1815	ifra.ifra_addr.sin6_addr = pr->ndpr_prefix.sin6_addr;
1816	ifra.ifra_addr.sin6_addr.s6_addr32[0] &= mask.s6_addr32[0];
1817	ifra.ifra_addr.sin6_addr.s6_addr32[1] &= mask.s6_addr32[1];
1818	ifra.ifra_addr.sin6_addr.s6_addr32[2] &= mask.s6_addr32[2];
1819	ifra.ifra_addr.sin6_addr.s6_addr32[3] &= mask.s6_addr32[3];
1820
1821	/* interface ID */
1822	ifra.ifra_addr.sin6_addr.s6_addr32[0] |=
1823	    (ib->ia_addr.sin6_addr.s6_addr32[0] & ~mask.s6_addr32[0]);
1824	ifra.ifra_addr.sin6_addr.s6_addr32[1] |=
1825	    (ib->ia_addr.sin6_addr.s6_addr32[1] & ~mask.s6_addr32[1]);
1826	ifra.ifra_addr.sin6_addr.s6_addr32[2] |=
1827	    (ib->ia_addr.sin6_addr.s6_addr32[2] & ~mask.s6_addr32[2]);
1828	ifra.ifra_addr.sin6_addr.s6_addr32[3] |=
1829	    (ib->ia_addr.sin6_addr.s6_addr32[3] & ~mask.s6_addr32[3]);
1830
1831	/* new prefix mask. */
1832	ifra.ifra_prefixmask.sin6_len = sizeof(struct sockaddr_in6);
1833	ifra.ifra_prefixmask.sin6_family = AF_INET6;
1834	bcopy(&mask, &ifra.ifra_prefixmask.sin6_addr,
1835	    sizeof(ifra.ifra_prefixmask.sin6_addr));
1836
1837	/* lifetimes. */
1838	ifra.ifra_lifetime.ia6t_vltime = pr->ndpr_vltime;
1839	ifra.ifra_lifetime.ia6t_pltime = pr->ndpr_pltime;
1840
1841	/* XXX: scope zone ID? */
1842
1843	ifra.ifra_flags |= IN6_IFF_AUTOCONF; /* obey autoconf */
1844
1845	/*
1846	 * Make sure that we do not have this address already.  This should
1847	 * usually not happen, but we can still see this case, e.g., if we
1848	 * have manually configured the exact address to be configured.
1849	 */
1850	if (in6ifa_ifpwithaddr(ifp, &ifra.ifra_addr.sin6_addr) != NULL) {
1851		/* this should be rare enough to make an explicit log */
1852		log(LOG_INFO, "in6_ifadd: %s is already configured\n",
1853		    ip6_sprintf(ip6buf, &ifra.ifra_addr.sin6_addr));
1854		return (NULL);
1855	}
1856
1857	/*
1858	 * Allocate ifaddr structure, link into chain, etc.
1859	 * If we are going to create a new address upon receiving a multicasted
1860	 * RA, we need to impose a random delay before starting DAD.
1861	 * [draft-ietf-ipv6-rfc2462bis-02.txt, Section 5.4.2]
1862	 */
1863	updateflags = 0;
1864	if (mcast)
1865		updateflags |= IN6_IFAUPDATE_DADDELAY;
1866	if ((error = in6_update_ifa(ifp, &ifra, NULL, updateflags)) != 0) {
1867		nd6log((LOG_ERR,
1868		    "in6_ifadd: failed to make ifaddr %s on %s (errno=%d)\n",
1869		    ip6_sprintf(ip6buf, &ifra.ifra_addr.sin6_addr),
1870		    if_name(ifp), error));
1871		return (NULL);	/* ifaddr must not have been allocated. */
1872	}
1873
1874	ia = in6ifa_ifpwithaddr(ifp, &ifra.ifra_addr.sin6_addr);
1875
1876	return (ia);		/* this is always non-NULL */
1877}
1878
1879/*
1880 * ia0 - corresponding public address
1881 */
1882int
1883in6_tmpifadd(const struct in6_ifaddr *ia0, int forcegen, int delay)
1884{
1885	INIT_VNET_INET6(curvnet);
1886	struct ifnet *ifp = ia0->ia_ifa.ifa_ifp;
1887	struct in6_ifaddr *newia, *ia;
1888	struct in6_aliasreq ifra;
1889	int i, error;
1890	int trylimit = 3;	/* XXX: adhoc value */
1891	int updateflags;
1892	u_int32_t randid[2];
1893	time_t vltime0, pltime0;
1894
1895	bzero(&ifra, sizeof(ifra));
1896	strncpy(ifra.ifra_name, if_name(ifp), sizeof(ifra.ifra_name));
1897	ifra.ifra_addr = ia0->ia_addr;
1898	/* copy prefix mask */
1899	ifra.ifra_prefixmask = ia0->ia_prefixmask;
1900	/* clear the old IFID */
1901	for (i = 0; i < 4; i++) {
1902		ifra.ifra_addr.sin6_addr.s6_addr32[i] &=
1903		    ifra.ifra_prefixmask.sin6_addr.s6_addr32[i];
1904	}
1905
1906  again:
1907	if (in6_get_tmpifid(ifp, (u_int8_t *)randid,
1908	    (const u_int8_t *)&ia0->ia_addr.sin6_addr.s6_addr[8], forcegen)) {
1909		nd6log((LOG_NOTICE, "in6_tmpifadd: failed to find a good "
1910		    "random IFID\n"));
1911		return (EINVAL);
1912	}
1913	ifra.ifra_addr.sin6_addr.s6_addr32[2] |=
1914	    (randid[0] & ~(ifra.ifra_prefixmask.sin6_addr.s6_addr32[2]));
1915	ifra.ifra_addr.sin6_addr.s6_addr32[3] |=
1916	    (randid[1] & ~(ifra.ifra_prefixmask.sin6_addr.s6_addr32[3]));
1917
1918	/*
1919	 * in6_get_tmpifid() quite likely provided a unique interface ID.
1920	 * However, we may still have a chance to see collision, because
1921	 * there may be a time lag between generation of the ID and generation
1922	 * of the address.  So, we'll do one more sanity check.
1923	 */
1924	for (ia = V_in6_ifaddr; ia; ia = ia->ia_next) {
1925		if (IN6_ARE_ADDR_EQUAL(&ia->ia_addr.sin6_addr,
1926		    &ifra.ifra_addr.sin6_addr)) {
1927			if (trylimit-- == 0) {
1928				/*
1929				 * Give up.  Something strange should have
1930				 * happened.
1931				 */
1932				nd6log((LOG_NOTICE, "in6_tmpifadd: failed to "
1933				    "find a unique random IFID\n"));
1934				return (EEXIST);
1935			}
1936			forcegen = 1;
1937			goto again;
1938		}
1939	}
1940
1941	/*
1942	 * The Valid Lifetime is the lower of the Valid Lifetime of the
1943         * public address or TEMP_VALID_LIFETIME.
1944	 * The Preferred Lifetime is the lower of the Preferred Lifetime
1945         * of the public address or TEMP_PREFERRED_LIFETIME -
1946         * DESYNC_FACTOR.
1947	 */
1948	if (ia0->ia6_lifetime.ia6t_vltime != ND6_INFINITE_LIFETIME) {
1949		vltime0 = IFA6_IS_INVALID(ia0) ? 0 :
1950		    (ia0->ia6_lifetime.ia6t_vltime -
1951		    (time_second - ia0->ia6_updatetime));
1952		if (vltime0 > V_ip6_temp_valid_lifetime)
1953			vltime0 = V_ip6_temp_valid_lifetime;
1954	} else
1955		vltime0 = V_ip6_temp_valid_lifetime;
1956	if (ia0->ia6_lifetime.ia6t_pltime != ND6_INFINITE_LIFETIME) {
1957		pltime0 = IFA6_IS_DEPRECATED(ia0) ? 0 :
1958		    (ia0->ia6_lifetime.ia6t_pltime -
1959		    (time_second - ia0->ia6_updatetime));
1960		if (pltime0 > V_ip6_temp_preferred_lifetime - V_ip6_desync_factor){
1961			pltime0 = V_ip6_temp_preferred_lifetime -
1962			    V_ip6_desync_factor;
1963		}
1964	} else
1965		pltime0 = V_ip6_temp_preferred_lifetime - V_ip6_desync_factor;
1966	ifra.ifra_lifetime.ia6t_vltime = vltime0;
1967	ifra.ifra_lifetime.ia6t_pltime = pltime0;
1968
1969	/*
1970	 * A temporary address is created only if this calculated Preferred
1971	 * Lifetime is greater than REGEN_ADVANCE time units.
1972	 */
1973	if (ifra.ifra_lifetime.ia6t_pltime <= V_ip6_temp_regen_advance)
1974		return (0);
1975
1976	/* XXX: scope zone ID? */
1977
1978	ifra.ifra_flags |= (IN6_IFF_AUTOCONF|IN6_IFF_TEMPORARY);
1979
1980	/* allocate ifaddr structure, link into chain, etc. */
1981	updateflags = 0;
1982	if (delay)
1983		updateflags |= IN6_IFAUPDATE_DADDELAY;
1984	if ((error = in6_update_ifa(ifp, &ifra, NULL, updateflags)) != 0)
1985		return (error);
1986
1987	newia = in6ifa_ifpwithaddr(ifp, &ifra.ifra_addr.sin6_addr);
1988	if (newia == NULL) {	/* XXX: can it happen? */
1989		nd6log((LOG_ERR,
1990		    "in6_tmpifadd: ifa update succeeded, but we got "
1991		    "no ifaddr\n"));
1992		return (EINVAL); /* XXX */
1993	}
1994	newia->ia6_ndpr = ia0->ia6_ndpr;
1995	newia->ia6_ndpr->ndpr_refcnt++;
1996
1997	/*
1998	 * A newly added address might affect the status of other addresses.
1999	 * XXX: when the temporary address is generated with a new public
2000	 * address, the onlink check is redundant.  However, it would be safe
2001	 * to do the check explicitly everywhere a new address is generated,
2002	 * and, in fact, we surely need the check when we create a new
2003	 * temporary address due to deprecation of an old temporary address.
2004	 */
2005	pfxlist_onlink_check();
2006
2007	return (0);
2008}
2009
2010static int
2011in6_init_prefix_ltimes(struct nd_prefix *ndpr)
2012{
2013	if (ndpr->ndpr_pltime == ND6_INFINITE_LIFETIME)
2014		ndpr->ndpr_preferred = 0;
2015	else
2016		ndpr->ndpr_preferred = time_second + ndpr->ndpr_pltime;
2017	if (ndpr->ndpr_vltime == ND6_INFINITE_LIFETIME)
2018		ndpr->ndpr_expire = 0;
2019	else
2020		ndpr->ndpr_expire = time_second + ndpr->ndpr_vltime;
2021
2022	return 0;
2023}
2024
2025static void
2026in6_init_address_ltimes(struct nd_prefix *new, struct in6_addrlifetime *lt6)
2027{
2028	/* init ia6t_expire */
2029	if (lt6->ia6t_vltime == ND6_INFINITE_LIFETIME)
2030		lt6->ia6t_expire = 0;
2031	else {
2032		lt6->ia6t_expire = time_second;
2033		lt6->ia6t_expire += lt6->ia6t_vltime;
2034	}
2035
2036	/* init ia6t_preferred */
2037	if (lt6->ia6t_pltime == ND6_INFINITE_LIFETIME)
2038		lt6->ia6t_preferred = 0;
2039	else {
2040		lt6->ia6t_preferred = time_second;
2041		lt6->ia6t_preferred += lt6->ia6t_pltime;
2042	}
2043}
2044
2045/*
2046 * Delete all the routing table entries that use the specified gateway.
2047 * XXX: this function causes search through all entries of routing table, so
2048 * it shouldn't be called when acting as a router.
2049 */
2050void
2051rt6_flush(struct in6_addr *gateway, struct ifnet *ifp)
2052{
2053	INIT_VNET_NET(curvnet);
2054	struct radix_node_head *rnh = V_rt_tables[0][AF_INET6];
2055	int s = splnet();
2056
2057	/* We'll care only link-local addresses */
2058	if (!IN6_IS_ADDR_LINKLOCAL(gateway)) {
2059		splx(s);
2060		return;
2061	}
2062
2063	RADIX_NODE_HEAD_LOCK(rnh);
2064	rnh->rnh_walktree(rnh, rt6_deleteroute, (void *)gateway);
2065	RADIX_NODE_HEAD_UNLOCK(rnh);
2066	splx(s);
2067}
2068
2069static int
2070rt6_deleteroute(struct radix_node *rn, void *arg)
2071{
2072#define SIN6(s)	((struct sockaddr_in6 *)s)
2073	struct rtentry *rt = (struct rtentry *)rn;
2074	struct in6_addr *gate = (struct in6_addr *)arg;
2075
2076	if (rt->rt_gateway == NULL || rt->rt_gateway->sa_family != AF_INET6)
2077		return (0);
2078
2079	if (!IN6_ARE_ADDR_EQUAL(gate, &SIN6(rt->rt_gateway)->sin6_addr)) {
2080		return (0);
2081	}
2082
2083	/*
2084	 * Do not delete a static route.
2085	 * XXX: this seems to be a bit ad-hoc. Should we consider the
2086	 * 'cloned' bit instead?
2087	 */
2088	if ((rt->rt_flags & RTF_STATIC) != 0)
2089		return (0);
2090
2091	/*
2092	 * We delete only host route. This means, in particular, we don't
2093	 * delete default route.
2094	 */
2095	if ((rt->rt_flags & RTF_HOST) == 0)
2096		return (0);
2097
2098	return (rtrequest(RTM_DELETE, rt_key(rt), rt->rt_gateway,
2099	    rt_mask(rt), rt->rt_flags, 0));
2100#undef SIN6
2101}
2102
2103int
2104nd6_setdefaultiface(int ifindex)
2105{
2106	INIT_VNET_NET(curvnet);
2107	INIT_VNET_INET6(curvnet);
2108	int error = 0;
2109
2110	if (ifindex < 0 || V_if_index < ifindex)
2111		return (EINVAL);
2112	if (ifindex != 0 && !ifnet_byindex(ifindex))
2113		return (EINVAL);
2114
2115	if (V_nd6_defifindex != ifindex) {
2116		V_nd6_defifindex = ifindex;
2117		if (V_nd6_defifindex > 0)
2118			V_nd6_defifp = ifnet_byindex(V_nd6_defifindex);
2119		else
2120			V_nd6_defifp = NULL;
2121
2122		/*
2123		 * Our current implementation assumes one-to-one maping between
2124		 * interfaces and links, so it would be natural to use the
2125		 * default interface as the default link.
2126		 */
2127		scope6_setdefault(V_nd6_defifp);
2128	}
2129
2130	return (error);
2131}
2132