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