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