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