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