Home | History | Annotate | Line # | Download | only in netinet6
in6_src.c revision 1.61
      1 /*	$NetBSD: in6_src.c,v 1.61 2016/06/21 03:28:27 ozaki-r 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.61 2016/06/21 03:28:27 ozaki-r 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 selectroute(struct sockaddr_in6 *, struct ip6_pktopts *,
    126 	struct ip6_moptions *, struct route *, struct ifnet **,
    127 	struct rtentry **, int, int);
    128 static int in6_selectif(struct sockaddr_in6 *, struct ip6_pktopts *,
    129 	struct ip6_moptions *, struct route *, struct ifnet **);
    130 
    131 static struct in6_addrpolicy *lookup_addrsel_policy(struct sockaddr_in6 *);
    132 
    133 static void init_policy_queue(void);
    134 static int add_addrsel_policyent(struct in6_addrpolicy *);
    135 static int delete_addrsel_policyent(struct in6_addrpolicy *);
    136 static int walk_addrsel_policy(int (*)(struct in6_addrpolicy *, void *),
    137 				    void *);
    138 static int dump_addrsel_policyent(struct in6_addrpolicy *, void *);
    139 static struct in6_addrpolicy *match_addrsel_policy(struct sockaddr_in6 *);
    140 
    141 /*
    142  * Return an IPv6 address, which is the most appropriate for a given
    143  * destination and user specified options.
    144  * If necessary, this function lookups the routing table and returns
    145  * an entry to the caller for later use.
    146  */
    147 #if 0				/* diabled ad-hoc */
    148 #define REPLACE(r) do {\
    149 	if ((r) < sizeof(ip6stat.ip6s_sources_rule) / \
    150 		sizeof(ip6stat.ip6s_sources_rule[0])) /* check for safety */ \
    151 		ip6stat.ip6s_sources_rule[(r)]++; \
    152 	/* 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)); */ \
    153 	goto replace; \
    154 } while(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("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)); */ \
    160 	goto next; 		/* XXX: we can't use 'continue' here */ \
    161 } while(0)
    162 #define BREAK(r) do { \
    163 	if ((r) < sizeof(ip6stat.ip6s_sources_rule) / \
    164 		sizeof(ip6stat.ip6s_sources_rule[0])) /* check for safety */ \
    165 		ip6stat.ip6s_sources_rule[(r)]++; \
    166 	goto out; 		/* XXX: we can't use 'break' here */ \
    167 } while(0)
    168 #else
    169 #define REPLACE(r) goto replace
    170 #define NEXT(r) goto next
    171 #define BREAK(r) goto out
    172 #endif
    173 
    174 struct in6_addr *
    175 in6_selectsrc(struct sockaddr_in6 *dstsock, struct ip6_pktopts *opts,
    176 	struct ip6_moptions *mopts, struct route *ro, struct in6_addr *laddr,
    177 	struct ifnet **ifpp, int *errorp)
    178 {
    179 	struct in6_addr dst;
    180 	struct ifnet *ifp = NULL;
    181 	struct in6_ifaddr *ia = NULL, *ia_best = NULL;
    182 	struct in6_pktinfo *pi = NULL;
    183 	int dst_scope = -1, best_scope = -1, best_matchlen = -1;
    184 	struct in6_addrpolicy *dst_policy = NULL, *best_policy = NULL;
    185 	u_int32_t odstzone;
    186 	int error;
    187 	int prefer_tempaddr;
    188 #if defined(MIP6) && NMIP > 0
    189 	u_int8_t ip6po_usecoa = 0;
    190 #endif /* MIP6 && NMIP > 0 */
    191 
    192 	dst = dstsock->sin6_addr; /* make a copy for local operation */
    193 	*errorp = 0;
    194 	if (ifpp)
    195 		*ifpp = NULL;
    196 
    197 	/*
    198 	 * Try to determine the outgoing interface for the given destination.
    199 	 * We do this regardless of whether the socket is bound, since the
    200 	 * caller may need this information as a side effect of the call
    201 	 * to this function (e.g., for identifying the appropriate scope zone
    202 	 * ID).
    203 	 */
    204 	error = in6_selectif(dstsock, opts, mopts, ro, &ifp);
    205 	if (ifpp)
    206 		*ifpp = ifp;
    207 
    208 	/*
    209 	 * If the source address is explicitly specified by the caller,
    210 	 * check if the requested source address is indeed a unicast address
    211 	 * assigned to the node, and can be used as the packet's source
    212 	 * address.  If everything is okay, use the address as source.
    213 	 */
    214 	if (opts && (pi = opts->ip6po_pktinfo) &&
    215 	    !IN6_IS_ADDR_UNSPECIFIED(&pi->ipi6_addr)) {
    216 		struct sockaddr_in6 srcsock;
    217 		struct in6_ifaddr *ia6;
    218 
    219 		/*
    220 		 * Determine the appropriate zone id of the source based on
    221 		 * the zone of the destination and the outgoing interface.
    222 		 * If the specified address is ambiguous wrt the scope zone,
    223 		 * the interface must be specified; otherwise, ifa_ifwithaddr()
    224 		 * will fail matching the address.
    225 		 */
    226 		memset(&srcsock, 0, sizeof(srcsock));
    227 		srcsock.sin6_family = AF_INET6;
    228 		srcsock.sin6_len = sizeof(srcsock);
    229 		srcsock.sin6_addr = pi->ipi6_addr;
    230 		if (ifp) {
    231 			*errorp = in6_setscope(&srcsock.sin6_addr, ifp, NULL);
    232 			if (*errorp != 0)
    233 				return (NULL);
    234 		}
    235 
    236 		ia6 = (struct in6_ifaddr *)ifa_ifwithaddr((struct sockaddr *)(&srcsock));
    237 		if (ia6 == NULL ||
    238 		    (ia6->ia6_flags & (IN6_IFF_ANYCAST | IN6_IFF_NOTREADY))) {
    239 			*errorp = EADDRNOTAVAIL;
    240 			return (NULL);
    241 		}
    242 		pi->ipi6_addr = srcsock.sin6_addr; /* XXX: this overrides pi */
    243 		if (ifpp)
    244 			*ifpp = ifp;
    245 		return (&ia6->ia_addr.sin6_addr);
    246 	}
    247 
    248 	/*
    249 	 * If the socket has already bound the source, just use it.  We don't
    250 	 * care at the moment whether in6_selectif() succeeded above, even
    251 	 * though it would eventually cause an error.
    252 	 */
    253 	if (laddr && !IN6_IS_ADDR_UNSPECIFIED(laddr))
    254 		return (laddr);
    255 
    256 	/*
    257 	 * The outgoing interface is crucial in the general selection procedure
    258 	 * below.  If it is not known at this point, we fail.
    259 	 */
    260 	if (ifp == NULL) {
    261 		*errorp = error;
    262 		return (NULL);
    263 	}
    264 
    265 	/*
    266 	 * If the address is not yet determined, choose the best one based on
    267 	 * the outgoing interface and the destination address.
    268 	 */
    269 
    270 #if defined(MIP6) && NMIP > 0
    271 	/*
    272 	 * a caller can specify IP6PO_USECOA to not to use a home
    273 	 * address.  for example, the case that the neighbour
    274 	 * unreachability detection to the global address.
    275 	 */
    276 	if (opts != NULL &&
    277 	    (opts->ip6po_flags & IP6PO_USECOA) != 0) {
    278 		ip6po_usecoa = 1;
    279 	}
    280 #endif /* MIP6 && NMIP > 0 */
    281 
    282 	*errorp = in6_setscope(&dst, ifp, &odstzone);
    283 	if (*errorp != 0)
    284 		return (NULL);
    285 
    286 	for (ia = in6_ifaddr; ia; ia = ia->ia_next) {
    287 		int new_scope = -1, new_matchlen = -1;
    288 		struct in6_addrpolicy *new_policy = NULL;
    289 		u_int32_t srczone, osrczone, dstzone;
    290 		struct in6_addr src;
    291 		struct ifnet *ifp1 = ia->ia_ifp;
    292 
    293 		/*
    294 		 * We'll never take an address that breaks the scope zone
    295 		 * of the destination.  We also skip an address if its zone
    296 		 * does not contain the outgoing interface.
    297 		 * XXX: we should probably use sin6_scope_id here.
    298 		 */
    299 		if (in6_setscope(&dst, ifp1, &dstzone) ||
    300 		    odstzone != dstzone) {
    301 			continue;
    302 		}
    303 		src = ia->ia_addr.sin6_addr;
    304 		if (in6_setscope(&src, ifp, &osrczone) ||
    305 		    in6_setscope(&src, ifp1, &srczone) ||
    306 		    osrczone != srczone) {
    307 			continue;
    308 		}
    309 
    310 		/* avoid unusable addresses */
    311 		if ((ia->ia6_flags &
    312 		     (IN6_IFF_NOTREADY | IN6_IFF_ANYCAST | IN6_IFF_DETACHED))) {
    313 				continue;
    314 		}
    315 		if (!ip6_use_deprecated && IFA6_IS_DEPRECATED(ia))
    316 			continue;
    317 
    318 #if defined(MIP6) && NMIP > 0
    319 		/* avoid unusable home addresses. */
    320 		if ((ia->ia6_flags & IN6_IFF_HOME) &&
    321 		    !mip6_ifa6_is_addr_valid_hoa(ia))
    322 			continue;
    323 #endif /* MIP6 && NMIP > 0 */
    324 
    325 		/* Rule 1: Prefer same address */
    326 		if (IN6_ARE_ADDR_EQUAL(&dst, &ia->ia_addr.sin6_addr)) {
    327 			ia_best = ia;
    328 			BREAK(1); /* there should be no better candidate */
    329 		}
    330 
    331 		if (ia_best == NULL)
    332 			REPLACE(0);
    333 
    334 		/* Rule 2: Prefer appropriate scope */
    335 		if (dst_scope < 0)
    336 			dst_scope = in6_addrscope(&dst);
    337 		new_scope = in6_addrscope(&ia->ia_addr.sin6_addr);
    338 		if (IN6_ARE_SCOPE_CMP(best_scope, new_scope) < 0) {
    339 			if (IN6_ARE_SCOPE_CMP(best_scope, dst_scope) < 0)
    340 				REPLACE(2);
    341 			NEXT(2);
    342 		} else if (IN6_ARE_SCOPE_CMP(new_scope, best_scope) < 0) {
    343 			if (IN6_ARE_SCOPE_CMP(new_scope, dst_scope) < 0)
    344 				NEXT(2);
    345 			REPLACE(2);
    346 		}
    347 
    348 		/*
    349 		 * Rule 3: Avoid deprecated addresses.  Note that the case of
    350 		 * !ip6_use_deprecated is already rejected above.
    351 		 */
    352 		if (!IFA6_IS_DEPRECATED(ia_best) && IFA6_IS_DEPRECATED(ia))
    353 			NEXT(3);
    354 		if (IFA6_IS_DEPRECATED(ia_best) && !IFA6_IS_DEPRECATED(ia))
    355 			REPLACE(3);
    356 
    357 		/* Rule 4: Prefer home addresses */
    358 #if defined(MIP6) && NMIP > 0
    359 		if (!MIP6_IS_MN)
    360 			goto skip_rule4;
    361 
    362 		if ((ia_best->ia6_flags & IN6_IFF_HOME) == 0 &&
    363 		    (ia->ia6_flags & IN6_IFF_HOME) == 0) {
    364 			/* both address are not home addresses. */
    365 			goto skip_rule4;
    366 		}
    367 
    368 		/*
    369 		 * If SA is simultaneously a home address and care-of
    370 		 * address and SB is not, then prefer SA. Similarly,
    371 		 * if SB is simultaneously a home address and care-of
    372 		 * address and SA is not, then prefer SB.
    373 		 */
    374 		if (((ia_best->ia6_flags & IN6_IFF_HOME) != 0 &&
    375 			ia_best->ia_ifp->if_type != IFT_MIP)
    376 		    &&
    377 		    ((ia->ia6_flags & IN6_IFF_HOME) != 0 &&
    378 			ia->ia_ifp->if_type == IFT_MIP))
    379 			NEXT(4);
    380 		if (((ia_best->ia6_flags & IN6_IFF_HOME) != 0 &&
    381 			ia_best->ia_ifp->if_type == IFT_MIP)
    382 		    &&
    383 		    ((ia->ia6_flags & IN6_IFF_HOME) != 0 &&
    384 			ia->ia_ifp->if_type != IFT_MIP))
    385 			REPLACE(4);
    386 		if (ip6po_usecoa == 0) {
    387 			/*
    388 			 * If SA is just a home address and SB is just
    389 			 * a care-of address, then prefer
    390 			 * SA. Similarly, if SB is just a home address
    391 			 * and SA is just a care-of address, then
    392 			 * prefer SB.
    393 			 */
    394 			if ((ia_best->ia6_flags & IN6_IFF_HOME) != 0 &&
    395 			    (ia->ia6_flags & IN6_IFF_HOME) == 0) {
    396 				NEXT(4);
    397 			}
    398 			if ((ia_best->ia6_flags & IN6_IFF_HOME) == 0 &&
    399 			    (ia->ia6_flags & IN6_IFF_HOME) != 0) {
    400 				REPLACE(4);
    401 			}
    402 		} else {
    403 			/*
    404 			 * a sender don't want to use a home address
    405 			 * because:
    406 			 *
    407 			 * 1) we cannot use.  (ex. NS or NA to global
    408 			 * addresses.)
    409 			 *
    410 			 * 2) a user specified not to use.
    411 			 * (ex. mip6control -u)
    412 			 */
    413 			if ((ia_best->ia6_flags & IN6_IFF_HOME) == 0 &&
    414 			    (ia->ia6_flags & IN6_IFF_HOME) != 0) {
    415 				/* XXX breaks stat */
    416 				NEXT(0);
    417 			}
    418 			if ((ia_best->ia6_flags & IN6_IFF_HOME) != 0 &&
    419 			    (ia->ia6_flags & IN6_IFF_HOME) == 0) {
    420 				/* XXX breaks stat */
    421 				REPLACE(0);
    422 			}
    423 		}
    424 	skip_rule4:
    425 #endif /* MIP6 && NMIP > 0 */
    426 
    427 		/* Rule 5: Prefer outgoing interface */
    428 		if (ia_best->ia_ifp == ifp && ia->ia_ifp != ifp)
    429 			NEXT(5);
    430 		if (ia_best->ia_ifp != ifp && ia->ia_ifp == ifp)
    431 			REPLACE(5);
    432 
    433 		/*
    434 		 * Rule 6: Prefer matching label
    435 		 * Note that best_policy should be non-NULL here.
    436 		 */
    437 		if (dst_policy == NULL)
    438 			dst_policy = lookup_addrsel_policy(dstsock);
    439 		if (dst_policy->label != ADDR_LABEL_NOTAPP) {
    440 			new_policy = lookup_addrsel_policy(&ia->ia_addr);
    441 			if (dst_policy->label == best_policy->label &&
    442 			    dst_policy->label != new_policy->label)
    443 				NEXT(6);
    444 			if (dst_policy->label != best_policy->label &&
    445 			    dst_policy->label == new_policy->label)
    446 				REPLACE(6);
    447 		}
    448 
    449 		/*
    450 		 * Rule 7: Prefer public addresses.
    451 		 * We allow users to reverse the logic by configuring
    452 		 * a sysctl variable, so that privacy conscious users can
    453 		 * always prefer temporary addresses.
    454 		 */
    455 		if (opts == NULL ||
    456 		    opts->ip6po_prefer_tempaddr == IP6PO_TEMPADDR_SYSTEM) {
    457 			prefer_tempaddr = ip6_prefer_tempaddr;
    458 		} else if (opts->ip6po_prefer_tempaddr ==
    459 		    IP6PO_TEMPADDR_NOTPREFER) {
    460 			prefer_tempaddr = 0;
    461 		} else
    462 			prefer_tempaddr = 1;
    463 		if (!(ia_best->ia6_flags & IN6_IFF_TEMPORARY) &&
    464 		    (ia->ia6_flags & IN6_IFF_TEMPORARY)) {
    465 			if (prefer_tempaddr)
    466 				REPLACE(7);
    467 			else
    468 				NEXT(7);
    469 		}
    470 		if ((ia_best->ia6_flags & IN6_IFF_TEMPORARY) &&
    471 		    !(ia->ia6_flags & IN6_IFF_TEMPORARY)) {
    472 			if (prefer_tempaddr)
    473 				NEXT(7);
    474 			else
    475 				REPLACE(7);
    476 		}
    477 
    478 		/*
    479 		 * Rule 8: prefer addresses on alive interfaces.
    480 		 * This is a KAME specific rule.
    481 		 */
    482 		if ((ia_best->ia_ifp->if_flags & IFF_UP) &&
    483 		    !(ia->ia_ifp->if_flags & IFF_UP))
    484 			NEXT(8);
    485 		if (!(ia_best->ia_ifp->if_flags & IFF_UP) &&
    486 		    (ia->ia_ifp->if_flags & IFF_UP))
    487 			REPLACE(8);
    488 
    489 		/*
    490 		 * Rule 9: prefer addresses on "preferred" interfaces.
    491 		 * This is a KAME specific rule.
    492 		 */
    493 #ifdef notyet			/* until introducing address selection */
    494 #define NDI_BEST ND_IFINFO(ia_best->ia_ifp)
    495 #define NDI_NEW  ND_IFINFO(ia->ia_ifp)
    496 		if ((NDI_BEST->flags & ND6_IFF_PREFER_SOURCE) &&
    497 		    !(NDI_NEW->flags & ND6_IFF_PREFER_SOURCE))
    498 			NEXT(9);
    499 		if (!(NDI_BEST->flags & ND6_IFF_PREFER_SOURCE) &&
    500 		    (NDI_NEW->flags & ND6_IFF_PREFER_SOURCE))
    501 			REPLACE(9);
    502 #undef NDI_BEST
    503 #undef NDI_NEW
    504 #endif
    505 
    506 		/*
    507 		 * Rule 14: Use longest matching prefix.
    508 		 * Note: in the address selection draft, this rule is
    509 		 * documented as "Rule 8".  However, since it is also
    510 		 * documented that this rule can be overridden, we assign
    511 		 * a large number so that it is easy to assign smaller numbers
    512 		 * to more preferred rules.
    513 		 */
    514 		new_matchlen = in6_matchlen(&ia->ia_addr.sin6_addr, &dst);
    515 		if (best_matchlen < new_matchlen)
    516 			REPLACE(14);
    517 		if (new_matchlen < best_matchlen)
    518 			NEXT(14);
    519 
    520 		/* Rule 15 is reserved. */
    521 
    522 		/*
    523 		 * Last resort: just keep the current candidate.
    524 		 * Or, do we need more rules?
    525 		 */
    526 		continue;
    527 
    528 	  replace:
    529 		ia_best = ia;
    530 		best_scope = (new_scope >= 0 ? new_scope :
    531 			      in6_addrscope(&ia_best->ia_addr.sin6_addr));
    532 		best_policy = (new_policy ? new_policy :
    533 			       lookup_addrsel_policy(&ia_best->ia_addr));
    534 		best_matchlen = (new_matchlen >= 0 ? new_matchlen :
    535 				 in6_matchlen(&ia_best->ia_addr.sin6_addr,
    536 					      &dst));
    537 
    538 	  next:
    539 		continue;
    540 
    541 	  out:
    542 		break;
    543 	}
    544 
    545 	if ((ia = ia_best) == NULL) {
    546 		*errorp = EADDRNOTAVAIL;
    547 		return (NULL);
    548 	}
    549 
    550 	return (&ia->ia_addr.sin6_addr);
    551 }
    552 #undef REPLACE
    553 #undef BREAK
    554 #undef NEXT
    555 
    556 static int
    557 selectroute(struct sockaddr_in6 *dstsock, struct ip6_pktopts *opts,
    558 	struct ip6_moptions *mopts, struct route *ro, struct ifnet **retifp,
    559 	struct rtentry **retrt, int clone, int norouteok)
    560 {
    561 	int error = 0;
    562 	struct ifnet *ifp = NULL;
    563 	struct rtentry *rt = NULL;
    564 	struct sockaddr_in6 *sin6_next;
    565 	struct in6_pktinfo *pi = NULL;
    566 	struct in6_addr *dst;
    567 
    568 	dst = &dstsock->sin6_addr;
    569 
    570 #if 0
    571 	if (dstsock->sin6_addr.s6_addr32[0] == 0 &&
    572 	    dstsock->sin6_addr.s6_addr32[1] == 0 &&
    573 	    !IN6_IS_ADDR_LOOPBACK(&dstsock->sin6_addr)) {
    574 		printf("in6_selectroute: strange destination %s\n",
    575 		       ip6_sprintf(&dstsock->sin6_addr));
    576 	} else {
    577 		printf("in6_selectroute: destination = %s%%%d\n",
    578 		       ip6_sprintf(&dstsock->sin6_addr),
    579 		       dstsock->sin6_scope_id); /* for debug */
    580 	}
    581 #endif
    582 
    583 	/* If the caller specify the outgoing interface explicitly, use it. */
    584 	if (opts && (pi = opts->ip6po_pktinfo) != NULL && pi->ipi6_ifindex) {
    585 		/* XXX boundary check is assumed to be already done. */
    586 		ifp = if_byindex(pi->ipi6_ifindex);
    587 		if (ifp != NULL &&
    588 		    (norouteok || retrt == NULL ||
    589 		    IN6_IS_ADDR_MULTICAST(dst))) {
    590 			/*
    591 			 * we do not have to check or get the route for
    592 			 * multicast.
    593 			 */
    594 			goto done;
    595 		} else
    596 			goto getroute;
    597 	}
    598 
    599 	/*
    600 	 * If the destination address is a multicast address and the outgoing
    601 	 * interface for the address is specified by the caller, use it.
    602 	 */
    603 	if (IN6_IS_ADDR_MULTICAST(dst) && mopts != NULL) {
    604 		/* XXX not MP-safe yet */
    605 		ifp = if_byindex(mopts->im6o_multicast_if_index);
    606 		if (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 sysctl_net_inet6_addrctlpolicy(SYSCTLFN_ARGS);
    887 int
    888 sysctl_net_inet6_addrctlpolicy(SYSCTLFN_ARGS)
    889 {
    890 	int error = 0;
    891 	int s;
    892 
    893 	s = splsoftnet();
    894 
    895 	if (newp) {
    896 		error = EPERM;
    897 		goto end;
    898 	}
    899 	if (oldp && oldlenp == NULL) {
    900 		error = EINVAL;
    901 		goto end;
    902 	}
    903 	if (oldp || oldlenp) {
    904 		struct sel_walkarg w;
    905 		size_t oldlen = *oldlenp;
    906 
    907 		memset(&w, 0, sizeof(w));
    908 		w.w_given = oldlen;
    909 		w.w_where = oldp;
    910 		if (oldp)
    911 			w.w_limit = (char *)oldp + oldlen;
    912 
    913 		error = walk_addrsel_policy(dump_addrsel_policyent, &w);
    914 
    915 		*oldlenp = w.w_total;
    916 		if (oldp && w.w_total > oldlen && error == 0)
    917 			error = ENOMEM;
    918 	}
    919 
    920   end:
    921 	splx(s);
    922 
    923 	return (error);
    924 }
    925 
    926 int
    927 in6_src_ioctl(u_long cmd, void *data)
    928 {
    929 	int i;
    930 	struct in6_addrpolicy ent0;
    931 
    932 	if (cmd != SIOCAADDRCTL_POLICY && cmd != SIOCDADDRCTL_POLICY)
    933 		return (EOPNOTSUPP); /* check for safety */
    934 
    935 	ent0 = *(struct in6_addrpolicy *)data;
    936 
    937 	if (ent0.label == ADDR_LABEL_NOTAPP)
    938 		return (EINVAL);
    939 	/* check if the prefix mask is consecutive. */
    940 	if (in6_mask2len(&ent0.addrmask.sin6_addr, NULL) < 0)
    941 		return (EINVAL);
    942 	/* clear trailing garbages (if any) of the prefix address. */
    943 	for (i = 0; i < 4; i++) {
    944 		ent0.addr.sin6_addr.s6_addr32[i] &=
    945 			ent0.addrmask.sin6_addr.s6_addr32[i];
    946 	}
    947 	ent0.use = 0;
    948 
    949 	switch (cmd) {
    950 	case SIOCAADDRCTL_POLICY:
    951 		return (add_addrsel_policyent(&ent0));
    952 	case SIOCDADDRCTL_POLICY:
    953 		return (delete_addrsel_policyent(&ent0));
    954 	}
    955 
    956 	return (0);		/* XXX: compromise compilers */
    957 }
    958 
    959 /*
    960  * The followings are implementation of the policy table using a
    961  * simple tail queue.
    962  * XXX such details should be hidden.
    963  * XXX implementation using binary tree should be more efficient.
    964  */
    965 struct addrsel_policyent {
    966 	TAILQ_ENTRY(addrsel_policyent) ape_entry;
    967 	struct in6_addrpolicy ape_policy;
    968 };
    969 
    970 TAILQ_HEAD(addrsel_policyhead, addrsel_policyent);
    971 
    972 struct addrsel_policyhead addrsel_policytab;
    973 
    974 static void
    975 init_policy_queue(void)
    976 {
    977 	TAILQ_INIT(&addrsel_policytab);
    978 }
    979 
    980 static int
    981 add_addrsel_policyent(struct in6_addrpolicy *newpolicy)
    982 {
    983 	struct addrsel_policyent *newpol, *pol;
    984 
    985 	/* duplication check */
    986 	TAILQ_FOREACH(pol, &addrsel_policytab, ape_entry) {
    987 		if (IN6_ARE_ADDR_EQUAL(&newpolicy->addr.sin6_addr,
    988 		    &pol->ape_policy.addr.sin6_addr) &&
    989 		    IN6_ARE_ADDR_EQUAL(&newpolicy->addrmask.sin6_addr,
    990 		    &pol->ape_policy.addrmask.sin6_addr)) {
    991 			return (EEXIST);	/* or override it? */
    992 		}
    993 	}
    994 
    995 	newpol = malloc(sizeof(*newpol), M_IFADDR, M_WAITOK|M_ZERO);
    996 
    997 	/* XXX: should validate entry */
    998 	newpol->ape_policy = *newpolicy;
    999 
   1000 	TAILQ_INSERT_TAIL(&addrsel_policytab, newpol, ape_entry);
   1001 
   1002 	return (0);
   1003 }
   1004 
   1005 static int
   1006 delete_addrsel_policyent(struct in6_addrpolicy *key)
   1007 {
   1008 	struct addrsel_policyent *pol;
   1009 
   1010 	/* search for the entry in the table */
   1011 	for (pol = TAILQ_FIRST(&addrsel_policytab); pol;
   1012 	     pol = TAILQ_NEXT(pol, ape_entry)) {
   1013 		if (IN6_ARE_ADDR_EQUAL(&key->addr.sin6_addr,
   1014 		    &pol->ape_policy.addr.sin6_addr) &&
   1015 		    IN6_ARE_ADDR_EQUAL(&key->addrmask.sin6_addr,
   1016 		    &pol->ape_policy.addrmask.sin6_addr)) {
   1017 			break;
   1018 		}
   1019 	}
   1020 	if (pol == NULL) {
   1021 		return (ESRCH);
   1022 	}
   1023 
   1024 	TAILQ_REMOVE(&addrsel_policytab, pol, ape_entry);
   1025 
   1026 	return (0);
   1027 }
   1028 
   1029 static int
   1030 walk_addrsel_policy(int (*callback)(struct in6_addrpolicy *, void *), void *w)
   1031 {
   1032 	struct addrsel_policyent *pol;
   1033 	int error = 0;
   1034 
   1035 	TAILQ_FOREACH(pol, &addrsel_policytab, ape_entry) {
   1036 		if ((error = (*callback)(&pol->ape_policy, w)) != 0)
   1037 			return error;
   1038 	}
   1039 
   1040 	return error;
   1041 }
   1042 
   1043 static int
   1044 dump_addrsel_policyent(struct in6_addrpolicy *pol, void *arg)
   1045 {
   1046 	int error = 0;
   1047 	struct sel_walkarg *w = arg;
   1048 
   1049 	if (w->w_where && (char *)w->w_where + sizeof(*pol) <= (char *)w->w_limit) {
   1050 		if ((error = copyout(pol, w->w_where, sizeof(*pol))) != 0)
   1051 			return error;
   1052 		w->w_where = (char *)w->w_where + sizeof(*pol);
   1053 	}
   1054 	w->w_total += sizeof(*pol);
   1055 
   1056 	return error;
   1057 }
   1058 
   1059 static struct in6_addrpolicy *
   1060 match_addrsel_policy(struct sockaddr_in6 *key)
   1061 {
   1062 	struct addrsel_policyent *pent;
   1063 	struct in6_addrpolicy *bestpol = NULL, *pol;
   1064 	int matchlen, bestmatchlen = -1;
   1065 	u_char *mp, *ep, *k, *p, m;
   1066 
   1067 	for (pent = TAILQ_FIRST(&addrsel_policytab); pent;
   1068 	     pent = TAILQ_NEXT(pent, ape_entry)) {
   1069 		matchlen = 0;
   1070 
   1071 		pol = &pent->ape_policy;
   1072 		mp = (u_char *)&pol->addrmask.sin6_addr;
   1073 		ep = mp + 16;	/* XXX: scope field? */
   1074 		k = (u_char *)&key->sin6_addr;
   1075 		p = (u_char *)&pol->addr.sin6_addr;
   1076 		for (; mp < ep && *mp; mp++, k++, p++) {
   1077 			m = *mp;
   1078 			if ((*k & m) != *p)
   1079 				goto next; /* not match */
   1080 			if (m == 0xff) /* short cut for a typical case */
   1081 				matchlen += 8;
   1082 			else {
   1083 				while (m >= 0x80) {
   1084 					matchlen++;
   1085 					m <<= 1;
   1086 				}
   1087 			}
   1088 		}
   1089 
   1090 		/* matched.  check if this is better than the current best. */
   1091 		if (bestpol == NULL ||
   1092 		    matchlen > bestmatchlen) {
   1093 			bestpol = pol;
   1094 			bestmatchlen = matchlen;
   1095 		}
   1096 
   1097 	  next:
   1098 		continue;
   1099 	}
   1100 
   1101 	return (bestpol);
   1102 }
   1103