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