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