xref: /netbsd-src/sys/netinet6/in6_src.c (revision 87d689fb734c654d2486f87f7be32f1b53ecdbec)
1 /*	$NetBSD: in6_src.c,v 1.84 2017/12/06 14:17:42 roy Exp $	*/
2 /*	$KAME: in6_src.c,v 1.159 2005/10/19 01:40:32 t-momose Exp $	*/
3 
4 /*
5  * Copyright (C) 1995, 1996, 1997, and 1998 WIDE Project.
6  * All rights reserved.
7  *
8  * Redistribution and use in source and binary forms, with or without
9  * modification, are permitted provided that the following conditions
10  * are met:
11  * 1. Redistributions of source code must retain the above copyright
12  *    notice, this list of conditions and the following disclaimer.
13  * 2. Redistributions in binary form must reproduce the above copyright
14  *    notice, this list of conditions and the following disclaimer in the
15  *    documentation and/or other materials provided with the distribution.
16  * 3. Neither the name of the project nor the names of its contributors
17  *    may be used to endorse or promote products derived from this software
18  *    without specific prior written permission.
19  *
20  * THIS SOFTWARE IS PROVIDED BY THE PROJECT AND CONTRIBUTORS ``AS IS'' AND
21  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
22  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
23  * ARE DISCLAIMED.  IN NO EVENT SHALL THE PROJECT OR CONTRIBUTORS BE LIABLE
24  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
25  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
26  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
27  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
28  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
29  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
30  * SUCH DAMAGE.
31  */
32 
33 /*
34  * Copyright (c) 1982, 1986, 1991, 1993
35  *	The Regents of the University of California.  All rights reserved.
36  *
37  * Redistribution and use in source and binary forms, with or without
38  * modification, are permitted provided that the following conditions
39  * are met:
40  * 1. Redistributions of source code must retain the above copyright
41  *    notice, this list of conditions and the following disclaimer.
42  * 2. Redistributions in binary form must reproduce the above copyright
43  *    notice, this list of conditions and the following disclaimer in the
44  *    documentation and/or other materials provided with the distribution.
45  * 3. All advertising materials mentioning features or use of this software
46  *    must display the following acknowledgement:
47  *	This product includes software developed by the University of
48  *	California, Berkeley and its contributors.
49  * 4. Neither the name of the University nor the names of its contributors
50  *    may be used to endorse or promote products derived from this software
51  *    without specific prior written permission.
52  *
53  * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
54  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
55  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
56  * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
57  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
58  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
59  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
60  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
61  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
62  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
63  * SUCH DAMAGE.
64  *
65  *	@(#)in_pcb.c	8.2 (Berkeley) 1/4/94
66  */
67 
68 #include <sys/cdefs.h>
69 __KERNEL_RCSID(0, "$NetBSD: in6_src.c,v 1.84 2017/12/06 14:17:42 roy Exp $");
70 
71 #ifdef _KERNEL_OPT
72 #include "opt_inet.h"
73 #endif
74 
75 #include <sys/param.h>
76 #include <sys/systm.h>
77 #include <sys/malloc.h>
78 #include <sys/mbuf.h>
79 #include <sys/protosw.h>
80 #include <sys/socket.h>
81 #include <sys/socketvar.h>
82 #include <sys/ioctl.h>
83 #include <sys/errno.h>
84 #include <sys/time.h>
85 #include <sys/kernel.h>
86 #include <sys/proc.h>
87 #include <sys/kauth.h>
88 
89 #include <net/if.h>
90 #include <net/if_types.h>
91 #include <net/route.h>
92 
93 #include <netinet/in.h>
94 #include <netinet/in_var.h>
95 #include <netinet/in_systm.h>
96 #include <netinet/ip.h>
97 #include <netinet/in_pcb.h>
98 #include <netinet/portalgo.h>
99 #include <netinet6/in6_var.h>
100 #include <netinet/ip6.h>
101 #include <netinet6/in6_pcb.h>
102 #include <netinet6/ip6_var.h>
103 #include <netinet6/ip6_private.h>
104 #include <netinet6/nd6.h>
105 #include <netinet6/scope6_var.h>
106 
107 #include <net/net_osdep.h>
108 
109 #ifdef MIP6
110 #include <netinet6/mip6.h>
111 #include <netinet6/mip6_var.h>
112 #include "mip.h"
113 #if NMIP > 0
114 #include <net/if_mip.h>
115 #endif /* NMIP > 0 */
116 #endif /* MIP6 */
117 
118 #include <netinet/tcp_vtw.h>
119 
120 #define ADDR_LABEL_NOTAPP (-1)
121 struct in6_addrpolicy defaultaddrpolicy;
122 
123 int ip6_prefer_tempaddr = 0;
124 
125 static int in6_selectif(struct sockaddr_in6 *, struct ip6_pktopts *,
126 	struct ip6_moptions *, struct route *, struct ifnet **, struct psref *);
127 
128 static struct in6_addrpolicy *lookup_addrsel_policy(struct sockaddr_in6 *);
129 
130 static void init_policy_queue(void);
131 static int add_addrsel_policyent(struct in6_addrpolicy *);
132 static int delete_addrsel_policyent(struct in6_addrpolicy *);
133 static int walk_addrsel_policy(int (*)(struct in6_addrpolicy *, void *),
134 				    void *);
135 static int dump_addrsel_policyent(struct in6_addrpolicy *, void *);
136 static struct in6_addrpolicy *match_addrsel_policy(struct sockaddr_in6 *);
137 
138 #define	IFA6_IS_VALIDATED(ia) \
139 	(((ia)->ia6_flags & (IN6_IFF_TENTATIVE | IN6_IFF_DETACHED)) == 0)
140 
141 /*
142  * Return an IPv6 address, which is the most appropriate for a given
143  * destination and user specified options.
144  * If necessary, this function lookups the routing table and returns
145  * an entry to the caller for later use.
146  */
147 #if 0				/* disabled ad-hoc */
148 #define REPLACE(r) do {\
149 	char _buf1[INET6_ADDRSTRLEN], _buf2[INET6_ADDRSTRLEN]; \
150 	if ((r) < sizeof(ip6stat.ip6s_sources_rule) / \
151 		sizeof(ip6stat.ip6s_sources_rule[0])) /* check for safety */ \
152 		ip6stat.ip6s_sources_rule[(r)]++; \
153 	printf("%s: replace %s with %s by %d\n", __func__, ia_best ? \
154 	    IN6_PRINT(_buf1, &ia_best->ia_addr.sin6_addr) : "none", \
155 	    IN6_PRINT(_buf2, &ia->ia_addr.sin6_addr), (r)); \
156 	goto replace; \
157 } while(/*CONSTCOND*/0)
158 #define NEXT(r) do {\
159 	if ((r) < sizeof(ip6stat.ip6s_sources_rule) / \
160 		sizeof(ip6stat.ip6s_sources_rule[0])) /* check for safety */ \
161 		ip6stat.ip6s_sources_rule[(r)]++; \
162 	printf("%s: keep %s against %s by %d\n", ia_best ? \
163 	    IN6_PRINT(_buf1, &ia_best->ia_addr.sin6_addr) : "none", \
164 	    IN6_PRINT(_buf2, &ia->ia_addr.sin6_addr), (r)); \
165 	goto next; 		/* XXX: we can't use 'continue' here */ \
166 } while(/*CONSTCOND*/0)
167 #define BREAK(r) do { \
168 	if ((r) < sizeof(ip6stat.ip6s_sources_rule) / \
169 		sizeof(ip6stat.ip6s_sources_rule[0])) /* check for safety */ \
170 		ip6stat.ip6s_sources_rule[(r)]++; \
171 	goto out; 		/* XXX: we can't use 'break' here */ \
172 } while(/*CONSTCOND*/0)
173 #else
174 #define REPLACE(r) goto replace
175 #define NEXT(r) goto next
176 #define BREAK(r) goto out
177 #endif
178 
179 /*
180  * Called inside pserialize critical section. Don't sleep/block.
181  */
182 static struct in6_ifaddr *
183 in6_select_best_ia(struct sockaddr_in6 *dstsock, struct in6_addr *dst,
184     const struct ifnet *ifp, const struct ip6_pktopts *opts,
185     const u_int32_t odstzone)
186 {
187 	struct in6_ifaddr *ia, *ia_best = NULL;
188 	int dst_scope = -1, best_scope = -1, best_matchlen = -1;
189 	struct in6_addrpolicy *dst_policy = NULL, *best_policy = NULL;
190 
191 	IN6_ADDRLIST_READER_FOREACH(ia) {
192 		int new_scope = -1, new_matchlen = -1;
193 		struct in6_addrpolicy *new_policy = NULL;
194 		u_int32_t srczone, osrczone, dstzone;
195 		struct in6_addr src;
196 		struct ifnet *ifp1 = ia->ia_ifp;
197 		int prefer_tempaddr;
198 
199 		/*
200 		 * We'll never take an address that breaks the scope zone
201 		 * of the destination.  We also skip an address if its zone
202 		 * does not contain the outgoing interface.
203 		 * XXX: we should probably use sin6_scope_id here.
204 		 */
205 		if (in6_setscope(dst, ifp1, &dstzone) ||
206 		    odstzone != dstzone) {
207 			continue;
208 		}
209 		src = ia->ia_addr.sin6_addr;
210 
211 		/* Skip the scope test in impossible cases */
212 		if (!(ifp->if_flags & IFF_LOOPBACK) &&
213 		    IN6_IS_ADDR_LOOPBACK(&src))
214 			continue;
215 
216 		if (in6_setscope(&src, ifp, &osrczone) ||
217 		    in6_setscope(&src, ifp1, &srczone) ||
218 		    osrczone != srczone) {
219 			continue;
220 		}
221 
222 		/* avoid unusable addresses */
223 		if ((ia->ia6_flags & (IN6_IFF_DUPLICATED | IN6_IFF_ANYCAST)))
224 			continue;
225 		if (!ip6_use_deprecated && IFA6_IS_DEPRECATED(ia))
226 			continue;
227 
228 #if defined(MIP6) && NMIP > 0
229 		/* avoid unusable home addresses. */
230 		if ((ia->ia6_flags & IN6_IFF_HOME) &&
231 		    !mip6_ifa6_is_addr_valid_hoa(ia))
232 			continue;
233 #endif /* MIP6 && NMIP > 0 */
234 
235 		/* Rule 1: Prefer same address */
236 		if (IN6_ARE_ADDR_EQUAL(dst, &ia->ia_addr.sin6_addr)) {
237 			ia_best = ia;
238 			BREAK(1); /* there should be no better candidate */
239 		}
240 
241 		if (ia_best == NULL)
242 			REPLACE(1);
243 
244 		/* Rule 2: Prefer appropriate scope */
245 		if (dst_scope < 0)
246 			dst_scope = in6_addrscope(dst);
247 		new_scope = in6_addrscope(&ia->ia_addr.sin6_addr);
248 		if (IN6_ARE_SCOPE_CMP(best_scope, new_scope) < 0) {
249 			if (IN6_ARE_SCOPE_CMP(best_scope, dst_scope) < 0)
250 				REPLACE(2);
251 			NEXT(2);
252 		} else if (IN6_ARE_SCOPE_CMP(new_scope, best_scope) < 0) {
253 			if (IN6_ARE_SCOPE_CMP(new_scope, dst_scope) < 0)
254 				NEXT(2);
255 			REPLACE(2);
256 		}
257 
258 		/*
259 		 * Rule 3: Avoid deprecated addresses.  Note that the case of
260 		 * !ip6_use_deprecated is already rejected above.
261 		 * Treat unvalidated addresses as deprecated here.
262 		 */
263 		if (IFA6_IS_VALIDATED(ia_best) && !IFA6_IS_VALIDATED(ia))
264 			NEXT(3);
265 		if (!IFA6_IS_VALIDATED(ia_best) && IFA6_IS_VALIDATED(ia))
266 			REPLACE(3);
267 		if (!IFA6_IS_DEPRECATED(ia_best) && IFA6_IS_DEPRECATED(ia))
268 			NEXT(3);
269 		if (IFA6_IS_DEPRECATED(ia_best) && !IFA6_IS_DEPRECATED(ia))
270 			REPLACE(3);
271 
272 		/* Rule 4: Prefer home addresses */
273 #if defined(MIP6) && NMIP > 0
274 		if (!MIP6_IS_MN)
275 			goto skip_rule4;
276 
277 		if ((ia_best->ia6_flags & IN6_IFF_HOME) == 0 &&
278 		    (ia->ia6_flags & IN6_IFF_HOME) == 0) {
279 			/* both address are not home addresses. */
280 			goto skip_rule4;
281 		}
282 
283 		/*
284 		 * If SA is simultaneously a home address and care-of
285 		 * address and SB is not, then prefer SA. Similarly,
286 		 * if SB is simultaneously a home address and care-of
287 		 * address and SA is not, then prefer SB.
288 		 */
289 		if (((ia_best->ia6_flags & IN6_IFF_HOME) != 0 &&
290 			ia_best->ia_ifp->if_type != IFT_MIP)
291 		    &&
292 		    ((ia->ia6_flags & IN6_IFF_HOME) != 0 &&
293 			ia->ia_ifp->if_type == IFT_MIP))
294 			NEXT(4);
295 		if (((ia_best->ia6_flags & IN6_IFF_HOME) != 0 &&
296 			ia_best->ia_ifp->if_type == IFT_MIP)
297 		    &&
298 		    ((ia->ia6_flags & IN6_IFF_HOME) != 0 &&
299 			ia->ia_ifp->if_type != IFT_MIP))
300 			REPLACE(4);
301 		if (ip6po_usecoa == 0) {
302 			/*
303 			 * If SA is just a home address and SB is just
304 			 * a care-of address, then prefer
305 			 * SA. Similarly, if SB is just a home address
306 			 * and SA is just a care-of address, then
307 			 * prefer SB.
308 			 */
309 			if ((ia_best->ia6_flags & IN6_IFF_HOME) != 0 &&
310 			    (ia->ia6_flags & IN6_IFF_HOME) == 0) {
311 				NEXT(4);
312 			}
313 			if ((ia_best->ia6_flags & IN6_IFF_HOME) == 0 &&
314 			    (ia->ia6_flags & IN6_IFF_HOME) != 0) {
315 				REPLACE(4);
316 			}
317 		} else {
318 			/*
319 			 * a sender don't want to use a home address
320 			 * because:
321 			 *
322 			 * 1) we cannot use.  (ex. NS or NA to global
323 			 * addresses.)
324 			 *
325 			 * 2) a user specified not to use.
326 			 * (ex. mip6control -u)
327 			 */
328 			if ((ia_best->ia6_flags & IN6_IFF_HOME) == 0 &&
329 			    (ia->ia6_flags & IN6_IFF_HOME) != 0) {
330 				/* XXX breaks stat */
331 				NEXT(0);
332 			}
333 			if ((ia_best->ia6_flags & IN6_IFF_HOME) != 0 &&
334 			    (ia->ia6_flags & IN6_IFF_HOME) == 0) {
335 				/* XXX breaks stat */
336 				REPLACE(0);
337 			}
338 		}
339 	skip_rule4:
340 #endif /* MIP6 && NMIP > 0 */
341 
342 		/* Rule 5: Prefer outgoing interface */
343 		if (ia_best->ia_ifp == ifp && ia->ia_ifp != ifp)
344 			NEXT(5);
345 		if (ia_best->ia_ifp != ifp && ia->ia_ifp == ifp)
346 			REPLACE(5);
347 
348 		/*
349 		 * Rule 6: Prefer matching label
350 		 * Note that best_policy should be non-NULL here.
351 		 */
352 		if (dst_policy == NULL)
353 			dst_policy = lookup_addrsel_policy(dstsock);
354 		if (dst_policy->label != ADDR_LABEL_NOTAPP) {
355 			new_policy = lookup_addrsel_policy(&ia->ia_addr);
356 			if (dst_policy->label == best_policy->label &&
357 			    dst_policy->label != new_policy->label)
358 				NEXT(6);
359 			if (dst_policy->label != best_policy->label &&
360 			    dst_policy->label == new_policy->label)
361 				REPLACE(6);
362 		}
363 
364 		/*
365 		 * Rule 7: Prefer public addresses.
366 		 * We allow users to reverse the logic by configuring
367 		 * a sysctl variable, so that privacy conscious users can
368 		 * always prefer temporary addresses.
369 		 */
370 		if (opts == NULL ||
371 		    opts->ip6po_prefer_tempaddr == IP6PO_TEMPADDR_SYSTEM) {
372 			prefer_tempaddr = ip6_prefer_tempaddr;
373 		} else if (opts->ip6po_prefer_tempaddr ==
374 		    IP6PO_TEMPADDR_NOTPREFER) {
375 			prefer_tempaddr = 0;
376 		} else
377 			prefer_tempaddr = 1;
378 		if (!(ia_best->ia6_flags & IN6_IFF_TEMPORARY) &&
379 		    (ia->ia6_flags & IN6_IFF_TEMPORARY)) {
380 			if (prefer_tempaddr)
381 				REPLACE(7);
382 			else
383 				NEXT(7);
384 		}
385 		if ((ia_best->ia6_flags & IN6_IFF_TEMPORARY) &&
386 		    !(ia->ia6_flags & IN6_IFF_TEMPORARY)) {
387 			if (prefer_tempaddr)
388 				NEXT(7);
389 			else
390 				REPLACE(7);
391 		}
392 
393 		/*
394 		 * Rule 8: prefer addresses on alive interfaces.
395 		 * This is a KAME specific rule.
396 		 */
397 		if ((ia_best->ia_ifp->if_flags & IFF_UP) &&
398 		    !(ia->ia_ifp->if_flags & IFF_UP))
399 			NEXT(8);
400 		if (!(ia_best->ia_ifp->if_flags & IFF_UP) &&
401 		    (ia->ia_ifp->if_flags & IFF_UP))
402 			REPLACE(8);
403 
404 		/*
405 		 * Rule 9: prefer addresses on "preferred" interfaces.
406 		 * This is a KAME specific rule.
407 		 */
408 #ifdef notyet			/* until introducing address selection */
409 #define NDI_BEST ND_IFINFO(ia_best->ia_ifp)
410 #define NDI_NEW  ND_IFINFO(ia->ia_ifp)
411 		if ((NDI_BEST->flags & ND6_IFF_PREFER_SOURCE) &&
412 		    !(NDI_NEW->flags & ND6_IFF_PREFER_SOURCE))
413 			NEXT(9);
414 		if (!(NDI_BEST->flags & ND6_IFF_PREFER_SOURCE) &&
415 		    (NDI_NEW->flags & ND6_IFF_PREFER_SOURCE))
416 			REPLACE(9);
417 #undef NDI_BEST
418 #undef NDI_NEW
419 #endif
420 
421 		/*
422 		 * Rule 14: Use longest matching prefix.
423 		 * Note: in the address selection draft, this rule is
424 		 * documented as "Rule 8".  However, since it is also
425 		 * documented that this rule can be overridden, we assign
426 		 * a large number so that it is easy to assign smaller numbers
427 		 * to more preferred rules.
428 		 */
429 		new_matchlen = in6_matchlen(&ia->ia_addr.sin6_addr, dst);
430 		if (best_matchlen < new_matchlen)
431 			REPLACE(14);
432 		if (new_matchlen < best_matchlen)
433 			NEXT(14);
434 
435 		/* Rule 15 is reserved. */
436 
437 		/*
438 		 * Last resort: just keep the current candidate.
439 		 * Or, do we need more rules?
440 		 */
441 		continue;
442 
443 	  replace:
444 		ia_best = ia;
445 		best_scope = (new_scope >= 0 ? new_scope :
446 			      in6_addrscope(&ia_best->ia_addr.sin6_addr));
447 		best_policy = (new_policy ? new_policy :
448 			       lookup_addrsel_policy(&ia_best->ia_addr));
449 		best_matchlen = (new_matchlen >= 0 ? new_matchlen :
450 				 in6_matchlen(&ia_best->ia_addr.sin6_addr,
451 					      dst));
452 
453 	  next:
454 		continue;
455 
456 	  out:
457 		break;
458 	}
459 
460 	return ia_best;
461 }
462 #undef REPLACE
463 #undef BREAK
464 #undef NEXT
465 
466 int
467 in6_selectsrc(struct sockaddr_in6 *dstsock, struct ip6_pktopts *opts,
468 	struct ip6_moptions *mopts, struct route *ro, struct in6_addr *laddr,
469 	struct ifnet **ifpp, struct psref *psref, struct in6_addr *ret_ia6)
470 {
471 	struct in6_addr dst;
472 	struct ifnet *ifp = NULL;
473 	struct in6_ifaddr *ia = NULL;
474 	struct in6_pktinfo *pi = NULL;
475 	u_int32_t odstzone;
476 	int error = 0, iferror;
477 #if defined(MIP6) && NMIP > 0
478 	u_int8_t ip6po_usecoa = 0;
479 #endif /* MIP6 && NMIP > 0 */
480 	struct psref local_psref;
481 	int bound = curlwp_bind();
482 #define PSREF (psref == NULL) ? &local_psref : psref
483 	int s;
484 
485 	KASSERT((ifpp != NULL && psref != NULL) ||
486 	        (ifpp == NULL && psref == NULL));
487 
488 	dst = dstsock->sin6_addr; /* make a copy for local operation */
489 	if (ifpp)
490 		*ifpp = NULL;
491 
492 	/*
493 	 * Try to determine the outgoing interface for the given destination.
494 	 * We do this regardless of whether the socket is bound, since the
495 	 * caller may need this information as a side effect of the call
496 	 * to this function (e.g., for identifying the appropriate scope zone
497 	 * ID).
498 	 */
499 	iferror = in6_selectif(dstsock, opts, mopts, ro, &ifp, PSREF);
500 	if (ifpp != NULL)
501 		*ifpp = ifp;
502 
503 	/*
504 	 * If the source address is explicitly specified by the caller,
505 	 * check if the requested source address is indeed a unicast address
506 	 * assigned to the node, and can be used as the packet's source
507 	 * address.  If everything is okay, use the address as source.
508 	 */
509 	if (opts && (pi = opts->ip6po_pktinfo) &&
510 	    !IN6_IS_ADDR_UNSPECIFIED(&pi->ipi6_addr)) {
511 		struct sockaddr_in6 srcsock;
512 		struct in6_ifaddr *ia6;
513 		int _s;
514 		struct ifaddr *ifa;
515 
516 		/*
517 		 * Determine the appropriate zone id of the source based on
518 		 * the zone of the destination and the outgoing interface.
519 		 * If the specified address is ambiguous wrt the scope zone,
520 		 * the interface must be specified; otherwise, ifa_ifwithaddr()
521 		 * will fail matching the address.
522 		 */
523 		memset(&srcsock, 0, sizeof(srcsock));
524 		srcsock.sin6_family = AF_INET6;
525 		srcsock.sin6_len = sizeof(srcsock);
526 		srcsock.sin6_addr = pi->ipi6_addr;
527 		if (ifp) {
528 			error = in6_setscope(&srcsock.sin6_addr, ifp, NULL);
529 			if (error != 0)
530 				goto exit;
531 		}
532 
533 		_s = pserialize_read_enter();
534 		ifa = ifa_ifwithaddr(sin6tosa(&srcsock));
535 		if ((ia6 = ifatoia6(ifa)) == NULL ||
536 		    ia6->ia6_flags &
537 		    (IN6_IFF_ANYCAST | IN6_IFF_NOTREADY)) {
538 			pserialize_read_exit(_s);
539 			error = EADDRNOTAVAIL;
540 			goto exit;
541 		}
542 		pi->ipi6_addr = srcsock.sin6_addr; /* XXX: this overrides pi */
543 		if (ifpp)
544 			*ifpp = ifp;
545 		*ret_ia6 = ia6->ia_addr.sin6_addr;
546 		pserialize_read_exit(_s);
547 		goto exit;
548 	}
549 
550 	/*
551 	 * If the socket has already bound the source, just use it.  We don't
552 	 * care at the moment whether in6_selectif() succeeded above, even
553 	 * though it would eventually cause an error.
554 	 */
555 	if (laddr && !IN6_IS_ADDR_UNSPECIFIED(laddr)) {
556 		*ret_ia6 = *laddr;
557 		goto exit;
558 	}
559 
560 	/*
561 	 * The outgoing interface is crucial in the general selection procedure
562 	 * below.  If it is not known at this point, we fail.
563 	 */
564 	if (ifp == NULL) {
565 		error = iferror;
566 		goto exit;
567 	}
568 
569 	/*
570 	 * If the address is not yet determined, choose the best one based on
571 	 * the outgoing interface and the destination address.
572 	 */
573 
574 #if defined(MIP6) && NMIP > 0
575 	/*
576 	 * a caller can specify IP6PO_USECOA to not to use a home
577 	 * address.  for example, the case that the neighbour
578 	 * unreachability detection to the global address.
579 	 */
580 	if (opts != NULL &&
581 	    (opts->ip6po_flags & IP6PO_USECOA) != 0) {
582 		ip6po_usecoa = 1;
583 	}
584 #endif /* MIP6 && NMIP > 0 */
585 
586 	error = in6_setscope(&dst, ifp, &odstzone);
587 	if (error != 0)
588 		goto exit;
589 
590 	s = pserialize_read_enter();
591 
592 	ia = in6_select_best_ia(dstsock, &dst, ifp, opts, odstzone);
593 	if (ia == NULL) {
594 		pserialize_read_exit(s);
595 		error = EADDRNOTAVAIL;
596 		goto exit;
597 	}
598 	*ret_ia6 = ia->ia_addr.sin6_addr;
599 
600 	pserialize_read_exit(s);
601 exit:
602 	if (ifpp == NULL)
603 		if_put(ifp, PSREF);
604 	curlwp_bindx(bound);
605 	return error;
606 #undef PSREF
607 }
608 
609 int
610 in6_selectroute(struct sockaddr_in6 *dstsock, struct ip6_pktopts *opts,
611     struct route **ro, struct rtentry **retrt, bool count_discard)
612 {
613 	int error = 0;
614 	struct rtentry *rt = NULL;
615 	union {
616 		struct sockaddr		dst;
617 		struct sockaddr_in6	dst6;
618 	} u;
619 
620 	KASSERT(ro != NULL);
621 	KASSERT(*ro != NULL);
622 	KASSERT(retrt != NULL);
623 
624 #if 0
625 	if (dstsock->sin6_addr.s6_addr32[0] == 0 &&
626 	    dstsock->sin6_addr.s6_addr32[1] == 0 &&
627 	    !IN6_IS_ADDR_LOOPBACK(&dstsock->sin6_addr)) {
628 		char ip6buf[INET6_ADDRSTRLEN];
629 		printf("%s: strange destination %s\n", __func__,
630 		       IN6_PRINT(ip6buf, &dstsock->sin6_addr));
631 	} else {
632 		char ip6buf[INET6_ADDRSTRLEN];
633 		printf("%s: destination = %s%%%d\n", __func__,
634 		       IN6_PRINT(ip6buf, &dstsock->sin6_addr),
635 		       dstsock->sin6_scope_id); /* for debug */
636 	}
637 #endif
638 
639 	/*
640 	 * If the next hop address for the packet is specified by the caller,
641 	 * use it as the gateway.
642 	 */
643 	if (opts && opts->ip6po_nexthop) {
644 		struct route *ron;
645 		struct sockaddr_in6 *sin6_next;
646 
647 		sin6_next = satosin6(opts->ip6po_nexthop);
648 
649 		/* at this moment, we only support AF_INET6 next hops */
650 		if (sin6_next->sin6_family != AF_INET6) {
651 			error = EAFNOSUPPORT; /* or should we proceed? */
652 			goto done;
653 		}
654 
655 		/*
656 		 * If the next hop is an IPv6 address, then the node identified
657 		 * by that address must be a neighbor of the sending host.
658 		 */
659 		ron = &opts->ip6po_nextroute;
660 		rt = rtcache_lookup(ron, sin6tosa(sin6_next));
661 		if (rt == NULL || (rt->rt_flags & RTF_GATEWAY) != 0 ||
662 		    !nd6_is_addr_neighbor(sin6_next, rt->rt_ifp)) {
663 			if (rt != NULL) {
664 				if (count_discard)
665 					in6_ifstat_inc(rt->rt_ifp,
666 					    ifs6_out_discard);
667 				rtcache_unref(rt, ron);
668 				rt = NULL;
669 			}
670 			rtcache_free(ron);
671 			error = EHOSTUNREACH;
672 			goto done;
673 		}
674 		*ro = ron;
675 
676 		goto done;
677 	}
678 
679 	/*
680 	 * Use a cached route if it exists and is valid, else try to allocate
681 	 * a new one.  Note that we should check the address family of the
682 	 * cached destination, in case of sharing the cache with IPv4.
683 	 */
684 	u.dst6 = *dstsock;
685 	u.dst6.sin6_scope_id = 0;
686 	rt = rtcache_lookup1(*ro, &u.dst, 1);
687 
688 	if (rt == NULL)
689 		error = EHOSTUNREACH;
690 
691 	/*
692 	 * Check if the outgoing interface conflicts with
693 	 * the interface specified by ipi6_ifindex (if specified).
694 	 * Note that loopback interface is always okay.
695 	 * (this may happen when we are sending a packet to one of
696 	 *  our own addresses.)
697 	 */
698 	if (opts && opts->ip6po_pktinfo && opts->ip6po_pktinfo->ipi6_ifindex) {
699 		if (rt != NULL && !(rt->rt_ifp->if_flags & IFF_LOOPBACK) &&
700 		    rt->rt_ifp->if_index != opts->ip6po_pktinfo->ipi6_ifindex) {
701 			if (count_discard)
702 				in6_ifstat_inc(rt->rt_ifp, ifs6_out_discard);
703 			error = EHOSTUNREACH;
704 			rt = NULL;
705 		}
706 	}
707 
708 done:
709 	if (error == EHOSTUNREACH)
710 		IP6_STATINC(IP6_STAT_NOROUTE);
711 	*retrt = rt;
712 	return error;
713 }
714 
715 static int
716 in6_selectif(struct sockaddr_in6 *dstsock, struct ip6_pktopts *opts,
717 	struct ip6_moptions *mopts, struct route *ro, struct ifnet **retifp,
718 	struct psref *psref)
719 {
720 	int error = 0;
721 	struct rtentry *rt = NULL;
722 	struct in6_addr *dst;
723 	struct in6_pktinfo *pi = NULL;
724 
725 	KASSERT(retifp != NULL);
726 	*retifp = NULL;
727 	dst = &dstsock->sin6_addr;
728 
729 	/* If the caller specify the outgoing interface explicitly, use it. */
730 	if (opts && (pi = opts->ip6po_pktinfo) != NULL && pi->ipi6_ifindex) {
731 		/* XXX boundary check is assumed to be already done. */
732 		*retifp = if_get_byindex(pi->ipi6_ifindex, psref);
733 		if (*retifp != NULL)
734 			return 0;
735 		goto getroute;
736 	}
737 
738 	/*
739 	 * If the destination address is a multicast address and the outgoing
740 	 * interface for the address is specified by the caller, use it.
741 	 */
742 	if (IN6_IS_ADDR_MULTICAST(dst) && mopts != NULL) {
743 		*retifp = if_get_byindex(mopts->im6o_multicast_if_index, psref);
744 		if (*retifp != NULL)
745 			return 0; /* we do not need a route for multicast. */
746 	}
747 
748 getroute:
749 	error = in6_selectroute(dstsock, opts, &ro, &rt, false);
750 	if (error != 0)
751 		return error;
752 
753 	*retifp = if_get_byindex(rt->rt_ifp->if_index, psref);
754 
755 	/*
756 	 * do not use a rejected or black hole route.
757 	 * XXX: this check should be done in the L2 output routine.
758 	 * However, if we skipped this check here, we'd see the following
759 	 * scenario:
760 	 * - install a rejected route for a scoped address prefix
761 	 *   (like fe80::/10)
762 	 * - send a packet to a destination that matches the scoped prefix,
763 	 *   with ambiguity about the scope zone.
764 	 * - pick the outgoing interface from the route, and disambiguate the
765 	 *   scope zone with the interface.
766 	 * - ip6_output() would try to get another route with the "new"
767 	 *   destination, which may be valid.
768 	 * - we'd see no error on output.
769 	 * Although this may not be very harmful, it should still be confusing.
770 	 * We thus reject the case here.
771 	 */
772 	if ((rt->rt_flags & (RTF_REJECT | RTF_BLACKHOLE))) {
773 		error = (rt->rt_flags & RTF_HOST ? EHOSTUNREACH : ENETUNREACH);
774 		/* XXX: ifp can be returned with psref even if error */
775 		goto out;
776 	}
777 
778 	/*
779 	 * Adjust the "outgoing" interface.  If we're going to loop the packet
780 	 * back to ourselves, the ifp would be the loopback interface.
781 	 * However, we'd rather know the interface associated to the
782 	 * destination address (which should probably be one of our own
783 	 * addresses.)
784 	 */
785 	if (rt->rt_ifa && rt->rt_ifa->ifa_ifp &&
786 	    rt->rt_ifa->ifa_ifp != *retifp &&
787 	    !if_is_deactivated(rt->rt_ifa->ifa_ifp)) {
788 		if_put(*retifp, psref);
789 		*retifp = rt->rt_ifa->ifa_ifp;
790 		if_acquire(*retifp, psref);
791 	}
792 out:
793 	rtcache_unref(rt, ro);
794 	return error;
795 }
796 
797 /*
798  * Default hop limit selection. The precedence is as follows:
799  * 1. Hoplimit value specified via ioctl.
800  * 2. (If the outgoing interface is detected) the current
801  *     hop limit of the interface specified by router advertisement.
802  * 3. The system default hoplimit.
803 */
804 int
805 in6_selecthlim(struct in6pcb *in6p, struct ifnet *ifp)
806 {
807 	if (in6p && in6p->in6p_hops >= 0)
808 		return (in6p->in6p_hops);
809 	else if (ifp)
810 		return (ND_IFINFO(ifp)->chlim);
811 	else
812 		return (ip6_defhlim);
813 }
814 
815 int
816 in6_selecthlim_rt(struct in6pcb *in6p)
817 {
818 	struct rtentry *rt;
819 
820 	if (in6p == NULL)
821 		return in6_selecthlim(in6p, NULL);
822 
823 	rt = rtcache_validate(&in6p->in6p_route);
824 	if (rt != NULL) {
825 		int ret = in6_selecthlim(in6p, rt->rt_ifp);
826 		rtcache_unref(rt, &in6p->in6p_route);
827 		return ret;
828 	} else
829 		return in6_selecthlim(in6p, NULL);
830 }
831 
832 /*
833  * Find an empty port and set it to the specified PCB.
834  */
835 int
836 in6_pcbsetport(struct sockaddr_in6 *sin6, struct in6pcb *in6p, struct lwp *l)
837 {
838 	struct socket *so = in6p->in6p_socket;
839 	struct inpcbtable *table = in6p->in6p_table;
840 	u_int16_t lport, *lastport;
841 	enum kauth_network_req req;
842 	int error = 0;
843 
844 	if (in6p->in6p_flags & IN6P_LOWPORT) {
845 #ifndef IPNOPRIVPORTS
846 		req = KAUTH_REQ_NETWORK_BIND_PRIVPORT;
847 #else
848 		req = KAUTH_REQ_NETWORK_BIND_PORT;
849 #endif
850 		lastport = &table->inpt_lastlow;
851 	} else {
852 		req = KAUTH_REQ_NETWORK_BIND_PORT;
853 
854 		lastport = &table->inpt_lastport;
855 	}
856 
857 	/* XXX-kauth: KAUTH_REQ_NETWORK_BIND_AUTOASSIGN_{,PRIV}PORT */
858 	error = kauth_authorize_network(l->l_cred, KAUTH_NETWORK_BIND, req, so,
859 	    sin6, NULL);
860 	if (error)
861 		return (EACCES);
862 
863        /*
864         * Use RFC6056 randomized port selection
865         */
866 	error = portalgo_randport(&lport, &in6p->in6p_head, l->l_cred);
867 	if (error)
868 		return error;
869 
870 	in6p->in6p_flags |= IN6P_ANONPORT;
871 	*lastport = lport;
872 	in6p->in6p_lport = htons(lport);
873 	in6_pcbstate(in6p, IN6P_BOUND);
874 	return (0);		/* success */
875 }
876 
877 void
878 addrsel_policy_init(void)
879 {
880 	init_policy_queue();
881 
882 	/* initialize the "last resort" policy */
883 	memset(&defaultaddrpolicy, 0, sizeof(defaultaddrpolicy));
884 	defaultaddrpolicy.label = ADDR_LABEL_NOTAPP;
885 }
886 
887 /*
888  * XXX: NOMPSAFE if a policy is set
889  */
890 static struct in6_addrpolicy *
891 lookup_addrsel_policy(struct sockaddr_in6 *key)
892 {
893 	struct in6_addrpolicy *match = NULL;
894 
895 	match = match_addrsel_policy(key);
896 
897 	if (match == NULL)
898 		match = &defaultaddrpolicy;
899 	else
900 		match->use++;
901 
902 	return (match);
903 }
904 
905 /*
906  * Subroutines to manage the address selection policy table via sysctl.
907  */
908 struct sel_walkarg {
909 	size_t	w_total;
910 	size_t	w_given;
911 	void *	w_where;
912 	void *w_limit;
913 };
914 
915 int sysctl_net_inet6_addrctlpolicy(SYSCTLFN_ARGS);
916 int
917 sysctl_net_inet6_addrctlpolicy(SYSCTLFN_ARGS)
918 {
919 	int error = 0;
920 	int s;
921 
922 	s = splsoftnet();
923 
924 	if (newp) {
925 		error = EPERM;
926 		goto end;
927 	}
928 	if (oldp && oldlenp == NULL) {
929 		error = EINVAL;
930 		goto end;
931 	}
932 	if (oldp || oldlenp) {
933 		struct sel_walkarg w;
934 		size_t oldlen = *oldlenp;
935 
936 		memset(&w, 0, sizeof(w));
937 		w.w_given = oldlen;
938 		w.w_where = oldp;
939 		if (oldp)
940 			w.w_limit = (char *)oldp + oldlen;
941 
942 		error = walk_addrsel_policy(dump_addrsel_policyent, &w);
943 
944 		*oldlenp = w.w_total;
945 		if (oldp && w.w_total > oldlen && error == 0)
946 			error = ENOMEM;
947 	}
948 
949   end:
950 	splx(s);
951 
952 	return (error);
953 }
954 
955 int
956 in6_src_ioctl(u_long cmd, void *data)
957 {
958 	int i;
959 	struct in6_addrpolicy ent0;
960 
961 	if (cmd != SIOCAADDRCTL_POLICY && cmd != SIOCDADDRCTL_POLICY)
962 		return (EOPNOTSUPP); /* check for safety */
963 
964 	ent0 = *(struct in6_addrpolicy *)data;
965 
966 	if (ent0.label == ADDR_LABEL_NOTAPP)
967 		return (EINVAL);
968 	/* check if the prefix mask is consecutive. */
969 	if (in6_mask2len(&ent0.addrmask.sin6_addr, NULL) < 0)
970 		return (EINVAL);
971 	/* clear trailing garbages (if any) of the prefix address. */
972 	for (i = 0; i < 4; i++) {
973 		ent0.addr.sin6_addr.s6_addr32[i] &=
974 			ent0.addrmask.sin6_addr.s6_addr32[i];
975 	}
976 	ent0.use = 0;
977 
978 	switch (cmd) {
979 	case SIOCAADDRCTL_POLICY:
980 		return (add_addrsel_policyent(&ent0));
981 	case SIOCDADDRCTL_POLICY:
982 		return (delete_addrsel_policyent(&ent0));
983 	}
984 
985 	return (0);		/* XXX: compromise compilers */
986 }
987 
988 /*
989  * The followings are implementation of the policy table using a
990  * simple tail queue.
991  * XXX such details should be hidden.
992  * XXX implementation using binary tree should be more efficient.
993  */
994 struct addrsel_policyent {
995 	TAILQ_ENTRY(addrsel_policyent) ape_entry;
996 	struct in6_addrpolicy ape_policy;
997 };
998 
999 TAILQ_HEAD(addrsel_policyhead, addrsel_policyent);
1000 
1001 struct addrsel_policyhead addrsel_policytab;
1002 
1003 static void
1004 init_policy_queue(void)
1005 {
1006 	TAILQ_INIT(&addrsel_policytab);
1007 }
1008 
1009 static int
1010 add_addrsel_policyent(struct in6_addrpolicy *newpolicy)
1011 {
1012 	struct addrsel_policyent *newpol, *pol;
1013 
1014 	/* duplication check */
1015 	TAILQ_FOREACH(pol, &addrsel_policytab, ape_entry) {
1016 		if (IN6_ARE_ADDR_EQUAL(&newpolicy->addr.sin6_addr,
1017 		    &pol->ape_policy.addr.sin6_addr) &&
1018 		    IN6_ARE_ADDR_EQUAL(&newpolicy->addrmask.sin6_addr,
1019 		    &pol->ape_policy.addrmask.sin6_addr)) {
1020 			return (EEXIST);	/* or override it? */
1021 		}
1022 	}
1023 
1024 	newpol = malloc(sizeof(*newpol), M_IFADDR, M_WAITOK|M_ZERO);
1025 
1026 	/* XXX: should validate entry */
1027 	newpol->ape_policy = *newpolicy;
1028 
1029 	TAILQ_INSERT_TAIL(&addrsel_policytab, newpol, ape_entry);
1030 
1031 	return (0);
1032 }
1033 
1034 static int
1035 delete_addrsel_policyent(struct in6_addrpolicy *key)
1036 {
1037 	struct addrsel_policyent *pol;
1038 
1039 	/* search for the entry in the table */
1040 	for (pol = TAILQ_FIRST(&addrsel_policytab); pol;
1041 	     pol = TAILQ_NEXT(pol, ape_entry)) {
1042 		if (IN6_ARE_ADDR_EQUAL(&key->addr.sin6_addr,
1043 		    &pol->ape_policy.addr.sin6_addr) &&
1044 		    IN6_ARE_ADDR_EQUAL(&key->addrmask.sin6_addr,
1045 		    &pol->ape_policy.addrmask.sin6_addr)) {
1046 			break;
1047 		}
1048 	}
1049 	if (pol == NULL) {
1050 		return (ESRCH);
1051 	}
1052 
1053 	TAILQ_REMOVE(&addrsel_policytab, pol, ape_entry);
1054 
1055 	return (0);
1056 }
1057 
1058 static int
1059 walk_addrsel_policy(int (*callback)(struct in6_addrpolicy *, void *), void *w)
1060 {
1061 	struct addrsel_policyent *pol;
1062 	int error = 0;
1063 
1064 	TAILQ_FOREACH(pol, &addrsel_policytab, ape_entry) {
1065 		if ((error = (*callback)(&pol->ape_policy, w)) != 0)
1066 			return error;
1067 	}
1068 
1069 	return error;
1070 }
1071 
1072 static int
1073 dump_addrsel_policyent(struct in6_addrpolicy *pol, void *arg)
1074 {
1075 	int error = 0;
1076 	struct sel_walkarg *w = arg;
1077 
1078 	if (w->w_where && (char *)w->w_where + sizeof(*pol) <= (char *)w->w_limit) {
1079 		if ((error = copyout(pol, w->w_where, sizeof(*pol))) != 0)
1080 			return error;
1081 		w->w_where = (char *)w->w_where + sizeof(*pol);
1082 	}
1083 	w->w_total += sizeof(*pol);
1084 
1085 	return error;
1086 }
1087 
1088 static struct in6_addrpolicy *
1089 match_addrsel_policy(struct sockaddr_in6 *key)
1090 {
1091 	struct addrsel_policyent *pent;
1092 	struct in6_addrpolicy *bestpol = NULL, *pol;
1093 	int matchlen, bestmatchlen = -1;
1094 	u_char *mp, *ep, *k, *p, m;
1095 
1096 	for (pent = TAILQ_FIRST(&addrsel_policytab); pent;
1097 	     pent = TAILQ_NEXT(pent, ape_entry)) {
1098 		matchlen = 0;
1099 
1100 		pol = &pent->ape_policy;
1101 		mp = (u_char *)&pol->addrmask.sin6_addr;
1102 		ep = mp + 16;	/* XXX: scope field? */
1103 		k = (u_char *)&key->sin6_addr;
1104 		p = (u_char *)&pol->addr.sin6_addr;
1105 		for (; mp < ep && *mp; mp++, k++, p++) {
1106 			m = *mp;
1107 			if ((*k & m) != *p)
1108 				goto next; /* not match */
1109 			if (m == 0xff) /* short cut for a typical case */
1110 				matchlen += 8;
1111 			else {
1112 				while (m >= 0x80) {
1113 					matchlen++;
1114 					m <<= 1;
1115 				}
1116 			}
1117 		}
1118 
1119 		/* matched.  check if this is better than the current best. */
1120 		if (bestpol == NULL ||
1121 		    matchlen > bestmatchlen) {
1122 			bestpol = pol;
1123 			bestmatchlen = matchlen;
1124 		}
1125 
1126 	  next:
1127 		continue;
1128 	}
1129 
1130 	return (bestpol);
1131 }
1132