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