nd6.c revision 123296
1143880Spjd/*	$FreeBSD: head/sys/netinet6/nd6.c 123296 2003-12-08 11:59:21Z ume $	*/
2143880Spjd/*	$KAME: nd6.c,v 1.144 2001/05/24 07:44:00 itojun Exp $	*/
3143880Spjd
4143880Spjd/*
5143880Spjd * Copyright (C) 1995, 1996, 1997, and 1998 WIDE Project.
6143880Spjd * All rights reserved.
7143880Spjd *
8143880Spjd * Redistribution and use in source and binary forms, with or without
9143880Spjd * modification, are permitted provided that the following conditions
10263351Sjmmv * are met:
11143880Spjd * 1. Redistributions of source code must retain the above copyright
12143880Spjd *    notice, this list of conditions and the following disclaimer.
13143880Spjd * 2. Redistributions in binary form must reproduce the above copyright
14143880Spjd *    notice, this list of conditions and the following disclaimer in the
15143880Spjd *    documentation and/or other materials provided with the distribution.
16143880Spjd * 3. Neither the name of the project nor the names of its contributors
17143880Spjd *    may be used to endorse or promote products derived from this software
18143880Spjd *    without specific prior written permission.
19143880Spjd *
20143880Spjd * THIS SOFTWARE IS PROVIDED BY THE PROJECT AND CONTRIBUTORS ``AS IS'' AND
21143880Spjd * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
22143880Spjd * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
23143880Spjd * ARE DISCLAIMED.  IN NO EVENT SHALL THE PROJECT OR CONTRIBUTORS BE LIABLE
24143880Spjd * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
25263351Sjmmv * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
26143880Spjd * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
27143880Spjd * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
28143880Spjd * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
29143880Spjd * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
30143880Spjd * SUCH DAMAGE.
31143880Spjd */
32143880Spjd
33143880Spjd#include "opt_inet.h"
34143880Spjd#include "opt_inet6.h"
35143880Spjd#include "opt_mac.h"
36143880Spjd
37143880Spjd#include <sys/param.h>
38#include <sys/systm.h>
39#include <sys/callout.h>
40#include <sys/mac.h>
41#include <sys/malloc.h>
42#include <sys/mbuf.h>
43#include <sys/socket.h>
44#include <sys/sockio.h>
45#include <sys/time.h>
46#include <sys/kernel.h>
47#include <sys/protosw.h>
48#include <sys/errno.h>
49#include <sys/syslog.h>
50#include <sys/queue.h>
51#include <sys/sysctl.h>
52
53#include <net/if.h>
54#include <net/if_arc.h>
55#include <net/if_dl.h>
56#include <net/if_types.h>
57#include <net/if_atm.h>
58#include <net/iso88025.h>
59#include <net/fddi.h>
60#include <net/route.h>
61
62#include <netinet/in.h>
63#include <netinet/if_ether.h>
64#include <netinet6/in6_var.h>
65#include <netinet/ip6.h>
66#include <netinet6/ip6_var.h>
67#include <netinet6/nd6.h>
68#include <netinet6/in6_prefix.h>
69#include <netinet/icmp6.h>
70
71#include <net/net_osdep.h>
72
73#define ND6_SLOWTIMER_INTERVAL (60 * 60) /* 1 hour */
74#define ND6_RECALC_REACHTM_INTERVAL (60 * 120) /* 2 hours */
75
76#define SIN6(s) ((struct sockaddr_in6 *)s)
77#define SDL(s) ((struct sockaddr_dl *)s)
78
79/* timer values */
80int	nd6_prune	= 1;	/* walk list every 1 seconds */
81int	nd6_delay	= 5;	/* delay first probe time 5 second */
82int	nd6_umaxtries	= 3;	/* maximum unicast query */
83int	nd6_mmaxtries	= 3;	/* maximum multicast query */
84int	nd6_useloopback = 1;	/* use loopback interface for local traffic */
85int	nd6_gctimer	= (60 * 60 * 24); /* 1 day: garbage collection timer */
86
87/* preventing too many loops in ND option parsing */
88int nd6_maxndopt = 10;	/* max # of ND options allowed */
89
90int nd6_maxnudhint = 0;	/* max # of subsequent upper layer hints */
91
92#ifdef ND6_DEBUG
93int nd6_debug = 1;
94#else
95int nd6_debug = 0;
96#endif
97
98/* for debugging? */
99static int nd6_inuse, nd6_allocated;
100
101struct llinfo_nd6 llinfo_nd6 = {&llinfo_nd6, &llinfo_nd6};
102struct nd_drhead nd_defrouter;
103struct nd_prhead nd_prefix = { 0 };
104
105int nd6_recalc_reachtm_interval = ND6_RECALC_REACHTM_INTERVAL;
106static struct sockaddr_in6 all1_sa;
107
108static void nd6_setmtu0 __P((struct ifnet *, struct nd_ifinfo *));
109static void nd6_slowtimo __P((void *));
110static int regen_tmpaddr __P((struct in6_ifaddr *));
111
112struct callout nd6_slowtimo_ch;
113struct callout nd6_timer_ch;
114extern struct callout in6_tmpaddrtimer_ch;
115
116void
117nd6_init()
118{
119	static int nd6_init_done = 0;
120	int i;
121
122	if (nd6_init_done) {
123		log(LOG_NOTICE, "nd6_init called more than once(ignored)\n");
124		return;
125	}
126
127	all1_sa.sin6_family = AF_INET6;
128	all1_sa.sin6_len = sizeof(struct sockaddr_in6);
129	for (i = 0; i < sizeof(all1_sa.sin6_addr); i++)
130		all1_sa.sin6_addr.s6_addr[i] = 0xff;
131
132	/* initialization of the default router list */
133	TAILQ_INIT(&nd_defrouter);
134
135	nd6_init_done = 1;
136
137	/* start timer */
138	callout_reset(&nd6_slowtimo_ch, ND6_SLOWTIMER_INTERVAL * hz,
139	    nd6_slowtimo, NULL);
140}
141
142struct nd_ifinfo *
143nd6_ifattach(ifp)
144	struct ifnet *ifp;
145{
146	struct nd_ifinfo *nd;
147
148	nd = (struct nd_ifinfo *)malloc(sizeof(*nd), M_IP6NDP, M_WAITOK);
149	bzero(nd, sizeof(*nd));
150
151	nd->initialized = 1;
152
153	nd->chlim = IPV6_DEFHLIM;
154	nd->basereachable = REACHABLE_TIME;
155	nd->reachable = ND_COMPUTE_RTIME(nd->basereachable);
156	nd->retrans = RETRANS_TIMER;
157	/*
158	 * Note that the default value of ip6_accept_rtadv is 0, which means
159	 * we won't accept RAs by default even if we set ND6_IFF_ACCEPT_RTADV
160	 * here.
161	 */
162	nd->flags = (ND6_IFF_PERFORMNUD | ND6_IFF_ACCEPT_RTADV);
163
164	/* XXX: we cannot call nd6_setmtu since ifp is not fully initialized */
165	nd6_setmtu0(ifp, nd);
166
167	return nd;
168}
169
170void
171nd6_ifdetach(nd)
172	struct nd_ifinfo *nd;
173{
174
175	free(nd, M_IP6NDP);
176}
177
178/*
179 * Reset ND level link MTU. This function is called when the physical MTU
180 * changes, which means we might have to adjust the ND level MTU.
181 */
182void
183nd6_setmtu(ifp)
184	struct ifnet *ifp;
185{
186
187	nd6_setmtu0(ifp, ND_IFINFO(ifp));
188}
189
190/* XXX todo: do not maintain copy of ifp->if_mtu in ndi->maxmtu */
191void
192nd6_setmtu0(ifp, ndi)
193	struct ifnet *ifp;
194	struct nd_ifinfo *ndi;
195{
196	u_int32_t omaxmtu;
197
198	omaxmtu = ndi->maxmtu;
199
200	switch (ifp->if_type) {
201	case IFT_ARCNET:
202		ndi->maxmtu = MIN(ARC_PHDS_MAXMTU, ifp->if_mtu); /* RFC2497 */
203		break;
204	case IFT_ETHER:
205		ndi->maxmtu = MIN(ETHERMTU, ifp->if_mtu);
206		break;
207	case IFT_FDDI:
208		ndi->maxmtu = MIN(FDDIIPMTU, ifp->if_mtu); /* RFC2467 */
209		break;
210	case IFT_ATM:
211		ndi->maxmtu = MIN(ATMMTU, ifp->if_mtu);
212		break;
213	case IFT_IEEE1394:	/* XXX should be IEEE1394MTU(1500) */
214		ndi->maxmtu = MIN(ETHERMTU, ifp->if_mtu);
215		break;
216#ifdef IFT_IEEE80211
217	case IFT_IEEE80211:	/* XXX should be IEEE80211MTU(1500) */
218		ndi->maxmtu = MIN(ETHERMTU, ifp->if_mtu);
219		break;
220#endif
221	 case IFT_ISO88025:
222		 ndi->maxmtu = MIN(ISO88025_MAX_MTU, ifp->if_mtu);
223		 break;
224	default:
225		ndi->maxmtu = ifp->if_mtu;
226		break;
227	}
228
229	/*
230	 * Decreasing the interface MTU under IPV6 minimum MTU may cause
231	 * undesirable situation.  We thus notify the operator of the change
232	 * explicitly.  The check for omaxmtu is necessary to restrict the
233	 * log to the case of changing the MTU, not initializing it.
234	 */
235	if (omaxmtu >= IPV6_MMTU && ndi->maxmtu < IPV6_MMTU) {
236		log(LOG_NOTICE, "nd6_setmtu0: "
237		    "new link MTU on %s (%lu) is too small for IPv6\n",
238		    if_name(ifp), (unsigned long)ndi->maxmtu);
239	}
240
241	if (ndi->maxmtu > in6_maxmtu)
242		in6_setmaxmtu(); /* check all interfaces just in case */
243
244#undef MIN
245}
246
247void
248nd6_option_init(opt, icmp6len, ndopts)
249	void *opt;
250	int icmp6len;
251	union nd_opts *ndopts;
252{
253
254	bzero(ndopts, sizeof(*ndopts));
255	ndopts->nd_opts_search = (struct nd_opt_hdr *)opt;
256	ndopts->nd_opts_last
257		= (struct nd_opt_hdr *)(((u_char *)opt) + icmp6len);
258
259	if (icmp6len == 0) {
260		ndopts->nd_opts_done = 1;
261		ndopts->nd_opts_search = NULL;
262	}
263}
264
265/*
266 * Take one ND option.
267 */
268struct nd_opt_hdr *
269nd6_option(ndopts)
270	union nd_opts *ndopts;
271{
272	struct nd_opt_hdr *nd_opt;
273	int olen;
274
275	if (!ndopts)
276		panic("ndopts == NULL in nd6_option");
277	if (!ndopts->nd_opts_last)
278		panic("uninitialized ndopts in nd6_option");
279	if (!ndopts->nd_opts_search)
280		return NULL;
281	if (ndopts->nd_opts_done)
282		return NULL;
283
284	nd_opt = ndopts->nd_opts_search;
285
286	/* make sure nd_opt_len is inside the buffer */
287	if ((caddr_t)&nd_opt->nd_opt_len >= (caddr_t)ndopts->nd_opts_last) {
288		bzero(ndopts, sizeof(*ndopts));
289		return NULL;
290	}
291
292	olen = nd_opt->nd_opt_len << 3;
293	if (olen == 0) {
294		/*
295		 * Message validation requires that all included
296		 * options have a length that is greater than zero.
297		 */
298		bzero(ndopts, sizeof(*ndopts));
299		return NULL;
300	}
301
302	ndopts->nd_opts_search = (struct nd_opt_hdr *)((caddr_t)nd_opt + olen);
303	if (ndopts->nd_opts_search > ndopts->nd_opts_last) {
304		/* option overruns the end of buffer, invalid */
305		bzero(ndopts, sizeof(*ndopts));
306		return NULL;
307	} else if (ndopts->nd_opts_search == ndopts->nd_opts_last) {
308		/* reached the end of options chain */
309		ndopts->nd_opts_done = 1;
310		ndopts->nd_opts_search = NULL;
311	}
312	return nd_opt;
313}
314
315/*
316 * Parse multiple ND options.
317 * This function is much easier to use, for ND routines that do not need
318 * multiple options of the same type.
319 */
320int
321nd6_options(ndopts)
322	union nd_opts *ndopts;
323{
324	struct nd_opt_hdr *nd_opt;
325	int i = 0;
326
327	if (!ndopts)
328		panic("ndopts == NULL in nd6_options");
329	if (!ndopts->nd_opts_last)
330		panic("uninitialized ndopts in nd6_options");
331	if (!ndopts->nd_opts_search)
332		return 0;
333
334	while (1) {
335		nd_opt = nd6_option(ndopts);
336		if (!nd_opt && !ndopts->nd_opts_last) {
337			/*
338			 * Message validation requires that all included
339			 * options have a length that is greater than zero.
340			 */
341			icmp6stat.icp6s_nd_badopt++;
342			bzero(ndopts, sizeof(*ndopts));
343			return -1;
344		}
345
346		if (!nd_opt)
347			goto skip1;
348
349		switch (nd_opt->nd_opt_type) {
350		case ND_OPT_SOURCE_LINKADDR:
351		case ND_OPT_TARGET_LINKADDR:
352		case ND_OPT_MTU:
353		case ND_OPT_REDIRECTED_HEADER:
354			if (ndopts->nd_opt_array[nd_opt->nd_opt_type]) {
355				nd6log((LOG_INFO,
356				    "duplicated ND6 option found (type=%d)\n",
357				    nd_opt->nd_opt_type));
358				/* XXX bark? */
359			} else {
360				ndopts->nd_opt_array[nd_opt->nd_opt_type]
361					= nd_opt;
362			}
363			break;
364		case ND_OPT_PREFIX_INFORMATION:
365			if (ndopts->nd_opt_array[nd_opt->nd_opt_type] == 0) {
366				ndopts->nd_opt_array[nd_opt->nd_opt_type]
367					= nd_opt;
368			}
369			ndopts->nd_opts_pi_end =
370				(struct nd_opt_prefix_info *)nd_opt;
371			break;
372		default:
373			/*
374			 * Unknown options must be silently ignored,
375			 * to accomodate future extension to the protocol.
376			 */
377			nd6log((LOG_DEBUG,
378			    "nd6_options: unsupported option %d - "
379			    "option ignored\n", nd_opt->nd_opt_type));
380		}
381
382skip1:
383		i++;
384		if (i > nd6_maxndopt) {
385			icmp6stat.icp6s_nd_toomanyopt++;
386			nd6log((LOG_INFO, "too many loop in nd opt\n"));
387			break;
388		}
389
390		if (ndopts->nd_opts_done)
391			break;
392	}
393
394	return 0;
395}
396
397/*
398 * ND6 timer routine to expire default route list and prefix list
399 */
400void
401nd6_timer(ignored_arg)
402	void	*ignored_arg;
403{
404	int s;
405	struct llinfo_nd6 *ln;
406	struct nd_defrouter *dr;
407	struct nd_prefix *pr;
408	struct ifnet *ifp;
409	struct in6_ifaddr *ia6, *nia6;
410	struct in6_addrlifetime *lt6;
411
412	s = splnet();
413	callout_reset(&nd6_timer_ch, nd6_prune * hz,
414	    nd6_timer, NULL);
415
416	ln = llinfo_nd6.ln_next;
417	while (ln && ln != &llinfo_nd6) {
418		struct rtentry *rt;
419		struct sockaddr_in6 *dst;
420		struct llinfo_nd6 *next = ln->ln_next;
421		/* XXX: used for the DELAY case only: */
422		struct nd_ifinfo *ndi = NULL;
423
424		if ((rt = ln->ln_rt) == NULL) {
425			ln = next;
426			continue;
427		}
428		if ((ifp = rt->rt_ifp) == NULL) {
429			ln = next;
430			continue;
431		}
432		ndi = ND_IFINFO(ifp);
433		dst = (struct sockaddr_in6 *)rt_key(rt);
434
435		if (ln->ln_expire > time_second) {
436			ln = next;
437			continue;
438		}
439
440		/* sanity check */
441		if (!rt)
442			panic("rt=0 in nd6_timer(ln=%p)", ln);
443		if (rt->rt_llinfo && (struct llinfo_nd6 *)rt->rt_llinfo != ln)
444			panic("rt_llinfo(%p) is not equal to ln(%p)",
445			      rt->rt_llinfo, ln);
446		if (!dst)
447			panic("dst=0 in nd6_timer(ln=%p)", ln);
448
449		switch (ln->ln_state) {
450		case ND6_LLINFO_INCOMPLETE:
451			if (ln->ln_asked < nd6_mmaxtries) {
452				ln->ln_asked++;
453				ln->ln_expire = time_second +
454					ND_IFINFO(ifp)->retrans / 1000;
455				nd6_ns_output(ifp, NULL, &dst->sin6_addr,
456					ln, 0);
457			} else {
458				struct mbuf *m = ln->ln_hold;
459				if (m) {
460					if (rt->rt_ifp) {
461						/*
462						 * Fake rcvif to make ICMP error
463						 * more helpful in diagnosing
464						 * for the receiver.
465						 * XXX: should we consider
466						 * older rcvif?
467						 */
468						m->m_pkthdr.rcvif = rt->rt_ifp;
469					}
470					icmp6_error(m, ICMP6_DST_UNREACH,
471						    ICMP6_DST_UNREACH_ADDR, 0);
472					ln->ln_hold = NULL;
473				}
474				next = nd6_free(rt);
475			}
476			break;
477		case ND6_LLINFO_REACHABLE:
478			if (ln->ln_expire) {
479				ln->ln_state = ND6_LLINFO_STALE;
480				ln->ln_expire = time_second + nd6_gctimer;
481			}
482			break;
483
484		case ND6_LLINFO_STALE:
485			/* Garbage Collection(RFC 2461 5.3) */
486			if (ln->ln_expire)
487				next = nd6_free(rt);
488			break;
489
490		case ND6_LLINFO_DELAY:
491			if (ndi && (ndi->flags & ND6_IFF_PERFORMNUD) != 0) {
492				/* We need NUD */
493				ln->ln_asked = 1;
494				ln->ln_state = ND6_LLINFO_PROBE;
495				ln->ln_expire = time_second +
496					ndi->retrans / 1000;
497				nd6_ns_output(ifp, &dst->sin6_addr,
498					      &dst->sin6_addr,
499					      ln, 0);
500			} else {
501				ln->ln_state = ND6_LLINFO_STALE; /* XXX */
502				ln->ln_expire = time_second + nd6_gctimer;
503			}
504			break;
505		case ND6_LLINFO_PROBE:
506			if (ln->ln_asked < nd6_umaxtries) {
507				ln->ln_asked++;
508				ln->ln_expire = time_second +
509					ND_IFINFO(ifp)->retrans / 1000;
510				nd6_ns_output(ifp, &dst->sin6_addr,
511					       &dst->sin6_addr, ln, 0);
512			} else {
513				next = nd6_free(rt);
514			}
515			break;
516		}
517		ln = next;
518	}
519
520	/* expire default router list */
521	dr = TAILQ_FIRST(&nd_defrouter);
522	while (dr) {
523		if (dr->expire && dr->expire < time_second) {
524			struct nd_defrouter *t;
525			t = TAILQ_NEXT(dr, dr_entry);
526			defrtrlist_del(dr);
527			dr = t;
528		} else {
529			dr = TAILQ_NEXT(dr, dr_entry);
530		}
531	}
532
533	/*
534	 * expire interface addresses.
535	 * in the past the loop was inside prefix expiry processing.
536	 * However, from a stricter speci-confrmance standpoint, we should
537	 * rather separate address lifetimes and prefix lifetimes.
538	 */
539  addrloop:
540	for (ia6 = in6_ifaddr; ia6; ia6 = nia6) {
541		nia6 = ia6->ia_next;
542		/* check address lifetime */
543		lt6 = &ia6->ia6_lifetime;
544		if (IFA6_IS_INVALID(ia6)) {
545			int regen = 0;
546
547			/*
548			 * If the expiring address is temporary, try
549			 * regenerating a new one.  This would be useful when
550			 * we suspended a laptop PC, then turned it on after a
551			 * period that could invalidate all temporary
552			 * addresses.  Although we may have to restart the
553			 * loop (see below), it must be after purging the
554			 * address.  Otherwise, we'd see an infinite loop of
555			 * regeneration.
556			 */
557			if (ip6_use_tempaddr &&
558			    (ia6->ia6_flags & IN6_IFF_TEMPORARY) != 0) {
559				if (regen_tmpaddr(ia6) == 0)
560					regen = 1;
561			}
562
563			in6_purgeaddr(&ia6->ia_ifa);
564
565			if (regen)
566				goto addrloop; /* XXX: see below */
567		}
568		if (IFA6_IS_DEPRECATED(ia6)) {
569			int oldflags = ia6->ia6_flags;
570
571			ia6->ia6_flags |= IN6_IFF_DEPRECATED;
572
573			/*
574			 * If a temporary address has just become deprecated,
575			 * regenerate a new one if possible.
576			 */
577			if (ip6_use_tempaddr &&
578			    (ia6->ia6_flags & IN6_IFF_TEMPORARY) != 0 &&
579			    (oldflags & IN6_IFF_DEPRECATED) == 0) {
580
581				if (regen_tmpaddr(ia6) == 0) {
582					/*
583					 * A new temporary address is
584					 * generated.
585					 * XXX: this means the address chain
586					 * has changed while we are still in
587					 * the loop.  Although the change
588					 * would not cause disaster (because
589					 * it's not a deletion, but an
590					 * addition,) we'd rather restart the
591					 * loop just for safety.  Or does this
592					 * significantly reduce performance??
593					 */
594					goto addrloop;
595				}
596			}
597		} else {
598			/*
599			 * A new RA might have made a deprecated address
600			 * preferred.
601			 */
602			ia6->ia6_flags &= ~IN6_IFF_DEPRECATED;
603		}
604	}
605
606	/* expire prefix list */
607	pr = nd_prefix.lh_first;
608	while (pr) {
609		/*
610		 * check prefix lifetime.
611		 * since pltime is just for autoconf, pltime processing for
612		 * prefix is not necessary.
613		 */
614		if (pr->ndpr_expire && pr->ndpr_expire < time_second) {
615			struct nd_prefix *t;
616			t = pr->ndpr_next;
617
618			/*
619			 * address expiration and prefix expiration are
620			 * separate.  NEVER perform in6_purgeaddr here.
621			 */
622
623			prelist_remove(pr);
624			pr = t;
625		} else
626			pr = pr->ndpr_next;
627	}
628	splx(s);
629}
630
631static int
632regen_tmpaddr(ia6)
633	struct in6_ifaddr *ia6; /* deprecated/invalidated temporary address */
634{
635	struct ifaddr *ifa;
636	struct ifnet *ifp;
637	struct in6_ifaddr *public_ifa6 = NULL;
638
639	ifp = ia6->ia_ifa.ifa_ifp;
640	for (ifa = ifp->if_addrlist.tqh_first; ifa;
641	     ifa = ifa->ifa_list.tqe_next) {
642		struct in6_ifaddr *it6;
643
644		if (ifa->ifa_addr->sa_family != AF_INET6)
645			continue;
646
647		it6 = (struct in6_ifaddr *)ifa;
648
649		/* ignore no autoconf addresses. */
650		if ((it6->ia6_flags & IN6_IFF_AUTOCONF) == 0)
651			continue;
652
653		/* ignore autoconf addresses with different prefixes. */
654		if (it6->ia6_ndpr == NULL || it6->ia6_ndpr != ia6->ia6_ndpr)
655			continue;
656
657		/*
658		 * Now we are looking at an autoconf address with the same
659		 * prefix as ours.  If the address is temporary and is still
660		 * preferred, do not create another one.  It would be rare, but
661		 * could happen, for example, when we resume a laptop PC after
662		 * a long period.
663		 */
664		if ((it6->ia6_flags & IN6_IFF_TEMPORARY) != 0 &&
665		    !IFA6_IS_DEPRECATED(it6)) {
666			public_ifa6 = NULL;
667			break;
668		}
669
670		/*
671		 * This is a public autoconf address that has the same prefix
672		 * as ours.  If it is preferred, keep it.  We can't break the
673		 * loop here, because there may be a still-preferred temporary
674		 * address with the prefix.
675		 */
676		if (!IFA6_IS_DEPRECATED(it6))
677		    public_ifa6 = it6;
678	}
679
680	if (public_ifa6 != NULL) {
681		int e;
682
683		if ((e = in6_tmpifadd(public_ifa6, 0)) != 0) {
684			log(LOG_NOTICE, "regen_tmpaddr: failed to create a new"
685			    " tmp addr,errno=%d\n", e);
686			return (-1);
687		}
688		return (0);
689	}
690
691	return (-1);
692}
693
694/*
695 * Nuke neighbor cache/prefix/default router management table, right before
696 * ifp goes away.
697 */
698void
699nd6_purge(ifp)
700	struct ifnet *ifp;
701{
702	struct llinfo_nd6 *ln, *nln;
703	struct nd_defrouter *dr, *ndr, drany;
704	struct nd_prefix *pr, *npr;
705
706	/* Nuke default router list entries toward ifp */
707	if ((dr = TAILQ_FIRST(&nd_defrouter)) != NULL) {
708		/*
709		 * The first entry of the list may be stored in
710		 * the routing table, so we'll delete it later.
711		 */
712		for (dr = TAILQ_NEXT(dr, dr_entry); dr; dr = ndr) {
713			ndr = TAILQ_NEXT(dr, dr_entry);
714			if (dr->ifp == ifp)
715				defrtrlist_del(dr);
716		}
717		dr = TAILQ_FIRST(&nd_defrouter);
718		if (dr->ifp == ifp)
719			defrtrlist_del(dr);
720	}
721
722	/* Nuke prefix list entries toward ifp */
723	for (pr = nd_prefix.lh_first; pr; pr = npr) {
724		npr = pr->ndpr_next;
725		if (pr->ndpr_ifp == ifp) {
726			/*
727			 * Previously, pr->ndpr_addr is removed as well,
728			 * but I strongly believe we don't have to do it.
729			 * nd6_purge() is only called from in6_ifdetach(),
730			 * which removes all the associated interface addresses
731			 * by itself.
732			 * (jinmei@kame.net 20010129)
733			 */
734			prelist_remove(pr);
735		}
736	}
737
738	/* cancel default outgoing interface setting */
739	if (nd6_defifindex == ifp->if_index)
740		nd6_setdefaultiface(0);
741
742	if (!ip6_forwarding && ip6_accept_rtadv) { /* XXX: too restrictive? */
743		/* refresh default router list */
744		bzero(&drany, sizeof(drany));
745		defrouter_delreq(&drany, 0);
746		defrouter_select();
747	}
748
749	/*
750	 * Nuke neighbor cache entries for the ifp.
751	 * Note that rt->rt_ifp may not be the same as ifp,
752	 * due to KAME goto ours hack.  See RTM_RESOLVE case in
753	 * nd6_rtrequest(), and ip6_input().
754	 */
755	ln = llinfo_nd6.ln_next;
756	while (ln && ln != &llinfo_nd6) {
757		struct rtentry *rt;
758		struct sockaddr_dl *sdl;
759
760		nln = ln->ln_next;
761		rt = ln->ln_rt;
762		if (rt && rt->rt_gateway &&
763		    rt->rt_gateway->sa_family == AF_LINK) {
764			sdl = (struct sockaddr_dl *)rt->rt_gateway;
765			if (sdl->sdl_index == ifp->if_index)
766				nln = nd6_free(rt);
767		}
768		ln = nln;
769	}
770}
771
772struct rtentry *
773nd6_lookup(addr6, create, ifp)
774	struct in6_addr *addr6;
775	int create;
776	struct ifnet *ifp;
777{
778	struct rtentry *rt;
779	struct sockaddr_in6 sin6;
780
781	bzero(&sin6, sizeof(sin6));
782	sin6.sin6_len = sizeof(struct sockaddr_in6);
783	sin6.sin6_family = AF_INET6;
784	sin6.sin6_addr = *addr6;
785	rt = rtalloc1((struct sockaddr *)&sin6, create, 0UL);
786	if (rt) {
787		if ((rt->rt_flags & RTF_LLINFO) == 0 && create) {
788			/*
789			 * This is the case for the default route.
790			 * If we want to create a neighbor cache for the
791			 * address, we should free the route for the
792			 * destination and allocate an interface route.
793			 */
794			RTFREE_LOCKED(rt);
795			rt = 0;
796		}
797	}
798	if (!rt) {
799		if (create && ifp) {
800			int e;
801
802			/*
803			 * If no route is available and create is set,
804			 * we allocate a host route for the destination
805			 * and treat it like an interface route.
806			 * This hack is necessary for a neighbor which can't
807			 * be covered by our own prefix.
808			 */
809			struct ifaddr *ifa =
810			    ifaof_ifpforaddr((struct sockaddr *)&sin6, ifp);
811			if (ifa == NULL)
812				return (NULL);
813
814			/*
815			 * Create a new route.  RTF_LLINFO is necessary
816			 * to create a Neighbor Cache entry for the
817			 * destination in nd6_rtrequest which will be
818			 * called in rtrequest via ifa->ifa_rtrequest.
819			 */
820			if ((e = rtrequest(RTM_ADD, (struct sockaddr *)&sin6,
821			    ifa->ifa_addr, (struct sockaddr *)&all1_sa,
822			    (ifa->ifa_flags | RTF_HOST | RTF_LLINFO) &
823			    ~RTF_CLONING, &rt)) != 0) {
824				log(LOG_ERR,
825				    "nd6_lookup: failed to add route for a "
826				    "neighbor(%s), errno=%d\n",
827				    ip6_sprintf(addr6), e);
828			}
829			if (rt == NULL)
830				return (NULL);
831			RT_LOCK(rt);
832			if (rt->rt_llinfo) {
833				struct llinfo_nd6 *ln =
834				    (struct llinfo_nd6 *)rt->rt_llinfo;
835				ln->ln_state = ND6_LLINFO_NOSTATE;
836			}
837		} else
838			return (NULL);
839	}
840	RT_LOCK_ASSERT(rt);
841	RT_REMREF(rt);
842	/*
843	 * Validation for the entry.
844	 * Note that the check for rt_llinfo is necessary because a cloned
845	 * route from a parent route that has the L flag (e.g. the default
846	 * route to a p2p interface) may have the flag, too, while the
847	 * destination is not actually a neighbor.
848	 * XXX: we can't use rt->rt_ifp to check for the interface, since
849	 *      it might be the loopback interface if the entry is for our
850	 *      own address on a non-loopback interface. Instead, we should
851	 *      use rt->rt_ifa->ifa_ifp, which would specify the REAL
852	 *	interface.
853	 */
854	if ((rt->rt_flags & RTF_GATEWAY) || (rt->rt_flags & RTF_LLINFO) == 0 ||
855	    rt->rt_gateway->sa_family != AF_LINK || rt->rt_llinfo == NULL ||
856	    (ifp && rt->rt_ifa->ifa_ifp != ifp)) {
857		if (create) {
858			log(LOG_DEBUG,
859			    "nd6_lookup: failed to lookup %s (if = %s)\n",
860			    ip6_sprintf(addr6),
861			    ifp ? if_name(ifp) : "unspec");
862			/* xxx more logs... kazu */
863		}
864		RT_UNLOCK(rt);
865		return (NULL);
866	}
867	RT_UNLOCK(rt);		/* XXX not ready to return rt locked */
868	return (rt);
869}
870
871/*
872 * Detect if a given IPv6 address identifies a neighbor on a given link.
873 * XXX: should take care of the destination of a p2p link?
874 */
875int
876nd6_is_addr_neighbor(addr, ifp)
877	struct sockaddr_in6 *addr;
878	struct ifnet *ifp;
879{
880	struct nd_prefix *pr;
881
882	/*
883	 * A link-local address is always a neighbor.
884	 * XXX: we should use the sin6_scope_id field rather than the embedded
885	 * interface index.
886	 * XXX: a link does not necessarily specify a single interface.
887	 */
888	if (IN6_IS_ADDR_LINKLOCAL(&addr->sin6_addr) &&
889	    ntohs(*(u_int16_t *)&addr->sin6_addr.s6_addr[2]) == ifp->if_index)
890		return (1);
891
892	/*
893	 * If the address matches one of our addresses,
894	 * it should be a neighbor.
895	 * If the address matches one of our on-link prefixes, it should be a
896	 * neighbor.
897	 */
898	for (pr = nd_prefix.lh_first; pr; pr = pr->ndpr_next) {
899		if (pr->ndpr_ifp != ifp)
900			continue;
901
902		if (!(pr->ndpr_stateflags & NDPRF_ONLINK))
903			continue;
904
905		if (IN6_ARE_MASKED_ADDR_EQUAL(&pr->ndpr_prefix.sin6_addr,
906		    &addr->sin6_addr, &pr->ndpr_mask))
907			return (1);
908	}
909
910	/*
911	 * If the default router list is empty, all addresses are regarded
912	 * as on-link, and thus, as a neighbor.
913	 * XXX: we restrict the condition to hosts, because routers usually do
914	 * not have the "default router list".
915	 */
916	if (!ip6_forwarding && TAILQ_FIRST(&nd_defrouter) == NULL &&
917	    nd6_defifindex == ifp->if_index) {
918		return (1);
919	}
920
921	/*
922	 * Even if the address matches none of our addresses, it might be
923	 * in the neighbor cache.
924	 */
925	if (nd6_lookup(&addr->sin6_addr, 0, ifp) != NULL)
926		return (1);
927
928	return (0);
929}
930
931/*
932 * Free an nd6 llinfo entry.
933 */
934struct llinfo_nd6 *
935nd6_free(rt)
936	struct rtentry *rt;
937{
938	struct llinfo_nd6 *ln = (struct llinfo_nd6 *)rt->rt_llinfo, *next;
939	struct in6_addr in6 = ((struct sockaddr_in6 *)rt_key(rt))->sin6_addr;
940	struct nd_defrouter *dr;
941
942	/*
943	 * we used to have pfctlinput(PRC_HOSTDEAD) here.
944	 * even though it is not harmful, it was not really necessary.
945	 */
946
947	if (!ip6_forwarding && ip6_accept_rtadv) { /* XXX: too restrictive? */
948		int s;
949		s = splnet();
950		dr = defrouter_lookup(&((struct sockaddr_in6 *)rt_key(rt))->sin6_addr,
951		    rt->rt_ifp);
952
953		if (ln->ln_router || dr) {
954			/*
955			 * rt6_flush must be called whether or not the neighbor
956			 * is in the Default Router List.
957			 * See a corresponding comment in nd6_na_input().
958			 */
959			rt6_flush(&in6, rt->rt_ifp);
960		}
961
962		if (dr) {
963			/*
964			 * Unreachablity of a router might affect the default
965			 * router selection and on-link detection of advertised
966			 * prefixes.
967			 */
968
969			/*
970			 * Temporarily fake the state to choose a new default
971			 * router and to perform on-link determination of
972			 * prefixes correctly.
973			 * Below the state will be set correctly,
974			 * or the entry itself will be deleted.
975			 */
976			ln->ln_state = ND6_LLINFO_INCOMPLETE;
977
978			/*
979			 * Since defrouter_select() does not affect the
980			 * on-link determination and MIP6 needs the check
981			 * before the default router selection, we perform
982			 * the check now.
983			 */
984			pfxlist_onlink_check();
985
986			if (dr == TAILQ_FIRST(&nd_defrouter)) {
987				/*
988				 * It is used as the current default router,
989				 * so we have to move it to the end of the
990				 * list and choose a new one.
991				 * XXX: it is not very efficient if this is
992				 *      the only router.
993				 */
994				TAILQ_REMOVE(&nd_defrouter, dr, dr_entry);
995				TAILQ_INSERT_TAIL(&nd_defrouter, dr, dr_entry);
996
997				defrouter_select();
998			}
999		}
1000		splx(s);
1001	}
1002
1003	/*
1004	 * Before deleting the entry, remember the next entry as the
1005	 * return value.  We need this because pfxlist_onlink_check() above
1006	 * might have freed other entries (particularly the old next entry) as
1007	 * a side effect (XXX).
1008	 */
1009	next = ln->ln_next;
1010
1011	/*
1012	 * Detach the route from the routing tree and the list of neighbor
1013	 * caches, and disable the route entry not to be used in already
1014	 * cached routes.
1015	 */
1016	rtrequest(RTM_DELETE, rt_key(rt), (struct sockaddr *)0,
1017	    rt_mask(rt), 0, (struct rtentry **)0);
1018
1019	return (next);
1020}
1021
1022/*
1023 * Upper-layer reachability hint for Neighbor Unreachability Detection.
1024 *
1025 * XXX cost-effective metods?
1026 */
1027void
1028nd6_nud_hint(rt, dst6, force)
1029	struct rtentry *rt;
1030	struct in6_addr *dst6;
1031	int force;
1032{
1033	struct llinfo_nd6 *ln;
1034
1035	/*
1036	 * If the caller specified "rt", use that.  Otherwise, resolve the
1037	 * routing table by supplied "dst6".
1038	 */
1039	if (!rt) {
1040		if (!dst6)
1041			return;
1042		if (!(rt = nd6_lookup(dst6, 0, NULL)))
1043			return;
1044	}
1045
1046	if ((rt->rt_flags & RTF_GATEWAY) != 0 ||
1047	    (rt->rt_flags & RTF_LLINFO) == 0 ||
1048	    !rt->rt_llinfo || !rt->rt_gateway ||
1049	    rt->rt_gateway->sa_family != AF_LINK) {
1050		/* This is not a host route. */
1051		return;
1052	}
1053
1054	ln = (struct llinfo_nd6 *)rt->rt_llinfo;
1055	if (ln->ln_state < ND6_LLINFO_REACHABLE)
1056		return;
1057
1058	/*
1059	 * if we get upper-layer reachability confirmation many times,
1060	 * it is possible we have false information.
1061	 */
1062	if (!force) {
1063		ln->ln_byhint++;
1064		if (ln->ln_byhint > nd6_maxnudhint)
1065			return;
1066	}
1067
1068	ln->ln_state = ND6_LLINFO_REACHABLE;
1069	if (ln->ln_expire)
1070		ln->ln_expire = time_second +
1071			ND_IFINFO(rt->rt_ifp)->reachable;
1072}
1073
1074void
1075nd6_rtrequest(req, rt, info)
1076	int	req;
1077	struct rtentry *rt;
1078	struct rt_addrinfo *info; /* xxx unused */
1079{
1080	struct sockaddr *gate = rt->rt_gateway;
1081	struct llinfo_nd6 *ln = (struct llinfo_nd6 *)rt->rt_llinfo;
1082	static struct sockaddr_dl null_sdl = {sizeof(null_sdl), AF_LINK};
1083	struct ifnet *ifp = rt->rt_ifp;
1084	struct ifaddr *ifa;
1085
1086	RT_LOCK_ASSERT(rt);
1087
1088	if ((rt->rt_flags & RTF_GATEWAY) != 0)
1089		return;
1090
1091	if (nd6_need_cache(ifp) == 0 && (rt->rt_flags & RTF_HOST) == 0) {
1092		/*
1093		 * This is probably an interface direct route for a link
1094		 * which does not need neighbor caches (e.g. fe80::%lo0/64).
1095		 * We do not need special treatment below for such a route.
1096		 * Moreover, the RTF_LLINFO flag which would be set below
1097		 * would annoy the ndp(8) command.
1098		 */
1099		return;
1100	}
1101
1102	if (req == RTM_RESOLVE &&
1103	    (nd6_need_cache(ifp) == 0 || /* stf case */
1104	     !nd6_is_addr_neighbor((struct sockaddr_in6 *)rt_key(rt), ifp))) {
1105		/*
1106		 * FreeBSD and BSD/OS often make a cloned host route based
1107		 * on a less-specific route (e.g. the default route).
1108		 * If the less specific route does not have a "gateway"
1109		 * (this is the case when the route just goes to a p2p or an
1110		 * stf interface), we'll mistakenly make a neighbor cache for
1111		 * the host route, and will see strange neighbor solicitation
1112		 * for the corresponding destination.  In order to avoid the
1113		 * confusion, we check if the destination of the route is
1114		 * a neighbor in terms of neighbor discovery, and stop the
1115		 * process if not.  Additionally, we remove the LLINFO flag
1116		 * so that ndp(8) will not try to get the neighbor information
1117		 * of the destination.
1118		 */
1119		rt->rt_flags &= ~RTF_LLINFO;
1120		return;
1121	}
1122
1123	switch (req) {
1124	case RTM_ADD:
1125		/*
1126		 * There is no backward compatibility :)
1127		 *
1128		 * if ((rt->rt_flags & RTF_HOST) == 0 &&
1129		 *     SIN(rt_mask(rt))->sin_addr.s_addr != 0xffffffff)
1130		 *	   rt->rt_flags |= RTF_CLONING;
1131		 */
1132		if (rt->rt_flags & (RTF_CLONING | RTF_LLINFO)) {
1133			/*
1134			 * Case 1: This route should come from
1135			 * a route to interface.  RTF_LLINFO flag is set
1136			 * for a host route whose destination should be
1137			 * treated as on-link.
1138			 */
1139			rt_setgate(rt, rt_key(rt),
1140				   (struct sockaddr *)&null_sdl);
1141			gate = rt->rt_gateway;
1142			SDL(gate)->sdl_type = ifp->if_type;
1143			SDL(gate)->sdl_index = ifp->if_index;
1144			if (ln)
1145				ln->ln_expire = time_second;
1146			if (ln && ln->ln_expire == 0) {
1147				/* kludge for desktops */
1148				ln->ln_expire = 1;
1149			}
1150			if ((rt->rt_flags & RTF_CLONING) != 0)
1151				break;
1152		}
1153		/*
1154		 * In IPv4 code, we try to annonuce new RTF_ANNOUNCE entry here.
1155		 * We don't do that here since llinfo is not ready yet.
1156		 *
1157		 * There are also couple of other things to be discussed:
1158		 * - unsolicited NA code needs improvement beforehand
1159		 * - RFC2461 says we MAY send multicast unsolicited NA
1160		 *   (7.2.6 paragraph 4), however, it also says that we
1161		 *   SHOULD provide a mechanism to prevent multicast NA storm.
1162		 *   we don't have anything like it right now.
1163		 *   note that the mechanism needs a mutual agreement
1164		 *   between proxies, which means that we need to implement
1165		 *   a new protocol, or a new kludge.
1166		 * - from RFC2461 6.2.4, host MUST NOT send an unsolicited NA.
1167		 *   we need to check ip6forwarding before sending it.
1168		 *   (or should we allow proxy ND configuration only for
1169		 *   routers?  there's no mention about proxy ND from hosts)
1170		 */
1171#if 0
1172		/* XXX it does not work */
1173		if (rt->rt_flags & RTF_ANNOUNCE)
1174			nd6_na_output(ifp,
1175			      &SIN6(rt_key(rt))->sin6_addr,
1176			      &SIN6(rt_key(rt))->sin6_addr,
1177			      ip6_forwarding ? ND_NA_FLAG_ROUTER : 0,
1178			      1, NULL);
1179#endif
1180		/* FALLTHROUGH */
1181	case RTM_RESOLVE:
1182		if ((ifp->if_flags & (IFF_POINTOPOINT | IFF_LOOPBACK)) == 0) {
1183			/*
1184			 * Address resolution isn't necessary for a point to
1185			 * point link, so we can skip this test for a p2p link.
1186			 */
1187			if (gate->sa_family != AF_LINK ||
1188			    gate->sa_len < sizeof(null_sdl)) {
1189				log(LOG_DEBUG,
1190				    "nd6_rtrequest: bad gateway value: %s\n",
1191				    if_name(ifp));
1192				break;
1193			}
1194			SDL(gate)->sdl_type = ifp->if_type;
1195			SDL(gate)->sdl_index = ifp->if_index;
1196		}
1197		if (ln != NULL)
1198			break;	/* This happens on a route change */
1199		/*
1200		 * Case 2: This route may come from cloning, or a manual route
1201		 * add with a LL address.
1202		 */
1203		R_Malloc(ln, struct llinfo_nd6 *, sizeof(*ln));
1204		rt->rt_llinfo = (caddr_t)ln;
1205		if (!ln) {
1206			log(LOG_DEBUG, "nd6_rtrequest: malloc failed\n");
1207			break;
1208		}
1209		nd6_inuse++;
1210		nd6_allocated++;
1211		Bzero(ln, sizeof(*ln));
1212		ln->ln_rt = rt;
1213		/* this is required for "ndp" command. - shin */
1214		if (req == RTM_ADD) {
1215		        /*
1216			 * gate should have some valid AF_LINK entry,
1217			 * and ln->ln_expire should have some lifetime
1218			 * which is specified by ndp command.
1219			 */
1220			ln->ln_state = ND6_LLINFO_REACHABLE;
1221			ln->ln_byhint = 0;
1222		} else {
1223		        /*
1224			 * When req == RTM_RESOLVE, rt is created and
1225			 * initialized in rtrequest(), so rt_expire is 0.
1226			 */
1227			ln->ln_state = ND6_LLINFO_NOSTATE;
1228			ln->ln_expire = time_second;
1229		}
1230		rt->rt_flags |= RTF_LLINFO;
1231		ln->ln_next = llinfo_nd6.ln_next;
1232		llinfo_nd6.ln_next = ln;
1233		ln->ln_prev = &llinfo_nd6;
1234		ln->ln_next->ln_prev = ln;
1235
1236		/*
1237		 * check if rt_key(rt) is one of my address assigned
1238		 * to the interface.
1239		 */
1240		ifa = (struct ifaddr *)in6ifa_ifpwithaddr(rt->rt_ifp,
1241		    &SIN6(rt_key(rt))->sin6_addr);
1242		if (ifa) {
1243			caddr_t macp = nd6_ifptomac(ifp);
1244			ln->ln_expire = 0;
1245			ln->ln_state = ND6_LLINFO_REACHABLE;
1246			ln->ln_byhint = 0;
1247			if (macp) {
1248				Bcopy(macp, LLADDR(SDL(gate)), ifp->if_addrlen);
1249				SDL(gate)->sdl_alen = ifp->if_addrlen;
1250			}
1251			if (nd6_useloopback) {
1252				rt->rt_ifp = &loif[0];	/* XXX */
1253				/*
1254				 * Make sure rt_ifa be equal to the ifaddr
1255				 * corresponding to the address.
1256				 * We need this because when we refer
1257				 * rt_ifa->ia6_flags in ip6_input, we assume
1258				 * that the rt_ifa points to the address instead
1259				 * of the loopback address.
1260				 */
1261				if (ifa != rt->rt_ifa) {
1262					IFAFREE(rt->rt_ifa);
1263					IFAREF(ifa);
1264					rt->rt_ifa = ifa;
1265				}
1266			}
1267		} else if (rt->rt_flags & RTF_ANNOUNCE) {
1268			ln->ln_expire = 0;
1269			ln->ln_state = ND6_LLINFO_REACHABLE;
1270			ln->ln_byhint = 0;
1271
1272			/* join solicited node multicast for proxy ND */
1273			if (ifp->if_flags & IFF_MULTICAST) {
1274				struct in6_addr llsol;
1275				int error;
1276
1277				llsol = SIN6(rt_key(rt))->sin6_addr;
1278				llsol.s6_addr16[0] = htons(0xff02);
1279				llsol.s6_addr16[1] = htons(ifp->if_index);
1280				llsol.s6_addr32[1] = 0;
1281				llsol.s6_addr32[2] = htonl(1);
1282				llsol.s6_addr8[12] = 0xff;
1283
1284				if (!in6_addmulti(&llsol, ifp, &error)) {
1285					nd6log((LOG_ERR, "%s: failed to join "
1286					    "%s (errno=%d)\n", if_name(ifp),
1287					    ip6_sprintf(&llsol), error));
1288				}
1289			}
1290		}
1291		break;
1292
1293	case RTM_DELETE:
1294		if (!ln)
1295			break;
1296		/* leave from solicited node multicast for proxy ND */
1297		if ((rt->rt_flags & RTF_ANNOUNCE) != 0 &&
1298		    (ifp->if_flags & IFF_MULTICAST) != 0) {
1299			struct in6_addr llsol;
1300			struct in6_multi *in6m;
1301
1302			llsol = SIN6(rt_key(rt))->sin6_addr;
1303			llsol.s6_addr16[0] = htons(0xff02);
1304			llsol.s6_addr16[1] = htons(ifp->if_index);
1305			llsol.s6_addr32[1] = 0;
1306			llsol.s6_addr32[2] = htonl(1);
1307			llsol.s6_addr8[12] = 0xff;
1308
1309			IN6_LOOKUP_MULTI(llsol, ifp, in6m);
1310			if (in6m)
1311				in6_delmulti(in6m);
1312		}
1313		nd6_inuse--;
1314		ln->ln_next->ln_prev = ln->ln_prev;
1315		ln->ln_prev->ln_next = ln->ln_next;
1316		ln->ln_prev = NULL;
1317		rt->rt_llinfo = 0;
1318		rt->rt_flags &= ~RTF_LLINFO;
1319		if (ln->ln_hold)
1320			m_freem(ln->ln_hold);
1321		Free((caddr_t)ln);
1322	}
1323}
1324
1325int
1326nd6_ioctl(cmd, data, ifp)
1327	u_long cmd;
1328	caddr_t	data;
1329	struct ifnet *ifp;
1330{
1331	struct in6_drlist *drl = (struct in6_drlist *)data;
1332	struct in6_oprlist *oprl = (struct in6_oprlist *)data;
1333	struct in6_ndireq *ndi = (struct in6_ndireq *)data;
1334	struct in6_nbrinfo *nbi = (struct in6_nbrinfo *)data;
1335	struct in6_ndifreq *ndif = (struct in6_ndifreq *)data;
1336	struct nd_defrouter *dr, any;
1337	struct nd_prefix *pr;
1338	struct rtentry *rt;
1339	int i = 0, error = 0;
1340	int s;
1341
1342	switch (cmd) {
1343	case SIOCGDRLST_IN6:
1344		/*
1345		 * obsolete API, use sysctl under net.inet6.icmp6
1346		 */
1347		bzero(drl, sizeof(*drl));
1348		s = splnet();
1349		dr = TAILQ_FIRST(&nd_defrouter);
1350		while (dr && i < DRLSTSIZ) {
1351			drl->defrouter[i].rtaddr = dr->rtaddr;
1352			in6_clearscope(&drl->defrouter[i].rtaddr);
1353
1354			drl->defrouter[i].flags = dr->flags;
1355			drl->defrouter[i].rtlifetime = dr->rtlifetime;
1356			drl->defrouter[i].expire = dr->expire;
1357			drl->defrouter[i].if_index = dr->ifp->if_index;
1358			i++;
1359			dr = TAILQ_NEXT(dr, dr_entry);
1360		}
1361		splx(s);
1362		break;
1363	case SIOCGPRLST_IN6:
1364		/*
1365		 * obsolete API, use sysctl under net.inet6.icmp6
1366		 *
1367		 * XXX the structure in6_prlist was changed in backward-
1368		 * incompatible manner.  in6_oprlist is used for SIOCGPRLST_IN6,
1369		 * in6_prlist is used for nd6_sysctl() - fill_prlist().
1370		 */
1371		/*
1372		 * XXX meaning of fields, especialy "raflags", is very
1373		 * differnet between RA prefix list and RR/static prefix list.
1374		 * how about separating ioctls into two?
1375		 */
1376		bzero(oprl, sizeof(*oprl));
1377		s = splnet();
1378		pr = nd_prefix.lh_first;
1379		while (pr && i < PRLSTSIZ) {
1380			struct nd_pfxrouter *pfr;
1381			int j;
1382
1383			(void)in6_embedscope(&oprl->prefix[i].prefix,
1384			    &pr->ndpr_prefix, NULL, NULL);
1385			oprl->prefix[i].raflags = pr->ndpr_raf;
1386			oprl->prefix[i].prefixlen = pr->ndpr_plen;
1387			oprl->prefix[i].vltime = pr->ndpr_vltime;
1388			oprl->prefix[i].pltime = pr->ndpr_pltime;
1389			oprl->prefix[i].if_index = pr->ndpr_ifp->if_index;
1390			oprl->prefix[i].expire = pr->ndpr_expire;
1391
1392			pfr = pr->ndpr_advrtrs.lh_first;
1393			j = 0;
1394			while (pfr) {
1395				if (j < DRLSTSIZ) {
1396#define RTRADDR oprl->prefix[i].advrtr[j]
1397					RTRADDR = pfr->router->rtaddr;
1398					in6_clearscope(&RTRADDR);
1399#undef RTRADDR
1400				}
1401				j++;
1402				pfr = pfr->pfr_next;
1403			}
1404			oprl->prefix[i].advrtrs = j;
1405			oprl->prefix[i].origin = PR_ORIG_RA;
1406
1407			i++;
1408			pr = pr->ndpr_next;
1409		}
1410	      {
1411		struct rr_prefix *rpp;
1412
1413		for (rpp = LIST_FIRST(&rr_prefix); rpp;
1414		     rpp = LIST_NEXT(rpp, rp_entry)) {
1415			if (i >= PRLSTSIZ)
1416				break;
1417			(void)in6_embedscope(&oprl->prefix[i].prefix,
1418			    &pr->ndpr_prefix, NULL, NULL);
1419			oprl->prefix[i].raflags = rpp->rp_raf;
1420			oprl->prefix[i].prefixlen = rpp->rp_plen;
1421			oprl->prefix[i].vltime = rpp->rp_vltime;
1422			oprl->prefix[i].pltime = rpp->rp_pltime;
1423			oprl->prefix[i].if_index = rpp->rp_ifp->if_index;
1424			oprl->prefix[i].expire = rpp->rp_expire;
1425			oprl->prefix[i].advrtrs = 0;
1426			oprl->prefix[i].origin = rpp->rp_origin;
1427			i++;
1428		}
1429	      }
1430		splx(s);
1431
1432		break;
1433	case OSIOCGIFINFO_IN6:
1434		/* XXX: old ndp(8) assumes a positive value for linkmtu. */
1435		bzero(&ndi->ndi, sizeof(ndi->ndi));
1436		ndi->ndi.linkmtu = IN6_LINKMTU(ifp);
1437		ndi->ndi.maxmtu = ND_IFINFO(ifp)->maxmtu;
1438		ndi->ndi.basereachable = ND_IFINFO(ifp)->basereachable;
1439		ndi->ndi.reachable = ND_IFINFO(ifp)->reachable;
1440		ndi->ndi.retrans = ND_IFINFO(ifp)->retrans;
1441		ndi->ndi.flags = ND_IFINFO(ifp)->flags;
1442		ndi->ndi.recalctm = ND_IFINFO(ifp)->recalctm;
1443		ndi->ndi.chlim = ND_IFINFO(ifp)->chlim;
1444		break;
1445	case SIOCGIFINFO_IN6:
1446		ndi->ndi = *ND_IFINFO(ifp);
1447		ndi->ndi.linkmtu = IN6_LINKMTU(ifp);
1448		break;
1449	case SIOCSIFINFO_FLAGS:
1450		ND_IFINFO(ifp)->flags = ndi->ndi.flags;
1451		break;
1452	case SIOCSNDFLUSH_IN6:	/* XXX: the ioctl name is confusing... */
1453		/* flush default router list */
1454		/*
1455		 * xxx sumikawa: should not delete route if default
1456		 * route equals to the top of default router list
1457		 */
1458		bzero(&any, sizeof(any));
1459		defrouter_delreq(&any, 0);
1460		defrouter_select();
1461		/* xxx sumikawa: flush prefix list */
1462		break;
1463	case SIOCSPFXFLUSH_IN6:
1464	{
1465		/* flush all the prefix advertised by routers */
1466		struct nd_prefix *pr, *next;
1467
1468		s = splnet();
1469		for (pr = nd_prefix.lh_first; pr; pr = next) {
1470			struct in6_ifaddr *ia, *ia_next;
1471
1472			next = pr->ndpr_next;
1473
1474			if (IN6_IS_ADDR_LINKLOCAL(&pr->ndpr_prefix.sin6_addr))
1475				continue; /* XXX */
1476
1477			/* do we really have to remove addresses as well? */
1478			for (ia = in6_ifaddr; ia; ia = ia_next) {
1479				/* ia might be removed.  keep the next ptr. */
1480				ia_next = ia->ia_next;
1481
1482				if ((ia->ia6_flags & IN6_IFF_AUTOCONF) == 0)
1483					continue;
1484
1485				if (ia->ia6_ndpr == pr)
1486					in6_purgeaddr(&ia->ia_ifa);
1487			}
1488			prelist_remove(pr);
1489		}
1490		splx(s);
1491		break;
1492	}
1493	case SIOCSRTRFLUSH_IN6:
1494	{
1495		/* flush all the default routers */
1496		struct nd_defrouter *dr, *next;
1497
1498		s = splnet();
1499		if ((dr = TAILQ_FIRST(&nd_defrouter)) != NULL) {
1500			/*
1501			 * The first entry of the list may be stored in
1502			 * the routing table, so we'll delete it later.
1503			 */
1504			for (dr = TAILQ_NEXT(dr, dr_entry); dr; dr = next) {
1505				next = TAILQ_NEXT(dr, dr_entry);
1506				defrtrlist_del(dr);
1507			}
1508			defrtrlist_del(TAILQ_FIRST(&nd_defrouter));
1509		}
1510		splx(s);
1511		break;
1512	}
1513	case SIOCGNBRINFO_IN6:
1514	{
1515		struct llinfo_nd6 *ln;
1516		struct in6_addr nb_addr = nbi->addr; /* make local for safety */
1517
1518		/*
1519		 * XXX: KAME specific hack for scoped addresses
1520		 *      XXXX: for other scopes than link-local?
1521		 */
1522		if (IN6_IS_ADDR_LINKLOCAL(&nbi->addr) ||
1523		    IN6_IS_ADDR_MC_LINKLOCAL(&nbi->addr)) {
1524			u_int16_t *idp = (u_int16_t *)&nb_addr.s6_addr[2];
1525
1526			if (*idp == 0)
1527				*idp = htons(ifp->if_index);
1528		}
1529
1530		s = splnet();
1531		if ((rt = nd6_lookup(&nb_addr, 0, ifp)) == NULL) {
1532			error = EINVAL;
1533			splx(s);
1534			break;
1535		}
1536		ln = (struct llinfo_nd6 *)rt->rt_llinfo;
1537		nbi->state = ln->ln_state;
1538		nbi->asked = ln->ln_asked;
1539		nbi->isrouter = ln->ln_router;
1540		nbi->expire = ln->ln_expire;
1541		splx(s);
1542
1543		break;
1544	}
1545	case SIOCGDEFIFACE_IN6:	/* XXX: should be implemented as a sysctl? */
1546		ndif->ifindex = nd6_defifindex;
1547		break;
1548	case SIOCSDEFIFACE_IN6:	/* XXX: should be implemented as a sysctl? */
1549		return (nd6_setdefaultiface(ndif->ifindex));
1550	}
1551	return (error);
1552}
1553
1554/*
1555 * Create neighbor cache entry and cache link-layer address,
1556 * on reception of inbound ND6 packets.  (RS/RA/NS/redirect)
1557 */
1558struct rtentry *
1559nd6_cache_lladdr(ifp, from, lladdr, lladdrlen, type, code)
1560	struct ifnet *ifp;
1561	struct in6_addr *from;
1562	char *lladdr;
1563	int lladdrlen;
1564	int type;	/* ICMP6 type */
1565	int code;	/* type dependent information */
1566{
1567	struct rtentry *rt = NULL;
1568	struct llinfo_nd6 *ln = NULL;
1569	int is_newentry;
1570	struct sockaddr_dl *sdl = NULL;
1571	int do_update;
1572	int olladdr;
1573	int llchange;
1574	int newstate = 0;
1575
1576	if (!ifp)
1577		panic("ifp == NULL in nd6_cache_lladdr");
1578	if (!from)
1579		panic("from == NULL in nd6_cache_lladdr");
1580
1581	/* nothing must be updated for unspecified address */
1582	if (IN6_IS_ADDR_UNSPECIFIED(from))
1583		return NULL;
1584
1585	/*
1586	 * Validation about ifp->if_addrlen and lladdrlen must be done in
1587	 * the caller.
1588	 *
1589	 * XXX If the link does not have link-layer adderss, what should
1590	 * we do? (ifp->if_addrlen == 0)
1591	 * Spec says nothing in sections for RA, RS and NA.  There's small
1592	 * description on it in NS section (RFC 2461 7.2.3).
1593	 */
1594
1595	rt = nd6_lookup(from, 0, ifp);
1596	if (!rt) {
1597#if 0
1598		/* nothing must be done if there's no lladdr */
1599		if (!lladdr || !lladdrlen)
1600			return NULL;
1601#endif
1602
1603		rt = nd6_lookup(from, 1, ifp);
1604		is_newentry = 1;
1605	} else {
1606		/* do nothing if static ndp is set */
1607		if (rt->rt_flags & RTF_STATIC)
1608			return NULL;
1609		is_newentry = 0;
1610	}
1611
1612	if (!rt)
1613		return NULL;
1614	if ((rt->rt_flags & (RTF_GATEWAY | RTF_LLINFO)) != RTF_LLINFO) {
1615fail:
1616		(void)nd6_free(rt);
1617		return NULL;
1618	}
1619	ln = (struct llinfo_nd6 *)rt->rt_llinfo;
1620	if (!ln)
1621		goto fail;
1622	if (!rt->rt_gateway)
1623		goto fail;
1624	if (rt->rt_gateway->sa_family != AF_LINK)
1625		goto fail;
1626	sdl = SDL(rt->rt_gateway);
1627
1628	olladdr = (sdl->sdl_alen) ? 1 : 0;
1629	if (olladdr && lladdr) {
1630		if (bcmp(lladdr, LLADDR(sdl), ifp->if_addrlen))
1631			llchange = 1;
1632		else
1633			llchange = 0;
1634	} else
1635		llchange = 0;
1636
1637	/*
1638	 * newentry olladdr  lladdr  llchange	(*=record)
1639	 *	0	n	n	--	(1)
1640	 *	0	y	n	--	(2)
1641	 *	0	n	y	--	(3) * STALE
1642	 *	0	y	y	n	(4) *
1643	 *	0	y	y	y	(5) * STALE
1644	 *	1	--	n	--	(6)   NOSTATE(= PASSIVE)
1645	 *	1	--	y	--	(7) * STALE
1646	 */
1647
1648	if (lladdr) {		/* (3-5) and (7) */
1649		/*
1650		 * Record source link-layer address
1651		 * XXX is it dependent to ifp->if_type?
1652		 */
1653		sdl->sdl_alen = ifp->if_addrlen;
1654		bcopy(lladdr, LLADDR(sdl), ifp->if_addrlen);
1655	}
1656
1657	if (!is_newentry) {
1658		if ((!olladdr && lladdr) ||		/* (3) */
1659		    (olladdr && lladdr && llchange)) {	/* (5) */
1660			do_update = 1;
1661			newstate = ND6_LLINFO_STALE;
1662		} else					/* (1-2,4) */
1663			do_update = 0;
1664	} else {
1665		do_update = 1;
1666		if (!lladdr)				/* (6) */
1667			newstate = ND6_LLINFO_NOSTATE;
1668		else					/* (7) */
1669			newstate = ND6_LLINFO_STALE;
1670	}
1671
1672	if (do_update) {
1673		/*
1674		 * Update the state of the neighbor cache.
1675		 */
1676		ln->ln_state = newstate;
1677
1678		if (ln->ln_state == ND6_LLINFO_STALE) {
1679			/*
1680			 * XXX: since nd6_output() below will cause
1681			 * state tansition to DELAY and reset the timer,
1682			 * we must set the timer now, although it is actually
1683			 * meaningless.
1684			 */
1685			ln->ln_expire = time_second + nd6_gctimer;
1686
1687			if (ln->ln_hold) {
1688				/*
1689				 * we assume ifp is not a p2p here, so just
1690				 * set the 2nd argument as the 1st one.
1691				 */
1692				nd6_output(ifp, ifp, ln->ln_hold,
1693				    (struct sockaddr_in6 *)rt_key(rt), rt);
1694				ln->ln_hold = NULL;
1695			}
1696		} else if (ln->ln_state == ND6_LLINFO_INCOMPLETE) {
1697			/* probe right away */
1698			ln->ln_expire = time_second;
1699		}
1700	}
1701
1702	/*
1703	 * ICMP6 type dependent behavior.
1704	 *
1705	 * NS: clear IsRouter if new entry
1706	 * RS: clear IsRouter
1707	 * RA: set IsRouter if there's lladdr
1708	 * redir: clear IsRouter if new entry
1709	 *
1710	 * RA case, (1):
1711	 * The spec says that we must set IsRouter in the following cases:
1712	 * - If lladdr exist, set IsRouter.  This means (1-5).
1713	 * - If it is old entry (!newentry), set IsRouter.  This means (7).
1714	 * So, based on the spec, in (1-5) and (7) cases we must set IsRouter.
1715	 * A quetion arises for (1) case.  (1) case has no lladdr in the
1716	 * neighbor cache, this is similar to (6).
1717	 * This case is rare but we figured that we MUST NOT set IsRouter.
1718	 *
1719	 * newentry olladdr  lladdr  llchange	    NS  RS  RA	redir
1720	 *							D R
1721	 *	0	n	n	--	(1)	c   ?     s
1722	 *	0	y	n	--	(2)	c   s     s
1723	 *	0	n	y	--	(3)	c   s     s
1724	 *	0	y	y	n	(4)	c   s     s
1725	 *	0	y	y	y	(5)	c   s     s
1726	 *	1	--	n	--	(6) c	c 	c s
1727	 *	1	--	y	--	(7) c	c   s	c s
1728	 *
1729	 *					(c=clear s=set)
1730	 */
1731	switch (type & 0xff) {
1732	case ND_NEIGHBOR_SOLICIT:
1733		/*
1734		 * New entry must have is_router flag cleared.
1735		 */
1736		if (is_newentry)	/* (6-7) */
1737			ln->ln_router = 0;
1738		break;
1739	case ND_REDIRECT:
1740		/*
1741		 * If the icmp is a redirect to a better router, always set the
1742		 * is_router flag.  Otherwise, if the entry is newly created,
1743		 * clear the flag.  [RFC 2461, sec 8.3]
1744		 */
1745		if (code == ND_REDIRECT_ROUTER)
1746			ln->ln_router = 1;
1747		else if (is_newentry) /* (6-7) */
1748			ln->ln_router = 0;
1749		break;
1750	case ND_ROUTER_SOLICIT:
1751		/*
1752		 * is_router flag must always be cleared.
1753		 */
1754		ln->ln_router = 0;
1755		break;
1756	case ND_ROUTER_ADVERT:
1757		/*
1758		 * Mark an entry with lladdr as a router.
1759		 */
1760		if ((!is_newentry && (olladdr || lladdr)) ||	/* (2-5) */
1761		    (is_newentry && lladdr)) {			/* (7) */
1762			ln->ln_router = 1;
1763		}
1764		break;
1765	}
1766
1767	/*
1768	 * When the link-layer address of a router changes, select the
1769	 * best router again.  In particular, when the neighbor entry is newly
1770	 * created, it might affect the selection policy.
1771	 * Question: can we restrict the first condition to the "is_newentry"
1772	 * case?
1773	 * XXX: when we hear an RA from a new router with the link-layer
1774	 * address option, defrouter_select() is called twice, since
1775	 * defrtrlist_update called the function as well.  However, I believe
1776	 * we can compromise the overhead, since it only happens the first
1777	 * time.
1778	 * XXX: although defrouter_select() should not have a bad effect
1779	 * for those are not autoconfigured hosts, we explicitly avoid such
1780	 * cases for safety.
1781	 */
1782	if (do_update && ln->ln_router && !ip6_forwarding && ip6_accept_rtadv)
1783		defrouter_select();
1784
1785	return rt;
1786}
1787
1788static void
1789nd6_slowtimo(ignored_arg)
1790    void *ignored_arg;
1791{
1792	int s = splnet();
1793	struct nd_ifinfo *nd6if;
1794	struct ifnet *ifp;
1795
1796	callout_reset(&nd6_slowtimo_ch, ND6_SLOWTIMER_INTERVAL * hz,
1797	    nd6_slowtimo, NULL);
1798	for (ifp = TAILQ_FIRST(&ifnet); ifp; ifp = TAILQ_NEXT(ifp, if_list)) {
1799		nd6if = ND_IFINFO(ifp);
1800		if (nd6if->basereachable && /* already initialized */
1801		    (nd6if->recalctm -= ND6_SLOWTIMER_INTERVAL) <= 0) {
1802			/*
1803			 * Since reachable time rarely changes by router
1804			 * advertisements, we SHOULD insure that a new random
1805			 * value gets recomputed at least once every few hours.
1806			 * (RFC 2461, 6.3.4)
1807			 */
1808			nd6if->recalctm = nd6_recalc_reachtm_interval;
1809			nd6if->reachable = ND_COMPUTE_RTIME(nd6if->basereachable);
1810		}
1811	}
1812	splx(s);
1813}
1814
1815#define senderr(e) { error = (e); goto bad;}
1816int
1817nd6_output(ifp, origifp, m0, dst, rt0)
1818	struct ifnet *ifp;
1819	struct ifnet *origifp;
1820	struct mbuf *m0;
1821	struct sockaddr_in6 *dst;
1822	struct rtentry *rt0;
1823{
1824	struct mbuf *m = m0;
1825	struct rtentry *rt = rt0;
1826	struct sockaddr_in6 *gw6 = NULL;
1827	struct llinfo_nd6 *ln = NULL;
1828	int error = 0;
1829
1830	if (IN6_IS_ADDR_MULTICAST(&dst->sin6_addr))
1831		goto sendpkt;
1832
1833	if (nd6_need_cache(ifp) == 0)
1834		goto sendpkt;
1835
1836	/*
1837	 * next hop determination.  This routine is derived from ether_outpout.
1838	 */
1839	if (rt) {
1840		if ((rt->rt_flags & RTF_UP) == 0) {
1841			rt0 = rt = rtalloc1((struct sockaddr *)dst, 1, 0UL);
1842			if (rt != NULL) {
1843				RT_REMREF(rt);
1844				RT_UNLOCK(rt);
1845				if (rt->rt_ifp != ifp) {
1846					/* XXX: loop care? */
1847					return nd6_output(ifp, origifp, m0,
1848					    dst, rt);
1849				}
1850			} else
1851				senderr(EHOSTUNREACH);
1852		}
1853
1854		if (rt->rt_flags & RTF_GATEWAY) {
1855			gw6 = (struct sockaddr_in6 *)rt->rt_gateway;
1856
1857			/*
1858			 * We skip link-layer address resolution and NUD
1859			 * if the gateway is not a neighbor from ND point
1860			 * of view, regardless of the value of nd_ifinfo.flags.
1861			 * The second condition is a bit tricky; we skip
1862			 * if the gateway is our own address, which is
1863			 * sometimes used to install a route to a p2p link.
1864			 */
1865			if (!nd6_is_addr_neighbor(gw6, ifp) ||
1866			    in6ifa_ifpwithaddr(ifp, &gw6->sin6_addr)) {
1867				/*
1868				 * We allow this kind of tricky route only
1869				 * when the outgoing interface is p2p.
1870				 * XXX: we may need a more generic rule here.
1871				 */
1872				if ((ifp->if_flags & IFF_POINTOPOINT) == 0)
1873					senderr(EHOSTUNREACH);
1874
1875				goto sendpkt;
1876			}
1877
1878			if (rt->rt_gwroute == 0)
1879				goto lookup;
1880			if (((rt = rt->rt_gwroute)->rt_flags & RTF_UP) == 0) {
1881				RT_LOCK(rt);
1882				rtfree(rt); rt = rt0;
1883			lookup:
1884				rt->rt_gwroute = rtalloc1(rt->rt_gateway, 1, 0UL);
1885				if ((rt = rt->rt_gwroute) == 0)
1886					senderr(EHOSTUNREACH);
1887				RT_UNLOCK(rt);
1888			}
1889		}
1890	}
1891
1892	/*
1893	 * Address resolution or Neighbor Unreachability Detection
1894	 * for the next hop.
1895	 * At this point, the destination of the packet must be a unicast
1896	 * or an anycast address(i.e. not a multicast).
1897	 */
1898
1899	/* Look up the neighbor cache for the nexthop */
1900	if (rt && (rt->rt_flags & RTF_LLINFO) != 0)
1901		ln = (struct llinfo_nd6 *)rt->rt_llinfo;
1902	else {
1903		/*
1904		 * Since nd6_is_addr_neighbor() internally calls nd6_lookup(),
1905		 * the condition below is not very efficient.  But we believe
1906		 * it is tolerable, because this should be a rare case.
1907		 */
1908		if (nd6_is_addr_neighbor(dst, ifp) &&
1909		    (rt = nd6_lookup(&dst->sin6_addr, 1, ifp)) != NULL)
1910			ln = (struct llinfo_nd6 *)rt->rt_llinfo;
1911	}
1912	if (!ln || !rt) {
1913		if ((ifp->if_flags & IFF_POINTOPOINT) == 0 &&
1914		    !(ND_IFINFO(ifp)->flags & ND6_IFF_PERFORMNUD)) {
1915			log(LOG_DEBUG,
1916			    "nd6_output: can't allocate llinfo for %s "
1917			    "(ln=%p, rt=%p)\n",
1918			    ip6_sprintf(&dst->sin6_addr), ln, rt);
1919			senderr(EIO);	/* XXX: good error? */
1920		}
1921
1922		goto sendpkt;	/* send anyway */
1923	}
1924
1925	/* We don't have to do link-layer address resolution on a p2p link. */
1926	if ((ifp->if_flags & IFF_POINTOPOINT) != 0 &&
1927	    ln->ln_state < ND6_LLINFO_REACHABLE) {
1928		ln->ln_state = ND6_LLINFO_STALE;
1929		ln->ln_expire = time_second + nd6_gctimer;
1930	}
1931
1932	/*
1933	 * The first time we send a packet to a neighbor whose entry is
1934	 * STALE, we have to change the state to DELAY and a sets a timer to
1935	 * expire in DELAY_FIRST_PROBE_TIME seconds to ensure do
1936	 * neighbor unreachability detection on expiration.
1937	 * (RFC 2461 7.3.3)
1938	 */
1939	if (ln->ln_state == ND6_LLINFO_STALE) {
1940		ln->ln_asked = 0;
1941		ln->ln_state = ND6_LLINFO_DELAY;
1942		ln->ln_expire = time_second + nd6_delay;
1943	}
1944
1945	/*
1946	 * If the neighbor cache entry has a state other than INCOMPLETE
1947	 * (i.e. its link-layer address is already resolved), just
1948	 * send the packet.
1949	 */
1950	if (ln->ln_state > ND6_LLINFO_INCOMPLETE)
1951		goto sendpkt;
1952
1953	/*
1954	 * There is a neighbor cache entry, but no ethernet address
1955	 * response yet.  Replace the held mbuf (if any) with this
1956	 * latest one.
1957	 *
1958	 * This code conforms to the rate-limiting rule described in Section
1959	 * 7.2.2 of RFC 2461, because the timer is set correctly after sending
1960	 * an NS below.
1961	 */
1962	if (ln->ln_state == ND6_LLINFO_NOSTATE)
1963		ln->ln_state = ND6_LLINFO_INCOMPLETE;
1964	if (ln->ln_hold)
1965		m_freem(ln->ln_hold);
1966	ln->ln_hold = m;
1967	if (ln->ln_expire) {
1968		if (ln->ln_asked < nd6_mmaxtries &&
1969		    ln->ln_expire < time_second) {
1970			ln->ln_asked++;
1971			ln->ln_expire = time_second +
1972				ND_IFINFO(ifp)->retrans / 1000;
1973			nd6_ns_output(ifp, NULL, &dst->sin6_addr, ln, 0);
1974		}
1975	}
1976	return (0);
1977
1978  sendpkt:
1979#ifdef IPSEC
1980	/* clean ipsec history once it goes out of the node */
1981	ipsec_delaux(m);
1982#endif
1983
1984#ifdef MAC
1985	mac_create_mbuf_linklayer(ifp, m);
1986#endif
1987	if ((ifp->if_flags & IFF_LOOPBACK) != 0) {
1988		return ((*ifp->if_output)(origifp, m, (struct sockaddr *)dst,
1989		    rt));
1990	}
1991	return ((*ifp->if_output)(ifp, m, (struct sockaddr *)dst, rt));
1992
1993  bad:
1994	if (m)
1995		m_freem(m);
1996	return (error);
1997}
1998#undef senderr
1999
2000int
2001nd6_need_cache(ifp)
2002	struct ifnet *ifp;
2003{
2004	/*
2005	 * XXX: we currently do not make neighbor cache on any interface
2006	 * other than ARCnet, Ethernet, FDDI and GIF.
2007	 *
2008	 * RFC2893 says:
2009	 * - unidirectional tunnels needs no ND
2010	 */
2011	switch (ifp->if_type) {
2012	case IFT_ARCNET:
2013	case IFT_ETHER:
2014	case IFT_FDDI:
2015	case IFT_IEEE1394:
2016#ifdef IFT_L2VLAN
2017	case IFT_L2VLAN:
2018#endif
2019#ifdef IFT_IEEE80211
2020	case IFT_IEEE80211:
2021#endif
2022	case IFT_GIF:		/* XXX need more cases? */
2023		return (1);
2024	default:
2025		return (0);
2026	}
2027}
2028
2029int
2030nd6_storelladdr(ifp, rt, m, dst, desten)
2031	struct ifnet *ifp;
2032	struct rtentry *rt;
2033	struct mbuf *m;
2034	struct sockaddr *dst;
2035	u_char *desten;
2036{
2037	int i;
2038	struct sockaddr_dl *sdl;
2039
2040	if (m->m_flags & M_MCAST) {
2041		switch (ifp->if_type) {
2042		case IFT_ETHER:
2043		case IFT_FDDI:
2044#ifdef IFT_L2VLAN
2045	case IFT_L2VLAN:
2046#endif
2047#ifdef IFT_IEEE80211
2048		case IFT_IEEE80211:
2049#endif
2050		case IFT_ISO88025:
2051			ETHER_MAP_IPV6_MULTICAST(&SIN6(dst)->sin6_addr,
2052						 desten);
2053			return (1);
2054		case IFT_IEEE1394:
2055			/*
2056			 * netbsd can use if_broadcastaddr, but we don't do so
2057			 * to reduce # of ifdef.
2058			 */
2059			for (i = 0; i < ifp->if_addrlen; i++)
2060				desten[i] = ~0;
2061			return (1);
2062		case IFT_ARCNET:
2063			*desten = 0;
2064			return (1);
2065		default:
2066			m_freem(m);
2067			return (0);
2068		}
2069	}
2070
2071	if (rt == NULL) {
2072		/* this could happen, if we could not allocate memory */
2073		m_freem(m);
2074		return (0);
2075	}
2076	if (rt->rt_gateway->sa_family != AF_LINK) {
2077		printf("nd6_storelladdr: something odd happens\n");
2078		m_freem(m);
2079		return (0);
2080	}
2081	sdl = SDL(rt->rt_gateway);
2082	if (sdl->sdl_alen == 0) {
2083		/* this should be impossible, but we bark here for debugging */
2084		printf("nd6_storelladdr: sdl_alen == 0\n");
2085		m_freem(m);
2086		return (0);
2087	}
2088
2089	bcopy(LLADDR(sdl), desten, sdl->sdl_alen);
2090	return (1);
2091}
2092
2093static int nd6_sysctl_drlist(SYSCTL_HANDLER_ARGS);
2094static int nd6_sysctl_prlist(SYSCTL_HANDLER_ARGS);
2095#ifdef SYSCTL_DECL
2096SYSCTL_DECL(_net_inet6_icmp6);
2097#endif
2098SYSCTL_NODE(_net_inet6_icmp6, ICMPV6CTL_ND6_DRLIST, nd6_drlist,
2099	CTLFLAG_RD, nd6_sysctl_drlist, "");
2100SYSCTL_NODE(_net_inet6_icmp6, ICMPV6CTL_ND6_PRLIST, nd6_prlist,
2101	CTLFLAG_RD, nd6_sysctl_prlist, "");
2102
2103static int
2104nd6_sysctl_drlist(SYSCTL_HANDLER_ARGS)
2105{
2106	int error;
2107	char buf[1024];
2108	struct in6_defrouter *d, *de;
2109	struct nd_defrouter *dr;
2110
2111	if (req->newptr)
2112		return EPERM;
2113	error = 0;
2114
2115	for (dr = TAILQ_FIRST(&nd_defrouter); dr;
2116	     dr = TAILQ_NEXT(dr, dr_entry)) {
2117		d = (struct in6_defrouter *)buf;
2118		de = (struct in6_defrouter *)(buf + sizeof(buf));
2119
2120		if (d + 1 <= de) {
2121			bzero(d, sizeof(*d));
2122			d->rtaddr.sin6_family = AF_INET6;
2123			d->rtaddr.sin6_len = sizeof(d->rtaddr);
2124			if (in6_recoverscope(&d->rtaddr, &dr->rtaddr,
2125			    dr->ifp) != 0)
2126				log(LOG_ERR,
2127				    "scope error in "
2128				    "default router list (%s)\n",
2129				    ip6_sprintf(&dr->rtaddr));
2130			d->flags = dr->flags;
2131			d->rtlifetime = dr->rtlifetime;
2132			d->expire = dr->expire;
2133			d->if_index = dr->ifp->if_index;
2134		} else
2135			panic("buffer too short");
2136
2137		error = SYSCTL_OUT(req, buf, sizeof(*d));
2138		if (error)
2139			break;
2140	}
2141
2142	return (error);
2143}
2144
2145static int
2146nd6_sysctl_prlist(SYSCTL_HANDLER_ARGS)
2147{
2148	int error;
2149	char buf[1024];
2150	struct in6_prefix *p, *pe;
2151	struct nd_prefix *pr;
2152
2153	if (req->newptr)
2154		return EPERM;
2155	error = 0;
2156
2157	for (pr = nd_prefix.lh_first; pr; pr = pr->ndpr_next) {
2158		u_short advrtrs;
2159		size_t advance;
2160		struct sockaddr_in6 *sin6, *s6;
2161		struct nd_pfxrouter *pfr;
2162
2163		p = (struct in6_prefix *)buf;
2164		pe = (struct in6_prefix *)(buf + sizeof(buf));
2165
2166		if (p + 1 <= pe) {
2167			bzero(p, sizeof(*p));
2168			sin6 = (struct sockaddr_in6 *)(p + 1);
2169
2170			p->prefix = pr->ndpr_prefix;
2171			if (in6_recoverscope(&p->prefix,
2172			    &p->prefix.sin6_addr, pr->ndpr_ifp) != 0)
2173				log(LOG_ERR,
2174				    "scope error in prefix list (%s)\n",
2175				    ip6_sprintf(&p->prefix.sin6_addr));
2176			p->raflags = pr->ndpr_raf;
2177			p->prefixlen = pr->ndpr_plen;
2178			p->vltime = pr->ndpr_vltime;
2179			p->pltime = pr->ndpr_pltime;
2180			p->if_index = pr->ndpr_ifp->if_index;
2181			p->expire = pr->ndpr_expire;
2182			p->refcnt = pr->ndpr_refcnt;
2183			p->flags = pr->ndpr_stateflags;
2184			p->origin = PR_ORIG_RA;
2185			advrtrs = 0;
2186			for (pfr = pr->ndpr_advrtrs.lh_first; pfr;
2187			     pfr = pfr->pfr_next) {
2188				if ((void *)&sin6[advrtrs + 1] > (void *)pe) {
2189					advrtrs++;
2190					continue;
2191				}
2192				s6 = &sin6[advrtrs];
2193				bzero(s6, sizeof(*s6));
2194				s6->sin6_family = AF_INET6;
2195				s6->sin6_len = sizeof(*sin6);
2196				if (in6_recoverscope(s6, &pfr->router->rtaddr,
2197				    pfr->router->ifp) != 0)
2198					log(LOG_ERR,
2199					    "scope error in "
2200					    "prefix list (%s)\n",
2201					    ip6_sprintf(&pfr->router->rtaddr));
2202				advrtrs++;
2203			}
2204			p->advrtrs = advrtrs;
2205		} else
2206			panic("buffer too short");
2207
2208		advance = sizeof(*p) + sizeof(*sin6) * advrtrs;
2209		error = SYSCTL_OUT(req, buf, advance);
2210		if (error)
2211			break;
2212	}
2213
2214	return (error);
2215}
2216