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