xref: /freebsd/sys/netinet6/in6_src.c (revision 35a04710d7286aa9538917fd7f8e417dbee95b82)
1 /*	$FreeBSD$	*/
2 /*	$KAME: in6_src.c,v 1.132 2003/08/26 04:42:27 keiichi 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  * 4. Neither the name of the University nor the names of its contributors
46  *    may be used to endorse or promote products derived from this software
47  *    without specific prior written permission.
48  *
49  * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
50  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
51  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
52  * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
53  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
54  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
55  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
56  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
57  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
58  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
59  * SUCH DAMAGE.
60  *
61  *	@(#)in_pcb.c	8.2 (Berkeley) 1/4/94
62  */
63 
64 #include "opt_inet.h"
65 #include "opt_inet6.h"
66 
67 #include <sys/param.h>
68 #include <sys/systm.h>
69 #include <sys/lock.h>
70 #include <sys/malloc.h>
71 #include <sys/mbuf.h>
72 #include <sys/priv.h>
73 #include <sys/protosw.h>
74 #include <sys/socket.h>
75 #include <sys/socketvar.h>
76 #include <sys/sockio.h>
77 #include <sys/sysctl.h>
78 #include <sys/errno.h>
79 #include <sys/time.h>
80 #include <sys/kernel.h>
81 #include <sys/sx.h>
82 
83 #include <net/if.h>
84 #include <net/route.h>
85 
86 #include <netinet/in.h>
87 #include <netinet/in_var.h>
88 #include <netinet/in_systm.h>
89 #include <netinet/ip.h>
90 #include <netinet/in_pcb.h>
91 #include <netinet6/in6_var.h>
92 #include <netinet/ip6.h>
93 #include <netinet6/in6_pcb.h>
94 #include <netinet6/ip6_var.h>
95 #include <netinet6/scope6_var.h>
96 #include <netinet6/nd6.h>
97 
98 static struct mtx addrsel_lock;
99 #define	ADDRSEL_LOCK_INIT()	mtx_init(&addrsel_lock, "addrsel_lock", NULL, MTX_DEF)
100 #define	ADDRSEL_LOCK()		mtx_lock(&addrsel_lock)
101 #define	ADDRSEL_UNLOCK()	mtx_unlock(&addrsel_lock)
102 #define	ADDRSEL_LOCK_ASSERT()	mtx_assert(&addrsel_lock, MA_OWNED)
103 
104 static struct sx addrsel_sxlock;
105 #define	ADDRSEL_SXLOCK_INIT()	sx_init(&addrsel_sxlock, "addrsel_sxlock")
106 #define	ADDRSEL_SLOCK()		sx_slock(&addrsel_sxlock)
107 #define	ADDRSEL_SUNLOCK()	sx_sunlock(&addrsel_sxlock)
108 #define	ADDRSEL_XLOCK()		sx_xlock(&addrsel_sxlock)
109 #define	ADDRSEL_XUNLOCK()	sx_xunlock(&addrsel_sxlock)
110 
111 #define ADDR_LABEL_NOTAPP (-1)
112 struct in6_addrpolicy defaultaddrpolicy;
113 
114 int ip6_prefer_tempaddr = 0;
115 
116 static int selectroute __P((struct sockaddr_in6 *, struct ip6_pktopts *,
117 	struct ip6_moptions *, struct route_in6 *, struct ifnet **,
118 	struct rtentry **, int, int));
119 static int in6_selectif __P((struct sockaddr_in6 *, struct ip6_pktopts *,
120 	struct ip6_moptions *, struct route_in6 *ro, struct ifnet **));
121 
122 static struct in6_addrpolicy *lookup_addrsel_policy __P((struct sockaddr_in6 *));
123 
124 static void init_policy_queue __P((void));
125 static int add_addrsel_policyent __P((struct in6_addrpolicy *));
126 static int delete_addrsel_policyent __P((struct in6_addrpolicy *));
127 static int walk_addrsel_policy __P((int (*)(struct in6_addrpolicy *, void *),
128 				    void *));
129 static int dump_addrsel_policyent __P((struct in6_addrpolicy *, void *));
130 static struct in6_addrpolicy *match_addrsel_policy __P((struct sockaddr_in6 *));
131 
132 /*
133  * Return an IPv6 address, which is the most appropriate for a given
134  * destination and user specified options.
135  * If necessary, this function lookups the routing table and returns
136  * an entry to the caller for later use.
137  */
138 #define REPLACE(r) do {\
139 	if ((r) < sizeof(ip6stat.ip6s_sources_rule) / \
140 		sizeof(ip6stat.ip6s_sources_rule[0])) /* check for safety */ \
141 		ip6stat.ip6s_sources_rule[(r)]++; \
142 	/* 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)); */ \
143 	goto replace; \
144 } while(0)
145 #define NEXT(r) do {\
146 	if ((r) < sizeof(ip6stat.ip6s_sources_rule) / \
147 		sizeof(ip6stat.ip6s_sources_rule[0])) /* check for safety */ \
148 		ip6stat.ip6s_sources_rule[(r)]++; \
149 	/* 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)); */ \
150 	goto next;		/* XXX: we can't use 'continue' here */ \
151 } while(0)
152 #define BREAK(r) do { \
153 	if ((r) < sizeof(ip6stat.ip6s_sources_rule) / \
154 		sizeof(ip6stat.ip6s_sources_rule[0])) /* check for safety */ \
155 		ip6stat.ip6s_sources_rule[(r)]++; \
156 	goto out;		/* XXX: we can't use 'break' here */ \
157 } while(0)
158 
159 struct in6_addr *
160 in6_selectsrc(struct sockaddr_in6 *dstsock, struct ip6_pktopts *opts,
161     struct ip6_moptions *mopts, struct route_in6 *ro,
162     struct in6_addr *laddr, struct ifnet **ifpp, int *errorp)
163 {
164 	struct in6_addr dst;
165 	struct ifnet *ifp = NULL;
166 	struct in6_ifaddr *ia = NULL, *ia_best = NULL;
167 	struct in6_pktinfo *pi = NULL;
168 	int dst_scope = -1, best_scope = -1, best_matchlen = -1;
169 	struct in6_addrpolicy *dst_policy = NULL, *best_policy = NULL;
170 	u_int32_t odstzone;
171 	int prefer_tempaddr;
172 
173 	dst = dstsock->sin6_addr; /* make a copy for local operation */
174 	*errorp = 0;
175 	if (ifpp)
176 		*ifpp = NULL;
177 
178 	/*
179 	 * If the source address is explicitly specified by the caller,
180 	 * check if the requested source address is indeed a unicast address
181 	 * assigned to the node, and can be used as the packet's source
182 	 * address.  If everything is okay, use the address as source.
183 	 */
184 	if (opts && (pi = opts->ip6po_pktinfo) &&
185 	    !IN6_IS_ADDR_UNSPECIFIED(&pi->ipi6_addr)) {
186 		struct sockaddr_in6 srcsock;
187 		struct in6_ifaddr *ia6;
188 
189 		/* get the outgoing interface */
190 		if ((*errorp = in6_selectif(dstsock, opts, mopts, ro, &ifp))
191 		    != 0) {
192 			return (NULL);
193 		}
194 
195 		/*
196 		 * determine the appropriate zone id of the source based on
197 		 * the zone of the destination and the outgoing interface.
198 		 * If the specified address is ambiguous wrt the scope zone,
199 		 * the interface must be specified; otherwise, ifa_ifwithaddr()
200 		 * will fail matching the address.
201 		 */
202 		bzero(&srcsock, sizeof(srcsock));
203 		srcsock.sin6_family = AF_INET6;
204 		srcsock.sin6_len = sizeof(srcsock);
205 		srcsock.sin6_addr = pi->ipi6_addr;
206 		if (ifp) {
207 			*errorp = in6_setscope(&srcsock.sin6_addr, ifp, NULL);
208 			if (*errorp != 0)
209 				return (NULL);
210 		}
211 
212 		ia6 = (struct in6_ifaddr *)ifa_ifwithaddr((struct sockaddr *)(&srcsock));
213 		if (ia6 == NULL ||
214 		    (ia6->ia6_flags & (IN6_IFF_ANYCAST | IN6_IFF_NOTREADY))) {
215 			*errorp = EADDRNOTAVAIL;
216 			return (NULL);
217 		}
218 		pi->ipi6_addr = srcsock.sin6_addr; /* XXX: this overrides pi */
219 		if (ifpp)
220 			*ifpp = ifp;
221 		return (&ia6->ia_addr.sin6_addr);
222 	}
223 
224 	/*
225 	 * Otherwise, if the socket has already bound the source, just use it.
226 	 */
227 	if (laddr && !IN6_IS_ADDR_UNSPECIFIED(laddr))
228 		return (laddr);
229 
230 	/*
231 	 * If the address is not specified, choose the best one based on
232 	 * the outgoing interface and the destination address.
233 	 */
234 	/* get the outgoing interface */
235 	if ((*errorp = in6_selectif(dstsock, opts, mopts, ro, &ifp)) != 0)
236 		return (NULL);
237 
238 #ifdef DIAGNOSTIC
239 	if (ifp == NULL)	/* this should not happen */
240 		panic("in6_selectsrc: NULL ifp");
241 #endif
242 	*errorp = in6_setscope(&dst, ifp, &odstzone);
243 	if (*errorp != 0)
244 		return (NULL);
245 
246 	for (ia = in6_ifaddr; ia; ia = ia->ia_next) {
247 		int new_scope = -1, new_matchlen = -1;
248 		struct in6_addrpolicy *new_policy = NULL;
249 		u_int32_t srczone, osrczone, dstzone;
250 		struct in6_addr src;
251 		struct ifnet *ifp1 = ia->ia_ifp;
252 
253 		/*
254 		 * We'll never take an address that breaks the scope zone
255 		 * of the destination.  We also skip an address if its zone
256 		 * does not contain the outgoing interface.
257 		 * XXX: we should probably use sin6_scope_id here.
258 		 */
259 		if (in6_setscope(&dst, ifp1, &dstzone) ||
260 		    odstzone != dstzone) {
261 			continue;
262 		}
263 		src = ia->ia_addr.sin6_addr;
264 		if (in6_setscope(&src, ifp, &osrczone) ||
265 		    in6_setscope(&src, ifp1, &srczone) ||
266 		    osrczone != srczone) {
267 			continue;
268 		}
269 
270 		/* avoid unusable addresses */
271 		if ((ia->ia6_flags &
272 		     (IN6_IFF_NOTREADY | IN6_IFF_ANYCAST | IN6_IFF_DETACHED))) {
273 				continue;
274 		}
275 		if (!ip6_use_deprecated && IFA6_IS_DEPRECATED(ia))
276 			continue;
277 
278 		/* Rule 1: Prefer same address */
279 		if (IN6_ARE_ADDR_EQUAL(&dst, &ia->ia_addr.sin6_addr)) {
280 			ia_best = ia;
281 			BREAK(1); /* there should be no better candidate */
282 		}
283 
284 		if (ia_best == NULL)
285 			REPLACE(0);
286 
287 		/* Rule 2: Prefer appropriate scope */
288 		if (dst_scope < 0)
289 			dst_scope = in6_addrscope(&dst);
290 		new_scope = in6_addrscope(&ia->ia_addr.sin6_addr);
291 		if (IN6_ARE_SCOPE_CMP(best_scope, new_scope) < 0) {
292 			if (IN6_ARE_SCOPE_CMP(best_scope, dst_scope) < 0)
293 				REPLACE(2);
294 			NEXT(2);
295 		} else if (IN6_ARE_SCOPE_CMP(new_scope, best_scope) < 0) {
296 			if (IN6_ARE_SCOPE_CMP(new_scope, dst_scope) < 0)
297 				NEXT(2);
298 			REPLACE(2);
299 		}
300 
301 		/*
302 		 * Rule 3: Avoid deprecated addresses.  Note that the case of
303 		 * !ip6_use_deprecated is already rejected above.
304 		 */
305 		if (!IFA6_IS_DEPRECATED(ia_best) && IFA6_IS_DEPRECATED(ia))
306 			NEXT(3);
307 		if (IFA6_IS_DEPRECATED(ia_best) && !IFA6_IS_DEPRECATED(ia))
308 			REPLACE(3);
309 
310 		/* Rule 4: Prefer home addresses */
311 		/*
312 		 * XXX: This is a TODO.  We should probably merge the MIP6
313 		 * case above.
314 		 */
315 
316 		/* Rule 5: Prefer outgoing interface */
317 		if (ia_best->ia_ifp == ifp && ia->ia_ifp != ifp)
318 			NEXT(5);
319 		if (ia_best->ia_ifp != ifp && ia->ia_ifp == ifp)
320 			REPLACE(5);
321 
322 		/*
323 		 * Rule 6: Prefer matching label
324 		 * Note that best_policy should be non-NULL here.
325 		 */
326 		if (dst_policy == NULL)
327 			dst_policy = lookup_addrsel_policy(dstsock);
328 		if (dst_policy->label != ADDR_LABEL_NOTAPP) {
329 			new_policy = lookup_addrsel_policy(&ia->ia_addr);
330 			if (dst_policy->label == best_policy->label &&
331 			    dst_policy->label != new_policy->label)
332 				NEXT(6);
333 			if (dst_policy->label != best_policy->label &&
334 			    dst_policy->label == new_policy->label)
335 				REPLACE(6);
336 		}
337 
338 		/*
339 		 * Rule 7: Prefer public addresses.
340 		 * We allow users to reverse the logic by configuring
341 		 * a sysctl variable, so that privacy conscious users can
342 		 * always prefer temporary addresses.
343 		 */
344 		if (opts == NULL ||
345 		    opts->ip6po_prefer_tempaddr == IP6PO_TEMPADDR_SYSTEM) {
346 			prefer_tempaddr = ip6_prefer_tempaddr;
347 		} else if (opts->ip6po_prefer_tempaddr ==
348 		    IP6PO_TEMPADDR_NOTPREFER) {
349 			prefer_tempaddr = 0;
350 		} else
351 			prefer_tempaddr = 1;
352 		if (!(ia_best->ia6_flags & IN6_IFF_TEMPORARY) &&
353 		    (ia->ia6_flags & IN6_IFF_TEMPORARY)) {
354 			if (prefer_tempaddr)
355 				REPLACE(7);
356 			else
357 				NEXT(7);
358 		}
359 		if ((ia_best->ia6_flags & IN6_IFF_TEMPORARY) &&
360 		    !(ia->ia6_flags & IN6_IFF_TEMPORARY)) {
361 			if (prefer_tempaddr)
362 				NEXT(7);
363 			else
364 				REPLACE(7);
365 		}
366 
367 		/*
368 		 * Rule 8: prefer addresses on alive interfaces.
369 		 * This is a KAME specific rule.
370 		 */
371 		if ((ia_best->ia_ifp->if_flags & IFF_UP) &&
372 		    !(ia->ia_ifp->if_flags & IFF_UP))
373 			NEXT(8);
374 		if (!(ia_best->ia_ifp->if_flags & IFF_UP) &&
375 		    (ia->ia_ifp->if_flags & IFF_UP))
376 			REPLACE(8);
377 
378 		/*
379 		 * Rule 14: Use longest matching prefix.
380 		 * Note: in the address selection draft, this rule is
381 		 * documented as "Rule 8".  However, since it is also
382 		 * documented that this rule can be overridden, we assign
383 		 * a large number so that it is easy to assign smaller numbers
384 		 * to more preferred rules.
385 		 */
386 		new_matchlen = in6_matchlen(&ia->ia_addr.sin6_addr, &dst);
387 		if (best_matchlen < new_matchlen)
388 			REPLACE(14);
389 		if (new_matchlen < best_matchlen)
390 			NEXT(14);
391 
392 		/* Rule 15 is reserved. */
393 
394 		/*
395 		 * Last resort: just keep the current candidate.
396 		 * Or, do we need more rules?
397 		 */
398 		continue;
399 
400 	  replace:
401 		ia_best = ia;
402 		best_scope = (new_scope >= 0 ? new_scope :
403 			      in6_addrscope(&ia_best->ia_addr.sin6_addr));
404 		best_policy = (new_policy ? new_policy :
405 			       lookup_addrsel_policy(&ia_best->ia_addr));
406 		best_matchlen = (new_matchlen >= 0 ? new_matchlen :
407 				 in6_matchlen(&ia_best->ia_addr.sin6_addr,
408 					      &dst));
409 
410 	  next:
411 		continue;
412 
413 	  out:
414 		break;
415 	}
416 
417 	if ((ia = ia_best) == NULL) {
418 		*errorp = EADDRNOTAVAIL;
419 		return (NULL);
420 	}
421 
422 	if (ifpp)
423 		*ifpp = ifp;
424 
425 	return (&ia->ia_addr.sin6_addr);
426 }
427 
428 /*
429  * clone - meaningful only for bsdi and freebsd
430  */
431 static int
432 selectroute(struct sockaddr_in6 *dstsock, struct ip6_pktopts *opts,
433     struct ip6_moptions *mopts, struct route_in6 *ro,
434     struct ifnet **retifp, struct rtentry **retrt, int clone,
435     int norouteok)
436 {
437 	int error = 0;
438 	struct ifnet *ifp = NULL;
439 	struct rtentry *rt = NULL;
440 	struct sockaddr_in6 *sin6_next;
441 	struct in6_pktinfo *pi = NULL;
442 	struct in6_addr *dst = &dstsock->sin6_addr;
443 #if 0
444 	char ip6buf[INET6_ADDRSTRLEN];
445 
446 	if (dstsock->sin6_addr.s6_addr32[0] == 0 &&
447 	    dstsock->sin6_addr.s6_addr32[1] == 0 &&
448 	    !IN6_IS_ADDR_LOOPBACK(&dstsock->sin6_addr)) {
449 		printf("in6_selectroute: strange destination %s\n",
450 		       ip6_sprintf(ip6buf, &dstsock->sin6_addr));
451 	} else {
452 		printf("in6_selectroute: destination = %s%%%d\n",
453 		       ip6_sprintf(ip6buf, &dstsock->sin6_addr),
454 		       dstsock->sin6_scope_id); /* for debug */
455 	}
456 #endif
457 
458 	/* If the caller specify the outgoing interface explicitly, use it. */
459 	if (opts && (pi = opts->ip6po_pktinfo) != NULL && pi->ipi6_ifindex) {
460 		/* XXX boundary check is assumed to be already done. */
461 		ifp = ifnet_byindex(pi->ipi6_ifindex);
462 		if (ifp != NULL &&
463 		    (norouteok || retrt == NULL ||
464 		    IN6_IS_ADDR_MULTICAST(dst))) {
465 			/*
466 			 * we do not have to check or get the route for
467 			 * multicast.
468 			 */
469 			goto done;
470 		} else
471 			goto getroute;
472 	}
473 
474 	/*
475 	 * If the destination address is a multicast address and the outgoing
476 	 * interface for the address is specified by the caller, use it.
477 	 */
478 	if (IN6_IS_ADDR_MULTICAST(dst) &&
479 	    mopts != NULL && (ifp = mopts->im6o_multicast_ifp) != NULL) {
480 		goto done; /* we do not need a route for multicast. */
481 	}
482 
483   getroute:
484 	/*
485 	 * If the next hop address for the packet is specified by the caller,
486 	 * use it as the gateway.
487 	 */
488 	if (opts && opts->ip6po_nexthop) {
489 		struct route_in6 *ron;
490 
491 		sin6_next = satosin6(opts->ip6po_nexthop);
492 
493 		/* at this moment, we only support AF_INET6 next hops */
494 		if (sin6_next->sin6_family != AF_INET6) {
495 			error = EAFNOSUPPORT; /* or should we proceed? */
496 			goto done;
497 		}
498 
499 		/*
500 		 * If the next hop is an IPv6 address, then the node identified
501 		 * by that address must be a neighbor of the sending host.
502 		 */
503 		ron = &opts->ip6po_nextroute;
504 		if ((ron->ro_rt &&
505 		     (ron->ro_rt->rt_flags & (RTF_UP | RTF_LLINFO)) !=
506 		     (RTF_UP | RTF_LLINFO)) ||
507 		    !IN6_ARE_ADDR_EQUAL(&satosin6(&ron->ro_dst)->sin6_addr,
508 		    &sin6_next->sin6_addr)) {
509 			if (ron->ro_rt) {
510 				RTFREE(ron->ro_rt);
511 				ron->ro_rt = NULL;
512 			}
513 			*satosin6(&ron->ro_dst) = *sin6_next;
514 		}
515 		if (ron->ro_rt == NULL) {
516 			rtalloc((struct route *)ron); /* multi path case? */
517 			if (ron->ro_rt == NULL ||
518 			    !(ron->ro_rt->rt_flags & RTF_LLINFO)) {
519 				if (ron->ro_rt) {
520 					RTFREE(ron->ro_rt);
521 					ron->ro_rt = NULL;
522 				}
523 				error = EHOSTUNREACH;
524 				goto done;
525 			}
526 		}
527 		rt = ron->ro_rt;
528 		ifp = rt->rt_ifp;
529 
530 		/*
531 		 * When cloning is required, try to allocate a route to the
532 		 * destination so that the caller can store path MTU
533 		 * information.
534 		 */
535 		if (!clone)
536 			goto done;
537 	}
538 
539 	/*
540 	 * Use a cached route if it exists and is valid, else try to allocate
541 	 * a new one.  Note that we should check the address family of the
542 	 * cached destination, in case of sharing the cache with IPv4.
543 	 */
544 	if (ro) {
545 		if (ro->ro_rt &&
546 		    (!(ro->ro_rt->rt_flags & RTF_UP) ||
547 		     ((struct sockaddr *)(&ro->ro_dst))->sa_family != AF_INET6 ||
548 		     !IN6_ARE_ADDR_EQUAL(&satosin6(&ro->ro_dst)->sin6_addr,
549 		     dst))) {
550 			RTFREE(ro->ro_rt);
551 			ro->ro_rt = (struct rtentry *)NULL;
552 		}
553 		if (ro->ro_rt == (struct rtentry *)NULL) {
554 			struct sockaddr_in6 *sa6;
555 
556 			/* No route yet, so try to acquire one */
557 			bzero(&ro->ro_dst, sizeof(struct sockaddr_in6));
558 			sa6 = (struct sockaddr_in6 *)&ro->ro_dst;
559 			*sa6 = *dstsock;
560 			sa6->sin6_scope_id = 0;
561 
562 			if (clone) {
563 				rtalloc((struct route *)ro);
564 			} else {
565 				ro->ro_rt = rtalloc1(&((struct route *)ro)
566 						     ->ro_dst, 0, 0UL);
567 				if (ro->ro_rt)
568 					RT_UNLOCK(ro->ro_rt);
569 			}
570 		}
571 
572 		/*
573 		 * do not care about the result if we have the nexthop
574 		 * explicitly specified.
575 		 */
576 		if (opts && opts->ip6po_nexthop)
577 			goto done;
578 
579 		if (ro->ro_rt) {
580 			ifp = ro->ro_rt->rt_ifp;
581 
582 			if (ifp == NULL) { /* can this really happen? */
583 				RTFREE(ro->ro_rt);
584 				ro->ro_rt = NULL;
585 			}
586 		}
587 		if (ro->ro_rt == NULL)
588 			error = EHOSTUNREACH;
589 		rt = ro->ro_rt;
590 
591 		/*
592 		 * Check if the outgoing interface conflicts with
593 		 * the interface specified by ipi6_ifindex (if specified).
594 		 * Note that loopback interface is always okay.
595 		 * (this may happen when we are sending a packet to one of
596 		 *  our own addresses.)
597 		 */
598 		if (ifp && opts && opts->ip6po_pktinfo &&
599 		    opts->ip6po_pktinfo->ipi6_ifindex) {
600 			if (!(ifp->if_flags & IFF_LOOPBACK) &&
601 			    ifp->if_index !=
602 			    opts->ip6po_pktinfo->ipi6_ifindex) {
603 				error = EHOSTUNREACH;
604 				goto done;
605 			}
606 		}
607 	}
608 
609   done:
610 	if (ifp == NULL && rt == NULL) {
611 		/*
612 		 * This can happen if the caller did not pass a cached route
613 		 * nor any other hints.  We treat this case an error.
614 		 */
615 		error = EHOSTUNREACH;
616 	}
617 	if (error == EHOSTUNREACH)
618 		ip6stat.ip6s_noroute++;
619 
620 	if (retifp != NULL)
621 		*retifp = ifp;
622 	if (retrt != NULL)
623 		*retrt = rt;	/* rt may be NULL */
624 
625 	return (error);
626 }
627 
628 static int
629 in6_selectif(struct sockaddr_in6 *dstsock, struct ip6_pktopts *opts,
630     struct ip6_moptions *mopts, struct route_in6 *ro, struct ifnet **retifp)
631 {
632 	int error;
633 	struct route_in6 sro;
634 	struct rtentry *rt = NULL;
635 
636 	if (ro == NULL) {
637 		bzero(&sro, sizeof(sro));
638 		ro = &sro;
639 	}
640 
641 	if ((error = selectroute(dstsock, opts, mopts, ro, retifp,
642 				     &rt, 0, 1)) != 0) {
643 		if (ro == &sro && rt && rt == sro.ro_rt)
644 			RTFREE(rt);
645 		return (error);
646 	}
647 
648 	/*
649 	 * do not use a rejected or black hole route.
650 	 * XXX: this check should be done in the L2 output routine.
651 	 * However, if we skipped this check here, we'd see the following
652 	 * scenario:
653 	 * - install a rejected route for a scoped address prefix
654 	 *   (like fe80::/10)
655 	 * - send a packet to a destination that matches the scoped prefix,
656 	 *   with ambiguity about the scope zone.
657 	 * - pick the outgoing interface from the route, and disambiguate the
658 	 *   scope zone with the interface.
659 	 * - ip6_output() would try to get another route with the "new"
660 	 *   destination, which may be valid.
661 	 * - we'd see no error on output.
662 	 * Although this may not be very harmful, it should still be confusing.
663 	 * We thus reject the case here.
664 	 */
665 	if (rt && (rt->rt_flags & (RTF_REJECT | RTF_BLACKHOLE))) {
666 		int flags = (rt->rt_flags & RTF_HOST ? EHOSTUNREACH : ENETUNREACH);
667 
668 		if (ro == &sro && rt && rt == sro.ro_rt)
669 			RTFREE(rt);
670 		return (flags);
671 	}
672 
673 	/*
674 	 * Adjust the "outgoing" interface.  If we're going to loop the packet
675 	 * back to ourselves, the ifp would be the loopback interface.
676 	 * However, we'd rather know the interface associated to the
677 	 * destination address (which should probably be one of our own
678 	 * addresses.)
679 	 */
680 	if (rt && rt->rt_ifa && rt->rt_ifa->ifa_ifp)
681 		*retifp = rt->rt_ifa->ifa_ifp;
682 
683 	if (ro == &sro && rt && rt == sro.ro_rt)
684 		RTFREE(rt);
685 	return (0);
686 }
687 
688 /*
689  * clone - meaningful only for bsdi and freebsd
690  */
691 int
692 in6_selectroute(struct sockaddr_in6 *dstsock, struct ip6_pktopts *opts,
693     struct ip6_moptions *mopts, struct route_in6 *ro,
694     struct ifnet **retifp, struct rtentry **retrt, int clone)
695 {
696 
697 	return (selectroute(dstsock, opts, mopts, ro, retifp,
698 	    retrt, clone, 0));
699 }
700 
701 /*
702  * Default hop limit selection. The precedence is as follows:
703  * 1. Hoplimit value specified via ioctl.
704  * 2. (If the outgoing interface is detected) the current
705  *     hop limit of the interface specified by router advertisement.
706  * 3. The system default hoplimit.
707  */
708 int
709 in6_selecthlim(struct in6pcb *in6p, struct ifnet *ifp)
710 {
711 
712 	if (in6p && in6p->in6p_hops >= 0)
713 		return (in6p->in6p_hops);
714 	else if (ifp)
715 		return (ND_IFINFO(ifp)->chlim);
716 	else if (in6p && !IN6_IS_ADDR_UNSPECIFIED(&in6p->in6p_faddr)) {
717 		struct route_in6 ro6;
718 		struct ifnet *lifp;
719 
720 		bzero(&ro6, sizeof(ro6));
721 		ro6.ro_dst.sin6_family = AF_INET6;
722 		ro6.ro_dst.sin6_len = sizeof(struct sockaddr_in6);
723 		ro6.ro_dst.sin6_addr = in6p->in6p_faddr;
724 		rtalloc((struct route *)&ro6);
725 		if (ro6.ro_rt) {
726 			lifp = ro6.ro_rt->rt_ifp;
727 			RTFREE(ro6.ro_rt);
728 			if (lifp)
729 				return (ND_IFINFO(lifp)->chlim);
730 		} else
731 			return (ip6_defhlim);
732 	}
733 	return (ip6_defhlim);
734 }
735 
736 /*
737  * XXX: this is borrowed from in6_pcbbind(). If possible, we should
738  * share this function by all *bsd*...
739  */
740 int
741 in6_pcbsetport(struct in6_addr *laddr, struct inpcb *inp, struct ucred *cred)
742 {
743 	struct socket *so = inp->inp_socket;
744 	u_int16_t lport = 0, first, last, *lastport;
745 	int count, error = 0, wild = 0;
746 	struct inpcbinfo *pcbinfo = inp->inp_pcbinfo;
747 
748 	INP_INFO_WLOCK_ASSERT(pcbinfo);
749 	INP_LOCK_ASSERT(inp);
750 
751 	/* XXX: this is redundant when called from in6_pcbbind */
752 	if ((so->so_options & (SO_REUSEADDR|SO_REUSEPORT)) == 0)
753 		wild = INPLOOKUP_WILDCARD;
754 
755 	inp->inp_flags |= INP_ANONPORT;
756 
757 	if (inp->inp_flags & INP_HIGHPORT) {
758 		first = ipport_hifirstauto;	/* sysctl */
759 		last  = ipport_hilastauto;
760 		lastport = &pcbinfo->ipi_lasthi;
761 	} else if (inp->inp_flags & INP_LOWPORT) {
762 		error = priv_check_cred(cred, PRIV_NETINET_RESERVEDPORT, 0);
763 		if (error)
764 			return error;
765 		first = ipport_lowfirstauto;	/* 1023 */
766 		last  = ipport_lowlastauto;	/* 600 */
767 		lastport = &pcbinfo->ipi_lastlow;
768 	} else {
769 		first = ipport_firstauto;	/* sysctl */
770 		last  = ipport_lastauto;
771 		lastport = &pcbinfo->ipi_lastport;
772 	}
773 	/*
774 	 * Simple check to ensure all ports are not used up causing
775 	 * a deadlock here.
776 	 *
777 	 * We split the two cases (up and down) so that the direction
778 	 * is not being tested on each round of the loop.
779 	 */
780 	if (first > last) {
781 		/*
782 		 * counting down
783 		 */
784 		count = first - last;
785 
786 		do {
787 			if (count-- < 0) {	/* completely used? */
788 				/*
789 				 * Undo any address bind that may have
790 				 * occurred above.
791 				 */
792 				inp->in6p_laddr = in6addr_any;
793 				return (EAGAIN);
794 			}
795 			--*lastport;
796 			if (*lastport > first || *lastport < last)
797 				*lastport = first;
798 			lport = htons(*lastport);
799 		} while (in6_pcblookup_local(pcbinfo, &inp->in6p_laddr,
800 					     lport, wild));
801 	} else {
802 		/*
803 			 * counting up
804 			 */
805 		count = last - first;
806 
807 		do {
808 			if (count-- < 0) {	/* completely used? */
809 				/*
810 				 * Undo any address bind that may have
811 				 * occurred above.
812 				 */
813 				inp->in6p_laddr = in6addr_any;
814 				return (EAGAIN);
815 			}
816 			++*lastport;
817 			if (*lastport < first || *lastport > last)
818 				*lastport = first;
819 			lport = htons(*lastport);
820 		} while (in6_pcblookup_local(pcbinfo,
821 					     &inp->in6p_laddr, lport, wild));
822 	}
823 
824 	inp->inp_lport = lport;
825 	if (in_pcbinshash(inp) != 0) {
826 		inp->in6p_laddr = in6addr_any;
827 		inp->inp_lport = 0;
828 		return (EAGAIN);
829 	}
830 
831 	return (0);
832 }
833 
834 void
835 addrsel_policy_init(void)
836 {
837 	ADDRSEL_LOCK_INIT();
838 	ADDRSEL_SXLOCK_INIT();
839 
840 	init_policy_queue();
841 
842 	/* initialize the "last resort" policy */
843 	bzero(&defaultaddrpolicy, sizeof(defaultaddrpolicy));
844 	defaultaddrpolicy.label = ADDR_LABEL_NOTAPP;
845 }
846 
847 static struct in6_addrpolicy *
848 lookup_addrsel_policy(struct sockaddr_in6 *key)
849 {
850 	struct in6_addrpolicy *match = NULL;
851 
852 	ADDRSEL_LOCK();
853 	match = match_addrsel_policy(key);
854 
855 	if (match == NULL)
856 		match = &defaultaddrpolicy;
857 	else
858 		match->use++;
859 	ADDRSEL_UNLOCK();
860 
861 	return (match);
862 }
863 
864 /*
865  * Subroutines to manage the address selection policy table via sysctl.
866  */
867 struct walkarg {
868 	struct sysctl_req *w_req;
869 };
870 
871 static int in6_src_sysctl(SYSCTL_HANDLER_ARGS);
872 SYSCTL_DECL(_net_inet6_ip6);
873 SYSCTL_NODE(_net_inet6_ip6, IPV6CTL_ADDRCTLPOLICY, addrctlpolicy,
874 	CTLFLAG_RD, in6_src_sysctl, "");
875 
876 static int
877 in6_src_sysctl(SYSCTL_HANDLER_ARGS)
878 {
879 	struct walkarg w;
880 
881 	if (req->newptr)
882 		return EPERM;
883 
884 	bzero(&w, sizeof(w));
885 	w.w_req = req;
886 
887 	return (walk_addrsel_policy(dump_addrsel_policyent, &w));
888 }
889 
890 int
891 in6_src_ioctl(u_long cmd, caddr_t data)
892 {
893 	int i;
894 	struct in6_addrpolicy ent0;
895 
896 	if (cmd != SIOCAADDRCTL_POLICY && cmd != SIOCDADDRCTL_POLICY)
897 		return (EOPNOTSUPP); /* check for safety */
898 
899 	ent0 = *(struct in6_addrpolicy *)data;
900 
901 	if (ent0.label == ADDR_LABEL_NOTAPP)
902 		return (EINVAL);
903 	/* check if the prefix mask is consecutive. */
904 	if (in6_mask2len(&ent0.addrmask.sin6_addr, NULL) < 0)
905 		return (EINVAL);
906 	/* clear trailing garbages (if any) of the prefix address. */
907 	for (i = 0; i < 4; i++) {
908 		ent0.addr.sin6_addr.s6_addr32[i] &=
909 			ent0.addrmask.sin6_addr.s6_addr32[i];
910 	}
911 	ent0.use = 0;
912 
913 	switch (cmd) {
914 	case SIOCAADDRCTL_POLICY:
915 		return (add_addrsel_policyent(&ent0));
916 	case SIOCDADDRCTL_POLICY:
917 		return (delete_addrsel_policyent(&ent0));
918 	}
919 
920 	return (0);		/* XXX: compromise compilers */
921 }
922 
923 /*
924  * The followings are implementation of the policy table using a
925  * simple tail queue.
926  * XXX such details should be hidden.
927  * XXX implementation using binary tree should be more efficient.
928  */
929 struct addrsel_policyent {
930 	TAILQ_ENTRY(addrsel_policyent) ape_entry;
931 	struct in6_addrpolicy ape_policy;
932 };
933 
934 TAILQ_HEAD(addrsel_policyhead, addrsel_policyent);
935 
936 struct addrsel_policyhead addrsel_policytab;
937 
938 static void
939 init_policy_queue(void)
940 {
941 
942 	TAILQ_INIT(&addrsel_policytab);
943 }
944 
945 static int
946 add_addrsel_policyent(struct in6_addrpolicy *newpolicy)
947 {
948 	struct addrsel_policyent *new, *pol;
949 
950 	MALLOC(new, struct addrsel_policyent *, sizeof(*new), M_IFADDR,
951 	       M_WAITOK);
952 	ADDRSEL_XLOCK();
953 	ADDRSEL_LOCK();
954 
955 	/* duplication check */
956 	TAILQ_FOREACH(pol, &addrsel_policytab, ape_entry) {
957 		if (IN6_ARE_ADDR_EQUAL(&newpolicy->addr.sin6_addr,
958 				       &pol->ape_policy.addr.sin6_addr) &&
959 		    IN6_ARE_ADDR_EQUAL(&newpolicy->addrmask.sin6_addr,
960 				       &pol->ape_policy.addrmask.sin6_addr)) {
961 			ADDRSEL_UNLOCK();
962 			ADDRSEL_XUNLOCK();
963 			FREE(new, M_IFADDR);
964 			return (EEXIST);	/* or override it? */
965 		}
966 	}
967 
968 	bzero(new, sizeof(*new));
969 
970 	/* XXX: should validate entry */
971 	new->ape_policy = *newpolicy;
972 
973 	TAILQ_INSERT_TAIL(&addrsel_policytab, new, ape_entry);
974 	ADDRSEL_UNLOCK();
975 	ADDRSEL_XUNLOCK();
976 
977 	return (0);
978 }
979 
980 static int
981 delete_addrsel_policyent(struct in6_addrpolicy *key)
982 {
983 	struct addrsel_policyent *pol;
984 
985 	ADDRSEL_XLOCK();
986 	ADDRSEL_LOCK();
987 
988 	/* search for the entry in the table */
989 	TAILQ_FOREACH(pol, &addrsel_policytab, ape_entry) {
990 		if (IN6_ARE_ADDR_EQUAL(&key->addr.sin6_addr,
991 		    &pol->ape_policy.addr.sin6_addr) &&
992 		    IN6_ARE_ADDR_EQUAL(&key->addrmask.sin6_addr,
993 		    &pol->ape_policy.addrmask.sin6_addr)) {
994 			break;
995 		}
996 	}
997 	if (pol == NULL) {
998 		ADDRSEL_UNLOCK();
999 		ADDRSEL_XUNLOCK();
1000 		return (ESRCH);
1001 	}
1002 
1003 	TAILQ_REMOVE(&addrsel_policytab, pol, ape_entry);
1004 	ADDRSEL_UNLOCK();
1005 	ADDRSEL_XUNLOCK();
1006 
1007 	return (0);
1008 }
1009 
1010 static int
1011 walk_addrsel_policy(int (*callback) __P((struct in6_addrpolicy *, void *)),
1012     void *w)
1013 {
1014 	struct addrsel_policyent *pol;
1015 	int error = 0;
1016 
1017 	ADDRSEL_SLOCK();
1018 	TAILQ_FOREACH(pol, &addrsel_policytab, ape_entry) {
1019 		if ((error = (*callback)(&pol->ape_policy, w)) != 0) {
1020 			ADDRSEL_SUNLOCK();
1021 			return (error);
1022 		}
1023 	}
1024 	ADDRSEL_SUNLOCK();
1025 	return (error);
1026 }
1027 
1028 static int
1029 dump_addrsel_policyent(struct in6_addrpolicy *pol, void *arg)
1030 {
1031 	int error = 0;
1032 	struct walkarg *w = arg;
1033 
1034 	error = SYSCTL_OUT(w->w_req, pol, sizeof(*pol));
1035 
1036 	return (error);
1037 }
1038 
1039 static struct in6_addrpolicy *
1040 match_addrsel_policy(struct sockaddr_in6 *key)
1041 {
1042 	struct addrsel_policyent *pent;
1043 	struct in6_addrpolicy *bestpol = NULL, *pol;
1044 	int matchlen, bestmatchlen = -1;
1045 	u_char *mp, *ep, *k, *p, m;
1046 
1047 	TAILQ_FOREACH(pent, &addrsel_policytab, ape_entry) {
1048 		matchlen = 0;
1049 
1050 		pol = &pent->ape_policy;
1051 		mp = (u_char *)&pol->addrmask.sin6_addr;
1052 		ep = mp + 16;	/* XXX: scope field? */
1053 		k = (u_char *)&key->sin6_addr;
1054 		p = (u_char *)&pol->addr.sin6_addr;
1055 		for (; mp < ep && *mp; mp++, k++, p++) {
1056 			m = *mp;
1057 			if ((*k & m) != *p)
1058 				goto next; /* not match */
1059 			if (m == 0xff) /* short cut for a typical case */
1060 				matchlen += 8;
1061 			else {
1062 				while (m >= 0x80) {
1063 					matchlen++;
1064 					m <<= 1;
1065 				}
1066 			}
1067 		}
1068 
1069 		/* matched.  check if this is better than the current best. */
1070 		if (bestpol == NULL ||
1071 		    matchlen > bestmatchlen) {
1072 			bestpol = pol;
1073 			bestmatchlen = matchlen;
1074 		}
1075 
1076 	  next:
1077 		continue;
1078 	}
1079 
1080 	return (bestpol);
1081 }
1082