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