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