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