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