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