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