1/*	$NetBSD: in_pcb.c,v 1.139 2011/09/24 17:18:17 christos Exp $	*/
2
3/*
4 * Copyright (C) 1995, 1996, 1997, and 1998 WIDE Project.
5 * All rights reserved.
6 *
7 * Redistribution and use in source and binary forms, with or without
8 * modification, are permitted provided that the following conditions
9 * are met:
10 * 1. Redistributions of source code must retain the above copyright
11 *    notice, this list of conditions and the following disclaimer.
12 * 2. Redistributions in binary form must reproduce the above copyright
13 *    notice, this list of conditions and the following disclaimer in the
14 *    documentation and/or other materials provided with the distribution.
15 * 3. Neither the name of the project nor the names of its contributors
16 *    may be used to endorse or promote products derived from this software
17 *    without specific prior written permission.
18 *
19 * THIS SOFTWARE IS PROVIDED BY THE PROJECT AND CONTRIBUTORS ``AS IS'' AND
20 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
21 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
22 * ARE DISCLAIMED.  IN NO EVENT SHALL THE PROJECT OR CONTRIBUTORS BE LIABLE
23 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
24 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
25 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
26 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
27 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
28 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
29 * SUCH DAMAGE.
30 */
31
32/*-
33 * Copyright (c) 1998, 2011 The NetBSD Foundation, Inc.
34 * All rights reserved.
35 *
36 * This code is derived from software contributed to The NetBSD Foundation
37 * by Coyote Point Systems, Inc.
38 * This code is derived from software contributed to The NetBSD Foundation
39 * by Public Access Networks Corporation ("Panix").  It was developed under
40 * contract to Panix by Eric Haszlakiewicz and Thor Lancelot Simon.
41 *
42 * Redistribution and use in source and binary forms, with or without
43 * modification, are permitted provided that the following conditions
44 * are met:
45 * 1. Redistributions of source code must retain the above copyright
46 *    notice, this list of conditions and the following disclaimer.
47 * 2. Redistributions in binary form must reproduce the above copyright
48 *    notice, this list of conditions and the following disclaimer in the
49 *    documentation and/or other materials provided with the distribution.
50 *
51 * THIS SOFTWARE IS PROVIDED BY THE NETBSD FOUNDATION, INC. AND CONTRIBUTORS
52 * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
53 * TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
54 * PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL THE FOUNDATION OR CONTRIBUTORS
55 * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
56 * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
57 * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
58 * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
59 * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
60 * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
61 * POSSIBILITY OF SUCH DAMAGE.
62 */
63
64/*
65 * Copyright (c) 1982, 1986, 1991, 1993, 1995
66 *	The Regents of the University of California.  All rights reserved.
67 *
68 * Redistribution and use in source and binary forms, with or without
69 * modification, are permitted provided that the following conditions
70 * are met:
71 * 1. Redistributions of source code must retain the above copyright
72 *    notice, this list of conditions and the following disclaimer.
73 * 2. Redistributions in binary form must reproduce the above copyright
74 *    notice, this list of conditions and the following disclaimer in the
75 *    documentation and/or other materials provided with the distribution.
76 * 3. Neither the name of the University nor the names of its contributors
77 *    may be used to endorse or promote products derived from this software
78 *    without specific prior written permission.
79 *
80 * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
81 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
82 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
83 * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
84 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
85 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
86 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
87 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
88 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
89 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
90 * SUCH DAMAGE.
91 *
92 *	@(#)in_pcb.c	8.4 (Berkeley) 5/24/95
93 */
94
95#include <sys/cdefs.h>
96__KERNEL_RCSID(0, "$NetBSD: in_pcb.c,v 1.139 2011/09/24 17:18:17 christos Exp $");
97
98#include "opt_inet.h"
99#include "opt_ipsec.h"
100
101#include <sys/param.h>
102#include <sys/systm.h>
103#include <sys/malloc.h>
104#include <sys/mbuf.h>
105#include <sys/protosw.h>
106#include <sys/socket.h>
107#include <sys/socketvar.h>
108#include <sys/ioctl.h>
109#include <sys/errno.h>
110#include <sys/time.h>
111#include <sys/once.h>
112#include <sys/pool.h>
113#include <sys/proc.h>
114#include <sys/kauth.h>
115#include <sys/uidinfo.h>
116#include <sys/domain.h>
117
118#include <net/if.h>
119#include <net/route.h>
120
121#include <netinet/in.h>
122#include <netinet/in_systm.h>
123#include <netinet/ip.h>
124#include <netinet/in_pcb.h>
125#include <netinet/in_var.h>
126#include <netinet/ip_var.h>
127#include <netinet/rfc6056.h>
128
129#ifdef INET6
130#include <netinet/ip6.h>
131#include <netinet6/ip6_var.h>
132#include <netinet6/in6_pcb.h>
133#endif
134
135#ifdef KAME_IPSEC
136#include <netinet6/ipsec.h>
137#include <netkey/key.h>
138#elif FAST_IPSEC
139#include <netipsec/ipsec.h>
140#include <netipsec/key.h>
141#endif /* IPSEC */
142
143#include <netinet/tcp_vtw.h>
144
145struct	in_addr zeroin_addr;
146
147#define	INPCBHASH_PORT(table, lport) \
148	&(table)->inpt_porthashtbl[ntohs(lport) & (table)->inpt_porthash]
149#define	INPCBHASH_BIND(table, laddr, lport) \
150	&(table)->inpt_bindhashtbl[ \
151	    ((ntohl((laddr).s_addr) + ntohs(lport))) & (table)->inpt_bindhash]
152#define	INPCBHASH_CONNECT(table, faddr, fport, laddr, lport) \
153	&(table)->inpt_connecthashtbl[ \
154	    ((ntohl((faddr).s_addr) + ntohs(fport)) + \
155	     (ntohl((laddr).s_addr) + ntohs(lport))) & (table)->inpt_connecthash]
156
157int	anonportmin = IPPORT_ANONMIN;
158int	anonportmax = IPPORT_ANONMAX;
159int	lowportmin  = IPPORT_RESERVEDMIN;
160int	lowportmax  = IPPORT_RESERVEDMAX;
161
162static struct pool inpcb_pool;
163
164static int
165inpcb_poolinit(void)
166{
167
168	pool_init(&inpcb_pool, sizeof(struct inpcb), 0, 0, 0, "inpcbpl", NULL,
169	    IPL_NET);
170	return 0;
171}
172
173void
174in_pcbinit(struct inpcbtable *table, int bindhashsize, int connecthashsize)
175{
176	static ONCE_DECL(control);
177
178	CIRCLEQ_INIT(&table->inpt_queue);
179	table->inpt_porthashtbl = hashinit(bindhashsize, HASH_LIST, true,
180	    &table->inpt_porthash);
181	table->inpt_bindhashtbl = hashinit(bindhashsize, HASH_LIST, true,
182	    &table->inpt_bindhash);
183	table->inpt_connecthashtbl = hashinit(connecthashsize, HASH_LIST, true,
184	    &table->inpt_connecthash);
185	table->inpt_lastlow = IPPORT_RESERVEDMAX;
186	table->inpt_lastport = (u_int16_t)anonportmax;
187
188	RUN_ONCE(&control, inpcb_poolinit);
189}
190
191int
192in_pcballoc(struct socket *so, void *v)
193{
194	struct inpcbtable *table = v;
195	struct inpcb *inp;
196	int s;
197#if defined(KAME_IPSEC) || defined(FAST_IPSEC)
198	int error;
199#endif
200
201	s = splnet();
202	inp = pool_get(&inpcb_pool, PR_NOWAIT);
203	splx(s);
204	if (inp == NULL)
205		return (ENOBUFS);
206	memset(inp, 0, sizeof(*inp));
207	inp->inp_af = AF_INET;
208	inp->inp_table = table;
209	inp->inp_socket = so;
210	inp->inp_errormtu = -1;
211	inp->inp_rfc6056algo = RFC6056_ALGO_DEFAULT;
212	inp->inp_bindportonsend = false;
213#if defined(KAME_IPSEC) || defined(FAST_IPSEC)
214	error = ipsec_init_pcbpolicy(so, &inp->inp_sp);
215	if (error != 0) {
216		s = splnet();
217		pool_put(&inpcb_pool, inp);
218		splx(s);
219		return error;
220	}
221#endif
222	so->so_pcb = inp;
223	s = splnet();
224	CIRCLEQ_INSERT_HEAD(&table->inpt_queue, &inp->inp_head,
225	    inph_queue);
226	LIST_INSERT_HEAD(INPCBHASH_PORT(table, inp->inp_lport), &inp->inp_head,
227	    inph_lhash);
228	in_pcbstate(inp, INP_ATTACHED);
229	splx(s);
230	return (0);
231}
232
233static int
234in_pcbsetport(struct sockaddr_in *sin, struct inpcb *inp, kauth_cred_t cred)
235{
236	struct inpcbtable *table = inp->inp_table;
237	struct socket *so = inp->inp_socket;
238	u_int16_t *lastport;
239	u_int16_t lport = 0;
240	enum kauth_network_req req;
241	int error;
242
243	if (inp->inp_flags & INP_LOWPORT) {
244#ifndef IPNOPRIVPORTS
245		req = KAUTH_REQ_NETWORK_BIND_PRIVPORT;
246#else
247		req = KAUTH_REQ_NETWORK_BIND_PORT;
248#endif
249
250		lastport = &table->inpt_lastlow;
251	} else {
252		req = KAUTH_REQ_NETWORK_BIND_PORT;
253
254		lastport = &table->inpt_lastport;
255	}
256
257	/* XXX-kauth: KAUTH_REQ_NETWORK_BIND_AUTOASSIGN_{,PRIV}PORT */
258	error = kauth_authorize_network(cred, KAUTH_NETWORK_BIND, req, so, sin,
259	    NULL);
260	if (error)
261		return (EACCES);
262
263       /*
264        * Use RFC6056 randomized port selection
265        */
266	error = rfc6056_randport(&lport, &inp->inp_head, cred);
267	if (error)
268		return error;
269
270	inp->inp_flags |= INP_ANONPORT;
271	*lastport = lport;
272	lport = htons(lport);
273	inp->inp_lport = lport;
274	in_pcbstate(inp, INP_BOUND);
275
276	return (0);
277}
278
279static int
280in_pcbbind_addr(struct inpcb *inp, struct sockaddr_in *sin, kauth_cred_t cred)
281{
282	if (sin->sin_family != AF_INET)
283		return (EAFNOSUPPORT);
284
285	if (IN_MULTICAST(sin->sin_addr.s_addr)) {
286		/* Always succeed; port reuse handled in in_pcbbind_port(). */
287	} else if (!in_nullhost(sin->sin_addr)) {
288		struct in_ifaddr *ia = NULL;
289
290		INADDR_TO_IA(sin->sin_addr, ia);
291		/* check for broadcast addresses */
292		if (ia == NULL)
293			ia = ifatoia(ifa_ifwithaddr(sintosa(sin)));
294		if (ia == NULL)
295			return (EADDRNOTAVAIL);
296	}
297
298	inp->inp_laddr = sin->sin_addr;
299
300	return (0);
301}
302
303static int
304in_pcbbind_port(struct inpcb *inp, struct sockaddr_in *sin, kauth_cred_t cred)
305{
306	struct inpcbtable *table = inp->inp_table;
307	struct socket *so = inp->inp_socket;
308	int reuseport = (so->so_options & SO_REUSEPORT);
309	int wild = 0, error;
310
311	if (IN_MULTICAST(sin->sin_addr.s_addr)) {
312		/*
313		 * Treat SO_REUSEADDR as SO_REUSEPORT for multicast;
314		 * allow complete duplication of binding if
315		 * SO_REUSEPORT is set, or if SO_REUSEADDR is set
316		 * and a multicast address is bound on both
317		 * new and duplicated sockets.
318		 */
319		if (so->so_options & SO_REUSEADDR)
320			reuseport = SO_REUSEADDR|SO_REUSEPORT;
321	}
322
323	if (sin->sin_port == 0) {
324		error = in_pcbsetport(sin, inp, cred);
325		if (error)
326			return (error);
327	} else {
328		struct inpcb *t;
329		vestigial_inpcb_t vestige;
330#ifdef INET6
331		struct in6pcb *t6;
332		struct in6_addr mapped;
333#endif
334		enum kauth_network_req req;
335
336		if ((so->so_options & (SO_REUSEADDR|SO_REUSEPORT)) == 0)
337			wild = 1;
338
339#ifndef IPNOPRIVPORTS
340		if (ntohs(sin->sin_port) < IPPORT_RESERVED)
341			req = KAUTH_REQ_NETWORK_BIND_PRIVPORT;
342		else
343#endif /* !IPNOPRIVPORTS */
344			req = KAUTH_REQ_NETWORK_BIND_PORT;
345
346		error = kauth_authorize_network(cred, KAUTH_NETWORK_BIND, req,
347		    so, sin, NULL);
348		if (error)
349			return (EACCES);
350
351#ifdef INET6
352		memset(&mapped, 0, sizeof(mapped));
353		mapped.s6_addr16[5] = 0xffff;
354		memcpy(&mapped.s6_addr32[3], &sin->sin_addr,
355		    sizeof(mapped.s6_addr32[3]));
356		t6 = in6_pcblookup_port(table, &mapped, sin->sin_port, wild, &vestige);
357		if (t6 && (reuseport & t6->in6p_socket->so_options) == 0)
358			return (EADDRINUSE);
359		if (!t6 && vestige.valid) {
360		    if (!!reuseport != !!vestige.reuse_port) {
361			return EADDRINUSE;
362		    }
363		}
364#endif
365
366		/* XXX-kauth */
367		if (so->so_uidinfo->ui_uid && !IN_MULTICAST(sin->sin_addr.s_addr)) {
368			t = in_pcblookup_port(table, sin->sin_addr, sin->sin_port, 1, &vestige);
369			/*
370			 * XXX:	investigate ramifications of loosening this
371			 *	restriction so that as long as both ports have
372			 *	SO_REUSEPORT allow the bind
373			 */
374			if (t &&
375			    (!in_nullhost(sin->sin_addr) ||
376			     !in_nullhost(t->inp_laddr) ||
377			     (t->inp_socket->so_options & SO_REUSEPORT) == 0)
378			    && (so->so_uidinfo->ui_uid != t->inp_socket->so_uidinfo->ui_uid)) {
379				return (EADDRINUSE);
380			}
381			if (!t && vestige.valid) {
382				if ((!in_nullhost(sin->sin_addr)
383				     || !in_nullhost(vestige.laddr.v4)
384				     || !vestige.reuse_port)
385				    && so->so_uidinfo->ui_uid != vestige.uid) {
386					return EADDRINUSE;
387				}
388			}
389		}
390		t = in_pcblookup_port(table, sin->sin_addr, sin->sin_port, wild, &vestige);
391		if (t && (reuseport & t->inp_socket->so_options) == 0)
392			return (EADDRINUSE);
393		if (!t
394		    && vestige.valid
395		    && !(reuseport && vestige.reuse_port))
396			return EADDRINUSE;
397
398		inp->inp_lport = sin->sin_port;
399		in_pcbstate(inp, INP_BOUND);
400	}
401
402	LIST_REMOVE(&inp->inp_head, inph_lhash);
403	LIST_INSERT_HEAD(INPCBHASH_PORT(table, inp->inp_lport), &inp->inp_head,
404	    inph_lhash);
405
406	return (0);
407}
408
409int
410in_pcbbind(void *v, struct mbuf *nam, struct lwp *l)
411{
412	struct inpcb *inp = v;
413	struct sockaddr_in *sin = NULL; /* XXXGCC */
414	struct sockaddr_in lsin;
415	int error;
416
417	if (inp->inp_af != AF_INET)
418		return (EINVAL);
419
420	if (TAILQ_FIRST(&in_ifaddrhead) == 0)
421		return (EADDRNOTAVAIL);
422	if (inp->inp_lport || !in_nullhost(inp->inp_laddr))
423		return (EINVAL);
424
425	if (nam != NULL) {
426		sin = mtod(nam, struct sockaddr_in *);
427		if (nam->m_len != sizeof (*sin))
428			return (EINVAL);
429	} else {
430		lsin = *((const struct sockaddr_in *)
431		    inp->inp_socket->so_proto->pr_domain->dom_sa_any);
432		sin = &lsin;
433	}
434
435	/* Bind address. */
436	error = in_pcbbind_addr(inp, sin, l->l_cred);
437	if (error)
438		return (error);
439
440	/* Bind port. */
441	error = in_pcbbind_port(inp, sin, l->l_cred);
442	if (error) {
443		inp->inp_laddr.s_addr = INADDR_ANY;
444
445		return (error);
446	}
447
448	return (0);
449}
450
451/*
452 * Connect from a socket to a specified address.
453 * Both address and port must be specified in argument sin.
454 * If don't have a local address for this socket yet,
455 * then pick one.
456 */
457int
458in_pcbconnect(void *v, struct mbuf *nam, struct lwp *l)
459{
460	struct inpcb *inp = v;
461	struct in_ifaddr *ia = NULL;
462	struct sockaddr_in *ifaddr = NULL;
463	struct sockaddr_in *sin = mtod(nam, struct sockaddr_in *);
464	vestigial_inpcb_t vestige;
465	int error;
466
467	if (inp->inp_af != AF_INET)
468		return (EINVAL);
469
470	if (nam->m_len != sizeof (*sin))
471		return (EINVAL);
472	if (sin->sin_family != AF_INET)
473		return (EAFNOSUPPORT);
474	if (sin->sin_port == 0)
475		return (EADDRNOTAVAIL);
476	if (TAILQ_FIRST(&in_ifaddrhead) != 0) {
477		/*
478		 * If the destination address is INADDR_ANY,
479		 * use any local address (likely loopback).
480		 * If the supplied address is INADDR_BROADCAST,
481		 * use the broadcast address of an interface
482		 * which supports broadcast. (loopback does not)
483		 */
484
485		if (in_nullhost(sin->sin_addr)) {
486			sin->sin_addr =
487			    TAILQ_FIRST(&in_ifaddrhead)->ia_addr.sin_addr;
488		} else if (sin->sin_addr.s_addr == INADDR_BROADCAST) {
489			TAILQ_FOREACH(ia, &in_ifaddrhead, ia_list) {
490				if (ia->ia_ifp->if_flags & IFF_BROADCAST) {
491					sin->sin_addr =
492					    ia->ia_broadaddr.sin_addr;
493					break;
494				}
495			}
496		}
497	}
498	/*
499	 * If we haven't bound which network number to use as ours,
500	 * we will use the number of the outgoing interface.
501	 * This depends on having done a routing lookup, which
502	 * we will probably have to do anyway, so we might
503	 * as well do it now.  On the other hand if we are
504	 * sending to multiple destinations we may have already
505	 * done the lookup, so see if we can use the route
506	 * from before.  In any case, we only
507	 * chose a port number once, even if sending to multiple
508	 * destinations.
509	 */
510	if (in_nullhost(inp->inp_laddr)) {
511		int xerror;
512		ifaddr = in_selectsrc(sin, &inp->inp_route,
513		    inp->inp_socket->so_options, inp->inp_moptions, &xerror);
514		if (ifaddr == NULL) {
515			if (xerror == 0)
516				xerror = EADDRNOTAVAIL;
517			return xerror;
518		}
519		INADDR_TO_IA(ifaddr->sin_addr, ia);
520		if (ia == NULL)
521			return (EADDRNOTAVAIL);
522	}
523	if (in_pcblookup_connect(inp->inp_table, sin->sin_addr, sin->sin_port,
524	    !in_nullhost(inp->inp_laddr) ? inp->inp_laddr : ifaddr->sin_addr,
525				 inp->inp_lport, &vestige) != 0
526	    || vestige.valid)
527		return (EADDRINUSE);
528	if (in_nullhost(inp->inp_laddr)) {
529		if (inp->inp_lport == 0) {
530			error = in_pcbbind(inp, NULL, l);
531			/*
532			 * This used to ignore the return value
533			 * completely, but we need to check for
534			 * ephemeral port shortage.
535			 * And attempts to request low ports if not root.
536			 */
537			if (error != 0)
538				return (error);
539		}
540		inp->inp_laddr = ifaddr->sin_addr;
541	}
542	inp->inp_faddr = sin->sin_addr;
543	inp->inp_fport = sin->sin_port;
544
545        /* Late bind, if needed */
546	if (inp->inp_bindportonsend) {
547               struct sockaddr_in lsin = *((const struct sockaddr_in *)
548		    inp->inp_socket->so_proto->pr_domain->dom_sa_any);
549		lsin.sin_addr = inp->inp_laddr;
550		lsin.sin_port = 0;
551
552               if ((error = in_pcbbind_port(inp, &lsin, l->l_cred)) != 0)
553                       return error;
554	}
555
556	in_pcbstate(inp, INP_CONNECTED);
557#if defined(KAME_IPSEC) || defined(FAST_IPSEC)
558	if (inp->inp_socket->so_type == SOCK_STREAM)
559		ipsec_pcbconn(inp->inp_sp);
560#endif
561	return (0);
562}
563
564void
565in_pcbdisconnect(void *v)
566{
567	struct inpcb *inp = v;
568
569	if (inp->inp_af != AF_INET)
570		return;
571
572	inp->inp_faddr = zeroin_addr;
573	inp->inp_fport = 0;
574	in_pcbstate(inp, INP_BOUND);
575#if defined(KAME_IPSEC) || defined(FAST_IPSEC)
576	ipsec_pcbdisconn(inp->inp_sp);
577#endif
578	if (inp->inp_socket->so_state & SS_NOFDREF)
579		in_pcbdetach(inp);
580}
581
582void
583in_pcbdetach(void *v)
584{
585	struct inpcb *inp = v;
586	struct socket *so = inp->inp_socket;
587	int s;
588
589	if (inp->inp_af != AF_INET)
590		return;
591
592#if defined(KAME_IPSEC) || defined(FAST_IPSEC)
593	ipsec4_delete_pcbpolicy(inp);
594#endif /*IPSEC*/
595	so->so_pcb = 0;
596	if (inp->inp_options)
597		(void)m_free(inp->inp_options);
598	rtcache_free(&inp->inp_route);
599	ip_freemoptions(inp->inp_moptions);
600	s = splnet();
601	in_pcbstate(inp, INP_ATTACHED);
602	LIST_REMOVE(&inp->inp_head, inph_lhash);
603	CIRCLEQ_REMOVE(&inp->inp_table->inpt_queue, &inp->inp_head,
604	    inph_queue);
605	pool_put(&inpcb_pool, inp);
606	splx(s);
607	sofree(so);			/* drops the socket's lock */
608	mutex_enter(softnet_lock);	/* reacquire the softnet_lock */
609}
610
611void
612in_setsockaddr(struct inpcb *inp, struct mbuf *nam)
613{
614	struct sockaddr_in *sin;
615
616	if (inp->inp_af != AF_INET)
617		return;
618
619	sin = mtod(nam, struct sockaddr_in *);
620	sockaddr_in_init(sin, &inp->inp_laddr, inp->inp_lport);
621	nam->m_len = sin->sin_len;
622}
623
624void
625in_setpeeraddr(struct inpcb *inp, struct mbuf *nam)
626{
627	struct sockaddr_in *sin;
628
629	if (inp->inp_af != AF_INET)
630		return;
631
632	sin = mtod(nam, struct sockaddr_in *);
633	sockaddr_in_init(sin, &inp->inp_faddr, inp->inp_fport);
634	nam->m_len = sin->sin_len;
635}
636
637/*
638 * Pass some notification to all connections of a protocol
639 * associated with address dst.  The local address and/or port numbers
640 * may be specified to limit the search.  The "usual action" will be
641 * taken, depending on the ctlinput cmd.  The caller must filter any
642 * cmds that are uninteresting (e.g., no error in the map).
643 * Call the protocol specific routine (if any) to report
644 * any errors for each matching socket.
645 *
646 * Must be called at splsoftnet.
647 */
648int
649in_pcbnotify(struct inpcbtable *table, struct in_addr faddr, u_int fport_arg,
650    struct in_addr laddr, u_int lport_arg, int errno,
651    void (*notify)(struct inpcb *, int))
652{
653	struct inpcbhead *head;
654	struct inpcb *inp, *ninp;
655	u_int16_t fport = fport_arg, lport = lport_arg;
656	int nmatch;
657
658	if (in_nullhost(faddr) || notify == 0)
659		return (0);
660
661	nmatch = 0;
662	head = INPCBHASH_CONNECT(table, faddr, fport, laddr, lport);
663	for (inp = (struct inpcb *)LIST_FIRST(head); inp != NULL; inp = ninp) {
664		ninp = (struct inpcb *)LIST_NEXT(inp, inp_hash);
665		if (inp->inp_af != AF_INET)
666			continue;
667		if (in_hosteq(inp->inp_faddr, faddr) &&
668		    inp->inp_fport == fport &&
669		    inp->inp_lport == lport &&
670		    in_hosteq(inp->inp_laddr, laddr)) {
671			(*notify)(inp, errno);
672			nmatch++;
673		}
674	}
675	return (nmatch);
676}
677
678void
679in_pcbnotifyall(struct inpcbtable *table, struct in_addr faddr, int errno,
680    void (*notify)(struct inpcb *, int))
681{
682	struct inpcb *inp, *ninp;
683
684	if (in_nullhost(faddr) || notify == 0)
685		return;
686
687	for (inp = (struct inpcb *)CIRCLEQ_FIRST(&table->inpt_queue);
688	    inp != (void *)&table->inpt_queue;
689	    inp = ninp) {
690		ninp = (struct inpcb *)CIRCLEQ_NEXT(inp, inp_queue);
691		if (inp->inp_af != AF_INET)
692			continue;
693		if (in_hosteq(inp->inp_faddr, faddr))
694			(*notify)(inp, errno);
695	}
696}
697
698void
699in_pcbpurgeif0(struct inpcbtable *table, struct ifnet *ifp)
700{
701	struct inpcb *inp, *ninp;
702	struct ip_moptions *imo;
703	int i, gap;
704
705	for (inp = (struct inpcb *)CIRCLEQ_FIRST(&table->inpt_queue);
706	    inp != (void *)&table->inpt_queue;
707	    inp = ninp) {
708		ninp = (struct inpcb *)CIRCLEQ_NEXT(inp, inp_queue);
709		if (inp->inp_af != AF_INET)
710			continue;
711		imo = inp->inp_moptions;
712		if (imo != NULL) {
713			/*
714			 * Unselect the outgoing interface if it is being
715			 * detached.
716			 */
717			if (imo->imo_multicast_ifp == ifp)
718				imo->imo_multicast_ifp = NULL;
719
720			/*
721			 * Drop multicast group membership if we joined
722			 * through the interface being detached.
723			 */
724			for (i = 0, gap = 0; i < imo->imo_num_memberships;
725			    i++) {
726				if (imo->imo_membership[i]->inm_ifp == ifp) {
727					in_delmulti(imo->imo_membership[i]);
728					gap++;
729				} else if (gap != 0)
730					imo->imo_membership[i - gap] =
731					    imo->imo_membership[i];
732			}
733			imo->imo_num_memberships -= gap;
734		}
735	}
736}
737
738void
739in_pcbpurgeif(struct inpcbtable *table, struct ifnet *ifp)
740{
741	struct rtentry *rt;
742	struct inpcb *inp, *ninp;
743
744	for (inp = (struct inpcb *)CIRCLEQ_FIRST(&table->inpt_queue);
745	    inp != (void *)&table->inpt_queue;
746	    inp = ninp) {
747		ninp = (struct inpcb *)CIRCLEQ_NEXT(inp, inp_queue);
748		if (inp->inp_af != AF_INET)
749			continue;
750		if ((rt = rtcache_validate(&inp->inp_route)) != NULL &&
751		    rt->rt_ifp == ifp)
752			in_rtchange(inp, 0);
753	}
754}
755
756/*
757 * Check for alternatives when higher level complains
758 * about service problems.  For now, invalidate cached
759 * routing information.  If the route was created dynamically
760 * (by a redirect), time to try a default gateway again.
761 */
762void
763in_losing(struct inpcb *inp)
764{
765	struct rtentry *rt;
766	struct rt_addrinfo info;
767
768	if (inp->inp_af != AF_INET)
769		return;
770
771	if ((rt = rtcache_validate(&inp->inp_route)) == NULL)
772		return;
773
774	memset(&info, 0, sizeof(info));
775	info.rti_info[RTAX_DST] = rtcache_getdst(&inp->inp_route);
776	info.rti_info[RTAX_GATEWAY] = rt->rt_gateway;
777	info.rti_info[RTAX_NETMASK] = rt_mask(rt);
778	rt_missmsg(RTM_LOSING, &info, rt->rt_flags, 0);
779	if (rt->rt_flags & RTF_DYNAMIC)
780		(void) rtrequest(RTM_DELETE, rt_getkey(rt),
781			rt->rt_gateway, rt_mask(rt), rt->rt_flags,
782			NULL);
783	/*
784	 * A new route can be allocated
785	 * the next time output is attempted.
786	 */
787	rtcache_free(&inp->inp_route);
788}
789
790/*
791 * After a routing change, flush old routing.  A new route can be
792 * allocated the next time output is attempted.
793 */
794void
795in_rtchange(struct inpcb *inp, int errno)
796{
797
798	if (inp->inp_af != AF_INET)
799		return;
800
801	rtcache_free(&inp->inp_route);
802
803	/* XXX SHOULD NOTIFY HIGHER-LEVEL PROTOCOLS */
804}
805
806struct inpcb *
807in_pcblookup_port(struct inpcbtable *table, struct in_addr laddr,
808		  u_int lport_arg, int lookup_wildcard, vestigial_inpcb_t *vp)
809{
810	struct inpcbhead *head;
811	struct inpcb_hdr *inph;
812	struct inpcb *inp, *match = 0;
813	int matchwild = 3, wildcard;
814	u_int16_t lport = lport_arg;
815
816	if (vp)
817		vp->valid = 0;
818
819	head = INPCBHASH_PORT(table, lport);
820	LIST_FOREACH(inph, head, inph_lhash) {
821		inp = (struct inpcb *)inph;
822		if (inp->inp_af != AF_INET)
823			continue;
824
825		if (inp->inp_lport != lport)
826			continue;
827		wildcard = 0;
828		if (!in_nullhost(inp->inp_faddr))
829			wildcard++;
830		if (in_nullhost(inp->inp_laddr)) {
831			if (!in_nullhost(laddr))
832				wildcard++;
833		} else {
834			if (in_nullhost(laddr))
835				wildcard++;
836			else {
837				if (!in_hosteq(inp->inp_laddr, laddr))
838					continue;
839			}
840		}
841		if (wildcard && !lookup_wildcard)
842			continue;
843		if (wildcard < matchwild) {
844			match = inp;
845			matchwild = wildcard;
846			if (matchwild == 0)
847				break;
848		}
849	}
850	if (match && matchwild == 0)
851		return match;
852
853	if (vp && table->vestige) {
854		void	*state = (*table->vestige->init_ports4)(laddr, lport_arg, lookup_wildcard);
855		vestigial_inpcb_t better;
856
857		while (table->vestige
858		       && (*table->vestige->next_port4)(state, vp)) {
859
860			if (vp->lport != lport)
861				continue;
862			wildcard = 0;
863			if (!in_nullhost(vp->faddr.v4))
864				wildcard++;
865			if (in_nullhost(vp->laddr.v4)) {
866				if (!in_nullhost(laddr))
867					wildcard++;
868			} else {
869				if (in_nullhost(laddr))
870					wildcard++;
871				else {
872					if (!in_hosteq(vp->laddr.v4, laddr))
873						continue;
874				}
875			}
876			if (wildcard && !lookup_wildcard)
877				continue;
878			if (wildcard < matchwild) {
879				better = *vp;
880				match  = (void*)&better;
881
882				matchwild = wildcard;
883				if (matchwild == 0)
884					break;
885			}
886		}
887
888		if (match) {
889			if (match != (void*)&better)
890				return match;
891			else {
892				*vp = better;
893				return 0;
894			}
895		}
896	}
897
898	return (match);
899}
900
901#ifdef DIAGNOSTIC
902int	in_pcbnotifymiss = 0;
903#endif
904
905struct inpcb *
906in_pcblookup_connect(struct inpcbtable *table,
907    struct in_addr faddr, u_int fport_arg,
908    struct in_addr laddr, u_int lport_arg,
909    vestigial_inpcb_t *vp)
910{
911	struct inpcbhead *head;
912	struct inpcb_hdr *inph;
913	struct inpcb *inp;
914	u_int16_t fport = fport_arg, lport = lport_arg;
915
916	if (vp)
917		vp->valid = 0;
918
919	head = INPCBHASH_CONNECT(table, faddr, fport, laddr, lport);
920	LIST_FOREACH(inph, head, inph_hash) {
921		inp = (struct inpcb *)inph;
922		if (inp->inp_af != AF_INET)
923			continue;
924
925		if (in_hosteq(inp->inp_faddr, faddr) &&
926		    inp->inp_fport == fport &&
927		    inp->inp_lport == lport &&
928		    in_hosteq(inp->inp_laddr, laddr))
929			goto out;
930	}
931	if (vp && table->vestige) {
932		if ((*table->vestige->lookup4)(faddr, fport_arg,
933					       laddr, lport_arg, vp))
934			return 0;
935	}
936
937#ifdef DIAGNOSTIC
938	if (in_pcbnotifymiss) {
939		printf("in_pcblookup_connect: faddr=%08x fport=%d laddr=%08x lport=%d\n",
940		    ntohl(faddr.s_addr), ntohs(fport),
941		    ntohl(laddr.s_addr), ntohs(lport));
942	}
943#endif
944	return (0);
945
946out:
947	/* Move this PCB to the head of hash chain. */
948	inph = &inp->inp_head;
949	if (inph != LIST_FIRST(head)) {
950		LIST_REMOVE(inph, inph_hash);
951		LIST_INSERT_HEAD(head, inph, inph_hash);
952	}
953	return (inp);
954}
955
956struct inpcb *
957in_pcblookup_bind(struct inpcbtable *table,
958    struct in_addr laddr, u_int lport_arg)
959{
960	struct inpcbhead *head;
961	struct inpcb_hdr *inph;
962	struct inpcb *inp;
963	u_int16_t lport = lport_arg;
964
965	head = INPCBHASH_BIND(table, laddr, lport);
966	LIST_FOREACH(inph, head, inph_hash) {
967		inp = (struct inpcb *)inph;
968		if (inp->inp_af != AF_INET)
969			continue;
970
971		if (inp->inp_lport == lport &&
972		    in_hosteq(inp->inp_laddr, laddr))
973			goto out;
974	}
975	head = INPCBHASH_BIND(table, zeroin_addr, lport);
976	LIST_FOREACH(inph, head, inph_hash) {
977		inp = (struct inpcb *)inph;
978		if (inp->inp_af != AF_INET)
979			continue;
980
981		if (inp->inp_lport == lport &&
982		    in_hosteq(inp->inp_laddr, zeroin_addr))
983			goto out;
984	}
985#ifdef DIAGNOSTIC
986	if (in_pcbnotifymiss) {
987		printf("in_pcblookup_bind: laddr=%08x lport=%d\n",
988		    ntohl(laddr.s_addr), ntohs(lport));
989	}
990#endif
991	return (0);
992
993out:
994	/* Move this PCB to the head of hash chain. */
995	inph = &inp->inp_head;
996	if (inph != LIST_FIRST(head)) {
997		LIST_REMOVE(inph, inph_hash);
998		LIST_INSERT_HEAD(head, inph, inph_hash);
999	}
1000	return (inp);
1001}
1002
1003void
1004in_pcbstate(struct inpcb *inp, int state)
1005{
1006
1007	if (inp->inp_af != AF_INET)
1008		return;
1009
1010	if (inp->inp_state > INP_ATTACHED)
1011		LIST_REMOVE(&inp->inp_head, inph_hash);
1012
1013	switch (state) {
1014	case INP_BOUND:
1015		LIST_INSERT_HEAD(INPCBHASH_BIND(inp->inp_table,
1016		    inp->inp_laddr, inp->inp_lport), &inp->inp_head,
1017		    inph_hash);
1018		break;
1019	case INP_CONNECTED:
1020		LIST_INSERT_HEAD(INPCBHASH_CONNECT(inp->inp_table,
1021		    inp->inp_faddr, inp->inp_fport,
1022		    inp->inp_laddr, inp->inp_lport), &inp->inp_head,
1023		    inph_hash);
1024		break;
1025	}
1026
1027	inp->inp_state = state;
1028}
1029
1030struct rtentry *
1031in_pcbrtentry(struct inpcb *inp)
1032{
1033	struct route *ro;
1034	union {
1035		struct sockaddr		dst;
1036		struct sockaddr_in	dst4;
1037	} u;
1038
1039	if (inp->inp_af != AF_INET)
1040		return (NULL);
1041
1042	ro = &inp->inp_route;
1043
1044	sockaddr_in_init(&u.dst4, &inp->inp_faddr, 0);
1045	return rtcache_lookup(ro, &u.dst);
1046}
1047
1048struct sockaddr_in *
1049in_selectsrc(struct sockaddr_in *sin, struct route *ro,
1050    int soopts, struct ip_moptions *mopts, int *errorp)
1051{
1052	struct rtentry *rt = NULL;
1053	struct in_ifaddr *ia = NULL;
1054
1055	/*
1056         * If route is known or can be allocated now, take the
1057         * source address from the interface.  Otherwise, punt.
1058	 */
1059	if ((soopts & SO_DONTROUTE) != 0)
1060		rtcache_free(ro);
1061	else {
1062		union {
1063			struct sockaddr		dst;
1064			struct sockaddr_in	dst4;
1065		} u;
1066
1067		sockaddr_in_init(&u.dst4, &sin->sin_addr, 0);
1068		rt = rtcache_lookup(ro, &u.dst);
1069	}
1070	/*
1071	 * If we found a route, use the address
1072	 * corresponding to the outgoing interface
1073	 * unless it is the loopback (in case a route
1074	 * to our address on another net goes to loopback).
1075	 *
1076	 * XXX Is this still true?  Do we care?
1077	 */
1078	if (rt != NULL && (rt->rt_ifp->if_flags & IFF_LOOPBACK) == 0)
1079		ia = ifatoia(rt->rt_ifa);
1080	if (ia == NULL) {
1081		u_int16_t fport = sin->sin_port;
1082
1083		sin->sin_port = 0;
1084		ia = ifatoia(ifa_ifwithladdr(sintosa(sin)));
1085		sin->sin_port = fport;
1086		if (ia == NULL) {
1087			/* Find 1st non-loopback AF_INET address */
1088			TAILQ_FOREACH(ia, &in_ifaddrhead, ia_list) {
1089				if (!(ia->ia_ifp->if_flags & IFF_LOOPBACK))
1090					break;
1091			}
1092		}
1093		if (ia == NULL) {
1094			*errorp = EADDRNOTAVAIL;
1095			return NULL;
1096		}
1097	}
1098	/*
1099	 * If the destination address is multicast and an outgoing
1100	 * interface has been set as a multicast option, use the
1101	 * address of that interface as our source address.
1102	 */
1103	if (IN_MULTICAST(sin->sin_addr.s_addr) && mopts != NULL) {
1104		struct ip_moptions *imo;
1105		struct ifnet *ifp;
1106
1107		imo = mopts;
1108		if (imo->imo_multicast_ifp != NULL) {
1109			ifp = imo->imo_multicast_ifp;
1110			IFP_TO_IA(ifp, ia);		/* XXX */
1111			if (ia == 0) {
1112				*errorp = EADDRNOTAVAIL;
1113				return NULL;
1114			}
1115		}
1116	}
1117	if (ia->ia_ifa.ifa_getifa != NULL) {
1118		ia = ifatoia((*ia->ia_ifa.ifa_getifa)(&ia->ia_ifa,
1119		                                      sintosa(sin)));
1120	}
1121#ifdef GETIFA_DEBUG
1122	else
1123		printf("%s: missing ifa_getifa\n", __func__);
1124#endif
1125	return satosin(&ia->ia_addr);
1126}
1127