1/*
2 * Copyright (c) 2000-2013 Apple Inc. All rights reserved.
3 *
4 * @APPLE_OSREFERENCE_LICENSE_HEADER_START@
5 *
6 * This file contains Original Code and/or Modifications of Original Code
7 * as defined in and that are subject to the Apple Public Source License
8 * Version 2.0 (the 'License'). You may not use this file except in
9 * compliance with the License. The rights granted to you under the License
10 * may not be used to create, or enable the creation or redistribution of,
11 * unlawful or unlicensed copies of an Apple operating system, or to
12 * circumvent, violate, or enable the circumvention or violation of, any
13 * terms of an Apple operating system software license agreement.
14 *
15 * Please obtain a copy of the License at
16 * http://www.opensource.apple.com/apsl/ and read it before using this file.
17 *
18 * The Original Code and all software distributed under the License are
19 * distributed on an 'AS IS' basis, WITHOUT WARRANTY OF ANY KIND, EITHER
20 * EXPRESS OR IMPLIED, AND APPLE HEREBY DISCLAIMS ALL SUCH WARRANTIES,
21 * INCLUDING WITHOUT LIMITATION, ANY WARRANTIES OF MERCHANTABILITY,
22 * FITNESS FOR A PARTICULAR PURPOSE, QUIET ENJOYMENT OR NON-INFRINGEMENT.
23 * Please see the License for the specific language governing rights and
24 * limitations under the License.
25 *
26 * @APPLE_OSREFERENCE_LICENSE_HEADER_END@
27 */
28
29/*
30 * Copyright (C) 1995, 1996, 1997, and 1998 WIDE Project.
31 * All rights reserved.
32 *
33 * Redistribution and use in source and binary forms, with or without
34 * modification, are permitted provided that the following conditions
35 * are met:
36 * 1. Redistributions of source code must retain the above copyright
37 *    notice, this list of conditions and the following disclaimer.
38 * 2. Redistributions in binary form must reproduce the above copyright
39 *    notice, this list of conditions and the following disclaimer in the
40 *    documentation and/or other materials provided with the distribution.
41 * 3. Neither the name of the project nor the names of its contributors
42 *    may be used to endorse or promote products derived from this software
43 *    without specific prior written permission.
44 *
45 * THIS SOFTWARE IS PROVIDED BY THE PROJECT AND CONTRIBUTORS ``AS IS'' AND
46 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
47 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
48 * ARE DISCLAIMED.  IN NO EVENT SHALL THE PROJECT OR CONTRIBUTORS BE LIABLE
49 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
50 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
51 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
52 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
53 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
54 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
55 * SUCH DAMAGE.
56 */
57
58/*
59 * Copyright (c) 1982, 1986, 1991, 1993
60 *	The Regents of the University of California.  All rights reserved.
61 *
62 * Redistribution and use in source and binary forms, with or without
63 * modification, are permitted provided that the following conditions
64 * are met:
65 * 1. Redistributions of source code must retain the above copyright
66 *    notice, this list of conditions and the following disclaimer.
67 * 2. Redistributions in binary form must reproduce the above copyright
68 *    notice, this list of conditions and the following disclaimer in the
69 *    documentation and/or other materials provided with the distribution.
70 * 3. All advertising materials mentioning features or use of this software
71 *    must display the following acknowledgement:
72 *	This product includes software developed by the University of
73 *	California, Berkeley and its contributors.
74 * 4. Neither the name of the University nor the names of its contributors
75 *    may be used to endorse or promote products derived from this software
76 *    without specific prior written permission.
77 *
78 * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
79 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
80 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
81 * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
82 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
83 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
84 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
85 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
86 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
87 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
88 * SUCH DAMAGE.
89 *
90 *	@(#)in_pcb.c	8.2 (Berkeley) 1/4/94
91 */
92
93
94#include <sys/param.h>
95#include <sys/systm.h>
96#include <sys/malloc.h>
97#include <sys/mbuf.h>
98#include <sys/protosw.h>
99#include <sys/socket.h>
100#include <sys/socketvar.h>
101#include <sys/errno.h>
102#include <sys/time.h>
103#include <sys/proc.h>
104#include <sys/sysctl.h>
105#include <sys/kauth.h>
106#include <sys/priv.h>
107#include <kern/lock.h>
108
109#include <net/if.h>
110#include <net/if_types.h>
111#include <net/route.h>
112
113#include <netinet/in.h>
114#include <netinet/in_var.h>
115#include <netinet/in_systm.h>
116#include <netinet/ip.h>
117#include <netinet/in_pcb.h>
118#include <netinet6/in6_var.h>
119#include <netinet/ip6.h>
120#include <netinet6/in6_pcb.h>
121#include <netinet6/ip6_var.h>
122#include <netinet6/scope6_var.h>
123#include <netinet6/nd6.h>
124
125#include <net/net_osdep.h>
126
127#include "loop.h"
128
129SYSCTL_DECL(_net_inet6_ip6);
130
131static int ip6_select_srcif_debug = 0;
132SYSCTL_INT(_net_inet6_ip6, OID_AUTO, select_srcif_debug,
133	CTLFLAG_RW | CTLFLAG_LOCKED, &ip6_select_srcif_debug, 0,
134	"log source interface selection debug info");
135
136#define	ADDR_LABEL_NOTAPP (-1)
137struct in6_addrpolicy defaultaddrpolicy;
138
139int ip6_prefer_tempaddr = 1;
140#ifdef ENABLE_ADDRSEL
141extern lck_mtx_t *addrsel_mutex;
142#define	ADDRSEL_LOCK()		lck_mtx_lock(addrsel_mutex)
143#define	ADDRSEL_UNLOCK()	lck_mtx_unlock(addrsel_mutex)
144#else
145#define	ADDRSEL_LOCK()
146#define	ADDRSEL_UNLOCK()
147#endif
148
149static int selectroute(struct sockaddr_in6 *, struct sockaddr_in6 *,
150	struct ip6_pktopts *, struct ip6_moptions *, struct in6_ifaddr **,
151	struct route_in6 *, struct ifnet **, struct rtentry **, int, int,
152	struct ip6_out_args *ip6oa);
153static int in6_selectif(struct sockaddr_in6 *, struct ip6_pktopts *,
154	struct ip6_moptions *, struct route_in6 *ro,
155	struct ip6_out_args *, struct ifnet **);
156static void init_policy_queue(void);
157static int add_addrsel_policyent(const struct in6_addrpolicy *);
158#ifdef ENABLE_ADDRSEL
159static int delete_addrsel_policyent(const struct in6_addrpolicy *);
160#endif
161static int walk_addrsel_policy(int (*)(const struct in6_addrpolicy *, void *),
162	void *);
163static int dump_addrsel_policyent(const struct in6_addrpolicy *, void *);
164static struct in6_addrpolicy *match_addrsel_policy(struct sockaddr_in6 *);
165void addrsel_policy_init(void);
166
167/*
168 * Return an IPv6 address, which is the most appropriate for a given
169 * destination and user specified options.
170 * If necessary, this function lookups the routing table and returns
171 * an entry to the caller for later use.
172 */
173#define	REPLACE(r) do {\
174	if ((r) < sizeof (ip6stat.ip6s_sources_rule) / \
175		sizeof (ip6stat.ip6s_sources_rule[0])) /* check for safety */ \
176		ip6stat.ip6s_sources_rule[(r)]++; \
177	goto replace; \
178} while (0)
179#define	NEXTSRC(r) do {\
180	if ((r) < sizeof (ip6stat.ip6s_sources_rule) / \
181		sizeof (ip6stat.ip6s_sources_rule[0])) /* check for safety */ \
182		ip6stat.ip6s_sources_rule[(r)]++; \
183	goto next;		/* XXX: we can't use 'continue' here */ \
184} while (0)
185#define	BREAK(r) do { \
186	if ((r) < sizeof (ip6stat.ip6s_sources_rule) / \
187		sizeof (ip6stat.ip6s_sources_rule[0])) /* check for safety */ \
188		ip6stat.ip6s_sources_rule[(r)]++; \
189	goto out;		/* XXX: we can't use 'break' here */ \
190} while (0)
191
192/*
193 * Regardless of error, it will return an ifp with a reference held if the
194 * caller provides a non-NULL ifpp.  The caller is responsible for checking
195 * if the returned ifp is valid and release its reference at all times.
196 */
197struct in6_addr *
198in6_selectsrc(struct sockaddr_in6 *dstsock, struct ip6_pktopts *opts,
199    struct inpcb *inp, struct route_in6 *ro,
200    struct ifnet **ifpp, struct in6_addr *src_storage, unsigned int ifscope,
201    int *errorp)
202{
203	struct in6_addr dst;
204	struct ifnet *ifp = NULL;
205	struct in6_ifaddr *ia = NULL, *ia_best = NULL;
206	struct in6_pktinfo *pi = NULL;
207	int dst_scope = -1, best_scope = -1, best_matchlen = -1;
208	struct in6_addrpolicy *dst_policy = NULL, *best_policy = NULL;
209	u_int32_t odstzone;
210	int prefer_tempaddr;
211	struct ip6_moptions *mopts;
212	struct ip6_out_args ip6oa = { ifscope, { 0 }, IP6OAF_SELECT_SRCIF, 0 };
213	boolean_t islocal = FALSE;
214	uint64_t secs = net_uptime();
215
216	dst = dstsock->sin6_addr; /* make a copy for local operation */
217	*errorp = 0;
218	if (ifpp != NULL)
219		*ifpp = NULL;
220
221	if (inp != NULL) {
222		mopts = inp->in6p_moptions;
223		if (inp->inp_flags & INP_NO_IFT_CELLULAR)
224			ip6oa.ip6oa_flags |= IP6OAF_NO_CELLULAR;
225	} else {
226		mopts = NULL;
227	}
228
229	if (ip6oa.ip6oa_boundif != IFSCOPE_NONE)
230		ip6oa.ip6oa_flags |= IP6OAF_BOUND_IF;
231
232	/*
233	 * If the source address is explicitly specified by the caller,
234	 * check if the requested source address is indeed a unicast address
235	 * assigned to the node, and can be used as the packet's source
236	 * address.  If everything is okay, use the address as source.
237	 */
238	if (opts && (pi = opts->ip6po_pktinfo) &&
239	    !IN6_IS_ADDR_UNSPECIFIED(&pi->ipi6_addr)) {
240		struct sockaddr_in6 srcsock;
241		struct in6_ifaddr *ia6;
242
243		/* get the outgoing interface */
244		if ((*errorp = in6_selectif(dstsock, opts, mopts, ro, &ip6oa,
245		    &ifp)) != 0) {
246			src_storage = NULL;
247			goto done;
248		}
249
250		/*
251		 * determine the appropriate zone id of the source based on
252		 * the zone of the destination and the outgoing interface.
253		 * If the specified address is ambiguous wrt the scope zone,
254		 * the interface must be specified; otherwise, ifa_ifwithaddr()
255		 * will fail matching the address.
256		 */
257		bzero(&srcsock, sizeof (srcsock));
258		srcsock.sin6_family = AF_INET6;
259		srcsock.sin6_len = sizeof (srcsock);
260		srcsock.sin6_addr = pi->ipi6_addr;
261		if (ifp != NULL) {
262			*errorp = in6_setscope(&srcsock.sin6_addr, ifp, NULL);
263			if (*errorp != 0) {
264				src_storage = NULL;
265				goto done;
266			}
267		}
268		ia6 = (struct in6_ifaddr *)ifa_ifwithaddr((struct sockaddr *)
269		    (&srcsock));
270		if (ia6 == NULL) {
271			*errorp = EADDRNOTAVAIL;
272			src_storage = NULL;
273			goto done;
274		}
275		IFA_LOCK_SPIN(&ia6->ia_ifa);
276		if ((ia6->ia6_flags & (IN6_IFF_ANYCAST | IN6_IFF_NOTREADY)) ||
277		    ((ip6oa.ip6oa_flags & IP6OAF_NO_CELLULAR) &&
278		    IFNET_IS_CELLULAR(ia6->ia_ifa.ifa_ifp))) {
279			IFA_UNLOCK(&ia6->ia_ifa);
280			IFA_REMREF(&ia6->ia_ifa);
281			*errorp = EHOSTUNREACH;
282			src_storage = NULL;
283			goto done;
284		}
285
286		*src_storage = satosin6(&ia6->ia_addr)->sin6_addr;
287		IFA_UNLOCK(&ia6->ia_ifa);
288		IFA_REMREF(&ia6->ia_ifa);
289		goto done;
290	}
291
292	/*
293	 * Otherwise, if the socket has already bound the source, just use it.
294	 */
295	if (inp != NULL && !IN6_IS_ADDR_UNSPECIFIED(&inp->in6p_laddr)) {
296		src_storage = &inp->in6p_laddr;
297		goto done;
298	}
299
300	/*
301	 * If the address is not specified, choose the best one based on
302	 * the outgoing interface and the destination address.
303	 */
304
305	/* get the outgoing interface */
306	if ((*errorp = in6_selectif(dstsock, opts, mopts, ro, &ip6oa,
307	    &ifp)) != 0) {
308		src_storage = NULL;
309		goto done;
310	}
311
312	*errorp = in6_setscope(&dst, ifp, &odstzone);
313	if (*errorp != 0) {
314		src_storage = NULL;
315		goto done;
316	}
317	lck_rw_lock_shared(&in6_ifaddr_rwlock);
318
319	for (ia = in6_ifaddrs; ia; ia = ia->ia_next) {
320		int new_scope = -1, new_matchlen = -1;
321		struct in6_addrpolicy *new_policy = NULL;
322		u_int32_t srczone, osrczone, dstzone;
323		struct in6_addr src;
324		struct ifnet *ifp1 = ia->ia_ifp;
325
326		IFA_LOCK(&ia->ia_ifa);
327		/*
328		 * We'll never take an address that breaks the scope zone
329		 * of the destination.  We also skip an address if its zone
330		 * does not contain the outgoing interface.
331		 * XXX: we should probably use sin6_scope_id here.
332		 */
333		if (in6_setscope(&dst, ifp1, &dstzone) ||
334		    odstzone != dstzone)
335			goto next;
336
337		src = ia->ia_addr.sin6_addr;
338		if (in6_setscope(&src, ifp, &osrczone) ||
339		    in6_setscope(&src, ifp1, &srczone) ||
340		    osrczone != srczone)
341			goto next;
342
343		/* avoid unusable addresses */
344		if ((ia->ia6_flags &
345		    (IN6_IFF_NOTREADY | IN6_IFF_ANYCAST | IN6_IFF_DETACHED)))
346			goto next;
347
348		if (!ip6_use_deprecated && IFA6_IS_DEPRECATED(ia, secs))
349			goto next;
350
351		if (!nd6_optimistic_dad &&
352		    (ia->ia6_flags & IN6_IFF_OPTIMISTIC) != 0)
353			goto next;
354
355		/* Rule 1: Prefer same address */
356		if (IN6_ARE_ADDR_EQUAL(&dst, &ia->ia_addr.sin6_addr))
357			BREAK(1); /* there should be no better candidate */
358
359		if (ia_best == NULL)
360			REPLACE(0);
361
362		/* Rule 2: Prefer appropriate scope */
363		if (dst_scope < 0)
364			dst_scope = in6_addrscope(&dst);
365		new_scope = in6_addrscope(&ia->ia_addr.sin6_addr);
366		if (IN6_ARE_SCOPE_CMP(best_scope, new_scope) < 0) {
367			if (IN6_ARE_SCOPE_CMP(best_scope, dst_scope) < 0)
368				REPLACE(2);
369			NEXTSRC(2);
370		} else if (IN6_ARE_SCOPE_CMP(new_scope, best_scope) < 0) {
371			if (IN6_ARE_SCOPE_CMP(new_scope, dst_scope) < 0)
372				NEXTSRC(2);
373			REPLACE(2);
374		}
375
376		/*
377		 * Rule 3: Avoid deprecated addresses.  Note that the case of
378		 * !ip6_use_deprecated is already rejected above.
379		 */
380		if (!IFA6_IS_DEPRECATED(ia_best, secs) &&
381		    IFA6_IS_DEPRECATED(ia, secs))
382			NEXTSRC(3);
383		if (IFA6_IS_DEPRECATED(ia_best, secs) &&
384		    !IFA6_IS_DEPRECATED(ia, secs))
385			REPLACE(3);
386
387		/*
388		 * RFC 4429 says that optimistic addresses are equivalent to
389		 * deprecated addresses, so avoid them here.
390		 */
391		if ((ia_best->ia6_flags & IN6_IFF_OPTIMISTIC) == 0 &&
392		    (ia->ia6_flags & IN6_IFF_OPTIMISTIC) != 0)
393			NEXTSRC(3);
394		if ((ia_best->ia6_flags & IN6_IFF_OPTIMISTIC) != 0 &&
395		    (ia->ia6_flags & IN6_IFF_OPTIMISTIC) == 0)
396			REPLACE(3);
397
398		/* Rule 4: Prefer home addresses */
399		/*
400		 * XXX: This is a TODO.  We should probably merge the MIP6
401		 * case above.
402		 */
403
404		/* Rule 5: Prefer outgoing interface */
405		if (ia_best->ia_ifp == ifp && ia->ia_ifp != ifp)
406			NEXTSRC(5);
407		if (ia_best->ia_ifp != ifp && ia->ia_ifp == ifp)
408			REPLACE(5);
409
410		/*
411		 * Rule 6: Prefer matching label
412		 * Note that best_policy should be non-NULL here.
413		 */
414		if (dst_policy == NULL)
415			dst_policy = in6_addrsel_lookup_policy(dstsock);
416		if (dst_policy->label != ADDR_LABEL_NOTAPP) {
417			new_policy = in6_addrsel_lookup_policy(&ia->ia_addr);
418			if (dst_policy->label == best_policy->label &&
419			    dst_policy->label != new_policy->label)
420				NEXTSRC(6);
421			if (dst_policy->label != best_policy->label &&
422			    dst_policy->label == new_policy->label)
423				REPLACE(6);
424		}
425
426		/*
427		 * Rule 7: Prefer public addresses.
428		 * We allow users to reverse the logic by configuring
429		 * a sysctl variable, so that privacy conscious users can
430		 * always prefer temporary addresses.
431		 * Don't use temporary addresses for local destinations or
432		 * for multicast addresses unless we were passed in an option.
433		 */
434		if (IN6_IS_ADDR_MULTICAST(&dst) ||
435		    in6_matchlen(&ia_best->ia_addr.sin6_addr, &dst) >=
436		    ia_best->ia_plen)
437			islocal = TRUE;
438		if (opts == NULL ||
439		    opts->ip6po_prefer_tempaddr == IP6PO_TEMPADDR_SYSTEM) {
440			prefer_tempaddr = islocal ? 0 : ip6_prefer_tempaddr;
441		} else if (opts->ip6po_prefer_tempaddr ==
442		    IP6PO_TEMPADDR_NOTPREFER) {
443			prefer_tempaddr = 0;
444		} else
445			prefer_tempaddr = 1;
446		if (!(ia_best->ia6_flags & IN6_IFF_TEMPORARY) &&
447		    (ia->ia6_flags & IN6_IFF_TEMPORARY)) {
448			if (prefer_tempaddr)
449				REPLACE(7);
450			else
451				NEXTSRC(7);
452		}
453		if ((ia_best->ia6_flags & IN6_IFF_TEMPORARY) &&
454		    !(ia->ia6_flags & IN6_IFF_TEMPORARY)) {
455			if (prefer_tempaddr)
456				NEXTSRC(7);
457			else
458				REPLACE(7);
459		}
460
461		/*
462		 * Rule 8: prefer addresses on alive interfaces.
463		 * This is a KAME specific rule.
464		 */
465		if ((ia_best->ia_ifp->if_flags & IFF_UP) &&
466		    !(ia->ia_ifp->if_flags & IFF_UP))
467			NEXTSRC(8);
468		if (!(ia_best->ia_ifp->if_flags & IFF_UP) &&
469		    (ia->ia_ifp->if_flags & IFF_UP))
470			REPLACE(8);
471
472		/*
473		 * Rule 14: Use longest matching prefix.
474		 * Note: in the address selection draft, this rule is
475		 * documented as "Rule 8".  However, since it is also
476		 * documented that this rule can be overridden, we assign
477		 * a large number so that it is easy to assign smaller numbers
478		 * to more preferred rules.
479		 */
480		new_matchlen = in6_matchlen(&ia->ia_addr.sin6_addr, &dst);
481		if (best_matchlen < new_matchlen)
482			REPLACE(14);
483		if (new_matchlen < best_matchlen)
484			NEXTSRC(14);
485
486		/* Rule 15 is reserved. */
487
488		/*
489		 * Last resort: just keep the current candidate.
490		 * Or, do we need more rules?
491		 */
492		IFA_UNLOCK(&ia->ia_ifa);
493		continue;
494
495replace:
496		best_scope = (new_scope >= 0 ? new_scope :
497		    in6_addrscope(&ia->ia_addr.sin6_addr));
498		best_policy = (new_policy ? new_policy :
499		    in6_addrsel_lookup_policy(&ia->ia_addr));
500		best_matchlen = (new_matchlen >= 0 ? new_matchlen :
501		    in6_matchlen(&ia->ia_addr.sin6_addr, &dst));
502		IFA_ADDREF_LOCKED(&ia->ia_ifa);	/* for ia_best */
503		IFA_UNLOCK(&ia->ia_ifa);
504		if (ia_best != NULL)
505			IFA_REMREF(&ia_best->ia_ifa);
506		ia_best = ia;
507		continue;
508
509next:
510		IFA_UNLOCK(&ia->ia_ifa);
511		continue;
512
513out:
514		IFA_ADDREF_LOCKED(&ia->ia_ifa);	/* for ia_best */
515		IFA_UNLOCK(&ia->ia_ifa);
516		if (ia_best != NULL)
517			IFA_REMREF(&ia_best->ia_ifa);
518		ia_best = ia;
519		break;
520	}
521
522	lck_rw_done(&in6_ifaddr_rwlock);
523
524	if (ia_best != NULL &&
525	    (ip6oa.ip6oa_flags & IP6OAF_NO_CELLULAR) &&
526	    IFNET_IS_CELLULAR(ia_best->ia_ifa.ifa_ifp)) {
527		IFA_REMREF(&ia_best->ia_ifa);
528		ia_best = NULL;
529		*errorp = EHOSTUNREACH;
530	}
531
532	if ((ia = ia_best) == NULL) {
533		if (*errorp == 0)
534			*errorp = EADDRNOTAVAIL;
535		src_storage = NULL;
536		goto done;
537	}
538
539	IFA_LOCK_SPIN(&ia->ia_ifa);
540	*src_storage = satosin6(&ia->ia_addr)->sin6_addr;
541	IFA_UNLOCK(&ia->ia_ifa);
542	IFA_REMREF(&ia->ia_ifa);
543done:
544	if (ifpp != NULL) {
545		/* if ifp is non-NULL, refcnt held in in6_selectif() */
546		*ifpp = ifp;
547	} else if (ifp != NULL) {
548		ifnet_release(ifp);
549	}
550	return (src_storage);
551}
552
553/*
554 * Given a source IPv6 address (and route, if available), determine the best
555 * interface to send the packet from.  Checking for (and updating) the
556 * ROF_SRCIF_SELECTED flag in the pcb-supplied route placeholder is done
557 * without any locks, based on the assumption that in the event this is
558 * called from ip6_output(), the output operation is single-threaded per-pcb,
559 * i.e. for any given pcb there can only be one thread performing output at
560 * the IPv6 layer.
561 *
562 * This routine is analogous to in_selectsrcif() for IPv4.  Regardless of
563 * error, it will return an ifp with a reference held if the caller provides
564 * a non-NULL retifp.  The caller is responsible for checking if the
565 * returned ifp is valid and release its reference at all times.
566 *
567 * clone - meaningful only for bsdi and freebsd
568 */
569static int
570selectroute(struct sockaddr_in6 *srcsock, struct sockaddr_in6 *dstsock,
571    struct ip6_pktopts *opts, struct ip6_moptions *mopts,
572    struct in6_ifaddr **retsrcia, struct route_in6 *ro,
573    struct ifnet **retifp, struct rtentry **retrt, int clone,
574    int norouteok, struct ip6_out_args *ip6oa)
575{
576	int error = 0;
577	struct ifnet *ifp = NULL, *ifp0 = NULL;
578	struct route_in6 *route = NULL;
579	struct sockaddr_in6 *sin6_next;
580	struct in6_pktinfo *pi = NULL;
581	struct in6_addr *dst = &dstsock->sin6_addr;
582	struct ifaddr *ifa = NULL;
583	char s_src[MAX_IPv6_STR_LEN], s_dst[MAX_IPv6_STR_LEN];
584	boolean_t select_srcif, proxied_ifa = FALSE, local_dst = FALSE;
585	unsigned int ifscope = ((ip6oa != NULL) ?
586	    ip6oa->ip6oa_boundif : IFSCOPE_NONE);
587
588#if 0
589	char ip6buf[INET6_ADDRSTRLEN];
590
591	if (dstsock->sin6_addr.s6_addr32[0] == 0 &&
592	    dstsock->sin6_addr.s6_addr32[1] == 0 &&
593	    !IN6_IS_ADDR_LOOPBACK(&dstsock->sin6_addr)) {
594		printf("in6_selectroute: strange destination %s\n",
595		    ip6_sprintf(ip6buf, &dstsock->sin6_addr));
596	} else {
597		printf("in6_selectroute: destination = %s%%%d\n",
598		    ip6_sprintf(ip6buf, &dstsock->sin6_addr),
599		    dstsock->sin6_scope_id); /* for debug */
600	}
601#endif
602
603	if (retifp != NULL)
604		*retifp = NULL;
605
606	if (retrt != NULL)
607		*retrt = NULL;
608
609	if (ip6_select_srcif_debug) {
610		struct in6_addr src;
611		src = (srcsock != NULL) ? srcsock->sin6_addr : in6addr_any;
612		(void) inet_ntop(AF_INET6, &src, s_src, sizeof (s_src));
613		(void) inet_ntop(AF_INET6, dst, s_dst, sizeof (s_dst));
614	}
615
616	/*
617	 * If the destination address is UNSPECIFIED addr, bail out.
618	 */
619	if (IN6_IS_ADDR_UNSPECIFIED(dst)) {
620		error = EHOSTUNREACH;
621		goto done;
622	}
623
624	/*
625	 * Perform source interface selection only if Scoped Routing
626	 * is enabled and a source address that isn't unspecified.
627	 */
628	select_srcif = (ip6_doscopedroute && srcsock != NULL &&
629	    !IN6_IS_ADDR_UNSPECIFIED(&srcsock->sin6_addr));
630
631	/*
632	 * If Scoped Routing is disabled, ignore the given ifscope.
633	 * Otherwise even if source selection won't be performed,
634	 * we still obey IPV6_BOUND_IF.
635	 */
636	if (!ip6_doscopedroute && ifscope != IFSCOPE_NONE)
637		ifscope = IFSCOPE_NONE;
638
639	/* If the caller specified the outgoing interface explicitly, use it */
640	if (opts != NULL && (pi = opts->ip6po_pktinfo) != NULL &&
641	    pi->ipi6_ifindex != 0) {
642		/*
643		 * If IPV6_PKTINFO takes precedence over IPV6_BOUND_IF.
644		 */
645		ifscope = pi->ipi6_ifindex;
646		ifnet_head_lock_shared();
647		/* ifp may be NULL if detached or out of range */
648		ifp = ifp0 =
649		    ((ifscope <= if_index) ? ifindex2ifnet[ifscope] : NULL);
650		ifnet_head_done();
651		if (norouteok || retrt == NULL || IN6_IS_ADDR_MULTICAST(dst)) {
652			/*
653			 * We do not have to check or get the route for
654			 * multicast.  If the caller didn't ask/care for
655			 * the route and we have no interface to use,
656			 * it's an error.
657			 */
658			if (ifp == NULL)
659				error = EHOSTUNREACH;
660			goto done;
661		} else {
662			goto getsrcif;
663		}
664	}
665
666	/*
667	 * If the destination address is a multicast address and the outgoing
668	 * interface for the address is specified by the caller, use it.
669	 */
670	if (IN6_IS_ADDR_MULTICAST(dst) && mopts != NULL) {
671		IM6O_LOCK(mopts);
672		if ((ifp = ifp0 = mopts->im6o_multicast_ifp) != NULL) {
673			IM6O_UNLOCK(mopts);
674			goto done; /* we do not need a route for multicast. */
675		}
676		IM6O_UNLOCK(mopts);
677	}
678
679getsrcif:
680	/*
681	 * If the outgoing interface was not set via IPV6_BOUND_IF or
682	 * IPV6_PKTINFO, use the scope ID in the destination address.
683	 */
684	if (ip6_doscopedroute && ifscope == IFSCOPE_NONE)
685		ifscope = dstsock->sin6_scope_id;
686
687	/*
688	 * Perform source interface selection; the source IPv6 address
689	 * must belong to one of the addresses of the interface used
690	 * by the route.  For performance reasons, do this only if
691	 * there is no route, or if the routing table has changed,
692	 * or if we haven't done source interface selection on this
693	 * route (for this PCB instance) before.
694	 */
695	if (!select_srcif) {
696		goto getroute;
697	} else if (!ROUTE_UNUSABLE(ro) && ro->ro_srcia != NULL &&
698	    (ro->ro_flags & ROF_SRCIF_SELECTED)) {
699		if (ro->ro_rt->rt_ifp->if_flags & IFF_LOOPBACK)
700			local_dst = TRUE;
701		ifa = ro->ro_srcia;
702		IFA_ADDREF(ifa);	/* for caller */
703		goto getroute;
704	}
705
706	/*
707	 * Given the source IPv6 address, find a suitable source interface
708	 * to use for transmission; if a scope ID has been specified,
709	 * optimize the search by looking at the addresses only for that
710	 * interface.  This is still suboptimal, however, as we need to
711	 * traverse the per-interface list.
712	 */
713	if (ifscope != IFSCOPE_NONE || (ro != NULL && ro->ro_rt != NULL)) {
714		unsigned int scope = ifscope;
715		struct ifnet *rt_ifp;
716
717		rt_ifp = (ro->ro_rt != NULL) ? ro->ro_rt->rt_ifp : NULL;
718
719		/*
720		 * If no scope is specified and the route is stale (pointing
721		 * to a defunct interface) use the current primary interface;
722		 * this happens when switching between interfaces configured
723		 * with the same IPv6 address.  Otherwise pick up the scope
724		 * information from the route; the ULP may have looked up a
725		 * correct route and we just need to verify it here and mark
726		 * it with the ROF_SRCIF_SELECTED flag below.
727		 */
728		if (scope == IFSCOPE_NONE) {
729			scope = rt_ifp->if_index;
730			if (scope != get_primary_ifscope(AF_INET6) &&
731			    ROUTE_UNUSABLE(ro))
732				scope = get_primary_ifscope(AF_INET6);
733		}
734
735		ifa = (struct ifaddr *)
736		    ifa_foraddr6_scoped(&srcsock->sin6_addr, scope);
737
738		/*
739		 * If we are forwarding and proxying prefix(es), see if the
740		 * source address is one of ours and is a proxied address;
741		 * if so, use it.
742		 */
743		if (ifa == NULL && ip6_forwarding && nd6_prproxy) {
744			ifa = (struct ifaddr *)
745			    ifa_foraddr6(&srcsock->sin6_addr);
746			if (ifa != NULL && !(proxied_ifa =
747			    nd6_prproxy_ifaddr((struct in6_ifaddr *)ifa))) {
748				IFA_REMREF(ifa);
749				ifa = NULL;
750			}
751		}
752
753		if (ip6_select_srcif_debug && ifa != NULL) {
754			if (ro->ro_rt != NULL) {
755				printf("%s->%s ifscope %d->%d ifa_if %s "
756				    "ro_if %s\n", s_src, s_dst, ifscope,
757				    scope, if_name(ifa->ifa_ifp),
758				    if_name(rt_ifp));
759			} else {
760				printf("%s->%s ifscope %d->%d ifa_if %s\n",
761				    s_src, s_dst, ifscope, scope,
762				    if_name(ifa->ifa_ifp));
763			}
764		}
765	}
766
767	/*
768	 * Slow path; search for an interface having the corresponding source
769	 * IPv6 address if the scope was not specified by the caller, and:
770	 *
771	 *   1) There currently isn't any route, or,
772	 *   2) The interface used by the route does not own that source
773	 *	IPv6 address; in this case, the route will get blown away
774	 *	and we'll do a more specific scoped search using the newly
775	 *	found interface.
776	 */
777	if (ifa == NULL && ifscope == IFSCOPE_NONE) {
778		struct ifaddr *ifadst;
779
780		/* Check if the destination address is one of ours */
781		ifadst = (struct ifaddr *)ifa_foraddr6(&dstsock->sin6_addr);
782		if (ifadst != NULL) {
783			local_dst = TRUE;
784			IFA_REMREF(ifadst);
785		}
786
787		ifa = (struct ifaddr *)ifa_foraddr6(&srcsock->sin6_addr);
788
789		if (ip6_select_srcif_debug && ifa != NULL) {
790			printf("%s->%s ifscope %d ifa_if %s\n",
791			    s_src, s_dst, ifscope, if_name(ifa->ifa_ifp));
792		}
793
794	}
795
796getroute:
797	if (ifa != NULL && !proxied_ifa && !local_dst)
798		ifscope = ifa->ifa_ifp->if_index;
799
800	/*
801	 * If the next hop address for the packet is specified by the caller,
802	 * use it as the gateway.
803	 */
804	if (opts != NULL && opts->ip6po_nexthop != NULL) {
805		struct route_in6 *ron;
806
807		sin6_next = satosin6(opts->ip6po_nexthop);
808
809		/* at this moment, we only support AF_INET6 next hops */
810		if (sin6_next->sin6_family != AF_INET6) {
811			error = EAFNOSUPPORT; /* or should we proceed? */
812			goto done;
813		}
814
815		/*
816		 * If the next hop is an IPv6 address, then the node identified
817		 * by that address must be a neighbor of the sending host.
818		 */
819		ron = &opts->ip6po_nextroute;
820		if (ron->ro_rt != NULL)
821			RT_LOCK(ron->ro_rt);
822		if (ROUTE_UNUSABLE(ron) || (ron->ro_rt != NULL &&
823		    (!(ron->ro_rt->rt_flags & RTF_LLINFO) ||
824		    (select_srcif && (ifa == NULL ||
825		    (ifa->ifa_ifp != ron->ro_rt->rt_ifp && !proxied_ifa))))) ||
826		    !IN6_ARE_ADDR_EQUAL(&satosin6(&ron->ro_dst)->sin6_addr,
827		    &sin6_next->sin6_addr)) {
828			if (ron->ro_rt != NULL)
829				RT_UNLOCK(ron->ro_rt);
830
831			ROUTE_RELEASE(ron);
832			*satosin6(&ron->ro_dst) = *sin6_next;
833		}
834		if (ron->ro_rt == NULL) {
835			rtalloc_scoped((struct route *)ron, ifscope);
836			if (ron->ro_rt != NULL)
837				RT_LOCK(ron->ro_rt);
838			if (ROUTE_UNUSABLE(ron) ||
839			    !(ron->ro_rt->rt_flags & RTF_LLINFO) ||
840			    !IN6_ARE_ADDR_EQUAL(&satosin6(rt_key(ron->ro_rt))->
841			    sin6_addr, &sin6_next->sin6_addr)) {
842				if (ron->ro_rt != NULL)
843					RT_UNLOCK(ron->ro_rt);
844
845				ROUTE_RELEASE(ron);
846				error = EHOSTUNREACH;
847				goto done;
848			}
849		}
850		route = ron;
851		ifp = ifp0 = ron->ro_rt->rt_ifp;
852
853		/*
854		 * When cloning is required, try to allocate a route to the
855		 * destination so that the caller can store path MTU
856		 * information.
857		 */
858		if (!clone) {
859			if (select_srcif) {
860				/* Keep the route locked */
861				goto validateroute;
862			}
863			RT_UNLOCK(ron->ro_rt);
864			goto done;
865		}
866		RT_UNLOCK(ron->ro_rt);
867	}
868
869	/*
870	 * Use a cached route if it exists and is valid, else try to allocate
871	 * a new one.  Note that we should check the address family of the
872	 * cached destination, in case of sharing the cache with IPv4.
873	 */
874	if (ro == NULL)
875		goto done;
876	if (ro->ro_rt != NULL)
877		RT_LOCK_SPIN(ro->ro_rt);
878	if (ROUTE_UNUSABLE(ro) || (ro->ro_rt != NULL &&
879	    (satosin6(&ro->ro_dst)->sin6_family != AF_INET6 ||
880	    !IN6_ARE_ADDR_EQUAL(&satosin6(&ro->ro_dst)->sin6_addr, dst) ||
881	    (select_srcif && (ifa == NULL ||
882	    (ifa->ifa_ifp != ro->ro_rt->rt_ifp && !proxied_ifa)))))) {
883		if (ro->ro_rt != NULL)
884			RT_UNLOCK(ro->ro_rt);
885
886		ROUTE_RELEASE(ro);
887	}
888	if (ro->ro_rt == NULL) {
889		struct sockaddr_in6 *sa6;
890
891		if (ro->ro_rt != NULL)
892			RT_UNLOCK(ro->ro_rt);
893		/* No route yet, so try to acquire one */
894		bzero(&ro->ro_dst, sizeof (struct sockaddr_in6));
895		sa6 = (struct sockaddr_in6 *)&ro->ro_dst;
896		sa6->sin6_family = AF_INET6;
897		sa6->sin6_len = sizeof (struct sockaddr_in6);
898		sa6->sin6_addr = *dst;
899		if (IN6_IS_ADDR_MULTICAST(dst)) {
900			ro->ro_rt = rtalloc1_scoped(
901			    &((struct route *)ro)->ro_dst, 0, 0, ifscope);
902		} else {
903			rtalloc_scoped((struct route *)ro, ifscope);
904		}
905		if (ro->ro_rt != NULL)
906			RT_LOCK_SPIN(ro->ro_rt);
907	}
908
909	/*
910	 * Do not care about the result if we have the nexthop
911	 * explicitly specified (in case we're asked to clone.)
912	 */
913	if (opts != NULL && opts->ip6po_nexthop != NULL) {
914		if (ro->ro_rt != NULL)
915			RT_UNLOCK(ro->ro_rt);
916		goto done;
917	}
918
919	if (ro->ro_rt != NULL) {
920		RT_LOCK_ASSERT_HELD(ro->ro_rt);
921		ifp = ifp0 = ro->ro_rt->rt_ifp;
922	} else {
923		error = EHOSTUNREACH;
924	}
925	route = ro;
926
927validateroute:
928	if (select_srcif) {
929		boolean_t has_route = (route != NULL && route->ro_rt != NULL);
930		boolean_t srcif_selected = FALSE;
931
932		if (has_route)
933			RT_LOCK_ASSERT_HELD(route->ro_rt);
934		/*
935		 * If there is a non-loopback route with the wrong interface,
936		 * or if there is no interface configured with such an address,
937		 * blow it away.  Except for local/loopback, we look for one
938		 * with a matching interface scope/index.
939		 */
940		if (has_route && (ifa == NULL ||
941		    (ifa->ifa_ifp != ifp && ifp != lo_ifp) ||
942		    !(route->ro_rt->rt_flags & RTF_UP))) {
943			/*
944			 * If the destination address belongs to a proxied
945			 * prefix, relax the requirement and allow the packet
946			 * to come out of the proxy interface with the source
947			 * address of the real interface.
948			 */
949			if (ifa != NULL && proxied_ifa &&
950			    (route->ro_rt->rt_flags & (RTF_UP|RTF_PROXY)) ==
951			    (RTF_UP|RTF_PROXY)) {
952				srcif_selected = TRUE;
953			} else {
954				if (ip6_select_srcif_debug) {
955					if (ifa != NULL) {
956						printf("%s->%s ifscope %d "
957						    "ro_if %s != ifa_if %s "
958						    "(cached route cleared)\n",
959						    s_src, s_dst,
960						    ifscope, if_name(ifp),
961						    if_name(ifa->ifa_ifp));
962					} else {
963						printf("%s->%s ifscope %d "
964						    "ro_if %s (no ifa_if "
965						    "found)\n", s_src, s_dst,
966						    ifscope, if_name(ifp));
967					}
968				}
969				RT_UNLOCK(route->ro_rt);
970				ROUTE_RELEASE(route);
971				error = EHOSTUNREACH;
972				/* Undo the settings done above */
973				route = NULL;
974				ifp = NULL;	/* ditch ifp; keep ifp0 */
975				has_route = FALSE;
976			}
977		} else if (has_route) {
978			srcif_selected = TRUE;
979		}
980
981		if (srcif_selected) {
982			VERIFY(has_route);
983			if (ifa != route->ro_srcia ||
984			    !(route->ro_flags & ROF_SRCIF_SELECTED)) {
985				RT_CONVERT_LOCK(route->ro_rt);
986				if (ifa != NULL)
987					IFA_ADDREF(ifa); /* for route_in6 */
988				if (route->ro_srcia != NULL)
989					IFA_REMREF(route->ro_srcia);
990				route->ro_srcia = ifa;
991				route->ro_flags |= ROF_SRCIF_SELECTED;
992				RT_GENID_SYNC(route->ro_rt);
993			}
994			RT_UNLOCK(route->ro_rt);
995		}
996	} else {
997		if (ro->ro_rt != NULL)
998			RT_UNLOCK(ro->ro_rt);
999		if (ifp != NULL && opts != NULL &&
1000		    opts->ip6po_pktinfo != NULL &&
1001		    opts->ip6po_pktinfo->ipi6_ifindex != 0) {
1002			/*
1003			 * Check if the outgoing interface conflicts with the
1004			 * interface specified by ipi6_ifindex (if specified).
1005			 * Note that loopback interface is always okay.
1006			 * (this may happen when we are sending a packet to
1007			 * one of our own addresses.)
1008			 */
1009			if (!(ifp->if_flags & IFF_LOOPBACK) && ifp->if_index !=
1010			    opts->ip6po_pktinfo->ipi6_ifindex) {
1011				error = EHOSTUNREACH;
1012				goto done;
1013			}
1014		}
1015	}
1016
1017done:
1018	if (error == 0) {
1019		if (ip6oa != NULL &&
1020		    (ip6oa->ip6oa_flags & IP6OAF_NO_CELLULAR) &&
1021		    ((ifp != NULL && IFNET_IS_CELLULAR(ifp)) ||
1022		    (route != NULL && route->ro_rt != NULL &&
1023		    IFNET_IS_CELLULAR(route->ro_rt->rt_ifp)))) {
1024			if (route != NULL && route->ro_rt != NULL) {
1025				ROUTE_RELEASE(route);
1026				route = NULL;
1027			}
1028			ifp = NULL;	/* ditch ifp; keep ifp0 */
1029			error = EHOSTUNREACH;
1030			ip6oa->ip6oa_retflags |= IP6OARF_IFDENIED;
1031		}
1032	}
1033
1034	/*
1035	 * If the interface is disabled for IPv6, then ENETDOWN error.
1036	 */
1037	if (error == 0 &&
1038	    ifp != NULL && (ifp->if_eflags & IFEF_IPV6_DISABLED)) {
1039		error = ENETDOWN;
1040	}
1041
1042	if (ifp == NULL && (route == NULL || route->ro_rt == NULL)) {
1043		/*
1044		 * This can happen if the caller did not pass a cached route
1045		 * nor any other hints.  We treat this case an error.
1046		 */
1047		error = EHOSTUNREACH;
1048	}
1049	if (error == EHOSTUNREACH || error == ENETDOWN)
1050		ip6stat.ip6s_noroute++;
1051
1052	/*
1053	 * We'll return ifp regardless of error, so pick it up from ifp0
1054	 * in case it was nullified above.  Caller is responsible for
1055	 * releasing the ifp if it is non-NULL.
1056	 */
1057	ifp = ifp0;
1058	if (retifp != NULL) {
1059		if (ifp != NULL)
1060			ifnet_reference(ifp);	/* for caller */
1061		*retifp = ifp;
1062	}
1063
1064	if (retsrcia != NULL) {
1065		if (ifa != NULL)
1066			IFA_ADDREF(ifa);	/* for caller */
1067		*retsrcia = (struct in6_ifaddr *)ifa;
1068	}
1069
1070	if (error == 0) {
1071		if (retrt != NULL && route != NULL)
1072			*retrt = route->ro_rt;	/* ro_rt may be NULL */
1073	} else if (select_srcif && ip6_select_srcif_debug) {
1074		printf("%s->%s ifscope %d ifa_if %s ro_if %s (error=%d)\n",
1075		    s_src, s_dst, ifscope,
1076		    (ifa != NULL) ? if_name(ifa->ifa_ifp) : "NONE",
1077		    (ifp != NULL) ? if_name(ifp) : "NONE", error);
1078	}
1079
1080	if (ifa != NULL)
1081		IFA_REMREF(ifa);
1082
1083	return (error);
1084}
1085
1086/*
1087 * Regardless of error, it will return an ifp with a reference held if the
1088 * caller provides a non-NULL retifp.  The caller is responsible for checking
1089 * if the returned ifp is valid and release its reference at all times.
1090 */
1091static int
1092in6_selectif(struct sockaddr_in6 *dstsock, struct ip6_pktopts *opts,
1093    struct ip6_moptions *mopts, struct route_in6 *ro,
1094    struct ip6_out_args *ip6oa, struct ifnet **retifp)
1095{
1096	int err = 0;
1097	struct route_in6 sro;
1098	struct rtentry *rt = NULL;
1099
1100	if (ro == NULL) {
1101		bzero(&sro, sizeof (sro));
1102		ro = &sro;
1103	}
1104
1105	if ((err = selectroute(NULL, dstsock, opts, mopts, NULL, ro, retifp,
1106	    &rt, 0, 1, ip6oa)) != 0)
1107		goto done;
1108
1109	/*
1110	 * do not use a rejected or black hole route.
1111	 * XXX: this check should be done in the L2 output routine.
1112	 * However, if we skipped this check here, we'd see the following
1113	 * scenario:
1114	 * - install a rejected route for a scoped address prefix
1115	 *   (like fe80::/10)
1116	 * - send a packet to a destination that matches the scoped prefix,
1117	 *   with ambiguity about the scope zone.
1118	 * - pick the outgoing interface from the route, and disambiguate the
1119	 *   scope zone with the interface.
1120	 * - ip6_output() would try to get another route with the "new"
1121	 *   destination, which may be valid.
1122	 * - we'd see no error on output.
1123	 * Although this may not be very harmful, it should still be confusing.
1124	 * We thus reject the case here.
1125	 */
1126	if (rt && (rt->rt_flags & (RTF_REJECT | RTF_BLACKHOLE))) {
1127		err = ((rt->rt_flags & RTF_HOST) ? EHOSTUNREACH : ENETUNREACH);
1128		goto done;
1129	}
1130
1131	/*
1132	 * Adjust the "outgoing" interface.  If we're going to loop the packet
1133	 * back to ourselves, the ifp would be the loopback interface.
1134	 * However, we'd rather know the interface associated to the
1135	 * destination address (which should probably be one of our own
1136	 * addresses.)
1137	 */
1138	if (rt != NULL && rt->rt_ifa != NULL && rt->rt_ifa->ifa_ifp != NULL &&
1139	    retifp != NULL) {
1140		ifnet_reference(rt->rt_ifa->ifa_ifp);
1141		if (*retifp != NULL)
1142			ifnet_release(*retifp);
1143		*retifp = rt->rt_ifa->ifa_ifp;
1144	}
1145
1146done:
1147	if (ro == &sro) {
1148		VERIFY(rt == NULL || rt == ro->ro_rt);
1149		ROUTE_RELEASE(ro);
1150	}
1151
1152	/*
1153	 * retifp might point to a valid ifp with a reference held;
1154	 * caller is responsible for releasing it if non-NULL.
1155	 */
1156	return (err);
1157}
1158
1159/*
1160 * Regardless of error, it will return an ifp with a reference held if the
1161 * caller provides a non-NULL retifp.  The caller is responsible for checking
1162 * if the returned ifp is valid and release its reference at all times.
1163 *
1164 * clone - meaningful only for bsdi and freebsd
1165 */
1166int
1167in6_selectroute(struct sockaddr_in6 *srcsock, struct sockaddr_in6 *dstsock,
1168    struct ip6_pktopts *opts, struct ip6_moptions *mopts,
1169    struct in6_ifaddr **retsrcia, struct route_in6 *ro, struct ifnet **retifp,
1170    struct rtentry **retrt, int clone, struct ip6_out_args *ip6oa)
1171{
1172
1173	return (selectroute(srcsock, dstsock, opts, mopts, retsrcia, ro, retifp,
1174	    retrt, clone, 0, ip6oa));
1175}
1176
1177/*
1178 * Default hop limit selection. The precedence is as follows:
1179 * 1. Hoplimit value specified via ioctl.
1180 * 2. (If the outgoing interface is detected) the current
1181 *     hop limit of the interface specified by router advertisement.
1182 * 3. The system default hoplimit.
1183 */
1184int
1185in6_selecthlim(struct in6pcb *in6p, struct ifnet *ifp)
1186{
1187	if (in6p && in6p->in6p_hops >= 0) {
1188		return (in6p->in6p_hops);
1189	} else {
1190		lck_rw_lock_shared(nd_if_rwlock);
1191		if (ifp && ifp->if_index < nd_ifinfo_indexlim) {
1192			u_int8_t chlim;
1193			struct nd_ifinfo *ndi = &nd_ifinfo[ifp->if_index];
1194
1195			if (ndi->initialized) {
1196				/* access chlim without lock, for performance */
1197				chlim = ndi->chlim;
1198			} else {
1199				chlim = ip6_defhlim;
1200			}
1201			lck_rw_done(nd_if_rwlock);
1202			return (chlim);
1203		} else {
1204			lck_rw_done(nd_if_rwlock);
1205			return (ip6_defhlim);
1206		}
1207	}
1208}
1209
1210/*
1211 * XXX: this is borrowed from in6_pcbbind(). If possible, we should
1212 * share this function by all *bsd*...
1213 */
1214int
1215in6_pcbsetport(struct in6_addr *laddr, struct inpcb *inp, struct proc *p,
1216    int locked)
1217{
1218#pragma unused(laddr)
1219	struct socket *so = inp->inp_socket;
1220	u_int16_t lport = 0, first, last, *lastport;
1221	int count, error = 0, wild = 0;
1222	struct inpcbinfo *pcbinfo = inp->inp_pcbinfo;
1223	kauth_cred_t cred;
1224	if (!locked) { /* Make sure we don't run into a deadlock: 4052373 */
1225		if (!lck_rw_try_lock_exclusive(pcbinfo->ipi_lock)) {
1226			socket_unlock(inp->inp_socket, 0);
1227			lck_rw_lock_exclusive(pcbinfo->ipi_lock);
1228			socket_lock(inp->inp_socket, 0);
1229		}
1230	}
1231
1232	/* XXX: this is redundant when called from in6_pcbbind */
1233	if ((so->so_options & (SO_REUSEADDR|SO_REUSEPORT)) == 0)
1234		wild = INPLOOKUP_WILDCARD;
1235
1236	inp->inp_flags |= INP_ANONPORT;
1237
1238	if (inp->inp_flags & INP_HIGHPORT) {
1239		first = ipport_hifirstauto;	/* sysctl */
1240		last  = ipport_hilastauto;
1241		lastport = &pcbinfo->ipi_lasthi;
1242	} else if (inp->inp_flags & INP_LOWPORT) {
1243		cred = kauth_cred_proc_ref(p);
1244		error = priv_check_cred(cred, PRIV_NETINET_RESERVEDPORT, 0);
1245		kauth_cred_unref(&cred);
1246		if (error != 0) {
1247			if (!locked)
1248				lck_rw_done(pcbinfo->ipi_lock);
1249			return (error);
1250		}
1251		first = ipport_lowfirstauto;	/* 1023 */
1252		last  = ipport_lowlastauto;	/* 600 */
1253		lastport = &pcbinfo->ipi_lastlow;
1254	} else {
1255		first = ipport_firstauto;	/* sysctl */
1256		last  = ipport_lastauto;
1257		lastport = &pcbinfo->ipi_lastport;
1258	}
1259	/*
1260	 * Simple check to ensure all ports are not used up causing
1261	 * a deadlock here.
1262	 *
1263	 * We split the two cases (up and down) so that the direction
1264	 * is not being tested on each round of the loop.
1265	 */
1266	if (first > last) {
1267		/*
1268		 * counting down
1269		 */
1270		count = first - last;
1271
1272		do {
1273			if (count-- < 0) {	/* completely used? */
1274				/*
1275				 * Undo any address bind that may have
1276				 * occurred above.
1277				 */
1278				inp->in6p_laddr = in6addr_any;
1279				inp->in6p_last_outifp = NULL;
1280				if (!locked)
1281					lck_rw_done(pcbinfo->ipi_lock);
1282				return (EAGAIN);
1283			}
1284			--*lastport;
1285			if (*lastport > first || *lastport < last)
1286				*lastport = first;
1287			lport = htons(*lastport);
1288		} while (in6_pcblookup_local(pcbinfo, &inp->in6p_laddr, lport,
1289		    wild));
1290	} else {
1291		/* counting up */
1292		count = last - first;
1293
1294		do {
1295			if (count-- < 0) {	/* completely used? */
1296				/*
1297				 * Undo any address bind that may have
1298				 * occurred above.
1299				 */
1300				inp->in6p_laddr = in6addr_any;
1301				inp->in6p_last_outifp = NULL;
1302				if (!locked)
1303					lck_rw_done(pcbinfo->ipi_lock);
1304				return (EAGAIN);
1305			}
1306			++*lastport;
1307			if (*lastport < first || *lastport > last)
1308				*lastport = first;
1309			lport = htons(*lastport);
1310		} while (in6_pcblookup_local(pcbinfo, &inp->in6p_laddr, lport,
1311		    wild));
1312	}
1313
1314	inp->inp_lport = lport;
1315	if (in_pcbinshash(inp, 1) != 0) {
1316		inp->in6p_laddr = in6addr_any;
1317		inp->inp_lport = 0;
1318		inp->in6p_last_outifp = NULL;
1319		if (!locked)
1320			lck_rw_done(pcbinfo->ipi_lock);
1321		return (EAGAIN);
1322	}
1323
1324	if (!locked)
1325		lck_rw_done(pcbinfo->ipi_lock);
1326	return (0);
1327}
1328
1329/*
1330 * The followings are implementation of the policy table using a
1331 * simple tail queue.
1332 * XXX such details should be hidden.
1333 * XXX implementation using binary tree should be more efficient.
1334 */
1335struct addrsel_policyent {
1336	TAILQ_ENTRY(addrsel_policyent) ape_entry;
1337	struct in6_addrpolicy ape_policy;
1338};
1339
1340TAILQ_HEAD(addrsel_policyhead, addrsel_policyent);
1341
1342struct addrsel_policyhead addrsel_policytab;
1343
1344static void
1345init_policy_queue(void)
1346{
1347	TAILQ_INIT(&addrsel_policytab);
1348}
1349
1350void
1351addrsel_policy_init(void)
1352{
1353	/*
1354	 * Default address selection policy based on RFC 3484 and
1355	 * draft-arifumi-6man-rfc3484-revise-03.
1356	 */
1357	static const struct in6_addrpolicy defaddrsel[] = {
1358		/* localhost */
1359		{
1360			.addr = {
1361				.sin6_family = AF_INET6,
1362				.sin6_addr   = IN6ADDR_LOOPBACK_INIT,
1363				.sin6_len    = sizeof (struct sockaddr_in6)
1364			},
1365			.addrmask = {
1366				.sin6_family = AF_INET6,
1367				.sin6_addr   = IN6MASK128,
1368				.sin6_len    = sizeof (struct sockaddr_in6)
1369			},
1370			.preced   = 60,
1371			.label    = 0
1372		},
1373
1374		/* ULA */
1375		{
1376			.addr = {
1377				.sin6_family = AF_INET6,
1378				.sin6_addr   = {{{ 0xfc }}},
1379				.sin6_len    = sizeof (struct sockaddr_in6)
1380			},
1381			.addrmask = {
1382				.sin6_family = AF_INET6,
1383				.sin6_addr   = IN6MASK7,
1384				.sin6_len    = sizeof (struct sockaddr_in6)
1385			},
1386			.preced   = 50,
1387			.label    = 1
1388		},
1389
1390		/* any IPv6 src */
1391		{
1392			.addr = {
1393				.sin6_family = AF_INET6,
1394				.sin6_addr   = IN6ADDR_ANY_INIT,
1395				.sin6_len    = sizeof (struct sockaddr_in6)
1396			},
1397			.addrmask = {
1398				.sin6_family = AF_INET6,
1399				.sin6_addr   = IN6MASK0,
1400				.sin6_len    = sizeof (struct sockaddr_in6)
1401			},
1402			.preced   = 40,
1403			.label    = 2 },
1404
1405		/* any IPv4 src */
1406		{
1407			.addr = {
1408				.sin6_family = AF_INET6,
1409				.sin6_addr   = IN6ADDR_V4MAPPED_INIT,
1410				.sin6_len    = sizeof (struct sockaddr_in6)
1411			},
1412			.addrmask = {
1413				.sin6_family = AF_INET6,
1414				.sin6_addr   = IN6MASK96,
1415				.sin6_len    = sizeof (struct sockaddr_in6)
1416			},
1417			.preced   = 30,
1418			.label    = 3
1419		},
1420
1421		/* 6to4 */
1422		{
1423			.addr = {
1424				.sin6_family = AF_INET6,
1425				.sin6_addr   = {{{ 0x20, 0x02 }}},
1426				.sin6_len    = sizeof (struct sockaddr_in6)
1427			},
1428			.addrmask = {
1429				.sin6_family = AF_INET6,
1430				.sin6_addr   = IN6MASK16,
1431				.sin6_len    = sizeof (struct sockaddr_in6)
1432			},
1433			.preced   = 20,
1434			.label    = 4
1435		},
1436
1437		/* Teredo */
1438		{
1439			.addr = {
1440				.sin6_family = AF_INET6,
1441				.sin6_addr   = {{{ 0x20, 0x01 }}},
1442				.sin6_len    = sizeof (struct sockaddr_in6)
1443			},
1444			.addrmask = {
1445				.sin6_family = AF_INET6,
1446				.sin6_addr   = IN6MASK32,
1447				.sin6_len    = sizeof (struct sockaddr_in6)
1448			},
1449			.preced   = 10,
1450			.label    = 5
1451		},
1452
1453		/* v4 compat addresses */
1454		{
1455			.addr = {
1456				.sin6_family = AF_INET6,
1457				.sin6_addr = IN6ADDR_ANY_INIT,
1458				.sin6_len    = sizeof (struct sockaddr_in6)
1459			},
1460			.addrmask = {
1461				.sin6_family = AF_INET6,
1462				.sin6_addr = IN6MASK96,
1463				.sin6_len    = sizeof (struct sockaddr_in6)
1464			},
1465			.preced   = 1,
1466			.label    = 10
1467		},
1468
1469		/* site-local (deprecated) */
1470		{
1471			.addr = {
1472				.sin6_family = AF_INET6,
1473				.sin6_addr = {{{ 0xfe, 0xc0 }}},
1474				.sin6_len    = sizeof (struct sockaddr_in6)
1475			},
1476			.addrmask = {
1477				.sin6_family = AF_INET6,
1478				.sin6_addr = IN6MASK16,
1479				.sin6_len    = sizeof (struct sockaddr_in6)
1480			},
1481			.preced   = 1,
1482			.label    = 11
1483		},
1484
1485		/* 6bone (deprecated) */
1486		{
1487			.addr = {
1488				.sin6_family = AF_INET6,
1489				.sin6_addr = {{{ 0x3f, 0xfe }}},
1490				.sin6_len    = sizeof (struct sockaddr_in6)
1491			},
1492			.addrmask = {
1493				.sin6_family = AF_INET6,
1494				.sin6_addr = IN6MASK16,
1495				.sin6_len    = sizeof (struct sockaddr_in6)
1496			},
1497			.preced   = 1,
1498			.label    = 12
1499		},
1500	};
1501	int i;
1502
1503	init_policy_queue();
1504
1505	/* initialize the "last resort" policy */
1506	bzero(&defaultaddrpolicy, sizeof (defaultaddrpolicy));
1507	defaultaddrpolicy.label = ADDR_LABEL_NOTAPP;
1508
1509	for (i = 0; i < sizeof (defaddrsel) / sizeof (defaddrsel[0]); i++)
1510		add_addrsel_policyent(&defaddrsel[i]);
1511
1512}
1513
1514struct in6_addrpolicy *
1515in6_addrsel_lookup_policy(struct sockaddr_in6 *key)
1516{
1517	struct in6_addrpolicy *match = NULL;
1518
1519	ADDRSEL_LOCK();
1520	match = match_addrsel_policy(key);
1521
1522	if (match == NULL)
1523		match = &defaultaddrpolicy;
1524	else
1525		match->use++;
1526	ADDRSEL_UNLOCK();
1527
1528	return (match);
1529}
1530
1531static struct in6_addrpolicy *
1532match_addrsel_policy(struct sockaddr_in6 *key)
1533{
1534	struct addrsel_policyent *pent;
1535	struct in6_addrpolicy *bestpol = NULL, *pol;
1536	int matchlen, bestmatchlen = -1;
1537	u_char *mp, *ep, *k, *p, m;
1538
1539	TAILQ_FOREACH(pent, &addrsel_policytab, ape_entry) {
1540		matchlen = 0;
1541
1542		pol = &pent->ape_policy;
1543		mp = (u_char *)&pol->addrmask.sin6_addr;
1544		ep = mp + 16;	/* XXX: scope field? */
1545		k = (u_char *)&key->sin6_addr;
1546		p = (u_char *)&pol->addr.sin6_addr;
1547		for (; mp < ep && *mp; mp++, k++, p++) {
1548			m = *mp;
1549			if ((*k & m) != *p)
1550				goto next; /* not match */
1551			if (m == 0xff) /* short cut for a typical case */
1552				matchlen += 8;
1553			else {
1554				while (m >= 0x80) {
1555					matchlen++;
1556					m <<= 1;
1557				}
1558			}
1559		}
1560
1561		/* matched.  check if this is better than the current best. */
1562		if (bestpol == NULL ||
1563		    matchlen > bestmatchlen) {
1564			bestpol = pol;
1565			bestmatchlen = matchlen;
1566		}
1567
1568	next:
1569		continue;
1570	}
1571
1572	return (bestpol);
1573}
1574
1575static int
1576add_addrsel_policyent(const struct in6_addrpolicy *newpolicy)
1577{
1578	struct addrsel_policyent *new, *pol;
1579
1580	MALLOC(new, struct addrsel_policyent *, sizeof (*new), M_IFADDR,
1581	    M_WAITOK);
1582
1583	ADDRSEL_LOCK();
1584
1585	/* duplication check */
1586	TAILQ_FOREACH(pol, &addrsel_policytab, ape_entry) {
1587		if (IN6_ARE_ADDR_EQUAL(&newpolicy->addr.sin6_addr,
1588		    &pol->ape_policy.addr.sin6_addr) &&
1589		    IN6_ARE_ADDR_EQUAL(&newpolicy->addrmask.sin6_addr,
1590		    &pol->ape_policy.addrmask.sin6_addr)) {
1591			ADDRSEL_UNLOCK();
1592			FREE(new, M_IFADDR);
1593			return (EEXIST);	/* or override it? */
1594		}
1595	}
1596
1597	bzero(new, sizeof (*new));
1598
1599	/* XXX: should validate entry */
1600	new->ape_policy = *newpolicy;
1601
1602	TAILQ_INSERT_TAIL(&addrsel_policytab, new, ape_entry);
1603	ADDRSEL_UNLOCK();
1604
1605	return (0);
1606}
1607#ifdef ENABLE_ADDRSEL
1608static int
1609delete_addrsel_policyent(const struct in6_addrpolicy *key)
1610{
1611	struct addrsel_policyent *pol;
1612
1613
1614	ADDRSEL_LOCK();
1615
1616	/* search for the entry in the table */
1617	TAILQ_FOREACH(pol, &addrsel_policytab, ape_entry) {
1618		if (IN6_ARE_ADDR_EQUAL(&key->addr.sin6_addr,
1619		    &pol->ape_policy.addr.sin6_addr) &&
1620		    IN6_ARE_ADDR_EQUAL(&key->addrmask.sin6_addr,
1621		    &pol->ape_policy.addrmask.sin6_addr)) {
1622			break;
1623		}
1624	}
1625	if (pol == NULL) {
1626		ADDRSEL_UNLOCK();
1627		return (ESRCH);
1628	}
1629
1630	TAILQ_REMOVE(&addrsel_policytab, pol, ape_entry);
1631	FREE(pol, M_IFADDR);
1632	pol = NULL;
1633	ADDRSEL_UNLOCK();
1634
1635	return (0);
1636}
1637#endif /* ENABLE_ADDRSEL */
1638
1639int
1640walk_addrsel_policy(int (*callback)(const struct in6_addrpolicy *, void *),
1641    void *w)
1642{
1643	struct addrsel_policyent *pol;
1644	int error = 0;
1645
1646	ADDRSEL_LOCK();
1647	TAILQ_FOREACH(pol, &addrsel_policytab, ape_entry) {
1648		if ((error = (*callback)(&pol->ape_policy, w)) != 0) {
1649			ADDRSEL_UNLOCK();
1650			return (error);
1651		}
1652	}
1653	ADDRSEL_UNLOCK();
1654	return (error);
1655}
1656/*
1657 * Subroutines to manage the address selection policy table via sysctl.
1658 */
1659struct walkarg {
1660	struct sysctl_req *w_req;
1661};
1662
1663
1664static int
1665dump_addrsel_policyent(const struct in6_addrpolicy *pol, void *arg)
1666{
1667	int error = 0;
1668	struct walkarg *w = arg;
1669
1670	error = SYSCTL_OUT(w->w_req, pol, sizeof (*pol));
1671
1672	return (error);
1673}
1674
1675static int
1676in6_src_sysctl SYSCTL_HANDLER_ARGS
1677{
1678#pragma unused(oidp, arg1, arg2)
1679struct walkarg w;
1680
1681	if (req->newptr)
1682		return (EPERM);
1683	bzero(&w, sizeof (w));
1684	w.w_req = req;
1685
1686	return (walk_addrsel_policy(dump_addrsel_policyent, &w));
1687}
1688
1689
1690SYSCTL_NODE(_net_inet6_ip6, IPV6CTL_ADDRCTLPOLICY, addrctlpolicy,
1691	CTLFLAG_RD | CTLFLAG_LOCKED, in6_src_sysctl, "");
1692int
1693in6_src_ioctl(u_long cmd, caddr_t data)
1694{
1695	int i;
1696	struct in6_addrpolicy ent0;
1697
1698	if (cmd != SIOCAADDRCTL_POLICY && cmd != SIOCDADDRCTL_POLICY)
1699		return (EOPNOTSUPP); /* check for safety */
1700
1701	bcopy(data, &ent0, sizeof (ent0));
1702
1703	if (ent0.label == ADDR_LABEL_NOTAPP)
1704		return (EINVAL);
1705	/* check if the prefix mask is consecutive. */
1706	if (in6_mask2len(&ent0.addrmask.sin6_addr, NULL) < 0)
1707		return (EINVAL);
1708	/* clear trailing garbages (if any) of the prefix address. */
1709	for (i = 0; i < 4; i++) {
1710		ent0.addr.sin6_addr.s6_addr32[i] &=
1711			ent0.addrmask.sin6_addr.s6_addr32[i];
1712	}
1713	ent0.use = 0;
1714
1715	switch (cmd) {
1716	case SIOCAADDRCTL_POLICY:
1717#ifdef ENABLE_ADDRSEL
1718		return (add_addrsel_policyent(&ent0));
1719#else
1720		return (ENOTSUP);
1721#endif
1722	case SIOCDADDRCTL_POLICY:
1723#ifdef ENABLE_ADDRSEL
1724		return (delete_addrsel_policyent(&ent0));
1725#else
1726		return (ENOTSUP);
1727#endif
1728	}
1729
1730	return (0);		/* XXX: compromise compilers */
1731}
1732
1733/*
1734 * generate kernel-internal form (scopeid embedded into s6_addr16[1]).
1735 * If the address scope of is link-local, embed the interface index in the
1736 * address.  The routine determines our precedence
1737 * between advanced API scope/interface specification and basic API
1738 * specification.
1739 *
1740 * this function should be nuked in the future, when we get rid of
1741 * embedded scopeid thing.
1742 *
1743 * XXX actually, it is over-specification to return ifp against sin6_scope_id.
1744 * there can be multiple interfaces that belong to a particular scope zone
1745 * (in specification, we have 1:N mapping between a scope zone and interfaces).
1746 * we may want to change the function to return something other than ifp.
1747 */
1748int
1749in6_embedscope(struct in6_addr *in6, const struct sockaddr_in6 *sin6,
1750    struct in6pcb *in6p, struct ifnet **ifpp, struct ip6_pktopts *opt)
1751{
1752	struct ifnet *ifp = NULL;
1753	u_int32_t scopeid;
1754	struct ip6_pktopts *optp = NULL;
1755
1756	*in6 = sin6->sin6_addr;
1757	scopeid = sin6->sin6_scope_id;
1758	if (ifpp != NULL)
1759		*ifpp = NULL;
1760
1761	/*
1762	 * don't try to read sin6->sin6_addr beyond here, since the caller may
1763	 * ask us to overwrite existing sockaddr_in6
1764	 */
1765
1766#ifdef ENABLE_DEFAULT_SCOPE
1767	if (scopeid == 0)
1768		scopeid = scope6_addr2default(in6);
1769#endif
1770
1771	if (IN6_IS_SCOPE_LINKLOCAL(in6)) {
1772		struct in6_pktinfo *pi;
1773		struct ifnet *im6o_multicast_ifp = NULL;
1774
1775		if (in6p != NULL && IN6_IS_ADDR_MULTICAST(in6) &&
1776		    in6p->in6p_moptions != NULL) {
1777			IM6O_LOCK(in6p->in6p_moptions);
1778			im6o_multicast_ifp =
1779			    in6p->in6p_moptions->im6o_multicast_ifp;
1780			IM6O_UNLOCK(in6p->in6p_moptions);
1781		}
1782
1783		if (opt != NULL)
1784			optp = opt;
1785		else if (in6p != NULL)
1786			optp = in6p->in6p_outputopts;
1787		/*
1788		 * KAME assumption: link id == interface id
1789		 */
1790		if (in6p != NULL && optp != NULL &&
1791		    (pi = optp->ip6po_pktinfo) != NULL &&
1792		    pi->ipi6_ifindex != 0) {
1793			/* ifp is needed here if only we're returning it */
1794			if (ifpp != NULL) {
1795				ifnet_head_lock_shared();
1796				ifp = ifindex2ifnet[pi->ipi6_ifindex];
1797				ifnet_head_done();
1798			}
1799			in6->s6_addr16[1] = htons(pi->ipi6_ifindex);
1800		} else if (in6p != NULL && IN6_IS_ADDR_MULTICAST(in6) &&
1801		    in6p->in6p_moptions != NULL && im6o_multicast_ifp != NULL) {
1802			ifp = im6o_multicast_ifp;
1803			in6->s6_addr16[1] = htons(ifp->if_index);
1804		} else if (scopeid != 0) {
1805			/*
1806			 * Since scopeid is unsigned, we only have to check it
1807			 * against if_index (ifnet_head_lock not needed since
1808			 * if_index is an ever-increasing integer.)
1809			 */
1810			if (if_index < scopeid)
1811				return (ENXIO);  /* XXX EINVAL? */
1812
1813			/* ifp is needed here only if we're returning it */
1814			if (ifpp != NULL) {
1815				ifnet_head_lock_shared();
1816				ifp = ifindex2ifnet[scopeid];
1817				ifnet_head_done();
1818			}
1819			/* XXX assignment to 16bit from 32bit variable */
1820			in6->s6_addr16[1] = htons(scopeid & 0xffff);
1821		}
1822
1823		if (ifpp != NULL) {
1824			if (ifp != NULL)
1825				ifnet_reference(ifp);	/* for caller */
1826			*ifpp = ifp;
1827		}
1828	}
1829
1830	return (0);
1831}
1832
1833/*
1834 * generate standard sockaddr_in6 from embedded form.
1835 * touches sin6_addr and sin6_scope_id only.
1836 *
1837 * this function should be nuked in the future, when we get rid of
1838 * embedded scopeid thing.
1839 */
1840int
1841in6_recoverscope(
1842	struct sockaddr_in6 *sin6,
1843	const struct in6_addr *in6,
1844	struct ifnet *ifp)
1845{
1846	u_int32_t scopeid;
1847
1848	sin6->sin6_addr = *in6;
1849
1850	/*
1851	 * don't try to read *in6 beyond here, since the caller may
1852	 * ask us to overwrite existing sockaddr_in6
1853	 */
1854
1855	sin6->sin6_scope_id = 0;
1856	if (IN6_IS_SCOPE_LINKLOCAL(in6)) {
1857		/*
1858		 * KAME assumption: link id == interface id
1859		 */
1860		scopeid = ntohs(sin6->sin6_addr.s6_addr16[1]);
1861		if (scopeid) {
1862			/*
1863			 * sanity check
1864			 *
1865			 * Since scopeid is unsigned, we only have to check it
1866			 * against if_index
1867			 */
1868			if (if_index < scopeid)
1869				return (ENXIO);
1870			if (ifp && ifp->if_index != scopeid)
1871				return (ENXIO);
1872			sin6->sin6_addr.s6_addr16[1] = 0;
1873			sin6->sin6_scope_id = scopeid;
1874		}
1875	}
1876
1877	return (0);
1878}
1879