xref: /freebsd-13.1/sys/netinet6/in6_src.c (revision e1bdecd9)
1 /*-
2  * SPDX-License-Identifier: BSD-3-Clause
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  *	$KAME: in6_src.c,v 1.132 2003/08/26 04:42:27 keiichi Exp $
32  */
33 
34 /*-
35  * Copyright (c) 1982, 1986, 1991, 1993
36  *	The Regents of the University of California.  All rights reserved.
37  *
38  * Redistribution and use in source and binary forms, with or without
39  * modification, are permitted provided that the following conditions
40  * are met:
41  * 1. Redistributions of source code must retain the above copyright
42  *    notice, this list of conditions and the following disclaimer.
43  * 2. Redistributions in binary form must reproduce the above copyright
44  *    notice, this list of conditions and the following disclaimer in the
45  *    documentation and/or other materials provided with the distribution.
46  * 3. Neither the name of the University nor the names of its contributors
47  *    may be used to endorse or promote products derived from this software
48  *    without specific prior written permission.
49  *
50  * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
51  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
52  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
53  * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
54  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
55  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
56  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
57  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
58  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
59  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
60  * SUCH DAMAGE.
61  *
62  *	@(#)in_pcb.c	8.2 (Berkeley) 1/4/94
63  */
64 
65 #include <sys/cdefs.h>
66 __FBSDID("$FreeBSD$");
67 
68 #include "opt_inet.h"
69 #include "opt_inet6.h"
70 #include <sys/param.h>
71 #include <sys/systm.h>
72 #include <sys/lock.h>
73 #include <sys/malloc.h>
74 #include <sys/mbuf.h>
75 #include <sys/priv.h>
76 #include <sys/protosw.h>
77 #include <sys/socket.h>
78 #include <sys/socketvar.h>
79 #include <sys/sockio.h>
80 #include <sys/sysctl.h>
81 #include <sys/errno.h>
82 #include <sys/time.h>
83 #include <sys/jail.h>
84 #include <sys/kernel.h>
85 #include <sys/rmlock.h>
86 #include <sys/sx.h>
87 
88 #include <net/if.h>
89 #include <net/if_var.h>
90 #include <net/if_dl.h>
91 #include <net/route.h>
92 #include <net/route/nhop.h>
93 #include <net/if_llatbl.h>
94 
95 #include <netinet/in.h>
96 #include <netinet/in_var.h>
97 #include <netinet/in_systm.h>
98 #include <netinet/ip.h>
99 #include <netinet/in_pcb.h>
100 #include <netinet/ip_var.h>
101 #include <netinet/udp.h>
102 #include <netinet/udp_var.h>
103 
104 #include <netinet6/in6_var.h>
105 #include <netinet/ip6.h>
106 #include <netinet6/in6_fib.h>
107 #include <netinet6/in6_pcb.h>
108 #include <netinet6/ip6_var.h>
109 #include <netinet6/scope6_var.h>
110 #include <netinet6/nd6.h>
111 
112 static struct mtx addrsel_lock;
113 #define	ADDRSEL_LOCK_INIT()	mtx_init(&addrsel_lock, "addrsel_lock", NULL, MTX_DEF)
114 #define	ADDRSEL_LOCK()		mtx_lock(&addrsel_lock)
115 #define	ADDRSEL_UNLOCK()	mtx_unlock(&addrsel_lock)
116 #define	ADDRSEL_LOCK_ASSERT()	mtx_assert(&addrsel_lock, MA_OWNED)
117 
118 static struct sx addrsel_sxlock;
119 #define	ADDRSEL_SXLOCK_INIT()	sx_init(&addrsel_sxlock, "addrsel_sxlock")
120 #define	ADDRSEL_SLOCK()		sx_slock(&addrsel_sxlock)
121 #define	ADDRSEL_SUNLOCK()	sx_sunlock(&addrsel_sxlock)
122 #define	ADDRSEL_XLOCK()		sx_xlock(&addrsel_sxlock)
123 #define	ADDRSEL_XUNLOCK()	sx_xunlock(&addrsel_sxlock)
124 
125 #define ADDR_LABEL_NOTAPP (-1)
126 VNET_DEFINE_STATIC(struct in6_addrpolicy, defaultaddrpolicy);
127 #define	V_defaultaddrpolicy		VNET(defaultaddrpolicy)
128 
129 VNET_DEFINE(int, ip6_prefer_tempaddr) = 0;
130 
131 static int selectroute(struct sockaddr_in6 *, struct ip6_pktopts *,
132 	struct ip6_moptions *, struct route_in6 *, struct ifnet **,
133 	struct nhop_object **, int, u_int, uint32_t);
134 static int in6_selectif(struct sockaddr_in6 *, struct ip6_pktopts *,
135 	struct ip6_moptions *, struct ifnet **,
136 	struct ifnet *, u_int);
137 static int in6_selectsrc(uint32_t, struct sockaddr_in6 *,
138 	struct ip6_pktopts *, struct inpcb *, struct ucred *,
139 	struct ifnet **, struct in6_addr *);
140 
141 static struct in6_addrpolicy *lookup_addrsel_policy(struct sockaddr_in6 *);
142 
143 static void init_policy_queue(void);
144 static int add_addrsel_policyent(struct in6_addrpolicy *);
145 static int delete_addrsel_policyent(struct in6_addrpolicy *);
146 static int walk_addrsel_policy(int (*)(struct in6_addrpolicy *, void *),
147 	void *);
148 static int dump_addrsel_policyent(struct in6_addrpolicy *, void *);
149 static struct in6_addrpolicy *match_addrsel_policy(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 #define REPLACE(r) do {\
158 	IP6STAT_INC(ip6s_sources_rule[(r)]); \
159 	/* { \
160 	char ip6buf[INET6_ADDRSTRLEN], ip6b[INET6_ADDRSTRLEN]; \
161 	printf("in6_selectsrc: replace %s with %s by %d\n", ia_best ? ip6_sprintf(ip6buf, &ia_best->ia_addr.sin6_addr) : "none", ip6_sprintf(ip6b, &ia->ia_addr.sin6_addr), (r)); \
162 	} */ \
163 	goto replace; \
164 } while(0)
165 #define NEXT(r) do {\
166 	/* { \
167 	char ip6buf[INET6_ADDRSTRLEN], ip6b[INET6_ADDRSTRLEN]; \
168 	printf("in6_selectsrc: keep %s against %s by %d\n", ia_best ? ip6_sprintf(ip6buf, &ia_best->ia_addr.sin6_addr) : "none", ip6_sprintf(ip6b, &ia->ia_addr.sin6_addr), (r)); \
169 	} */ \
170 	goto next;		/* XXX: we can't use 'continue' here */ \
171 } while(0)
172 #define BREAK(r) do { \
173 	IP6STAT_INC(ip6s_sources_rule[(r)]); \
174 	goto out;		/* XXX: we can't use 'break' here */ \
175 } while(0)
176 
177 static int
178 in6_selectsrc(uint32_t fibnum, struct sockaddr_in6 *dstsock,
179     struct ip6_pktopts *opts, struct inpcb *inp, struct ucred *cred,
180     struct ifnet **ifpp, struct in6_addr *srcp)
181 {
182 	struct rm_priotracker in6_ifa_tracker;
183 	struct in6_addr dst, tmp;
184 	struct ifnet *ifp = NULL, *oifp = NULL;
185 	struct in6_ifaddr *ia = NULL, *ia_best = NULL;
186 	struct in6_pktinfo *pi = NULL;
187 	int dst_scope = -1, best_scope = -1, best_matchlen = -1;
188 	struct in6_addrpolicy *dst_policy = NULL, *best_policy = NULL;
189 	u_int32_t odstzone;
190 	int prefer_tempaddr;
191 	int error;
192 	struct ip6_moptions *mopts;
193 
194 	KASSERT(srcp != NULL, ("%s: srcp is NULL", __func__));
195 
196 	dst = dstsock->sin6_addr; /* make a copy for local operation */
197 	if (ifpp) {
198 		/*
199 		 * Save a possibly passed in ifp for in6_selectsrc. Only
200 		 * neighbor discovery code should use this feature, where
201 		 * we may know the interface but not the FIB number holding
202 		 * the connected subnet in case someone deleted it from the
203 		 * default FIB and we need to check the interface.
204 		 */
205 		if (*ifpp != NULL)
206 			oifp = *ifpp;
207 		*ifpp = NULL;
208 	}
209 
210 	if (inp != NULL) {
211 		INP_LOCK_ASSERT(inp);
212 		mopts = inp->in6p_moptions;
213 	} else {
214 		mopts = NULL;
215 	}
216 
217 	/*
218 	 * If the source address is explicitly specified by the caller,
219 	 * check if the requested source address is indeed a unicast address
220 	 * assigned to the node, and can be used as the packet's source
221 	 * address.  If everything is okay, use the address as source.
222 	 */
223 	if (opts && (pi = opts->ip6po_pktinfo) &&
224 	    !IN6_IS_ADDR_UNSPECIFIED(&pi->ipi6_addr)) {
225 		/* get the outgoing interface */
226 		if ((error = in6_selectif(dstsock, opts, mopts, &ifp, oifp,
227 		    fibnum))
228 		    != 0)
229 			return (error);
230 
231 		/*
232 		 * determine the appropriate zone id of the source based on
233 		 * the zone of the destination and the outgoing interface.
234 		 * If the specified address is ambiguous wrt the scope zone,
235 		 * the interface must be specified; otherwise, ifa_ifwithaddr()
236 		 * will fail matching the address.
237 		 */
238 		tmp = pi->ipi6_addr;
239 		if (ifp) {
240 			error = in6_setscope(&tmp, ifp, &odstzone);
241 			if (error)
242 				return (error);
243 		}
244 		if (cred != NULL && (error = prison_local_ip6(cred,
245 		    &tmp, (inp->inp_flags & IN6P_IPV6_V6ONLY) != 0)) != 0)
246 			return (error);
247 
248 		/*
249 		 * If IPV6_BINDANY socket option is set, we allow to specify
250 		 * non local addresses as source address in IPV6_PKTINFO
251 		 * ancillary data.
252 		 */
253 		if ((inp->inp_flags & INP_BINDANY) == 0) {
254 			ia = in6ifa_ifwithaddr(&tmp, 0 /* XXX */, false);
255 			if (ia == NULL || (ia->ia6_flags & (IN6_IFF_ANYCAST |
256 			    IN6_IFF_NOTREADY)))
257 				return (EADDRNOTAVAIL);
258 			bcopy(&ia->ia_addr.sin6_addr, srcp, sizeof(*srcp));
259 		} else
260 			bcopy(&tmp, srcp, sizeof(*srcp));
261 		pi->ipi6_addr = tmp; /* XXX: this overrides pi */
262 		if (ifpp)
263 			*ifpp = ifp;
264 		return (0);
265 	}
266 
267 	/*
268 	 * Otherwise, if the socket has already bound the source, just use it.
269 	 */
270 	if (inp != NULL && !IN6_IS_ADDR_UNSPECIFIED(&inp->in6p_laddr)) {
271 		if (cred != NULL &&
272 		    (error = prison_local_ip6(cred, &inp->in6p_laddr,
273 		    ((inp->inp_flags & IN6P_IPV6_V6ONLY) != 0))) != 0)
274 			return (error);
275 		bcopy(&inp->in6p_laddr, srcp, sizeof(*srcp));
276 		return (0);
277 	}
278 
279 	/*
280 	 * Bypass source address selection and use the primary jail IP
281 	 * if requested.
282 	 */
283 	if (cred != NULL && !prison_saddrsel_ip6(cred, srcp))
284 		return (0);
285 
286 	/*
287 	 * If the address is not specified, choose the best one based on
288 	 * the outgoing interface and the destination address.
289 	 */
290 	/* get the outgoing interface */
291 	if ((error = in6_selectif(dstsock, opts, mopts, &ifp, oifp,
292 	    (inp != NULL) ? inp->inp_inc.inc_fibnum : fibnum)) != 0)
293 		return (error);
294 
295 #ifdef DIAGNOSTIC
296 	if (ifp == NULL)	/* this should not happen */
297 		panic("in6_selectsrc: NULL ifp");
298 #endif
299 	error = in6_setscope(&dst, ifp, &odstzone);
300 	if (error)
301 		return (error);
302 
303 	IN6_IFADDR_RLOCK(&in6_ifa_tracker);
304 	CK_STAILQ_FOREACH(ia, &V_in6_ifaddrhead, ia_link) {
305 		int new_scope = -1, new_matchlen = -1;
306 		struct in6_addrpolicy *new_policy = NULL;
307 		u_int32_t srczone, osrczone, dstzone;
308 		struct in6_addr src;
309 		struct ifnet *ifp1 = ia->ia_ifp;
310 
311 		/*
312 		 * We'll never take an address that breaks the scope zone
313 		 * of the destination.  We also skip an address if its zone
314 		 * does not contain the outgoing interface.
315 		 * XXX: we should probably use sin6_scope_id here.
316 		 */
317 		if (in6_setscope(&dst, ifp1, &dstzone) ||
318 		    odstzone != dstzone) {
319 			continue;
320 		}
321 		src = ia->ia_addr.sin6_addr;
322 		if (in6_setscope(&src, ifp, &osrczone) ||
323 		    in6_setscope(&src, ifp1, &srczone) ||
324 		    osrczone != srczone) {
325 			continue;
326 		}
327 
328 		/* avoid unusable addresses */
329 		if ((ia->ia6_flags &
330 		     (IN6_IFF_NOTREADY | IN6_IFF_ANYCAST | IN6_IFF_DETACHED))) {
331 				continue;
332 		}
333 		if (!V_ip6_use_deprecated && IFA6_IS_DEPRECATED(ia))
334 			continue;
335 
336 		/* If jailed only take addresses of the jail into account. */
337 		if (cred != NULL &&
338 		    prison_check_ip6(cred, &ia->ia_addr.sin6_addr) != 0)
339 			continue;
340 
341 		/* Rule 1: Prefer same address */
342 		if (IN6_ARE_ADDR_EQUAL(&dst, &ia->ia_addr.sin6_addr)) {
343 			ia_best = ia;
344 			BREAK(1); /* there should be no better candidate */
345 		}
346 
347 		if (ia_best == NULL)
348 			REPLACE(0);
349 
350 		/* Rule 2: Prefer appropriate scope */
351 		if (dst_scope < 0)
352 			dst_scope = in6_addrscope(&dst);
353 		new_scope = in6_addrscope(&ia->ia_addr.sin6_addr);
354 		if (IN6_ARE_SCOPE_CMP(best_scope, new_scope) < 0) {
355 			if (IN6_ARE_SCOPE_CMP(best_scope, dst_scope) < 0)
356 				REPLACE(2);
357 			NEXT(2);
358 		} else if (IN6_ARE_SCOPE_CMP(new_scope, best_scope) < 0) {
359 			if (IN6_ARE_SCOPE_CMP(new_scope, dst_scope) < 0)
360 				NEXT(2);
361 			REPLACE(2);
362 		}
363 
364 		/*
365 		 * Rule 3: Avoid deprecated addresses.  Note that the case of
366 		 * !ip6_use_deprecated is already rejected above.
367 		 */
368 		if (!IFA6_IS_DEPRECATED(ia_best) && IFA6_IS_DEPRECATED(ia))
369 			NEXT(3);
370 		if (IFA6_IS_DEPRECATED(ia_best) && !IFA6_IS_DEPRECATED(ia))
371 			REPLACE(3);
372 
373 		/* Rule 4: Prefer home addresses */
374 		/*
375 		 * XXX: This is a TODO.  We should probably merge the MIP6
376 		 * case above.
377 		 */
378 
379 		/* Rule 5: Prefer outgoing interface */
380 		if (!(ND_IFINFO(ifp)->flags & ND6_IFF_NO_PREFER_IFACE)) {
381 			if (ia_best->ia_ifp == ifp && ia->ia_ifp != ifp)
382 				NEXT(5);
383 			if (ia_best->ia_ifp != ifp && ia->ia_ifp == ifp)
384 				REPLACE(5);
385 		}
386 
387 		/*
388 		 * Rule 6: Prefer matching label
389 		 * Note that best_policy should be non-NULL here.
390 		 */
391 		if (dst_policy == NULL)
392 			dst_policy = lookup_addrsel_policy(dstsock);
393 		if (dst_policy->label != ADDR_LABEL_NOTAPP) {
394 			new_policy = lookup_addrsel_policy(&ia->ia_addr);
395 			if (dst_policy->label == best_policy->label &&
396 			    dst_policy->label != new_policy->label)
397 				NEXT(6);
398 			if (dst_policy->label != best_policy->label &&
399 			    dst_policy->label == new_policy->label)
400 				REPLACE(6);
401 		}
402 
403 		/*
404 		 * Rule 7: Prefer public addresses.
405 		 * We allow users to reverse the logic by configuring
406 		 * a sysctl variable, so that privacy conscious users can
407 		 * always prefer temporary addresses.
408 		 */
409 		if (opts == NULL ||
410 		    opts->ip6po_prefer_tempaddr == IP6PO_TEMPADDR_SYSTEM) {
411 			prefer_tempaddr = V_ip6_prefer_tempaddr;
412 		} else if (opts->ip6po_prefer_tempaddr ==
413 		    IP6PO_TEMPADDR_NOTPREFER) {
414 			prefer_tempaddr = 0;
415 		} else
416 			prefer_tempaddr = 1;
417 		if (!(ia_best->ia6_flags & IN6_IFF_TEMPORARY) &&
418 		    (ia->ia6_flags & IN6_IFF_TEMPORARY)) {
419 			if (prefer_tempaddr)
420 				REPLACE(7);
421 			else
422 				NEXT(7);
423 		}
424 		if ((ia_best->ia6_flags & IN6_IFF_TEMPORARY) &&
425 		    !(ia->ia6_flags & IN6_IFF_TEMPORARY)) {
426 			if (prefer_tempaddr)
427 				NEXT(7);
428 			else
429 				REPLACE(7);
430 		}
431 
432 		/*
433 		 * Rule 8: prefer addresses on alive interfaces.
434 		 * This is a KAME specific rule.
435 		 */
436 		if ((ia_best->ia_ifp->if_flags & IFF_UP) &&
437 		    !(ia->ia_ifp->if_flags & IFF_UP))
438 			NEXT(8);
439 		if (!(ia_best->ia_ifp->if_flags & IFF_UP) &&
440 		    (ia->ia_ifp->if_flags & IFF_UP))
441 			REPLACE(8);
442 
443 		/*
444 		 * Rule 9: prefer address with better virtual status.
445 		 */
446 		if (ifa_preferred(&ia_best->ia_ifa, &ia->ia_ifa))
447 			REPLACE(9);
448 		if (ifa_preferred(&ia->ia_ifa, &ia_best->ia_ifa))
449 			NEXT(9);
450 
451 		/*
452 		 * Rule 10: prefer address with `prefer_source' flag.
453 		 */
454 		if ((ia_best->ia6_flags & IN6_IFF_PREFER_SOURCE) == 0 &&
455 		    (ia->ia6_flags & IN6_IFF_PREFER_SOURCE) != 0)
456 			REPLACE(10);
457 		if ((ia_best->ia6_flags & IN6_IFF_PREFER_SOURCE) != 0 &&
458 		    (ia->ia6_flags & IN6_IFF_PREFER_SOURCE) == 0)
459 			NEXT(10);
460 
461 		/*
462 		 * Rule 14: Use longest matching prefix.
463 		 * Note: in the address selection draft, this rule is
464 		 * documented as "Rule 8".  However, since it is also
465 		 * documented that this rule can be overridden, we assign
466 		 * a large number so that it is easy to assign smaller numbers
467 		 * to more preferred rules.
468 		 */
469 		new_matchlen = in6_matchlen(&ia->ia_addr.sin6_addr, &dst);
470 		if (best_matchlen < new_matchlen)
471 			REPLACE(14);
472 		if (new_matchlen < best_matchlen)
473 			NEXT(14);
474 
475 		/* Rule 15 is reserved. */
476 
477 		/*
478 		 * Last resort: just keep the current candidate.
479 		 * Or, do we need more rules?
480 		 */
481 		continue;
482 
483 	  replace:
484 		ia_best = ia;
485 		best_scope = (new_scope >= 0 ? new_scope :
486 			      in6_addrscope(&ia_best->ia_addr.sin6_addr));
487 		best_policy = (new_policy ? new_policy :
488 			       lookup_addrsel_policy(&ia_best->ia_addr));
489 		best_matchlen = (new_matchlen >= 0 ? new_matchlen :
490 				 in6_matchlen(&ia_best->ia_addr.sin6_addr,
491 					      &dst));
492 
493 	  next:
494 		continue;
495 
496 	  out:
497 		break;
498 	}
499 
500 	if ((ia = ia_best) == NULL) {
501 		IN6_IFADDR_RUNLOCK(&in6_ifa_tracker);
502 		IP6STAT_INC(ip6s_sources_none);
503 		return (EADDRNOTAVAIL);
504 	}
505 
506 	/*
507 	 * At this point at least one of the addresses belonged to the jail
508 	 * but it could still be, that we want to further restrict it, e.g.
509 	 * theoratically IN6_IS_ADDR_LOOPBACK.
510 	 * It must not be IN6_IS_ADDR_UNSPECIFIED anymore.
511 	 * prison_local_ip6() will fix an IN6_IS_ADDR_LOOPBACK but should
512 	 * let all others previously selected pass.
513 	 * Use tmp to not change ::1 on lo0 to the primary jail address.
514 	 */
515 	tmp = ia->ia_addr.sin6_addr;
516 	if (cred != NULL && prison_local_ip6(cred, &tmp, (inp != NULL &&
517 	    (inp->inp_flags & IN6P_IPV6_V6ONLY) != 0)) != 0) {
518 		IN6_IFADDR_RUNLOCK(&in6_ifa_tracker);
519 		IP6STAT_INC(ip6s_sources_none);
520 		return (EADDRNOTAVAIL);
521 	}
522 
523 	if (ifpp)
524 		*ifpp = ifp;
525 
526 	bcopy(&tmp, srcp, sizeof(*srcp));
527 	if (ia->ia_ifp == ifp)
528 		IP6STAT_INC(ip6s_sources_sameif[best_scope]);
529 	else
530 		IP6STAT_INC(ip6s_sources_otherif[best_scope]);
531 	if (dst_scope == best_scope)
532 		IP6STAT_INC(ip6s_sources_samescope[best_scope]);
533 	else
534 		IP6STAT_INC(ip6s_sources_otherscope[best_scope]);
535 	if (IFA6_IS_DEPRECATED(ia))
536 		IP6STAT_INC(ip6s_sources_deprecated[best_scope]);
537 	IN6_IFADDR_RUNLOCK(&in6_ifa_tracker);
538 	return (0);
539 }
540 
541 /*
542  * Select source address based on @inp, @dstsock and @opts.
543  * Stores selected address to @srcp. If @scope_ambiguous is set,
544  * embed scope from selected outgoing interface. If @hlim pointer
545  * is provided, stores calculated hop limit there.
546  * Returns 0 on success.
547  */
548 int
549 in6_selectsrc_socket(struct sockaddr_in6 *dstsock, struct ip6_pktopts *opts,
550     struct inpcb *inp, struct ucred *cred, int scope_ambiguous,
551     struct in6_addr *srcp, int *hlim)
552 {
553 	struct ifnet *retifp;
554 	uint32_t fibnum;
555 	int error;
556 
557 	fibnum = inp->inp_inc.inc_fibnum;
558 	retifp = NULL;
559 
560 	error = in6_selectsrc(fibnum, dstsock, opts, inp, cred, &retifp, srcp);
561 	if (error != 0)
562 		return (error);
563 
564 	if (hlim != NULL)
565 		*hlim = in6_selecthlim(inp, retifp);
566 
567 	if (retifp == NULL || scope_ambiguous == 0)
568 		return (0);
569 
570 	/*
571 	 * Application should provide a proper zone ID or the use of
572 	 * default zone IDs should be enabled.  Unfortunately, some
573 	 * applications do not behave as it should, so we need a
574 	 * workaround.  Even if an appropriate ID is not determined
575 	 * (when it's required), if we can determine the outgoing
576 	 * interface. determine the zone ID based on the interface.
577 	 */
578 	error = in6_setscope(&dstsock->sin6_addr, retifp, NULL);
579 
580 	return (error);
581 }
582 
583 /*
584  * Select source address based on @fibnum, @dst and @scopeid.
585  * Stores selected address to @srcp.
586  * Returns 0 on success.
587  *
588  * Used by non-socket based consumers (ND code mostly)
589  */
590 int
591 in6_selectsrc_addr(uint32_t fibnum, const struct in6_addr *dst,
592     uint32_t scopeid, struct ifnet *ifp, struct in6_addr *srcp,
593     int *hlim)
594 {
595 	struct ifnet *retifp;
596 	struct sockaddr_in6 dst_sa;
597 	int error;
598 
599 	retifp = ifp;
600 	bzero(&dst_sa, sizeof(dst_sa));
601 	dst_sa.sin6_family = AF_INET6;
602 	dst_sa.sin6_len = sizeof(dst_sa);
603 	dst_sa.sin6_addr = *dst;
604 	dst_sa.sin6_scope_id = scopeid;
605 	sa6_embedscope(&dst_sa, 0);
606 
607 	error = in6_selectsrc(fibnum, &dst_sa, NULL, NULL, NULL, &retifp, srcp);
608 	if (hlim != NULL)
609 		*hlim = in6_selecthlim(NULL, retifp);
610 
611 	return (error);
612 }
613 
614 /*
615  * clone - meaningful only for bsdi and freebsd
616  */
617 static int
618 selectroute(struct sockaddr_in6 *dstsock, struct ip6_pktopts *opts,
619     struct ip6_moptions *mopts, struct route_in6 *ro,
620     struct ifnet **retifp, struct nhop_object **retnh, int norouteok,
621     u_int fibnum, uint32_t flowid)
622 {
623 	int error = 0;
624 	struct ifnet *ifp = NULL;
625 	struct nhop_object *nh = NULL;
626 	struct sockaddr_in6 *sin6_next;
627 	struct in6_pktinfo *pi = NULL;
628 	struct in6_addr *dst = &dstsock->sin6_addr;
629 	uint32_t zoneid;
630 #if 0
631 	char ip6buf[INET6_ADDRSTRLEN];
632 
633 	if (dstsock->sin6_addr.s6_addr32[0] == 0 &&
634 	    dstsock->sin6_addr.s6_addr32[1] == 0 &&
635 	    !IN6_IS_ADDR_LOOPBACK(&dstsock->sin6_addr)) {
636 		printf("%s: strange destination %s\n", __func__,
637 		       ip6_sprintf(ip6buf, &dstsock->sin6_addr));
638 	} else {
639 		printf("%s: destination = %s%%%d\n", __func__,
640 		       ip6_sprintf(ip6buf, &dstsock->sin6_addr),
641 		       dstsock->sin6_scope_id); /* for debug */
642 	}
643 #endif
644 
645 	/* If the caller specify the outgoing interface explicitly, use it. */
646 	if (opts && (pi = opts->ip6po_pktinfo) != NULL && pi->ipi6_ifindex) {
647 		/* XXX boundary check is assumed to be already done. */
648 		ifp = ifnet_byindex(pi->ipi6_ifindex);
649 		if (ifp != NULL &&
650 		    (norouteok || retnh == NULL ||
651 		    IN6_IS_ADDR_MULTICAST(dst))) {
652 			/*
653 			 * we do not have to check or get the route for
654 			 * multicast.
655 			 */
656 			goto done;
657 		} else
658 			goto getroute;
659 	}
660 	/*
661 	 * If the destination address is a multicast address and the outgoing
662 	 * interface for the address is specified by the caller, use it.
663 	 */
664 	if (IN6_IS_ADDR_MULTICAST(dst) &&
665 	    mopts != NULL && (ifp = mopts->im6o_multicast_ifp) != NULL) {
666 		goto done; /* we do not need a route for multicast. */
667 	}
668 	/*
669 	 * If destination address is LLA or link- or node-local multicast,
670 	 * use it's embedded scope zone id to determine outgoing interface.
671 	 */
672 	if (IN6_IS_ADDR_MC_LINKLOCAL(dst) ||
673 	    IN6_IS_ADDR_MC_NODELOCAL(dst)) {
674 		zoneid = ntohs(in6_getscope(dst));
675 		if (zoneid > 0) {
676 			ifp = in6_getlinkifnet(zoneid);
677 			goto done;
678 		}
679 	}
680 
681   getroute:
682 	/*
683 	 * If the next hop address for the packet is specified by the caller,
684 	 * use it as the gateway.
685 	 */
686 	if (opts && opts->ip6po_nexthop) {
687 		struct route_in6 *ron;
688 
689 		sin6_next = satosin6(opts->ip6po_nexthop);
690 		if (IN6_IS_ADDR_LINKLOCAL(&sin6_next->sin6_addr)) {
691 			/*
692 			 * Next hop is LLA, thus it should be neighbor.
693 			 * Determine outgoing interface by zone index.
694 			 */
695 			zoneid = ntohs(in6_getscope(&sin6_next->sin6_addr));
696 			if (zoneid > 0) {
697 				ifp = in6_getlinkifnet(zoneid);
698 				goto done;
699 			}
700 		}
701 		ron = &opts->ip6po_nextroute;
702 		/* Use a cached route if it exists and is valid. */
703 		if (ron->ro_nh != NULL && (
704 		    !NH_IS_VALID(ron->ro_nh) ||
705 		    ron->ro_dst.sin6_family != AF_INET6 ||
706 		    !IN6_ARE_ADDR_EQUAL(&ron->ro_dst.sin6_addr,
707 			&sin6_next->sin6_addr)))
708 			RO_NHFREE(ron);
709 		if (ron->ro_nh == NULL) {
710 			ron->ro_dst = *sin6_next;
711 			/*
712 			 * sin6_next is not link-local OR scopeid is 0,
713 			 * no need to clear scope
714 			 */
715 			ron->ro_nh = fib6_lookup(fibnum,
716 			    &sin6_next->sin6_addr, 0, NHR_REF, flowid);
717 		}
718 		/*
719 		 * The node identified by that address must be a
720 		 * neighbor of the sending host.
721 		 */
722 		if (ron->ro_nh == NULL ||
723 		    (ron->ro_nh->nh_flags & NHF_GATEWAY) != 0)
724 			error = EHOSTUNREACH;
725 		else {
726 			nh = ron->ro_nh;
727 			ifp = nh->nh_ifp;
728 		}
729 		goto done;
730 	}
731 
732 	/*
733 	 * Use a cached route if it exists and is valid, else try to allocate
734 	 * a new one.  Note that we should check the address family of the
735 	 * cached destination, in case of sharing the cache with IPv4.
736 	 */
737 	if (ro) {
738 		if (ro->ro_nh &&
739 		    (!NH_IS_VALID(ro->ro_nh) ||
740 		     ((struct sockaddr *)(&ro->ro_dst))->sa_family != AF_INET6 ||
741 		     !IN6_ARE_ADDR_EQUAL(&satosin6(&ro->ro_dst)->sin6_addr,
742 		     dst))) {
743 			RO_NHFREE(ro);
744 		}
745 		if (ro->ro_nh == (struct nhop_object *)NULL) {
746 			struct sockaddr_in6 *sa6;
747 
748 			/* No route yet, so try to acquire one */
749 			bzero(&ro->ro_dst, sizeof(struct sockaddr_in6));
750 			sa6 = (struct sockaddr_in6 *)&ro->ro_dst;
751 			*sa6 = *dstsock;
752 			sa6->sin6_scope_id = 0;
753 
754 			/*
755 			 * Currently dst has scopeid embedded iff it is LL.
756 			 * New routing API accepts scopeid as a separate argument.
757 			 * Convert dst before/after doing lookup
758 			 */
759 			uint32_t scopeid = 0;
760 			if (IN6_IS_SCOPE_LINKLOCAL(&sa6->sin6_addr)) {
761 				/* Unwrap in6_getscope() and in6_clearscope() */
762 				scopeid = ntohs(sa6->sin6_addr.s6_addr16[1]);
763 				sa6->sin6_addr.s6_addr16[1] = 0;
764 			}
765 
766 			ro->ro_nh = fib6_lookup(fibnum,
767 			    &sa6->sin6_addr, scopeid, NHR_REF, flowid);
768 
769 			if (IN6_IS_SCOPE_LINKLOCAL(&sa6->sin6_addr))
770 				sa6->sin6_addr.s6_addr16[1] = htons(scopeid);
771 		}
772 
773 		/*
774 		 * do not care about the result if we have the nexthop
775 		 * explicitly specified.
776 		 */
777 		if (opts && opts->ip6po_nexthop)
778 			goto done;
779 
780 		if (ro->ro_nh)
781 			ifp = ro->ro_nh->nh_ifp;
782 		else
783 			error = EHOSTUNREACH;
784 		nh = ro->ro_nh;
785 
786 		/*
787 		 * Check if the outgoing interface conflicts with
788 		 * the interface specified by ipi6_ifindex (if specified).
789 		 * Note that loopback interface is always okay.
790 		 * (this may happen when we are sending a packet to one of
791 		 *  our own addresses.)
792 		 */
793 		if (ifp && opts && opts->ip6po_pktinfo &&
794 		    opts->ip6po_pktinfo->ipi6_ifindex) {
795 			if (!(ifp->if_flags & IFF_LOOPBACK) &&
796 			    ifp->if_index !=
797 			    opts->ip6po_pktinfo->ipi6_ifindex) {
798 				error = EHOSTUNREACH;
799 				goto done;
800 			}
801 		}
802 	}
803 
804   done:
805 	if (ifp == NULL && nh == NULL) {
806 		/*
807 		 * This can happen if the caller did not pass a cached route
808 		 * nor any other hints.  We treat this case an error.
809 		 */
810 		error = EHOSTUNREACH;
811 	}
812 	if (error == EHOSTUNREACH)
813 		IP6STAT_INC(ip6s_noroute);
814 
815 	if (retifp != NULL) {
816 		if (nh != NULL)
817 			*retifp = nh->nh_aifp;
818 		else
819 			*retifp = ifp;
820 	}
821 
822 	if (retnh != NULL)
823 		*retnh = nh;	/* nh may be NULL */
824 
825 	return (error);
826 }
827 
828 static int
829 in6_selectif(struct sockaddr_in6 *dstsock, struct ip6_pktopts *opts,
830     struct ip6_moptions *mopts, struct ifnet **retifp,
831     struct ifnet *oifp, u_int fibnum)
832 {
833 	int error;
834 	struct route_in6 sro;
835 	struct nhop_object *nh = NULL;
836 	uint16_t nh_flags;
837 
838 	KASSERT(retifp != NULL, ("%s: retifp is NULL", __func__));
839 
840 	bzero(&sro, sizeof(sro));
841 	nh_flags = 0;
842 
843 	error = selectroute(dstsock, opts, mopts, &sro, retifp, &nh, 1, fibnum, 0);
844 
845 	if (nh != NULL)
846 		nh_flags = nh->nh_flags;
847 	if (nh != NULL && nh == sro.ro_nh)
848 		NH_FREE(nh);
849 
850 	if (error != 0) {
851 		/* Help ND. See oifp comment in in6_selectsrc(). */
852 		if (oifp != NULL && fibnum == RT_DEFAULT_FIB) {
853 			*retifp = oifp;
854 			error = 0;
855 		}
856 		return (error);
857 	}
858 
859 	/*
860 	 * do not use a rejected or black hole route.
861 	 * XXX: this check should be done in the L2 output routine.
862 	 * However, if we skipped this check here, we'd see the following
863 	 * scenario:
864 	 * - install a rejected route for a scoped address prefix
865 	 *   (like fe80::/10)
866 	 * - send a packet to a destination that matches the scoped prefix,
867 	 *   with ambiguity about the scope zone.
868 	 * - pick the outgoing interface from the route, and disambiguate the
869 	 *   scope zone with the interface.
870 	 * - ip6_output() would try to get another route with the "new"
871 	 *   destination, which may be valid.
872 	 * - we'd see no error on output.
873 	 * Although this may not be very harmful, it should still be confusing.
874 	 * We thus reject the case here.
875 	 */
876 
877 	if (nh_flags & (NHF_REJECT | NHF_BLACKHOLE)) {
878 		error = (nh_flags & NHF_HOST ? EHOSTUNREACH : ENETUNREACH);
879 		return (error);
880 	}
881 
882 	return (0);
883 }
884 
885 /* Public wrapper function to selectroute(). */
886 int
887 in6_selectroute(struct sockaddr_in6 *dstsock, struct ip6_pktopts *opts,
888     struct ip6_moptions *mopts, struct route_in6 *ro,
889     struct ifnet **retifp, struct nhop_object **retnh, u_int fibnum, uint32_t flowid)
890 {
891 
892 	return (selectroute(dstsock, opts, mopts, ro, retifp,
893 	    retnh, 0, fibnum, flowid));
894 }
895 
896 /*
897  * Default hop limit selection. The precedence is as follows:
898  * 1. Hoplimit value specified via ioctl.
899  * 2. (If the outgoing interface is detected) the current
900  *     hop limit of the interface specified by router advertisement.
901  * 3. The system default hoplimit.
902  */
903 int
904 in6_selecthlim(struct inpcb *inp, struct ifnet *ifp)
905 {
906 
907 	if (inp && inp->in6p_hops >= 0)
908 		return (inp->in6p_hops);
909 	else if (ifp)
910 		return (ND_IFINFO(ifp)->chlim);
911 	else if (inp && !IN6_IS_ADDR_UNSPECIFIED(&inp->in6p_faddr)) {
912 		struct nhop_object *nh;
913 		struct in6_addr dst;
914 		uint32_t fibnum, scopeid;
915 		int hlim;
916 
917 		fibnum = inp->inp_inc.inc_fibnum;
918 		in6_splitscope(&inp->in6p_faddr, &dst, &scopeid);
919 		nh = fib6_lookup(fibnum, &dst, scopeid, 0, 0);
920 		if (nh != NULL) {
921 			hlim = ND_IFINFO(nh->nh_ifp)->chlim;
922 			return (hlim);
923 		}
924 	}
925 	return (V_ip6_defhlim);
926 }
927 
928 /*
929  * XXX: this is borrowed from in6_pcbbind(). If possible, we should
930  * share this function by all *bsd*...
931  */
932 int
933 in6_pcbsetport(struct in6_addr *laddr, struct inpcb *inp, struct ucred *cred)
934 {
935 	struct socket *so = inp->inp_socket;
936 	u_int16_t lport = 0;
937 	int error, lookupflags = 0;
938 #ifdef INVARIANTS
939 	struct inpcbinfo *pcbinfo = inp->inp_pcbinfo;
940 #endif
941 
942 	INP_WLOCK_ASSERT(inp);
943 	INP_HASH_WLOCK_ASSERT(pcbinfo);
944 
945 	error = prison_local_ip6(cred, laddr,
946 	    ((inp->inp_flags & IN6P_IPV6_V6ONLY) != 0));
947 	if (error)
948 		return(error);
949 
950 	/* XXX: this is redundant when called from in6_pcbbind */
951 	if ((so->so_options & (SO_REUSEADDR|SO_REUSEPORT|SO_REUSEPORT_LB)) == 0)
952 		lookupflags = INPLOOKUP_WILDCARD;
953 
954 	inp->inp_flags |= INP_ANONPORT;
955 
956 	error = in_pcb_lport(inp, NULL, &lport, cred, lookupflags);
957 	if (error != 0)
958 		return (error);
959 
960 	inp->inp_lport = lport;
961 	if (in_pcbinshash(inp) != 0) {
962 		inp->in6p_laddr = in6addr_any;
963 		inp->inp_lport = 0;
964 		return (EAGAIN);
965 	}
966 
967 	return (0);
968 }
969 
970 void
971 addrsel_policy_init(void)
972 {
973 
974 	init_policy_queue();
975 
976 	/* initialize the "last resort" policy */
977 	bzero(&V_defaultaddrpolicy, sizeof(V_defaultaddrpolicy));
978 	V_defaultaddrpolicy.label = ADDR_LABEL_NOTAPP;
979 
980 	if (!IS_DEFAULT_VNET(curvnet))
981 		return;
982 
983 	ADDRSEL_LOCK_INIT();
984 	ADDRSEL_SXLOCK_INIT();
985 }
986 
987 static struct in6_addrpolicy *
988 lookup_addrsel_policy(struct sockaddr_in6 *key)
989 {
990 	struct in6_addrpolicy *match = NULL;
991 
992 	ADDRSEL_LOCK();
993 	match = match_addrsel_policy(key);
994 
995 	if (match == NULL)
996 		match = &V_defaultaddrpolicy;
997 	else
998 		match->use++;
999 	ADDRSEL_UNLOCK();
1000 
1001 	return (match);
1002 }
1003 
1004 /*
1005  * Subroutines to manage the address selection policy table via sysctl.
1006  */
1007 struct walkarg {
1008 	struct sysctl_req *w_req;
1009 };
1010 
1011 static int in6_src_sysctl(SYSCTL_HANDLER_ARGS);
1012 SYSCTL_DECL(_net_inet6_ip6);
1013 static SYSCTL_NODE(_net_inet6_ip6, IPV6CTL_ADDRCTLPOLICY, addrctlpolicy,
1014     CTLFLAG_RD | CTLFLAG_MPSAFE, in6_src_sysctl,
1015     "");
1016 
1017 static int
1018 in6_src_sysctl(SYSCTL_HANDLER_ARGS)
1019 {
1020 	struct walkarg w;
1021 
1022 	if (req->newptr)
1023 		return EPERM;
1024 
1025 	bzero(&w, sizeof(w));
1026 	w.w_req = req;
1027 
1028 	return (walk_addrsel_policy(dump_addrsel_policyent, &w));
1029 }
1030 
1031 int
1032 in6_src_ioctl(u_long cmd, caddr_t data)
1033 {
1034 	struct in6_addrpolicy ent0;
1035 
1036 	if (cmd != SIOCAADDRCTL_POLICY && cmd != SIOCDADDRCTL_POLICY)
1037 		return (EOPNOTSUPP); /* check for safety */
1038 
1039 	ent0 = *(struct in6_addrpolicy *)data;
1040 
1041 	if (ent0.label == ADDR_LABEL_NOTAPP)
1042 		return (EINVAL);
1043 	/* check if the prefix mask is consecutive. */
1044 	if (in6_mask2len(&ent0.addrmask.sin6_addr, NULL) < 0)
1045 		return (EINVAL);
1046 	/* clear trailing garbages (if any) of the prefix address. */
1047 	IN6_MASK_ADDR(&ent0.addr.sin6_addr, &ent0.addrmask.sin6_addr);
1048 	ent0.use = 0;
1049 
1050 	switch (cmd) {
1051 	case SIOCAADDRCTL_POLICY:
1052 		return (add_addrsel_policyent(&ent0));
1053 	case SIOCDADDRCTL_POLICY:
1054 		return (delete_addrsel_policyent(&ent0));
1055 	}
1056 
1057 	return (0);		/* XXX: compromise compilers */
1058 }
1059 
1060 /*
1061  * The followings are implementation of the policy table using a
1062  * simple tail queue.
1063  * XXX such details should be hidden.
1064  * XXX implementation using binary tree should be more efficient.
1065  */
1066 struct addrsel_policyent {
1067 	TAILQ_ENTRY(addrsel_policyent) ape_entry;
1068 	struct in6_addrpolicy ape_policy;
1069 };
1070 
1071 TAILQ_HEAD(addrsel_policyhead, addrsel_policyent);
1072 
1073 VNET_DEFINE_STATIC(struct addrsel_policyhead, addrsel_policytab);
1074 #define	V_addrsel_policytab		VNET(addrsel_policytab)
1075 
1076 static void
1077 init_policy_queue(void)
1078 {
1079 
1080 	TAILQ_INIT(&V_addrsel_policytab);
1081 }
1082 
1083 static int
1084 add_addrsel_policyent(struct in6_addrpolicy *newpolicy)
1085 {
1086 	struct addrsel_policyent *new, *pol;
1087 
1088 	new = malloc(sizeof(*new), M_IFADDR,
1089 	       M_WAITOK);
1090 	ADDRSEL_XLOCK();
1091 	ADDRSEL_LOCK();
1092 
1093 	/* duplication check */
1094 	TAILQ_FOREACH(pol, &V_addrsel_policytab, ape_entry) {
1095 		if (IN6_ARE_ADDR_EQUAL(&newpolicy->addr.sin6_addr,
1096 				       &pol->ape_policy.addr.sin6_addr) &&
1097 		    IN6_ARE_ADDR_EQUAL(&newpolicy->addrmask.sin6_addr,
1098 				       &pol->ape_policy.addrmask.sin6_addr)) {
1099 			ADDRSEL_UNLOCK();
1100 			ADDRSEL_XUNLOCK();
1101 			free(new, M_IFADDR);
1102 			return (EEXIST);	/* or override it? */
1103 		}
1104 	}
1105 
1106 	bzero(new, sizeof(*new));
1107 
1108 	/* XXX: should validate entry */
1109 	new->ape_policy = *newpolicy;
1110 
1111 	TAILQ_INSERT_TAIL(&V_addrsel_policytab, new, ape_entry);
1112 	ADDRSEL_UNLOCK();
1113 	ADDRSEL_XUNLOCK();
1114 
1115 	return (0);
1116 }
1117 
1118 static int
1119 delete_addrsel_policyent(struct in6_addrpolicy *key)
1120 {
1121 	struct addrsel_policyent *pol;
1122 
1123 	ADDRSEL_XLOCK();
1124 	ADDRSEL_LOCK();
1125 
1126 	/* search for the entry in the table */
1127 	TAILQ_FOREACH(pol, &V_addrsel_policytab, ape_entry) {
1128 		if (IN6_ARE_ADDR_EQUAL(&key->addr.sin6_addr,
1129 		    &pol->ape_policy.addr.sin6_addr) &&
1130 		    IN6_ARE_ADDR_EQUAL(&key->addrmask.sin6_addr,
1131 		    &pol->ape_policy.addrmask.sin6_addr)) {
1132 			break;
1133 		}
1134 	}
1135 	if (pol == NULL) {
1136 		ADDRSEL_UNLOCK();
1137 		ADDRSEL_XUNLOCK();
1138 		return (ESRCH);
1139 	}
1140 
1141 	TAILQ_REMOVE(&V_addrsel_policytab, pol, ape_entry);
1142 	ADDRSEL_UNLOCK();
1143 	ADDRSEL_XUNLOCK();
1144 	free(pol, M_IFADDR);
1145 
1146 	return (0);
1147 }
1148 
1149 static int
1150 walk_addrsel_policy(int (*callback)(struct in6_addrpolicy *, void *), void *w)
1151 {
1152 	struct addrsel_policyent *pol;
1153 	int error = 0;
1154 
1155 	ADDRSEL_SLOCK();
1156 	TAILQ_FOREACH(pol, &V_addrsel_policytab, ape_entry) {
1157 		if ((error = (*callback)(&pol->ape_policy, w)) != 0) {
1158 			ADDRSEL_SUNLOCK();
1159 			return (error);
1160 		}
1161 	}
1162 	ADDRSEL_SUNLOCK();
1163 	return (error);
1164 }
1165 
1166 static int
1167 dump_addrsel_policyent(struct in6_addrpolicy *pol, void *arg)
1168 {
1169 	int error = 0;
1170 	struct walkarg *w = arg;
1171 
1172 	error = SYSCTL_OUT(w->w_req, pol, sizeof(*pol));
1173 
1174 	return (error);
1175 }
1176 
1177 static struct in6_addrpolicy *
1178 match_addrsel_policy(struct sockaddr_in6 *key)
1179 {
1180 	struct addrsel_policyent *pent;
1181 	struct in6_addrpolicy *bestpol = NULL, *pol;
1182 	int matchlen, bestmatchlen = -1;
1183 	u_char *mp, *ep, *k, *p, m;
1184 
1185 	TAILQ_FOREACH(pent, &V_addrsel_policytab, ape_entry) {
1186 		matchlen = 0;
1187 
1188 		pol = &pent->ape_policy;
1189 		mp = (u_char *)&pol->addrmask.sin6_addr;
1190 		ep = mp + 16;	/* XXX: scope field? */
1191 		k = (u_char *)&key->sin6_addr;
1192 		p = (u_char *)&pol->addr.sin6_addr;
1193 		for (; mp < ep && *mp; mp++, k++, p++) {
1194 			m = *mp;
1195 			if ((*k & m) != *p)
1196 				goto next; /* not match */
1197 			if (m == 0xff) /* short cut for a typical case */
1198 				matchlen += 8;
1199 			else {
1200 				while (m >= 0x80) {
1201 					matchlen++;
1202 					m <<= 1;
1203 				}
1204 			}
1205 		}
1206 
1207 		/* matched.  check if this is better than the current best. */
1208 		if (bestpol == NULL ||
1209 		    matchlen > bestmatchlen) {
1210 			bestpol = pol;
1211 			bestmatchlen = matchlen;
1212 		}
1213 
1214 	  next:
1215 		continue;
1216 	}
1217 
1218 	return (bestpol);
1219 }
1220