xref: /dragonfly/sys/netinet6/in6_pcb.c (revision 61c0377f)
1 /*	$FreeBSD: src/sys/netinet6/in6_pcb.c,v 1.10.2.9 2003/01/24 05:11:35 sam Exp $	*/
2 /*	$KAME: in6_pcb.c,v 1.31 2001/05/21 05:45:10 jinmei 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 /*
35  * Copyright (c) 1982, 1986, 1991, 1993
36  *	The Regents of the University of California.  All rights reserved.
37  *
38  * Redistribution and use in source and binary forms, with or without
39  * modification, are permitted provided that the following conditions
40  * are met:
41  * 1. Redistributions of source code must retain the above copyright
42  *    notice, this list of conditions and the following disclaimer.
43  * 2. Redistributions in binary form must reproduce the above copyright
44  *    notice, this list of conditions and the following disclaimer in the
45  *    documentation and/or other materials provided with the distribution.
46  * 3. Neither the name of the University nor the names of its contributors
47  *    may be used to endorse or promote products derived from this software
48  *    without specific prior written permission.
49  *
50  * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
51  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
52  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
53  * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
54  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
55  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
56  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
57  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
58  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
59  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
60  * SUCH DAMAGE.
61  *
62  *	@(#)in_pcb.c	8.2 (Berkeley) 1/4/94
63  */
64 
65 #include "opt_inet.h"
66 #include "opt_inet6.h"
67 #include "opt_ipsec.h"
68 
69 #include <sys/param.h>
70 #include <sys/systm.h>
71 #include <sys/malloc.h>
72 #include <sys/mbuf.h>
73 #include <sys/domain.h>
74 #include <sys/protosw.h>
75 #include <sys/socket.h>
76 #include <sys/socketvar.h>
77 #include <sys/sockio.h>
78 #include <sys/errno.h>
79 #include <sys/time.h>
80 #include <sys/proc.h>
81 #include <sys/priv.h>
82 #include <sys/jail.h>
83 
84 #include <sys/thread2.h>
85 #include <sys/msgport2.h>
86 
87 #include <vm/vm_zone.h>
88 
89 #include <net/if.h>
90 #include <net/if_types.h>
91 #include <net/route.h>
92 
93 #include <netinet/in.h>
94 #include <netinet/in_var.h>
95 #include <netinet/in_systm.h>
96 #include <netinet/ip6.h>
97 #include <netinet/ip_var.h>
98 #include <netinet6/ip6_var.h>
99 #include <netinet6/nd6.h>
100 #include <netinet/in_pcb.h>
101 #include <netinet6/in6_pcb.h>
102 
103 #ifdef IPSEC
104 #include <netinet6/ipsec.h>
105 #ifdef INET6
106 #include <netinet6/ipsec6.h>
107 #endif
108 #include <netinet6/ah.h>
109 #ifdef INET6
110 #include <netinet6/ah6.h>
111 #endif
112 #include <netproto/key/key.h>
113 #endif /* IPSEC */
114 
115 #ifdef FAST_IPSEC
116 #include <netproto/ipsec/ipsec.h>
117 #include <netproto/ipsec/ipsec6.h>
118 #include <netproto/ipsec/key.h>
119 #define	IPSEC
120 #endif /* FAST_IPSEC */
121 
122 struct	in6_addr zeroin6_addr;
123 
124 int
125 in6_pcbbind(struct inpcb *inp, struct sockaddr *nam, struct thread *td)
126 {
127 	struct socket *so = inp->inp_socket;
128 	struct sockaddr_in6 jsin6;
129 	int error;
130 
131 	if (!in6_ifaddr) /* XXX broken! */
132 		return (EADDRNOTAVAIL);
133 	if (inp->inp_lport || !IN6_IS_ADDR_UNSPECIFIED(&inp->in6p_laddr))
134 		return (EINVAL);
135 
136 	if (nam) {
137 		struct sockaddr_in6 *sin6 = (struct sockaddr_in6 *)nam;
138 		struct inpcbinfo *pcbinfo;
139 		struct inpcbportinfo *portinfo;
140 		int wild = 0, reuseport = (so->so_options & SO_REUSEPORT);
141 		struct ucred *cred = NULL;
142 		struct inpcb *t;
143 		u_short	lport, lport_ho;
144 
145 		if ((so->so_options & (SO_REUSEADDR|SO_REUSEPORT)) == 0)
146 			wild = 1;
147 		if (td->td_proc != NULL)
148 			cred = td->td_proc->p_ucred;
149 
150 		if (nam->sa_len != sizeof(*sin6))
151 			return (EINVAL);
152 		/*
153 		 * family check.
154 		 */
155 		if (nam->sa_family != AF_INET6)
156 			return (EAFNOSUPPORT);
157 
158 		if (!prison_replace_wildcards(td, nam))
159 			return (EINVAL);
160 
161 		/* KAME hack: embed scopeid */
162 		if (in6_embedscope(&sin6->sin6_addr, sin6, inp, NULL) != 0)
163 			return (EINVAL);
164 		/* this must be cleared for ifa_ifwithaddr() */
165 		sin6->sin6_scope_id = 0;
166 
167 		lport = sin6->sin6_port;
168 		if (IN6_IS_ADDR_MULTICAST(&sin6->sin6_addr)) {
169 			/*
170 			 * Treat SO_REUSEADDR as SO_REUSEPORT for multicast;
171 			 * allow compepte duplication of binding if
172 			 * SO_REUSEPORT is set, or if SO_REUSEADDR is set
173 			 * and a multicast address is bound on both
174 			 * new and duplicated sockets.
175 			 */
176 			if (so->so_options & SO_REUSEADDR)
177 				reuseport = SO_REUSEADDR|SO_REUSEPORT;
178 		} else if (!IN6_IS_ADDR_UNSPECIFIED(&sin6->sin6_addr)) {
179 			struct ifaddr *ia = NULL;
180 
181 			sin6->sin6_port = 0;		/* yech... */
182 			if (!prison_replace_wildcards(td, (struct sockaddr *)sin6)) {
183 				sin6->sin6_addr = kin6addr_any;
184 				return (EINVAL);
185 			}
186 			if ((ia = ifa_ifwithaddr((struct sockaddr *)sin6)) == NULL)
187 				return (EADDRNOTAVAIL);
188 
189 			/*
190 			 * XXX: bind to an anycast address might accidentally
191 			 * cause sending a packet with anycast source address.
192 			 * We should allow to bind to a deprecated address, since
193 			 * the application dare to use it.
194 			 */
195 			if (ia &&
196 			    ((struct in6_ifaddr *)ia)->ia6_flags &
197 			    (IN6_IFF_ANYCAST|IN6_IFF_NOTREADY|IN6_IFF_DETACHED))
198 				return (EADDRNOTAVAIL);
199 		}
200 
201 		inp->in6p_laddr = sin6->sin6_addr;
202 
203 		if (lport == 0)
204 			goto auto_select;
205 		lport_ho = ntohs(lport);
206 
207 		/* GROSS */
208 		if (lport_ho < IPV6PORT_RESERVED && cred &&
209 		    priv_check_cred(cred, PRIV_NETINET_RESERVEDPORT, 0)) {
210 			inp->in6p_laddr = kin6addr_any;
211 			return (EACCES);
212 		}
213 
214 		/*
215 		 * Locate the proper portinfo based on lport
216 		 */
217 		pcbinfo = inp->inp_pcbinfo;
218 		portinfo =
219 		    &pcbinfo->portinfo[lport_ho & pcbinfo->portinfo_mask];
220 		KKASSERT((lport_ho & pcbinfo->portinfo_mask) ==
221 		    portinfo->offset);
222 
223 		/*
224 		 * This has to be atomic.  If the porthash is shared across
225 		 * multiple protocol threads (aka tcp) then the token must
226 		 * be held.
227 		 */
228 		GET_PORT_TOKEN(portinfo);
229 
230 		if (so->so_cred->cr_uid != 0 &&
231 		    !IN6_IS_ADDR_MULTICAST(&sin6->sin6_addr)) {
232 			t = in6_pcblookup_local(portinfo,
233 			    &sin6->sin6_addr, lport, INPLOOKUP_WILDCARD, cred);
234 			if (t &&
235 			    (!IN6_IS_ADDR_UNSPECIFIED(&sin6->sin6_addr) ||
236 			     !IN6_IS_ADDR_UNSPECIFIED(&t->in6p_laddr) ||
237 			     (t->inp_socket->so_options & SO_REUSEPORT) == 0) &&
238 			    (so->so_cred->cr_uid !=
239 			     t->inp_socket->so_cred->cr_uid)) {
240 				inp->in6p_laddr = kin6addr_any;
241 				error = EADDRINUSE;
242 				goto done;
243 			}
244 			if ((inp->inp_flags & IN6P_IPV6_V6ONLY) == 0 &&
245 			    IN6_IS_ADDR_UNSPECIFIED(&sin6->sin6_addr)) {
246 				struct sockaddr_in sin;
247 
248 				in6_sin6_2_sin(&sin, sin6);
249 				t = in_pcblookup_local(portinfo,
250 				    sin.sin_addr, lport,
251 				    INPLOOKUP_WILDCARD, cred);
252 				if (t &&
253 				    (so->so_cred->cr_uid !=
254 				     t->inp_socket->so_cred->cr_uid) &&
255 				    (ntohl(t->inp_laddr.s_addr) != INADDR_ANY ||
256 				     INP_SOCKAF(so) ==
257 				     INP_SOCKAF(t->inp_socket))) {
258 					inp->in6p_laddr = kin6addr_any;
259 					error = EADDRINUSE;
260 					goto done;
261 				}
262 			}
263 		}
264 		if (cred && cred->cr_prison &&
265 		    !prison_replace_wildcards(td, nam)) {
266 			inp->in6p_laddr = kin6addr_any;
267 			error = EADDRNOTAVAIL;
268 			goto done;
269 		}
270 		t = in6_pcblookup_local(portinfo, &sin6->sin6_addr, lport,
271 		    wild, cred);
272 		if (t && (reuseport & t->inp_socket->so_options) == 0) {
273 			inp->in6p_laddr = kin6addr_any;
274 			error = EADDRINUSE;
275 			goto done;
276 		}
277 		if ((inp->inp_flags & IN6P_IPV6_V6ONLY) == 0 &&
278 		    IN6_IS_ADDR_UNSPECIFIED(&sin6->sin6_addr)) {
279 			struct sockaddr_in sin;
280 
281 			in6_sin6_2_sin(&sin, sin6);
282 			t = in_pcblookup_local(portinfo, sin.sin_addr, lport,
283 			    wild, cred);
284 			if (t && (reuseport & t->inp_socket->so_options) == 0 &&
285 			    (ntohl(t->inp_laddr.s_addr) != INADDR_ANY ||
286 			     INP_SOCKAF(so) == INP_SOCKAF(t->inp_socket))) {
287 				inp->in6p_laddr = kin6addr_any;
288 				error = EADDRINUSE;
289 				goto done;
290 			}
291 		}
292 
293 		inp->inp_lport = lport;
294 		in_pcbinsporthash(portinfo, inp);
295 		error = 0;
296 done:
297 		REL_PORT_TOKEN(portinfo);
298 		return (error);
299 	} else {
300 auto_select:
301 		jsin6.sin6_addr = inp->in6p_laddr;
302 		jsin6.sin6_family = AF_INET6;
303 		if (!prison_replace_wildcards(td, (struct sockaddr*)&jsin6)) {
304 			inp->in6p_laddr = kin6addr_any;
305 			inp->inp_lport = 0;
306 			return (EINVAL);
307 		}
308 
309 		return in6_pcbsetlport(&inp->in6p_laddr, inp, td);
310 	}
311 }
312 
313 /*
314  *   Transform old in6_pcbconnect() into an inner subroutine for new
315  *   in6_pcbconnect(): Do some validity-checking on the remote
316  *   address (in mbuf 'nam') and then determine local host address
317  *   (i.e., which interface) to use to access that remote host.
318  *
319  *   This preserves definition of in6_pcbconnect(), while supporting a
320  *   slightly different version for T/TCP.  (This is more than
321  *   a bit of a kludge, but cleaning up the internal interfaces would
322  *   have forced minor changes in every protocol).
323  */
324 
325 int
326 in6_pcbladdr(struct inpcb *inp, struct sockaddr *nam,
327 	     struct in6_addr **plocal_addr6, struct thread *td)
328 {
329 	struct sockaddr_in6 *sin6 = (struct sockaddr_in6 *)nam;
330 	struct ifnet *ifp = NULL;
331 	int error = 0;
332 
333 	if (nam->sa_len != sizeof (*sin6))
334 		return (EINVAL);
335 	if (sin6->sin6_family != AF_INET6)
336 		return (EAFNOSUPPORT);
337 	if (sin6->sin6_port == 0)
338 		return (EADDRNOTAVAIL);
339 
340 	/* KAME hack: embed scopeid */
341 	if (in6_embedscope(&sin6->sin6_addr, sin6, inp, &ifp) != 0)
342 		return EINVAL;
343 
344 	if (in6_ifaddr) {
345 		/*
346 		 * If the destination address is UNSPECIFIED addr,
347 		 * use the loopback addr, e.g ::1.
348 		 */
349 		if (IN6_IS_ADDR_UNSPECIFIED(&sin6->sin6_addr))
350 			sin6->sin6_addr = kin6addr_loopback;
351 	}
352 	{
353 		/*
354 		 * XXX: in6_selectsrc might replace the bound local address
355 		 * with the address specified by setsockopt(IPV6_PKTINFO).
356 		 * Is it the intended behavior?
357 		 */
358 		*plocal_addr6 = in6_selectsrc(sin6, inp->in6p_outputopts,
359 					      inp->in6p_moptions,
360 					      &inp->in6p_route,
361 					      &inp->in6p_laddr, &error, td);
362 		if (*plocal_addr6 == NULL) {
363 			if (error == 0)
364 				error = EADDRNOTAVAIL;
365 			return (error);
366 		}
367 		/*
368 		 * Don't do pcblookup call here; return interface in
369 		 * plocal_addr6
370 		 * and exit to caller, that will do the lookup.
371 		 */
372 	}
373 
374 	if (inp->in6p_route.ro_rt)
375 		ifp = inp->in6p_route.ro_rt->rt_ifp;
376 
377 	return (0);
378 }
379 
380 /*
381  * Outer subroutine:
382  * Connect from a socket to a specified address.
383  * Both address and port must be specified in argument sin.
384  * If don't have a local address for this socket yet,
385  * then pick one.
386  */
387 int
388 in6_pcbconnect(struct inpcb *inp, struct sockaddr *nam, struct thread *td)
389 {
390 	struct in6_addr *addr6;
391 	struct sockaddr_in6 *sin6 = (struct sockaddr_in6 *)nam;
392 	int error;
393 
394 	/*
395 	 * Call inner routine, to assign local interface address.
396 	 * in6_pcbladdr() may automatically fill in sin6_scope_id.
397 	 */
398 	if ((error = in6_pcbladdr(inp, nam, &addr6, td)) != 0)
399 		return (error);
400 
401 	if (in6_pcblookup_hash(inp->inp_cpcbinfo, &sin6->sin6_addr,
402 			       sin6->sin6_port,
403 			      IN6_IS_ADDR_UNSPECIFIED(&inp->in6p_laddr)
404 			      ? addr6 : &inp->in6p_laddr,
405 			      inp->inp_lport, 0, NULL) != NULL) {
406 		return (EADDRINUSE);
407 	}
408 	if (IN6_IS_ADDR_UNSPECIFIED(&inp->in6p_laddr)) {
409 		if (inp->inp_lport == 0) {
410 			error = in6_pcbbind(inp, NULL, td);
411 			if (error)
412 				return (error);
413 		}
414 		inp->in6p_laddr = *addr6;
415 	}
416 	inp->in6p_faddr = sin6->sin6_addr;
417 	inp->inp_fport = sin6->sin6_port;
418 	/* update flowinfo - draft-itojun-ipv6-flowlabel-api-00 */
419 	inp->in6p_flowinfo &= ~IPV6_FLOWLABEL_MASK;
420 	if (inp->in6p_flags & IN6P_AUTOFLOWLABEL)
421 		inp->in6p_flowinfo |=
422 		    (htonl(ip6_flow_seq++) & IPV6_FLOWLABEL_MASK);
423 
424 	in_pcbinsconnhash(inp);
425 	return (0);
426 }
427 
428 #if 0
429 /*
430  * Return an IPv6 address, which is the most appropriate for given
431  * destination and user specified options.
432  * If necessary, this function lookups the routing table and return
433  * an entry to the caller for later use.
434  */
435 struct in6_addr *
436 in6_selectsrc(struct sockaddr_in6 *dstsock, struct ip6_pktopts *opts,
437 	      struct ip6_moptions *mopts, struct route_in6 *ro,
438 	      struct in6_addr *laddr, int *errorp, struct thread *td)
439 {
440 	struct sockaddr_in6 jsin6;
441 	struct ucred *cred = NULL;
442 	struct in6_addr *dst;
443 	struct in6_ifaddr *ia6 = 0;
444 	struct in6_pktinfo *pi = NULL;
445 	int jailed = 0;
446 
447 	if (td && td->td_proc && td->td_proc->p_ucred)
448 		cred = td->td_proc->p_ucred;
449 	if (cred && cred->cr_prison)
450 		jailed = 1;
451 	jsin6.sin6_family = AF_INET6;
452 	dst = &dstsock->sin6_addr;
453 	*errorp = 0;
454 
455 	/*
456 	 * If the source address is explicitly specified by the caller,
457 	 * use it.
458 	 */
459 	if (opts && (pi = opts->ip6po_pktinfo) &&
460 	    !IN6_IS_ADDR_UNSPECIFIED(&pi->ipi6_addr)) {
461 		jsin6.sin6_addr = pi->ipi6_addr;
462 		if (jailed && !jailed_ip(cred->cr_prison,
463 		    (struct sockaddr *)&jsin6)) {
464 			return(0);
465 		} else {
466 			return (&pi->ipi6_addr);
467 		}
468 	}
469 
470 	/*
471 	 * If the source address is not specified but the socket(if any)
472 	 * is already bound, use the bound address.
473 	 */
474 	if (laddr && !IN6_IS_ADDR_UNSPECIFIED(laddr)) {
475 		jsin6.sin6_addr = *laddr;
476 		if (jailed && !jailed_ip(cred->cr_prison,
477 		    (struct sockaddr *)&jsin6)) {
478 			return(0);
479 		} else {
480 			return (laddr);
481 		}
482 	}
483 
484 	/*
485 	 * If the caller doesn't specify the source address but
486 	 * the outgoing interface, use an address associated with
487 	 * the interface.
488 	 */
489 	if (pi && pi->ipi6_ifindex) {
490 		/* XXX boundary check is assumed to be already done. */
491 		ia6 = in6_ifawithscope(ifindex2ifnet[pi->ipi6_ifindex],
492 				       dst, cred);
493 
494 		if (ia6 && jailed) {
495 			jsin6.sin6_addr = (&ia6->ia_addr)->sin6_addr;
496 			if (!jailed_ip(cred->cr_prison,
497 				(struct sockaddr *)&jsin6))
498 				ia6 = 0;
499 		}
500 
501 		if (ia6 == 0) {
502 			*errorp = EADDRNOTAVAIL;
503 			return (0);
504 		}
505 		return (&satosin6(&ia6->ia_addr)->sin6_addr);
506 	}
507 
508 	/*
509 	 * If the destination address is a link-local unicast address or
510 	 * a multicast address, and if the outgoing interface is specified
511 	 * by the sin6_scope_id filed, use an address associated with the
512 	 * interface.
513 	 * XXX: We're now trying to define more specific semantics of
514 	 *      sin6_scope_id field, so this part will be rewritten in
515 	 *      the near future.
516 	 */
517 	if ((IN6_IS_ADDR_LINKLOCAL(dst) || IN6_IS_ADDR_MULTICAST(dst)) &&
518 	    dstsock->sin6_scope_id) {
519 		/*
520 		 * I'm not sure if boundary check for scope_id is done
521 		 * somewhere...
522 		 */
523 		if (dstsock->sin6_scope_id < 0 ||
524 		    if_index < dstsock->sin6_scope_id) {
525 			*errorp = ENXIO; /* XXX: better error? */
526 			return (0);
527 		}
528 		ia6 = in6_ifawithscope(ifindex2ifnet[dstsock->sin6_scope_id],
529 				       dst, cred);
530 
531 		if (ia6 && jailed) {
532 			jsin6.sin6_addr = (&ia6->ia_addr)->sin6_addr;
533 			if (!jailed_ip(cred->cr_prison,
534 				(struct sockaddr *)&jsin6))
535 				ia6 = 0;
536 		}
537 
538 		if (ia6 == 0) {
539 			*errorp = EADDRNOTAVAIL;
540 			return (0);
541 		}
542 		return (&satosin6(&ia6->ia_addr)->sin6_addr);
543 	}
544 
545 	/*
546 	 * If the destination address is a multicast address and
547 	 * the outgoing interface for the address is specified
548 	 * by the caller, use an address associated with the interface.
549 	 * There is a sanity check here; if the destination has node-local
550 	 * scope, the outgoing interfacde should be a loopback address.
551 	 * Even if the outgoing interface is not specified, we also
552 	 * choose a loopback interface as the outgoing interface.
553 	 */
554 	if (!jailed && IN6_IS_ADDR_MULTICAST(dst)) {
555 		struct ifnet *ifp = mopts ? mopts->im6o_multicast_ifp : NULL;
556 
557 		if (ifp == NULL && IN6_IS_ADDR_MC_NODELOCAL(dst)) {
558 			ifp = &loif[0];
559 		}
560 
561 		if (ifp) {
562 			ia6 = in6_ifawithscope(ifp, dst, cred);
563 			if (ia6 == 0) {
564 				*errorp = EADDRNOTAVAIL;
565 				return (0);
566 			}
567 			return (&ia6->ia_addr.sin6_addr);
568 		}
569 	}
570 
571 	/*
572 	 * If the next hop address for the packet is specified
573 	 * by caller, use an address associated with the route
574 	 * to the next hop.
575 	 */
576 	{
577 		struct sockaddr_in6 *sin6_next;
578 		struct rtentry *rt;
579 
580 		if (opts && opts->ip6po_nexthop) {
581 			sin6_next = satosin6(opts->ip6po_nexthop);
582 			rt = nd6_lookup(&sin6_next->sin6_addr, 1, NULL);
583 			if (rt) {
584 				ia6 = in6_ifawithscope(rt->rt_ifp, dst, cred);
585 				if (ia6 == 0)
586 					ia6 = ifatoia6(rt->rt_ifa);
587 			}
588 			if (ia6 && jailed) {
589 				jsin6.sin6_addr = (&ia6->ia_addr)->sin6_addr;
590 				if (!jailed_ip(cred->cr_prison,
591 					(struct sockaddr *)&jsin6))
592 					ia6 = 0;
593 			}
594 
595 			if (ia6 == 0) {
596 				*errorp = EADDRNOTAVAIL;
597 				return (0);
598 			}
599 			return (&satosin6(&ia6->ia_addr)->sin6_addr);
600 		}
601 	}
602 
603 	/*
604 	 * If route is known or can be allocated now,
605 	 * our src addr is taken from the i/f, else punt.
606 	 */
607 	if (ro) {
608 		if (ro->ro_rt &&
609 		    !IN6_ARE_ADDR_EQUAL(&satosin6(&ro->ro_dst)->sin6_addr, dst)) {
610 			RTFREE(ro->ro_rt);
611 			ro->ro_rt = NULL;
612 		}
613 		if (ro->ro_rt == NULL || ro->ro_rt->rt_ifp == NULL) {
614 			struct sockaddr_in6 *dst6;
615 
616 			/* No route yet, so try to acquire one */
617 			bzero(&ro->ro_dst, sizeof(struct sockaddr_in6));
618 			dst6 = &ro->ro_dst;
619 			dst6->sin6_family = AF_INET6;
620 			dst6->sin6_len = sizeof(struct sockaddr_in6);
621 			dst6->sin6_addr = *dst;
622 			if (!jailed && IN6_IS_ADDR_MULTICAST(dst)) {
623 				ro->ro_rt =
624 				  rtpurelookup((struct sockaddr *)&ro->ro_dst);
625 			} else {
626 				rtalloc((struct route *)ro);
627 			}
628 		}
629 
630 		/*
631 		 * in_pcbconnect() checks out IFF_LOOPBACK to skip using
632 		 * the address. But we don't know why it does so.
633 		 * It is necessary to ensure the scope even for lo0
634 		 * so doesn't check out IFF_LOOPBACK.
635 		 */
636 
637 		if (ro->ro_rt) {
638 			ia6 = in6_ifawithscope(ro->ro_rt->rt_ifa->ifa_ifp, dst, cred);
639 			if (ia6 && jailed) {
640 				jsin6.sin6_addr = (&ia6->ia_addr)->sin6_addr;
641 				if (!jailed_ip(cred->cr_prison,
642 					(struct sockaddr *)&jsin6))
643 					ia6 = 0;
644 			}
645 
646 			if (ia6 == 0) /* xxx scope error ?*/
647 				ia6 = ifatoia6(ro->ro_rt->rt_ifa);
648 
649 			if (ia6 && jailed) {
650 				jsin6.sin6_addr = (&ia6->ia_addr)->sin6_addr;
651 				if (!jailed_ip(cred->cr_prison,
652 					(struct sockaddr *)&jsin6))
653 					ia6 = 0;
654 			}
655 		}
656 		if (ia6 == 0) {
657 			*errorp = EHOSTUNREACH;	/* no route */
658 			return (0);
659 		}
660 		return (&satosin6(&ia6->ia_addr)->sin6_addr);
661 	}
662 
663 	*errorp = EADDRNOTAVAIL;
664 	return (0);
665 }
666 
667 /*
668  * Default hop limit selection. The precedence is as follows:
669  * 1. Hoplimit valued specified via ioctl.
670  * 2. (If the outgoing interface is detected) the current
671  *     hop limit of the interface specified by router advertisement.
672  * 3. The system default hoplimit.
673 */
674 int
675 in6_selecthlim(struct in6pcb *in6p, struct ifnet *ifp)
676 {
677 	if (in6p && in6p->in6p_hops >= 0)
678 		return (in6p->in6p_hops);
679 	else if (ifp)
680 		return (ND_IFINFO(ifp)->chlim);
681 	else
682 		return (ip6_defhlim);
683 }
684 #endif
685 
686 void
687 in6_pcbdisconnect(struct inpcb *inp)
688 {
689 	bzero((caddr_t)&inp->in6p_faddr, sizeof(inp->in6p_faddr));
690 	inp->inp_fport = 0;
691 	/* clear flowinfo - draft-itojun-ipv6-flowlabel-api-00 */
692 	inp->in6p_flowinfo &= ~IPV6_FLOWLABEL_MASK;
693 	in_pcbremconnhash(inp);
694 	if (inp->inp_socket->so_state & SS_NOFDREF)
695 		in6_pcbdetach(inp);
696 }
697 
698 void
699 in6_pcbdetach(struct inpcb *inp)
700 {
701 	struct socket *so = inp->inp_socket;
702 	struct inpcbinfo *ipi = inp->inp_pcbinfo;
703 
704 #ifdef IPSEC
705 	if (inp->in6p_sp != NULL)
706 		ipsec6_delete_pcbpolicy(inp);
707 #endif /* IPSEC */
708 	inp->inp_gencnt = ++ipi->ipi_gencnt;
709 	in_pcbremlists(inp);
710 	so->so_pcb = NULL;
711 	KKASSERT((so->so_state & SS_ASSERTINPROG) == 0);
712 	sofree(so);		/* remove pcb ref */
713 
714 	if (inp->in6p_options)
715 		m_freem(inp->in6p_options);
716 	ip6_freepcbopts(inp->in6p_outputopts);
717 	ip6_freemoptions(inp->in6p_moptions);
718 	if (inp->in6p_route.ro_rt)
719 		rtfree(inp->in6p_route.ro_rt);
720 	/* Check and free IPv4 related resources in case of mapped addr */
721 	if (inp->inp_options)
722 		m_free(inp->inp_options);
723 	ip_freemoptions(inp->inp_moptions);
724 
725 	inp->inp_vflag = 0;
726 	kfree(inp, M_PCB);
727 }
728 
729 /*
730  * The calling convention of in6_setsockaddr() and in6_setpeeraddr() was
731  * modified to match the pru_sockaddr() and pru_peeraddr() entry points
732  * in struct pr_usrreqs, so that protocols can just reference then directly
733  * without the need for a wrapper function.  The socket must have a valid
734  * (i.e., non-nil) PCB, but it should be impossible to get an invalid one
735  * except through a kernel programming error, so it is acceptable to panic
736  * (or in this case trap) if the PCB is invalid.  (Actually, we don't trap
737  * because there actually /is/ a programming error somewhere... XXX)
738  */
739 void
740 in6_setsockaddr_dispatch(netmsg_t msg)
741 {
742 	int error;
743 
744 	error = in6_setsockaddr(msg->sockaddr.base.nm_so, msg->sockaddr.nm_nam);
745 	lwkt_replymsg(&msg->sockaddr.base.lmsg, error);
746 }
747 
748 int
749 in6_setsockaddr(struct socket *so, struct sockaddr **nam)
750 {
751 	struct inpcb *inp;
752 	struct sockaddr_in6 *sin6;
753 
754 	/*
755 	 * Do the malloc first in case it blocks.
756 	 */
757 	sin6 = kmalloc(sizeof *sin6, M_SONAME, M_WAITOK | M_ZERO);
758 	sin6->sin6_family = AF_INET6;
759 	sin6->sin6_len = sizeof(*sin6);
760 
761 	crit_enter();
762 	inp = so->so_pcb;
763 	if (!inp) {
764 		crit_exit();
765 		kfree(sin6, M_SONAME);
766 		return EINVAL;
767 	}
768 	sin6->sin6_port = inp->inp_lport;
769 	sin6->sin6_addr = inp->in6p_laddr;
770 	crit_exit();
771 	if (IN6_IS_SCOPE_LINKLOCAL(&sin6->sin6_addr))
772 		sin6->sin6_scope_id = ntohs(sin6->sin6_addr.s6_addr16[1]);
773 	else
774 		sin6->sin6_scope_id = 0;	/*XXX*/
775 	if (IN6_IS_SCOPE_LINKLOCAL(&sin6->sin6_addr))
776 		sin6->sin6_addr.s6_addr16[1] = 0;
777 
778 	*nam = (struct sockaddr *)sin6;
779 	return 0;
780 }
781 
782 void
783 in6_setpeeraddr_dispatch(netmsg_t msg)
784 {
785 	int error;
786 
787 	error = in6_setpeeraddr(msg->peeraddr.base.nm_so, msg->peeraddr.nm_nam);
788 	lwkt_replymsg(&msg->peeraddr.base.lmsg, error);
789 }
790 
791 int
792 in6_setpeeraddr(struct socket *so, struct sockaddr **nam)
793 {
794 	struct inpcb *inp;
795 	struct sockaddr_in6 *sin6;
796 
797 	/*
798 	 * Do the malloc first in case it blocks.
799 	 */
800 	sin6 = kmalloc(sizeof(*sin6), M_SONAME, M_WAITOK | M_ZERO);
801 	sin6->sin6_family = AF_INET6;
802 	sin6->sin6_len = sizeof(struct sockaddr_in6);
803 
804 	crit_enter();
805 	inp = so->so_pcb;
806 	if (!inp) {
807 		crit_exit();
808 		kfree(sin6, M_SONAME);
809 		return EINVAL;
810 	}
811 	sin6->sin6_port = inp->inp_fport;
812 	sin6->sin6_addr = inp->in6p_faddr;
813 	crit_exit();
814 	if (IN6_IS_SCOPE_LINKLOCAL(&sin6->sin6_addr))
815 		sin6->sin6_scope_id = ntohs(sin6->sin6_addr.s6_addr16[1]);
816 	else
817 		sin6->sin6_scope_id = 0;	/*XXX*/
818 	if (IN6_IS_SCOPE_LINKLOCAL(&sin6->sin6_addr))
819 		sin6->sin6_addr.s6_addr16[1] = 0;
820 
821 	*nam = (struct sockaddr *)sin6;
822 	return 0;
823 }
824 
825 void
826 in6_mapped_sockaddr_dispatch(netmsg_t msg)
827 {
828 	int error;
829 
830 	error = in6_mapped_sockaddr(msg->sockaddr.base.nm_so,
831 				    msg->sockaddr.nm_nam);
832 	lwkt_replymsg(&msg->sockaddr.base.lmsg, error);
833 }
834 
835 int
836 in6_mapped_sockaddr(struct socket *so, struct sockaddr **nam)
837 {
838 	struct	inpcb *inp = so->so_pcb;
839 	int	error;
840 
841 	if (inp == NULL)
842 		return EINVAL;
843 	if (inp->inp_vflag & INP_IPV4) {
844 		error = in_setsockaddr(so, nam);
845 		if (error == 0)
846 			in6_sin_2_v4mapsin6_in_sock(nam);
847 	} else
848 	/* scope issues will be handled in in6_setsockaddr(). */
849 	error = in6_setsockaddr(so, nam);
850 
851 	return error;
852 }
853 
854 int
855 in6_mapped_peeraddr(struct socket *so, struct sockaddr **nam)
856 {
857 	struct	inpcb *inp = so->so_pcb;
858 	int	error;
859 
860 	if (inp == NULL)
861 		return EINVAL;
862 	if (inp->inp_vflag & INP_IPV4) {
863 		error = in_setpeeraddr(so, nam);
864 		if (error == 0)
865 			in6_sin_2_v4mapsin6_in_sock(nam);
866 	} else
867 	/* scope issues will be handled in in6_setpeeraddr(). */
868 	error = in6_setpeeraddr(so, nam);
869 
870 	return error;
871 }
872 
873 void
874 in6_mapped_peeraddr_dispatch(netmsg_t msg)
875 {
876 	int error;
877 
878 	error = in6_mapped_peeraddr(msg->base.nm_so, msg->peeraddr.nm_nam);
879 	lwkt_replymsg(&msg->base.lmsg, error);
880 }
881 
882 /*
883  * Pass some notification to all connections of a protocol
884  * associated with address dst.  The local address and/or port numbers
885  * may be specified to limit the search.  The "usual action" will be
886  * taken, depending on the ctlinput cmd.  The caller must filter any
887  * cmds that are uninteresting (e.g., no error in the map).
888  * Call the protocol specific routine (if any) to report
889  * any errors for each matching socket.
890  *
891  * Must be called under crit_enter().
892  */
893 void
894 in6_pcbnotify(struct inpcbhead *head, struct sockaddr *dst, in_port_t fport,
895 	      const struct sockaddr *src, in_port_t lport, int cmd, int arg,
896 	      void (*notify) (struct inpcb *, int))
897 {
898 	struct inpcb *inp, *ninp;
899 	struct sockaddr_in6 sa6_src, *sa6_dst;
900 	u_int32_t flowinfo;
901 
902 	if ((unsigned)cmd >= PRC_NCMDS || dst->sa_family != AF_INET6)
903 		return;
904 
905 	sa6_dst = (struct sockaddr_in6 *)dst;
906 	if (IN6_IS_ADDR_UNSPECIFIED(&sa6_dst->sin6_addr))
907 		return;
908 
909 	/*
910 	 * note that src can be NULL when we get notify by local fragmentation.
911 	 */
912 	sa6_src = (src == NULL) ? sa6_any : *(const struct sockaddr_in6 *)src;
913 	flowinfo = sa6_src.sin6_flowinfo;
914 
915 	/*
916 	 * Redirects go to all references to the destination,
917 	 * and use in6_rtchange to invalidate the route cache.
918 	 * Dead host indications: also use in6_rtchange to invalidate
919 	 * the cache, and deliver the error to all the sockets.
920 	 * Otherwise, if we have knowledge of the local port and address,
921 	 * deliver only to that socket.
922 	 */
923 	if (PRC_IS_REDIRECT(cmd) || cmd == PRC_HOSTDEAD) {
924 		fport = 0;
925 		lport = 0;
926 		bzero((caddr_t)&sa6_src.sin6_addr, sizeof(sa6_src.sin6_addr));
927 
928 		if (cmd != PRC_HOSTDEAD)
929 			notify = in6_rtchange;
930 	}
931 	if (cmd != PRC_MSGSIZE)
932 		arg = inet6ctlerrmap[cmd];
933 	crit_enter();
934 	for (inp = LIST_FIRST(head); inp != NULL; inp = ninp) {
935 		ninp = LIST_NEXT(inp, inp_list);
936 
937 		if (inp->inp_flags & INP_PLACEMARKER)
938 			continue;
939 
940 		if ((inp->inp_vflag & INP_IPV6) == 0)
941 			continue;
942 		/*
943 		 * If the error designates a new path MTU for a destination
944 		 * and the application (associated with this socket) wanted to
945 		 * know the value, notify. Note that we notify for all
946 		 * disconnected sockets if the corresponding application
947 		 * wanted. This is because some UDP applications keep sending
948 		 * sockets disconnected.
949 		 * XXX: should we avoid to notify the value to TCP sockets?
950 		 */
951 		if (cmd == PRC_MSGSIZE && (inp->inp_flags & IN6P_MTU) != 0 &&
952 		    (IN6_IS_ADDR_UNSPECIFIED(&inp->in6p_faddr) ||
953 		     IN6_ARE_ADDR_EQUAL(&inp->in6p_faddr, &sa6_dst->sin6_addr))) {
954 			ip6_notify_pmtu(inp, (struct sockaddr_in6 *)dst, &arg);
955 		}
956 
957 		/*
958 		 * Detect if we should notify the error. If no source and
959 		 * destination ports are specifed, but non-zero flowinfo and
960 		 * local address match, notify the error. This is the case
961 		 * when the error is delivered with an encrypted buffer
962 		 * by ESP. Otherwise, just compare addresses and ports
963 		 * as usual.
964 		 */
965 		if (lport == 0 && fport == 0 && flowinfo &&
966 		    inp->inp_socket != NULL &&
967 		    flowinfo == (inp->in6p_flowinfo & IPV6_FLOWLABEL_MASK) &&
968 		    IN6_ARE_ADDR_EQUAL(&inp->in6p_laddr, &sa6_src.sin6_addr))
969 			goto do_notify;
970 		else if (!IN6_ARE_ADDR_EQUAL(&inp->in6p_faddr,
971 					     &sa6_dst->sin6_addr) ||
972 			 inp->inp_socket == 0 ||
973 			 (lport && inp->inp_lport != lport) ||
974 			 (!IN6_IS_ADDR_UNSPECIFIED(&sa6_src.sin6_addr) &&
975 			  !IN6_ARE_ADDR_EQUAL(&inp->in6p_laddr,
976 					      &sa6_src.sin6_addr)) ||
977 			 (fport && inp->inp_fport != fport))
978 			continue;
979 
980 do_notify:
981 		if (notify)
982 			(*notify)(inp, arg);
983 	}
984 	crit_exit();
985 }
986 
987 /*
988  * Lookup a PCB based on the local address and port.
989  */
990 struct inpcb *
991 in6_pcblookup_local(struct inpcbportinfo *portinfo,
992     const struct in6_addr *laddr, u_int lport_arg, int wild_okay,
993     struct ucred *cred)
994 {
995 	struct inpcb *inp;
996 	int matchwild = 3, wildcard;
997 	u_short lport = lport_arg;
998 	struct inpcbporthead *porthash;
999 	struct inpcbport *phd;
1000 	struct inpcb *match = NULL;
1001 
1002 	/*
1003 	 * If the porthashbase is shared across several cpus, it must
1004 	 * have been locked.
1005 	 */
1006 	ASSERT_PORT_TOKEN_HELD(portinfo);
1007 
1008 	/*
1009 	 * Best fit PCB lookup.
1010 	 *
1011 	 * First see if this local port is in use by looking on the
1012 	 * port hash list.
1013 	 */
1014 	porthash = &portinfo->porthashbase[
1015 				INP_PCBPORTHASH(lport, portinfo->porthashmask)];
1016 	LIST_FOREACH(phd, porthash, phd_hash) {
1017 		if (phd->phd_port == lport)
1018 			break;
1019 	}
1020 
1021 	if (phd != NULL) {
1022 		/*
1023 		 * Port is in use by one or more PCBs. Look for best
1024 		 * fit.
1025 		 */
1026 		LIST_FOREACH(inp, &phd->phd_pcblist, inp_portlist) {
1027 			wildcard = 0;
1028 			if ((inp->inp_vflag & INP_IPV6) == 0)
1029 				continue;
1030 			if (!IN6_IS_ADDR_UNSPECIFIED(&inp->in6p_faddr))
1031 				wildcard++;
1032 			if (!IN6_IS_ADDR_UNSPECIFIED(&inp->in6p_laddr)) {
1033 				if (IN6_IS_ADDR_UNSPECIFIED(laddr))
1034 					wildcard++;
1035 				else if (!IN6_ARE_ADDR_EQUAL(
1036 					&inp->in6p_laddr, laddr))
1037 					continue;
1038 			} else {
1039 				if (!IN6_IS_ADDR_UNSPECIFIED(laddr))
1040 					wildcard++;
1041 			}
1042 			if (wildcard && !wild_okay)
1043 				continue;
1044 			if (wildcard < matchwild &&
1045 			    (cred == NULL ||
1046 			     cred->cr_prison ==
1047 					inp->inp_socket->so_cred->cr_prison)) {
1048 				match = inp;
1049 				matchwild = wildcard;
1050 				if (wildcard == 0)
1051 					break;
1052 				else
1053 					matchwild = wildcard;
1054 			}
1055 		}
1056 	}
1057 	return (match);
1058 }
1059 
1060 void
1061 in6_pcbpurgeif0(struct in6pcb *head, struct ifnet *ifp)
1062 {
1063 	struct in6pcb *in6p;
1064 	struct ip6_moptions *im6o;
1065 	struct in6_multi_mship *imm, *nimm;
1066 
1067 	for (in6p = head; in6p != NULL; in6p = LIST_NEXT(in6p, inp_list)) {
1068 		if (in6p->in6p_flags & INP_PLACEMARKER)
1069 			continue;
1070 		im6o = in6p->in6p_moptions;
1071 		if ((in6p->inp_vflag & INP_IPV6) &&
1072 		    im6o) {
1073 			/*
1074 			 * Unselect the outgoing interface if it is being
1075 			 * detached.
1076 			 */
1077 			if (im6o->im6o_multicast_ifp == ifp)
1078 				im6o->im6o_multicast_ifp = NULL;
1079 
1080 			/*
1081 			 * Drop multicast group membership if we joined
1082 			 * through the interface being detached.
1083 			 * XXX controversial - is it really legal for kernel
1084 			 * to force this?
1085 			 */
1086 			for (imm = im6o->im6o_memberships.lh_first;
1087 			     imm != NULL; imm = nimm) {
1088 				nimm = imm->i6mm_chain.le_next;
1089 				if (imm->i6mm_maddr->in6m_ifp == ifp) {
1090 					LIST_REMOVE(imm, i6mm_chain);
1091 					in6_delmulti(imm->i6mm_maddr);
1092 					kfree(imm, M_IPMADDR);
1093 				}
1094 			}
1095 		}
1096 	}
1097 }
1098 
1099 /*
1100  * Check for alternatives when higher level complains
1101  * about service problems.  For now, invalidate cached
1102  * routing information.  If the route was created dynamically
1103  * (by a redirect), time to try a default gateway again.
1104  */
1105 void
1106 in6_losing(struct inpcb *in6p)
1107 {
1108 	struct rtentry *rt;
1109 	struct rt_addrinfo info;
1110 
1111 	if ((rt = in6p->in6p_route.ro_rt) != NULL) {
1112 		bzero((caddr_t)&info, sizeof(info));
1113 		info.rti_flags = rt->rt_flags;
1114 		info.rti_info[RTAX_DST] = rt_key(rt);
1115 		info.rti_info[RTAX_GATEWAY] = rt->rt_gateway;
1116 		info.rti_info[RTAX_NETMASK] = rt_mask(rt);
1117 		rt_missmsg(RTM_LOSING, &info, rt->rt_flags, 0);
1118 		if (rt->rt_flags & RTF_DYNAMIC) {
1119 			rtrequest(RTM_DELETE, rt_key(rt), rt->rt_gateway,
1120 			    rt_mask(rt), rt->rt_flags, NULL);
1121 		}
1122 		in6p->in6p_route.ro_rt = NULL;
1123 		rtfree(rt);
1124 		/*
1125 		 * A new route can be allocated
1126 		 * the next time output is attempted.
1127 		 */
1128 	}
1129 }
1130 
1131 /*
1132  * After a routing change, flush old routing
1133  * and allocate a (hopefully) better one.
1134  */
1135 void
1136 in6_rtchange(struct inpcb *inp, int error)
1137 {
1138 	if (inp->in6p_route.ro_rt) {
1139 		rtfree(inp->in6p_route.ro_rt);
1140 		inp->in6p_route.ro_rt = 0;
1141 		/*
1142 		 * A new route can be allocated the next time
1143 		 * output is attempted.
1144 		 */
1145 	}
1146 }
1147 
1148 /*
1149  * Lookup PCB in hash list.
1150  */
1151 struct inpcb *
1152 in6_pcblookup_hash(struct inpcbinfo *pcbinfo, struct in6_addr *faddr,
1153 		   u_int fport_arg, struct in6_addr *laddr, u_int lport_arg,
1154 		   int wildcard, struct ifnet *ifp)
1155 {
1156 	struct inpcbhead *head;
1157 	struct inpcb *inp;
1158 	struct inpcb *jinp = NULL;
1159 	u_short fport = fport_arg, lport = lport_arg;
1160 	int faith;
1161 
1162 	if (faithprefix_p != NULL)
1163 		faith = (*faithprefix_p)(laddr);
1164 	else
1165 		faith = 0;
1166 
1167 	/*
1168 	 * First look for an exact match.
1169 	 */
1170 	head = &pcbinfo->hashbase[INP_PCBCONNHASH(faddr->s6_addr32[3] /* XXX */,
1171 					      fport,
1172 					      laddr->s6_addr32[3], /* XXX JH */
1173 					      lport,
1174 					      pcbinfo->hashmask)];
1175 	LIST_FOREACH(inp, head, inp_hash) {
1176 		if ((inp->inp_vflag & INP_IPV6) == 0)
1177 			continue;
1178 		if (IN6_ARE_ADDR_EQUAL(&inp->in6p_faddr, faddr) &&
1179 		    IN6_ARE_ADDR_EQUAL(&inp->in6p_laddr, laddr) &&
1180 		    inp->inp_fport == fport &&
1181 		    inp->inp_lport == lport) {
1182 			/*
1183 			 * Found.
1184 			 */
1185 			if (inp->inp_socket == NULL ||
1186 			inp->inp_socket->so_cred->cr_prison == NULL) {
1187 				return (inp);
1188 			} else {
1189 				if  (jinp == NULL)
1190 					jinp = inp;
1191 			}
1192 		}
1193 	}
1194 	if (jinp != NULL)
1195 		return(jinp);
1196 	if (wildcard) {
1197 		struct inpcontainerhead *chead;
1198 		struct inpcontainer *ic;
1199 		struct inpcb *local_wild = NULL;
1200 		struct inpcb *jinp_wild = NULL;
1201 		struct sockaddr_in6 jsin6;
1202 		struct ucred *cred;
1203 
1204 		/*
1205 		 * Order of socket selection:
1206 		 * 1. non-jailed, non-wild.
1207 		 * 2. non-jailed, wild.
1208 		 * 3. jailed, non-wild.
1209 		 * 4. jailed, wild.
1210 		 */
1211 		jsin6.sin6_family = AF_INET6;
1212 		chead = &pcbinfo->wildcardhashbase[INP_PCBWILDCARDHASH(lport,
1213 		    pcbinfo->wildcardhashmask)];
1214 		LIST_FOREACH(ic, chead, ic_list) {
1215 			inp = ic->ic_inp;
1216 
1217 			if (!(inp->inp_vflag & INP_IPV6))
1218 				continue;
1219 			if (inp->inp_socket != NULL)
1220 				cred = inp->inp_socket->so_cred;
1221 			else
1222 				cred = NULL;
1223 
1224 			if (cred != NULL && jailed(cred)) {
1225 				if (jinp != NULL) {
1226 					continue;
1227 				} else {
1228 		                        jsin6.sin6_addr = *laddr;
1229 					if (!jailed_ip(cred->cr_prison,
1230 					    (struct sockaddr *)&jsin6))
1231 						continue;
1232 				}
1233 			}
1234 			if (IN6_IS_ADDR_UNSPECIFIED(&inp->in6p_faddr) &&
1235 			    inp->inp_lport == lport) {
1236 				if (faith && (inp->inp_flags & INP_FAITH) == 0)
1237 					continue;
1238 				if (IN6_ARE_ADDR_EQUAL(&inp->in6p_laddr,
1239 						       laddr)) {
1240 					if (cred != NULL && jailed(cred))
1241 						jinp = inp;
1242 					else
1243 						return (inp);
1244 				} else if (IN6_IS_ADDR_UNSPECIFIED(&inp->in6p_laddr)) {
1245 					if (cred != NULL && jailed(cred))
1246 						jinp_wild = inp;
1247 					else
1248 						local_wild = inp;
1249 				}
1250 			}
1251 		}
1252 		if (local_wild != NULL)
1253 			return (local_wild);
1254 		if (jinp != NULL)
1255 			return (jinp);
1256 		return (jinp_wild);
1257 	}
1258 
1259 	/*
1260 	 * Not found.
1261 	 */
1262 	return (NULL);
1263 }
1264 
1265 void
1266 init_sin6(struct sockaddr_in6 *sin6, struct mbuf *m)
1267 {
1268 	struct ip6_hdr *ip;
1269 
1270 	ip = mtod(m, struct ip6_hdr *);
1271 	bzero(sin6, sizeof(*sin6));
1272 	sin6->sin6_len = sizeof(*sin6);
1273 	sin6->sin6_family = AF_INET6;
1274 	sin6->sin6_addr = ip->ip6_src;
1275 	if (IN6_IS_SCOPE_LINKLOCAL(&sin6->sin6_addr))
1276 		sin6->sin6_addr.s6_addr16[1] = 0;
1277 	sin6->sin6_scope_id =
1278 		(m->m_pkthdr.rcvif && IN6_IS_SCOPE_LINKLOCAL(&sin6->sin6_addr))
1279 		? m->m_pkthdr.rcvif->if_index : 0;
1280 
1281 	return;
1282 }
1283 
1284 static void
1285 in6_savefaddr(struct socket *so, const struct sockaddr *faddr)
1286 {
1287 	struct sockaddr_in6 *sin6;
1288 
1289 	KASSERT(faddr->sa_family == AF_INET6,
1290 	    ("not AF_INET6 faddr %d", faddr->sa_family));
1291 
1292 	sin6 = kmalloc(sizeof(*sin6), M_SONAME, M_WAITOK | M_ZERO);
1293 	sin6->sin6_family = AF_INET6;
1294 	sin6->sin6_len = sizeof(*sin6);
1295 
1296 	sin6->sin6_port = ((const struct sockaddr_in6 *)faddr)->sin6_port;
1297 	sin6->sin6_addr = ((const struct sockaddr_in6 *)faddr)->sin6_addr;
1298 
1299 	if (IN6_IS_SCOPE_LINKLOCAL(&sin6->sin6_addr))
1300 		sin6->sin6_scope_id = ntohs(sin6->sin6_addr.s6_addr16[1]);
1301 	else
1302 		sin6->sin6_scope_id = 0;	/*XXX*/
1303 	if (IN6_IS_SCOPE_LINKLOCAL(&sin6->sin6_addr))
1304 		sin6->sin6_addr.s6_addr16[1] = 0;
1305 
1306 	so->so_faddr = (struct sockaddr *)sin6;
1307 }
1308 
1309 void
1310 in6_mapped_savefaddr(struct socket *so, const struct sockaddr *faddr)
1311 {
1312 	if (faddr->sa_family == AF_INET) {
1313 		in_savefaddr(so, faddr);
1314 		in6_sin_2_v4mapsin6_in_sock(&so->so_faddr);
1315 	} else {
1316 		in6_savefaddr(so, faddr);
1317 	}
1318 }
1319