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