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