xref: /freebsd/sys/netinet/in_pcb.c (revision 0f8f86b71f022b803e99151c19db81b280f245dc)
1 /*
2  * Copyright (c) 1982, 1986, 1991, 1993, 1995
3  *	The Regents of the University of California.  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. All advertising materials mentioning features or use of this software
14  *    must display the following acknowledgement:
15  *	This product includes software developed by the University of
16  *	California, Berkeley and its contributors.
17  * 4. Neither the name of the University nor the names of its contributors
18  *    may be used to endorse or promote products derived from this software
19  *    without specific prior written permission.
20  *
21  * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
22  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
23  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
24  * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
25  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
26  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
27  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
28  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
29  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
30  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
31  * SUCH DAMAGE.
32  *
33  *	@(#)in_pcb.c	8.4 (Berkeley) 5/24/95
34  * $FreeBSD$
35  */
36 
37 #include "opt_ipsec.h"
38 #include "opt_inet6.h"
39 #include "opt_mac.h"
40 
41 #include <sys/param.h>
42 #include <sys/systm.h>
43 #include <sys/limits.h>
44 #include <sys/mac.h>
45 #include <sys/malloc.h>
46 #include <sys/mbuf.h>
47 #include <sys/domain.h>
48 #include <sys/protosw.h>
49 #include <sys/socket.h>
50 #include <sys/socketvar.h>
51 #include <sys/proc.h>
52 #include <sys/jail.h>
53 #include <sys/kernel.h>
54 #include <sys/sysctl.h>
55 
56 #include <vm/uma.h>
57 
58 #include <net/if.h>
59 #include <net/if_types.h>
60 #include <net/route.h>
61 
62 #include <netinet/in.h>
63 #include <netinet/in_pcb.h>
64 #include <netinet/in_var.h>
65 #include <netinet/ip_var.h>
66 #include <netinet/tcp_var.h>
67 #ifdef INET6
68 #include <netinet/ip6.h>
69 #include <netinet6/ip6_var.h>
70 #endif /* INET6 */
71 
72 #ifdef IPSEC
73 #include <netinet6/ipsec.h>
74 #include <netkey/key.h>
75 #endif /* IPSEC */
76 
77 #ifdef FAST_IPSEC
78 #if defined(IPSEC) || defined(IPSEC_ESP)
79 #error "Bad idea: don't compile with both IPSEC and FAST_IPSEC!"
80 #endif
81 
82 #include <netipsec/ipsec.h>
83 #include <netipsec/key.h>
84 #endif /* FAST_IPSEC */
85 
86 /*
87  * These configure the range of local port addresses assigned to
88  * "unspecified" outgoing connections/packets/whatever.
89  */
90 int	ipport_lowfirstauto  = IPPORT_RESERVED - 1;	/* 1023 */
91 int	ipport_lowlastauto = IPPORT_RESERVEDSTART;	/* 600 */
92 int	ipport_firstauto = IPPORT_HIFIRSTAUTO;		/* 49152 */
93 int	ipport_lastauto  = IPPORT_HILASTAUTO;		/* 65535 */
94 int	ipport_hifirstauto = IPPORT_HIFIRSTAUTO;	/* 49152 */
95 int	ipport_hilastauto  = IPPORT_HILASTAUTO;		/* 65535 */
96 
97 /*
98  * Reserved ports accessible only to root. There are significant
99  * security considerations that must be accounted for when changing these,
100  * but the security benefits can be great. Please be careful.
101  */
102 int	ipport_reservedhigh = IPPORT_RESERVED - 1;	/* 1023 */
103 int	ipport_reservedlow = 0;
104 
105 #define RANGECHK(var, min, max) \
106 	if ((var) < (min)) { (var) = (min); } \
107 	else if ((var) > (max)) { (var) = (max); }
108 
109 static int
110 sysctl_net_ipport_check(SYSCTL_HANDLER_ARGS)
111 {
112 	int error = sysctl_handle_int(oidp,
113 		oidp->oid_arg1, oidp->oid_arg2, req);
114 	if (!error) {
115 		RANGECHK(ipport_lowfirstauto, 1, IPPORT_RESERVED - 1);
116 		RANGECHK(ipport_lowlastauto, 1, IPPORT_RESERVED - 1);
117 		RANGECHK(ipport_firstauto, IPPORT_RESERVED, USHRT_MAX);
118 		RANGECHK(ipport_lastauto, IPPORT_RESERVED, USHRT_MAX);
119 		RANGECHK(ipport_hifirstauto, IPPORT_RESERVED, USHRT_MAX);
120 		RANGECHK(ipport_hilastauto, IPPORT_RESERVED, USHRT_MAX);
121 	}
122 	return error;
123 }
124 
125 #undef RANGECHK
126 
127 SYSCTL_NODE(_net_inet_ip, IPPROTO_IP, portrange, CTLFLAG_RW, 0, "IP Ports");
128 
129 SYSCTL_PROC(_net_inet_ip_portrange, OID_AUTO, lowfirst, CTLTYPE_INT|CTLFLAG_RW,
130 	   &ipport_lowfirstauto, 0, &sysctl_net_ipport_check, "I", "");
131 SYSCTL_PROC(_net_inet_ip_portrange, OID_AUTO, lowlast, CTLTYPE_INT|CTLFLAG_RW,
132 	   &ipport_lowlastauto, 0, &sysctl_net_ipport_check, "I", "");
133 SYSCTL_PROC(_net_inet_ip_portrange, OID_AUTO, first, CTLTYPE_INT|CTLFLAG_RW,
134 	   &ipport_firstauto, 0, &sysctl_net_ipport_check, "I", "");
135 SYSCTL_PROC(_net_inet_ip_portrange, OID_AUTO, last, CTLTYPE_INT|CTLFLAG_RW,
136 	   &ipport_lastauto, 0, &sysctl_net_ipport_check, "I", "");
137 SYSCTL_PROC(_net_inet_ip_portrange, OID_AUTO, hifirst, CTLTYPE_INT|CTLFLAG_RW,
138 	   &ipport_hifirstauto, 0, &sysctl_net_ipport_check, "I", "");
139 SYSCTL_PROC(_net_inet_ip_portrange, OID_AUTO, hilast, CTLTYPE_INT|CTLFLAG_RW,
140 	   &ipport_hilastauto, 0, &sysctl_net_ipport_check, "I", "");
141 SYSCTL_INT(_net_inet_ip_portrange, OID_AUTO, reservedhigh,
142 	   CTLFLAG_RW|CTLFLAG_SECURE, &ipport_reservedhigh, 0, "");
143 SYSCTL_INT(_net_inet_ip_portrange, OID_AUTO, reservedlow,
144 	   CTLFLAG_RW|CTLFLAG_SECURE, &ipport_reservedlow, 0, "");
145 
146 /*
147  * in_pcb.c: manage the Protocol Control Blocks.
148  *
149  * NOTE: It is assumed that most of these functions will be called at
150  * splnet(). XXX - There are, unfortunately, a few exceptions to this
151  * rule that should be fixed.
152  */
153 
154 /*
155  * Allocate a PCB and associate it with the socket.
156  */
157 int
158 in_pcballoc(so, pcbinfo, td, type)
159 	struct socket *so;
160 	struct inpcbinfo *pcbinfo;
161 	struct thread *td;
162 	const char *type;
163 {
164 	register struct inpcb *inp;
165 	int error;
166 
167 	INP_INFO_WLOCK_ASSERT(pcbinfo);
168 	error = 0;
169 	inp = uma_zalloc(pcbinfo->ipi_zone, M_NOWAIT | M_ZERO);
170 	if (inp == NULL)
171 		return (ENOBUFS);
172 	inp->inp_gencnt = ++pcbinfo->ipi_gencnt;
173 	inp->inp_pcbinfo = pcbinfo;
174 	inp->inp_socket = so;
175 #ifdef MAC
176 	error = mac_init_inpcb(inp, M_NOWAIT);
177 	if (error != 0)
178 		goto out;
179 	mac_create_inpcb_from_socket(so, inp);
180 #endif
181 #if defined(IPSEC) || defined(FAST_IPSEC)
182 #ifdef FAST_IPSEC
183 	error = ipsec_init_policy(so, &inp->inp_sp);
184 #else
185 	error = ipsec_init_pcbpolicy(so, &inp->inp_sp);
186 #endif
187 	if (error != 0)
188 		goto out;
189 #endif /*IPSEC*/
190 #if defined(INET6)
191 	if (INP_SOCKAF(so) == AF_INET6) {
192 		inp->inp_vflag |= INP_IPV6PROTO;
193 		if (ip6_v6only)
194 			inp->inp_flags |= IN6P_IPV6_V6ONLY;
195 	}
196 #endif
197 	LIST_INSERT_HEAD(pcbinfo->listhead, inp, inp_list);
198 	pcbinfo->ipi_count++;
199 	so->so_pcb = (caddr_t)inp;
200 	INP_LOCK_INIT(inp, "inp", type);
201 #ifdef INET6
202 	if (ip6_auto_flowlabel)
203 		inp->inp_flags |= IN6P_AUTOFLOWLABEL;
204 #endif
205 #if defined(IPSEC) || defined(FAST_IPSEC) || defined(MAC)
206 out:
207 	if (error != 0)
208 		uma_zfree(pcbinfo->ipi_zone, inp);
209 #endif
210 	return (error);
211 }
212 
213 int
214 in_pcbbind(inp, nam, td)
215 	register struct inpcb *inp;
216 	struct sockaddr *nam;
217 	struct thread *td;
218 {
219 	int anonport, error;
220 
221 	INP_INFO_WLOCK_ASSERT(inp->inp_pcbinfo);
222 	INP_LOCK_ASSERT(inp);
223 
224 	if (inp->inp_lport != 0 || inp->inp_laddr.s_addr != INADDR_ANY)
225 		return (EINVAL);
226 	anonport = inp->inp_lport == 0 && (nam == NULL ||
227 	    ((struct sockaddr_in *)nam)->sin_port == 0);
228 	error = in_pcbbind_setup(inp, nam, &inp->inp_laddr.s_addr,
229 	    &inp->inp_lport, td);
230 	if (error)
231 		return (error);
232 	if (in_pcbinshash(inp) != 0) {
233 		inp->inp_laddr.s_addr = INADDR_ANY;
234 		inp->inp_lport = 0;
235 		return (EAGAIN);
236 	}
237 	if (anonport)
238 		inp->inp_flags |= INP_ANONPORT;
239 	return (0);
240 }
241 
242 /*
243  * Set up a bind operation on a PCB, performing port allocation
244  * as required, but do not actually modify the PCB. Callers can
245  * either complete the bind by setting inp_laddr/inp_lport and
246  * calling in_pcbinshash(), or they can just use the resulting
247  * port and address to authorise the sending of a once-off packet.
248  *
249  * On error, the values of *laddrp and *lportp are not changed.
250  */
251 int
252 in_pcbbind_setup(inp, nam, laddrp, lportp, td)
253 	struct inpcb *inp;
254 	struct sockaddr *nam;
255 	in_addr_t *laddrp;
256 	u_short *lportp;
257 	struct thread *td;
258 {
259 	struct socket *so = inp->inp_socket;
260 	unsigned short *lastport;
261 	struct sockaddr_in *sin;
262 	struct inpcbinfo *pcbinfo = inp->inp_pcbinfo;
263 	struct in_addr laddr;
264 	u_short lport = 0;
265 	int wild = 0, reuseport = (so->so_options & SO_REUSEPORT);
266 	int error, prison = 0;
267 
268 	INP_INFO_WLOCK_ASSERT(pcbinfo);
269 	INP_LOCK_ASSERT(inp);
270 
271 	if (TAILQ_EMPTY(&in_ifaddrhead)) /* XXX broken! */
272 		return (EADDRNOTAVAIL);
273 	laddr.s_addr = *laddrp;
274 	if (nam != NULL && laddr.s_addr != INADDR_ANY)
275 		return (EINVAL);
276 	if ((so->so_options & (SO_REUSEADDR|SO_REUSEPORT)) == 0)
277 		wild = 1;
278 	if (nam) {
279 		sin = (struct sockaddr_in *)nam;
280 		if (nam->sa_len != sizeof (*sin))
281 			return (EINVAL);
282 #ifdef notdef
283 		/*
284 		 * We should check the family, but old programs
285 		 * incorrectly fail to initialize it.
286 		 */
287 		if (sin->sin_family != AF_INET)
288 			return (EAFNOSUPPORT);
289 #endif
290 		if (sin->sin_addr.s_addr != INADDR_ANY)
291 			if (prison_ip(td->td_ucred, 0, &sin->sin_addr.s_addr))
292 				return(EINVAL);
293 		if (sin->sin_port != *lportp) {
294 			/* Don't allow the port to change. */
295 			if (*lportp != 0)
296 				return (EINVAL);
297 			lport = sin->sin_port;
298 		}
299 		/* NB: lport is left as 0 if the port isn't being changed. */
300 		if (IN_MULTICAST(ntohl(sin->sin_addr.s_addr))) {
301 			/*
302 			 * Treat SO_REUSEADDR as SO_REUSEPORT for multicast;
303 			 * allow complete duplication of binding if
304 			 * SO_REUSEPORT is set, or if SO_REUSEADDR is set
305 			 * and a multicast address is bound on both
306 			 * new and duplicated sockets.
307 			 */
308 			if (so->so_options & SO_REUSEADDR)
309 				reuseport = SO_REUSEADDR|SO_REUSEPORT;
310 		} else if (sin->sin_addr.s_addr != INADDR_ANY) {
311 			sin->sin_port = 0;		/* yech... */
312 			bzero(&sin->sin_zero, sizeof(sin->sin_zero));
313 			if (ifa_ifwithaddr((struct sockaddr *)sin) == 0)
314 				return (EADDRNOTAVAIL);
315 		}
316 		laddr = sin->sin_addr;
317 		if (lport) {
318 			struct inpcb *t;
319 			/* GROSS */
320 			if (ntohs(lport) <= ipport_reservedhigh &&
321 			    ntohs(lport) >= ipport_reservedlow &&
322 			    td && suser_cred(td->td_ucred, PRISON_ROOT))
323 				return (EACCES);
324 			if (td && jailed(td->td_ucred))
325 				prison = 1;
326 			if (so->so_cred->cr_uid != 0 &&
327 			    !IN_MULTICAST(ntohl(sin->sin_addr.s_addr))) {
328 				t = in_pcblookup_local(inp->inp_pcbinfo,
329 				    sin->sin_addr, lport,
330 				    prison ? 0 :  INPLOOKUP_WILDCARD);
331 	/*
332 	 * XXX
333 	 * This entire block sorely needs a rewrite.
334 	 */
335 				if (t && (t->inp_vflag & INP_TIMEWAIT)) {
336 					if ((ntohl(sin->sin_addr.s_addr) != INADDR_ANY ||
337 					    ntohl(t->inp_laddr.s_addr) != INADDR_ANY ||
338 					    (intotw(t)->tw_so_options & SO_REUSEPORT) == 0) &&
339 					    (so->so_cred->cr_uid != intotw(t)->tw_cred->cr_uid))
340 						return (EADDRINUSE);
341 				} else
342 				if (t &&
343 				    (ntohl(sin->sin_addr.s_addr) != INADDR_ANY ||
344 				     ntohl(t->inp_laddr.s_addr) != INADDR_ANY ||
345 				     (t->inp_socket->so_options &
346 					 SO_REUSEPORT) == 0) &&
347 				    (so->so_cred->cr_uid !=
348 				     t->inp_socket->so_cred->cr_uid)) {
349 #if defined(INET6)
350 					if (ntohl(sin->sin_addr.s_addr) !=
351 					    INADDR_ANY ||
352 					    ntohl(t->inp_laddr.s_addr) !=
353 					    INADDR_ANY ||
354 					    INP_SOCKAF(so) ==
355 					    INP_SOCKAF(t->inp_socket))
356 #endif /* defined(INET6) */
357 					return (EADDRINUSE);
358 				}
359 			}
360 			if (prison &&
361 			    prison_ip(td->td_ucred, 0, &sin->sin_addr.s_addr))
362 				return (EADDRNOTAVAIL);
363 			t = in_pcblookup_local(pcbinfo, sin->sin_addr,
364 			    lport, prison ? 0 : wild);
365 			if (t && (t->inp_vflag & INP_TIMEWAIT)) {
366 				if ((reuseport & intotw(t)->tw_so_options) == 0)
367 					return (EADDRINUSE);
368 			} else
369 			if (t &&
370 			    (reuseport & t->inp_socket->so_options) == 0) {
371 #if defined(INET6)
372 				if (ntohl(sin->sin_addr.s_addr) !=
373 				    INADDR_ANY ||
374 				    ntohl(t->inp_laddr.s_addr) !=
375 				    INADDR_ANY ||
376 				    INP_SOCKAF(so) ==
377 				    INP_SOCKAF(t->inp_socket))
378 #endif /* defined(INET6) */
379 				return (EADDRINUSE);
380 			}
381 		}
382 	}
383 	if (*lportp != 0)
384 		lport = *lportp;
385 	if (lport == 0) {
386 		u_short first, last;
387 		int count;
388 
389 		if (laddr.s_addr != INADDR_ANY)
390 			if (prison_ip(td->td_ucred, 0, &laddr.s_addr))
391 				return (EINVAL);
392 
393 		if (inp->inp_flags & INP_HIGHPORT) {
394 			first = ipport_hifirstauto;	/* sysctl */
395 			last  = ipport_hilastauto;
396 			lastport = &pcbinfo->lasthi;
397 		} else if (inp->inp_flags & INP_LOWPORT) {
398 			if (td && (error = suser_cred(td->td_ucred,
399 			    PRISON_ROOT)) != 0)
400 				return error;
401 			first = ipport_lowfirstauto;	/* 1023 */
402 			last  = ipport_lowlastauto;	/* 600 */
403 			lastport = &pcbinfo->lastlow;
404 		} else {
405 			first = ipport_firstauto;	/* sysctl */
406 			last  = ipport_lastauto;
407 			lastport = &pcbinfo->lastport;
408 		}
409 		/*
410 		 * Simple check to ensure all ports are not used up causing
411 		 * a deadlock here.
412 		 *
413 		 * We split the two cases (up and down) so that the direction
414 		 * is not being tested on each round of the loop.
415 		 */
416 		if (first > last) {
417 			/*
418 			 * counting down
419 			 */
420 			count = first - last;
421 
422 			do {
423 				if (count-- < 0)	/* completely used? */
424 					return (EADDRNOTAVAIL);
425 				--*lastport;
426 				if (*lastport > first || *lastport < last)
427 					*lastport = first;
428 				lport = htons(*lastport);
429 			} while (in_pcblookup_local(pcbinfo, laddr, lport,
430 			    wild));
431 		} else {
432 			/*
433 			 * counting up
434 			 */
435 			count = last - first;
436 
437 			do {
438 				if (count-- < 0)	/* completely used? */
439 					return (EADDRNOTAVAIL);
440 				++*lastport;
441 				if (*lastport < first || *lastport > last)
442 					*lastport = first;
443 				lport = htons(*lastport);
444 			} while (in_pcblookup_local(pcbinfo, laddr, lport,
445 			    wild));
446 		}
447 	}
448 	if (prison_ip(td->td_ucred, 0, &laddr.s_addr))
449 		return (EINVAL);
450 	*laddrp = laddr.s_addr;
451 	*lportp = lport;
452 	return (0);
453 }
454 
455 /*
456  * Connect from a socket to a specified address.
457  * Both address and port must be specified in argument sin.
458  * If don't have a local address for this socket yet,
459  * then pick one.
460  */
461 int
462 in_pcbconnect(inp, nam, td)
463 	register struct inpcb *inp;
464 	struct sockaddr *nam;
465 	struct thread *td;
466 {
467 	u_short lport, fport;
468 	in_addr_t laddr, faddr;
469 	int anonport, error;
470 
471 	lport = inp->inp_lport;
472 	laddr = inp->inp_laddr.s_addr;
473 	anonport = (lport == 0);
474 	error = in_pcbconnect_setup(inp, nam, &laddr, &lport, &faddr, &fport,
475 	    NULL, td);
476 	if (error)
477 		return (error);
478 
479 	/* Do the initial binding of the local address if required. */
480 	if (inp->inp_laddr.s_addr == INADDR_ANY && inp->inp_lport == 0) {
481 		inp->inp_lport = lport;
482 		inp->inp_laddr.s_addr = laddr;
483 		if (in_pcbinshash(inp) != 0) {
484 			inp->inp_laddr.s_addr = INADDR_ANY;
485 			inp->inp_lport = 0;
486 			return (EAGAIN);
487 		}
488 	}
489 
490 	/* Commit the remaining changes. */
491 	inp->inp_lport = lport;
492 	inp->inp_laddr.s_addr = laddr;
493 	inp->inp_faddr.s_addr = faddr;
494 	inp->inp_fport = fport;
495 	in_pcbrehash(inp);
496 #ifdef IPSEC
497 	if (inp->inp_socket->so_type == SOCK_STREAM)
498 		ipsec_pcbconn(inp->inp_sp);
499 #endif
500 	if (anonport)
501 		inp->inp_flags |= INP_ANONPORT;
502 	return (0);
503 }
504 
505 /*
506  * Set up for a connect from a socket to the specified address.
507  * On entry, *laddrp and *lportp should contain the current local
508  * address and port for the PCB; these are updated to the values
509  * that should be placed in inp_laddr and inp_lport to complete
510  * the connect.
511  *
512  * On success, *faddrp and *fportp will be set to the remote address
513  * and port. These are not updated in the error case.
514  *
515  * If the operation fails because the connection already exists,
516  * *oinpp will be set to the PCB of that connection so that the
517  * caller can decide to override it. In all other cases, *oinpp
518  * is set to NULL.
519  */
520 int
521 in_pcbconnect_setup(inp, nam, laddrp, lportp, faddrp, fportp, oinpp, td)
522 	register struct inpcb *inp;
523 	struct sockaddr *nam;
524 	in_addr_t *laddrp;
525 	u_short *lportp;
526 	in_addr_t *faddrp;
527 	u_short *fportp;
528 	struct inpcb **oinpp;
529 	struct thread *td;
530 {
531 	struct sockaddr_in *sin = (struct sockaddr_in *)nam;
532 	struct in_ifaddr *ia;
533 	struct sockaddr_in sa;
534 	struct ucred *cred;
535 	struct inpcb *oinp;
536 	struct in_addr laddr, faddr;
537 	u_short lport, fport;
538 	int error;
539 
540 	if (oinpp != NULL)
541 		*oinpp = NULL;
542 	if (nam->sa_len != sizeof (*sin))
543 		return (EINVAL);
544 	if (sin->sin_family != AF_INET)
545 		return (EAFNOSUPPORT);
546 	if (sin->sin_port == 0)
547 		return (EADDRNOTAVAIL);
548 	laddr.s_addr = *laddrp;
549 	lport = *lportp;
550 	faddr = sin->sin_addr;
551 	fport = sin->sin_port;
552 	cred = inp->inp_socket->so_cred;
553 	if (laddr.s_addr == INADDR_ANY && jailed(cred)) {
554 		bzero(&sa, sizeof(sa));
555 		sa.sin_addr.s_addr = htonl(prison_getip(cred));
556 		sa.sin_len = sizeof(sa);
557 		sa.sin_family = AF_INET;
558 		error = in_pcbbind_setup(inp, (struct sockaddr *)&sa,
559 		    &laddr.s_addr, &lport, td);
560 		if (error)
561 			return (error);
562 	}
563 	if (!TAILQ_EMPTY(&in_ifaddrhead)) {
564 		/*
565 		 * If the destination address is INADDR_ANY,
566 		 * use the primary local address.
567 		 * If the supplied address is INADDR_BROADCAST,
568 		 * and the primary interface supports broadcast,
569 		 * choose the broadcast address for that interface.
570 		 */
571 		if (faddr.s_addr == INADDR_ANY)
572 			faddr = IA_SIN(TAILQ_FIRST(&in_ifaddrhead))->sin_addr;
573 		else if (faddr.s_addr == (u_long)INADDR_BROADCAST &&
574 		    (TAILQ_FIRST(&in_ifaddrhead)->ia_ifp->if_flags &
575 		    IFF_BROADCAST))
576 			faddr = satosin(&TAILQ_FIRST(
577 			    &in_ifaddrhead)->ia_broadaddr)->sin_addr;
578 	}
579 	if (laddr.s_addr == INADDR_ANY) {
580 		struct route sro;
581 
582 		bzero(&sro, sizeof(sro));
583 		ia = (struct in_ifaddr *)0;
584 		/*
585 		 * If route is known our src addr is taken from the i/f,
586 		 * else punt.
587 		 */
588 		if ((inp->inp_socket->so_options & SO_DONTROUTE) == 0) {
589 			/* Find out route to destination */
590 			sro.ro_dst.sa_family = AF_INET;
591 			sro.ro_dst.sa_len = sizeof(struct sockaddr_in);
592 			((struct sockaddr_in *)&sro.ro_dst)->sin_addr = faddr;
593 			rtalloc_ign(&sro, RTF_CLONING);
594 		}
595 		/*
596 		 * If we found a route, use the address
597 		 * corresponding to the outgoing interface
598 		 * unless it is the loopback (in case a route
599 		 * to our address on another net goes to loopback).
600 		 */
601 		if (sro.ro_rt && !(sro.ro_rt->rt_ifp->if_flags & IFF_LOOPBACK))
602 			ia = ifatoia(sro.ro_rt->rt_ifa);
603 		if (sro.ro_rt)
604 			RTFREE(sro.ro_rt);
605 		if (ia == 0) {
606 			bzero(&sa, sizeof(sa));
607 			sa.sin_addr = faddr;
608 			sa.sin_len = sizeof(sa);
609 			sa.sin_family = AF_INET;
610 
611 			ia = ifatoia(ifa_ifwithdstaddr(sintosa(&sa)));
612 			if (ia == 0)
613 				ia = ifatoia(ifa_ifwithnet(sintosa(&sa)));
614 			if (ia == 0)
615 				ia = TAILQ_FIRST(&in_ifaddrhead);
616 			if (ia == 0)
617 				return (EADDRNOTAVAIL);
618 		}
619 		/*
620 		 * If the destination address is multicast and an outgoing
621 		 * interface has been set as a multicast option, use the
622 		 * address of that interface as our source address.
623 		 */
624 		if (IN_MULTICAST(ntohl(faddr.s_addr)) &&
625 		    inp->inp_moptions != NULL) {
626 			struct ip_moptions *imo;
627 			struct ifnet *ifp;
628 
629 			imo = inp->inp_moptions;
630 			if (imo->imo_multicast_ifp != NULL) {
631 				ifp = imo->imo_multicast_ifp;
632 				TAILQ_FOREACH(ia, &in_ifaddrhead, ia_link)
633 					if (ia->ia_ifp == ifp)
634 						break;
635 				if (ia == 0)
636 					return (EADDRNOTAVAIL);
637 			}
638 		}
639 		laddr = ia->ia_addr.sin_addr;
640 	}
641 
642 	oinp = in_pcblookup_hash(inp->inp_pcbinfo, faddr, fport, laddr, lport,
643 	    0, NULL);
644 	if (oinp != NULL) {
645 		if (oinpp != NULL)
646 			*oinpp = oinp;
647 		return (EADDRINUSE);
648 	}
649 	if (lport == 0) {
650 		error = in_pcbbind_setup(inp, NULL, &laddr.s_addr, &lport, td);
651 		if (error)
652 			return (error);
653 	}
654 	*laddrp = laddr.s_addr;
655 	*lportp = lport;
656 	*faddrp = faddr.s_addr;
657 	*fportp = fport;
658 	return (0);
659 }
660 
661 void
662 in_pcbdisconnect(inp)
663 	struct inpcb *inp;
664 {
665 	INP_LOCK_ASSERT(inp);
666 
667 	inp->inp_faddr.s_addr = INADDR_ANY;
668 	inp->inp_fport = 0;
669 	in_pcbrehash(inp);
670 #ifdef IPSEC
671 	ipsec_pcbdisconn(inp->inp_sp);
672 #endif
673 	if (inp->inp_socket->so_state & SS_NOFDREF)
674 		in_pcbdetach(inp);
675 }
676 
677 void
678 in_pcbdetach(inp)
679 	struct inpcb *inp;
680 {
681 	struct socket *so = inp->inp_socket;
682 	struct inpcbinfo *ipi = inp->inp_pcbinfo;
683 
684 	INP_LOCK_ASSERT(inp);
685 
686 #if defined(IPSEC) || defined(FAST_IPSEC)
687 	ipsec4_delete_pcbpolicy(inp);
688 #endif /*IPSEC*/
689 	inp->inp_gencnt = ++ipi->ipi_gencnt;
690 	in_pcbremlists(inp);
691 	if (so) {
692 		so->so_pcb = 0;
693 		sotryfree(so);
694 	}
695 	if (inp->inp_options)
696 		(void)m_free(inp->inp_options);
697 	ip_freemoptions(inp->inp_moptions);
698 	inp->inp_vflag = 0;
699 	INP_LOCK_DESTROY(inp);
700 #ifdef MAC
701 	mac_destroy_inpcb(inp);
702 #endif
703 	uma_zfree(ipi->ipi_zone, inp);
704 }
705 
706 struct sockaddr *
707 in_sockaddr(port, addr_p)
708 	in_port_t port;
709 	struct in_addr *addr_p;
710 {
711 	struct sockaddr_in *sin;
712 
713 	MALLOC(sin, struct sockaddr_in *, sizeof *sin, M_SONAME,
714 		M_WAITOK | M_ZERO);
715 	sin->sin_family = AF_INET;
716 	sin->sin_len = sizeof(*sin);
717 	sin->sin_addr = *addr_p;
718 	sin->sin_port = port;
719 
720 	return (struct sockaddr *)sin;
721 }
722 
723 /*
724  * The wrapper function will pass down the pcbinfo for this function to lock.
725  * The socket must have a valid
726  * (i.e., non-nil) PCB, but it should be impossible to get an invalid one
727  * except through a kernel programming error, so it is acceptable to panic
728  * (or in this case trap) if the PCB is invalid.  (Actually, we don't trap
729  * because there actually /is/ a programming error somewhere... XXX)
730  */
731 int
732 in_setsockaddr(so, nam, pcbinfo)
733 	struct socket *so;
734 	struct sockaddr **nam;
735 	struct inpcbinfo *pcbinfo;
736 {
737 	int s;
738 	register struct inpcb *inp;
739 	struct in_addr addr;
740 	in_port_t port;
741 
742 	s = splnet();
743 	INP_INFO_RLOCK(pcbinfo);
744 	inp = sotoinpcb(so);
745 	if (!inp) {
746 		INP_INFO_RUNLOCK(pcbinfo);
747 		splx(s);
748 		return ECONNRESET;
749 	}
750 	INP_LOCK(inp);
751 	port = inp->inp_lport;
752 	addr = inp->inp_laddr;
753 	INP_UNLOCK(inp);
754 	INP_INFO_RUNLOCK(pcbinfo);
755 	splx(s);
756 
757 	*nam = in_sockaddr(port, &addr);
758 	return 0;
759 }
760 
761 /*
762  * The wrapper function will pass down the pcbinfo for this function to lock.
763  */
764 int
765 in_setpeeraddr(so, nam, pcbinfo)
766 	struct socket *so;
767 	struct sockaddr **nam;
768 	struct inpcbinfo *pcbinfo;
769 {
770 	int s;
771 	register struct inpcb *inp;
772 	struct in_addr addr;
773 	in_port_t port;
774 
775 	s = splnet();
776 	INP_INFO_RLOCK(pcbinfo);
777 	inp = sotoinpcb(so);
778 	if (!inp) {
779 		INP_INFO_RUNLOCK(pcbinfo);
780 		splx(s);
781 		return ECONNRESET;
782 	}
783 	INP_LOCK(inp);
784 	port = inp->inp_fport;
785 	addr = inp->inp_faddr;
786 	INP_UNLOCK(inp);
787 	INP_INFO_RUNLOCK(pcbinfo);
788 	splx(s);
789 
790 	*nam = in_sockaddr(port, &addr);
791 	return 0;
792 }
793 
794 void
795 in_pcbnotifyall(pcbinfo, faddr, errno, notify)
796 	struct inpcbinfo *pcbinfo;
797 	struct in_addr faddr;
798 	int errno;
799 	struct inpcb *(*notify)(struct inpcb *, int);
800 {
801 	struct inpcb *inp, *ninp;
802 	struct inpcbhead *head;
803 	int s;
804 
805 	s = splnet();
806 	INP_INFO_WLOCK(pcbinfo);
807 	head = pcbinfo->listhead;
808 	for (inp = LIST_FIRST(head); inp != NULL; inp = ninp) {
809 		INP_LOCK(inp);
810 		ninp = LIST_NEXT(inp, inp_list);
811 #ifdef INET6
812 		if ((inp->inp_vflag & INP_IPV4) == 0) {
813 			INP_UNLOCK(inp);
814 			continue;
815 		}
816 #endif
817 		if (inp->inp_faddr.s_addr != faddr.s_addr ||
818 		    inp->inp_socket == NULL) {
819 			INP_UNLOCK(inp);
820 			continue;
821 		}
822 		if ((*notify)(inp, errno))
823 			INP_UNLOCK(inp);
824 	}
825 	INP_INFO_WUNLOCK(pcbinfo);
826 	splx(s);
827 }
828 
829 void
830 in_pcbpurgeif0(pcbinfo, ifp)
831 	struct inpcbinfo *pcbinfo;
832 	struct ifnet *ifp;
833 {
834 	struct inpcb *inp;
835 	struct ip_moptions *imo;
836 	int i, gap;
837 
838 	/* why no splnet here? XXX */
839 	INP_INFO_RLOCK(pcbinfo);
840 	LIST_FOREACH(inp, pcbinfo->listhead, inp_list) {
841 		INP_LOCK(inp);
842 		imo = inp->inp_moptions;
843 		if ((inp->inp_vflag & INP_IPV4) &&
844 		    imo != NULL) {
845 			/*
846 			 * Unselect the outgoing interface if it is being
847 			 * detached.
848 			 */
849 			if (imo->imo_multicast_ifp == ifp)
850 				imo->imo_multicast_ifp = NULL;
851 
852 			/*
853 			 * Drop multicast group membership if we joined
854 			 * through the interface being detached.
855 			 */
856 			for (i = 0, gap = 0; i < imo->imo_num_memberships;
857 			    i++) {
858 				if (imo->imo_membership[i]->inm_ifp == ifp) {
859 					in_delmulti(imo->imo_membership[i]);
860 					gap++;
861 				} else if (gap != 0)
862 					imo->imo_membership[i - gap] =
863 					    imo->imo_membership[i];
864 			}
865 			imo->imo_num_memberships -= gap;
866 		}
867 		INP_UNLOCK(inp);
868 	}
869 	INP_INFO_RUNLOCK(pcbinfo);
870 }
871 
872 /*
873  * Lookup a PCB based on the local address and port.
874  */
875 struct inpcb *
876 in_pcblookup_local(pcbinfo, laddr, lport_arg, wild_okay)
877 	struct inpcbinfo *pcbinfo;
878 	struct in_addr laddr;
879 	u_int lport_arg;
880 	int wild_okay;
881 {
882 	register struct inpcb *inp;
883 	int matchwild = 3, wildcard;
884 	u_short lport = lport_arg;
885 
886 	INP_INFO_WLOCK_ASSERT(pcbinfo);
887 
888 	if (!wild_okay) {
889 		struct inpcbhead *head;
890 		/*
891 		 * Look for an unconnected (wildcard foreign addr) PCB that
892 		 * matches the local address and port we're looking for.
893 		 */
894 		head = &pcbinfo->hashbase[INP_PCBHASH(INADDR_ANY, lport, 0, pcbinfo->hashmask)];
895 		LIST_FOREACH(inp, head, inp_hash) {
896 #ifdef INET6
897 			if ((inp->inp_vflag & INP_IPV4) == 0)
898 				continue;
899 #endif
900 			if (inp->inp_faddr.s_addr == INADDR_ANY &&
901 			    inp->inp_laddr.s_addr == laddr.s_addr &&
902 			    inp->inp_lport == lport) {
903 				/*
904 				 * Found.
905 				 */
906 				return (inp);
907 			}
908 		}
909 		/*
910 		 * Not found.
911 		 */
912 		return (NULL);
913 	} else {
914 		struct inpcbporthead *porthash;
915 		struct inpcbport *phd;
916 		struct inpcb *match = NULL;
917 		/*
918 		 * Best fit PCB lookup.
919 		 *
920 		 * First see if this local port is in use by looking on the
921 		 * port hash list.
922 		 */
923 		retrylookup:
924 		porthash = &pcbinfo->porthashbase[INP_PCBPORTHASH(lport,
925 		    pcbinfo->porthashmask)];
926 		LIST_FOREACH(phd, porthash, phd_hash) {
927 			if (phd->phd_port == lport)
928 				break;
929 		}
930 		if (phd != NULL) {
931 			/*
932 			 * Port is in use by one or more PCBs. Look for best
933 			 * fit.
934 			 */
935 			LIST_FOREACH(inp, &phd->phd_pcblist, inp_portlist) {
936 				wildcard = 0;
937 #ifdef INET6
938 				if ((inp->inp_vflag & INP_IPV4) == 0)
939 					continue;
940 #endif
941 				/*
942 				 * Clean out old time_wait sockets if they
943 				 * are clogging up needed local ports.
944 				 */
945 				if ((inp->inp_vflag & INP_TIMEWAIT) != 0) {
946 					if (tcp_twrecycleable((struct tcptw *)inp->inp_ppcb)) {
947 						INP_LOCK(inp);
948 						tcp_twclose((struct tcptw *)inp->inp_ppcb, 0);
949 						match = NULL;
950 						goto retrylookup;
951 					}
952 				}
953 				if (inp->inp_faddr.s_addr != INADDR_ANY)
954 					wildcard++;
955 				if (inp->inp_laddr.s_addr != INADDR_ANY) {
956 					if (laddr.s_addr == INADDR_ANY)
957 						wildcard++;
958 					else if (inp->inp_laddr.s_addr != laddr.s_addr)
959 						continue;
960 				} else {
961 					if (laddr.s_addr != INADDR_ANY)
962 						wildcard++;
963 				}
964 				if (wildcard < matchwild) {
965 					match = inp;
966 					matchwild = wildcard;
967 					if (matchwild == 0) {
968 						break;
969 					}
970 				}
971 			}
972 		}
973 		return (match);
974 	}
975 }
976 
977 /*
978  * Lookup PCB in hash list.
979  */
980 struct inpcb *
981 in_pcblookup_hash(pcbinfo, faddr, fport_arg, laddr, lport_arg, wildcard,
982 		  ifp)
983 	struct inpcbinfo *pcbinfo;
984 	struct in_addr faddr, laddr;
985 	u_int fport_arg, lport_arg;
986 	int wildcard;
987 	struct ifnet *ifp;
988 {
989 	struct inpcbhead *head;
990 	register struct inpcb *inp;
991 	u_short fport = fport_arg, lport = lport_arg;
992 
993 	INP_INFO_RLOCK_ASSERT(pcbinfo);
994 	/*
995 	 * First look for an exact match.
996 	 */
997 	head = &pcbinfo->hashbase[INP_PCBHASH(faddr.s_addr, lport, fport, pcbinfo->hashmask)];
998 	LIST_FOREACH(inp, head, inp_hash) {
999 #ifdef INET6
1000 		if ((inp->inp_vflag & INP_IPV4) == 0)
1001 			continue;
1002 #endif
1003 		if (inp->inp_faddr.s_addr == faddr.s_addr &&
1004 		    inp->inp_laddr.s_addr == laddr.s_addr &&
1005 		    inp->inp_fport == fport &&
1006 		    inp->inp_lport == lport) {
1007 			/*
1008 			 * Found.
1009 			 */
1010 			return (inp);
1011 		}
1012 	}
1013 	if (wildcard) {
1014 		struct inpcb *local_wild = NULL;
1015 #if defined(INET6)
1016 		struct inpcb *local_wild_mapped = NULL;
1017 #endif /* defined(INET6) */
1018 
1019 		head = &pcbinfo->hashbase[INP_PCBHASH(INADDR_ANY, lport, 0, pcbinfo->hashmask)];
1020 		LIST_FOREACH(inp, head, inp_hash) {
1021 #ifdef INET6
1022 			if ((inp->inp_vflag & INP_IPV4) == 0)
1023 				continue;
1024 #endif
1025 			if (inp->inp_faddr.s_addr == INADDR_ANY &&
1026 			    inp->inp_lport == lport) {
1027 				if (ifp && ifp->if_type == IFT_FAITH &&
1028 				    (inp->inp_flags & INP_FAITH) == 0)
1029 					continue;
1030 				if (inp->inp_laddr.s_addr == laddr.s_addr)
1031 					return (inp);
1032 				else if (inp->inp_laddr.s_addr == INADDR_ANY) {
1033 #if defined(INET6)
1034 					if (INP_CHECK_SOCKAF(inp->inp_socket,
1035 							     AF_INET6))
1036 						local_wild_mapped = inp;
1037 					else
1038 #endif /* defined(INET6) */
1039 					local_wild = inp;
1040 				}
1041 			}
1042 		}
1043 #if defined(INET6)
1044 		if (local_wild == NULL)
1045 			return (local_wild_mapped);
1046 #endif /* defined(INET6) */
1047 		return (local_wild);
1048 	}
1049 
1050 	/*
1051 	 * Not found.
1052 	 */
1053 	return (NULL);
1054 }
1055 
1056 /*
1057  * Insert PCB onto various hash lists.
1058  */
1059 int
1060 in_pcbinshash(inp)
1061 	struct inpcb *inp;
1062 {
1063 	struct inpcbhead *pcbhash;
1064 	struct inpcbporthead *pcbporthash;
1065 	struct inpcbinfo *pcbinfo = inp->inp_pcbinfo;
1066 	struct inpcbport *phd;
1067 	u_int32_t hashkey_faddr;
1068 
1069 	INP_INFO_WLOCK_ASSERT(pcbinfo);
1070 #ifdef INET6
1071 	if (inp->inp_vflag & INP_IPV6)
1072 		hashkey_faddr = inp->in6p_faddr.s6_addr32[3] /* XXX */;
1073 	else
1074 #endif /* INET6 */
1075 	hashkey_faddr = inp->inp_faddr.s_addr;
1076 
1077 	pcbhash = &pcbinfo->hashbase[INP_PCBHASH(hashkey_faddr,
1078 		 inp->inp_lport, inp->inp_fport, pcbinfo->hashmask)];
1079 
1080 	pcbporthash = &pcbinfo->porthashbase[INP_PCBPORTHASH(inp->inp_lport,
1081 	    pcbinfo->porthashmask)];
1082 
1083 	/*
1084 	 * Go through port list and look for a head for this lport.
1085 	 */
1086 	LIST_FOREACH(phd, pcbporthash, phd_hash) {
1087 		if (phd->phd_port == inp->inp_lport)
1088 			break;
1089 	}
1090 	/*
1091 	 * If none exists, malloc one and tack it on.
1092 	 */
1093 	if (phd == NULL) {
1094 		MALLOC(phd, struct inpcbport *, sizeof(struct inpcbport), M_PCB, M_NOWAIT);
1095 		if (phd == NULL) {
1096 			return (ENOBUFS); /* XXX */
1097 		}
1098 		phd->phd_port = inp->inp_lport;
1099 		LIST_INIT(&phd->phd_pcblist);
1100 		LIST_INSERT_HEAD(pcbporthash, phd, phd_hash);
1101 	}
1102 	inp->inp_phd = phd;
1103 	LIST_INSERT_HEAD(&phd->phd_pcblist, inp, inp_portlist);
1104 	LIST_INSERT_HEAD(pcbhash, inp, inp_hash);
1105 	return (0);
1106 }
1107 
1108 /*
1109  * Move PCB to the proper hash bucket when { faddr, fport } have  been
1110  * changed. NOTE: This does not handle the case of the lport changing (the
1111  * hashed port list would have to be updated as well), so the lport must
1112  * not change after in_pcbinshash() has been called.
1113  */
1114 void
1115 in_pcbrehash(inp)
1116 	struct inpcb *inp;
1117 {
1118 	struct inpcbinfo *pcbinfo = inp->inp_pcbinfo;
1119 	struct inpcbhead *head;
1120 	u_int32_t hashkey_faddr;
1121 
1122 	INP_INFO_WLOCK_ASSERT(pcbinfo);
1123 	/* XXX? INP_LOCK_ASSERT(inp); */
1124 #ifdef INET6
1125 	if (inp->inp_vflag & INP_IPV6)
1126 		hashkey_faddr = inp->in6p_faddr.s6_addr32[3] /* XXX */;
1127 	else
1128 #endif /* INET6 */
1129 	hashkey_faddr = inp->inp_faddr.s_addr;
1130 
1131 	head = &pcbinfo->hashbase[INP_PCBHASH(hashkey_faddr,
1132 		inp->inp_lport, inp->inp_fport, pcbinfo->hashmask)];
1133 
1134 	LIST_REMOVE(inp, inp_hash);
1135 	LIST_INSERT_HEAD(head, inp, inp_hash);
1136 }
1137 
1138 /*
1139  * Remove PCB from various lists.
1140  */
1141 void
1142 in_pcbremlists(inp)
1143 	struct inpcb *inp;
1144 {
1145 	struct inpcbinfo *pcbinfo = inp->inp_pcbinfo;
1146 
1147 	INP_INFO_WLOCK_ASSERT(pcbinfo);
1148 	INP_LOCK_ASSERT(inp);
1149 
1150 	inp->inp_gencnt = ++pcbinfo->ipi_gencnt;
1151 	if (inp->inp_lport) {
1152 		struct inpcbport *phd = inp->inp_phd;
1153 
1154 		LIST_REMOVE(inp, inp_hash);
1155 		LIST_REMOVE(inp, inp_portlist);
1156 		if (LIST_FIRST(&phd->phd_pcblist) == NULL) {
1157 			LIST_REMOVE(phd, phd_hash);
1158 			free(phd, M_PCB);
1159 		}
1160 	}
1161 	LIST_REMOVE(inp, inp_list);
1162 	pcbinfo->ipi_count--;
1163 }
1164 
1165 /*
1166  * A set label operation has occurred at the socket layer, propagate the
1167  * label change into the in_pcb for the socket.
1168  */
1169 void
1170 in_pcbsosetlabel(so)
1171 	struct socket *so;
1172 {
1173 #ifdef MAC
1174 	struct inpcb *inp;
1175 
1176 	/* XXX: Will assert socket lock when we have them. */
1177 	inp = (struct inpcb *)so->so_pcb;
1178 	INP_LOCK(inp);
1179 	mac_inpcb_sosetlabel(so, inp);
1180 	INP_UNLOCK(inp);
1181 #endif
1182 }
1183 
1184 int
1185 prison_xinpcb(struct thread *td, struct inpcb *inp)
1186 {
1187 	if (!jailed(td->td_ucred))
1188 		return (0);
1189 	if (ntohl(inp->inp_laddr.s_addr) == prison_getip(td->td_ucred))
1190 		return (0);
1191 	return (1);
1192 }
1193