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