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