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