in6_src.c revision 1.53.4.1 1 /* $NetBSD: in6_src.c,v 1.53.4.1 2013/07/17 03:16:31 rmind Exp $ */
2 /* $KAME: in6_src.c,v 1.159 2005/10/19 01:40:32 t-momose Exp $ */
3
4 /*
5 * Copyright (C) 1995, 1996, 1997, and 1998 WIDE Project.
6 * All rights reserved.
7 *
8 * Redistribution and use in source and binary forms, with or without
9 * modification, are permitted provided that the following conditions
10 * are met:
11 * 1. Redistributions of source code must retain the above copyright
12 * notice, this list of conditions and the following disclaimer.
13 * 2. Redistributions in binary form must reproduce the above copyright
14 * notice, this list of conditions and the following disclaimer in the
15 * documentation and/or other materials provided with the distribution.
16 * 3. Neither the name of the project nor the names of its contributors
17 * may be used to endorse or promote products derived from this software
18 * without specific prior written permission.
19 *
20 * THIS SOFTWARE IS PROVIDED BY THE PROJECT AND CONTRIBUTORS ``AS IS'' AND
21 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
22 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
23 * ARE DISCLAIMED. IN NO EVENT SHALL THE PROJECT OR CONTRIBUTORS BE LIABLE
24 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
25 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
26 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
27 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
28 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
29 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
30 * SUCH DAMAGE.
31 */
32
33 /*
34 * Copyright (c) 1982, 1986, 1991, 1993
35 * The Regents of the University of California. All rights reserved.
36 *
37 * Redistribution and use in source and binary forms, with or without
38 * modification, are permitted provided that the following conditions
39 * are met:
40 * 1. Redistributions of source code must retain the above copyright
41 * notice, this list of conditions and the following disclaimer.
42 * 2. Redistributions in binary form must reproduce the above copyright
43 * notice, this list of conditions and the following disclaimer in the
44 * documentation and/or other materials provided with the distribution.
45 * 3. All advertising materials mentioning features or use of this software
46 * must display the following acknowledgement:
47 * This product includes software developed by the University of
48 * California, Berkeley and its contributors.
49 * 4. Neither the name of the University nor the names of its contributors
50 * may be used to endorse or promote products derived from this software
51 * without specific prior written permission.
52 *
53 * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
54 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
55 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
56 * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
57 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
58 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
59 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
60 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
61 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
62 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
63 * SUCH DAMAGE.
64 *
65 * @(#)in_pcb.c 8.2 (Berkeley) 1/4/94
66 */
67
68 #include <sys/cdefs.h>
69 __KERNEL_RCSID(0, "$NetBSD: in6_src.c,v 1.53.4.1 2013/07/17 03:16:31 rmind Exp $");
70
71 #include "opt_inet.h"
72
73 #include <sys/param.h>
74 #include <sys/systm.h>
75 #include <sys/malloc.h>
76 #include <sys/mbuf.h>
77 #include <sys/protosw.h>
78 #include <sys/socket.h>
79 #include <sys/socketvar.h>
80 #include <sys/ioctl.h>
81 #include <sys/errno.h>
82 #include <sys/time.h>
83 #include <sys/kernel.h>
84 #include <sys/proc.h>
85 #include <sys/kauth.h>
86
87 #include <net/if.h>
88 #include <net/if_types.h>
89 #include <net/route.h>
90
91 #include <netinet/in.h>
92 #include <netinet/in_var.h>
93 #include <netinet/in_systm.h>
94 #include <netinet/ip.h>
95 #define __INPCB_PRIVATE
96 #include <netinet/in_pcb.h>
97 #include <netinet/portalgo.h>
98 #include <netinet6/in6_var.h>
99 #include <netinet/ip6.h>
100 #include <netinet6/in6_pcb.h>
101 #include <netinet6/ip6_var.h>
102 #include <netinet6/ip6_private.h>
103 #include <netinet6/nd6.h>
104 #include <netinet6/scope6_var.h>
105
106 #include <net/net_osdep.h>
107
108 #ifdef MIP6
109 #include <netinet6/mip6.h>
110 #include <netinet6/mip6_var.h>
111 #include "mip.h"
112 #if NMIP > 0
113 #include <net/if_mip.h>
114 #endif /* NMIP > 0 */
115 #endif /* MIP6 */
116
117 #include <netinet/tcp_vtw.h>
118
119 #define ADDR_LABEL_NOTAPP (-1)
120 struct in6_addrpolicy defaultaddrpolicy;
121
122 #ifdef notyet /* until introducing ND extensions and address selection */
123 int ip6_prefer_tempaddr = 0;
124 #endif
125
126 static int selectroute(struct sockaddr_in6 *, struct ip6_pktopts *,
127 struct ip6_moptions *, struct route *, struct ifnet **,
128 struct rtentry **, int, int);
129 static int in6_selectif(struct sockaddr_in6 *, struct ip6_pktopts *,
130 struct ip6_moptions *, struct route *, struct ifnet **);
131
132 static struct in6_addrpolicy *lookup_addrsel_policy(struct sockaddr_in6 *);
133
134 static void init_policy_queue(void);
135 static int add_addrsel_policyent(struct in6_addrpolicy *);
136 static int delete_addrsel_policyent(struct in6_addrpolicy *);
137 static int walk_addrsel_policy(int (*)(struct in6_addrpolicy *, void *),
138 void *);
139 static int dump_addrsel_policyent(struct in6_addrpolicy *, void *);
140 static struct in6_addrpolicy *match_addrsel_policy(struct sockaddr_in6 *);
141
142 /*
143 * Return an IPv6 address, which is the most appropriate for a given
144 * destination and user specified options.
145 * If necessary, this function lookups the routing table and returns
146 * an entry to the caller for later use.
147 */
148 #if 0 /* diabled ad-hoc */
149 #define REPLACE(r) do {\
150 if ((r) < sizeof(ip6stat.ip6s_sources_rule) / \
151 sizeof(ip6stat.ip6s_sources_rule[0])) /* check for safety */ \
152 ip6stat.ip6s_sources_rule[(r)]++; \
153 /* printf("in6_selectsrc: replace %s with %s by %d\n", ia_best ? ip6_sprintf(&ia_best->ia_addr.sin6_addr) : "none", ip6_sprintf(&ia->ia_addr.sin6_addr), (r)); */ \
154 goto replace; \
155 } while(0)
156 #define NEXT(r) do {\
157 if ((r) < sizeof(ip6stat.ip6s_sources_rule) / \
158 sizeof(ip6stat.ip6s_sources_rule[0])) /* check for safety */ \
159 ip6stat.ip6s_sources_rule[(r)]++; \
160 /* printf("in6_selectsrc: keep %s against %s by %d\n", ia_best ? ip6_sprintf(&ia_best->ia_addr.sin6_addr) : "none", ip6_sprintf(&ia->ia_addr.sin6_addr), (r)); */ \
161 goto next; /* XXX: we can't use 'continue' here */ \
162 } while(0)
163 #define BREAK(r) do { \
164 if ((r) < sizeof(ip6stat.ip6s_sources_rule) / \
165 sizeof(ip6stat.ip6s_sources_rule[0])) /* check for safety */ \
166 ip6stat.ip6s_sources_rule[(r)]++; \
167 goto out; /* XXX: we can't use 'break' here */ \
168 } while(0)
169 #else
170 #define REPLACE(r) goto replace
171 #define NEXT(r) goto next
172 #define BREAK(r) goto out
173 #endif
174
175 struct in6_addr *
176 in6_selectsrc(struct sockaddr_in6 *dstsock, struct ip6_pktopts *opts,
177 struct ip6_moptions *mopts, struct route *ro, struct in6_addr *laddr,
178 struct ifnet **ifpp, int *errorp)
179 {
180 struct in6_addr dst;
181 struct ifnet *ifp = NULL;
182 struct in6_ifaddr *ia = NULL, *ia_best = NULL;
183 struct in6_pktinfo *pi = NULL;
184 int dst_scope = -1, best_scope = -1, best_matchlen = -1;
185 struct in6_addrpolicy *dst_policy = NULL, *best_policy = NULL;
186 u_int32_t odstzone;
187 int error;
188 #ifdef notyet /* until introducing ND extensions and address selection */
189 int prefer_tempaddr;
190 #endif
191 #if defined(MIP6) && NMIP > 0
192 u_int8_t ip6po_usecoa = 0;
193 #endif /* MIP6 && NMIP > 0 */
194
195 dst = dstsock->sin6_addr; /* make a copy for local operation */
196 *errorp = 0;
197 if (ifpp)
198 *ifpp = NULL;
199
200 /*
201 * Try to determine the outgoing interface for the given destination.
202 * We do this regardless of whether the socket is bound, since the
203 * caller may need this information as a side effect of the call
204 * to this function (e.g., for identifying the appropriate scope zone
205 * ID).
206 */
207 error = in6_selectif(dstsock, opts, mopts, ro, &ifp);
208 if (ifpp)
209 *ifpp = ifp;
210
211 /*
212 * If the source address is explicitly specified by the caller,
213 * check if the requested source address is indeed a unicast address
214 * assigned to the node, and can be used as the packet's source
215 * address. If everything is okay, use the address as source.
216 */
217 if (opts && (pi = opts->ip6po_pktinfo) &&
218 !IN6_IS_ADDR_UNSPECIFIED(&pi->ipi6_addr)) {
219 struct sockaddr_in6 srcsock;
220 struct in6_ifaddr *ia6;
221
222 /*
223 * Determine the appropriate zone id of the source based on
224 * the zone of the destination and the outgoing interface.
225 * If the specified address is ambiguous wrt the scope zone,
226 * the interface must be specified; otherwise, ifa_ifwithaddr()
227 * will fail matching the address.
228 */
229 memset(&srcsock, 0, sizeof(srcsock));
230 srcsock.sin6_family = AF_INET6;
231 srcsock.sin6_len = sizeof(srcsock);
232 srcsock.sin6_addr = pi->ipi6_addr;
233 if (ifp) {
234 *errorp = in6_setscope(&srcsock.sin6_addr, ifp, NULL);
235 if (*errorp != 0)
236 return (NULL);
237 }
238
239 ia6 = (struct in6_ifaddr *)ifa_ifwithaddr((struct sockaddr *)(&srcsock));
240 if (ia6 == NULL ||
241 (ia6->ia6_flags & (IN6_IFF_ANYCAST | IN6_IFF_NOTREADY))) {
242 *errorp = EADDRNOTAVAIL;
243 return (NULL);
244 }
245 pi->ipi6_addr = srcsock.sin6_addr; /* XXX: this overrides pi */
246 if (ifpp)
247 *ifpp = ifp;
248 return (&ia6->ia_addr.sin6_addr);
249 }
250
251 /*
252 * If the socket has already bound the source, just use it. We don't
253 * care at the moment whether in6_selectif() succeeded above, even
254 * though it would eventually cause an error.
255 */
256 if (laddr && !IN6_IS_ADDR_UNSPECIFIED(laddr))
257 return (laddr);
258
259 /*
260 * The outgoing interface is crucial in the general selection procedure
261 * below. If it is not known at this point, we fail.
262 */
263 if (ifp == NULL) {
264 *errorp = error;
265 return (NULL);
266 }
267
268 /*
269 * If the address is not yet determined, choose the best one based on
270 * the outgoing interface and the destination address.
271 */
272
273 #if defined(MIP6) && NMIP > 0
274 /*
275 * a caller can specify IP6PO_USECOA to not to use a home
276 * address. for example, the case that the neighbour
277 * unreachability detection to the global address.
278 */
279 if (opts != NULL &&
280 (opts->ip6po_flags & IP6PO_USECOA) != 0) {
281 ip6po_usecoa = 1;
282 }
283 #endif /* MIP6 && NMIP > 0 */
284
285 #ifdef DIAGNOSTIC
286 if (ifp == NULL) /* this should not happen */
287 panic("in6_selectsrc: NULL ifp");
288 #endif
289 *errorp = in6_setscope(&dst, ifp, &odstzone);
290 if (*errorp != 0)
291 return (NULL);
292
293 for (ia = in6_ifaddr; ia; ia = ia->ia_next) {
294 int new_scope = -1, new_matchlen = -1;
295 struct in6_addrpolicy *new_policy = NULL;
296 u_int32_t srczone, osrczone, dstzone;
297 struct in6_addr src;
298 struct ifnet *ifp1 = ia->ia_ifp;
299
300 /*
301 * We'll never take an address that breaks the scope zone
302 * of the destination. We also skip an address if its zone
303 * does not contain the outgoing interface.
304 * XXX: we should probably use sin6_scope_id here.
305 */
306 if (in6_setscope(&dst, ifp1, &dstzone) ||
307 odstzone != dstzone) {
308 continue;
309 }
310 src = ia->ia_addr.sin6_addr;
311 if (in6_setscope(&src, ifp, &osrczone) ||
312 in6_setscope(&src, ifp1, &srczone) ||
313 osrczone != srczone) {
314 continue;
315 }
316
317 /* avoid unusable addresses */
318 if ((ia->ia6_flags &
319 (IN6_IFF_NOTREADY | IN6_IFF_ANYCAST | IN6_IFF_DETACHED))) {
320 continue;
321 }
322 if (!ip6_use_deprecated && IFA6_IS_DEPRECATED(ia))
323 continue;
324
325 #if defined(MIP6) && NMIP > 0
326 /* avoid unusable home addresses. */
327 if ((ia->ia6_flags & IN6_IFF_HOME) &&
328 !mip6_ifa6_is_addr_valid_hoa(ia))
329 continue;
330 #endif /* MIP6 && NMIP > 0 */
331
332 /* Rule 1: Prefer same address */
333 if (IN6_ARE_ADDR_EQUAL(&dst, &ia->ia_addr.sin6_addr)) {
334 ia_best = ia;
335 BREAK(1); /* there should be no better candidate */
336 }
337
338 if (ia_best == NULL)
339 REPLACE(0);
340
341 /* Rule 2: Prefer appropriate scope */
342 if (dst_scope < 0)
343 dst_scope = in6_addrscope(&dst);
344 new_scope = in6_addrscope(&ia->ia_addr.sin6_addr);
345 if (IN6_ARE_SCOPE_CMP(best_scope, new_scope) < 0) {
346 if (IN6_ARE_SCOPE_CMP(best_scope, dst_scope) < 0)
347 REPLACE(2);
348 NEXT(2);
349 } else if (IN6_ARE_SCOPE_CMP(new_scope, best_scope) < 0) {
350 if (IN6_ARE_SCOPE_CMP(new_scope, dst_scope) < 0)
351 NEXT(2);
352 REPLACE(2);
353 }
354
355 /*
356 * Rule 3: Avoid deprecated addresses. Note that the case of
357 * !ip6_use_deprecated is already rejected above.
358 */
359 if (!IFA6_IS_DEPRECATED(ia_best) && IFA6_IS_DEPRECATED(ia))
360 NEXT(3);
361 if (IFA6_IS_DEPRECATED(ia_best) && !IFA6_IS_DEPRECATED(ia))
362 REPLACE(3);
363
364 /* Rule 4: Prefer home addresses */
365 #if defined(MIP6) && NMIP > 0
366 if (!MIP6_IS_MN)
367 goto skip_rule4;
368
369 if ((ia_best->ia6_flags & IN6_IFF_HOME) == 0 &&
370 (ia->ia6_flags & IN6_IFF_HOME) == 0) {
371 /* both address are not home addresses. */
372 goto skip_rule4;
373 }
374
375 /*
376 * If SA is simultaneously a home address and care-of
377 * address and SB is not, then prefer SA. Similarly,
378 * if SB is simultaneously a home address and care-of
379 * address and SA is not, then prefer SB.
380 */
381 if (((ia_best->ia6_flags & IN6_IFF_HOME) != 0 &&
382 ia_best->ia_ifp->if_type != IFT_MIP)
383 &&
384 ((ia->ia6_flags & IN6_IFF_HOME) != 0 &&
385 ia->ia_ifp->if_type == IFT_MIP))
386 NEXT(4);
387 if (((ia_best->ia6_flags & IN6_IFF_HOME) != 0 &&
388 ia_best->ia_ifp->if_type == IFT_MIP)
389 &&
390 ((ia->ia6_flags & IN6_IFF_HOME) != 0 &&
391 ia->ia_ifp->if_type != IFT_MIP))
392 REPLACE(4);
393 if (ip6po_usecoa == 0) {
394 /*
395 * If SA is just a home address and SB is just
396 * a care-of address, then prefer
397 * SA. Similarly, if SB is just a home address
398 * and SA is just a care-of address, then
399 * prefer SB.
400 */
401 if ((ia_best->ia6_flags & IN6_IFF_HOME) != 0 &&
402 (ia->ia6_flags & IN6_IFF_HOME) == 0) {
403 NEXT(4);
404 }
405 if ((ia_best->ia6_flags & IN6_IFF_HOME) == 0 &&
406 (ia->ia6_flags & IN6_IFF_HOME) != 0) {
407 REPLACE(4);
408 }
409 } else {
410 /*
411 * a sender don't want to use a home address
412 * because:
413 *
414 * 1) we cannot use. (ex. NS or NA to global
415 * addresses.)
416 *
417 * 2) a user specified not to use.
418 * (ex. mip6control -u)
419 */
420 if ((ia_best->ia6_flags & IN6_IFF_HOME) == 0 &&
421 (ia->ia6_flags & IN6_IFF_HOME) != 0) {
422 /* XXX breaks stat */
423 NEXT(0);
424 }
425 if ((ia_best->ia6_flags & IN6_IFF_HOME) != 0 &&
426 (ia->ia6_flags & IN6_IFF_HOME) == 0) {
427 /* XXX breaks stat */
428 REPLACE(0);
429 }
430 }
431 skip_rule4:
432 #endif /* MIP6 && NMIP > 0 */
433
434 /* Rule 5: Prefer outgoing interface */
435 if (ia_best->ia_ifp == ifp && ia->ia_ifp != ifp)
436 NEXT(5);
437 if (ia_best->ia_ifp != ifp && ia->ia_ifp == ifp)
438 REPLACE(5);
439
440 /*
441 * Rule 6: Prefer matching label
442 * Note that best_policy should be non-NULL here.
443 */
444 if (dst_policy == NULL)
445 dst_policy = lookup_addrsel_policy(dstsock);
446 if (dst_policy->label != ADDR_LABEL_NOTAPP) {
447 new_policy = lookup_addrsel_policy(&ia->ia_addr);
448 if (dst_policy->label == best_policy->label &&
449 dst_policy->label != new_policy->label)
450 NEXT(6);
451 if (dst_policy->label != best_policy->label &&
452 dst_policy->label == new_policy->label)
453 REPLACE(6);
454 }
455
456 /*
457 * Rule 7: Prefer public addresses.
458 * We allow users to reverse the logic by configuring
459 * a sysctl variable, so that privacy conscious users can
460 * always prefer temporary addresses.
461 */
462 #ifdef notyet /* until introducing ND extensions and address selection */
463 if (opts == NULL ||
464 opts->ip6po_prefer_tempaddr == IP6PO_TEMPADDR_SYSTEM) {
465 prefer_tempaddr = ip6_prefer_tempaddr;
466 } else if (opts->ip6po_prefer_tempaddr ==
467 IP6PO_TEMPADDR_NOTPREFER) {
468 prefer_tempaddr = 0;
469 } else
470 prefer_tempaddr = 1;
471 if (!(ia_best->ia6_flags & IN6_IFF_TEMPORARY) &&
472 (ia->ia6_flags & IN6_IFF_TEMPORARY)) {
473 if (prefer_tempaddr)
474 REPLACE(7);
475 else
476 NEXT(7);
477 }
478 if ((ia_best->ia6_flags & IN6_IFF_TEMPORARY) &&
479 !(ia->ia6_flags & IN6_IFF_TEMPORARY)) {
480 if (prefer_tempaddr)
481 NEXT(7);
482 else
483 REPLACE(7);
484 }
485 #endif
486
487 /*
488 * Rule 8: prefer addresses on alive interfaces.
489 * This is a KAME specific rule.
490 */
491 if ((ia_best->ia_ifp->if_flags & IFF_UP) &&
492 !(ia->ia_ifp->if_flags & IFF_UP))
493 NEXT(8);
494 if (!(ia_best->ia_ifp->if_flags & IFF_UP) &&
495 (ia->ia_ifp->if_flags & IFF_UP))
496 REPLACE(8);
497
498 /*
499 * Rule 9: prefer addresses on "preferred" interfaces.
500 * This is a KAME specific rule.
501 */
502 #ifdef notyet /* until introducing address selection */
503 #define NDI_BEST ND_IFINFO(ia_best->ia_ifp)
504 #define NDI_NEW ND_IFINFO(ia->ia_ifp)
505 if ((NDI_BEST->flags & ND6_IFF_PREFER_SOURCE) &&
506 !(NDI_NEW->flags & ND6_IFF_PREFER_SOURCE))
507 NEXT(9);
508 if (!(NDI_BEST->flags & ND6_IFF_PREFER_SOURCE) &&
509 (NDI_NEW->flags & ND6_IFF_PREFER_SOURCE))
510 REPLACE(9);
511 #undef NDI_BEST
512 #undef NDI_NEW
513 #endif
514
515 /*
516 * Rule 14: Use longest matching prefix.
517 * Note: in the address selection draft, this rule is
518 * documented as "Rule 8". However, since it is also
519 * documented that this rule can be overridden, we assign
520 * a large number so that it is easy to assign smaller numbers
521 * to more preferred rules.
522 */
523 new_matchlen = in6_matchlen(&ia->ia_addr.sin6_addr, &dst);
524 if (best_matchlen < new_matchlen)
525 REPLACE(14);
526 if (new_matchlen < best_matchlen)
527 NEXT(14);
528
529 /* Rule 15 is reserved. */
530
531 /*
532 * Last resort: just keep the current candidate.
533 * Or, do we need more rules?
534 */
535 continue;
536
537 replace:
538 ia_best = ia;
539 best_scope = (new_scope >= 0 ? new_scope :
540 in6_addrscope(&ia_best->ia_addr.sin6_addr));
541 best_policy = (new_policy ? new_policy :
542 lookup_addrsel_policy(&ia_best->ia_addr));
543 best_matchlen = (new_matchlen >= 0 ? new_matchlen :
544 in6_matchlen(&ia_best->ia_addr.sin6_addr,
545 &dst));
546
547 next:
548 continue;
549
550 out:
551 break;
552 }
553
554 if ((ia = ia_best) == NULL) {
555 *errorp = EADDRNOTAVAIL;
556 return (NULL);
557 }
558
559 return (&ia->ia_addr.sin6_addr);
560 }
561 #undef REPLACE
562 #undef BREAK
563 #undef NEXT
564
565 static int
566 selectroute(struct sockaddr_in6 *dstsock, struct ip6_pktopts *opts,
567 struct ip6_moptions *mopts, struct route *ro, struct ifnet **retifp,
568 struct rtentry **retrt, int clone, int norouteok)
569 {
570 int error = 0;
571 struct ifnet *ifp = NULL;
572 struct rtentry *rt = NULL;
573 struct sockaddr_in6 *sin6_next;
574 struct in6_pktinfo *pi = NULL;
575 struct in6_addr *dst;
576
577 dst = &dstsock->sin6_addr;
578
579 #if 0
580 if (dstsock->sin6_addr.s6_addr32[0] == 0 &&
581 dstsock->sin6_addr.s6_addr32[1] == 0 &&
582 !IN6_IS_ADDR_LOOPBACK(&dstsock->sin6_addr)) {
583 printf("in6_selectroute: strange destination %s\n",
584 ip6_sprintf(&dstsock->sin6_addr));
585 } else {
586 printf("in6_selectroute: destination = %s%%%d\n",
587 ip6_sprintf(&dstsock->sin6_addr),
588 dstsock->sin6_scope_id); /* for debug */
589 }
590 #endif
591
592 /* If the caller specify the outgoing interface explicitly, use it. */
593 if (opts && (pi = opts->ip6po_pktinfo) != NULL && pi->ipi6_ifindex) {
594 ifp = if_byindex(pi->ipi6_ifindex);
595 if (ifp != NULL &&
596 (norouteok || retrt == NULL ||
597 IN6_IS_ADDR_MULTICAST(dst))) {
598 /*
599 * we do not have to check or get the route for
600 * multicast.
601 */
602 goto done;
603 } else
604 goto getroute;
605 }
606
607 /*
608 * If the destination address is a multicast address and the outgoing
609 * interface for the address is specified by the caller, use it.
610 */
611 if (IN6_IS_ADDR_MULTICAST(dst) &&
612 mopts != NULL && (ifp = mopts->im6o_multicast_ifp) != NULL) {
613 goto done; /* we do not need a route for multicast. */
614 }
615
616 getroute:
617 /*
618 * If the next hop address for the packet is specified by the caller,
619 * use it as the gateway.
620 */
621 if (opts && opts->ip6po_nexthop) {
622 struct route *ron;
623
624 sin6_next = satosin6(opts->ip6po_nexthop);
625
626 /* at this moment, we only support AF_INET6 next hops */
627 if (sin6_next->sin6_family != AF_INET6) {
628 error = EAFNOSUPPORT; /* or should we proceed? */
629 goto done;
630 }
631
632 /*
633 * If the next hop is an IPv6 address, then the node identified
634 * by that address must be a neighbor of the sending host.
635 */
636 ron = &opts->ip6po_nextroute;
637 if ((rt = rtcache_lookup(ron, sin6tosa(sin6_next))) == NULL ||
638 (rt->rt_flags & RTF_GATEWAY) != 0 ||
639 !nd6_is_addr_neighbor(sin6_next, rt->rt_ifp)) {
640 rtcache_free(ron);
641 error = EHOSTUNREACH;
642 goto done;
643 }
644 ifp = rt->rt_ifp;
645
646 /*
647 * When cloning is required, try to allocate a route to the
648 * destination so that the caller can store path MTU
649 * information.
650 */
651 if (!clone)
652 goto done;
653 }
654
655 /*
656 * Use a cached route if it exists and is valid, else try to allocate
657 * a new one. Note that we should check the address family of the
658 * cached destination, in case of sharing the cache with IPv4.
659 */
660 if (ro != NULL) {
661 union {
662 struct sockaddr dst;
663 struct sockaddr_in6 dst6;
664 } u;
665
666 /* No route yet, so try to acquire one */
667 u.dst6 = *dstsock;
668 u.dst6.sin6_scope_id = 0;
669 rt = rtcache_lookup1(ro, &u.dst, clone);
670
671 /*
672 * do not care about the result if we have the nexthop
673 * explicitly specified.
674 */
675 if (opts && opts->ip6po_nexthop)
676 goto done;
677
678 if (rt == NULL)
679 error = EHOSTUNREACH;
680 else
681 ifp = rt->rt_ifp;
682
683 /*
684 * Check if the outgoing interface conflicts with
685 * the interface specified by ipi6_ifindex (if specified).
686 * Note that loopback interface is always okay.
687 * (this may happen when we are sending a packet to one of
688 * our own addresses.)
689 */
690 if (opts && opts->ip6po_pktinfo &&
691 opts->ip6po_pktinfo->ipi6_ifindex) {
692 if (!(ifp->if_flags & IFF_LOOPBACK) &&
693 ifp->if_index !=
694 opts->ip6po_pktinfo->ipi6_ifindex) {
695 error = EHOSTUNREACH;
696 goto done;
697 }
698 }
699 }
700
701 done:
702 if (ifp == NULL && rt == NULL) {
703 /*
704 * This can happen if the caller did not pass a cached route
705 * nor any other hints. We treat this case an error.
706 */
707 error = EHOSTUNREACH;
708 }
709 if (error == EHOSTUNREACH)
710 IP6_STATINC(IP6_STAT_NOROUTE);
711
712 if (retifp != NULL)
713 *retifp = ifp;
714 if (retrt != NULL)
715 *retrt = rt; /* rt may be NULL */
716
717 return (error);
718 }
719
720 static int
721 in6_selectif(struct sockaddr_in6 *dstsock, struct ip6_pktopts *opts,
722 struct ip6_moptions *mopts, struct route *ro, struct ifnet **retifp)
723 {
724 int error, clone;
725 struct rtentry *rt = NULL;
726
727 clone = IN6_IS_ADDR_MULTICAST(&dstsock->sin6_addr) ? 0 : 1;
728 if ((error = selectroute(dstsock, opts, mopts, ro, retifp,
729 &rt, clone, 1)) != 0) {
730 return (error);
731 }
732
733 /*
734 * do not use a rejected or black hole route.
735 * XXX: this check should be done in the L2 output routine.
736 * However, if we skipped this check here, we'd see the following
737 * scenario:
738 * - install a rejected route for a scoped address prefix
739 * (like fe80::/10)
740 * - send a packet to a destination that matches the scoped prefix,
741 * with ambiguity about the scope zone.
742 * - pick the outgoing interface from the route, and disambiguate the
743 * scope zone with the interface.
744 * - ip6_output() would try to get another route with the "new"
745 * destination, which may be valid.
746 * - we'd see no error on output.
747 * Although this may not be very harmful, it should still be confusing.
748 * We thus reject the case here.
749 */
750 if (rt && (rt->rt_flags & (RTF_REJECT | RTF_BLACKHOLE)))
751 return (rt->rt_flags & RTF_HOST ? EHOSTUNREACH : ENETUNREACH);
752
753 /*
754 * Adjust the "outgoing" interface. If we're going to loop the packet
755 * back to ourselves, the ifp would be the loopback interface.
756 * However, we'd rather know the interface associated to the
757 * destination address (which should probably be one of our own
758 * addresses.)
759 */
760 if (rt && rt->rt_ifa && rt->rt_ifa->ifa_ifp)
761 *retifp = rt->rt_ifa->ifa_ifp;
762
763 return (0);
764 }
765
766 /*
767 * close - meaningful only for bsdi and freebsd.
768 */
769
770 int
771 in6_selectroute(struct sockaddr_in6 *dstsock, struct ip6_pktopts *opts,
772 struct ip6_moptions *mopts, struct route *ro, struct ifnet **retifp,
773 struct rtentry **retrt, int clone)
774 {
775 return selectroute(dstsock, opts, mopts, ro, retifp,
776 retrt, clone, 0);
777 }
778
779 /*
780 * Default hop limit selection. The precedence is as follows:
781 * 1. Hoplimit value specified via ioctl.
782 * 2. (If the outgoing interface is detected) the current
783 * hop limit of the interface specified by router advertisement.
784 * 3. The system default hoplimit.
785 */
786 int
787 in6_selecthlim(struct in6pcb *in6p, struct ifnet *ifp)
788 {
789 if (in6p && in6p->in6p_hops >= 0)
790 return (in6p->in6p_hops);
791 else if (ifp)
792 return (ND_IFINFO(ifp)->chlim);
793 else
794 return (ip6_defhlim);
795 }
796
797 /*
798 * Find an empty port and set it to the specified PCB.
799 */
800 int
801 in6_pcbsetport(struct sockaddr_in6 *sin6, struct in6pcb *in6p, struct lwp *l)
802 {
803 struct socket *so = in6p->in6p_socket;
804 struct inpcbtable *table = in6p->in6p_table;
805 u_int16_t lport, *lastport;
806 enum kauth_network_req req;
807 int error = 0;
808
809 if (in6p->in6p_flags & IN6P_LOWPORT) {
810 #ifndef IPNOPRIVPORTS
811 req = KAUTH_REQ_NETWORK_BIND_PRIVPORT;
812 #else
813 req = KAUTH_REQ_NETWORK_BIND_PORT;
814 #endif
815 lastport = &table->inpt_lastlow;
816 } else {
817 req = KAUTH_REQ_NETWORK_BIND_PORT;
818
819 lastport = &table->inpt_lastport;
820 }
821
822 /* XXX-kauth: KAUTH_REQ_NETWORK_BIND_AUTOASSIGN_{,PRIV}PORT */
823 error = kauth_authorize_network(l->l_cred, KAUTH_NETWORK_BIND, req, so,
824 sin6, NULL);
825 if (error)
826 return (EACCES);
827
828 /*
829 * Use RFC6056 randomized port selection
830 */
831 error = portalgo_randport(&lport, &in6p->in6p_head, l->l_cred);
832 if (error)
833 return error;
834
835 in6p->in6p_flags |= IN6P_ANONPORT;
836 *lastport = lport;
837 in6p->in6p_lport = htons(lport);
838 in6_pcbstate(in6p, IN6P_BOUND);
839 return (0); /* success */
840 }
841
842 void
843 addrsel_policy_init(void)
844 {
845 init_policy_queue();
846
847 /* initialize the "last resort" policy */
848 memset(&defaultaddrpolicy, 0, sizeof(defaultaddrpolicy));
849 defaultaddrpolicy.label = ADDR_LABEL_NOTAPP;
850 }
851
852 static struct in6_addrpolicy *
853 lookup_addrsel_policy(struct sockaddr_in6 *key)
854 {
855 struct in6_addrpolicy *match = NULL;
856
857 match = match_addrsel_policy(key);
858
859 if (match == NULL)
860 match = &defaultaddrpolicy;
861 else
862 match->use++;
863
864 return (match);
865 }
866
867 /*
868 * Subroutines to manage the address selection policy table via sysctl.
869 */
870 struct sel_walkarg {
871 size_t w_total;
872 size_t w_given;
873 void * w_where;
874 void *w_limit;
875 };
876
877 int
878 in6_src_sysctl(void *oldp, size_t *oldlenp, void *newp, size_t newlen)
879 {
880 int error = 0;
881 int s;
882
883 s = splsoftnet();
884
885 if (newp) {
886 error = EPERM;
887 goto end;
888 }
889 if (oldp && oldlenp == NULL) {
890 error = EINVAL;
891 goto end;
892 }
893 if (oldp || oldlenp) {
894 struct sel_walkarg w;
895 size_t oldlen = *oldlenp;
896
897 memset(&w, 0, sizeof(w));
898 w.w_given = oldlen;
899 w.w_where = oldp;
900 if (oldp)
901 w.w_limit = (char *)oldp + oldlen;
902
903 error = walk_addrsel_policy(dump_addrsel_policyent, &w);
904
905 *oldlenp = w.w_total;
906 if (oldp && w.w_total > oldlen && error == 0)
907 error = ENOMEM;
908 }
909
910 end:
911 splx(s);
912
913 return (error);
914 }
915
916 int
917 in6_src_ioctl(u_long cmd, void *data)
918 {
919 int i;
920 struct in6_addrpolicy ent0;
921
922 if (cmd != SIOCAADDRCTL_POLICY && cmd != SIOCDADDRCTL_POLICY)
923 return (EOPNOTSUPP); /* check for safety */
924
925 ent0 = *(struct in6_addrpolicy *)data;
926
927 if (ent0.label == ADDR_LABEL_NOTAPP)
928 return (EINVAL);
929 /* check if the prefix mask is consecutive. */
930 if (in6_mask2len(&ent0.addrmask.sin6_addr, NULL) < 0)
931 return (EINVAL);
932 /* clear trailing garbages (if any) of the prefix address. */
933 for (i = 0; i < 4; i++) {
934 ent0.addr.sin6_addr.s6_addr32[i] &=
935 ent0.addrmask.sin6_addr.s6_addr32[i];
936 }
937 ent0.use = 0;
938
939 switch (cmd) {
940 case SIOCAADDRCTL_POLICY:
941 return (add_addrsel_policyent(&ent0));
942 case SIOCDADDRCTL_POLICY:
943 return (delete_addrsel_policyent(&ent0));
944 }
945
946 return (0); /* XXX: compromise compilers */
947 }
948
949 /*
950 * The followings are implementation of the policy table using a
951 * simple tail queue.
952 * XXX such details should be hidden.
953 * XXX implementation using binary tree should be more efficient.
954 */
955 struct addrsel_policyent {
956 TAILQ_ENTRY(addrsel_policyent) ape_entry;
957 struct in6_addrpolicy ape_policy;
958 };
959
960 TAILQ_HEAD(addrsel_policyhead, addrsel_policyent);
961
962 struct addrsel_policyhead addrsel_policytab;
963
964 static void
965 init_policy_queue(void)
966 {
967 TAILQ_INIT(&addrsel_policytab);
968 }
969
970 static int
971 add_addrsel_policyent(struct in6_addrpolicy *newpolicy)
972 {
973 struct addrsel_policyent *new, *pol;
974
975 /* duplication check */
976 for (pol = TAILQ_FIRST(&addrsel_policytab); pol;
977 pol = TAILQ_NEXT(pol, ape_entry)) {
978 if (IN6_ARE_ADDR_EQUAL(&newpolicy->addr.sin6_addr,
979 &pol->ape_policy.addr.sin6_addr) &&
980 IN6_ARE_ADDR_EQUAL(&newpolicy->addrmask.sin6_addr,
981 &pol->ape_policy.addrmask.sin6_addr)) {
982 return (EEXIST); /* or override it? */
983 }
984 }
985
986 new = malloc(sizeof(*new), M_IFADDR, M_WAITOK|M_ZERO);
987
988 /* XXX: should validate entry */
989 new->ape_policy = *newpolicy;
990
991 TAILQ_INSERT_TAIL(&addrsel_policytab, new, ape_entry);
992
993 return (0);
994 }
995
996 static int
997 delete_addrsel_policyent(struct in6_addrpolicy *key)
998 {
999 struct addrsel_policyent *pol;
1000
1001 /* search for the entry in the table */
1002 for (pol = TAILQ_FIRST(&addrsel_policytab); pol;
1003 pol = TAILQ_NEXT(pol, ape_entry)) {
1004 if (IN6_ARE_ADDR_EQUAL(&key->addr.sin6_addr,
1005 &pol->ape_policy.addr.sin6_addr) &&
1006 IN6_ARE_ADDR_EQUAL(&key->addrmask.sin6_addr,
1007 &pol->ape_policy.addrmask.sin6_addr)) {
1008 break;
1009 }
1010 }
1011 if (pol == NULL) {
1012 return (ESRCH);
1013 }
1014
1015 TAILQ_REMOVE(&addrsel_policytab, pol, ape_entry);
1016
1017 return (0);
1018 }
1019
1020 static int
1021 walk_addrsel_policy(int (*callback)(struct in6_addrpolicy *, void *), void *w)
1022 {
1023 struct addrsel_policyent *pol;
1024 int error = 0;
1025
1026 TAILQ_FOREACH(pol, &addrsel_policytab, ape_entry) {
1027 if ((error = (*callback)(&pol->ape_policy, w)) != 0)
1028 return error;
1029 }
1030
1031 return error;
1032 }
1033
1034 static int
1035 dump_addrsel_policyent(struct in6_addrpolicy *pol, void *arg)
1036 {
1037 int error = 0;
1038 struct sel_walkarg *w = arg;
1039
1040 if (w->w_where && (char *)w->w_where + sizeof(*pol) <= (char *)w->w_limit) {
1041 if ((error = copyout(pol, w->w_where, sizeof(*pol))) != 0)
1042 return error;
1043 w->w_where = (char *)w->w_where + sizeof(*pol);
1044 }
1045 w->w_total += sizeof(*pol);
1046
1047 return error;
1048 }
1049
1050 static struct in6_addrpolicy *
1051 match_addrsel_policy(struct sockaddr_in6 *key)
1052 {
1053 struct addrsel_policyent *pent;
1054 struct in6_addrpolicy *bestpol = NULL, *pol;
1055 int matchlen, bestmatchlen = -1;
1056 u_char *mp, *ep, *k, *p, m;
1057
1058 for (pent = TAILQ_FIRST(&addrsel_policytab); pent;
1059 pent = TAILQ_NEXT(pent, ape_entry)) {
1060 matchlen = 0;
1061
1062 pol = &pent->ape_policy;
1063 mp = (u_char *)&pol->addrmask.sin6_addr;
1064 ep = mp + 16; /* XXX: scope field? */
1065 k = (u_char *)&key->sin6_addr;
1066 p = (u_char *)&pol->addr.sin6_addr;
1067 for (; mp < ep && *mp; mp++, k++, p++) {
1068 m = *mp;
1069 if ((*k & m) != *p)
1070 goto next; /* not match */
1071 if (m == 0xff) /* short cut for a typical case */
1072 matchlen += 8;
1073 else {
1074 while (m >= 0x80) {
1075 matchlen++;
1076 m <<= 1;
1077 }
1078 }
1079 }
1080
1081 /* matched. check if this is better than the current best. */
1082 if (bestpol == NULL ||
1083 matchlen > bestmatchlen) {
1084 bestpol = pol;
1085 bestmatchlen = matchlen;
1086 }
1087
1088 next:
1089 continue;
1090 }
1091
1092 return (bestpol);
1093 }
1094