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