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