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