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