xref: /netbsd-src/sys/netinet6/in6_src.c (revision b1c86f5f087524e68db12794ee9c3e3da1ab17a0)
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.49 2009/05/25 22:49:23 pooka 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 #define ADDR_LABEL_NOTAPP (-1)
115 struct in6_addrpolicy defaultaddrpolicy;
116 
117 #ifdef notyet /* until introducing ND extensions and address selection */
118 int ip6_prefer_tempaddr = 0;
119 #endif
120 
121 static int selectroute(struct sockaddr_in6 *, struct ip6_pktopts *,
122 	struct ip6_moptions *, struct route *, struct ifnet **,
123 	struct rtentry **, int, int);
124 static int in6_selectif(struct sockaddr_in6 *, struct ip6_pktopts *,
125 	struct ip6_moptions *, struct route *, struct ifnet **);
126 
127 static struct in6_addrpolicy *lookup_addrsel_policy(struct sockaddr_in6 *);
128 
129 static void init_policy_queue(void);
130 static int add_addrsel_policyent(struct in6_addrpolicy *);
131 static int delete_addrsel_policyent(struct in6_addrpolicy *);
132 static int walk_addrsel_policy(int (*)(struct in6_addrpolicy *, void *),
133 				    void *);
134 static int dump_addrsel_policyent(struct in6_addrpolicy *, void *);
135 static struct in6_addrpolicy *match_addrsel_policy(struct sockaddr_in6 *);
136 
137 /*
138  * Return an IPv6 address, which is the most appropriate for a given
139  * destination and user specified options.
140  * If necessary, this function lookups the routing table and returns
141  * an entry to the caller for later use.
142  */
143 #if 0				/* diabled ad-hoc */
144 #define REPLACE(r) do {\
145 	if ((r) < sizeof(ip6stat.ip6s_sources_rule) / \
146 		sizeof(ip6stat.ip6s_sources_rule[0])) /* check for safety */ \
147 		ip6stat.ip6s_sources_rule[(r)]++; \
148 	/* 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)); */ \
149 	goto replace; \
150 } while(0)
151 #define NEXT(r) do {\
152 	if ((r) < sizeof(ip6stat.ip6s_sources_rule) / \
153 		sizeof(ip6stat.ip6s_sources_rule[0])) /* check for safety */ \
154 		ip6stat.ip6s_sources_rule[(r)]++; \
155 	/* 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)); */ \
156 	goto next; 		/* XXX: we can't use 'continue' here */ \
157 } while(0)
158 #define BREAK(r) do { \
159 	if ((r) < sizeof(ip6stat.ip6s_sources_rule) / \
160 		sizeof(ip6stat.ip6s_sources_rule[0])) /* check for safety */ \
161 		ip6stat.ip6s_sources_rule[(r)]++; \
162 	goto out; 		/* XXX: we can't use 'break' here */ \
163 } while(0)
164 #else
165 #define REPLACE(r) goto replace
166 #define NEXT(r) goto next
167 #define BREAK(r) goto out
168 #endif
169 
170 struct in6_addr *
171 in6_selectsrc(struct sockaddr_in6 *dstsock, struct ip6_pktopts *opts,
172 	struct ip6_moptions *mopts, struct route *ro, struct in6_addr *laddr,
173 	struct ifnet **ifpp, int *errorp)
174 {
175 	struct in6_addr dst;
176 	struct ifnet *ifp = NULL;
177 	struct in6_ifaddr *ia = NULL, *ia_best = NULL;
178 	struct in6_pktinfo *pi = NULL;
179 	int dst_scope = -1, best_scope = -1, best_matchlen = -1;
180 	struct in6_addrpolicy *dst_policy = NULL, *best_policy = NULL;
181 	u_int32_t odstzone;
182 	int error;
183 #ifdef notyet /* until introducing ND extensions and address selection */
184 	int prefer_tempaddr;
185 #endif
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 #ifdef notyet /* until introducing ND extensions and address selection */
458 		if (opts == NULL ||
459 		    opts->ip6po_prefer_tempaddr == IP6PO_TEMPADDR_SYSTEM) {
460 			prefer_tempaddr = ip6_prefer_tempaddr;
461 		} else if (opts->ip6po_prefer_tempaddr ==
462 		    IP6PO_TEMPADDR_NOTPREFER) {
463 			prefer_tempaddr = 0;
464 		} else
465 			prefer_tempaddr = 1;
466 		if (!(ia_best->ia6_flags & IN6_IFF_TEMPORARY) &&
467 		    (ia->ia6_flags & IN6_IFF_TEMPORARY)) {
468 			if (prefer_tempaddr)
469 				REPLACE(7);
470 			else
471 				NEXT(7);
472 		}
473 		if ((ia_best->ia6_flags & IN6_IFF_TEMPORARY) &&
474 		    !(ia->ia6_flags & IN6_IFF_TEMPORARY)) {
475 			if (prefer_tempaddr)
476 				NEXT(7);
477 			else
478 				REPLACE(7);
479 		}
480 #endif
481 
482 		/*
483 		 * Rule 8: prefer addresses on alive interfaces.
484 		 * This is a KAME specific rule.
485 		 */
486 		if ((ia_best->ia_ifp->if_flags & IFF_UP) &&
487 		    !(ia->ia_ifp->if_flags & IFF_UP))
488 			NEXT(8);
489 		if (!(ia_best->ia_ifp->if_flags & IFF_UP) &&
490 		    (ia->ia_ifp->if_flags & IFF_UP))
491 			REPLACE(8);
492 
493 		/*
494 		 * Rule 9: prefer addresses on "preferred" interfaces.
495 		 * This is a KAME specific rule.
496 		 */
497 #ifdef notyet			/* until introducing address selection */
498 #define NDI_BEST ND_IFINFO(ia_best->ia_ifp)
499 #define NDI_NEW  ND_IFINFO(ia->ia_ifp)
500 		if ((NDI_BEST->flags & ND6_IFF_PREFER_SOURCE) &&
501 		    !(NDI_NEW->flags & ND6_IFF_PREFER_SOURCE))
502 			NEXT(9);
503 		if (!(NDI_BEST->flags & ND6_IFF_PREFER_SOURCE) &&
504 		    (NDI_NEW->flags & ND6_IFF_PREFER_SOURCE))
505 			REPLACE(9);
506 #undef NDI_BEST
507 #undef NDI_NEW
508 #endif
509 
510 		/*
511 		 * Rule 14: Use longest matching prefix.
512 		 * Note: in the address selection draft, this rule is
513 		 * documented as "Rule 8".  However, since it is also
514 		 * documented that this rule can be overridden, we assign
515 		 * a large number so that it is easy to assign smaller numbers
516 		 * to more preferred rules.
517 		 */
518 		new_matchlen = in6_matchlen(&ia->ia_addr.sin6_addr, &dst);
519 		if (best_matchlen < new_matchlen)
520 			REPLACE(14);
521 		if (new_matchlen < best_matchlen)
522 			NEXT(14);
523 
524 		/* Rule 15 is reserved. */
525 
526 		/*
527 		 * Last resort: just keep the current candidate.
528 		 * Or, do we need more rules?
529 		 */
530 		continue;
531 
532 	  replace:
533 		ia_best = ia;
534 		best_scope = (new_scope >= 0 ? new_scope :
535 			      in6_addrscope(&ia_best->ia_addr.sin6_addr));
536 		best_policy = (new_policy ? new_policy :
537 			       lookup_addrsel_policy(&ia_best->ia_addr));
538 		best_matchlen = (new_matchlen >= 0 ? new_matchlen :
539 				 in6_matchlen(&ia_best->ia_addr.sin6_addr,
540 					      &dst));
541 
542 	  next:
543 		continue;
544 
545 	  out:
546 		break;
547 	}
548 
549 	if ((ia = ia_best) == NULL) {
550 		*errorp = EADDRNOTAVAIL;
551 		return (NULL);
552 	}
553 
554 	return (&ia->ia_addr.sin6_addr);
555 }
556 #undef REPLACE
557 #undef BREAK
558 #undef NEXT
559 
560 static int
561 selectroute(struct sockaddr_in6 *dstsock, struct ip6_pktopts *opts,
562 	struct ip6_moptions *mopts, struct route *ro, struct ifnet **retifp,
563 	struct rtentry **retrt, int clone, int norouteok)
564 {
565 	int error = 0;
566 	struct ifnet *ifp = NULL;
567 	struct rtentry *rt = NULL;
568 	struct sockaddr_in6 *sin6_next;
569 	struct in6_pktinfo *pi = NULL;
570 	struct in6_addr *dst;
571 
572 	dst = &dstsock->sin6_addr;
573 
574 #if 0
575 	if (dstsock->sin6_addr.s6_addr32[0] == 0 &&
576 	    dstsock->sin6_addr.s6_addr32[1] == 0 &&
577 	    !IN6_IS_ADDR_LOOPBACK(&dstsock->sin6_addr)) {
578 		printf("in6_selectroute: strange destination %s\n",
579 		       ip6_sprintf(&dstsock->sin6_addr));
580 	} else {
581 		printf("in6_selectroute: destination = %s%%%d\n",
582 		       ip6_sprintf(&dstsock->sin6_addr),
583 		       dstsock->sin6_scope_id); /* for debug */
584 	}
585 #endif
586 
587 	/* If the caller specify the outgoing interface explicitly, use it. */
588 	if (opts && (pi = opts->ip6po_pktinfo) != NULL && pi->ipi6_ifindex) {
589 		/* XXX boundary check is assumed to be already done. */
590 		ifp = ifindex2ifnet[pi->ipi6_ifindex];
591 		if (ifp != NULL &&
592 		    (norouteok || retrt == NULL ||
593 		    IN6_IS_ADDR_MULTICAST(dst))) {
594 			/*
595 			 * we do not have to check or get the route for
596 			 * multicast.
597 			 */
598 			goto done;
599 		} else
600 			goto getroute;
601 	}
602 
603 	/*
604 	 * If the destination address is a multicast address and the outgoing
605 	 * interface for the address is specified by the caller, use it.
606 	 */
607 	if (IN6_IS_ADDR_MULTICAST(dst) &&
608 	    mopts != NULL && (ifp = mopts->im6o_multicast_ifp) != NULL) {
609 		goto done; /* we do not need a route for multicast. */
610 	}
611 
612   getroute:
613 	/*
614 	 * If the next hop address for the packet is specified by the caller,
615 	 * use it as the gateway.
616 	 */
617 	if (opts && opts->ip6po_nexthop) {
618 		struct route *ron;
619 
620 		sin6_next = satosin6(opts->ip6po_nexthop);
621 
622 		/* at this moment, we only support AF_INET6 next hops */
623 		if (sin6_next->sin6_family != AF_INET6) {
624 			error = EAFNOSUPPORT; /* or should we proceed? */
625 			goto done;
626 		}
627 
628 		/*
629 		 * If the next hop is an IPv6 address, then the node identified
630 		 * by that address must be a neighbor of the sending host.
631 		 */
632 		ron = &opts->ip6po_nextroute;
633 		if ((rt = rtcache_lookup(ron, sin6tosa(sin6_next))) == NULL ||
634 		    (rt->rt_flags & RTF_GATEWAY) != 0 ||
635 		    !nd6_is_addr_neighbor(sin6_next, rt->rt_ifp)) {
636 			rtcache_free(ron);
637 			error = EHOSTUNREACH;
638 			goto done;
639 		}
640 		ifp = rt->rt_ifp;
641 
642 		/*
643 		 * When cloning is required, try to allocate a route to the
644 		 * destination so that the caller can store path MTU
645 		 * information.
646 		 */
647 		if (!clone)
648 			goto done;
649 	}
650 
651 	/*
652 	 * Use a cached route if it exists and is valid, else try to allocate
653 	 * a new one.  Note that we should check the address family of the
654 	 * cached destination, in case of sharing the cache with IPv4.
655 	 */
656 	if (ro != NULL) {
657 		union {
658 			struct sockaddr		dst;
659 			struct sockaddr_in6	dst6;
660 		} u;
661 
662 		/* No route yet, so try to acquire one */
663 		u.dst6 = *dstsock;
664 		u.dst6.sin6_scope_id = 0;
665 		rt = rtcache_lookup1(ro, &u.dst, clone);
666 
667 		/*
668 		 * do not care about the result if we have the nexthop
669 		 * explicitly specified.
670 		 */
671 		if (opts && opts->ip6po_nexthop)
672 			goto done;
673 
674 		if (rt == NULL)
675 			error = EHOSTUNREACH;
676 		else
677 			ifp = rt->rt_ifp;
678 
679 		/*
680 		 * Check if the outgoing interface conflicts with
681 		 * the interface specified by ipi6_ifindex (if specified).
682 		 * Note that loopback interface is always okay.
683 		 * (this may happen when we are sending a packet to one of
684 		 *  our own addresses.)
685 		 */
686 		if (opts && opts->ip6po_pktinfo &&
687 		    opts->ip6po_pktinfo->ipi6_ifindex) {
688 			if (!(ifp->if_flags & IFF_LOOPBACK) &&
689 			    ifp->if_index !=
690 			    opts->ip6po_pktinfo->ipi6_ifindex) {
691 				error = EHOSTUNREACH;
692 				goto done;
693 			}
694 		}
695 	}
696 
697   done:
698 	if (ifp == NULL && rt == NULL) {
699 		/*
700 		 * This can happen if the caller did not pass a cached route
701 		 * nor any other hints.  We treat this case an error.
702 		 */
703 		error = EHOSTUNREACH;
704 	}
705 	if (error == EHOSTUNREACH)
706 		IP6_STATINC(IP6_STAT_NOROUTE);
707 
708 	if (retifp != NULL)
709 		*retifp = ifp;
710 	if (retrt != NULL)
711 		*retrt = rt;	/* rt may be NULL */
712 
713 	return (error);
714 }
715 
716 static int
717 in6_selectif(struct sockaddr_in6 *dstsock, struct ip6_pktopts *opts,
718 	struct ip6_moptions *mopts, struct route *ro, struct ifnet **retifp)
719 {
720 	int error, clone;
721 	struct rtentry *rt = NULL;
722 
723 	clone = IN6_IS_ADDR_MULTICAST(&dstsock->sin6_addr) ? 0 : 1;
724 	if ((error = selectroute(dstsock, opts, mopts, ro, retifp,
725 	    &rt, clone, 1)) != 0) {
726 		return (error);
727 	}
728 
729 	/*
730 	 * do not use a rejected or black hole route.
731 	 * XXX: this check should be done in the L2 output routine.
732 	 * However, if we skipped this check here, we'd see the following
733 	 * scenario:
734 	 * - install a rejected route for a scoped address prefix
735 	 *   (like fe80::/10)
736 	 * - send a packet to a destination that matches the scoped prefix,
737 	 *   with ambiguity about the scope zone.
738 	 * - pick the outgoing interface from the route, and disambiguate the
739 	 *   scope zone with the interface.
740 	 * - ip6_output() would try to get another route with the "new"
741 	 *   destination, which may be valid.
742 	 * - we'd see no error on output.
743 	 * Although this may not be very harmful, it should still be confusing.
744 	 * We thus reject the case here.
745 	 */
746 	if (rt && (rt->rt_flags & (RTF_REJECT | RTF_BLACKHOLE)))
747 		return (rt->rt_flags & RTF_HOST ? EHOSTUNREACH : ENETUNREACH);
748 
749 	/*
750 	 * Adjust the "outgoing" interface.  If we're going to loop the packet
751 	 * back to ourselves, the ifp would be the loopback interface.
752 	 * However, we'd rather know the interface associated to the
753 	 * destination address (which should probably be one of our own
754 	 * addresses.)
755 	 */
756 	if (rt && rt->rt_ifa && rt->rt_ifa->ifa_ifp)
757 		*retifp = rt->rt_ifa->ifa_ifp;
758 
759 	return (0);
760 }
761 
762 /*
763  * close - meaningful only for bsdi and freebsd.
764  */
765 
766 int
767 in6_selectroute(struct sockaddr_in6 *dstsock, struct ip6_pktopts *opts,
768 	struct ip6_moptions *mopts, struct route *ro, struct ifnet **retifp,
769 	struct rtentry **retrt, int clone)
770 {
771 	return selectroute(dstsock, opts, mopts, ro, retifp,
772 	    retrt, clone, 0);
773 }
774 
775 /*
776  * Default hop limit selection. The precedence is as follows:
777  * 1. Hoplimit value specified via ioctl.
778  * 2. (If the outgoing interface is detected) the current
779  *     hop limit of the interface specified by router advertisement.
780  * 3. The system default hoplimit.
781 */
782 int
783 in6_selecthlim(struct in6pcb *in6p, struct ifnet *ifp)
784 {
785 	if (in6p && in6p->in6p_hops >= 0)
786 		return (in6p->in6p_hops);
787 	else if (ifp)
788 		return (ND_IFINFO(ifp)->chlim);
789 	else
790 		return (ip6_defhlim);
791 }
792 
793 /*
794  * Find an empty port and set it to the specified PCB.
795  */
796 int
797 in6_pcbsetport(struct sockaddr_in6 *sin6, struct in6pcb *in6p, struct lwp *l)
798 {
799 	struct socket *so = in6p->in6p_socket;
800 	struct inpcbtable *table = in6p->in6p_table;
801 	int cnt;
802 	u_int16_t minport, maxport;
803 	u_int16_t lport, *lastport;
804 	int wild = 0;
805 	void *t;
806 	int error;
807 	enum kauth_network_req req;
808 
809 	/* XXX: this is redundant when called from in6_pcbbind */
810 	if ((so->so_options & (SO_REUSEADDR|SO_REUSEPORT)) == 0 &&
811 	   ((so->so_proto->pr_flags & PR_CONNREQUIRED) == 0 ||
812 	    (so->so_options & SO_ACCEPTCONN) == 0))
813 		wild = 1;
814 
815 	if (in6p->in6p_flags & IN6P_LOWPORT) {
816 #ifndef IPNOPRIVPORTS
817 		req = KAUTH_REQ_NETWORK_BIND_PRIVPORT;
818 #else
819 		req = KAUTH_REQ_NETWORK_BIND_PORT;
820 #endif
821 
822 		minport = ip6_lowportmin;
823 		maxport = ip6_lowportmax;
824 		lastport = &table->inpt_lastlow;
825 	} else {
826 		req = KAUTH_REQ_NETWORK_BIND_PORT;
827 
828 		minport = ip6_anonportmin;
829 		maxport = ip6_anonportmax;
830 		lastport = &table->inpt_lastport;
831 	}
832 
833 	/* XXX-kauth: KAUTH_REQ_NETWORK_BIND_AUTOASSIGN_{,PRIV}PORT */
834 	error = kauth_authorize_network(l->l_cred, KAUTH_NETWORK_BIND, req, so,
835 	    sin6, NULL);
836 	if (error)
837 		return (EACCES);
838 
839 	if (minport > maxport) {	/* sanity check */
840 		u_int16_t swp;
841 
842 		swp = minport;
843 		minport = maxport;
844 		maxport = swp;
845 	}
846 
847 	lport = *lastport - 1;
848 	for (cnt = maxport - minport + 1; cnt; cnt--, lport--) {
849 		if (lport < minport || lport > maxport)
850 			lport = maxport;
851 #ifdef INET
852 		if (IN6_IS_ADDR_V4MAPPED(&sin6->sin6_addr)) {
853 			t = in_pcblookup_port(table,
854 			    *(struct in_addr *)&sin6->sin6_addr.s6_addr32[3],
855 			    htons(lport), wild);
856 		} else
857 #endif
858 		{
859 			t = in6_pcblookup_port(table, &sin6->sin6_addr,
860 			    htons(lport), wild);
861 		}
862 		if (t == 0) {
863 			/* We have a free port. Check with the secmodel. */
864 			sin6->sin6_port = lport;
865 			error = kauth_authorize_network(l->l_cred,
866 			    KAUTH_NETWORK_BIND, req, so, sin6, NULL);
867 			if (error) {
868 				/* Secmodel says no. Keep looking. */
869 				continue;
870 			}
871 
872 			goto found;
873 		}
874 	}
875 
876 	return (EAGAIN);
877 
878 found:
879 	in6p->in6p_flags |= IN6P_ANONPORT;
880 	*lastport = lport;
881 	in6p->in6p_lport = htons(lport);
882 	in6_pcbstate(in6p, IN6P_BOUND);
883 	return (0);		/* success */
884 }
885 
886 void
887 addrsel_policy_init(void)
888 {
889 	init_policy_queue();
890 
891 	/* initialize the "last resort" policy */
892 	memset(&defaultaddrpolicy, 0, sizeof(defaultaddrpolicy));
893 	defaultaddrpolicy.label = ADDR_LABEL_NOTAPP;
894 }
895 
896 static struct in6_addrpolicy *
897 lookup_addrsel_policy(struct sockaddr_in6 *key)
898 {
899 	struct in6_addrpolicy *match = NULL;
900 
901 	match = match_addrsel_policy(key);
902 
903 	if (match == NULL)
904 		match = &defaultaddrpolicy;
905 	else
906 		match->use++;
907 
908 	return (match);
909 }
910 
911 /*
912  * Subroutines to manage the address selection policy table via sysctl.
913  */
914 struct sel_walkarg {
915 	size_t	w_total;
916 	size_t	w_given;
917 	void *	w_where;
918 	void *w_limit;
919 };
920 
921 int
922 in6_src_sysctl(void *oldp, size_t *oldlenp, void *newp, size_t newlen)
923 {
924 	int error = 0;
925 	int s;
926 
927 	s = splsoftnet();
928 
929 	if (newp) {
930 		error = EPERM;
931 		goto end;
932 	}
933 	if (oldp && oldlenp == NULL) {
934 		error = EINVAL;
935 		goto end;
936 	}
937 	if (oldp || oldlenp) {
938 		struct sel_walkarg w;
939 		size_t oldlen = *oldlenp;
940 
941 		memset(&w, 0, sizeof(w));
942 		w.w_given = oldlen;
943 		w.w_where = oldp;
944 		if (oldp)
945 			w.w_limit = (char *)oldp + oldlen;
946 
947 		error = walk_addrsel_policy(dump_addrsel_policyent, &w);
948 
949 		*oldlenp = w.w_total;
950 		if (oldp && w.w_total > oldlen && error == 0)
951 			error = ENOMEM;
952 	}
953 
954   end:
955 	splx(s);
956 
957 	return (error);
958 }
959 
960 int
961 in6_src_ioctl(u_long cmd, void *data)
962 {
963 	int i;
964 	struct in6_addrpolicy ent0;
965 
966 	if (cmd != SIOCAADDRCTL_POLICY && cmd != SIOCDADDRCTL_POLICY)
967 		return (EOPNOTSUPP); /* check for safety */
968 
969 	ent0 = *(struct in6_addrpolicy *)data;
970 
971 	if (ent0.label == ADDR_LABEL_NOTAPP)
972 		return (EINVAL);
973 	/* check if the prefix mask is consecutive. */
974 	if (in6_mask2len(&ent0.addrmask.sin6_addr, NULL) < 0)
975 		return (EINVAL);
976 	/* clear trailing garbages (if any) of the prefix address. */
977 	for (i = 0; i < 4; i++) {
978 		ent0.addr.sin6_addr.s6_addr32[i] &=
979 			ent0.addrmask.sin6_addr.s6_addr32[i];
980 	}
981 	ent0.use = 0;
982 
983 	switch (cmd) {
984 	case SIOCAADDRCTL_POLICY:
985 		return (add_addrsel_policyent(&ent0));
986 	case SIOCDADDRCTL_POLICY:
987 		return (delete_addrsel_policyent(&ent0));
988 	}
989 
990 	return (0);		/* XXX: compromise compilers */
991 }
992 
993 /*
994  * The followings are implementation of the policy table using a
995  * simple tail queue.
996  * XXX such details should be hidden.
997  * XXX implementation using binary tree should be more efficient.
998  */
999 struct addrsel_policyent {
1000 	TAILQ_ENTRY(addrsel_policyent) ape_entry;
1001 	struct in6_addrpolicy ape_policy;
1002 };
1003 
1004 TAILQ_HEAD(addrsel_policyhead, addrsel_policyent);
1005 
1006 struct addrsel_policyhead addrsel_policytab;
1007 
1008 static void
1009 init_policy_queue(void)
1010 {
1011 	TAILQ_INIT(&addrsel_policytab);
1012 }
1013 
1014 static int
1015 add_addrsel_policyent(struct in6_addrpolicy *newpolicy)
1016 {
1017 	struct addrsel_policyent *new, *pol;
1018 
1019 	/* duplication check */
1020 	for (pol = TAILQ_FIRST(&addrsel_policytab); pol;
1021 	     pol = TAILQ_NEXT(pol, ape_entry)) {
1022 		if (IN6_ARE_ADDR_EQUAL(&newpolicy->addr.sin6_addr,
1023 		    &pol->ape_policy.addr.sin6_addr) &&
1024 		    IN6_ARE_ADDR_EQUAL(&newpolicy->addrmask.sin6_addr,
1025 		    &pol->ape_policy.addrmask.sin6_addr)) {
1026 			return (EEXIST);	/* or override it? */
1027 		}
1028 	}
1029 
1030 	new = malloc(sizeof(*new), M_IFADDR, M_WAITOK|M_ZERO);
1031 
1032 	/* XXX: should validate entry */
1033 	new->ape_policy = *newpolicy;
1034 
1035 	TAILQ_INSERT_TAIL(&addrsel_policytab, new, ape_entry);
1036 
1037 	return (0);
1038 }
1039 
1040 static int
1041 delete_addrsel_policyent(struct in6_addrpolicy *key)
1042 {
1043 	struct addrsel_policyent *pol;
1044 
1045 	/* search for the entry in the table */
1046 	for (pol = TAILQ_FIRST(&addrsel_policytab); pol;
1047 	     pol = TAILQ_NEXT(pol, ape_entry)) {
1048 		if (IN6_ARE_ADDR_EQUAL(&key->addr.sin6_addr,
1049 		    &pol->ape_policy.addr.sin6_addr) &&
1050 		    IN6_ARE_ADDR_EQUAL(&key->addrmask.sin6_addr,
1051 		    &pol->ape_policy.addrmask.sin6_addr)) {
1052 			break;
1053 		}
1054 	}
1055 	if (pol == NULL) {
1056 		return (ESRCH);
1057 	}
1058 
1059 	TAILQ_REMOVE(&addrsel_policytab, pol, ape_entry);
1060 
1061 	return (0);
1062 }
1063 
1064 static int
1065 walk_addrsel_policy(int (*callback)(struct in6_addrpolicy *, void *), void *w)
1066 {
1067 	struct addrsel_policyent *pol;
1068 	int error = 0;
1069 
1070 	TAILQ_FOREACH(pol, &addrsel_policytab, ape_entry) {
1071 		if ((error = (*callback)(&pol->ape_policy, w)) != 0)
1072 			return error;
1073 	}
1074 
1075 	return error;
1076 }
1077 
1078 static int
1079 dump_addrsel_policyent(struct in6_addrpolicy *pol, void *arg)
1080 {
1081 	int error = 0;
1082 	struct sel_walkarg *w = arg;
1083 
1084 	if (w->w_where && (char *)w->w_where + sizeof(*pol) <= (char *)w->w_limit) {
1085 		if ((error = copyout(pol, w->w_where, sizeof(*pol))) != 0)
1086 			return error;
1087 		w->w_where = (char *)w->w_where + sizeof(*pol);
1088 	}
1089 	w->w_total += sizeof(*pol);
1090 
1091 	return error;
1092 }
1093 
1094 static struct in6_addrpolicy *
1095 match_addrsel_policy(struct sockaddr_in6 *key)
1096 {
1097 	struct addrsel_policyent *pent;
1098 	struct in6_addrpolicy *bestpol = NULL, *pol;
1099 	int matchlen, bestmatchlen = -1;
1100 	u_char *mp, *ep, *k, *p, m;
1101 
1102 	for (pent = TAILQ_FIRST(&addrsel_policytab); pent;
1103 	     pent = TAILQ_NEXT(pent, ape_entry)) {
1104 		matchlen = 0;
1105 
1106 		pol = &pent->ape_policy;
1107 		mp = (u_char *)&pol->addrmask.sin6_addr;
1108 		ep = mp + 16;	/* XXX: scope field? */
1109 		k = (u_char *)&key->sin6_addr;
1110 		p = (u_char *)&pol->addr.sin6_addr;
1111 		for (; mp < ep && *mp; mp++, k++, p++) {
1112 			m = *mp;
1113 			if ((*k & m) != *p)
1114 				goto next; /* not match */
1115 			if (m == 0xff) /* short cut for a typical case */
1116 				matchlen += 8;
1117 			else {
1118 				while (m >= 0x80) {
1119 					matchlen++;
1120 					m <<= 1;
1121 				}
1122 			}
1123 		}
1124 
1125 		/* matched.  check if this is better than the current best. */
1126 		if (bestpol == NULL ||
1127 		    matchlen > bestmatchlen) {
1128 			bestpol = pol;
1129 			bestmatchlen = matchlen;
1130 		}
1131 
1132 	  next:
1133 		continue;
1134 	}
1135 
1136 	return (bestpol);
1137 }
1138