xref: /freebsd/sys/netinet/in_pcb.c (revision 64db83a8ab2d1f72a9b2174b39d2ef42b5b0580c)
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/vm_zone.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 #ifdef INET6
66 #include <netinet/ip6.h>
67 #include <netinet6/ip6_var.h>
68 #endif /* INET6 */
69 
70 #include "faith.h"
71 
72 #ifdef IPSEC
73 #include <netinet6/ipsec.h>
74 #include <netkey/key.h>
75 #include <netkey/key_debug.h>
76 #endif /* IPSEC */
77 
78 struct	in_addr zeroin_addr;
79 
80 static void	in_rtchange __P((struct inpcb *, int));
81 
82 /*
83  * These configure the range of local port addresses assigned to
84  * "unspecified" outgoing connections/packets/whatever.
85  */
86 int	ipport_lowfirstauto  = IPPORT_RESERVED - 1;	/* 1023 */
87 int	ipport_lowlastauto = IPPORT_RESERVEDSTART;	/* 600 */
88 int	ipport_firstauto = IPPORT_RESERVED;		/* 1024 */
89 int	ipport_lastauto  = IPPORT_USERRESERVED;		/* 5000 */
90 int	ipport_hifirstauto = IPPORT_HIFIRSTAUTO;	/* 49152 */
91 int	ipport_hilastauto  = IPPORT_HILASTAUTO;		/* 65535 */
92 
93 #define RANGECHK(var, min, max) \
94 	if ((var) < (min)) { (var) = (min); } \
95 	else if ((var) > (max)) { (var) = (max); }
96 
97 static int
98 sysctl_net_ipport_check SYSCTL_HANDLER_ARGS
99 {
100 	int error = sysctl_handle_int(oidp,
101 		oidp->oid_arg1, oidp->oid_arg2, req);
102 	if (!error) {
103 		RANGECHK(ipport_lowfirstauto, 1, IPPORT_RESERVED - 1);
104 		RANGECHK(ipport_lowlastauto, 1, IPPORT_RESERVED - 1);
105 		RANGECHK(ipport_firstauto, IPPORT_RESERVED, USHRT_MAX);
106 		RANGECHK(ipport_lastauto, IPPORT_RESERVED, USHRT_MAX);
107 		RANGECHK(ipport_hifirstauto, IPPORT_RESERVED, USHRT_MAX);
108 		RANGECHK(ipport_hilastauto, IPPORT_RESERVED, USHRT_MAX);
109 	}
110 	return error;
111 }
112 
113 #undef RANGECHK
114 
115 SYSCTL_NODE(_net_inet_ip, IPPROTO_IP, portrange, CTLFLAG_RW, 0, "IP Ports");
116 
117 SYSCTL_PROC(_net_inet_ip_portrange, OID_AUTO, lowfirst, CTLTYPE_INT|CTLFLAG_RW,
118 	   &ipport_lowfirstauto, 0, &sysctl_net_ipport_check, "I", "");
119 SYSCTL_PROC(_net_inet_ip_portrange, OID_AUTO, lowlast, CTLTYPE_INT|CTLFLAG_RW,
120 	   &ipport_lowlastauto, 0, &sysctl_net_ipport_check, "I", "");
121 SYSCTL_PROC(_net_inet_ip_portrange, OID_AUTO, first, CTLTYPE_INT|CTLFLAG_RW,
122 	   &ipport_firstauto, 0, &sysctl_net_ipport_check, "I", "");
123 SYSCTL_PROC(_net_inet_ip_portrange, OID_AUTO, last, CTLTYPE_INT|CTLFLAG_RW,
124 	   &ipport_lastauto, 0, &sysctl_net_ipport_check, "I", "");
125 SYSCTL_PROC(_net_inet_ip_portrange, OID_AUTO, hifirst, CTLTYPE_INT|CTLFLAG_RW,
126 	   &ipport_hifirstauto, 0, &sysctl_net_ipport_check, "I", "");
127 SYSCTL_PROC(_net_inet_ip_portrange, OID_AUTO, hilast, CTLTYPE_INT|CTLFLAG_RW,
128 	   &ipport_hilastauto, 0, &sysctl_net_ipport_check, "I", "");
129 
130 /*
131  * in_pcb.c: manage the Protocol Control Blocks.
132  *
133  * NOTE: It is assumed that most of these functions will be called at
134  * splnet(). XXX - There are, unfortunately, a few exceptions to this
135  * rule that should be fixed.
136  */
137 
138 /*
139  * Allocate a PCB and associate it with the socket.
140  */
141 int
142 in_pcballoc(so, pcbinfo, p)
143 	struct socket *so;
144 	struct inpcbinfo *pcbinfo;
145 	struct proc *p;
146 {
147 	register struct inpcb *inp;
148 
149 	inp = zalloci(pcbinfo->ipi_zone);
150 	if (inp == NULL)
151 		return (ENOBUFS);
152 	bzero((caddr_t)inp, sizeof(*inp));
153 	inp->inp_gencnt = ++pcbinfo->ipi_gencnt;
154 	inp->inp_pcbinfo = pcbinfo;
155 	inp->inp_socket = so;
156 #if defined(INET6)
157 	if (ip6_mapped_addr_on)
158 		inp->inp_flags &= ~IN6P_BINDV6ONLY;
159 	else
160 		inp->inp_flags |= IN6P_BINDV6ONLY;
161 #endif
162 	LIST_INSERT_HEAD(pcbinfo->listhead, inp, inp_list);
163 	pcbinfo->ipi_count++;
164 	so->so_pcb = (caddr_t)inp;
165 	return (0);
166 }
167 
168 int
169 in_pcbbind(inp, nam, p)
170 	register struct inpcb *inp;
171 	struct sockaddr *nam;
172 	struct proc *p;
173 {
174 	register struct socket *so = inp->inp_socket;
175 	unsigned short *lastport;
176 	struct sockaddr_in *sin;
177 	struct inpcbinfo *pcbinfo = inp->inp_pcbinfo;
178 	u_short lport = 0;
179 	int wild = 0, reuseport = (so->so_options & SO_REUSEPORT);
180 	int error, prison = 0;
181 
182 	if (TAILQ_EMPTY(&in_ifaddrhead)) /* XXX broken! */
183 		return (EADDRNOTAVAIL);
184 	if (inp->inp_lport || inp->inp_laddr.s_addr != INADDR_ANY)
185 		return (EINVAL);
186 	if ((so->so_options & (SO_REUSEADDR|SO_REUSEPORT)) == 0)
187 		wild = 1;
188 	if (nam) {
189 		sin = (struct sockaddr_in *)nam;
190 		if (nam->sa_len != sizeof (*sin))
191 			return (EINVAL);
192 #ifdef notdef
193 		/*
194 		 * We should check the family, but old programs
195 		 * incorrectly fail to initialize it.
196 		 */
197 		if (sin->sin_family != AF_INET)
198 			return (EAFNOSUPPORT);
199 #endif
200 		if (prison_ip(p, 0, &sin->sin_addr.s_addr))
201 			return(EINVAL);
202 		lport = sin->sin_port;
203 		if (IN_MULTICAST(ntohl(sin->sin_addr.s_addr))) {
204 			/*
205 			 * Treat SO_REUSEADDR as SO_REUSEPORT for multicast;
206 			 * allow complete duplication of binding if
207 			 * SO_REUSEPORT is set, or if SO_REUSEADDR is set
208 			 * and a multicast address is bound on both
209 			 * new and duplicated sockets.
210 			 */
211 			if (so->so_options & SO_REUSEADDR)
212 				reuseport = SO_REUSEADDR|SO_REUSEPORT;
213 		} else if (sin->sin_addr.s_addr != INADDR_ANY) {
214 			sin->sin_port = 0;		/* yech... */
215 			if (ifa_ifwithaddr((struct sockaddr *)sin) == 0)
216 				return (EADDRNOTAVAIL);
217 		}
218 		if (lport) {
219 			struct inpcb *t;
220 
221 			/* GROSS */
222 			if (ntohs(lport) < IPPORT_RESERVED && p &&
223 			    suser_xxx(0, p, PRISON_ROOT))
224 				return (EACCES);
225 			if (p && p->p_prison)
226 				prison = 1;
227 			if (so->so_cred->cr_uid != 0 &&
228 			    !IN_MULTICAST(ntohl(sin->sin_addr.s_addr))) {
229 				t = in_pcblookup_local(inp->inp_pcbinfo,
230 				    sin->sin_addr, lport,
231 				    prison ? 0 :  INPLOOKUP_WILDCARD);
232 				if (t &&
233 				    (ntohl(sin->sin_addr.s_addr) != INADDR_ANY ||
234 				     ntohl(t->inp_laddr.s_addr) != INADDR_ANY ||
235 				     (t->inp_socket->so_options &
236 					 SO_REUSEPORT) == 0) &&
237 				    (so->so_cred->cr_uid !=
238 				     t->inp_socket->so_cred->cr_uid)) {
239 #if defined(INET6)
240 					if ((inp->inp_flags &
241 					     IN6P_BINDV6ONLY) != 0 ||
242 					    ntohl(sin->sin_addr.s_addr) !=
243 					    INADDR_ANY ||
244 					    ntohl(t->inp_laddr.s_addr) !=
245 					    INADDR_ANY ||
246 					    INP_SOCKAF(so) ==
247 					    INP_SOCKAF(t->inp_socket))
248 #endif /* defined(INET6) */
249 					return (EADDRINUSE);
250 				}
251 			}
252 			t = in_pcblookup_local(pcbinfo, sin->sin_addr,
253 			    lport, prison ? 0 : wild);
254 			if (t &&
255 			    (reuseport & t->inp_socket->so_options) == 0) {
256 #if defined(INET6)
257 				if ((inp->inp_flags & IN6P_BINDV6ONLY) != 0 ||
258 				    ntohl(sin->sin_addr.s_addr) !=
259 				    INADDR_ANY ||
260 				    ntohl(t->inp_laddr.s_addr) !=
261 				    INADDR_ANY ||
262 				    INP_SOCKAF(so) ==
263 				    INP_SOCKAF(t->inp_socket))
264 #endif /* defined(INET6) */
265 				return (EADDRINUSE);
266 			}
267 		}
268 		inp->inp_laddr = sin->sin_addr;
269 	}
270 	if (lport == 0) {
271 		ushort first, last;
272 		int count;
273 
274 		if (prison_ip(p, 0, &inp->inp_laddr.s_addr ))
275 			return (EINVAL);
276 		inp->inp_flags |= INP_ANONPORT;
277 
278 		if (inp->inp_flags & INP_HIGHPORT) {
279 			first = ipport_hifirstauto;	/* sysctl */
280 			last  = ipport_hilastauto;
281 			lastport = &pcbinfo->lasthi;
282 		} else if (inp->inp_flags & INP_LOWPORT) {
283 			if (p && (error = suser_xxx(0, p, PRISON_ROOT)))
284 				return error;
285 			first = ipport_lowfirstauto;	/* 1023 */
286 			last  = ipport_lowlastauto;	/* 600 */
287 			lastport = &pcbinfo->lastlow;
288 		} else {
289 			first = ipport_firstauto;	/* sysctl */
290 			last  = ipport_lastauto;
291 			lastport = &pcbinfo->lastport;
292 		}
293 		/*
294 		 * Simple check to ensure all ports are not used up causing
295 		 * a deadlock here.
296 		 *
297 		 * We split the two cases (up and down) so that the direction
298 		 * is not being tested on each round of the loop.
299 		 */
300 		if (first > last) {
301 			/*
302 			 * counting down
303 			 */
304 			count = first - last;
305 
306 			do {
307 				if (count-- < 0) {	/* completely used? */
308 					/*
309 					 * Undo any address bind that may have
310 					 * occurred above.
311 					 */
312 					inp->inp_laddr.s_addr = INADDR_ANY;
313 					return (EAGAIN);
314 				}
315 				--*lastport;
316 				if (*lastport > first || *lastport < last)
317 					*lastport = first;
318 				lport = htons(*lastport);
319 			} while (in_pcblookup_local(pcbinfo,
320 				 inp->inp_laddr, lport, wild));
321 		} else {
322 			/*
323 			 * counting up
324 			 */
325 			count = last - first;
326 
327 			do {
328 				if (count-- < 0) {	/* completely used? */
329 					/*
330 					 * Undo any address bind that may have
331 					 * occurred above.
332 					 */
333 					inp->inp_laddr.s_addr = INADDR_ANY;
334 					return (EAGAIN);
335 				}
336 				++*lastport;
337 				if (*lastport < first || *lastport > last)
338 					*lastport = first;
339 				lport = htons(*lastport);
340 			} while (in_pcblookup_local(pcbinfo,
341 				 inp->inp_laddr, lport, wild));
342 		}
343 	}
344 	inp->inp_lport = lport;
345 	if (in_pcbinshash(inp) != 0) {
346 		inp->inp_laddr.s_addr = INADDR_ANY;
347 		inp->inp_lport = 0;
348 		return (EAGAIN);
349 	}
350 	return (0);
351 }
352 
353 /*
354  *   Transform old in_pcbconnect() into an inner subroutine for new
355  *   in_pcbconnect(): Do some validity-checking on the remote
356  *   address (in mbuf 'nam') and then determine local host address
357  *   (i.e., which interface) to use to access that remote host.
358  *
359  *   This preserves definition of in_pcbconnect(), while supporting a
360  *   slightly different version for T/TCP.  (This is more than
361  *   a bit of a kludge, but cleaning up the internal interfaces would
362  *   have forced minor changes in every protocol).
363  */
364 
365 int
366 in_pcbladdr(inp, nam, plocal_sin)
367 	register struct inpcb *inp;
368 	struct sockaddr *nam;
369 	struct sockaddr_in **plocal_sin;
370 {
371 	struct in_ifaddr *ia;
372 	register struct sockaddr_in *sin = (struct sockaddr_in *)nam;
373 
374 	if (nam->sa_len != sizeof (*sin))
375 		return (EINVAL);
376 	if (sin->sin_family != AF_INET)
377 		return (EAFNOSUPPORT);
378 	if (sin->sin_port == 0)
379 		return (EADDRNOTAVAIL);
380 	if (!TAILQ_EMPTY(&in_ifaddrhead)) {
381 		/*
382 		 * If the destination address is INADDR_ANY,
383 		 * use the primary local address.
384 		 * If the supplied address is INADDR_BROADCAST,
385 		 * and the primary interface supports broadcast,
386 		 * choose the broadcast address for that interface.
387 		 */
388 #define	satosin(sa)	((struct sockaddr_in *)(sa))
389 #define sintosa(sin)	((struct sockaddr *)(sin))
390 #define ifatoia(ifa)	((struct in_ifaddr *)(ifa))
391 		if (sin->sin_addr.s_addr == INADDR_ANY)
392 		    sin->sin_addr = IA_SIN(in_ifaddrhead.tqh_first)->sin_addr;
393 		else if (sin->sin_addr.s_addr == (u_long)INADDR_BROADCAST &&
394 		  (in_ifaddrhead.tqh_first->ia_ifp->if_flags & IFF_BROADCAST))
395 		    sin->sin_addr = satosin(&in_ifaddrhead.tqh_first->ia_broadaddr)->sin_addr;
396 	}
397 	if (inp->inp_laddr.s_addr == INADDR_ANY) {
398 		register struct route *ro;
399 
400 		ia = (struct in_ifaddr *)0;
401 		/*
402 		 * If route is known or can be allocated now,
403 		 * our src addr is taken from the i/f, else punt.
404 		 */
405 		ro = &inp->inp_route;
406 		if (ro->ro_rt &&
407 		    (satosin(&ro->ro_dst)->sin_addr.s_addr !=
408 			sin->sin_addr.s_addr ||
409 		    inp->inp_socket->so_options & SO_DONTROUTE)) {
410 			RTFREE(ro->ro_rt);
411 			ro->ro_rt = (struct rtentry *)0;
412 		}
413 		if ((inp->inp_socket->so_options & SO_DONTROUTE) == 0 && /*XXX*/
414 		    (ro->ro_rt == (struct rtentry *)0 ||
415 		    ro->ro_rt->rt_ifp == (struct ifnet *)0)) {
416 			/* No route yet, so try to acquire one */
417 			ro->ro_dst.sa_family = AF_INET;
418 			ro->ro_dst.sa_len = sizeof(struct sockaddr_in);
419 			((struct sockaddr_in *) &ro->ro_dst)->sin_addr =
420 				sin->sin_addr;
421 			rtalloc(ro);
422 		}
423 		/*
424 		 * If we found a route, use the address
425 		 * corresponding to the outgoing interface
426 		 * unless it is the loopback (in case a route
427 		 * to our address on another net goes to loopback).
428 		 */
429 		if (ro->ro_rt && !(ro->ro_rt->rt_ifp->if_flags & IFF_LOOPBACK))
430 			ia = ifatoia(ro->ro_rt->rt_ifa);
431 		if (ia == 0) {
432 			u_short fport = sin->sin_port;
433 
434 			sin->sin_port = 0;
435 			ia = ifatoia(ifa_ifwithdstaddr(sintosa(sin)));
436 			if (ia == 0)
437 				ia = ifatoia(ifa_ifwithnet(sintosa(sin)));
438 			sin->sin_port = fport;
439 			if (ia == 0)
440 				ia = in_ifaddrhead.tqh_first;
441 			if (ia == 0)
442 				return (EADDRNOTAVAIL);
443 		}
444 		/*
445 		 * If the destination address is multicast and an outgoing
446 		 * interface has been set as a multicast option, use the
447 		 * address of that interface as our source address.
448 		 */
449 		if (IN_MULTICAST(ntohl(sin->sin_addr.s_addr)) &&
450 		    inp->inp_moptions != NULL) {
451 			struct ip_moptions *imo;
452 			struct ifnet *ifp;
453 
454 			imo = inp->inp_moptions;
455 			if (imo->imo_multicast_ifp != NULL) {
456 				ifp = imo->imo_multicast_ifp;
457 				for (ia = in_ifaddrhead.tqh_first; ia;
458 				     ia = ia->ia_link.tqe_next)
459 					if (ia->ia_ifp == ifp)
460 						break;
461 				if (ia == 0)
462 					return (EADDRNOTAVAIL);
463 			}
464 		}
465 	/*
466 	 * Don't do pcblookup call here; return interface in plocal_sin
467 	 * and exit to caller, that will do the lookup.
468 	 */
469 		*plocal_sin = &ia->ia_addr;
470 
471 	}
472 	return(0);
473 }
474 
475 /*
476  * Outer subroutine:
477  * Connect from a socket to a specified address.
478  * Both address and port must be specified in argument sin.
479  * If don't have a local address for this socket yet,
480  * then pick one.
481  */
482 int
483 in_pcbconnect(inp, nam, p)
484 	register struct inpcb *inp;
485 	struct sockaddr *nam;
486 	struct proc *p;
487 {
488 	struct sockaddr_in *ifaddr;
489 	register struct sockaddr_in *sin = (struct sockaddr_in *)nam;
490 	int error;
491 
492 	/*
493 	 *   Call inner routine, to assign local interface address.
494 	 */
495 	if ((error = in_pcbladdr(inp, nam, &ifaddr)) != 0)
496 		return(error);
497 
498 	if (in_pcblookup_hash(inp->inp_pcbinfo, sin->sin_addr, sin->sin_port,
499 	    inp->inp_laddr.s_addr ? inp->inp_laddr : ifaddr->sin_addr,
500 	    inp->inp_lport, 0, NULL) != NULL) {
501 		return (EADDRINUSE);
502 	}
503 	if (inp->inp_laddr.s_addr == INADDR_ANY) {
504 		if (inp->inp_lport == 0) {
505 			error = in_pcbbind(inp, (struct sockaddr *)0, p);
506 			if (error)
507 			    return (error);
508 		}
509 		inp->inp_laddr = ifaddr->sin_addr;
510 	}
511 	inp->inp_faddr = sin->sin_addr;
512 	inp->inp_fport = sin->sin_port;
513 	in_pcbrehash(inp);
514 	return (0);
515 }
516 
517 void
518 in_pcbdisconnect(inp)
519 	struct inpcb *inp;
520 {
521 
522 	inp->inp_faddr.s_addr = INADDR_ANY;
523 	inp->inp_fport = 0;
524 	in_pcbrehash(inp);
525 	if (inp->inp_socket->so_state & SS_NOFDREF)
526 		in_pcbdetach(inp);
527 }
528 
529 void
530 in_pcbdetach(inp)
531 	struct inpcb *inp;
532 {
533 	struct socket *so = inp->inp_socket;
534 	struct inpcbinfo *ipi = inp->inp_pcbinfo;
535 
536 #ifdef IPSEC
537 	if (inp->inp_sp != NULL)
538 		ipsec4_delete_pcbpolicy(inp);
539 #endif /*IPSEC*/
540 	inp->inp_gencnt = ++ipi->ipi_gencnt;
541 	in_pcbremlists(inp);
542 	so->so_pcb = 0;
543 	sofree(so);
544 	if (inp->inp_options)
545 		(void)m_free(inp->inp_options);
546 	if (inp->inp_route.ro_rt)
547 		rtfree(inp->inp_route.ro_rt);
548 	ip_freemoptions(inp->inp_moptions);
549 	inp->inp_vflag = 0;
550 	zfreei(ipi->ipi_zone, inp);
551 }
552 
553 /*
554  * The calling convention of in_setsockaddr() and in_setpeeraddr() was
555  * modified to match the pru_sockaddr() and pru_peeraddr() entry points
556  * in struct pr_usrreqs, so that protocols can just reference then directly
557  * without the need for a wrapper function.  The socket must have a valid
558  * (i.e., non-nil) PCB, but it should be impossible to get an invalid one
559  * except through a kernel programming error, so it is acceptable to panic
560  * (or in this case trap) if the PCB is invalid.  (Actually, we don't trap
561  * because there actually /is/ a programming error somewhere... XXX)
562  */
563 int
564 in_setsockaddr(so, nam)
565 	struct socket *so;
566 	struct sockaddr **nam;
567 {
568 	int s;
569 	register struct inpcb *inp;
570 	register struct sockaddr_in *sin;
571 
572 	/*
573 	 * Do the malloc first in case it blocks.
574 	 */
575 	MALLOC(sin, struct sockaddr_in *, sizeof *sin, M_SONAME, M_WAITOK);
576 	bzero(sin, sizeof *sin);
577 	sin->sin_family = AF_INET;
578 	sin->sin_len = sizeof(*sin);
579 
580 	s = splnet();
581 	inp = sotoinpcb(so);
582 	if (!inp) {
583 		splx(s);
584 		free(sin, M_SONAME);
585 		return ECONNRESET;
586 	}
587 	sin->sin_port = inp->inp_lport;
588 	sin->sin_addr = inp->inp_laddr;
589 	splx(s);
590 
591 	*nam = (struct sockaddr *)sin;
592 	return 0;
593 }
594 
595 int
596 in_setpeeraddr(so, nam)
597 	struct socket *so;
598 	struct sockaddr **nam;
599 {
600 	int s;
601 	struct inpcb *inp;
602 	register struct sockaddr_in *sin;
603 
604 	/*
605 	 * Do the malloc first in case it blocks.
606 	 */
607 	MALLOC(sin, struct sockaddr_in *, sizeof *sin, M_SONAME, M_WAITOK);
608 	bzero(sin, sizeof (*sin));
609 	sin->sin_family = AF_INET;
610 	sin->sin_len = sizeof(*sin);
611 
612 	s = splnet();
613 	inp = sotoinpcb(so);
614 	if (!inp) {
615 		splx(s);
616 		free(sin, M_SONAME);
617 		return ECONNRESET;
618 	}
619 	sin->sin_port = inp->inp_fport;
620 	sin->sin_addr = inp->inp_faddr;
621 	splx(s);
622 
623 	*nam = (struct sockaddr *)sin;
624 	return 0;
625 }
626 
627 /*
628  * Pass some notification to all connections of a protocol
629  * associated with address dst.  The local address and/or port numbers
630  * may be specified to limit the search.  The "usual action" will be
631  * taken, depending on the ctlinput cmd.  The caller must filter any
632  * cmds that are uninteresting (e.g., no error in the map).
633  * Call the protocol specific routine (if any) to report
634  * any errors for each matching socket.
635  */
636 void
637 in_pcbnotify(head, dst, fport_arg, laddr, lport_arg, cmd, notify)
638 	struct inpcbhead *head;
639 	struct sockaddr *dst;
640 	u_int fport_arg, lport_arg;
641 	struct in_addr laddr;
642 	int cmd;
643 	void (*notify) __P((struct inpcb *, int));
644 {
645 	register struct inpcb *inp, *oinp;
646 	struct in_addr faddr;
647 	u_short fport = fport_arg, lport = lport_arg;
648 	int errno, s;
649 
650 	if ((unsigned)cmd > PRC_NCMDS || dst->sa_family != AF_INET)
651 		return;
652 	faddr = ((struct sockaddr_in *)dst)->sin_addr;
653 	if (faddr.s_addr == INADDR_ANY)
654 		return;
655 
656 	/*
657 	 * Redirects go to all references to the destination,
658 	 * and use in_rtchange to invalidate the route cache.
659 	 * Dead host indications: notify all references to the destination.
660 	 * Otherwise, if we have knowledge of the local port and address,
661 	 * deliver only to that socket.
662 	 */
663 	if (PRC_IS_REDIRECT(cmd) || cmd == PRC_HOSTDEAD) {
664 		fport = 0;
665 		lport = 0;
666 		laddr.s_addr = 0;
667 		if (cmd != PRC_HOSTDEAD)
668 			notify = in_rtchange;
669 	}
670 	errno = inetctlerrmap[cmd];
671 	s = splnet();
672 	for (inp = head->lh_first; inp != NULL;) {
673 #ifdef INET6
674 		if ((inp->inp_vflag & INP_IPV4) == 0) {
675 			inp = LIST_NEXT(inp, inp_list);
676 			continue;
677 		}
678 #endif
679 		if (inp->inp_faddr.s_addr != faddr.s_addr ||
680 		    inp->inp_socket == 0 ||
681 		    (lport && inp->inp_lport != lport) ||
682 		    (laddr.s_addr && inp->inp_laddr.s_addr != laddr.s_addr) ||
683 		    (fport && inp->inp_fport != fport)) {
684 			inp = inp->inp_list.le_next;
685 			continue;
686 		}
687 		oinp = inp;
688 		inp = inp->inp_list.le_next;
689 		if (notify)
690 			(*notify)(oinp, errno);
691 	}
692 	splx(s);
693 }
694 
695 /*
696  * Check for alternatives when higher level complains
697  * about service problems.  For now, invalidate cached
698  * routing information.  If the route was created dynamically
699  * (by a redirect), time to try a default gateway again.
700  */
701 void
702 in_losing(inp)
703 	struct inpcb *inp;
704 {
705 	register struct rtentry *rt;
706 	struct rt_addrinfo info;
707 
708 	if ((rt = inp->inp_route.ro_rt)) {
709 		inp->inp_route.ro_rt = 0;
710 		bzero((caddr_t)&info, sizeof(info));
711 		info.rti_info[RTAX_DST] =
712 			(struct sockaddr *)&inp->inp_route.ro_dst;
713 		info.rti_info[RTAX_GATEWAY] = rt->rt_gateway;
714 		info.rti_info[RTAX_NETMASK] = rt_mask(rt);
715 		rt_missmsg(RTM_LOSING, &info, rt->rt_flags, 0);
716 		if (rt->rt_flags & RTF_DYNAMIC)
717 			(void) rtrequest(RTM_DELETE, rt_key(rt),
718 				rt->rt_gateway, rt_mask(rt), rt->rt_flags,
719 				(struct rtentry **)0);
720 		else
721 		/*
722 		 * A new route can be allocated
723 		 * the next time output is attempted.
724 		 */
725 			rtfree(rt);
726 	}
727 }
728 
729 /*
730  * After a routing change, flush old routing
731  * and allocate a (hopefully) better one.
732  */
733 static void
734 in_rtchange(inp, errno)
735 	register struct inpcb *inp;
736 	int errno;
737 {
738 	if (inp->inp_route.ro_rt) {
739 		rtfree(inp->inp_route.ro_rt);
740 		inp->inp_route.ro_rt = 0;
741 		/*
742 		 * A new route can be allocated the next time
743 		 * output is attempted.
744 		 */
745 	}
746 }
747 
748 /*
749  * Lookup a PCB based on the local address and port.
750  */
751 struct inpcb *
752 in_pcblookup_local(pcbinfo, laddr, lport_arg, wild_okay)
753 	struct inpcbinfo *pcbinfo;
754 	struct in_addr laddr;
755 	u_int lport_arg;
756 	int wild_okay;
757 {
758 	register struct inpcb *inp;
759 	int matchwild = 3, wildcard;
760 	u_short lport = lport_arg;
761 
762 	if (!wild_okay) {
763 		struct inpcbhead *head;
764 		/*
765 		 * Look for an unconnected (wildcard foreign addr) PCB that
766 		 * matches the local address and port we're looking for.
767 		 */
768 		head = &pcbinfo->hashbase[INP_PCBHASH(INADDR_ANY, lport, 0, pcbinfo->hashmask)];
769 		for (inp = head->lh_first; inp != NULL; inp = inp->inp_hash.le_next) {
770 #ifdef INET6
771 			if ((inp->inp_vflag & INP_IPV4) == 0)
772 				continue;
773 #endif
774 			if (inp->inp_faddr.s_addr == INADDR_ANY &&
775 			    inp->inp_laddr.s_addr == laddr.s_addr &&
776 			    inp->inp_lport == lport) {
777 				/*
778 				 * Found.
779 				 */
780 				return (inp);
781 			}
782 		}
783 		/*
784 		 * Not found.
785 		 */
786 		return (NULL);
787 	} else {
788 		struct inpcbporthead *porthash;
789 		struct inpcbport *phd;
790 		struct inpcb *match = NULL;
791 		/*
792 		 * Best fit PCB lookup.
793 		 *
794 		 * First see if this local port is in use by looking on the
795 		 * port hash list.
796 		 */
797 		porthash = &pcbinfo->porthashbase[INP_PCBPORTHASH(lport,
798 		    pcbinfo->porthashmask)];
799 		for (phd = porthash->lh_first; phd != NULL; phd = phd->phd_hash.le_next) {
800 			if (phd->phd_port == lport)
801 				break;
802 		}
803 		if (phd != NULL) {
804 			/*
805 			 * Port is in use by one or more PCBs. Look for best
806 			 * fit.
807 			 */
808 			for (inp = phd->phd_pcblist.lh_first; inp != NULL;
809 			    inp = inp->inp_portlist.le_next) {
810 				wildcard = 0;
811 #ifdef INET6
812 				if ((inp->inp_vflag & INP_IPV4) == 0)
813 					continue;
814 #endif
815 				if (inp->inp_faddr.s_addr != INADDR_ANY)
816 					wildcard++;
817 				if (inp->inp_laddr.s_addr != INADDR_ANY) {
818 					if (laddr.s_addr == INADDR_ANY)
819 						wildcard++;
820 					else if (inp->inp_laddr.s_addr != laddr.s_addr)
821 						continue;
822 				} else {
823 					if (laddr.s_addr != INADDR_ANY)
824 						wildcard++;
825 				}
826 				if (wildcard < matchwild) {
827 					match = inp;
828 					matchwild = wildcard;
829 					if (matchwild == 0) {
830 						break;
831 					}
832 				}
833 			}
834 		}
835 		return (match);
836 	}
837 }
838 
839 /*
840  * Lookup PCB in hash list.
841  */
842 struct inpcb *
843 in_pcblookup_hash(pcbinfo, faddr, fport_arg, laddr, lport_arg, wildcard,
844 		  ifp)
845 	struct inpcbinfo *pcbinfo;
846 	struct in_addr faddr, laddr;
847 	u_int fport_arg, lport_arg;
848 	int wildcard;
849 	struct ifnet *ifp;
850 {
851 	struct inpcbhead *head;
852 	register struct inpcb *inp;
853 	u_short fport = fport_arg, lport = lport_arg;
854 
855 	/*
856 	 * First look for an exact match.
857 	 */
858 	head = &pcbinfo->hashbase[INP_PCBHASH(faddr.s_addr, lport, fport, pcbinfo->hashmask)];
859 	for (inp = head->lh_first; inp != NULL; inp = inp->inp_hash.le_next) {
860 #ifdef INET6
861 		if ((inp->inp_vflag & INP_IPV4) == 0)
862 			continue;
863 #endif
864 		if (inp->inp_faddr.s_addr == faddr.s_addr &&
865 		    inp->inp_laddr.s_addr == laddr.s_addr &&
866 		    inp->inp_fport == fport &&
867 		    inp->inp_lport == lport) {
868 			/*
869 			 * Found.
870 			 */
871 			return (inp);
872 		}
873 	}
874 	if (wildcard) {
875 		struct inpcb *local_wild = NULL;
876 #if defined(INET6)
877 		struct inpcb *local_wild_mapped = NULL;
878 #endif /* defined(INET6) */
879 
880 		head = &pcbinfo->hashbase[INP_PCBHASH(INADDR_ANY, lport, 0, pcbinfo->hashmask)];
881 		for (inp = head->lh_first; inp != NULL; inp = inp->inp_hash.le_next) {
882 #ifdef INET6
883 			if ((inp->inp_vflag & INP_IPV4) == 0)
884 				continue;
885 #endif
886 			if (inp->inp_faddr.s_addr == INADDR_ANY &&
887 			    inp->inp_lport == lport) {
888 #if defined(NFAITH) && NFAITH > 0
889 				if (ifp && ifp->if_type == IFT_FAITH &&
890 				    (inp->inp_flags & INP_FAITH) == 0)
891 					continue;
892 #endif
893 				if (inp->inp_laddr.s_addr == laddr.s_addr)
894 					return (inp);
895 				else if (inp->inp_laddr.s_addr == INADDR_ANY) {
896 #if defined(INET6)
897 					if (INP_CHECK_SOCKAF(inp->inp_socket,
898 							     AF_INET6))
899 						local_wild_mapped = inp;
900 					else
901 #endif /* defined(INET6) */
902 					local_wild = inp;
903 				}
904 			}
905 		}
906 #if defined(INET6)
907 		if (local_wild == NULL)
908 			return (local_wild_mapped);
909 #endif /* defined(INET6) */
910 		return (local_wild);
911 	}
912 
913 	/*
914 	 * Not found.
915 	 */
916 	return (NULL);
917 }
918 
919 /*
920  * Insert PCB onto various hash lists.
921  */
922 int
923 in_pcbinshash(inp)
924 	struct inpcb *inp;
925 {
926 	struct inpcbhead *pcbhash;
927 	struct inpcbporthead *pcbporthash;
928 	struct inpcbinfo *pcbinfo = inp->inp_pcbinfo;
929 	struct inpcbport *phd;
930 	u_int32_t hashkey_faddr;
931 
932 #ifdef INET6
933 	if (inp->inp_vflag & INP_IPV6)
934 		hashkey_faddr = inp->in6p_faddr.s6_addr32[3] /* XXX */;
935 	else
936 #endif /* INET6 */
937 	hashkey_faddr = inp->inp_faddr.s_addr;
938 
939 	pcbhash = &pcbinfo->hashbase[INP_PCBHASH(hashkey_faddr,
940 		 inp->inp_lport, inp->inp_fport, pcbinfo->hashmask)];
941 
942 	pcbporthash = &pcbinfo->porthashbase[INP_PCBPORTHASH(inp->inp_lport,
943 	    pcbinfo->porthashmask)];
944 
945 	/*
946 	 * Go through port list and look for a head for this lport.
947 	 */
948 	for (phd = pcbporthash->lh_first; phd != NULL; phd = phd->phd_hash.le_next) {
949 		if (phd->phd_port == inp->inp_lport)
950 			break;
951 	}
952 	/*
953 	 * If none exists, malloc one and tack it on.
954 	 */
955 	if (phd == NULL) {
956 		MALLOC(phd, struct inpcbport *, sizeof(struct inpcbport), M_PCB, M_NOWAIT);
957 		if (phd == NULL) {
958 			return (ENOBUFS); /* XXX */
959 		}
960 		phd->phd_port = inp->inp_lport;
961 		LIST_INIT(&phd->phd_pcblist);
962 		LIST_INSERT_HEAD(pcbporthash, phd, phd_hash);
963 	}
964 	inp->inp_phd = phd;
965 	LIST_INSERT_HEAD(&phd->phd_pcblist, inp, inp_portlist);
966 	LIST_INSERT_HEAD(pcbhash, inp, inp_hash);
967 	return (0);
968 }
969 
970 /*
971  * Move PCB to the proper hash bucket when { faddr, fport } have  been
972  * changed. NOTE: This does not handle the case of the lport changing (the
973  * hashed port list would have to be updated as well), so the lport must
974  * not change after in_pcbinshash() has been called.
975  */
976 void
977 in_pcbrehash(inp)
978 	struct inpcb *inp;
979 {
980 	struct inpcbhead *head;
981 	u_int32_t hashkey_faddr;
982 
983 #ifdef INET6
984 	if (inp->inp_vflag & INP_IPV6)
985 		hashkey_faddr = inp->in6p_faddr.s6_addr32[3] /* XXX */;
986 	else
987 #endif /* INET6 */
988 	hashkey_faddr = inp->inp_faddr.s_addr;
989 
990 	head = &inp->inp_pcbinfo->hashbase[INP_PCBHASH(hashkey_faddr,
991 		inp->inp_lport, inp->inp_fport, inp->inp_pcbinfo->hashmask)];
992 
993 	LIST_REMOVE(inp, inp_hash);
994 	LIST_INSERT_HEAD(head, inp, inp_hash);
995 }
996 
997 /*
998  * Remove PCB from various lists.
999  */
1000 void
1001 in_pcbremlists(inp)
1002 	struct inpcb *inp;
1003 {
1004 	inp->inp_gencnt = ++inp->inp_pcbinfo->ipi_gencnt;
1005 	if (inp->inp_lport) {
1006 		struct inpcbport *phd = inp->inp_phd;
1007 
1008 		LIST_REMOVE(inp, inp_hash);
1009 		LIST_REMOVE(inp, inp_portlist);
1010 		if (phd->phd_pcblist.lh_first == NULL) {
1011 			LIST_REMOVE(phd, phd_hash);
1012 			free(phd, M_PCB);
1013 		}
1014 	}
1015 	LIST_REMOVE(inp, inp_list);
1016 	inp->inp_pcbinfo->ipi_count--;
1017 }
1018 
1019 int
1020 prison_xinpcb(struct proc *p, struct inpcb *inp)
1021 {
1022 	if (!p->p_prison)
1023 		return (0);
1024 	if (ntohl(inp->inp_laddr.s_addr) == p->p_prison->pr_ip)
1025 		return (0);
1026 	return (1);
1027 }
1028