xref: /xnu-8020.101.4/bsd/netinet6/in6_src.c (revision e7776783b89a353188416a9a346c6cdb4928faad)
1 /*
2  * Copyright (c) 2000-2021 Apple Inc. All rights reserved.
3  *
4  * @APPLE_OSREFERENCE_LICENSE_HEADER_START@
5  *
6  * This file contains Original Code and/or Modifications of Original Code
7  * as defined in and that are subject to the Apple Public Source License
8  * Version 2.0 (the 'License'). You may not use this file except in
9  * compliance with the License. The rights granted to you under the License
10  * may not be used to create, or enable the creation or redistribution of,
11  * unlawful or unlicensed copies of an Apple operating system, or to
12  * circumvent, violate, or enable the circumvention or violation of, any
13  * terms of an Apple operating system software license agreement.
14  *
15  * Please obtain a copy of the License at
16  * http://www.opensource.apple.com/apsl/ and read it before using this file.
17  *
18  * The Original Code and all software distributed under the License are
19  * distributed on an 'AS IS' basis, WITHOUT WARRANTY OF ANY KIND, EITHER
20  * EXPRESS OR IMPLIED, AND APPLE HEREBY DISCLAIMS ALL SUCH WARRANTIES,
21  * INCLUDING WITHOUT LIMITATION, ANY WARRANTIES OF MERCHANTABILITY,
22  * FITNESS FOR A PARTICULAR PURPOSE, QUIET ENJOYMENT OR NON-INFRINGEMENT.
23  * Please see the License for the specific language governing rights and
24  * limitations under the License.
25  *
26  * @APPLE_OSREFERENCE_LICENSE_HEADER_END@
27  */
28 
29 /*
30  * Copyright (C) 1995, 1996, 1997, and 1998 WIDE Project.
31  * All rights reserved.
32  *
33  * Redistribution and use in source and binary forms, with or without
34  * modification, are permitted provided that the following conditions
35  * are met:
36  * 1. Redistributions of source code must retain the above copyright
37  *    notice, this list of conditions and the following disclaimer.
38  * 2. Redistributions in binary form must reproduce the above copyright
39  *    notice, this list of conditions and the following disclaimer in the
40  *    documentation and/or other materials provided with the distribution.
41  * 3. Neither the name of the project nor the names of its contributors
42  *    may be used to endorse or promote products derived from this software
43  *    without specific prior written permission.
44  *
45  * THIS SOFTWARE IS PROVIDED BY THE PROJECT AND CONTRIBUTORS ``AS IS'' AND
46  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
47  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
48  * ARE DISCLAIMED.  IN NO EVENT SHALL THE PROJECT OR CONTRIBUTORS BE LIABLE
49  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
50  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
51  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
52  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
53  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
54  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
55  * SUCH DAMAGE.
56  */
57 
58 /*
59  * Copyright (c) 1982, 1986, 1991, 1993
60  *	The Regents of the University of California.  All rights reserved.
61  *
62  * Redistribution and use in source and binary forms, with or without
63  * modification, are permitted provided that the following conditions
64  * are met:
65  * 1. Redistributions of source code must retain the above copyright
66  *    notice, this list of conditions and the following disclaimer.
67  * 2. Redistributions in binary form must reproduce the above copyright
68  *    notice, this list of conditions and the following disclaimer in the
69  *    documentation and/or other materials provided with the distribution.
70  * 3. All advertising materials mentioning features or use of this software
71  *    must display the following acknowledgement:
72  *	This product includes software developed by the University of
73  *	California, Berkeley and its contributors.
74  * 4. Neither the name of the University nor the names of its contributors
75  *    may be used to endorse or promote products derived from this software
76  *    without specific prior written permission.
77  *
78  * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
79  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
80  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
81  * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
82  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
83  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
84  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
85  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
86  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
87  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
88  * SUCH DAMAGE.
89  *
90  *	@(#)in_pcb.c	8.2 (Berkeley) 1/4/94
91  */
92 
93 
94 #include <sys/param.h>
95 #include <sys/systm.h>
96 #include <sys/malloc.h>
97 #include <sys/mbuf.h>
98 #include <sys/protosw.h>
99 #include <sys/socket.h>
100 #include <sys/socketvar.h>
101 #include <sys/errno.h>
102 #include <sys/time.h>
103 #include <sys/proc.h>
104 #include <sys/sysctl.h>
105 #include <sys/kauth.h>
106 #include <sys/priv.h>
107 #include <kern/locks.h>
108 #include <sys/random.h>
109 
110 #include <net/if.h>
111 #include <net/if_types.h>
112 #include <net/route.h>
113 #include <net/restricted_in_port.h>
114 
115 #include <netinet/in.h>
116 #include <netinet/in_var.h>
117 #include <netinet/in_systm.h>
118 #include <netinet/ip.h>
119 #include <netinet/in_pcb.h>
120 
121 #include <netinet6/in6_var.h>
122 #include <netinet/ip6.h>
123 #include <netinet6/in6_pcb.h>
124 #include <netinet6/ip6_var.h>
125 #include <netinet6/scope6_var.h>
126 #include <netinet6/nd6.h>
127 
128 #include <net/net_osdep.h>
129 
130 #include "loop.h"
131 
132 SYSCTL_DECL(_net_inet6_ip6);
133 
134 static int ip6_select_srcif_debug = 0;
135 SYSCTL_INT(_net_inet6_ip6, OID_AUTO, select_srcif_debug,
136     CTLFLAG_RW | CTLFLAG_LOCKED, &ip6_select_srcif_debug, 0,
137     "log source interface selection debug info");
138 
139 static int ip6_select_srcaddr_debug = 0;
140 SYSCTL_INT(_net_inet6_ip6, OID_AUTO, select_srcaddr_debug,
141     CTLFLAG_RW | CTLFLAG_LOCKED, &ip6_select_srcaddr_debug, 0,
142     "log source address selection debug info");
143 
144 static int ip6_select_src_expensive_secondary_if = 0;
145 SYSCTL_INT(_net_inet6_ip6, OID_AUTO, select_src_expensive_secondary_if,
146     CTLFLAG_RW | CTLFLAG_LOCKED, &ip6_select_src_expensive_secondary_if, 0,
147     "allow source interface selection to use expensive secondaries");
148 
149 static int ip6_select_src_strong_end = 1;
150 SYSCTL_INT(_net_inet6_ip6, OID_AUTO, select_src_strong_end,
151     CTLFLAG_RW | CTLFLAG_LOCKED, &ip6_select_src_strong_end, 0,
152     "limit source address selection to outgoing interface");
153 
154 #define ADDR_LABEL_NOTAPP (-1)
155 struct in6_addrpolicy defaultaddrpolicy;
156 
157 int ip6_prefer_tempaddr = 1;
158 
159 int ip6_cga_conflict_retries = IPV6_CGA_CONFLICT_RETRIES_DEFAULT;
160 
161 #ifdef ENABLE_ADDRSEL
162 static LCK_MTX_DECLARE_ATTR(addrsel_mutex, &ip6_mutex_grp, &ip6_mutex_attr);
163 #define ADDRSEL_LOCK()          lck_mtx_lock(&addrsel_mutex)
164 #define ADDRSEL_UNLOCK()        lck_mtx_unlock(&addrsel_mutex)
165 #else
166 #define ADDRSEL_LOCK()
167 #define ADDRSEL_UNLOCK()
168 #endif
169 extern int      udp_use_randomport;
170 extern int      tcp_use_randomport;
171 
172 static int selectroute(struct sockaddr_in6 *, struct sockaddr_in6 *,
173     struct ip6_pktopts *, struct ip6_moptions *, struct in6_ifaddr **,
174     struct route_in6 *, struct ifnet **, struct rtentry **, int, int,
175     struct ip6_out_args *ip6oa);
176 static int in6_selectif(struct sockaddr_in6 *, struct ip6_pktopts *,
177     struct ip6_moptions *, struct route_in6 *ro,
178     struct ip6_out_args *, struct ifnet **);
179 static void init_policy_queue(void);
180 static int add_addrsel_policyent(const struct in6_addrpolicy *);
181 #ifdef ENABLE_ADDRSEL
182 static int delete_addrsel_policyent(const struct in6_addrpolicy *);
183 #endif
184 static int walk_addrsel_policy(int (*)(const struct in6_addrpolicy *, void *),
185     void *);
186 static int dump_addrsel_policyent(const struct in6_addrpolicy *, void *);
187 static struct in6_addrpolicy *match_addrsel_policy(struct sockaddr_in6 *);
188 void addrsel_policy_init(void);
189 
190 #define SASEL_DO_DBG(inp) \
191 	(ip6_select_srcaddr_debug && (inp) != NULL && \
192 	    (inp)->inp_socket != NULL && \
193 	    ((inp)->inp_socket->so_options & SO_DEBUG))
194 
195 #define SASEL_LOG(fmt, ...) \
196 do { \
197 	if (srcsel_debug) \
198 	        os_log(OS_LOG_DEFAULT, "%s:%d " fmt,\
199 	            __FUNCTION__, __LINE__, ##__VA_ARGS__); \
200 } while (0); \
201 
202 /*
203  * Return an IPv6 address, which is the most appropriate for a given
204  * destination and user specified options.
205  * If necessary, this function lookups the routing table and returns
206  * an entry to the caller for later use.
207  */
208 #define REPLACE(r) do {\
209 	SASEL_LOG("REPLACE r %d ia %s ifp1 %s\n", \
210 	    (r), s_src, ifp1->if_xname); \
211 	srcrule = (r); \
212 	goto replace; \
213 } while (0)
214 
215 #define NEXTSRC(r) do {\
216 	SASEL_LOG("NEXTSRC r %d ia %s ifp1 %s\n", \
217 	    (r), s_src, ifp1->if_xname); \
218 	goto next;              /* XXX: we can't use 'continue' here */ \
219 } while (0)
220 
221 #define BREAK(r) do { \
222 	SASEL_LOG("BREAK r %d ia %s ifp1 %s\n", \
223 	    (r), s_src, ifp1->if_xname); \
224 	srcrule = (r); \
225 	goto out;               /* XXX: we can't use 'break' here */ \
226 } while (0)
227 
228 
229 struct ifaddr *
in6_selectsrc_core_ifa(struct sockaddr_in6 * addr,struct ifnet * ifp,int srcsel_debug)230 in6_selectsrc_core_ifa(struct sockaddr_in6 *addr, struct ifnet *ifp, int srcsel_debug)
231 {
232 	int err = 0;
233 	struct ifnet *src_ifp = NULL;
234 	struct in6_addr src_storage = {};
235 	struct in6_addr *in6 = NULL;
236 	struct ifaddr *ifa = NULL;
237 
238 	if ((in6 = in6_selectsrc_core(addr,
239 	    (ip6_prefer_tempaddr ? IPV6_SRCSEL_HINT_PREFER_TMPADDR : 0),
240 	    ifp, 0, &src_storage, &src_ifp, &err, &ifa)) == NULL) {
241 		if (err == 0) {
242 			err = EADDRNOTAVAIL;
243 		}
244 		VERIFY(src_ifp == NULL);
245 		if (ifa != NULL) {
246 			IFA_REMREF(ifa);
247 			ifa = NULL;
248 		}
249 		goto done;
250 	}
251 
252 	if (src_ifp != ifp) {
253 		if (err == 0) {
254 			err = ENETUNREACH;
255 		}
256 		if (ifa != NULL) {
257 			IFA_REMREF(ifa);
258 			ifa = NULL;
259 		}
260 		goto done;
261 	}
262 
263 	VERIFY(ifa != NULL);
264 	ifnet_lock_shared(ifp);
265 	if ((ifa->ifa_debug & IFD_DETACHING) != 0) {
266 		err = EHOSTUNREACH;
267 		ifnet_lock_done(ifp);
268 		IFA_REMREF(ifa);
269 		ifa = NULL;
270 		goto done;
271 	}
272 	ifnet_lock_done(ifp);
273 
274 done:
275 	SASEL_LOG("Returned with error: %d", err);
276 	if (src_ifp != NULL) {
277 		ifnet_release(src_ifp);
278 	}
279 	return ifa;
280 }
281 
282 struct in6_addr *
in6_selectsrc_core(struct sockaddr_in6 * dstsock,uint32_t hint_mask,struct ifnet * ifp,int srcsel_debug,struct in6_addr * src_storage,struct ifnet ** sifp,int * errorp,struct ifaddr ** ifapp)283 in6_selectsrc_core(struct sockaddr_in6 *dstsock, uint32_t hint_mask,
284     struct ifnet *ifp, int srcsel_debug, struct in6_addr *src_storage,
285     struct ifnet **sifp, int *errorp, struct ifaddr **ifapp)
286 {
287 	u_int32_t odstzone;
288 	int bestrule = IP6S_SRCRULE_0;
289 	struct in6_addrpolicy *dst_policy = NULL, *best_policy = NULL;
290 	struct in6_addr dst;
291 	struct in6_ifaddr *ia = NULL, *ia_best = NULL;
292 	char s_src[MAX_IPv6_STR_LEN] = {0};
293 	char s_dst[MAX_IPv6_STR_LEN] = {0};
294 	const struct in6_addr *tmp = NULL;
295 	int dst_scope = -1, best_scope = -1, best_matchlen = -1;
296 	uint64_t secs = net_uptime();
297 	VERIFY(dstsock != NULL);
298 	VERIFY(src_storage != NULL);
299 	VERIFY(ifp != NULL);
300 
301 	if (sifp != NULL) {
302 		*sifp = NULL;
303 	}
304 
305 	if (ifapp != NULL) {
306 		*ifapp = NULL;
307 	}
308 
309 	dst = dstsock->sin6_addr; /* make a copy for local operation */
310 
311 	if (srcsel_debug) {
312 		(void) inet_ntop(AF_INET6, &dst, s_dst, sizeof(s_src));
313 
314 		tmp = &in6addr_any;
315 		(void) inet_ntop(AF_INET6, tmp, s_src, sizeof(s_src));
316 		os_log(OS_LOG_DEFAULT, "%s out src %s dst %s ifp %s",
317 		    __func__, s_src, s_dst, ifp->if_xname);
318 	}
319 
320 	*errorp = in6_setscope(&dst, ifp, &odstzone);
321 	if (*errorp != 0) {
322 		src_storage = NULL;
323 		goto done;
324 	}
325 
326 	lck_rw_lock_shared(&in6_ifaddr_rwlock);
327 	TAILQ_FOREACH(ia, &in6_ifaddrhead, ia6_link) {
328 		int new_scope = -1, new_matchlen = -1;
329 		struct in6_addrpolicy *new_policy = NULL;
330 		u_int32_t srczone = 0, osrczone, dstzone;
331 		struct in6_addr src;
332 		struct ifnet *ifp1 = ia->ia_ifp;
333 		int srcrule;
334 
335 		if (srcsel_debug) {
336 			(void) inet_ntop(AF_INET6, &ia->ia_addr.sin6_addr,
337 			    s_src, sizeof(s_src));
338 		}
339 
340 		IFA_LOCK(&ia->ia_ifa);
341 
342 		/*
343 		 * Simply skip addresses reserved for CLAT46
344 		 */
345 		if (ia->ia6_flags & IN6_IFF_CLAT46) {
346 			SASEL_LOG("NEXT ia %s address on ifp1 %s skipped as it is "
347 			    "reserved for CLAT46", s_src, ifp1->if_xname);
348 			goto next;
349 		}
350 
351 		/*
352 		 * XXX By default we are strong end system and will
353 		 * limit candidate set of source address to the ones
354 		 * configured on the outgoing interface.
355 		 */
356 		if (ip6_select_src_strong_end &&
357 		    ifp1 != ifp) {
358 			SASEL_LOG("NEXT ia %s ifp1 %s address is not on outgoing "
359 			    "interface \n", s_src, ifp1->if_xname);
360 			goto next;
361 		}
362 
363 		/*
364 		 * We'll never take an address that breaks the scope zone
365 		 * of the destination. We also skip an address if its zone
366 		 * does not contain the outgoing interface.
367 		 * XXX: we should probably use sin6_scope_id here.
368 		 */
369 		if (in6_setscope(&dst, ifp1, &dstzone) ||
370 		    odstzone != dstzone) {
371 			SASEL_LOG("NEXT ia %s ifp1 %s odstzone %d != dstzone %d\n",
372 			    s_src, ifp1->if_xname, odstzone, dstzone);
373 			goto next;
374 		}
375 		src = ia->ia_addr.sin6_addr;
376 		if (in6_setscope(&src, ifp, &osrczone) ||
377 		    in6_setscope(&src, ifp1, &srczone) ||
378 		    osrczone != srczone) {
379 			SASEL_LOG("NEXT ia %s ifp1 %s osrczone %d != srczone %d\n",
380 			    s_src, ifp1->if_xname, osrczone, srczone);
381 			goto next;
382 		}
383 		/* avoid unusable addresses */
384 		if ((ia->ia6_flags &
385 		    (IN6_IFF_NOTREADY | IN6_IFF_ANYCAST | IN6_IFF_DETACHED))) {
386 			SASEL_LOG("NEXT ia %s ifp1 %s ia6_flags 0x%x\n",
387 			    s_src, ifp1->if_xname, ia->ia6_flags);
388 			goto next;
389 		}
390 		if (!ip6_use_deprecated && IFA6_IS_DEPRECATED(ia, secs)) {
391 			SASEL_LOG("NEXT ia %s ifp1 %s IFA6_IS_DEPRECATED\n",
392 			    s_src, ifp1->if_xname);
393 			goto next;
394 		}
395 		if (!nd6_optimistic_dad &&
396 		    (ia->ia6_flags & IN6_IFF_OPTIMISTIC) != 0) {
397 			SASEL_LOG("NEXT ia %s ifp1 %s IN6_IFF_OPTIMISTIC\n",
398 			    s_src, ifp1->if_xname);
399 			goto next;
400 		}
401 		/* Rule 1: Prefer same address */
402 		if (in6_are_addr_equal_scoped(&dst, &ia->ia_addr.sin6_addr, dstzone, srczone)) {
403 			BREAK(IP6S_SRCRULE_1); /* there should be no better candidate */
404 		}
405 		if (ia_best == NULL) {
406 			REPLACE(IP6S_SRCRULE_0);
407 		}
408 
409 		/* Rule 2: Prefer appropriate scope */
410 		if (dst_scope < 0) {
411 			dst_scope = in6_addrscope(&dst);
412 		}
413 		new_scope = in6_addrscope(&ia->ia_addr.sin6_addr);
414 		if (IN6_ARE_SCOPE_CMP(best_scope, new_scope) < 0) {
415 			if (IN6_ARE_SCOPE_CMP(best_scope, dst_scope) < 0) {
416 				REPLACE(IP6S_SRCRULE_2);
417 			}
418 			NEXTSRC(IP6S_SRCRULE_2);
419 		} else if (IN6_ARE_SCOPE_CMP(new_scope, best_scope) < 0) {
420 			if (IN6_ARE_SCOPE_CMP(new_scope, dst_scope) < 0) {
421 				NEXTSRC(IP6S_SRCRULE_2);
422 			}
423 			REPLACE(IP6S_SRCRULE_2);
424 		}
425 
426 		/*
427 		 * Rule 3: Avoid deprecated addresses.  Note that the case of
428 		 * !ip6_use_deprecated is already rejected above.
429 		 */
430 		if (!IFA6_IS_DEPRECATED(ia_best, secs) &&
431 		    IFA6_IS_DEPRECATED(ia, secs)) {
432 			NEXTSRC(IP6S_SRCRULE_3);
433 		}
434 		if (IFA6_IS_DEPRECATED(ia_best, secs) &&
435 		    !IFA6_IS_DEPRECATED(ia, secs)) {
436 			REPLACE(IP6S_SRCRULE_3);
437 		}
438 
439 		/*
440 		 * RFC 4429 says that optimistic addresses are equivalent to
441 		 * deprecated addresses, so avoid them here.
442 		 */
443 		if ((ia_best->ia6_flags & IN6_IFF_OPTIMISTIC) == 0 &&
444 		    (ia->ia6_flags & IN6_IFF_OPTIMISTIC) != 0) {
445 			NEXTSRC(IP6S_SRCRULE_3);
446 		}
447 		if ((ia_best->ia6_flags & IN6_IFF_OPTIMISTIC) != 0 &&
448 		    (ia->ia6_flags & IN6_IFF_OPTIMISTIC) == 0) {
449 			REPLACE(IP6S_SRCRULE_3);
450 		}
451 
452 		/* Rule 4: Prefer home addresses */
453 		/*
454 		 * XXX: This is a TODO.  We should probably merge the MIP6
455 		 * case above.
456 		 */
457 
458 		/* Rule 5: Prefer outgoing interface */
459 		/*
460 		 * XXX By default we are strong end with source address
461 		 * selection. That means all address selection candidate
462 		 * addresses will be the ones hosted on the outgoing interface
463 		 * making the following check redundant.
464 		 */
465 		if (ip6_select_src_strong_end == 0) {
466 			if (ia_best->ia_ifp == ifp && ia->ia_ifp != ifp) {
467 				NEXTSRC(IP6S_SRCRULE_5);
468 			}
469 			if (ia_best->ia_ifp != ifp && ia->ia_ifp == ifp) {
470 				REPLACE(IP6S_SRCRULE_5);
471 			}
472 		}
473 
474 		/*
475 		 * Rule 6: Prefer matching label
476 		 * Note that best_policy should be non-NULL here.
477 		 */
478 		if (dst_policy == NULL) {
479 			dst_policy = in6_addrsel_lookup_policy(dstsock);
480 		}
481 		if (dst_policy->label != ADDR_LABEL_NOTAPP) {
482 			new_policy = in6_addrsel_lookup_policy(&ia->ia_addr);
483 			if (dst_policy->label == best_policy->label &&
484 			    dst_policy->label != new_policy->label) {
485 				NEXTSRC(IP6S_SRCRULE_6);
486 			}
487 			if (dst_policy->label != best_policy->label &&
488 			    dst_policy->label == new_policy->label) {
489 				REPLACE(IP6S_SRCRULE_6);
490 			}
491 		}
492 
493 		/*
494 		 * Rule 7: Prefer temporary addresses.
495 		 * We allow users to reverse the logic by configuring
496 		 * a sysctl variable, so that transparency conscious users can
497 		 * always prefer stable addresses.
498 		 */
499 		if (!(ia_best->ia6_flags & IN6_IFF_TEMPORARY) &&
500 		    (ia->ia6_flags & IN6_IFF_TEMPORARY)) {
501 			if (hint_mask & IPV6_SRCSEL_HINT_PREFER_TMPADDR) {
502 				REPLACE(IP6S_SRCRULE_7);
503 			} else {
504 				NEXTSRC(IP6S_SRCRULE_7);
505 			}
506 		}
507 		if ((ia_best->ia6_flags & IN6_IFF_TEMPORARY) &&
508 		    !(ia->ia6_flags & IN6_IFF_TEMPORARY)) {
509 			if (hint_mask & IPV6_SRCSEL_HINT_PREFER_TMPADDR) {
510 				NEXTSRC(IP6S_SRCRULE_7);
511 			} else {
512 				REPLACE(IP6S_SRCRULE_7);
513 			}
514 		}
515 
516 		/*
517 		 * Rule 7x: prefer addresses on alive interfaces.
518 		 * This is a KAME specific rule.
519 		 */
520 		if ((ia_best->ia_ifp->if_flags & IFF_UP) &&
521 		    !(ia->ia_ifp->if_flags & IFF_UP)) {
522 			NEXTSRC(IP6S_SRCRULE_7x);
523 		}
524 		if (!(ia_best->ia_ifp->if_flags & IFF_UP) &&
525 		    (ia->ia_ifp->if_flags & IFF_UP)) {
526 			REPLACE(IP6S_SRCRULE_7x);
527 		}
528 
529 		/*
530 		 * Rule 8: Use longest matching prefix.
531 		 */
532 		new_matchlen = in6_matchlen(&ia->ia_addr.sin6_addr, &dst);
533 		if (best_matchlen < new_matchlen) {
534 			REPLACE(IP6S_SRCRULE_8);
535 		}
536 		if (new_matchlen < best_matchlen) {
537 			NEXTSRC(IP6S_SRCRULE_8);
538 		}
539 
540 		/*
541 		 * Last resort: just keep the current candidate.
542 		 * Or, do we need more rules?
543 		 */
544 		if (ifp1 != ifp && (ifp1->if_eflags & IFEF_EXPENSIVE) &&
545 		    ip6_select_src_expensive_secondary_if == 0) {
546 			SASEL_LOG("NEXT ia %s ifp1 %s IFEF_EXPENSIVE\n",
547 			    s_src, ifp1->if_xname);
548 			ip6stat.ip6s_sources_skip_expensive_secondary_if++;
549 			goto next;
550 		}
551 		SASEL_LOG("NEXT ia %s ifp1 %s last resort\n",
552 		    s_src, ifp1->if_xname);
553 		IFA_UNLOCK(&ia->ia_ifa);
554 		continue;
555 
556 replace:
557 		/*
558 		 * Ignore addresses on secondary interfaces that are marked
559 		 * expensive
560 		 */
561 		if (ifp1 != ifp && (ifp1->if_eflags & IFEF_EXPENSIVE) &&
562 		    ip6_select_src_expensive_secondary_if == 0) {
563 			SASEL_LOG("NEXT ia %s ifp1 %s IFEF_EXPENSIVE\n",
564 			    s_src, ifp1->if_xname);
565 			ip6stat.ip6s_sources_skip_expensive_secondary_if++;
566 			goto next;
567 		}
568 		bestrule = srcrule;
569 		best_scope = (new_scope >= 0 ? new_scope :
570 		    in6_addrscope(&ia->ia_addr.sin6_addr));
571 		best_policy = (new_policy ? new_policy :
572 		    in6_addrsel_lookup_policy(&ia->ia_addr));
573 		best_matchlen = (new_matchlen >= 0 ? new_matchlen :
574 		    in6_matchlen(&ia->ia_addr.sin6_addr, &dst));
575 		SASEL_LOG("NEXT ia %s ifp1 %s best_scope %d new_scope %d dst_scope %d\n",
576 		    s_src, ifp1->if_xname, best_scope, new_scope, dst_scope);
577 		IFA_ADDREF_LOCKED(&ia->ia_ifa); /* for ia_best */
578 		IFA_UNLOCK(&ia->ia_ifa);
579 		if (ia_best != NULL) {
580 			IFA_REMREF(&ia_best->ia_ifa);
581 		}
582 		ia_best = ia;
583 		continue;
584 
585 next:
586 		IFA_UNLOCK(&ia->ia_ifa);
587 		continue;
588 
589 out:
590 		IFA_ADDREF_LOCKED(&ia->ia_ifa); /* for ia_best */
591 		IFA_UNLOCK(&ia->ia_ifa);
592 		if (ia_best != NULL) {
593 			IFA_REMREF(&ia_best->ia_ifa);
594 		}
595 		ia_best = ia;
596 		break;
597 	}
598 
599 	lck_rw_done(&in6_ifaddr_rwlock);
600 
601 	if ((ia = ia_best) == NULL) {
602 		if (*errorp == 0) {
603 			*errorp = EADDRNOTAVAIL;
604 		}
605 		src_storage = NULL;
606 		goto done;
607 	}
608 
609 	if (sifp != NULL) {
610 		*sifp = ia->ia_ifa.ifa_ifp;
611 		ifnet_reference(*sifp);
612 	}
613 
614 	IFA_LOCK_SPIN(&ia->ia_ifa);
615 	if (bestrule < IP6S_SRCRULE_COUNT) {
616 		ip6stat.ip6s_sources_rule[bestrule]++;
617 	}
618 	*src_storage = satosin6(&ia->ia_addr)->sin6_addr;
619 	IFA_UNLOCK(&ia->ia_ifa);
620 
621 	if (ifapp != NULL) {
622 		*ifapp = &ia->ia_ifa;
623 	} else {
624 		IFA_REMREF(&ia->ia_ifa);
625 	}
626 
627 done:
628 	if (srcsel_debug) {
629 		(void) inet_ntop(AF_INET6, &dst, s_dst, sizeof(s_src));
630 
631 		tmp = (src_storage != NULL) ? src_storage : &in6addr_any;
632 		(void) inet_ntop(AF_INET6, tmp, s_src, sizeof(s_src));
633 
634 		os_log(OS_LOG_DEFAULT, "%s out src %s dst %s dst_scope %d best_scope %d",
635 		    __func__, s_src, s_dst, dst_scope, best_scope);
636 	}
637 
638 	return src_storage;
639 }
640 
641 /*
642  * Regardless of error, it will return an ifp with a reference held if the
643  * caller provides a non-NULL ifpp.  The caller is responsible for checking
644  * if the returned ifp is valid and release its reference at all times.
645  */
646 struct in6_addr *
in6_selectsrc(struct sockaddr_in6 * dstsock,struct ip6_pktopts * opts,struct inpcb * inp,struct route_in6 * ro,struct ifnet ** ifpp,struct in6_addr * src_storage,unsigned int ifscope,int * errorp)647 in6_selectsrc(struct sockaddr_in6 *dstsock, struct ip6_pktopts *opts,
648     struct inpcb *inp, struct route_in6 *ro,
649     struct ifnet **ifpp, struct in6_addr *src_storage, unsigned int ifscope,
650     int *errorp)
651 {
652 	struct ifnet *ifp = NULL;
653 	struct in6_pktinfo *pi = NULL;
654 	struct ip6_moptions *mopts;
655 	struct ip6_out_args ip6oa;
656 	boolean_t inp_debug = FALSE;
657 	uint32_t hint_mask = 0;
658 	int prefer_tempaddr = 0;
659 	struct ifnet *sifp = NULL;
660 
661 	bzero(&ip6oa, sizeof(ip6oa));
662 	ip6oa.ip6oa_boundif = ifscope;
663 	ip6oa.ip6oa_flags = IP6OAF_SELECT_SRCIF;
664 	ip6oa.ip6oa_sotc = SO_TC_UNSPEC;
665 	ip6oa.ip6oa_netsvctype = _NET_SERVICE_TYPE_UNSPEC;
666 
667 	*errorp = 0;
668 	if (ifpp != NULL) {
669 		*ifpp = NULL;
670 	}
671 
672 	if (inp != NULL) {
673 		inp_debug = SASEL_DO_DBG(inp);
674 		mopts = inp->in6p_moptions;
675 		if (INP_NO_CELLULAR(inp)) {
676 			ip6oa.ip6oa_flags |= IP6OAF_NO_CELLULAR;
677 		}
678 		if (INP_NO_EXPENSIVE(inp)) {
679 			ip6oa.ip6oa_flags |= IP6OAF_NO_EXPENSIVE;
680 		}
681 		if (INP_NO_CONSTRAINED(inp)) {
682 			ip6oa.ip6oa_flags |= IP6OAF_NO_CONSTRAINED;
683 		}
684 		if (INP_AWDL_UNRESTRICTED(inp)) {
685 			ip6oa.ip6oa_flags |= IP6OAF_AWDL_UNRESTRICTED;
686 		}
687 		if (INP_INTCOPROC_ALLOWED(inp)) {
688 			ip6oa.ip6oa_flags |= IP6OAF_INTCOPROC_ALLOWED;
689 		}
690 	} else {
691 		mopts = NULL;
692 		/* Allow the kernel to retransmit packets. */
693 		ip6oa.ip6oa_flags |= IP6OAF_INTCOPROC_ALLOWED |
694 		    IP6OAF_AWDL_UNRESTRICTED;
695 	}
696 
697 	if (ip6oa.ip6oa_boundif != IFSCOPE_NONE) {
698 		ip6oa.ip6oa_flags |= IP6OAF_BOUND_IF;
699 	}
700 
701 	/*
702 	 * If the source address is explicitly specified by the caller,
703 	 * check if the requested source address is indeed a unicast address
704 	 * assigned to the node, and can be used as the packet's source
705 	 * address.  If everything is okay, use the address as source.
706 	 */
707 	if (opts && (pi = opts->ip6po_pktinfo) &&
708 	    !IN6_IS_ADDR_UNSPECIFIED(&pi->ipi6_addr)) {
709 		struct sockaddr_in6 srcsock;
710 		struct in6_ifaddr *ia6;
711 
712 		/* get the outgoing interface */
713 		if ((*errorp = in6_selectif(dstsock, opts, mopts, ro, &ip6oa,
714 		    &ifp)) != 0) {
715 			src_storage = NULL;
716 			goto done;
717 		}
718 
719 		/*
720 		 * determine the appropriate zone id of the source based on
721 		 * the zone of the destination and the outgoing interface.
722 		 * If the specified address is ambiguous wrt the scope zone,
723 		 * the interface must be specified; otherwise, ifa_ifwithaddr()
724 		 * will fail matching the address.
725 		 */
726 		bzero(&srcsock, sizeof(srcsock));
727 		srcsock.sin6_family = AF_INET6;
728 		srcsock.sin6_len = sizeof(srcsock);
729 		srcsock.sin6_addr = pi->ipi6_addr;
730 		if (ifp != NULL) {
731 			*errorp = in6_setscope(&srcsock.sin6_addr, ifp, IN6_NULL_IF_EMBEDDED_SCOPE(&srcsock.sin6_scope_id));
732 			if (*errorp != 0) {
733 				src_storage = NULL;
734 				goto done;
735 			}
736 		}
737 		ia6 = (struct in6_ifaddr *)ifa_ifwithaddr((struct sockaddr *)
738 		    (&srcsock));
739 		if (ia6 == NULL) {
740 			*errorp = EADDRNOTAVAIL;
741 			src_storage = NULL;
742 			goto done;
743 		}
744 		IFA_LOCK_SPIN(&ia6->ia_ifa);
745 		if ((ia6->ia6_flags & (IN6_IFF_ANYCAST | IN6_IFF_NOTREADY | IN6_IFF_CLAT46)) ||
746 		    (inp && inp_restricted_send(inp, ia6->ia_ifa.ifa_ifp))) {
747 			IFA_UNLOCK(&ia6->ia_ifa);
748 			IFA_REMREF(&ia6->ia_ifa);
749 			*errorp = EHOSTUNREACH;
750 			src_storage = NULL;
751 			goto done;
752 		}
753 
754 		*src_storage = satosin6(&ia6->ia_addr)->sin6_addr;
755 		IFA_UNLOCK(&ia6->ia_ifa);
756 		IFA_REMREF(&ia6->ia_ifa);
757 		goto done;
758 	}
759 
760 	/*
761 	 * Otherwise, if the socket has already bound the source, just use it.
762 	 */
763 	if (inp != NULL && !IN6_IS_ADDR_UNSPECIFIED(&inp->in6p_laddr)) {
764 		src_storage = &inp->in6p_laddr;
765 		goto done;
766 	}
767 
768 	/*
769 	 * If the address is not specified, choose the best one based on
770 	 * the outgoing interface and the destination address.
771 	 */
772 	/* get the outgoing interface */
773 	if ((*errorp = in6_selectif(dstsock, opts, mopts, ro, &ip6oa,
774 	    &ifp)) != 0) {
775 		src_storage = NULL;
776 		goto done;
777 	}
778 
779 	VERIFY(ifp != NULL);
780 
781 	if (opts == NULL ||
782 	    opts->ip6po_prefer_tempaddr == IP6PO_TEMPADDR_SYSTEM) {
783 		prefer_tempaddr = ip6_prefer_tempaddr;
784 	} else if (opts->ip6po_prefer_tempaddr == IP6PO_TEMPADDR_NOTPREFER) {
785 		prefer_tempaddr = 0;
786 	} else {
787 		prefer_tempaddr = 1;
788 	}
789 
790 	if (prefer_tempaddr) {
791 		hint_mask |= IPV6_SRCSEL_HINT_PREFER_TMPADDR;
792 	}
793 
794 	if (in6_selectsrc_core(dstsock, hint_mask, ifp, inp_debug, src_storage,
795 	    &sifp, errorp, NULL) == NULL) {
796 		src_storage = NULL;
797 		goto done;
798 	}
799 
800 	VERIFY(sifp != NULL);
801 
802 	if (inp && inp_restricted_send(inp, sifp)) {
803 		src_storage = NULL;
804 		*errorp = EHOSTUNREACH;
805 		ifnet_release(sifp);
806 		goto done;
807 	} else {
808 		ifnet_release(sifp);
809 	}
810 
811 done:
812 	if (ifpp != NULL) {
813 		/* if ifp is non-NULL, refcnt held in in6_selectif() */
814 		*ifpp = ifp;
815 	} else if (ifp != NULL) {
816 		ifnet_release(ifp);
817 	}
818 	return src_storage;
819 }
820 
821 /*
822  * Given a source IPv6 address (and route, if available), determine the best
823  * interface to send the packet from.  Checking for (and updating) the
824  * ROF_SRCIF_SELECTED flag in the pcb-supplied route placeholder is done
825  * without any locks, based on the assumption that in the event this is
826  * called from ip6_output(), the output operation is single-threaded per-pcb,
827  * i.e. for any given pcb there can only be one thread performing output at
828  * the IPv6 layer.
829  *
830  * This routine is analogous to in_selectsrcif() for IPv4.  Regardless of
831  * error, it will return an ifp with a reference held if the caller provides
832  * a non-NULL retifp.  The caller is responsible for checking if the
833  * returned ifp is valid and release its reference at all times.
834  *
835  * clone - meaningful only for bsdi and freebsd
836  */
837 static int
selectroute(struct sockaddr_in6 * srcsock,struct sockaddr_in6 * dstsock,struct ip6_pktopts * opts,struct ip6_moptions * mopts,struct in6_ifaddr ** retsrcia,struct route_in6 * ro,struct ifnet ** retifp,struct rtentry ** retrt,int clone,int norouteok,struct ip6_out_args * ip6oa)838 selectroute(struct sockaddr_in6 *srcsock, struct sockaddr_in6 *dstsock,
839     struct ip6_pktopts *opts, struct ip6_moptions *mopts,
840     struct in6_ifaddr **retsrcia, struct route_in6 *ro,
841     struct ifnet **retifp, struct rtentry **retrt, int clone,
842     int norouteok, struct ip6_out_args *ip6oa)
843 {
844 	int error = 0;
845 	struct ifnet *ifp = NULL, *ifp0 = NULL;
846 	struct route_in6 *route = NULL;
847 	struct sockaddr_in6 *sin6_next;
848 	struct in6_pktinfo *pi = NULL;
849 	struct in6_addr *dst = &dstsock->sin6_addr;
850 	struct ifaddr *ifa = NULL;
851 	char s_src[MAX_IPv6_STR_LEN], s_dst[MAX_IPv6_STR_LEN];
852 	boolean_t select_srcif, proxied_ifa = FALSE, local_dst = FALSE;
853 	unsigned int ifscope = ((ip6oa != NULL) ?
854 	    ip6oa->ip6oa_boundif : IFSCOPE_NONE);
855 	boolean_t is_direct = FALSE;
856 
857 	if (retifp != NULL) {
858 		*retifp = NULL;
859 	}
860 
861 	if (retrt != NULL) {
862 		*retrt = NULL;
863 	}
864 
865 	if (ip6_select_srcif_debug) {
866 		struct in6_addr src;
867 		src = (srcsock != NULL) ? srcsock->sin6_addr : in6addr_any;
868 		(void) inet_ntop(AF_INET6, &src, s_src, sizeof(s_src));
869 		(void) inet_ntop(AF_INET6, dst, s_dst, sizeof(s_dst));
870 	}
871 
872 	/*
873 	 * If the destination address is UNSPECIFIED addr, bail out.
874 	 */
875 	if (IN6_IS_ADDR_UNSPECIFIED(dst)) {
876 		error = EHOSTUNREACH;
877 		goto done;
878 	}
879 
880 	/*
881 	 * Perform source interface selection if Scoped Routing
882 	 * is enabled and a source address that isn't unspecified.
883 	 */
884 	select_srcif = (srcsock != NULL &&
885 	    !IN6_IS_ADDR_UNSPECIFIED(&srcsock->sin6_addr));
886 
887 	/*
888 	 * For scoped routing, if interface scope is 0 or src/dst addr is linklocal
889 	 * or dst addr is multicast, source interface selection should be performed even
890 	 * if the destination is directly reachable.
891 	 */
892 	if (ifscope != IFSCOPE_NONE &&
893 	    !(srcsock != NULL && IN6_IS_ADDR_LINKLOCAL(&srcsock->sin6_addr)) &&
894 	    !IN6_IS_ADDR_MULTICAST(dst) && !IN6_IS_ADDR_LINKLOCAL(dst)) {
895 		struct rtentry *temp_rt = NULL;
896 
897 		lck_mtx_lock(rnh_lock);
898 		temp_rt = rt_lookup(TRUE, (struct sockaddr *)dstsock,
899 		    NULL, rt_tables[AF_INET6], ifscope);
900 		lck_mtx_unlock(rnh_lock);
901 
902 		/*
903 		 * If the destination is directly reachable, relax
904 		 * the behavior around select_srcif, i.e. don't force
905 		 * the packet to go out from the interface that is hosting
906 		 * the source address.
907 		 * It happens when we share v6 with NAT66 and want
908 		 * the external interface's v6 address to be reachable
909 		 * to the clients we are sharing v6 connectivity with
910 		 * using NAT.
911 		 */
912 		if (temp_rt != NULL) {
913 			if ((temp_rt->rt_flags & RTF_GATEWAY) == 0) {
914 				select_srcif = FALSE;
915 				is_direct = TRUE;
916 			}
917 			rtfree(temp_rt);
918 		}
919 	}
920 
921 	if (ip6_select_srcif_debug) {
922 		os_log(OS_LOG_DEFAULT, "%s src %s dst %s ifscope %d "
923 		    "is_direct %d select_srcif %d",
924 		    __func__, s_src, s_dst, ifscope, is_direct, select_srcif);
925 	}
926 
927 	/* If the caller specified the outgoing interface explicitly, use it */
928 	if (opts != NULL && (pi = opts->ip6po_pktinfo) != NULL &&
929 	    pi->ipi6_ifindex != 0) {
930 		/*
931 		 * If IPV6_PKTINFO takes precedence over IPV6_BOUND_IF.
932 		 */
933 		ifscope = pi->ipi6_ifindex;
934 		ifnet_head_lock_shared();
935 		/* ifp may be NULL if detached or out of range */
936 		ifp = ifp0 =
937 		    ((ifscope <= if_index) ? ifindex2ifnet[ifscope] : NULL);
938 		ifnet_head_done();
939 		if (norouteok || retrt == NULL || IN6_IS_ADDR_MC_LINKLOCAL(dst)) {
940 			/*
941 			 * We do not have to check or get the route for
942 			 * multicast.  If the caller didn't ask/care for
943 			 * the route and we have no interface to use,
944 			 * it's an error.
945 			 */
946 			if (ifp == NULL) {
947 				error = EHOSTUNREACH;
948 			}
949 			goto done;
950 		} else {
951 			goto getsrcif;
952 		}
953 	}
954 
955 	/*
956 	 * If the destination address is a multicast address and the outgoing
957 	 * interface for the address is specified by the caller, use it.
958 	 */
959 	if (IN6_IS_ADDR_MULTICAST(dst) && mopts != NULL) {
960 		IM6O_LOCK(mopts);
961 		ifp = ifp0 = mopts->im6o_multicast_ifp;
962 		if (ifp != NULL && IN6_IS_ADDR_MC_LINKLOCAL(dst)) {
963 			IM6O_UNLOCK(mopts);
964 			goto done; /* we don't need a route for link-local multicast */
965 		}
966 		IM6O_UNLOCK(mopts);
967 	}
968 
969 getsrcif:
970 	/*
971 	 * If the outgoing interface was not set via IPV6_BOUND_IF or
972 	 * IPV6_PKTINFO, use the scope ID in the destination address.
973 	 */
974 	if (ifscope == IFSCOPE_NONE) {
975 		ifscope = dstsock->sin6_scope_id;
976 	}
977 
978 	/*
979 	 * Perform source interface selection; the source IPv6 address
980 	 * must belong to one of the addresses of the interface used
981 	 * by the route.  For performance reasons, do this only if
982 	 * there is no route, or if the routing table has changed,
983 	 * or if we haven't done source interface selection on this
984 	 * route (for this PCB instance) before.
985 	 */
986 	if (!select_srcif) {
987 		goto getroute;
988 	} else if (!ROUTE_UNUSABLE(ro) && ro->ro_srcia != NULL &&
989 	    (ro->ro_flags & ROF_SRCIF_SELECTED)) {
990 		if (ro->ro_rt->rt_ifp->if_flags & IFF_LOOPBACK) {
991 			local_dst = TRUE;
992 		}
993 		ifa = ro->ro_srcia;
994 		IFA_ADDREF(ifa);        /* for caller */
995 		goto getroute;
996 	}
997 
998 	/*
999 	 * Given the source IPv6 address, find a suitable source interface
1000 	 * to use for transmission; if a scope ID has been specified,
1001 	 * optimize the search by looking at the addresses only for that
1002 	 * interface.  This is still suboptimal, however, as we need to
1003 	 * traverse the per-interface list.
1004 	 */
1005 	if (ifscope != IFSCOPE_NONE || (ro != NULL && ro->ro_rt != NULL)) {
1006 		unsigned int scope = ifscope;
1007 		struct ifnet *rt_ifp;
1008 
1009 		rt_ifp = (ro->ro_rt != NULL) ? ro->ro_rt->rt_ifp : NULL;
1010 
1011 		/*
1012 		 * If no scope is specified and the route is stale (pointing
1013 		 * to a defunct interface) use the current primary interface;
1014 		 * this happens when switching between interfaces configured
1015 		 * with the same IPv6 address.  Otherwise pick up the scope
1016 		 * information from the route; the ULP may have looked up a
1017 		 * correct route and we just need to verify it here and mark
1018 		 * it with the ROF_SRCIF_SELECTED flag below.
1019 		 */
1020 		if (scope == IFSCOPE_NONE) {
1021 			scope = rt_ifp->if_index;
1022 			if (scope != get_primary_ifscope(AF_INET6) &&
1023 			    ROUTE_UNUSABLE(ro)) {
1024 				scope = get_primary_ifscope(AF_INET6);
1025 			}
1026 		}
1027 
1028 		ifa = (struct ifaddr *)
1029 		    ifa_foraddr6_scoped(&srcsock->sin6_addr, scope);
1030 
1031 		/*
1032 		 * If we are forwarding and proxying prefix(es), see if the
1033 		 * source address is one of ours and is a proxied address;
1034 		 * if so, use it.
1035 		 */
1036 		if (ifa == NULL && ip6_forwarding && nd6_prproxy) {
1037 			ifa = (struct ifaddr *)
1038 			    ifa_foraddr6(&srcsock->sin6_addr);
1039 			if (ifa != NULL && !(proxied_ifa =
1040 			    nd6_prproxy_ifaddr((struct in6_ifaddr *)ifa))) {
1041 				IFA_REMREF(ifa);
1042 				ifa = NULL;
1043 			}
1044 		}
1045 
1046 		if (ip6_select_srcif_debug && ifa != NULL) {
1047 			if (ro->ro_rt != NULL) {
1048 				os_log(OS_LOG_DEFAULT, "%s %s->%s ifscope %d->%d ifa_if %s "
1049 				    "ro_if %s",
1050 				    __func__,
1051 				    s_src, s_dst, ifscope,
1052 				    scope, if_name(ifa->ifa_ifp),
1053 				    if_name(rt_ifp));
1054 			} else {
1055 				os_log(OS_LOG_DEFAULT, "%s %s->%s ifscope %d->%d ifa_if %s",
1056 				    __func__,
1057 				    s_src, s_dst, ifscope, scope,
1058 				    if_name(ifa->ifa_ifp));
1059 			}
1060 		}
1061 	}
1062 
1063 	/*
1064 	 * Slow path; search for an interface having the corresponding source
1065 	 * IPv6 address if the scope was not specified by the caller, and:
1066 	 *
1067 	 *   1) There currently isn't any route, or,
1068 	 *   2) The interface used by the route does not own that source
1069 	 *	IPv6 address; in this case, the route will get blown away
1070 	 *	and we'll do a more specific scoped search using the newly
1071 	 *	found interface.
1072 	 */
1073 	if (ifa == NULL && ifscope == IFSCOPE_NONE) {
1074 		struct ifaddr *ifadst;
1075 
1076 		/* Check if the destination address is one of ours */
1077 		ifadst = (struct ifaddr *)ifa_foraddr6(&dstsock->sin6_addr);
1078 		if (ifadst != NULL) {
1079 			local_dst = TRUE;
1080 			IFA_REMREF(ifadst);
1081 		}
1082 
1083 		ifa = (struct ifaddr *)ifa_foraddr6(&srcsock->sin6_addr);
1084 
1085 		if (ip6_select_srcif_debug && ifa != NULL) {
1086 			os_log(OS_LOG_DEFAULT, "%s %s->%s ifscope %d ifa_if %s",
1087 			    __func__,
1088 			    s_src, s_dst, ifscope, if_name(ifa->ifa_ifp));
1089 		} else if (ip6_select_srcif_debug) {
1090 			os_log(OS_LOG_DEFAULT, "%s %s->%s ifscope %d ifa_if NULL",
1091 			    __func__,
1092 			    s_src, s_dst, ifscope);
1093 		}
1094 	}
1095 
1096 getroute:
1097 	if (ifa != NULL && !proxied_ifa && !local_dst) {
1098 		ifscope = ifa->ifa_ifp->if_index;
1099 	}
1100 
1101 	/*
1102 	 * If the next hop address for the packet is specified by the caller,
1103 	 * use it as the gateway.
1104 	 */
1105 	if (opts != NULL && opts->ip6po_nexthop != NULL) {
1106 		struct route_in6 *ron;
1107 
1108 		sin6_next = satosin6(opts->ip6po_nexthop);
1109 
1110 		/* at this moment, we only support AF_INET6 next hops */
1111 		if (sin6_next->sin6_family != AF_INET6) {
1112 			error = EAFNOSUPPORT; /* or should we proceed? */
1113 			goto done;
1114 		}
1115 
1116 		/*
1117 		 * If the next hop is an IPv6 address, then the node identified
1118 		 * by that address must be a neighbor of the sending host.
1119 		 */
1120 		ron = &opts->ip6po_nextroute;
1121 		if (ron->ro_rt != NULL) {
1122 			RT_LOCK(ron->ro_rt);
1123 		}
1124 		if (ROUTE_UNUSABLE(ron) || (ron->ro_rt != NULL &&
1125 		    (!(ron->ro_rt->rt_flags & RTF_LLINFO) ||
1126 		    (select_srcif && (ifa == NULL ||
1127 		    (ifa->ifa_ifp != ron->ro_rt->rt_ifp && !proxied_ifa))))) ||
1128 		    !in6_are_addr_equal_scoped(&satosin6(&ron->ro_dst)->sin6_addr,
1129 		    &sin6_next->sin6_addr, ron->ro_rt->rt_ifp->if_index, sin6_next->sin6_scope_id)) {
1130 			if (ron->ro_rt != NULL) {
1131 				RT_UNLOCK(ron->ro_rt);
1132 			}
1133 
1134 			ROUTE_RELEASE(ron);
1135 			*satosin6(&ron->ro_dst) = *sin6_next;
1136 		}
1137 		if (ron->ro_rt == NULL) {
1138 			rtalloc_scoped((struct route *)ron, ifscope);
1139 			if (ron->ro_rt != NULL) {
1140 				RT_LOCK(ron->ro_rt);
1141 			}
1142 			if (ROUTE_UNUSABLE(ron) ||
1143 			    !(ron->ro_rt->rt_flags & RTF_LLINFO) ||
1144 			    !in6_are_addr_equal_scoped(&satosin6(rt_key(ron->ro_rt))->
1145 			    sin6_addr, &sin6_next->sin6_addr, ron->ro_rt->rt_ifp->if_index, sin6_next->sin6_scope_id)) {
1146 				if (ron->ro_rt != NULL) {
1147 					RT_UNLOCK(ron->ro_rt);
1148 				}
1149 
1150 				ROUTE_RELEASE(ron);
1151 				error = EHOSTUNREACH;
1152 				goto done;
1153 			}
1154 		}
1155 		route = ron;
1156 		ifp = ifp0 = ron->ro_rt->rt_ifp;
1157 
1158 		/*
1159 		 * When cloning is required, try to allocate a route to the
1160 		 * destination so that the caller can store path MTU
1161 		 * information.
1162 		 */
1163 		if (!clone) {
1164 			if (select_srcif) {
1165 				/* Keep the route locked */
1166 				goto validateroute;
1167 			}
1168 			RT_UNLOCK(ron->ro_rt);
1169 			goto done;
1170 		}
1171 		RT_UNLOCK(ron->ro_rt);
1172 	}
1173 
1174 	/*
1175 	 * Use a cached route if it exists and is valid, else try to allocate
1176 	 * a new one.  Note that we should check the address family of the
1177 	 * cached destination, in case of sharing the cache with IPv4.
1178 	 */
1179 	if (ro == NULL) {
1180 		goto done;
1181 	}
1182 	if (ro->ro_rt != NULL) {
1183 		RT_LOCK_SPIN(ro->ro_rt);
1184 	}
1185 	if (ROUTE_UNUSABLE(ro) || (ro->ro_rt != NULL &&
1186 	    (satosin6(&ro->ro_dst)->sin6_family != AF_INET6 ||
1187 	    !in6_are_addr_equal_scoped(&satosin6(&ro->ro_dst)->sin6_addr, dst, ro->ro_rt->rt_ifp->if_index, dstsock->sin6_scope_id) ||
1188 	    (select_srcif && (ifa == NULL ||
1189 	    (ifa->ifa_ifp != ro->ro_rt->rt_ifp && !proxied_ifa)))))) {
1190 		if (ro->ro_rt != NULL) {
1191 			RT_UNLOCK(ro->ro_rt);
1192 		}
1193 
1194 		ROUTE_RELEASE(ro);
1195 	}
1196 	if (ro->ro_rt == NULL) {
1197 		struct sockaddr_in6 *sa6;
1198 
1199 		/* No route yet, so try to acquire one */
1200 		bzero(&ro->ro_dst, sizeof(struct sockaddr_in6));
1201 		sa6 = (struct sockaddr_in6 *)&ro->ro_dst;
1202 		sa6->sin6_family = AF_INET6;
1203 		sa6->sin6_len = sizeof(struct sockaddr_in6);
1204 		sa6->sin6_addr = *dst;
1205 		if (IN6_IS_ADDR_MC_LINKLOCAL(dst)) {
1206 			ro->ro_rt = rtalloc1_scoped(
1207 				&((struct route *)ro)->ro_dst, 0, 0, ifscope);
1208 		} else {
1209 			rtalloc_scoped((struct route *)ro, ifscope);
1210 		}
1211 		if (ro->ro_rt != NULL) {
1212 			RT_LOCK_SPIN(ro->ro_rt);
1213 		}
1214 	}
1215 
1216 	/*
1217 	 * Do not care about the result if we have the nexthop
1218 	 * explicitly specified (in case we're asked to clone.)
1219 	 */
1220 	if (opts != NULL && opts->ip6po_nexthop != NULL) {
1221 		if (ro->ro_rt != NULL) {
1222 			RT_UNLOCK(ro->ro_rt);
1223 		}
1224 		goto done;
1225 	}
1226 
1227 	if (ro->ro_rt != NULL) {
1228 		RT_LOCK_ASSERT_HELD(ro->ro_rt);
1229 		ifp = ifp0 = ro->ro_rt->rt_ifp;
1230 	} else {
1231 		error = EHOSTUNREACH;
1232 	}
1233 	route = ro;
1234 
1235 validateroute:
1236 	if (select_srcif) {
1237 		boolean_t has_route = (route != NULL && route->ro_rt != NULL);
1238 		boolean_t srcif_selected = FALSE;
1239 
1240 		if (has_route) {
1241 			RT_LOCK_ASSERT_HELD(route->ro_rt);
1242 		}
1243 		/*
1244 		 * If there is a non-loopback route with the wrong interface,
1245 		 * or if there is no interface configured with such an address,
1246 		 * blow it away.  Except for local/loopback, we look for one
1247 		 * with a matching interface scope/index.
1248 		 */
1249 		if (has_route && (ifa == NULL ||
1250 		    (ifa->ifa_ifp != ifp && ifp != lo_ifp) ||
1251 		    !(route->ro_rt->rt_flags & RTF_UP))) {
1252 			/*
1253 			 * If the destination address belongs to a proxied
1254 			 * prefix, relax the requirement and allow the packet
1255 			 * to come out of the proxy interface with the source
1256 			 * address of the real interface.
1257 			 */
1258 			if (ifa != NULL && proxied_ifa &&
1259 			    (route->ro_rt->rt_flags & (RTF_UP | RTF_PROXY)) ==
1260 			    (RTF_UP | RTF_PROXY)) {
1261 				srcif_selected = TRUE;
1262 			} else {
1263 				if (ip6_select_srcif_debug) {
1264 					if (ifa != NULL) {
1265 						os_log(OS_LOG_DEFAULT,
1266 						    "%s->%s ifscope %d "
1267 						    "ro_if %s != ifa_if %s "
1268 						    "(cached route cleared)",
1269 						    s_src, s_dst,
1270 						    ifscope, if_name(ifp),
1271 						    if_name(ifa->ifa_ifp));
1272 					} else {
1273 						os_log(OS_LOG_DEFAULT,
1274 						    "%s->%s ifscope %d "
1275 						    "ro_if %s (no ifa_if "
1276 						    "found)", s_src, s_dst,
1277 						    ifscope, if_name(ifp));
1278 					}
1279 				}
1280 				RT_UNLOCK(route->ro_rt);
1281 				ROUTE_RELEASE(route);
1282 				error = EHOSTUNREACH;
1283 				/* Undo the settings done above */
1284 				route = NULL;
1285 				ifp = NULL;     /* ditch ifp; keep ifp0 */
1286 				has_route = FALSE;
1287 			}
1288 		} else if (has_route) {
1289 			srcif_selected = TRUE;
1290 		}
1291 
1292 		if (srcif_selected) {
1293 			VERIFY(has_route);
1294 			if (ifa != route->ro_srcia ||
1295 			    !(route->ro_flags & ROF_SRCIF_SELECTED)) {
1296 				RT_CONVERT_LOCK(route->ro_rt);
1297 				if (ifa != NULL) {
1298 					IFA_ADDREF(ifa); /* for route_in6 */
1299 				}
1300 				if (route->ro_srcia != NULL) {
1301 					IFA_REMREF(route->ro_srcia);
1302 				}
1303 				route->ro_srcia = ifa;
1304 				route->ro_flags |= ROF_SRCIF_SELECTED;
1305 				RT_GENID_SYNC(route->ro_rt);
1306 			}
1307 			RT_UNLOCK(route->ro_rt);
1308 		}
1309 	} else {
1310 		if (ro->ro_rt != NULL) {
1311 			RT_UNLOCK(ro->ro_rt);
1312 		}
1313 		if (ifp != NULL && opts != NULL &&
1314 		    opts->ip6po_pktinfo != NULL &&
1315 		    opts->ip6po_pktinfo->ipi6_ifindex != 0) {
1316 			/*
1317 			 * Check if the outgoing interface conflicts with the
1318 			 * interface specified by ipi6_ifindex (if specified).
1319 			 * Note that loopback interface is always okay.
1320 			 * (this may happen when we are sending a packet to
1321 			 * one of our own addresses.)
1322 			 */
1323 			if (!(ifp->if_flags & IFF_LOOPBACK) && ifp->if_index !=
1324 			    opts->ip6po_pktinfo->ipi6_ifindex) {
1325 				error = EHOSTUNREACH;
1326 				goto done;
1327 			}
1328 		}
1329 	}
1330 
1331 done:
1332 	/*
1333 	 * Check for interface restrictions.
1334 	 */
1335 #define CHECK_RESTRICTIONS(_ip6oa, _ifp)                        \
1336 	((((_ip6oa)->ip6oa_flags & IP6OAF_NO_CELLULAR) &&       \
1337 	    IFNET_IS_CELLULAR(_ifp)) ||                         \
1338 	(((_ip6oa)->ip6oa_flags & IP6OAF_NO_EXPENSIVE) &&       \
1339 	    IFNET_IS_EXPENSIVE(_ifp)) ||                        \
1340 	(((_ip6oa)->ip6oa_flags & IP6OAF_NO_CONSTRAINED) &&     \
1341 	    IFNET_IS_CONSTRAINED(_ifp)) ||                      \
1342 	(!((_ip6oa)->ip6oa_flags & IP6OAF_INTCOPROC_ALLOWED) && \
1343 	    IFNET_IS_INTCOPROC(_ifp)) ||                        \
1344 	(!((_ip6oa)->ip6oa_flags & IP6OAF_AWDL_UNRESTRICTED) && \
1345 	    IFNET_IS_AWDL_RESTRICTED(_ifp)))
1346 
1347 	if (error == 0 && ip6oa != NULL &&
1348 	    ((ifp && CHECK_RESTRICTIONS(ip6oa, ifp)) ||
1349 	    (route && route->ro_rt &&
1350 	    CHECK_RESTRICTIONS(ip6oa, route->ro_rt->rt_ifp)))) {
1351 		if (route != NULL && route->ro_rt != NULL) {
1352 			ROUTE_RELEASE(route);
1353 			route = NULL;
1354 		}
1355 		ifp = NULL;     /* ditch ifp; keep ifp0 */
1356 		error = EHOSTUNREACH;
1357 		ip6oa->ip6oa_flags |= IP6OAF_R_IFDENIED;
1358 	}
1359 #undef CHECK_RESTRICTIONS
1360 
1361 	/*
1362 	 * If the interface is disabled for IPv6, then ENETDOWN error.
1363 	 */
1364 	if (error == 0 &&
1365 	    ifp != NULL && (ifp->if_eflags & IFEF_IPV6_DISABLED)) {
1366 		error = ENETDOWN;
1367 	}
1368 
1369 	if (ifp == NULL && (route == NULL || route->ro_rt == NULL)) {
1370 		/*
1371 		 * This can happen if the caller did not pass a cached route
1372 		 * nor any other hints.  We treat this case an error.
1373 		 */
1374 		error = EHOSTUNREACH;
1375 	}
1376 	if (error == EHOSTUNREACH || error == ENETDOWN) {
1377 		ip6stat.ip6s_noroute++;
1378 	}
1379 
1380 	/*
1381 	 * We'll return ifp regardless of error, so pick it up from ifp0
1382 	 * in case it was nullified above.  Caller is responsible for
1383 	 * releasing the ifp if it is non-NULL.
1384 	 */
1385 	ifp = ifp0;
1386 	if (retifp != NULL) {
1387 		if (ifp != NULL) {
1388 			ifnet_reference(ifp);   /* for caller */
1389 		}
1390 		*retifp = ifp;
1391 	}
1392 
1393 	if (retsrcia != NULL) {
1394 		if (ifa != NULL) {
1395 			IFA_ADDREF(ifa);        /* for caller */
1396 		}
1397 		*retsrcia = (struct in6_ifaddr *)ifa;
1398 	}
1399 
1400 	if (error == 0) {
1401 		if (retrt != NULL && route != NULL) {
1402 			*retrt = route->ro_rt;  /* ro_rt may be NULL */
1403 		}
1404 	}
1405 	if (ip6_select_srcif_debug) {
1406 		os_log(OS_LOG_DEFAULT,
1407 		    "%s %s->%s ifscope %d ifa_if %s ro_if %s (error=%d)",
1408 		    __func__,
1409 		    s_src, s_dst, ifscope,
1410 		    (ifa != NULL) ? if_name(ifa->ifa_ifp) : "NONE",
1411 		    (ifp != NULL) ? if_name(ifp) : "NONE", error);
1412 	}
1413 
1414 	if (ifa != NULL) {
1415 		IFA_REMREF(ifa);
1416 	}
1417 
1418 	return error;
1419 }
1420 
1421 /*
1422  * Regardless of error, it will return an ifp with a reference held if the
1423  * caller provides a non-NULL retifp.  The caller is responsible for checking
1424  * if the returned ifp is valid and release its reference at all times.
1425  */
1426 int
in6_selectif(struct sockaddr_in6 * dstsock,struct ip6_pktopts * opts,struct ip6_moptions * mopts,struct route_in6 * ro,struct ip6_out_args * ip6oa,struct ifnet ** retifp)1427 in6_selectif(struct sockaddr_in6 *dstsock, struct ip6_pktopts *opts,
1428     struct ip6_moptions *mopts, struct route_in6 *ro,
1429     struct ip6_out_args *ip6oa, struct ifnet **retifp)
1430 {
1431 	int err = 0;
1432 	struct route_in6 sro;
1433 	struct rtentry *rt = NULL;
1434 
1435 	if (ro == NULL) {
1436 		bzero(&sro, sizeof(sro));
1437 		ro = &sro;
1438 	}
1439 
1440 	if ((err = selectroute(NULL, dstsock, opts, mopts, NULL, ro, retifp,
1441 	    &rt, 0, 1, ip6oa)) != 0) {
1442 		goto done;
1443 	}
1444 
1445 	/*
1446 	 * do not use a rejected or black hole route.
1447 	 * XXX: this check should be done in the L2 output routine.
1448 	 * However, if we skipped this check here, we'd see the following
1449 	 * scenario:
1450 	 * - install a rejected route for a scoped address prefix
1451 	 *   (like fe80::/10)
1452 	 * - send a packet to a destination that matches the scoped prefix,
1453 	 *   with ambiguity about the scope zone.
1454 	 * - pick the outgoing interface from the route, and disambiguate the
1455 	 *   scope zone with the interface.
1456 	 * - ip6_output() would try to get another route with the "new"
1457 	 *   destination, which may be valid.
1458 	 * - we'd see no error on output.
1459 	 * Although this may not be very harmful, it should still be confusing.
1460 	 * We thus reject the case here.
1461 	 */
1462 	if (rt && (rt->rt_flags & (RTF_REJECT | RTF_BLACKHOLE))) {
1463 		err = ((rt->rt_flags & RTF_HOST) ? EHOSTUNREACH : ENETUNREACH);
1464 		goto done;
1465 	}
1466 
1467 	/*
1468 	 * Adjust the "outgoing" interface.  If we're going to loop the packet
1469 	 * back to ourselves, the ifp would be the loopback interface.
1470 	 * However, we'd rather know the interface associated to the
1471 	 * destination address (which should probably be one of our own
1472 	 * addresses.)
1473 	 */
1474 	if (rt != NULL && rt->rt_ifa != NULL && rt->rt_ifa->ifa_ifp != NULL &&
1475 	    retifp != NULL) {
1476 		ifnet_reference(rt->rt_ifa->ifa_ifp);
1477 		if (*retifp != NULL) {
1478 			ifnet_release(*retifp);
1479 		}
1480 		*retifp = rt->rt_ifa->ifa_ifp;
1481 	}
1482 
1483 done:
1484 	if (ro == &sro) {
1485 		VERIFY(rt == NULL || rt == ro->ro_rt);
1486 		ROUTE_RELEASE(ro);
1487 	}
1488 
1489 	/*
1490 	 * retifp might point to a valid ifp with a reference held;
1491 	 * caller is responsible for releasing it if non-NULL.
1492 	 */
1493 	return err;
1494 }
1495 
1496 /*
1497  * Regardless of error, it will return an ifp with a reference held if the
1498  * caller provides a non-NULL retifp.  The caller is responsible for checking
1499  * if the returned ifp is valid and release its reference at all times.
1500  *
1501  * clone - meaningful only for bsdi and freebsd
1502  */
1503 int
in6_selectroute(struct sockaddr_in6 * srcsock,struct sockaddr_in6 * dstsock,struct ip6_pktopts * opts,struct ip6_moptions * mopts,struct in6_ifaddr ** retsrcia,struct route_in6 * ro,struct ifnet ** retifp,struct rtentry ** retrt,int clone,struct ip6_out_args * ip6oa)1504 in6_selectroute(struct sockaddr_in6 *srcsock, struct sockaddr_in6 *dstsock,
1505     struct ip6_pktopts *opts, struct ip6_moptions *mopts,
1506     struct in6_ifaddr **retsrcia, struct route_in6 *ro, struct ifnet **retifp,
1507     struct rtentry **retrt, int clone, struct ip6_out_args *ip6oa)
1508 {
1509 	return selectroute(srcsock, dstsock, opts, mopts, retsrcia, ro, retifp,
1510 	           retrt, clone, 0, ip6oa);
1511 }
1512 
1513 /*
1514  * Default hop limit selection. The precedence is as follows:
1515  * 1. Hoplimit value specified via socket option.
1516  * 2. (If the outgoing interface is detected) the current
1517  *     hop limit of the interface specified by router advertisement.
1518  * 3. The system default hoplimit.
1519  */
1520 uint8_t
in6_selecthlim(struct in6pcb * in6p,struct ifnet * ifp)1521 in6_selecthlim(struct in6pcb *in6p, struct ifnet *ifp)
1522 {
1523 	if (in6p && in6p->in6p_hops >= 0) {
1524 		return (uint8_t)in6p->in6p_hops;
1525 	} else if (NULL != ifp) {
1526 		uint8_t chlim;
1527 		struct nd_ifinfo *ndi = ND_IFINFO(ifp);
1528 		if (ndi && ndi->initialized) {
1529 			/* access chlim without lock, for performance */
1530 			chlim = ndi->chlim;
1531 		} else {
1532 			chlim = (uint8_t)ip6_defhlim;
1533 		}
1534 		return chlim;
1535 	}
1536 
1537 	return (uint8_t)ip6_defhlim;
1538 }
1539 
1540 /*
1541  * XXX: this is borrowed from in6_pcbbind(). If possible, we should
1542  * share this function by all *bsd*...
1543  */
1544 int
in6_pcbsetport(struct in6_addr * laddr,struct inpcb * inp,struct proc * p,int locked)1545 in6_pcbsetport(struct in6_addr *laddr, struct inpcb *inp, struct proc *p,
1546     int locked)
1547 {
1548 	struct socket *so = inp->inp_socket;
1549 	uint16_t lport = 0, first, last, *lastport, rand_port;
1550 	int count, error = 0, wild = 0;
1551 	boolean_t counting_down;
1552 	bool found, randomport;
1553 	struct inpcbinfo *pcbinfo = inp->inp_pcbinfo;
1554 	kauth_cred_t cred;
1555 #if SKYWALK
1556 	bool laddr_unspecified = IN6_IS_ADDR_UNSPECIFIED(laddr);
1557 #else
1558 #pragma unused(laddr)
1559 #endif
1560 	if (!locked) { /* Make sure we don't run into a deadlock: 4052373 */
1561 		if (!lck_rw_try_lock_exclusive(&pcbinfo->ipi_lock)) {
1562 			socket_unlock(inp->inp_socket, 0);
1563 			lck_rw_lock_exclusive(&pcbinfo->ipi_lock);
1564 			socket_lock(inp->inp_socket, 0);
1565 		}
1566 
1567 		/*
1568 		 * Check if a local port was assigned to the inp while
1569 		 * this thread was waiting for the pcbinfo lock
1570 		 */
1571 		if (inp->inp_lport != 0) {
1572 			VERIFY(inp->inp_flags2 & INP2_INHASHLIST);
1573 			lck_rw_done(&pcbinfo->ipi_lock);
1574 
1575 			/*
1576 			 * It is not an error if another thread allocated
1577 			 * a port
1578 			 */
1579 			return 0;
1580 		}
1581 	}
1582 
1583 	/* XXX: this is redundant when called from in6_pcbbind */
1584 	if ((so->so_options & (SO_REUSEADDR | SO_REUSEPORT)) == 0) {
1585 		wild = INPLOOKUP_WILDCARD;
1586 	}
1587 
1588 	randomport = (so->so_flags & SOF_BINDRANDOMPORT) > 0 ||
1589 	    (so->so_type == SOCK_STREAM ? tcp_use_randomport :
1590 	    udp_use_randomport) > 0;
1591 
1592 	if (inp->inp_flags & INP_HIGHPORT) {
1593 		first = (uint16_t)ipport_hifirstauto;     /* sysctl */
1594 		last  = (uint16_t)ipport_hilastauto;
1595 		lastport = &pcbinfo->ipi_lasthi;
1596 	} else if (inp->inp_flags & INP_LOWPORT) {
1597 		cred = kauth_cred_proc_ref(p);
1598 		error = priv_check_cred(cred, PRIV_NETINET_RESERVEDPORT, 0);
1599 		kauth_cred_unref(&cred);
1600 		if (error != 0) {
1601 			if (!locked) {
1602 				lck_rw_done(&pcbinfo->ipi_lock);
1603 			}
1604 			return error;
1605 		}
1606 		first = (uint16_t)ipport_lowfirstauto;    /* 1023 */
1607 		last  = (uint16_t)ipport_lowlastauto;     /* 600 */
1608 		lastport = &pcbinfo->ipi_lastlow;
1609 	} else {
1610 		first = (uint16_t)ipport_firstauto;       /* sysctl */
1611 		last  = (uint16_t)ipport_lastauto;
1612 		lastport = &pcbinfo->ipi_lastport;
1613 	}
1614 
1615 	if (first == last) {
1616 		randomport = false;
1617 	}
1618 	/*
1619 	 * Simple check to ensure all ports are not used up causing
1620 	 * a deadlock here.
1621 	 */
1622 	found = false;
1623 	if (first > last) {
1624 		/* counting down */
1625 		if (randomport) {
1626 			read_frandom(&rand_port, sizeof(rand_port));
1627 			*lastport = first - (rand_port % (first - last));
1628 		}
1629 		count = first - last;
1630 		counting_down = TRUE;
1631 	} else {
1632 		/* counting up */
1633 		if (randomport) {
1634 			read_frandom(&rand_port, sizeof(rand_port));
1635 			*lastport = first + (rand_port % (first - last));
1636 		}
1637 		count = last - first;
1638 		counting_down = FALSE;
1639 	}
1640 	do {
1641 		if (count-- < 0) {      /* completely used? */
1642 			/*
1643 			 * Undo any address bind that may have
1644 			 * occurred above.
1645 			 */
1646 			inp->in6p_laddr = in6addr_any;
1647 			inp->in6p_last_outifp = NULL;
1648 			inp->inp_lifscope = IFSCOPE_NONE;
1649 #if SKYWALK
1650 			if (NETNS_TOKEN_VALID(&inp->inp_netns_token)) {
1651 				netns_set_ifnet(&inp->inp_netns_token,
1652 				    NULL);
1653 			}
1654 #endif /* SKYWALK */
1655 			if (!locked) {
1656 				lck_rw_done(&pcbinfo->ipi_lock);
1657 			}
1658 			return EAGAIN;
1659 		}
1660 		if (counting_down) {
1661 			--*lastport;
1662 			if (*lastport > first || *lastport < last) {
1663 				*lastport = first;
1664 			}
1665 		} else {
1666 			++*lastport;
1667 			if (*lastport < first || *lastport > last) {
1668 				*lastport = first;
1669 			}
1670 		}
1671 		lport = htons(*lastport);
1672 
1673 		/*
1674 		 * Skip if this is a restricted port as we do not want to
1675 		 * restricted ports as ephemeral
1676 		 */
1677 		if (IS_RESTRICTED_IN_PORT(lport)) {
1678 			continue;
1679 		}
1680 
1681 		found = (in6_pcblookup_local(pcbinfo, &inp->in6p_laddr,
1682 		    lport, inp->inp_lifscope, wild) == NULL);
1683 #if SKYWALK
1684 		if (found &&
1685 		    (SOCK_PROTO(so) == IPPROTO_TCP ||
1686 		    SOCK_PROTO(so) == IPPROTO_UDP) &&
1687 		    !(inp->inp_flags2 & INP2_EXTERNAL_PORT)) {
1688 			if (laddr_unspecified &&
1689 			    (inp->inp_flags & IN6P_IPV6_V6ONLY) == 0) {
1690 				struct in_addr ip_zero = { .s_addr = 0 };
1691 
1692 				netns_release(&inp->inp_wildcard_netns_token);
1693 				if (netns_reserve_in(
1694 					    &inp->inp_wildcard_netns_token,
1695 					    ip_zero,
1696 					    (uint8_t)SOCK_PROTO(so), lport,
1697 					    NETNS_BSD, NULL) != 0) {
1698 					/* port in use in IPv4 namespace */
1699 					found = false;
1700 				}
1701 			}
1702 			if (found &&
1703 			    netns_reserve_in6(&inp->inp_netns_token,
1704 			    inp->in6p_laddr, (uint8_t)SOCK_PROTO(so), lport,
1705 			    NETNS_BSD, NULL) != 0) {
1706 				netns_release(&inp->inp_wildcard_netns_token);
1707 				found = false;
1708 			}
1709 		}
1710 #endif /* SKYWALK */
1711 	} while (!found);
1712 
1713 	inp->inp_lport = lport;
1714 	inp->inp_flags |= INP_ANONPORT;
1715 
1716 	if (in_pcbinshash(inp, 1) != 0) {
1717 		inp->in6p_laddr = in6addr_any;
1718 		inp->in6p_last_outifp = NULL;
1719 		inp->inp_lifscope = IFSCOPE_NONE;
1720 #if SKYWALK
1721 		netns_release(&inp->inp_netns_token);
1722 #endif /* SKYWALK */
1723 		inp->inp_lport = 0;
1724 		inp->inp_flags &= ~INP_ANONPORT;
1725 		if (!locked) {
1726 			lck_rw_done(&pcbinfo->ipi_lock);
1727 		}
1728 		return EAGAIN;
1729 	}
1730 
1731 	if (!locked) {
1732 		lck_rw_done(&pcbinfo->ipi_lock);
1733 	}
1734 	return 0;
1735 }
1736 
1737 /*
1738  * The followings are implementation of the policy table using a
1739  * simple tail queue.
1740  * XXX such details should be hidden.
1741  * XXX implementation using binary tree should be more efficient.
1742  */
1743 struct addrsel_policyent {
1744 	TAILQ_ENTRY(addrsel_policyent) ape_entry;
1745 	struct in6_addrpolicy ape_policy;
1746 };
1747 
1748 TAILQ_HEAD(addrsel_policyhead, addrsel_policyent);
1749 
1750 struct addrsel_policyhead addrsel_policytab;
1751 
1752 static void
init_policy_queue(void)1753 init_policy_queue(void)
1754 {
1755 	TAILQ_INIT(&addrsel_policytab);
1756 }
1757 
1758 void
addrsel_policy_init(void)1759 addrsel_policy_init(void)
1760 {
1761 	/*
1762 	 * Default address selection policy based on RFC 6724.
1763 	 */
1764 	static const struct in6_addrpolicy defaddrsel[] = {
1765 		/* Loopback -- prefix=::1/128, precedence=50, label=0 */
1766 		{
1767 			.addr = {
1768 				.sin6_family = AF_INET6,
1769 				.sin6_addr   = IN6ADDR_LOOPBACK_INIT,
1770 				.sin6_len    = sizeof(struct sockaddr_in6)
1771 			},
1772 			.addrmask = {
1773 				.sin6_family = AF_INET6,
1774 				.sin6_addr   = IN6MASK128,
1775 				.sin6_len    = sizeof(struct sockaddr_in6)
1776 			},
1777 			.preced   = 50,
1778 			.label    = 0
1779 		},
1780 
1781 		/* Unspecified -- prefix=::/0, precedence=40, label=1 */
1782 		{
1783 			.addr = {
1784 				.sin6_family = AF_INET6,
1785 				.sin6_addr   = IN6ADDR_ANY_INIT,
1786 				.sin6_len    = sizeof(struct sockaddr_in6)
1787 			},
1788 			.addrmask = {
1789 				.sin6_family = AF_INET6,
1790 				.sin6_addr   = IN6MASK0,
1791 				.sin6_len    = sizeof(struct sockaddr_in6)
1792 			},
1793 			.preced   = 40,
1794 			.label    = 1
1795 		},
1796 
1797 		/* IPv4 Mapped -- prefix=::ffff:0:0/96, precedence=35, label=4 */
1798 		{
1799 			.addr = {
1800 				.sin6_family = AF_INET6,
1801 				.sin6_addr   = IN6ADDR_V4MAPPED_INIT,
1802 				.sin6_len    = sizeof(struct sockaddr_in6)
1803 			},
1804 			.addrmask = {
1805 				.sin6_family = AF_INET6,
1806 				.sin6_addr   = IN6MASK96,
1807 				.sin6_len    = sizeof(struct sockaddr_in6)
1808 			},
1809 			.preced   = 35,
1810 			.label    = 4
1811 		},
1812 
1813 		/* 6to4 -- prefix=2002::/16, precedence=30, label=2 */
1814 		{
1815 			.addr = {
1816 				.sin6_family = AF_INET6,
1817 				.sin6_addr   = {{{ 0x20, 0x02 }}},
1818 				.sin6_len    = sizeof(struct sockaddr_in6)
1819 			},
1820 			.addrmask = {
1821 				.sin6_family = AF_INET6,
1822 				.sin6_addr   = IN6MASK16,
1823 				.sin6_len    = sizeof(struct sockaddr_in6)
1824 			},
1825 			.preced   = 30,
1826 			.label    = 2
1827 		},
1828 
1829 		/* Teredo -- prefix=2001::/32, precedence=5, label=5 */
1830 		{
1831 			.addr = {
1832 				.sin6_family = AF_INET6,
1833 				.sin6_addr   = {{{ 0x20, 0x01 }}},
1834 				.sin6_len    = sizeof(struct sockaddr_in6)
1835 			},
1836 			.addrmask = {
1837 				.sin6_family = AF_INET6,
1838 				.sin6_addr   = IN6MASK32,
1839 				.sin6_len    = sizeof(struct sockaddr_in6)
1840 			},
1841 			.preced   = 5,
1842 			.label    = 5
1843 		},
1844 
1845 		/* Unique Local (ULA) -- prefix=fc00::/7, precedence=3, label=13 */
1846 		{
1847 			.addr = {
1848 				.sin6_family = AF_INET6,
1849 				.sin6_addr   = {{{ 0xfc }}},
1850 				.sin6_len    = sizeof(struct sockaddr_in6)
1851 			},
1852 			.addrmask = {
1853 				.sin6_family = AF_INET6,
1854 				.sin6_addr   = IN6MASK7,
1855 				.sin6_len    = sizeof(struct sockaddr_in6)
1856 			},
1857 			.preced   = 3,
1858 			.label    = 13
1859 		},
1860 
1861 		/* IPv4 Compatible -- prefix=::/96, precedence=1, label=3 */
1862 		{
1863 			.addr = {
1864 				.sin6_family = AF_INET6,
1865 				.sin6_addr = IN6ADDR_ANY_INIT,
1866 				.sin6_len    = sizeof(struct sockaddr_in6)
1867 			},
1868 			.addrmask = {
1869 				.sin6_family = AF_INET6,
1870 				.sin6_addr = IN6MASK96,
1871 				.sin6_len    = sizeof(struct sockaddr_in6)
1872 			},
1873 			.preced   = 1,
1874 			.label    = 3
1875 		},
1876 
1877 		/* Site-local (deprecated) -- prefix=fec0::/10, precedence=1, label=11 */
1878 		{
1879 			.addr = {
1880 				.sin6_family = AF_INET6,
1881 				.sin6_addr = {{{ 0xfe, 0xc0 }}},
1882 				.sin6_len    = sizeof(struct sockaddr_in6)
1883 			},
1884 			.addrmask = {
1885 				.sin6_family = AF_INET6,
1886 				.sin6_addr = IN6MASK16,
1887 				.sin6_len    = sizeof(struct sockaddr_in6)
1888 			},
1889 			.preced   = 1,
1890 			.label    = 11
1891 		},
1892 
1893 		/* 6bone (deprecated) -- prefix=3ffe::/16, precedence=1, label=12 */
1894 		{
1895 			.addr = {
1896 				.sin6_family = AF_INET6,
1897 				.sin6_addr = {{{ 0x3f, 0xfe }}},
1898 				.sin6_len    = sizeof(struct sockaddr_in6)
1899 			},
1900 			.addrmask = {
1901 				.sin6_family = AF_INET6,
1902 				.sin6_addr = IN6MASK16,
1903 				.sin6_len    = sizeof(struct sockaddr_in6)
1904 			},
1905 			.preced   = 1,
1906 			.label    = 12
1907 		},
1908 	};
1909 	int i;
1910 
1911 	init_policy_queue();
1912 
1913 	/* initialize the "last resort" policy */
1914 	bzero(&defaultaddrpolicy, sizeof(defaultaddrpolicy));
1915 	defaultaddrpolicy.label = ADDR_LABEL_NOTAPP;
1916 
1917 	for (i = 0; i < sizeof(defaddrsel) / sizeof(defaddrsel[0]); i++) {
1918 		add_addrsel_policyent(&defaddrsel[i]);
1919 	}
1920 }
1921 
1922 struct in6_addrpolicy *
in6_addrsel_lookup_policy(struct sockaddr_in6 * key)1923 in6_addrsel_lookup_policy(struct sockaddr_in6 *key)
1924 {
1925 	struct in6_addrpolicy *match = NULL;
1926 
1927 	ADDRSEL_LOCK();
1928 	match = match_addrsel_policy(key);
1929 
1930 	if (match == NULL) {
1931 		match = &defaultaddrpolicy;
1932 	} else {
1933 		match->use++;
1934 	}
1935 	ADDRSEL_UNLOCK();
1936 
1937 	return match;
1938 }
1939 
1940 static struct in6_addrpolicy *
match_addrsel_policy(struct sockaddr_in6 * key)1941 match_addrsel_policy(struct sockaddr_in6 *key)
1942 {
1943 	struct addrsel_policyent *pent;
1944 	struct in6_addrpolicy *bestpol = NULL, *pol;
1945 	int matchlen, bestmatchlen = -1;
1946 	u_char *mp, *ep, *k, *p, m;
1947 
1948 	TAILQ_FOREACH(pent, &addrsel_policytab, ape_entry) {
1949 		matchlen = 0;
1950 
1951 		pol = &pent->ape_policy;
1952 		mp = (u_char *)&pol->addrmask.sin6_addr;
1953 		ep = mp + 16;   /* XXX: scope field? */
1954 		k = (u_char *)&key->sin6_addr;
1955 		p = (u_char *)&pol->addr.sin6_addr;
1956 		for (; mp < ep && *mp; mp++, k++, p++) {
1957 			m = *mp;
1958 			if ((*k & m) != *p) {
1959 				goto next; /* not match */
1960 			}
1961 			if (m == 0xff) { /* short cut for a typical case */
1962 				matchlen += 8;
1963 			} else {
1964 				while (m >= 0x80) {
1965 					matchlen++;
1966 					m <<= 1;
1967 				}
1968 			}
1969 		}
1970 
1971 		/* matched.  check if this is better than the current best. */
1972 		if (bestpol == NULL ||
1973 		    matchlen > bestmatchlen) {
1974 			bestpol = pol;
1975 			bestmatchlen = matchlen;
1976 		}
1977 
1978 next:
1979 		continue;
1980 	}
1981 
1982 	return bestpol;
1983 }
1984 
1985 static int
add_addrsel_policyent(const struct in6_addrpolicy * newpolicy)1986 add_addrsel_policyent(const struct in6_addrpolicy *newpolicy)
1987 {
1988 	struct addrsel_policyent *new, *pol;
1989 
1990 	new = kalloc_type(struct addrsel_policyent, Z_WAITOK | Z_ZERO);
1991 
1992 	ADDRSEL_LOCK();
1993 
1994 	/* duplication check */
1995 	TAILQ_FOREACH(pol, &addrsel_policytab, ape_entry) {
1996 		if (IN6_ARE_ADDR_EQUAL(&newpolicy->addr.sin6_addr,
1997 		    &pol->ape_policy.addr.sin6_addr) &&
1998 		    IN6_ARE_ADDR_EQUAL(&newpolicy->addrmask.sin6_addr,
1999 		    &pol->ape_policy.addrmask.sin6_addr)) {
2000 			ADDRSEL_UNLOCK();
2001 			kfree_type(struct addrsel_policyent, new);
2002 			return EEXIST;        /* or override it? */
2003 		}
2004 	}
2005 
2006 	/* XXX: should validate entry */
2007 	new->ape_policy = *newpolicy;
2008 
2009 	TAILQ_INSERT_TAIL(&addrsel_policytab, new, ape_entry);
2010 	ADDRSEL_UNLOCK();
2011 
2012 	return 0;
2013 }
2014 #ifdef ENABLE_ADDRSEL
2015 static int
delete_addrsel_policyent(const struct in6_addrpolicy * key)2016 delete_addrsel_policyent(const struct in6_addrpolicy *key)
2017 {
2018 	struct addrsel_policyent *pol;
2019 
2020 
2021 	ADDRSEL_LOCK();
2022 
2023 	/* search for the entry in the table */
2024 	TAILQ_FOREACH(pol, &addrsel_policytab, ape_entry) {
2025 		if (in6_are_addr_equal_scoped(&key->addr.sin6_addr,
2026 		    &pol->ape_policy.addr.sin6_addr, key->addr.sin6_scope_id, pol->ape_policy.addr.sin6_scope_id) &&
2027 		    IN6_ARE_ADDR_EQUAL(&key->addrmask.sin6_addr,
2028 		    &pol->ape_policy.addrmask.sin6_addr)) {
2029 			break;
2030 		}
2031 	}
2032 	if (pol == NULL) {
2033 		ADDRSEL_UNLOCK();
2034 		return ESRCH;
2035 	}
2036 
2037 	TAILQ_REMOVE(&addrsel_policytab, pol, ape_entry);
2038 	kfree_type(struct addrsel_policyent, pol);
2039 	pol = NULL;
2040 	ADDRSEL_UNLOCK();
2041 
2042 	return 0;
2043 }
2044 #endif /* ENABLE_ADDRSEL */
2045 
2046 int
walk_addrsel_policy(int (* callback)(const struct in6_addrpolicy *,void *),void * w)2047 walk_addrsel_policy(int (*callback)(const struct in6_addrpolicy *, void *),
2048     void *w)
2049 {
2050 	struct addrsel_policyent *pol;
2051 	int error = 0;
2052 
2053 	ADDRSEL_LOCK();
2054 	TAILQ_FOREACH(pol, &addrsel_policytab, ape_entry) {
2055 		if ((error = (*callback)(&pol->ape_policy, w)) != 0) {
2056 			ADDRSEL_UNLOCK();
2057 			return error;
2058 		}
2059 	}
2060 	ADDRSEL_UNLOCK();
2061 	return error;
2062 }
2063 /*
2064  * Subroutines to manage the address selection policy table via sysctl.
2065  */
2066 struct walkarg {
2067 	struct sysctl_req *w_req;
2068 };
2069 
2070 
2071 static int
dump_addrsel_policyent(const struct in6_addrpolicy * pol,void * arg)2072 dump_addrsel_policyent(const struct in6_addrpolicy *pol, void *arg)
2073 {
2074 	int error = 0;
2075 	struct walkarg *w = arg;
2076 
2077 	error = SYSCTL_OUT(w->w_req, pol, sizeof(*pol));
2078 
2079 	return error;
2080 }
2081 
2082 static int
2083 in6_src_sysctl SYSCTL_HANDLER_ARGS
2084 {
2085 #pragma unused(oidp, arg1, arg2)
2086 	struct walkarg w;
2087 
2088 	if (req->newptr) {
2089 		return EPERM;
2090 	}
2091 	bzero(&w, sizeof(w));
2092 	w.w_req = req;
2093 
2094 	return walk_addrsel_policy(dump_addrsel_policyent, &w);
2095 }
2096 
2097 
2098 SYSCTL_NODE(_net_inet6_ip6, IPV6CTL_ADDRCTLPOLICY, addrctlpolicy,
2099     CTLFLAG_RD | CTLFLAG_LOCKED, in6_src_sysctl, "");
2100 int
in6_src_ioctl(u_long cmd,caddr_t data)2101 in6_src_ioctl(u_long cmd, caddr_t data)
2102 {
2103 	int i;
2104 	struct in6_addrpolicy ent0;
2105 
2106 	if (cmd != SIOCAADDRCTL_POLICY && cmd != SIOCDADDRCTL_POLICY) {
2107 		return EOPNOTSUPP; /* check for safety */
2108 	}
2109 	bcopy(data, &ent0, sizeof(ent0));
2110 
2111 	if (ent0.label == ADDR_LABEL_NOTAPP) {
2112 		return EINVAL;
2113 	}
2114 	/* check if the prefix mask is consecutive. */
2115 	if (in6_mask2len(&ent0.addrmask.sin6_addr, NULL) < 0) {
2116 		return EINVAL;
2117 	}
2118 	/* clear trailing garbages (if any) of the prefix address. */
2119 	for (i = 0; i < 4; i++) {
2120 		ent0.addr.sin6_addr.s6_addr32[i] &=
2121 		    ent0.addrmask.sin6_addr.s6_addr32[i];
2122 	}
2123 	ent0.use = 0;
2124 
2125 	switch (cmd) {
2126 	case SIOCAADDRCTL_POLICY:
2127 #ifdef ENABLE_ADDRSEL
2128 		return add_addrsel_policyent(&ent0);
2129 #else
2130 		return ENOTSUP;
2131 #endif
2132 	case SIOCDADDRCTL_POLICY:
2133 #ifdef ENABLE_ADDRSEL
2134 		return delete_addrsel_policyent(&ent0);
2135 #else
2136 		return ENOTSUP;
2137 #endif
2138 	}
2139 
2140 	return 0;             /* XXX: compromise compilers */
2141 }
2142 
2143 /*
2144  * generate kernel-internal form (scopeid embedded into s6_addr16[1]).
2145  * If the address scope of is link-local, embed the interface index in the
2146  * address.  The routine determines our precedence
2147  * between advanced API scope/interface specification and basic API
2148  * specification.
2149  *
2150  * this function should be nuked in the future, when we get rid of
2151  * embedded scopeid thing.
2152  *
2153  * XXX actually, it is over-specification to return ifp against sin6_scope_id.
2154  * there can be multiple interfaces that belong to a particular scope zone
2155  * (in specification, we have 1:N mapping between a scope zone and interfaces).
2156  * we may want to change the function to return something other than ifp.
2157  */
2158 int
in6_embedscope(struct in6_addr * in6,const struct sockaddr_in6 * sin6,struct in6pcb * in6p,struct ifnet ** ifpp,struct ip6_pktopts * opt,uint32_t * ret_ifscope)2159 in6_embedscope(struct in6_addr *in6, const struct sockaddr_in6 *sin6,
2160     struct in6pcb *in6p, struct ifnet **ifpp, struct ip6_pktopts *opt, uint32_t *ret_ifscope)
2161 {
2162 	struct ifnet *ifp = NULL;
2163 	u_int32_t scopeid;
2164 	struct ip6_pktopts *optp = NULL;
2165 
2166 	*in6 = sin6->sin6_addr;
2167 	scopeid = sin6->sin6_scope_id;
2168 	if (ifpp != NULL) {
2169 		*ifpp = NULL;
2170 	}
2171 
2172 	/*
2173 	 * don't try to read sin6->sin6_addr beyond here, since the caller may
2174 	 * ask us to overwrite existing sockaddr_in6
2175 	 */
2176 
2177 #ifdef ENABLE_DEFAULT_SCOPE
2178 	if (scopeid == 0) {
2179 		scopeid = scope6_addr2default(in6);
2180 	}
2181 #endif
2182 
2183 	if (IN6_IS_SCOPE_LINKLOCAL(in6) || IN6_IS_ADDR_MC_INTFACELOCAL(in6)) {
2184 		struct in6_pktinfo *pi;
2185 		struct ifnet *im6o_multicast_ifp = NULL;
2186 
2187 		if (in6p != NULL && IN6_IS_ADDR_MULTICAST(in6) &&
2188 		    in6p->in6p_moptions != NULL) {
2189 			IM6O_LOCK(in6p->in6p_moptions);
2190 			im6o_multicast_ifp =
2191 			    in6p->in6p_moptions->im6o_multicast_ifp;
2192 			IM6O_UNLOCK(in6p->in6p_moptions);
2193 		}
2194 
2195 		if (opt != NULL) {
2196 			optp = opt;
2197 		} else if (in6p != NULL) {
2198 			optp = in6p->in6p_outputopts;
2199 		}
2200 		/*
2201 		 * KAME assumption: link id == interface id
2202 		 */
2203 		if (in6p != NULL && optp != NULL &&
2204 		    (pi = optp->ip6po_pktinfo) != NULL &&
2205 		    pi->ipi6_ifindex != 0) {
2206 			/* ifp is needed here if only we're returning it */
2207 			if (ifpp != NULL) {
2208 				ifnet_head_lock_shared();
2209 				ifp = ifindex2ifnet[pi->ipi6_ifindex];
2210 				ifnet_head_done();
2211 			}
2212 
2213 			if (in6_embedded_scope) {
2214 				in6->s6_addr16[1] = htons((uint16_t)pi->ipi6_ifindex);
2215 			}
2216 			if (ret_ifscope != NULL) {
2217 				*ret_ifscope = pi->ipi6_ifindex;
2218 			}
2219 		} else if (in6p != NULL && IN6_IS_ADDR_MULTICAST(in6) &&
2220 		    in6p->in6p_moptions != NULL && im6o_multicast_ifp != NULL) {
2221 			ifp = im6o_multicast_ifp;
2222 			if (in6_embedded_scope) {
2223 				in6->s6_addr16[1] = htons(ifp->if_index);
2224 			}
2225 			if (ret_ifscope != NULL) {
2226 				*ret_ifscope = ifp->if_index;
2227 			}
2228 		} else if (scopeid != 0) {
2229 			/*
2230 			 * Since scopeid is unsigned, we only have to check it
2231 			 * against if_index (ifnet_head_lock not needed since
2232 			 * if_index is an ever-increasing integer.)
2233 			 */
2234 			if (if_index < scopeid) {
2235 				return ENXIO;  /* XXX EINVAL? */
2236 			}
2237 			/* ifp is needed here only if we're returning it */
2238 			if (ifpp != NULL) {
2239 				ifnet_head_lock_shared();
2240 				ifp = ifindex2ifnet[scopeid];
2241 				ifnet_head_done();
2242 			}
2243 			if (in6_embedded_scope) {
2244 				/* XXX assignment to 16bit from 32bit variable */
2245 				in6->s6_addr16[1] = htons(scopeid & 0xffff);
2246 			}
2247 			if (ret_ifscope != NULL) {
2248 				*ret_ifscope = scopeid;
2249 			}
2250 		}
2251 
2252 		if (ifpp != NULL) {
2253 			if (ifp != NULL) {
2254 				ifnet_reference(ifp);   /* for caller */
2255 			}
2256 			*ifpp = ifp;
2257 		}
2258 	}
2259 
2260 	return 0;
2261 }
2262 
2263 /*
2264  * generate standard sockaddr_in6 from embedded form.
2265  * touches sin6_addr and sin6_scope_id only.
2266  *
2267  * this function should be nuked in the future, when we get rid of
2268  * embedded scopeid thing.
2269  */
2270 int
in6_recoverscope(struct sockaddr_in6 * sin6,const struct in6_addr * in6,struct ifnet * ifp)2271 in6_recoverscope(
2272 	struct sockaddr_in6 *sin6,
2273 	const struct in6_addr *in6,
2274 	struct ifnet *ifp)
2275 {
2276 	u_int32_t scopeid;
2277 
2278 	sin6->sin6_addr = *in6;
2279 
2280 	if (!in6_embedded_scope) {
2281 		if (ifp != NULL && IN6_IS_SCOPE_EMBED(in6)) {
2282 			sin6->sin6_scope_id = ifp->if_index;
2283 		}
2284 		return 0;
2285 	}
2286 	/*
2287 	 * don't try to read *in6 beyond here, since the caller may
2288 	 * ask us to overwrite existing sockaddr_in6
2289 	 */
2290 
2291 	sin6->sin6_scope_id = 0;
2292 	if (IN6_IS_SCOPE_LINKLOCAL(in6) || IN6_IS_ADDR_MC_INTFACELOCAL(in6)) {
2293 		/*
2294 		 * KAME assumption: link id == interface id
2295 		 */
2296 		scopeid = ntohs(sin6->sin6_addr.s6_addr16[1]);
2297 		if (scopeid) {
2298 			/*
2299 			 * sanity check
2300 			 *
2301 			 * Since scopeid is unsigned, we only have to check it
2302 			 * against if_index
2303 			 */
2304 			if (if_index < scopeid) {
2305 				return ENXIO;
2306 			}
2307 			if (ifp && ifp->if_index != scopeid) {
2308 				return ENXIO;
2309 			}
2310 			sin6->sin6_addr.s6_addr16[1] = 0;
2311 			sin6->sin6_scope_id = scopeid;
2312 		}
2313 	}
2314 
2315 	return 0;
2316 }
2317