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