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