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