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