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