xref: /xnu-8019.80.24/bsd/netinet6/in6.c (revision a325d9c4a84054e40bbe985afedcb50ab80993ea) !
1 /*
2  * Copyright (c) 2003-2021 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 /*
59  * Copyright (c) 1982, 1986, 1991, 1993
60  *	The Regents of the University of California.  All rights reserved.
61  *
62  * Redistribution and use in source and binary forms, with or without
63  * modification, are permitted provided that the following conditions
64  * are met:
65  * 1. Redistributions of source code must retain the above copyright
66  *    notice, this list of conditions and the following disclaimer.
67  * 2. Redistributions in binary form must reproduce the above copyright
68  *    notice, this list of conditions and the following disclaimer in the
69  *    documentation and/or other materials provided with the distribution.
70  * 3. All advertising materials mentioning features or use of this software
71  *    must display the following acknowledgement:
72  *	This product includes software developed by the University of
73  *	California, Berkeley and its contributors.
74  * 4. Neither the name of the University nor the names of its contributors
75  *    may be used to endorse or promote products derived from this software
76  *    without specific prior written permission.
77  *
78  * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
79  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
80  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
81  * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
82  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
83  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
84  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
85  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
86  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
87  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
88  * SUCH DAMAGE.
89  *
90  *	@(#)in.c	8.2 (Berkeley) 11/15/93
91  */
92 
93 
94 #include <sys/param.h>
95 #include <sys/ioctl.h>
96 #include <sys/errno.h>
97 #include <sys/malloc.h>
98 #include <sys/socket.h>
99 #include <sys/socketvar.h>
100 #include <sys/sockio.h>
101 #include <sys/systm.h>
102 #include <sys/time.h>
103 #include <sys/kernel.h>
104 #include <sys/syslog.h>
105 #include <sys/kern_event.h>
106 #include <sys/mcache.h>
107 #include <sys/protosw.h>
108 #include <sys/sysctl.h>
109 
110 #include <kern/locks.h>
111 #include <kern/zalloc.h>
112 #include <kern/clock.h>
113 #include <libkern/OSAtomic.h>
114 #include <machine/machine_routines.h>
115 #include <mach/boolean.h>
116 
117 #include <net/if.h>
118 #include <net/if_types.h>
119 #include <net/if_var.h>
120 #include <net/route.h>
121 #include <net/if_dl.h>
122 #include <net/kpi_protocol.h>
123 #include <net/nwk_wq.h>
124 
125 #include <netinet/in.h>
126 #include <netinet/in_var.h>
127 #include <netinet/if_ether.h>
128 #include <netinet/in_systm.h>
129 #include <netinet/ip.h>
130 #include <netinet/in_pcb.h>
131 #include <netinet/icmp6.h>
132 #include <netinet/tcp.h>
133 #include <netinet/tcp_seq.h>
134 #include <netinet/tcp_var.h>
135 
136 #include <netinet6/nd6.h>
137 #include <netinet/ip6.h>
138 #include <netinet6/ip6_var.h>
139 #include <netinet6/mld6_var.h>
140 #include <netinet6/in6_ifattach.h>
141 #include <netinet6/scope6_var.h>
142 #include <netinet6/in6_var.h>
143 #include <netinet6/in6_pcb.h>
144 
145 #include <net/net_osdep.h>
146 
147 #include <net/dlil.h>
148 #include <net/if_llatbl.h>
149 
150 #if PF
151 #include <net/pfvar.h>
152 #endif /* PF */
153 
154 /*
155  * Definitions of some costant IP6 addresses.
156  */
157 const struct in6_addr in6addr_any = IN6ADDR_ANY_INIT;
158 const struct in6_addr in6addr_loopback = IN6ADDR_LOOPBACK_INIT;
159 const struct in6_addr in6addr_nodelocal_allnodes =
160     IN6ADDR_NODELOCAL_ALLNODES_INIT;
161 const struct in6_addr in6addr_linklocal_allnodes =
162     IN6ADDR_LINKLOCAL_ALLNODES_INIT;
163 const struct in6_addr in6addr_linklocal_allrouters =
164     IN6ADDR_LINKLOCAL_ALLROUTERS_INIT;
165 const struct in6_addr in6addr_linklocal_allv2routers =
166     IN6ADDR_LINKLOCAL_ALLV2ROUTERS_INIT;
167 const struct in6_addr in6addr_multicast_prefix =
168     IN6ADDR_MULTICAST_PREFIX;
169 
170 const struct in6_addr in6mask0 = IN6MASK0;
171 const struct in6_addr in6mask7 = IN6MASK7;
172 const struct in6_addr in6mask8 = IN6MASK8;
173 const struct in6_addr in6mask16 = IN6MASK16;
174 const struct in6_addr in6mask32 = IN6MASK32;
175 const struct in6_addr in6mask64 = IN6MASK64;
176 const struct in6_addr in6mask96 = IN6MASK96;
177 const struct in6_addr in6mask128 = IN6MASK128;
178 
179 const struct sockaddr_in6 sa6_any = {
180 	.sin6_len = sizeof(sa6_any),
181 	.sin6_family = AF_INET6,
182 	.sin6_port = 0,
183 	.sin6_flowinfo = 0,
184 	.sin6_addr = IN6ADDR_ANY_INIT,
185 	.sin6_scope_id = 0
186 };
187 
188 static int in6ctl_associd(struct socket *, u_long, caddr_t);
189 static int in6ctl_connid(struct socket *, u_long, caddr_t);
190 static int in6ctl_conninfo(struct socket *, u_long, caddr_t);
191 static int in6ctl_llstart(struct ifnet *, u_long, caddr_t);
192 static int in6ctl_llstop(struct ifnet *);
193 static int in6ctl_cgastart(struct ifnet *, u_long, caddr_t);
194 static int in6ctl_gifaddr(struct ifnet *, struct in6_ifaddr *, u_long,
195     struct in6_ifreq *);
196 static int in6ctl_gifstat(struct ifnet *, u_long, struct in6_ifreq *);
197 static int in6ctl_alifetime(struct in6_ifaddr *, u_long, struct in6_ifreq *,
198     boolean_t);
199 static int in6ctl_aifaddr(struct ifnet *, struct in6_aliasreq *);
200 static void in6ctl_difaddr(struct ifnet *, struct in6_ifaddr *);
201 static int in6_autoconf(struct ifnet *, int);
202 static int in6_setrouter(struct ifnet *, ipv6_router_mode_t);
203 static int in6_ifinit(struct ifnet *, struct in6_ifaddr *, int);
204 static int in6_ifaupdate_aux(struct in6_ifaddr *, struct ifnet *, int);
205 static void in6_unlink_ifa(struct in6_ifaddr *, struct ifnet *);
206 static struct in6_ifaddr *in6_ifaddr_alloc(zalloc_flags_t);
207 static void in6_ifaddr_attached(struct ifaddr *);
208 static void in6_ifaddr_detached(struct ifaddr *);
209 static void in6_ifaddr_free(struct ifaddr *);
210 static void in6_ifaddr_trace(struct ifaddr *, int);
211 #if defined(__LP64__)
212 static void in6_cgareq_32_to_64(const struct in6_cgareq_32 *,
213     struct in6_cgareq_64 *);
214 #else
215 static void in6_cgareq_64_to_32(const struct in6_cgareq_64 *,
216     struct in6_cgareq_32 *);
217 #endif
218 static struct in6_aliasreq *in6_aliasreq_to_native(void *, int,
219     struct in6_aliasreq *);
220 static int in6_to_kamescope(struct sockaddr_in6 *, struct ifnet *);
221 static int in6_getassocids(struct socket *, uint32_t *, user_addr_t);
222 static int in6_getconnids(struct socket *, sae_associd_t, uint32_t *,
223     user_addr_t);
224 
225 static void in6_if_up_dad_start(struct ifnet *);
226 
227 #define IA6_HASH_INIT(ia) {                                      \
228 	(ia)->ia6_hash.tqe_next = (void *)(uintptr_t)-1;         \
229 	(ia)->ia6_hash.tqe_prev = (void *)(uintptr_t)-1;         \
230 }
231 
232 #define IA6_IS_HASHED(ia)                                        \
233 	(!((ia)->ia6_hash.tqe_next == (void *)(uintptr_t)-1 ||   \
234 	(ia)->ia6_hash.tqe_prev == (void *)(uintptr_t)-1))
235 
236 static void in6_iahash_remove(struct in6_ifaddr *);
237 static void in6_iahash_insert(struct in6_ifaddr *);
238 static void in6_iahash_insert_ptp(struct in6_ifaddr *);
239 
240 #define IN6IFA_TRACE_HIST_SIZE  32      /* size of trace history */
241 
242 /* For gdb */
243 __private_extern__ unsigned int in6ifa_trace_hist_size = IN6IFA_TRACE_HIST_SIZE;
244 
245 struct in6_ifaddr_dbg {
246 	struct in6_ifaddr       in6ifa;                 /* in6_ifaddr */
247 	struct in6_ifaddr       in6ifa_old;             /* saved in6_ifaddr */
248 	u_int16_t               in6ifa_refhold_cnt;     /* # of IFA_ADDREF */
249 	u_int16_t               in6ifa_refrele_cnt;     /* # of IFA_REMREF */
250 	/*
251 	 * Alloc and free callers.
252 	 */
253 	ctrace_t                in6ifa_alloc;
254 	ctrace_t                in6ifa_free;
255 	/*
256 	 * Circular lists of IFA_ADDREF and IFA_REMREF callers.
257 	 */
258 	ctrace_t                in6ifa_refhold[IN6IFA_TRACE_HIST_SIZE];
259 	ctrace_t                in6ifa_refrele[IN6IFA_TRACE_HIST_SIZE];
260 	/*
261 	 * Trash list linkage
262 	 */
263 	TAILQ_ENTRY(in6_ifaddr_dbg) in6ifa_trash_link;
264 };
265 
266 /* List of trash in6_ifaddr entries protected by in6ifa_trash_lock */
267 static TAILQ_HEAD(, in6_ifaddr_dbg) in6ifa_trash_head;
268 static LCK_MTX_DECLARE_ATTR(in6ifa_trash_lock, &ifa_mtx_grp, &ifa_mtx_attr);
269 
270 #if DEBUG
271 static unsigned int in6ifa_debug = 1;           /* debugging (enabled) */
272 #else
273 static unsigned int in6ifa_debug;               /* debugging (disabled) */
274 #endif /* !DEBUG */
275 static struct zone *in6ifa_zone;                /* zone for in6_ifaddr */
276 #define IN6IFA_ZONE_NAME        "in6_ifaddr"    /* zone name */
277 
278 struct eventhandler_lists_ctxt in6_evhdlr_ctxt;
279 struct eventhandler_lists_ctxt in6_clat46_evhdlr_ctxt;
280 /*
281  * Subroutine for in6_ifaddloop() and in6_ifremloop().
282  * This routine does actual work.
283  */
284 static void
in6_ifloop_request(int cmd,struct ifaddr * ifa)285 in6_ifloop_request(int cmd, struct ifaddr *ifa)
286 {
287 	struct sockaddr_in6 all1_sa;
288 	struct rtentry *nrt = NULL;
289 	int e;
290 
291 	bzero(&all1_sa, sizeof(all1_sa));
292 	all1_sa.sin6_family = AF_INET6;
293 	all1_sa.sin6_len = sizeof(struct sockaddr_in6);
294 	all1_sa.sin6_addr = in6mask128;
295 
296 	/*
297 	 * We specify the address itself as the gateway, and set the
298 	 * RTF_LLINFO flag, so that the corresponding host route would have
299 	 * the flag, and thus applications that assume traditional behavior
300 	 * would be happy.  Note that we assume the caller of the function
301 	 * (probably implicitly) set nd6_rtrequest() to ifa->ifa_rtrequest,
302 	 * which changes the outgoing interface to the loopback interface.
303 	 * ifa_addr for INET6 is set once during init; no need to hold lock.
304 	 */
305 	lck_mtx_lock(rnh_lock);
306 	e = rtrequest_locked(cmd, ifa->ifa_addr, ifa->ifa_addr,
307 	    (struct sockaddr *)&all1_sa, RTF_UP | RTF_HOST | RTF_LLINFO, &nrt);
308 	if (e != 0) {
309 		log(LOG_ERR, "in6_ifloop_request: "
310 		    "%s operation failed for %s (errno=%d)\n",
311 		    cmd == RTM_ADD ? "ADD" : "DELETE",
312 		    ip6_sprintf(&((struct in6_ifaddr *)ifa)->ia_addr.sin6_addr),
313 		    e);
314 	}
315 
316 	if (nrt != NULL) {
317 		RT_LOCK(nrt);
318 	}
319 	/*
320 	 * Make sure rt_ifa be equal to IFA, the second argument of the
321 	 * function.
322 	 * We need this because when we refer to rt_ifa->ia6_flags in
323 	 * ip6_input, we assume that the rt_ifa points to the address instead
324 	 * of the loopback address.
325 	 */
326 	if (cmd == RTM_ADD && nrt && ifa != nrt->rt_ifa) {
327 		rtsetifa(nrt, ifa);
328 	}
329 
330 	/*
331 	 * Report the addition/removal of the address to the routing socket.
332 	 * XXX: since we called rtinit for a p2p interface with a destination,
333 	 *   we end up reporting twice in such a case.  Should we rather
334 	 *   omit the second report?
335 	 */
336 	if (nrt != NULL) {
337 		rt_newaddrmsg((u_char)cmd, ifa, e, nrt);
338 		if (cmd == RTM_DELETE) {
339 			RT_UNLOCK(nrt);
340 			rtfree_locked(nrt);
341 		} else {
342 			/* the cmd must be RTM_ADD here */
343 			RT_REMREF_LOCKED(nrt);
344 			RT_UNLOCK(nrt);
345 		}
346 	}
347 	lck_mtx_unlock(rnh_lock);
348 }
349 
350 /*
351  * Add ownaddr as loopback rtentry.  We previously add the route only if
352  * necessary (ex. on a p2p link).  However, since we now manage addresses
353  * separately from prefixes, we should always add the route.  We can't
354  * rely on the cloning mechanism from the corresponding interface route
355  * any more.
356  */
357 static void
in6_ifaddloop(struct ifaddr * ifa)358 in6_ifaddloop(struct ifaddr *ifa)
359 {
360 	struct rtentry *rt;
361 
362 	/*
363 	 * If there is no loopback entry, allocate one.  ifa_addr for
364 	 * INET6 is set once during init; no need to hold lock.
365 	 */
366 	rt = rtalloc1(ifa->ifa_addr, 0, 0);
367 	if (rt != NULL) {
368 		RT_LOCK(rt);
369 	}
370 	if (rt == NULL || (rt->rt_flags & RTF_HOST) == 0 ||
371 	    (rt->rt_ifp->if_flags & IFF_LOOPBACK) == 0) {
372 		if (rt != NULL) {
373 			RT_REMREF_LOCKED(rt);
374 			RT_UNLOCK(rt);
375 		}
376 		in6_ifloop_request(RTM_ADD, ifa);
377 	} else if (rt != NULL) {
378 		RT_REMREF_LOCKED(rt);
379 		RT_UNLOCK(rt);
380 	}
381 }
382 
383 /*
384  * Remove loopback rtentry of ownaddr generated by in6_ifaddloop(),
385  * if it exists.
386  */
387 static void
in6_ifremloop(struct ifaddr * ifa)388 in6_ifremloop(struct ifaddr *ifa)
389 {
390 	struct in6_ifaddr *ia;
391 	struct rtentry *rt;
392 	int ia_count = 0;
393 
394 	/*
395 	 * Some of BSD variants do not remove cloned routes
396 	 * from an interface direct route, when removing the direct route
397 	 * (see comments in net/net_osdep.h).  Even for variants that do remove
398 	 * cloned routes, they could fail to remove the cloned routes when
399 	 * we handle multple addresses that share a common prefix.
400 	 * So, we should remove the route corresponding to the deleted address
401 	 * regardless of the result of in6_is_ifloop_auto().
402 	 */
403 
404 	/*
405 	 * Delete the entry only if exact one ifa exists.  More than one ifa
406 	 * can exist if we assign a same single address to multiple
407 	 * (probably p2p) interfaces.
408 	 * XXX: we should avoid such a configuration in IPv6...
409 	 */
410 	lck_rw_lock_exclusive(&in6_ifaddr_rwlock);
411 	TAILQ_FOREACH(ia, IN6ADDR_HASH(IFA_IN6(ifa)), ia6_hash) {
412 		IFA_LOCK(&ia->ia_ifa);
413 		if (in6_are_addr_equal_scoped(IFA_IN6(ifa), &ia->ia_addr.sin6_addr, IFA_SIN6(ifa)->sin6_scope_id, ia->ia_addr.sin6_scope_id)) {
414 			ia_count++;
415 			if (ia_count > 1) {
416 				IFA_UNLOCK(&ia->ia_ifa);
417 				break;
418 			}
419 		}
420 		IFA_UNLOCK(&ia->ia_ifa);
421 	}
422 	lck_rw_done(&in6_ifaddr_rwlock);
423 
424 	if (ia_count == 1) {
425 		/*
426 		 * Before deleting, check if a corresponding loopbacked host
427 		 * route surely exists.  With this check, we can avoid to
428 		 * delete an interface direct route whose destination is same
429 		 * as the address being removed.  This can happen when removing
430 		 * a subnet-router anycast address on an interface attahced
431 		 * to a shared medium.  ifa_addr for INET6 is set once during
432 		 * init; no need to hold lock.
433 		 */
434 		rt = rtalloc1(ifa->ifa_addr, 0, 0);
435 		if (rt != NULL) {
436 			RT_LOCK(rt);
437 			if ((rt->rt_flags & RTF_HOST) != 0 &&
438 			    (rt->rt_ifp->if_flags & IFF_LOOPBACK) != 0) {
439 				RT_REMREF_LOCKED(rt);
440 				RT_UNLOCK(rt);
441 				in6_ifloop_request(RTM_DELETE, ifa);
442 			} else {
443 				RT_UNLOCK(rt);
444 			}
445 		}
446 	}
447 }
448 
449 
450 int
in6_mask2len(struct in6_addr * mask,u_char * lim0)451 in6_mask2len(struct in6_addr *mask, u_char *lim0)
452 {
453 	int x = 0, y;
454 	u_char *lim = lim0, *p;
455 
456 	/* ignore the scope_id part */
457 	if (lim0 == NULL || lim0 - (u_char *)mask > sizeof(*mask)) {
458 		lim = (u_char *)mask + sizeof(*mask);
459 	}
460 	for (p = (u_char *)mask; p < lim; x++, p++) {
461 		if (*p != 0xff) {
462 			break;
463 		}
464 	}
465 	y = 0;
466 	if (p < lim) {
467 		for (y = 0; y < 8; y++) {
468 			if ((*p & (0x80 >> y)) == 0) {
469 				break;
470 			}
471 		}
472 	}
473 
474 	/*
475 	 * when the limit pointer is given, do a stricter check on the
476 	 * remaining bits.
477 	 */
478 	if (p < lim) {
479 		if (y != 0 && (*p & (0x00ff >> y)) != 0) {
480 			return -1;
481 		}
482 		for (p = p + 1; p < lim; p++) {
483 			if (*p != 0) {
484 				return -1;
485 			}
486 		}
487 	}
488 
489 	return x * 8 + y;
490 }
491 
492 void
in6_len2mask(struct in6_addr * mask,int len)493 in6_len2mask(struct in6_addr *mask, int len)
494 {
495 	int i;
496 
497 	bzero(mask, sizeof(*mask));
498 	for (i = 0; i < len / 8; i++) {
499 		mask->s6_addr8[i] = 0xff;
500 	}
501 	if (len % 8) {
502 		mask->s6_addr8[i] = (0xff00 >> (len % 8)) & 0xff;
503 	}
504 }
505 
506 void
in6_aliasreq_64_to_32(struct in6_aliasreq_64 * src,struct in6_aliasreq_32 * dst)507 in6_aliasreq_64_to_32(struct in6_aliasreq_64 *src, struct in6_aliasreq_32 *dst)
508 {
509 	bzero(dst, sizeof(*dst));
510 	bcopy(src->ifra_name, dst->ifra_name, sizeof(dst->ifra_name));
511 	dst->ifra_addr = src->ifra_addr;
512 	dst->ifra_dstaddr = src->ifra_dstaddr;
513 	dst->ifra_prefixmask = src->ifra_prefixmask;
514 	dst->ifra_flags = src->ifra_flags;
515 	dst->ifra_lifetime.ia6t_expire = (u_int32_t)src->ifra_lifetime.ia6t_expire;
516 	dst->ifra_lifetime.ia6t_preferred = (u_int32_t)src->ifra_lifetime.ia6t_preferred;
517 	dst->ifra_lifetime.ia6t_vltime = src->ifra_lifetime.ia6t_vltime;
518 	dst->ifra_lifetime.ia6t_pltime = src->ifra_lifetime.ia6t_pltime;
519 }
520 
521 void
in6_aliasreq_32_to_64(struct in6_aliasreq_32 * src,struct in6_aliasreq_64 * dst)522 in6_aliasreq_32_to_64(struct in6_aliasreq_32 *src, struct in6_aliasreq_64 *dst)
523 {
524 	bzero(dst, sizeof(*dst));
525 	bcopy(src->ifra_name, dst->ifra_name, sizeof(dst->ifra_name));
526 	dst->ifra_addr = src->ifra_addr;
527 	dst->ifra_dstaddr = src->ifra_dstaddr;
528 	dst->ifra_prefixmask = src->ifra_prefixmask;
529 	dst->ifra_flags = src->ifra_flags;
530 	dst->ifra_lifetime.ia6t_expire = src->ifra_lifetime.ia6t_expire;
531 	dst->ifra_lifetime.ia6t_preferred = src->ifra_lifetime.ia6t_preferred;
532 	dst->ifra_lifetime.ia6t_vltime = src->ifra_lifetime.ia6t_vltime;
533 	dst->ifra_lifetime.ia6t_pltime = src->ifra_lifetime.ia6t_pltime;
534 }
535 
536 #if defined(__LP64__)
537 static void
in6_cgareq_32_to_64(const struct in6_cgareq_32 * src,struct in6_cgareq_64 * dst)538 in6_cgareq_32_to_64(const struct in6_cgareq_32 *src,
539     struct in6_cgareq_64 *dst)
540 {
541 	bzero(dst, sizeof(*dst));
542 	bcopy(src->cgar_name, dst->cgar_name, sizeof(dst->cgar_name));
543 	dst->cgar_flags = src->cgar_flags;
544 	bcopy(src->cgar_cgaprep.cga_modifier.octets,
545 	    dst->cgar_cgaprep.cga_modifier.octets,
546 	    sizeof(dst->cgar_cgaprep.cga_modifier.octets));
547 	dst->cgar_cgaprep.cga_security_level =
548 	    src->cgar_cgaprep.cga_security_level;
549 	dst->cgar_lifetime.ia6t_expire = src->cgar_lifetime.ia6t_expire;
550 	dst->cgar_lifetime.ia6t_preferred = src->cgar_lifetime.ia6t_preferred;
551 	dst->cgar_lifetime.ia6t_vltime = src->cgar_lifetime.ia6t_vltime;
552 	dst->cgar_lifetime.ia6t_pltime = src->cgar_lifetime.ia6t_pltime;
553 	dst->cgar_collision_count = src->cgar_collision_count;
554 }
555 #endif
556 
557 #if !defined(__LP64__)
558 static void
in6_cgareq_64_to_32(const struct in6_cgareq_64 * src,struct in6_cgareq_32 * dst)559 in6_cgareq_64_to_32(const struct in6_cgareq_64 *src,
560     struct in6_cgareq_32 *dst)
561 {
562 	bzero(dst, sizeof(*dst));
563 	bcopy(src->cgar_name, dst->cgar_name, sizeof(dst->cgar_name));
564 	dst->cgar_flags = src->cgar_flags;
565 	bcopy(src->cgar_cgaprep.cga_modifier.octets,
566 	    dst->cgar_cgaprep.cga_modifier.octets,
567 	    sizeof(dst->cgar_cgaprep.cga_modifier.octets));
568 	dst->cgar_cgaprep.cga_security_level =
569 	    src->cgar_cgaprep.cga_security_level;
570 	dst->cgar_lifetime.ia6t_expire = (u_int32_t)src->cgar_lifetime.ia6t_expire;
571 	dst->cgar_lifetime.ia6t_preferred = (u_int32_t)src->cgar_lifetime.ia6t_preferred;
572 	dst->cgar_lifetime.ia6t_vltime = src->cgar_lifetime.ia6t_vltime;
573 	dst->cgar_lifetime.ia6t_pltime = src->cgar_lifetime.ia6t_pltime;
574 	dst->cgar_collision_count = src->cgar_collision_count;
575 }
576 #endif
577 
578 static struct in6_aliasreq *
in6_aliasreq_to_native(void * data,int data_is_64,struct in6_aliasreq * dst)579 in6_aliasreq_to_native(void *data, int data_is_64, struct in6_aliasreq *dst)
580 {
581 #if defined(__LP64__)
582 	if (data_is_64) {
583 		bcopy(data, dst, sizeof(*dst));
584 	} else {
585 		in6_aliasreq_32_to_64((struct in6_aliasreq_32 *)data,
586 		    (struct in6_aliasreq_64 *)dst);
587 	}
588 #else
589 	if (data_is_64) {
590 		in6_aliasreq_64_to_32((struct in6_aliasreq_64 *)data,
591 		    (struct in6_aliasreq_32 *)dst);
592 	} else {
593 		bcopy(data, dst, sizeof(*dst));
594 	}
595 #endif /* __LP64__ */
596 	return dst;
597 }
598 
599 void
in6_cgareq_copy_from_user(const void * user_data,int user_is_64,struct in6_cgareq * cgareq)600 in6_cgareq_copy_from_user(const void *user_data, int user_is_64,
601     struct in6_cgareq *cgareq)
602 {
603 #if defined(__LP64__)
604 	if (user_is_64) {
605 		bcopy(user_data, cgareq, sizeof(*cgareq));
606 	} else {
607 		in6_cgareq_32_to_64((const struct in6_cgareq_32 *)user_data,
608 		    (struct in6_cgareq_64 *)cgareq);
609 	}
610 #else
611 	if (user_is_64) {
612 		in6_cgareq_64_to_32((const struct in6_cgareq_64 *)user_data,
613 		    (struct in6_cgareq_32 *)cgareq);
614 	} else {
615 		bcopy(user_data, cgareq, sizeof(*cgareq));
616 	}
617 #endif /* __LP64__ */
618 }
619 
620 static __attribute__((noinline)) int
in6ctl_associd(struct socket * so,u_long cmd,caddr_t data)621 in6ctl_associd(struct socket *so, u_long cmd, caddr_t data)
622 {
623 	int error = 0;
624 	union {
625 		struct so_aidreq32 a32;
626 		struct so_aidreq64 a64;
627 	} u;
628 
629 	VERIFY(so != NULL);
630 
631 	switch (cmd) {
632 	case SIOCGASSOCIDS32: {         /* struct so_aidreq32 */
633 		bcopy(data, &u.a32, sizeof(u.a32));
634 		error = in6_getassocids(so, &u.a32.sar_cnt, u.a32.sar_aidp);
635 		if (error == 0) {
636 			bcopy(&u.a32, data, sizeof(u.a32));
637 		}
638 		break;
639 	}
640 
641 	case SIOCGASSOCIDS64: {         /* struct so_aidreq64 */
642 		bcopy(data, &u.a64, sizeof(u.a64));
643 		error = in6_getassocids(so, &u.a64.sar_cnt, (user_addr_t)u.a64.sar_aidp);
644 		if (error == 0) {
645 			bcopy(&u.a64, data, sizeof(u.a64));
646 		}
647 		break;
648 	}
649 
650 	default:
651 		VERIFY(0);
652 		/* NOTREACHED */
653 	}
654 
655 	return error;
656 }
657 
658 static __attribute__((noinline)) int
in6ctl_connid(struct socket * so,u_long cmd,caddr_t data)659 in6ctl_connid(struct socket *so, u_long cmd, caddr_t data)
660 {
661 	int error = 0;
662 	union {
663 		struct so_cidreq32 c32;
664 		struct so_cidreq64 c64;
665 	} u;
666 
667 	VERIFY(so != NULL);
668 
669 	switch (cmd) {
670 	case SIOCGCONNIDS32: {          /* struct so_cidreq32 */
671 		bcopy(data, &u.c32, sizeof(u.c32));
672 		error = in6_getconnids(so, u.c32.scr_aid, &u.c32.scr_cnt,
673 		    u.c32.scr_cidp);
674 		if (error == 0) {
675 			bcopy(&u.c32, data, sizeof(u.c32));
676 		}
677 		break;
678 	}
679 
680 	case SIOCGCONNIDS64: {          /* struct so_cidreq64 */
681 		bcopy(data, &u.c64, sizeof(u.c64));
682 		error = in6_getconnids(so, u.c64.scr_aid, &u.c64.scr_cnt,
683 		    (user_addr_t)u.c64.scr_cidp);
684 		if (error == 0) {
685 			bcopy(&u.c64, data, sizeof(u.c64));
686 		}
687 		break;
688 	}
689 
690 	default:
691 		VERIFY(0);
692 		/* NOTREACHED */
693 	}
694 
695 	return error;
696 }
697 
698 static __attribute__((noinline)) int
in6ctl_conninfo(struct socket * so,u_long cmd,caddr_t data)699 in6ctl_conninfo(struct socket *so, u_long cmd, caddr_t data)
700 {
701 	int error = 0;
702 	union {
703 		struct so_cinforeq32 ci32;
704 		struct so_cinforeq64 ci64;
705 	} u;
706 
707 	VERIFY(so != NULL);
708 
709 	switch (cmd) {
710 	case SIOCGCONNINFO32: {         /* struct so_cinforeq32 */
711 		bcopy(data, &u.ci32, sizeof(u.ci32));
712 		error = in6_getconninfo(so, u.ci32.scir_cid, &u.ci32.scir_flags,
713 		    &u.ci32.scir_ifindex, &u.ci32.scir_error, u.ci32.scir_src,
714 		    &u.ci32.scir_src_len, u.ci32.scir_dst, &u.ci32.scir_dst_len,
715 		    &u.ci32.scir_aux_type, u.ci32.scir_aux_data,
716 		    &u.ci32.scir_aux_len);
717 		if (error == 0) {
718 			bcopy(&u.ci32, data, sizeof(u.ci32));
719 		}
720 		break;
721 	}
722 
723 	case SIOCGCONNINFO64: {         /* struct so_cinforeq64 */
724 		bcopy(data, &u.ci64, sizeof(u.ci64));
725 		error = in6_getconninfo(so, u.ci64.scir_cid, &u.ci64.scir_flags,
726 		    &u.ci64.scir_ifindex, &u.ci64.scir_error, (user_addr_t)u.ci64.scir_src,
727 		    &u.ci64.scir_src_len, (user_addr_t)u.ci64.scir_dst, &u.ci64.scir_dst_len,
728 		    &u.ci64.scir_aux_type, (user_addr_t)u.ci64.scir_aux_data,
729 		    &u.ci64.scir_aux_len);
730 		if (error == 0) {
731 			bcopy(&u.ci64, data, sizeof(u.ci64));
732 		}
733 		break;
734 	}
735 
736 	default:
737 		VERIFY(0);
738 		/* NOTREACHED */
739 	}
740 
741 	return error;
742 }
743 
744 static __attribute__((noinline)) int
in6ctl_llstart(struct ifnet * ifp,u_long cmd,caddr_t data)745 in6ctl_llstart(struct ifnet *ifp, u_long cmd, caddr_t data)
746 {
747 	struct in6_aliasreq sifra, *ifra = NULL;
748 	boolean_t is64;
749 	int error = 0;
750 
751 	VERIFY(ifp != NULL);
752 
753 	switch (cmd) {
754 	case SIOCLL_START_32:           /* struct in6_aliasreq_32 */
755 	case SIOCLL_START_64:           /* struct in6_aliasreq_64 */
756 		is64 = (cmd == SIOCLL_START_64);
757 		/*
758 		 * Convert user ifra to the kernel form, when appropriate.
759 		 * This allows the conversion between different data models
760 		 * to be centralized, so that it can be passed around to other
761 		 * routines that are expecting the kernel form.
762 		 */
763 		ifra = in6_aliasreq_to_native(data, is64, &sifra);
764 
765 		/*
766 		 * NOTE: All the interface specific DLIL attachements should
767 		 * be done here.  They are currently done in in6_ifattach_aux()
768 		 * for the interfaces that need it.
769 		 */
770 		if (ifra->ifra_addr.sin6_family == AF_INET6 &&
771 		    /* Only check ifra_dstaddr if valid */
772 		    (ifra->ifra_dstaddr.sin6_len == 0 ||
773 		    ifra->ifra_dstaddr.sin6_family == AF_INET6)) {
774 			/* some interfaces may provide LinkLocal addresses */
775 			error = in6_ifattach_aliasreq(ifp, NULL, ifra);
776 		} else {
777 			error = in6_ifattach_aliasreq(ifp, NULL, NULL);
778 		}
779 		if (error == 0) {
780 			in6_if_up_dad_start(ifp);
781 		}
782 		break;
783 
784 	default:
785 		VERIFY(0);
786 		/* NOTREACHED */
787 	}
788 
789 	return error;
790 }
791 
792 static __attribute__((noinline)) int
in6ctl_llstop(struct ifnet * ifp)793 in6ctl_llstop(struct ifnet *ifp)
794 {
795 	struct in6_ifaddr *ia;
796 	struct nd_prefix pr0, *pr;
797 
798 	VERIFY(ifp != NULL);
799 
800 	/* Remove link local addresses from interface */
801 	lck_rw_lock_exclusive(&in6_ifaddr_rwlock);
802 	boolean_t from_begining = TRUE;
803 	while (from_begining) {
804 		from_begining = FALSE;
805 		TAILQ_FOREACH(ia, &in6_ifaddrhead, ia6_link) {
806 			if (ia->ia_ifa.ifa_ifp != ifp) {
807 				continue;
808 			}
809 			IFA_LOCK(&ia->ia_ifa);
810 			if (IN6_IS_ADDR_LINKLOCAL(&ia->ia_addr.sin6_addr)) {
811 				IFA_ADDREF_LOCKED(&ia->ia_ifa); /* for us */
812 				IFA_UNLOCK(&ia->ia_ifa);
813 				lck_rw_done(&in6_ifaddr_rwlock);
814 				in6_purgeaddr(&ia->ia_ifa);
815 				IFA_REMREF(&ia->ia_ifa);        /* for us */
816 				lck_rw_lock_exclusive(&in6_ifaddr_rwlock);
817 				/*
818 				 * Purging the address caused in6_ifaddr_rwlock
819 				 * to be dropped and reacquired;
820 				 * therefore search again from the beginning
821 				 * of in6_ifaddrs list.
822 				 */
823 				from_begining = TRUE;
824 				break;
825 			}
826 			IFA_UNLOCK(&ia->ia_ifa);
827 		}
828 	}
829 	lck_rw_done(&in6_ifaddr_rwlock);
830 
831 	/* Delete the link local prefix */
832 	bzero(&pr0, sizeof(pr0));
833 	pr0.ndpr_plen = 64;
834 	pr0.ndpr_ifp = ifp;
835 	pr0.ndpr_prefix.sin6_addr.s6_addr16[0] = IPV6_ADDR_INT16_ULL;
836 	(void)in6_setscope(&pr0.ndpr_prefix.sin6_addr, ifp, IN6_NULL_IF_EMBEDDED_SCOPE(&pr0.ndpr_prefix.sin6_scope_id));
837 	pr = nd6_prefix_lookup(&pr0, ND6_PREFIX_EXPIRY_UNSPEC);
838 	if (pr) {
839 		lck_mtx_lock(nd6_mutex);
840 		NDPR_LOCK(pr);
841 		prelist_remove(pr);
842 		NDPR_UNLOCK(pr);
843 		NDPR_REMREF(pr); /* Drop the reference from lookup */
844 		lck_mtx_unlock(nd6_mutex);
845 	}
846 
847 	return 0;
848 }
849 
850 /*
851  * This routine configures secure link local address
852  */
853 static __attribute__((noinline)) int
in6ctl_cgastart(struct ifnet * ifp,u_long cmd,caddr_t data)854 in6ctl_cgastart(struct ifnet *ifp, u_long cmd, caddr_t data)
855 {
856 	struct in6_cgareq llcgasr;
857 	int is64, error = 0;
858 
859 	VERIFY(ifp != NULL);
860 
861 	switch (cmd) {
862 	case SIOCLL_CGASTART_32:        /* struct in6_cgareq_32 */
863 	case SIOCLL_CGASTART_64:        /* struct in6_cgareq_64 */
864 		is64 = (cmd == SIOCLL_CGASTART_64);
865 		/*
866 		 * Convert user cgareq to the kernel form, when appropriate.
867 		 * This allows the conversion between different data models
868 		 * to be centralized, so that it can be passed around to other
869 		 * routines that are expecting the kernel form.
870 		 */
871 		in6_cgareq_copy_from_user(data, is64, &llcgasr);
872 
873 		/*
874 		 * NOTE: All the interface specific DLIL attachements
875 		 * should be done here.  They are currently done in
876 		 * in6_ifattach_cgareq() for the interfaces that
877 		 * need it.
878 		 */
879 		error = in6_ifattach_llcgareq(ifp, &llcgasr);
880 		if (error == 0) {
881 			in6_if_up_dad_start(ifp);
882 		}
883 		break;
884 
885 	default:
886 		VERIFY(0);
887 		/* NOTREACHED */
888 	}
889 
890 	return error;
891 }
892 
893 /*
894  * Caller passes in the ioctl data pointer directly via "ifr", with the
895  * expectation that this routine always uses bcopy() or other byte-aligned
896  * memory accesses.
897  */
898 static __attribute__((noinline)) int
in6ctl_gifaddr(struct ifnet * ifp,struct in6_ifaddr * ia,u_long cmd,struct in6_ifreq * ifr)899 in6ctl_gifaddr(struct ifnet *ifp, struct in6_ifaddr *ia, u_long cmd,
900     struct in6_ifreq *ifr)
901 {
902 	struct sockaddr_in6 addr;
903 	int error = 0;
904 
905 	VERIFY(ifp != NULL);
906 
907 	if (ia == NULL) {
908 		return EADDRNOTAVAIL;
909 	}
910 
911 	switch (cmd) {
912 	case SIOCGIFADDR_IN6:           /* struct in6_ifreq */
913 		IFA_LOCK(&ia->ia_ifa);
914 		bcopy(&ia->ia_addr, &addr, sizeof(addr));
915 		IFA_UNLOCK(&ia->ia_ifa);
916 		if ((error = sa6_recoverscope(&addr, TRUE)) != 0) {
917 			break;
918 		}
919 		bcopy(&addr, &ifr->ifr_addr, sizeof(addr));
920 		break;
921 
922 	case SIOCGIFDSTADDR_IN6:        /* struct in6_ifreq */
923 		if (!(ifp->if_flags & IFF_POINTOPOINT)) {
924 			error = EINVAL;
925 			break;
926 		}
927 		/*
928 		 * XXX: should we check if ifa_dstaddr is NULL and return
929 		 * an error?
930 		 */
931 		IFA_LOCK(&ia->ia_ifa);
932 		bcopy(&ia->ia_dstaddr, &addr, sizeof(addr));
933 		IFA_UNLOCK(&ia->ia_ifa);
934 		if ((error = sa6_recoverscope(&addr, TRUE)) != 0) {
935 			break;
936 		}
937 		bcopy(&addr, &ifr->ifr_dstaddr, sizeof(addr));
938 		break;
939 
940 	default:
941 		VERIFY(0);
942 		/* NOTREACHED */
943 	}
944 
945 	return error;
946 }
947 
948 /*
949  * Caller passes in the ioctl data pointer directly via "ifr", with the
950  * expectation that this routine always uses bcopy() or other byte-aligned
951  * memory accesses.
952  */
953 static __attribute__((noinline)) int
in6ctl_gifstat(struct ifnet * ifp,u_long cmd,struct in6_ifreq * ifr)954 in6ctl_gifstat(struct ifnet *ifp, u_long cmd, struct in6_ifreq *ifr)
955 {
956 	int error = 0, index;
957 
958 	VERIFY(ifp != NULL);
959 	index = ifp->if_index;
960 
961 	switch (cmd) {
962 	case SIOCGIFSTAT_IN6:           /* struct in6_ifreq */
963 		/* N.B.: if_inet6data is never freed once set. */
964 		if (IN6_IFEXTRA(ifp) == NULL) {
965 			/* return (EAFNOSUPPORT)? */
966 			bzero(&ifr->ifr_ifru.ifru_stat,
967 			    sizeof(ifr->ifr_ifru.ifru_stat));
968 		} else {
969 			bcopy(&IN6_IFEXTRA(ifp)->in6_ifstat,
970 			    &ifr->ifr_ifru.ifru_stat,
971 			    sizeof(ifr->ifr_ifru.ifru_stat));
972 		}
973 		break;
974 
975 	case SIOCGIFSTAT_ICMP6:         /* struct in6_ifreq */
976 		/* N.B.: if_inet6data is never freed once set. */
977 		if (IN6_IFEXTRA(ifp) == NULL) {
978 			/* return (EAFNOSUPPORT)? */
979 			bzero(&ifr->ifr_ifru.ifru_icmp6stat,
980 			    sizeof(ifr->ifr_ifru.ifru_icmp6stat));
981 		} else {
982 			bcopy(&IN6_IFEXTRA(ifp)->icmp6_ifstat,
983 			    &ifr->ifr_ifru.ifru_icmp6stat,
984 			    sizeof(ifr->ifr_ifru.ifru_icmp6stat));
985 		}
986 		break;
987 
988 	default:
989 		VERIFY(0);
990 		/* NOTREACHED */
991 	}
992 
993 	return error;
994 }
995 
996 /*
997  * Caller passes in the ioctl data pointer directly via "ifr", with the
998  * expectation that this routine always uses bcopy() or other byte-aligned
999  * memory accesses.
1000  */
1001 static __attribute__((noinline)) int
in6ctl_alifetime(struct in6_ifaddr * ia,u_long cmd,struct in6_ifreq * ifr,boolean_t p64)1002 in6ctl_alifetime(struct in6_ifaddr *ia, u_long cmd, struct in6_ifreq *ifr,
1003     boolean_t p64)
1004 {
1005 	uint64_t timenow = net_uptime();
1006 	struct in6_addrlifetime ia6_lt;
1007 	struct timeval caltime;
1008 	int error = 0;
1009 
1010 	if (ia == NULL) {
1011 		return EADDRNOTAVAIL;
1012 	}
1013 
1014 	switch (cmd) {
1015 	case SIOCGIFALIFETIME_IN6:      /* struct in6_ifreq */
1016 		IFA_LOCK(&ia->ia_ifa);
1017 		/* retrieve time as calendar time (last arg is 1) */
1018 		in6ifa_getlifetime(ia, &ia6_lt, 1);
1019 		if (p64) {
1020 			struct in6_addrlifetime_64 lt;
1021 
1022 			bzero(&lt, sizeof(lt));
1023 			lt.ia6t_expire = ia6_lt.ia6t_expire;
1024 			lt.ia6t_preferred = ia6_lt.ia6t_preferred;
1025 			lt.ia6t_vltime = ia6_lt.ia6t_vltime;
1026 			lt.ia6t_pltime = ia6_lt.ia6t_pltime;
1027 			bcopy(&lt, &ifr->ifr_ifru.ifru_lifetime, sizeof(ifr->ifr_ifru.ifru_lifetime));
1028 		} else {
1029 			struct in6_addrlifetime_32 lt;
1030 
1031 			bzero(&lt, sizeof(lt));
1032 			lt.ia6t_expire = (uint32_t)ia6_lt.ia6t_expire;
1033 			lt.ia6t_preferred = (uint32_t)ia6_lt.ia6t_preferred;
1034 			lt.ia6t_vltime = (uint32_t)ia6_lt.ia6t_vltime;
1035 			lt.ia6t_pltime = (uint32_t)ia6_lt.ia6t_pltime;
1036 			bcopy(&lt, &ifr->ifr_ifru.ifru_lifetime, sizeof(ifr->ifr_ifru.ifru_lifetime));
1037 		}
1038 		IFA_UNLOCK(&ia->ia_ifa);
1039 		break;
1040 
1041 	case SIOCSIFALIFETIME_IN6:      /* struct in6_ifreq */
1042 		getmicrotime(&caltime);
1043 
1044 		/* sanity for overflow - beware unsigned */
1045 		if (p64) {
1046 			struct in6_addrlifetime_64 lt;
1047 
1048 			bcopy(&ifr->ifr_ifru.ifru_lifetime, &lt, sizeof(lt));
1049 			if (lt.ia6t_vltime != ND6_INFINITE_LIFETIME &&
1050 			    lt.ia6t_vltime + caltime.tv_sec < caltime.tv_sec) {
1051 				error = EINVAL;
1052 				break;
1053 			}
1054 			if (lt.ia6t_pltime != ND6_INFINITE_LIFETIME &&
1055 			    lt.ia6t_pltime + caltime.tv_sec < caltime.tv_sec) {
1056 				error = EINVAL;
1057 				break;
1058 			}
1059 		} else {
1060 			struct in6_addrlifetime_32 lt;
1061 
1062 			bcopy(&ifr->ifr_ifru.ifru_lifetime, &lt, sizeof(lt));
1063 			if (lt.ia6t_vltime != ND6_INFINITE_LIFETIME &&
1064 			    lt.ia6t_vltime + caltime.tv_sec < caltime.tv_sec) {
1065 				error = EINVAL;
1066 				break;
1067 			}
1068 			if (lt.ia6t_pltime != ND6_INFINITE_LIFETIME &&
1069 			    lt.ia6t_pltime + caltime.tv_sec < caltime.tv_sec) {
1070 				error = EINVAL;
1071 				break;
1072 			}
1073 		}
1074 
1075 		IFA_LOCK(&ia->ia_ifa);
1076 		if (p64) {
1077 			struct in6_addrlifetime_64 lt;
1078 
1079 			bcopy(&ifr->ifr_ifru.ifru_lifetime, &lt, sizeof(lt));
1080 			ia6_lt.ia6t_expire = (time_t)lt.ia6t_expire;
1081 			ia6_lt.ia6t_preferred = (time_t)lt.ia6t_preferred;
1082 			ia6_lt.ia6t_vltime = lt.ia6t_vltime;
1083 			ia6_lt.ia6t_pltime = lt.ia6t_pltime;
1084 		} else {
1085 			struct in6_addrlifetime_32 lt;
1086 
1087 			bcopy(&ifr->ifr_ifru.ifru_lifetime, &lt, sizeof(lt));
1088 			ia6_lt.ia6t_expire = (uint32_t)lt.ia6t_expire;
1089 			ia6_lt.ia6t_preferred = (uint32_t)lt.ia6t_preferred;
1090 			ia6_lt.ia6t_vltime = lt.ia6t_vltime;
1091 			ia6_lt.ia6t_pltime = lt.ia6t_pltime;
1092 		}
1093 		/* for sanity */
1094 		if (ia6_lt.ia6t_vltime != ND6_INFINITE_LIFETIME) {
1095 			ia6_lt.ia6t_expire = (time_t)(timenow + ia6_lt.ia6t_vltime);
1096 		} else {
1097 			ia6_lt.ia6t_expire = 0;
1098 		}
1099 
1100 		if (ia6_lt.ia6t_pltime != ND6_INFINITE_LIFETIME) {
1101 			ia6_lt.ia6t_preferred = (time_t)(timenow + ia6_lt.ia6t_pltime);
1102 		} else {
1103 			ia6_lt.ia6t_preferred = 0;
1104 		}
1105 
1106 		in6ifa_setlifetime(ia, &ia6_lt);
1107 		IFA_UNLOCK(&ia->ia_ifa);
1108 		break;
1109 
1110 	default:
1111 		VERIFY(0);
1112 		/* NOTREACHED */
1113 	}
1114 
1115 	return error;
1116 }
1117 
1118 static int
in6ctl_clat46start(struct ifnet * ifp)1119 in6ctl_clat46start(struct ifnet *ifp)
1120 {
1121 	struct nd_prefix *pr = NULL;
1122 	struct nd_prefix *next = NULL;
1123 	struct in6_ifaddr *ia6 = NULL;
1124 	int error = 0;
1125 
1126 	if (ifp == lo_ifp) {
1127 		return EINVAL;
1128 	}
1129 	/*
1130 	 * Traverse the list of prefixes and find the first non-linklocal
1131 	 * prefix on the interface.
1132 	 * For that found eligible prefix, configure a CLAT46 reserved address.
1133 	 */
1134 	lck_mtx_lock(nd6_mutex);
1135 	for (pr = nd_prefix.lh_first; pr; pr = next) {
1136 		next = pr->ndpr_next;
1137 
1138 		NDPR_LOCK(pr);
1139 		if (pr->ndpr_ifp != ifp) {
1140 			NDPR_UNLOCK(pr);
1141 			continue;
1142 		}
1143 
1144 		if (IN6_IS_ADDR_LINKLOCAL(&pr->ndpr_prefix.sin6_addr)) {
1145 			NDPR_UNLOCK(pr);
1146 			continue; /* XXX */
1147 		}
1148 
1149 		if (pr->ndpr_raf_auto == 0) {
1150 			NDPR_UNLOCK(pr);
1151 			continue;
1152 		}
1153 
1154 		if (pr->ndpr_stateflags & NDPRF_DEFUNCT) {
1155 			NDPR_UNLOCK(pr);
1156 			continue;
1157 		}
1158 
1159 		if ((pr->ndpr_stateflags & NDPRF_CLAT46) == 0
1160 		    && pr->ndpr_vltime != 0) {
1161 			NDPR_ADDREF(pr); /* Take reference for rest of the processing */
1162 			NDPR_UNLOCK(pr);
1163 			break;
1164 		} else {
1165 			NDPR_UNLOCK(pr);
1166 			continue;
1167 		}
1168 	}
1169 	lck_mtx_unlock(nd6_mutex);
1170 
1171 	if (pr != NULL) {
1172 		if ((ia6 = in6_pfx_newpersistaddr(pr, FALSE, &error,
1173 		    TRUE, CLAT46_COLLISION_COUNT_OFFSET)) == NULL) {
1174 			nd6log0(error,
1175 			    "Could not configure CLAT46 address on"
1176 			    " interface %s.\n", ifp->if_xname);
1177 		} else {
1178 			IFA_LOCK(&ia6->ia_ifa);
1179 			NDPR_LOCK(pr);
1180 			ia6->ia6_ndpr = pr;
1181 			NDPR_ADDREF(pr); /* for addr reference */
1182 			pr->ndpr_stateflags |= NDPRF_CLAT46;
1183 			pr->ndpr_addrcnt++;
1184 			VERIFY(pr->ndpr_addrcnt != 0);
1185 			NDPR_UNLOCK(pr);
1186 			IFA_UNLOCK(&ia6->ia_ifa);
1187 			IFA_REMREF(&ia6->ia_ifa);
1188 			ia6 = NULL;
1189 			/*
1190 			 * A newly added address might affect the status
1191 			 * of other addresses, so we check and update it.
1192 			 * XXX: what if address duplication happens?
1193 			 */
1194 			lck_mtx_lock(nd6_mutex);
1195 			pfxlist_onlink_check();
1196 			lck_mtx_unlock(nd6_mutex);
1197 		}
1198 		NDPR_REMREF(pr);
1199 	}
1200 	return error;
1201 }
1202 
1203 static int
in6ctl_clat46stop(struct ifnet * ifp)1204 in6ctl_clat46stop(struct ifnet *ifp)
1205 {
1206 	int error = 0;
1207 	struct in6_ifaddr *ia = NULL;
1208 
1209 	if (ifp == lo_ifp) {
1210 		return EINVAL;
1211 	}
1212 	if ((ifp->if_eflags & IFEF_CLAT46) == 0) {
1213 		/* CLAT46 isn't enabled */
1214 		goto done;
1215 	}
1216 	if_clear_eflags(ifp, IFEF_CLAT46);
1217 
1218 	/* find CLAT46 address and remove it */
1219 	lck_rw_lock_exclusive(&in6_ifaddr_rwlock);
1220 	TAILQ_FOREACH(ia, &in6_ifaddrhead, ia6_link) {
1221 		if (ia->ia_ifa.ifa_ifp != ifp) {
1222 			continue;
1223 		}
1224 		IFA_LOCK(&ia->ia_ifa);
1225 		if ((ia->ia6_flags & IN6_IFF_CLAT46) != 0) {
1226 			IFA_ADDREF_LOCKED(&ia->ia_ifa); /* for us */
1227 			IFA_UNLOCK(&ia->ia_ifa);
1228 			lck_rw_done(&in6_ifaddr_rwlock);
1229 			in6_purgeaddr(&ia->ia_ifa);
1230 			IFA_REMREF(&ia->ia_ifa);        /* for us */
1231 			goto done;
1232 		}
1233 		IFA_UNLOCK(&ia->ia_ifa);
1234 	}
1235 	lck_rw_done(&in6_ifaddr_rwlock);
1236 
1237 done:
1238 	return error;
1239 }
1240 
1241 #define ifa2ia6(ifa)    ((struct in6_ifaddr *)(void *)(ifa))
1242 
1243 /*
1244  * Generic INET6 control operations (ioctl's).
1245  *
1246  * ifp is NULL if not an interface-specific ioctl.
1247  *
1248  * Most of the routines called to handle the ioctls would end up being
1249  * tail-call optimized, which unfortunately causes this routine to
1250  * consume too much stack space; this is the reason for the "noinline"
1251  * attribute used on those routines.
1252  *
1253  * If called directly from within the networking stack (as opposed to via
1254  * pru_control), the socket parameter may be NULL.
1255  */
1256 int
in6_control(struct socket * so,u_long cmd,caddr_t data,struct ifnet * ifp,struct proc * p)1257 in6_control(struct socket *so, u_long cmd, caddr_t data, struct ifnet *ifp,
1258     struct proc *p)
1259 {
1260 	struct in6_ifreq *ifr = (struct in6_ifreq *)(void *)data;
1261 	struct in6_aliasreq sifra, *ifra = NULL;
1262 	struct in6_ifaddr *ia = NULL;
1263 	struct sockaddr_in6 sin6, *sa6 = NULL;
1264 	boolean_t privileged = (proc_suser(p) == 0);
1265 	boolean_t p64 = proc_is64bit(p);
1266 	boolean_t so_unlocked = FALSE;
1267 	int intval, error = 0;
1268 
1269 	/* In case it's NULL, make sure it came from the kernel */
1270 	VERIFY(so != NULL || p == kernproc);
1271 
1272 	/*
1273 	 * ioctls which don't require ifp, may require socket.
1274 	 */
1275 	switch (cmd) {
1276 	case SIOCAADDRCTL_POLICY:       /* struct in6_addrpolicy */
1277 	case SIOCDADDRCTL_POLICY:       /* struct in6_addrpolicy */
1278 		if (!privileged) {
1279 			return EPERM;
1280 		}
1281 		return in6_src_ioctl(cmd, data);
1282 	/* NOTREACHED */
1283 
1284 	case SIOCDRADD_IN6_32:          /* struct in6_defrouter_32 */
1285 	case SIOCDRADD_IN6_64:          /* struct in6_defrouter_64 */
1286 	case SIOCDRDEL_IN6_32:          /* struct in6_defrouter_32 */
1287 	case SIOCDRDEL_IN6_64:          /* struct in6_defrouter_64 */
1288 		if (!privileged) {
1289 			return EPERM;
1290 		}
1291 		return defrtrlist_ioctl(cmd, data);
1292 	/* NOTREACHED */
1293 
1294 	case SIOCGASSOCIDS32:           /* struct so_aidreq32 */
1295 	case SIOCGASSOCIDS64:           /* struct so_aidreq64 */
1296 		return in6ctl_associd(so, cmd, data);
1297 	/* NOTREACHED */
1298 
1299 	case SIOCGCONNIDS32:            /* struct so_cidreq32 */
1300 	case SIOCGCONNIDS64:            /* struct so_cidreq64 */
1301 		return in6ctl_connid(so, cmd, data);
1302 	/* NOTREACHED */
1303 
1304 	case SIOCGCONNINFO32:           /* struct so_cinforeq32 */
1305 	case SIOCGCONNINFO64:           /* struct so_cinforeq64 */
1306 		return in6ctl_conninfo(so, cmd, data);
1307 		/* NOTREACHED */
1308 	}
1309 
1310 	/*
1311 	 * The rest of ioctls require ifp; reject if we don't have one;
1312 	 * return ENXIO to be consistent with ifioctl().
1313 	 */
1314 	if (ifp == NULL) {
1315 		return ENXIO;
1316 	}
1317 
1318 	/*
1319 	 * Unlock the socket since ifnet_ioctl() may be invoked by
1320 	 * one of the ioctl handlers below.  Socket will be re-locked
1321 	 * prior to returning.
1322 	 */
1323 	if (so != NULL) {
1324 		socket_unlock(so, 0);
1325 		so_unlocked = TRUE;
1326 	}
1327 
1328 	/*
1329 	 * ioctls which require ifp but not interface address.
1330 	 */
1331 	switch (cmd) {
1332 	case SIOCAUTOCONF_START:        /* struct in6_ifreq */
1333 		if (!privileged) {
1334 			error = EPERM;
1335 			goto done;
1336 		}
1337 		error = in6_autoconf(ifp, TRUE);
1338 		goto done;
1339 
1340 	case SIOCAUTOCONF_STOP:         /* struct in6_ifreq */
1341 		if (!privileged) {
1342 			error = EPERM;
1343 			goto done;
1344 		}
1345 		error = in6_autoconf(ifp, FALSE);
1346 		goto done;
1347 
1348 	case SIOCLL_START_32:           /* struct in6_aliasreq_32 */
1349 	case SIOCLL_START_64:           /* struct in6_aliasreq_64 */
1350 		if (!privileged) {
1351 			error = EPERM;
1352 			goto done;
1353 		}
1354 		error = in6ctl_llstart(ifp, cmd, data);
1355 		goto done;
1356 
1357 	case SIOCLL_STOP:               /* struct in6_ifreq */
1358 		if (!privileged) {
1359 			error = EPERM;
1360 			goto done;
1361 		}
1362 		error = in6ctl_llstop(ifp);
1363 		goto done;
1364 
1365 	case SIOCCLAT46_START:          /* struct in6_ifreq */
1366 		if (!privileged) {
1367 			error = EPERM;
1368 			goto done;
1369 		}
1370 		error = in6ctl_clat46start(ifp);
1371 		if (error == 0) {
1372 			if_set_eflags(ifp, IFEF_CLAT46);
1373 		}
1374 		goto done;
1375 
1376 	case SIOCCLAT46_STOP:           /* struct in6_ifreq */
1377 		if (!privileged) {
1378 			error = EPERM;
1379 			goto done;
1380 		}
1381 		error = in6ctl_clat46stop(ifp);
1382 		goto done;
1383 	case SIOCGETROUTERMODE_IN6:     /* struct in6_ifreq */
1384 		intval = ifp->if_ipv6_router_mode;
1385 		bcopy(&intval, &((struct in6_ifreq *)(void *)data)->ifr_intval,
1386 		    sizeof(intval));
1387 		goto done;
1388 	case SIOCSETROUTERMODE_IN6:     /* struct in6_ifreq */
1389 		if (!privileged) {
1390 			error = EPERM;
1391 			goto done;
1392 		}
1393 		bcopy(&((struct in6_ifreq *)(void *)data)->ifr_intval,
1394 		    &intval, sizeof(intval));
1395 		switch (intval) {
1396 		case IPV6_ROUTER_MODE_DISABLED:
1397 		case IPV6_ROUTER_MODE_EXCLUSIVE:
1398 		case IPV6_ROUTER_MODE_HYBRID:
1399 			break;
1400 		default:
1401 			error = EINVAL;
1402 			goto done;
1403 		}
1404 		error = in6_setrouter(ifp, (ipv6_router_mode_t)intval);
1405 		goto done;
1406 
1407 	case SIOCPROTOATTACH_IN6_32:    /* struct in6_aliasreq_32 */
1408 	case SIOCPROTOATTACH_IN6_64:    /* struct in6_aliasreq_64 */
1409 		if (!privileged) {
1410 			error = EPERM;
1411 			goto done;
1412 		}
1413 		error = in6_domifattach(ifp);
1414 		goto done;
1415 
1416 	case SIOCPROTODETACH_IN6:       /* struct in6_ifreq */
1417 		if (!privileged) {
1418 			error = EPERM;
1419 			goto done;
1420 		}
1421 		/* Cleanup interface routes and addresses */
1422 		in6_purgeif(ifp);
1423 
1424 		if ((error = proto_unplumb(PF_INET6, ifp))) {
1425 			log(LOG_ERR, "SIOCPROTODETACH_IN6: %s error=%d\n",
1426 			    if_name(ifp), error);
1427 		}
1428 		goto done;
1429 
1430 	case SIOCSNDFLUSH_IN6:          /* struct in6_ifreq */
1431 	case SIOCSPFXFLUSH_IN6:         /* struct in6_ifreq */
1432 	case SIOCSRTRFLUSH_IN6:         /* struct in6_ifreq */
1433 	case SIOCSDEFIFACE_IN6_32:      /* struct in6_ndifreq_32 */
1434 	case SIOCSDEFIFACE_IN6_64:      /* struct in6_ndifreq_64 */
1435 	case SIOCSIFINFO_FLAGS:         /* struct in6_ndireq */
1436 	case SIOCGIFCGAPREP_IN6_32:     /* struct in6_cgareq_32 */
1437 	case SIOCGIFCGAPREP_IN6_64:     /* struct in6_cgareq_64 */
1438 	case SIOCSIFCGAPREP_IN6_32:     /* struct in6_cgareq_32 */
1439 	case SIOCSIFCGAPREP_IN6_64:     /* struct in6_cgareq_32 */
1440 		if (!privileged) {
1441 			error = EPERM;
1442 			goto done;
1443 		}
1444 		OS_FALLTHROUGH;
1445 	case OSIOCGIFINFO_IN6:          /* struct in6_ondireq */
1446 	case SIOCGIFINFO_IN6:           /* struct in6_ondireq */
1447 	case SIOCGDRLST_IN6_32:         /* struct in6_drlist_32 */
1448 	case SIOCGDRLST_IN6_64:         /* struct in6_drlist_64 */
1449 	case SIOCGPRLST_IN6_32:         /* struct in6_prlist_32 */
1450 	case SIOCGPRLST_IN6_64:         /* struct in6_prlist_64 */
1451 	case SIOCGNBRINFO_IN6_32:       /* struct in6_nbrinfo_32 */
1452 	case SIOCGNBRINFO_IN6_64:       /* struct in6_nbrinfo_64 */
1453 	case SIOCGDEFIFACE_IN6_32:      /* struct in6_ndifreq_32 */
1454 	case SIOCGDEFIFACE_IN6_64:      /* struct in6_ndifreq_64 */
1455 		error = nd6_ioctl(cmd, data, ifp);
1456 		goto done;
1457 
1458 	case SIOCSIFPREFIX_IN6:         /* struct in6_prefixreq (deprecated) */
1459 	case SIOCDIFPREFIX_IN6:         /* struct in6_prefixreq (deprecated) */
1460 	case SIOCAIFPREFIX_IN6:         /* struct in6_rrenumreq (deprecated) */
1461 	case SIOCCIFPREFIX_IN6:         /* struct in6_rrenumreq (deprecated) */
1462 	case SIOCSGIFPREFIX_IN6:        /* struct in6_rrenumreq (deprecated) */
1463 	case SIOCGIFPREFIX_IN6:         /* struct in6_prefixreq (deprecated) */
1464 		log(LOG_NOTICE,
1465 		    "prefix ioctls are now invalidated. "
1466 		    "please use ifconfig.\n");
1467 		error = EOPNOTSUPP;
1468 		goto done;
1469 
1470 	case SIOCSSCOPE6:               /* struct in6_ifreq (deprecated) */
1471 	case SIOCGSCOPE6:               /* struct in6_ifreq (deprecated) */
1472 	case SIOCGSCOPE6DEF:            /* struct in6_ifreq (deprecated) */
1473 		error = EOPNOTSUPP;
1474 		goto done;
1475 
1476 	case SIOCLL_CGASTART_32:        /* struct in6_cgareq_32 */
1477 	case SIOCLL_CGASTART_64:        /* struct in6_cgareq_64 */
1478 		if (!privileged) {
1479 			error = EPERM;
1480 		} else {
1481 			error = in6ctl_cgastart(ifp, cmd, data);
1482 		}
1483 		goto done;
1484 
1485 	case SIOCGIFSTAT_IN6:           /* struct in6_ifreq */
1486 	case SIOCGIFSTAT_ICMP6:         /* struct in6_ifreq */
1487 		error = in6ctl_gifstat(ifp, cmd, ifr);
1488 		goto done;
1489 	}
1490 
1491 	/*
1492 	 * ioctls which require interface address; obtain sockaddr_in6.
1493 	 */
1494 	switch (cmd) {
1495 	case SIOCSIFADDR_IN6:           /* struct in6_ifreq (deprecated) */
1496 	case SIOCSIFDSTADDR_IN6:        /* struct in6_ifreq (deprecated) */
1497 	case SIOCSIFNETMASK_IN6:        /* struct in6_ifreq (deprecated) */
1498 		/*
1499 		 * Since IPv6 allows a node to assign multiple addresses
1500 		 * on a single interface, SIOCSIFxxx ioctls are deprecated.
1501 		 */
1502 		/* we decided to obsolete this command (20000704) */
1503 		error = EOPNOTSUPP;
1504 		goto done;
1505 
1506 	case SIOCAIFADDR_IN6_32:        /* struct in6_aliasreq_32 */
1507 	case SIOCAIFADDR_IN6_64:        /* struct in6_aliasreq_64 */
1508 		if (!privileged) {
1509 			error = EPERM;
1510 			goto done;
1511 		}
1512 		/*
1513 		 * Convert user ifra to the kernel form, when appropriate.
1514 		 * This allows the conversion between different data models
1515 		 * to be centralized, so that it can be passed around to other
1516 		 * routines that are expecting the kernel form.
1517 		 */
1518 		ifra = in6_aliasreq_to_native(data,
1519 		    (cmd == SIOCAIFADDR_IN6_64), &sifra);
1520 		bcopy(&ifra->ifra_addr, &sin6, sizeof(sin6));
1521 		sa6 = &sin6;
1522 		break;
1523 
1524 	case SIOCDIFADDR_IN6:           /* struct in6_ifreq */
1525 	case SIOCSIFALIFETIME_IN6:      /* struct in6_ifreq */
1526 		if (!privileged) {
1527 			error = EPERM;
1528 			goto done;
1529 		}
1530 		OS_FALLTHROUGH;
1531 	case SIOCGIFADDR_IN6:           /* struct in6_ifreq */
1532 	case SIOCGIFDSTADDR_IN6:        /* struct in6_ifreq */
1533 	case SIOCGIFNETMASK_IN6:        /* struct in6_ifreq */
1534 	case SIOCGIFAFLAG_IN6:          /* struct in6_ifreq */
1535 	case SIOCGIFALIFETIME_IN6:      /* struct in6_ifreq */
1536 		bcopy(&ifr->ifr_addr, &sin6, sizeof(sin6));
1537 		sa6 = &sin6;
1538 		break;
1539 	case SIOCGIFDSTADDR:
1540 	case SIOCSIFDSTADDR:
1541 	case SIOCGIFBRDADDR:
1542 	case SIOCSIFBRDADDR:
1543 	case SIOCGIFNETMASK:
1544 	case SIOCSIFNETMASK:
1545 	case SIOCGIFADDR:
1546 	case SIOCSIFADDR:
1547 	case SIOCAIFADDR:
1548 	case SIOCDIFADDR:
1549 		/* Do not handle these AF_INET commands in AF_INET6 path */
1550 		error = EINVAL;
1551 		goto done;
1552 	}
1553 
1554 	/*
1555 	 * Find address for this interface, if it exists.
1556 	 *
1557 	 * In netinet code, we have checked ifra_addr in SIOCSIF*ADDR operation
1558 	 * only, and used the first interface address as the target of other
1559 	 * operations (without checking ifra_addr).  This was because netinet
1560 	 * code/API assumed at most 1 interface address per interface.
1561 	 * Since IPv6 allows a node to assign multiple addresses
1562 	 * on a single interface, we almost always look and check the
1563 	 * presence of ifra_addr, and reject invalid ones here.
1564 	 * It also decreases duplicated code among SIOC*_IN6 operations.
1565 	 */
1566 	VERIFY(ia == NULL);
1567 	if (sa6 != NULL && sa6->sin6_family == AF_INET6) {
1568 		if (IN6_IS_ADDR_LINKLOCAL(&sa6->sin6_addr)) {
1569 			if (in6_embedded_scope) {
1570 				if (sa6->sin6_addr.s6_addr16[1] == 0) {
1571 					/* link ID is not embedded by the user */
1572 					sa6->sin6_addr.s6_addr16[1] =
1573 					    htons(ifp->if_index);
1574 				} else if (sa6->sin6_addr.s6_addr16[1] !=
1575 				    htons(ifp->if_index)) {
1576 					error = EINVAL; /* link ID contradicts */
1577 					goto done;
1578 				}
1579 				if (sa6->sin6_scope_id) {
1580 					if (sa6->sin6_scope_id !=
1581 					    (u_int32_t)ifp->if_index) {
1582 						error = EINVAL;
1583 						goto done;
1584 					}
1585 					sa6->sin6_scope_id = 0; /* XXX: good way? */
1586 				}
1587 			} else {
1588 				if (sa6->sin6_scope_id == IFSCOPE_NONE) {
1589 					sa6->sin6_scope_id = ifp->if_index;
1590 				} else if (sa6->sin6_scope_id != ifp->if_index) {
1591 					error = EINVAL; /* link ID contradicts */
1592 					goto done;
1593 				}
1594 			}
1595 		}
1596 		/*
1597 		 * Any failures from this point on must take into account
1598 		 * a non-NULL "ia" with an outstanding reference count, and
1599 		 * therefore requires IFA_REMREF.  Jump to "done" label
1600 		 * instead of calling return if "ia" is valid.
1601 		 */
1602 		ia = in6ifa_ifpwithaddr(ifp, &sa6->sin6_addr);
1603 	}
1604 
1605 	/*
1606 	 * SIOCDIFADDR_IN6/SIOCAIFADDR_IN6 specific tests.
1607 	 */
1608 	switch (cmd) {
1609 	case SIOCDIFADDR_IN6:           /* struct in6_ifreq */
1610 		if (ia == NULL) {
1611 			error = EADDRNOTAVAIL;
1612 			goto done;
1613 		}
1614 		OS_FALLTHROUGH;
1615 	case SIOCAIFADDR_IN6_32:        /* struct in6_aliasreq_32 */
1616 	case SIOCAIFADDR_IN6_64:        /* struct in6_aliasreq_64 */
1617 		VERIFY(sa6 != NULL);
1618 		/*
1619 		 * We always require users to specify a valid IPv6 address for
1620 		 * the corresponding operation.  Use "sa6" instead of "ifra"
1621 		 * since SIOCDIFADDR_IN6 falls thru above.
1622 		 */
1623 		if (sa6->sin6_family != AF_INET6 ||
1624 		    sa6->sin6_len != sizeof(struct sockaddr_in6)) {
1625 			error = EAFNOSUPPORT;
1626 			goto done;
1627 		}
1628 
1629 		if ((cmd == SIOCAIFADDR_IN6_32 || cmd == SIOCAIFADDR_IN6_64) &&
1630 		    (IN6_IS_ADDR_UNSPECIFIED(&sa6->sin6_addr) ||
1631 		    IN6_IS_ADDR_MULTICAST(&sa6->sin6_addr) ||
1632 		    IN6_IS_ADDR_V4MAPPED(&sa6->sin6_addr) ||
1633 		    IN6_IS_ADDR_V4COMPAT(&sa6->sin6_addr))) {
1634 			error = EINVAL;
1635 			goto done;
1636 		}
1637 		break;
1638 	}
1639 
1640 	/*
1641 	 * And finally process address-related ioctls.
1642 	 */
1643 	switch (cmd) {
1644 	case SIOCGIFADDR_IN6:           /* struct in6_ifreq */
1645 	/* This interface is basically deprecated. use SIOCGIFCONF. */
1646 	/* FALLTHRU */
1647 	case SIOCGIFDSTADDR_IN6:        /* struct in6_ifreq */
1648 		error = in6ctl_gifaddr(ifp, ia, cmd, ifr);
1649 		break;
1650 
1651 	case SIOCGIFNETMASK_IN6:        /* struct in6_ifreq */
1652 		if (ia != NULL) {
1653 			IFA_LOCK(&ia->ia_ifa);
1654 			bcopy(&ia->ia_prefixmask, &ifr->ifr_addr,
1655 			    sizeof(struct sockaddr_in6));
1656 			IFA_UNLOCK(&ia->ia_ifa);
1657 		} else {
1658 			error = EADDRNOTAVAIL;
1659 		}
1660 		break;
1661 
1662 	case SIOCGIFAFLAG_IN6:          /* struct in6_ifreq */
1663 		if (ia != NULL) {
1664 			IFA_LOCK(&ia->ia_ifa);
1665 			bcopy(&ia->ia6_flags, &ifr->ifr_ifru.ifru_flags6,
1666 			    sizeof(ifr->ifr_ifru.ifru_flags6));
1667 			IFA_UNLOCK(&ia->ia_ifa);
1668 		} else {
1669 			error = EADDRNOTAVAIL;
1670 		}
1671 		break;
1672 
1673 	case SIOCGIFALIFETIME_IN6:      /* struct in6_ifreq */
1674 	case SIOCSIFALIFETIME_IN6:      /* struct in6_ifreq */
1675 		error = in6ctl_alifetime(ia, cmd, ifr, p64);
1676 		break;
1677 
1678 	case SIOCAIFADDR_IN6_32:        /* struct in6_aliasreq_32 */
1679 	case SIOCAIFADDR_IN6_64:        /* struct in6_aliasreq_64 */
1680 		error = in6ctl_aifaddr(ifp, ifra);
1681 		break;
1682 
1683 	case SIOCDIFADDR_IN6:
1684 		in6ctl_difaddr(ifp, ia);
1685 		break;
1686 
1687 	default:
1688 		error = ifnet_ioctl(ifp, PF_INET6, cmd, data);
1689 		break;
1690 	}
1691 
1692 done:
1693 	if (ia != NULL) {
1694 		IFA_REMREF(&ia->ia_ifa);
1695 	}
1696 	if (so_unlocked) {
1697 		socket_lock(so, 0);
1698 	}
1699 
1700 	return error;
1701 }
1702 
1703 static __attribute__((noinline)) int
in6ctl_aifaddr(struct ifnet * ifp,struct in6_aliasreq * ifra)1704 in6ctl_aifaddr(struct ifnet *ifp, struct in6_aliasreq *ifra)
1705 {
1706 	int i, error, addtmp;
1707 	uint8_t plen;
1708 	struct nd_prefix pr0, *pr;
1709 	struct in6_ifaddr *ia;
1710 
1711 	VERIFY(ifp != NULL && ifra != NULL);
1712 	ia = NULL;
1713 
1714 	/* Attempt to attach the protocol, in case it isn't attached */
1715 	error = in6_domifattach(ifp);
1716 	if (error == 0) {
1717 		/* PF_INET6 wasn't previously attached */
1718 		error = in6_ifattach_aliasreq(ifp, NULL, NULL);
1719 		if (error != 0) {
1720 			goto done;
1721 		}
1722 
1723 		in6_if_up_dad_start(ifp);
1724 	} else if (error != EEXIST) {
1725 		goto done;
1726 	}
1727 
1728 	/*
1729 	 * First, make or update the interface address structure, and link it
1730 	 * to the list.
1731 	 */
1732 	error = in6_update_ifa(ifp, ifra, 0, &ia);
1733 	if (error != 0) {
1734 		goto done;
1735 	}
1736 	VERIFY(ia != NULL);
1737 
1738 	/* Now, make the prefix on-link on the interface. */
1739 	plen = (uint8_t)in6_mask2len(&ifra->ifra_prefixmask.sin6_addr, NULL);
1740 	if (plen == 128) {
1741 		goto done;
1742 	}
1743 
1744 	/*
1745 	 * NOTE: We'd rather create the prefix before the address, but we need
1746 	 * at least one address to install the corresponding interface route,
1747 	 * so we configure the address first.
1748 	 */
1749 
1750 	/*
1751 	 * Convert mask to prefix length (prefixmask has already been validated
1752 	 * in in6_update_ifa().
1753 	 */
1754 	bzero(&pr0, sizeof(pr0));
1755 	pr0.ndpr_plen = plen;
1756 	pr0.ndpr_ifp = ifp;
1757 	pr0.ndpr_prefix = ifra->ifra_addr;
1758 	pr0.ndpr_mask = ifra->ifra_prefixmask.sin6_addr;
1759 
1760 	/* apply the mask for safety. */
1761 	for (i = 0; i < 4; i++) {
1762 		pr0.ndpr_prefix.sin6_addr.s6_addr32[i] &=
1763 		    ifra->ifra_prefixmask.sin6_addr.s6_addr32[i];
1764 	}
1765 
1766 	/*
1767 	 * Since we don't have an API to set prefix (not address) lifetimes, we
1768 	 * just use the same lifetimes as addresses. The (temporarily)
1769 	 * installed lifetimes can be overridden by later advertised RAs (when
1770 	 * accept_rtadv is non 0), which is an intended behavior.
1771 	 */
1772 	pr0.ndpr_raf_onlink = 1; /* should be configurable? */
1773 	pr0.ndpr_raf_auto = !!(ifra->ifra_flags & IN6_IFF_AUTOCONF);
1774 	if (ifra->ifra_flags & (IN6_IFF_AUTOCONF | IN6_IFF_DYNAMIC)) {
1775 		pr0.ndpr_vltime = ifra->ifra_lifetime.ia6t_vltime;
1776 		pr0.ndpr_pltime = ifra->ifra_lifetime.ia6t_pltime;
1777 	} else {
1778 		pr0.ndpr_vltime = ND6_INFINITE_LIFETIME;
1779 		pr0.ndpr_pltime = ND6_INFINITE_LIFETIME;
1780 	}
1781 	pr0.ndpr_stateflags |= NDPRF_STATIC;
1782 	lck_mtx_init(&pr0.ndpr_lock, &ifa_mtx_grp, &ifa_mtx_attr);
1783 
1784 	/* add the prefix if there's none. */
1785 	if ((pr = nd6_prefix_lookup(&pr0, ND6_PREFIX_EXPIRY_NEVER)) == NULL) {
1786 		/*
1787 		 * nd6_prelist_add will install the corresponding interface
1788 		 * route.
1789 		 */
1790 		error = nd6_prelist_add(&pr0, NULL, &pr, FALSE);
1791 		if (error != 0) {
1792 			goto done;
1793 		}
1794 
1795 		if (pr == NULL) {
1796 			log(LOG_ERR, "%s: nd6_prelist_add okay, but"
1797 			    " no prefix.\n", __func__);
1798 			error = EINVAL;
1799 			goto done;
1800 		}
1801 	}
1802 
1803 	IFA_LOCK(&ia->ia_ifa);
1804 
1805 	/* if this is a new autoconfed addr */
1806 	addtmp = FALSE;
1807 	if (ia->ia6_ndpr == NULL) {
1808 		NDPR_LOCK(pr);
1809 		++pr->ndpr_addrcnt;
1810 		VERIFY(pr->ndpr_addrcnt != 0);
1811 		ia->ia6_ndpr = pr;
1812 		NDPR_ADDREF(pr); /* for addr reference */
1813 
1814 		/*
1815 		 * If this is the first autoconf address from the prefix,
1816 		 * create a temporary address as well (when specified).
1817 		 */
1818 		if ((ia->ia6_flags & IN6_IFF_AUTOCONF) != 0 &&
1819 		    ip6_use_tempaddr &&
1820 		    pr->ndpr_addrcnt == 1 &&
1821 		    (!IN6_IS_ADDR_UNIQUE_LOCAL(&ia->ia_addr.sin6_addr)
1822 		    || ip6_ula_use_tempaddr)) {
1823 			addtmp = true;
1824 		}
1825 		NDPR_UNLOCK(pr);
1826 	}
1827 
1828 	IFA_UNLOCK(&ia->ia_ifa);
1829 
1830 	if (addtmp) {
1831 		int e;
1832 		e = in6_tmpifadd(ia, 1);
1833 		if (e != 0) {
1834 			log(LOG_NOTICE, "%s: failed to create a"
1835 			    " temporary address, error=%d\n",
1836 			    __func__, e);
1837 		}
1838 	}
1839 
1840 	/*
1841 	 * This might affect the status of autoconfigured addresses, that is,
1842 	 * this address might make other addresses detached.
1843 	 */
1844 	lck_mtx_lock(nd6_mutex);
1845 	pfxlist_onlink_check();
1846 	lck_mtx_unlock(nd6_mutex);
1847 
1848 	/* Drop use count held above during lookup/add */
1849 	NDPR_REMREF(pr);
1850 
1851 done:
1852 	if (ia != NULL) {
1853 		IFA_REMREF(&ia->ia_ifa);
1854 	}
1855 	return error;
1856 }
1857 
1858 static __attribute__((noinline)) void
in6ctl_difaddr(struct ifnet * ifp,struct in6_ifaddr * ia)1859 in6ctl_difaddr(struct ifnet *ifp, struct in6_ifaddr *ia)
1860 {
1861 	int i = 0;
1862 	struct nd_prefix pr0, *pr;
1863 
1864 	VERIFY(ifp != NULL && ia != NULL);
1865 
1866 	/*
1867 	 * If the address being deleted is the only one that owns
1868 	 * the corresponding prefix, expire the prefix as well.
1869 	 * XXX: theoretically, we don't have to worry about such
1870 	 * relationship, since we separate the address management
1871 	 * and the prefix management.  We do this, however, to provide
1872 	 * as much backward compatibility as possible in terms of
1873 	 * the ioctl operation.
1874 	 * Note that in6_purgeaddr() will decrement ndpr_addrcnt.
1875 	 */
1876 	IFA_LOCK(&ia->ia_ifa);
1877 	bzero(&pr0, sizeof(pr0));
1878 	pr0.ndpr_ifp = ifp;
1879 	pr0.ndpr_plen = (uint8_t)in6_mask2len(&ia->ia_prefixmask.sin6_addr, NULL);
1880 	if (pr0.ndpr_plen == 128) {
1881 		IFA_UNLOCK(&ia->ia_ifa);
1882 		goto purgeaddr;
1883 	}
1884 	pr0.ndpr_prefix = ia->ia_addr;
1885 	pr0.ndpr_mask = ia->ia_prefixmask.sin6_addr;
1886 	for (i = 0; i < 4; i++) {
1887 		pr0.ndpr_prefix.sin6_addr.s6_addr32[i] &=
1888 		    ia->ia_prefixmask.sin6_addr.s6_addr32[i];
1889 	}
1890 	IFA_UNLOCK(&ia->ia_ifa);
1891 
1892 	if ((pr = nd6_prefix_lookup(&pr0, ND6_PREFIX_EXPIRY_UNSPEC)) != NULL) {
1893 		IFA_LOCK(&ia->ia_ifa);
1894 		NDPR_LOCK(pr);
1895 		if (pr->ndpr_addrcnt == 1) {
1896 			/* XXX: just for expiration */
1897 			pr->ndpr_expire = 1;
1898 		}
1899 		NDPR_UNLOCK(pr);
1900 		IFA_UNLOCK(&ia->ia_ifa);
1901 
1902 		/* Drop use count held above during lookup */
1903 		NDPR_REMREF(pr);
1904 	}
1905 
1906 purgeaddr:
1907 	in6_purgeaddr(&ia->ia_ifa);
1908 }
1909 
1910 static __attribute__((noinline)) int
in6_autoconf(struct ifnet * ifp,int enable)1911 in6_autoconf(struct ifnet *ifp, int enable)
1912 {
1913 	int error = 0;
1914 
1915 	VERIFY(ifp != NULL);
1916 
1917 	if (ifp->if_flags & IFF_LOOPBACK) {
1918 		return EINVAL;
1919 	}
1920 
1921 	if (enable) {
1922 		/*
1923 		 * An interface in IPv6 router mode implies that it
1924 		 * is either configured with a static IP address or
1925 		 * autoconfigured via a locally-generated RA.  Prevent
1926 		 * SIOCAUTOCONF_START from being set in that mode.
1927 		 */
1928 		ifnet_lock_exclusive(ifp);
1929 		if (ifp->if_ipv6_router_mode == IPV6_ROUTER_MODE_EXCLUSIVE) {
1930 			if_clear_eflags(ifp, IFEF_ACCEPT_RTADV);
1931 			error = EBUSY;
1932 		} else {
1933 			if_set_eflags(ifp, IFEF_ACCEPT_RTADV);
1934 		}
1935 		ifnet_lock_done(ifp);
1936 	} else {
1937 		struct in6_ifaddr *ia = NULL;
1938 
1939 		if_clear_eflags(ifp, IFEF_ACCEPT_RTADV);
1940 
1941 		/* Remove autoconfigured address from interface */
1942 		lck_rw_lock_exclusive(&in6_ifaddr_rwlock);
1943 		boolean_t from_begining = TRUE;
1944 		while (from_begining) {
1945 			from_begining = FALSE;
1946 			TAILQ_FOREACH(ia, &in6_ifaddrhead, ia6_link) {
1947 				if (ia->ia_ifa.ifa_ifp != ifp) {
1948 					continue;
1949 				}
1950 				IFA_LOCK(&ia->ia_ifa);
1951 				if (ia->ia6_flags & IN6_IFF_AUTOCONF) {
1952 					IFA_ADDREF_LOCKED(&ia->ia_ifa); /* for us */
1953 					IFA_UNLOCK(&ia->ia_ifa);
1954 					lck_rw_done(&in6_ifaddr_rwlock);
1955 					in6_purgeaddr(&ia->ia_ifa);
1956 					IFA_REMREF(&ia->ia_ifa);        /* for us */
1957 					lck_rw_lock_exclusive(&in6_ifaddr_rwlock);
1958 					/*
1959 					 * Purging the address caused in6_ifaddr_rwlock
1960 					 * to be dropped and reacquired;
1961 					 * therefore search again from the beginning
1962 					 * of in6_ifaddrs list.
1963 					 */
1964 					from_begining = TRUE;
1965 					break;
1966 				}
1967 				IFA_UNLOCK(&ia->ia_ifa);
1968 			}
1969 		}
1970 		lck_rw_done(&in6_ifaddr_rwlock);
1971 	}
1972 	return error;
1973 }
1974 
1975 /*
1976  * Handle SIOCSETROUTERMODE_IN6 to set the IPv6 router mode on the interface
1977  * Entering or exiting IPV6_ROUTER_MODE_EXCLUSIVE will result in the removal of
1978  * autoconfigured IPv6 addresses on the interface.
1979  */
1980 static __attribute__((noinline)) int
in6_setrouter(struct ifnet * ifp,ipv6_router_mode_t mode)1981 in6_setrouter(struct ifnet *ifp, ipv6_router_mode_t mode)
1982 {
1983 	int                     error = 0;
1984 	ipv6_router_mode_t      prev_mode;
1985 
1986 	VERIFY(ifp != NULL);
1987 
1988 	if (ifp->if_flags & IFF_LOOPBACK) {
1989 		return ENODEV;
1990 	}
1991 
1992 	prev_mode = ifp->if_ipv6_router_mode;
1993 	if (prev_mode == mode) {
1994 		/* no mode change, there's nothing to do */
1995 		return 0;
1996 	}
1997 	if (mode == IPV6_ROUTER_MODE_EXCLUSIVE) {
1998 		struct nd_ifinfo *ndi = NULL;
1999 
2000 		ndi = ND_IFINFO(ifp);
2001 		if (ndi != NULL && ndi->initialized) {
2002 			lck_mtx_lock(&ndi->lock);
2003 			if (ndi->flags & ND6_IFF_PROXY_PREFIXES) {
2004 				/* No proxy if we are an advertising router */
2005 				ndi->flags &= ~ND6_IFF_PROXY_PREFIXES;
2006 				lck_mtx_unlock(&ndi->lock);
2007 				(void) nd6_if_prproxy(ifp, FALSE);
2008 			} else {
2009 				lck_mtx_unlock(&ndi->lock);
2010 			}
2011 		}
2012 	}
2013 
2014 	ifp->if_ipv6_router_mode = mode;
2015 	lck_mtx_lock(nd6_mutex);
2016 	defrouter_select(ifp, NULL);
2017 	lck_mtx_unlock(nd6_mutex);
2018 	if_allmulti(ifp, (mode == IPV6_ROUTER_MODE_EXCLUSIVE));
2019 	if (mode == IPV6_ROUTER_MODE_EXCLUSIVE ||
2020 	    (prev_mode == IPV6_ROUTER_MODE_EXCLUSIVE
2021 	    && mode == IPV6_ROUTER_MODE_DISABLED)) {
2022 		error = in6_autoconf(ifp, FALSE);
2023 	}
2024 	return error;
2025 }
2026 
2027 static int
in6_to_kamescope(struct sockaddr_in6 * sin6,struct ifnet * ifp)2028 in6_to_kamescope(struct sockaddr_in6 *sin6, struct ifnet *ifp)
2029 {
2030 	struct sockaddr_in6 tmp;
2031 	int error, id;
2032 
2033 	VERIFY(sin6 != NULL);
2034 	tmp = *sin6;
2035 
2036 	error = in6_recoverscope(&tmp, &sin6->sin6_addr, ifp);
2037 	if (error != 0) {
2038 		return error;
2039 	}
2040 
2041 	id = in6_addr2scopeid(ifp, &tmp.sin6_addr);
2042 	if (tmp.sin6_scope_id == 0) {
2043 		tmp.sin6_scope_id = id;
2044 	} else if (tmp.sin6_scope_id != id) {
2045 		return EINVAL; /* scope ID mismatch. */
2046 	}
2047 	error = in6_embedscope(&tmp.sin6_addr, &tmp, NULL, NULL, NULL, IN6_NULL_IF_EMBEDDED_SCOPE(&tmp.sin6_scope_id));
2048 	if (error != 0) {
2049 		return error;
2050 	}
2051 
2052 	if (in6_embedded_scope || !IN6_IS_SCOPE_EMBED(&tmp.sin6_addr)) {
2053 		tmp.sin6_scope_id = 0;
2054 	}
2055 	*sin6 = tmp;
2056 	return 0;
2057 }
2058 
2059 /*
2060  * When the address is being configured we should clear out certain flags
2061  * coming in from the caller.
2062  */
2063 #define IN6_IFF_CLR_ADDR_FLAG_MASK      (~(IN6_IFF_DEPRECATED | IN6_IFF_DETACHED | IN6_IFF_DUPLICATED))
2064 
2065 static int
in6_ifaupdate_aux(struct in6_ifaddr * ia,struct ifnet * ifp,int ifaupflags)2066 in6_ifaupdate_aux(struct in6_ifaddr *ia, struct ifnet *ifp, int ifaupflags)
2067 {
2068 	struct sockaddr_in6 mltaddr, mltmask;
2069 	struct in6_addr llsol;
2070 	struct ifaddr *ifa;
2071 	struct in6_multi *in6m_sol;
2072 	struct in6_multi_mship *imm;
2073 	struct rtentry *rt;
2074 	int delay, error = 0;
2075 
2076 	VERIFY(ifp != NULL && ia != NULL);
2077 	ifa = &ia->ia_ifa;
2078 	in6m_sol = NULL;
2079 
2080 	nd6log2(debug, "%s - %s ifp %s ia6_flags 0x%x ifaupflags 0x%x\n",
2081 	    __func__,
2082 	    ip6_sprintf(&ia->ia_addr.sin6_addr),
2083 	    if_name(ia->ia_ifp),
2084 	    ia->ia6_flags,
2085 	    ifaupflags);
2086 
2087 	/*
2088 	 * Just to be safe, always clear certain flags when address
2089 	 * is being configured
2090 	 */
2091 	ia->ia6_flags &= IN6_IFF_CLR_ADDR_FLAG_MASK;
2092 
2093 	/*
2094 	 * Mark the address as tentative before joining multicast addresses,
2095 	 * so that corresponding MLD responses would not have a tentative
2096 	 * source address.
2097 	 */
2098 	if (in6if_do_dad(ifp)) {
2099 		in6_ifaddr_set_dadprogress(ia);
2100 		/*
2101 		 * Do not delay sending neighbor solicitations when using optimistic
2102 		 * duplicate address detection, c.f. RFC 4429.
2103 		 */
2104 		if (ia->ia6_flags & IN6_IFF_OPTIMISTIC) {
2105 			ifaupflags &= ~IN6_IFAUPDATE_DADDELAY;
2106 		} else {
2107 			ifaupflags |= IN6_IFAUPDATE_DADDELAY;
2108 		}
2109 	} else {
2110 		/*
2111 		 * If the interface has been marked to not perform
2112 		 * DAD, make sure to reset DAD in progress flags
2113 		 * that may come in from the caller.
2114 		 */
2115 		ia->ia6_flags &= ~IN6_IFF_DADPROGRESS;
2116 	}
2117 
2118 	/* Join necessary multicast groups */
2119 	if ((ifp->if_flags & IFF_MULTICAST) != 0) {
2120 		/* join solicited multicast addr for new host id */
2121 		bzero(&llsol, sizeof(struct in6_addr));
2122 		llsol.s6_addr32[0] = IPV6_ADDR_INT32_MLL;
2123 		llsol.s6_addr32[1] = 0;
2124 		llsol.s6_addr32[2] = htonl(1);
2125 		llsol.s6_addr32[3] = ia->ia_addr.sin6_addr.s6_addr32[3];
2126 		llsol.s6_addr8[12] = 0xff;
2127 		if ((error = in6_setscope(&llsol, ifp, NULL)) != 0) {
2128 			/* XXX: should not happen */
2129 			log(LOG_ERR, "%s: in6_setscope failed\n", __func__);
2130 			goto unwind;
2131 		}
2132 		delay = 0;
2133 		if ((ifaupflags & IN6_IFAUPDATE_DADDELAY)) {
2134 			/*
2135 			 * We need a random delay for DAD on the address
2136 			 * being configured.  It also means delaying
2137 			 * transmission of the corresponding MLD report to
2138 			 * avoid report collision. [RFC 4862]
2139 			 */
2140 			delay = random() % MAX_RTR_SOLICITATION_DELAY;
2141 		}
2142 		imm = in6_joingroup(ifp, &llsol, &error, delay);
2143 		if (imm == NULL) {
2144 			nd6log(info,
2145 			    "%s: addmulti failed for %s on %s (errno=%d)\n",
2146 			    __func__, ip6_sprintf(&llsol), if_name(ifp),
2147 			    error);
2148 			VERIFY(error != 0);
2149 			goto unwind;
2150 		}
2151 		in6m_sol = imm->i6mm_maddr;
2152 		/* take a refcount for this routine */
2153 		IN6M_ADDREF(in6m_sol);
2154 
2155 		IFA_LOCK_SPIN(ifa);
2156 		LIST_INSERT_HEAD(&ia->ia6_memberships, imm, i6mm_chain);
2157 		IFA_UNLOCK(ifa);
2158 
2159 		bzero(&mltmask, sizeof(mltmask));
2160 		mltmask.sin6_len = sizeof(struct sockaddr_in6);
2161 		mltmask.sin6_family = AF_INET6;
2162 		mltmask.sin6_addr = in6mask32;
2163 #define MLTMASK_LEN  4  /* mltmask's masklen (=32bit=4octet) */
2164 
2165 		/*
2166 		 * join link-local all-nodes address
2167 		 */
2168 		bzero(&mltaddr, sizeof(mltaddr));
2169 		mltaddr.sin6_len = sizeof(struct sockaddr_in6);
2170 		mltaddr.sin6_family = AF_INET6;
2171 		mltaddr.sin6_addr = in6addr_linklocal_allnodes;
2172 		if ((error = in6_setscope(&mltaddr.sin6_addr, ifp, IN6_NULL_IF_EMBEDDED_SCOPE(&mltaddr.sin6_scope_id))) != 0) {
2173 			goto unwind; /* XXX: should not fail */
2174 		}
2175 		/*
2176 		 * XXX: do we really need this automatic routes?
2177 		 * We should probably reconsider this stuff.  Most applications
2178 		 * actually do not need the routes, since they usually specify
2179 		 * the outgoing interface.
2180 		 */
2181 		rt = rtalloc1_scoped((struct sockaddr *)&mltaddr, 0, 0UL,
2182 		    ia->ia_ifp->if_index);
2183 		if (rt) {
2184 			if (memcmp(&mltaddr.sin6_addr, &((struct sockaddr_in6 *)
2185 			    (void *)rt_key(rt))->sin6_addr, MLTMASK_LEN)) {
2186 				rtfree(rt);
2187 				rt = NULL;
2188 			}
2189 		}
2190 		if (!rt) {
2191 			error = rtrequest_scoped(RTM_ADD,
2192 			    (struct sockaddr *)&mltaddr,
2193 			    (struct sockaddr *)&ia->ia_addr,
2194 			    (struct sockaddr *)&mltmask, RTF_UP | RTF_CLONING,
2195 			    NULL, ia->ia_ifp->if_index);
2196 			if (error) {
2197 				goto unwind;
2198 			}
2199 		} else {
2200 			rtfree(rt);
2201 		}
2202 
2203 		imm = in6_joingroup(ifp, &mltaddr.sin6_addr, &error, 0);
2204 		if (!imm) {
2205 			nd6log(info,
2206 			    "%s: addmulti failed for %s on %s (errno=%d)\n",
2207 			    __func__, ip6_sprintf(&mltaddr.sin6_addr),
2208 			    if_name(ifp), error);
2209 			VERIFY(error != 0);
2210 			goto unwind;
2211 		}
2212 		IFA_LOCK_SPIN(ifa);
2213 		LIST_INSERT_HEAD(&ia->ia6_memberships, imm, i6mm_chain);
2214 		IFA_UNLOCK(ifa);
2215 
2216 		/*
2217 		 * join node information group address
2218 		 */
2219 #define hostnamelen     strlen(hostname)
2220 		delay = 0;
2221 		if ((ifaupflags & IN6_IFAUPDATE_DADDELAY)) {
2222 			/*
2223 			 * The spec doesn't say anything about delay for this
2224 			 * group, but the same logic should apply.
2225 			 */
2226 			delay = random() % MAX_RTR_SOLICITATION_DELAY;
2227 		}
2228 		lck_mtx_lock(&hostname_lock);
2229 		int n = in6_nigroup(ifp, hostname, hostnamelen, &mltaddr.sin6_addr, IN6_NULL_IF_EMBEDDED_SCOPE(&mltaddr.sin6_scope_id));
2230 		lck_mtx_unlock(&hostname_lock);
2231 		if (n == 0) {
2232 			imm = in6_joingroup(ifp, &mltaddr.sin6_addr, &error,
2233 			    delay); /* XXX jinmei */
2234 			if (!imm) {
2235 				nd6log(info,
2236 				    "%s: addmulti failed for %s on %s "
2237 				    "(errno=%d)\n",
2238 				    __func__, ip6_sprintf(&mltaddr.sin6_addr),
2239 				    if_name(ifp), error);
2240 				/* XXX not very fatal, go on... */
2241 				error = 0;
2242 			} else {
2243 				IFA_LOCK_SPIN(ifa);
2244 				LIST_INSERT_HEAD(&ia->ia6_memberships,
2245 				    imm, i6mm_chain);
2246 				IFA_UNLOCK(ifa);
2247 			}
2248 		}
2249 #undef hostnamelen
2250 
2251 		/*
2252 		 * join interface-local all-nodes address.
2253 		 * (ff01::1%ifN, and ff01::%ifN/32)
2254 		 */
2255 		mltaddr.sin6_addr = in6addr_nodelocal_allnodes;
2256 		if ((error = in6_setscope(&mltaddr.sin6_addr, ifp, IN6_NULL_IF_EMBEDDED_SCOPE(&mltaddr.sin6_scope_id))) != 0) {
2257 			goto unwind; /* XXX: should not fail */
2258 		}
2259 		/* XXX: again, do we really need the route? */
2260 		rt = rtalloc1_scoped((struct sockaddr *)&mltaddr, 0, 0UL,
2261 		    ia->ia_ifp->if_index);
2262 		if (rt) {
2263 			if (memcmp(&mltaddr.sin6_addr, &((struct sockaddr_in6 *)
2264 			    (void *)rt_key(rt))->sin6_addr, MLTMASK_LEN)) {
2265 				rtfree(rt);
2266 				rt = NULL;
2267 			}
2268 		}
2269 		if (!rt) {
2270 			error = rtrequest_scoped(RTM_ADD,
2271 			    (struct sockaddr *)&mltaddr,
2272 			    (struct sockaddr *)&ia->ia_addr,
2273 			    (struct sockaddr *)&mltmask, RTF_UP | RTF_CLONING,
2274 			    NULL, ia->ia_ifp->if_index);
2275 			if (error) {
2276 				goto unwind;
2277 			}
2278 		} else {
2279 			rtfree(rt);
2280 		}
2281 
2282 		imm = in6_joingroup(ifp, &mltaddr.sin6_addr, &error, 0);
2283 		if (!imm) {
2284 			nd6log(info,
2285 			    "%s: addmulti failed for %s on %s (errno=%d)\n",
2286 			    __func__, ip6_sprintf(&mltaddr.sin6_addr),
2287 			    if_name(ifp), error);
2288 			VERIFY(error != 0);
2289 			goto unwind;
2290 		}
2291 		IFA_LOCK(ifa);
2292 		LIST_INSERT_HEAD(&ia->ia6_memberships, imm, i6mm_chain);
2293 		IFA_UNLOCK(ifa);
2294 #undef  MLTMASK_LEN
2295 
2296 		/*
2297 		 * create a ff00::/8 route
2298 		 */
2299 		bzero(&mltmask, sizeof(mltmask));
2300 		mltmask.sin6_len = sizeof(struct sockaddr_in6);
2301 		mltmask.sin6_family = AF_INET6;
2302 		mltmask.sin6_addr = in6mask8;
2303 #define MLTMASK_LEN_8_BITS  1  /* ff00::/8 mltmask's masklen (=8bit=1octet) */
2304 
2305 		bzero(&mltaddr, sizeof(mltaddr));
2306 		mltaddr.sin6_len = sizeof(struct sockaddr_in6);
2307 		mltaddr.sin6_family = AF_INET6;
2308 		mltaddr.sin6_addr = in6addr_multicast_prefix;
2309 
2310 		rt = rtalloc1_scoped((struct sockaddr *)&mltaddr, 0, 0UL,
2311 		    ia->ia_ifp->if_index);
2312 		if (rt) {
2313 			if (memcmp(&mltaddr.sin6_addr, &((struct sockaddr_in6 *)
2314 			    (void *)rt_key(rt))->sin6_addr, MLTMASK_LEN_8_BITS)) {
2315 				rtfree(rt);
2316 				rt = NULL;
2317 			}
2318 		}
2319 		if (!rt) {
2320 			error = rtrequest_scoped(RTM_ADD,
2321 			    (struct sockaddr *)&mltaddr,
2322 			    (struct sockaddr *)&ia->ia_addr,
2323 			    (struct sockaddr *)&mltmask, RTF_UP | RTF_CLONING,
2324 			    NULL, ia->ia_ifp->if_index);
2325 			if (error) {
2326 				goto unwind;
2327 			}
2328 		} else {
2329 			rtfree(rt);
2330 		}
2331 	}
2332 #undef  MLTMASK_LEN_8_BITS
2333 
2334 	/* Ensure nd6_service() is scheduled as soon as it's convenient */
2335 	++nd6_sched_timeout_want;
2336 
2337 	/*
2338 	 * Perform DAD, if:
2339 	 * * Interface is marked to perform DAD, AND
2340 	 * * Address is not marked to skip DAD, AND
2341 	 * * Address is in a pre-DAD state (Tentative or Optimistic)
2342 	 */
2343 	IFA_LOCK_SPIN(ifa);
2344 	if (in6if_do_dad(ifp) && (ia->ia6_flags & IN6_IFF_NODAD) == 0 &&
2345 	    (ia->ia6_flags & IN6_IFF_DADPROGRESS) != 0) {
2346 		int mindelay, maxdelay;
2347 		int *delayptr, delayval;
2348 
2349 		IFA_UNLOCK(ifa);
2350 		delayptr = NULL;
2351 		/*
2352 		 * Avoid the DAD delay if the caller wants us to skip it.
2353 		 * This is not compliant with RFC 2461, but it's only being
2354 		 * used for signalling and not for actual DAD.
2355 		 */
2356 		if ((ifaupflags & IN6_IFAUPDATE_DADDELAY) &&
2357 		    !(ia->ia6_flags & IN6_IFF_SWIFTDAD)) {
2358 			/*
2359 			 * We need to impose a delay before sending an NS
2360 			 * for DAD.  Check if we also needed a delay for the
2361 			 * corresponding MLD message.  If we did, the delay
2362 			 * should be larger than the MLD delay (this could be
2363 			 * relaxed a bit, but this simple logic is at least
2364 			 * safe).
2365 			 */
2366 			mindelay = 0;
2367 			if (in6m_sol != NULL) {
2368 				IN6M_LOCK(in6m_sol);
2369 				if (in6m_sol->in6m_state ==
2370 				    MLD_REPORTING_MEMBER) {
2371 					mindelay = in6m_sol->in6m_timer;
2372 				}
2373 				IN6M_UNLOCK(in6m_sol);
2374 			}
2375 			maxdelay = MAX_RTR_SOLICITATION_DELAY * hz;
2376 			if (maxdelay - mindelay == 0) {
2377 				delayval = 0;
2378 			} else {
2379 				delayval =
2380 				    (random() % (maxdelay - mindelay)) +
2381 				    mindelay;
2382 			}
2383 			delayptr = &delayval;
2384 		}
2385 
2386 		nd6_dad_start((struct ifaddr *)ia, delayptr);
2387 	} else {
2388 		IFA_UNLOCK(ifa);
2389 	}
2390 
2391 	goto done;
2392 
2393 unwind:
2394 	VERIFY(error != 0);
2395 	in6_purgeaddr(&ia->ia_ifa);
2396 
2397 done:
2398 	/* release reference held for this routine */
2399 	if (in6m_sol != NULL) {
2400 		IN6M_REMREF(in6m_sol);
2401 	}
2402 	return error;
2403 }
2404 
2405 /*
2406  * Request an IPv6 interface address.  If the address is new, then it will be
2407  * constructed and appended to the interface address chains.  The interface
2408  * address structure is optionally returned with a reference for the caller.
2409  */
2410 int
in6_update_ifa(struct ifnet * ifp,struct in6_aliasreq * ifra,int ifaupflags,struct in6_ifaddr ** iar)2411 in6_update_ifa(struct ifnet *ifp, struct in6_aliasreq *ifra, int ifaupflags,
2412     struct in6_ifaddr **iar)
2413 {
2414 	struct in6_addrlifetime ia6_lt;
2415 	struct in6_ifaddr *ia;
2416 	struct ifaddr *ifa;
2417 	struct ifaddr *xifa;
2418 	struct in6_addrlifetime *lt;
2419 	uint64_t timenow;
2420 	int plen, error;
2421 
2422 	/* Sanity check parameters and initialize locals */
2423 	VERIFY(ifp != NULL && ifra != NULL && iar != NULL);
2424 	ia = NULL;
2425 	ifa = NULL;
2426 	error = 0;
2427 
2428 	/*
2429 	 * We always require users to specify a valid IPv6 address for
2430 	 * the corresponding operation.
2431 	 */
2432 	if (ifra->ifra_addr.sin6_family != AF_INET6 ||
2433 	    ifra->ifra_addr.sin6_len != sizeof(struct sockaddr_in6)) {
2434 		error = EAFNOSUPPORT;
2435 		goto unwind;
2436 	}
2437 
2438 	/* Validate ifra_prefixmask.sin6_len is properly bounded. */
2439 	if (ifra->ifra_prefixmask.sin6_len == 0 ||
2440 	    ifra->ifra_prefixmask.sin6_len > sizeof(struct sockaddr_in6)) {
2441 		error = EINVAL;
2442 		goto unwind;
2443 	}
2444 
2445 	/* Validate prefix length extracted from ifra_prefixmask structure. */
2446 	plen = (uint8_t)in6_mask2len(&ifra->ifra_prefixmask.sin6_addr,
2447 	    (u_char *)&ifra->ifra_prefixmask + ifra->ifra_prefixmask.sin6_len);
2448 	if (plen <= 0) {
2449 		error = EINVAL;
2450 		goto unwind;
2451 	}
2452 
2453 	/* Validate lifetimes */
2454 	lt = &ifra->ifra_lifetime;
2455 	if (lt->ia6t_pltime > lt->ia6t_vltime) {
2456 		log(LOG_INFO,
2457 		    "%s: pltime 0x%x > vltime 0x%x for %s\n", __func__,
2458 		    lt->ia6t_pltime, lt->ia6t_vltime,
2459 		    ip6_sprintf(&ifra->ifra_addr.sin6_addr));
2460 		error = EINVAL;
2461 		goto unwind;
2462 	}
2463 	if (lt->ia6t_vltime == 0) {
2464 		/*
2465 		 * the following log might be noisy, but this is a typical
2466 		 * configuration mistake or a tool's bug.
2467 		 */
2468 		log(LOG_INFO, "%s: valid lifetime is 0 for %s\n", __func__,
2469 		    ip6_sprintf(&ifra->ifra_addr.sin6_addr));
2470 	}
2471 
2472 	/*
2473 	 * Before we lock the ifnet structure, we first check to see if the
2474 	 * address already exists. If so, then we don't allocate and link a
2475 	 * new one here.
2476 	 */
2477 	struct sockaddr_in6 lookup_address = ifra->ifra_addr;
2478 	if (IN6_IS_ADDR_LINKLOCAL(&lookup_address.sin6_addr)) {
2479 		if (in6_embedded_scope) {
2480 			if (lookup_address.sin6_addr.s6_addr16[1] == 0) {
2481 				/* link ID is not embedded by the user */
2482 				lookup_address.sin6_addr.s6_addr16[1] =
2483 				    htons(ifp->if_index);
2484 			} else if (lookup_address.sin6_addr.s6_addr16[1] !=
2485 			    htons(ifp->if_index)) {
2486 				error = EINVAL; /* link ID contradicts */
2487 				goto done;
2488 			}
2489 		} else {
2490 			if (lookup_address.sin6_scope_id == IFSCOPE_NONE) {
2491 				lookup_address.sin6_scope_id = ifp->if_index;
2492 			}
2493 		}
2494 		if (lookup_address.sin6_scope_id != 0 &&
2495 		    lookup_address.sin6_scope_id !=
2496 		    (u_int32_t)ifp->if_index) {
2497 			error = EINVAL;
2498 			goto done;
2499 		}
2500 	}
2501 
2502 	ia = in6ifa_ifpwithaddr(ifp, &lookup_address.sin6_addr);
2503 	if (ia != NULL) {
2504 		ifa = &ia->ia_ifa;
2505 	}
2506 
2507 	/*
2508 	 * Validate destination address on interface types that require it.
2509 	 */
2510 	if ((ifp->if_flags & (IFF_LOOPBACK | IFF_POINTOPOINT)) != 0) {
2511 		switch (ifra->ifra_dstaddr.sin6_family) {
2512 		case AF_INET6:
2513 			if (plen != 128) {
2514 				/* noisy message for diagnostic purposes */
2515 				log(LOG_INFO,
2516 				    "%s: prefix length < 128 with"
2517 				    " explicit dstaddr.\n", __func__);
2518 				error = EINVAL;
2519 				goto unwind;
2520 			}
2521 			break;
2522 
2523 		case AF_UNSPEC:
2524 			break;
2525 
2526 		default:
2527 			error = EAFNOSUPPORT;
2528 			goto unwind;
2529 		}
2530 	} else if (ifra->ifra_dstaddr.sin6_family != AF_UNSPEC) {
2531 		log(LOG_INFO,
2532 		    "%s: dstaddr valid only on p2p and loopback interfaces.\n",
2533 		    __func__);
2534 		error = EINVAL;
2535 		goto unwind;
2536 	}
2537 
2538 	timenow = net_uptime();
2539 
2540 	if (ia == NULL) {
2541 		zalloc_flags_t how;
2542 
2543 		/* Is this the first new IPv6 address for the interface? */
2544 		ifaupflags |= IN6_IFAUPDATE_NEWADDR;
2545 
2546 		/* Allocate memory for IPv6 interface address structure. */
2547 		how = (ifaupflags & IN6_IFAUPDATE_NOWAIT) ? Z_NOWAIT : Z_WAITOK;
2548 		ia = in6_ifaddr_alloc(how);
2549 		if (ia == NULL) {
2550 			error = ENOBUFS;
2551 			goto unwind;
2552 		}
2553 
2554 		ifa = &ia->ia_ifa;
2555 
2556 		/*
2557 		 * Initialize interface address structure.
2558 		 *
2559 		 * Note well: none of these sockaddr_in6 structures contain a
2560 		 * valid sin6_port, sin6_flowinfo or even a sin6_scope_id field.
2561 		 * We still embed link-local scope identifiers at the end of an
2562 		 * arbitrary fe80::/32 prefix, for historical reasons. Also, the
2563 		 * ifa_dstaddr field is always non-NULL on point-to-point and
2564 		 * loopback interfaces, and conventionally points to a socket
2565 		 * address of AF_UNSPEC family when there is no destination.
2566 		 *
2567 		 * Please enjoy the dancing sea turtle.
2568 		 */
2569 		IFA_ADDREF(ifa); /* for this and optionally for caller */
2570 		IA6_HASH_INIT(ia);
2571 		ifa->ifa_addr = (struct sockaddr *)&ia->ia_addr;
2572 		if (ifra->ifra_dstaddr.sin6_family == AF_INET6 ||
2573 		    (ifp->if_flags & (IFF_POINTOPOINT | IFF_LOOPBACK)) != 0) {
2574 			ifa->ifa_dstaddr = (struct sockaddr *)&ia->ia_dstaddr;
2575 		}
2576 		ifa->ifa_netmask = (struct sockaddr *)&ia->ia_prefixmask;
2577 		ifa->ifa_ifp = ifp;
2578 		ifa->ifa_metric = ifp->if_metric;
2579 		ifa->ifa_rtrequest = nd6_rtrequest;
2580 
2581 		LIST_INIT(&ia->ia6_memberships);
2582 		ia->ia_addr.sin6_family = AF_INET6;
2583 		ia->ia_addr.sin6_len = sizeof(ia->ia_addr);
2584 		ia->ia_addr.sin6_addr = ifra->ifra_addr.sin6_addr;
2585 		ia->ia_prefixmask.sin6_family = AF_INET6;
2586 		ia->ia_prefixmask.sin6_len = sizeof(ia->ia_prefixmask);
2587 		ia->ia_prefixmask.sin6_addr = ifra->ifra_prefixmask.sin6_addr;
2588 		error = in6_to_kamescope(&ia->ia_addr, ifp);
2589 		if (error != 0) {
2590 			goto unwind;
2591 		}
2592 		if (ifa->ifa_dstaddr != NULL) {
2593 			ia->ia_dstaddr = ifra->ifra_dstaddr;
2594 			error = in6_to_kamescope(&ia->ia_dstaddr, ifp);
2595 			if (error != 0) {
2596 				goto unwind;
2597 			}
2598 		}
2599 
2600 		/* Append to address chains */
2601 		ifnet_lock_exclusive(ifp);
2602 		ifaupflags |= IN6_IFAUPDATE_1STADDR;
2603 		TAILQ_FOREACH(xifa, &ifp->if_addrlist, ifa_list) {
2604 			IFA_LOCK_SPIN(xifa);
2605 			if (xifa->ifa_addr->sa_family != AF_INET6) {
2606 				IFA_UNLOCK(xifa);
2607 				ifaupflags &= ~IN6_IFAUPDATE_1STADDR;
2608 				break;
2609 			}
2610 			IFA_UNLOCK(xifa);
2611 		}
2612 
2613 		IFA_LOCK_SPIN(ifa);
2614 		if_attach_ifa(ifp, ifa); /* holds reference for ifnet link */
2615 		IFA_UNLOCK(ifa);
2616 		ifnet_lock_done(ifp);
2617 
2618 		lck_rw_lock_exclusive(&in6_ifaddr_rwlock);
2619 		TAILQ_INSERT_TAIL(&in6_ifaddrhead, ia, ia6_link);
2620 		IFA_ADDREF(ifa); /* hold for in6_ifaddrs link */
2621 		lck_rw_done(&in6_ifaddr_rwlock);
2622 	} else {
2623 		ifa = &ia->ia_ifa;
2624 		ifaupflags &= ~(IN6_IFAUPDATE_NEWADDR | IN6_IFAUPDATE_1STADDR);
2625 	}
2626 
2627 	VERIFY(ia != NULL && ifa == &ia->ia_ifa);
2628 	IFA_LOCK(ifa);
2629 
2630 	/*
2631 	 * Set lifetimes.  We do not refer to ia6t_expire and ia6t_preferred
2632 	 * to see if the address is deprecated or invalidated, but initialize
2633 	 * these members for applications.
2634 	 */
2635 	ia->ia6_updatetime = ia->ia6_createtime = timenow;
2636 	ia6_lt = *lt;
2637 	if (ia6_lt.ia6t_vltime != ND6_INFINITE_LIFETIME) {
2638 		ia6_lt.ia6t_expire = (time_t)(timenow + ia6_lt.ia6t_vltime);
2639 	} else {
2640 		ia6_lt.ia6t_expire = 0;
2641 	}
2642 	if (ia6_lt.ia6t_pltime != ND6_INFINITE_LIFETIME) {
2643 		ia6_lt.ia6t_preferred = (time_t)(timenow + ia6_lt.ia6t_pltime);
2644 	} else {
2645 		ia6_lt.ia6t_preferred = 0;
2646 	}
2647 	in6ifa_setlifetime(ia, &ia6_lt);
2648 
2649 	/*
2650 	 * Backward compatibility - if IN6_IFF_DEPRECATED is set from the
2651 	 * userland, make it deprecated.
2652 	 */
2653 	if ((ia->ia6_flags & IN6_IFF_DEPRECATED) != 0) {
2654 		ia->ia6_lifetime.ia6ti_pltime = 0;
2655 		ia->ia6_lifetime.ia6ti_preferred = timenow;
2656 	}
2657 
2658 	/*
2659 	 * Update flag or prefix length
2660 	 */
2661 	ia->ia_plen = plen;
2662 	ia->ia6_flags = ifra->ifra_flags;
2663 
2664 	/* Release locks (new address available to concurrent tasks) */
2665 	IFA_UNLOCK(ifa);
2666 
2667 	/* Further initialization of the interface address */
2668 	error = in6_ifinit(ifp, ia, ifaupflags);
2669 	if (error != 0) {
2670 		goto unwind;
2671 	}
2672 
2673 	/* Finish updating the address while other tasks are working with it */
2674 	error = in6_ifaupdate_aux(ia, ifp, ifaupflags);
2675 	if (error != 0) {
2676 		goto unwind;
2677 	}
2678 
2679 	/* Return success (optionally w/ address for caller). */
2680 	VERIFY(error == 0);
2681 	(void) ifnet_notify_address(ifp, AF_INET6);
2682 
2683 	goto done;
2684 
2685 unwind:
2686 	VERIFY(error != 0);
2687 	if (ia != NULL) {
2688 		VERIFY(ifa == &ia->ia_ifa);
2689 		IFA_REMREF(ifa);
2690 		ia = NULL;
2691 	}
2692 
2693 done:
2694 	*iar = ia;
2695 	return error;
2696 }
2697 
2698 void
in6_purgeaddr(struct ifaddr * ifa)2699 in6_purgeaddr(struct ifaddr *ifa)
2700 {
2701 	struct ifnet *ifp = ifa->ifa_ifp;
2702 	struct in6_ifaddr *ia = (struct in6_ifaddr *)ifa;
2703 	struct in6_multi_mship *imm;
2704 
2705 	LCK_MTX_ASSERT(nd6_mutex, LCK_MTX_ASSERT_NOTOWNED);
2706 
2707 	/* stop DAD processing */
2708 	nd6_dad_stop(ifa);
2709 
2710 	/*
2711 	 * delete route to the destination of the address being purged.
2712 	 * The interface must be p2p or loopback in this case.
2713 	 */
2714 	IFA_LOCK(ifa);
2715 	if ((ia->ia_flags & IFA_ROUTE) && ia->ia_plen == 128) {
2716 		int error, rtf;
2717 
2718 		IFA_UNLOCK(ifa);
2719 		rtf = (ia->ia_dstaddr.sin6_family == AF_INET6) ? RTF_HOST : 0;
2720 		error = rtinit(&(ia->ia_ifa), RTM_DELETE, rtf);
2721 		if (error != 0) {
2722 			log(LOG_ERR, "in6_purgeaddr: failed to remove "
2723 			    "a route to the p2p destination: %s on %s, "
2724 			    "errno=%d\n",
2725 			    ip6_sprintf(&ia->ia_addr.sin6_addr), if_name(ifp),
2726 			    error);
2727 			/* proceed anyway... */
2728 		}
2729 		IFA_LOCK_SPIN(ifa);
2730 		ia->ia_flags &= ~IFA_ROUTE;
2731 	}
2732 	IFA_UNLOCK(ifa);
2733 
2734 	/* Remove ownaddr's loopback rtentry, if it exists. */
2735 	in6_ifremloop(&(ia->ia_ifa));
2736 
2737 	/*
2738 	 * leave from multicast groups we have joined for the interface
2739 	 */
2740 	IFA_LOCK(ifa);
2741 	while ((imm = ia->ia6_memberships.lh_first) != NULL) {
2742 		LIST_REMOVE(imm, i6mm_chain);
2743 		IFA_UNLOCK(ifa);
2744 		in6_leavegroup(imm);
2745 		IFA_LOCK(ifa);
2746 	}
2747 	IFA_UNLOCK(ifa);
2748 
2749 	/* in6_unlink_ifa() will need exclusive access */
2750 	in6_unlink_ifa(ia, ifp);
2751 	in6_post_msg(ifp, KEV_INET6_ADDR_DELETED, ia, NULL);
2752 
2753 	(void) ifnet_notify_address(ifp, AF_INET6);
2754 }
2755 
2756 static void
in6_unlink_ifa(struct in6_ifaddr * ia,struct ifnet * ifp)2757 in6_unlink_ifa(struct in6_ifaddr *ia, struct ifnet *ifp)
2758 {
2759 	struct in6_ifaddr *nia;
2760 	struct ifaddr *ifa;
2761 	int unlinked;
2762 
2763 	LCK_MTX_ASSERT(nd6_mutex, LCK_MTX_ASSERT_NOTOWNED);
2764 
2765 	ifa = &ia->ia_ifa;
2766 	IFA_ADDREF(ifa);
2767 
2768 	ifnet_lock_exclusive(ifp);
2769 	IFA_LOCK(ifa);
2770 	if (ifa->ifa_debug & IFD_ATTACHED) {
2771 		if_detach_ifa(ifp, ifa);
2772 	}
2773 	IFA_UNLOCK(ifa);
2774 	ifnet_lock_done(ifp);
2775 
2776 	unlinked = 0;
2777 	lck_rw_lock_exclusive(&in6_ifaddr_rwlock);
2778 	TAILQ_FOREACH(nia, &in6_ifaddrhead, ia6_link) {
2779 		if (ia == nia) {
2780 			TAILQ_REMOVE(&in6_ifaddrhead, ia, ia6_link);
2781 			IFA_LOCK(ifa);
2782 			if (IA6_IS_HASHED(ia)) {
2783 				in6_iahash_remove(ia);
2784 			}
2785 			IFA_UNLOCK(ifa);
2786 			unlinked = 1;
2787 			break;
2788 		}
2789 	}
2790 
2791 	/*
2792 	 * When IPv6 address is being removed, release the
2793 	 * reference to the base prefix.
2794 	 * Also, since the release might, affect the status
2795 	 * of other (detached) addresses, call
2796 	 * pfxlist_onlink_check().
2797 	 */
2798 	IFA_LOCK(ifa);
2799 	/*
2800 	 * Only log the below message for addresses other than
2801 	 * link local.
2802 	 * Only one LLA (auto-configured or statically) is allowed
2803 	 * on an interface.
2804 	 * LLA prefix, while added to the prefix list, is not
2805 	 * reference countedi (as it is the only one).
2806 	 * The prefix also never expires on its own as LLAs
2807 	 * have infinite lifetime.
2808 	 *
2809 	 * For now quiece down the log message for LLAs.
2810 	 */
2811 	if (!IN6_IS_ADDR_LINKLOCAL(&ia->ia_addr.sin6_addr)) {
2812 		if (ia->ia6_ndpr == NULL) {
2813 			log(LOG_NOTICE, "in6_unlink_ifa: IPv6 address "
2814 			    "0x%llx has no prefix\n",
2815 			    (uint64_t)VM_KERNEL_ADDRPERM(ia));
2816 		} else {
2817 			struct nd_prefix *pr = ia->ia6_ndpr;
2818 			ia->ia6_flags &= ~IN6_IFF_AUTOCONF;
2819 			ia->ia6_ndpr = NULL;
2820 			NDPR_LOCK(pr);
2821 			VERIFY(pr->ndpr_addrcnt != 0);
2822 			pr->ndpr_addrcnt--;
2823 			if (ia->ia6_flags & IN6_IFF_CLAT46) {
2824 				pr->ndpr_stateflags &= ~NDPRF_CLAT46;
2825 			}
2826 			NDPR_UNLOCK(pr);
2827 			NDPR_REMREF(pr);        /* release addr reference */
2828 		}
2829 	}
2830 	IFA_UNLOCK(ifa);
2831 	lck_rw_done(&in6_ifaddr_rwlock);
2832 
2833 	if ((ia->ia6_flags & IN6_IFF_AUTOCONF) != 0) {
2834 		lck_mtx_lock(nd6_mutex);
2835 		pfxlist_onlink_check();
2836 		lck_mtx_unlock(nd6_mutex);
2837 	}
2838 	/*
2839 	 * release another refcnt for the link from in6_ifaddrs.
2840 	 * Do this only if it's not already unlinked in the event that we lost
2841 	 * the race, since in6_ifaddr_rwlock was momentarily dropped above.
2842 	 */
2843 	if (unlinked) {
2844 		IFA_REMREF(ifa);
2845 	}
2846 
2847 	/* release reference held for this routine */
2848 	IFA_REMREF(ifa);
2849 
2850 	/* invalidate route caches */
2851 	routegenid_inet6_update();
2852 }
2853 
2854 void
in6_purgeif(struct ifnet * ifp)2855 in6_purgeif(struct ifnet *ifp)
2856 {
2857 	struct in6_ifaddr *ia;
2858 
2859 	if (ifp == NULL) {
2860 		return;
2861 	}
2862 
2863 	LCK_MTX_ASSERT(nd6_mutex, LCK_MTX_ASSERT_NOTOWNED);
2864 
2865 	lck_rw_lock_exclusive(&in6_ifaddr_rwlock);
2866 	boolean_t from_begining = TRUE;
2867 	while (from_begining) {
2868 		from_begining = FALSE;
2869 		TAILQ_FOREACH(ia, &in6_ifaddrhead, ia6_link) {
2870 			if (ia->ia_ifa.ifa_ifp != ifp) {
2871 				continue;
2872 			}
2873 			IFA_ADDREF(&ia->ia_ifa);        /* for us */
2874 			lck_rw_done(&in6_ifaddr_rwlock);
2875 			in6_purgeaddr(&ia->ia_ifa);
2876 			IFA_REMREF(&ia->ia_ifa);        /* for us */
2877 			lck_rw_lock_exclusive(&in6_ifaddr_rwlock);
2878 			/*
2879 			 * Purging the address would have caused
2880 			 * in6_ifaddr_rwlock to be dropped and reacquired;
2881 			 * therefore search again from the beginning
2882 			 * of in6_ifaddrs list.
2883 			 */
2884 			from_begining = TRUE;
2885 			break;
2886 		}
2887 	}
2888 	lck_rw_done(&in6_ifaddr_rwlock);
2889 
2890 	in6_ifdetach(ifp);
2891 }
2892 
2893 /*
2894  * Initialize an interface's internet6 address and routing table entry.
2895  */
2896 static int
in6_ifinit(struct ifnet * ifp,struct in6_ifaddr * ia,int ifaupflags)2897 in6_ifinit(struct ifnet *ifp, struct in6_ifaddr *ia, int ifaupflags)
2898 {
2899 	int error;
2900 	struct ifaddr *ifa;
2901 
2902 	error = 0;
2903 	ifa = &ia->ia_ifa;
2904 
2905 	lck_rw_lock_exclusive(&in6_ifaddr_rwlock);
2906 	IFA_LOCK(&ia->ia_ifa);
2907 	if (IA6_IS_HASHED(ia)) {
2908 		in6_iahash_remove(ia);
2909 	}
2910 	if ((ifp->if_flags & IFF_POINTOPOINT)) {
2911 		in6_iahash_insert_ptp(ia);
2912 	} else {
2913 		in6_iahash_insert(ia);
2914 	}
2915 	IFA_UNLOCK(&ia->ia_ifa);
2916 	lck_rw_done(&in6_ifaddr_rwlock);
2917 
2918 	/*
2919 	 * NOTE: SIOCSIFADDR is defined with struct ifreq as parameter,
2920 	 * but here we are sending it down to the interface with a pointer
2921 	 * to struct ifaddr, for legacy reasons.
2922 	 */
2923 	if ((ifaupflags & IN6_IFAUPDATE_1STADDR) != 0) {
2924 		error = ifnet_ioctl(ifp, PF_INET6, SIOCSIFADDR, ia);
2925 		if (error != 0) {
2926 			if (error != EOPNOTSUPP) {
2927 				goto failed;
2928 			}
2929 			error = 0;
2930 		}
2931 	}
2932 
2933 	IFA_LOCK(ifa);
2934 
2935 	/*
2936 	 * Special case:
2937 	 * If the destination address is specified for a point-to-point
2938 	 * interface, install a route to the destination as an interface
2939 	 * direct route.
2940 	 */
2941 	if (!(ia->ia_flags & IFA_ROUTE) && ia->ia_plen == 128 &&
2942 	    ia->ia_dstaddr.sin6_family == AF_INET6) {
2943 		IFA_UNLOCK(ifa);
2944 		error = rtinit(ifa, RTM_ADD, RTF_UP | RTF_HOST);
2945 		if (error != 0) {
2946 			goto failed;
2947 		}
2948 		IFA_LOCK(ifa);
2949 		ia->ia_flags |= IFA_ROUTE;
2950 	}
2951 	IFA_LOCK_ASSERT_HELD(ifa);
2952 	if (ia->ia_plen < 128) {
2953 		/*
2954 		 * The RTF_CLONING flag is necessary for in6_is_ifloop_auto().
2955 		 */
2956 		ia->ia_flags |= RTF_CLONING;
2957 	}
2958 
2959 	IFA_UNLOCK(ifa);
2960 
2961 	/* Add ownaddr as loopback rtentry, if necessary (ex. on p2p link). */
2962 	if ((ifaupflags & IN6_IFAUPDATE_NEWADDR) != 0) {
2963 		in6_ifaddloop(ifa);
2964 	}
2965 
2966 	/* invalidate route caches */
2967 	routegenid_inet6_update();
2968 
2969 	VERIFY(error == 0);
2970 	return 0;
2971 failed:
2972 	VERIFY(error != 0);
2973 	lck_rw_lock_exclusive(&in6_ifaddr_rwlock);
2974 	IFA_LOCK(&ia->ia_ifa);
2975 	if (IA6_IS_HASHED(ia)) {
2976 		in6_iahash_remove(ia);
2977 	}
2978 	IFA_UNLOCK(&ia->ia_ifa);
2979 	lck_rw_done(&in6_ifaddr_rwlock);
2980 
2981 	return error;
2982 }
2983 
2984 void
in6_purgeaddrs(struct ifnet * ifp)2985 in6_purgeaddrs(struct ifnet *ifp)
2986 {
2987 	in6_purgeif(ifp);
2988 }
2989 
2990 /*
2991  * Find an IPv6 interface link-local address specific to an interface.
2992  */
2993 struct in6_ifaddr *
in6ifa_ifpforlinklocal(struct ifnet * ifp,int ignoreflags)2994 in6ifa_ifpforlinklocal(struct ifnet *ifp, int ignoreflags)
2995 {
2996 	struct ifaddr *ifa;
2997 
2998 	ifnet_lock_shared(ifp);
2999 	TAILQ_FOREACH(ifa, &ifp->if_addrlist, ifa_list)
3000 	{
3001 		IFA_LOCK_SPIN(ifa);
3002 		if (ifa->ifa_addr->sa_family != AF_INET6) {
3003 			IFA_UNLOCK(ifa);
3004 			continue;
3005 		}
3006 		if (IN6_IS_ADDR_LINKLOCAL(IFA_IN6(ifa))) {
3007 			if ((((struct in6_ifaddr *)ifa)->ia6_flags &
3008 			    ignoreflags) != 0) {
3009 				IFA_UNLOCK(ifa);
3010 				continue;
3011 			}
3012 			IFA_ADDREF_LOCKED(ifa); /* for caller */
3013 			IFA_UNLOCK(ifa);
3014 			break;
3015 		}
3016 		IFA_UNLOCK(ifa);
3017 	}
3018 	ifnet_lock_done(ifp);
3019 
3020 	return (struct in6_ifaddr *)ifa;
3021 }
3022 
3023 struct in6_ifaddr *
in6ifa_ifpwithflag(struct ifnet * ifp,int flag)3024 in6ifa_ifpwithflag(struct ifnet * ifp, int flag)
3025 {
3026 	struct ifaddr *ifa;
3027 
3028 	ifnet_lock_shared(ifp);
3029 	TAILQ_FOREACH(ifa, &ifp->if_addrlist, ifa_list)
3030 	{
3031 		IFA_LOCK_SPIN(ifa);
3032 		if (ifa->ifa_addr->sa_family != AF_INET6) {
3033 			IFA_UNLOCK(ifa);
3034 			continue;
3035 		}
3036 		if ((((struct in6_ifaddr *)ifa)->ia6_flags & flag) == flag) {
3037 			IFA_ADDREF_LOCKED(ifa);
3038 			IFA_UNLOCK(ifa);
3039 			break;
3040 		}
3041 		IFA_UNLOCK(ifa);
3042 	}
3043 	ifnet_lock_done(ifp);
3044 
3045 	return (struct in6_ifaddr *)ifa;
3046 }
3047 
3048 /*
3049  * find the internet address corresponding to a given interface and address.
3050  */
3051 struct in6_ifaddr *
in6ifa_ifpwithaddr(struct ifnet * ifp,struct in6_addr * addr)3052 in6ifa_ifpwithaddr(struct ifnet *ifp, struct in6_addr *addr)
3053 {
3054 	struct ifaddr *ifa;
3055 
3056 	ifnet_lock_shared(ifp);
3057 	TAILQ_FOREACH(ifa, &ifp->if_addrlist, ifa_list)
3058 	{
3059 		IFA_LOCK_SPIN(ifa);
3060 		if (ifa->ifa_addr->sa_family != AF_INET6) {
3061 			IFA_UNLOCK(ifa);
3062 			continue;
3063 		}
3064 		if (IN6_ARE_ADDR_EQUAL(addr, IFA_IN6(ifa))) {
3065 			IFA_ADDREF_LOCKED(ifa); /* for caller */
3066 			IFA_UNLOCK(ifa);
3067 			break;
3068 		}
3069 		IFA_UNLOCK(ifa);
3070 	}
3071 	ifnet_lock_done(ifp);
3072 
3073 	return (struct in6_ifaddr *)ifa;
3074 }
3075 
3076 struct in6_ifaddr *
in6ifa_prproxyaddr(struct in6_addr * addr,uint32_t ifscope)3077 in6ifa_prproxyaddr(struct in6_addr *addr, uint32_t ifscope)
3078 {
3079 	struct in6_ifaddr *ia;
3080 
3081 	lck_rw_lock_shared(&in6_ifaddr_rwlock);
3082 	TAILQ_FOREACH(ia, IN6ADDR_HASH(addr), ia6_hash) {
3083 		IFA_LOCK(&ia->ia_ifa);
3084 		if (in6_are_addr_equal_scoped(addr, IFA_IN6(&ia->ia_ifa), ifscope, ia->ia_ifp->if_index)) {
3085 			IFA_ADDREF_LOCKED(&ia->ia_ifa); /* for caller */
3086 			IFA_UNLOCK(&ia->ia_ifa);
3087 			break;
3088 		}
3089 		IFA_UNLOCK(&ia->ia_ifa);
3090 	}
3091 	lck_rw_done(&in6_ifaddr_rwlock);
3092 
3093 	if (ia != NULL && !nd6_prproxy_ifaddr(ia)) {
3094 		IFA_REMREF(&ia->ia_ifa);
3095 		ia = NULL;
3096 	}
3097 
3098 	return ia;
3099 }
3100 
3101 void
in6ifa_getlifetime(struct in6_ifaddr * ia6,struct in6_addrlifetime * t_dst,int iscalendar)3102 in6ifa_getlifetime(struct in6_ifaddr *ia6, struct in6_addrlifetime *t_dst,
3103     int iscalendar)
3104 {
3105 	struct in6_addrlifetime_i *t_src = &ia6->ia6_lifetime;
3106 	struct timeval caltime;
3107 
3108 	t_dst->ia6t_vltime = t_src->ia6ti_vltime;
3109 	t_dst->ia6t_pltime = t_src->ia6ti_pltime;
3110 	t_dst->ia6t_expire = 0;
3111 	t_dst->ia6t_preferred = 0;
3112 
3113 	/* account for system time change */
3114 	getmicrotime(&caltime);
3115 	t_src->ia6ti_base_calendartime +=
3116 	    NET_CALCULATE_CLOCKSKEW(caltime,
3117 	    t_src->ia6ti_base_calendartime, net_uptime(),
3118 	    t_src->ia6ti_base_uptime);
3119 
3120 	if (iscalendar) {
3121 		if (t_src->ia6ti_expire != 0 &&
3122 		    t_src->ia6ti_vltime != ND6_INFINITE_LIFETIME) {
3123 			t_dst->ia6t_expire = (time_t)(t_src->ia6ti_base_calendartime +
3124 			    t_src->ia6ti_expire - t_src->ia6ti_base_uptime);
3125 		}
3126 
3127 		if (t_src->ia6ti_preferred != 0 &&
3128 		    t_src->ia6ti_pltime != ND6_INFINITE_LIFETIME) {
3129 			t_dst->ia6t_preferred = (time_t)(t_src->ia6ti_base_calendartime +
3130 			    t_src->ia6ti_preferred - t_src->ia6ti_base_uptime);
3131 		}
3132 	} else {
3133 		if (t_src->ia6ti_expire != 0 &&
3134 		    t_src->ia6ti_vltime != ND6_INFINITE_LIFETIME) {
3135 			t_dst->ia6t_expire = (time_t)t_src->ia6ti_expire;
3136 		}
3137 
3138 		if (t_src->ia6ti_preferred != 0 &&
3139 		    t_src->ia6ti_pltime != ND6_INFINITE_LIFETIME) {
3140 			t_dst->ia6t_preferred = (time_t)t_src->ia6ti_preferred;
3141 		}
3142 	}
3143 }
3144 
3145 void
in6ifa_setlifetime(struct in6_ifaddr * ia6,struct in6_addrlifetime * t_src)3146 in6ifa_setlifetime(struct in6_ifaddr *ia6, struct in6_addrlifetime *t_src)
3147 {
3148 	struct in6_addrlifetime_i *t_dst = &ia6->ia6_lifetime;
3149 	struct timeval caltime;
3150 
3151 	/* account for system time change */
3152 	getmicrotime(&caltime);
3153 	t_dst->ia6ti_base_calendartime +=
3154 	    NET_CALCULATE_CLOCKSKEW(caltime,
3155 	    t_dst->ia6ti_base_calendartime, net_uptime(),
3156 	    t_dst->ia6ti_base_uptime);
3157 
3158 	/* trust the caller for the values */
3159 	t_dst->ia6ti_expire = t_src->ia6t_expire;
3160 	t_dst->ia6ti_preferred = t_src->ia6t_preferred;
3161 	t_dst->ia6ti_vltime = t_src->ia6t_vltime;
3162 	t_dst->ia6ti_pltime = t_src->ia6t_pltime;
3163 }
3164 
3165 /*
3166  * Convert IP6 address to printable (loggable) representation.
3167  */
3168 char *
ip6_sprintf(const struct in6_addr * addr)3169 ip6_sprintf(const struct in6_addr *addr)
3170 {
3171 	static const char digits[] = "0123456789abcdef";
3172 	static int ip6round = 0;
3173 	static char ip6buf[8][48];
3174 
3175 	int i;
3176 	char *cp;
3177 	const u_short *a = (const u_short *)addr;
3178 	const u_char *d;
3179 	u_char n;
3180 	int dcolon = 0;
3181 	int zpad = 0;
3182 
3183 	ip6round = (ip6round + 1) & 7;
3184 	cp = ip6buf[ip6round];
3185 
3186 	for (i = 0; i < 8; i++) {
3187 		if (dcolon == 1) {
3188 			if (*a == 0) {
3189 				if (i == 7) {
3190 					*cp++ = ':';
3191 				}
3192 				a++;
3193 				continue;
3194 			} else {
3195 				dcolon = 2;
3196 			}
3197 		}
3198 		if (*a == 0) {
3199 			if (dcolon == 0 && *(a + 1) == 0) {
3200 				if (i == 0) {
3201 					*cp++ = ':';
3202 				}
3203 				*cp++ = ':';
3204 				dcolon = 1;
3205 			} else {
3206 				*cp++ = '0';
3207 				*cp++ = ':';
3208 			}
3209 			a++;
3210 			continue;
3211 		}
3212 		d = (const u_char *)a;
3213 		zpad = 0;
3214 		if ((n = *d >> 4) != 0) {
3215 			*cp++ = digits[n];
3216 			zpad = 1;
3217 		}
3218 		if ((n = *d++ & 0xf) != 0 || zpad) {
3219 			*cp++ = digits[n];
3220 			zpad = 1;
3221 		}
3222 		if ((n = *d >> 4) != 0 || zpad) {
3223 			*cp++ = digits[n];
3224 			zpad = 1;
3225 		}
3226 		if ((n = *d & 0xf) != 0 || zpad) {
3227 			*cp++ = digits[n];
3228 		}
3229 		*cp++ = ':';
3230 		a++;
3231 	}
3232 	*--cp = 0;
3233 	return ip6buf[ip6round];
3234 }
3235 
3236 int
in6addr_local(struct in6_addr * in6)3237 in6addr_local(struct in6_addr *in6)
3238 {
3239 	struct rtentry *rt;
3240 	struct sockaddr_in6 sin6;
3241 	int local = 0;
3242 
3243 	if (IN6_IS_ADDR_LOOPBACK(in6) || IN6_IS_SCOPE_LINKLOCAL(in6)) {
3244 		return 1;
3245 	}
3246 
3247 	sin6.sin6_family = AF_INET6;
3248 	sin6.sin6_len = sizeof(sin6);
3249 	bcopy(in6, &sin6.sin6_addr, sizeof(*in6));
3250 	rt = rtalloc1((struct sockaddr *)&sin6, 0, 0);
3251 
3252 	if (rt != NULL) {
3253 		RT_LOCK_SPIN(rt);
3254 		if (rt->rt_gateway->sa_family == AF_LINK) {
3255 			local = 1;
3256 		}
3257 		RT_UNLOCK(rt);
3258 		rtfree(rt);
3259 	} else {
3260 		local = in6_localaddr(in6);
3261 	}
3262 	return local;
3263 }
3264 
3265 int
in6_localaddr(struct in6_addr * in6)3266 in6_localaddr(struct in6_addr *in6)
3267 {
3268 	struct in6_ifaddr *ia;
3269 
3270 	if (IN6_IS_ADDR_LOOPBACK(in6) || IN6_IS_ADDR_LINKLOCAL(in6) || IN6_IS_ADDR_MC_UNICAST_BASED_LINKLOCAL(in6)) {
3271 		return 1;
3272 	}
3273 
3274 	lck_rw_lock_shared(&in6_ifaddr_rwlock);
3275 	TAILQ_FOREACH(ia, &in6_ifaddrhead, ia6_link) {
3276 		IFA_LOCK_SPIN(&ia->ia_ifa);
3277 		if (IN6_ARE_MASKED_ADDR_EQUAL(in6, &ia->ia_addr.sin6_addr,
3278 		    &ia->ia_prefixmask.sin6_addr)) {
3279 			IFA_UNLOCK(&ia->ia_ifa);
3280 			lck_rw_done(&in6_ifaddr_rwlock);
3281 			return 1;
3282 		}
3283 		IFA_UNLOCK(&ia->ia_ifa);
3284 	}
3285 	lck_rw_done(&in6_ifaddr_rwlock);
3286 	return 0;
3287 }
3288 
3289 /*
3290  * return length of part which dst and src are equal
3291  * hard coding...
3292  */
3293 int
in6_matchlen(struct in6_addr * src,struct in6_addr * dst)3294 in6_matchlen(struct in6_addr *src, struct in6_addr *dst)
3295 {
3296 	int match = 0;
3297 	u_char *s = (u_char *)src, *d = (u_char *)dst;
3298 	u_char *lim = s + 16, r;
3299 
3300 	while (s < lim) {
3301 		if ((r = (*d++ ^ *s++)) != 0) {
3302 			while (r < 128) {
3303 				match++;
3304 				r <<= 1;
3305 			}
3306 			break;
3307 		} else {
3308 			match += 8;
3309 		}
3310 	}
3311 	return match;
3312 }
3313 
3314 /* XXX: to be scope conscious */
3315 int
in6_are_prefix_equal(struct in6_addr * p1,uint32_t ifscope1,struct in6_addr * p2,uint32_t ifscope2,int len)3316 in6_are_prefix_equal(struct in6_addr *p1, uint32_t ifscope1, struct in6_addr *p2, uint32_t ifscope2, int len)
3317 {
3318 	int bytelen, bitlen;
3319 
3320 	/* sanity check */
3321 	if (0 > len || len > 128) {
3322 		log(LOG_ERR, "%s: invalid prefix length(%d)\n", __func__, len);
3323 		return 0;
3324 	}
3325 
3326 	bytelen = len / 8;
3327 	bitlen = len % 8;
3328 
3329 	if (bcmp(&p1->s6_addr, &p2->s6_addr, bytelen)) {
3330 		return 0;
3331 	}
3332 	if (bitlen != 0 &&
3333 	    p1->s6_addr[bytelen] >> (8 - bitlen) !=
3334 	    p2->s6_addr[bytelen] >> (8 - bitlen)) {
3335 		return 0;
3336 	}
3337 
3338 	if (IN6_IS_SCOPE_EMBED(p1) && !in6_embedded_scope) {
3339 		return ifscope1 == ifscope2;
3340 	}
3341 
3342 	return 1;
3343 }
3344 
3345 void
in6_prefixlen2mask(struct in6_addr * maskp,int len)3346 in6_prefixlen2mask(struct in6_addr *maskp, int len)
3347 {
3348 	u_char maskarray[8] = {0x80, 0xc0, 0xe0, 0xf0, 0xf8, 0xfc, 0xfe, 0xff};
3349 	int bytelen, bitlen, i;
3350 
3351 	/* sanity check */
3352 	if (0 > len || len > 128) {
3353 		log(LOG_ERR, "%s: invalid prefix length(%d)\n", __func__, len);
3354 		return;
3355 	}
3356 
3357 	bzero(maskp, sizeof(*maskp));
3358 	bytelen = len / 8;
3359 	bitlen = len % 8;
3360 	for (i = 0; i < bytelen; i++) {
3361 		maskp->s6_addr[i] = 0xff;
3362 	}
3363 	if (bitlen) {
3364 		maskp->s6_addr[bytelen] = maskarray[bitlen - 1];
3365 	}
3366 }
3367 
3368 /*
3369  * return the best address out of the same scope
3370  */
3371 struct in6_ifaddr *
in6_ifawithscope(struct ifnet * oifp,struct in6_addr * dst)3372 in6_ifawithscope(struct ifnet *oifp, struct in6_addr *dst)
3373 {
3374 	int dst_scope = in6_addrscope(dst), src_scope, best_scope = 0;
3375 	int blen = -1;
3376 	struct ifaddr *ifa;
3377 	struct ifnet *ifp;
3378 	struct in6_ifaddr *ifa_best = NULL;
3379 
3380 	if (oifp == NULL) {
3381 		return NULL;
3382 	}
3383 
3384 	/*
3385 	 * We search for all addresses on all interfaces from the beginning.
3386 	 * Comparing an interface with the outgoing interface will be done
3387 	 * only at the final stage of tiebreaking.
3388 	 */
3389 	ifnet_head_lock_shared();
3390 	TAILQ_FOREACH(ifp, &ifnet_head, if_list) {
3391 		/*
3392 		 * We can never take an address that breaks the scope zone
3393 		 * of the destination.
3394 		 */
3395 		if (in6_addr2scopeid(ifp, dst) != in6_addr2scopeid(oifp, dst)) {
3396 			continue;
3397 		}
3398 
3399 		ifnet_lock_shared(ifp);
3400 		TAILQ_FOREACH(ifa, &ifp->if_addrlist, ifa_list) {
3401 			int tlen = -1, dscopecmp, bscopecmp, matchcmp;
3402 
3403 			IFA_LOCK(ifa);
3404 			if (ifa->ifa_addr->sa_family != AF_INET6) {
3405 				IFA_UNLOCK(ifa);
3406 				continue;
3407 			}
3408 			src_scope = in6_addrscope(IFA_IN6(ifa));
3409 
3410 			/*
3411 			 * Don't use an address before completing DAD
3412 			 * nor a duplicated address.
3413 			 */
3414 			if (((struct in6_ifaddr *)ifa)->ia6_flags &
3415 			    (IN6_IFF_NOTREADY | IN6_IFF_CLAT46)) {
3416 				IFA_UNLOCK(ifa);
3417 				continue;
3418 			}
3419 			/* XXX: is there any case to allow anycasts? */
3420 			if (((struct in6_ifaddr *)ifa)->ia6_flags &
3421 			    IN6_IFF_ANYCAST) {
3422 				IFA_UNLOCK(ifa);
3423 				continue;
3424 			}
3425 			if (((struct in6_ifaddr *)ifa)->ia6_flags &
3426 			    IN6_IFF_DETACHED) {
3427 				IFA_UNLOCK(ifa);
3428 				continue;
3429 			}
3430 			/*
3431 			 * If this is the first address we find,
3432 			 * keep it anyway.
3433 			 */
3434 			if (ifa_best == NULL) {
3435 				goto replace;
3436 			}
3437 
3438 			/*
3439 			 * ifa_best is never NULL beyond this line except
3440 			 * within the block labeled "replace".
3441 			 */
3442 
3443 			/*
3444 			 * If ifa_best has a smaller scope than dst and
3445 			 * the current address has a larger one than
3446 			 * (or equal to) dst, always replace ifa_best.
3447 			 * Also, if the current address has a smaller scope
3448 			 * than dst, ignore it unless ifa_best also has a
3449 			 * smaller scope.
3450 			 * Consequently, after the two if-clause below,
3451 			 * the followings must be satisfied:
3452 			 * (scope(src) < scope(dst) &&
3453 			 *  scope(best) < scope(dst))
3454 			 *  OR
3455 			 * (scope(best) >= scope(dst) &&
3456 			 *  scope(src) >= scope(dst))
3457 			 */
3458 			if (IN6_ARE_SCOPE_CMP(best_scope, dst_scope) < 0 &&
3459 			    IN6_ARE_SCOPE_CMP(src_scope, dst_scope) >= 0) {
3460 				goto replace; /* (A) */
3461 			}
3462 			if (IN6_ARE_SCOPE_CMP(src_scope, dst_scope) < 0 &&
3463 			    IN6_ARE_SCOPE_CMP(best_scope, dst_scope) >= 0) {
3464 				IFA_UNLOCK(ifa);
3465 				continue; /* (B) */
3466 			}
3467 			/*
3468 			 * A deprecated address SHOULD NOT be used in new
3469 			 * communications if an alternate (non-deprecated)
3470 			 * address is available and has sufficient scope.
3471 			 * RFC 4862, Section 5.5.4.
3472 			 */
3473 			if (((struct in6_ifaddr *)ifa)->ia6_flags &
3474 			    IN6_IFF_DEPRECATED) {
3475 				/*
3476 				 * Ignore any deprecated addresses if
3477 				 * specified by configuration.
3478 				 */
3479 				if (!ip6_use_deprecated) {
3480 					IFA_UNLOCK(ifa);
3481 					continue;
3482 				}
3483 				/*
3484 				 * If we have already found a non-deprecated
3485 				 * candidate, just ignore deprecated addresses.
3486 				 */
3487 				if ((ifa_best->ia6_flags & IN6_IFF_DEPRECATED)
3488 				    == 0) {
3489 					IFA_UNLOCK(ifa);
3490 					continue;
3491 				}
3492 			}
3493 
3494 			/*
3495 			 * A non-deprecated address is always preferred
3496 			 * to a deprecated one regardless of scopes and
3497 			 * address matching (Note invariants ensured by the
3498 			 * conditions (A) and (B) above.)
3499 			 */
3500 			if ((ifa_best->ia6_flags & IN6_IFF_DEPRECATED) &&
3501 			    (((struct in6_ifaddr *)ifa)->ia6_flags &
3502 			    IN6_IFF_DEPRECATED) == 0) {
3503 				goto replace;
3504 			}
3505 
3506 			/*
3507 			 * When we use temporary addresses described in
3508 			 * RFC 4941, we prefer temporary addresses to
3509 			 * public autoconf addresses.  Again, note the
3510 			 * invariants from (A) and (B).  Also note that we
3511 			 * don't have any preference between static addresses
3512 			 * and autoconf addresses (despite of whether or not
3513 			 * the latter is temporary or public.)
3514 			 */
3515 			if (ip6_use_tempaddr) {
3516 				struct in6_ifaddr *ifat;
3517 
3518 				ifat = (struct in6_ifaddr *)ifa;
3519 				if ((ifa_best->ia6_flags &
3520 				    (IN6_IFF_AUTOCONF | IN6_IFF_TEMPORARY))
3521 				    == IN6_IFF_AUTOCONF &&
3522 				    (ifat->ia6_flags &
3523 				    (IN6_IFF_AUTOCONF | IN6_IFF_TEMPORARY))
3524 				    == (IN6_IFF_AUTOCONF | IN6_IFF_TEMPORARY)) {
3525 					goto replace;
3526 				}
3527 				if ((ifa_best->ia6_flags &
3528 				    (IN6_IFF_AUTOCONF | IN6_IFF_TEMPORARY))
3529 				    == (IN6_IFF_AUTOCONF | IN6_IFF_TEMPORARY) &&
3530 				    (ifat->ia6_flags &
3531 				    (IN6_IFF_AUTOCONF | IN6_IFF_TEMPORARY))
3532 				    == IN6_IFF_AUTOCONF) {
3533 					IFA_UNLOCK(ifa);
3534 					continue;
3535 				}
3536 			}
3537 
3538 			/*
3539 			 * At this point, we have two cases:
3540 			 * 1. we are looking at a non-deprecated address,
3541 			 *    and ifa_best is also non-deprecated.
3542 			 * 2. we are looking at a deprecated address,
3543 			 *    and ifa_best is also deprecated.
3544 			 * Also, we do not have to consider a case where
3545 			 * the scope of if_best is larger(smaller) than dst and
3546 			 * the scope of the current address is smaller(larger)
3547 			 * than dst. Such a case has already been covered.
3548 			 * Tiebreaking is done according to the following
3549 			 * items:
3550 			 * - the scope comparison between the address and
3551 			 *   dst (dscopecmp)
3552 			 * - the scope comparison between the address and
3553 			 *   ifa_best (bscopecmp)
3554 			 * - if the address match dst longer than ifa_best
3555 			 *   (matchcmp)
3556 			 * - if the address is on the outgoing I/F (outI/F)
3557 			 *
3558 			 * Roughly speaking, the selection policy is
3559 			 * - the most important item is scope. The same scope
3560 			 *   is best. Then search for a larger scope.
3561 			 *   Smaller scopes are the last resort.
3562 			 * - A deprecated address is chosen only when we have
3563 			 *   no address that has an enough scope, but is
3564 			 *   prefered to any addresses of smaller scopes
3565 			 *   (this must be already done above.)
3566 			 * - addresses on the outgoing I/F are preferred to
3567 			 *   ones on other interfaces if none of above
3568 			 *   tiebreaks.  In the table below, the column "bI"
3569 			 *   means if the best_ifa is on the outgoing
3570 			 *   interface, and the column "sI" means if the ifa
3571 			 *   is on the outgoing interface.
3572 			 * - If there is no other reasons to choose one,
3573 			 *   longest address match against dst is considered.
3574 			 *
3575 			 * The precise decision table is as follows:
3576 			 * dscopecmp bscopecmp  match   bI oI | replace?
3577 			 *   N/A       equal    N/A     Y   N |   No (1)
3578 			 *   N/A       equal    N/A     N   Y |  Yes (2)
3579 			 *   N/A       equal    larger   N/A  |  Yes (3)
3580 			 *   N/A       equal    !larger  N/A  |   No (4)
3581 			 *   larger    larger   N/A      N/A  |   No (5)
3582 			 *   larger    smaller  N/A      N/A  |  Yes (6)
3583 			 *   smaller   larger   N/A      N/A  |  Yes (7)
3584 			 *   smaller   smaller  N/A      N/A  |   No (8)
3585 			 *   equal     smaller  N/A      N/A  |  Yes (9)
3586 			 *   equal     larger   (already done at A above)
3587 			 */
3588 			dscopecmp = IN6_ARE_SCOPE_CMP(src_scope, dst_scope);
3589 			bscopecmp = IN6_ARE_SCOPE_CMP(src_scope, best_scope);
3590 
3591 			if (bscopecmp == 0) {
3592 				struct ifnet *bifp = ifa_best->ia_ifp;
3593 
3594 				if (bifp == oifp && ifp != oifp) { /* (1) */
3595 					IFA_UNLOCK(ifa);
3596 					continue;
3597 				}
3598 				if (bifp != oifp && ifp == oifp) { /* (2) */
3599 					goto replace;
3600 				}
3601 
3602 				/*
3603 				 * Both bifp and ifp are on the outgoing
3604 				 * interface, or both two are on a different
3605 				 * interface from the outgoing I/F.
3606 				 * now we need address matching against dst
3607 				 * for tiebreaking.
3608 				 */
3609 				tlen = in6_matchlen(IFA_IN6(ifa), dst);
3610 				matchcmp = tlen - blen;
3611 				if (matchcmp > 0) { /* (3) */
3612 					goto replace;
3613 				}
3614 				IFA_UNLOCK(ifa);
3615 				continue; /* (4) */
3616 			}
3617 			if (dscopecmp > 0) {
3618 				if (bscopecmp > 0) { /* (5) */
3619 					IFA_UNLOCK(ifa);
3620 					continue;
3621 				}
3622 				goto replace; /* (6) */
3623 			}
3624 			if (dscopecmp < 0) {
3625 				if (bscopecmp > 0) { /* (7) */
3626 					goto replace;
3627 				}
3628 				IFA_UNLOCK(ifa);
3629 				continue; /* (8) */
3630 			}
3631 
3632 			/* now dscopecmp must be 0 */
3633 			if (bscopecmp < 0) {
3634 				goto replace; /* (9) */
3635 			}
3636 replace:
3637 			IFA_ADDREF_LOCKED(ifa); /* for ifa_best */
3638 			blen = tlen >= 0 ? tlen :
3639 			    in6_matchlen(IFA_IN6(ifa), dst);
3640 			best_scope =
3641 			    in6_addrscope(&ifa2ia6(ifa)->ia_addr.sin6_addr);
3642 			IFA_UNLOCK(ifa);
3643 			if (ifa_best) {
3644 				IFA_REMREF(&ifa_best->ia_ifa);
3645 			}
3646 			ifa_best = (struct in6_ifaddr *)ifa;
3647 		}
3648 		ifnet_lock_done(ifp);
3649 	}
3650 	ifnet_head_done();
3651 
3652 	/* count statistics for future improvements */
3653 	if (ifa_best == NULL) {
3654 		ip6stat.ip6s_sources_none++;
3655 	} else {
3656 		IFA_LOCK_SPIN(&ifa_best->ia_ifa);
3657 		if (oifp == ifa_best->ia_ifp) {
3658 			ip6stat.ip6s_sources_sameif[best_scope]++;
3659 		} else {
3660 			ip6stat.ip6s_sources_otherif[best_scope]++;
3661 		}
3662 
3663 		if (best_scope == dst_scope) {
3664 			ip6stat.ip6s_sources_samescope[best_scope]++;
3665 		} else {
3666 			ip6stat.ip6s_sources_otherscope[best_scope]++;
3667 		}
3668 
3669 		if ((ifa_best->ia6_flags & IN6_IFF_DEPRECATED) != 0) {
3670 			ip6stat.ip6s_sources_deprecated[best_scope]++;
3671 		}
3672 		IFA_UNLOCK(&ifa_best->ia_ifa);
3673 	}
3674 
3675 	return ifa_best;
3676 }
3677 
3678 /*
3679  * return the best address out of the same scope. if no address was
3680  * found, return the first valid address from designated IF.
3681  */
3682 struct in6_ifaddr *
in6_ifawithifp(struct ifnet * ifp,struct in6_addr * dst)3683 in6_ifawithifp(struct ifnet *ifp, struct in6_addr *dst)
3684 {
3685 	int dst_scope = in6_addrscope(dst), blen = -1, tlen;
3686 	struct ifaddr *ifa;
3687 	struct in6_ifaddr *besta = NULL;
3688 	struct in6_ifaddr *dep[2];      /* last-resort: deprecated */
3689 
3690 	dep[0] = dep[1] = NULL;
3691 
3692 	/*
3693 	 * We first look for addresses in the same scope.
3694 	 * If there is one, return it.
3695 	 * If two or more, return one which matches the dst longest.
3696 	 * If none, return one of global addresses assigned other ifs.
3697 	 */
3698 	ifnet_lock_shared(ifp);
3699 	TAILQ_FOREACH(ifa, &ifp->if_addrlist, ifa_list) {
3700 		IFA_LOCK(ifa);
3701 		if (ifa->ifa_addr->sa_family != AF_INET6) {
3702 			IFA_UNLOCK(ifa);
3703 			continue;
3704 		}
3705 		if (ifa2ia6(ifa)->ia6_flags & IN6_IFF_ANYCAST) {
3706 			IFA_UNLOCK(ifa);
3707 			continue; /* XXX: is there any case to allow anycast? */
3708 		}
3709 		if (ifa2ia6(ifa)->ia6_flags & (IN6_IFF_NOTREADY | IN6_IFF_CLAT46)) {
3710 			IFA_UNLOCK(ifa);
3711 			continue; /* don't use this interface */
3712 		}
3713 		if (ifa2ia6(ifa)->ia6_flags & IN6_IFF_DETACHED) {
3714 			IFA_UNLOCK(ifa);
3715 			continue;
3716 		}
3717 		if (ifa2ia6(ifa)->ia6_flags & IN6_IFF_DEPRECATED) {
3718 			if (ip6_use_deprecated) {
3719 				IFA_ADDREF_LOCKED(ifa); /* for dep[0] */
3720 				IFA_UNLOCK(ifa);
3721 				if (dep[0] != NULL) {
3722 					IFA_REMREF(&dep[0]->ia_ifa);
3723 				}
3724 				dep[0] = (struct in6_ifaddr *)ifa;
3725 			} else {
3726 				IFA_UNLOCK(ifa);
3727 			}
3728 			continue;
3729 		}
3730 
3731 		if (dst_scope == in6_addrscope(IFA_IN6(ifa))) {
3732 			/*
3733 			 * call in6_matchlen() as few as possible
3734 			 */
3735 			if (besta) {
3736 				if (blen == -1) {
3737 					IFA_UNLOCK(ifa);
3738 					IFA_LOCK(&besta->ia_ifa);
3739 					blen = in6_matchlen(
3740 						&besta->ia_addr.sin6_addr, dst);
3741 					IFA_UNLOCK(&besta->ia_ifa);
3742 					IFA_LOCK(ifa);
3743 				}
3744 				tlen = in6_matchlen(IFA_IN6(ifa), dst);
3745 				if (tlen > blen) {
3746 					blen = tlen;
3747 					IFA_ADDREF_LOCKED(ifa); /* for besta */
3748 					IFA_UNLOCK(ifa);
3749 					IFA_REMREF(&besta->ia_ifa);
3750 					besta = (struct in6_ifaddr *)ifa;
3751 				} else {
3752 					IFA_UNLOCK(ifa);
3753 				}
3754 			} else {
3755 				besta = (struct in6_ifaddr *)ifa;
3756 				IFA_ADDREF_LOCKED(ifa); /* for besta */
3757 				IFA_UNLOCK(ifa);
3758 			}
3759 		} else {
3760 			IFA_UNLOCK(ifa);
3761 		}
3762 	}
3763 	if (besta) {
3764 		ifnet_lock_done(ifp);
3765 		if (dep[0] != NULL) {
3766 			IFA_REMREF(&dep[0]->ia_ifa);
3767 		}
3768 		return besta;
3769 	}
3770 
3771 	TAILQ_FOREACH(ifa, &ifp->if_addrlist, ifa_list) {
3772 		IFA_LOCK(ifa);
3773 		if (ifa->ifa_addr->sa_family != AF_INET6) {
3774 			IFA_UNLOCK(ifa);
3775 			continue;
3776 		}
3777 		if (ifa2ia6(ifa)->ia6_flags & IN6_IFF_ANYCAST) {
3778 			IFA_UNLOCK(ifa);
3779 			continue; /* XXX: is there any case to allow anycast? */
3780 		}
3781 		if (ifa2ia6(ifa)->ia6_flags & (IN6_IFF_NOTREADY | IN6_IFF_CLAT46)) {
3782 			IFA_UNLOCK(ifa);
3783 			continue; /* don't use this interface */
3784 		}
3785 		if (ifa2ia6(ifa)->ia6_flags & IN6_IFF_DETACHED) {
3786 			IFA_UNLOCK(ifa);
3787 			continue;
3788 		}
3789 		if (ifa2ia6(ifa)->ia6_flags & IN6_IFF_DEPRECATED) {
3790 			if (ip6_use_deprecated) {
3791 				IFA_ADDREF_LOCKED(ifa); /* for dep[1] */
3792 				IFA_UNLOCK(ifa);
3793 				if (dep[1] != NULL) {
3794 					IFA_REMREF(&dep[1]->ia_ifa);
3795 				}
3796 				dep[1] = (struct in6_ifaddr *)ifa;
3797 			} else {
3798 				IFA_UNLOCK(ifa);
3799 			}
3800 			continue;
3801 		}
3802 		IFA_ADDREF_LOCKED(ifa); /* for caller */
3803 		IFA_UNLOCK(ifa);
3804 		ifnet_lock_done(ifp);
3805 		if (dep[0] != NULL) {
3806 			IFA_REMREF(&dep[0]->ia_ifa);
3807 		}
3808 		if (dep[1] != NULL) {
3809 			IFA_REMREF(&dep[1]->ia_ifa);
3810 		}
3811 		return (struct in6_ifaddr *)ifa;
3812 	}
3813 	ifnet_lock_done(ifp);
3814 
3815 	/* use the last-resort values, that are, deprecated addresses */
3816 	if (dep[0]) {
3817 		if (dep[1] != NULL) {
3818 			IFA_REMREF(&dep[1]->ia_ifa);
3819 		}
3820 		return dep[0];
3821 	}
3822 	if (dep[1]) {
3823 		return dep[1];
3824 	}
3825 
3826 	return NULL;
3827 }
3828 
3829 /*
3830  * perform DAD when interface becomes IFF_UP.
3831  */
3832 static void
in6_if_up_dad_start(struct ifnet * ifp)3833 in6_if_up_dad_start(struct ifnet *ifp)
3834 {
3835 	struct ifaddr *ifa;
3836 	struct nd_ifinfo *ndi = NULL;
3837 
3838 	ndi = ND_IFINFO(ifp);
3839 	VERIFY((NULL != ndi) && (TRUE == ndi->initialized));
3840 	if (!(ndi->flags & ND6_IFF_DAD)) {
3841 		return;
3842 	}
3843 
3844 	/* start DAD on all the interface addresses */
3845 	ifnet_lock_exclusive(ifp);
3846 	TAILQ_FOREACH(ifa, &ifp->if_addrlist, ifa_list) {
3847 		struct in6_ifaddr *ia6;
3848 
3849 		IFA_LOCK_SPIN(ifa);
3850 		if (ifa->ifa_addr->sa_family != AF_INET6) {
3851 			IFA_UNLOCK(ifa);
3852 			continue;
3853 		}
3854 		ia6 = (struct in6_ifaddr *)ifa;
3855 		if (ia6->ia6_flags & IN6_IFF_DADPROGRESS) {
3856 			int delay = 0;  /* delay ticks before DAD output */
3857 			IFA_UNLOCK(ifa);
3858 			nd6_dad_start(ifa, &delay);
3859 		} else {
3860 			IFA_UNLOCK(ifa);
3861 		}
3862 	}
3863 	ifnet_lock_done(ifp);
3864 }
3865 
3866 int
in6if_do_dad(struct ifnet * ifp)3867 in6if_do_dad(
3868 	struct ifnet *ifp)
3869 {
3870 	struct nd_ifinfo *ndi = NULL;
3871 
3872 	if ((ifp->if_flags & IFF_LOOPBACK) != 0) {
3873 		return 0;
3874 	}
3875 
3876 	ndi = ND_IFINFO(ifp);
3877 	VERIFY((NULL != ndi) && (TRUE == ndi->initialized));
3878 	if (!(ndi->flags & ND6_IFF_DAD)) {
3879 		return 0;
3880 	}
3881 
3882 	/*
3883 	 * If we are using the alternative neighbor discovery
3884 	 * interface on this interface, then skip DAD.
3885 	 *
3886 	 * Also, skip it for interfaces marked "local private"
3887 	 * for now, even when not marked as using the alternative
3888 	 * interface.  This is for historical reasons.
3889 	 */
3890 	if (ifp->if_eflags &
3891 	    (IFEF_IPV6_ND6ALT | IFEF_LOCALNET_PRIVATE | IFEF_DIRECTLINK)) {
3892 		return 0;
3893 	}
3894 
3895 	if (ifp->if_family == IFNET_FAMILY_IPSEC ||
3896 	    ifp->if_family == IFNET_FAMILY_UTUN) {
3897 		/*
3898 		 * Ignore DAD for tunneling virtual interfaces, which get
3899 		 * their IPv6 address explicitly assigned.
3900 		 */
3901 		return 0;
3902 	}
3903 
3904 	switch (ifp->if_type) {
3905 #if IFT_DUMMY
3906 	case IFT_DUMMY:
3907 #endif
3908 	case IFT_FAITH:
3909 		/*
3910 		 * These interfaces do not have the IFF_LOOPBACK flag,
3911 		 * but loop packets back.  We do not have to do DAD on such
3912 		 * interfaces.  We should even omit it, because loop-backed
3913 		 * NS would confuse the DAD procedure.
3914 		 */
3915 		return 0;
3916 	default:
3917 		/*
3918 		 * Our DAD routine requires the interface up and running.
3919 		 * However, some interfaces can be up before the RUNNING
3920 		 * status.  Additionaly, users may try to assign addresses
3921 		 * before the interface becomes up (or running).
3922 		 * We simply skip DAD in such a case as a work around.
3923 		 * XXX: we should rather mark "tentative" on such addresses,
3924 		 * and do DAD after the interface becomes ready.
3925 		 */
3926 		if ((ifp->if_flags & (IFF_UP | IFF_RUNNING)) !=
3927 		    (IFF_UP | IFF_RUNNING)) {
3928 			return 0;
3929 		}
3930 
3931 		return 1;
3932 	}
3933 }
3934 
3935 /*
3936  * Calculate max IPv6 MTU through all the interfaces and store it
3937  * to in6_maxmtu.
3938  */
3939 void
in6_setmaxmtu(void)3940 in6_setmaxmtu(void)
3941 {
3942 	u_int32_t maxmtu = 0;
3943 	struct ifnet *ifp;
3944 
3945 	ifnet_head_lock_shared();
3946 	TAILQ_FOREACH(ifp, &ifnet_head, if_list) {
3947 		struct nd_ifinfo *ndi = NULL;
3948 
3949 		if ((ndi = ND_IFINFO(ifp)) != NULL && !ndi->initialized) {
3950 			ndi = NULL;
3951 		}
3952 		if (ndi != NULL) {
3953 			lck_mtx_lock(&ndi->lock);
3954 		}
3955 		if ((ifp->if_flags & IFF_LOOPBACK) == 0 &&
3956 		    IN6_LINKMTU(ifp) > maxmtu) {
3957 			maxmtu = IN6_LINKMTU(ifp);
3958 		}
3959 		if (ndi != NULL) {
3960 			lck_mtx_unlock(&ndi->lock);
3961 		}
3962 	}
3963 	ifnet_head_done();
3964 	if (maxmtu) {   /* update only when maxmtu is positive */
3965 		in6_maxmtu = maxmtu;
3966 	}
3967 }
3968 /*
3969  * Provide the length of interface identifiers to be used for the link attached
3970  * to the given interface.  The length should be defined in "IPv6 over
3971  * xxx-link" document.  Note that address architecture might also define
3972  * the length for a particular set of address prefixes, regardless of the
3973  * link type.  Also see RFC 4862 for additional background.
3974  */
3975 int
in6_if2idlen(struct ifnet * ifp)3976 in6_if2idlen(struct ifnet *ifp)
3977 {
3978 	switch (ifp->if_type) {
3979 	case IFT_ETHER:         /* RFC2464 */
3980 	case IFT_IEEE8023ADLAG: /* IEEE802.3ad Link Aggregate */
3981 #ifdef IFT_PROPVIRTUAL
3982 	case IFT_PROPVIRTUAL:   /* XXX: no RFC. treat it as ether */
3983 #endif
3984 #ifdef IFT_L2VLAN
3985 	case IFT_L2VLAN:        /* ditto */
3986 #endif
3987 #ifdef IFT_IEEE80211
3988 	case IFT_IEEE80211:     /* ditto */
3989 #endif
3990 #ifdef IFT_MIP
3991 	case IFT_MIP:   /* ditto */
3992 #endif
3993 		return 64;
3994 	case IFT_FDDI:          /* RFC2467 */
3995 		return 64;
3996 	case IFT_ISO88025:      /* RFC2470 (IPv6 over Token Ring) */
3997 		return 64;
3998 	case IFT_PPP:           /* RFC2472 */
3999 		return 64;
4000 	case IFT_ARCNET:        /* RFC2497 */
4001 		return 64;
4002 	case IFT_FRELAY:        /* RFC2590 */
4003 		return 64;
4004 	case IFT_IEEE1394:      /* RFC3146 */
4005 		return 64;
4006 	case IFT_GIF:
4007 		return 64;    /* draft-ietf-v6ops-mech-v2-07 */
4008 	case IFT_LOOP:
4009 		return 64;    /* XXX: is this really correct? */
4010 	case IFT_OTHER:
4011 		return 64;    /* for utun interfaces */
4012 	case IFT_CELLULAR:
4013 		return 64;    /* Packet Data over Cellular */
4014 	case IFT_BRIDGE:
4015 		return 64;    /* Transparent bridge interface */
4016 	case IFT_6LOWPAN:
4017 		return 64;    /* 6LoWPAN */
4018 	default:
4019 		/*
4020 		 * Unknown link type:
4021 		 * It might be controversial to use the today's common constant
4022 		 * of 64 for these cases unconditionally.  For full compliance,
4023 		 * we should return an error in this case.  On the other hand,
4024 		 * if we simply miss the standard for the link type or a new
4025 		 * standard is defined for a new link type, the IFID length
4026 		 * is very likely to be the common constant.  As a compromise,
4027 		 * we always use the constant, but make an explicit notice
4028 		 * indicating the "unknown" case.
4029 		 */
4030 		log(LOG_NOTICE, "%s: unknown link type (%d)\n", __func__,
4031 		    ifp->if_type);
4032 		return 64;
4033 	}
4034 }
4035 /*
4036  * Convert sockaddr_in6 to sockaddr_in.  Original sockaddr_in6 must be
4037  * v4 mapped addr or v4 compat addr
4038  */
4039 void
in6_sin6_2_sin(struct sockaddr_in * sin,struct sockaddr_in6 * sin6)4040 in6_sin6_2_sin(struct sockaddr_in *sin, struct sockaddr_in6 *sin6)
4041 {
4042 	bzero(sin, sizeof(*sin));
4043 	sin->sin_len = sizeof(struct sockaddr_in);
4044 	sin->sin_family = AF_INET;
4045 	sin->sin_port = sin6->sin6_port;
4046 	sin->sin_addr.s_addr = sin6->sin6_addr.s6_addr32[3];
4047 }
4048 
4049 /* Convert sockaddr_in to sockaddr_in6 in v4 mapped addr format. */
4050 void
in6_sin_2_v4mapsin6(struct sockaddr_in * sin,struct sockaddr_in6 * sin6)4051 in6_sin_2_v4mapsin6(struct sockaddr_in *sin, struct sockaddr_in6 *sin6)
4052 {
4053 	bzero(sin6, sizeof(*sin6));
4054 	sin6->sin6_len = sizeof(struct sockaddr_in6);
4055 	sin6->sin6_family = AF_INET6;
4056 	sin6->sin6_port = sin->sin_port;
4057 	sin6->sin6_addr.s6_addr32[0] = 0;
4058 	sin6->sin6_addr.s6_addr32[1] = 0;
4059 	if (sin->sin_addr.s_addr) {
4060 		sin6->sin6_addr.s6_addr32[2] = IPV6_ADDR_INT32_SMP;
4061 		sin6->sin6_addr.s6_addr32[3] = sin->sin_addr.s_addr;
4062 	} else {
4063 		sin6->sin6_addr.s6_addr32[2] = 0;
4064 		sin6->sin6_addr.s6_addr32[3] = 0;
4065 	}
4066 }
4067 
4068 /* Convert sockaddr_in6 into sockaddr_in. */
4069 void
in6_sin6_2_sin_in_sock(struct sockaddr * nam)4070 in6_sin6_2_sin_in_sock(struct sockaddr *nam)
4071 {
4072 	struct sockaddr_in *sin_p;
4073 	struct sockaddr_in6 sin6;
4074 
4075 	/*
4076 	 * Save original sockaddr_in6 addr and convert it
4077 	 * to sockaddr_in.
4078 	 */
4079 	sin6 = *(struct sockaddr_in6 *)(void *)nam;
4080 	sin_p = (struct sockaddr_in *)(void *)nam;
4081 	in6_sin6_2_sin(sin_p, &sin6);
4082 }
4083 
4084 /* Convert sockaddr_in into sockaddr_in6 in v4 mapped addr format. */
4085 int
in6_sin_2_v4mapsin6_in_sock(struct sockaddr ** nam)4086 in6_sin_2_v4mapsin6_in_sock(struct sockaddr **nam)
4087 {
4088 	struct sockaddr_in *sin_p;
4089 	struct sockaddr_in6 *sin6_p;
4090 
4091 	sin6_p = (struct sockaddr_in6 *)alloc_sockaddr(sizeof(*sin6_p),
4092 	    Z_WAITOK | Z_NOFAIL);
4093 
4094 	sin_p = (struct sockaddr_in *)(void *)*nam;
4095 	in6_sin_2_v4mapsin6(sin_p, sin6_p);
4096 	free_sockaddr(*nam);
4097 	*nam = (struct sockaddr *)sin6_p;
4098 
4099 	return 0;
4100 }
4101 
4102 /*
4103  * Posts in6_event_data message kernel events.
4104  *
4105  * To get the same size of kev_in6_data between ILP32 and LP64 data models
4106  * we are using a special version of the in6_addrlifetime structure that
4107  * uses only 32 bits fields to be compatible with Leopard, and that
4108  * are large enough to span 68 years.
4109  */
4110 void
in6_post_msg(struct ifnet * ifp,u_int32_t event_code,struct in6_ifaddr * ifa,uint8_t * mac)4111 in6_post_msg(struct ifnet *ifp, u_int32_t event_code, struct in6_ifaddr *ifa,
4112     uint8_t *mac)
4113 {
4114 	struct kev_msg ev_msg;
4115 	struct kev_in6_data in6_event_data;
4116 	struct in6_addrlifetime ia6_lt;
4117 
4118 	bzero(&in6_event_data, sizeof(struct kev_in6_data));
4119 	bzero(&ev_msg, sizeof(struct kev_msg));
4120 	ev_msg.vendor_code      = KEV_VENDOR_APPLE;
4121 	ev_msg.kev_class        = KEV_NETWORK_CLASS;
4122 	ev_msg.kev_subclass     = KEV_INET6_SUBCLASS;
4123 	ev_msg.event_code       = event_code;
4124 
4125 	if (ifa) {
4126 		IFA_LOCK(&ifa->ia_ifa);
4127 		in6_event_data.ia_addr          = ifa->ia_addr;
4128 		in6_event_data.ia_net           = ifa->ia_net;
4129 		in6_event_data.ia_dstaddr       = ifa->ia_dstaddr;
4130 		in6_event_data.ia_prefixmask    = ifa->ia_prefixmask;
4131 		in6_event_data.ia_plen          = ifa->ia_plen;
4132 		in6_event_data.ia6_flags        = (u_int32_t)ifa->ia6_flags;
4133 
4134 		/* retrieve time as calendar time (last arg is 1) */
4135 		in6ifa_getlifetime(ifa, &ia6_lt, 1);
4136 		in6_event_data.ia_lifetime.ia6t_expire = (u_int32_t)ia6_lt.ia6t_expire;
4137 		in6_event_data.ia_lifetime.ia6t_preferred = (u_int32_t)ia6_lt.ia6t_preferred;
4138 		in6_event_data.ia_lifetime.ia6t_vltime = ia6_lt.ia6t_vltime;
4139 		in6_event_data.ia_lifetime.ia6t_pltime = ia6_lt.ia6t_pltime;
4140 		IFA_UNLOCK(&ifa->ia_ifa);
4141 	}
4142 
4143 	if (ifp != NULL) {
4144 		(void) strlcpy(&in6_event_data.link_data.if_name[0],
4145 		    ifp->if_name, IFNAMSIZ);
4146 		in6_event_data.link_data.if_family = ifp->if_family;
4147 		in6_event_data.link_data.if_unit  = (u_int32_t)ifp->if_unit;
4148 	}
4149 
4150 	if (mac != NULL) {
4151 		memcpy(&in6_event_data.ia_mac, mac,
4152 		    sizeof(in6_event_data.ia_mac));
4153 	}
4154 
4155 	ev_msg.dv[0].data_ptr    = &in6_event_data;
4156 	ev_msg.dv[0].data_length = sizeof(in6_event_data);
4157 	ev_msg.dv[1].data_length = 0;
4158 
4159 	dlil_post_complete_msg(NULL, &ev_msg);
4160 }
4161 
4162 /*
4163  * Called as part of ip6_init
4164  */
4165 void
in6_ifaddr_init(void)4166 in6_ifaddr_init(void)
4167 {
4168 	in6_cga_init();
4169 	in6_multi_init();
4170 
4171 	PE_parse_boot_argn("ifa_debug", &in6ifa_debug, sizeof(in6ifa_debug));
4172 
4173 	vm_size_t in6ifa_size = (in6ifa_debug == 0) ? sizeof(struct in6_ifaddr) :
4174 	    sizeof(struct in6_ifaddr_dbg);
4175 
4176 	in6ifa_zone = zone_create(IN6IFA_ZONE_NAME, in6ifa_size, ZC_ZFREE_CLEARMEM);
4177 
4178 	TAILQ_INIT(&in6ifa_trash_head);
4179 }
4180 
4181 static struct in6_ifaddr *
in6_ifaddr_alloc(zalloc_flags_t how)4182 in6_ifaddr_alloc(zalloc_flags_t how)
4183 {
4184 	struct in6_ifaddr *in6ifa;
4185 
4186 	in6ifa = zalloc_flags(in6ifa_zone, how | Z_ZERO);
4187 	if (in6ifa != NULL) {
4188 		in6ifa->ia_ifa.ifa_free = in6_ifaddr_free;
4189 		in6ifa->ia_ifa.ifa_debug |= IFD_ALLOC;
4190 		in6ifa->ia_ifa.ifa_del_wc = &in6ifa->ia_ifa.ifa_debug;
4191 		in6ifa->ia_ifa.ifa_del_waiters = 0;
4192 		ifa_lock_init(&in6ifa->ia_ifa);
4193 		if (in6ifa_debug != 0) {
4194 			struct in6_ifaddr_dbg *in6ifa_dbg =
4195 			    (struct in6_ifaddr_dbg *)in6ifa;
4196 			in6ifa->ia_ifa.ifa_debug |= IFD_DEBUG;
4197 			in6ifa->ia_ifa.ifa_trace = in6_ifaddr_trace;
4198 			in6ifa->ia_ifa.ifa_attached = in6_ifaddr_attached;
4199 			in6ifa->ia_ifa.ifa_detached = in6_ifaddr_detached;
4200 			ctrace_record(&in6ifa_dbg->in6ifa_alloc);
4201 		}
4202 	}
4203 
4204 	return in6ifa;
4205 }
4206 
4207 static void
in6_ifaddr_free(struct ifaddr * ifa)4208 in6_ifaddr_free(struct ifaddr *ifa)
4209 {
4210 	IFA_LOCK_ASSERT_HELD(ifa);
4211 
4212 	if (ifa->ifa_refcnt != 0) {
4213 		panic("%s: ifa %p bad ref cnt", __func__, ifa);
4214 		/* NOTREACHED */
4215 	} else if (!(ifa->ifa_debug & IFD_ALLOC)) {
4216 		panic("%s: ifa %p cannot be freed", __func__, ifa);
4217 		/* NOTREACHED */
4218 	}
4219 	if (ifa->ifa_debug & IFD_DEBUG) {
4220 		struct in6_ifaddr_dbg *in6ifa_dbg =
4221 		    (struct in6_ifaddr_dbg *)ifa;
4222 		ctrace_record(&in6ifa_dbg->in6ifa_free);
4223 		bcopy(&in6ifa_dbg->in6ifa, &in6ifa_dbg->in6ifa_old,
4224 		    sizeof(struct in6_ifaddr));
4225 		if (ifa->ifa_debug & IFD_TRASHED) {
4226 			/* Become a regular mutex, just in case */
4227 			IFA_CONVERT_LOCK(ifa);
4228 			lck_mtx_lock(&in6ifa_trash_lock);
4229 			TAILQ_REMOVE(&in6ifa_trash_head, in6ifa_dbg,
4230 			    in6ifa_trash_link);
4231 			lck_mtx_unlock(&in6ifa_trash_lock);
4232 			ifa->ifa_debug &= ~IFD_TRASHED;
4233 		}
4234 	}
4235 	IFA_UNLOCK(ifa);
4236 	ifa_lock_destroy(ifa);
4237 	bzero(ifa, sizeof(struct in6_ifaddr));
4238 	zfree(in6ifa_zone, ifa);
4239 }
4240 
4241 static void
in6_ifaddr_attached(struct ifaddr * ifa)4242 in6_ifaddr_attached(struct ifaddr *ifa)
4243 {
4244 	struct in6_ifaddr_dbg *in6ifa_dbg = (struct in6_ifaddr_dbg *)ifa;
4245 
4246 	IFA_LOCK_ASSERT_HELD(ifa);
4247 
4248 	if (!(ifa->ifa_debug & IFD_DEBUG)) {
4249 		panic("%s: ifa %p has no debug structure", __func__, ifa);
4250 		/* NOTREACHED */
4251 	}
4252 	if (ifa->ifa_debug & IFD_TRASHED) {
4253 		/* Become a regular mutex, just in case */
4254 		IFA_CONVERT_LOCK(ifa);
4255 		lck_mtx_lock(&in6ifa_trash_lock);
4256 		TAILQ_REMOVE(&in6ifa_trash_head, in6ifa_dbg, in6ifa_trash_link);
4257 		lck_mtx_unlock(&in6ifa_trash_lock);
4258 		ifa->ifa_debug &= ~IFD_TRASHED;
4259 	}
4260 }
4261 
4262 static void
in6_ifaddr_detached(struct ifaddr * ifa)4263 in6_ifaddr_detached(struct ifaddr *ifa)
4264 {
4265 	struct in6_ifaddr_dbg *in6ifa_dbg = (struct in6_ifaddr_dbg *)ifa;
4266 
4267 	IFA_LOCK_ASSERT_HELD(ifa);
4268 
4269 	if (!(ifa->ifa_debug & IFD_DEBUG)) {
4270 		panic("%s: ifa %p has no debug structure", __func__, ifa);
4271 		/* NOTREACHED */
4272 	} else if (ifa->ifa_debug & IFD_TRASHED) {
4273 		panic("%s: ifa %p is already in trash list", __func__, ifa);
4274 		/* NOTREACHED */
4275 	}
4276 	ifa->ifa_debug |= IFD_TRASHED;
4277 	/* Become a regular mutex, just in case */
4278 	IFA_CONVERT_LOCK(ifa);
4279 	lck_mtx_lock(&in6ifa_trash_lock);
4280 	TAILQ_INSERT_TAIL(&in6ifa_trash_head, in6ifa_dbg, in6ifa_trash_link);
4281 	lck_mtx_unlock(&in6ifa_trash_lock);
4282 }
4283 
4284 static void
in6_ifaddr_trace(struct ifaddr * ifa,int refhold)4285 in6_ifaddr_trace(struct ifaddr *ifa, int refhold)
4286 {
4287 	struct in6_ifaddr_dbg *in6ifa_dbg = (struct in6_ifaddr_dbg *)ifa;
4288 	ctrace_t *tr;
4289 	u_int32_t idx;
4290 	u_int16_t *cnt;
4291 
4292 	if (!(ifa->ifa_debug & IFD_DEBUG)) {
4293 		panic("%s: ifa %p has no debug structure", __func__, ifa);
4294 		/* NOTREACHED */
4295 	}
4296 	if (refhold) {
4297 		cnt = &in6ifa_dbg->in6ifa_refhold_cnt;
4298 		tr = in6ifa_dbg->in6ifa_refhold;
4299 	} else {
4300 		cnt = &in6ifa_dbg->in6ifa_refrele_cnt;
4301 		tr = in6ifa_dbg->in6ifa_refrele;
4302 	}
4303 
4304 	idx = atomic_add_16_ov(cnt, 1) % IN6IFA_TRACE_HIST_SIZE;
4305 	ctrace_record(&tr[idx]);
4306 }
4307 
4308 /*
4309  * Handle SIOCGASSOCIDS ioctl for PF_INET6 domain.
4310  */
4311 static int
in6_getassocids(struct socket * so,uint32_t * cnt,user_addr_t aidp)4312 in6_getassocids(struct socket *so, uint32_t *cnt, user_addr_t aidp)
4313 {
4314 	struct in6pcb *in6p = sotoin6pcb(so);
4315 	sae_associd_t aid;
4316 
4317 	if (in6p == NULL || in6p->inp_state == INPCB_STATE_DEAD) {
4318 		return EINVAL;
4319 	}
4320 
4321 	/* IN6PCB has no concept of association */
4322 	aid = SAE_ASSOCID_ANY;
4323 	*cnt = 0;
4324 
4325 	/* just asking how many there are? */
4326 	if (aidp == USER_ADDR_NULL) {
4327 		return 0;
4328 	}
4329 
4330 	return copyout(&aid, aidp, sizeof(aid));
4331 }
4332 
4333 /*
4334  * Handle SIOCGCONNIDS ioctl for PF_INET6 domain.
4335  */
4336 static int
in6_getconnids(struct socket * so,sae_associd_t aid,uint32_t * cnt,user_addr_t cidp)4337 in6_getconnids(struct socket *so, sae_associd_t aid, uint32_t *cnt,
4338     user_addr_t cidp)
4339 {
4340 	struct in6pcb *in6p = sotoin6pcb(so);
4341 	sae_connid_t cid;
4342 
4343 	if (in6p == NULL || in6p->inp_state == INPCB_STATE_DEAD) {
4344 		return EINVAL;
4345 	}
4346 
4347 	if (aid != SAE_ASSOCID_ANY && aid != SAE_ASSOCID_ALL) {
4348 		return EINVAL;
4349 	}
4350 
4351 	/* if connected, return 1 connection count */
4352 	*cnt = ((so->so_state & SS_ISCONNECTED) ? 1 : 0);
4353 
4354 	/* just asking how many there are? */
4355 	if (cidp == USER_ADDR_NULL) {
4356 		return 0;
4357 	}
4358 
4359 	/* if IN6PCB is connected, assign it connid 1 */
4360 	cid = ((*cnt != 0) ? 1 : SAE_CONNID_ANY);
4361 
4362 	return copyout(&cid, cidp, sizeof(cid));
4363 }
4364 
4365 /*
4366  * Handle SIOCGCONNINFO ioctl for PF_INET6 domain.
4367  */
4368 int
in6_getconninfo(struct socket * so,sae_connid_t cid,uint32_t * flags,uint32_t * ifindex,int32_t * soerror,user_addr_t src,socklen_t * src_len,user_addr_t dst,socklen_t * dst_len,uint32_t * aux_type,user_addr_t aux_data,uint32_t * aux_len)4369 in6_getconninfo(struct socket *so, sae_connid_t cid, uint32_t *flags,
4370     uint32_t *ifindex, int32_t *soerror, user_addr_t src, socklen_t *src_len,
4371     user_addr_t dst, socklen_t *dst_len, uint32_t *aux_type,
4372     user_addr_t aux_data, uint32_t *aux_len)
4373 {
4374 	struct in6pcb *in6p = sotoin6pcb(so);
4375 	struct sockaddr_in6 sin6;
4376 	struct ifnet *ifp = NULL;
4377 	int error = 0;
4378 	u_int32_t copy_len = 0;
4379 
4380 	/*
4381 	 * Don't test for INPCB_STATE_DEAD since this may be called
4382 	 * after SOF_PCBCLEARING is set, e.g. after tcp_close().
4383 	 */
4384 	if (in6p == NULL) {
4385 		error = EINVAL;
4386 		goto out;
4387 	}
4388 
4389 	if (cid != SAE_CONNID_ANY && cid != SAE_CONNID_ALL && cid != 1) {
4390 		error = EINVAL;
4391 		goto out;
4392 	}
4393 
4394 	ifp = in6p->in6p_last_outifp;
4395 	*ifindex = ((ifp != NULL) ? ifp->if_index : 0);
4396 	*soerror = so->so_error;
4397 	*flags = 0;
4398 	if (so->so_state & SS_ISCONNECTED) {
4399 		*flags |= (CIF_CONNECTED | CIF_PREFERRED);
4400 	}
4401 	if (in6p->in6p_flags & INP_BOUND_IF) {
4402 		*flags |= CIF_BOUND_IF;
4403 	}
4404 	if (!(in6p->in6p_flags & INP_IN6ADDR_ANY)) {
4405 		*flags |= CIF_BOUND_IP;
4406 	}
4407 	if (!(in6p->in6p_flags & INP_ANONPORT)) {
4408 		*flags |= CIF_BOUND_PORT;
4409 	}
4410 
4411 	bzero(&sin6, sizeof(sin6));
4412 	sin6.sin6_len = sizeof(sin6);
4413 	sin6.sin6_family = AF_INET6;
4414 
4415 	/* source address and port */
4416 	sin6.sin6_port = in6p->in6p_lport;
4417 	if (!in6_embedded_scope) {
4418 		sin6.sin6_scope_id = in6p->inp_lifscope;
4419 	}
4420 	in6_recoverscope(&sin6, &in6p->in6p_laddr, NULL);
4421 	if (*src_len == 0) {
4422 		*src_len = sin6.sin6_len;
4423 	} else {
4424 		if (src != USER_ADDR_NULL) {
4425 			copy_len = min(*src_len, sizeof(sin6));
4426 			error = copyout(&sin6, src, copy_len);
4427 			if (error != 0) {
4428 				goto out;
4429 			}
4430 			*src_len = copy_len;
4431 		}
4432 	}
4433 
4434 	/* destination address and port */
4435 	sin6.sin6_port = in6p->in6p_fport;
4436 	if (!in6_embedded_scope) {
4437 		sin6.sin6_scope_id = in6p->inp_fifscope;
4438 	}
4439 	in6_recoverscope(&sin6, &in6p->in6p_faddr, NULL);
4440 	if (*dst_len == 0) {
4441 		*dst_len = sin6.sin6_len;
4442 	} else {
4443 		if (dst != USER_ADDR_NULL) {
4444 			copy_len = min(*dst_len, sizeof(sin6));
4445 			error = copyout(&sin6, dst, copy_len);
4446 			if (error != 0) {
4447 				goto out;
4448 			}
4449 			*dst_len = copy_len;
4450 		}
4451 	}
4452 
4453 	if (SOCK_PROTO(so) == IPPROTO_TCP) {
4454 		struct conninfo_tcp tcp_ci;
4455 
4456 		*aux_type = CIAUX_TCP;
4457 		if (*aux_len == 0) {
4458 			*aux_len = sizeof(tcp_ci);
4459 		} else {
4460 			if (aux_data != USER_ADDR_NULL) {
4461 				copy_len = min(*aux_len, sizeof(tcp_ci));
4462 				bzero(&tcp_ci, sizeof(tcp_ci));
4463 				tcp_getconninfo(so, &tcp_ci);
4464 				error = copyout(&tcp_ci, aux_data, copy_len);
4465 				if (error != 0) {
4466 					goto out;
4467 				}
4468 				*aux_len = copy_len;
4469 			}
4470 		}
4471 	} else {
4472 		*aux_type = 0;
4473 		*aux_len = 0;
4474 	}
4475 
4476 out:
4477 	return error;
4478 }
4479 
4480 /*
4481  * 'u' group ioctls.
4482  *
4483  * The switch statement below does nothing at runtime, as it serves as a
4484  * compile time check to ensure that all of the socket 'u' ioctls (those
4485  * in the 'u' group going thru soo_ioctl) that are made available by the
4486  * networking stack is unique.  This works as long as this routine gets
4487  * updated each time a new interface ioctl gets added.
4488  *
4489  * Any failures at compile time indicates duplicated ioctl values.
4490  */
4491 static __attribute__((unused)) void
in6ioctl_cassert(void)4492 in6ioctl_cassert(void)
4493 {
4494 	/*
4495 	 * This is equivalent to _CASSERT() and the compiler wouldn't
4496 	 * generate any instructions, thus for compile time only.
4497 	 */
4498 	switch ((u_long)0) {
4499 	case 0:
4500 
4501 	/* bsd/netinet6/in6_var.h */
4502 	case SIOCAADDRCTL_POLICY:
4503 	case SIOCDADDRCTL_POLICY:
4504 	case SIOCDRADD_IN6_32:
4505 	case SIOCDRADD_IN6_64:
4506 	case SIOCDRDEL_IN6_32:
4507 	case SIOCDRDEL_IN6_64:
4508 		;
4509 	}
4510 }
4511 
4512 struct in6_llentry {
4513 	struct llentry          base;
4514 };
4515 
4516 #define        IN6_LLTBL_DEFAULT_HSIZE 32
4517 #define        IN6_LLTBL_HASH(k, h) \
4518 	((((((((k) >> 8) ^ (k)) >> 8) ^ (k)) >> 8) ^ (k)) & ((h) - 1))
4519 
4520 /*
4521  * Do actual deallocation of @lle.
4522  */
4523 static void
in6_lltable_destroy_lle_unlocked(struct llentry * lle)4524 in6_lltable_destroy_lle_unlocked(struct llentry *lle)
4525 {
4526 	LLE_LOCK_DESTROY(lle);
4527 	LLE_REQ_DESTROY(lle);
4528 	kfree_type(struct in6_llentry, lle);
4529 }
4530 
4531 /*
4532  * Called by LLE_FREE_LOCKED when number of references
4533  * drops to zero.
4534  */
4535 static void
in6_lltable_destroy_lle(struct llentry * lle)4536 in6_lltable_destroy_lle(struct llentry *lle)
4537 {
4538 	LLE_WUNLOCK(lle);
4539 	/* XXX TBD */
4540 	//thread_call_free(lle->lle_timer);
4541 	in6_lltable_destroy_lle_unlocked(lle);
4542 }
4543 
4544 
4545 static struct llentry *
in6_lltable_new(const struct in6_addr * addr6,uint16_t flags)4546 in6_lltable_new(const struct in6_addr *addr6, uint16_t flags)
4547 {
4548 #pragma unused(flags)
4549 	struct in6_llentry *lle;
4550 
4551 	lle = kalloc_type(struct in6_llentry, Z_NOWAIT | Z_ZERO);
4552 	if (lle == NULL) {              /* NB: caller generates msg */
4553 		return NULL;
4554 	}
4555 
4556 	lle->base.r_l3addr.addr6 = *addr6;
4557 	lle->base.lle_refcnt = 1;
4558 	lle->base.lle_free = in6_lltable_destroy_lle;
4559 	LLE_LOCK_INIT(&lle->base);
4560 	LLE_REQ_INIT(&lle->base);
4561 #if 0
4562 	/* XXX TBD */
4563 	lle->base.lle_timer = thread_call_allocate(nd6_llinfo_timer, lle);
4564 
4565 	if (lle->base.lle_timer == NULL) {
4566 		printf("lle_timer thread call could not be allocated.\n");
4567 		LLE_LOCK_DESTROY(&lle->base);
4568 		LLE_REQ_DESTROY(&lle->base);
4569 		kfree_type(struct in6_llentry, lle);
4570 		return NULL;
4571 	}
4572 #endif
4573 	return &lle->base;
4574 }
4575 
4576 static int
in6_lltable_match_prefix(const struct sockaddr * saddr,const struct sockaddr * smask,uint16_t flags,struct llentry * lle)4577 in6_lltable_match_prefix(const struct sockaddr *saddr,
4578     const struct sockaddr *smask, uint16_t flags, struct llentry *lle)
4579 {
4580 	const struct in6_addr *addr, *mask, *lle_addr;
4581 
4582 	addr = &((const struct sockaddr_in6 *)(const void *)saddr)->sin6_addr;
4583 	mask = &((const struct sockaddr_in6 *)(const void *)smask)->sin6_addr;
4584 	lle_addr = &lle->r_l3addr.addr6;
4585 	uint32_t lle_addr_ifscope = lle->lle_tbl->llt_ifp->if_index;
4586 	uint32_t addr_ifscope = ((const struct sockaddr_in6 *)(const void *)saddr)->sin6_scope_id;
4587 
4588 	if (in6_are_masked_addr_scope_equal(lle_addr, lle_addr_ifscope, addr, addr_ifscope, mask) == 0) {
4589 		return 0;
4590 	}
4591 
4592 	if (lle->la_flags & LLE_IFADDR) {
4593 		/*
4594 		 * Delete LLE_IFADDR records IFF address & flag matches.
4595 		 * Note that addr is the interface address within prefix
4596 		 * being matched.
4597 		 */
4598 		if (in6_are_addr_equal_scoped(addr, lle_addr, addr_ifscope, lle_addr_ifscope) &&
4599 		    (flags & LLE_STATIC) != 0) {
4600 			return 1;
4601 		}
4602 		return 0;
4603 	}
4604 
4605 	/* flags & LLE_STATIC means deleting both dynamic and static entries */
4606 	if ((flags & LLE_STATIC) || !(lle->la_flags & LLE_STATIC)) {
4607 		return 1;
4608 	}
4609 
4610 	return 0;
4611 }
4612 
4613 static void
in6_lltable_free_entry(struct lltable * llt,struct llentry * lle)4614 in6_lltable_free_entry(struct lltable *llt, struct llentry *lle)
4615 {
4616 	struct ifnet *ifp;
4617 
4618 	LLE_WLOCK_ASSERT(lle);
4619 	KASSERT(llt != NULL, ("lltable is NULL"));
4620 
4621 	/* Unlink entry from table */
4622 	if ((lle->la_flags & LLE_LINKED) != 0) {
4623 		ifp = llt->llt_ifp;
4624 		if_afdata_wlock_assert(ifp, llt->llt_af);
4625 		lltable_unlink_entry(llt, lle);
4626 	}
4627 
4628 #if 0
4629 	/* XXX TBD */
4630 	if (thread_call_cancel(lle->lle_timer) == TRUE) {
4631 		LLE_REMREF(lle);
4632 	}
4633 #endif
4634 	llentry_free(lle);
4635 }
4636 
4637 static int
in6_lltable_rtcheck(struct ifnet * ifp,uint16_t flags,const struct sockaddr * l3addr)4638 in6_lltable_rtcheck(struct ifnet *ifp,
4639     uint16_t flags, const struct sockaddr *l3addr)
4640 {
4641 #pragma unused(flags)
4642 	struct rtentry *rt;
4643 
4644 	KASSERT(l3addr->sa_family == AF_INET6,
4645 	    ("sin_family %d", l3addr->sa_family));
4646 	/* XXX rtalloc1 should take a const param */
4647 	rt = rtalloc1(__DECONST(struct sockaddr *, l3addr), 0, 0);
4648 	if (rt == NULL || (rt->rt_flags & RTF_GATEWAY) || rt->rt_ifp != ifp) {
4649 		struct ifaddr *ifa;
4650 		/*
4651 		 * Create an ND6 cache for an IPv6 neighbor
4652 		 * that is not covered by our own prefix.
4653 		 */
4654 		/* XXX ifaof_ifpforaddr should take a const param */
4655 		ifa = ifaof_ifpforaddr(__DECONST(struct sockaddr *, l3addr), ifp);
4656 		if (ifa != NULL) {
4657 			IFA_REMREF(ifa);
4658 			if (rt != NULL) {
4659 				rtfree(rt);
4660 			}
4661 			return 0;
4662 		}
4663 		log(LOG_INFO, "IPv6 address: \"%s\" is not on the network\n",
4664 		    ip6_sprintf(&((const struct sockaddr_in6 *)(const void *)l3addr)->sin6_addr));
4665 		if (rt != NULL) {
4666 			rtfree(rt);
4667 		}
4668 		return EINVAL;
4669 	}
4670 	rtfree(rt);
4671 	return 0;
4672 }
4673 
4674 static inline uint32_t
in6_lltable_hash_dst(const struct in6_addr * dst,uint32_t hsize)4675 in6_lltable_hash_dst(const struct in6_addr *dst, uint32_t hsize)
4676 {
4677 	return IN6_LLTBL_HASH(dst->s6_addr32[3], hsize);
4678 }
4679 
4680 static uint32_t
in6_lltable_hash(const struct llentry * lle,uint32_t hsize)4681 in6_lltable_hash(const struct llentry *lle, uint32_t hsize)
4682 {
4683 	return in6_lltable_hash_dst(&lle->r_l3addr.addr6, hsize);
4684 }
4685 
4686 static void
in6_lltable_fill_sa_entry(const struct llentry * lle,struct sockaddr * sa)4687 in6_lltable_fill_sa_entry(const struct llentry *lle, struct sockaddr *sa)
4688 {
4689 	struct sockaddr_in6 *sin6;
4690 
4691 	sin6 = (struct sockaddr_in6 *)(void *)sa;
4692 	bzero(sin6, sizeof(*sin6));
4693 	sin6->sin6_family = AF_INET6;
4694 	sin6->sin6_len = sizeof(*sin6);
4695 	sin6->sin6_addr = lle->r_l3addr.addr6;
4696 }
4697 
4698 static inline struct llentry *
in6_lltable_find_dst(struct lltable * llt,const struct in6_addr * dst)4699 in6_lltable_find_dst(struct lltable *llt, const struct in6_addr *dst)
4700 {
4701 	struct llentry *lle;
4702 	struct llentries *lleh;
4703 	u_int hashidx;
4704 
4705 	hashidx = in6_lltable_hash_dst(dst, llt->llt_hsize);
4706 	lleh = &llt->lle_head[hashidx];
4707 	LIST_FOREACH(lle, lleh, lle_next) {
4708 		if (lle->la_flags & LLE_DELETED) {
4709 			continue;
4710 		}
4711 		if (IN6_ARE_ADDR_EQUAL(&lle->r_l3addr.addr6, dst)) {
4712 			break;
4713 		}
4714 	}
4715 
4716 	return lle;
4717 }
4718 
4719 static void
in6_lltable_delete_entry(struct lltable * llt,struct llentry * lle)4720 in6_lltable_delete_entry(struct lltable *llt, struct llentry *lle)
4721 {
4722 #pragma unused(llt)
4723 	lle->la_flags |= LLE_DELETED;
4724 	EVENTHANDLER_INVOKE(NULL, lle_event, lle, LLENTRY_DELETED);
4725 #ifdef DIAGNOSTIC
4726 	log(LOG_INFO, "ifaddr cache = %p is deleted\n", lle);
4727 #endif
4728 	llentry_free(lle);
4729 }
4730 
4731 static struct llentry *
in6_lltable_alloc(struct lltable * llt,uint16_t flags,const struct sockaddr * l3addr)4732 in6_lltable_alloc(struct lltable *llt, uint16_t flags,
4733     const struct sockaddr *l3addr)
4734 {
4735 	const struct sockaddr_in6 *sin6 = (const struct sockaddr_in6 *)(const void *)l3addr;
4736 	struct ifnet *ifp = llt->llt_ifp;
4737 	struct llentry *lle;
4738 
4739 	KASSERT(l3addr->sa_family == AF_INET6,
4740 	    ("sin_family %d", l3addr->sa_family));
4741 
4742 	/*
4743 	 * A route that covers the given address must have
4744 	 * been installed 1st because we are doing a resolution,
4745 	 * verify this.
4746 	 */
4747 	if (!(flags & LLE_IFADDR) &&
4748 	    in6_lltable_rtcheck(ifp, flags, l3addr) != 0) {
4749 		return NULL;
4750 	}
4751 
4752 	lle = in6_lltable_new(&sin6->sin6_addr, flags);
4753 	if (lle == NULL) {
4754 		log(LOG_INFO, "lla_lookup: new lle malloc failed\n");
4755 		return NULL;
4756 	}
4757 	lle->la_flags = (uint16_t)flags;
4758 	if ((flags & LLE_IFADDR) == LLE_IFADDR) {
4759 		lltable_set_entry_addr(ifp, lle, LLADDR(SDL(ifp->if_lladdr->ifa_addr)));
4760 		lle->la_flags |= LLE_STATIC;
4761 	}
4762 
4763 	if ((lle->la_flags & LLE_STATIC) != 0) {
4764 		lle->ln_state = ND6_LLINFO_REACHABLE;
4765 	}
4766 
4767 	return lle;
4768 }
4769 
4770 static struct llentry *
in6_lltable_lookup(struct lltable * llt,uint16_t flags,const struct sockaddr * l3addr)4771 in6_lltable_lookup(struct lltable *llt, uint16_t flags,
4772     const struct sockaddr *l3addr)
4773 {
4774 	const struct sockaddr_in6 *sin6 = (const struct sockaddr_in6 *)(const void *)l3addr;
4775 	struct llentry *lle;
4776 
4777 	IF_AFDATA_LOCK_ASSERT(llt->llt_ifp, llt->llt_af);
4778 	KASSERT(l3addr->sa_family == AF_INET6,
4779 	    ("sin_family %d", l3addr->sa_family));
4780 
4781 	lle = in6_lltable_find_dst(llt, &sin6->sin6_addr);
4782 
4783 	if (lle == NULL) {
4784 		return NULL;
4785 	}
4786 
4787 	KASSERT((flags & (LLE_UNLOCKED | LLE_EXCLUSIVE)) !=
4788 	    (LLE_UNLOCKED | LLE_EXCLUSIVE), ("wrong lle request flags: 0x%X",
4789 	    flags));
4790 
4791 	if (flags & LLE_UNLOCKED) {
4792 		return lle;
4793 	}
4794 
4795 	if (flags & LLE_EXCLUSIVE) {
4796 		LLE_WLOCK(lle);
4797 	} else {
4798 		LLE_RLOCK(lle);
4799 	}
4800 	return lle;
4801 }
4802 
4803 static int
in6_lltable_dump_entry(struct lltable * llt,struct llentry * lle,struct sysctl_req * wr)4804 in6_lltable_dump_entry(struct lltable *llt, struct llentry *lle,
4805     struct sysctl_req *wr)
4806 {
4807 	struct ifnet *ifp = llt->llt_ifp;
4808 	/* XXX stack use */
4809 	struct {
4810 		struct rt_msghdr        rtm;
4811 		struct sockaddr_in6     sin6;
4812 		/*
4813 		 * ndp.c assumes that sdl is word aligned
4814 		 */
4815 #ifdef __LP64__
4816 		uint32_t                pad;
4817 #endif
4818 		struct sockaddr_dl      sdl;
4819 	} ndpc;
4820 	struct sockaddr_dl *sdl;
4821 	int error;
4822 
4823 	bzero(&ndpc, sizeof(ndpc));
4824 	/* skip deleted entries */
4825 	if ((lle->la_flags & LLE_DELETED) == LLE_DELETED) {
4826 		return 0;
4827 	}
4828 	/* Skip if jailed and not a valid IP of the prison. */
4829 	lltable_fill_sa_entry(lle,
4830 	    (struct sockaddr *)&ndpc.sin6);
4831 	/*
4832 	 * produce a msg made of:
4833 	 *  struct rt_msghdr;
4834 	 *  struct sockaddr_in6 (IPv6)
4835 	 *  struct sockaddr_dl;
4836 	 */
4837 	ndpc.rtm.rtm_msglen = sizeof(ndpc);
4838 	ndpc.rtm.rtm_version = RTM_VERSION;
4839 	ndpc.rtm.rtm_type = RTM_GET;
4840 	ndpc.rtm.rtm_flags = RTF_UP;
4841 	ndpc.rtm.rtm_addrs = RTA_DST | RTA_GATEWAY;
4842 
4843 	/* publish */
4844 	if (lle->la_flags & LLE_PUB) {
4845 		ndpc.rtm.rtm_flags |= RTF_ANNOUNCE;
4846 	}
4847 	sdl = &ndpc.sdl;
4848 	sdl->sdl_family = AF_LINK;
4849 	sdl->sdl_len = sizeof(*sdl);
4850 	sdl->sdl_index = ifp->if_index;
4851 	sdl->sdl_type = ifp->if_type;
4852 	if ((lle->la_flags & LLE_VALID) == LLE_VALID) {
4853 		sdl->sdl_alen = ifp->if_addrlen;
4854 		bcopy(&lle->ll_addr, LLADDR(sdl), ifp->if_addrlen);
4855 	} else {
4856 		sdl->sdl_alen = 0;
4857 		bzero(LLADDR(sdl), ifp->if_addrlen);
4858 	}
4859 	if (lle->la_expire != 0) {
4860 		clock_sec_t secs;
4861 		clock_usec_t usecs;
4862 
4863 		clock_get_calendar_microtime(&secs, &usecs);
4864 		ndpc.rtm.rtm_rmx.rmx_expire = (int32_t)(lle->la_expire +
4865 		    lle->lle_remtime / hz +
4866 		    secs - net_uptime());
4867 	}
4868 	ndpc.rtm.rtm_flags |= (RTF_HOST | RTF_LLDATA);
4869 	if (lle->la_flags & LLE_STATIC) {
4870 		ndpc.rtm.rtm_flags |= RTF_STATIC;
4871 	}
4872 	if (lle->la_flags & LLE_IFADDR) {
4873 		ndpc.rtm.rtm_flags |= RTF_PINNED;
4874 	}
4875 	if (lle->ln_router != 0) {
4876 		ndpc.rtm.rtm_flags |= RTF_GATEWAY;
4877 	}
4878 	ndpc.rtm.rtm_rmx.rmx_pksent = lle->la_asked;
4879 	/* Store state in rmx_weight value */
4880 	ndpc.rtm.rtm_rmx.rmx_state = lle->ln_state;
4881 	ndpc.rtm.rtm_index = ifp->if_index;
4882 	error = SYSCTL_OUT(wr, &ndpc, sizeof(ndpc));
4883 
4884 	return error;
4885 }
4886 
4887 struct lltable *
in6_lltattach(struct ifnet * ifp)4888 in6_lltattach(struct ifnet *ifp)
4889 {
4890 	struct lltable *llt;
4891 
4892 	llt = lltable_allocate_htbl(IN6_LLTBL_DEFAULT_HSIZE);
4893 	llt->llt_af = AF_INET6;
4894 	llt->llt_ifp = ifp;
4895 
4896 	llt->llt_lookup = in6_lltable_lookup;
4897 	llt->llt_alloc_entry = in6_lltable_alloc;
4898 	llt->llt_delete_entry = in6_lltable_delete_entry;
4899 	llt->llt_dump_entry = in6_lltable_dump_entry;
4900 	llt->llt_hash = in6_lltable_hash;
4901 	llt->llt_fill_sa_entry = in6_lltable_fill_sa_entry;
4902 	llt->llt_free_entry = in6_lltable_free_entry;
4903 	llt->llt_match_prefix = in6_lltable_match_prefix;
4904 	lltable_link(llt);
4905 
4906 	return llt;
4907 }
4908 
4909 void
in6_ip6_to_sockaddr(const struct in6_addr * ip6,u_int16_t port,uint32_t ifscope,struct sockaddr_in6 * sin6,u_int32_t maxlen)4910 in6_ip6_to_sockaddr(const struct in6_addr *ip6, u_int16_t port, uint32_t ifscope,
4911     struct sockaddr_in6 *sin6, u_int32_t maxlen)
4912 {
4913 	if (maxlen < sizeof(struct sockaddr_in6)) {
4914 		return;
4915 	}
4916 
4917 	*sin6 = (struct sockaddr_in6) {
4918 		.sin6_family = AF_INET6,
4919 		.sin6_len = sizeof(*sin6),
4920 		.sin6_port = port,
4921 		.sin6_addr = *ip6,
4922 		.sin6_scope_id = IN6_IS_SCOPE_EMBED(ip6) ? ifscope : IFSCOPE_NONE,
4923 	};
4924 
4925 	if (IN6_IS_SCOPE_EMBED(&sin6->sin6_addr)) {
4926 		in6_verify_ifscope(&sin6->sin6_addr, ifscope);
4927 		if (in6_embedded_scope) {
4928 			sin6->sin6_scope_id = ntohs(sin6->sin6_addr.s6_addr16[1]);
4929 			sin6->sin6_addr.s6_addr16[1] = 0;
4930 		}
4931 	}
4932 }
4933 
4934 /* IPv6 events */
4935 struct in6_event {
4936 	in6_evhdlr_code_t in6_event_code;
4937 	struct ifnet *in6_ifp;
4938 	struct in6_addr in6_address;
4939 	uint32_t val;
4940 };
4941 
4942 struct in6_event2kev in6_event2kev_array[IN6_EVENT_MAX] = {
4943 	{
4944 		.in6_event_code = IN6_ADDR_MARKED_DUPLICATED,
4945 		.in6_event_kev_subclass = KEV_ND6_SUBCLASS,
4946 		.in6_event_kev_code = KEV_ND6_DAD_FAILURE,
4947 		.in6_event_str = "IN6_ADDR_MARKED_DUPLICATED",
4948 	},
4949 	{
4950 		.in6_event_code = IN6_ADDR_MARKED_DETACHED,
4951 		.in6_event_kev_subclass = KEV_ND6_SUBCLASS,
4952 		.in6_event_kev_code = KEV_ND6_ADDR_DETACHED,
4953 		.in6_event_str = "IN6_ADDR_MARKED_DETACHED",
4954 	},
4955 	{
4956 		.in6_event_code = IN6_ADDR_MARKED_DEPRECATED,
4957 		.in6_event_kev_subclass = KEV_ND6_SUBCLASS,
4958 		.in6_event_kev_code = KEV_ND6_ADDR_DEPRECATED,
4959 		.in6_event_str = "IN6_ADDR_MARKED_DEPRECATED",
4960 	},
4961 	{
4962 		.in6_event_code = IN6_NDP_RTR_EXPIRY,
4963 		.in6_event_kev_subclass = KEV_ND6_SUBCLASS,
4964 		.in6_event_kev_code = KEV_ND6_RTR_EXPIRED,
4965 		.in6_event_str = "IN6_NDP_RTR_EXPIRY",
4966 	},
4967 	{
4968 		.in6_event_code = IN6_NDP_PFX_EXPIRY,
4969 		.in6_event_kev_subclass = KEV_ND6_SUBCLASS,
4970 		.in6_event_kev_code = KEV_ND6_PFX_EXPIRED,
4971 		.in6_event_str = "IN6_NDP_PFX_EXPIRY",
4972 	},
4973 	{
4974 		.in6_event_code = IN6_NDP_ADDR_EXPIRY,
4975 		.in6_event_kev_subclass = KEV_ND6_SUBCLASS,
4976 		.in6_event_kev_code = KEV_ND6_ADDR_EXPIRED,
4977 		.in6_event_str = "IN6_NDP_ADDR_EXPIRY",
4978 	},
4979 };
4980 
4981 void
in6_eventhdlr_callback(struct eventhandler_entry_arg arg0 __unused,in6_evhdlr_code_t in6_ev_code,struct ifnet * ifp,struct in6_addr * p_addr6,uint32_t val)4982 in6_eventhdlr_callback(struct eventhandler_entry_arg arg0 __unused,
4983     in6_evhdlr_code_t in6_ev_code, struct ifnet *ifp,
4984     struct in6_addr *p_addr6, uint32_t val)
4985 {
4986 	struct kev_msg ev_msg;
4987 	struct kev_nd6_event nd6_event;
4988 
4989 	bzero(&ev_msg, sizeof(ev_msg));
4990 	bzero(&nd6_event, sizeof(nd6_event));
4991 
4992 	nd6log0(info, "%s Event %s received for %s\n",
4993 	    __func__, in6_event2kev_array[in6_ev_code].in6_event_str,
4994 	    ip6_sprintf(p_addr6));
4995 
4996 	ev_msg.vendor_code      = KEV_VENDOR_APPLE;
4997 	ev_msg.kev_class        = KEV_NETWORK_CLASS;
4998 	ev_msg.kev_subclass     =
4999 	    in6_event2kev_array[in6_ev_code].in6_event_kev_subclass;
5000 	ev_msg.event_code       =
5001 	    in6_event2kev_array[in6_ev_code].in6_event_kev_code;
5002 
5003 	nd6_event.link_data.if_family = ifp->if_family;
5004 	nd6_event.link_data.if_unit = ifp->if_unit;
5005 	strlcpy(nd6_event.link_data.if_name, ifp->if_name,
5006 	    sizeof(nd6_event.link_data.if_name));
5007 
5008 	VERIFY(p_addr6 != NULL);
5009 	bcopy(p_addr6, &nd6_event.in6_address,
5010 	    sizeof(nd6_event.in6_address));
5011 	nd6_event.val = val;
5012 
5013 	ev_msg.dv[0].data_ptr = &nd6_event;
5014 	ev_msg.dv[0].data_length = sizeof(nd6_event);
5015 
5016 	kev_post_msg(&ev_msg);
5017 }
5018 
5019 static void
in6_event_callback(void * arg)5020 in6_event_callback(void *arg)
5021 {
5022 	struct in6_event *p_in6_ev = (struct in6_event *)arg;
5023 
5024 	EVENTHANDLER_INVOKE(&in6_evhdlr_ctxt, in6_event,
5025 	    p_in6_ev->in6_event_code, p_in6_ev->in6_ifp,
5026 	    &p_in6_ev->in6_address, p_in6_ev->val);
5027 }
5028 
5029 struct in6_event_nwk_wq_entry {
5030 	struct nwk_wq_entry nwk_wqe;
5031 	struct in6_event in6_ev_arg;
5032 };
5033 
5034 void
in6_event_enqueue_nwk_wq_entry(in6_evhdlr_code_t in6_event_code,struct ifnet * ifp,struct in6_addr * p_addr6,uint32_t val)5035 in6_event_enqueue_nwk_wq_entry(in6_evhdlr_code_t in6_event_code,
5036     struct ifnet *ifp, struct in6_addr *p_addr6,
5037     uint32_t val)
5038 {
5039 	struct in6_event_nwk_wq_entry *p_in6_ev = NULL;
5040 
5041 	MALLOC(p_in6_ev, struct in6_event_nwk_wq_entry *,
5042 	    sizeof(struct in6_event_nwk_wq_entry),
5043 	    M_NWKWQ, M_WAITOK | M_ZERO);
5044 
5045 	p_in6_ev->nwk_wqe.func = in6_event_callback;
5046 	p_in6_ev->nwk_wqe.is_arg_managed = TRUE;
5047 	p_in6_ev->nwk_wqe.arg = &p_in6_ev->in6_ev_arg;
5048 
5049 	p_in6_ev->in6_ev_arg.in6_event_code = in6_event_code;
5050 	p_in6_ev->in6_ev_arg.in6_ifp = ifp;
5051 	if (p_addr6 != NULL) {
5052 		bcopy(p_addr6, &p_in6_ev->in6_ev_arg.in6_address,
5053 		    sizeof(p_in6_ev->in6_ev_arg.in6_address));
5054 	}
5055 	p_in6_ev->in6_ev_arg.val = val;
5056 
5057 	nwk_wq_enqueue((struct nwk_wq_entry*)p_in6_ev);
5058 }
5059 
5060 /*
5061  * Caller must hold in6_ifaddr_rwlock as writer.
5062  */
5063 static void
in6_iahash_remove(struct in6_ifaddr * ia)5064 in6_iahash_remove(struct in6_ifaddr *ia)
5065 {
5066 	LCK_RW_ASSERT(&in6_ifaddr_rwlock, LCK_RW_ASSERT_EXCLUSIVE);
5067 	IFA_LOCK_ASSERT_HELD(&ia->ia_ifa);
5068 
5069 	if (!IA6_IS_HASHED(ia)) {
5070 		panic("%s: attempt to remove wrong ia %p from ipv6 hash table", __func__, ia);
5071 		/* NOTREACHED */
5072 	}
5073 	TAILQ_REMOVE(IN6ADDR_HASH(&ia->ia_addr.sin6_addr), ia, ia6_hash);
5074 	IA6_HASH_INIT(ia);
5075 	if (IFA_REMREF_LOCKED(&ia->ia_ifa) == NULL) {
5076 		panic("%s: unexpected (missing) refcnt ifa=%p", __func__,
5077 		    &ia->ia_ifa);
5078 		/* NOTREACHED */
5079 	}
5080 }
5081 
5082 /*
5083  * Caller must hold in6_ifaddr_rwlock as writer.
5084  */
5085 static void
in6_iahash_insert(struct in6_ifaddr * ia)5086 in6_iahash_insert(struct in6_ifaddr *ia)
5087 {
5088 	LCK_RW_ASSERT(&in6_ifaddr_rwlock, LCK_RW_ASSERT_EXCLUSIVE);
5089 	IFA_LOCK_ASSERT_HELD(&ia->ia_ifa);
5090 
5091 	if (ia->ia_addr.sin6_family != AF_INET6) {
5092 		panic("%s: attempt to insert wrong ia %p into hash table", __func__, ia);
5093 		/* NOTREACHED */
5094 	} else if (IA6_IS_HASHED(ia)) {
5095 		panic("%s: attempt to double-insert ia %p into hash table", __func__, ia);
5096 		/* NOTREACHED */
5097 	}
5098 	TAILQ_INSERT_HEAD(IN6ADDR_HASH(&ia->ia_addr.sin6_addr),
5099 	    ia, ia6_hash);
5100 	IFA_ADDREF_LOCKED(&ia->ia_ifa);
5101 }
5102 
5103 /*
5104  * Some point to point interfaces that are tunnels borrow the address from
5105  * an underlying interface (e.g. VPN server). In order for source address
5106  * selection logic to find the underlying interface first, we add the address
5107  * of borrowing point to point interfaces at the end of the list.
5108  * (see rdar://6733789)
5109  *
5110  * Caller must hold in6_ifaddr_rwlock as writer.
5111  */
5112 static void
in6_iahash_insert_ptp(struct in6_ifaddr * ia)5113 in6_iahash_insert_ptp(struct in6_ifaddr *ia)
5114 {
5115 	struct in6_ifaddr *tmp_ifa;
5116 	struct ifnet *tmp_ifp;
5117 
5118 	LCK_RW_ASSERT(&in6_ifaddr_rwlock, LCK_RW_ASSERT_EXCLUSIVE);
5119 	IFA_LOCK_ASSERT_HELD(&ia->ia_ifa);
5120 
5121 	if (ia->ia_addr.sin6_family != AF_INET6) {
5122 		panic("%s: attempt to insert wrong ia %p into hash table", __func__, ia);
5123 		/* NOTREACHED */
5124 	} else if (IA6_IS_HASHED(ia)) {
5125 		panic("%s: attempt to double-insert ia %p into hash table", __func__, ia);
5126 		/* NOTREACHED */
5127 	}
5128 	IFA_UNLOCK(&ia->ia_ifa);
5129 	TAILQ_FOREACH(tmp_ifa, IN6ADDR_HASH(&ia->ia_addr.sin6_addr), ia6_hash) {
5130 		IFA_LOCK(&tmp_ifa->ia_ifa);
5131 		/* ia->ia_addr won't change, so check without lock */
5132 		if (in6_are_addr_equal_scoped(&tmp_ifa->ia_addr.sin6_addr, &ia->ia_addr.sin6_addr, tmp_ifa->ia_addr.sin6_scope_id, ia->ia_addr.sin6_scope_id)) {
5133 			IFA_UNLOCK(&tmp_ifa->ia_ifa);
5134 			break;
5135 		}
5136 		IFA_UNLOCK(&tmp_ifa->ia_ifa);
5137 	}
5138 	tmp_ifp = (tmp_ifa == NULL) ? NULL : tmp_ifa->ia_ifp;
5139 
5140 	IFA_LOCK(&ia->ia_ifa);
5141 	if (tmp_ifp == NULL) {
5142 		TAILQ_INSERT_HEAD(IN6ADDR_HASH(&ia->ia_addr.sin6_addr),
5143 		    ia, ia6_hash);
5144 	} else {
5145 		TAILQ_INSERT_TAIL(IN6ADDR_HASH(&ia->ia_addr.sin6_addr),
5146 		    ia, ia6_hash);
5147 	}
5148 	IFA_ADDREF_LOCKED(&ia->ia_ifa);
5149 }
5150