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