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