xref: /xnu-11215.1.10/bsd/netinet6/nd6_nbr.c (revision 8d741a5de7ff4191bf97d57b9f54c2f6d4a15585)
1 /*
2  * Copyright (c) 2000-2024 Apple Inc. All rights reserved.
3  *
4  * @APPLE_OSREFERENCE_LICENSE_HEADER_START@
5  *
6  * This file contains Original Code and/or Modifications of Original Code
7  * as defined in and that are subject to the Apple Public Source License
8  * Version 2.0 (the 'License'). You may not use this file except in
9  * compliance with the License. The rights granted to you under the License
10  * may not be used to create, or enable the creation or redistribution of,
11  * unlawful or unlicensed copies of an Apple operating system, or to
12  * circumvent, violate, or enable the circumvention or violation of, any
13  * terms of an Apple operating system software license agreement.
14  *
15  * Please obtain a copy of the License at
16  * http://www.opensource.apple.com/apsl/ and read it before using this file.
17  *
18  * The Original Code and all software distributed under the License are
19  * distributed on an 'AS IS' basis, WITHOUT WARRANTY OF ANY KIND, EITHER
20  * EXPRESS OR IMPLIED, AND APPLE HEREBY DISCLAIMS ALL SUCH WARRANTIES,
21  * INCLUDING WITHOUT LIMITATION, ANY WARRANTIES OF MERCHANTABILITY,
22  * FITNESS FOR A PARTICULAR PURPOSE, QUIET ENJOYMENT OR NON-INFRINGEMENT.
23  * Please see the License for the specific language governing rights and
24  * limitations under the License.
25  *
26  * @APPLE_OSREFERENCE_LICENSE_HEADER_END@
27  */
28 
29 /*
30  * Copyright (C) 1995, 1996, 1997, and 1998 WIDE Project.
31  * All rights reserved.
32  *
33  * Redistribution and use in source and binary forms, with or without
34  * modification, are permitted provided that the following conditions
35  * are met:
36  * 1. Redistributions of source code must retain the above copyright
37  *    notice, this list of conditions and the following disclaimer.
38  * 2. Redistributions in binary form must reproduce the above copyright
39  *    notice, this list of conditions and the following disclaimer in the
40  *    documentation and/or other materials provided with the distribution.
41  * 3. Neither the name of the project nor the names of its contributors
42  *    may be used to endorse or promote products derived from this software
43  *    without specific prior written permission.
44  *
45  * THIS SOFTWARE IS PROVIDED BY THE PROJECT AND CONTRIBUTORS ``AS IS'' AND
46  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
47  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
48  * ARE DISCLAIMED.  IN NO EVENT SHALL THE PROJECT OR CONTRIBUTORS BE LIABLE
49  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
50  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
51  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
52  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
53  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
54  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
55  * SUCH DAMAGE.
56  */
57 
58 #include <sys/param.h>
59 #include <sys/systm.h>
60 #include <sys/malloc.h>
61 #include <sys/mbuf.h>
62 #include <sys/socket.h>
63 #include <sys/sockio.h>
64 #include <sys/time.h>
65 #include <sys/kernel.h>
66 #include <sys/errno.h>
67 #include <sys/syslog.h>
68 #include <sys/sysctl.h>
69 #include <sys/mcache.h>
70 #include <sys/protosw.h>
71 #include <kern/queue.h>
72 #include <dev/random/randomdev.h>
73 
74 #include <kern/locks.h>
75 #include <kern/zalloc.h>
76 
77 #include <net/if.h>
78 #include <net/if_var.h>
79 #include <net/if_types.h>
80 #include <net/if_dl.h>
81 #include <net/if_llreach.h>
82 #include <net/route.h>
83 #include <net/dlil.h>
84 #include <net/nwk_wq.h>
85 #include <net/droptap.h>
86 
87 #include <netinet/in.h>
88 #include <netinet/in_var.h>
89 #include <netinet6/in6_var.h>
90 #include <netinet6/in6_ifattach.h>
91 #include <netinet/ip6.h>
92 #include <netinet6/ip6_var.h>
93 #include <netinet6/nd6.h>
94 #include <netinet6/scope6_var.h>
95 #include <netinet/icmp6.h>
96 
97 #if IPSEC
98 #include <netinet6/ipsec.h>
99 #include <netinet6/ipsec6.h>
100 #endif
101 
102 #include <net/sockaddr_utils.h>
103 
104 struct dadq;
105 static struct dadq *nd6_dad_find(struct ifaddr *, struct nd_opt_nonce *);
106 void nd6_dad_stoptimer(struct ifaddr *);
107 static void nd6_dad_timer(struct ifaddr *);
108 static void nd6_dad_ns_output(struct dadq *, struct ifaddr *);
109 static void nd6_dad_ns_input(struct ifaddr *, char *__sized_by(lladdrlen), int lladdrlen, struct nd_opt_nonce *);
110 static struct mbuf *nd6_dad_na_input(struct mbuf *, struct ifnet *,
111     struct in6_addr *, caddr_t  __counted_by(lladdrlen), int lladdrlen);
112 static void dad_addref(struct dadq *, int);
113 static void dad_remref(struct dadq *);
114 static struct dadq *nd6_dad_attach(struct dadq *, struct ifaddr *);
115 static void nd6_dad_detach(struct dadq *, struct ifaddr *);
116 static void nd6_dad_duplicated(struct ifaddr *);
117 
118 static int dad_maxtry = 15;     /* max # of *tries* to transmit DAD packet */
119 
120 #define DAD_LOCK_ASSERT_HELD(_dp)                                       \
121 	LCK_MTX_ASSERT(&(_dp)->dad_lock, LCK_MTX_ASSERT_OWNED)
122 
123 #define DAD_LOCK_ASSERT_NOTHELD(_dp)                                    \
124 	LCK_MTX_ASSERT(&(_dp)->dad_lock, LCK_MTX_ASSERT_NOTOWNED)
125 
126 #define DAD_LOCK(_dp)                                                   \
127 	lck_mtx_lock(&(_dp)->dad_lock)
128 
129 #define DAD_LOCK_SPIN(_dp)                                              \
130 	lck_mtx_lock_spin(&(_dp)->dad_lock)
131 
132 #define DAD_CONVERT_LOCK(_dp) do {                                      \
133 	DAD_LOCK_ASSERT_HELD(_dp);                                      \
134 	lck_mtx_convert_spin(&(_dp)->dad_lock);                         \
135 } while (0)
136 
137 #define DAD_UNLOCK(_dp)                                                 \
138 	lck_mtx_unlock(&(_dp)->dad_lock)
139 
140 #define DAD_ADDREF(_dp)                                                 \
141 	dad_addref(_dp, 0)
142 
143 #define DAD_ADDREF_LOCKED(_dp)                                          \
144 	dad_addref(_dp, 1)
145 
146 #define DAD_REMREF(_dp)                                                 \
147 	dad_remref(_dp)
148 
149 static LCK_MTX_DECLARE_ATTR(dad6_mutex, &ip6_mutex_grp, &ip6_mutex_attr);
150 
151 static struct sockaddr_in6 hostrtmask;
152 
153 static int nd6_llreach_base = 30;        /* seconds */
154 SYSCTL_DECL(_net_inet6_icmp6);
155 SYSCTL_INT(_net_inet6_icmp6, OID_AUTO, nd6_llreach_base,
156     CTLFLAG_RW | CTLFLAG_LOCKED, &nd6_llreach_base, 0,
157     "default ND6 link-layer reachability max lifetime (in seconds)");
158 
159 int dad_enhanced = ND6_DAD_ENHANCED_DEFAULT;
160 SYSCTL_DECL(_net_inet6_ip6);
161 SYSCTL_INT(_net_inet6_ip6, OID_AUTO, dad_enhanced, CTLFLAG_RW | CTLFLAG_LOCKED,
162     &dad_enhanced, 0,
163     "Enable Enhanced DAD, which adds a random nonce to NS messages for DAD.");
164 
165 static uint32_t nd6_dad_nonce_max_count = 3;
166 SYSCTL_UINT(_net_inet6_ip6, OID_AUTO, nd6_dad_nonce_max_count,
167     CTLFLAG_RW | CTLFLAG_LOCKED, &nd6_dad_nonce_max_count, 0, "Number of times to ignore same nonce for DAD");
168 
169 #if DEBUG || DEVELOPMENT
170 static int  ip6_p2p_debug = 0;
171 SYSCTL_INT(_net_inet6_ip6, OID_AUTO, ip6_p2p_debug, CTLFLAG_RW | CTLFLAG_LOCKED,
172     &ip6_p2p_debug, 0,
173     "Enable more instrumentation for IPv6 P2P use-case");
174 #endif
175 
176 /*
177  * Obtain a link-layer source cache entry for the sender.
178  *
179  * NOTE: This is currently only for ND6/Ethernet.
180  */
181 void
nd6_llreach_alloc(struct rtentry * rt,struct ifnet * ifp,void * addr __sized_by (alen),unsigned int alen,boolean_t solicited)182 nd6_llreach_alloc(struct rtentry *rt, struct ifnet *ifp, void *addr __sized_by(alen),
183     unsigned int alen, boolean_t solicited)
184 {
185 	struct llinfo_nd6 *__single ln = rt->rt_llinfo;
186 
187 	if (nd6_llreach_base != 0 &&
188 	    (ln->ln_expire != 0 || (ifp->if_eflags & IFEF_IPV6_ND6ALT) != 0) &&
189 	    !(rt->rt_ifp->if_flags & IFF_LOOPBACK) &&
190 	    ifp->if_addrlen == IF_LLREACH_MAXLEN &&     /* Ethernet */
191 	    alen == ifp->if_addrlen) {
192 		struct if_llreach *__single lr;
193 		const char *why = NULL, *type = "";
194 
195 		/* Become a regular mutex, just in case */
196 		RT_CONVERT_LOCK(rt);
197 
198 		if ((lr = ln->ln_llreach) != NULL) {
199 			type = (solicited ? "ND6 advertisement" :
200 			    "ND6 unsolicited announcement");
201 			/*
202 			 * If target has changed, create a new record;
203 			 * otherwise keep existing record.
204 			 */
205 			IFLR_LOCK(lr);
206 			if (bcmp(addr, lr->lr_key.addr, alen) != 0) {
207 				IFLR_UNLOCK(lr);
208 				/* Purge any link-layer info caching */
209 				VERIFY(rt->rt_llinfo_purge != NULL);
210 				rt->rt_llinfo_purge(rt);
211 				lr = NULL;
212 				why = " for different target HW address; "
213 				    "using new llreach record";
214 			} else {
215 				lr->lr_probes = 0;      /* reset probe count */
216 				IFLR_UNLOCK(lr);
217 				if (solicited) {
218 					why = " for same target HW address; "
219 					    "keeping existing llreach record";
220 				}
221 			}
222 		}
223 
224 		if (lr == NULL) {
225 			lr = ln->ln_llreach = ifnet_llreach_alloc(ifp,
226 			    ETHERTYPE_IPV6, addr, alen, nd6_llreach_base);
227 			if (lr != NULL) {
228 				lr->lr_probes = 0;      /* reset probe count */
229 				if (why == NULL) {
230 					why = "creating new llreach record";
231 				}
232 			}
233 		}
234 
235 		if (nd6_debug && lr != NULL && why != NULL) {
236 			char tmp[MAX_IPv6_STR_LEN];
237 
238 			nd6log2(debug, "%s: %s%s for %s iface=%s\n", __func__,
239 			    type, why, inet_ntop(AF_INET6,
240 			    &SIN6(rt_key(rt))->sin6_addr, tmp, sizeof(tmp)),
241 			    if_name(ifp));
242 		}
243 	}
244 }
245 
246 void
nd6_llreach_use(struct llinfo_nd6 * ln)247 nd6_llreach_use(struct llinfo_nd6 *ln)
248 {
249 	if (ln->ln_llreach != NULL) {
250 		ln->ln_lastused = net_uptime();
251 	}
252 }
253 
254 /*
255  * Input a Neighbor Solicitation Message.
256  *
257  * Based on RFC 4861
258  * Based on RFC 4862 (duplicate address detection)
259  */
260 void
nd6_ns_input(struct mbuf * m,int off,int icmp6len)261 nd6_ns_input(
262 	struct mbuf *m,
263 	int off,
264 	int icmp6len)
265 {
266 	ifnet_ref_t ifp = m->m_pkthdr.rcvif;
267 	struct ip6_hdr *ip6 = mtod(m, struct ip6_hdr *);
268 	struct nd_neighbor_solicit *nd_ns = NULL;
269 	struct in6_addr saddr6 = ip6->ip6_src;
270 	struct in6_addr daddr6 = ip6->ip6_dst;
271 	uint32_t saddr_ifscope = IN6_IS_SCOPE_EMBED(&saddr6) ? ip6_input_getsrcifscope(m) : IFSCOPE_NONE;
272 	struct in6_addr taddr6 = {};
273 	struct in6_addr myaddr6 = {};
274 	uint32_t myaddr_ifscope = IFSCOPE_NONE;
275 	int lladdrlen = 0;
276 	char *lladdr = NULL;
277 	struct ifaddr *__single ifa = NULL;
278 	int anycast = 0, proxy = 0, dadprogress = 0;
279 	int tlladdr = 0;
280 	union nd_opts ndopts = {};
281 	struct sockaddr_dl proxydl = {};
282 	boolean_t advrouter = FALSE;
283 	boolean_t is_dad_probe = FALSE;
284 	int oflgclr = 0;
285 	uint32_t taddr_ifscope;
286 
287 	/* Expect 32-bit aligned data pointer on strict-align platforms */
288 	MBUF_STRICT_DATA_ALIGNMENT_CHECK_32(m);
289 
290 	IP6_EXTHDR_CHECK(m, off, icmp6len, return );
291 	ip6 = mtod(m, struct ip6_hdr *);
292 	nd_ns = (struct nd_neighbor_solicit *)((caddr_t)ip6 + off);
293 	m->m_pkthdr.pkt_flags |= PKTF_INET6_RESOLVE;
294 
295 	taddr6 = nd_ns->nd_ns_target;
296 	if (in6_setscope(&taddr6, ifp, &taddr_ifscope) != 0) {
297 		m_drop(m, DROPTAP_FLAG_DIR_IN | DROPTAP_FLAG_L2_MISSING, DROP_REASON_IP6_BAD_SCOPE, NULL, 0);
298 		goto bad;
299 	}
300 
301 	if (ip6->ip6_hlim != IPV6_MAXHLIM) {
302 		nd6log(error,
303 		    "nd6_ns_input: invalid hlim (%d) from %s to %s on %s\n",
304 		    ip6->ip6_hlim, ip6_sprintf(&ip6->ip6_src),
305 		    ip6_sprintf(&ip6->ip6_dst), if_name(ifp));
306 		m_drop(m, DROPTAP_FLAG_DIR_IN | DROPTAP_FLAG_L2_MISSING, DROP_REASON_IP6_BAD_HLIM, NULL, 0);
307 		goto bad;
308 	}
309 
310 	is_dad_probe = IN6_IS_ADDR_UNSPECIFIED(&saddr6);
311 	if (is_dad_probe) {
312 		/* dst has to be a solicited node multicast address. */
313 		if (daddr6.s6_addr16[0] == IPV6_ADDR_INT16_MLL &&
314 		    /* don't check ifindex portion */
315 		    daddr6.s6_addr32[1] == 0 &&
316 		    daddr6.s6_addr32[2] == IPV6_ADDR_INT32_ONE &&
317 		    daddr6.s6_addr8[12] == 0xff) {
318 			; /* good */
319 		} else {
320 			nd6log(info, "nd6_ns_input: bad DAD packet (wrong ip6 dst)\n");
321 			m_drop(m, DROPTAP_FLAG_DIR_IN | DROPTAP_FLAG_L2_MISSING, DROP_REASON_IP6_BAD_DAD, NULL, 0);
322 			goto bad;
323 		}
324 	} else if (!nd6_onlink_ns_rfc4861) {
325 		struct sockaddr_in6 src_sa6;
326 
327 		/*
328 		 * According to recent IETF discussions, it is not a good idea
329 		 * to accept a NS from an address which would not be deemed
330 		 * to be a neighbor otherwise.  This point is expected to be
331 		 * clarified in future revisions of the specification.
332 		 */
333 		SOCKADDR_ZERO(&src_sa6, sizeof(src_sa6));
334 		src_sa6.sin6_family = AF_INET6;
335 		src_sa6.sin6_len = sizeof(src_sa6);
336 		src_sa6.sin6_addr = saddr6;
337 		if (!in6_embedded_scope) {
338 			src_sa6.sin6_scope_id = saddr_ifscope;
339 		}
340 		if (!nd6_is_addr_neighbor(&src_sa6, ifp, 0)) {
341 			nd6log(info, "nd6_ns_input: NS packet from non-neighbor\n");
342 			m_drop(m, DROPTAP_FLAG_DIR_IN | DROPTAP_FLAG_L2_MISSING, DROP_REASON_IP6_BAD_ND_STATE, NULL, 0);
343 			goto bad;
344 		}
345 	}
346 
347 	if (IN6_IS_ADDR_MULTICAST(&taddr6)) {
348 		nd6log(info, "nd6_ns_input: bad NS target (multicast)\n");
349 		m_drop(m, DROPTAP_FLAG_DIR_IN | DROPTAP_FLAG_L2_MISSING, DROP_REASON_IP6_BAD_ND_STATE, NULL, 0);
350 		goto bad;
351 	}
352 
353 	icmp6len -= sizeof(*nd_ns);
354 
355 	nd6_option_init(nd_ns + 1, icmp6len, &ndopts);
356 	if (nd6_options(&ndopts) < 0) {
357 		nd6log(info, "nd6_ns_input: invalid ND option, ignored\n");
358 		/* nd6_options have incremented stats */
359 		m_drop(m, DROPTAP_FLAG_DIR_IN | DROPTAP_FLAG_L2_MISSING, DROP_REASON_IP6_BAD_ND_STATE, NULL, 0);
360 		goto bad;
361 	}
362 
363 	if (ndopts.nd_opts_src_lladdr) {
364 		ND_OPT_LLADDR(ndopts.nd_opts_src_lladdr, nd_opt_len, lladdr, lladdrlen);
365 	}
366 
367 	if (is_dad_probe && lladdr) {
368 		nd6log(info, "nd6_ns_input: bad DAD packet "
369 		    "(link-layer address option)\n");
370 		m_drop(m, DROPTAP_FLAG_DIR_IN | DROPTAP_FLAG_L2_MISSING, DROP_REASON_IP6_BAD_DAD, NULL, 0);
371 		goto bad;
372 	}
373 
374 	/*
375 	 * Attaching target link-layer address to the NA?
376 	 * (RFC 2461 7.2.4)
377 	 *
378 	 * NS IP dst is unicast/anycast			MUST NOT add
379 	 * NS IP dst is solicited-node multicast	MUST add
380 	 *
381 	 * In implementation, we add target link-layer address by default.
382 	 * We do not add one in MUST NOT cases.
383 	 */
384 	if (!IN6_IS_ADDR_MULTICAST(&daddr6)) {
385 		tlladdr = 0;
386 	} else {
387 		tlladdr = 1;
388 	}
389 
390 	/*
391 	 * Target address (taddr6) must be either:
392 	 * (1) Valid unicast/anycast address for my receiving interface,
393 	 * (2) Unicast address for which I'm offering proxy service, or
394 	 * (3) "tentative" or "optimistic" address [DAD is in progress].
395 	 */
396 	/* (1) and (3) check. */
397 	ifa = (struct ifaddr *)in6ifa_ifpwithaddr(ifp, &taddr6);
398 
399 	/* (2) check. */
400 	if (ifa == NULL) {
401 		rtentry_ref_t rt;
402 		struct sockaddr_in6 tsin6;
403 
404 		SOCKADDR_ZERO(&tsin6, sizeof tsin6);
405 		tsin6.sin6_len = sizeof(struct sockaddr_in6);
406 		tsin6.sin6_family = AF_INET6;
407 		tsin6.sin6_addr = taddr6;
408 
409 		rt = rtalloc1_scoped(SA(&tsin6), 0, 0, ifp->if_index);
410 
411 		if (rt != NULL) {
412 			RT_LOCK(rt);
413 			if ((rt->rt_flags & RTF_ANNOUNCE) != 0 &&
414 			    rt->rt_gateway->sa_family == AF_LINK) {
415 				/*
416 				 * proxy NDP for single entry
417 				 */
418 				ifa = (struct ifaddr *)in6ifa_ifpforlinklocal(
419 					ifp, IN6_IFF_NOTREADY | IN6_IFF_ANYCAST);
420 				if (ifa) {
421 					proxy = 1;
422 					proxydl = *SDL(rt->rt_gateway);
423 				}
424 			}
425 			RT_UNLOCK(rt);
426 			rtfree(rt);
427 		}
428 	}
429 	if (ifa == NULL && ip6_forwarding && nd6_prproxy) {
430 		/*
431 		 * Is the target address part of the prefix that is being
432 		 * proxied and installed on another interface?
433 		 */
434 		ifa = (struct ifaddr *)in6ifa_prproxyaddr(&taddr6, taddr_ifscope);
435 	}
436 	if (ifa == NULL) {
437 		/*
438 		 * We've got an NS packet, and we don't have that address
439 		 * assigned for us.  We MUST silently ignore it on this
440 		 * interface, c.f. RFC 4861 7.2.3.
441 		 *
442 		 * Forwarding associated with NDPRF_PRPROXY may apply.
443 		 */
444 		if (ip6_forwarding && nd6_prproxy) {
445 			size_t noncelen = (ndopts.nd_opts_nonce == NULL) ? 0 :
446 			    ndopts.nd_opts_nonce->nd_opt_nonce_len << 3;
447 			uint8_t *nonce = (ndopts.nd_opts_nonce == NULL) ? NULL :
448 			    __unsafe_forge_bidi_indexable(uint8_t *, ndopts.nd_opts_nonce->nd_opt_nonce, noncelen);
449 
450 			nd6_prproxy_ns_input(ifp, &saddr6, lladdr,
451 			    lladdrlen, &daddr6, &taddr6,
452 			    nonce, noncelen);
453 		}
454 		goto freeit;
455 	}
456 	IFA_LOCK(ifa);
457 	myaddr6 = *IFA_IN6(ifa);
458 	myaddr_ifscope = IFA_SIN6_SCOPE(ifa);
459 	anycast = (ifatoia6(ifa))->ia6_flags & IN6_IFF_ANYCAST;
460 	dadprogress =
461 	    (ifatoia6(ifa))->ia6_flags & IN6_IFF_DADPROGRESS;
462 	if ((ifatoia6(ifa))->ia6_flags & IN6_IFF_DUPLICATED) {
463 		IFA_UNLOCK(ifa);
464 		goto freeit;
465 	}
466 	IFA_UNLOCK(ifa);
467 
468 	if (lladdr && ((ifp->if_addrlen + 2 + 7) & ~7) != lladdrlen) {
469 		nd6log(info,
470 		    "nd6_ns_input: lladdrlen mismatch for %s "
471 		    "(if %d, NS packet %d)\n",
472 		    ip6_sprintf(&taddr6), ifp->if_addrlen, lladdrlen - 2);
473 		m_drop(m, DROPTAP_FLAG_DIR_IN | DROPTAP_FLAG_L2_MISSING, DROP_REASON_IP6_BAD_ND_STATE, NULL, 0);
474 		goto bad;
475 	}
476 
477 	if (in6_are_addr_equal_scoped(&myaddr6, &saddr6, myaddr_ifscope, saddr_ifscope)) {
478 		nd6log(info,
479 		    "nd6_ns_input: duplicate IP6 address %s\n",
480 		    ip6_sprintf(&saddr6));
481 		m_drop(m, DROPTAP_FLAG_DIR_IN | DROPTAP_FLAG_L2_MISSING, DROP_REASON_IP6_BAD_ND_STATE, NULL, 0);
482 		goto bad;
483 	}
484 
485 	/*
486 	 * We have neighbor solicitation packet, with target address equals to
487 	 * one of my DAD in-progress addresses.
488 	 *
489 	 * src addr	how to process?
490 	 * ---		---
491 	 * multicast	of course, invalid (rejected in ip6_input)
492 	 * unicast	somebody is doing address resolution
493 	 * unspec	dup address detection
494 	 *
495 	 * The processing is defined in the "draft standard" RFC 4862 (and by
496 	 * RFC 4429, which is a "proposed standard" update to its obsolete
497 	 * predecessor, RFC 2462)  The reason optimistic DAD is not included
498 	 * in RFC 4862 is entirely due to IETF procedural considerations.
499 	 */
500 	if (dadprogress) {
501 		/*
502 		 * If source address is unspecified address, it is for
503 		 * duplicate address detection.
504 		 *
505 		 * If not, the packet is for addess resolution;
506 		 * silently ignore it when not optimistic
507 		 *
508 		 * Per RFC 4429 the reply for an optimistic address must
509 		 * have the Override flag cleared
510 		 */
511 		if (!is_dad_probe && (dadprogress & IN6_IFF_OPTIMISTIC) != 0) {
512 			oflgclr = 1;
513 		} else {
514 			if (is_dad_probe) {
515 				nd6_dad_ns_input(ifa, lladdr, lladdrlen, ndopts.nd_opts_nonce);
516 			}
517 
518 			goto freeit;
519 		}
520 	}
521 
522 	/* Are we an advertising router on this interface? */
523 	advrouter = (ifp->if_ipv6_router_mode != IPV6_ROUTER_MODE_DISABLED);
524 
525 	/*
526 	 * If the source address is unspecified address, entries must not
527 	 * be created or updated.
528 	 * It looks that sender is performing DAD.  If I'm using the address,
529 	 * and it's a "preferred" address, i.e. not optimistic, then output NA
530 	 * toward all-node multicast address, to tell the sender that I'm using
531 	 * the address.
532 	 * S bit ("solicited") must be zero.
533 	 */
534 	if (is_dad_probe) {
535 		saddr6 = in6addr_linklocal_allnodes;
536 		if (in6_setscope(&saddr6, ifp, NULL) != 0) {
537 			m_drop(m, DROPTAP_FLAG_DIR_IN | DROPTAP_FLAG_L2_MISSING, DROP_REASON_IP6_BAD_SCOPE, NULL, 0);
538 			goto bad;
539 		}
540 		if ((dadprogress & IN6_IFF_OPTIMISTIC) == 0) {
541 			nd6_na_output(ifp, &saddr6, &taddr6,
542 			    ((anycast || proxy || !tlladdr) ? 0 :
543 			    ND_NA_FLAG_OVERRIDE) | (advrouter ?
544 			    ND_NA_FLAG_ROUTER : 0), tlladdr, proxy ?
545 			    SA(&proxydl) : NULL);
546 		}
547 		goto freeit;
548 	}
549 
550 	nd6_cache_lladdr(ifp, &saddr6, lladdr, lladdrlen,
551 	    ND_NEIGHBOR_SOLICIT, 0, NULL);
552 
553 	nd6_na_output(ifp, &saddr6, &taddr6,
554 	    ((anycast || proxy || !tlladdr || oflgclr) ? 0 : ND_NA_FLAG_OVERRIDE) |
555 	    (advrouter ? ND_NA_FLAG_ROUTER : 0) | ND_NA_FLAG_SOLICITED,
556 	    tlladdr, proxy ? SA(&proxydl) : NULL);
557 freeit:
558 	m_freem(m);
559 	if (ifa != NULL) {
560 		ifa_remref(ifa);
561 	}
562 	return;
563 
564 bad:
565 	nd6log(error, "nd6_ns_input: src=%s\n", ip6_sprintf(&saddr6));
566 	nd6log(error, "nd6_ns_input: dst=%s\n", ip6_sprintf(&daddr6));
567 	nd6log(error, "nd6_ns_input: tgt=%s\n", ip6_sprintf(&taddr6));
568 	icmp6stat.icp6s_badns++;
569 	if (ifa != NULL) {
570 		ifa_remref(ifa);
571 	}
572 }
573 
574 /*
575  * Output a Neighbor Solicitation Message. Caller specifies:
576  *	- ICMP6 header source IP6 address
577  *	- ND6 header target IP6 address
578  *	- ND6 header source datalink address
579  *
580  * Based on RFC 4861
581  * Based on RFC 4862 (duplicate address detection)
582  * Based on RFC 4429 (optimistic duplicate address detection)
583  *
584  * Caller must bump up ln->ln_rt refcnt to make sure 'ln' doesn't go
585  * away if there is a llinfo_nd6 passed in.
586  */
587 void
nd6_ns_output(struct ifnet * ifp,const struct in6_addr * daddr6,const struct in6_addr * taddr6,struct llinfo_nd6 * ln,uint8_t * __counted_by (noncelen)nonce,size_t noncelen)588 nd6_ns_output(
589 	struct ifnet *ifp,
590 	const struct in6_addr *daddr6,
591 	const struct in6_addr *taddr6,
592 	struct llinfo_nd6 *ln,  /* for source address determination */
593 	uint8_t *__counted_by(noncelen) nonce,
594 	size_t noncelen)
595 {
596 #pragma unused(noncelen)
597 
598 	mbuf_ref_t m;
599 	struct ip6_hdr *ip6;
600 	struct nd_neighbor_solicit *nd_ns;
601 	struct in6_ifaddr *ia = NULL;
602 	struct in6_addr *__single src, src_in, src_storage;
603 	struct ip6_moptions *__single im6o = NULL;
604 	ifnet_ref_t outif = NULL;
605 	int icmp6len;
606 	int maxlen;
607 	int flags;
608 	caddr_t mac;
609 	struct route_in6 ro;
610 	struct ip6_out_args ip6oa;
611 	u_int32_t rtflags = 0;
612 	boolean_t is_optimistic = FALSE;
613 	drop_reason_t drop_reason = DROP_REASON_UNSPECIFIED;
614 
615 	if ((ifp->if_eflags & IFEF_IPV6_ND6ALT) || IN6_IS_ADDR_MULTICAST(taddr6)) {
616 		return;
617 	}
618 
619 	bzero(&ro, sizeof(ro));
620 	bzero(&ip6oa, sizeof(ip6oa));
621 	ip6oa.ip6oa_boundif = ifp->if_index;
622 	ip6oa.ip6oa_flags = IP6OAF_SELECT_SRCIF | IP6OAF_BOUND_SRCADDR |
623 	    IP6OAF_AWDL_UNRESTRICTED | IP6OAF_INTCOPROC_ALLOWED |
624 	    IP6OAF_MANAGEMENT_ALLOWED;
625 	ip6oa.ip6oa_sotc = SO_TC_UNSPEC;
626 	ip6oa.ip6oa_netsvctype = _NET_SERVICE_TYPE_UNSPEC;
627 
628 	ip6oa.ip6oa_flags |= IP6OAF_BOUND_IF;
629 
630 	/* estimate the size of message */
631 	maxlen = sizeof(*ip6) + sizeof(*nd_ns);
632 	maxlen += (sizeof(struct nd_opt_hdr) + ifp->if_addrlen + 7) & ~7;
633 	if (max_linkhdr + maxlen >= MCLBYTES) {
634 #if DIAGNOSTIC
635 		printf("nd6_ns_output: max_linkhdr + maxlen >= MCLBYTES "
636 		    "(%d + %d > %d)\n", max_linkhdr, maxlen, MCLBYTES);
637 #endif
638 		return;
639 	}
640 
641 	MGETHDR(m, M_DONTWAIT, MT_DATA);        /* XXXMAC: mac_create_mbuf_linklayer() probably */
642 	if (m && max_linkhdr + maxlen >= MHLEN) {
643 		MCLGET(m, M_DONTWAIT);
644 		if ((m->m_flags & M_EXT) == 0) {
645 			m_free(m);
646 			m = NULL;
647 		}
648 	}
649 	if (m == NULL) {
650 		return;
651 	}
652 	m->m_pkthdr.rcvif = NULL;
653 
654 	if (daddr6 == NULL || IN6_IS_ADDR_MULTICAST(daddr6)) {
655 		m->m_flags |= M_MCAST;
656 
657 		im6o = ip6_allocmoptions(Z_NOWAIT);
658 		if (im6o == NULL) {
659 			m_freem(m);
660 			return;
661 		}
662 
663 		im6o->im6o_multicast_ifp = ifp;
664 		im6o->im6o_multicast_hlim = IPV6_MAXHLIM;
665 		im6o->im6o_multicast_loop = 0;
666 	}
667 
668 	icmp6len = sizeof(*nd_ns);
669 	m->m_pkthdr.len = m->m_len = sizeof(*ip6) + icmp6len;
670 	m->m_data += max_linkhdr;       /* or MH_ALIGN() equivalent? */
671 
672 	/* fill neighbor solicitation packet */
673 	ip6 = mtod(m, struct ip6_hdr *);
674 	ip6->ip6_flow = 0;
675 	ip6->ip6_vfc &= ~IPV6_VERSION_MASK;
676 	ip6->ip6_vfc |= IPV6_VERSION;
677 	/* ip6->ip6_plen will be set later */
678 	ip6->ip6_nxt = IPPROTO_ICMPV6;
679 	ip6->ip6_hlim = IPV6_MAXHLIM;
680 	if (daddr6) {
681 		ip6->ip6_dst = *daddr6;
682 		ip6_output_setdstifscope(m, ifp->if_index, NULL);
683 	} else {
684 		ip6->ip6_dst.s6_addr16[0] = IPV6_ADDR_INT16_MLL;
685 		ip6->ip6_dst.s6_addr16[1] = 0;
686 		ip6->ip6_dst.s6_addr32[1] = 0;
687 		ip6->ip6_dst.s6_addr32[2] = IPV6_ADDR_INT32_ONE;
688 		ip6->ip6_dst.s6_addr32[3] = taddr6->s6_addr32[3];
689 		ip6->ip6_dst.s6_addr8[12] = 0xff;
690 		ip6_output_setdstifscope(m, ifp->if_index, NULL);
691 		if (in6_setscope(&ip6->ip6_dst, ifp, NULL) != 0) {
692 			drop_reason = DROP_REASON_IP6_BAD_SCOPE;
693 			goto bad;
694 		}
695 	}
696 	if (nonce == NULL) {
697 		/*
698 		 * RFC2461 7.2.2:
699 		 * "If the source address of the packet prompting the
700 		 * solicitation is the same as one of the addresses assigned
701 		 * to the outgoing interface, that address SHOULD be placed
702 		 * in the IP Source Address of the outgoing solicitation.
703 		 * Otherwise, any one of the addresses assigned to the
704 		 * interface should be used."
705 		 *
706 		 * We use the source address for the prompting packet
707 		 * (saddr6), if:
708 		 * - saddr6 is given from the caller (by giving "ln"), and
709 		 * - saddr6 belongs to the outgoing interface.
710 		 * Otherwise, we perform the source address selection as usual.
711 		 */
712 		struct ip6_hdr *__single hip6;           /* hold ip6 */
713 		struct in6_addr *__single hsrc = NULL;
714 
715 		/* Caller holds ref on this route */
716 		if (ln != NULL) {
717 			RT_LOCK(ln->ln_rt);
718 			/*
719 			 * assuming every packet in ln_hold has the same IP
720 			 * header
721 			 */
722 			if (ln->ln_hold != NULL) {
723 				hip6 = mtod(ln->ln_hold, struct ip6_hdr *);
724 				/* XXX pullup? */
725 				if (sizeof(*hip6) < ln->ln_hold->m_len) {
726 					hsrc = &hip6->ip6_src;
727 				} else {
728 					hsrc = NULL;
729 				}
730 			}
731 			/* Update probe count, if applicable */
732 			if (ln->ln_llreach != NULL) {
733 				IFLR_LOCK_SPIN(ln->ln_llreach);
734 				ln->ln_llreach->lr_probes++;
735 				IFLR_UNLOCK(ln->ln_llreach);
736 			}
737 			rtflags = ln->ln_rt->rt_flags;
738 			RT_UNLOCK(ln->ln_rt);
739 		}
740 		if (hsrc != NULL && (ia = in6ifa_ifpwithaddr(ifp, hsrc)) &&
741 		    (ia->ia6_flags & IN6_IFF_OPTIMISTIC) == 0) {
742 			src = hsrc;
743 		} else {
744 			int error;
745 			struct sockaddr_in6 dst_sa;
746 
747 			SOCKADDR_ZERO(&dst_sa, sizeof(dst_sa));
748 			dst_sa.sin6_family = AF_INET6;
749 			dst_sa.sin6_len = sizeof(dst_sa);
750 			dst_sa.sin6_addr = ip6->ip6_dst;
751 
752 			src = in6_selectsrc(&dst_sa, NULL,
753 			    NULL, &ro, NULL, &src_storage, ip6oa.ip6oa_boundif,
754 			    &error);
755 			if (src == NULL) {
756 				nd6log(info,
757 				    "nd6_ns_output: source can't be "
758 				    "determined: dst=%s, error=%d\n",
759 				    ip6_sprintf(&dst_sa.sin6_addr),
760 				    error);
761 				drop_reason = DROP_REASON_IP_SRC_ADDR_NO_AVAIL;
762 				goto bad;
763 			}
764 
765 			if (ia != NULL) {
766 				ifa_remref(&ia->ia_ifa);
767 				ia = NULL;
768 			}
769 			/*
770 			 * RFC 4429 section 3.2:
771 			 * When a node has a unicast packet to send
772 			 * from an Optimistic Address to a neighbor,
773 			 * but does not know the neighbor's link-layer
774 			 * address, it MUST NOT perform Address
775 			 * Resolution.
776 			 */
777 			ia = in6ifa_ifpwithaddr(ifp, src);
778 			if (ia == NULL) {
779 				nd6log(info,
780 				    "nd6_ns_output: no preferred source "
781 				    "available: dst=%s\n",
782 				    ip6_sprintf(&dst_sa.sin6_addr));
783 				drop_reason = DROP_REASON_IP_SRC_ADDR_NO_AVAIL;
784 				goto bad;
785 			}
786 			if (ia->ia6_flags & IN6_IFF_OPTIMISTIC) {
787 				is_optimistic = TRUE;
788 				nd6log(info,
789 				    "nd6_ns_output: preferred source "
790 				    "available is optimistic: dst=%s\n",
791 				    ip6_sprintf(&dst_sa.sin6_addr));
792 			}
793 		}
794 	} else {
795 		/*
796 		 * Source address for DAD packet must always be IPv6
797 		 * unspecified address. (0::0)
798 		 * We actually don't have to 0-clear the address (we did it
799 		 * above), but we do so here explicitly to make the intention
800 		 * clearer.
801 		 */
802 		bzero(&src_in, sizeof(src_in));
803 		src = &src_in;
804 		ip6oa.ip6oa_flags &= ~IP6OAF_BOUND_SRCADDR;
805 	}
806 	ip6->ip6_src = *src;
807 	ip6_output_setsrcifscope(m, ifp->if_index, ia);
808 	nd_ns = (struct nd_neighbor_solicit *)(ip6 + 1);
809 	nd_ns->nd_ns_type = ND_NEIGHBOR_SOLICIT;
810 	nd_ns->nd_ns_code = 0;
811 	nd_ns->nd_ns_reserved = 0;
812 	nd_ns->nd_ns_target = *taddr6;
813 	in6_clearscope(&nd_ns->nd_ns_target); /* XXX */
814 
815 	/*
816 	 * Add source link-layer address option.
817 	 *
818 	 *				spec		implementation
819 	 *				---		---
820 	 * DAD packet			MUST NOT	do not add the option
821 	 * Source is optimistic         MUST NOT        do not add the option
822 	 * there's no link layer address:
823 	 *				impossible	do not add the option
824 	 * there's link layer address:
825 	 *	Multicast NS		MUST add one	add the option
826 	 *	Unicast NS		SHOULD add one	add the option
827 	 *
828 	 * XXX We deviate from RFC 4429 and still use optimistic DAD as source
829 	 * for address resolution. However to ensure that we do not interfere
830 	 * with neighbor cache entries of other neighbors, we MUST ensure
831 	 * that SLLAO is not sent. Also note, sending multicast NS without SLLAO
832 	 * is also a deviation from RFC 4861.
833 	 */
834 	if (nonce == NULL && (mac = nd6_ifptomac(ifp)) && !is_optimistic) {
835 		int optlen = sizeof(struct nd_opt_hdr) + ifp->if_addrlen;
836 		struct nd_opt_hdr *nd_opt = (struct nd_opt_hdr *)(nd_ns + 1);
837 		/* 8 byte alignments... */
838 		optlen = (optlen + 7) & ~7;
839 
840 		m->m_pkthdr.len += optlen;
841 		m->m_len += optlen;
842 		icmp6len += optlen;
843 		bzero((caddr_t)nd_opt, optlen);
844 		nd_opt->nd_opt_type = ND_OPT_SOURCE_LINKADDR;
845 		nd_opt->nd_opt_len = (uint8_t)(optlen >> 3);
846 		bcopy(mac, (caddr_t)(nd_opt + 1), ifp->if_addrlen);
847 	}
848 	/*
849 	 * Add a Nonce option (RFC 3971) to detect looped back NS messages.
850 	 * This behavior is documented as Enhanced Duplicate Address
851 	 * Detection in draft-ietf-6man-enhanced-dad-13.
852 	 * net.inet6.ip6.dad_enhanced=0 disables this.
853 	 */
854 	if (dad_enhanced != 0 && nonce != NULL && !(ifp->if_flags & IFF_POINTOPOINT)) {
855 		int optlen = sizeof(struct nd_opt_hdr) + ND_OPT_NONCE_LEN;
856 		struct nd_opt_hdr *nd_opt = (struct nd_opt_hdr *)(nd_ns + 1);
857 		/* 8-byte alignment is required. */
858 		optlen = (optlen + 7) & ~7;
859 
860 		m->m_pkthdr.len += optlen;
861 		m->m_len += optlen;
862 		icmp6len += optlen;
863 		bzero((caddr_t)nd_opt, optlen);
864 		nd_opt->nd_opt_type = ND_OPT_NONCE;
865 		nd_opt->nd_opt_len = (uint8_t)(optlen >> 3);
866 		bcopy(nonce, (caddr_t)(nd_opt + 1), ND_OPT_NONCE_LEN);
867 	}
868 	ip6->ip6_plen = htons((u_short)icmp6len);
869 	nd_ns->nd_ns_cksum = 0;
870 	nd_ns->nd_ns_cksum
871 	        = in6_cksum(m, IPPROTO_ICMPV6, sizeof(*ip6), icmp6len);
872 
873 	flags = nonce ? IPV6_UNSPECSRC : 0;
874 	flags |= IPV6_OUTARGS;
875 
876 	/*
877 	 * PKTF_{INET,INET6}_RESOLVE_RTR are mutually exclusive, so make
878 	 * sure only one of them is set (just in case.)
879 	 */
880 	m->m_pkthdr.pkt_flags &= ~(PKTF_INET_RESOLVE | PKTF_RESOLVE_RTR);
881 	m->m_pkthdr.pkt_flags |= PKTF_INET6_RESOLVE;
882 	/*
883 	 * If this is a NS for resolving the (default) router, mark
884 	 * the packet accordingly so that the driver can find out,
885 	 * in case it needs to perform driver-specific action(s).
886 	 */
887 	if (rtflags & RTF_ROUTER) {
888 		m->m_pkthdr.pkt_flags |= PKTF_RESOLVE_RTR;
889 	}
890 
891 	if (ifp->if_eflags & IFEF_TXSTART) {
892 		/*
893 		 * Use control service class if the interface
894 		 * supports transmit-start model
895 		 */
896 		(void) m_set_service_class(m, MBUF_SC_CTL);
897 	}
898 
899 	ip6oa.ip6oa_flags |= IP6OAF_SKIP_PF;
900 	ip6oa.ip6oa_flags |= IP6OAF_DONT_FRAG;
901 	ip6_output(m, NULL, NULL, flags, im6o, &outif, &ip6oa);
902 	if (outif) {
903 		icmp6_ifstat_inc(outif, ifs6_out_msg);
904 		icmp6_ifstat_inc(outif, ifs6_out_neighborsolicit);
905 		ifnet_release(outif);
906 	}
907 	icmp6stat.icp6s_outhist[ND_NEIGHBOR_SOLICIT]++;
908 
909 exit:
910 	if (im6o != NULL) {
911 		IM6O_REMREF(im6o);
912 	}
913 
914 	ROUTE_RELEASE(&ro);     /* we don't cache this route. */
915 
916 	if (ia != NULL) {
917 		ifa_remref(&ia->ia_ifa);
918 	}
919 	return;
920 
921 bad:
922 	m_drop(m, DROPTAP_FLAG_DIR_OUT | DROPTAP_FLAG_L2_MISSING, drop_reason, NULL, 0);
923 	goto exit;
924 }
925 
926 /*
927  * Neighbor advertisement input handling.
928  *
929  * Based on RFC 4861
930  * Based on RFC 4862 (duplicate address detection)
931  *
932  * the following items are not implemented yet:
933  * - anycast advertisement delay rule (RFC 4861 7.2.7, SHOULD)
934  * - proxy advertisement delay rule (RFC 4861 7.2.8, last paragraph, "should")
935  */
936 void
nd6_na_input(struct mbuf * m,int off,int icmp6len)937 nd6_na_input(struct mbuf *m, int off, int icmp6len)
938 {
939 	ifnet_ref_t ifp = m->m_pkthdr.rcvif;
940 	struct ip6_hdr *ip6 = mtod(m, struct ip6_hdr *);
941 	struct nd_neighbor_advert *nd_na;
942 	struct in6_addr saddr6 = ip6->ip6_src;
943 	struct in6_addr daddr6 = ip6->ip6_dst;
944 	struct in6_addr taddr6;
945 	int flags;
946 	int is_router;
947 	int is_solicited;
948 	int is_override;
949 	char *lladdr = NULL;
950 	int lladdrlen = 0;
951 	struct llinfo_nd6 *__single ln;
952 	rtentry_ref_t rt;
953 	struct sockaddr_dl *sdl;
954 	union nd_opts ndopts;
955 	uint64_t timenow;
956 	bool send_nc_alive_kev = false;
957 	drop_reason_t drop_reason = DROP_REASON_UNSPECIFIED;
958 
959 	if ((ifp->if_eflags & IFEF_IPV6_ND6ALT) != 0) {
960 		nd6log(info, "nd6_na_input: on ND6ALT interface!\n");
961 		drop_reason = DROP_REASON_IP6_NO_ND6ALT_IF;
962 		goto freeit;
963 	}
964 
965 	/* Expect 32-bit aligned data pointer on strict-align platforms */
966 	MBUF_STRICT_DATA_ALIGNMENT_CHECK_32(m);
967 
968 	if (ip6->ip6_hlim != IPV6_MAXHLIM) {
969 		nd6log(error,
970 		    "nd6_na_input: invalid hlim (%d) from %s to %s on %s\n",
971 		    ip6->ip6_hlim, ip6_sprintf(&ip6->ip6_src),
972 		    ip6_sprintf(&ip6->ip6_dst), if_name(ifp));
973 		drop_reason = DROP_REASON_IP6_BAD_HLIM;
974 		goto bad;
975 	}
976 
977 	IP6_EXTHDR_CHECK(m, off, icmp6len, return );
978 	ip6 = mtod(m, struct ip6_hdr *);
979 	nd_na = (struct nd_neighbor_advert *)((caddr_t)ip6 + off);
980 	m->m_pkthdr.pkt_flags |= PKTF_INET6_RESOLVE;
981 
982 	flags = nd_na->nd_na_flags_reserved;
983 	is_router = ((flags & ND_NA_FLAG_ROUTER) != 0);
984 	is_solicited = ((flags & ND_NA_FLAG_SOLICITED) != 0);
985 	is_override = ((flags & ND_NA_FLAG_OVERRIDE) != 0);
986 
987 	taddr6 = nd_na->nd_na_target;
988 	if (in6_setscope(&taddr6, ifp, NULL)) {
989 		drop_reason = DROP_REASON_IP6_BAD_SCOPE;
990 		goto bad;       /* XXX: impossible */
991 	}
992 	if (IN6_IS_ADDR_MULTICAST(&taddr6)) {
993 		nd6log(error,
994 		    "nd6_na_input: invalid target address %s\n",
995 		    ip6_sprintf(&taddr6));
996 		drop_reason = DROP_REASON_IP_DST_ADDR_NO_AVAIL;
997 		goto bad;
998 	}
999 	if (IN6_IS_ADDR_MULTICAST(&daddr6)) {
1000 		if (is_solicited) {
1001 			nd6log(error,
1002 			    "nd6_na_input: a solicited adv is multicasted\n");
1003 			drop_reason = DROP_REASON_IP6_BAD_ND_STATE;
1004 			goto bad;
1005 		}
1006 	}
1007 
1008 	icmp6len -= sizeof(*nd_na);
1009 	nd6_option_init(nd_na + 1, icmp6len, &ndopts);
1010 	if (nd6_options(&ndopts) < 0) {
1011 		nd6log(info,
1012 		    "nd6_na_input: invalid ND option, ignored\n");
1013 		/* nd6_options have incremented stats */
1014 		drop_reason = DROP_REASON_IP6_TOO_MANY_OPTIONS;
1015 		goto freeit;
1016 	}
1017 
1018 	if (ndopts.nd_opts_tgt_lladdr) {
1019 		ND_OPT_LLADDR(ndopts.nd_opts_tgt_lladdr, nd_opt_len, lladdr, lladdrlen);
1020 
1021 		if (((ifp->if_addrlen + 2 + 7) & ~7) != lladdrlen) {
1022 			nd6log(info,
1023 			    "nd6_na_input: lladdrlen mismatch for %s "
1024 			    "(if %d, NA packet %d)\n",
1025 			    ip6_sprintf(&taddr6), ifp->if_addrlen,
1026 			    lladdrlen - 2);
1027 			drop_reason = DROP_REASON_IP6_BAD_ND_STATE;
1028 			goto bad;
1029 		}
1030 	}
1031 
1032 	m = nd6_dad_na_input(m, ifp, &taddr6, lladdr, lladdrlen);
1033 	if (m == NULL) {
1034 		return;
1035 	}
1036 
1037 	/* Forwarding associated with NDPRF_PRPROXY may apply. */
1038 	if (ip6_forwarding && nd6_prproxy) {
1039 		nd6_prproxy_na_input(ifp, &saddr6, &daddr6, &taddr6, flags);
1040 	}
1041 
1042 	/*
1043 	 * If no neighbor cache entry is found, NA SHOULD silently be
1044 	 * discarded.  If we are forwarding (and Scoped Routing is in
1045 	 * effect), try to see if there is a neighbor cache entry on
1046 	 * another interface (in case we are doing prefix proxying.)
1047 	 */
1048 	if ((rt = nd6_lookup(&taddr6, 0, ifp, 0)) == NULL) {
1049 		if (!ip6_forwarding || !nd6_prproxy) {
1050 			drop_reason = DROP_REASON_IP6_BAD_ND_STATE;
1051 			goto freeit;
1052 		}
1053 
1054 		if ((rt = nd6_lookup(&taddr6, 0, NULL, 0)) == NULL) {
1055 			drop_reason = DROP_REASON_IP6_BAD_ND_STATE;
1056 			goto freeit;
1057 		}
1058 
1059 		RT_LOCK_ASSERT_HELD(rt);
1060 		if (rt->rt_ifp != ifp) {
1061 			/*
1062 			 * Purge any link-layer info caching.
1063 			 */
1064 			if (rt->rt_llinfo_purge != NULL) {
1065 				rt->rt_llinfo_purge(rt);
1066 			}
1067 
1068 			/* Adjust route ref count for the interfaces */
1069 			if (rt->rt_if_ref_fn != NULL) {
1070 				rt->rt_if_ref_fn(ifp, 1);
1071 				rt->rt_if_ref_fn(rt->rt_ifp, -1);
1072 			}
1073 
1074 			/* Change the interface when the existing route is on */
1075 			rt->rt_ifp = ifp;
1076 
1077 			/*
1078 			 * If rmx_mtu is not locked, update it
1079 			 * to the MTU used by the new interface.
1080 			 */
1081 			if (!(rt->rt_rmx.rmx_locks & RTV_MTU)) {
1082 				rt->rt_rmx.rmx_mtu = rt->rt_ifp->if_mtu;
1083 			}
1084 		}
1085 	}
1086 
1087 	RT_LOCK_ASSERT_HELD(rt);
1088 	if ((ln = rt->rt_llinfo) == NULL ||
1089 	    (sdl = SDL(rt->rt_gateway)) == NULL) {
1090 		RT_REMREF_LOCKED(rt);
1091 		RT_UNLOCK(rt);
1092 		drop_reason = DROP_REASON_IP6_BAD_ND_STATE;
1093 		goto freeit;
1094 	}
1095 
1096 	timenow = net_uptime();
1097 
1098 	if (ln->ln_state == ND6_LLINFO_INCOMPLETE) {
1099 		/*
1100 		 * If the link-layer has address, and no lladdr option came,
1101 		 * discard the packet.
1102 		 */
1103 		if (ifp->if_addrlen && !lladdr) {
1104 			RT_REMREF_LOCKED(rt);
1105 			RT_UNLOCK(rt);
1106 			drop_reason = DROP_REASON_IP6_BAD_ND_STATE;
1107 			goto freeit;
1108 		}
1109 
1110 		/*
1111 		 * Record link-layer address, and update the state.
1112 		 */
1113 		sdl->sdl_alen = ifp->if_addrlen;
1114 		bcopy(lladdr, LLADDR(sdl), ifp->if_addrlen);
1115 		if (is_solicited) {
1116 			send_nc_alive_kev = (rt->rt_flags & RTF_ROUTER) ? true : false;
1117 			ND6_CACHE_STATE_TRANSITION(ln, ND6_LLINFO_REACHABLE);
1118 			if (ln->ln_expire != 0) {
1119 				struct nd_ifinfo *__single ndi = NULL;
1120 
1121 				ndi = ND_IFINFO(rt->rt_ifp);
1122 				VERIFY(ndi != NULL && ndi->initialized);
1123 				lck_mtx_lock(&ndi->lock);
1124 				ln_setexpire(ln, timenow + ndi->reachable);
1125 				lck_mtx_unlock(&ndi->lock);
1126 				RT_UNLOCK(rt);
1127 				lck_mtx_lock(rnh_lock);
1128 				nd6_sched_timeout(NULL, NULL);
1129 				lck_mtx_unlock(rnh_lock);
1130 				RT_LOCK(rt);
1131 			}
1132 		} else {
1133 			ND6_CACHE_STATE_TRANSITION(ln, ND6_LLINFO_STALE);
1134 			ln_setexpire(ln, timenow + nd6_gctimer);
1135 		}
1136 
1137 		/*
1138 		 * Enqueue work item to invoke callback for this
1139 		 * route entry
1140 		 */
1141 		route_event_enqueue_nwk_wq_entry(rt, NULL,
1142 		    ROUTE_LLENTRY_RESOLVED, NULL, TRUE);
1143 
1144 		if ((ln->ln_router = (short)is_router) != 0) {
1145 			struct radix_node_head  *__single rnh = NULL;
1146 			struct in6_addr rt_addr = SIN6(rt_key(rt))->sin6_addr;
1147 			ifnet_ref_t rt_ifp = rt->rt_ifp;
1148 
1149 			struct route_event rt_ev;
1150 			route_event_init(&rt_ev, rt, NULL, ROUTE_LLENTRY_RESOLVED);
1151 			/*
1152 			 * This means a router's state has changed from
1153 			 * non-reachable to probably reachable, and might
1154 			 * affect the status of associated prefixes..
1155 			 * We already have a reference on rt. Don't need to
1156 			 * take one for the unlock/lock.
1157 			 */
1158 			RT_UNLOCK(rt);
1159 			defrouter_set_reachability(&rt_addr, rt_ifp, TRUE);
1160 			lck_mtx_lock(rnh_lock);
1161 			rnh = rt_tables[AF_INET6];
1162 
1163 			if (rnh != NULL) {
1164 				(void) rnh->rnh_walktree(rnh, route_event_walktree,
1165 				    (void *)&rt_ev);
1166 			}
1167 			lck_mtx_unlock(rnh_lock);
1168 			lck_mtx_lock(nd6_mutex);
1169 			pfxlist_onlink_check();
1170 			lck_mtx_unlock(nd6_mutex);
1171 			RT_LOCK(rt);
1172 		}
1173 	} else {
1174 		int llchange = 0;
1175 
1176 		/*
1177 		 * Check if the link-layer address has changed or not.
1178 		 */
1179 		if (lladdr == NULL) {
1180 			llchange = 0;
1181 		} else {
1182 			if (sdl->sdl_alen) {
1183 				if (bcmp(lladdr, LLADDR(sdl), ifp->if_addrlen)) {
1184 					llchange = 1;
1185 				} else {
1186 					llchange = 0;
1187 				}
1188 			} else {
1189 				llchange = 1;
1190 			}
1191 		}
1192 
1193 		/*
1194 		 * This is VERY complex. Look at it with care.
1195 		 *
1196 		 * override solicit lladdr llchange	action
1197 		 *					(L: record lladdr)
1198 		 *
1199 		 *	0	0	n	--	(2c)
1200 		 *	0	0	y	n	(2b) L
1201 		 *	0	0	y	y	(1)    REACHABLE->STALE
1202 		 *	0	1	n	--	(2c)   *->REACHABLE
1203 		 *	0	1	y	n	(2b) L *->REACHABLE
1204 		 *	0	1	y	y	(1)    REACHABLE->STALE
1205 		 *	1	0	n	--	(2a)
1206 		 *	1	0	y	n	(2a) L
1207 		 *	1	0	y	y	(2a) L *->STALE
1208 		 *	1	1	n	--	(2a)   *->REACHABLE
1209 		 *	1	1	y	n	(2a) L *->REACHABLE
1210 		 *	1	1	y	y	(2a) L *->REACHABLE
1211 		 */
1212 		if (!is_override && (lladdr != NULL && llchange)) {  /* (1) */
1213 			/*
1214 			 * If state is REACHABLE, make it STALE.
1215 			 * no other updates should be done.
1216 			 */
1217 			if (ln->ln_state == ND6_LLINFO_REACHABLE) {
1218 				ND6_CACHE_STATE_TRANSITION(ln, ND6_LLINFO_STALE);
1219 				ln_setexpire(ln, timenow + nd6_gctimer);
1220 			}
1221 			RT_REMREF_LOCKED(rt);
1222 			RT_UNLOCK(rt);
1223 			drop_reason = DROP_REASON_IP6_BAD_ND_STATE;
1224 			goto freeit;
1225 		} else if (is_override                             /* (2a) */
1226 		    || (!is_override && (lladdr && !llchange))     /* (2b) */
1227 		    || !lladdr) {                                  /* (2c) */
1228 			/*
1229 			 * Update link-local address, if any.
1230 			 */
1231 			if (lladdr) {
1232 				sdl->sdl_alen = ifp->if_addrlen;
1233 				bcopy(lladdr, LLADDR(sdl), ifp->if_addrlen);
1234 			}
1235 
1236 			/*
1237 			 * If solicited, make the state REACHABLE.
1238 			 * If not solicited and the link-layer address was
1239 			 * changed, make it STALE.
1240 			 */
1241 			if (is_solicited) {
1242 				ND6_CACHE_STATE_TRANSITION(ln, ND6_LLINFO_REACHABLE);
1243 				if (ln->ln_expire != 0) {
1244 					struct nd_ifinfo *__single ndi = NULL;
1245 
1246 					ndi = ND_IFINFO(ifp);
1247 					VERIFY(ndi != NULL && ndi->initialized);
1248 					lck_mtx_lock(&ndi->lock);
1249 					ln_setexpire(ln,
1250 					    timenow + ndi->reachable);
1251 					lck_mtx_unlock(&ndi->lock);
1252 					RT_UNLOCK(rt);
1253 					lck_mtx_lock(rnh_lock);
1254 					nd6_sched_timeout(NULL, NULL);
1255 					lck_mtx_unlock(rnh_lock);
1256 					RT_LOCK(rt);
1257 				}
1258 			} else {
1259 				if (lladdr && llchange) {
1260 					ND6_CACHE_STATE_TRANSITION(ln, ND6_LLINFO_STALE);
1261 					ln_setexpire(ln, timenow + nd6_gctimer);
1262 				}
1263 			}
1264 
1265 			/*
1266 			 * XXX
1267 			 * The above is somewhat convoluted, for now just
1268 			 * issue a callback for LLENTRY changed.
1269 			 */
1270 			/* Enqueue work item to invoke callback for this route entry */
1271 			if (llchange) {
1272 				route_event_enqueue_nwk_wq_entry(rt, NULL,
1273 				    ROUTE_LLENTRY_CHANGED, NULL, TRUE);
1274 			}
1275 
1276 			/*
1277 			 * If the router's link-layer address has changed,
1278 			 * notify routes using this as gateway so they can
1279 			 * update any cached information.
1280 			 */
1281 			if (ln->ln_router && is_router && llchange) {
1282 				struct radix_node_head *__single rnh = NULL;
1283 				struct in6_addr rt_addr = SIN6(rt_key(rt))->sin6_addr;
1284 				ifnet_ref_t rt_ifp = rt->rt_ifp;
1285 				struct route_event rt_ev;
1286 				route_event_init(&rt_ev, rt, NULL, ROUTE_LLENTRY_CHANGED);
1287 
1288 				/*
1289 				 * This means a router's state has changed from
1290 				 * non-reachable to probably reachable, and might
1291 				 * affect the status of associated prefixes..
1292 				 *
1293 				 * We already have a valid rt reference here.
1294 				 * We don't need to take another one for unlock/lock.
1295 				 */
1296 				RT_UNLOCK(rt);
1297 				defrouter_set_reachability(&rt_addr, rt_ifp, TRUE);
1298 				lck_mtx_lock(rnh_lock);
1299 				rnh = rt_tables[AF_INET6];
1300 
1301 				if (rnh != NULL) {
1302 					(void) rnh->rnh_walktree(rnh, route_event_walktree,
1303 					    (void *)&rt_ev);
1304 				}
1305 				lck_mtx_unlock(rnh_lock);
1306 				RT_LOCK(rt);
1307 			}
1308 		}
1309 
1310 		if (ln->ln_router && !is_router) {
1311 			/*
1312 			 * The peer dropped the router flag.
1313 			 * Remove the sender from the Default Router List and
1314 			 * update the Destination Cache entries.
1315 			 */
1316 			struct nd_defrouter *__single dr;
1317 			struct in6_addr *__single in6;
1318 			ifnet_ref_t rt_ifp = rt->rt_ifp;
1319 
1320 			in6 = &SIN6(rt_key(rt))->sin6_addr;
1321 
1322 			RT_UNLOCK(rt);
1323 			lck_mtx_lock(nd6_mutex);
1324 			/*
1325 			 * XXX Handle router lists for route information option
1326 			 * as well.
1327 			 */
1328 			dr = defrouter_lookup(NULL, in6, rt_ifp);
1329 			if (dr) {
1330 				TAILQ_REMOVE(&nd_defrouter_list, dr, dr_entry);
1331 				defrtrlist_del(dr, NULL);
1332 				NDDR_REMREF(dr);        /* remove list reference */
1333 				NDDR_REMREF(dr);
1334 				lck_mtx_unlock(nd6_mutex);
1335 			} else {
1336 				lck_mtx_unlock(nd6_mutex);
1337 				/*
1338 				 * Even if the neighbor is not in the
1339 				 * default router list, the neighbor
1340 				 * may be used as a next hop for some
1341 				 * destinations (e.g. redirect case).
1342 				 * So we must call rt6_flush explicitly.
1343 				 */
1344 				rt6_flush(&ip6->ip6_src, rt_ifp);
1345 			}
1346 			RT_LOCK(rt);
1347 		}
1348 		ln->ln_router = (short)is_router;
1349 	}
1350 
1351 	if (send_nc_alive_kev && (ifp->if_addrlen == IF_LLREACH_MAXLEN)) {
1352 		struct kev_msg ev_msg;
1353 		struct kev_nd6_ndalive nd6_ndalive;
1354 		bzero(&ev_msg, sizeof(ev_msg));
1355 		bzero(&nd6_ndalive, sizeof(nd6_ndalive));
1356 		ev_msg.vendor_code      = KEV_VENDOR_APPLE;
1357 		ev_msg.kev_class        = KEV_NETWORK_CLASS;
1358 		ev_msg.kev_subclass     = KEV_ND6_SUBCLASS;
1359 		ev_msg.event_code       = KEV_ND6_NDALIVE;
1360 
1361 		nd6_ndalive.link_data.if_family = ifp->if_family;
1362 		nd6_ndalive.link_data.if_unit = ifp->if_unit;
1363 		strlcpy(nd6_ndalive.link_data.if_name,
1364 		    ifp->if_name,
1365 		    sizeof(nd6_ndalive.link_data.if_name));
1366 		ev_msg.dv[0].data_ptr = &nd6_ndalive;
1367 		ev_msg.dv[0].data_length =
1368 		    sizeof(nd6_ndalive);
1369 		dlil_post_complete_msg(NULL, &ev_msg);
1370 	}
1371 
1372 	RT_LOCK_ASSERT_HELD(rt);
1373 	rt->rt_flags &= ~RTF_REJECT;
1374 
1375 	/* cache the gateway (sender HW) address */
1376 	nd6_llreach_alloc(rt, ifp, LLADDR(sdl), sdl->sdl_alen, TRUE);
1377 
1378 	/* update the llinfo, send a queued packet if there is one */
1379 	ln->ln_asked = 0;
1380 	if (ln->ln_hold != NULL) {
1381 		mbuf_ref_t m_hold, m_hold_next;
1382 		struct sockaddr_in6 sin6;
1383 
1384 		rtkey_to_sa6(rt, &sin6);
1385 		/*
1386 		 * reset the ln_hold in advance, to explicitly
1387 		 * prevent a ln_hold lookup in nd6_output()
1388 		 * (wouldn't happen, though...)
1389 		 */
1390 		m_hold = ln->ln_hold;
1391 		ln->ln_hold = NULL;
1392 		for (; m_hold; m_hold = m_hold_next) {
1393 			m_hold_next = m_hold->m_nextpkt;
1394 			m_hold->m_nextpkt = NULL;
1395 			/*
1396 			 * we assume ifp is not a loopback here, so just set
1397 			 * the 2nd argument as the 1st one.
1398 			 */
1399 			RT_UNLOCK(rt);
1400 			nd6_output(ifp, ifp, m_hold, &sin6, rt, NULL);
1401 			RT_LOCK_SPIN(rt);
1402 		}
1403 	}
1404 	RT_REMREF_LOCKED(rt);
1405 	RT_UNLOCK(rt);
1406 	m_freem(m);
1407 	return;
1408 
1409 bad:
1410 	icmp6stat.icp6s_badna++;
1411 	/* fall through */
1412 
1413 freeit:
1414 	m_drop(m, DROPTAP_FLAG_DIR_IN | DROPTAP_FLAG_L2_MISSING, drop_reason, NULL, 0);
1415 	return;
1416 }
1417 
1418 /*
1419  * Neighbor advertisement output handling.
1420  *
1421  * Based on RFC 2461
1422  *
1423  * the following items are not implemented yet:
1424  * - proxy advertisement delay rule (RFC2461 7.2.8, last paragraph, SHOULD)
1425  * - anycast advertisement delay rule (RFC2461 7.2.7, SHOULD)
1426  *
1427  * tlladdr - 1 if include target link-layer address
1428  * sdl0 - sockaddr_dl (= proxy NA) or NULL
1429  */
1430 void
nd6_na_output(struct ifnet * ifp,const struct in6_addr * daddr6_0,const struct in6_addr * taddr6,uint32_t flags,int tlladdr,struct sockaddr * sdl0)1431 nd6_na_output(
1432 	struct ifnet *ifp,
1433 	const struct in6_addr *daddr6_0,
1434 	const struct in6_addr *taddr6,
1435 	uint32_t flags,
1436 	int tlladdr,            /* 1 if include target link-layer address */
1437 	struct sockaddr *sdl0)  /* sockaddr_dl (= proxy NA) or NULL */
1438 {
1439 	mbuf_ref_t m;
1440 	struct ip6_hdr *ip6;
1441 	struct nd_neighbor_advert *nd_na;
1442 	struct ip6_moptions *__single im6o = NULL;
1443 	caddr_t mac = NULL;
1444 	struct route_in6 ro;
1445 	struct in6_addr *__single src;
1446 	struct in6_addr src_storage, daddr6;
1447 	struct in6_ifaddr *__single ia;
1448 	struct sockaddr_in6 dst_sa;
1449 	int icmp6len, maxlen, error;
1450 	ifnet_ref_t outif = NULL;
1451 
1452 	struct ip6_out_args ip6oa;
1453 	bzero(&ro, sizeof(ro));
1454 
1455 	daddr6 = *daddr6_0;     /* make a local copy for modification */
1456 
1457 	bzero(&ip6oa, sizeof(ip6oa));
1458 	ip6oa.ip6oa_boundif = ifp->if_index;
1459 	ip6oa.ip6oa_flags = IP6OAF_SELECT_SRCIF | IP6OAF_BOUND_SRCADDR |
1460 	    IP6OAF_AWDL_UNRESTRICTED | IP6OAF_INTCOPROC_ALLOWED |
1461 	    IP6OAF_MANAGEMENT_ALLOWED;
1462 	ip6oa.ip6oa_sotc = SO_TC_UNSPEC;
1463 	ip6oa.ip6oa_netsvctype = _NET_SERVICE_TYPE_UNSPEC;
1464 
1465 	ip6oa.ip6oa_flags |= IP6OAF_BOUND_IF;
1466 
1467 	/* estimate the size of message */
1468 	maxlen = sizeof(*ip6) + sizeof(*nd_na);
1469 	maxlen += (sizeof(struct nd_opt_hdr) + ifp->if_addrlen + 7) & ~7;
1470 	if (max_linkhdr + maxlen >= MCLBYTES) {
1471 #if DIAGNOSTIC
1472 		printf("nd6_na_output: max_linkhdr + maxlen >= MCLBYTES "
1473 		    "(%d + %d > %d)\n", max_linkhdr, maxlen, MCLBYTES);
1474 #endif
1475 		return;
1476 	}
1477 
1478 	MGETHDR(m, M_DONTWAIT, MT_DATA);        /* XXXMAC: mac_create_mbuf_linklayer() probably */
1479 	if (m && max_linkhdr + maxlen >= MHLEN) {
1480 		MCLGET(m, M_DONTWAIT);
1481 		if ((m->m_flags & M_EXT) == 0) {
1482 			m_free(m);
1483 			m = NULL;
1484 		}
1485 	}
1486 	if (m == NULL) {
1487 		return;
1488 	}
1489 	m->m_pkthdr.rcvif = NULL;
1490 
1491 	if (IN6_IS_ADDR_MULTICAST(&daddr6)) {
1492 		m->m_flags |= M_MCAST;
1493 
1494 		im6o = ip6_allocmoptions(Z_NOWAIT);
1495 		if (im6o == NULL) {
1496 			m_freem(m);
1497 			return;
1498 		}
1499 
1500 		im6o->im6o_multicast_ifp = ifp;
1501 		im6o->im6o_multicast_hlim = IPV6_MAXHLIM;
1502 		im6o->im6o_multicast_loop = 0;
1503 	}
1504 
1505 	icmp6len = sizeof(*nd_na);
1506 	m->m_pkthdr.len = m->m_len = sizeof(struct ip6_hdr) + icmp6len;
1507 	m->m_data += max_linkhdr;       /* or MH_ALIGN() equivalent? */
1508 
1509 	/* fill neighbor advertisement packet */
1510 	ip6 = mtod(m, struct ip6_hdr *);
1511 	ip6->ip6_flow = 0;
1512 	ip6->ip6_vfc &= ~IPV6_VERSION_MASK;
1513 	ip6->ip6_vfc |= IPV6_VERSION;
1514 	ip6->ip6_nxt = IPPROTO_ICMPV6;
1515 	ip6->ip6_hlim = IPV6_MAXHLIM;
1516 	if (IN6_IS_ADDR_UNSPECIFIED(&daddr6)) {
1517 		/* reply to DAD */
1518 		daddr6.s6_addr16[0] = IPV6_ADDR_INT16_MLL;
1519 		daddr6.s6_addr16[1] = 0;
1520 		daddr6.s6_addr32[1] = 0;
1521 		daddr6.s6_addr32[2] = 0;
1522 		daddr6.s6_addr32[3] = IPV6_ADDR_INT32_ONE;
1523 		if (in6_setscope(&daddr6, ifp, NULL)) {
1524 			m_drop(m, DROPTAP_FLAG_DIR_OUT | DROPTAP_FLAG_L2_MISSING, DROP_REASON_IP6_BAD_SCOPE, NULL, 0);
1525 			goto exit;
1526 		}
1527 
1528 		flags &= ~ND_NA_FLAG_SOLICITED;
1529 	} else {
1530 		ip6->ip6_dst = daddr6;
1531 		ip6_output_setdstifscope(m, ifp->if_index, NULL);
1532 	}
1533 
1534 	SOCKADDR_ZERO(&dst_sa, sizeof(struct sockaddr_in6));
1535 	dst_sa.sin6_family = AF_INET6;
1536 	dst_sa.sin6_len = sizeof(struct sockaddr_in6);
1537 	dst_sa.sin6_addr = daddr6;
1538 
1539 	/*
1540 	 * Select a source whose scope is the same as that of the dest.
1541 	 */
1542 	SOCKADDR_COPY(&dst_sa, &ro.ro_dst, sizeof(dst_sa));
1543 	src = in6_selectsrc(&dst_sa, NULL, NULL, &ro, NULL, &src_storage,
1544 	    ip6oa.ip6oa_boundif, &error);
1545 	if (src == NULL) {
1546 		nd6log(info, "nd6_na_output: source can't be "
1547 		    "determined: dst=%s, error=%d\n",
1548 		    ip6_sprintf(&dst_sa.sin6_addr), error);
1549 		m_drop(m, DROPTAP_FLAG_DIR_IN | DROPTAP_FLAG_L2_MISSING, DROP_REASON_IP6_BAD_ND_STATE, NULL, 0);
1550 		goto exit;
1551 	}
1552 	ip6->ip6_src = *src;
1553 
1554 	/*
1555 	 * RFC 4429 requires not setting "override" flag on NA packets sent
1556 	 * from optimistic addresses.
1557 	 */
1558 	ia = in6ifa_ifpwithaddr(ifp, src);
1559 	ip6_output_setsrcifscope(m, ifp->if_index, ia);
1560 	if (ia != NULL) {
1561 		if (ia->ia6_flags & IN6_IFF_OPTIMISTIC) {
1562 			flags &= ~ND_NA_FLAG_OVERRIDE;
1563 		}
1564 		ifa_remref(&ia->ia_ifa);
1565 	}
1566 
1567 	nd_na = (struct nd_neighbor_advert *)(ip6 + 1);
1568 	nd_na->nd_na_type = ND_NEIGHBOR_ADVERT;
1569 	nd_na->nd_na_code = 0;
1570 	nd_na->nd_na_target = *taddr6;
1571 	in6_clearscope(&nd_na->nd_na_target); /* XXX */
1572 
1573 	/*
1574 	 * "tlladdr" indicates NS's condition for adding tlladdr or not.
1575 	 * see nd6_ns_input() for details.
1576 	 * Basically, if NS packet is sent to unicast/anycast addr,
1577 	 * target lladdr option SHOULD NOT be included.
1578 	 */
1579 	if (tlladdr) {
1580 		/*
1581 		 * sdl0 != NULL indicates proxy NA.  If we do proxy, use
1582 		 * lladdr in sdl0.  If we are not proxying (sending NA for
1583 		 * my address) use lladdr configured for the interface.
1584 		 */
1585 		if (sdl0 == NULL) {
1586 			mac = nd6_ifptomac(ifp);
1587 		} else if (sdl0->sa_family == AF_LINK) {
1588 			struct sockaddr_dl *sdl;
1589 			sdl = SDL(sdl0);
1590 			if (sdl->sdl_alen == ifp->if_addrlen) {
1591 				mac = LLADDR(sdl);
1592 			}
1593 		}
1594 	}
1595 	if (tlladdr && mac) {
1596 		int optlen = sizeof(struct nd_opt_hdr) + ifp->if_addrlen;
1597 		struct nd_opt_hdr *nd_opt = (struct nd_opt_hdr *)(nd_na + 1);
1598 
1599 		/* roundup to 8 bytes alignment! */
1600 		optlen = (optlen + 7) & ~7;
1601 
1602 		m->m_pkthdr.len += optlen;
1603 		m->m_len += optlen;
1604 		icmp6len += optlen;
1605 		bzero((caddr_t)nd_opt, optlen);
1606 		nd_opt->nd_opt_type = ND_OPT_TARGET_LINKADDR;
1607 		nd_opt->nd_opt_len = (uint8_t)(optlen >> 3);
1608 		bcopy(mac, (caddr_t)(nd_opt + 1), ifp->if_addrlen);
1609 	} else {
1610 		flags &= ~ND_NA_FLAG_OVERRIDE;
1611 	}
1612 
1613 	ip6->ip6_plen = htons((u_short)icmp6len);
1614 	nd_na->nd_na_flags_reserved = flags;
1615 	nd_na->nd_na_cksum = 0;
1616 	nd_na->nd_na_cksum =
1617 	    in6_cksum(m, IPPROTO_ICMPV6, sizeof(struct ip6_hdr), icmp6len);
1618 
1619 	m->m_pkthdr.pkt_flags |= PKTF_INET6_RESOLVE;
1620 
1621 	if (ifp->if_eflags & IFEF_TXSTART) {
1622 		/* Use control service class if the interface supports
1623 		 * transmit-start model.
1624 		 */
1625 		(void) m_set_service_class(m, MBUF_SC_CTL);
1626 	}
1627 
1628 	ip6oa.ip6oa_flags |= IP6OAF_SKIP_PF;
1629 	ip6oa.ip6oa_flags |= IP6OAF_DONT_FRAG;
1630 	ip6_output(m, NULL, NULL, IPV6_OUTARGS, im6o, &outif, &ip6oa);
1631 	if (outif) {
1632 		icmp6_ifstat_inc(outif, ifs6_out_msg);
1633 		icmp6_ifstat_inc(outif, ifs6_out_neighboradvert);
1634 		ifnet_release(outif);
1635 	}
1636 	icmp6stat.icp6s_outhist[ND_NEIGHBOR_ADVERT]++;
1637 
1638 exit:
1639 	if (im6o != NULL) {
1640 		IM6O_REMREF(im6o);
1641 	}
1642 
1643 	ROUTE_RELEASE(&ro);
1644 }
1645 
1646 TAILQ_HEAD(dadq_head, dadq);
1647 struct dadq {
1648 	decl_lck_mtx_data(, dad_lock);
1649 	u_int32_t dad_refcount; /* reference count */
1650 	int dad_attached;
1651 	TAILQ_ENTRY(dadq) dad_list;
1652 	struct ifaddr *dad_ifa;
1653 	int dad_count;          /* max NS to send */
1654 	int dad_ns_tcount;      /* # of trials to send NS */
1655 	int dad_ns_ocount;      /* NS sent so far */
1656 	int dad_ns_icount;
1657 	int dad_na_icount;
1658 	int dad_ns_lcount;      /* looped back NS */
1659 	int dad_loopbackprobe;  /* probing state for loopback detection */
1660 	uint8_t dad_lladdr[ETHER_ADDR_LEN];
1661 	uint8_t dad_lladdrlen;
1662 #define ND_OPT_NONCE_LEN32 \
1663     ((ND_OPT_NONCE_LEN + sizeof(uint32_t) - 1)/sizeof(uint32_t))
1664 	uint32_t dad_nonce[ND_OPT_NONCE_LEN32];
1665 	uint32_t dad_same_nonce_count; /* # of consecutive times we've ignored DAD failure because of optimistic DAD  */
1666 };
1667 
1668 static KALLOC_TYPE_DEFINE(dad_zone, struct dadq, NET_KT_DEFAULT);
1669 static struct dadq_head dadq;
1670 
1671 void
nd6_nbr_init(void)1672 nd6_nbr_init(void)
1673 {
1674 	int i;
1675 
1676 	TAILQ_INIT(&dadq);
1677 
1678 	SOCKADDR_ZERO(&hostrtmask, sizeof hostrtmask);
1679 	hostrtmask.sin6_family = AF_INET6;
1680 	hostrtmask.sin6_len = sizeof hostrtmask;
1681 	for (i = 0; i < sizeof hostrtmask.sin6_addr; ++i) {
1682 		hostrtmask.sin6_addr.s6_addr[i] = 0xff;
1683 	}
1684 }
1685 
1686 static struct dadq *
nd6_dad_find(struct ifaddr * ifa,struct nd_opt_nonce * nonce)1687 nd6_dad_find(struct ifaddr *ifa, struct nd_opt_nonce *nonce)
1688 {
1689 	struct dadq *__single dp;
1690 	boolean_t same_nonce = false;
1691 
1692 	lck_mtx_lock(&dad6_mutex);
1693 	for (dp = dadq.tqh_first; dp; dp = dp->dad_list.tqe_next) {
1694 		DAD_LOCK_SPIN(dp);
1695 		if (dp->dad_ifa != ifa) {
1696 			DAD_UNLOCK(dp);
1697 			continue;
1698 		}
1699 
1700 		/*
1701 		 * Skip if the nonce matches the received one.
1702 		 * +2 in the length is required because of type and
1703 		 * length fields are included in a header.
1704 		 */
1705 		same_nonce = nonce != NULL &&
1706 		    nonce->nd_opt_nonce_len == (ND_OPT_NONCE_LEN + 2) / 8 &&
1707 		    memcmp(&nonce->nd_opt_nonce[0], &dp->dad_nonce[0],
1708 		    ND_OPT_NONCE_LEN) == 0;
1709 
1710 		if (same_nonce &&
1711 		    dp->dad_same_nonce_count <= nd6_dad_nonce_max_count) {
1712 			nd6log(error, "%s: a looped back NS message is "
1713 			    "detected during DAD for if=%s %s. Ignoring.\n",
1714 			    __func__,
1715 			    if_name(ifa->ifa_ifp),
1716 			    ip6_sprintf(IFA_IN6(ifa)));
1717 			dp->dad_same_nonce_count++;
1718 			dp->dad_ns_lcount++;
1719 			++ip6stat.ip6s_dad_loopcount;
1720 			DAD_UNLOCK(dp);
1721 			continue;
1722 		} else if (!same_nonce) {
1723 			// Not the same nonce, reset counter
1724 			dp->dad_same_nonce_count = 1;
1725 		}
1726 
1727 		DAD_ADDREF_LOCKED(dp);
1728 		DAD_UNLOCK(dp);
1729 		break;
1730 	}
1731 	lck_mtx_unlock(&dad6_mutex);
1732 	return dp;
1733 }
1734 
1735 void
nd6_dad_stoptimer(struct ifaddr * ifa)1736 nd6_dad_stoptimer(
1737 	struct ifaddr *ifa)
1738 {
1739 	untimeout((void (*)(void *))nd6_dad_timer, (void *)ifa);
1740 }
1741 
1742 /*
1743  * Start Duplicate Address Detection (DAD) for specified interface address.
1744  */
1745 void
nd6_dad_start(struct ifaddr * ifa,int * tick_delay)1746 nd6_dad_start(
1747 	struct ifaddr *ifa,
1748 	int *tick_delay)        /* minimum delay ticks for IFF_UP event */
1749 {
1750 	struct in6_ifaddr *__single ia = ifatoia6(ifa);
1751 	struct dadq *__single dp;
1752 
1753 	if (ifa->ifa_ifp == NULL) {
1754 		panic("nd6_dad_start: ifa->ifa_ifp == NULL");
1755 	}
1756 
1757 	nd6log2(debug, "%s - %s ifp %s ia6_flags 0x%x\n",
1758 	    __func__,
1759 	    ip6_sprintf(&ia->ia_addr.sin6_addr),
1760 	    if_name(ia->ia_ifp),
1761 	    ia->ia6_flags);
1762 
1763 	/*
1764 	 * If we don't need DAD, don't do it.
1765 	 * There are several cases:
1766 	 * - DAD is disabled (ip6_dad_count == 0)
1767 	 * - the interface address is anycast
1768 	 */
1769 	IFA_LOCK(&ia->ia_ifa);
1770 	if (!(ia->ia6_flags & IN6_IFF_DADPROGRESS)) {
1771 		nd6log0(info,
1772 		    "nd6_dad_start: not a tentative or optimistic address "
1773 		    "%s(%s)\n",
1774 		    ip6_sprintf(&ia->ia_addr.sin6_addr),
1775 		    ifa->ifa_ifp ? if_name(ifa->ifa_ifp) : "???");
1776 		IFA_UNLOCK(&ia->ia_ifa);
1777 		return;
1778 	}
1779 	if (!ip6_dad_count || (ia->ia6_flags & IN6_IFF_ANYCAST) != 0) {
1780 		ia->ia6_flags &= ~IN6_IFF_DADPROGRESS;
1781 		IFA_UNLOCK(&ia->ia_ifa);
1782 		return;
1783 	}
1784 	IFA_UNLOCK(&ia->ia_ifa);
1785 
1786 	if (!(ifa->ifa_ifp->if_flags & IFF_UP) ||
1787 	    (ifa->ifa_ifp->if_eflags & IFEF_IPV6_ND6ALT)) {
1788 		return;
1789 	}
1790 	if ((dp = nd6_dad_find(ifa, NULL)) != NULL) {
1791 		DAD_REMREF(dp);
1792 		/* DAD already in progress */
1793 		return;
1794 	}
1795 
1796 	dp = zalloc_flags(dad_zone, Z_WAITOK | Z_ZERO);
1797 	lck_mtx_init(&dp->dad_lock, &ifa_mtx_grp, &ifa_mtx_attr);
1798 
1799 	/* Callee adds one reference for us */
1800 	dp = nd6_dad_attach(dp, ifa);
1801 
1802 	nd6log0(info, "%s: starting %sDAD %sfor %s\n",
1803 	    if_name(ifa->ifa_ifp),
1804 	    (ia->ia6_flags & IN6_IFF_OPTIMISTIC) ? "optimistic " : "",
1805 	    (tick_delay == NULL) ? "immediately " : "",
1806 	    ip6_sprintf(&ia->ia_addr.sin6_addr));
1807 
1808 	/*
1809 	 * Send NS packet for DAD, ip6_dad_count times.
1810 	 * Note that we must delay the first transmission, if this is the
1811 	 * first packet to be sent from the interface after interface
1812 	 * (re)initialization.
1813 	 */
1814 	if (tick_delay == NULL) {
1815 		u_int32_t retrans;
1816 		struct nd_ifinfo *__single ndi = NULL;
1817 
1818 		nd6_dad_ns_output(dp, ifa);
1819 		ndi = ND_IFINFO(ifa->ifa_ifp);
1820 		VERIFY(ndi != NULL && ndi->initialized);
1821 		lck_mtx_lock(&ndi->lock);
1822 		retrans = ndi->retrans * hz / 1000;
1823 		lck_mtx_unlock(&ndi->lock);
1824 		timeout((void (*)(void *))nd6_dad_timer, (void *)ifa, retrans);
1825 	} else {
1826 		int ntick;
1827 
1828 		if (*tick_delay == 0) {
1829 			ntick = random() % (MAX_RTR_SOLICITATION_DELAY * hz);
1830 		} else {
1831 			ntick = *tick_delay + random() % (hz / 2);
1832 		}
1833 		*tick_delay = ntick;
1834 		timeout((void (*)(void *))nd6_dad_timer, (void *)ifa,
1835 		    ntick);
1836 	}
1837 
1838 	DAD_REMREF(dp);         /* drop our reference */
1839 }
1840 
1841 static struct dadq *
nd6_dad_attach(struct dadq * dp,struct ifaddr * ifa)1842 nd6_dad_attach(struct dadq *dp, struct ifaddr *ifa)
1843 {
1844 	lck_mtx_lock(&dad6_mutex);
1845 	DAD_LOCK(dp);
1846 	dp->dad_ifa = ifa;
1847 	ifa_addref(ifa);        /* for dad_ifa */
1848 	dp->dad_count = ip6_dad_count;
1849 	dp->dad_ns_icount = dp->dad_na_icount = 0;
1850 	dp->dad_ns_ocount = dp->dad_ns_tcount = 0;
1851 	dp->dad_ns_lcount = dp->dad_loopbackprobe = 0;
1852 	VERIFY(!dp->dad_attached);
1853 	dp->dad_same_nonce_count = 1;
1854 	dp->dad_attached = 1;
1855 	dp->dad_lladdrlen = 0;
1856 	DAD_ADDREF_LOCKED(dp);  /* for caller */
1857 	DAD_ADDREF_LOCKED(dp);  /* for dadq_head list */
1858 	TAILQ_INSERT_TAIL(&dadq, (struct dadq *)dp, dad_list);
1859 	DAD_UNLOCK(dp);
1860 	lck_mtx_unlock(&dad6_mutex);
1861 
1862 	return dp;
1863 }
1864 
1865 static void
nd6_dad_detach(struct dadq * dp,struct ifaddr * ifa)1866 nd6_dad_detach(struct dadq *dp, struct ifaddr *ifa)
1867 {
1868 	int detached;
1869 
1870 	lck_mtx_lock(&dad6_mutex);
1871 	DAD_LOCK(dp);
1872 	if ((detached = dp->dad_attached)) {
1873 		VERIFY(dp->dad_ifa == ifa);
1874 		TAILQ_REMOVE(&dadq, (struct dadq *)dp, dad_list);
1875 		dp->dad_list.tqe_next = NULL;
1876 		dp->dad_list.tqe_prev = NULL;
1877 		dp->dad_attached = 0;
1878 	}
1879 	DAD_UNLOCK(dp);
1880 	lck_mtx_unlock(&dad6_mutex);
1881 	if (detached) {
1882 		DAD_REMREF(dp);         /* drop dadq_head reference */
1883 	}
1884 }
1885 
1886 /*
1887  * terminate DAD unconditionally.  used for address removals.
1888  */
1889 void
nd6_dad_stop(struct ifaddr * ifa)1890 nd6_dad_stop(struct ifaddr *ifa)
1891 {
1892 	struct dadq *__single dp;
1893 
1894 	dp = nd6_dad_find(ifa, NULL);
1895 	if (!dp) {
1896 		/* DAD wasn't started yet */
1897 		return;
1898 	}
1899 
1900 	untimeout((void (*)(void *))nd6_dad_timer, (void *)ifa);
1901 
1902 	nd6_dad_detach(dp, ifa);
1903 	DAD_REMREF(dp);         /* drop our reference */
1904 }
1905 
1906 static void
nd6_unsol_na_output(struct ifaddr * ifa)1907 nd6_unsol_na_output(struct ifaddr *ifa)
1908 {
1909 	struct in6_ifaddr *__single ia = ifatoia6(ifa);
1910 	ifnet_ref_t ifp = ifa->ifa_ifp;
1911 	struct in6_addr saddr6, taddr6;
1912 
1913 	if ((ifp->if_flags & IFF_UP) == 0 ||
1914 	    (ifp->if_flags & IFF_RUNNING) == 0 ||
1915 	    (ifp->if_eflags & IFEF_IPV6_ND6ALT) != 0) {
1916 		return;
1917 	}
1918 
1919 	IFA_LOCK_SPIN(&ia->ia_ifa);
1920 	taddr6 = ia->ia_addr.sin6_addr;
1921 	IFA_UNLOCK(&ia->ia_ifa);
1922 	if (in6_setscope(&taddr6, ifp, NULL) != 0) {
1923 		return;
1924 	}
1925 	saddr6 = in6addr_linklocal_allnodes;
1926 	if (in6_setscope(&saddr6, ifp, NULL) != 0) {
1927 		return;
1928 	}
1929 
1930 	nd6log(info, "%s: sending unsolicited NA\n",
1931 	    if_name(ifa->ifa_ifp));
1932 
1933 	nd6_na_output(ifp, &saddr6, &taddr6, ND_NA_FLAG_OVERRIDE, 1, NULL);
1934 }
1935 
1936 static void
nd6_dad_timer(struct ifaddr * ifa)1937 nd6_dad_timer(struct ifaddr *ifa)
1938 {
1939 	struct in6_ifaddr *__single ia = ifatoia6(ifa);
1940 	struct dadq *__single dp = NULL;
1941 	struct nd_ifinfo *ndi = NULL;
1942 	u_int32_t retrans;
1943 
1944 	/* Sanity check */
1945 	if (ia == NULL) {
1946 		nd6log0(error, "nd6_dad_timer: called with null parameter\n");
1947 		goto done;
1948 	}
1949 
1950 	nd6log2(debug, "%s - %s ifp %s ia6_flags 0x%x\n",
1951 	    __func__,
1952 	    ip6_sprintf(&ia->ia_addr.sin6_addr),
1953 	    if_name(ia->ia_ifp),
1954 	    ia->ia6_flags);
1955 
1956 	dp = nd6_dad_find(ifa, NULL);
1957 	if (dp == NULL) {
1958 		nd6log0(error, "nd6_dad_timer: DAD structure not found\n");
1959 		goto done;
1960 	}
1961 	IFA_LOCK(&ia->ia_ifa);
1962 	if (ia->ia6_flags & IN6_IFF_DUPLICATED) {
1963 		nd6log0(error, "nd6_dad_timer: called with duplicated address "
1964 		    "%s(%s)\n",
1965 		    ip6_sprintf(&ia->ia_addr.sin6_addr),
1966 		    ifa->ifa_ifp ? if_name(ifa->ifa_ifp) : "???");
1967 		IFA_UNLOCK(&ia->ia_ifa);
1968 		goto done;
1969 	}
1970 	if ((ia->ia6_flags & IN6_IFF_DADPROGRESS) == 0) {
1971 		nd6log0(error, "nd6_dad_timer: not a tentative or optimistic "
1972 		    "address %s(%s)\n",
1973 		    ip6_sprintf(&ia->ia_addr.sin6_addr),
1974 		    ifa->ifa_ifp ? if_name(ifa->ifa_ifp) : "???");
1975 		IFA_UNLOCK(&ia->ia_ifa);
1976 		goto done;
1977 	}
1978 	IFA_UNLOCK(&ia->ia_ifa);
1979 
1980 	/* timeouted with IFF_{RUNNING,UP} check */
1981 	DAD_LOCK(dp);
1982 	if (dp->dad_ns_tcount > dad_maxtry) {
1983 		DAD_UNLOCK(dp);
1984 		nd6log0(info, "%s: could not run DAD, driver problem?\n",
1985 		    if_name(ifa->ifa_ifp));
1986 
1987 		nd6_dad_detach(dp, ifa);
1988 		goto done;
1989 	}
1990 
1991 	/* Need more checks? */
1992 	if (dp->dad_ns_ocount < dp->dad_count) {
1993 		DAD_UNLOCK(dp);
1994 		/*
1995 		 * We have more NS to go.  Send NS packet for DAD.
1996 		 */
1997 		nd6_dad_ns_output(dp, ifa);
1998 		ndi = ND_IFINFO(ifa->ifa_ifp);
1999 		VERIFY(ndi != NULL && ndi->initialized);
2000 		lck_mtx_lock(&ndi->lock);
2001 		retrans = ndi->retrans * hz / 1000;
2002 		lck_mtx_unlock(&ndi->lock);
2003 		timeout((void (*)(void *))nd6_dad_timer, (void *)ifa, retrans);
2004 	} else {
2005 		/*
2006 		 * We have transmitted sufficient number of DAD packets.
2007 		 * See what we've got.
2008 		 */
2009 		if (dp->dad_na_icount > 0 || dp->dad_ns_icount) {
2010 			/* We've seen NS or NA, means DAD has failed. */
2011 			DAD_UNLOCK(dp);
2012 			nd6log0(info,
2013 			    "%s: duplicate IPv6 address %s if:%s [timer]\n",
2014 			    __func__, ip6_sprintf(&ia->ia_addr.sin6_addr),
2015 			    if_name(ia->ia_ifp));
2016 			nd6_dad_duplicated(ifa);
2017 			/* (*dp) will be freed in nd6_dad_duplicated() */
2018 #if SKYWALK
2019 			SK_NXS_MS_IF_ADDR_GENCNT_INC(ia->ia_ifp);
2020 #endif /* SKYWALK */
2021 		} else if (dad_enhanced != 0 &&
2022 		    dp->dad_ns_lcount > 0 &&
2023 		    dp->dad_ns_lcount > dp->dad_loopbackprobe &&
2024 		    dp->dad_same_nonce_count > 0 &&
2025 		    dp->dad_same_nonce_count > nd6_dad_nonce_max_count) {
2026 			dp->dad_loopbackprobe = dp->dad_ns_lcount;
2027 			dp->dad_count =
2028 			    dp->dad_ns_ocount + dad_maxtry - 1;
2029 			DAD_UNLOCK(dp);
2030 			ndi = ND_IFINFO(ifa->ifa_ifp);
2031 			VERIFY(ndi != NULL && ndi->initialized);
2032 			lck_mtx_lock(&ndi->lock);
2033 			retrans = ndi->retrans * hz / 1000;
2034 			lck_mtx_unlock(&ndi->lock);
2035 
2036 			/*
2037 			 * Sec. 4.1 in RFC 7527 requires transmission of
2038 			 * additional probes until the loopback condition
2039 			 * becomes clear when a looped back probe is detected.
2040 			 */
2041 			nd6log0(info,
2042 			    "%s: a looped back NS message is detected during DAD for %s. Another DAD probe is being sent on interface %s.\n",
2043 			    __func__, ip6_sprintf(&ia->ia_addr.sin6_addr),
2044 			    if_name(ia->ia_ifp));
2045 			/*
2046 			 * Send an NS immediately and increase dad_count by
2047 			 * nd6_mmaxtries - 1.
2048 			 */
2049 			nd6_dad_ns_output(dp, ifa);
2050 			timeout((void (*)(void *))nd6_dad_timer, (void *)ifa, retrans);
2051 			goto done;
2052 		} else {
2053 			boolean_t txunsolna;
2054 			DAD_UNLOCK(dp);
2055 			/*
2056 			 * We are done with DAD.  No NA came, no NS came.
2057 			 * No duplicate address found.
2058 			 */
2059 			IFA_LOCK_SPIN(&ia->ia_ifa);
2060 			ia->ia6_flags &= ~IN6_IFF_DADPROGRESS;
2061 			IFA_UNLOCK(&ia->ia_ifa);
2062 
2063 			ndi = ND_IFINFO(ifa->ifa_ifp);
2064 			VERIFY(ndi != NULL && ndi->initialized);
2065 			lck_mtx_lock(&ndi->lock);
2066 			txunsolna = (ndi->flags & ND6_IFF_REPLICATED) != 0;
2067 			lck_mtx_unlock(&ndi->lock);
2068 
2069 			if (txunsolna) {
2070 				nd6_unsol_na_output(ifa);
2071 			}
2072 
2073 			nd6log0(info,
2074 			    "%s: DAD complete for %s - no duplicates found %s\n",
2075 			    if_name(ifa->ifa_ifp),
2076 			    ip6_sprintf(&ia->ia_addr.sin6_addr),
2077 			    txunsolna ? ", tx unsolicited NA with O=1" : ".");
2078 
2079 			if (dp->dad_ns_lcount > 0) {
2080 				nd6log0(info,
2081 				    "%s: DAD completed while "
2082 				    "a looped back NS message is detected "
2083 				    "during DAD for %s om interface %s\n",
2084 				    __func__,
2085 				    ip6_sprintf(&ia->ia_addr.sin6_addr),
2086 				    if_name(ia->ia_ifp));
2087 			}
2088 
2089 			in6_post_msg(ia->ia_ifp, KEV_INET6_NEW_USER_ADDR, ia,
2090 			    dp->dad_lladdr, ETHER_ADDR_LEN);
2091 			nd6_dad_detach(dp, ifa);
2092 #if SKYWALK
2093 			SK_NXS_MS_IF_ADDR_GENCNT_INC(ia->ia_ifp);
2094 #endif /* SKYWALK */
2095 		}
2096 	}
2097 
2098 done:
2099 	if (dp != NULL) {
2100 		DAD_REMREF(dp);         /* drop our reference */
2101 	}
2102 }
2103 
2104 static void
nd6_dad_duplicated(struct ifaddr * ifa)2105 nd6_dad_duplicated(struct ifaddr *ifa)
2106 {
2107 	struct in6_ifaddr *__single ia = ifatoia6(ifa);
2108 	struct dadq *__single dp;
2109 	ifnet_ref_t ifp = ifa->ifa_ifp;
2110 	boolean_t candisable;
2111 
2112 	dp = nd6_dad_find(ifa, NULL);
2113 	if (dp == NULL) {
2114 		log(LOG_ERR, "%s: DAD structure not found.\n", __func__);
2115 		return;
2116 	}
2117 	IFA_LOCK(&ia->ia_ifa);
2118 	DAD_LOCK(dp);
2119 	nd6log(error, "%s: NS in/out/loopback=%d/%d/%d, NA in=%d\n",
2120 	    __func__, dp->dad_ns_icount, dp->dad_ns_ocount, dp->dad_ns_lcount,
2121 	    dp->dad_na_icount);
2122 	candisable = FALSE;
2123 
2124 	if (IN6_IS_ADDR_LINKLOCAL(&ia->ia_addr.sin6_addr) &&
2125 	    !(ia->ia6_flags & IN6_IFF_SECURED)) {
2126 		struct in6_addr in6;
2127 		struct ifaddr *__single llifa = NULL;
2128 		struct sockaddr_dl *sdl = NULL;
2129 		uint8_t *lladdr = dp->dad_lladdr;
2130 		uint8_t lladdrlen = dp->dad_lladdrlen;
2131 
2132 		/*
2133 		 * To avoid over-reaction, we only apply this logic when we are
2134 		 * very sure that hardware addresses are supposed to be unique.
2135 		 */
2136 		switch (ifp->if_type) {
2137 		case IFT_BRIDGE:
2138 		case IFT_ETHER:
2139 		case IFT_FDDI:
2140 		case IFT_ATM:
2141 		case IFT_IEEE1394:
2142 #ifdef IFT_IEEE80211
2143 		case IFT_IEEE80211:
2144 #endif
2145 			/*
2146 			 * Check if our hardware address matches the
2147 			 * link layer information received in the
2148 			 * NS/NA
2149 			 */
2150 			llifa = ifp->if_lladdr;
2151 			IFA_LOCK(llifa);
2152 			sdl = SDL(llifa->ifa_addr);
2153 			if (lladdrlen == sdl->sdl_alen &&
2154 			    bcmp(lladdr, LLADDR(sdl), lladdrlen) == 0) {
2155 				candisable = TRUE;
2156 			}
2157 			IFA_UNLOCK(llifa);
2158 
2159 			in6 = ia->ia_addr.sin6_addr;
2160 			if (in6_iid_from_hw(ifp, &in6) != 0) {
2161 				break;
2162 			}
2163 
2164 			/* Refine decision about whether IPv6 can be disabled */
2165 			if (candisable &&
2166 			    !IN6_ARE_ADDR_EQUAL(&ia->ia_addr.sin6_addr, &in6)) {
2167 				/*
2168 				 * Apply this logic only to the embedded MAC
2169 				 * address form of link-local IPv6 address.
2170 				 */
2171 				candisable = FALSE;
2172 			} else if (lladdr == NULL &&
2173 			    IN6_ARE_ADDR_EQUAL(&ia->ia_addr.sin6_addr, &in6)) {
2174 				/*
2175 				 * We received a NA with no target link-layer
2176 				 * address option. This means that someone else
2177 				 * has our address. Mark it as a hardware
2178 				 * duplicate so we disable IPv6 later on.
2179 				 */
2180 				candisable = TRUE;
2181 			}
2182 			break;
2183 		default:
2184 			break;
2185 		}
2186 	}
2187 	DAD_UNLOCK(dp);
2188 
2189 	ia->ia6_flags &= ~IN6_IFF_DADPROGRESS;
2190 	ia->ia6_flags |= IN6_IFF_DUPLICATED;
2191 	in6_event_enqueue_nwk_wq_entry(IN6_ADDR_MARKED_DUPLICATED,
2192 	    ia->ia_ifa.ifa_ifp, &ia->ia_addr.sin6_addr,
2193 	    0);
2194 	IFA_UNLOCK(&ia->ia_ifa);
2195 
2196 	/* increment DAD collision counter */
2197 	++ip6stat.ip6s_dad_collide;
2198 
2199 	/* We are done with DAD, with duplicated address found. (failure) */
2200 	untimeout((void (*)(void *))nd6_dad_timer, (void *)ifa);
2201 
2202 	IFA_LOCK(&ia->ia_ifa);
2203 	log(LOG_ERR, "%s: DAD complete for %s - duplicate found.\n",
2204 	    if_name(ifp), ip6_sprintf(&ia->ia_addr.sin6_addr));
2205 	IFA_UNLOCK(&ia->ia_ifa);
2206 
2207 	if (candisable) {
2208 		struct nd_ifinfo *__single ndi = ND_IFINFO(ifp);
2209 		log(LOG_ERR, "%s: possible hardware address duplication "
2210 		    "detected, disabling IPv6 for interface.\n", if_name(ifp));
2211 
2212 		VERIFY((NULL != ndi) && (TRUE == ndi->initialized));
2213 		ndi->flags |= ND6_IFF_IFDISABLED;
2214 		/* Make sure to set IFEF_IPV6_DISABLED too */
2215 		nd6_if_disable(ifp, TRUE);
2216 	}
2217 
2218 	log(LOG_ERR,
2219 	    "%s: manual intervention may be required.\n",
2220 	    if_name(ifp));
2221 
2222 	/* Send an event to the configuration agent so that the
2223 	 * duplicate address will be notified to the user and will
2224 	 * be removed.
2225 	 */
2226 	in6_post_msg(ifp, KEV_INET6_NEW_USER_ADDR, ia, dp->dad_lladdr, ETHER_ADDR_LEN);
2227 	nd6_dad_detach(dp, ifa);
2228 	DAD_REMREF(dp);         /* drop our reference */
2229 }
2230 
2231 static void
nd6_dad_ns_output(struct dadq * dp,struct ifaddr * ifa)2232 nd6_dad_ns_output(struct dadq *dp, struct ifaddr *ifa)
2233 {
2234 	struct in6_ifaddr *__single ia = ifatoia6(ifa);
2235 	ifnet_ref_t ifp = ifa->ifa_ifp;
2236 	int i = 0;
2237 	struct in6_addr taddr6;
2238 
2239 	DAD_LOCK(dp);
2240 	dp->dad_ns_tcount++;
2241 	if ((ifp->if_flags & IFF_UP) == 0) {
2242 		DAD_UNLOCK(dp);
2243 		return;
2244 	}
2245 	if ((ifp->if_flags & IFF_RUNNING) == 0) {
2246 		DAD_UNLOCK(dp);
2247 		return;
2248 	}
2249 
2250 	dp->dad_ns_ocount++;
2251 	DAD_UNLOCK(dp);
2252 	IFA_LOCK_SPIN(&ia->ia_ifa);
2253 	taddr6 = ia->ia_addr.sin6_addr;
2254 	IFA_UNLOCK(&ia->ia_ifa);
2255 	if (dad_enhanced != 0 && !(ifp->if_flags & IFF_POINTOPOINT)) {
2256 		for (i = 0; i < ND_OPT_NONCE_LEN32; i++) {
2257 			dp->dad_nonce[i] = RandomULong();
2258 		}
2259 
2260 		/*
2261 		 * XXXHRS: Note that in the case that
2262 		 * DupAddrDetectTransmits > 1, multiple NS messages with
2263 		 * different nonces can be looped back in an unexpected
2264 		 * order.  The current implementation recognizes only
2265 		 * the latest nonce on the sender side.  Practically it
2266 		 * should work well in almost all cases.
2267 		 */
2268 	}
2269 	nd6_ns_output(ifp, NULL, &taddr6, NULL,
2270 	    (uint8_t *)&dp->dad_nonce[0], ND_OPT_NONCE_LEN);
2271 }
2272 
2273 /*
2274  * @brief       Called to process DAD NS
2275  *
2276  * @param       ifa is the pointer to the interface's address
2277  * @param       lladdr is source link layer information
2278  * @param       lladdrlen is source's linklayer length
2279  *
2280  * @return      void
2281  */
2282 static void
nd6_dad_ns_input(struct ifaddr * ifa,char * lladdr __sized_by (lladdrlen),int lladdrlen,struct nd_opt_nonce * ndopt_nonce)2283 nd6_dad_ns_input(struct ifaddr *ifa, char *lladdr __sized_by(lladdrlen),
2284     int lladdrlen, struct nd_opt_nonce *ndopt_nonce)
2285 {
2286 	struct dadq *__single dp;
2287 	VERIFY(ifa != NULL);
2288 
2289 	/* Ignore Nonce option when Enhanced DAD is disabled. */
2290 	if (dad_enhanced == 0) {
2291 		ndopt_nonce = NULL;
2292 	}
2293 
2294 	dp = nd6_dad_find(ifa, ndopt_nonce);
2295 	if (dp == NULL) {
2296 		return;
2297 	}
2298 
2299 	DAD_LOCK(dp);
2300 	++dp->dad_ns_icount;
2301 	if (lladdr && lladdrlen >= ETHER_ADDR_LEN) {
2302 		memcpy(dp->dad_lladdr, lladdr, ETHER_ADDR_LEN);
2303 		/* fine to truncate as it is compared against sdl_alen */
2304 		dp->dad_lladdrlen = (uint8_t)lladdrlen;
2305 	}
2306 	DAD_UNLOCK(dp);
2307 	DAD_REMREF(dp);
2308 }
2309 
2310 /*
2311  * @brief	Called to process received NA for DAD
2312  *
2313  * @param	m is the pointer to the packet's mbuf
2314  * @param	ifp is the pointer to the interface on which packet
2315  *              was receicved.
2316  * @param	taddr is pointer to target's IPv6 address
2317  * @param	lladdr is target's link layer information
2318  * @param	lladdrlen is target's linklayer length
2319  *
2320  * @return	NULL if the packet is consumed by DAD processing, else
2321  *              pointer to the mbuf.
2322  */
2323 static struct mbuf *
nd6_dad_na_input(struct mbuf * m,struct ifnet * ifp,struct in6_addr * taddr,caddr_t lladdr __counted_by (lladdrlen),int lladdrlen)2324 nd6_dad_na_input(struct mbuf *m, struct ifnet *ifp, struct in6_addr *taddr,
2325     caddr_t lladdr __counted_by(lladdrlen), int lladdrlen)
2326 {
2327 	struct ifaddr *__single ifa = NULL;
2328 	struct in6_ifaddr *__single ia = NULL;
2329 	struct dadq *__single dp = NULL;
2330 	struct nd_ifinfo *__single ndi = NULL;
2331 	boolean_t replicated;
2332 
2333 	ifa = (struct ifaddr *) in6ifa_ifpwithaddr(ifp, taddr);
2334 	if (ifa == NULL) {
2335 		return m;
2336 	}
2337 
2338 	replicated = FALSE;
2339 
2340 	/* Get the ND6_IFF_REPLICATED flag. */
2341 	ndi = ND_IFINFO(ifp);
2342 	if (ndi != NULL && ndi->initialized) {
2343 		lck_mtx_lock(&ndi->lock);
2344 		replicated = !!(ndi->flags & ND6_IFF_REPLICATED);
2345 		lck_mtx_unlock(&ndi->lock);
2346 	}
2347 
2348 	if (replicated) {
2349 		nd6log(info, "%s: ignoring duplicate NA on "
2350 		    "replicated interface %s\n", __func__, if_name(ifp));
2351 		goto done;
2352 	}
2353 
2354 	/* Lock the interface address until done (see label below). */
2355 	IFA_LOCK(ifa);
2356 	ia = ifatoia6(ifa);
2357 
2358 	if (!(ia->ia6_flags & IN6_IFF_DADPROGRESS)) {
2359 		IFA_UNLOCK(ifa);
2360 		nd6log(info, "%s: ignoring duplicate NA on "
2361 		    "%s [DAD not in progress]\n", __func__,
2362 		    if_name(ifp));
2363 		goto done;
2364 	}
2365 
2366 	/* Some sleep proxies improperly send the client's Ethernet address in
2367 	 * the target link-layer address option, so detect this by comparing
2368 	 * the L2-header source address, if we have seen it, with the target
2369 	 * address, and ignoring the NA if they don't match.
2370 	 */
2371 	if (lladdr != NULL && lladdrlen >= ETHER_ADDR_LEN) {
2372 		struct ip6aux *__single ip6a = ip6_findaux(m);
2373 		if (ip6a && (ip6a->ip6a_flags & IP6A_HASEEN) != 0 &&
2374 		    bcmp(ip6a->ip6a_ehsrc, lladdr, ETHER_ADDR_LEN) != 0) {
2375 			IFA_UNLOCK(ifa);
2376 			nd6log(error, "%s: ignoring duplicate NA on %s "
2377 			    "[eh_src != tgtlladdr]\n", __func__, if_name(ifp));
2378 			goto done;
2379 		}
2380 	}
2381 
2382 	IFA_UNLOCK(ifa);
2383 
2384 	dp = nd6_dad_find(ifa, NULL);
2385 	if (dp == NULL) {
2386 		nd6log(info, "%s: no DAD structure for %s on %s.\n",
2387 		    __func__, ip6_sprintf(taddr), if_name(ifp));
2388 		goto done;
2389 	}
2390 
2391 	DAD_LOCK_SPIN(dp);
2392 	if (lladdr != NULL && lladdrlen >= ETHER_ADDR_LEN) {
2393 		memcpy(dp->dad_lladdr, lladdr, ETHER_ADDR_LEN);
2394 		dp->dad_lladdrlen = (uint8_t)lladdrlen;
2395 	}
2396 	dp->dad_na_icount++;
2397 	DAD_UNLOCK(dp);
2398 	DAD_REMREF(dp);
2399 
2400 	/* remove the address. */
2401 	nd6log(info,
2402 	    "%s: duplicate IPv6 address %s [processing NA on %s]\n", __func__,
2403 	    ip6_sprintf(taddr), if_name(ifp));
2404 done:
2405 	IFA_LOCK_ASSERT_NOTHELD(ifa);
2406 	ifa_remref(ifa);
2407 	m_freem(m);
2408 	return NULL;
2409 }
2410 
2411 static void
dad_addref(struct dadq * dp,int locked)2412 dad_addref(struct dadq *dp, int locked)
2413 {
2414 	if (!locked) {
2415 		DAD_LOCK_SPIN(dp);
2416 	} else {
2417 		DAD_LOCK_ASSERT_HELD(dp);
2418 	}
2419 
2420 	if (++dp->dad_refcount == 0) {
2421 		panic("%s: dad %p wraparound refcnt", __func__, dp);
2422 		/* NOTREACHED */
2423 	}
2424 	if (!locked) {
2425 		DAD_UNLOCK(dp);
2426 	}
2427 }
2428 
2429 static void
dad_remref(struct dadq * dp)2430 dad_remref(struct dadq *dp)
2431 {
2432 	struct ifaddr *__single ifa;
2433 
2434 	DAD_LOCK_SPIN(dp);
2435 	if (dp->dad_refcount == 0) {
2436 		panic("%s: dad %p negative refcnt", __func__, dp);
2437 	}
2438 	--dp->dad_refcount;
2439 	if (dp->dad_refcount > 0) {
2440 		DAD_UNLOCK(dp);
2441 		return;
2442 	}
2443 	DAD_UNLOCK(dp);
2444 
2445 	if (dp->dad_attached ||
2446 	    dp->dad_list.tqe_next != NULL || dp->dad_list.tqe_prev != NULL) {
2447 		panic("%s: attached dad=%p is being freed", __func__, dp);
2448 		/* NOTREACHED */
2449 	}
2450 
2451 	if ((ifa = dp->dad_ifa) != NULL) {
2452 		ifa_remref(ifa);        /* drop dad_ifa reference */
2453 		dp->dad_ifa = NULL;
2454 	}
2455 
2456 	lck_mtx_destroy(&dp->dad_lock, &ifa_mtx_grp);
2457 	zfree(dad_zone, dp);
2458 }
2459 
2460 void
nd6_llreach_set_reachable(struct ifnet * ifp,void * __sized_by (alen)addr,unsigned int alen)2461 nd6_llreach_set_reachable(struct ifnet *ifp, void *__sized_by(alen) addr, unsigned int alen)
2462 {
2463 	/* Nothing more to do if it's disabled */
2464 	if (nd6_llreach_base == 0) {
2465 		return;
2466 	}
2467 
2468 	ifnet_llreach_set_reachable(ifp, ETHERTYPE_IPV6, addr, alen);
2469 }
2470 
2471 void
nd6_alt_node_addr_decompose(struct ifnet * ifp,struct sockaddr * sa,struct sockaddr_dl * isdl,struct sockaddr_in6 * sin6)2472 nd6_alt_node_addr_decompose(struct ifnet *ifp, struct sockaddr *sa,
2473     struct sockaddr_dl* isdl, struct sockaddr_in6 *sin6)
2474 {
2475 	static const size_t EUI64_LENGTH = 8;
2476 	struct sockaddr_dl *sdl = SDL(isdl);
2477 
2478 	VERIFY(nd6_need_cache(ifp));
2479 	VERIFY(sa);
2480 	VERIFY(sdl && (void *)sa != (void *)sdl);
2481 	VERIFY(sin6 && (void *)sa != (void *)sin6);
2482 
2483 	SOCKADDR_ZERO(sin6, sizeof(*sin6));
2484 	sin6->sin6_len = sizeof *sin6;
2485 	sin6->sin6_family = AF_INET6;
2486 
2487 	SOCKADDR_ZERO(sdl, sizeof(*sdl));
2488 	sdl->sdl_len = sizeof *sdl;
2489 	sdl->sdl_family = AF_LINK;
2490 	sdl->sdl_type = ifp->if_type;
2491 	sdl->sdl_index = ifp->if_index;
2492 	sdl->sdl_nlen = 0;
2493 
2494 	switch (sa->sa_family) {
2495 	case AF_INET6: {
2496 		struct sockaddr_in6 *__single sin6a = SIN6(sa);
2497 		struct in6_addr *__single in6 = &sin6a->sin6_addr;
2498 
2499 		VERIFY(sa->sa_len == sizeof *sin6);
2500 		if (in6->s6_addr[11] == 0xff && in6->s6_addr[12] == 0xfe) {
2501 			sdl->sdl_alen = ETHER_ADDR_LEN;
2502 			LLADDR(sdl)[0] = (in6->s6_addr[8] ^ ND6_EUI64_UBIT);
2503 			LLADDR(sdl)[1] = in6->s6_addr[9];
2504 			LLADDR(sdl)[2] = in6->s6_addr[10];
2505 			LLADDR(sdl)[3] = in6->s6_addr[13];
2506 			LLADDR(sdl)[4] = in6->s6_addr[14];
2507 			LLADDR(sdl)[5] = in6->s6_addr[15];
2508 		} else {
2509 			sdl->sdl_alen = EUI64_LENGTH;
2510 			bcopy(&in6->s6_addr[8], LLADDR(sdl), EUI64_LENGTH);
2511 		}
2512 
2513 		sdl->sdl_slen = 0;
2514 		break;
2515 	}
2516 	case AF_LINK: {
2517 		struct sockaddr_dl *sdla = SDL(sa);
2518 		struct in6_addr *__single in6 = &sin6->sin6_addr;
2519 		caddr_t lla = LLADDR(sdla);
2520 		VERIFY(sa->sa_len <= sizeof(*sdl));
2521 		SOCKADDR_COPY(sa, sdl, sa->sa_len);
2522 
2523 		sin6->sin6_scope_id = sdla->sdl_index;
2524 		if (sin6->sin6_scope_id == 0) {
2525 			sin6->sin6_scope_id = ifp->if_index;
2526 		}
2527 		in6->s6_addr[0] = 0xfe;
2528 		in6->s6_addr[1] = 0x80;
2529 		if (sdla->sdl_alen == EUI64_LENGTH) {
2530 			bcopy(lla, &in6->s6_addr[8], EUI64_LENGTH);
2531 		} else {
2532 			VERIFY(sdla->sdl_alen == ETHER_ADDR_LEN);
2533 
2534 			in6->s6_addr[8] = ((uint8_t) lla[0] ^ ND6_EUI64_UBIT);
2535 			in6->s6_addr[9] = (uint8_t) lla[1];
2536 			in6->s6_addr[10] = (uint8_t) lla[2];
2537 			in6->s6_addr[11] = 0xff;
2538 			in6->s6_addr[12] = 0xfe;
2539 			in6->s6_addr[13] = (uint8_t) lla[3];
2540 			in6->s6_addr[14] = (uint8_t) lla[4];
2541 			in6->s6_addr[15] = (uint8_t) lla[5];
2542 		}
2543 
2544 		break;
2545 	}
2546 	default:
2547 		VERIFY(false);
2548 		break;
2549 	}
2550 }
2551 
2552 int
nd6_alt_node_present(struct ifnet * ifp,struct sockaddr_in6 * sin6,struct sockaddr_dl * isdl,int32_t rssi,int lqm,int npm)2553 nd6_alt_node_present(struct ifnet *ifp, struct sockaddr_in6 *sin6,
2554     struct sockaddr_dl *isdl, int32_t rssi, int lqm, int npm)
2555 {
2556 	struct sockaddr_dl *sdl = SDL(isdl);
2557 	rtentry_ref_t rt = NULL;
2558 	struct llinfo_nd6 *__single ln = NULL;
2559 	struct if_llreach *__single lr = NULL;
2560 	int nd6_nc_updated = 0;
2561 	const uint32_t temp_embedded_id = sin6->sin6_addr.s6_addr16[1];
2562 	const uint32_t temp_ifscope_id = sin6->sin6_scope_id;
2563 
2564 	if (IN6_IS_SCOPE_LINKLOCAL(&sin6->sin6_addr)) {
2565 		if (in6_embedded_scope) {
2566 			if (temp_embedded_id == 0) {
2567 				sin6->sin6_addr.s6_addr16[1] = htons(ifp->if_index);
2568 			}
2569 		} else if (temp_ifscope_id == 0) {
2570 			sin6->sin6_scope_id = ifp->if_index;
2571 		}
2572 	}
2573 
2574 	nd6_cache_lladdr(ifp, &sin6->sin6_addr, LLADDR(sdl), sdl->sdl_alen,
2575 	    ND_NEIGHBOR_ADVERT, 0, &nd6_nc_updated);
2576 
2577 	LCK_MTX_ASSERT(rnh_lock, LCK_MTX_ASSERT_NOTOWNED);
2578 	lck_mtx_lock(rnh_lock);
2579 
2580 	rt = rtalloc1_scoped_locked(SA(sin6), 1, 0, ifp->if_index);
2581 
2582 	/* Restore the address that was passed to us */
2583 	if (in6_embedded_scope) {
2584 		if (temp_embedded_id == 0) {
2585 			sin6->sin6_addr.s6_addr16[1] = 0;
2586 		}
2587 	} else if (temp_ifscope_id == 0) {
2588 		sin6->sin6_scope_id = 0;
2589 	}
2590 
2591 	if (rt != NULL) {
2592 		RT_LOCK(rt);
2593 		VERIFY(rt->rt_flags & RTF_LLINFO);
2594 		VERIFY(rt->rt_llinfo);
2595 
2596 		ln = rt->rt_llinfo;
2597 		ND6_CACHE_STATE_TRANSITION(ln, ND6_LLINFO_REACHABLE);
2598 		ln_setexpire(ln, 0);
2599 
2600 		lr = ln->ln_llreach;
2601 		if (lr) {
2602 			IFLR_LOCK(lr);
2603 			lr->lr_rssi = rssi;
2604 			lr->lr_lqm = (int32_t) lqm;
2605 			lr->lr_npm = (int32_t) npm;
2606 			IFLR_UNLOCK(lr);
2607 		}
2608 
2609 		RT_UNLOCK(rt);
2610 		RT_REMREF(rt);
2611 	}
2612 
2613 	lck_mtx_unlock(rnh_lock);
2614 
2615 	if (rt == NULL) {
2616 		log(LOG_ERR, "%s: failed to add/update host route to %s.\n",
2617 		    __func__, ip6_sprintf(&sin6->sin6_addr));
2618 #if DEBUG || DEVELOPMENT
2619 		if (ip6_p2p_debug) {
2620 			panic("%s: failed to add/update host route to %s.\n",
2621 			    __func__, ip6_sprintf(&sin6->sin6_addr));
2622 		}
2623 #endif
2624 		return EHOSTUNREACH;
2625 	}
2626 
2627 	nd6log(info, "%s: Successfully added/updated host route to %s [lr=0x%llx]\n",
2628 	    __func__, ip6_sprintf(&sin6->sin6_addr),
2629 	    (uint64_t)VM_KERNEL_ADDRPERM(lr));
2630 	/*
2631 	 * nd6_nc_updated not set implies that nothing was updated
2632 	 * in the neighbor cache. Convey that as EEXIST to callers.
2633 	 */
2634 	if (nd6_nc_updated == 0) {
2635 		return EEXIST;
2636 	}
2637 	return 0;
2638 }
2639 
2640 int
nd6_alt_node_absent(struct ifnet * ifp,struct sockaddr_in6 * sin6,struct sockaddr_dl * sdl)2641 nd6_alt_node_absent(struct ifnet *ifp, struct sockaddr_in6 *sin6, struct sockaddr_dl *sdl)
2642 {
2643 	rtentry_ref_t rt = NULL;
2644 	int error = 0;
2645 	const uint32_t temp_embedded_id = sin6->sin6_addr.s6_addr16[1];
2646 	const uint32_t temp_ifscope_id = sin6->sin6_scope_id;
2647 
2648 	nd6log2(debug, "%s: host route to %s\n", __func__,
2649 	    ip6_sprintf(&sin6->sin6_addr));
2650 
2651 	if (IN6_IS_SCOPE_LINKLOCAL(&sin6->sin6_addr)) {
2652 		if (in6_embedded_scope) {
2653 			if (temp_embedded_id == 0) {
2654 				sin6->sin6_addr.s6_addr16[1] = htons(ifp->if_index);
2655 			}
2656 		} else if (temp_ifscope_id == 0) {
2657 			sin6->sin6_scope_id = ifp->if_index;
2658 		}
2659 	}
2660 
2661 	LCK_MTX_ASSERT(rnh_lock, LCK_MTX_ASSERT_NOTOWNED);
2662 	lck_mtx_lock(rnh_lock);
2663 
2664 	rt = rtalloc1_scoped_locked(SA(sin6), 0, 0, ifp->if_index);
2665 
2666 	/* Restore the address that was passed to us */
2667 	if (in6_embedded_scope) {
2668 		if (temp_embedded_id == 0) {
2669 			sin6->sin6_addr.s6_addr16[1] = 0;
2670 		}
2671 	} else if (temp_ifscope_id == 0) {
2672 		sin6->sin6_scope_id = 0;
2673 	}
2674 
2675 	if (rt != NULL) {
2676 		RT_LOCK(rt);
2677 		if (IS_DYNAMIC_DIRECT_HOSTROUTE(rt)) {
2678 			/*
2679 			 * Copy the link layer information in SDL when present
2680 			 * as it later gets used to issue the kernel event for
2681 			 * node absence.
2682 			 */
2683 			if (sdl != NULL && rt->rt_gateway != NULL &&
2684 			    rt->rt_gateway->sa_family == AF_LINK &&
2685 			    SDL(rt->rt_gateway)->sdl_len <= sizeof(*sdl)) {
2686 				SOCKADDR_COPY(rt->rt_gateway, sdl, SDL(rt->rt_gateway)->sdl_len);
2687 			}
2688 
2689 			rt->rt_flags |= RTF_CONDEMNED;
2690 			RT_UNLOCK(rt);
2691 
2692 			error = rtrequest_locked(RTM_DELETE, rt_key(rt), NULL, rt_mask(rt),
2693 			    0, (struct rtentry **)NULL);
2694 
2695 			rtfree_locked(rt);
2696 		} else {
2697 			error = EHOSTUNREACH;
2698 			RT_REMREF_LOCKED(rt);
2699 			RT_UNLOCK(rt);
2700 		}
2701 	} else {
2702 		error = EHOSTUNREACH;
2703 	}
2704 
2705 	if (error == 0) {
2706 		nd6log(info, "%s: Successfully deleted host route to %s "
2707 		    "for interface %s.\n", __func__, ip6_sprintf(&sin6->sin6_addr),
2708 		    ifp->if_xname);
2709 	} else {
2710 		nd6log(error, "%s: Failed to delete host route to %s "
2711 		    "for interface %s with error :%d.\n", __func__,
2712 		    ip6_sprintf(&sin6->sin6_addr),
2713 		    ifp->if_xname, error);
2714 	}
2715 
2716 	lck_mtx_unlock(rnh_lock);
2717 	return error;
2718 }
2719