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