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