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