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