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