xref: /netbsd-src/sys/netinet/in_pcb.c (revision 181254a7b1bdde6873432bffef2d2decc4b5c22f)
1 /*	$NetBSD: in_pcb.c,v 1.184 2020/08/20 21:21:32 riastradh Exp $	*/
2 
3 /*
4  * Copyright (C) 1995, 1996, 1997, and 1998 WIDE Project.
5  * All rights reserved.
6  *
7  * Redistribution and use in source and binary forms, with or without
8  * modification, are permitted provided that the following conditions
9  * are met:
10  * 1. Redistributions of source code must retain the above copyright
11  *    notice, this list of conditions and the following disclaimer.
12  * 2. Redistributions in binary form must reproduce the above copyright
13  *    notice, this list of conditions and the following disclaimer in the
14  *    documentation and/or other materials provided with the distribution.
15  * 3. Neither the name of the project nor the names of its contributors
16  *    may be used to endorse or promote products derived from this software
17  *    without specific prior written permission.
18  *
19  * THIS SOFTWARE IS PROVIDED BY THE PROJECT AND CONTRIBUTORS ``AS IS'' AND
20  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
21  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
22  * ARE DISCLAIMED.  IN NO EVENT SHALL THE PROJECT OR CONTRIBUTORS BE LIABLE
23  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
24  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
25  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
26  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
27  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
28  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
29  * SUCH DAMAGE.
30  */
31 
32 /*-
33  * Copyright (c) 1998, 2011 The NetBSD Foundation, Inc.
34  * All rights reserved.
35  *
36  * This code is derived from software contributed to The NetBSD Foundation
37  * by Coyote Point Systems, Inc.
38  * This code is derived from software contributed to The NetBSD Foundation
39  * by Public Access Networks Corporation ("Panix").  It was developed under
40  * contract to Panix by Eric Haszlakiewicz and Thor Lancelot Simon.
41  *
42  * Redistribution and use in source and binary forms, with or without
43  * modification, are permitted provided that the following conditions
44  * are met:
45  * 1. Redistributions of source code must retain the above copyright
46  *    notice, this list of conditions and the following disclaimer.
47  * 2. Redistributions in binary form must reproduce the above copyright
48  *    notice, this list of conditions and the following disclaimer in the
49  *    documentation and/or other materials provided with the distribution.
50  *
51  * THIS SOFTWARE IS PROVIDED BY THE NETBSD FOUNDATION, INC. AND CONTRIBUTORS
52  * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
53  * TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
54  * PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL THE FOUNDATION OR CONTRIBUTORS
55  * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
56  * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
57  * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
58  * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
59  * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
60  * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
61  * POSSIBILITY OF SUCH DAMAGE.
62  */
63 
64 /*
65  * Copyright (c) 1982, 1986, 1991, 1993, 1995
66  *	The Regents of the University of California.  All rights reserved.
67  *
68  * Redistribution and use in source and binary forms, with or without
69  * modification, are permitted provided that the following conditions
70  * are met:
71  * 1. Redistributions of source code must retain the above copyright
72  *    notice, this list of conditions and the following disclaimer.
73  * 2. Redistributions in binary form must reproduce the above copyright
74  *    notice, this list of conditions and the following disclaimer in the
75  *    documentation and/or other materials provided with the distribution.
76  * 3. Neither the name of the University nor the names of its contributors
77  *    may be used to endorse or promote products derived from this software
78  *    without specific prior written permission.
79  *
80  * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
81  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
82  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
83  * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
84  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
85  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
86  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
87  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
88  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
89  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
90  * SUCH DAMAGE.
91  *
92  *	@(#)in_pcb.c	8.4 (Berkeley) 5/24/95
93  */
94 
95 #include <sys/cdefs.h>
96 __KERNEL_RCSID(0, "$NetBSD: in_pcb.c,v 1.184 2020/08/20 21:21:32 riastradh Exp $");
97 
98 #ifdef _KERNEL_OPT
99 #include "opt_inet.h"
100 #include "opt_ipsec.h"
101 #endif
102 
103 #include <sys/param.h>
104 #include <sys/systm.h>
105 #include <sys/mbuf.h>
106 #include <sys/socket.h>
107 #include <sys/socketvar.h>
108 #include <sys/ioctl.h>
109 #include <sys/errno.h>
110 #include <sys/time.h>
111 #include <sys/once.h>
112 #include <sys/pool.h>
113 #include <sys/proc.h>
114 #include <sys/kauth.h>
115 #include <sys/uidinfo.h>
116 #include <sys/domain.h>
117 
118 #include <net/if.h>
119 #include <net/route.h>
120 
121 #include <netinet/in.h>
122 #include <netinet/in_systm.h>
123 #include <netinet/ip.h>
124 #include <netinet/in_pcb.h>
125 #include <netinet/in_var.h>
126 #include <netinet/ip_var.h>
127 #include <netinet/portalgo.h>
128 
129 #ifdef INET6
130 #include <netinet/ip6.h>
131 #include <netinet6/ip6_var.h>
132 #include <netinet6/in6_pcb.h>
133 #endif
134 
135 #ifdef IPSEC
136 #include <netipsec/ipsec.h>
137 #include <netipsec/key.h>
138 #endif /* IPSEC */
139 
140 #include <netinet/tcp_vtw.h>
141 
142 struct	in_addr zeroin_addr;
143 
144 #define	INPCBHASH_PORT(table, lport) \
145 	&(table)->inpt_porthashtbl[ntohs(lport) & (table)->inpt_porthash]
146 #define	INPCBHASH_BIND(table, laddr, lport) \
147 	&(table)->inpt_bindhashtbl[ \
148 	    ((ntohl((laddr).s_addr) + ntohs(lport))) & (table)->inpt_bindhash]
149 #define	INPCBHASH_CONNECT(table, faddr, fport, laddr, lport) \
150 	&(table)->inpt_connecthashtbl[ \
151 	    ((ntohl((faddr).s_addr) + ntohs(fport)) + \
152 	     (ntohl((laddr).s_addr) + ntohs(lport))) & (table)->inpt_connecthash]
153 
154 int	anonportmin = IPPORT_ANONMIN;
155 int	anonportmax = IPPORT_ANONMAX;
156 int	lowportmin  = IPPORT_RESERVEDMIN;
157 int	lowportmax  = IPPORT_RESERVEDMAX;
158 
159 static struct pool inpcb_pool;
160 
161 static int
162 inpcb_poolinit(void)
163 {
164 
165 	pool_init(&inpcb_pool, sizeof(struct inpcb), 0, 0, 0, "inpcbpl", NULL,
166 	    IPL_NET);
167 	return 0;
168 }
169 
170 void
171 in_pcbinit(struct inpcbtable *table, int bindhashsize, int connecthashsize)
172 {
173 	static ONCE_DECL(control);
174 
175 	TAILQ_INIT(&table->inpt_queue);
176 	table->inpt_porthashtbl = hashinit(bindhashsize, HASH_LIST, true,
177 	    &table->inpt_porthash);
178 	table->inpt_bindhashtbl = hashinit(bindhashsize, HASH_LIST, true,
179 	    &table->inpt_bindhash);
180 	table->inpt_connecthashtbl = hashinit(connecthashsize, HASH_LIST, true,
181 	    &table->inpt_connecthash);
182 	table->inpt_lastlow = IPPORT_RESERVEDMAX;
183 	table->inpt_lastport = (u_int16_t)anonportmax;
184 
185 	RUN_ONCE(&control, inpcb_poolinit);
186 }
187 
188 int
189 in_pcballoc(struct socket *so, void *v)
190 {
191 	struct inpcbtable *table = v;
192 	struct inpcb *inp;
193 	int s;
194 
195 	KASSERT(so->so_proto->pr_domain->dom_family == AF_INET);
196 
197 	inp = pool_get(&inpcb_pool, PR_NOWAIT);
198 	if (inp == NULL)
199 		return (ENOBUFS);
200 	memset(inp, 0, sizeof(*inp));
201 	inp->inp_af = AF_INET;
202 	inp->inp_table = table;
203 	inp->inp_socket = so;
204 	inp->inp_errormtu = -1;
205 	inp->inp_portalgo = PORTALGO_DEFAULT;
206 	inp->inp_bindportonsend = false;
207 	inp->inp_prefsrcip.s_addr = INADDR_ANY;
208 	inp->inp_overudp_cb = NULL;
209 	inp->inp_overudp_arg = NULL;
210 #if defined(IPSEC)
211 	if (ipsec_enabled) {
212 		int error = ipsec_init_pcbpolicy(so, &inp->inp_sp);
213 		if (error != 0) {
214 			pool_put(&inpcb_pool, inp);
215 			return error;
216 		}
217 		inp->inp_sp->sp_inph = (struct inpcb_hdr *)inp;
218 	}
219 #endif
220 	so->so_pcb = inp;
221 	s = splsoftnet();
222 	TAILQ_INSERT_HEAD(&table->inpt_queue, &inp->inp_head, inph_queue);
223 	LIST_INSERT_HEAD(INPCBHASH_PORT(table, inp->inp_lport), &inp->inp_head,
224 	    inph_lhash);
225 	in_pcbstate(inp, INP_ATTACHED);
226 	splx(s);
227 	return (0);
228 }
229 
230 static int
231 in_pcbsetport(struct sockaddr_in *sin, struct inpcb *inp, kauth_cred_t cred)
232 {
233 	struct inpcbtable *table = inp->inp_table;
234 	struct socket *so = inp->inp_socket;
235 	u_int16_t *lastport;
236 	u_int16_t lport = 0;
237 	enum kauth_network_req req;
238 	int error;
239 
240 	if (inp->inp_flags & INP_LOWPORT) {
241 #ifndef IPNOPRIVPORTS
242 		req = KAUTH_REQ_NETWORK_BIND_PRIVPORT;
243 #else
244 		req = KAUTH_REQ_NETWORK_BIND_PORT;
245 #endif
246 
247 		lastport = &table->inpt_lastlow;
248 	} else {
249 		req = KAUTH_REQ_NETWORK_BIND_PORT;
250 
251 		lastport = &table->inpt_lastport;
252 	}
253 
254 	/* XXX-kauth: KAUTH_REQ_NETWORK_BIND_AUTOASSIGN_{,PRIV}PORT */
255 	error = kauth_authorize_network(cred, KAUTH_NETWORK_BIND, req, so, sin,
256 	    NULL);
257 	if (error)
258 		return (EACCES);
259 
260        /*
261         * Use RFC6056 randomized port selection
262         */
263 	error = portalgo_randport(&lport, &inp->inp_head, cred);
264 	if (error)
265 		return error;
266 
267 	inp->inp_flags |= INP_ANONPORT;
268 	*lastport = lport;
269 	lport = htons(lport);
270 	inp->inp_lport = lport;
271 	in_pcbstate(inp, INP_BOUND);
272 
273 	return (0);
274 }
275 
276 int
277 in_pcbbindableaddr(struct sockaddr_in *sin, kauth_cred_t cred)
278 {
279 	int error = EADDRNOTAVAIL;
280 	struct ifaddr *ifa = NULL;
281 	int s;
282 
283 	if (sin->sin_family != AF_INET)
284 		return (EAFNOSUPPORT);
285 
286 	s = pserialize_read_enter();
287 	if (IN_MULTICAST(sin->sin_addr.s_addr)) {
288 		/* Always succeed; port reuse handled in in_pcbbind_port(). */
289 	} else if (!in_nullhost(sin->sin_addr)) {
290 		struct in_ifaddr *ia;
291 
292 		ia = in_get_ia(sin->sin_addr);
293 		/* check for broadcast addresses */
294 		if (ia == NULL) {
295 			ifa = ifa_ifwithaddr(sintosa(sin));
296 			if (ifa != NULL)
297 				ia = ifatoia(ifa);
298 		}
299 		if (ia == NULL)
300 			goto error;
301 		if (ia->ia4_flags & IN_IFF_DUPLICATED)
302 			goto error;
303 	}
304 	error = 0;
305  error:
306 	pserialize_read_exit(s);
307 	return error;
308 }
309 
310 static int
311 in_pcbbind_addr(struct inpcb *inp, struct sockaddr_in *sin, kauth_cred_t cred)
312 {
313 	int error;
314 
315 	error = in_pcbbindableaddr(sin, cred);
316 	if (error == 0)
317 		inp->inp_laddr = sin->sin_addr;
318 	return error;
319 }
320 
321 static int
322 in_pcbbind_port(struct inpcb *inp, struct sockaddr_in *sin, kauth_cred_t cred)
323 {
324 	struct inpcbtable *table = inp->inp_table;
325 	struct socket *so = inp->inp_socket;
326 	int reuseport = (so->so_options & SO_REUSEPORT);
327 	int wild = 0, error;
328 
329 	if (IN_MULTICAST(sin->sin_addr.s_addr)) {
330 		/*
331 		 * Treat SO_REUSEADDR as SO_REUSEPORT for multicast;
332 		 * allow complete duplication of binding if
333 		 * SO_REUSEPORT is set, or if SO_REUSEADDR is set
334 		 * and a multicast address is bound on both
335 		 * new and duplicated sockets.
336 		 */
337 		if (so->so_options & (SO_REUSEADDR | SO_REUSEPORT))
338 			reuseport = SO_REUSEADDR|SO_REUSEPORT;
339 	}
340 
341 	if (sin->sin_port == 0) {
342 		error = in_pcbsetport(sin, inp, cred);
343 		if (error)
344 			return (error);
345 	} else {
346 		struct inpcb *t;
347 		vestigial_inpcb_t vestige;
348 #ifdef INET6
349 		struct in6pcb *t6;
350 		struct in6_addr mapped;
351 #endif
352 		enum kauth_network_req req;
353 
354 		if ((so->so_options & (SO_REUSEADDR|SO_REUSEPORT)) == 0)
355 			wild = 1;
356 
357 #ifndef IPNOPRIVPORTS
358 		if (ntohs(sin->sin_port) < IPPORT_RESERVED)
359 			req = KAUTH_REQ_NETWORK_BIND_PRIVPORT;
360 		else
361 #endif /* !IPNOPRIVPORTS */
362 			req = KAUTH_REQ_NETWORK_BIND_PORT;
363 
364 		error = kauth_authorize_network(cred, KAUTH_NETWORK_BIND, req,
365 		    so, sin, NULL);
366 		if (error)
367 			return (EACCES);
368 
369 #ifdef INET6
370 		in6_in_2_v4mapin6(&sin->sin_addr, &mapped);
371 		t6 = in6_pcblookup_port(table, &mapped, sin->sin_port, wild, &vestige);
372 		if (t6 && (reuseport & t6->in6p_socket->so_options) == 0)
373 			return (EADDRINUSE);
374 		if (!t6 && vestige.valid) {
375 		    if (!!reuseport != !!vestige.reuse_port) {
376 			return EADDRINUSE;
377 		    }
378 		}
379 #endif
380 
381 		/* XXX-kauth */
382 		if (so->so_uidinfo->ui_uid && !IN_MULTICAST(sin->sin_addr.s_addr)) {
383 			t = in_pcblookup_port(table, sin->sin_addr, sin->sin_port, 1, &vestige);
384 			/*
385 			 * XXX:	investigate ramifications of loosening this
386 			 *	restriction so that as long as both ports have
387 			 *	SO_REUSEPORT allow the bind
388 			 */
389 			if (t &&
390 			    (!in_nullhost(sin->sin_addr) ||
391 			     !in_nullhost(t->inp_laddr) ||
392 			     (t->inp_socket->so_options & SO_REUSEPORT) == 0)
393 			    && (so->so_uidinfo->ui_uid != t->inp_socket->so_uidinfo->ui_uid)) {
394 				return (EADDRINUSE);
395 			}
396 			if (!t && vestige.valid) {
397 				if ((!in_nullhost(sin->sin_addr)
398 				     || !in_nullhost(vestige.laddr.v4)
399 				     || !vestige.reuse_port)
400 				    && so->so_uidinfo->ui_uid != vestige.uid) {
401 					return EADDRINUSE;
402 				}
403 			}
404 		}
405 		t = in_pcblookup_port(table, sin->sin_addr, sin->sin_port, wild, &vestige);
406 		if (t && (reuseport & t->inp_socket->so_options) == 0)
407 			return (EADDRINUSE);
408 		if (!t
409 		    && vestige.valid
410 		    && !(reuseport && vestige.reuse_port))
411 			return EADDRINUSE;
412 
413 		inp->inp_lport = sin->sin_port;
414 		in_pcbstate(inp, INP_BOUND);
415 	}
416 
417 	LIST_REMOVE(&inp->inp_head, inph_lhash);
418 	LIST_INSERT_HEAD(INPCBHASH_PORT(table, inp->inp_lport), &inp->inp_head,
419 	    inph_lhash);
420 
421 	return (0);
422 }
423 
424 int
425 in_pcbbind(void *v, struct sockaddr_in *sin, struct lwp *l)
426 {
427 	struct inpcb *inp = v;
428 	struct sockaddr_in lsin;
429 	int error;
430 
431 	if (inp->inp_af != AF_INET)
432 		return (EINVAL);
433 
434 	if (IN_ADDRLIST_READER_EMPTY())
435 		return (EADDRNOTAVAIL);
436 	if (inp->inp_lport || !in_nullhost(inp->inp_laddr))
437 		return (EINVAL);
438 
439 	if (NULL != sin) {
440 		if (sin->sin_len != sizeof(*sin))
441 			return (EINVAL);
442 	} else {
443 		lsin = *((const struct sockaddr_in *)
444 		    inp->inp_socket->so_proto->pr_domain->dom_sa_any);
445 		sin = &lsin;
446 	}
447 
448 	/* Bind address. */
449 	error = in_pcbbind_addr(inp, sin, l->l_cred);
450 	if (error)
451 		return (error);
452 
453 	/* Bind port. */
454 	error = in_pcbbind_port(inp, sin, l->l_cred);
455 	if (error) {
456 		inp->inp_laddr.s_addr = INADDR_ANY;
457 
458 		return (error);
459 	}
460 
461 	return (0);
462 }
463 
464 /*
465  * Connect from a socket to a specified address.
466  * Both address and port must be specified in argument sin.
467  * If don't have a local address for this socket yet,
468  * then pick one.
469  */
470 int
471 in_pcbconnect(void *v, struct sockaddr_in *sin, struct lwp *l)
472 {
473 	struct inpcb *inp = v;
474 	vestigial_inpcb_t vestige;
475 	int error;
476 	struct in_addr laddr;
477 
478 	if (inp->inp_af != AF_INET)
479 		return (EINVAL);
480 
481 	if (sin->sin_len != sizeof (*sin))
482 		return (EINVAL);
483 	if (sin->sin_family != AF_INET)
484 		return (EAFNOSUPPORT);
485 	if (sin->sin_port == 0)
486 		return (EADDRNOTAVAIL);
487 
488 	if (IN_MULTICAST(sin->sin_addr.s_addr) &&
489 	    inp->inp_socket->so_type == SOCK_STREAM)
490 		return EADDRNOTAVAIL;
491 
492 	if (!IN_ADDRLIST_READER_EMPTY()) {
493 		/*
494 		 * If the destination address is INADDR_ANY,
495 		 * use any local address (likely loopback).
496 		 * If the supplied address is INADDR_BROADCAST,
497 		 * use the broadcast address of an interface
498 		 * which supports broadcast. (loopback does not)
499 		 */
500 
501 		if (in_nullhost(sin->sin_addr)) {
502 			/* XXX racy */
503 			sin->sin_addr =
504 			    IN_ADDRLIST_READER_FIRST()->ia_addr.sin_addr;
505 		} else if (sin->sin_addr.s_addr == INADDR_BROADCAST) {
506 			struct in_ifaddr *ia;
507 			int s = pserialize_read_enter();
508 			IN_ADDRLIST_READER_FOREACH(ia) {
509 				if (ia->ia_ifp->if_flags & IFF_BROADCAST) {
510 					sin->sin_addr =
511 					    ia->ia_broadaddr.sin_addr;
512 					break;
513 				}
514 			}
515 			pserialize_read_exit(s);
516 		}
517 	}
518 	/*
519 	 * If we haven't bound which network number to use as ours,
520 	 * we will use the number of the outgoing interface.
521 	 * This depends on having done a routing lookup, which
522 	 * we will probably have to do anyway, so we might
523 	 * as well do it now.  On the other hand if we are
524 	 * sending to multiple destinations we may have already
525 	 * done the lookup, so see if we can use the route
526 	 * from before.  In any case, we only
527 	 * chose a port number once, even if sending to multiple
528 	 * destinations.
529 	 */
530 	if (in_nullhost(inp->inp_laddr)) {
531 		int xerror;
532 		struct in_ifaddr *ia, *_ia;
533 		int s;
534 		struct psref psref;
535 		int bound;
536 
537 		bound = curlwp_bind();
538 		ia = in_selectsrc(sin, &inp->inp_route,
539 		    inp->inp_socket->so_options, inp->inp_moptions, &xerror,
540 		    &psref);
541 		if (ia == NULL) {
542 			curlwp_bindx(bound);
543 			if (xerror == 0)
544 				xerror = EADDRNOTAVAIL;
545 			return xerror;
546 		}
547 		s = pserialize_read_enter();
548 		_ia = in_get_ia(IA_SIN(ia)->sin_addr);
549 		if (_ia == NULL) {
550 			pserialize_read_exit(s);
551 			ia4_release(ia, &psref);
552 			curlwp_bindx(bound);
553 			return (EADDRNOTAVAIL);
554 		}
555 		pserialize_read_exit(s);
556 		laddr = IA_SIN(ia)->sin_addr;
557 		ia4_release(ia, &psref);
558 		curlwp_bindx(bound);
559 	} else
560 		laddr = inp->inp_laddr;
561 	if (in_pcblookup_connect(inp->inp_table, sin->sin_addr, sin->sin_port,
562 	                         laddr, inp->inp_lport, &vestige) != NULL ||
563 	    vestige.valid) {
564 		return (EADDRINUSE);
565 	}
566 	if (in_nullhost(inp->inp_laddr)) {
567 		if (inp->inp_lport == 0) {
568 			error = in_pcbbind(inp, NULL, l);
569 			/*
570 			 * This used to ignore the return value
571 			 * completely, but we need to check for
572 			 * ephemeral port shortage.
573 			 * And attempts to request low ports if not root.
574 			 */
575 			if (error != 0)
576 				return (error);
577 		}
578 		inp->inp_laddr = laddr;
579 	}
580 	inp->inp_faddr = sin->sin_addr;
581 	inp->inp_fport = sin->sin_port;
582 
583         /* Late bind, if needed */
584 	if (inp->inp_bindportonsend) {
585                struct sockaddr_in lsin = *((const struct sockaddr_in *)
586 		    inp->inp_socket->so_proto->pr_domain->dom_sa_any);
587 		lsin.sin_addr = inp->inp_laddr;
588 		lsin.sin_port = 0;
589 
590                if ((error = in_pcbbind_port(inp, &lsin, l->l_cred)) != 0)
591                        return error;
592 	}
593 
594 	in_pcbstate(inp, INP_CONNECTED);
595 #if defined(IPSEC)
596 	if (ipsec_enabled && inp->inp_socket->so_type == SOCK_STREAM)
597 		ipsec_pcbconn(inp->inp_sp);
598 #endif
599 	return (0);
600 }
601 
602 void
603 in_pcbdisconnect(void *v)
604 {
605 	struct inpcb *inp = v;
606 
607 	if (inp->inp_af != AF_INET)
608 		return;
609 
610 	inp->inp_faddr = zeroin_addr;
611 	inp->inp_fport = 0;
612 	in_pcbstate(inp, INP_BOUND);
613 #if defined(IPSEC)
614 	if (ipsec_enabled)
615 		ipsec_pcbdisconn(inp->inp_sp);
616 #endif
617 	if (inp->inp_socket->so_state & SS_NOFDREF)
618 		in_pcbdetach(inp);
619 }
620 
621 void
622 in_pcbdetach(void *v)
623 {
624 	struct inpcb *inp = v;
625 	struct socket *so = inp->inp_socket;
626 	int s;
627 
628 	if (inp->inp_af != AF_INET)
629 		return;
630 
631 #if defined(IPSEC)
632 	if (ipsec_enabled)
633 		ipsec_delete_pcbpolicy(inp);
634 #endif
635 	so->so_pcb = NULL;
636 
637 	s = splsoftnet();
638 	in_pcbstate(inp, INP_ATTACHED);
639 	LIST_REMOVE(&inp->inp_head, inph_lhash);
640 	TAILQ_REMOVE(&inp->inp_table->inpt_queue, &inp->inp_head, inph_queue);
641 	splx(s);
642 
643 	if (inp->inp_options) {
644 		m_free(inp->inp_options);
645 	}
646 	rtcache_free(&inp->inp_route);
647 	ip_freemoptions(inp->inp_moptions);
648 	sofree(so);			/* drops the socket's lock */
649 
650 	pool_put(&inpcb_pool, inp);
651 	mutex_enter(softnet_lock);	/* reacquire the softnet_lock */
652 }
653 
654 void
655 in_setsockaddr(struct inpcb *inp, struct sockaddr_in *sin)
656 {
657 
658 	if (inp->inp_af != AF_INET)
659 		return;
660 
661 	sockaddr_in_init(sin, &inp->inp_laddr, inp->inp_lport);
662 }
663 
664 void
665 in_setpeeraddr(struct inpcb *inp, struct sockaddr_in *sin)
666 {
667 
668 	if (inp->inp_af != AF_INET)
669 		return;
670 
671 	sockaddr_in_init(sin, &inp->inp_faddr, inp->inp_fport);
672 }
673 
674 /*
675  * Pass some notification to all connections of a protocol
676  * associated with address dst.  The local address and/or port numbers
677  * may be specified to limit the search.  The "usual action" will be
678  * taken, depending on the ctlinput cmd.  The caller must filter any
679  * cmds that are uninteresting (e.g., no error in the map).
680  * Call the protocol specific routine (if any) to report
681  * any errors for each matching socket.
682  *
683  * Must be called at splsoftnet.
684  */
685 int
686 in_pcbnotify(struct inpcbtable *table, struct in_addr faddr, u_int fport_arg,
687     struct in_addr laddr, u_int lport_arg, int errno,
688     void (*notify)(struct inpcb *, int))
689 {
690 	struct inpcbhead *head;
691 	struct inpcb *inp, *ninp;
692 	u_int16_t fport = fport_arg, lport = lport_arg;
693 	int nmatch;
694 
695 	if (in_nullhost(faddr) || notify == 0)
696 		return (0);
697 
698 	nmatch = 0;
699 	head = INPCBHASH_CONNECT(table, faddr, fport, laddr, lport);
700 	for (inp = (struct inpcb *)LIST_FIRST(head); inp != NULL; inp = ninp) {
701 		ninp = (struct inpcb *)LIST_NEXT(inp, inp_hash);
702 		if (inp->inp_af != AF_INET)
703 			continue;
704 		if (in_hosteq(inp->inp_faddr, faddr) &&
705 		    inp->inp_fport == fport &&
706 		    inp->inp_lport == lport &&
707 		    in_hosteq(inp->inp_laddr, laddr)) {
708 			(*notify)(inp, errno);
709 			nmatch++;
710 		}
711 	}
712 	return (nmatch);
713 }
714 
715 void
716 in_pcbnotifyall(struct inpcbtable *table, struct in_addr faddr, int errno,
717     void (*notify)(struct inpcb *, int))
718 {
719 	struct inpcb_hdr *inph, *ninph;
720 
721 	if (in_nullhost(faddr) || notify == 0)
722 		return;
723 
724 	TAILQ_FOREACH_SAFE(inph, &table->inpt_queue, inph_queue, ninph) {
725 		struct inpcb *inp = (struct inpcb *)inph;
726 		if (inp->inp_af != AF_INET)
727 			continue;
728 		if (in_hosteq(inp->inp_faddr, faddr))
729 			(*notify)(inp, errno);
730 	}
731 }
732 
733 void
734 in_purgeifmcast(struct ip_moptions *imo, struct ifnet *ifp)
735 {
736 	int i, gap;
737 
738 	/* The owner of imo should be protected by solock */
739 	KASSERT(ifp != NULL);
740 
741 	if (imo == NULL)
742 		return;
743 
744 	/*
745 	 * Unselect the outgoing interface if it is being
746 	 * detached.
747 	 */
748 	if (imo->imo_multicast_if_index == ifp->if_index)
749 		imo->imo_multicast_if_index = 0;
750 
751 	/*
752 	 * Drop multicast group membership if we joined
753 	 * through the interface being detached.
754 	 */
755 	for (i = 0, gap = 0; i < imo->imo_num_memberships; i++) {
756 		if (imo->imo_membership[i]->inm_ifp == ifp) {
757 			in_delmulti(imo->imo_membership[i]);
758 			gap++;
759 		} else if (gap != 0)
760 			imo->imo_membership[i - gap] = imo->imo_membership[i];
761 	}
762 	imo->imo_num_memberships -= gap;
763 }
764 
765 void
766 in_pcbpurgeif0(struct inpcbtable *table, struct ifnet *ifp)
767 {
768 	struct inpcb_hdr *inph, *ninph;
769 
770 	TAILQ_FOREACH_SAFE(inph, &table->inpt_queue, inph_queue, ninph) {
771 		struct inpcb *inp = (struct inpcb *)inph;
772 		bool need_unlock = false;
773 
774 		if (inp->inp_af != AF_INET)
775 			continue;
776 
777 		/* The caller holds either one of inps' lock */
778 		if (!inp_locked(inp)) {
779 			inp_lock(inp);
780 			need_unlock = true;
781 		}
782 
783 		/* IFNET_LOCK must be taken after solock */
784 		in_purgeifmcast(inp->inp_moptions, ifp);
785 
786 		if (need_unlock)
787 			inp_unlock(inp);
788 	}
789 }
790 
791 void
792 in_pcbpurgeif(struct inpcbtable *table, struct ifnet *ifp)
793 {
794 	struct rtentry *rt;
795 	struct inpcb_hdr *inph, *ninph;
796 
797 	TAILQ_FOREACH_SAFE(inph, &table->inpt_queue, inph_queue, ninph) {
798 		struct inpcb *inp = (struct inpcb *)inph;
799 		if (inp->inp_af != AF_INET)
800 			continue;
801 		if ((rt = rtcache_validate(&inp->inp_route)) != NULL &&
802 		    rt->rt_ifp == ifp) {
803 			rtcache_unref(rt, &inp->inp_route);
804 			in_rtchange(inp, 0);
805 		} else
806 			rtcache_unref(rt, &inp->inp_route);
807 	}
808 }
809 
810 /*
811  * Check for alternatives when higher level complains
812  * about service problems.  For now, invalidate cached
813  * routing information.  If the route was created dynamically
814  * (by a redirect), time to try a default gateway again.
815  */
816 void
817 in_losing(struct inpcb *inp)
818 {
819 	struct rtentry *rt;
820 	struct rt_addrinfo info;
821 
822 	if (inp->inp_af != AF_INET)
823 		return;
824 
825 	if ((rt = rtcache_validate(&inp->inp_route)) == NULL)
826 		return;
827 
828 	memset(&info, 0, sizeof(info));
829 	info.rti_info[RTAX_DST] = rtcache_getdst(&inp->inp_route);
830 	info.rti_info[RTAX_GATEWAY] = rt->rt_gateway;
831 	info.rti_info[RTAX_NETMASK] = rt_mask(rt);
832 	rt_missmsg(RTM_LOSING, &info, rt->rt_flags, 0);
833 	if (rt->rt_flags & RTF_DYNAMIC) {
834 		int error;
835 		struct rtentry *nrt;
836 
837 		error = rtrequest(RTM_DELETE, rt_getkey(rt),
838 		    rt->rt_gateway, rt_mask(rt), rt->rt_flags, &nrt);
839 		rtcache_unref(rt, &inp->inp_route);
840 		if (error == 0)
841 			rt_free(nrt);
842 	} else
843 		rtcache_unref(rt, &inp->inp_route);
844 	/*
845 	 * A new route can be allocated
846 	 * the next time output is attempted.
847 	 */
848 	rtcache_free(&inp->inp_route);
849 }
850 
851 /*
852  * After a routing change, flush old routing.  A new route can be
853  * allocated the next time output is attempted.
854  */
855 void
856 in_rtchange(struct inpcb *inp, int errno)
857 {
858 
859 	if (inp->inp_af != AF_INET)
860 		return;
861 
862 	rtcache_free(&inp->inp_route);
863 
864 	/* XXX SHOULD NOTIFY HIGHER-LEVEL PROTOCOLS */
865 }
866 
867 struct inpcb *
868 in_pcblookup_port(struct inpcbtable *table, struct in_addr laddr,
869 		  u_int lport_arg, int lookup_wildcard, vestigial_inpcb_t *vp)
870 {
871 	struct inpcbhead *head;
872 	struct inpcb_hdr *inph;
873 	struct inpcb *match = NULL;
874 	int matchwild = 3;
875 	int wildcard;
876 	u_int16_t lport = lport_arg;
877 
878 	if (vp)
879 		vp->valid = 0;
880 
881 	head = INPCBHASH_PORT(table, lport);
882 	LIST_FOREACH(inph, head, inph_lhash) {
883 		struct inpcb * const inp = (struct inpcb *)inph;
884 
885 		if (inp->inp_af != AF_INET)
886 			continue;
887 		if (inp->inp_lport != lport)
888 			continue;
889 		/*
890 		 * check if inp's faddr and laddr match with ours.
891 		 * our faddr is considered null.
892 		 * count the number of wildcard matches. (0 - 2)
893 		 *
894 		 *	null	null	match
895 		 *	A	null	wildcard match
896 		 *	null	B	wildcard match
897 		 *	A	B	non match
898 		 *	A	A	match
899 		 */
900 		wildcard = 0;
901 		if (!in_nullhost(inp->inp_faddr))
902 			wildcard++;
903 		if (in_nullhost(inp->inp_laddr)) {
904 			if (!in_nullhost(laddr))
905 				wildcard++;
906 		} else {
907 			if (in_nullhost(laddr))
908 				wildcard++;
909 			else {
910 				if (!in_hosteq(inp->inp_laddr, laddr))
911 					continue;
912 			}
913 		}
914 		if (wildcard && !lookup_wildcard)
915 			continue;
916 		/*
917 		 * prefer an address with less wildcards.
918 		 */
919 		if (wildcard < matchwild) {
920 			match = inp;
921 			matchwild = wildcard;
922 			if (matchwild == 0)
923 				break;
924 		}
925 	}
926 	if (match && matchwild == 0)
927 		return match;
928 
929 	if (vp && table->vestige) {
930 		void	*state = (*table->vestige->init_ports4)(laddr, lport_arg, lookup_wildcard);
931 		vestigial_inpcb_t better;
932 
933 		while (table->vestige
934 		       && (*table->vestige->next_port4)(state, vp)) {
935 
936 			if (vp->lport != lport)
937 				continue;
938 			wildcard = 0;
939 			if (!in_nullhost(vp->faddr.v4))
940 				wildcard++;
941 			if (in_nullhost(vp->laddr.v4)) {
942 				if (!in_nullhost(laddr))
943 					wildcard++;
944 			} else {
945 				if (in_nullhost(laddr))
946 					wildcard++;
947 				else {
948 					if (!in_hosteq(vp->laddr.v4, laddr))
949 						continue;
950 				}
951 			}
952 			if (wildcard && !lookup_wildcard)
953 				continue;
954 			if (wildcard < matchwild) {
955 				better = *vp;
956 				match  = (void*)&better;
957 
958 				matchwild = wildcard;
959 				if (matchwild == 0)
960 					break;
961 			}
962 		}
963 
964 		if (match) {
965 			if (match != (void*)&better)
966 				return match;
967 			else {
968 				*vp = better;
969 				return 0;
970 			}
971 		}
972 	}
973 
974 	return (match);
975 }
976 
977 #ifdef DIAGNOSTIC
978 int	in_pcbnotifymiss = 0;
979 #endif
980 
981 struct inpcb *
982 in_pcblookup_connect(struct inpcbtable *table,
983     struct in_addr faddr, u_int fport_arg,
984     struct in_addr laddr, u_int lport_arg,
985     vestigial_inpcb_t *vp)
986 {
987 	struct inpcbhead *head;
988 	struct inpcb_hdr *inph;
989 	struct inpcb *inp;
990 	u_int16_t fport = fport_arg, lport = lport_arg;
991 
992 	if (vp)
993 		vp->valid = 0;
994 
995 	head = INPCBHASH_CONNECT(table, faddr, fport, laddr, lport);
996 	LIST_FOREACH(inph, head, inph_hash) {
997 		inp = (struct inpcb *)inph;
998 		if (inp->inp_af != AF_INET)
999 			continue;
1000 
1001 		if (in_hosteq(inp->inp_faddr, faddr) &&
1002 		    inp->inp_fport == fport &&
1003 		    inp->inp_lport == lport &&
1004 		    in_hosteq(inp->inp_laddr, laddr))
1005 			goto out;
1006 	}
1007 	if (vp && table->vestige) {
1008 		if ((*table->vestige->lookup4)(faddr, fport_arg,
1009 					       laddr, lport_arg, vp))
1010 			return 0;
1011 	}
1012 
1013 #ifdef DIAGNOSTIC
1014 	if (in_pcbnotifymiss) {
1015 		printf("in_pcblookup_connect: faddr=%08x fport=%d laddr=%08x lport=%d\n",
1016 		    ntohl(faddr.s_addr), ntohs(fport),
1017 		    ntohl(laddr.s_addr), ntohs(lport));
1018 	}
1019 #endif
1020 	return (0);
1021 
1022 out:
1023 	/* Move this PCB to the head of hash chain. */
1024 	inph = &inp->inp_head;
1025 	if (inph != LIST_FIRST(head)) {
1026 		LIST_REMOVE(inph, inph_hash);
1027 		LIST_INSERT_HEAD(head, inph, inph_hash);
1028 	}
1029 	return (inp);
1030 }
1031 
1032 struct inpcb *
1033 in_pcblookup_bind(struct inpcbtable *table,
1034     struct in_addr laddr, u_int lport_arg)
1035 {
1036 	struct inpcbhead *head;
1037 	struct inpcb_hdr *inph;
1038 	struct inpcb *inp;
1039 	u_int16_t lport = lport_arg;
1040 
1041 	head = INPCBHASH_BIND(table, laddr, lport);
1042 	LIST_FOREACH(inph, head, inph_hash) {
1043 		inp = (struct inpcb *)inph;
1044 		if (inp->inp_af != AF_INET)
1045 			continue;
1046 
1047 		if (inp->inp_lport == lport &&
1048 		    in_hosteq(inp->inp_laddr, laddr))
1049 			goto out;
1050 	}
1051 	head = INPCBHASH_BIND(table, zeroin_addr, lport);
1052 	LIST_FOREACH(inph, head, inph_hash) {
1053 		inp = (struct inpcb *)inph;
1054 		if (inp->inp_af != AF_INET)
1055 			continue;
1056 
1057 		if (inp->inp_lport == lport &&
1058 		    in_hosteq(inp->inp_laddr, zeroin_addr))
1059 			goto out;
1060 	}
1061 #ifdef DIAGNOSTIC
1062 	if (in_pcbnotifymiss) {
1063 		printf("in_pcblookup_bind: laddr=%08x lport=%d\n",
1064 		    ntohl(laddr.s_addr), ntohs(lport));
1065 	}
1066 #endif
1067 	return (0);
1068 
1069 out:
1070 	/* Move this PCB to the head of hash chain. */
1071 	inph = &inp->inp_head;
1072 	if (inph != LIST_FIRST(head)) {
1073 		LIST_REMOVE(inph, inph_hash);
1074 		LIST_INSERT_HEAD(head, inph, inph_hash);
1075 	}
1076 	return (inp);
1077 }
1078 
1079 void
1080 in_pcbstate(struct inpcb *inp, int state)
1081 {
1082 
1083 	if (inp->inp_af != AF_INET)
1084 		return;
1085 
1086 	if (inp->inp_state > INP_ATTACHED)
1087 		LIST_REMOVE(&inp->inp_head, inph_hash);
1088 
1089 	switch (state) {
1090 	case INP_BOUND:
1091 		LIST_INSERT_HEAD(INPCBHASH_BIND(inp->inp_table,
1092 		    inp->inp_laddr, inp->inp_lport), &inp->inp_head,
1093 		    inph_hash);
1094 		break;
1095 	case INP_CONNECTED:
1096 		LIST_INSERT_HEAD(INPCBHASH_CONNECT(inp->inp_table,
1097 		    inp->inp_faddr, inp->inp_fport,
1098 		    inp->inp_laddr, inp->inp_lport), &inp->inp_head,
1099 		    inph_hash);
1100 		break;
1101 	}
1102 
1103 	inp->inp_state = state;
1104 }
1105 
1106 struct rtentry *
1107 in_pcbrtentry(struct inpcb *inp)
1108 {
1109 	struct route *ro;
1110 	union {
1111 		struct sockaddr		dst;
1112 		struct sockaddr_in	dst4;
1113 	} u;
1114 
1115 	if (inp->inp_af != AF_INET)
1116 		return (NULL);
1117 
1118 	ro = &inp->inp_route;
1119 
1120 	sockaddr_in_init(&u.dst4, &inp->inp_faddr, 0);
1121 	return rtcache_lookup(ro, &u.dst);
1122 }
1123 
1124 void
1125 in_pcbrtentry_unref(struct rtentry *rt, struct inpcb *inp)
1126 {
1127 
1128 	rtcache_unref(rt, &inp->inp_route);
1129 }
1130