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