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