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