xref: /openbsd-src/sys/netinet/in_pcb.c (revision 99fd087599a8791921855f21bd7e36130f39aadc)
1 /*	$OpenBSD: in_pcb.c,v 1.248 2019/07/15 12:40:42 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 	switch (sotopf(inp->inp_socket)) {
534 #ifdef INET6
535 	case PF_INET6:
536 		inp->inp_faddr6 = in6addr_any;
537 		break;
538 #endif
539 	case PF_INET:
540 		inp->inp_faddr.s_addr = INADDR_ANY;
541 		break;
542 	}
543 
544 	inp->inp_fport = 0;
545 	in_pcbrehash(inp);
546 	if (inp->inp_socket->so_state & SS_NOFDREF)
547 		in_pcbdetach(inp);
548 }
549 
550 void
551 in_pcbdetach(struct inpcb *inp)
552 {
553 	struct socket *so = inp->inp_socket;
554 
555 	NET_ASSERT_LOCKED();
556 
557 	so->so_pcb = NULL;
558 	/*
559 	 * As long as the NET_LOCK() is the default lock for Internet
560 	 * sockets, do not release it to not introduce new sleeping
561 	 * points.
562 	 */
563 	sofree(so, SL_NOUNLOCK);
564 	m_freem(inp->inp_options);
565 	if (inp->inp_route.ro_rt) {
566 		rtfree(inp->inp_route.ro_rt);
567 		inp->inp_route.ro_rt = NULL;
568 	}
569 #ifdef INET6
570 	if (inp->inp_flags & INP_IPV6) {
571 		ip6_freepcbopts(inp->inp_outputopts6);
572 		ip6_freemoptions(inp->inp_moptions6);
573 	} else
574 #endif
575 		ip_freemoptions(inp->inp_moptions);
576 #if NPF > 0
577 	if (inp->inp_pf_sk) {
578 		pf_remove_divert_state(inp->inp_pf_sk);
579 		/* pf_remove_divert_state() may have detached the state */
580 		pf_inp_unlink(inp);
581 	}
582 #endif
583 	LIST_REMOVE(inp, inp_lhash);
584 	LIST_REMOVE(inp, inp_hash);
585 	TAILQ_REMOVE(&inp->inp_table->inpt_queue, inp, inp_queue);
586 	inp->inp_table->inpt_count--;
587 	in_pcbunref(inp);
588 }
589 
590 struct inpcb *
591 in_pcbref(struct inpcb *inp)
592 {
593 	if (inp != NULL)
594 		refcnt_take(&inp->inp_refcnt);
595 	return inp;
596 }
597 
598 void
599 in_pcbunref(struct inpcb *inp)
600 {
601 	if (refcnt_rele(&inp->inp_refcnt)) {
602 		KASSERT((LIST_NEXT(inp, inp_hash) == NULL) ||
603 		    (LIST_NEXT(inp, inp_hash) == _Q_INVALID));
604 		KASSERT((LIST_NEXT(inp, inp_lhash) == NULL) ||
605 		    (LIST_NEXT(inp, inp_lhash) == _Q_INVALID));
606 		KASSERT((TAILQ_NEXT(inp, inp_queue) == NULL) ||
607 		    (TAILQ_NEXT(inp, inp_queue) == _Q_INVALID));
608 		pool_put(&inpcb_pool, inp);
609 	}
610 }
611 
612 void
613 in_setsockaddr(struct inpcb *inp, struct mbuf *nam)
614 {
615 	struct sockaddr_in *sin;
616 
617 	nam->m_len = sizeof(*sin);
618 	sin = mtod(nam, struct sockaddr_in *);
619 	memset(sin, 0, sizeof(*sin));
620 	sin->sin_family = AF_INET;
621 	sin->sin_len = sizeof(*sin);
622 	sin->sin_port = inp->inp_lport;
623 	sin->sin_addr = inp->inp_laddr;
624 }
625 
626 void
627 in_setpeeraddr(struct inpcb *inp, struct mbuf *nam)
628 {
629 	struct sockaddr_in *sin;
630 
631 #ifdef INET6
632 	if (sotopf(inp->inp_socket) == PF_INET6) {
633 		in6_setpeeraddr(inp, nam);
634 		return;
635 	}
636 #endif /* INET6 */
637 
638 	nam->m_len = sizeof(*sin);
639 	sin = mtod(nam, struct sockaddr_in *);
640 	memset(sin, 0, sizeof(*sin));
641 	sin->sin_family = AF_INET;
642 	sin->sin_len = sizeof(*sin);
643 	sin->sin_port = inp->inp_fport;
644 	sin->sin_addr = inp->inp_faddr;
645 }
646 
647 /*
648  * Pass some notification to all connections of a protocol
649  * associated with address dst.  The "usual action" will be
650  * taken, depending on the ctlinput cmd.  The caller must filter any
651  * cmds that are uninteresting (e.g., no error in the map).
652  * Call the protocol specific routine (if any) to report
653  * any errors for each matching socket.
654  */
655 void
656 in_pcbnotifyall(struct inpcbtable *table, struct sockaddr *dst, u_int rtable,
657     int errno, void (*notify)(struct inpcb *, int))
658 {
659 	struct inpcb *inp, *ninp;
660 	struct in_addr faddr;
661 	u_int rdomain;
662 
663 	NET_ASSERT_LOCKED();
664 
665 #ifdef INET6
666 	/*
667 	 * See in6_pcbnotify() for IPv6 codepath.  By the time this
668 	 * gets called, the addresses passed are either definitely IPv4 or
669 	 * IPv6; *_pcbnotify() never gets called with v4-mapped v6 addresses.
670 	 */
671 #endif /* INET6 */
672 
673 	if (dst->sa_family != AF_INET)
674 		return;
675 	faddr = satosin(dst)->sin_addr;
676 	if (faddr.s_addr == INADDR_ANY)
677 		return;
678 
679 	rdomain = rtable_l2(rtable);
680 	TAILQ_FOREACH_SAFE(inp, &table->inpt_queue, inp_queue, ninp) {
681 #ifdef INET6
682 		if (inp->inp_flags & INP_IPV6)
683 			continue;
684 #endif
685 		if (inp->inp_faddr.s_addr != faddr.s_addr ||
686 		    rtable_l2(inp->inp_rtableid) != rdomain ||
687 		    inp->inp_socket == NULL) {
688 			continue;
689 		}
690 		if (notify)
691 			(*notify)(inp, errno);
692 	}
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(struct inpcb *inp)
703 {
704 	struct rtentry *rt = inp->inp_route.ro_rt;
705 
706 	if (rt) {
707 		inp->inp_route.ro_rt = NULL;
708 
709 		if (rt->rt_flags & RTF_DYNAMIC) {
710 			struct ifnet *ifp;
711 
712 			ifp = if_get(rt->rt_ifidx);
713 			/*
714 			 * If the interface is gone, all its attached
715 			 * route entries have been removed from the table,
716 			 * so we're dealing with a stale cache and have
717 			 * nothing to do.
718 			 */
719 			if (ifp != NULL)
720 				rtdeletemsg(rt, ifp, inp->inp_rtableid);
721 			if_put(ifp);
722 		}
723 		/*
724 		 * A new route can be allocated
725 		 * the next time output is attempted.
726 		 * rtfree() needs to be called in anycase because the inp
727 		 * is still holding a reference to rt.
728 		 */
729 		rtfree(rt);
730 	}
731 }
732 
733 /*
734  * After a routing change, flush old routing
735  * and allocate a (hopefully) better one.
736  */
737 void
738 in_rtchange(struct inpcb *inp, int errno)
739 {
740 	if (inp->inp_route.ro_rt) {
741 		rtfree(inp->inp_route.ro_rt);
742 		inp->inp_route.ro_rt = 0;
743 		/*
744 		 * A new route can be allocated the next time
745 		 * output is attempted.
746 		 */
747 	}
748 }
749 
750 struct inpcb *
751 in_pcblookup_local(struct inpcbtable *table, void *laddrp, u_int lport_arg,
752     int flags, u_int rtable)
753 {
754 	struct inpcb *inp, *match = NULL;
755 	int matchwild = 3, wildcard;
756 	u_int16_t lport = lport_arg;
757 	struct in_addr laddr = *(struct in_addr *)laddrp;
758 #ifdef INET6
759 	struct in6_addr *laddr6 = (struct in6_addr *)laddrp;
760 #endif
761 	struct inpcbhead *head;
762 	u_int rdomain;
763 
764 	rdomain = rtable_l2(rtable);
765 	head = in_pcblhash(table, rdomain, lport);
766 	LIST_FOREACH(inp, head, inp_lhash) {
767 		if (rtable_l2(inp->inp_rtableid) != rdomain)
768 			continue;
769 		if (inp->inp_lport != lport)
770 			continue;
771 		wildcard = 0;
772 #ifdef INET6
773 		if (ISSET(flags, INPLOOKUP_IPV6)) {
774 			if (!ISSET(inp->inp_flags, INP_IPV6))
775 				continue;
776 
777 			if (!IN6_IS_ADDR_UNSPECIFIED(&inp->inp_faddr6))
778 				wildcard++;
779 
780 			if (!IN6_ARE_ADDR_EQUAL(&inp->inp_laddr6, laddr6)) {
781 				if (IN6_IS_ADDR_UNSPECIFIED(&inp->inp_laddr6) ||
782 				    IN6_IS_ADDR_UNSPECIFIED(laddr6))
783 					wildcard++;
784 				else
785 					continue;
786 			}
787 
788 		} else
789 #endif /* INET6 */
790 		{
791 #ifdef INET6
792 			if (ISSET(inp->inp_flags, INP_IPV6))
793 				continue;
794 #endif /* INET6 */
795 
796 			if (inp->inp_faddr.s_addr != INADDR_ANY)
797 				wildcard++;
798 
799 			if (inp->inp_laddr.s_addr != laddr.s_addr) {
800 				if (inp->inp_laddr.s_addr == INADDR_ANY ||
801 				    laddr.s_addr == INADDR_ANY)
802 					wildcard++;
803 				else
804 					continue;
805 			}
806 
807 		}
808 		if ((!wildcard || (flags & INPLOOKUP_WILDCARD)) &&
809 		    wildcard < matchwild) {
810 			match = inp;
811 			if ((matchwild = wildcard) == 0)
812 				break;
813 		}
814 	}
815 	return (match);
816 }
817 
818 struct rtentry *
819 in_pcbrtentry(struct inpcb *inp)
820 {
821 	struct route *ro;
822 
823 	ro = &inp->inp_route;
824 
825 	/* check if route is still valid */
826 	if (!rtisvalid(ro->ro_rt)) {
827 		rtfree(ro->ro_rt);
828 		ro->ro_rt = NULL;
829 	}
830 
831 	/*
832 	 * No route yet, so try to acquire one.
833 	 */
834 	if (ro->ro_rt == NULL) {
835 #ifdef INET6
836 		memset(ro, 0, sizeof(struct route_in6));
837 #else
838 		memset(ro, 0, sizeof(struct route));
839 #endif
840 
841 		switch(sotopf(inp->inp_socket)) {
842 #ifdef INET6
843 		case PF_INET6:
844 			if (IN6_IS_ADDR_UNSPECIFIED(&inp->inp_faddr6))
845 				break;
846 			ro->ro_dst.sa_family = AF_INET6;
847 			ro->ro_dst.sa_len = sizeof(struct sockaddr_in6);
848 			satosin6(&ro->ro_dst)->sin6_addr = inp->inp_faddr6;
849 			ro->ro_tableid = inp->inp_rtableid;
850 			ro->ro_rt = rtalloc_mpath(&ro->ro_dst,
851 			    &inp->inp_laddr6.s6_addr32[0], ro->ro_tableid);
852 			break;
853 #endif /* INET6 */
854 		case PF_INET:
855 			if (inp->inp_faddr.s_addr == INADDR_ANY)
856 				break;
857 			ro->ro_dst.sa_family = AF_INET;
858 			ro->ro_dst.sa_len = sizeof(struct sockaddr_in);
859 			satosin(&ro->ro_dst)->sin_addr = inp->inp_faddr;
860 			ro->ro_tableid = inp->inp_rtableid;
861 			ro->ro_rt = rtalloc_mpath(&ro->ro_dst,
862 			    &inp->inp_laddr.s_addr, ro->ro_tableid);
863 			break;
864 		}
865 	}
866 	return (ro->ro_rt);
867 }
868 
869 /*
870  * Return an IPv4 address, which is the most appropriate for a given
871  * destination.
872  * If necessary, this function lookups the routing table and returns
873  * an entry to the caller for later use.
874  */
875 int
876 in_pcbselsrc(struct in_addr **insrc, struct sockaddr_in *sin,
877     struct inpcb *inp)
878 {
879 	struct ip_moptions *mopts = inp->inp_moptions;
880 	struct route *ro = &inp->inp_route;
881 	struct in_addr *laddr = &inp->inp_laddr;
882 	u_int rtableid = inp->inp_rtableid;
883 
884 	struct sockaddr_in *sin2;
885 	struct in_ifaddr *ia = NULL;
886 
887 	/*
888 	 * If the socket(if any) is already bound, use that bound address
889 	 * unless it is INADDR_ANY or INADDR_BROADCAST.
890 	 */
891 	if (laddr && laddr->s_addr != INADDR_ANY &&
892 	    laddr->s_addr != INADDR_BROADCAST) {
893 		*insrc = laddr;
894 		return (0);
895 	}
896 
897 	/*
898 	 * If the destination address is multicast and an outgoing
899 	 * interface has been set as a multicast option, use the
900 	 * address of that interface as our source address.
901 	 */
902 	if (IN_MULTICAST(sin->sin_addr.s_addr) && mopts != NULL) {
903 		struct ifnet *ifp;
904 
905 		ifp = if_get(mopts->imo_ifidx);
906 		if (ifp != NULL) {
907 			if (ifp->if_rdomain == rtable_l2(rtableid))
908 				IFP_TO_IA(ifp, ia);
909 			if (ia == NULL) {
910 				if_put(ifp);
911 				return (EADDRNOTAVAIL);
912 			}
913 
914 			*insrc = &ia->ia_addr.sin_addr;
915 			if_put(ifp);
916 			return (0);
917 		}
918 	}
919 	/*
920 	 * If route is known or can be allocated now,
921 	 * our src addr is taken from the i/f, else punt.
922 	 */
923 	if (!rtisvalid(ro->ro_rt) || (ro->ro_tableid != rtableid) ||
924 	    (satosin(&ro->ro_dst)->sin_addr.s_addr != sin->sin_addr.s_addr)) {
925 		rtfree(ro->ro_rt);
926 		ro->ro_rt = NULL;
927 	}
928 	if (ro->ro_rt == NULL) {
929 		/* No route yet, so try to acquire one */
930 		ro->ro_dst.sa_family = AF_INET;
931 		ro->ro_dst.sa_len = sizeof(struct sockaddr_in);
932 		satosin(&ro->ro_dst)->sin_addr = sin->sin_addr;
933 		ro->ro_tableid = rtableid;
934 		ro->ro_rt = rtalloc_mpath(&ro->ro_dst, NULL, ro->ro_tableid);
935 
936 		/*
937 		 * It is important to zero out the rest of the
938 		 * struct sockaddr_in when mixing v6 & v4!
939 		 */
940 		sin2 = satosin(&ro->ro_dst);
941 		memset(sin2->sin_zero, 0, sizeof(sin2->sin_zero));
942 	}
943 	/*
944 	 * If we found a route, use the address
945 	 * corresponding to the outgoing interface.
946 	 */
947 	if (ro->ro_rt != NULL)
948 		ia = ifatoia(ro->ro_rt->rt_ifa);
949 
950 	if (ia == NULL)
951 		return (EADDRNOTAVAIL);
952 
953 	*insrc = &ia->ia_addr.sin_addr;
954 	return (0);
955 }
956 
957 void
958 in_pcbrehash(struct inpcb *inp)
959 {
960 	struct inpcbtable *table = inp->inp_table;
961 	struct inpcbhead *head;
962 
963 	NET_ASSERT_LOCKED();
964 
965 	LIST_REMOVE(inp, inp_lhash);
966 	head = in_pcblhash(table, inp->inp_rtableid, inp->inp_lport);
967 	LIST_INSERT_HEAD(head, inp, inp_lhash);
968 	LIST_REMOVE(inp, inp_hash);
969 #ifdef INET6
970 	if (inp->inp_flags & INP_IPV6)
971 		head = in6_pcbhash(table, rtable_l2(inp->inp_rtableid),
972 		    &inp->inp_faddr6, inp->inp_fport,
973 		    &inp->inp_laddr6, inp->inp_lport);
974 	else
975 #endif /* INET6 */
976 		head = in_pcbhash(table, rtable_l2(inp->inp_rtableid),
977 		    &inp->inp_faddr, inp->inp_fport,
978 		    &inp->inp_laddr, inp->inp_lport);
979 	LIST_INSERT_HEAD(head, inp, inp_hash);
980 }
981 
982 int
983 in_pcbresize(struct inpcbtable *table, int hashsize)
984 {
985 	u_long nmask, nlmask;
986 	int osize;
987 	void *nhashtbl, *nlhashtbl, *ohashtbl, *olhashtbl;
988 	struct inpcb *inp;
989 
990 	ohashtbl = table->inpt_hashtbl;
991 	olhashtbl = table->inpt_lhashtbl;
992 	osize = table->inpt_size;
993 
994 	nhashtbl = hashinit(hashsize, M_PCB, M_NOWAIT, &nmask);
995 	if (nhashtbl == NULL)
996 		return ENOBUFS;
997 	nlhashtbl = hashinit(hashsize, M_PCB, M_NOWAIT, &nlmask);
998 	if (nlhashtbl == NULL) {
999 		hashfree(nhashtbl, hashsize, M_PCB);
1000 		return ENOBUFS;
1001 	}
1002 	table->inpt_hashtbl = nhashtbl;
1003 	table->inpt_lhashtbl = nlhashtbl;
1004 	table->inpt_mask = nmask;
1005 	table->inpt_lmask = nlmask;
1006 	table->inpt_size = hashsize;
1007 	arc4random_buf(&table->inpt_key, sizeof(table->inpt_key));
1008 	arc4random_buf(&table->inpt_lkey, sizeof(table->inpt_lkey));
1009 
1010 	TAILQ_FOREACH(inp, &table->inpt_queue, inp_queue) {
1011 		in_pcbrehash(inp);
1012 	}
1013 	hashfree(ohashtbl, osize, M_PCB);
1014 	hashfree(olhashtbl, osize, M_PCB);
1015 
1016 	return (0);
1017 }
1018 
1019 #ifdef DIAGNOSTIC
1020 int	in_pcbnotifymiss = 0;
1021 #endif
1022 
1023 /*
1024  * The in(6)_pcbhashlookup functions are used to locate connected sockets
1025  * quickly:
1026  *     faddr.fport <-> laddr.lport
1027  * No wildcard matching is done so that listening sockets are not found.
1028  * If the functions return NULL in(6)_pcblookup_listen can be used to
1029  * find a listening/bound socket that may accept the connection.
1030  * After those two lookups no other are necessary.
1031  */
1032 struct inpcb *
1033 in_pcbhashlookup(struct inpcbtable *table, struct in_addr faddr,
1034     u_int fport_arg, struct in_addr laddr, u_int lport_arg, u_int rtable)
1035 {
1036 	struct inpcbhead *head;
1037 	struct inpcb *inp;
1038 	u_int16_t fport = fport_arg, lport = lport_arg;
1039 	u_int rdomain;
1040 
1041 	rdomain = rtable_l2(rtable);
1042 	head = in_pcbhash(table, rdomain, &faddr, fport, &laddr, lport);
1043 	LIST_FOREACH(inp, head, inp_hash) {
1044 #ifdef INET6
1045 		if (inp->inp_flags & INP_IPV6)
1046 			continue;	/*XXX*/
1047 #endif
1048 		if (inp->inp_faddr.s_addr == faddr.s_addr &&
1049 		    inp->inp_fport == fport && inp->inp_lport == lport &&
1050 		    inp->inp_laddr.s_addr == laddr.s_addr &&
1051 		    rtable_l2(inp->inp_rtableid) == rdomain) {
1052 			/*
1053 			 * Move this PCB to the head of hash chain so that
1054 			 * repeated accesses are quicker.  This is analogous to
1055 			 * the historic single-entry PCB cache.
1056 			 */
1057 			if (inp != LIST_FIRST(head)) {
1058 				LIST_REMOVE(inp, inp_hash);
1059 				LIST_INSERT_HEAD(head, inp, inp_hash);
1060 			}
1061 			break;
1062 		}
1063 	}
1064 #ifdef DIAGNOSTIC
1065 	if (inp == NULL && in_pcbnotifymiss) {
1066 		printf("%s: faddr=%08x fport=%d laddr=%08x lport=%d rdom=%u\n",
1067 		    __func__, ntohl(faddr.s_addr), ntohs(fport),
1068 		    ntohl(laddr.s_addr), ntohs(lport), rdomain);
1069 	}
1070 #endif
1071 	return (inp);
1072 }
1073 
1074 /*
1075  * The in(6)_pcblookup_listen functions are used to locate listening
1076  * sockets quickly.  This are sockets with unspecified foreign address
1077  * and port:
1078  *		*.*     <-> laddr.lport
1079  *		*.*     <->     *.lport
1080  */
1081 struct inpcb *
1082 in_pcblookup_listen(struct inpcbtable *table, struct in_addr laddr,
1083     u_int lport_arg, struct mbuf *m, u_int rtable)
1084 {
1085 	struct inpcbhead *head;
1086 	const struct in_addr *key1, *key2;
1087 	struct inpcb *inp;
1088 	u_int16_t lport = lport_arg;
1089 	u_int rdomain;
1090 
1091 	key1 = &laddr;
1092 	key2 = &zeroin_addr;
1093 #if NPF > 0
1094 	if (m && m->m_pkthdr.pf.flags & PF_TAG_DIVERTED) {
1095 		struct pf_divert *divert;
1096 
1097 		divert = pf_find_divert(m);
1098 		KASSERT(divert != NULL);
1099 		switch (divert->type) {
1100 		case PF_DIVERT_TO:
1101 			key1 = key2 = &divert->addr.v4;
1102 			lport = divert->port;
1103 			break;
1104 		case PF_DIVERT_REPLY:
1105 			return (NULL);
1106 		default:
1107 			panic("%s: unknown divert type %d, mbuf %p, divert %p",
1108 			    __func__, divert->type, m, divert);
1109 		}
1110 	} else if (m && m->m_pkthdr.pf.flags & PF_TAG_TRANSLATE_LOCALHOST) {
1111 		/*
1112 		 * Redirected connections should not be treated the same
1113 		 * as connections directed to 127.0.0.0/8 since localhost
1114 		 * can only be accessed from the host itself.
1115 		 * For example portmap(8) grants more permissions for
1116 		 * connections to the socket bound to 127.0.0.1 than
1117 		 * to the * socket.
1118 		 */
1119 		key1 = &zeroin_addr;
1120 		key2 = &laddr;
1121 	}
1122 #endif
1123 
1124 	rdomain = rtable_l2(rtable);
1125 	head = in_pcbhash(table, rdomain, &zeroin_addr, 0, key1, lport);
1126 	LIST_FOREACH(inp, head, inp_hash) {
1127 #ifdef INET6
1128 		if (inp->inp_flags & INP_IPV6)
1129 			continue;	/*XXX*/
1130 #endif
1131 		if (inp->inp_lport == lport && inp->inp_fport == 0 &&
1132 		    inp->inp_laddr.s_addr == key1->s_addr &&
1133 		    inp->inp_faddr.s_addr == INADDR_ANY &&
1134 		    rtable_l2(inp->inp_rtableid) == rdomain)
1135 			break;
1136 	}
1137 	if (inp == NULL && key1->s_addr != key2->s_addr) {
1138 		head = in_pcbhash(table, rdomain,
1139 		    &zeroin_addr, 0, key2, lport);
1140 		LIST_FOREACH(inp, head, inp_hash) {
1141 #ifdef INET6
1142 			if (inp->inp_flags & INP_IPV6)
1143 				continue;	/*XXX*/
1144 #endif
1145 			if (inp->inp_lport == lport && inp->inp_fport == 0 &&
1146 			    inp->inp_laddr.s_addr == key2->s_addr &&
1147 			    inp->inp_faddr.s_addr == INADDR_ANY &&
1148 			    rtable_l2(inp->inp_rtableid) == rdomain)
1149 				break;
1150 		}
1151 	}
1152 	/*
1153 	 * Move this PCB to the head of hash chain so that
1154 	 * repeated accesses are quicker.  This is analogous to
1155 	 * the historic single-entry PCB cache.
1156 	 */
1157 	if (inp != NULL && inp != LIST_FIRST(head)) {
1158 		LIST_REMOVE(inp, inp_hash);
1159 		LIST_INSERT_HEAD(head, inp, inp_hash);
1160 	}
1161 #ifdef DIAGNOSTIC
1162 	if (inp == NULL && in_pcbnotifymiss) {
1163 		printf("%s: laddr=%08x lport=%d rdom=%u\n",
1164 		    __func__, ntohl(laddr.s_addr), ntohs(lport), rdomain);
1165 	}
1166 #endif
1167 	return (inp);
1168 }
1169