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