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