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