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