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