xref: /openbsd-src/sys/netinet/in_pcb.c (revision 505ee9ea3b177e2387d907a91ca7da069f3f14d8)
1 /*	$OpenBSD: in_pcb.c,v 1.249 2020/05/27 20:44:07 bluhm Exp $	*/
2 /*	$NetBSD: in_pcb.c,v 1.25 1996/02/13 23:41:53 christos Exp $	*/
3 
4 /*
5  * Copyright (c) 1982, 1986, 1991, 1993
6  *	The Regents of the University of California.  All rights reserved.
7  *
8  * Redistribution and use in source and binary forms, with or without
9  * modification, are permitted provided that the following conditions
10  * are met:
11  * 1. Redistributions of source code must retain the above copyright
12  *    notice, this list of conditions and the following disclaimer.
13  * 2. Redistributions in binary form must reproduce the above copyright
14  *    notice, this list of conditions and the following disclaimer in the
15  *    documentation and/or other materials provided with the distribution.
16  * 3. Neither the name of the University nor the names of its contributors
17  *    may be used to endorse or promote products derived from this software
18  *    without specific prior written permission.
19  *
20  * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
21  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
22  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
23  * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
24  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
25  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
26  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
27  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
28  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
29  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
30  * SUCH DAMAGE.
31  *
32  *	@(#)COPYRIGHT	1.1 (NRL) 17 January 1995
33  *
34  * NRL grants permission for redistribution and use in source and binary
35  * forms, with or without modification, of the software and documentation
36  * created at NRL provided that the following conditions are met:
37  *
38  * 1. Redistributions of source code must retain the above copyright
39  *    notice, this list of conditions and the following disclaimer.
40  * 2. Redistributions in binary form must reproduce the above copyright
41  *    notice, this list of conditions and the following disclaimer in the
42  *    documentation and/or other materials provided with the distribution.
43  * 3. All advertising materials mentioning features or use of this software
44  *    must display the following acknowledgements:
45  *	This product includes software developed by the University of
46  *	California, Berkeley and its contributors.
47  *	This product includes software developed at the Information
48  *	Technology Division, US Naval Research Laboratory.
49  * 4. Neither the name of the NRL nor the names of its contributors
50  *    may be used to endorse or promote products derived from this software
51  *    without specific prior written permission.
52  *
53  * THE SOFTWARE PROVIDED BY NRL IS PROVIDED BY NRL AND CONTRIBUTORS ``AS
54  * IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
55  * TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A
56  * PARTICULAR PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL NRL OR
57  * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
58  * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
59  * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
60  * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
61  * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
62  * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
63  * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
64  *
65  * The views and conclusions contained in the software and documentation
66  * are those of the authors and should not be interpreted as representing
67  * official policies, either expressed or implied, of the US Naval
68  * Research Laboratory (NRL).
69  */
70 
71 #include "pf.h"
72 
73 #include <sys/param.h>
74 #include <sys/systm.h>
75 #include <sys/mbuf.h>
76 #include <sys/protosw.h>
77 #include <sys/socket.h>
78 #include <sys/socketvar.h>
79 #include <sys/domain.h>
80 #include <sys/mount.h>
81 #include <sys/pool.h>
82 #include <sys/proc.h>
83 
84 #include <net/if.h>
85 #include <net/if_var.h>
86 #include <net/pfvar.h>
87 #include <net/route.h>
88 
89 #include <netinet/in.h>
90 #include <netinet/in_var.h>
91 #include <netinet/ip.h>
92 #include <netinet/ip_var.h>
93 #include <netinet/in_pcb.h>
94 #ifdef IPSEC
95 #include <netinet/ip_esp.h>
96 #endif /* IPSEC */
97 
98 const struct in_addr zeroin_addr;
99 
100 union {
101 	struct in_addr	za_in;
102 	struct in6_addr	za_in6;
103 } zeroin46_addr;
104 
105 /*
106  * These configure the range of local port addresses assigned to
107  * "unspecified" outgoing connections/packets/whatever.
108  */
109 int ipport_firstauto = IPPORT_RESERVED;
110 int ipport_lastauto = IPPORT_USERRESERVED;
111 int ipport_hifirstauto = IPPORT_HIFIRSTAUTO;
112 int ipport_hilastauto = IPPORT_HILASTAUTO;
113 
114 struct baddynamicports baddynamicports;
115 struct baddynamicports rootonlyports;
116 struct pool inpcb_pool;
117 
118 int in_pcbresize (struct inpcbtable *, int);
119 
120 #define	INPCBHASH_LOADFACTOR(_x)	(((_x) * 3) / 4)
121 
122 struct inpcbhead *in_pcbhash(struct inpcbtable *, int,
123     const struct in_addr *, u_short, const struct in_addr *, u_short);
124 struct inpcbhead *in_pcblhash(struct inpcbtable *, int, u_short);
125 
126 /*
127  * in_pcb is used for inet and inet6.  in6_pcb only contains special
128  * IPv6 cases.  So the internet initializer is used for both domains.
129  */
130 void
131 in_init(void)
132 {
133 	pool_init(&inpcb_pool, sizeof(struct inpcb), 0,
134 	    IPL_SOFTNET, 0, "inpcb", NULL);
135 }
136 
137 struct inpcbhead *
138 in_pcbhash(struct inpcbtable *table, int rdom,
139     const struct in_addr *faddr, u_short fport,
140     const struct in_addr *laddr, u_short lport)
141 {
142 	SIPHASH_CTX ctx;
143 	u_int32_t nrdom = htonl(rdom);
144 
145 	SipHash24_Init(&ctx, &table->inpt_key);
146 	SipHash24_Update(&ctx, &nrdom, sizeof(nrdom));
147 	SipHash24_Update(&ctx, faddr, sizeof(*faddr));
148 	SipHash24_Update(&ctx, &fport, sizeof(fport));
149 	SipHash24_Update(&ctx, laddr, sizeof(*laddr));
150 	SipHash24_Update(&ctx, &lport, sizeof(lport));
151 
152 	return (&table->inpt_hashtbl[SipHash24_End(&ctx) & table->inpt_mask]);
153 }
154 
155 struct inpcbhead *
156 in_pcblhash(struct inpcbtable *table, int rdom, u_short lport)
157 {
158 	SIPHASH_CTX ctx;
159 	u_int32_t nrdom = htonl(rdom);
160 
161 	SipHash24_Init(&ctx, &table->inpt_lkey);
162 	SipHash24_Update(&ctx, &nrdom, sizeof(nrdom));
163 	SipHash24_Update(&ctx, &lport, sizeof(lport));
164 
165 	return (&table->inpt_lhashtbl[SipHash24_End(&ctx) & table->inpt_lmask]);
166 }
167 
168 void
169 in_pcbinit(struct inpcbtable *table, int hashsize)
170 {
171 
172 	TAILQ_INIT(&table->inpt_queue);
173 	table->inpt_hashtbl = hashinit(hashsize, M_PCB, M_NOWAIT,
174 	    &table->inpt_mask);
175 	if (table->inpt_hashtbl == NULL)
176 		panic("in_pcbinit: hashinit failed");
177 	table->inpt_lhashtbl = hashinit(hashsize, M_PCB, M_NOWAIT,
178 	    &table->inpt_lmask);
179 	if (table->inpt_lhashtbl == NULL)
180 		panic("in_pcbinit: hashinit failed for lport");
181 	table->inpt_count = 0;
182 	table->inpt_size = hashsize;
183 	arc4random_buf(&table->inpt_key, sizeof(table->inpt_key));
184 	arc4random_buf(&table->inpt_lkey, sizeof(table->inpt_lkey));
185 }
186 
187 /*
188  * Check if the specified port is invalid for dynamic allocation.
189  */
190 int
191 in_baddynamic(u_int16_t port, u_int16_t proto)
192 {
193 	switch (proto) {
194 	case IPPROTO_TCP:
195 		return (DP_ISSET(baddynamicports.tcp, port));
196 	case IPPROTO_UDP:
197 #ifdef IPSEC
198 		/* Cannot preset this as it is a sysctl */
199 		if (port == udpencap_port)
200 			return (1);
201 #endif
202 		return (DP_ISSET(baddynamicports.udp, port));
203 	default:
204 		return (0);
205 	}
206 }
207 
208 int
209 in_rootonly(u_int16_t port, u_int16_t proto)
210 {
211 	switch (proto) {
212 	case IPPROTO_TCP:
213 		return (port < IPPORT_RESERVED ||
214 		    DP_ISSET(rootonlyports.tcp, port));
215 	case IPPROTO_UDP:
216 		return (port < IPPORT_RESERVED ||
217 		    DP_ISSET(rootonlyports.udp, port));
218 	default:
219 		return (0);
220 	}
221 }
222 
223 int
224 in_pcballoc(struct socket *so, struct inpcbtable *table)
225 {
226 	struct inpcb *inp;
227 	struct inpcbhead *head;
228 
229 	NET_ASSERT_LOCKED();
230 
231 	inp = pool_get(&inpcb_pool, PR_NOWAIT|PR_ZERO);
232 	if (inp == NULL)
233 		return (ENOBUFS);
234 	inp->inp_table = table;
235 	inp->inp_socket = so;
236 	refcnt_init(&inp->inp_refcnt);
237 	inp->inp_seclevel[SL_AUTH] = IPSEC_AUTH_LEVEL_DEFAULT;
238 	inp->inp_seclevel[SL_ESP_TRANS] = IPSEC_ESP_TRANS_LEVEL_DEFAULT;
239 	inp->inp_seclevel[SL_ESP_NETWORK] = IPSEC_ESP_NETWORK_LEVEL_DEFAULT;
240 	inp->inp_seclevel[SL_IPCOMP] = IPSEC_IPCOMP_LEVEL_DEFAULT;
241 	inp->inp_rtableid = curproc->p_p->ps_rtableid;
242 	inp->inp_hops = -1;
243 #ifdef INET6
244 	/*
245 	 * Small change in this function to set the INP_IPV6 flag so routines
246 	 * outside pcb-specific routines don't need to use sotopf(), and all
247 	 * of its pointer chasing, later.
248 	 */
249 	if (sotopf(so) == PF_INET6)
250 		inp->inp_flags = INP_IPV6;
251 	inp->inp_cksum6 = -1;
252 #endif /* INET6 */
253 
254 	if (table->inpt_count++ > INPCBHASH_LOADFACTOR(table->inpt_size))
255 		(void)in_pcbresize(table, table->inpt_size * 2);
256 	TAILQ_INSERT_HEAD(&table->inpt_queue, inp, inp_queue);
257 	head = in_pcblhash(table, inp->inp_rtableid, inp->inp_lport);
258 	LIST_INSERT_HEAD(head, inp, inp_lhash);
259 #ifdef INET6
260 	if (sotopf(so) == PF_INET6)
261 		head = in6_pcbhash(table, rtable_l2(inp->inp_rtableid),
262 		    &inp->inp_faddr6, inp->inp_fport,
263 		    &inp->inp_laddr6, inp->inp_lport);
264 	else
265 #endif /* INET6 */
266 		head = in_pcbhash(table, rtable_l2(inp->inp_rtableid),
267 		    &inp->inp_faddr, inp->inp_fport,
268 		    &inp->inp_laddr, inp->inp_lport);
269 	LIST_INSERT_HEAD(head, inp, inp_hash);
270 	so->so_pcb = inp;
271 
272 	return (0);
273 }
274 
275 int
276 in_pcbbind(struct inpcb *inp, struct mbuf *nam, struct proc *p)
277 {
278 	struct socket *so = inp->inp_socket;
279 	u_int16_t lport = 0;
280 	int wild = 0;
281 	void *laddr = &zeroin46_addr;
282 	int error;
283 
284 	if (inp->inp_lport)
285 		return (EINVAL);
286 
287 	if ((so->so_options & (SO_REUSEADDR|SO_REUSEPORT)) == 0 &&
288 	    ((so->so_proto->pr_flags & PR_CONNREQUIRED) == 0 ||
289 	     (so->so_options & SO_ACCEPTCONN) == 0))
290 		wild = INPLOOKUP_WILDCARD;
291 
292 	switch (sotopf(so)) {
293 #ifdef INET6
294 	case PF_INET6:
295 		if (!IN6_IS_ADDR_UNSPECIFIED(&inp->inp_laddr6))
296 			return (EINVAL);
297 		wild |= INPLOOKUP_IPV6;
298 
299 		if (nam) {
300 			struct sockaddr_in6 *sin6;
301 
302 			if ((error = in6_nam2sin6(nam, &sin6)))
303 				return (error);
304 			if ((error = in6_pcbaddrisavail(inp, sin6, wild, p)))
305 				return (error);
306 			laddr = &sin6->sin6_addr;
307 			lport = sin6->sin6_port;
308 		}
309 		break;
310 #endif
311 	case PF_INET:
312 		if (inp->inp_laddr.s_addr != INADDR_ANY)
313 			return (EINVAL);
314 
315 		if (nam) {
316 			struct sockaddr_in *sin;
317 
318 			if ((error = in_nam2sin(nam, &sin)))
319 				return (error);
320 			if ((error = in_pcbaddrisavail(inp, sin, wild, p)))
321 				return (error);
322 			laddr = &sin->sin_addr;
323 			lport = sin->sin_port;
324 		}
325 		break;
326 	default:
327 		return (EINVAL);
328 	}
329 
330 	if (lport == 0) {
331 		if ((error = in_pcbpickport(&lport, laddr, wild, inp, p)))
332 			return (error);
333 	} else {
334 		if (in_rootonly(ntohs(lport), so->so_proto->pr_protocol) &&
335 		    suser(p) != 0)
336 			return (EACCES);
337 	}
338 	if (nam) {
339 		switch (sotopf(so)) {
340 #ifdef INET6
341 		case PF_INET6:
342 			inp->inp_laddr6 = *(struct in6_addr *)laddr;
343 			break;
344 #endif
345 		case PF_INET:
346 			inp->inp_laddr = *(struct in_addr *)laddr;
347 			break;
348 		}
349 	}
350 	inp->inp_lport = lport;
351 	in_pcbrehash(inp);
352 	return (0);
353 }
354 
355 int
356 in_pcbaddrisavail(struct inpcb *inp, struct sockaddr_in *sin, int wild,
357     struct proc *p)
358 {
359 	struct socket *so = inp->inp_socket;
360 	struct inpcbtable *table = inp->inp_table;
361 	u_int16_t lport = sin->sin_port;
362 	int reuseport = (so->so_options & SO_REUSEPORT);
363 
364 	if (IN_MULTICAST(sin->sin_addr.s_addr)) {
365 		/*
366 		 * Treat SO_REUSEADDR as SO_REUSEPORT for multicast;
367 		 * allow complete duplication of binding if
368 		 * SO_REUSEPORT is set, or if SO_REUSEADDR is set
369 		 * and a multicast address is bound on both
370 		 * new and duplicated sockets.
371 		 */
372 		if (so->so_options & (SO_REUSEADDR|SO_REUSEPORT))
373 			reuseport = SO_REUSEADDR|SO_REUSEPORT;
374 	} else if (sin->sin_addr.s_addr != INADDR_ANY) {
375 		/*
376 		 * we must check that we are binding to an address we
377 		 * own except when:
378 		 * - SO_BINDANY is set or
379 		 * - we are binding a UDP socket to 255.255.255.255 or
380 		 * - we are binding a UDP socket to one of our broadcast
381 		 *   addresses
382 		 */
383 		if (!ISSET(so->so_options, SO_BINDANY) &&
384 		    !(so->so_type == SOCK_DGRAM &&
385 		    sin->sin_addr.s_addr == INADDR_BROADCAST) &&
386 		    !(so->so_type == SOCK_DGRAM &&
387 		    in_broadcast(sin->sin_addr, inp->inp_rtableid))) {
388 			struct ifaddr *ia;
389 
390 			sin->sin_port = 0;
391 			memset(sin->sin_zero, 0, sizeof(sin->sin_zero));
392 			ia = ifa_ifwithaddr(sintosa(sin), inp->inp_rtableid);
393 			sin->sin_port = lport;
394 
395 			if (ia == NULL)
396 				return (EADDRNOTAVAIL);
397 		}
398 	}
399 	if (lport) {
400 		struct inpcb *t;
401 
402 		if (so->so_euid) {
403 			t = in_pcblookup_local(table, &sin->sin_addr, lport,
404 			    INPLOOKUP_WILDCARD, inp->inp_rtableid);
405 			if (t && (so->so_euid != t->inp_socket->so_euid))
406 				return (EADDRINUSE);
407 		}
408 		t = in_pcblookup_local(table, &sin->sin_addr, lport,
409 		    wild, inp->inp_rtableid);
410 		if (t && (reuseport & t->inp_socket->so_options) == 0)
411 			return (EADDRINUSE);
412 	}
413 
414 	return (0);
415 }
416 
417 int
418 in_pcbpickport(u_int16_t *lport, void *laddr, int wild, struct inpcb *inp,
419     struct proc *p)
420 {
421 	struct socket *so = inp->inp_socket;
422 	struct inpcbtable *table = inp->inp_table;
423 	u_int16_t first, last, lower, higher, candidate, localport;
424 	int count;
425 
426 	if (inp->inp_flags & INP_HIGHPORT) {
427 		first = ipport_hifirstauto;	/* sysctl */
428 		last = ipport_hilastauto;
429 	} else if (inp->inp_flags & INP_LOWPORT) {
430 		if (suser(p))
431 			return (EACCES);
432 		first = IPPORT_RESERVED-1; /* 1023 */
433 		last = 600;		   /* not IPPORT_RESERVED/2 */
434 	} else {
435 		first = ipport_firstauto;	/* sysctl */
436 		last = ipport_lastauto;
437 	}
438 	if (first < last) {
439 		lower = first;
440 		higher = last;
441 	} else {
442 		lower = last;
443 		higher = first;
444 	}
445 
446 	/*
447 	 * Simple check to ensure all ports are not used up causing
448 	 * a deadlock here.
449 	 */
450 
451 	count = higher - lower;
452 	candidate = lower + arc4random_uniform(count);
453 
454 	do {
455 		if (count-- < 0)	/* completely used? */
456 			return (EADDRNOTAVAIL);
457 		++candidate;
458 		if (candidate < lower || candidate > higher)
459 			candidate = lower;
460 		localport = htons(candidate);
461 	} while (in_baddynamic(candidate, so->so_proto->pr_protocol) ||
462 	    in_pcblookup_local(table, laddr, localport, wild,
463 	    inp->inp_rtableid));
464 	*lport = localport;
465 
466 	return (0);
467 }
468 
469 /*
470  * Connect from a socket to a specified address.
471  * Both address and port must be specified in argument sin.
472  * If don't have a local address for this socket yet,
473  * then pick one.
474  */
475 int
476 in_pcbconnect(struct inpcb *inp, struct mbuf *nam)
477 {
478 	struct in_addr *ina = NULL;
479 	struct sockaddr_in *sin;
480 	int error;
481 
482 #ifdef INET6
483 	if (sotopf(inp->inp_socket) == PF_INET6)
484 		return (in6_pcbconnect(inp, nam));
485 	KASSERT((inp->inp_flags & INP_IPV6) == 0);
486 #endif /* INET6 */
487 
488 	if ((error = in_nam2sin(nam, &sin)))
489 		return (error);
490 	if (sin->sin_port == 0)
491 		return (EADDRNOTAVAIL);
492 	error = in_pcbselsrc(&ina, sin, inp);
493 	if (error)
494 		return (error);
495 
496 	if (in_pcbhashlookup(inp->inp_table, sin->sin_addr, sin->sin_port,
497 	    *ina, inp->inp_lport, inp->inp_rtableid) != NULL)
498 		return (EADDRINUSE);
499 
500 	KASSERT(inp->inp_laddr.s_addr == INADDR_ANY || inp->inp_lport);
501 
502 	if (inp->inp_laddr.s_addr == INADDR_ANY) {
503 		if (inp->inp_lport == 0) {
504 			error = in_pcbbind(inp, NULL, curproc);
505 			if (error)
506 				return (error);
507 			if (in_pcbhashlookup(inp->inp_table, sin->sin_addr,
508 			    sin->sin_port, *ina, inp->inp_lport,
509 			    inp->inp_rtableid) != NULL) {
510 				inp->inp_lport = 0;
511 				return (EADDRINUSE);
512 			}
513 		}
514 		inp->inp_laddr = *ina;
515 	}
516 	inp->inp_faddr = sin->sin_addr;
517 	inp->inp_fport = sin->sin_port;
518 	in_pcbrehash(inp);
519 #ifdef IPSEC
520 	{
521 		/* Cause an IPsec SA to be established. */
522 		/* error is just ignored */
523 		ipsp_spd_inp(NULL, AF_INET, 0, &error, IPSP_DIRECTION_OUT,
524 		    NULL, inp, NULL);
525 	}
526 #endif
527 	return (0);
528 }
529 
530 void
531 in_pcbdisconnect(struct inpcb *inp)
532 {
533 #if NPF > 0
534 	if (inp->inp_pf_sk) {
535 		pf_remove_divert_state(inp->inp_pf_sk);
536 		/* pf_remove_divert_state() may have detached the state */
537 		pf_inp_unlink(inp);
538 	}
539 #endif
540 	switch (sotopf(inp->inp_socket)) {
541 #ifdef INET6
542 	case PF_INET6:
543 		inp->inp_faddr6 = in6addr_any;
544 		break;
545 #endif
546 	case PF_INET:
547 		inp->inp_faddr.s_addr = INADDR_ANY;
548 		break;
549 	}
550 
551 	inp->inp_fport = 0;
552 	in_pcbrehash(inp);
553 	if (inp->inp_socket->so_state & SS_NOFDREF)
554 		in_pcbdetach(inp);
555 }
556 
557 void
558 in_pcbdetach(struct inpcb *inp)
559 {
560 	struct socket *so = inp->inp_socket;
561 
562 	NET_ASSERT_LOCKED();
563 
564 	so->so_pcb = NULL;
565 	/*
566 	 * As long as the NET_LOCK() is the default lock for Internet
567 	 * sockets, do not release it to not introduce new sleeping
568 	 * points.
569 	 */
570 	sofree(so, SL_NOUNLOCK);
571 	m_freem(inp->inp_options);
572 	if (inp->inp_route.ro_rt) {
573 		rtfree(inp->inp_route.ro_rt);
574 		inp->inp_route.ro_rt = NULL;
575 	}
576 #ifdef INET6
577 	if (inp->inp_flags & INP_IPV6) {
578 		ip6_freepcbopts(inp->inp_outputopts6);
579 		ip6_freemoptions(inp->inp_moptions6);
580 	} else
581 #endif
582 		ip_freemoptions(inp->inp_moptions);
583 #if NPF > 0
584 	if (inp->inp_pf_sk) {
585 		pf_remove_divert_state(inp->inp_pf_sk);
586 		/* pf_remove_divert_state() may have detached the state */
587 		pf_inp_unlink(inp);
588 	}
589 #endif
590 	LIST_REMOVE(inp, inp_lhash);
591 	LIST_REMOVE(inp, inp_hash);
592 	TAILQ_REMOVE(&inp->inp_table->inpt_queue, inp, inp_queue);
593 	inp->inp_table->inpt_count--;
594 	in_pcbunref(inp);
595 }
596 
597 struct inpcb *
598 in_pcbref(struct inpcb *inp)
599 {
600 	if (inp != NULL)
601 		refcnt_take(&inp->inp_refcnt);
602 	return inp;
603 }
604 
605 void
606 in_pcbunref(struct inpcb *inp)
607 {
608 	if (refcnt_rele(&inp->inp_refcnt)) {
609 		KASSERT((LIST_NEXT(inp, inp_hash) == NULL) ||
610 		    (LIST_NEXT(inp, inp_hash) == _Q_INVALID));
611 		KASSERT((LIST_NEXT(inp, inp_lhash) == NULL) ||
612 		    (LIST_NEXT(inp, inp_lhash) == _Q_INVALID));
613 		KASSERT((TAILQ_NEXT(inp, inp_queue) == NULL) ||
614 		    (TAILQ_NEXT(inp, inp_queue) == _Q_INVALID));
615 		pool_put(&inpcb_pool, inp);
616 	}
617 }
618 
619 void
620 in_setsockaddr(struct inpcb *inp, struct mbuf *nam)
621 {
622 	struct sockaddr_in *sin;
623 
624 	nam->m_len = sizeof(*sin);
625 	sin = mtod(nam, struct sockaddr_in *);
626 	memset(sin, 0, sizeof(*sin));
627 	sin->sin_family = AF_INET;
628 	sin->sin_len = sizeof(*sin);
629 	sin->sin_port = inp->inp_lport;
630 	sin->sin_addr = inp->inp_laddr;
631 }
632 
633 void
634 in_setpeeraddr(struct inpcb *inp, struct mbuf *nam)
635 {
636 	struct sockaddr_in *sin;
637 
638 #ifdef INET6
639 	if (sotopf(inp->inp_socket) == PF_INET6) {
640 		in6_setpeeraddr(inp, nam);
641 		return;
642 	}
643 #endif /* INET6 */
644 
645 	nam->m_len = sizeof(*sin);
646 	sin = mtod(nam, struct sockaddr_in *);
647 	memset(sin, 0, sizeof(*sin));
648 	sin->sin_family = AF_INET;
649 	sin->sin_len = sizeof(*sin);
650 	sin->sin_port = inp->inp_fport;
651 	sin->sin_addr = inp->inp_faddr;
652 }
653 
654 /*
655  * Pass some notification to all connections of a protocol
656  * associated with address dst.  The "usual action" will be
657  * taken, depending on the ctlinput cmd.  The caller must filter any
658  * cmds that are uninteresting (e.g., no error in the map).
659  * Call the protocol specific routine (if any) to report
660  * any errors for each matching socket.
661  */
662 void
663 in_pcbnotifyall(struct inpcbtable *table, struct sockaddr *dst, u_int rtable,
664     int errno, void (*notify)(struct inpcb *, int))
665 {
666 	struct inpcb *inp, *ninp;
667 	struct in_addr faddr;
668 	u_int rdomain;
669 
670 	NET_ASSERT_LOCKED();
671 
672 #ifdef INET6
673 	/*
674 	 * See in6_pcbnotify() for IPv6 codepath.  By the time this
675 	 * gets called, the addresses passed are either definitely IPv4 or
676 	 * IPv6; *_pcbnotify() never gets called with v4-mapped v6 addresses.
677 	 */
678 #endif /* INET6 */
679 
680 	if (dst->sa_family != AF_INET)
681 		return;
682 	faddr = satosin(dst)->sin_addr;
683 	if (faddr.s_addr == INADDR_ANY)
684 		return;
685 
686 	rdomain = rtable_l2(rtable);
687 	TAILQ_FOREACH_SAFE(inp, &table->inpt_queue, inp_queue, ninp) {
688 #ifdef INET6
689 		if (inp->inp_flags & INP_IPV6)
690 			continue;
691 #endif
692 		if (inp->inp_faddr.s_addr != faddr.s_addr ||
693 		    rtable_l2(inp->inp_rtableid) != rdomain ||
694 		    inp->inp_socket == NULL) {
695 			continue;
696 		}
697 		if (notify)
698 			(*notify)(inp, errno);
699 	}
700 }
701 
702 /*
703  * Check for alternatives when higher level complains
704  * about service problems.  For now, invalidate cached
705  * routing information.  If the route was created dynamically
706  * (by a redirect), time to try a default gateway again.
707  */
708 void
709 in_losing(struct inpcb *inp)
710 {
711 	struct rtentry *rt = inp->inp_route.ro_rt;
712 
713 	if (rt) {
714 		inp->inp_route.ro_rt = NULL;
715 
716 		if (rt->rt_flags & RTF_DYNAMIC) {
717 			struct ifnet *ifp;
718 
719 			ifp = if_get(rt->rt_ifidx);
720 			/*
721 			 * If the interface is gone, all its attached
722 			 * route entries have been removed from the table,
723 			 * so we're dealing with a stale cache and have
724 			 * nothing to do.
725 			 */
726 			if (ifp != NULL)
727 				rtdeletemsg(rt, ifp, inp->inp_rtableid);
728 			if_put(ifp);
729 		}
730 		/*
731 		 * A new route can be allocated
732 		 * the next time output is attempted.
733 		 * rtfree() needs to be called in anycase because the inp
734 		 * is still holding a reference to rt.
735 		 */
736 		rtfree(rt);
737 	}
738 }
739 
740 /*
741  * After a routing change, flush old routing
742  * and allocate a (hopefully) better one.
743  */
744 void
745 in_rtchange(struct inpcb *inp, int errno)
746 {
747 	if (inp->inp_route.ro_rt) {
748 		rtfree(inp->inp_route.ro_rt);
749 		inp->inp_route.ro_rt = 0;
750 		/*
751 		 * A new route can be allocated the next time
752 		 * output is attempted.
753 		 */
754 	}
755 }
756 
757 struct inpcb *
758 in_pcblookup_local(struct inpcbtable *table, void *laddrp, u_int lport_arg,
759     int flags, u_int rtable)
760 {
761 	struct inpcb *inp, *match = NULL;
762 	int matchwild = 3, wildcard;
763 	u_int16_t lport = lport_arg;
764 	struct in_addr laddr = *(struct in_addr *)laddrp;
765 #ifdef INET6
766 	struct in6_addr *laddr6 = (struct in6_addr *)laddrp;
767 #endif
768 	struct inpcbhead *head;
769 	u_int rdomain;
770 
771 	rdomain = rtable_l2(rtable);
772 	head = in_pcblhash(table, rdomain, lport);
773 	LIST_FOREACH(inp, head, inp_lhash) {
774 		if (rtable_l2(inp->inp_rtableid) != rdomain)
775 			continue;
776 		if (inp->inp_lport != lport)
777 			continue;
778 		wildcard = 0;
779 #ifdef INET6
780 		if (ISSET(flags, INPLOOKUP_IPV6)) {
781 			if (!ISSET(inp->inp_flags, INP_IPV6))
782 				continue;
783 
784 			if (!IN6_IS_ADDR_UNSPECIFIED(&inp->inp_faddr6))
785 				wildcard++;
786 
787 			if (!IN6_ARE_ADDR_EQUAL(&inp->inp_laddr6, laddr6)) {
788 				if (IN6_IS_ADDR_UNSPECIFIED(&inp->inp_laddr6) ||
789 				    IN6_IS_ADDR_UNSPECIFIED(laddr6))
790 					wildcard++;
791 				else
792 					continue;
793 			}
794 
795 		} else
796 #endif /* INET6 */
797 		{
798 #ifdef INET6
799 			if (ISSET(inp->inp_flags, INP_IPV6))
800 				continue;
801 #endif /* INET6 */
802 
803 			if (inp->inp_faddr.s_addr != INADDR_ANY)
804 				wildcard++;
805 
806 			if (inp->inp_laddr.s_addr != laddr.s_addr) {
807 				if (inp->inp_laddr.s_addr == INADDR_ANY ||
808 				    laddr.s_addr == INADDR_ANY)
809 					wildcard++;
810 				else
811 					continue;
812 			}
813 
814 		}
815 		if ((!wildcard || (flags & INPLOOKUP_WILDCARD)) &&
816 		    wildcard < matchwild) {
817 			match = inp;
818 			if ((matchwild = wildcard) == 0)
819 				break;
820 		}
821 	}
822 	return (match);
823 }
824 
825 struct rtentry *
826 in_pcbrtentry(struct inpcb *inp)
827 {
828 	struct route *ro;
829 
830 	ro = &inp->inp_route;
831 
832 	/* check if route is still valid */
833 	if (!rtisvalid(ro->ro_rt)) {
834 		rtfree(ro->ro_rt);
835 		ro->ro_rt = NULL;
836 	}
837 
838 	/*
839 	 * No route yet, so try to acquire one.
840 	 */
841 	if (ro->ro_rt == NULL) {
842 #ifdef INET6
843 		memset(ro, 0, sizeof(struct route_in6));
844 #else
845 		memset(ro, 0, sizeof(struct route));
846 #endif
847 
848 		switch(sotopf(inp->inp_socket)) {
849 #ifdef INET6
850 		case PF_INET6:
851 			if (IN6_IS_ADDR_UNSPECIFIED(&inp->inp_faddr6))
852 				break;
853 			ro->ro_dst.sa_family = AF_INET6;
854 			ro->ro_dst.sa_len = sizeof(struct sockaddr_in6);
855 			satosin6(&ro->ro_dst)->sin6_addr = inp->inp_faddr6;
856 			ro->ro_tableid = inp->inp_rtableid;
857 			ro->ro_rt = rtalloc_mpath(&ro->ro_dst,
858 			    &inp->inp_laddr6.s6_addr32[0], ro->ro_tableid);
859 			break;
860 #endif /* INET6 */
861 		case PF_INET:
862 			if (inp->inp_faddr.s_addr == INADDR_ANY)
863 				break;
864 			ro->ro_dst.sa_family = AF_INET;
865 			ro->ro_dst.sa_len = sizeof(struct sockaddr_in);
866 			satosin(&ro->ro_dst)->sin_addr = inp->inp_faddr;
867 			ro->ro_tableid = inp->inp_rtableid;
868 			ro->ro_rt = rtalloc_mpath(&ro->ro_dst,
869 			    &inp->inp_laddr.s_addr, ro->ro_tableid);
870 			break;
871 		}
872 	}
873 	return (ro->ro_rt);
874 }
875 
876 /*
877  * Return an IPv4 address, which is the most appropriate for a given
878  * destination.
879  * If necessary, this function lookups the routing table and returns
880  * an entry to the caller for later use.
881  */
882 int
883 in_pcbselsrc(struct in_addr **insrc, struct sockaddr_in *sin,
884     struct inpcb *inp)
885 {
886 	struct ip_moptions *mopts = inp->inp_moptions;
887 	struct route *ro = &inp->inp_route;
888 	struct in_addr *laddr = &inp->inp_laddr;
889 	u_int rtableid = inp->inp_rtableid;
890 
891 	struct sockaddr_in *sin2;
892 	struct in_ifaddr *ia = NULL;
893 
894 	/*
895 	 * If the socket(if any) is already bound, use that bound address
896 	 * unless it is INADDR_ANY or INADDR_BROADCAST.
897 	 */
898 	if (laddr && laddr->s_addr != INADDR_ANY &&
899 	    laddr->s_addr != INADDR_BROADCAST) {
900 		*insrc = laddr;
901 		return (0);
902 	}
903 
904 	/*
905 	 * If the destination address is multicast and an outgoing
906 	 * interface has been set as a multicast option, use the
907 	 * address of that interface as our source address.
908 	 */
909 	if (IN_MULTICAST(sin->sin_addr.s_addr) && mopts != NULL) {
910 		struct ifnet *ifp;
911 
912 		ifp = if_get(mopts->imo_ifidx);
913 		if (ifp != NULL) {
914 			if (ifp->if_rdomain == rtable_l2(rtableid))
915 				IFP_TO_IA(ifp, ia);
916 			if (ia == NULL) {
917 				if_put(ifp);
918 				return (EADDRNOTAVAIL);
919 			}
920 
921 			*insrc = &ia->ia_addr.sin_addr;
922 			if_put(ifp);
923 			return (0);
924 		}
925 	}
926 	/*
927 	 * If route is known or can be allocated now,
928 	 * our src addr is taken from the i/f, else punt.
929 	 */
930 	if (!rtisvalid(ro->ro_rt) || (ro->ro_tableid != rtableid) ||
931 	    (satosin(&ro->ro_dst)->sin_addr.s_addr != sin->sin_addr.s_addr)) {
932 		rtfree(ro->ro_rt);
933 		ro->ro_rt = NULL;
934 	}
935 	if (ro->ro_rt == NULL) {
936 		/* No route yet, so try to acquire one */
937 		ro->ro_dst.sa_family = AF_INET;
938 		ro->ro_dst.sa_len = sizeof(struct sockaddr_in);
939 		satosin(&ro->ro_dst)->sin_addr = sin->sin_addr;
940 		ro->ro_tableid = rtableid;
941 		ro->ro_rt = rtalloc_mpath(&ro->ro_dst, NULL, ro->ro_tableid);
942 
943 		/*
944 		 * It is important to zero out the rest of the
945 		 * struct sockaddr_in when mixing v6 & v4!
946 		 */
947 		sin2 = satosin(&ro->ro_dst);
948 		memset(sin2->sin_zero, 0, sizeof(sin2->sin_zero));
949 	}
950 	/*
951 	 * If we found a route, use the address
952 	 * corresponding to the outgoing interface.
953 	 */
954 	if (ro->ro_rt != NULL)
955 		ia = ifatoia(ro->ro_rt->rt_ifa);
956 
957 	if (ia == NULL)
958 		return (EADDRNOTAVAIL);
959 
960 	*insrc = &ia->ia_addr.sin_addr;
961 	return (0);
962 }
963 
964 void
965 in_pcbrehash(struct inpcb *inp)
966 {
967 	struct inpcbtable *table = inp->inp_table;
968 	struct inpcbhead *head;
969 
970 	NET_ASSERT_LOCKED();
971 
972 	LIST_REMOVE(inp, inp_lhash);
973 	head = in_pcblhash(table, inp->inp_rtableid, inp->inp_lport);
974 	LIST_INSERT_HEAD(head, inp, inp_lhash);
975 	LIST_REMOVE(inp, inp_hash);
976 #ifdef INET6
977 	if (inp->inp_flags & INP_IPV6)
978 		head = in6_pcbhash(table, rtable_l2(inp->inp_rtableid),
979 		    &inp->inp_faddr6, inp->inp_fport,
980 		    &inp->inp_laddr6, inp->inp_lport);
981 	else
982 #endif /* INET6 */
983 		head = in_pcbhash(table, rtable_l2(inp->inp_rtableid),
984 		    &inp->inp_faddr, inp->inp_fport,
985 		    &inp->inp_laddr, inp->inp_lport);
986 	LIST_INSERT_HEAD(head, inp, inp_hash);
987 }
988 
989 int
990 in_pcbresize(struct inpcbtable *table, int hashsize)
991 {
992 	u_long nmask, nlmask;
993 	int osize;
994 	void *nhashtbl, *nlhashtbl, *ohashtbl, *olhashtbl;
995 	struct inpcb *inp;
996 
997 	ohashtbl = table->inpt_hashtbl;
998 	olhashtbl = table->inpt_lhashtbl;
999 	osize = table->inpt_size;
1000 
1001 	nhashtbl = hashinit(hashsize, M_PCB, M_NOWAIT, &nmask);
1002 	if (nhashtbl == NULL)
1003 		return ENOBUFS;
1004 	nlhashtbl = hashinit(hashsize, M_PCB, M_NOWAIT, &nlmask);
1005 	if (nlhashtbl == NULL) {
1006 		hashfree(nhashtbl, hashsize, M_PCB);
1007 		return ENOBUFS;
1008 	}
1009 	table->inpt_hashtbl = nhashtbl;
1010 	table->inpt_lhashtbl = nlhashtbl;
1011 	table->inpt_mask = nmask;
1012 	table->inpt_lmask = nlmask;
1013 	table->inpt_size = hashsize;
1014 	arc4random_buf(&table->inpt_key, sizeof(table->inpt_key));
1015 	arc4random_buf(&table->inpt_lkey, sizeof(table->inpt_lkey));
1016 
1017 	TAILQ_FOREACH(inp, &table->inpt_queue, inp_queue) {
1018 		in_pcbrehash(inp);
1019 	}
1020 	hashfree(ohashtbl, osize, M_PCB);
1021 	hashfree(olhashtbl, osize, M_PCB);
1022 
1023 	return (0);
1024 }
1025 
1026 #ifdef DIAGNOSTIC
1027 int	in_pcbnotifymiss = 0;
1028 #endif
1029 
1030 /*
1031  * The in(6)_pcbhashlookup functions are used to locate connected sockets
1032  * quickly:
1033  *     faddr.fport <-> laddr.lport
1034  * No wildcard matching is done so that listening sockets are not found.
1035  * If the functions return NULL in(6)_pcblookup_listen can be used to
1036  * find a listening/bound socket that may accept the connection.
1037  * After those two lookups no other are necessary.
1038  */
1039 struct inpcb *
1040 in_pcbhashlookup(struct inpcbtable *table, struct in_addr faddr,
1041     u_int fport_arg, struct in_addr laddr, u_int lport_arg, u_int rtable)
1042 {
1043 	struct inpcbhead *head;
1044 	struct inpcb *inp;
1045 	u_int16_t fport = fport_arg, lport = lport_arg;
1046 	u_int rdomain;
1047 
1048 	rdomain = rtable_l2(rtable);
1049 	head = in_pcbhash(table, rdomain, &faddr, fport, &laddr, lport);
1050 	LIST_FOREACH(inp, head, inp_hash) {
1051 #ifdef INET6
1052 		if (inp->inp_flags & INP_IPV6)
1053 			continue;	/*XXX*/
1054 #endif
1055 		if (inp->inp_faddr.s_addr == faddr.s_addr &&
1056 		    inp->inp_fport == fport && inp->inp_lport == lport &&
1057 		    inp->inp_laddr.s_addr == laddr.s_addr &&
1058 		    rtable_l2(inp->inp_rtableid) == rdomain) {
1059 			/*
1060 			 * Move this PCB to the head of hash chain so that
1061 			 * repeated accesses are quicker.  This is analogous to
1062 			 * the historic single-entry PCB cache.
1063 			 */
1064 			if (inp != LIST_FIRST(head)) {
1065 				LIST_REMOVE(inp, inp_hash);
1066 				LIST_INSERT_HEAD(head, inp, inp_hash);
1067 			}
1068 			break;
1069 		}
1070 	}
1071 #ifdef DIAGNOSTIC
1072 	if (inp == NULL && in_pcbnotifymiss) {
1073 		printf("%s: faddr=%08x fport=%d laddr=%08x lport=%d rdom=%u\n",
1074 		    __func__, ntohl(faddr.s_addr), ntohs(fport),
1075 		    ntohl(laddr.s_addr), ntohs(lport), rdomain);
1076 	}
1077 #endif
1078 	return (inp);
1079 }
1080 
1081 /*
1082  * The in(6)_pcblookup_listen functions are used to locate listening
1083  * sockets quickly.  This are sockets with unspecified foreign address
1084  * and port:
1085  *		*.*     <-> laddr.lport
1086  *		*.*     <->     *.lport
1087  */
1088 struct inpcb *
1089 in_pcblookup_listen(struct inpcbtable *table, struct in_addr laddr,
1090     u_int lport_arg, struct mbuf *m, u_int rtable)
1091 {
1092 	struct inpcbhead *head;
1093 	const struct in_addr *key1, *key2;
1094 	struct inpcb *inp;
1095 	u_int16_t lport = lport_arg;
1096 	u_int rdomain;
1097 
1098 	key1 = &laddr;
1099 	key2 = &zeroin_addr;
1100 #if NPF > 0
1101 	if (m && m->m_pkthdr.pf.flags & PF_TAG_DIVERTED) {
1102 		struct pf_divert *divert;
1103 
1104 		divert = pf_find_divert(m);
1105 		KASSERT(divert != NULL);
1106 		switch (divert->type) {
1107 		case PF_DIVERT_TO:
1108 			key1 = key2 = &divert->addr.v4;
1109 			lport = divert->port;
1110 			break;
1111 		case PF_DIVERT_REPLY:
1112 			return (NULL);
1113 		default:
1114 			panic("%s: unknown divert type %d, mbuf %p, divert %p",
1115 			    __func__, divert->type, m, divert);
1116 		}
1117 	} else if (m && m->m_pkthdr.pf.flags & PF_TAG_TRANSLATE_LOCALHOST) {
1118 		/*
1119 		 * Redirected connections should not be treated the same
1120 		 * as connections directed to 127.0.0.0/8 since localhost
1121 		 * can only be accessed from the host itself.
1122 		 * For example portmap(8) grants more permissions for
1123 		 * connections to the socket bound to 127.0.0.1 than
1124 		 * to the * socket.
1125 		 */
1126 		key1 = &zeroin_addr;
1127 		key2 = &laddr;
1128 	}
1129 #endif
1130 
1131 	rdomain = rtable_l2(rtable);
1132 	head = in_pcbhash(table, rdomain, &zeroin_addr, 0, key1, lport);
1133 	LIST_FOREACH(inp, head, inp_hash) {
1134 #ifdef INET6
1135 		if (inp->inp_flags & INP_IPV6)
1136 			continue;	/*XXX*/
1137 #endif
1138 		if (inp->inp_lport == lport && inp->inp_fport == 0 &&
1139 		    inp->inp_laddr.s_addr == key1->s_addr &&
1140 		    inp->inp_faddr.s_addr == INADDR_ANY &&
1141 		    rtable_l2(inp->inp_rtableid) == rdomain)
1142 			break;
1143 	}
1144 	if (inp == NULL && key1->s_addr != key2->s_addr) {
1145 		head = in_pcbhash(table, rdomain,
1146 		    &zeroin_addr, 0, key2, lport);
1147 		LIST_FOREACH(inp, head, inp_hash) {
1148 #ifdef INET6
1149 			if (inp->inp_flags & INP_IPV6)
1150 				continue;	/*XXX*/
1151 #endif
1152 			if (inp->inp_lport == lport && inp->inp_fport == 0 &&
1153 			    inp->inp_laddr.s_addr == key2->s_addr &&
1154 			    inp->inp_faddr.s_addr == INADDR_ANY &&
1155 			    rtable_l2(inp->inp_rtableid) == rdomain)
1156 				break;
1157 		}
1158 	}
1159 	/*
1160 	 * Move this PCB to the head of hash chain so that
1161 	 * repeated accesses are quicker.  This is analogous to
1162 	 * the historic single-entry PCB cache.
1163 	 */
1164 	if (inp != NULL && inp != LIST_FIRST(head)) {
1165 		LIST_REMOVE(inp, inp_hash);
1166 		LIST_INSERT_HEAD(head, inp, inp_hash);
1167 	}
1168 #ifdef DIAGNOSTIC
1169 	if (inp == NULL && in_pcbnotifymiss) {
1170 		printf("%s: laddr=%08x lport=%d rdom=%u\n",
1171 		    __func__, ntohl(laddr.s_addr), ntohs(lport), rdomain);
1172 	}
1173 #endif
1174 	return (inp);
1175 }
1176