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