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