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