xref: /xnu-8796.101.5/bsd/netinet6/in6.c (revision aca3beaa3dfbd42498b42c5e5ce20a938e6554e5)
1 /*
2  * Copyright (c) 2003-2022 Apple Inc. All rights reserved.
3  *
4  * @APPLE_OSREFERENCE_LICENSE_HEADER_START@
5  *
6  * This file contains Original Code and/or Modifications of Original Code
7  * as defined in and that are subject to the Apple Public Source License
8  * Version 2.0 (the 'License'). You may not use this file except in
9  * compliance with the License. The rights granted to you under the License
10  * may not be used to create, or enable the creation or redistribution of,
11  * unlawful or unlicensed copies of an Apple operating system, or to
12  * circumvent, violate, or enable the circumvention or violation of, any
13  * terms of an Apple operating system software license agreement.
14  *
15  * Please obtain a copy of the License at
16  * http://www.opensource.apple.com/apsl/ and read it before using this file.
17  *
18  * The Original Code and all software distributed under the License are
19  * distributed on an 'AS IS' basis, WITHOUT WARRANTY OF ANY KIND, EITHER
20  * EXPRESS OR IMPLIED, AND APPLE HEREBY DISCLAIMS ALL SUCH WARRANTIES,
21  * INCLUDING WITHOUT LIMITATION, ANY WARRANTIES OF MERCHANTABILITY,
22  * FITNESS FOR A PARTICULAR PURPOSE, QUIET ENJOYMENT OR NON-INFRINGEMENT.
23  * Please see the License for the specific language governing rights and
24  * limitations under the License.
25  *
26  * @APPLE_OSREFERENCE_LICENSE_HEADER_END@
27  */
28 
29 /*
30  * Copyright (C) 1995, 1996, 1997, and 1998 WIDE Project.
31  * All rights reserved.
32  *
33  * Redistribution and use in source and binary forms, with or without
34  * modification, are permitted provided that the following conditions
35  * are met:
36  * 1. Redistributions of source code must retain the above copyright
37  *    notice, this list of conditions and the following disclaimer.
38  * 2. Redistributions in binary form must reproduce the above copyright
39  *    notice, this list of conditions and the following disclaimer in the
40  *    documentation and/or other materials provided with the distribution.
41  * 3. Neither the name of the project nor the names of its contributors
42  *    may be used to endorse or promote products derived from this software
43  *    without specific prior written permission.
44  *
45  * THIS SOFTWARE IS PROVIDED BY THE PROJECT AND CONTRIBUTORS ``AS IS'' AND
46  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
47  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
48  * ARE DISCLAIMED.  IN NO EVENT SHALL THE PROJECT OR CONTRIBUTORS BE LIABLE
49  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
50  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
51  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
52  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
53  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
54  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
55  * SUCH DAMAGE.
56  */
57 
58 /*
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 			/*
1037 			 * 32-bit userland expects a 32-bit in6_addrlifetime to
1038 			 * come back:
1039 			 */
1040 			bcopy(&lt, &ifr->ifr_ifru.ifru_lifetime, sizeof(lt));
1041 		}
1042 		IFA_UNLOCK(&ia->ia_ifa);
1043 		break;
1044 
1045 	case SIOCSIFALIFETIME_IN6:      /* struct in6_ifreq */
1046 		getmicrotime(&caltime);
1047 
1048 		/* sanity for overflow - beware unsigned */
1049 		if (p64) {
1050 			struct in6_addrlifetime_64 lt;
1051 
1052 			bcopy(&ifr->ifr_ifru.ifru_lifetime, &lt, sizeof(lt));
1053 			if (lt.ia6t_vltime != ND6_INFINITE_LIFETIME &&
1054 			    lt.ia6t_vltime + caltime.tv_sec < caltime.tv_sec) {
1055 				error = EINVAL;
1056 				break;
1057 			}
1058 			if (lt.ia6t_pltime != ND6_INFINITE_LIFETIME &&
1059 			    lt.ia6t_pltime + caltime.tv_sec < caltime.tv_sec) {
1060 				error = EINVAL;
1061 				break;
1062 			}
1063 		} else {
1064 			struct in6_addrlifetime_32 lt;
1065 
1066 			bcopy(&ifr->ifr_ifru.ifru_lifetime, &lt, sizeof(lt));
1067 			if (lt.ia6t_vltime != ND6_INFINITE_LIFETIME &&
1068 			    lt.ia6t_vltime + caltime.tv_sec < caltime.tv_sec) {
1069 				error = EINVAL;
1070 				break;
1071 			}
1072 			if (lt.ia6t_pltime != ND6_INFINITE_LIFETIME &&
1073 			    lt.ia6t_pltime + caltime.tv_sec < caltime.tv_sec) {
1074 				error = EINVAL;
1075 				break;
1076 			}
1077 		}
1078 
1079 		IFA_LOCK(&ia->ia_ifa);
1080 		if (p64) {
1081 			struct in6_addrlifetime_64 lt;
1082 
1083 			bcopy(&ifr->ifr_ifru.ifru_lifetime, &lt, sizeof(lt));
1084 			ia6_lt.ia6t_expire = (time_t)lt.ia6t_expire;
1085 			ia6_lt.ia6t_preferred = (time_t)lt.ia6t_preferred;
1086 			ia6_lt.ia6t_vltime = lt.ia6t_vltime;
1087 			ia6_lt.ia6t_pltime = lt.ia6t_pltime;
1088 		} else {
1089 			struct in6_addrlifetime_32 lt;
1090 
1091 			bcopy(&ifr->ifr_ifru.ifru_lifetime, &lt, sizeof(lt));
1092 			ia6_lt.ia6t_expire = (uint32_t)lt.ia6t_expire;
1093 			ia6_lt.ia6t_preferred = (uint32_t)lt.ia6t_preferred;
1094 			ia6_lt.ia6t_vltime = lt.ia6t_vltime;
1095 			ia6_lt.ia6t_pltime = lt.ia6t_pltime;
1096 		}
1097 		/* for sanity */
1098 		if (ia6_lt.ia6t_vltime != ND6_INFINITE_LIFETIME) {
1099 			ia6_lt.ia6t_expire = (time_t)(timenow + ia6_lt.ia6t_vltime);
1100 		} else {
1101 			ia6_lt.ia6t_expire = 0;
1102 		}
1103 
1104 		if (ia6_lt.ia6t_pltime != ND6_INFINITE_LIFETIME) {
1105 			ia6_lt.ia6t_preferred = (time_t)(timenow + ia6_lt.ia6t_pltime);
1106 		} else {
1107 			ia6_lt.ia6t_preferred = 0;
1108 		}
1109 
1110 		in6ifa_setlifetime(ia, &ia6_lt);
1111 		IFA_UNLOCK(&ia->ia_ifa);
1112 		break;
1113 
1114 	default:
1115 		VERIFY(0);
1116 		/* NOTREACHED */
1117 	}
1118 
1119 	return error;
1120 }
1121 
1122 static int
in6ctl_clat46start(struct ifnet * ifp)1123 in6ctl_clat46start(struct ifnet *ifp)
1124 {
1125 	struct nd_prefix *pr = NULL;
1126 	struct nd_prefix *next = NULL;
1127 	struct in6_ifaddr *ia6 = NULL;
1128 	int error = 0;
1129 
1130 	if (ifp == lo_ifp) {
1131 		return EINVAL;
1132 	}
1133 	/*
1134 	 * Traverse the list of prefixes and find the first non-linklocal
1135 	 * prefix on the interface.
1136 	 * For that found eligible prefix, configure a CLAT46 reserved address.
1137 	 */
1138 	lck_mtx_lock(nd6_mutex);
1139 	for (pr = nd_prefix.lh_first; pr; pr = next) {
1140 		next = pr->ndpr_next;
1141 
1142 		NDPR_LOCK(pr);
1143 		if (pr->ndpr_ifp != ifp) {
1144 			NDPR_UNLOCK(pr);
1145 			continue;
1146 		}
1147 
1148 		if (IN6_IS_ADDR_LINKLOCAL(&pr->ndpr_prefix.sin6_addr)) {
1149 			NDPR_UNLOCK(pr);
1150 			continue; /* XXX */
1151 		}
1152 
1153 		if (pr->ndpr_raf_auto == 0) {
1154 			NDPR_UNLOCK(pr);
1155 			continue;
1156 		}
1157 
1158 		if (pr->ndpr_stateflags & NDPRF_DEFUNCT) {
1159 			NDPR_UNLOCK(pr);
1160 			continue;
1161 		}
1162 
1163 		if ((pr->ndpr_stateflags & NDPRF_CLAT46) == 0
1164 		    && pr->ndpr_vltime != 0) {
1165 			NDPR_ADDREF(pr); /* Take reference for rest of the processing */
1166 			NDPR_UNLOCK(pr);
1167 			break;
1168 		} else {
1169 			NDPR_UNLOCK(pr);
1170 			continue;
1171 		}
1172 	}
1173 	lck_mtx_unlock(nd6_mutex);
1174 
1175 	if (pr != NULL) {
1176 		if ((ia6 = in6_pfx_newpersistaddr(pr, FALSE, &error,
1177 		    TRUE, CLAT46_COLLISION_COUNT_OFFSET)) == NULL) {
1178 			nd6log0(error,
1179 			    "Could not configure CLAT46 address on"
1180 			    " interface %s.\n", ifp->if_xname);
1181 		} else {
1182 			IFA_LOCK(&ia6->ia_ifa);
1183 			NDPR_LOCK(pr);
1184 			ia6->ia6_ndpr = pr;
1185 			NDPR_ADDREF(pr); /* for addr reference */
1186 			pr->ndpr_stateflags |= NDPRF_CLAT46;
1187 			pr->ndpr_addrcnt++;
1188 			VERIFY(pr->ndpr_addrcnt != 0);
1189 			NDPR_UNLOCK(pr);
1190 			IFA_UNLOCK(&ia6->ia_ifa);
1191 			IFA_REMREF(&ia6->ia_ifa);
1192 			ia6 = NULL;
1193 			/*
1194 			 * A newly added address might affect the status
1195 			 * of other addresses, so we check and update it.
1196 			 * XXX: what if address duplication happens?
1197 			 */
1198 			lck_mtx_lock(nd6_mutex);
1199 			pfxlist_onlink_check();
1200 			lck_mtx_unlock(nd6_mutex);
1201 		}
1202 		NDPR_REMREF(pr);
1203 	}
1204 	return error;
1205 }
1206 
1207 static int
in6ctl_clat46stop(struct ifnet * ifp)1208 in6ctl_clat46stop(struct ifnet *ifp)
1209 {
1210 	int error = 0;
1211 	struct in6_ifaddr *ia = NULL;
1212 
1213 	if (ifp == lo_ifp) {
1214 		return EINVAL;
1215 	}
1216 	if ((ifp->if_eflags & IFEF_CLAT46) == 0) {
1217 		/* CLAT46 isn't enabled */
1218 		goto done;
1219 	}
1220 	if_clear_eflags(ifp, IFEF_CLAT46);
1221 
1222 	/* find CLAT46 address and remove it */
1223 	lck_rw_lock_exclusive(&in6_ifaddr_rwlock);
1224 	TAILQ_FOREACH(ia, &in6_ifaddrhead, ia6_link) {
1225 		if (ia->ia_ifa.ifa_ifp != ifp) {
1226 			continue;
1227 		}
1228 		IFA_LOCK(&ia->ia_ifa);
1229 		if ((ia->ia6_flags & IN6_IFF_CLAT46) != 0) {
1230 			IFA_ADDREF_LOCKED(&ia->ia_ifa); /* for us */
1231 			IFA_UNLOCK(&ia->ia_ifa);
1232 			lck_rw_done(&in6_ifaddr_rwlock);
1233 			in6_purgeaddr(&ia->ia_ifa);
1234 			IFA_REMREF(&ia->ia_ifa);        /* for us */
1235 			goto done;
1236 		}
1237 		IFA_UNLOCK(&ia->ia_ifa);
1238 	}
1239 	lck_rw_done(&in6_ifaddr_rwlock);
1240 
1241 done:
1242 	return error;
1243 }
1244 
1245 #define ifa2ia6(ifa)    ((struct in6_ifaddr *)(void *)(ifa))
1246 
1247 /*
1248  * Generic INET6 control operations (ioctl's).
1249  *
1250  * ifp is NULL if not an interface-specific ioctl.
1251  *
1252  * Most of the routines called to handle the ioctls would end up being
1253  * tail-call optimized, which unfortunately causes this routine to
1254  * consume too much stack space; this is the reason for the "noinline"
1255  * attribute used on those routines.
1256  *
1257  * If called directly from within the networking stack (as opposed to via
1258  * pru_control), the socket parameter may be NULL.
1259  */
1260 int
in6_control(struct socket * so,u_long cmd,caddr_t data,struct ifnet * ifp,struct proc * p)1261 in6_control(struct socket *so, u_long cmd, caddr_t data, struct ifnet *ifp,
1262     struct proc *p)
1263 {
1264 	struct in6_ifreq *ifr = (struct in6_ifreq *)(void *)data;
1265 	struct in6_aliasreq sifra, *ifra = NULL;
1266 	struct in6_ifaddr *ia = NULL;
1267 	struct sockaddr_in6 sin6, *sa6 = NULL;
1268 	boolean_t privileged = (proc_suser(p) == 0);
1269 	boolean_t p64 = proc_is64bit(p);
1270 	boolean_t so_unlocked = FALSE;
1271 	int intval, error = 0;
1272 
1273 	/* In case it's NULL, make sure it came from the kernel */
1274 	VERIFY(so != NULL || p == kernproc);
1275 
1276 	/*
1277 	 * ioctls which don't require ifp, may require socket.
1278 	 */
1279 	switch (cmd) {
1280 	case SIOCAADDRCTL_POLICY:       /* struct in6_addrpolicy */
1281 	case SIOCDADDRCTL_POLICY:       /* struct in6_addrpolicy */
1282 		if (!privileged) {
1283 			return EPERM;
1284 		}
1285 		return in6_src_ioctl(cmd, data);
1286 	/* NOTREACHED */
1287 
1288 	case SIOCDRADD_IN6_32:          /* struct in6_defrouter_32 */
1289 	case SIOCDRADD_IN6_64:          /* struct in6_defrouter_64 */
1290 	case SIOCDRDEL_IN6_32:          /* struct in6_defrouter_32 */
1291 	case SIOCDRDEL_IN6_64:          /* struct in6_defrouter_64 */
1292 		if (!privileged) {
1293 			return EPERM;
1294 		}
1295 		return defrtrlist_ioctl(cmd, data);
1296 	/* NOTREACHED */
1297 
1298 	case SIOCGASSOCIDS32:           /* struct so_aidreq32 */
1299 	case SIOCGASSOCIDS64:           /* struct so_aidreq64 */
1300 		return in6ctl_associd(so, cmd, data);
1301 	/* NOTREACHED */
1302 
1303 	case SIOCGCONNIDS32:            /* struct so_cidreq32 */
1304 	case SIOCGCONNIDS64:            /* struct so_cidreq64 */
1305 		return in6ctl_connid(so, cmd, data);
1306 	/* NOTREACHED */
1307 
1308 	case SIOCGCONNINFO32:           /* struct so_cinforeq32 */
1309 	case SIOCGCONNINFO64:           /* struct so_cinforeq64 */
1310 		return in6ctl_conninfo(so, cmd, data);
1311 		/* NOTREACHED */
1312 	}
1313 
1314 	/*
1315 	 * The rest of ioctls require ifp; reject if we don't have one;
1316 	 * return ENXIO to be consistent with ifioctl().
1317 	 */
1318 	if (ifp == NULL) {
1319 		return ENXIO;
1320 	}
1321 
1322 	/*
1323 	 * Unlock the socket since ifnet_ioctl() may be invoked by
1324 	 * one of the ioctl handlers below.  Socket will be re-locked
1325 	 * prior to returning.
1326 	 */
1327 	if (so != NULL) {
1328 		socket_unlock(so, 0);
1329 		so_unlocked = TRUE;
1330 	}
1331 
1332 	lck_mtx_lock(&ifp->if_inet6_ioctl_lock);
1333 	while (ifp->if_inet6_ioctl_busy) {
1334 		(void) msleep(&ifp->if_inet6_ioctl_busy, &ifp->if_inet6_ioctl_lock, (PZERO - 1),
1335 		    __func__, NULL);
1336 		LCK_MTX_ASSERT(&ifp->if_inet6_ioctl_lock, LCK_MTX_ASSERT_OWNED);
1337 	}
1338 	ifp->if_inet6_ioctl_busy = TRUE;
1339 	lck_mtx_unlock(&ifp->if_inet6_ioctl_lock);
1340 
1341 	/*
1342 	 * ioctls which require ifp but not interface address.
1343 	 */
1344 	switch (cmd) {
1345 	case SIOCAUTOCONF_START:        /* struct in6_ifreq */
1346 		if (!privileged) {
1347 			error = EPERM;
1348 			goto done;
1349 		}
1350 		error = in6_autoconf(ifp, TRUE);
1351 		goto done;
1352 
1353 	case SIOCAUTOCONF_STOP:         /* struct in6_ifreq */
1354 		if (!privileged) {
1355 			error = EPERM;
1356 			goto done;
1357 		}
1358 		error = in6_autoconf(ifp, FALSE);
1359 		goto done;
1360 
1361 	case SIOCLL_START_32:           /* struct in6_aliasreq_32 */
1362 	case SIOCLL_START_64:           /* struct in6_aliasreq_64 */
1363 		if (!privileged) {
1364 			error = EPERM;
1365 			goto done;
1366 		}
1367 		error = in6ctl_llstart(ifp, cmd, data);
1368 		goto done;
1369 
1370 	case SIOCLL_STOP:               /* struct in6_ifreq */
1371 		if (!privileged) {
1372 			error = EPERM;
1373 			goto done;
1374 		}
1375 		error = in6ctl_llstop(ifp);
1376 		goto done;
1377 
1378 	case SIOCCLAT46_START:          /* struct in6_ifreq */
1379 		if (!privileged) {
1380 			error = EPERM;
1381 			goto done;
1382 		}
1383 		error = in6ctl_clat46start(ifp);
1384 		if (error == 0) {
1385 			if_set_eflags(ifp, IFEF_CLAT46);
1386 		}
1387 		goto done;
1388 
1389 	case SIOCCLAT46_STOP:           /* struct in6_ifreq */
1390 		if (!privileged) {
1391 			error = EPERM;
1392 			goto done;
1393 		}
1394 		error = in6ctl_clat46stop(ifp);
1395 		goto done;
1396 	case SIOCGETROUTERMODE_IN6:     /* struct in6_ifreq */
1397 		intval = ifp->if_ipv6_router_mode;
1398 		bcopy(&intval, &((struct in6_ifreq *)(void *)data)->ifr_intval,
1399 		    sizeof(intval));
1400 		goto done;
1401 	case SIOCSETROUTERMODE_IN6:     /* struct in6_ifreq */
1402 		if (!privileged) {
1403 			error = EPERM;
1404 			goto done;
1405 		}
1406 		bcopy(&((struct in6_ifreq *)(void *)data)->ifr_intval,
1407 		    &intval, sizeof(intval));
1408 		switch (intval) {
1409 		case IPV6_ROUTER_MODE_DISABLED:
1410 		case IPV6_ROUTER_MODE_EXCLUSIVE:
1411 		case IPV6_ROUTER_MODE_HYBRID:
1412 			break;
1413 		default:
1414 			error = EINVAL;
1415 			goto done;
1416 		}
1417 		error = in6_setrouter(ifp, (ipv6_router_mode_t)intval);
1418 		goto done;
1419 
1420 	case SIOCPROTOATTACH_IN6_32:    /* struct in6_aliasreq_32 */
1421 	case SIOCPROTOATTACH_IN6_64:    /* struct in6_aliasreq_64 */
1422 		if (!privileged) {
1423 			error = EPERM;
1424 			goto done;
1425 		}
1426 		error = in6_domifattach(ifp);
1427 		goto done;
1428 
1429 	case SIOCPROTODETACH_IN6:       /* struct in6_ifreq */
1430 		if (!privileged) {
1431 			error = EPERM;
1432 			goto done;
1433 		}
1434 		/* Cleanup interface routes and addresses */
1435 		in6_purgeif(ifp);
1436 
1437 		if ((error = proto_unplumb(PF_INET6, ifp))) {
1438 			log(LOG_ERR, "SIOCPROTODETACH_IN6: %s error=%d\n",
1439 			    if_name(ifp), error);
1440 		}
1441 		goto done;
1442 
1443 	case SIOCSNDFLUSH_IN6:          /* struct in6_ifreq */
1444 	case SIOCSPFXFLUSH_IN6:         /* struct in6_ifreq */
1445 	case SIOCSRTRFLUSH_IN6:         /* struct in6_ifreq */
1446 	case SIOCSDEFIFACE_IN6_32:      /* struct in6_ndifreq_32 */
1447 	case SIOCSDEFIFACE_IN6_64:      /* struct in6_ndifreq_64 */
1448 	case SIOCSIFINFO_FLAGS:         /* struct in6_ndireq */
1449 	case SIOCGIFCGAPREP_IN6_32:     /* struct in6_cgareq_32 */
1450 	case SIOCGIFCGAPREP_IN6_64:     /* struct in6_cgareq_64 */
1451 	case SIOCSIFCGAPREP_IN6_32:     /* struct in6_cgareq_32 */
1452 	case SIOCSIFCGAPREP_IN6_64:     /* struct in6_cgareq_32 */
1453 		if (!privileged) {
1454 			error = EPERM;
1455 			goto done;
1456 		}
1457 		OS_FALLTHROUGH;
1458 	case OSIOCGIFINFO_IN6:          /* struct in6_ondireq */
1459 	case SIOCGIFINFO_IN6:           /* struct in6_ondireq */
1460 	case SIOCGDRLST_IN6_32:         /* struct in6_drlist_32 */
1461 	case SIOCGDRLST_IN6_64:         /* struct in6_drlist_64 */
1462 	case SIOCGPRLST_IN6_32:         /* struct in6_prlist_32 */
1463 	case SIOCGPRLST_IN6_64:         /* struct in6_prlist_64 */
1464 	case SIOCGNBRINFO_IN6_32:       /* struct in6_nbrinfo_32 */
1465 	case SIOCGNBRINFO_IN6_64:       /* struct in6_nbrinfo_64 */
1466 	case SIOCGDEFIFACE_IN6_32:      /* struct in6_ndifreq_32 */
1467 	case SIOCGDEFIFACE_IN6_64:      /* struct in6_ndifreq_64 */
1468 		error = nd6_ioctl(cmd, data, ifp);
1469 		goto done;
1470 
1471 	case SIOCSIFPREFIX_IN6:         /* struct in6_prefixreq (deprecated) */
1472 	case SIOCDIFPREFIX_IN6:         /* struct in6_prefixreq (deprecated) */
1473 	case SIOCAIFPREFIX_IN6:         /* struct in6_rrenumreq (deprecated) */
1474 	case SIOCCIFPREFIX_IN6:         /* struct in6_rrenumreq (deprecated) */
1475 	case SIOCSGIFPREFIX_IN6:        /* struct in6_rrenumreq (deprecated) */
1476 	case SIOCGIFPREFIX_IN6:         /* struct in6_prefixreq (deprecated) */
1477 		log(LOG_NOTICE,
1478 		    "prefix ioctls are now invalidated. "
1479 		    "please use ifconfig.\n");
1480 		error = EOPNOTSUPP;
1481 		goto done;
1482 
1483 	case SIOCSSCOPE6:               /* struct in6_ifreq (deprecated) */
1484 	case SIOCGSCOPE6:               /* struct in6_ifreq (deprecated) */
1485 	case SIOCGSCOPE6DEF:            /* struct in6_ifreq (deprecated) */
1486 		error = EOPNOTSUPP;
1487 		goto done;
1488 
1489 	case SIOCLL_CGASTART_32:        /* struct in6_cgareq_32 */
1490 	case SIOCLL_CGASTART_64:        /* struct in6_cgareq_64 */
1491 		if (!privileged) {
1492 			error = EPERM;
1493 		} else {
1494 			error = in6ctl_cgastart(ifp, cmd, data);
1495 		}
1496 		goto done;
1497 
1498 	case SIOCGIFSTAT_IN6:           /* struct in6_ifreq */
1499 	case SIOCGIFSTAT_ICMP6:         /* struct in6_ifreq */
1500 		error = in6ctl_gifstat(ifp, cmd, ifr);
1501 		goto done;
1502 	}
1503 
1504 	/*
1505 	 * ioctls which require interface address; obtain sockaddr_in6.
1506 	 */
1507 	switch (cmd) {
1508 	case SIOCSIFADDR_IN6:           /* struct in6_ifreq (deprecated) */
1509 	case SIOCSIFDSTADDR_IN6:        /* struct in6_ifreq (deprecated) */
1510 	case SIOCSIFNETMASK_IN6:        /* struct in6_ifreq (deprecated) */
1511 		/*
1512 		 * Since IPv6 allows a node to assign multiple addresses
1513 		 * on a single interface, SIOCSIFxxx ioctls are deprecated.
1514 		 */
1515 		/* we decided to obsolete this command (20000704) */
1516 		error = EOPNOTSUPP;
1517 		goto done;
1518 
1519 	case SIOCAIFADDR_IN6_32:        /* struct in6_aliasreq_32 */
1520 	case SIOCAIFADDR_IN6_64:        /* struct in6_aliasreq_64 */
1521 		if (!privileged) {
1522 			error = EPERM;
1523 			goto done;
1524 		}
1525 		/*
1526 		 * Convert user ifra to the kernel form, when appropriate.
1527 		 * This allows the conversion between different data models
1528 		 * to be centralized, so that it can be passed around to other
1529 		 * routines that are expecting the kernel form.
1530 		 */
1531 		ifra = in6_aliasreq_to_native(data,
1532 		    (cmd == SIOCAIFADDR_IN6_64), &sifra);
1533 		bcopy(&ifra->ifra_addr, &sin6, sizeof(sin6));
1534 		sa6 = &sin6;
1535 		break;
1536 
1537 	case SIOCDIFADDR_IN6:           /* struct in6_ifreq */
1538 	case SIOCSIFALIFETIME_IN6:      /* struct in6_ifreq */
1539 		if (!privileged) {
1540 			error = EPERM;
1541 			goto done;
1542 		}
1543 		OS_FALLTHROUGH;
1544 	case SIOCGIFADDR_IN6:           /* struct in6_ifreq */
1545 	case SIOCGIFDSTADDR_IN6:        /* struct in6_ifreq */
1546 	case SIOCGIFNETMASK_IN6:        /* struct in6_ifreq */
1547 	case SIOCGIFAFLAG_IN6:          /* struct in6_ifreq */
1548 	case SIOCGIFALIFETIME_IN6:      /* struct in6_ifreq */
1549 		bcopy(&ifr->ifr_addr, &sin6, sizeof(sin6));
1550 		sa6 = &sin6;
1551 		break;
1552 	case SIOCGIFDSTADDR:
1553 	case SIOCSIFDSTADDR:
1554 	case SIOCGIFBRDADDR:
1555 	case SIOCSIFBRDADDR:
1556 	case SIOCGIFNETMASK:
1557 	case SIOCSIFNETMASK:
1558 	case SIOCGIFADDR:
1559 	case SIOCSIFADDR:
1560 	case SIOCAIFADDR:
1561 	case SIOCDIFADDR:
1562 		/* Do not handle these AF_INET commands in AF_INET6 path */
1563 		error = EINVAL;
1564 		goto done;
1565 	}
1566 
1567 	/*
1568 	 * Find address for this interface, if it exists.
1569 	 *
1570 	 * In netinet code, we have checked ifra_addr in SIOCSIF*ADDR operation
1571 	 * only, and used the first interface address as the target of other
1572 	 * operations (without checking ifra_addr).  This was because netinet
1573 	 * code/API assumed at most 1 interface address per interface.
1574 	 * Since IPv6 allows a node to assign multiple addresses
1575 	 * on a single interface, we almost always look and check the
1576 	 * presence of ifra_addr, and reject invalid ones here.
1577 	 * It also decreases duplicated code among SIOC*_IN6 operations.
1578 	 */
1579 	VERIFY(ia == NULL);
1580 	if (sa6 != NULL && sa6->sin6_family == AF_INET6) {
1581 		if (IN6_IS_ADDR_LINKLOCAL(&sa6->sin6_addr)) {
1582 			if (in6_embedded_scope) {
1583 				if (sa6->sin6_addr.s6_addr16[1] == 0) {
1584 					/* link ID is not embedded by the user */
1585 					sa6->sin6_addr.s6_addr16[1] =
1586 					    htons(ifp->if_index);
1587 				} else if (sa6->sin6_addr.s6_addr16[1] !=
1588 				    htons(ifp->if_index)) {
1589 					error = EINVAL; /* link ID contradicts */
1590 					goto done;
1591 				}
1592 				if (sa6->sin6_scope_id) {
1593 					if (sa6->sin6_scope_id !=
1594 					    (u_int32_t)ifp->if_index) {
1595 						error = EINVAL;
1596 						goto done;
1597 					}
1598 					sa6->sin6_scope_id = 0; /* XXX: good way? */
1599 				}
1600 			} else {
1601 				if (sa6->sin6_scope_id == IFSCOPE_NONE) {
1602 					sa6->sin6_scope_id = ifp->if_index;
1603 				} else if (sa6->sin6_scope_id != ifp->if_index) {
1604 					error = EINVAL; /* link ID contradicts */
1605 					goto done;
1606 				}
1607 			}
1608 		}
1609 		/*
1610 		 * Any failures from this point on must take into account
1611 		 * a non-NULL "ia" with an outstanding reference count, and
1612 		 * therefore requires IFA_REMREF.  Jump to "done" label
1613 		 * instead of calling return if "ia" is valid.
1614 		 */
1615 		ia = in6ifa_ifpwithaddr(ifp, &sa6->sin6_addr);
1616 	}
1617 
1618 	/*
1619 	 * SIOCDIFADDR_IN6/SIOCAIFADDR_IN6 specific tests.
1620 	 */
1621 	switch (cmd) {
1622 	case SIOCDIFADDR_IN6:           /* struct in6_ifreq */
1623 		if (ia == NULL) {
1624 			error = EADDRNOTAVAIL;
1625 			goto done;
1626 		}
1627 		OS_FALLTHROUGH;
1628 	case SIOCAIFADDR_IN6_32:        /* struct in6_aliasreq_32 */
1629 	case SIOCAIFADDR_IN6_64:        /* struct in6_aliasreq_64 */
1630 		VERIFY(sa6 != NULL);
1631 		/*
1632 		 * We always require users to specify a valid IPv6 address for
1633 		 * the corresponding operation.  Use "sa6" instead of "ifra"
1634 		 * since SIOCDIFADDR_IN6 falls thru above.
1635 		 */
1636 		if (sa6->sin6_family != AF_INET6 ||
1637 		    sa6->sin6_len != sizeof(struct sockaddr_in6)) {
1638 			error = EAFNOSUPPORT;
1639 			goto done;
1640 		}
1641 
1642 		if ((cmd == SIOCAIFADDR_IN6_32 || cmd == SIOCAIFADDR_IN6_64) &&
1643 		    (IN6_IS_ADDR_UNSPECIFIED(&sa6->sin6_addr) ||
1644 		    IN6_IS_ADDR_MULTICAST(&sa6->sin6_addr) ||
1645 		    IN6_IS_ADDR_V4MAPPED(&sa6->sin6_addr) ||
1646 		    IN6_IS_ADDR_V4COMPAT(&sa6->sin6_addr))) {
1647 			error = EINVAL;
1648 			goto done;
1649 		}
1650 		break;
1651 	}
1652 
1653 	/*
1654 	 * And finally process address-related ioctls.
1655 	 */
1656 	switch (cmd) {
1657 	case SIOCGIFADDR_IN6:           /* struct in6_ifreq */
1658 	/* This interface is basically deprecated. use SIOCGIFCONF. */
1659 	/* FALLTHRU */
1660 	case SIOCGIFDSTADDR_IN6:        /* struct in6_ifreq */
1661 		error = in6ctl_gifaddr(ifp, ia, cmd, ifr);
1662 		break;
1663 
1664 	case SIOCGIFNETMASK_IN6:        /* struct in6_ifreq */
1665 		if (ia != NULL) {
1666 			IFA_LOCK(&ia->ia_ifa);
1667 			bcopy(&ia->ia_prefixmask, &ifr->ifr_addr,
1668 			    sizeof(struct sockaddr_in6));
1669 			IFA_UNLOCK(&ia->ia_ifa);
1670 		} else {
1671 			error = EADDRNOTAVAIL;
1672 		}
1673 		break;
1674 
1675 	case SIOCGIFAFLAG_IN6:          /* struct in6_ifreq */
1676 		if (ia != NULL) {
1677 			IFA_LOCK(&ia->ia_ifa);
1678 			bcopy(&ia->ia6_flags, &ifr->ifr_ifru.ifru_flags6,
1679 			    sizeof(ifr->ifr_ifru.ifru_flags6));
1680 			IFA_UNLOCK(&ia->ia_ifa);
1681 		} else {
1682 			error = EADDRNOTAVAIL;
1683 		}
1684 		break;
1685 
1686 	case SIOCGIFALIFETIME_IN6:      /* struct in6_ifreq */
1687 	case SIOCSIFALIFETIME_IN6:      /* struct in6_ifreq */
1688 		error = in6ctl_alifetime(ia, cmd, ifr, p64);
1689 		break;
1690 
1691 	case SIOCAIFADDR_IN6_32:        /* struct in6_aliasreq_32 */
1692 	case SIOCAIFADDR_IN6_64:        /* struct in6_aliasreq_64 */
1693 		error = in6ctl_aifaddr(ifp, ifra);
1694 		break;
1695 
1696 	case SIOCDIFADDR_IN6:
1697 		in6ctl_difaddr(ifp, ia);
1698 		break;
1699 
1700 	default:
1701 		error = ifnet_ioctl(ifp, PF_INET6, cmd, data);
1702 		break;
1703 	}
1704 
1705 done:
1706 	if (ifp != NULL) {
1707 		lck_mtx_lock(&ifp->if_inet6_ioctl_lock);
1708 		ifp->if_inet6_ioctl_busy = FALSE;
1709 		lck_mtx_unlock(&ifp->if_inet6_ioctl_lock);
1710 		wakeup(&ifp->if_inet6_ioctl_busy);
1711 	}
1712 
1713 	if (ia != NULL) {
1714 		IFA_REMREF(&ia->ia_ifa);
1715 	}
1716 	if (so_unlocked) {
1717 		socket_lock(so, 0);
1718 	}
1719 
1720 	return error;
1721 }
1722 
1723 static __attribute__((noinline)) int
in6ctl_aifaddr(struct ifnet * ifp,struct in6_aliasreq * ifra)1724 in6ctl_aifaddr(struct ifnet *ifp, struct in6_aliasreq *ifra)
1725 {
1726 	int i, error, addtmp;
1727 	uint8_t plen;
1728 	struct nd_prefix pr0, *pr;
1729 	struct in6_ifaddr *ia;
1730 
1731 	VERIFY(ifp != NULL && ifra != NULL);
1732 	ia = NULL;
1733 
1734 	/*
1735 	 * XXX This interface is not meant to be used for static LLA
1736 	 * configuration.
1737 	 * Instead one can use SIOCLL_START can be used to configure LLA
1738 	 * statically.
1739 	 * For bin-compat reasons though, allow it for now and only make
1740 	 * sure that scope gets communicated correctly.
1741 	 */
1742 	if (IN6_IS_ADDR_LINKLOCAL(&ifra->ifra_addr.sin6_addr)) {
1743 		if (in6_embedded_scope) {
1744 			ifra->ifra_addr.sin6_addr.s6_addr16[1] = htons(ifp->if_index);
1745 		} else {
1746 			/*
1747 			 * XXX May be we should rather also check if sin6_scope_id
1748 			 * is already set or enforce if set that it is same
1749 			 * as interface index?
1750 			 * For now to avoid any unintended consequence, just use
1751 			 * interface index and set sin6_scope_id.
1752 			 * Also should we just prohibit this interface to configure
1753 			 * additional link local and limti LLA configuration through
1754 			 * other *_start ioctls?
1755 			 */
1756 			ifra->ifra_addr.sin6_addr.s6_addr16[1] = 0;
1757 			ifra->ifra_addr.sin6_scope_id = ifp->if_index;
1758 		}
1759 	}
1760 
1761 	/* Attempt to attach the protocol, in case it isn't attached */
1762 	error = in6_domifattach(ifp);
1763 	if (error == 0) {
1764 		/* PF_INET6 wasn't previously attached */
1765 		error = in6_ifattach_aliasreq(ifp, NULL, NULL);
1766 		if (error != 0) {
1767 			goto done;
1768 		}
1769 
1770 		in6_if_up_dad_start(ifp);
1771 	} else if (error != EEXIST) {
1772 		goto done;
1773 	}
1774 
1775 	/*
1776 	 * First, make or update the interface address structure, and link it
1777 	 * to the list.
1778 	 */
1779 	error = in6_update_ifa(ifp, ifra, 0, &ia);
1780 	if (error != 0) {
1781 		goto done;
1782 	}
1783 	VERIFY(ia != NULL);
1784 
1785 	/* Now, make the prefix on-link on the interface. */
1786 	plen = (uint8_t)in6_mask2len(&ifra->ifra_prefixmask.sin6_addr, NULL);
1787 	if (plen == 128) {
1788 		goto done;
1789 	}
1790 
1791 	/*
1792 	 * NOTE: We'd rather create the prefix before the address, but we need
1793 	 * at least one address to install the corresponding interface route,
1794 	 * so we configure the address first.
1795 	 */
1796 
1797 	/*
1798 	 * Convert mask to prefix length (prefixmask has already been validated
1799 	 * in in6_update_ifa().
1800 	 */
1801 	bzero(&pr0, sizeof(pr0));
1802 	pr0.ndpr_plen = plen;
1803 	pr0.ndpr_ifp = ifp;
1804 	pr0.ndpr_prefix = ifra->ifra_addr;
1805 	pr0.ndpr_mask = ifra->ifra_prefixmask.sin6_addr;
1806 
1807 	/* apply the mask for safety. */
1808 	for (i = 0; i < 4; i++) {
1809 		pr0.ndpr_prefix.sin6_addr.s6_addr32[i] &=
1810 		    ifra->ifra_prefixmask.sin6_addr.s6_addr32[i];
1811 	}
1812 
1813 	/*
1814 	 * Since we don't have an API to set prefix (not address) lifetimes, we
1815 	 * just use the same lifetimes as addresses. The (temporarily)
1816 	 * installed lifetimes can be overridden by later advertised RAs (when
1817 	 * accept_rtadv is non 0), which is an intended behavior.
1818 	 */
1819 	pr0.ndpr_raf_onlink = 1; /* should be configurable? */
1820 	pr0.ndpr_raf_auto = !!(ifra->ifra_flags & IN6_IFF_AUTOCONF);
1821 	if (ifra->ifra_flags & (IN6_IFF_AUTOCONF | IN6_IFF_DYNAMIC)) {
1822 		pr0.ndpr_vltime = ifra->ifra_lifetime.ia6t_vltime;
1823 		pr0.ndpr_pltime = ifra->ifra_lifetime.ia6t_pltime;
1824 	} else {
1825 		pr0.ndpr_vltime = ND6_INFINITE_LIFETIME;
1826 		pr0.ndpr_pltime = ND6_INFINITE_LIFETIME;
1827 	}
1828 	pr0.ndpr_stateflags |= NDPRF_STATIC;
1829 	lck_mtx_init(&pr0.ndpr_lock, &ifa_mtx_grp, &ifa_mtx_attr);
1830 
1831 	/* add the prefix if there's none. */
1832 	if ((pr = nd6_prefix_lookup(&pr0, ND6_PREFIX_EXPIRY_NEVER)) == NULL) {
1833 		/*
1834 		 * nd6_prelist_add will install the corresponding interface
1835 		 * route.
1836 		 */
1837 		error = nd6_prelist_add(&pr0, NULL, &pr, FALSE);
1838 		if (error != 0) {
1839 			goto done;
1840 		}
1841 
1842 		if (pr == NULL) {
1843 			log(LOG_ERR, "%s: nd6_prelist_add okay, but"
1844 			    " no prefix.\n", __func__);
1845 			error = EINVAL;
1846 			goto done;
1847 		}
1848 	}
1849 
1850 	IFA_LOCK(&ia->ia_ifa);
1851 
1852 	/* if this is a new autoconfed addr */
1853 	addtmp = FALSE;
1854 	if (ia->ia6_ndpr == NULL) {
1855 		NDPR_LOCK(pr);
1856 		++pr->ndpr_addrcnt;
1857 		if (!(ia->ia6_flags & IN6_IFF_NOTMANUAL)) {
1858 			++pr->ndpr_manual_addrcnt;
1859 			VERIFY(pr->ndpr_manual_addrcnt != 0);
1860 		}
1861 		VERIFY(pr->ndpr_addrcnt != 0);
1862 		ia->ia6_ndpr = pr;
1863 		NDPR_ADDREF(pr); /* for addr reference */
1864 
1865 		/*
1866 		 * If this is the first autoconf address from the prefix,
1867 		 * create a temporary address as well (when specified).
1868 		 */
1869 		if ((ia->ia6_flags & IN6_IFF_AUTOCONF) != 0 &&
1870 		    ip6_use_tempaddr &&
1871 		    pr->ndpr_addrcnt == 1 &&
1872 		    (!IN6_IS_ADDR_UNIQUE_LOCAL(&ia->ia_addr.sin6_addr)
1873 		    || ip6_ula_use_tempaddr)) {
1874 			addtmp = true;
1875 		}
1876 		NDPR_UNLOCK(pr);
1877 	}
1878 
1879 	IFA_UNLOCK(&ia->ia_ifa);
1880 
1881 	if (addtmp) {
1882 		int e;
1883 		e = in6_tmpifadd(ia, 1);
1884 		if (e != 0) {
1885 			log(LOG_NOTICE, "%s: failed to create a"
1886 			    " temporary address, error=%d\n",
1887 			    __func__, e);
1888 		}
1889 	}
1890 
1891 	/*
1892 	 * This might affect the status of autoconfigured addresses, that is,
1893 	 * this address might make other addresses detached.
1894 	 */
1895 	lck_mtx_lock(nd6_mutex);
1896 	pfxlist_onlink_check();
1897 	lck_mtx_unlock(nd6_mutex);
1898 
1899 	/* Drop use count held above during lookup/add */
1900 	NDPR_REMREF(pr);
1901 
1902 done:
1903 	if (ia != NULL) {
1904 		IFA_REMREF(&ia->ia_ifa);
1905 	}
1906 	return error;
1907 }
1908 
1909 static __attribute__((noinline)) void
in6ctl_difaddr(struct ifnet * ifp,struct in6_ifaddr * ia)1910 in6ctl_difaddr(struct ifnet *ifp, struct in6_ifaddr *ia)
1911 {
1912 	int i = 0;
1913 	struct nd_prefix pr0, *pr;
1914 
1915 	VERIFY(ifp != NULL && ia != NULL);
1916 
1917 	/*
1918 	 * If the address being deleted is the only one that owns
1919 	 * the corresponding prefix, expire the prefix as well.
1920 	 * XXX: theoretically, we don't have to worry about such
1921 	 * relationship, since we separate the address management
1922 	 * and the prefix management.  We do this, however, to provide
1923 	 * as much backward compatibility as possible in terms of
1924 	 * the ioctl operation.
1925 	 * Note that in6_purgeaddr() will decrement ndpr_addrcnt.
1926 	 */
1927 	IFA_LOCK(&ia->ia_ifa);
1928 	bzero(&pr0, sizeof(pr0));
1929 	pr0.ndpr_ifp = ifp;
1930 	pr0.ndpr_plen = (uint8_t)in6_mask2len(&ia->ia_prefixmask.sin6_addr, NULL);
1931 	if (pr0.ndpr_plen == 128) {
1932 		IFA_UNLOCK(&ia->ia_ifa);
1933 		goto purgeaddr;
1934 	}
1935 	pr0.ndpr_prefix = ia->ia_addr;
1936 	pr0.ndpr_mask = ia->ia_prefixmask.sin6_addr;
1937 	for (i = 0; i < 4; i++) {
1938 		pr0.ndpr_prefix.sin6_addr.s6_addr32[i] &=
1939 		    ia->ia_prefixmask.sin6_addr.s6_addr32[i];
1940 	}
1941 	IFA_UNLOCK(&ia->ia_ifa);
1942 
1943 	if ((pr = nd6_prefix_lookup(&pr0, ND6_PREFIX_EXPIRY_UNSPEC)) != NULL) {
1944 		IFA_LOCK(&ia->ia_ifa);
1945 		NDPR_LOCK(pr);
1946 		if (pr->ndpr_addrcnt == 1) {
1947 			/* XXX: just for expiration */
1948 			pr->ndpr_expire = 1;
1949 		}
1950 		NDPR_UNLOCK(pr);
1951 		IFA_UNLOCK(&ia->ia_ifa);
1952 
1953 		/* Drop use count held above during lookup */
1954 		NDPR_REMREF(pr);
1955 	}
1956 
1957 purgeaddr:
1958 	in6_purgeaddr(&ia->ia_ifa);
1959 }
1960 
1961 static __attribute__((noinline)) int
in6_autoconf(struct ifnet * ifp,int enable)1962 in6_autoconf(struct ifnet *ifp, int enable)
1963 {
1964 	int error = 0;
1965 
1966 	VERIFY(ifp != NULL);
1967 
1968 	if (ifp->if_flags & IFF_LOOPBACK) {
1969 		return EINVAL;
1970 	}
1971 
1972 	if (enable) {
1973 		/*
1974 		 * An interface in IPv6 router mode implies that it
1975 		 * is either configured with a static IP address or
1976 		 * autoconfigured via a locally-generated RA.  Prevent
1977 		 * SIOCAUTOCONF_START from being set in that mode.
1978 		 */
1979 		ifnet_lock_exclusive(ifp);
1980 		if (ifp->if_ipv6_router_mode == IPV6_ROUTER_MODE_EXCLUSIVE) {
1981 			if_clear_eflags(ifp, IFEF_ACCEPT_RTADV);
1982 			error = EBUSY;
1983 		} else {
1984 			if_set_eflags(ifp, IFEF_ACCEPT_RTADV);
1985 		}
1986 		ifnet_lock_done(ifp);
1987 	} else {
1988 		struct in6_ifaddr *ia = NULL;
1989 
1990 		if_clear_eflags(ifp, IFEF_ACCEPT_RTADV);
1991 
1992 		/* Remove autoconfigured address from interface */
1993 		lck_rw_lock_exclusive(&in6_ifaddr_rwlock);
1994 		boolean_t from_begining = TRUE;
1995 		while (from_begining) {
1996 			from_begining = FALSE;
1997 			TAILQ_FOREACH(ia, &in6_ifaddrhead, ia6_link) {
1998 				if (ia->ia_ifa.ifa_ifp != ifp) {
1999 					continue;
2000 				}
2001 				IFA_LOCK(&ia->ia_ifa);
2002 				if (ia->ia6_flags & IN6_IFF_AUTOCONF) {
2003 					IFA_ADDREF_LOCKED(&ia->ia_ifa); /* for us */
2004 					IFA_UNLOCK(&ia->ia_ifa);
2005 					lck_rw_done(&in6_ifaddr_rwlock);
2006 					in6_purgeaddr(&ia->ia_ifa);
2007 					IFA_REMREF(&ia->ia_ifa);        /* for us */
2008 					lck_rw_lock_exclusive(&in6_ifaddr_rwlock);
2009 					/*
2010 					 * Purging the address caused in6_ifaddr_rwlock
2011 					 * to be dropped and reacquired;
2012 					 * therefore search again from the beginning
2013 					 * of in6_ifaddrs list.
2014 					 */
2015 					from_begining = TRUE;
2016 					break;
2017 				}
2018 				IFA_UNLOCK(&ia->ia_ifa);
2019 			}
2020 		}
2021 		lck_rw_done(&in6_ifaddr_rwlock);
2022 	}
2023 	return error;
2024 }
2025 
2026 /*
2027  * Handle SIOCSETROUTERMODE_IN6 to set the IPv6 router mode on the interface
2028  * Entering or exiting IPV6_ROUTER_MODE_EXCLUSIVE will result in the removal of
2029  * autoconfigured IPv6 addresses on the interface.
2030  */
2031 static __attribute__((noinline)) int
in6_setrouter(struct ifnet * ifp,ipv6_router_mode_t mode)2032 in6_setrouter(struct ifnet *ifp, ipv6_router_mode_t mode)
2033 {
2034 	int                     error = 0;
2035 	ipv6_router_mode_t      prev_mode;
2036 
2037 	VERIFY(ifp != NULL);
2038 
2039 	if (ifp->if_flags & IFF_LOOPBACK) {
2040 		return ENODEV;
2041 	}
2042 
2043 	prev_mode = ifp->if_ipv6_router_mode;
2044 	if (prev_mode == mode) {
2045 		/* no mode change, there's nothing to do */
2046 		return 0;
2047 	}
2048 	if (mode == IPV6_ROUTER_MODE_EXCLUSIVE) {
2049 		struct nd_ifinfo *ndi = NULL;
2050 
2051 		ndi = ND_IFINFO(ifp);
2052 		if (ndi != NULL && ndi->initialized) {
2053 			lck_mtx_lock(&ndi->lock);
2054 			if (ndi->flags & ND6_IFF_PROXY_PREFIXES) {
2055 				/* No proxy if we are an advertising router */
2056 				ndi->flags &= ~ND6_IFF_PROXY_PREFIXES;
2057 				lck_mtx_unlock(&ndi->lock);
2058 				(void) nd6_if_prproxy(ifp, FALSE);
2059 			} else {
2060 				lck_mtx_unlock(&ndi->lock);
2061 			}
2062 		}
2063 	}
2064 
2065 	ifp->if_ipv6_router_mode = mode;
2066 	lck_mtx_lock(nd6_mutex);
2067 	defrouter_select(ifp, NULL);
2068 	lck_mtx_unlock(nd6_mutex);
2069 	if_allmulti(ifp, (mode == IPV6_ROUTER_MODE_EXCLUSIVE));
2070 	if (mode == IPV6_ROUTER_MODE_EXCLUSIVE ||
2071 	    (prev_mode == IPV6_ROUTER_MODE_EXCLUSIVE
2072 	    && mode == IPV6_ROUTER_MODE_DISABLED)) {
2073 		error = in6_autoconf(ifp, FALSE);
2074 	}
2075 	return error;
2076 }
2077 
2078 static int
in6_to_kamescope(struct sockaddr_in6 * sin6,struct ifnet * ifp)2079 in6_to_kamescope(struct sockaddr_in6 *sin6, struct ifnet *ifp)
2080 {
2081 	struct sockaddr_in6 tmp;
2082 	int error, id;
2083 
2084 	VERIFY(sin6 != NULL);
2085 	tmp = *sin6;
2086 
2087 	error = in6_recoverscope(&tmp, &sin6->sin6_addr, ifp);
2088 	if (error != 0) {
2089 		return error;
2090 	}
2091 
2092 	id = in6_addr2scopeid(ifp, &tmp.sin6_addr);
2093 	if (tmp.sin6_scope_id == 0) {
2094 		tmp.sin6_scope_id = id;
2095 	} else if (tmp.sin6_scope_id != id) {
2096 		return EINVAL; /* scope ID mismatch. */
2097 	}
2098 	error = in6_embedscope(&tmp.sin6_addr, &tmp, NULL, NULL, NULL, IN6_NULL_IF_EMBEDDED_SCOPE(&tmp.sin6_scope_id));
2099 	if (error != 0) {
2100 		return error;
2101 	}
2102 
2103 	if (in6_embedded_scope || !IN6_IS_SCOPE_EMBED(&tmp.sin6_addr)) {
2104 		tmp.sin6_scope_id = 0;
2105 	}
2106 	*sin6 = tmp;
2107 	return 0;
2108 }
2109 
2110 /*
2111  * When the address is being configured we should clear out certain flags
2112  * coming in from the caller.
2113  */
2114 #define IN6_IFF_CLR_ADDR_FLAG_MASK      (~(IN6_IFF_DEPRECATED | IN6_IFF_DETACHED | IN6_IFF_DUPLICATED))
2115 
2116 static int
in6_ifaupdate_aux(struct in6_ifaddr * ia,struct ifnet * ifp,int ifaupflags)2117 in6_ifaupdate_aux(struct in6_ifaddr *ia, struct ifnet *ifp, int ifaupflags)
2118 {
2119 	struct sockaddr_in6 mltaddr, mltmask;
2120 	struct in6_addr llsol;
2121 	struct ifaddr *ifa;
2122 	struct in6_multi *in6m_sol;
2123 	struct in6_multi_mship *imm;
2124 	struct rtentry *rt;
2125 	int delay, error = 0;
2126 
2127 	VERIFY(ifp != NULL && ia != NULL);
2128 	ifa = &ia->ia_ifa;
2129 	in6m_sol = NULL;
2130 
2131 	nd6log2(debug, "%s - %s ifp %s ia6_flags 0x%x ifaupflags 0x%x\n",
2132 	    __func__,
2133 	    ip6_sprintf(&ia->ia_addr.sin6_addr),
2134 	    if_name(ia->ia_ifp),
2135 	    ia->ia6_flags,
2136 	    ifaupflags);
2137 
2138 	/*
2139 	 * Just to be safe, always clear certain flags when address
2140 	 * is being configured
2141 	 */
2142 	ia->ia6_flags &= IN6_IFF_CLR_ADDR_FLAG_MASK;
2143 
2144 	/*
2145 	 * Mark the address as tentative before joining multicast addresses,
2146 	 * so that corresponding MLD responses would not have a tentative
2147 	 * source address.
2148 	 */
2149 	if (in6if_do_dad(ifp)) {
2150 		in6_ifaddr_set_dadprogress(ia);
2151 		/*
2152 		 * Do not delay sending neighbor solicitations when using optimistic
2153 		 * duplicate address detection, c.f. RFC 4429.
2154 		 */
2155 		if (ia->ia6_flags & IN6_IFF_OPTIMISTIC) {
2156 			ifaupflags &= ~IN6_IFAUPDATE_DADDELAY;
2157 		} else {
2158 			ifaupflags |= IN6_IFAUPDATE_DADDELAY;
2159 		}
2160 	} else {
2161 		/*
2162 		 * If the interface has been marked to not perform
2163 		 * DAD, make sure to reset DAD in progress flags
2164 		 * that may come in from the caller.
2165 		 */
2166 		ia->ia6_flags &= ~IN6_IFF_DADPROGRESS;
2167 	}
2168 
2169 	/* Join necessary multicast groups */
2170 	if ((ifp->if_flags & IFF_MULTICAST) != 0) {
2171 		/* join solicited multicast addr for new host id */
2172 		bzero(&llsol, sizeof(struct in6_addr));
2173 		llsol.s6_addr32[0] = IPV6_ADDR_INT32_MLL;
2174 		llsol.s6_addr32[1] = 0;
2175 		llsol.s6_addr32[2] = htonl(1);
2176 		llsol.s6_addr32[3] = ia->ia_addr.sin6_addr.s6_addr32[3];
2177 		llsol.s6_addr8[12] = 0xff;
2178 		if ((error = in6_setscope(&llsol, ifp, NULL)) != 0) {
2179 			/* XXX: should not happen */
2180 			log(LOG_ERR, "%s: in6_setscope failed\n", __func__);
2181 			goto unwind;
2182 		}
2183 		delay = 0;
2184 		if ((ifaupflags & IN6_IFAUPDATE_DADDELAY)) {
2185 			/*
2186 			 * We need a random delay for DAD on the address
2187 			 * being configured.  It also means delaying
2188 			 * transmission of the corresponding MLD report to
2189 			 * avoid report collision. [RFC 4862]
2190 			 */
2191 			delay = random() % MAX_RTR_SOLICITATION_DELAY;
2192 		}
2193 		imm = in6_joingroup(ifp, &llsol, &error, delay);
2194 		if (imm == NULL) {
2195 			nd6log(info,
2196 			    "%s: addmulti failed for %s on %s (errno=%d)\n",
2197 			    __func__, ip6_sprintf(&llsol), if_name(ifp),
2198 			    error);
2199 			VERIFY(error != 0);
2200 			goto unwind;
2201 		}
2202 		in6m_sol = imm->i6mm_maddr;
2203 		/* take a refcount for this routine */
2204 		IN6M_ADDREF(in6m_sol);
2205 
2206 		IFA_LOCK_SPIN(ifa);
2207 		LIST_INSERT_HEAD(&ia->ia6_memberships, imm, i6mm_chain);
2208 		IFA_UNLOCK(ifa);
2209 
2210 		bzero(&mltmask, sizeof(mltmask));
2211 		mltmask.sin6_len = sizeof(struct sockaddr_in6);
2212 		mltmask.sin6_family = AF_INET6;
2213 		mltmask.sin6_addr = in6mask32;
2214 #define MLTMASK_LEN  4  /* mltmask's masklen (=32bit=4octet) */
2215 
2216 		/*
2217 		 * join link-local all-nodes address
2218 		 */
2219 		bzero(&mltaddr, sizeof(mltaddr));
2220 		mltaddr.sin6_len = sizeof(struct sockaddr_in6);
2221 		mltaddr.sin6_family = AF_INET6;
2222 		mltaddr.sin6_addr = in6addr_linklocal_allnodes;
2223 		if ((error = in6_setscope(&mltaddr.sin6_addr, ifp, IN6_NULL_IF_EMBEDDED_SCOPE(&mltaddr.sin6_scope_id))) != 0) {
2224 			goto unwind; /* XXX: should not fail */
2225 		}
2226 		/*
2227 		 * XXX: do we really need this automatic routes?
2228 		 * We should probably reconsider this stuff.  Most applications
2229 		 * actually do not need the routes, since they usually specify
2230 		 * the outgoing interface.
2231 		 */
2232 		rt = rtalloc1_scoped((struct sockaddr *)&mltaddr, 0, 0UL,
2233 		    ia->ia_ifp->if_index);
2234 		if (rt) {
2235 			if (memcmp(&mltaddr.sin6_addr, &((struct sockaddr_in6 *)
2236 			    (void *)rt_key(rt))->sin6_addr, MLTMASK_LEN)) {
2237 				rtfree(rt);
2238 				rt = NULL;
2239 			}
2240 		}
2241 		if (!rt) {
2242 			error = rtrequest_scoped(RTM_ADD,
2243 			    (struct sockaddr *)&mltaddr,
2244 			    (struct sockaddr *)&ia->ia_addr,
2245 			    (struct sockaddr *)&mltmask, RTF_UP | RTF_CLONING,
2246 			    NULL, ia->ia_ifp->if_index);
2247 			if (error) {
2248 				goto unwind;
2249 			}
2250 		} else {
2251 			rtfree(rt);
2252 		}
2253 
2254 		imm = in6_joingroup(ifp, &mltaddr.sin6_addr, &error, 0);
2255 		if (!imm) {
2256 			nd6log(info,
2257 			    "%s: addmulti failed for %s on %s (errno=%d)\n",
2258 			    __func__, ip6_sprintf(&mltaddr.sin6_addr),
2259 			    if_name(ifp), error);
2260 			VERIFY(error != 0);
2261 			goto unwind;
2262 		}
2263 		IFA_LOCK_SPIN(ifa);
2264 		LIST_INSERT_HEAD(&ia->ia6_memberships, imm, i6mm_chain);
2265 		IFA_UNLOCK(ifa);
2266 
2267 		/*
2268 		 * join node information group address
2269 		 */
2270 #define hostnamelen     strlen(hostname)
2271 		delay = 0;
2272 		if ((ifaupflags & IN6_IFAUPDATE_DADDELAY)) {
2273 			/*
2274 			 * The spec doesn't say anything about delay for this
2275 			 * group, but the same logic should apply.
2276 			 */
2277 			delay = random() % MAX_RTR_SOLICITATION_DELAY;
2278 		}
2279 		lck_mtx_lock(&hostname_lock);
2280 		int n = in6_nigroup(ifp, hostname, hostnamelen, &mltaddr.sin6_addr, IN6_NULL_IF_EMBEDDED_SCOPE(&mltaddr.sin6_scope_id));
2281 		lck_mtx_unlock(&hostname_lock);
2282 		if (n == 0) {
2283 			imm = in6_joingroup(ifp, &mltaddr.sin6_addr, &error,
2284 			    delay); /* XXX jinmei */
2285 			if (!imm) {
2286 				nd6log(info,
2287 				    "%s: addmulti failed for %s on %s "
2288 				    "(errno=%d)\n",
2289 				    __func__, ip6_sprintf(&mltaddr.sin6_addr),
2290 				    if_name(ifp), error);
2291 				/* XXX not very fatal, go on... */
2292 				error = 0;
2293 			} else {
2294 				IFA_LOCK_SPIN(ifa);
2295 				LIST_INSERT_HEAD(&ia->ia6_memberships,
2296 				    imm, i6mm_chain);
2297 				IFA_UNLOCK(ifa);
2298 			}
2299 		}
2300 #undef hostnamelen
2301 
2302 		/*
2303 		 * join interface-local all-nodes address.
2304 		 * (ff01::1%ifN, and ff01::%ifN/32)
2305 		 */
2306 		mltaddr.sin6_addr = in6addr_nodelocal_allnodes;
2307 		if ((error = in6_setscope(&mltaddr.sin6_addr, ifp, IN6_NULL_IF_EMBEDDED_SCOPE(&mltaddr.sin6_scope_id))) != 0) {
2308 			goto unwind; /* XXX: should not fail */
2309 		}
2310 		/* XXX: again, do we really need the route? */
2311 		rt = rtalloc1_scoped((struct sockaddr *)&mltaddr, 0, 0UL,
2312 		    ia->ia_ifp->if_index);
2313 		if (rt) {
2314 			if (memcmp(&mltaddr.sin6_addr, &((struct sockaddr_in6 *)
2315 			    (void *)rt_key(rt))->sin6_addr, MLTMASK_LEN)) {
2316 				rtfree(rt);
2317 				rt = NULL;
2318 			}
2319 		}
2320 		if (!rt) {
2321 			error = rtrequest_scoped(RTM_ADD,
2322 			    (struct sockaddr *)&mltaddr,
2323 			    (struct sockaddr *)&ia->ia_addr,
2324 			    (struct sockaddr *)&mltmask, RTF_UP | RTF_CLONING,
2325 			    NULL, ia->ia_ifp->if_index);
2326 			if (error) {
2327 				goto unwind;
2328 			}
2329 		} else {
2330 			rtfree(rt);
2331 		}
2332 
2333 		imm = in6_joingroup(ifp, &mltaddr.sin6_addr, &error, 0);
2334 		if (!imm) {
2335 			nd6log(info,
2336 			    "%s: addmulti failed for %s on %s (errno=%d)\n",
2337 			    __func__, ip6_sprintf(&mltaddr.sin6_addr),
2338 			    if_name(ifp), error);
2339 			VERIFY(error != 0);
2340 			goto unwind;
2341 		}
2342 		IFA_LOCK(ifa);
2343 		LIST_INSERT_HEAD(&ia->ia6_memberships, imm, i6mm_chain);
2344 		IFA_UNLOCK(ifa);
2345 #undef  MLTMASK_LEN
2346 
2347 		/*
2348 		 * create a ff00::/8 route
2349 		 */
2350 		bzero(&mltmask, sizeof(mltmask));
2351 		mltmask.sin6_len = sizeof(struct sockaddr_in6);
2352 		mltmask.sin6_family = AF_INET6;
2353 		mltmask.sin6_addr = in6mask8;
2354 #define MLTMASK_LEN_8_BITS  1  /* ff00::/8 mltmask's masklen (=8bit=1octet) */
2355 
2356 		bzero(&mltaddr, sizeof(mltaddr));
2357 		mltaddr.sin6_len = sizeof(struct sockaddr_in6);
2358 		mltaddr.sin6_family = AF_INET6;
2359 		mltaddr.sin6_addr = in6addr_multicast_prefix;
2360 
2361 		rt = rtalloc1_scoped((struct sockaddr *)&mltaddr, 0, 0UL,
2362 		    ia->ia_ifp->if_index);
2363 		if (rt) {
2364 			if (memcmp(&mltaddr.sin6_addr, &((struct sockaddr_in6 *)
2365 			    (void *)rt_key(rt))->sin6_addr, MLTMASK_LEN_8_BITS)) {
2366 				rtfree(rt);
2367 				rt = NULL;
2368 			}
2369 		}
2370 		if (!rt) {
2371 			error = rtrequest_scoped(RTM_ADD,
2372 			    (struct sockaddr *)&mltaddr,
2373 			    (struct sockaddr *)&ia->ia_addr,
2374 			    (struct sockaddr *)&mltmask, RTF_UP | RTF_CLONING,
2375 			    NULL, ia->ia_ifp->if_index);
2376 			if (error) {
2377 				goto unwind;
2378 			}
2379 		} else {
2380 			rtfree(rt);
2381 		}
2382 	}
2383 #undef  MLTMASK_LEN_8_BITS
2384 
2385 	/* Ensure nd6_service() is scheduled as soon as it's convenient */
2386 	++nd6_sched_timeout_want;
2387 
2388 	/*
2389 	 * Perform DAD, if:
2390 	 * * Interface is marked to perform DAD, AND
2391 	 * * Address is not marked to skip DAD, AND
2392 	 * * Address is in a pre-DAD state (Tentative or Optimistic)
2393 	 */
2394 	IFA_LOCK_SPIN(ifa);
2395 	if (in6if_do_dad(ifp) && (ia->ia6_flags & IN6_IFF_NODAD) == 0 &&
2396 	    (ia->ia6_flags & IN6_IFF_DADPROGRESS) != 0) {
2397 		int mindelay, maxdelay;
2398 		int *delayptr, delayval;
2399 
2400 		IFA_UNLOCK(ifa);
2401 		delayptr = NULL;
2402 		/*
2403 		 * Avoid the DAD delay if the caller wants us to skip it.
2404 		 * This is not compliant with RFC 2461, but it's only being
2405 		 * used for signalling and not for actual DAD.
2406 		 */
2407 		if ((ifaupflags & IN6_IFAUPDATE_DADDELAY) &&
2408 		    !(ia->ia6_flags & IN6_IFF_SWIFTDAD)) {
2409 			/*
2410 			 * We need to impose a delay before sending an NS
2411 			 * for DAD.  Check if we also needed a delay for the
2412 			 * corresponding MLD message.  If we did, the delay
2413 			 * should be larger than the MLD delay (this could be
2414 			 * relaxed a bit, but this simple logic is at least
2415 			 * safe).
2416 			 */
2417 			mindelay = 0;
2418 			if (in6m_sol != NULL) {
2419 				IN6M_LOCK(in6m_sol);
2420 				if (in6m_sol->in6m_state ==
2421 				    MLD_REPORTING_MEMBER) {
2422 					mindelay = in6m_sol->in6m_timer;
2423 				}
2424 				IN6M_UNLOCK(in6m_sol);
2425 			}
2426 			maxdelay = MAX_RTR_SOLICITATION_DELAY * hz;
2427 			if (maxdelay - mindelay == 0) {
2428 				delayval = 0;
2429 			} else {
2430 				delayval =
2431 				    (random() % (maxdelay - mindelay)) +
2432 				    mindelay;
2433 			}
2434 			delayptr = &delayval;
2435 		}
2436 
2437 		nd6_dad_start((struct ifaddr *)ia, delayptr);
2438 	} else {
2439 		IFA_UNLOCK(ifa);
2440 	}
2441 
2442 	goto done;
2443 
2444 unwind:
2445 	VERIFY(error != 0);
2446 	in6_purgeaddr(&ia->ia_ifa);
2447 
2448 done:
2449 	/* release reference held for this routine */
2450 	if (in6m_sol != NULL) {
2451 		IN6M_REMREF(in6m_sol);
2452 	}
2453 	return error;
2454 }
2455 
2456 /*
2457  * Request an IPv6 interface address.  If the address is new, then it will be
2458  * constructed and appended to the interface address chains.  The interface
2459  * address structure is optionally returned with a reference for the caller.
2460  */
2461 int
in6_update_ifa(struct ifnet * ifp,struct in6_aliasreq * ifra,int ifaupflags,struct in6_ifaddr ** iar)2462 in6_update_ifa(struct ifnet *ifp, struct in6_aliasreq *ifra, int ifaupflags,
2463     struct in6_ifaddr **iar)
2464 {
2465 	struct in6_addrlifetime ia6_lt;
2466 	struct in6_ifaddr *ia;
2467 	struct ifaddr *ifa;
2468 	struct ifaddr *xifa;
2469 	struct in6_addrlifetime *lt;
2470 	uint64_t timenow;
2471 	int plen, error;
2472 
2473 	/* Sanity check parameters and initialize locals */
2474 	VERIFY(ifp != NULL && ifra != NULL && iar != NULL);
2475 	ia = NULL;
2476 	ifa = NULL;
2477 	error = 0;
2478 
2479 	/*
2480 	 * We always require users to specify a valid IPv6 address for
2481 	 * the corresponding operation.
2482 	 */
2483 	if (ifra->ifra_addr.sin6_family != AF_INET6 ||
2484 	    ifra->ifra_addr.sin6_len != sizeof(struct sockaddr_in6)) {
2485 		error = EAFNOSUPPORT;
2486 		goto unwind;
2487 	}
2488 
2489 	/* Validate ifra_prefixmask.sin6_len is properly bounded. */
2490 	if (ifra->ifra_prefixmask.sin6_len == 0 ||
2491 	    ifra->ifra_prefixmask.sin6_len > sizeof(struct sockaddr_in6)) {
2492 		error = EINVAL;
2493 		goto unwind;
2494 	}
2495 
2496 	/* Validate prefix length extracted from ifra_prefixmask structure. */
2497 	plen = (uint8_t)in6_mask2len(&ifra->ifra_prefixmask.sin6_addr,
2498 	    (u_char *)&ifra->ifra_prefixmask + ifra->ifra_prefixmask.sin6_len);
2499 	if (plen <= 0) {
2500 		error = EINVAL;
2501 		goto unwind;
2502 	}
2503 
2504 	/* Validate lifetimes */
2505 	lt = &ifra->ifra_lifetime;
2506 	if (lt->ia6t_pltime > lt->ia6t_vltime) {
2507 		log(LOG_INFO,
2508 		    "%s: pltime 0x%x > vltime 0x%x for %s\n", __func__,
2509 		    lt->ia6t_pltime, lt->ia6t_vltime,
2510 		    ip6_sprintf(&ifra->ifra_addr.sin6_addr));
2511 		error = EINVAL;
2512 		goto unwind;
2513 	}
2514 	if (lt->ia6t_vltime == 0) {
2515 		/*
2516 		 * the following log might be noisy, but this is a typical
2517 		 * configuration mistake or a tool's bug.
2518 		 */
2519 		log(LOG_INFO, "%s: valid lifetime is 0 for %s\n", __func__,
2520 		    ip6_sprintf(&ifra->ifra_addr.sin6_addr));
2521 	}
2522 
2523 	/*
2524 	 * Before we lock the ifnet structure, we first check to see if the
2525 	 * address already exists. If so, then we don't allocate and link a
2526 	 * new one here.
2527 	 */
2528 	struct sockaddr_in6 lookup_address = ifra->ifra_addr;
2529 	if (IN6_IS_ADDR_LINKLOCAL(&lookup_address.sin6_addr)) {
2530 		if (in6_embedded_scope) {
2531 			if (lookup_address.sin6_addr.s6_addr16[1] == 0) {
2532 				/* link ID is not embedded by the user */
2533 				lookup_address.sin6_addr.s6_addr16[1] =
2534 				    htons(ifp->if_index);
2535 			} else if (lookup_address.sin6_addr.s6_addr16[1] !=
2536 			    htons(ifp->if_index)) {
2537 				error = EINVAL; /* link ID contradicts */
2538 				goto done;
2539 			}
2540 		} else {
2541 			if (lookup_address.sin6_scope_id == IFSCOPE_NONE) {
2542 				lookup_address.sin6_scope_id = ifp->if_index;
2543 			}
2544 		}
2545 		if (lookup_address.sin6_scope_id != 0 &&
2546 		    lookup_address.sin6_scope_id !=
2547 		    (u_int32_t)ifp->if_index) {
2548 			error = EINVAL;
2549 			goto done;
2550 		}
2551 	}
2552 
2553 	ia = in6ifa_ifpwithaddr(ifp, &lookup_address.sin6_addr);
2554 	if (ia != NULL) {
2555 		ifa = &ia->ia_ifa;
2556 	}
2557 
2558 	/*
2559 	 * Validate destination address on interface types that require it.
2560 	 */
2561 	if ((ifp->if_flags & (IFF_LOOPBACK | IFF_POINTOPOINT)) != 0) {
2562 		switch (ifra->ifra_dstaddr.sin6_family) {
2563 		case AF_INET6:
2564 			if (plen != 128) {
2565 				/* noisy message for diagnostic purposes */
2566 				log(LOG_INFO,
2567 				    "%s: prefix length < 128 with"
2568 				    " explicit dstaddr.\n", __func__);
2569 				error = EINVAL;
2570 				goto unwind;
2571 			}
2572 			break;
2573 
2574 		case AF_UNSPEC:
2575 			break;
2576 
2577 		default:
2578 			error = EAFNOSUPPORT;
2579 			goto unwind;
2580 		}
2581 	} else if (ifra->ifra_dstaddr.sin6_family != AF_UNSPEC) {
2582 		log(LOG_INFO,
2583 		    "%s: dstaddr valid only on p2p and loopback interfaces.\n",
2584 		    __func__);
2585 		error = EINVAL;
2586 		goto unwind;
2587 	}
2588 
2589 	timenow = net_uptime();
2590 
2591 	if (ia == NULL) {
2592 		zalloc_flags_t how;
2593 
2594 		/* Is this the first new IPv6 address for the interface? */
2595 		ifaupflags |= IN6_IFAUPDATE_NEWADDR;
2596 
2597 		/* Allocate memory for IPv6 interface address structure. */
2598 		how = (ifaupflags & IN6_IFAUPDATE_NOWAIT) ? Z_NOWAIT : Z_WAITOK;
2599 		ia = in6_ifaddr_alloc(how);
2600 		if (ia == NULL) {
2601 			error = ENOBUFS;
2602 			goto unwind;
2603 		}
2604 
2605 		ifa = &ia->ia_ifa;
2606 
2607 		/*
2608 		 * Initialize interface address structure.
2609 		 *
2610 		 * Note well: none of these sockaddr_in6 structures contain a
2611 		 * valid sin6_port, sin6_flowinfo or even a sin6_scope_id field.
2612 		 * We still embed link-local scope identifiers at the end of an
2613 		 * arbitrary fe80::/32 prefix, for historical reasons. Also, the
2614 		 * ifa_dstaddr field is always non-NULL on point-to-point and
2615 		 * loopback interfaces, and conventionally points to a socket
2616 		 * address of AF_UNSPEC family when there is no destination.
2617 		 *
2618 		 * Please enjoy the dancing sea turtle.
2619 		 */
2620 		IFA_ADDREF(ifa); /* for this and optionally for caller */
2621 		IA6_HASH_INIT(ia);
2622 		ifa->ifa_addr = (struct sockaddr *)&ia->ia_addr;
2623 		if (ifra->ifra_dstaddr.sin6_family == AF_INET6 ||
2624 		    (ifp->if_flags & (IFF_POINTOPOINT | IFF_LOOPBACK)) != 0) {
2625 			ifa->ifa_dstaddr = (struct sockaddr *)&ia->ia_dstaddr;
2626 		}
2627 		ifa->ifa_netmask = (struct sockaddr *)&ia->ia_prefixmask;
2628 		ifa->ifa_ifp = ifp;
2629 		ifa->ifa_metric = ifp->if_metric;
2630 		ifa->ifa_rtrequest = nd6_rtrequest;
2631 
2632 		LIST_INIT(&ia->ia6_memberships);
2633 		ia->ia_addr.sin6_family = AF_INET6;
2634 		ia->ia_addr.sin6_len = sizeof(ia->ia_addr);
2635 		ia->ia_addr.sin6_addr = ifra->ifra_addr.sin6_addr;
2636 		ia->ia_prefixmask.sin6_family = AF_INET6;
2637 		ia->ia_prefixmask.sin6_len = sizeof(ia->ia_prefixmask);
2638 		ia->ia_prefixmask.sin6_addr = ifra->ifra_prefixmask.sin6_addr;
2639 		error = in6_to_kamescope(&ia->ia_addr, ifp);
2640 		if (error != 0) {
2641 			goto unwind;
2642 		}
2643 		if (ifa->ifa_dstaddr != NULL) {
2644 			ia->ia_dstaddr = ifra->ifra_dstaddr;
2645 			error = in6_to_kamescope(&ia->ia_dstaddr, ifp);
2646 			if (error != 0) {
2647 				goto unwind;
2648 			}
2649 		}
2650 
2651 		/* Append to address chains */
2652 		ifnet_lock_exclusive(ifp);
2653 		ifaupflags |= IN6_IFAUPDATE_1STADDR;
2654 		TAILQ_FOREACH(xifa, &ifp->if_addrlist, ifa_list) {
2655 			IFA_LOCK_SPIN(xifa);
2656 			if (xifa->ifa_addr->sa_family != AF_INET6) {
2657 				IFA_UNLOCK(xifa);
2658 				ifaupflags &= ~IN6_IFAUPDATE_1STADDR;
2659 				break;
2660 			}
2661 			IFA_UNLOCK(xifa);
2662 		}
2663 
2664 		IFA_LOCK_SPIN(ifa);
2665 		if_attach_ifa(ifp, ifa); /* holds reference for ifnet link */
2666 		IFA_UNLOCK(ifa);
2667 		ifnet_lock_done(ifp);
2668 
2669 		lck_rw_lock_exclusive(&in6_ifaddr_rwlock);
2670 		TAILQ_INSERT_TAIL(&in6_ifaddrhead, ia, ia6_link);
2671 		IFA_ADDREF(ifa); /* hold for in6_ifaddrs link */
2672 		os_atomic_inc(&in6_ifaddrlist_genid, relaxed);
2673 		lck_rw_done(&in6_ifaddr_rwlock);
2674 	} else {
2675 		ifa = &ia->ia_ifa;
2676 		ifaupflags &= ~(IN6_IFAUPDATE_NEWADDR | IN6_IFAUPDATE_1STADDR);
2677 	}
2678 
2679 	VERIFY(ia != NULL && ifa == &ia->ia_ifa);
2680 	IFA_LOCK(ifa);
2681 
2682 	/*
2683 	 * Set lifetimes.  We do not refer to ia6t_expire and ia6t_preferred
2684 	 * to see if the address is deprecated or invalidated, but initialize
2685 	 * these members for applications.
2686 	 */
2687 	ia->ia6_updatetime = ia->ia6_createtime = timenow;
2688 	ia6_lt = *lt;
2689 	if (ia6_lt.ia6t_vltime != ND6_INFINITE_LIFETIME) {
2690 		ia6_lt.ia6t_expire = (time_t)(timenow + ia6_lt.ia6t_vltime);
2691 	} else {
2692 		ia6_lt.ia6t_expire = 0;
2693 	}
2694 	if (ia6_lt.ia6t_pltime != ND6_INFINITE_LIFETIME) {
2695 		ia6_lt.ia6t_preferred = (time_t)(timenow + ia6_lt.ia6t_pltime);
2696 	} else {
2697 		ia6_lt.ia6t_preferred = 0;
2698 	}
2699 	in6ifa_setlifetime(ia, &ia6_lt);
2700 
2701 	/*
2702 	 * Backward compatibility - if IN6_IFF_DEPRECATED is set from the
2703 	 * userland, make it deprecated.
2704 	 */
2705 	if ((ia->ia6_flags & IN6_IFF_DEPRECATED) != 0) {
2706 		ia->ia6_lifetime.ia6ti_pltime = 0;
2707 		ia->ia6_lifetime.ia6ti_preferred = timenow;
2708 	}
2709 
2710 	/*
2711 	 * Update flag or prefix length
2712 	 */
2713 	ia->ia_plen = plen;
2714 	ia->ia6_flags = ifra->ifra_flags;
2715 
2716 	/* Release locks (new address available to concurrent tasks) */
2717 	IFA_UNLOCK(ifa);
2718 
2719 	/* Further initialization of the interface address */
2720 	error = in6_ifinit(ifp, ia, ifaupflags);
2721 	if (error != 0) {
2722 		goto unwind;
2723 	}
2724 
2725 	/* Finish updating the address while other tasks are working with it */
2726 	error = in6_ifaupdate_aux(ia, ifp, ifaupflags);
2727 	if (error != 0) {
2728 		goto unwind;
2729 	}
2730 
2731 	/* Return success (optionally w/ address for caller). */
2732 	VERIFY(error == 0);
2733 	(void) ifnet_notify_address(ifp, AF_INET6);
2734 
2735 	goto done;
2736 
2737 unwind:
2738 	VERIFY(error != 0);
2739 	if (ia != NULL) {
2740 		VERIFY(ifa == &ia->ia_ifa);
2741 		IFA_REMREF(ifa);
2742 		ia = NULL;
2743 	}
2744 
2745 done:
2746 	*iar = ia;
2747 	return error;
2748 }
2749 
2750 void
in6_purgeaddr(struct ifaddr * ifa)2751 in6_purgeaddr(struct ifaddr *ifa)
2752 {
2753 	struct ifnet *ifp = ifa->ifa_ifp;
2754 	struct in6_ifaddr *ia = (struct in6_ifaddr *)ifa;
2755 	struct in6_multi_mship *imm;
2756 
2757 	LCK_MTX_ASSERT(nd6_mutex, LCK_MTX_ASSERT_NOTOWNED);
2758 
2759 	/* stop DAD processing */
2760 	nd6_dad_stop(ifa);
2761 
2762 	/*
2763 	 * delete route to the destination of the address being purged.
2764 	 * The interface must be p2p or loopback in this case.
2765 	 */
2766 	IFA_LOCK(ifa);
2767 	if ((ia->ia_flags & IFA_ROUTE) && ia->ia_plen == 128) {
2768 		int error, rtf;
2769 
2770 		IFA_UNLOCK(ifa);
2771 		rtf = (ia->ia_dstaddr.sin6_family == AF_INET6) ? RTF_HOST : 0;
2772 		error = rtinit(&(ia->ia_ifa), RTM_DELETE, rtf);
2773 		if (error != 0) {
2774 			log(LOG_ERR, "in6_purgeaddr: failed to remove "
2775 			    "a route to the p2p destination: %s on %s, "
2776 			    "errno=%d\n",
2777 			    ip6_sprintf(&ia->ia_addr.sin6_addr), if_name(ifp),
2778 			    error);
2779 			/* proceed anyway... */
2780 		}
2781 		IFA_LOCK_SPIN(ifa);
2782 		ia->ia_flags &= ~IFA_ROUTE;
2783 	}
2784 	IFA_UNLOCK(ifa);
2785 
2786 	/* Remove ownaddr's loopback rtentry, if it exists. */
2787 	in6_ifremloop(&(ia->ia_ifa));
2788 
2789 	/*
2790 	 * leave from multicast groups we have joined for the interface
2791 	 */
2792 	IFA_LOCK(ifa);
2793 	while ((imm = ia->ia6_memberships.lh_first) != NULL) {
2794 		LIST_REMOVE(imm, i6mm_chain);
2795 		IFA_UNLOCK(ifa);
2796 		in6_leavegroup(imm);
2797 		IFA_LOCK(ifa);
2798 	}
2799 	IFA_UNLOCK(ifa);
2800 
2801 	/* in6_unlink_ifa() will need exclusive access */
2802 	in6_unlink_ifa(ia, ifp);
2803 	in6_post_msg(ifp, KEV_INET6_ADDR_DELETED, ia, NULL);
2804 
2805 	(void) ifnet_notify_address(ifp, AF_INET6);
2806 }
2807 
2808 static void
in6_unlink_ifa(struct in6_ifaddr * ia,struct ifnet * ifp)2809 in6_unlink_ifa(struct in6_ifaddr *ia, struct ifnet *ifp)
2810 {
2811 	struct in6_ifaddr *nia;
2812 	struct ifaddr *ifa;
2813 	int unlinked;
2814 
2815 	LCK_MTX_ASSERT(nd6_mutex, LCK_MTX_ASSERT_NOTOWNED);
2816 
2817 	ifa = &ia->ia_ifa;
2818 	IFA_ADDREF(ifa);
2819 
2820 	ifnet_lock_exclusive(ifp);
2821 	IFA_LOCK(ifa);
2822 	if (ifa->ifa_debug & IFD_ATTACHED) {
2823 		if_detach_ifa(ifp, ifa);
2824 	}
2825 	IFA_UNLOCK(ifa);
2826 	ifnet_lock_done(ifp);
2827 
2828 	unlinked = 0;
2829 	lck_rw_lock_exclusive(&in6_ifaddr_rwlock);
2830 	TAILQ_FOREACH(nia, &in6_ifaddrhead, ia6_link) {
2831 		if (ia == nia) {
2832 			TAILQ_REMOVE(&in6_ifaddrhead, ia, ia6_link);
2833 			os_atomic_inc(&in6_ifaddrlist_genid, relaxed);
2834 			IFA_LOCK(ifa);
2835 			if (IA6_IS_HASHED(ia)) {
2836 				in6_iahash_remove(ia);
2837 			}
2838 			IFA_UNLOCK(ifa);
2839 			unlinked = 1;
2840 			break;
2841 		}
2842 	}
2843 
2844 	/*
2845 	 * When IPv6 address is being removed, release the
2846 	 * reference to the base prefix.
2847 	 * Also, since the release might, affect the status
2848 	 * of other (detached) addresses, call
2849 	 * pfxlist_onlink_check().
2850 	 */
2851 	IFA_LOCK(ifa);
2852 	/*
2853 	 * Only log the below message for addresses other than
2854 	 * link local.
2855 	 * Only one LLA (auto-configured or statically) is allowed
2856 	 * on an interface.
2857 	 * LLA prefix, while added to the prefix list, is not
2858 	 * reference countedi (as it is the only one).
2859 	 * The prefix also never expires on its own as LLAs
2860 	 * have infinite lifetime.
2861 	 *
2862 	 * For now quiece down the log message for LLAs.
2863 	 */
2864 	if (!IN6_IS_ADDR_LINKLOCAL(&ia->ia_addr.sin6_addr)) {
2865 		if (ia->ia6_ndpr == NULL) {
2866 			log(LOG_NOTICE, "in6_unlink_ifa: IPv6 address "
2867 			    "0x%llx has no prefix\n",
2868 			    (uint64_t)VM_KERNEL_ADDRPERM(ia));
2869 		} else {
2870 			struct nd_prefix *pr = ia->ia6_ndpr;
2871 
2872 			NDPR_LOCK(pr);
2873 			if (!(ia->ia6_flags & IN6_IFF_NOTMANUAL)) {
2874 				VERIFY(pr->ndpr_manual_addrcnt != 0);
2875 				pr->ndpr_manual_addrcnt--;
2876 			}
2877 			ia->ia6_flags &= ~IN6_IFF_AUTOCONF;
2878 			ia->ia6_ndpr = NULL;
2879 			VERIFY(pr->ndpr_addrcnt != 0);
2880 			pr->ndpr_addrcnt--;
2881 			if (ia->ia6_flags & IN6_IFF_CLAT46) {
2882 				pr->ndpr_stateflags &= ~NDPRF_CLAT46;
2883 			}
2884 			NDPR_UNLOCK(pr);
2885 			NDPR_REMREF(pr);        /* release addr reference */
2886 		}
2887 	}
2888 	IFA_UNLOCK(ifa);
2889 	lck_rw_done(&in6_ifaddr_rwlock);
2890 
2891 	if ((ia->ia6_flags & IN6_IFF_AUTOCONF) != 0) {
2892 		lck_mtx_lock(nd6_mutex);
2893 		pfxlist_onlink_check();
2894 		lck_mtx_unlock(nd6_mutex);
2895 	}
2896 	/*
2897 	 * release another refcnt for the link from in6_ifaddrs.
2898 	 * Do this only if it's not already unlinked in the event that we lost
2899 	 * the race, since in6_ifaddr_rwlock was momentarily dropped above.
2900 	 */
2901 	if (unlinked) {
2902 		IFA_REMREF(ifa);
2903 	}
2904 
2905 	/* release reference held for this routine */
2906 	IFA_REMREF(ifa);
2907 
2908 	/* invalidate route caches */
2909 	routegenid_inet6_update();
2910 }
2911 
2912 void
in6_purgeif(struct ifnet * ifp)2913 in6_purgeif(struct ifnet *ifp)
2914 {
2915 	struct in6_ifaddr *ia;
2916 
2917 	if (ifp == NULL) {
2918 		return;
2919 	}
2920 
2921 	LCK_MTX_ASSERT(nd6_mutex, LCK_MTX_ASSERT_NOTOWNED);
2922 
2923 	lck_rw_lock_exclusive(&in6_ifaddr_rwlock);
2924 	boolean_t from_begining = TRUE;
2925 	while (from_begining) {
2926 		from_begining = FALSE;
2927 		TAILQ_FOREACH(ia, &in6_ifaddrhead, ia6_link) {
2928 			if (ia->ia_ifa.ifa_ifp != ifp) {
2929 				continue;
2930 			}
2931 			IFA_ADDREF(&ia->ia_ifa);        /* for us */
2932 			lck_rw_done(&in6_ifaddr_rwlock);
2933 			in6_purgeaddr(&ia->ia_ifa);
2934 			IFA_REMREF(&ia->ia_ifa);        /* for us */
2935 			lck_rw_lock_exclusive(&in6_ifaddr_rwlock);
2936 			/*
2937 			 * Purging the address would have caused
2938 			 * in6_ifaddr_rwlock to be dropped and reacquired;
2939 			 * therefore search again from the beginning
2940 			 * of in6_ifaddrs list.
2941 			 */
2942 			from_begining = TRUE;
2943 			break;
2944 		}
2945 	}
2946 	lck_rw_done(&in6_ifaddr_rwlock);
2947 
2948 	in6_ifdetach(ifp);
2949 }
2950 
2951 /*
2952  * Initialize an interface's internet6 address and routing table entry.
2953  */
2954 static int
in6_ifinit(struct ifnet * ifp,struct in6_ifaddr * ia,int ifaupflags)2955 in6_ifinit(struct ifnet *ifp, struct in6_ifaddr *ia, int ifaupflags)
2956 {
2957 	int error;
2958 	struct ifaddr *ifa;
2959 
2960 	error = 0;
2961 	ifa = &ia->ia_ifa;
2962 
2963 	lck_rw_lock_exclusive(&in6_ifaddr_rwlock);
2964 	IFA_LOCK(&ia->ia_ifa);
2965 	if (IA6_IS_HASHED(ia)) {
2966 		in6_iahash_remove(ia);
2967 	}
2968 	if ((ifp->if_flags & IFF_POINTOPOINT)) {
2969 		in6_iahash_insert_ptp(ia);
2970 	} else {
2971 		in6_iahash_insert(ia);
2972 	}
2973 	IFA_UNLOCK(&ia->ia_ifa);
2974 	lck_rw_done(&in6_ifaddr_rwlock);
2975 
2976 	/*
2977 	 * NOTE: SIOCSIFADDR is defined with struct ifreq as parameter,
2978 	 * but here we are sending it down to the interface with a pointer
2979 	 * to struct ifaddr, for legacy reasons.
2980 	 */
2981 	if ((ifaupflags & IN6_IFAUPDATE_1STADDR) != 0) {
2982 		error = ifnet_ioctl(ifp, PF_INET6, SIOCSIFADDR, ia);
2983 		if (error != 0) {
2984 			if (error != EOPNOTSUPP) {
2985 				goto failed;
2986 			}
2987 			error = 0;
2988 		}
2989 	}
2990 
2991 	IFA_LOCK(ifa);
2992 
2993 	/*
2994 	 * Special case:
2995 	 * If the destination address is specified for a point-to-point
2996 	 * interface, install a route to the destination as an interface
2997 	 * direct route.
2998 	 */
2999 	if (!(ia->ia_flags & IFA_ROUTE) && ia->ia_plen == 128 &&
3000 	    ia->ia_dstaddr.sin6_family == AF_INET6) {
3001 		IFA_UNLOCK(ifa);
3002 		error = rtinit(ifa, RTM_ADD, RTF_UP | RTF_HOST);
3003 		if (error != 0) {
3004 			goto failed;
3005 		}
3006 		IFA_LOCK(ifa);
3007 		ia->ia_flags |= IFA_ROUTE;
3008 	}
3009 	IFA_LOCK_ASSERT_HELD(ifa);
3010 	if (ia->ia_plen < 128) {
3011 		/*
3012 		 * The RTF_CLONING flag is necessary for in6_is_ifloop_auto().
3013 		 */
3014 		ia->ia_flags |= RTF_CLONING;
3015 	}
3016 
3017 	IFA_UNLOCK(ifa);
3018 
3019 	/* Add ownaddr as loopback rtentry, if necessary (ex. on p2p link). */
3020 	if ((ifaupflags & IN6_IFAUPDATE_NEWADDR) != 0) {
3021 		in6_ifaddloop(ifa);
3022 	}
3023 
3024 	/* invalidate route caches */
3025 	routegenid_inet6_update();
3026 
3027 	VERIFY(error == 0);
3028 	return 0;
3029 failed:
3030 	VERIFY(error != 0);
3031 	lck_rw_lock_exclusive(&in6_ifaddr_rwlock);
3032 	IFA_LOCK(&ia->ia_ifa);
3033 	if (IA6_IS_HASHED(ia)) {
3034 		in6_iahash_remove(ia);
3035 	}
3036 	IFA_UNLOCK(&ia->ia_ifa);
3037 	lck_rw_done(&in6_ifaddr_rwlock);
3038 
3039 	return error;
3040 }
3041 
3042 void
in6_purgeaddrs(struct ifnet * ifp)3043 in6_purgeaddrs(struct ifnet *ifp)
3044 {
3045 	in6_purgeif(ifp);
3046 }
3047 
3048 /*
3049  * Find an IPv6 interface link-local address specific to an interface.
3050  */
3051 struct in6_ifaddr *
in6ifa_ifpforlinklocal(struct ifnet * ifp,int ignoreflags)3052 in6ifa_ifpforlinklocal(struct ifnet *ifp, int ignoreflags)
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_IS_ADDR_LINKLOCAL(IFA_IN6(ifa))) {
3065 			if ((((struct in6_ifaddr *)ifa)->ia6_flags &
3066 			    ignoreflags) != 0) {
3067 				IFA_UNLOCK(ifa);
3068 				continue;
3069 			}
3070 			IFA_ADDREF_LOCKED(ifa); /* for caller */
3071 			IFA_UNLOCK(ifa);
3072 			break;
3073 		}
3074 		IFA_UNLOCK(ifa);
3075 	}
3076 	ifnet_lock_done(ifp);
3077 
3078 	return (struct in6_ifaddr *)ifa;
3079 }
3080 
3081 struct in6_ifaddr *
in6ifa_ifpwithflag(struct ifnet * ifp,int flag)3082 in6ifa_ifpwithflag(struct ifnet * ifp, int flag)
3083 {
3084 	struct ifaddr *ifa;
3085 
3086 	ifnet_lock_shared(ifp);
3087 	TAILQ_FOREACH(ifa, &ifp->if_addrlist, ifa_list)
3088 	{
3089 		IFA_LOCK_SPIN(ifa);
3090 		if (ifa->ifa_addr->sa_family != AF_INET6) {
3091 			IFA_UNLOCK(ifa);
3092 			continue;
3093 		}
3094 		if ((((struct in6_ifaddr *)ifa)->ia6_flags & flag) == flag) {
3095 			IFA_ADDREF_LOCKED(ifa);
3096 			IFA_UNLOCK(ifa);
3097 			break;
3098 		}
3099 		IFA_UNLOCK(ifa);
3100 	}
3101 	ifnet_lock_done(ifp);
3102 
3103 	return (struct in6_ifaddr *)ifa;
3104 }
3105 
3106 /*
3107  * find the internet address corresponding to a given interface and address.
3108  */
3109 struct in6_ifaddr *
in6ifa_ifpwithaddr(struct ifnet * ifp,struct in6_addr * addr)3110 in6ifa_ifpwithaddr(struct ifnet *ifp, struct in6_addr *addr)
3111 {
3112 	struct ifaddr *ifa;
3113 
3114 	ifnet_lock_shared(ifp);
3115 	TAILQ_FOREACH(ifa, &ifp->if_addrlist, ifa_list)
3116 	{
3117 		IFA_LOCK_SPIN(ifa);
3118 		if (ifa->ifa_addr->sa_family != AF_INET6) {
3119 			IFA_UNLOCK(ifa);
3120 			continue;
3121 		}
3122 		if (IN6_ARE_ADDR_EQUAL(addr, IFA_IN6(ifa))) {
3123 			IFA_ADDREF_LOCKED(ifa); /* for caller */
3124 			IFA_UNLOCK(ifa);
3125 			break;
3126 		}
3127 		IFA_UNLOCK(ifa);
3128 	}
3129 	ifnet_lock_done(ifp);
3130 
3131 	return (struct in6_ifaddr *)ifa;
3132 }
3133 
3134 struct in6_ifaddr *
in6ifa_prproxyaddr(struct in6_addr * addr,uint32_t ifscope)3135 in6ifa_prproxyaddr(struct in6_addr *addr, uint32_t ifscope)
3136 {
3137 	struct in6_ifaddr *ia;
3138 
3139 	lck_rw_lock_shared(&in6_ifaddr_rwlock);
3140 	TAILQ_FOREACH(ia, IN6ADDR_HASH(addr), ia6_hash) {
3141 		IFA_LOCK(&ia->ia_ifa);
3142 		if (in6_are_addr_equal_scoped(addr, IFA_IN6(&ia->ia_ifa), ifscope, ia->ia_ifp->if_index)) {
3143 			IFA_ADDREF_LOCKED(&ia->ia_ifa); /* for caller */
3144 			IFA_UNLOCK(&ia->ia_ifa);
3145 			break;
3146 		}
3147 		IFA_UNLOCK(&ia->ia_ifa);
3148 	}
3149 	lck_rw_done(&in6_ifaddr_rwlock);
3150 
3151 	if (ia != NULL && !nd6_prproxy_ifaddr(ia)) {
3152 		IFA_REMREF(&ia->ia_ifa);
3153 		ia = NULL;
3154 	}
3155 
3156 	return ia;
3157 }
3158 
3159 void
in6ifa_getlifetime(struct in6_ifaddr * ia6,struct in6_addrlifetime * t_dst,int iscalendar)3160 in6ifa_getlifetime(struct in6_ifaddr *ia6, struct in6_addrlifetime *t_dst,
3161     int iscalendar)
3162 {
3163 	struct in6_addrlifetime_i *t_src = &ia6->ia6_lifetime;
3164 	struct timeval caltime;
3165 
3166 	t_dst->ia6t_vltime = t_src->ia6ti_vltime;
3167 	t_dst->ia6t_pltime = t_src->ia6ti_pltime;
3168 	t_dst->ia6t_expire = 0;
3169 	t_dst->ia6t_preferred = 0;
3170 
3171 	/* account for system time change */
3172 	getmicrotime(&caltime);
3173 	t_src->ia6ti_base_calendartime +=
3174 	    NET_CALCULATE_CLOCKSKEW(caltime,
3175 	    t_src->ia6ti_base_calendartime, net_uptime(),
3176 	    t_src->ia6ti_base_uptime);
3177 
3178 	if (iscalendar) {
3179 		if (t_src->ia6ti_expire != 0 &&
3180 		    t_src->ia6ti_vltime != ND6_INFINITE_LIFETIME) {
3181 			t_dst->ia6t_expire = (time_t)(t_src->ia6ti_base_calendartime +
3182 			    t_src->ia6ti_expire - t_src->ia6ti_base_uptime);
3183 		}
3184 
3185 		if (t_src->ia6ti_preferred != 0 &&
3186 		    t_src->ia6ti_pltime != ND6_INFINITE_LIFETIME) {
3187 			t_dst->ia6t_preferred = (time_t)(t_src->ia6ti_base_calendartime +
3188 			    t_src->ia6ti_preferred - t_src->ia6ti_base_uptime);
3189 		}
3190 	} else {
3191 		if (t_src->ia6ti_expire != 0 &&
3192 		    t_src->ia6ti_vltime != ND6_INFINITE_LIFETIME) {
3193 			t_dst->ia6t_expire = (time_t)t_src->ia6ti_expire;
3194 		}
3195 
3196 		if (t_src->ia6ti_preferred != 0 &&
3197 		    t_src->ia6ti_pltime != ND6_INFINITE_LIFETIME) {
3198 			t_dst->ia6t_preferred = (time_t)t_src->ia6ti_preferred;
3199 		}
3200 	}
3201 }
3202 
3203 void
in6ifa_setlifetime(struct in6_ifaddr * ia6,struct in6_addrlifetime * t_src)3204 in6ifa_setlifetime(struct in6_ifaddr *ia6, struct in6_addrlifetime *t_src)
3205 {
3206 	struct in6_addrlifetime_i *t_dst = &ia6->ia6_lifetime;
3207 	struct timeval caltime;
3208 
3209 	/* account for system time change */
3210 	getmicrotime(&caltime);
3211 	t_dst->ia6ti_base_calendartime +=
3212 	    NET_CALCULATE_CLOCKSKEW(caltime,
3213 	    t_dst->ia6ti_base_calendartime, net_uptime(),
3214 	    t_dst->ia6ti_base_uptime);
3215 
3216 	/* trust the caller for the values */
3217 	t_dst->ia6ti_expire = t_src->ia6t_expire;
3218 	t_dst->ia6ti_preferred = t_src->ia6t_preferred;
3219 	t_dst->ia6ti_vltime = t_src->ia6t_vltime;
3220 	t_dst->ia6ti_pltime = t_src->ia6t_pltime;
3221 }
3222 
3223 /*
3224  * Convert IP6 address to printable (loggable) representation.
3225  */
3226 char *
ip6_sprintf(const struct in6_addr * addr)3227 ip6_sprintf(const struct in6_addr *addr)
3228 {
3229 	static const char digits[] = "0123456789abcdef";
3230 	static int ip6round = 0;
3231 	static char ip6buf[8][48];
3232 
3233 	int i;
3234 	char *cp;
3235 	const u_short *a = (const u_short *)addr;
3236 	const u_char *d;
3237 	u_char n;
3238 	int dcolon = 0;
3239 	int zpad = 0;
3240 
3241 	ip6round = (ip6round + 1) & 7;
3242 	cp = ip6buf[ip6round];
3243 
3244 	for (i = 0; i < 8; i++) {
3245 		if (dcolon == 1) {
3246 			if (*a == 0) {
3247 				if (i == 7) {
3248 					*cp++ = ':';
3249 				}
3250 				a++;
3251 				continue;
3252 			} else {
3253 				dcolon = 2;
3254 			}
3255 		}
3256 		if (*a == 0) {
3257 			if (dcolon == 0 && *(a + 1) == 0) {
3258 				if (i == 0) {
3259 					*cp++ = ':';
3260 				}
3261 				*cp++ = ':';
3262 				dcolon = 1;
3263 			} else {
3264 				*cp++ = '0';
3265 				*cp++ = ':';
3266 			}
3267 			a++;
3268 			continue;
3269 		}
3270 		d = (const u_char *)a;
3271 		zpad = 0;
3272 		if ((n = *d >> 4) != 0) {
3273 			*cp++ = digits[n];
3274 			zpad = 1;
3275 		}
3276 		if ((n = *d++ & 0xf) != 0 || zpad) {
3277 			*cp++ = digits[n];
3278 			zpad = 1;
3279 		}
3280 		if ((n = *d >> 4) != 0 || zpad) {
3281 			*cp++ = digits[n];
3282 			zpad = 1;
3283 		}
3284 		if ((n = *d & 0xf) != 0 || zpad) {
3285 			*cp++ = digits[n];
3286 		}
3287 		*cp++ = ':';
3288 		a++;
3289 	}
3290 	*--cp = 0;
3291 	return ip6buf[ip6round];
3292 }
3293 
3294 int
in6addr_local(struct in6_addr * in6)3295 in6addr_local(struct in6_addr *in6)
3296 {
3297 	struct rtentry *rt;
3298 	struct sockaddr_in6 sin6;
3299 	int local = 0;
3300 
3301 	if (IN6_IS_ADDR_LOOPBACK(in6) || IN6_IS_SCOPE_LINKLOCAL(in6)) {
3302 		return 1;
3303 	}
3304 
3305 	sin6.sin6_family = AF_INET6;
3306 	sin6.sin6_len = sizeof(sin6);
3307 	bcopy(in6, &sin6.sin6_addr, sizeof(*in6));
3308 	rt = rtalloc1((struct sockaddr *)&sin6, 0, 0);
3309 
3310 	if (rt != NULL) {
3311 		RT_LOCK_SPIN(rt);
3312 		if (rt->rt_gateway->sa_family == AF_LINK) {
3313 			local = 1;
3314 		}
3315 		RT_UNLOCK(rt);
3316 		rtfree(rt);
3317 	} else {
3318 		local = in6_localaddr(in6);
3319 	}
3320 	return local;
3321 }
3322 
3323 int
in6_localaddr(struct in6_addr * in6)3324 in6_localaddr(struct in6_addr *in6)
3325 {
3326 	struct in6_ifaddr *ia;
3327 
3328 	if (IN6_IS_ADDR_LOOPBACK(in6) || IN6_IS_ADDR_LINKLOCAL(in6) || IN6_IS_ADDR_MC_UNICAST_BASED_LINKLOCAL(in6)) {
3329 		return 1;
3330 	}
3331 
3332 	lck_rw_lock_shared(&in6_ifaddr_rwlock);
3333 	TAILQ_FOREACH(ia, &in6_ifaddrhead, ia6_link) {
3334 		IFA_LOCK_SPIN(&ia->ia_ifa);
3335 		if (IN6_ARE_MASKED_ADDR_EQUAL(in6, &ia->ia_addr.sin6_addr,
3336 		    &ia->ia_prefixmask.sin6_addr)) {
3337 			IFA_UNLOCK(&ia->ia_ifa);
3338 			lck_rw_done(&in6_ifaddr_rwlock);
3339 			return 1;
3340 		}
3341 		IFA_UNLOCK(&ia->ia_ifa);
3342 	}
3343 	lck_rw_done(&in6_ifaddr_rwlock);
3344 	return 0;
3345 }
3346 
3347 /*
3348  * return length of part which dst and src are equal
3349  * hard coding...
3350  */
3351 int
in6_matchlen(struct in6_addr * src,struct in6_addr * dst)3352 in6_matchlen(struct in6_addr *src, struct in6_addr *dst)
3353 {
3354 	int match = 0;
3355 	u_char *s = (u_char *)src, *d = (u_char *)dst;
3356 	u_char *lim = s + 16, r;
3357 
3358 	while (s < lim) {
3359 		if ((r = (*d++ ^ *s++)) != 0) {
3360 			while (r < 128) {
3361 				match++;
3362 				r <<= 1;
3363 			}
3364 			break;
3365 		} else {
3366 			match += 8;
3367 		}
3368 	}
3369 	return match;
3370 }
3371 
3372 /* XXX: to be scope conscious */
3373 int
in6_are_prefix_equal(struct in6_addr * p1,uint32_t ifscope1,struct in6_addr * p2,uint32_t ifscope2,int len)3374 in6_are_prefix_equal(struct in6_addr *p1, uint32_t ifscope1, struct in6_addr *p2, uint32_t ifscope2, int len)
3375 {
3376 	int bytelen, bitlen;
3377 
3378 	/* sanity check */
3379 	if (0 > len || len > 128) {
3380 		log(LOG_ERR, "%s: invalid prefix length(%d)\n", __func__, len);
3381 		return 0;
3382 	}
3383 
3384 	bytelen = len / 8;
3385 	bitlen = len % 8;
3386 
3387 	if (bcmp(&p1->s6_addr, &p2->s6_addr, bytelen)) {
3388 		return 0;
3389 	}
3390 	if (bitlen != 0 &&
3391 	    p1->s6_addr[bytelen] >> (8 - bitlen) !=
3392 	    p2->s6_addr[bytelen] >> (8 - bitlen)) {
3393 		return 0;
3394 	}
3395 
3396 	if (IN6_IS_SCOPE_EMBED(p1) && !in6_embedded_scope) {
3397 		return ifscope1 == ifscope2;
3398 	}
3399 
3400 	return 1;
3401 }
3402 
3403 void
in6_prefixlen2mask(struct in6_addr * maskp,int len)3404 in6_prefixlen2mask(struct in6_addr *maskp, int len)
3405 {
3406 	u_char maskarray[8] = {0x80, 0xc0, 0xe0, 0xf0, 0xf8, 0xfc, 0xfe, 0xff};
3407 	int bytelen, bitlen, i;
3408 
3409 	/* sanity check */
3410 	if (0 > len || len > 128) {
3411 		log(LOG_ERR, "%s: invalid prefix length(%d)\n", __func__, len);
3412 		return;
3413 	}
3414 
3415 	bzero(maskp, sizeof(*maskp));
3416 	bytelen = len / 8;
3417 	bitlen = len % 8;
3418 	for (i = 0; i < bytelen; i++) {
3419 		maskp->s6_addr[i] = 0xff;
3420 	}
3421 	if (bitlen) {
3422 		maskp->s6_addr[bytelen] = maskarray[bitlen - 1];
3423 	}
3424 }
3425 
3426 /*
3427  * return the best address out of the same scope
3428  */
3429 struct in6_ifaddr *
in6_ifawithscope(struct ifnet * oifp,struct in6_addr * dst)3430 in6_ifawithscope(struct ifnet *oifp, struct in6_addr *dst)
3431 {
3432 	int dst_scope = in6_addrscope(dst), src_scope, best_scope = 0;
3433 	int blen = -1;
3434 	struct ifaddr *ifa;
3435 	struct ifnet *ifp;
3436 	struct in6_ifaddr *ifa_best = NULL;
3437 
3438 	if (oifp == NULL) {
3439 		return NULL;
3440 	}
3441 
3442 	/*
3443 	 * We search for all addresses on all interfaces from the beginning.
3444 	 * Comparing an interface with the outgoing interface will be done
3445 	 * only at the final stage of tiebreaking.
3446 	 */
3447 	ifnet_head_lock_shared();
3448 	TAILQ_FOREACH(ifp, &ifnet_head, if_list) {
3449 		/*
3450 		 * We can never take an address that breaks the scope zone
3451 		 * of the destination.
3452 		 */
3453 		if (in6_addr2scopeid(ifp, dst) != in6_addr2scopeid(oifp, dst)) {
3454 			continue;
3455 		}
3456 
3457 		ifnet_lock_shared(ifp);
3458 		TAILQ_FOREACH(ifa, &ifp->if_addrlist, ifa_list) {
3459 			int tlen = -1, dscopecmp, bscopecmp, matchcmp;
3460 
3461 			IFA_LOCK(ifa);
3462 			if (ifa->ifa_addr->sa_family != AF_INET6) {
3463 				IFA_UNLOCK(ifa);
3464 				continue;
3465 			}
3466 			src_scope = in6_addrscope(IFA_IN6(ifa));
3467 
3468 			/*
3469 			 * Don't use an address before completing DAD
3470 			 * nor a duplicated address.
3471 			 */
3472 			if (((struct in6_ifaddr *)ifa)->ia6_flags &
3473 			    (IN6_IFF_NOTREADY | IN6_IFF_CLAT46)) {
3474 				IFA_UNLOCK(ifa);
3475 				continue;
3476 			}
3477 			/* XXX: is there any case to allow anycasts? */
3478 			if (((struct in6_ifaddr *)ifa)->ia6_flags &
3479 			    IN6_IFF_ANYCAST) {
3480 				IFA_UNLOCK(ifa);
3481 				continue;
3482 			}
3483 			if (((struct in6_ifaddr *)ifa)->ia6_flags &
3484 			    IN6_IFF_DETACHED) {
3485 				IFA_UNLOCK(ifa);
3486 				continue;
3487 			}
3488 			/*
3489 			 * If this is the first address we find,
3490 			 * keep it anyway.
3491 			 */
3492 			if (ifa_best == NULL) {
3493 				goto replace;
3494 			}
3495 
3496 			/*
3497 			 * ifa_best is never NULL beyond this line except
3498 			 * within the block labeled "replace".
3499 			 */
3500 
3501 			/*
3502 			 * If ifa_best has a smaller scope than dst and
3503 			 * the current address has a larger one than
3504 			 * (or equal to) dst, always replace ifa_best.
3505 			 * Also, if the current address has a smaller scope
3506 			 * than dst, ignore it unless ifa_best also has a
3507 			 * smaller scope.
3508 			 * Consequently, after the two if-clause below,
3509 			 * the followings must be satisfied:
3510 			 * (scope(src) < scope(dst) &&
3511 			 *  scope(best) < scope(dst))
3512 			 *  OR
3513 			 * (scope(best) >= scope(dst) &&
3514 			 *  scope(src) >= scope(dst))
3515 			 */
3516 			if (IN6_ARE_SCOPE_CMP(best_scope, dst_scope) < 0 &&
3517 			    IN6_ARE_SCOPE_CMP(src_scope, dst_scope) >= 0) {
3518 				goto replace; /* (A) */
3519 			}
3520 			if (IN6_ARE_SCOPE_CMP(src_scope, dst_scope) < 0 &&
3521 			    IN6_ARE_SCOPE_CMP(best_scope, dst_scope) >= 0) {
3522 				IFA_UNLOCK(ifa);
3523 				continue; /* (B) */
3524 			}
3525 			/*
3526 			 * A deprecated address SHOULD NOT be used in new
3527 			 * communications if an alternate (non-deprecated)
3528 			 * address is available and has sufficient scope.
3529 			 * RFC 4862, Section 5.5.4.
3530 			 */
3531 			if (((struct in6_ifaddr *)ifa)->ia6_flags &
3532 			    IN6_IFF_DEPRECATED) {
3533 				/*
3534 				 * Ignore any deprecated addresses if
3535 				 * specified by configuration.
3536 				 */
3537 				if (!ip6_use_deprecated) {
3538 					IFA_UNLOCK(ifa);
3539 					continue;
3540 				}
3541 				/*
3542 				 * If we have already found a non-deprecated
3543 				 * candidate, just ignore deprecated addresses.
3544 				 */
3545 				if ((ifa_best->ia6_flags & IN6_IFF_DEPRECATED)
3546 				    == 0) {
3547 					IFA_UNLOCK(ifa);
3548 					continue;
3549 				}
3550 			}
3551 
3552 			/*
3553 			 * A non-deprecated address is always preferred
3554 			 * to a deprecated one regardless of scopes and
3555 			 * address matching (Note invariants ensured by the
3556 			 * conditions (A) and (B) above.)
3557 			 */
3558 			if ((ifa_best->ia6_flags & IN6_IFF_DEPRECATED) &&
3559 			    (((struct in6_ifaddr *)ifa)->ia6_flags &
3560 			    IN6_IFF_DEPRECATED) == 0) {
3561 				goto replace;
3562 			}
3563 
3564 			/*
3565 			 * When we use temporary addresses described in
3566 			 * RFC 4941, we prefer temporary addresses to
3567 			 * public autoconf addresses.  Again, note the
3568 			 * invariants from (A) and (B).  Also note that we
3569 			 * don't have any preference between static addresses
3570 			 * and autoconf addresses (despite of whether or not
3571 			 * the latter is temporary or public.)
3572 			 */
3573 			if (ip6_use_tempaddr) {
3574 				struct in6_ifaddr *ifat;
3575 
3576 				ifat = (struct in6_ifaddr *)ifa;
3577 				if ((ifa_best->ia6_flags &
3578 				    (IN6_IFF_AUTOCONF | IN6_IFF_TEMPORARY))
3579 				    == IN6_IFF_AUTOCONF &&
3580 				    (ifat->ia6_flags &
3581 				    (IN6_IFF_AUTOCONF | IN6_IFF_TEMPORARY))
3582 				    == (IN6_IFF_AUTOCONF | IN6_IFF_TEMPORARY)) {
3583 					goto replace;
3584 				}
3585 				if ((ifa_best->ia6_flags &
3586 				    (IN6_IFF_AUTOCONF | IN6_IFF_TEMPORARY))
3587 				    == (IN6_IFF_AUTOCONF | IN6_IFF_TEMPORARY) &&
3588 				    (ifat->ia6_flags &
3589 				    (IN6_IFF_AUTOCONF | IN6_IFF_TEMPORARY))
3590 				    == IN6_IFF_AUTOCONF) {
3591 					IFA_UNLOCK(ifa);
3592 					continue;
3593 				}
3594 			}
3595 
3596 			/*
3597 			 * At this point, we have two cases:
3598 			 * 1. we are looking at a non-deprecated address,
3599 			 *    and ifa_best is also non-deprecated.
3600 			 * 2. we are looking at a deprecated address,
3601 			 *    and ifa_best is also deprecated.
3602 			 * Also, we do not have to consider a case where
3603 			 * the scope of if_best is larger(smaller) than dst and
3604 			 * the scope of the current address is smaller(larger)
3605 			 * than dst. Such a case has already been covered.
3606 			 * Tiebreaking is done according to the following
3607 			 * items:
3608 			 * - the scope comparison between the address and
3609 			 *   dst (dscopecmp)
3610 			 * - the scope comparison between the address and
3611 			 *   ifa_best (bscopecmp)
3612 			 * - if the address match dst longer than ifa_best
3613 			 *   (matchcmp)
3614 			 * - if the address is on the outgoing I/F (outI/F)
3615 			 *
3616 			 * Roughly speaking, the selection policy is
3617 			 * - the most important item is scope. The same scope
3618 			 *   is best. Then search for a larger scope.
3619 			 *   Smaller scopes are the last resort.
3620 			 * - A deprecated address is chosen only when we have
3621 			 *   no address that has an enough scope, but is
3622 			 *   prefered to any addresses of smaller scopes
3623 			 *   (this must be already done above.)
3624 			 * - addresses on the outgoing I/F are preferred to
3625 			 *   ones on other interfaces if none of above
3626 			 *   tiebreaks.  In the table below, the column "bI"
3627 			 *   means if the best_ifa is on the outgoing
3628 			 *   interface, and the column "sI" means if the ifa
3629 			 *   is on the outgoing interface.
3630 			 * - If there is no other reasons to choose one,
3631 			 *   longest address match against dst is considered.
3632 			 *
3633 			 * The precise decision table is as follows:
3634 			 * dscopecmp bscopecmp  match   bI oI | replace?
3635 			 *   N/A       equal    N/A     Y   N |   No (1)
3636 			 *   N/A       equal    N/A     N   Y |  Yes (2)
3637 			 *   N/A       equal    larger   N/A  |  Yes (3)
3638 			 *   N/A       equal    !larger  N/A  |   No (4)
3639 			 *   larger    larger   N/A      N/A  |   No (5)
3640 			 *   larger    smaller  N/A      N/A  |  Yes (6)
3641 			 *   smaller   larger   N/A      N/A  |  Yes (7)
3642 			 *   smaller   smaller  N/A      N/A  |   No (8)
3643 			 *   equal     smaller  N/A      N/A  |  Yes (9)
3644 			 *   equal     larger   (already done at A above)
3645 			 */
3646 			dscopecmp = IN6_ARE_SCOPE_CMP(src_scope, dst_scope);
3647 			bscopecmp = IN6_ARE_SCOPE_CMP(src_scope, best_scope);
3648 
3649 			if (bscopecmp == 0) {
3650 				struct ifnet *bifp = ifa_best->ia_ifp;
3651 
3652 				if (bifp == oifp && ifp != oifp) { /* (1) */
3653 					IFA_UNLOCK(ifa);
3654 					continue;
3655 				}
3656 				if (bifp != oifp && ifp == oifp) { /* (2) */
3657 					goto replace;
3658 				}
3659 
3660 				/*
3661 				 * Both bifp and ifp are on the outgoing
3662 				 * interface, or both two are on a different
3663 				 * interface from the outgoing I/F.
3664 				 * now we need address matching against dst
3665 				 * for tiebreaking.
3666 				 */
3667 				tlen = in6_matchlen(IFA_IN6(ifa), dst);
3668 				matchcmp = tlen - blen;
3669 				if (matchcmp > 0) { /* (3) */
3670 					goto replace;
3671 				}
3672 				IFA_UNLOCK(ifa);
3673 				continue; /* (4) */
3674 			}
3675 			if (dscopecmp > 0) {
3676 				if (bscopecmp > 0) { /* (5) */
3677 					IFA_UNLOCK(ifa);
3678 					continue;
3679 				}
3680 				goto replace; /* (6) */
3681 			}
3682 			if (dscopecmp < 0) {
3683 				if (bscopecmp > 0) { /* (7) */
3684 					goto replace;
3685 				}
3686 				IFA_UNLOCK(ifa);
3687 				continue; /* (8) */
3688 			}
3689 
3690 			/* now dscopecmp must be 0 */
3691 			if (bscopecmp < 0) {
3692 				goto replace; /* (9) */
3693 			}
3694 replace:
3695 			IFA_ADDREF_LOCKED(ifa); /* for ifa_best */
3696 			blen = tlen >= 0 ? tlen :
3697 			    in6_matchlen(IFA_IN6(ifa), dst);
3698 			best_scope =
3699 			    in6_addrscope(&ifa2ia6(ifa)->ia_addr.sin6_addr);
3700 			IFA_UNLOCK(ifa);
3701 			if (ifa_best) {
3702 				IFA_REMREF(&ifa_best->ia_ifa);
3703 			}
3704 			ifa_best = (struct in6_ifaddr *)ifa;
3705 		}
3706 		ifnet_lock_done(ifp);
3707 	}
3708 	ifnet_head_done();
3709 
3710 	/* count statistics for future improvements */
3711 	if (ifa_best == NULL) {
3712 		ip6stat.ip6s_sources_none++;
3713 	} else {
3714 		IFA_LOCK_SPIN(&ifa_best->ia_ifa);
3715 		if (oifp == ifa_best->ia_ifp) {
3716 			ip6stat.ip6s_sources_sameif[best_scope]++;
3717 		} else {
3718 			ip6stat.ip6s_sources_otherif[best_scope]++;
3719 		}
3720 
3721 		if (best_scope == dst_scope) {
3722 			ip6stat.ip6s_sources_samescope[best_scope]++;
3723 		} else {
3724 			ip6stat.ip6s_sources_otherscope[best_scope]++;
3725 		}
3726 
3727 		if ((ifa_best->ia6_flags & IN6_IFF_DEPRECATED) != 0) {
3728 			ip6stat.ip6s_sources_deprecated[best_scope]++;
3729 		}
3730 		IFA_UNLOCK(&ifa_best->ia_ifa);
3731 	}
3732 
3733 	return ifa_best;
3734 }
3735 
3736 /*
3737  * return the best address out of the same scope. if no address was
3738  * found, return the first valid address from designated IF.
3739  */
3740 struct in6_ifaddr *
in6_ifawithifp(struct ifnet * ifp,struct in6_addr * dst)3741 in6_ifawithifp(struct ifnet *ifp, struct in6_addr *dst)
3742 {
3743 	int dst_scope = in6_addrscope(dst), blen = -1, tlen;
3744 	struct ifaddr *ifa;
3745 	struct in6_ifaddr *besta = NULL;
3746 	struct in6_ifaddr *dep[2];      /* last-resort: deprecated */
3747 
3748 	dep[0] = dep[1] = NULL;
3749 
3750 	/*
3751 	 * We first look for addresses in the same scope.
3752 	 * If there is one, return it.
3753 	 * If two or more, return one which matches the dst longest.
3754 	 * If none, return one of global addresses assigned other ifs.
3755 	 */
3756 	ifnet_lock_shared(ifp);
3757 	TAILQ_FOREACH(ifa, &ifp->if_addrlist, ifa_list) {
3758 		IFA_LOCK(ifa);
3759 		if (ifa->ifa_addr->sa_family != AF_INET6) {
3760 			IFA_UNLOCK(ifa);
3761 			continue;
3762 		}
3763 		if (ifa2ia6(ifa)->ia6_flags & IN6_IFF_ANYCAST) {
3764 			IFA_UNLOCK(ifa);
3765 			continue; /* XXX: is there any case to allow anycast? */
3766 		}
3767 		if (ifa2ia6(ifa)->ia6_flags & (IN6_IFF_NOTREADY | IN6_IFF_CLAT46)) {
3768 			IFA_UNLOCK(ifa);
3769 			continue; /* don't use this interface */
3770 		}
3771 		if (ifa2ia6(ifa)->ia6_flags & IN6_IFF_DETACHED) {
3772 			IFA_UNLOCK(ifa);
3773 			continue;
3774 		}
3775 		if (ifa2ia6(ifa)->ia6_flags & IN6_IFF_DEPRECATED) {
3776 			if (ip6_use_deprecated) {
3777 				IFA_ADDREF_LOCKED(ifa); /* for dep[0] */
3778 				IFA_UNLOCK(ifa);
3779 				if (dep[0] != NULL) {
3780 					IFA_REMREF(&dep[0]->ia_ifa);
3781 				}
3782 				dep[0] = (struct in6_ifaddr *)ifa;
3783 			} else {
3784 				IFA_UNLOCK(ifa);
3785 			}
3786 			continue;
3787 		}
3788 
3789 		if (dst_scope == in6_addrscope(IFA_IN6(ifa))) {
3790 			/*
3791 			 * call in6_matchlen() as few as possible
3792 			 */
3793 			if (besta) {
3794 				if (blen == -1) {
3795 					IFA_UNLOCK(ifa);
3796 					IFA_LOCK(&besta->ia_ifa);
3797 					blen = in6_matchlen(
3798 						&besta->ia_addr.sin6_addr, dst);
3799 					IFA_UNLOCK(&besta->ia_ifa);
3800 					IFA_LOCK(ifa);
3801 				}
3802 				tlen = in6_matchlen(IFA_IN6(ifa), dst);
3803 				if (tlen > blen) {
3804 					blen = tlen;
3805 					IFA_ADDREF_LOCKED(ifa); /* for besta */
3806 					IFA_UNLOCK(ifa);
3807 					IFA_REMREF(&besta->ia_ifa);
3808 					besta = (struct in6_ifaddr *)ifa;
3809 				} else {
3810 					IFA_UNLOCK(ifa);
3811 				}
3812 			} else {
3813 				besta = (struct in6_ifaddr *)ifa;
3814 				IFA_ADDREF_LOCKED(ifa); /* for besta */
3815 				IFA_UNLOCK(ifa);
3816 			}
3817 		} else {
3818 			IFA_UNLOCK(ifa);
3819 		}
3820 	}
3821 	if (besta) {
3822 		ifnet_lock_done(ifp);
3823 		if (dep[0] != NULL) {
3824 			IFA_REMREF(&dep[0]->ia_ifa);
3825 		}
3826 		return besta;
3827 	}
3828 
3829 	TAILQ_FOREACH(ifa, &ifp->if_addrlist, ifa_list) {
3830 		IFA_LOCK(ifa);
3831 		if (ifa->ifa_addr->sa_family != AF_INET6) {
3832 			IFA_UNLOCK(ifa);
3833 			continue;
3834 		}
3835 		if (ifa2ia6(ifa)->ia6_flags & IN6_IFF_ANYCAST) {
3836 			IFA_UNLOCK(ifa);
3837 			continue; /* XXX: is there any case to allow anycast? */
3838 		}
3839 		if (ifa2ia6(ifa)->ia6_flags & (IN6_IFF_NOTREADY | IN6_IFF_CLAT46)) {
3840 			IFA_UNLOCK(ifa);
3841 			continue; /* don't use this interface */
3842 		}
3843 		if (ifa2ia6(ifa)->ia6_flags & IN6_IFF_DETACHED) {
3844 			IFA_UNLOCK(ifa);
3845 			continue;
3846 		}
3847 		if (ifa2ia6(ifa)->ia6_flags & IN6_IFF_DEPRECATED) {
3848 			if (ip6_use_deprecated) {
3849 				IFA_ADDREF_LOCKED(ifa); /* for dep[1] */
3850 				IFA_UNLOCK(ifa);
3851 				if (dep[1] != NULL) {
3852 					IFA_REMREF(&dep[1]->ia_ifa);
3853 				}
3854 				dep[1] = (struct in6_ifaddr *)ifa;
3855 			} else {
3856 				IFA_UNLOCK(ifa);
3857 			}
3858 			continue;
3859 		}
3860 		IFA_ADDREF_LOCKED(ifa); /* for caller */
3861 		IFA_UNLOCK(ifa);
3862 		ifnet_lock_done(ifp);
3863 		if (dep[0] != NULL) {
3864 			IFA_REMREF(&dep[0]->ia_ifa);
3865 		}
3866 		if (dep[1] != NULL) {
3867 			IFA_REMREF(&dep[1]->ia_ifa);
3868 		}
3869 		return (struct in6_ifaddr *)ifa;
3870 	}
3871 	ifnet_lock_done(ifp);
3872 
3873 	/* use the last-resort values, that are, deprecated addresses */
3874 	if (dep[0]) {
3875 		if (dep[1] != NULL) {
3876 			IFA_REMREF(&dep[1]->ia_ifa);
3877 		}
3878 		return dep[0];
3879 	}
3880 	if (dep[1]) {
3881 		return dep[1];
3882 	}
3883 
3884 	return NULL;
3885 }
3886 
3887 /*
3888  * perform DAD when interface becomes IFF_UP.
3889  */
3890 static void
in6_if_up_dad_start(struct ifnet * ifp)3891 in6_if_up_dad_start(struct ifnet *ifp)
3892 {
3893 	struct ifaddr *ifa;
3894 	struct nd_ifinfo *ndi = NULL;
3895 
3896 	ndi = ND_IFINFO(ifp);
3897 	VERIFY((NULL != ndi) && (TRUE == ndi->initialized));
3898 	if (!(ndi->flags & ND6_IFF_DAD)) {
3899 		return;
3900 	}
3901 
3902 	/* start DAD on all the interface addresses */
3903 	ifnet_lock_exclusive(ifp);
3904 	TAILQ_FOREACH(ifa, &ifp->if_addrlist, ifa_list) {
3905 		struct in6_ifaddr *ia6;
3906 
3907 		IFA_LOCK_SPIN(ifa);
3908 		if (ifa->ifa_addr->sa_family != AF_INET6) {
3909 			IFA_UNLOCK(ifa);
3910 			continue;
3911 		}
3912 		ia6 = (struct in6_ifaddr *)ifa;
3913 		if (ia6->ia6_flags & IN6_IFF_DADPROGRESS) {
3914 			int delay = 0;  /* delay ticks before DAD output */
3915 			IFA_UNLOCK(ifa);
3916 			nd6_dad_start(ifa, &delay);
3917 		} else {
3918 			IFA_UNLOCK(ifa);
3919 		}
3920 	}
3921 	ifnet_lock_done(ifp);
3922 }
3923 
3924 int
in6if_do_dad(struct ifnet * ifp)3925 in6if_do_dad(
3926 	struct ifnet *ifp)
3927 {
3928 	struct nd_ifinfo *ndi = NULL;
3929 
3930 	if ((ifp->if_flags & IFF_LOOPBACK) != 0) {
3931 		return 0;
3932 	}
3933 
3934 	ndi = ND_IFINFO(ifp);
3935 	VERIFY((NULL != ndi) && (TRUE == ndi->initialized));
3936 	if (!(ndi->flags & ND6_IFF_DAD)) {
3937 		return 0;
3938 	}
3939 
3940 	/*
3941 	 * If we are using the alternative neighbor discovery
3942 	 * interface on this interface, then skip DAD.
3943 	 *
3944 	 * Also, skip it for interfaces marked "local private"
3945 	 * for now, even when not marked as using the alternative
3946 	 * interface.  This is for historical reasons.
3947 	 */
3948 	if (ifp->if_eflags &
3949 	    (IFEF_IPV6_ND6ALT | IFEF_LOCALNET_PRIVATE | IFEF_DIRECTLINK)) {
3950 		return 0;
3951 	}
3952 
3953 	if (ifp->if_family == IFNET_FAMILY_IPSEC ||
3954 	    ifp->if_family == IFNET_FAMILY_UTUN) {
3955 		/*
3956 		 * Ignore DAD for tunneling virtual interfaces, which get
3957 		 * their IPv6 address explicitly assigned.
3958 		 */
3959 		return 0;
3960 	}
3961 
3962 	switch (ifp->if_type) {
3963 #if IFT_DUMMY
3964 	case IFT_DUMMY:
3965 #endif
3966 	case IFT_FAITH:
3967 		/*
3968 		 * These interfaces do not have the IFF_LOOPBACK flag,
3969 		 * but loop packets back.  We do not have to do DAD on such
3970 		 * interfaces.  We should even omit it, because loop-backed
3971 		 * NS would confuse the DAD procedure.
3972 		 */
3973 		return 0;
3974 	default:
3975 		/*
3976 		 * Our DAD routine requires the interface up and running.
3977 		 * However, some interfaces can be up before the RUNNING
3978 		 * status.  Additionaly, users may try to assign addresses
3979 		 * before the interface becomes up (or running).
3980 		 * We simply skip DAD in such a case as a work around.
3981 		 * XXX: we should rather mark "tentative" on such addresses,
3982 		 * and do DAD after the interface becomes ready.
3983 		 */
3984 		if ((ifp->if_flags & (IFF_UP | IFF_RUNNING)) !=
3985 		    (IFF_UP | IFF_RUNNING)) {
3986 			return 0;
3987 		}
3988 
3989 		return 1;
3990 	}
3991 }
3992 
3993 /*
3994  * Calculate max IPv6 MTU through all the interfaces and store it
3995  * to in6_maxmtu.
3996  */
3997 void
in6_setmaxmtu(void)3998 in6_setmaxmtu(void)
3999 {
4000 	u_int32_t maxmtu = 0;
4001 	struct ifnet *ifp;
4002 
4003 	ifnet_head_lock_shared();
4004 	TAILQ_FOREACH(ifp, &ifnet_head, if_list) {
4005 		struct nd_ifinfo *ndi = NULL;
4006 
4007 		if ((ndi = ND_IFINFO(ifp)) != NULL && !ndi->initialized) {
4008 			ndi = NULL;
4009 		}
4010 		if (ndi != NULL) {
4011 			lck_mtx_lock(&ndi->lock);
4012 		}
4013 		if ((ifp->if_flags & IFF_LOOPBACK) == 0 &&
4014 		    IN6_LINKMTU(ifp) > maxmtu) {
4015 			maxmtu = IN6_LINKMTU(ifp);
4016 		}
4017 		if (ndi != NULL) {
4018 			lck_mtx_unlock(&ndi->lock);
4019 		}
4020 	}
4021 	ifnet_head_done();
4022 	if (maxmtu) {   /* update only when maxmtu is positive */
4023 		in6_maxmtu = maxmtu;
4024 	}
4025 }
4026 /*
4027  * Provide the length of interface identifiers to be used for the link attached
4028  * to the given interface.  The length should be defined in "IPv6 over
4029  * xxx-link" document.  Note that address architecture might also define
4030  * the length for a particular set of address prefixes, regardless of the
4031  * link type.  Also see RFC 4862 for additional background.
4032  */
4033 int
in6_if2idlen(struct ifnet * ifp)4034 in6_if2idlen(struct ifnet *ifp)
4035 {
4036 	switch (ifp->if_type) {
4037 	case IFT_ETHER:         /* RFC2464 */
4038 	case IFT_IEEE8023ADLAG: /* IEEE802.3ad Link Aggregate */
4039 #ifdef IFT_PROPVIRTUAL
4040 	case IFT_PROPVIRTUAL:   /* XXX: no RFC. treat it as ether */
4041 #endif
4042 #ifdef IFT_L2VLAN
4043 	case IFT_L2VLAN:        /* ditto */
4044 #endif
4045 #ifdef IFT_IEEE80211
4046 	case IFT_IEEE80211:     /* ditto */
4047 #endif
4048 #ifdef IFT_MIP
4049 	case IFT_MIP:   /* ditto */
4050 #endif
4051 		return 64;
4052 	case IFT_FDDI:          /* RFC2467 */
4053 		return 64;
4054 	case IFT_ISO88025:      /* RFC2470 (IPv6 over Token Ring) */
4055 		return 64;
4056 	case IFT_PPP:           /* RFC2472 */
4057 		return 64;
4058 	case IFT_ARCNET:        /* RFC2497 */
4059 		return 64;
4060 	case IFT_FRELAY:        /* RFC2590 */
4061 		return 64;
4062 	case IFT_IEEE1394:      /* RFC3146 */
4063 		return 64;
4064 	case IFT_GIF:
4065 		return 64;    /* draft-ietf-v6ops-mech-v2-07 */
4066 	case IFT_LOOP:
4067 		return 64;    /* XXX: is this really correct? */
4068 	case IFT_OTHER:
4069 		return 64;    /* for utun interfaces */
4070 	case IFT_CELLULAR:
4071 		return 64;    /* Packet Data over Cellular */
4072 	case IFT_BRIDGE:
4073 		return 64;    /* Transparent bridge interface */
4074 	default:
4075 		/*
4076 		 * Unknown link type:
4077 		 * It might be controversial to use the today's common constant
4078 		 * of 64 for these cases unconditionally.  For full compliance,
4079 		 * we should return an error in this case.  On the other hand,
4080 		 * if we simply miss the standard for the link type or a new
4081 		 * standard is defined for a new link type, the IFID length
4082 		 * is very likely to be the common constant.  As a compromise,
4083 		 * we always use the constant, but make an explicit notice
4084 		 * indicating the "unknown" case.
4085 		 */
4086 		log(LOG_NOTICE, "%s: unknown link type (%d)\n", __func__,
4087 		    ifp->if_type);
4088 		return 64;
4089 	}
4090 }
4091 /*
4092  * Convert sockaddr_in6 to sockaddr_in.  Original sockaddr_in6 must be
4093  * v4 mapped addr or v4 compat addr
4094  */
4095 void
in6_sin6_2_sin(struct sockaddr_in * sin,struct sockaddr_in6 * sin6)4096 in6_sin6_2_sin(struct sockaddr_in *sin, struct sockaddr_in6 *sin6)
4097 {
4098 	bzero(sin, sizeof(*sin));
4099 	sin->sin_len = sizeof(struct sockaddr_in);
4100 	sin->sin_family = AF_INET;
4101 	sin->sin_port = sin6->sin6_port;
4102 	sin->sin_addr.s_addr = sin6->sin6_addr.s6_addr32[3];
4103 }
4104 
4105 /* Convert sockaddr_in to sockaddr_in6 in v4 mapped addr format. */
4106 void
in6_sin_2_v4mapsin6(struct sockaddr_in * sin,struct sockaddr_in6 * sin6)4107 in6_sin_2_v4mapsin6(struct sockaddr_in *sin, struct sockaddr_in6 *sin6)
4108 {
4109 	bzero(sin6, sizeof(*sin6));
4110 	sin6->sin6_len = sizeof(struct sockaddr_in6);
4111 	sin6->sin6_family = AF_INET6;
4112 	sin6->sin6_port = sin->sin_port;
4113 	sin6->sin6_addr.s6_addr32[0] = 0;
4114 	sin6->sin6_addr.s6_addr32[1] = 0;
4115 	if (sin->sin_addr.s_addr) {
4116 		sin6->sin6_addr.s6_addr32[2] = IPV6_ADDR_INT32_SMP;
4117 		sin6->sin6_addr.s6_addr32[3] = sin->sin_addr.s_addr;
4118 	} else {
4119 		sin6->sin6_addr.s6_addr32[2] = 0;
4120 		sin6->sin6_addr.s6_addr32[3] = 0;
4121 	}
4122 }
4123 
4124 /* Convert sockaddr_in6 into sockaddr_in. */
4125 void
in6_sin6_2_sin_in_sock(struct sockaddr * nam)4126 in6_sin6_2_sin_in_sock(struct sockaddr *nam)
4127 {
4128 	struct sockaddr_in *sin_p;
4129 	struct sockaddr_in6 sin6;
4130 
4131 	/*
4132 	 * Save original sockaddr_in6 addr and convert it
4133 	 * to sockaddr_in.
4134 	 */
4135 	sin6 = *(struct sockaddr_in6 *)(void *)nam;
4136 	sin_p = (struct sockaddr_in *)(void *)nam;
4137 	in6_sin6_2_sin(sin_p, &sin6);
4138 }
4139 
4140 /* Convert sockaddr_in into sockaddr_in6 in v4 mapped addr format. */
4141 int
in6_sin_2_v4mapsin6_in_sock(struct sockaddr ** nam)4142 in6_sin_2_v4mapsin6_in_sock(struct sockaddr **nam)
4143 {
4144 	struct sockaddr_in *sin_p;
4145 	struct sockaddr_in6 *sin6_p;
4146 
4147 	sin6_p = (struct sockaddr_in6 *)alloc_sockaddr(sizeof(*sin6_p),
4148 	    Z_WAITOK | Z_NOFAIL);
4149 
4150 	sin_p = (struct sockaddr_in *)(void *)*nam;
4151 	in6_sin_2_v4mapsin6(sin_p, sin6_p);
4152 	free_sockaddr(*nam);
4153 	*nam = (struct sockaddr *)sin6_p;
4154 
4155 	return 0;
4156 }
4157 
4158 /*
4159  * Posts in6_event_data message kernel events.
4160  *
4161  * To get the same size of kev_in6_data between ILP32 and LP64 data models
4162  * we are using a special version of the in6_addrlifetime structure that
4163  * uses only 32 bits fields to be compatible with Leopard, and that
4164  * are large enough to span 68 years.
4165  */
4166 void
in6_post_msg(struct ifnet * ifp,u_int32_t event_code,struct in6_ifaddr * ifa,uint8_t * mac)4167 in6_post_msg(struct ifnet *ifp, u_int32_t event_code, struct in6_ifaddr *ifa,
4168     uint8_t *mac)
4169 {
4170 	struct kev_msg ev_msg;
4171 	struct kev_in6_data in6_event_data;
4172 	struct in6_addrlifetime ia6_lt;
4173 
4174 	bzero(&in6_event_data, sizeof(struct kev_in6_data));
4175 	bzero(&ev_msg, sizeof(struct kev_msg));
4176 	ev_msg.vendor_code      = KEV_VENDOR_APPLE;
4177 	ev_msg.kev_class        = KEV_NETWORK_CLASS;
4178 	ev_msg.kev_subclass     = KEV_INET6_SUBCLASS;
4179 	ev_msg.event_code       = event_code;
4180 
4181 	if (ifa) {
4182 		IFA_LOCK(&ifa->ia_ifa);
4183 		in6_event_data.ia_addr          = ifa->ia_addr;
4184 		in6_event_data.ia_net           = ifa->ia_net;
4185 		in6_event_data.ia_dstaddr       = ifa->ia_dstaddr;
4186 		in6_event_data.ia_prefixmask    = ifa->ia_prefixmask;
4187 		in6_event_data.ia_plen          = ifa->ia_plen;
4188 		in6_event_data.ia6_flags        = (u_int32_t)ifa->ia6_flags;
4189 
4190 		/* retrieve time as calendar time (last arg is 1) */
4191 		in6ifa_getlifetime(ifa, &ia6_lt, 1);
4192 		in6_event_data.ia_lifetime.ia6t_expire = (u_int32_t)ia6_lt.ia6t_expire;
4193 		in6_event_data.ia_lifetime.ia6t_preferred = (u_int32_t)ia6_lt.ia6t_preferred;
4194 		in6_event_data.ia_lifetime.ia6t_vltime = ia6_lt.ia6t_vltime;
4195 		in6_event_data.ia_lifetime.ia6t_pltime = ia6_lt.ia6t_pltime;
4196 		IFA_UNLOCK(&ifa->ia_ifa);
4197 	}
4198 
4199 	if (ifp != NULL) {
4200 		(void) strlcpy(&in6_event_data.link_data.if_name[0],
4201 		    ifp->if_name, IFNAMSIZ);
4202 		in6_event_data.link_data.if_family = ifp->if_family;
4203 		in6_event_data.link_data.if_unit  = (u_int32_t)ifp->if_unit;
4204 	}
4205 
4206 	if (mac != NULL) {
4207 		memcpy(&in6_event_data.ia_mac, mac,
4208 		    sizeof(in6_event_data.ia_mac));
4209 	}
4210 
4211 	ev_msg.dv[0].data_ptr    = &in6_event_data;
4212 	ev_msg.dv[0].data_length = sizeof(in6_event_data);
4213 	ev_msg.dv[1].data_length = 0;
4214 
4215 	dlil_post_complete_msg(NULL, &ev_msg);
4216 }
4217 
4218 /*
4219  * Called as part of ip6_init
4220  */
4221 void
in6_ifaddr_init(void)4222 in6_ifaddr_init(void)
4223 {
4224 	in6_cga_init();
4225 	in6_multi_init();
4226 
4227 	PE_parse_boot_argn("ifa_debug", &in6ifa_debug, sizeof(in6ifa_debug));
4228 
4229 	vm_size_t in6ifa_size = (in6ifa_debug == 0) ? sizeof(struct in6_ifaddr) :
4230 	    sizeof(struct in6_ifaddr_dbg);
4231 
4232 	in6ifa_zone = zone_create(IN6IFA_ZONE_NAME, in6ifa_size, ZC_ZFREE_CLEARMEM);
4233 
4234 	TAILQ_INIT(&in6ifa_trash_head);
4235 }
4236 
4237 static struct in6_ifaddr *
in6_ifaddr_alloc(zalloc_flags_t how)4238 in6_ifaddr_alloc(zalloc_flags_t how)
4239 {
4240 	struct in6_ifaddr *in6ifa;
4241 
4242 	in6ifa = zalloc_flags(in6ifa_zone, how | Z_ZERO);
4243 	if (in6ifa != NULL) {
4244 		in6ifa->ia_ifa.ifa_free = in6_ifaddr_free;
4245 		in6ifa->ia_ifa.ifa_debug |= IFD_ALLOC;
4246 		in6ifa->ia_ifa.ifa_del_wc = &in6ifa->ia_ifa.ifa_debug;
4247 		in6ifa->ia_ifa.ifa_del_waiters = 0;
4248 		ifa_lock_init(&in6ifa->ia_ifa);
4249 		if (in6ifa_debug != 0) {
4250 			struct in6_ifaddr_dbg *in6ifa_dbg =
4251 			    (struct in6_ifaddr_dbg *)in6ifa;
4252 			in6ifa->ia_ifa.ifa_debug |= IFD_DEBUG;
4253 			in6ifa->ia_ifa.ifa_trace = in6_ifaddr_trace;
4254 			in6ifa->ia_ifa.ifa_attached = in6_ifaddr_attached;
4255 			in6ifa->ia_ifa.ifa_detached = in6_ifaddr_detached;
4256 			ctrace_record(&in6ifa_dbg->in6ifa_alloc);
4257 		}
4258 	}
4259 
4260 	return in6ifa;
4261 }
4262 
4263 static void
in6_ifaddr_free(struct ifaddr * ifa)4264 in6_ifaddr_free(struct ifaddr *ifa)
4265 {
4266 	IFA_LOCK_ASSERT_HELD(ifa);
4267 
4268 	if (ifa->ifa_refcnt != 0) {
4269 		panic("%s: ifa %p bad ref cnt", __func__, ifa);
4270 		/* NOTREACHED */
4271 	} else if (!(ifa->ifa_debug & IFD_ALLOC)) {
4272 		panic("%s: ifa %p cannot be freed", __func__, ifa);
4273 		/* NOTREACHED */
4274 	}
4275 	if (ifa->ifa_debug & IFD_DEBUG) {
4276 		struct in6_ifaddr_dbg *in6ifa_dbg =
4277 		    (struct in6_ifaddr_dbg *)ifa;
4278 		ctrace_record(&in6ifa_dbg->in6ifa_free);
4279 		bcopy(&in6ifa_dbg->in6ifa, &in6ifa_dbg->in6ifa_old,
4280 		    sizeof(struct in6_ifaddr));
4281 		if (ifa->ifa_debug & IFD_TRASHED) {
4282 			/* Become a regular mutex, just in case */
4283 			IFA_CONVERT_LOCK(ifa);
4284 			lck_mtx_lock(&in6ifa_trash_lock);
4285 			TAILQ_REMOVE(&in6ifa_trash_head, in6ifa_dbg,
4286 			    in6ifa_trash_link);
4287 			lck_mtx_unlock(&in6ifa_trash_lock);
4288 			ifa->ifa_debug &= ~IFD_TRASHED;
4289 		}
4290 	}
4291 	IFA_UNLOCK(ifa);
4292 	ifa_lock_destroy(ifa);
4293 	bzero(ifa, sizeof(struct in6_ifaddr));
4294 	zfree(in6ifa_zone, ifa);
4295 }
4296 
4297 static void
in6_ifaddr_attached(struct ifaddr * ifa)4298 in6_ifaddr_attached(struct ifaddr *ifa)
4299 {
4300 	struct in6_ifaddr_dbg *in6ifa_dbg = (struct in6_ifaddr_dbg *)ifa;
4301 
4302 	IFA_LOCK_ASSERT_HELD(ifa);
4303 
4304 	if (!(ifa->ifa_debug & IFD_DEBUG)) {
4305 		panic("%s: ifa %p has no debug structure", __func__, ifa);
4306 		/* NOTREACHED */
4307 	}
4308 	if (ifa->ifa_debug & IFD_TRASHED) {
4309 		/* Become a regular mutex, just in case */
4310 		IFA_CONVERT_LOCK(ifa);
4311 		lck_mtx_lock(&in6ifa_trash_lock);
4312 		TAILQ_REMOVE(&in6ifa_trash_head, in6ifa_dbg, in6ifa_trash_link);
4313 		lck_mtx_unlock(&in6ifa_trash_lock);
4314 		ifa->ifa_debug &= ~IFD_TRASHED;
4315 	}
4316 }
4317 
4318 static void
in6_ifaddr_detached(struct ifaddr * ifa)4319 in6_ifaddr_detached(struct ifaddr *ifa)
4320 {
4321 	struct in6_ifaddr_dbg *in6ifa_dbg = (struct in6_ifaddr_dbg *)ifa;
4322 
4323 	IFA_LOCK_ASSERT_HELD(ifa);
4324 
4325 	if (!(ifa->ifa_debug & IFD_DEBUG)) {
4326 		panic("%s: ifa %p has no debug structure", __func__, ifa);
4327 		/* NOTREACHED */
4328 	} else if (ifa->ifa_debug & IFD_TRASHED) {
4329 		panic("%s: ifa %p is already in trash list", __func__, ifa);
4330 		/* NOTREACHED */
4331 	}
4332 	ifa->ifa_debug |= IFD_TRASHED;
4333 	/* Become a regular mutex, just in case */
4334 	IFA_CONVERT_LOCK(ifa);
4335 	lck_mtx_lock(&in6ifa_trash_lock);
4336 	TAILQ_INSERT_TAIL(&in6ifa_trash_head, in6ifa_dbg, in6ifa_trash_link);
4337 	lck_mtx_unlock(&in6ifa_trash_lock);
4338 }
4339 
4340 static void
in6_ifaddr_trace(struct ifaddr * ifa,int refhold)4341 in6_ifaddr_trace(struct ifaddr *ifa, int refhold)
4342 {
4343 	struct in6_ifaddr_dbg *in6ifa_dbg = (struct in6_ifaddr_dbg *)ifa;
4344 	ctrace_t *tr;
4345 	u_int32_t idx;
4346 	u_int16_t *cnt;
4347 
4348 	if (!(ifa->ifa_debug & IFD_DEBUG)) {
4349 		panic("%s: ifa %p has no debug structure", __func__, ifa);
4350 		/* NOTREACHED */
4351 	}
4352 	if (refhold) {
4353 		cnt = &in6ifa_dbg->in6ifa_refhold_cnt;
4354 		tr = in6ifa_dbg->in6ifa_refhold;
4355 	} else {
4356 		cnt = &in6ifa_dbg->in6ifa_refrele_cnt;
4357 		tr = in6ifa_dbg->in6ifa_refrele;
4358 	}
4359 
4360 	idx = atomic_add_16_ov(cnt, 1) % IN6IFA_TRACE_HIST_SIZE;
4361 	ctrace_record(&tr[idx]);
4362 }
4363 
4364 /*
4365  * Handle SIOCGASSOCIDS ioctl for PF_INET6 domain.
4366  */
4367 static int
in6_getassocids(struct socket * so,uint32_t * cnt,user_addr_t aidp)4368 in6_getassocids(struct socket *so, uint32_t *cnt, user_addr_t aidp)
4369 {
4370 	struct in6pcb *in6p = sotoin6pcb(so);
4371 	sae_associd_t aid;
4372 
4373 	if (in6p == NULL || in6p->inp_state == INPCB_STATE_DEAD) {
4374 		return EINVAL;
4375 	}
4376 
4377 	/* IN6PCB has no concept of association */
4378 	aid = SAE_ASSOCID_ANY;
4379 	*cnt = 0;
4380 
4381 	/* just asking how many there are? */
4382 	if (aidp == USER_ADDR_NULL) {
4383 		return 0;
4384 	}
4385 
4386 	return copyout(&aid, aidp, sizeof(aid));
4387 }
4388 
4389 /*
4390  * Handle SIOCGCONNIDS ioctl for PF_INET6 domain.
4391  */
4392 static int
in6_getconnids(struct socket * so,sae_associd_t aid,uint32_t * cnt,user_addr_t cidp)4393 in6_getconnids(struct socket *so, sae_associd_t aid, uint32_t *cnt,
4394     user_addr_t cidp)
4395 {
4396 	struct in6pcb *in6p = sotoin6pcb(so);
4397 	sae_connid_t cid;
4398 
4399 	if (in6p == NULL || in6p->inp_state == INPCB_STATE_DEAD) {
4400 		return EINVAL;
4401 	}
4402 
4403 	if (aid != SAE_ASSOCID_ANY && aid != SAE_ASSOCID_ALL) {
4404 		return EINVAL;
4405 	}
4406 
4407 	/* if connected, return 1 connection count */
4408 	*cnt = ((so->so_state & SS_ISCONNECTED) ? 1 : 0);
4409 
4410 	/* just asking how many there are? */
4411 	if (cidp == USER_ADDR_NULL) {
4412 		return 0;
4413 	}
4414 
4415 	/* if IN6PCB is connected, assign it connid 1 */
4416 	cid = ((*cnt != 0) ? 1 : SAE_CONNID_ANY);
4417 
4418 	return copyout(&cid, cidp, sizeof(cid));
4419 }
4420 
4421 /*
4422  * Handle SIOCGCONNINFO ioctl for PF_INET6 domain.
4423  */
4424 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)4425 in6_getconninfo(struct socket *so, sae_connid_t cid, uint32_t *flags,
4426     uint32_t *ifindex, int32_t *soerror, user_addr_t src, socklen_t *src_len,
4427     user_addr_t dst, socklen_t *dst_len, uint32_t *aux_type,
4428     user_addr_t aux_data, uint32_t *aux_len)
4429 {
4430 	struct in6pcb *in6p = sotoin6pcb(so);
4431 	struct sockaddr_in6 sin6;
4432 	struct ifnet *ifp = NULL;
4433 	int error = 0;
4434 	u_int32_t copy_len = 0;
4435 
4436 	/*
4437 	 * Don't test for INPCB_STATE_DEAD since this may be called
4438 	 * after SOF_PCBCLEARING is set, e.g. after tcp_close().
4439 	 */
4440 	if (in6p == NULL) {
4441 		error = EINVAL;
4442 		goto out;
4443 	}
4444 
4445 	if (cid != SAE_CONNID_ANY && cid != SAE_CONNID_ALL && cid != 1) {
4446 		error = EINVAL;
4447 		goto out;
4448 	}
4449 
4450 	ifp = in6p->in6p_last_outifp;
4451 	*ifindex = ((ifp != NULL) ? ifp->if_index : 0);
4452 	*soerror = so->so_error;
4453 	*flags = 0;
4454 	if (so->so_state & SS_ISCONNECTED) {
4455 		*flags |= (CIF_CONNECTED | CIF_PREFERRED);
4456 	}
4457 	if (in6p->in6p_flags & INP_BOUND_IF) {
4458 		*flags |= CIF_BOUND_IF;
4459 	}
4460 	if (!(in6p->in6p_flags & INP_IN6ADDR_ANY)) {
4461 		*flags |= CIF_BOUND_IP;
4462 	}
4463 	if (!(in6p->in6p_flags & INP_ANONPORT)) {
4464 		*flags |= CIF_BOUND_PORT;
4465 	}
4466 
4467 	bzero(&sin6, sizeof(sin6));
4468 	sin6.sin6_len = sizeof(sin6);
4469 	sin6.sin6_family = AF_INET6;
4470 
4471 	/* source address and port */
4472 	sin6.sin6_port = in6p->in6p_lport;
4473 	if (!in6_embedded_scope) {
4474 		sin6.sin6_scope_id = in6p->inp_lifscope;
4475 	}
4476 	in6_recoverscope(&sin6, &in6p->in6p_laddr, NULL);
4477 	if (*src_len == 0) {
4478 		*src_len = sin6.sin6_len;
4479 	} else {
4480 		if (src != USER_ADDR_NULL) {
4481 			copy_len = min(*src_len, sizeof(sin6));
4482 			error = copyout(&sin6, src, copy_len);
4483 			if (error != 0) {
4484 				goto out;
4485 			}
4486 			*src_len = copy_len;
4487 		}
4488 	}
4489 
4490 	/* destination address and port */
4491 	sin6.sin6_port = in6p->in6p_fport;
4492 	if (!in6_embedded_scope) {
4493 		sin6.sin6_scope_id = in6p->inp_fifscope;
4494 	}
4495 	in6_recoverscope(&sin6, &in6p->in6p_faddr, NULL);
4496 	if (*dst_len == 0) {
4497 		*dst_len = sin6.sin6_len;
4498 	} else {
4499 		if (dst != USER_ADDR_NULL) {
4500 			copy_len = min(*dst_len, sizeof(sin6));
4501 			error = copyout(&sin6, dst, copy_len);
4502 			if (error != 0) {
4503 				goto out;
4504 			}
4505 			*dst_len = copy_len;
4506 		}
4507 	}
4508 
4509 	if (SOCK_PROTO(so) == IPPROTO_TCP) {
4510 		struct conninfo_tcp tcp_ci;
4511 
4512 		*aux_type = CIAUX_TCP;
4513 		if (*aux_len == 0) {
4514 			*aux_len = sizeof(tcp_ci);
4515 		} else {
4516 			if (aux_data != USER_ADDR_NULL) {
4517 				copy_len = min(*aux_len, sizeof(tcp_ci));
4518 				bzero(&tcp_ci, sizeof(tcp_ci));
4519 				tcp_getconninfo(so, &tcp_ci);
4520 				error = copyout(&tcp_ci, aux_data, copy_len);
4521 				if (error != 0) {
4522 					goto out;
4523 				}
4524 				*aux_len = copy_len;
4525 			}
4526 		}
4527 	} else {
4528 		*aux_type = 0;
4529 		*aux_len = 0;
4530 	}
4531 
4532 out:
4533 	return error;
4534 }
4535 
4536 /*
4537  * 'u' group ioctls.
4538  *
4539  * The switch statement below does nothing at runtime, as it serves as a
4540  * compile time check to ensure that all of the socket 'u' ioctls (those
4541  * in the 'u' group going thru soo_ioctl) that are made available by the
4542  * networking stack is unique.  This works as long as this routine gets
4543  * updated each time a new interface ioctl gets added.
4544  *
4545  * Any failures at compile time indicates duplicated ioctl values.
4546  */
4547 static __attribute__((unused)) void
in6ioctl_cassert(void)4548 in6ioctl_cassert(void)
4549 {
4550 	/*
4551 	 * This is equivalent to _CASSERT() and the compiler wouldn't
4552 	 * generate any instructions, thus for compile time only.
4553 	 */
4554 	switch ((u_long)0) {
4555 	case 0:
4556 
4557 	/* bsd/netinet6/in6_var.h */
4558 	case SIOCAADDRCTL_POLICY:
4559 	case SIOCDADDRCTL_POLICY:
4560 	case SIOCDRADD_IN6_32:
4561 	case SIOCDRADD_IN6_64:
4562 	case SIOCDRDEL_IN6_32:
4563 	case SIOCDRDEL_IN6_64:
4564 		;
4565 	}
4566 }
4567 
4568 struct in6_llentry {
4569 	struct llentry          base;
4570 };
4571 
4572 #define        IN6_LLTBL_DEFAULT_HSIZE 32
4573 #define        IN6_LLTBL_HASH(k, h) \
4574 	((((((((k) >> 8) ^ (k)) >> 8) ^ (k)) >> 8) ^ (k)) & ((h) - 1))
4575 
4576 /*
4577  * Do actual deallocation of @lle.
4578  */
4579 static void
in6_lltable_destroy_lle_unlocked(struct llentry * lle)4580 in6_lltable_destroy_lle_unlocked(struct llentry *lle)
4581 {
4582 	LLE_LOCK_DESTROY(lle);
4583 	LLE_REQ_DESTROY(lle);
4584 	struct in6_llentry *in_lle = (struct in6_llentry *)lle;
4585 	kfree_type(struct in6_llentry, in_lle);
4586 }
4587 
4588 /*
4589  * Called by LLE_FREE_LOCKED when number of references
4590  * drops to zero.
4591  */
4592 static void
in6_lltable_destroy_lle(struct llentry * lle)4593 in6_lltable_destroy_lle(struct llentry *lle)
4594 {
4595 	LLE_WUNLOCK(lle);
4596 	/* XXX TBD */
4597 	//thread_call_free(lle->lle_timer);
4598 	in6_lltable_destroy_lle_unlocked(lle);
4599 }
4600 
4601 
4602 static struct llentry *
in6_lltable_new(const struct in6_addr * addr6,uint16_t flags)4603 in6_lltable_new(const struct in6_addr *addr6, uint16_t flags)
4604 {
4605 #pragma unused(flags)
4606 	struct in6_llentry *lle;
4607 
4608 	lle = kalloc_type(struct in6_llentry, Z_NOWAIT | Z_ZERO);
4609 	if (lle == NULL) {              /* NB: caller generates msg */
4610 		return NULL;
4611 	}
4612 
4613 	lle->base.r_l3addr.addr6 = *addr6;
4614 	lle->base.lle_refcnt = 1;
4615 	lle->base.lle_free = in6_lltable_destroy_lle;
4616 	LLE_LOCK_INIT(&lle->base);
4617 	LLE_REQ_INIT(&lle->base);
4618 #if 0
4619 	/* XXX TBD */
4620 	lle->base.lle_timer = thread_call_allocate(nd6_llinfo_timer, lle);
4621 
4622 	if (lle->base.lle_timer == NULL) {
4623 		printf("lle_timer thread call could not be allocated.\n");
4624 		LLE_LOCK_DESTROY(&lle->base);
4625 		LLE_REQ_DESTROY(&lle->base);
4626 		kfree_type(struct in6_llentry, lle);
4627 		return NULL;
4628 	}
4629 #endif
4630 	return &lle->base;
4631 }
4632 
4633 static int
in6_lltable_match_prefix(const struct sockaddr * saddr,const struct sockaddr * smask,uint16_t flags,struct llentry * lle)4634 in6_lltable_match_prefix(const struct sockaddr *saddr,
4635     const struct sockaddr *smask, uint16_t flags, struct llentry *lle)
4636 {
4637 	const struct in6_addr *addr, *mask, *lle_addr;
4638 
4639 	addr = &((const struct sockaddr_in6 *)(const void *)saddr)->sin6_addr;
4640 	mask = &((const struct sockaddr_in6 *)(const void *)smask)->sin6_addr;
4641 	lle_addr = &lle->r_l3addr.addr6;
4642 	uint32_t lle_addr_ifscope = lle->lle_tbl->llt_ifp->if_index;
4643 	uint32_t addr_ifscope = ((const struct sockaddr_in6 *)(const void *)saddr)->sin6_scope_id;
4644 
4645 	if (in6_are_masked_addr_scope_equal(lle_addr, lle_addr_ifscope, addr, addr_ifscope, mask) == 0) {
4646 		return 0;
4647 	}
4648 
4649 	if (lle->la_flags & LLE_IFADDR) {
4650 		/*
4651 		 * Delete LLE_IFADDR records IFF address & flag matches.
4652 		 * Note that addr is the interface address within prefix
4653 		 * being matched.
4654 		 */
4655 		if (in6_are_addr_equal_scoped(addr, lle_addr, addr_ifscope, lle_addr_ifscope) &&
4656 		    (flags & LLE_STATIC) != 0) {
4657 			return 1;
4658 		}
4659 		return 0;
4660 	}
4661 
4662 	/* flags & LLE_STATIC means deleting both dynamic and static entries */
4663 	if ((flags & LLE_STATIC) || !(lle->la_flags & LLE_STATIC)) {
4664 		return 1;
4665 	}
4666 
4667 	return 0;
4668 }
4669 
4670 static void
in6_lltable_free_entry(struct lltable * llt,struct llentry * lle)4671 in6_lltable_free_entry(struct lltable *llt, struct llentry *lle)
4672 {
4673 	struct ifnet *ifp;
4674 
4675 	LLE_WLOCK_ASSERT(lle);
4676 	KASSERT(llt != NULL, ("lltable is NULL"));
4677 
4678 	/* Unlink entry from table */
4679 	if ((lle->la_flags & LLE_LINKED) != 0) {
4680 		ifp = llt->llt_ifp;
4681 		if_afdata_wlock_assert(ifp, llt->llt_af);
4682 		lltable_unlink_entry(llt, lle);
4683 	}
4684 
4685 #if 0
4686 	/* XXX TBD */
4687 	if (thread_call_cancel(lle->lle_timer) == TRUE) {
4688 		LLE_REMREF(lle);
4689 	}
4690 #endif
4691 	llentry_free(lle);
4692 }
4693 
4694 static int
in6_lltable_rtcheck(struct ifnet * ifp,uint16_t flags,const struct sockaddr * l3addr)4695 in6_lltable_rtcheck(struct ifnet *ifp,
4696     uint16_t flags, const struct sockaddr *l3addr)
4697 {
4698 #pragma unused(flags)
4699 	struct rtentry *rt;
4700 
4701 	KASSERT(l3addr->sa_family == AF_INET6,
4702 	    ("sin_family %d", l3addr->sa_family));
4703 	/* XXX rtalloc1 should take a const param */
4704 	rt = rtalloc1(__DECONST(struct sockaddr *, l3addr), 0, 0);
4705 	if (rt == NULL || (rt->rt_flags & RTF_GATEWAY) || rt->rt_ifp != ifp) {
4706 		struct ifaddr *ifa;
4707 		/*
4708 		 * Create an ND6 cache for an IPv6 neighbor
4709 		 * that is not covered by our own prefix.
4710 		 */
4711 		/* XXX ifaof_ifpforaddr should take a const param */
4712 		ifa = ifaof_ifpforaddr(__DECONST(struct sockaddr *, l3addr), ifp);
4713 		if (ifa != NULL) {
4714 			IFA_REMREF(ifa);
4715 			if (rt != NULL) {
4716 				rtfree(rt);
4717 			}
4718 			return 0;
4719 		}
4720 		log(LOG_INFO, "IPv6 address: \"%s\" is not on the network\n",
4721 		    ip6_sprintf(&((const struct sockaddr_in6 *)(const void *)l3addr)->sin6_addr));
4722 		if (rt != NULL) {
4723 			rtfree(rt);
4724 		}
4725 		return EINVAL;
4726 	}
4727 	rtfree(rt);
4728 	return 0;
4729 }
4730 
4731 static inline uint32_t
in6_lltable_hash_dst(const struct in6_addr * dst,uint32_t hsize)4732 in6_lltable_hash_dst(const struct in6_addr *dst, uint32_t hsize)
4733 {
4734 	return IN6_LLTBL_HASH(dst->s6_addr32[3], hsize);
4735 }
4736 
4737 static uint32_t
in6_lltable_hash(const struct llentry * lle,uint32_t hsize)4738 in6_lltable_hash(const struct llentry *lle, uint32_t hsize)
4739 {
4740 	return in6_lltable_hash_dst(&lle->r_l3addr.addr6, hsize);
4741 }
4742 
4743 static void
in6_lltable_fill_sa_entry(const struct llentry * lle,struct sockaddr * sa)4744 in6_lltable_fill_sa_entry(const struct llentry *lle, struct sockaddr *sa)
4745 {
4746 	struct sockaddr_in6 *sin6;
4747 
4748 	sin6 = (struct sockaddr_in6 *)(void *)sa;
4749 	bzero(sin6, sizeof(*sin6));
4750 	sin6->sin6_family = AF_INET6;
4751 	sin6->sin6_len = sizeof(*sin6);
4752 	sin6->sin6_addr = lle->r_l3addr.addr6;
4753 }
4754 
4755 static inline struct llentry *
in6_lltable_find_dst(struct lltable * llt,const struct in6_addr * dst)4756 in6_lltable_find_dst(struct lltable *llt, const struct in6_addr *dst)
4757 {
4758 	struct llentry *lle;
4759 	struct llentries *lleh;
4760 	u_int hashidx;
4761 
4762 	hashidx = in6_lltable_hash_dst(dst, llt->llt_hsize);
4763 	lleh = &llt->lle_head[hashidx];
4764 	LIST_FOREACH(lle, lleh, lle_next) {
4765 		if (lle->la_flags & LLE_DELETED) {
4766 			continue;
4767 		}
4768 		if (IN6_ARE_ADDR_EQUAL(&lle->r_l3addr.addr6, dst)) {
4769 			break;
4770 		}
4771 	}
4772 
4773 	return lle;
4774 }
4775 
4776 static void
in6_lltable_delete_entry(struct lltable * llt,struct llentry * lle)4777 in6_lltable_delete_entry(struct lltable *llt, struct llentry *lle)
4778 {
4779 #pragma unused(llt)
4780 	lle->la_flags |= LLE_DELETED;
4781 	EVENTHANDLER_INVOKE(NULL, lle_event, lle, LLENTRY_DELETED);
4782 #ifdef DIAGNOSTIC
4783 	log(LOG_INFO, "ifaddr cache = %p is deleted\n", lle);
4784 #endif
4785 	llentry_free(lle);
4786 }
4787 
4788 static struct llentry *
in6_lltable_alloc(struct lltable * llt,uint16_t flags,const struct sockaddr * l3addr)4789 in6_lltable_alloc(struct lltable *llt, uint16_t flags,
4790     const struct sockaddr *l3addr)
4791 {
4792 	const struct sockaddr_in6 *sin6 = (const struct sockaddr_in6 *)(const void *)l3addr;
4793 	struct ifnet *ifp = llt->llt_ifp;
4794 	struct llentry *lle;
4795 
4796 	KASSERT(l3addr->sa_family == AF_INET6,
4797 	    ("sin_family %d", l3addr->sa_family));
4798 
4799 	/*
4800 	 * A route that covers the given address must have
4801 	 * been installed 1st because we are doing a resolution,
4802 	 * verify this.
4803 	 */
4804 	if (!(flags & LLE_IFADDR) &&
4805 	    in6_lltable_rtcheck(ifp, flags, l3addr) != 0) {
4806 		return NULL;
4807 	}
4808 
4809 	lle = in6_lltable_new(&sin6->sin6_addr, flags);
4810 	if (lle == NULL) {
4811 		log(LOG_INFO, "lla_lookup: new lle malloc failed\n");
4812 		return NULL;
4813 	}
4814 	lle->la_flags = (uint16_t)flags;
4815 	if ((flags & LLE_IFADDR) == LLE_IFADDR) {
4816 		lltable_set_entry_addr(ifp, lle, LLADDR(SDL(ifp->if_lladdr->ifa_addr)));
4817 		lle->la_flags |= LLE_STATIC;
4818 	}
4819 
4820 	if ((lle->la_flags & LLE_STATIC) != 0) {
4821 		lle->ln_state = ND6_LLINFO_REACHABLE;
4822 	}
4823 
4824 	return lle;
4825 }
4826 
4827 static struct llentry *
in6_lltable_lookup(struct lltable * llt,uint16_t flags,const struct sockaddr * l3addr)4828 in6_lltable_lookup(struct lltable *llt, uint16_t flags,
4829     const struct sockaddr *l3addr)
4830 {
4831 	const struct sockaddr_in6 *sin6 = (const struct sockaddr_in6 *)(const void *)l3addr;
4832 	struct llentry *lle;
4833 
4834 	IF_AFDATA_LOCK_ASSERT(llt->llt_ifp, llt->llt_af);
4835 	KASSERT(l3addr->sa_family == AF_INET6,
4836 	    ("sin_family %d", l3addr->sa_family));
4837 
4838 	lle = in6_lltable_find_dst(llt, &sin6->sin6_addr);
4839 
4840 	if (lle == NULL) {
4841 		return NULL;
4842 	}
4843 
4844 	KASSERT((flags & (LLE_UNLOCKED | LLE_EXCLUSIVE)) !=
4845 	    (LLE_UNLOCKED | LLE_EXCLUSIVE), ("wrong lle request flags: 0x%X",
4846 	    flags));
4847 
4848 	if (flags & LLE_UNLOCKED) {
4849 		return lle;
4850 	}
4851 
4852 	if (flags & LLE_EXCLUSIVE) {
4853 		LLE_WLOCK(lle);
4854 	} else {
4855 		LLE_RLOCK(lle);
4856 	}
4857 	return lle;
4858 }
4859 
4860 static int
in6_lltable_dump_entry(struct lltable * llt,struct llentry * lle,struct sysctl_req * wr)4861 in6_lltable_dump_entry(struct lltable *llt, struct llentry *lle,
4862     struct sysctl_req *wr)
4863 {
4864 	struct ifnet *ifp = llt->llt_ifp;
4865 	/* XXX stack use */
4866 	struct {
4867 		struct rt_msghdr        rtm;
4868 		struct sockaddr_in6     sin6;
4869 		/*
4870 		 * ndp.c assumes that sdl is word aligned
4871 		 */
4872 #ifdef __LP64__
4873 		uint32_t                pad;
4874 #endif
4875 		struct sockaddr_dl      sdl;
4876 	} ndpc;
4877 	struct sockaddr_dl *sdl;
4878 	int error;
4879 
4880 	bzero(&ndpc, sizeof(ndpc));
4881 	/* skip deleted entries */
4882 	if ((lle->la_flags & LLE_DELETED) == LLE_DELETED) {
4883 		return 0;
4884 	}
4885 	/* Skip if jailed and not a valid IP of the prison. */
4886 	lltable_fill_sa_entry(lle,
4887 	    (struct sockaddr *)&ndpc.sin6);
4888 	/*
4889 	 * produce a msg made of:
4890 	 *  struct rt_msghdr;
4891 	 *  struct sockaddr_in6 (IPv6)
4892 	 *  struct sockaddr_dl;
4893 	 */
4894 	ndpc.rtm.rtm_msglen = sizeof(ndpc);
4895 	ndpc.rtm.rtm_version = RTM_VERSION;
4896 	ndpc.rtm.rtm_type = RTM_GET;
4897 	ndpc.rtm.rtm_flags = RTF_UP;
4898 	ndpc.rtm.rtm_addrs = RTA_DST | RTA_GATEWAY;
4899 
4900 	/* publish */
4901 	if (lle->la_flags & LLE_PUB) {
4902 		ndpc.rtm.rtm_flags |= RTF_ANNOUNCE;
4903 	}
4904 	sdl = &ndpc.sdl;
4905 	sdl->sdl_family = AF_LINK;
4906 	sdl->sdl_len = sizeof(*sdl);
4907 	sdl->sdl_index = ifp->if_index;
4908 	sdl->sdl_type = ifp->if_type;
4909 	if ((lle->la_flags & LLE_VALID) == LLE_VALID) {
4910 		sdl->sdl_alen = ifp->if_addrlen;
4911 		bcopy(&lle->ll_addr, LLADDR(sdl), ifp->if_addrlen);
4912 	} else {
4913 		sdl->sdl_alen = 0;
4914 		bzero(LLADDR(sdl), ifp->if_addrlen);
4915 	}
4916 	if (lle->la_expire != 0) {
4917 		clock_sec_t secs;
4918 		clock_usec_t usecs;
4919 
4920 		clock_get_calendar_microtime(&secs, &usecs);
4921 		ndpc.rtm.rtm_rmx.rmx_expire = (int32_t)(lle->la_expire +
4922 		    lle->lle_remtime / hz +
4923 		    secs - net_uptime());
4924 	}
4925 	ndpc.rtm.rtm_flags |= (RTF_HOST | RTF_LLDATA);
4926 	if (lle->la_flags & LLE_STATIC) {
4927 		ndpc.rtm.rtm_flags |= RTF_STATIC;
4928 	}
4929 	if (lle->la_flags & LLE_IFADDR) {
4930 		ndpc.rtm.rtm_flags |= RTF_PINNED;
4931 	}
4932 	if (lle->ln_router != 0) {
4933 		ndpc.rtm.rtm_flags |= RTF_GATEWAY;
4934 	}
4935 	ndpc.rtm.rtm_rmx.rmx_pksent = lle->la_asked;
4936 	/* Store state in rmx_weight value */
4937 	ndpc.rtm.rtm_rmx.rmx_state = lle->ln_state;
4938 	ndpc.rtm.rtm_index = ifp->if_index;
4939 	error = SYSCTL_OUT(wr, &ndpc, sizeof(ndpc));
4940 
4941 	return error;
4942 }
4943 
4944 struct lltable *
in6_lltattach(struct ifnet * ifp)4945 in6_lltattach(struct ifnet *ifp)
4946 {
4947 	struct lltable *llt;
4948 
4949 	llt = lltable_allocate_htbl(IN6_LLTBL_DEFAULT_HSIZE);
4950 	llt->llt_af = AF_INET6;
4951 	llt->llt_ifp = ifp;
4952 
4953 	llt->llt_lookup = in6_lltable_lookup;
4954 	llt->llt_alloc_entry = in6_lltable_alloc;
4955 	llt->llt_delete_entry = in6_lltable_delete_entry;
4956 	llt->llt_dump_entry = in6_lltable_dump_entry;
4957 	llt->llt_hash = in6_lltable_hash;
4958 	llt->llt_fill_sa_entry = in6_lltable_fill_sa_entry;
4959 	llt->llt_free_entry = in6_lltable_free_entry;
4960 	llt->llt_match_prefix = in6_lltable_match_prefix;
4961 	lltable_link(llt);
4962 
4963 	return llt;
4964 }
4965 
4966 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)4967 in6_ip6_to_sockaddr(const struct in6_addr *ip6, u_int16_t port, uint32_t ifscope,
4968     struct sockaddr_in6 *sin6, u_int32_t maxlen)
4969 {
4970 	if (maxlen < sizeof(struct sockaddr_in6)) {
4971 		return;
4972 	}
4973 
4974 	*sin6 = (struct sockaddr_in6) {
4975 		.sin6_family = AF_INET6,
4976 		.sin6_len = sizeof(*sin6),
4977 		.sin6_port = port,
4978 		.sin6_addr = *ip6,
4979 		.sin6_scope_id = IN6_IS_SCOPE_EMBED(ip6) ? ifscope : IFSCOPE_NONE,
4980 	};
4981 
4982 	if (IN6_IS_SCOPE_EMBED(&sin6->sin6_addr)) {
4983 		in6_verify_ifscope(&sin6->sin6_addr, ifscope);
4984 		if (in6_embedded_scope) {
4985 			sin6->sin6_scope_id = ntohs(sin6->sin6_addr.s6_addr16[1]);
4986 			sin6->sin6_addr.s6_addr16[1] = 0;
4987 		}
4988 	}
4989 }
4990 
4991 /* IPv6 events */
4992 struct in6_event {
4993 	in6_evhdlr_code_t in6_event_code;
4994 	struct ifnet *in6_ifp;
4995 	struct in6_addr in6_address;
4996 	uint32_t val;
4997 };
4998 
4999 struct in6_event2kev in6_event2kev_array[IN6_EVENT_MAX] = {
5000 	{
5001 		.in6_event_code = IN6_ADDR_MARKED_DUPLICATED,
5002 		.in6_event_kev_subclass = KEV_ND6_SUBCLASS,
5003 		.in6_event_kev_code = KEV_ND6_DAD_FAILURE,
5004 		.in6_event_str = "IN6_ADDR_MARKED_DUPLICATED",
5005 	},
5006 	{
5007 		.in6_event_code = IN6_ADDR_MARKED_DETACHED,
5008 		.in6_event_kev_subclass = KEV_ND6_SUBCLASS,
5009 		.in6_event_kev_code = KEV_ND6_ADDR_DETACHED,
5010 		.in6_event_str = "IN6_ADDR_MARKED_DETACHED",
5011 	},
5012 	{
5013 		.in6_event_code = IN6_ADDR_MARKED_DEPRECATED,
5014 		.in6_event_kev_subclass = KEV_ND6_SUBCLASS,
5015 		.in6_event_kev_code = KEV_ND6_ADDR_DEPRECATED,
5016 		.in6_event_str = "IN6_ADDR_MARKED_DEPRECATED",
5017 	},
5018 	{
5019 		.in6_event_code = IN6_NDP_RTR_EXPIRY,
5020 		.in6_event_kev_subclass = KEV_ND6_SUBCLASS,
5021 		.in6_event_kev_code = KEV_ND6_RTR_EXPIRED,
5022 		.in6_event_str = "IN6_NDP_RTR_EXPIRY",
5023 	},
5024 	{
5025 		.in6_event_code = IN6_NDP_PFX_EXPIRY,
5026 		.in6_event_kev_subclass = KEV_ND6_SUBCLASS,
5027 		.in6_event_kev_code = KEV_ND6_PFX_EXPIRED,
5028 		.in6_event_str = "IN6_NDP_PFX_EXPIRY",
5029 	},
5030 	{
5031 		.in6_event_code = IN6_NDP_ADDR_EXPIRY,
5032 		.in6_event_kev_subclass = KEV_ND6_SUBCLASS,
5033 		.in6_event_kev_code = KEV_ND6_ADDR_EXPIRED,
5034 		.in6_event_str = "IN6_NDP_ADDR_EXPIRY",
5035 	},
5036 };
5037 
5038 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)5039 in6_eventhdlr_callback(struct eventhandler_entry_arg arg0 __unused,
5040     in6_evhdlr_code_t in6_ev_code, struct ifnet *ifp,
5041     struct in6_addr *p_addr6, uint32_t val)
5042 {
5043 	struct kev_msg ev_msg;
5044 	struct kev_nd6_event nd6_event;
5045 
5046 	bzero(&ev_msg, sizeof(ev_msg));
5047 	bzero(&nd6_event, sizeof(nd6_event));
5048 
5049 	nd6log0(info, "%s Event %s received for %s\n",
5050 	    __func__, in6_event2kev_array[in6_ev_code].in6_event_str,
5051 	    ip6_sprintf(p_addr6));
5052 
5053 	ev_msg.vendor_code      = KEV_VENDOR_APPLE;
5054 	ev_msg.kev_class        = KEV_NETWORK_CLASS;
5055 	ev_msg.kev_subclass     =
5056 	    in6_event2kev_array[in6_ev_code].in6_event_kev_subclass;
5057 	ev_msg.event_code       =
5058 	    in6_event2kev_array[in6_ev_code].in6_event_kev_code;
5059 
5060 	nd6_event.link_data.if_family = ifp->if_family;
5061 	nd6_event.link_data.if_unit = ifp->if_unit;
5062 	strlcpy(nd6_event.link_data.if_name, ifp->if_name,
5063 	    sizeof(nd6_event.link_data.if_name));
5064 
5065 	VERIFY(p_addr6 != NULL);
5066 	bcopy(p_addr6, &nd6_event.in6_address,
5067 	    sizeof(nd6_event.in6_address));
5068 	nd6_event.val = val;
5069 
5070 	ev_msg.dv[0].data_ptr = &nd6_event;
5071 	ev_msg.dv[0].data_length = sizeof(nd6_event);
5072 
5073 	kev_post_msg(&ev_msg);
5074 }
5075 
5076 struct in6_event_nwk_wq_entry {
5077 	struct nwk_wq_entry nwk_wqe;
5078 	struct in6_event in6_ev_arg;
5079 };
5080 
5081 static void
in6_event_callback(struct nwk_wq_entry * nwk_item)5082 in6_event_callback(struct nwk_wq_entry *nwk_item)
5083 {
5084 	struct in6_event_nwk_wq_entry *p_ev;
5085 
5086 	p_ev = __container_of(nwk_item, struct in6_event_nwk_wq_entry, nwk_wqe);
5087 
5088 	EVENTHANDLER_INVOKE(&in6_evhdlr_ctxt, in6_event,
5089 	    p_ev->in6_ev_arg.in6_event_code, p_ev->in6_ev_arg.in6_ifp,
5090 	    &p_ev->in6_ev_arg.in6_address, p_ev->in6_ev_arg.val);
5091 
5092 	kfree_type(struct in6_event_nwk_wq_entry, p_ev);
5093 }
5094 
5095 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)5096 in6_event_enqueue_nwk_wq_entry(in6_evhdlr_code_t in6_event_code,
5097     struct ifnet *ifp, struct in6_addr *p_addr6,
5098     uint32_t val)
5099 {
5100 	struct in6_event_nwk_wq_entry *p_in6_ev = NULL;
5101 
5102 	p_in6_ev = kalloc_type(struct in6_event_nwk_wq_entry,
5103 	    Z_WAITOK | Z_ZERO | Z_NOFAIL);
5104 
5105 	p_in6_ev->nwk_wqe.func = in6_event_callback;
5106 	p_in6_ev->in6_ev_arg.in6_event_code = in6_event_code;
5107 	p_in6_ev->in6_ev_arg.in6_ifp = ifp;
5108 	if (p_addr6 != NULL) {
5109 		bcopy(p_addr6, &p_in6_ev->in6_ev_arg.in6_address,
5110 		    sizeof(p_in6_ev->in6_ev_arg.in6_address));
5111 	}
5112 	p_in6_ev->in6_ev_arg.val = val;
5113 
5114 	nwk_wq_enqueue(&p_in6_ev->nwk_wqe);
5115 }
5116 
5117 /*
5118  * Caller must hold in6_ifaddr_rwlock as writer.
5119  */
5120 static void
in6_iahash_remove(struct in6_ifaddr * ia)5121 in6_iahash_remove(struct in6_ifaddr *ia)
5122 {
5123 	LCK_RW_ASSERT(&in6_ifaddr_rwlock, LCK_RW_ASSERT_EXCLUSIVE);
5124 	IFA_LOCK_ASSERT_HELD(&ia->ia_ifa);
5125 
5126 	if (!IA6_IS_HASHED(ia)) {
5127 		panic("%s: attempt to remove wrong ia %p from ipv6 hash table", __func__, ia);
5128 		/* NOTREACHED */
5129 	}
5130 	TAILQ_REMOVE(IN6ADDR_HASH(&ia->ia_addr.sin6_addr), ia, ia6_hash);
5131 	IA6_HASH_INIT(ia);
5132 	if (IFA_REMREF_LOCKED(&ia->ia_ifa) == NULL) {
5133 		panic("%s: unexpected (missing) refcnt ifa=%p", __func__,
5134 		    &ia->ia_ifa);
5135 		/* NOTREACHED */
5136 	}
5137 }
5138 
5139 /*
5140  * Caller must hold in6_ifaddr_rwlock as writer.
5141  */
5142 static void
in6_iahash_insert(struct in6_ifaddr * ia)5143 in6_iahash_insert(struct in6_ifaddr *ia)
5144 {
5145 	LCK_RW_ASSERT(&in6_ifaddr_rwlock, LCK_RW_ASSERT_EXCLUSIVE);
5146 	IFA_LOCK_ASSERT_HELD(&ia->ia_ifa);
5147 
5148 	if (ia->ia_addr.sin6_family != AF_INET6) {
5149 		panic("%s: attempt to insert wrong ia %p into hash table", __func__, ia);
5150 		/* NOTREACHED */
5151 	} else if (IA6_IS_HASHED(ia)) {
5152 		panic("%s: attempt to double-insert ia %p into hash table", __func__, ia);
5153 		/* NOTREACHED */
5154 	}
5155 	TAILQ_INSERT_HEAD(IN6ADDR_HASH(&ia->ia_addr.sin6_addr),
5156 	    ia, ia6_hash);
5157 	IFA_ADDREF_LOCKED(&ia->ia_ifa);
5158 }
5159 
5160 /*
5161  * Some point to point interfaces that are tunnels borrow the address from
5162  * an underlying interface (e.g. VPN server). In order for source address
5163  * selection logic to find the underlying interface first, we add the address
5164  * of borrowing point to point interfaces at the end of the list.
5165  * (see rdar://6733789)
5166  *
5167  * Caller must hold in6_ifaddr_rwlock as writer.
5168  */
5169 static void
in6_iahash_insert_ptp(struct in6_ifaddr * ia)5170 in6_iahash_insert_ptp(struct in6_ifaddr *ia)
5171 {
5172 	struct in6_ifaddr *tmp_ifa;
5173 	struct ifnet *tmp_ifp;
5174 
5175 	LCK_RW_ASSERT(&in6_ifaddr_rwlock, LCK_RW_ASSERT_EXCLUSIVE);
5176 	IFA_LOCK_ASSERT_HELD(&ia->ia_ifa);
5177 
5178 	if (ia->ia_addr.sin6_family != AF_INET6) {
5179 		panic("%s: attempt to insert wrong ia %p into hash table", __func__, ia);
5180 		/* NOTREACHED */
5181 	} else if (IA6_IS_HASHED(ia)) {
5182 		panic("%s: attempt to double-insert ia %p into hash table", __func__, ia);
5183 		/* NOTREACHED */
5184 	}
5185 	IFA_UNLOCK(&ia->ia_ifa);
5186 	TAILQ_FOREACH(tmp_ifa, IN6ADDR_HASH(&ia->ia_addr.sin6_addr), ia6_hash) {
5187 		IFA_LOCK(&tmp_ifa->ia_ifa);
5188 		/* ia->ia_addr won't change, so check without lock */
5189 		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)) {
5190 			IFA_UNLOCK(&tmp_ifa->ia_ifa);
5191 			break;
5192 		}
5193 		IFA_UNLOCK(&tmp_ifa->ia_ifa);
5194 	}
5195 	tmp_ifp = (tmp_ifa == NULL) ? NULL : tmp_ifa->ia_ifp;
5196 
5197 	IFA_LOCK(&ia->ia_ifa);
5198 	if (tmp_ifp == NULL) {
5199 		TAILQ_INSERT_HEAD(IN6ADDR_HASH(&ia->ia_addr.sin6_addr),
5200 		    ia, ia6_hash);
5201 	} else {
5202 		TAILQ_INSERT_TAIL(IN6ADDR_HASH(&ia->ia_addr.sin6_addr),
5203 		    ia, ia6_hash);
5204 	}
5205 	IFA_ADDREF_LOCKED(&ia->ia_ifa);
5206 }
5207 
5208 /*
5209  * ipv6 socket options.
5210  *
5211  * The switch statement below does nothing at runtime, as it serves as a
5212  * compile time check to ensure that all of the ipv6 socket options are
5213  * unique.  This works as long as this routine gets updated each time a
5214  * new ipv6 socket option gets added.
5215  *
5216  * Any failures at compile time indicates duplicated ipv6 socket option
5217  * values.
5218  */
5219 static __attribute__((unused)) void
tcpsockopt_cassert(void)5220 tcpsockopt_cassert(void)
5221 {
5222 	/*
5223 	 * This is equivalent to _CASSERT() and the compiler wouldn't
5224 	 * generate any instructions, thus for compile time only.
5225 	 */
5226 	switch ((int)0) {
5227 	case 0:
5228 
5229 	/* bsd/netinet6/in6.h */
5230 	case IPV6_SOCKOPT_RESERVED1:
5231 	case IPV6_UNICAST_HOPS:
5232 	case IPV6_MULTICAST_IF:
5233 	case IPV6_MULTICAST_HOPS:
5234 	case IPV6_MULTICAST_LOOP:
5235 	case IPV6_JOIN_GROUP:
5236 	case IPV6_LEAVE_GROUP:
5237 	case IPV6_PORTRANGE:
5238 	case ICMP6_FILTER:
5239 	case IPV6_2292PKTINFO:
5240 	case IPV6_2292HOPLIMIT:
5241 	case IPV6_2292NEXTHOP:
5242 	case IPV6_2292HOPOPTS:
5243 	case IPV6_2292DSTOPTS:
5244 	case IPV6_2292RTHDR:
5245 	case IPV6_2292PKTOPTIONS:
5246 #ifdef __APPLE_USE_RFC_2292
5247 // #define IPV6_PKTINFO    IPV6_3542PKTINFO
5248 // #define IPV6_HOPLIMIT   IPV6_3542HOPLIMIT
5249 // #define IPV6_NEXTHOP    IPV6_3542NEXTHOP
5250 // #define IPV6_HOPOPTS    IPV6_3542HOPOPTS
5251 // #define IPV6_DSTOPTS    IPV6_3542DSTOPTS
5252 // #define IPV6_RTHDR      IPV6_3542RTHDR
5253 	case IPV6_PKTOPTIONS:
5254 #endif /* __APPLE_USE_RFC_2292 */
5255 	case IPV6_CHECKSUM:
5256 	case IPV6_V6ONLY:
5257 #ifndef KERNEL
5258 // #define IPV6_BINDV6ONLY         IPV6_V6ONLY
5259 #endif /* KERNEL */
5260 	case IPV6_IPSEC_POLICY:
5261 	case IPV6_FAITH:
5262 	case IPV6_FW_ADD:
5263 	case IPV6_FW_DEL:
5264 	case IPV6_FW_FLUSH:
5265 	case IPV6_FW_ZERO:
5266 	case IPV6_FW_GET:
5267 	case IPV6_RECVTCLASS:
5268 	case IPV6_TCLASS:
5269 #ifdef __APPLE_USE_RFC_3542
5270 	case IPV6_RTHDRDSTOPTS:
5271 	case IPV6_RECVPKTINFO:
5272 	case IPV6_RECVHOPLIMIT:
5273 	case IPV6_RECVRTHDR:
5274 	case IPV6_RECVHOPOPTS:
5275 	case IPV6_RECVDSTOPTS:
5276 #ifdef KERNEL
5277 	case IPV6_RECVRTHDRDSTOPTS:
5278 #endif
5279 	case IPV6_USE_MIN_MTU:
5280 	case IPV6_RECVPATHMTU:
5281 	case IPV6_PATHMTU:
5282 	case IPV6_3542PKTINFO:
5283 	case IPV6_3542HOPLIMIT:
5284 	case IPV6_3542NEXTHOP:
5285 	case IPV6_3542HOPOPTS:
5286 	case IPV6_3542DSTOPTS:
5287 	case IPV6_3542RTHDR:
5288 // #define IPV6_PKTINFO    IPV6_3542PKTINFO
5289 // #define IPV6_HOPLIMIT   IPV6_3542HOPLIMIT
5290 // #define IPV6_NEXTHOP    IPV6_3542NEXTHOP
5291 // #define IPV6_HOPOPTS    IPV6_3542HOPOPTS
5292 // #define IPV6_DSTOPTS    IPV6_3542DSTOPTS
5293 // #define IPV6_RTHDR      IPV6_3542RTHDR
5294 	case IPV6_AUTOFLOWLABEL:
5295 	case IPV6_DONTFRAG:
5296 	case IPV6_PREFER_TEMPADDR:
5297 	case IPV6_MSFILTER:
5298 #endif /* __APPLE_USE_RFC_3542 */
5299 	case IPV6_BOUND_IF:
5300 
5301 	/* bsd/netinet6/in6_private.h */
5302 	case IPV6_NO_IFT_CELLULAR:
5303 	case IPV6_OUT_IF:
5304 		;
5305 	}
5306 }
5307