Home | History | Annotate | Line # | Download | only in netinet6
in6_src.c revision 1.55.2.9
      1 /*	$NetBSD: in6_src.c,v 1.55.2.9 2017/02/05 13:40:59 skrll 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.55.2.9 2017/02/05 13:40:59 skrll 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;
    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 	error = 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 		goto exit;
    554 
    555 	/*
    556 	 * If the address is not yet determined, choose the best one based on
    557 	 * the outgoing interface and the destination address.
    558 	 */
    559 
    560 #if defined(MIP6) && NMIP > 0
    561 	/*
    562 	 * a caller can specify IP6PO_USECOA to not to use a home
    563 	 * address.  for example, the case that the neighbour
    564 	 * unreachability detection to the global address.
    565 	 */
    566 	if (opts != NULL &&
    567 	    (opts->ip6po_flags & IP6PO_USECOA) != 0) {
    568 		ip6po_usecoa = 1;
    569 	}
    570 #endif /* MIP6 && NMIP > 0 */
    571 
    572 	error = in6_setscope(&dst, ifp, &odstzone);
    573 	if (error != 0)
    574 		goto exit;
    575 
    576 	s = pserialize_read_enter();
    577 
    578 	ia = in6_select_best_ia(dstsock, &dst, ifp, opts, odstzone);
    579 	if (ia == NULL) {
    580 		pserialize_read_exit(s);
    581 		error = EADDRNOTAVAIL;
    582 		goto exit;
    583 	}
    584 	*ret_ia6 = ia->ia_addr.sin6_addr;
    585 
    586 	pserialize_read_exit(s);
    587 exit:
    588 	if (ifpp == NULL)
    589 		if_put(ifp, PSREF);
    590 	curlwp_bindx(bound);
    591 	return error;
    592 #undef PSREF
    593 }
    594 
    595 int
    596 in6_selectroute(struct sockaddr_in6 *dstsock, struct ip6_pktopts *opts,
    597     struct route **ro, struct rtentry **retrt, bool count_discard)
    598 {
    599 	int error = 0;
    600 	struct rtentry *rt = NULL;
    601 	union {
    602 		struct sockaddr		dst;
    603 		struct sockaddr_in6	dst6;
    604 	} u;
    605 
    606 	KASSERT(ro != NULL);
    607 	KASSERT(*ro != NULL);
    608 	KASSERT(retrt != NULL);
    609 
    610 #if 0
    611 	if (dstsock->sin6_addr.s6_addr32[0] == 0 &&
    612 	    dstsock->sin6_addr.s6_addr32[1] == 0 &&
    613 	    !IN6_IS_ADDR_LOOPBACK(&dstsock->sin6_addr)) {
    614 		char ip6buf[INET6_ADDRSTRLEN];
    615 		printf("in6_selectroute: strange destination %s\n",
    616 		       IN6_PRINT(ip6buf, &dstsock->sin6_addr));
    617 	} else {
    618 		char ip6buf[INET6_ADDRSTRLEN];
    619 		printf("in6_selectroute: destination = %s%%%d\n",
    620 		       IN6_PRINT(ip6buf, &dstsock->sin6_addr),
    621 		       dstsock->sin6_scope_id); /* for debug */
    622 	}
    623 #endif
    624 
    625 	/*
    626 	 * If the next hop address for the packet is specified by the caller,
    627 	 * use it as the gateway.
    628 	 */
    629 	if (opts && opts->ip6po_nexthop) {
    630 		struct route *ron;
    631 		struct sockaddr_in6 *sin6_next;
    632 
    633 		sin6_next = satosin6(opts->ip6po_nexthop);
    634 
    635 		/* at this moment, we only support AF_INET6 next hops */
    636 		if (sin6_next->sin6_family != AF_INET6) {
    637 			error = EAFNOSUPPORT; /* or should we proceed? */
    638 			goto done;
    639 		}
    640 
    641 		/*
    642 		 * If the next hop is an IPv6 address, then the node identified
    643 		 * by that address must be a neighbor of the sending host.
    644 		 */
    645 		ron = &opts->ip6po_nextroute;
    646 		rt = rtcache_lookup(ron, sin6tosa(sin6_next));
    647 		if (rt == NULL || (rt->rt_flags & RTF_GATEWAY) != 0 ||
    648 		    !nd6_is_addr_neighbor(sin6_next, rt->rt_ifp)) {
    649 			if (rt != NULL) {
    650 				if (count_discard)
    651 					in6_ifstat_inc(rt->rt_ifp,
    652 					    ifs6_out_discard);
    653 				rtcache_unref(rt, ron);
    654 				rt = NULL;
    655 			}
    656 			rtcache_free(ron);
    657 			error = EHOSTUNREACH;
    658 			goto done;
    659 		}
    660 		*ro = ron;
    661 
    662 		goto done;
    663 	}
    664 
    665 	/*
    666 	 * Use a cached route if it exists and is valid, else try to allocate
    667 	 * a new one.  Note that we should check the address family of the
    668 	 * cached destination, in case of sharing the cache with IPv4.
    669 	 */
    670 	u.dst6 = *dstsock;
    671 	u.dst6.sin6_scope_id = 0;
    672 	rt = rtcache_lookup1(*ro, &u.dst, 1);
    673 
    674 	if (rt == NULL)
    675 		error = EHOSTUNREACH;
    676 
    677 	/*
    678 	 * Check if the outgoing interface conflicts with
    679 	 * the interface specified by ipi6_ifindex (if specified).
    680 	 * Note that loopback interface is always okay.
    681 	 * (this may happen when we are sending a packet to one of
    682 	 *  our own addresses.)
    683 	 */
    684 	if (opts && opts->ip6po_pktinfo && opts->ip6po_pktinfo->ipi6_ifindex) {
    685 		if (rt != NULL && !(rt->rt_ifp->if_flags & IFF_LOOPBACK) &&
    686 		    rt->rt_ifp->if_index != opts->ip6po_pktinfo->ipi6_ifindex) {
    687 			if (count_discard)
    688 				in6_ifstat_inc(rt->rt_ifp, ifs6_out_discard);
    689 			error = EHOSTUNREACH;
    690 			rt = NULL;
    691 		}
    692 	}
    693 
    694 done:
    695 	if (error == EHOSTUNREACH)
    696 		IP6_STATINC(IP6_STAT_NOROUTE);
    697 	*retrt = rt;
    698 	return error;
    699 }
    700 
    701 static int
    702 in6_selectif(struct sockaddr_in6 *dstsock, struct ip6_pktopts *opts,
    703 	struct ip6_moptions *mopts, struct route *ro, struct ifnet **retifp,
    704 	struct psref *psref)
    705 {
    706 	int error = 0;
    707 	struct rtentry *rt = NULL;
    708 	struct in6_addr *dst;
    709 	struct in6_pktinfo *pi = NULL;
    710 
    711 	KASSERT(retifp != NULL);
    712 	*retifp = NULL;
    713 	dst = &dstsock->sin6_addr;
    714 
    715 	/* If the caller specify the outgoing interface explicitly, use it. */
    716 	if (opts && (pi = opts->ip6po_pktinfo) != NULL && pi->ipi6_ifindex) {
    717 		/* XXX boundary check is assumed to be already done. */
    718 		*retifp = if_get_byindex(pi->ipi6_ifindex, psref);
    719 		if (*retifp != NULL)
    720 			return 0;
    721 		goto getroute;
    722 	}
    723 
    724 	/*
    725 	 * If the destination address is a multicast address and the outgoing
    726 	 * interface for the address is specified by the caller, use it.
    727 	 */
    728 	if (IN6_IS_ADDR_MULTICAST(dst) && mopts != NULL) {
    729 		*retifp = if_get_byindex(mopts->im6o_multicast_if_index, psref);
    730 		if (*retifp != NULL)
    731 			return 0; /* we do not need a route for multicast. */
    732 	}
    733 
    734 getroute:
    735 	error = in6_selectroute(dstsock, opts, &ro, &rt, false);
    736 	if (error != 0)
    737 		return error;
    738 
    739 	*retifp = if_get_byindex(rt->rt_ifp->if_index, psref);
    740 
    741 	/*
    742 	 * do not use a rejected or black hole route.
    743 	 * XXX: this check should be done in the L2 output routine.
    744 	 * However, if we skipped this check here, we'd see the following
    745 	 * scenario:
    746 	 * - install a rejected route for a scoped address prefix
    747 	 *   (like fe80::/10)
    748 	 * - send a packet to a destination that matches the scoped prefix,
    749 	 *   with ambiguity about the scope zone.
    750 	 * - pick the outgoing interface from the route, and disambiguate the
    751 	 *   scope zone with the interface.
    752 	 * - ip6_output() would try to get another route with the "new"
    753 	 *   destination, which may be valid.
    754 	 * - we'd see no error on output.
    755 	 * Although this may not be very harmful, it should still be confusing.
    756 	 * We thus reject the case here.
    757 	 */
    758 	if ((rt->rt_flags & (RTF_REJECT | RTF_BLACKHOLE))) {
    759 		error = (rt->rt_flags & RTF_HOST ? EHOSTUNREACH : ENETUNREACH);
    760 		/* XXX: ifp can be returned with psref even if error */
    761 		goto out;
    762 	}
    763 
    764 	/*
    765 	 * Adjust the "outgoing" interface.  If we're going to loop the packet
    766 	 * back to ourselves, the ifp would be the loopback interface.
    767 	 * However, we'd rather know the interface associated to the
    768 	 * destination address (which should probably be one of our own
    769 	 * addresses.)
    770 	 */
    771 	if (rt->rt_ifa && rt->rt_ifa->ifa_ifp &&
    772 	    rt->rt_ifa->ifa_ifp != *retifp &&
    773 	    !if_is_deactivated(rt->rt_ifa->ifa_ifp)) {
    774 		if_put(*retifp, psref);
    775 		*retifp = rt->rt_ifa->ifa_ifp;
    776 		if_acquire_NOMPSAFE(*retifp, psref);
    777 	}
    778 out:
    779 	rtcache_unref(rt, ro);
    780 	return error;
    781 }
    782 
    783 /*
    784  * Default hop limit selection. The precedence is as follows:
    785  * 1. Hoplimit value specified via ioctl.
    786  * 2. (If the outgoing interface is detected) the current
    787  *     hop limit of the interface specified by router advertisement.
    788  * 3. The system default hoplimit.
    789 */
    790 int
    791 in6_selecthlim(struct in6pcb *in6p, struct ifnet *ifp)
    792 {
    793 	if (in6p && in6p->in6p_hops >= 0)
    794 		return (in6p->in6p_hops);
    795 	else if (ifp)
    796 		return (ND_IFINFO(ifp)->chlim);
    797 	else
    798 		return (ip6_defhlim);
    799 }
    800 
    801 int
    802 in6_selecthlim_rt(struct in6pcb *in6p)
    803 {
    804 	struct rtentry *rt;
    805 
    806 	if (in6p == NULL)
    807 		return in6_selecthlim(in6p, NULL);
    808 
    809 	rt = rtcache_validate(&in6p->in6p_route);
    810 	if (rt != NULL) {
    811 		int ret = in6_selecthlim(in6p, rt->rt_ifp);
    812 		rtcache_unref(rt, &in6p->in6p_route);
    813 		return ret;
    814 	} else
    815 		return in6_selecthlim(in6p, NULL);
    816 }
    817 
    818 /*
    819  * Find an empty port and set it to the specified PCB.
    820  */
    821 int
    822 in6_pcbsetport(struct sockaddr_in6 *sin6, struct in6pcb *in6p, struct lwp *l)
    823 {
    824 	struct socket *so = in6p->in6p_socket;
    825 	struct inpcbtable *table = in6p->in6p_table;
    826 	u_int16_t lport, *lastport;
    827 	enum kauth_network_req req;
    828 	int error = 0;
    829 
    830 	if (in6p->in6p_flags & IN6P_LOWPORT) {
    831 #ifndef IPNOPRIVPORTS
    832 		req = KAUTH_REQ_NETWORK_BIND_PRIVPORT;
    833 #else
    834 		req = KAUTH_REQ_NETWORK_BIND_PORT;
    835 #endif
    836 		lastport = &table->inpt_lastlow;
    837 	} else {
    838 		req = KAUTH_REQ_NETWORK_BIND_PORT;
    839 
    840 		lastport = &table->inpt_lastport;
    841 	}
    842 
    843 	/* XXX-kauth: KAUTH_REQ_NETWORK_BIND_AUTOASSIGN_{,PRIV}PORT */
    844 	error = kauth_authorize_network(l->l_cred, KAUTH_NETWORK_BIND, req, so,
    845 	    sin6, NULL);
    846 	if (error)
    847 		return (EACCES);
    848 
    849        /*
    850         * Use RFC6056 randomized port selection
    851         */
    852 	error = portalgo_randport(&lport, &in6p->in6p_head, l->l_cred);
    853 	if (error)
    854 		return error;
    855 
    856 	in6p->in6p_flags |= IN6P_ANONPORT;
    857 	*lastport = lport;
    858 	in6p->in6p_lport = htons(lport);
    859 	in6_pcbstate(in6p, IN6P_BOUND);
    860 	return (0);		/* success */
    861 }
    862 
    863 void
    864 addrsel_policy_init(void)
    865 {
    866 	init_policy_queue();
    867 
    868 	/* initialize the "last resort" policy */
    869 	memset(&defaultaddrpolicy, 0, sizeof(defaultaddrpolicy));
    870 	defaultaddrpolicy.label = ADDR_LABEL_NOTAPP;
    871 }
    872 
    873 static struct in6_addrpolicy *
    874 lookup_addrsel_policy(struct sockaddr_in6 *key)
    875 {
    876 	struct in6_addrpolicy *match = NULL;
    877 
    878 	match = match_addrsel_policy(key);
    879 
    880 	if (match == NULL)
    881 		match = &defaultaddrpolicy;
    882 	else
    883 		match->use++;
    884 
    885 	return (match);
    886 }
    887 
    888 /*
    889  * Subroutines to manage the address selection policy table via sysctl.
    890  */
    891 struct sel_walkarg {
    892 	size_t	w_total;
    893 	size_t	w_given;
    894 	void *	w_where;
    895 	void *w_limit;
    896 };
    897 
    898 int sysctl_net_inet6_addrctlpolicy(SYSCTLFN_ARGS);
    899 int
    900 sysctl_net_inet6_addrctlpolicy(SYSCTLFN_ARGS)
    901 {
    902 	int error = 0;
    903 	int s;
    904 
    905 	s = splsoftnet();
    906 
    907 	if (newp) {
    908 		error = EPERM;
    909 		goto end;
    910 	}
    911 	if (oldp && oldlenp == NULL) {
    912 		error = EINVAL;
    913 		goto end;
    914 	}
    915 	if (oldp || oldlenp) {
    916 		struct sel_walkarg w;
    917 		size_t oldlen = *oldlenp;
    918 
    919 		memset(&w, 0, sizeof(w));
    920 		w.w_given = oldlen;
    921 		w.w_where = oldp;
    922 		if (oldp)
    923 			w.w_limit = (char *)oldp + oldlen;
    924 
    925 		error = walk_addrsel_policy(dump_addrsel_policyent, &w);
    926 
    927 		*oldlenp = w.w_total;
    928 		if (oldp && w.w_total > oldlen && error == 0)
    929 			error = ENOMEM;
    930 	}
    931 
    932   end:
    933 	splx(s);
    934 
    935 	return (error);
    936 }
    937 
    938 int
    939 in6_src_ioctl(u_long cmd, void *data)
    940 {
    941 	int i;
    942 	struct in6_addrpolicy ent0;
    943 
    944 	if (cmd != SIOCAADDRCTL_POLICY && cmd != SIOCDADDRCTL_POLICY)
    945 		return (EOPNOTSUPP); /* check for safety */
    946 
    947 	ent0 = *(struct in6_addrpolicy *)data;
    948 
    949 	if (ent0.label == ADDR_LABEL_NOTAPP)
    950 		return (EINVAL);
    951 	/* check if the prefix mask is consecutive. */
    952 	if (in6_mask2len(&ent0.addrmask.sin6_addr, NULL) < 0)
    953 		return (EINVAL);
    954 	/* clear trailing garbages (if any) of the prefix address. */
    955 	for (i = 0; i < 4; i++) {
    956 		ent0.addr.sin6_addr.s6_addr32[i] &=
    957 			ent0.addrmask.sin6_addr.s6_addr32[i];
    958 	}
    959 	ent0.use = 0;
    960 
    961 	switch (cmd) {
    962 	case SIOCAADDRCTL_POLICY:
    963 		return (add_addrsel_policyent(&ent0));
    964 	case SIOCDADDRCTL_POLICY:
    965 		return (delete_addrsel_policyent(&ent0));
    966 	}
    967 
    968 	return (0);		/* XXX: compromise compilers */
    969 }
    970 
    971 /*
    972  * The followings are implementation of the policy table using a
    973  * simple tail queue.
    974  * XXX such details should be hidden.
    975  * XXX implementation using binary tree should be more efficient.
    976  */
    977 struct addrsel_policyent {
    978 	TAILQ_ENTRY(addrsel_policyent) ape_entry;
    979 	struct in6_addrpolicy ape_policy;
    980 };
    981 
    982 TAILQ_HEAD(addrsel_policyhead, addrsel_policyent);
    983 
    984 struct addrsel_policyhead addrsel_policytab;
    985 
    986 static void
    987 init_policy_queue(void)
    988 {
    989 	TAILQ_INIT(&addrsel_policytab);
    990 }
    991 
    992 static int
    993 add_addrsel_policyent(struct in6_addrpolicy *newpolicy)
    994 {
    995 	struct addrsel_policyent *newpol, *pol;
    996 
    997 	/* duplication check */
    998 	TAILQ_FOREACH(pol, &addrsel_policytab, ape_entry) {
    999 		if (IN6_ARE_ADDR_EQUAL(&newpolicy->addr.sin6_addr,
   1000 		    &pol->ape_policy.addr.sin6_addr) &&
   1001 		    IN6_ARE_ADDR_EQUAL(&newpolicy->addrmask.sin6_addr,
   1002 		    &pol->ape_policy.addrmask.sin6_addr)) {
   1003 			return (EEXIST);	/* or override it? */
   1004 		}
   1005 	}
   1006 
   1007 	newpol = malloc(sizeof(*newpol), M_IFADDR, M_WAITOK|M_ZERO);
   1008 
   1009 	/* XXX: should validate entry */
   1010 	newpol->ape_policy = *newpolicy;
   1011 
   1012 	TAILQ_INSERT_TAIL(&addrsel_policytab, newpol, ape_entry);
   1013 
   1014 	return (0);
   1015 }
   1016 
   1017 static int
   1018 delete_addrsel_policyent(struct in6_addrpolicy *key)
   1019 {
   1020 	struct addrsel_policyent *pol;
   1021 
   1022 	/* search for the entry in the table */
   1023 	for (pol = TAILQ_FIRST(&addrsel_policytab); pol;
   1024 	     pol = TAILQ_NEXT(pol, ape_entry)) {
   1025 		if (IN6_ARE_ADDR_EQUAL(&key->addr.sin6_addr,
   1026 		    &pol->ape_policy.addr.sin6_addr) &&
   1027 		    IN6_ARE_ADDR_EQUAL(&key->addrmask.sin6_addr,
   1028 		    &pol->ape_policy.addrmask.sin6_addr)) {
   1029 			break;
   1030 		}
   1031 	}
   1032 	if (pol == NULL) {
   1033 		return (ESRCH);
   1034 	}
   1035 
   1036 	TAILQ_REMOVE(&addrsel_policytab, pol, ape_entry);
   1037 
   1038 	return (0);
   1039 }
   1040 
   1041 static int
   1042 walk_addrsel_policy(int (*callback)(struct in6_addrpolicy *, void *), void *w)
   1043 {
   1044 	struct addrsel_policyent *pol;
   1045 	int error = 0;
   1046 
   1047 	TAILQ_FOREACH(pol, &addrsel_policytab, ape_entry) {
   1048 		if ((error = (*callback)(&pol->ape_policy, w)) != 0)
   1049 			return error;
   1050 	}
   1051 
   1052 	return error;
   1053 }
   1054 
   1055 static int
   1056 dump_addrsel_policyent(struct in6_addrpolicy *pol, void *arg)
   1057 {
   1058 	int error = 0;
   1059 	struct sel_walkarg *w = arg;
   1060 
   1061 	if (w->w_where && (char *)w->w_where + sizeof(*pol) <= (char *)w->w_limit) {
   1062 		if ((error = copyout(pol, w->w_where, sizeof(*pol))) != 0)
   1063 			return error;
   1064 		w->w_where = (char *)w->w_where + sizeof(*pol);
   1065 	}
   1066 	w->w_total += sizeof(*pol);
   1067 
   1068 	return error;
   1069 }
   1070 
   1071 static struct in6_addrpolicy *
   1072 match_addrsel_policy(struct sockaddr_in6 *key)
   1073 {
   1074 	struct addrsel_policyent *pent;
   1075 	struct in6_addrpolicy *bestpol = NULL, *pol;
   1076 	int matchlen, bestmatchlen = -1;
   1077 	u_char *mp, *ep, *k, *p, m;
   1078 
   1079 	for (pent = TAILQ_FIRST(&addrsel_policytab); pent;
   1080 	     pent = TAILQ_NEXT(pent, ape_entry)) {
   1081 		matchlen = 0;
   1082 
   1083 		pol = &pent->ape_policy;
   1084 		mp = (u_char *)&pol->addrmask.sin6_addr;
   1085 		ep = mp + 16;	/* XXX: scope field? */
   1086 		k = (u_char *)&key->sin6_addr;
   1087 		p = (u_char *)&pol->addr.sin6_addr;
   1088 		for (; mp < ep && *mp; mp++, k++, p++) {
   1089 			m = *mp;
   1090 			if ((*k & m) != *p)
   1091 				goto next; /* not match */
   1092 			if (m == 0xff) /* short cut for a typical case */
   1093 				matchlen += 8;
   1094 			else {
   1095 				while (m >= 0x80) {
   1096 					matchlen++;
   1097 					m <<= 1;
   1098 				}
   1099 			}
   1100 		}
   1101 
   1102 		/* matched.  check if this is better than the current best. */
   1103 		if (bestpol == NULL ||
   1104 		    matchlen > bestmatchlen) {
   1105 			bestpol = pol;
   1106 			bestmatchlen = matchlen;
   1107 		}
   1108 
   1109 	  next:
   1110 		continue;
   1111 	}
   1112 
   1113 	return (bestpol);
   1114 }
   1115