xref: /openbsd-src/sys/netinet6/nd6.c (revision 25c4e8bd056e974b28f4a0ffd39d76c190a56013)
1 /*	$OpenBSD: nd6.c,v 1.240 2022/07/22 13:27:17 kn Exp $	*/
2 /*	$KAME: nd6.c,v 1.280 2002/06/08 19:52:07 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 <sys/param.h>
34 #include <sys/systm.h>
35 #include <sys/timeout.h>
36 #include <sys/malloc.h>
37 #include <sys/mbuf.h>
38 #include <sys/socket.h>
39 #include <sys/sockio.h>
40 #include <sys/time.h>
41 #include <sys/kernel.h>
42 #include <sys/pool.h>
43 #include <sys/errno.h>
44 #include <sys/ioctl.h>
45 #include <sys/syslog.h>
46 #include <sys/queue.h>
47 #include <sys/stdint.h>
48 #include <sys/task.h>
49 
50 #include <net/if.h>
51 #include <net/if_dl.h>
52 #include <net/if_types.h>
53 #include <net/route.h>
54 
55 #include <netinet/in.h>
56 #include <netinet/if_ether.h>
57 #include <netinet/ip_ipsp.h>
58 
59 #include <netinet6/in6_var.h>
60 #include <netinet/ip6.h>
61 #include <netinet6/ip6_var.h>
62 #include <netinet6/nd6.h>
63 #include <netinet/icmp6.h>
64 
65 #define ND6_SLOWTIMER_INTERVAL (60 * 60) /* 1 hour */
66 #define ND6_RECALC_REACHTM_INTERVAL (60 * 120) /* 2 hours */
67 
68 /* timer values */
69 int	nd6_timer_next	= -1;	/* at which uptime nd6_timer runs */
70 time_t	nd6_expire_next	= -1;	/* at which uptime nd6_expire runs */
71 int	nd6_delay	= 5;	/* delay first probe time 5 second */
72 int	nd6_umaxtries	= 3;	/* maximum unicast query */
73 int	nd6_mmaxtries	= 3;	/* maximum multicast query */
74 int	nd6_gctimer	= (60 * 60 * 24); /* 1 day: garbage collection timer */
75 
76 /* preventing too many loops in ND option parsing */
77 int nd6_maxndopt = 10;	/* max # of ND options allowed */
78 
79 int nd6_maxnudhint = 0;	/* max # of subsequent upper layer hints */
80 
81 #ifdef ND6_DEBUG
82 int nd6_debug = 1;
83 #else
84 int nd6_debug = 0;
85 #endif
86 
87 TAILQ_HEAD(llinfo_nd6_head, llinfo_nd6) nd6_list;
88 struct	pool nd6_pool;		/* pool for llinfo_nd6 structures */
89 int	nd6_inuse;
90 
91 int nd6_recalc_reachtm_interval = ND6_RECALC_REACHTM_INTERVAL;
92 
93 void nd6_timer(void *);
94 void nd6_slowtimo(void *);
95 void nd6_expire(void *);
96 void nd6_expire_timer(void *);
97 void nd6_invalidate(struct rtentry *);
98 void nd6_free(struct rtentry *);
99 int nd6_llinfo_timer(struct rtentry *);
100 
101 struct timeout nd6_timer_to;
102 struct timeout nd6_slowtimo_ch;
103 struct timeout nd6_expire_timeout;
104 struct task nd6_expire_task;
105 
106 void
107 nd6_init(void)
108 {
109 	static int nd6_init_done = 0;
110 
111 	if (nd6_init_done) {
112 		log(LOG_NOTICE, "%s called more than once\n", __func__);
113 		return;
114 	}
115 
116 	TAILQ_INIT(&nd6_list);
117 	pool_init(&nd6_pool, sizeof(struct llinfo_nd6), 0,
118 	    IPL_SOFTNET, 0, "nd6", NULL);
119 
120 	task_set(&nd6_expire_task, nd6_expire, NULL);
121 
122 	nd6_init_done = 1;
123 
124 	/* start timer */
125 	timeout_set_proc(&nd6_timer_to, nd6_timer, NULL);
126 	timeout_set_proc(&nd6_slowtimo_ch, nd6_slowtimo, NULL);
127 	timeout_add_sec(&nd6_slowtimo_ch, ND6_SLOWTIMER_INTERVAL);
128 	timeout_set(&nd6_expire_timeout, nd6_expire_timer, NULL);
129 }
130 
131 struct nd_ifinfo *
132 nd6_ifattach(struct ifnet *ifp)
133 {
134 	struct nd_ifinfo *nd;
135 
136 	nd = malloc(sizeof(*nd), M_IP6NDP, M_WAITOK | M_ZERO);
137 
138 	nd->initialized = 1;
139 
140 	nd->basereachable = REACHABLE_TIME;
141 	nd->reachable = ND_COMPUTE_RTIME(nd->basereachable);
142 	nd->retrans = RETRANS_TIMER;
143 
144 	return nd;
145 }
146 
147 void
148 nd6_ifdetach(struct nd_ifinfo *nd)
149 {
150 
151 	free(nd, M_IP6NDP, sizeof(*nd));
152 }
153 
154 void
155 nd6_option_init(void *opt, int icmp6len, union nd_opts *ndopts)
156 {
157 	bzero(ndopts, sizeof(*ndopts));
158 	ndopts->nd_opts_search = (struct nd_opt_hdr *)opt;
159 	ndopts->nd_opts_last
160 		= (struct nd_opt_hdr *)(((u_char *)opt) + icmp6len);
161 
162 	if (icmp6len == 0) {
163 		ndopts->nd_opts_done = 1;
164 		ndopts->nd_opts_search = NULL;
165 	}
166 }
167 
168 /*
169  * Take one ND option.
170  */
171 struct nd_opt_hdr *
172 nd6_option(union nd_opts *ndopts)
173 {
174 	struct nd_opt_hdr *nd_opt;
175 	int olen;
176 
177 	if (!ndopts)
178 		panic("%s: ndopts == NULL", __func__);
179 	if (!ndopts->nd_opts_last)
180 		panic("%s: uninitialized ndopts", __func__);
181 	if (!ndopts->nd_opts_search)
182 		return NULL;
183 	if (ndopts->nd_opts_done)
184 		return NULL;
185 
186 	nd_opt = ndopts->nd_opts_search;
187 
188 	/* make sure nd_opt_len is inside the buffer */
189 	if ((caddr_t)&nd_opt->nd_opt_len >= (caddr_t)ndopts->nd_opts_last) {
190 		bzero(ndopts, sizeof(*ndopts));
191 		return NULL;
192 	}
193 
194 	olen = nd_opt->nd_opt_len << 3;
195 	if (olen == 0) {
196 		/*
197 		 * Message validation requires that all included
198 		 * options have a length that is greater than zero.
199 		 */
200 		bzero(ndopts, sizeof(*ndopts));
201 		return NULL;
202 	}
203 
204 	ndopts->nd_opts_search = (struct nd_opt_hdr *)((caddr_t)nd_opt + olen);
205 	if (ndopts->nd_opts_search > ndopts->nd_opts_last) {
206 		/* option overruns the end of buffer, invalid */
207 		bzero(ndopts, sizeof(*ndopts));
208 		return NULL;
209 	} else if (ndopts->nd_opts_search == ndopts->nd_opts_last) {
210 		/* reached the end of options chain */
211 		ndopts->nd_opts_done = 1;
212 		ndopts->nd_opts_search = NULL;
213 	}
214 	return nd_opt;
215 }
216 
217 /*
218  * Parse multiple ND options.
219  * This function is much easier to use, for ND routines that do not need
220  * multiple options of the same type.
221  */
222 int
223 nd6_options(union nd_opts *ndopts)
224 {
225 	struct nd_opt_hdr *nd_opt;
226 	int i = 0;
227 
228 	if (!ndopts)
229 		panic("%s: ndopts == NULL", __func__);
230 	if (!ndopts->nd_opts_last)
231 		panic("%s: uninitialized ndopts", __func__);
232 	if (!ndopts->nd_opts_search)
233 		return 0;
234 
235 	while (1) {
236 		nd_opt = nd6_option(ndopts);
237 		if (!nd_opt && !ndopts->nd_opts_last) {
238 			/*
239 			 * Message validation requires that all included
240 			 * options have a length that is greater than zero.
241 			 */
242 			icmp6stat_inc(icp6s_nd_badopt);
243 			bzero(ndopts, sizeof(*ndopts));
244 			return -1;
245 		}
246 
247 		if (!nd_opt)
248 			goto skip1;
249 
250 		switch (nd_opt->nd_opt_type) {
251 		case ND_OPT_SOURCE_LINKADDR:
252 		case ND_OPT_TARGET_LINKADDR:
253 		case ND_OPT_MTU:
254 		case ND_OPT_REDIRECTED_HEADER:
255 			if (ndopts->nd_opt_array[nd_opt->nd_opt_type]) {
256 				nd6log((LOG_INFO,
257 				    "duplicated ND6 option found (type=%d)\n",
258 				    nd_opt->nd_opt_type));
259 				/* XXX bark? */
260 			} else {
261 				ndopts->nd_opt_array[nd_opt->nd_opt_type]
262 					= nd_opt;
263 			}
264 			break;
265 		case ND_OPT_PREFIX_INFORMATION:
266 			if (ndopts->nd_opt_array[nd_opt->nd_opt_type] == 0) {
267 				ndopts->nd_opt_array[nd_opt->nd_opt_type]
268 					= nd_opt;
269 			}
270 			ndopts->nd_opts_pi_end =
271 				(struct nd_opt_prefix_info *)nd_opt;
272 			break;
273 		case ND_OPT_DNSSL:
274 		case ND_OPT_RDNSS:
275 			/* Don't warn */
276 			break;
277 		default:
278 			/*
279 			 * Unknown options must be silently ignored,
280 			 * to accommodate future extension to the protocol.
281 			 */
282 			nd6log((LOG_DEBUG,
283 			    "nd6_options: unsupported option %d - "
284 			    "option ignored\n", nd_opt->nd_opt_type));
285 		}
286 
287 skip1:
288 		i++;
289 		if (i > nd6_maxndopt) {
290 			icmp6stat_inc(icp6s_nd_toomanyopt);
291 			nd6log((LOG_INFO, "too many loop in nd opt\n"));
292 			break;
293 		}
294 
295 		if (ndopts->nd_opts_done)
296 			break;
297 	}
298 
299 	return 0;
300 }
301 
302 /*
303  * ND6 timer routine to handle ND6 entries
304  */
305 void
306 nd6_llinfo_settimer(struct llinfo_nd6 *ln, unsigned int secs)
307 {
308 	time_t expire = getuptime() + secs;
309 
310 	NET_ASSERT_LOCKED();
311 	KASSERT(!ISSET(ln->ln_rt->rt_flags, RTF_LOCAL));
312 
313 	ln->ln_rt->rt_expire = expire;
314 	if (!timeout_pending(&nd6_timer_to) || expire < nd6_timer_next) {
315 		nd6_timer_next = expire;
316 		timeout_add_sec(&nd6_timer_to, secs);
317 	}
318 }
319 
320 void
321 nd6_timer(void *unused)
322 {
323 	struct llinfo_nd6 *ln, *nln;
324 	time_t expire = getuptime() + nd6_gctimer;
325 	int secs;
326 
327 	NET_LOCK();
328 	TAILQ_FOREACH_SAFE(ln, &nd6_list, ln_list, nln) {
329 		struct rtentry *rt = ln->ln_rt;
330 
331 		if (rt->rt_expire && rt->rt_expire <= getuptime())
332 			if (nd6_llinfo_timer(rt))
333 				continue;
334 
335 		if (rt->rt_expire && rt->rt_expire < expire)
336 			expire = rt->rt_expire;
337 	}
338 
339 	secs = expire - getuptime();
340 	if (secs < 0)
341 		secs = 0;
342 	if (!TAILQ_EMPTY(&nd6_list)) {
343 		nd6_timer_next = getuptime() + secs;
344 		timeout_add_sec(&nd6_timer_to, secs);
345 	}
346 
347 	NET_UNLOCK();
348 }
349 
350 /*
351  * ND timer state handling.
352  *
353  * Returns 1 if `rt' should no longer be used, 0 otherwise.
354  */
355 int
356 nd6_llinfo_timer(struct rtentry *rt)
357 {
358 	struct llinfo_nd6 *ln = (struct llinfo_nd6 *)rt->rt_llinfo;
359 	struct sockaddr_in6 *dst = satosin6(rt_key(rt));
360 	struct ifnet *ifp;
361 	struct nd_ifinfo *ndi = NULL;
362 
363 	NET_ASSERT_LOCKED();
364 
365 	if ((ifp = if_get(rt->rt_ifidx)) == NULL)
366 		return 1;
367 
368 	ndi = ND_IFINFO(ifp);
369 
370 	switch (ln->ln_state) {
371 	case ND6_LLINFO_INCOMPLETE:
372 		if (ln->ln_asked < nd6_mmaxtries) {
373 			ln->ln_asked++;
374 			nd6_llinfo_settimer(ln, ndi->retrans / 1000);
375 			nd6_ns_output(ifp, NULL, &dst->sin6_addr, ln, 0);
376 		} else {
377 			struct mbuf *m = ln->ln_hold;
378 			if (m) {
379 				ln->ln_hold = NULL;
380 				/*
381 				 * Fake rcvif to make the ICMP error
382 				 * more helpful in diagnosing for the
383 				 * receiver.
384 				 * XXX: should we consider
385 				 * older rcvif?
386 				 */
387 				m->m_pkthdr.ph_ifidx = rt->rt_ifidx;
388 
389 				icmp6_error(m, ICMP6_DST_UNREACH,
390 				    ICMP6_DST_UNREACH_ADDR, 0);
391 				if (ln->ln_hold == m) {
392 					/* m is back in ln_hold. Discard. */
393 					m_freem(ln->ln_hold);
394 					ln->ln_hold = NULL;
395 				}
396 			}
397 			nd6_free(rt);
398 			ln = NULL;
399 		}
400 		break;
401 	case ND6_LLINFO_REACHABLE:
402 		if (!ND6_LLINFO_PERMANENT(ln)) {
403 			ln->ln_state = ND6_LLINFO_STALE;
404 			nd6_llinfo_settimer(ln, nd6_gctimer);
405 		}
406 		break;
407 
408 	case ND6_LLINFO_STALE:
409 	case ND6_LLINFO_PURGE:
410 		/* Garbage Collection(RFC 2461 5.3) */
411 		if (!ND6_LLINFO_PERMANENT(ln)) {
412 			nd6_free(rt);
413 			ln = NULL;
414 		}
415 		break;
416 
417 	case ND6_LLINFO_DELAY:
418 		if (ndi) {
419 			/* We need NUD */
420 			ln->ln_asked = 1;
421 			ln->ln_state = ND6_LLINFO_PROBE;
422 			nd6_llinfo_settimer(ln, ndi->retrans / 1000);
423 			nd6_ns_output(ifp, &dst->sin6_addr,
424 			    &dst->sin6_addr, ln, 0);
425 		}
426 		break;
427 	case ND6_LLINFO_PROBE:
428 		if (ln->ln_asked < nd6_umaxtries) {
429 			ln->ln_asked++;
430 			nd6_llinfo_settimer(ln, ndi->retrans / 1000);
431 			nd6_ns_output(ifp, &dst->sin6_addr,
432 			    &dst->sin6_addr, ln, 0);
433 		} else {
434 			nd6_free(rt);
435 			ln = NULL;
436 		}
437 		break;
438 	}
439 
440 	if_put(ifp);
441 
442 	return (ln == NULL);
443 }
444 
445 void
446 nd6_expire_timer_update(struct in6_ifaddr *ia6)
447 {
448 	time_t expire_time = INT64_MAX;
449 	int secs;
450 
451 	KERNEL_ASSERT_LOCKED();
452 
453 	if (ia6->ia6_lifetime.ia6t_vltime != ND6_INFINITE_LIFETIME)
454 		expire_time = ia6->ia6_lifetime.ia6t_expire;
455 
456 	if (!(ia6->ia6_flags & IN6_IFF_DEPRECATED) &&
457 	    ia6->ia6_lifetime.ia6t_pltime != ND6_INFINITE_LIFETIME &&
458 	    expire_time > ia6->ia6_lifetime.ia6t_preferred)
459 		expire_time = ia6->ia6_lifetime.ia6t_preferred;
460 
461 	if (expire_time == INT64_MAX)
462 		return;
463 
464 	/*
465 	 * IFA6_IS_INVALID() and IFA6_IS_DEPRECATED() check for uptime
466 	 * greater than ia6t_expire or ia6t_preferred, not greater or equal.
467 	 * Schedule timeout one second later so that either IFA6_IS_INVALID()
468 	 * or IFA6_IS_DEPRECATED() is true.
469 	 */
470 	expire_time++;
471 
472 	if (!timeout_pending(&nd6_expire_timeout) ||
473 	    nd6_expire_next > expire_time) {
474 		secs = expire_time - getuptime();
475 		if (secs < 0)
476 			secs = 0;
477 
478 		timeout_add_sec(&nd6_expire_timeout, secs);
479 		nd6_expire_next = expire_time;
480 	}
481 }
482 
483 /*
484  * Expire interface addresses.
485  */
486 void
487 nd6_expire(void *unused)
488 {
489 	struct ifnet *ifp;
490 
491 	KERNEL_LOCK();
492 	NET_LOCK();
493 
494 	TAILQ_FOREACH(ifp, &ifnet, if_list) {
495 		struct ifaddr *ifa, *nifa;
496 		struct in6_ifaddr *ia6;
497 
498 		TAILQ_FOREACH_SAFE(ifa, &ifp->if_addrlist, ifa_list, nifa) {
499 			if (ifa->ifa_addr->sa_family != AF_INET6)
500 				continue;
501 			ia6 = ifatoia6(ifa);
502 			/* check address lifetime */
503 			if (IFA6_IS_INVALID(ia6)) {
504 				in6_purgeaddr(&ia6->ia_ifa);
505 			} else {
506 				if (IFA6_IS_DEPRECATED(ia6))
507 					ia6->ia6_flags |= IN6_IFF_DEPRECATED;
508 				nd6_expire_timer_update(ia6);
509 			}
510 		}
511 	}
512 
513 	NET_UNLOCK();
514 	KERNEL_UNLOCK();
515 }
516 
517 void
518 nd6_expire_timer(void *unused)
519 {
520 	task_add(net_tq(0), &nd6_expire_task);
521 }
522 
523 /*
524  * Nuke neighbor cache/prefix/default router management table, right before
525  * ifp goes away.
526  */
527 void
528 nd6_purge(struct ifnet *ifp)
529 {
530 	struct llinfo_nd6 *ln, *nln;
531 
532 	NET_ASSERT_LOCKED();
533 
534 	/*
535 	 * Nuke neighbor cache entries for the ifp.
536 	 */
537 	TAILQ_FOREACH_SAFE(ln, &nd6_list, ln_list, nln) {
538 		struct rtentry *rt;
539 		struct sockaddr_dl *sdl;
540 
541 		rt = ln->ln_rt;
542 		if (rt != NULL && rt->rt_gateway != NULL &&
543 		    rt->rt_gateway->sa_family == AF_LINK) {
544 			sdl = satosdl(rt->rt_gateway);
545 			if (sdl->sdl_index == ifp->if_index)
546 				nd6_free(rt);
547 		}
548 	}
549 }
550 
551 struct rtentry *
552 nd6_lookup(struct in6_addr *addr6, int create, struct ifnet *ifp,
553     u_int rtableid)
554 {
555 	struct rtentry *rt;
556 	struct sockaddr_in6 sin6;
557 	int flags;
558 
559 	bzero(&sin6, sizeof(sin6));
560 	sin6.sin6_len = sizeof(struct sockaddr_in6);
561 	sin6.sin6_family = AF_INET6;
562 	sin6.sin6_addr = *addr6;
563 	flags = (create) ? RT_RESOLVE : 0;
564 
565 	rt = rtalloc(sin6tosa(&sin6), flags, rtableid);
566 	if (rt != NULL && (rt->rt_flags & RTF_LLINFO) == 0) {
567 		/*
568 		 * This is the case for the default route.
569 		 * If we want to create a neighbor cache for the address, we
570 		 * should free the route for the destination and allocate an
571 		 * interface route.
572 		 */
573 		if (create) {
574 			rtfree(rt);
575 			rt = NULL;
576 		}
577 	}
578 	if (rt == NULL) {
579 		if (create && ifp) {
580 			struct rt_addrinfo info;
581 			struct ifaddr *ifa;
582 			int error;
583 
584 			/*
585 			 * If no route is available and create is set,
586 			 * we allocate a host route for the destination
587 			 * and treat it like an interface route.
588 			 * This hack is necessary for a neighbor which can't
589 			 * be covered by our own prefix.
590 			 */
591 			ifa = ifaof_ifpforaddr(sin6tosa(&sin6), ifp);
592 			if (ifa == NULL)
593 				return (NULL);
594 
595 			/*
596 			 * Create a new route.  RTF_LLINFO is necessary
597 			 * to create a Neighbor Cache entry for the
598 			 * destination in nd6_rtrequest which will be
599 			 * called in rtrequest.
600 			 */
601 			bzero(&info, sizeof(info));
602 			info.rti_ifa = ifa;
603 			info.rti_flags = RTF_HOST | RTF_LLINFO;
604 			info.rti_info[RTAX_DST] = sin6tosa(&sin6);
605 			info.rti_info[RTAX_GATEWAY] = sdltosa(ifp->if_sadl);
606 			error = rtrequest(RTM_ADD, &info, RTP_CONNECTED, &rt,
607 			    rtableid);
608 			if (error)
609 				return (NULL);
610 			if (rt->rt_llinfo != NULL) {
611 				struct llinfo_nd6 *ln =
612 				    (struct llinfo_nd6 *)rt->rt_llinfo;
613 				ln->ln_state = ND6_LLINFO_NOSTATE;
614 			}
615 		} else
616 			return (NULL);
617 	}
618 	/*
619 	 * Validation for the entry.
620 	 * Note that the check for rt_llinfo is necessary because a cloned
621 	 * route from a parent route that has the L flag (e.g. the default
622 	 * route to a p2p interface) may have the flag, too, while the
623 	 * destination is not actually a neighbor.
624 	 */
625 	if ((rt->rt_flags & RTF_GATEWAY) || (rt->rt_flags & RTF_LLINFO) == 0 ||
626 	    rt->rt_gateway->sa_family != AF_LINK || rt->rt_llinfo == NULL ||
627 	    (ifp != NULL && rt->rt_ifidx != ifp->if_index)) {
628 		if (create) {
629 			char addr[INET6_ADDRSTRLEN];
630 			nd6log((LOG_DEBUG, "%s: failed to lookup %s (if=%s)\n",
631 			    __func__,
632 			    inet_ntop(AF_INET6, addr6, addr, sizeof(addr)),
633 			    ifp ? ifp->if_xname : "unspec"));
634 		}
635 		rtfree(rt);
636 		return (NULL);
637 	}
638 	return (rt);
639 }
640 
641 /*
642  * Detect if a given IPv6 address identifies a neighbor on a given link.
643  * XXX: should take care of the destination of a p2p link?
644  */
645 int
646 nd6_is_addr_neighbor(struct sockaddr_in6 *addr, struct ifnet *ifp)
647 {
648 	struct in6_ifaddr *ia6;
649 	struct ifaddr *ifa;
650 	struct rtentry *rt;
651 
652 	/*
653 	 * A link-local address is always a neighbor.
654 	 * XXX: we should use the sin6_scope_id field rather than the embedded
655 	 * interface index.
656 	 * XXX: a link does not necessarily specify a single interface.
657 	 */
658 	if (IN6_IS_ADDR_LINKLOCAL(&addr->sin6_addr) &&
659 	    ntohs(*(u_int16_t *)&addr->sin6_addr.s6_addr[2]) == ifp->if_index)
660 		return (1);
661 
662 	TAILQ_FOREACH(ifa, &ifp->if_addrlist, ifa_list) {
663 		if (ifa->ifa_addr->sa_family != AF_INET6)
664 			continue;
665 
666 		ia6 = ifatoia6(ifa);
667 
668 		/* Prefix check down below. */
669 		if (ia6->ia6_flags & IN6_IFF_AUTOCONF)
670 			continue;
671 
672 		if (IN6_ARE_MASKED_ADDR_EQUAL(&addr->sin6_addr,
673 		    &ia6->ia_addr.sin6_addr,
674 		    &ia6->ia_prefixmask.sin6_addr))
675 			return (1);
676 	}
677 
678 	/*
679 	 * Even if the address matches none of our addresses, it might be
680 	 * in the neighbor cache.
681 	 */
682 	rt = nd6_lookup(&addr->sin6_addr, 0, ifp, ifp->if_rdomain);
683 	if (rt != NULL) {
684 		rtfree(rt);
685 		return (1);
686 	}
687 
688 	return (0);
689 }
690 
691 void
692 nd6_invalidate(struct rtentry *rt)
693 {
694 	struct llinfo_nd6 *ln = (struct llinfo_nd6 *)rt->rt_llinfo;
695 	struct sockaddr_dl *sdl = satosdl(rt->rt_gateway);
696 
697 	m_freem(ln->ln_hold);
698 	sdl->sdl_alen = 0;
699 	ln->ln_hold = NULL;
700 	ln->ln_state = ND6_LLINFO_INCOMPLETE;
701 	ln->ln_asked = 0;
702 }
703 
704 /*
705  * Free an nd6 llinfo entry.
706  * Since the function would cause significant changes in the kernel, DO NOT
707  * make it global, unless you have a strong reason for the change, and are sure
708  * that the change is safe.
709  */
710 void
711 nd6_free(struct rtentry *rt)
712 {
713 	struct llinfo_nd6 *ln = (struct llinfo_nd6 *)rt->rt_llinfo;
714 	struct in6_addr in6 = satosin6(rt_key(rt))->sin6_addr;
715 	struct ifnet *ifp;
716 
717 	NET_ASSERT_LOCKED();
718 
719 	ifp = if_get(rt->rt_ifidx);
720 
721 	if (!ip6_forwarding) {
722 		if (ln->ln_router) {
723 			/*
724 			 * rt6_flush must be called whether or not the neighbor
725 			 * is in the Default Router List.
726 			 * See a corresponding comment in nd6_na_input().
727 			 */
728 			rt6_flush(&in6, ifp);
729 		}
730 	}
731 
732 	KASSERT(!ISSET(rt->rt_flags, RTF_LOCAL));
733 	nd6_invalidate(rt);
734 
735 	/*
736 	 * Detach the route from the routing tree and the list of neighbor
737 	 * caches, and disable the route entry not to be used in already
738 	 * cached routes.
739 	 */
740 	if (!ISSET(rt->rt_flags, RTF_STATIC|RTF_CACHED))
741 		rtdeletemsg(rt, ifp, ifp->if_rdomain);
742 
743 	if_put(ifp);
744 }
745 
746 /*
747  * Upper-layer reachability hint for Neighbor Unreachability Detection.
748  *
749  * XXX cost-effective methods?
750  */
751 void
752 nd6_nud_hint(struct rtentry *rt)
753 {
754 	struct llinfo_nd6 *ln;
755 	struct ifnet *ifp;
756 
757 	ifp = if_get(rt->rt_ifidx);
758 	if (ifp == NULL)
759 		return;
760 
761 	if ((rt->rt_flags & RTF_GATEWAY) != 0 ||
762 	    (rt->rt_flags & RTF_LLINFO) == 0 ||
763 	    rt->rt_llinfo == NULL || rt->rt_gateway == NULL ||
764 	    rt->rt_gateway->sa_family != AF_LINK) {
765 		/* This is not a host route. */
766 		goto out;
767 	}
768 
769 	ln = (struct llinfo_nd6 *)rt->rt_llinfo;
770 	if (ln->ln_state < ND6_LLINFO_REACHABLE)
771 		goto out;
772 
773 	/*
774 	 * if we get upper-layer reachability confirmation many times,
775 	 * it is possible we have false information.
776 	 */
777 	ln->ln_byhint++;
778 	if (ln->ln_byhint > nd6_maxnudhint)
779 		goto out;
780 
781 	ln->ln_state = ND6_LLINFO_REACHABLE;
782 	if (!ND6_LLINFO_PERMANENT(ln))
783 		nd6_llinfo_settimer(ln, ND_IFINFO(ifp)->reachable);
784 out:
785 	if_put(ifp);
786 }
787 
788 void
789 nd6_rtrequest(struct ifnet *ifp, int req, struct rtentry *rt)
790 {
791 	struct sockaddr *gate = rt->rt_gateway;
792 	struct llinfo_nd6 *ln = (struct llinfo_nd6 *)rt->rt_llinfo;
793 	struct ifaddr *ifa;
794 	struct in6_ifaddr *ifa6;
795 
796 	if (ISSET(rt->rt_flags, RTF_GATEWAY|RTF_MULTICAST|RTF_MPLS))
797 		return;
798 
799 	if (nd6_need_cache(ifp) == 0 && (rt->rt_flags & RTF_HOST) == 0) {
800 		/*
801 		 * This is probably an interface direct route for a link
802 		 * which does not need neighbor caches (e.g. fe80::%lo0/64).
803 		 * We do not need special treatment below for such a route.
804 		 * Moreover, the RTF_LLINFO flag which would be set below
805 		 * would annoy the ndp(8) command.
806 		 */
807 		return;
808 	}
809 
810 	if (req == RTM_RESOLVE && nd6_need_cache(ifp) == 0) {
811 		/*
812 		 * For routing daemons like ospf6d we allow neighbor discovery
813 		 * based on the cloning route only.  This allows us to sent
814 		 * packets directly into a network without having an address
815 		 * with matching prefix on the interface.  If the cloning
816 		 * route is used for an stf interface, we would mistakenly
817 		 * make a neighbor cache for the host route, and would see
818 		 * strange neighbor solicitation for the corresponding
819 		 * destination.  In order to avoid confusion, we check if the
820 		 * interface is suitable for neighbor discovery, and stop the
821 		 * process if not.  Additionally, we remove the LLINFO flag
822 		 * so that ndp(8) will not try to get the neighbor information
823 		 * of the destination.
824 		 */
825 		rt->rt_flags &= ~RTF_LLINFO;
826 		return;
827 	}
828 
829 	switch (req) {
830 	case RTM_ADD:
831 		if ((rt->rt_flags & RTF_CLONING) ||
832 		    ((rt->rt_flags & (RTF_LLINFO | RTF_LOCAL)) && ln == NULL)) {
833 			if (ln != NULL)
834 				nd6_llinfo_settimer(ln, 0);
835 			if ((rt->rt_flags & RTF_CLONING) != 0)
836 				break;
837 		}
838 		/*
839 		 * In IPv4 code, we try to announce new RTF_ANNOUNCE entry here.
840 		 * We don't do that here since llinfo is not ready yet.
841 		 *
842 		 * There are also couple of other things to be discussed:
843 		 * - unsolicited NA code needs improvement beforehand
844 		 * - RFC2461 says we MAY send multicast unsolicited NA
845 		 *   (7.2.6 paragraph 4), however, it also says that we
846 		 *   SHOULD provide a mechanism to prevent multicast NA storm.
847 		 *   we don't have anything like it right now.
848 		 *   note that the mechanism needs a mutual agreement
849 		 *   between proxies, which means that we need to implement
850 		 *   a new protocol, or a new kludge.
851 		 * - from RFC2461 6.2.4, host MUST NOT send an unsolicited NA.
852 		 *   we need to check ip6forwarding before sending it.
853 		 *   (or should we allow proxy ND configuration only for
854 		 *   routers?  there's no mention about proxy ND from hosts)
855 		 */
856 #if 0
857 		/* XXX it does not work */
858 		if (rt->rt_flags & RTF_ANNOUNCE)
859 			nd6_na_output(ifp,
860 			      &satosin6(rt_key(rt))->sin6_addr,
861 			      &satosin6(rt_key(rt))->sin6_addr,
862 			      ip6_forwarding ? ND_NA_FLAG_ROUTER : 0,
863 			      1, NULL);
864 #endif
865 		/* FALLTHROUGH */
866 	case RTM_RESOLVE:
867 		if (gate->sa_family != AF_LINK ||
868 		    gate->sa_len < sizeof(struct sockaddr_dl)) {
869 			log(LOG_DEBUG, "%s: bad gateway value: %s\n",
870 			    __func__, ifp->if_xname);
871 			break;
872 		}
873 		satosdl(gate)->sdl_type = ifp->if_type;
874 		satosdl(gate)->sdl_index = ifp->if_index;
875 		if (ln != NULL)
876 			break;	/* This happens on a route change */
877 		/*
878 		 * Case 2: This route may come from cloning, or a manual route
879 		 * add with a LL address.
880 		 */
881 		ln = pool_get(&nd6_pool, PR_NOWAIT | PR_ZERO);
882 		rt->rt_llinfo = (caddr_t)ln;
883 		if (ln == NULL) {
884 			log(LOG_DEBUG, "%s: pool get failed\n", __func__);
885 			break;
886 		}
887 		nd6_inuse++;
888 		ln->ln_rt = rt;
889 		/* this is required for "ndp" command. - shin */
890 		if (req == RTM_ADD) {
891 		        /*
892 			 * gate should have some valid AF_LINK entry,
893 			 * and ln expire should have some lifetime
894 			 * which is specified by ndp command.
895 			 */
896 			ln->ln_state = ND6_LLINFO_REACHABLE;
897 			ln->ln_byhint = 0;
898 		} else {
899 		        /*
900 			 * When req == RTM_RESOLVE, rt is created and
901 			 * initialized in rtrequest(), so rt_expire is 0.
902 			 */
903 			ln->ln_state = ND6_LLINFO_NOSTATE;
904 			nd6_llinfo_settimer(ln, 0);
905 		}
906 		rt->rt_flags |= RTF_LLINFO;
907 		TAILQ_INSERT_HEAD(&nd6_list, ln, ln_list);
908 
909 		/*
910 		 * If we have too many cache entries, initiate immediate
911 		 * purging for some "less recently used" entries.  Note that
912 		 * we cannot directly call nd6_free() here because it would
913 		 * cause re-entering rtable related routines triggering an LOR
914 		 * problem for FreeBSD.
915 		 */
916 		if (ip6_neighborgcthresh >= 0 &&
917 		    nd6_inuse >= ip6_neighborgcthresh) {
918 			int i;
919 
920 			for (i = 0; i < 10; i++) {
921 				struct llinfo_nd6 *ln_end;
922 
923 				ln_end = TAILQ_LAST(&nd6_list, llinfo_nd6_head);
924 				if (ln_end == ln)
925 					break;
926 
927 				/* Move this entry to the head */
928 				TAILQ_REMOVE(&nd6_list, ln_end, ln_list);
929 				TAILQ_INSERT_HEAD(&nd6_list, ln_end, ln_list);
930 
931 				if (ND6_LLINFO_PERMANENT(ln_end))
932 					continue;
933 
934 				if (ln_end->ln_state > ND6_LLINFO_INCOMPLETE)
935 					ln_end->ln_state = ND6_LLINFO_STALE;
936 				else
937 					ln_end->ln_state = ND6_LLINFO_PURGE;
938 				nd6_llinfo_settimer(ln_end, 0);
939 			}
940 		}
941 
942 		/*
943 		 * check if rt_key(rt) is one of my address assigned
944 		 * to the interface.
945 		 */
946 		ifa6 = in6ifa_ifpwithaddr(ifp,
947 		    &satosin6(rt_key(rt))->sin6_addr);
948 		ifa = ifa6 ? &ifa6->ia_ifa : NULL;
949 		if (ifa) {
950 			ln->ln_state = ND6_LLINFO_REACHABLE;
951 			ln->ln_byhint = 0;
952 			rt->rt_expire = 0;
953 			KASSERT(ifa == rt->rt_ifa);
954 		} else if (rt->rt_flags & RTF_ANNOUNCE) {
955 			ln->ln_state = ND6_LLINFO_REACHABLE;
956 			ln->ln_byhint = 0;
957 			rt->rt_expire = 0;
958 
959 			/* join solicited node multicast for proxy ND */
960 			if (ifp->if_flags & IFF_MULTICAST) {
961 				struct in6_addr llsol;
962 				int error;
963 
964 				llsol = satosin6(rt_key(rt))->sin6_addr;
965 				llsol.s6_addr16[0] = htons(0xff02);
966 				llsol.s6_addr16[1] = htons(ifp->if_index);
967 				llsol.s6_addr32[1] = 0;
968 				llsol.s6_addr32[2] = htonl(1);
969 				llsol.s6_addr8[12] = 0xff;
970 
971 				if (in6_addmulti(&llsol, ifp, &error)) {
972 					char addr[INET6_ADDRSTRLEN];
973 					nd6log((LOG_ERR, "%s: failed to join "
974 					    "%s (errno=%d)\n", ifp->if_xname,
975 					    inet_ntop(AF_INET6, &llsol,
976 						addr, sizeof(addr)),
977 					    error));
978 				}
979 			}
980 		}
981 		break;
982 
983 	case RTM_DELETE:
984 		if (ln == NULL)
985 			break;
986 		/* leave from solicited node multicast for proxy ND */
987 		if ((rt->rt_flags & RTF_ANNOUNCE) != 0 &&
988 		    (ifp->if_flags & IFF_MULTICAST) != 0) {
989 			struct in6_addr llsol;
990 			struct in6_multi *in6m;
991 
992 			llsol = satosin6(rt_key(rt))->sin6_addr;
993 			llsol.s6_addr16[0] = htons(0xff02);
994 			llsol.s6_addr16[1] = htons(ifp->if_index);
995 			llsol.s6_addr32[1] = 0;
996 			llsol.s6_addr32[2] = htonl(1);
997 			llsol.s6_addr8[12] = 0xff;
998 
999 			IN6_LOOKUP_MULTI(llsol, ifp, in6m);
1000 			if (in6m)
1001 				in6_delmulti(in6m);
1002 		}
1003 		nd6_inuse--;
1004 		TAILQ_REMOVE(&nd6_list, ln, ln_list);
1005 		rt->rt_expire = 0;
1006 		rt->rt_llinfo = NULL;
1007 		rt->rt_flags &= ~RTF_LLINFO;
1008 		m_freem(ln->ln_hold);
1009 		pool_put(&nd6_pool, ln);
1010 		break;
1011 
1012 	case RTM_INVALIDATE:
1013 		if (ln == NULL)
1014 			break;
1015 		if (!ISSET(rt->rt_flags, RTF_LOCAL))
1016 			nd6_invalidate(rt);
1017 		break;
1018 	}
1019 }
1020 
1021 int
1022 nd6_ioctl(u_long cmd, caddr_t data, struct ifnet *ifp)
1023 {
1024 	struct in6_ndireq *ndi = (struct in6_ndireq *)data;
1025 	struct in6_nbrinfo *nbi = (struct in6_nbrinfo *)data;
1026 	struct rtentry *rt;
1027 
1028 	switch (cmd) {
1029 	case SIOCGIFINFO_IN6:
1030 		NET_RLOCK_IN_IOCTL();
1031 		ndi->ndi = *ND_IFINFO(ifp);
1032 		NET_RUNLOCK_IN_IOCTL();
1033 		return (0);
1034 	case SIOCGNBRINFO_IN6:
1035 	{
1036 		struct llinfo_nd6 *ln;
1037 		struct in6_addr nb_addr = nbi->addr; /* make local for safety */
1038 		time_t expire;
1039 
1040 		NET_RLOCK_IN_IOCTL();
1041 		/*
1042 		 * XXX: KAME specific hack for scoped addresses
1043 		 *      XXXX: for other scopes than link-local?
1044 		 */
1045 		if (IN6_IS_ADDR_LINKLOCAL(&nbi->addr) ||
1046 		    IN6_IS_ADDR_MC_LINKLOCAL(&nbi->addr)) {
1047 			u_int16_t *idp = (u_int16_t *)&nb_addr.s6_addr[2];
1048 
1049 			if (*idp == 0)
1050 				*idp = htons(ifp->if_index);
1051 		}
1052 
1053 		rt = nd6_lookup(&nb_addr, 0, ifp, ifp->if_rdomain);
1054 		if (rt == NULL ||
1055 		    (ln = (struct llinfo_nd6 *)rt->rt_llinfo) == NULL) {
1056 			rtfree(rt);
1057 			NET_RUNLOCK_IN_IOCTL();
1058 			return (EINVAL);
1059 		}
1060 		expire = ln->ln_rt->rt_expire;
1061 		if (expire != 0) {
1062 			expire -= getuptime();
1063 			expire += gettime();
1064 		}
1065 
1066 		nbi->state = ln->ln_state;
1067 		nbi->asked = ln->ln_asked;
1068 		nbi->isrouter = ln->ln_router;
1069 		nbi->expire = expire;
1070 
1071 		rtfree(rt);
1072 		NET_RUNLOCK_IN_IOCTL();
1073 		return (0);
1074 	}
1075 	}
1076 	return (0);
1077 }
1078 
1079 /*
1080  * Create neighbor cache entry and cache link-layer address,
1081  * on reception of inbound ND6 packets.  (RS/RA/NS/redirect)
1082  *
1083  * type - ICMP6 type
1084  * code - type dependent information
1085  */
1086 void
1087 nd6_cache_lladdr(struct ifnet *ifp, struct in6_addr *from, char *lladdr,
1088     int lladdrlen, int type, int code)
1089 {
1090 	struct rtentry *rt = NULL;
1091 	struct llinfo_nd6 *ln = NULL;
1092 	int is_newentry;
1093 	struct sockaddr_dl *sdl = NULL;
1094 	int do_update;
1095 	int olladdr;
1096 	int llchange;
1097 	int newstate = 0;
1098 
1099 	if (!ifp)
1100 		panic("%s: ifp == NULL", __func__);
1101 	if (!from)
1102 		panic("%s: from == NULL", __func__);
1103 
1104 	/* nothing must be updated for unspecified address */
1105 	if (IN6_IS_ADDR_UNSPECIFIED(from))
1106 		return;
1107 
1108 	/*
1109 	 * Validation about ifp->if_addrlen and lladdrlen must be done in
1110 	 * the caller.
1111 	 *
1112 	 * XXX If the link does not have link-layer address, what should
1113 	 * we do? (ifp->if_addrlen == 0)
1114 	 * Spec says nothing in sections for RA, RS and NA.  There's small
1115 	 * description on it in NS section (RFC 2461 7.2.3).
1116 	 */
1117 
1118 	rt = nd6_lookup(from, 0, ifp, ifp->if_rdomain);
1119 	if (rt == NULL) {
1120 		rt = nd6_lookup(from, 1, ifp, ifp->if_rdomain);
1121 		is_newentry = 1;
1122 	} else {
1123 		/* do not overwrite local or static entry */
1124 		if (ISSET(rt->rt_flags, RTF_STATIC|RTF_LOCAL)) {
1125 			rtfree(rt);
1126 			return;
1127 		}
1128 		is_newentry = 0;
1129 	}
1130 
1131 	if (!rt)
1132 		return;
1133 	if ((rt->rt_flags & (RTF_GATEWAY | RTF_LLINFO)) != RTF_LLINFO) {
1134 fail:
1135 		nd6_free(rt);
1136 		rtfree(rt);
1137 		return;
1138 	}
1139 	ln = (struct llinfo_nd6 *)rt->rt_llinfo;
1140 	if (ln == NULL)
1141 		goto fail;
1142 	if (rt->rt_gateway == NULL)
1143 		goto fail;
1144 	if (rt->rt_gateway->sa_family != AF_LINK)
1145 		goto fail;
1146 	sdl = satosdl(rt->rt_gateway);
1147 
1148 	olladdr = (sdl->sdl_alen) ? 1 : 0;
1149 	if (olladdr && lladdr) {
1150 		if (bcmp(lladdr, LLADDR(sdl), ifp->if_addrlen))
1151 			llchange = 1;
1152 		else
1153 			llchange = 0;
1154 	} else
1155 		llchange = 0;
1156 
1157 	/*
1158 	 * newentry olladdr  lladdr  llchange	(*=record)
1159 	 *	0	n	n	--	(1)
1160 	 *	0	y	n	--	(2)
1161 	 *	0	n	y	--	(3) * STALE
1162 	 *	0	y	y	n	(4) *
1163 	 *	0	y	y	y	(5) * STALE
1164 	 *	1	--	n	--	(6)   NOSTATE(= PASSIVE)
1165 	 *	1	--	y	--	(7) * STALE
1166 	 */
1167 
1168 	if (llchange) {
1169 		char addr[INET6_ADDRSTRLEN];
1170 		log(LOG_INFO, "ndp info overwritten for %s by %s on %s\n",
1171 		    inet_ntop(AF_INET6, from, addr, sizeof(addr)),
1172 		    ether_sprintf(lladdr), ifp->if_xname);
1173 	}
1174 	if (lladdr) {		/* (3-5) and (7) */
1175 		/*
1176 		 * Record source link-layer address
1177 		 * XXX is it dependent to ifp->if_type?
1178 		 */
1179 		sdl->sdl_alen = ifp->if_addrlen;
1180 		bcopy(lladdr, LLADDR(sdl), ifp->if_addrlen);
1181 	}
1182 
1183 	if (!is_newentry) {
1184 		if ((!olladdr && lladdr) ||		/* (3) */
1185 		    (olladdr && lladdr && llchange)) {	/* (5) */
1186 			do_update = 1;
1187 			newstate = ND6_LLINFO_STALE;
1188 		} else					/* (1-2,4) */
1189 			do_update = 0;
1190 	} else {
1191 		do_update = 1;
1192 		if (!lladdr)				/* (6) */
1193 			newstate = ND6_LLINFO_NOSTATE;
1194 		else					/* (7) */
1195 			newstate = ND6_LLINFO_STALE;
1196 	}
1197 
1198 	if (do_update) {
1199 		/*
1200 		 * Update the state of the neighbor cache.
1201 		 */
1202 		ln->ln_state = newstate;
1203 
1204 		if (ln->ln_state == ND6_LLINFO_STALE) {
1205 			/*
1206 			 * Since nd6_resolve() in ifp->if_output() will cause
1207 			 * state transition to DELAY and reset the timer,
1208 			 * we must set the timer now, although it is actually
1209 			 * meaningless.
1210 			 */
1211 			nd6_llinfo_settimer(ln, nd6_gctimer);
1212 
1213 			if (ln->ln_hold) {
1214 				struct mbuf *n = ln->ln_hold;
1215 				ln->ln_hold = NULL;
1216 				/*
1217 				 * we assume ifp is not a p2p here, so just
1218 				 * set the 2nd argument as the 1st one.
1219 				 */
1220 				ifp->if_output(ifp, n, rt_key(rt), rt);
1221 				if (ln->ln_hold == n) {
1222 					/* n is back in ln_hold. Discard. */
1223 					m_freem(ln->ln_hold);
1224 					ln->ln_hold = NULL;
1225 				}
1226 			}
1227 		} else if (ln->ln_state == ND6_LLINFO_INCOMPLETE) {
1228 			/* probe right away */
1229 			nd6_llinfo_settimer(ln, 0);
1230 		}
1231 	}
1232 
1233 	/*
1234 	 * ICMP6 type dependent behavior.
1235 	 *
1236 	 * NS: clear IsRouter if new entry
1237 	 * RS: clear IsRouter
1238 	 * RA: set IsRouter if there's lladdr
1239 	 * redir: clear IsRouter if new entry
1240 	 *
1241 	 * RA case, (1):
1242 	 * The spec says that we must set IsRouter in the following cases:
1243 	 * - If lladdr exist, set IsRouter.  This means (1-5).
1244 	 * - If it is old entry (!newentry), set IsRouter.  This means (7).
1245 	 * So, based on the spec, in (1-5) and (7) cases we must set IsRouter.
1246 	 * A question arises for (1) case.  (1) case has no lladdr in the
1247 	 * neighbor cache, this is similar to (6).
1248 	 * This case is rare but we figured that we MUST NOT set IsRouter.
1249 	 *
1250 	 * newentry olladdr  lladdr  llchange	    NS  RS  RA	redir
1251 	 *							D R
1252 	 *	0	n	n	--	(1)	c   ?     s
1253 	 *	0	y	n	--	(2)	c   s     s
1254 	 *	0	n	y	--	(3)	c   s     s
1255 	 *	0	y	y	n	(4)	c   s     s
1256 	 *	0	y	y	y	(5)	c   s     s
1257 	 *	1	--	n	--	(6) c	c	c s
1258 	 *	1	--	y	--	(7) c	c   s	c s
1259 	 *
1260 	 *					(c=clear s=set)
1261 	 */
1262 	switch (type & 0xff) {
1263 	case ND_NEIGHBOR_SOLICIT:
1264 		/*
1265 		 * New entry must have is_router flag cleared.
1266 		 */
1267 		if (is_newentry)	/* (6-7) */
1268 			ln->ln_router = 0;
1269 		break;
1270 	case ND_REDIRECT:
1271 		/*
1272 		 * If the icmp is a redirect to a better router, always set the
1273 		 * is_router flag.  Otherwise, if the entry is newly created,
1274 		 * clear the flag.  [RFC 2461, sec 8.3]
1275 		 */
1276 		if (code == ND_REDIRECT_ROUTER)
1277 			ln->ln_router = 1;
1278 		else if (is_newentry) /* (6-7) */
1279 			ln->ln_router = 0;
1280 		break;
1281 	case ND_ROUTER_SOLICIT:
1282 		/*
1283 		 * is_router flag must always be cleared.
1284 		 */
1285 		ln->ln_router = 0;
1286 		break;
1287 	case ND_ROUTER_ADVERT:
1288 		/*
1289 		 * Mark an entry with lladdr as a router.
1290 		 */
1291 		if ((!is_newentry && (olladdr || lladdr)) ||	/* (2-5) */
1292 		    (is_newentry && lladdr)) {			/* (7) */
1293 			ln->ln_router = 1;
1294 		}
1295 		break;
1296 	}
1297 
1298 	rtfree(rt);
1299 }
1300 
1301 void
1302 nd6_slowtimo(void *ignored_arg)
1303 {
1304 	struct nd_ifinfo *nd6if;
1305 	struct ifnet *ifp;
1306 
1307 	NET_LOCK();
1308 
1309 	timeout_add_sec(&nd6_slowtimo_ch, ND6_SLOWTIMER_INTERVAL);
1310 
1311 	TAILQ_FOREACH(ifp, &ifnet, if_list) {
1312 		nd6if = ND_IFINFO(ifp);
1313 		if (nd6if->basereachable && /* already initialized */
1314 		    (nd6if->recalctm -= ND6_SLOWTIMER_INTERVAL) <= 0) {
1315 			/*
1316 			 * Since reachable time rarely changes by router
1317 			 * advertisements, we SHOULD insure that a new random
1318 			 * value gets recomputed at least once every few hours.
1319 			 * (RFC 2461, 6.3.4)
1320 			 */
1321 			nd6if->recalctm = nd6_recalc_reachtm_interval;
1322 			nd6if->reachable = ND_COMPUTE_RTIME(nd6if->basereachable);
1323 		}
1324 	}
1325 	NET_UNLOCK();
1326 }
1327 
1328 int
1329 nd6_resolve(struct ifnet *ifp, struct rtentry *rt0, struct mbuf *m,
1330     struct sockaddr *dst, u_char *desten)
1331 {
1332 	struct sockaddr_dl *sdl;
1333 	struct rtentry *rt;
1334 	struct llinfo_nd6 *ln = NULL;
1335 
1336 	if (m->m_flags & M_MCAST) {
1337 		ETHER_MAP_IPV6_MULTICAST(&satosin6(dst)->sin6_addr, desten);
1338 		return (0);
1339 	}
1340 
1341 	rt = rt_getll(rt0);
1342 
1343 	if (ISSET(rt->rt_flags, RTF_REJECT) &&
1344 	    (rt->rt_expire == 0 || getuptime() < rt->rt_expire)) {
1345 		m_freem(m);
1346 		return (rt == rt0 ? EHOSTDOWN : EHOSTUNREACH);
1347 	}
1348 
1349 	/*
1350 	 * Address resolution or Neighbor Unreachability Detection
1351 	 * for the next hop.
1352 	 * At this point, the destination of the packet must be a unicast
1353 	 * or an anycast address(i.e. not a multicast).
1354 	 */
1355 	if (!ISSET(rt->rt_flags, RTF_LLINFO)) {
1356 		char addr[INET6_ADDRSTRLEN];
1357 		log(LOG_DEBUG, "%s: %s: route contains no ND information\n",
1358 		    __func__, inet_ntop(AF_INET6,
1359 		    &satosin6(rt_key(rt))->sin6_addr, addr, sizeof(addr)));
1360 		m_freem(m);
1361 		return (EINVAL);
1362 	}
1363 
1364 	if (rt->rt_gateway->sa_family != AF_LINK) {
1365 		printf("%s: something odd happens\n", __func__);
1366 		m_freem(m);
1367 		return (EINVAL);
1368 	}
1369 
1370 	ln = (struct llinfo_nd6 *)rt->rt_llinfo;
1371 	KASSERT(ln != NULL);
1372 
1373 	/*
1374 	 * Move this entry to the head of the queue so that it is less likely
1375 	 * for this entry to be a target of forced garbage collection (see
1376 	 * nd6_rtrequest()).
1377 	 */
1378 	TAILQ_REMOVE(&nd6_list, ln, ln_list);
1379 	TAILQ_INSERT_HEAD(&nd6_list, ln, ln_list);
1380 
1381 	/*
1382 	 * The first time we send a packet to a neighbor whose entry is
1383 	 * STALE, we have to change the state to DELAY and a sets a timer to
1384 	 * expire in DELAY_FIRST_PROBE_TIME seconds to ensure do
1385 	 * neighbor unreachability detection on expiration.
1386 	 * (RFC 2461 7.3.3)
1387 	 */
1388 	if (ln->ln_state == ND6_LLINFO_STALE) {
1389 		ln->ln_asked = 0;
1390 		ln->ln_state = ND6_LLINFO_DELAY;
1391 		nd6_llinfo_settimer(ln, nd6_delay);
1392 	}
1393 
1394 	/*
1395 	 * If the neighbor cache entry has a state other than INCOMPLETE
1396 	 * (i.e. its link-layer address is already resolved), just
1397 	 * send the packet.
1398 	 */
1399 	if (ln->ln_state > ND6_LLINFO_INCOMPLETE) {
1400 		sdl = satosdl(rt->rt_gateway);
1401 		if (sdl->sdl_alen != ETHER_ADDR_LEN) {
1402 			char addr[INET6_ADDRSTRLEN];
1403 			log(LOG_DEBUG, "%s: %s: incorrect nd6 information\n",
1404 			    __func__,
1405 			    inet_ntop(AF_INET6, &satosin6(dst)->sin6_addr,
1406 				addr, sizeof(addr)));
1407 			m_freem(m);
1408 			return (EINVAL);
1409 		}
1410 
1411 		bcopy(LLADDR(sdl), desten, sdl->sdl_alen);
1412 		return (0);
1413 	}
1414 
1415 	/*
1416 	 * There is a neighbor cache entry, but no ethernet address
1417 	 * response yet.  Replace the held mbuf (if any) with this
1418 	 * latest one.
1419 	 */
1420 	if (ln->ln_state == ND6_LLINFO_NOSTATE)
1421 		ln->ln_state = ND6_LLINFO_INCOMPLETE;
1422 	m_freem(ln->ln_hold);
1423 	ln->ln_hold = m;
1424 
1425 	/*
1426 	 * If there has been no NS for the neighbor after entering the
1427 	 * INCOMPLETE state, send the first solicitation.
1428 	 */
1429 	if (!ND6_LLINFO_PERMANENT(ln) && ln->ln_asked == 0) {
1430 		ln->ln_asked++;
1431 		nd6_llinfo_settimer(ln, ND_IFINFO(ifp)->retrans / 1000);
1432 		nd6_ns_output(ifp, NULL, &satosin6(dst)->sin6_addr, ln, 0);
1433 	}
1434 	return (EAGAIN);
1435 }
1436 
1437 int
1438 nd6_need_cache(struct ifnet *ifp)
1439 {
1440 	/*
1441 	 * RFC2893 says:
1442 	 * - unidirectional tunnels needs no ND
1443 	 */
1444 	switch (ifp->if_type) {
1445 	case IFT_ETHER:
1446 	case IFT_IEEE80211:
1447 	case IFT_CARP:
1448 		return (1);
1449 	default:
1450 		return (0);
1451 	}
1452 }
1453