xref: /netbsd-src/sys/netinet/in_pcb.c (revision 53b02e147d4ed531c0d2a5ca9b3e8026ba3e99b5)
1 /*	$NetBSD: in_pcb.c,v 1.186 2021/10/19 20:01:09 roy 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.186 2021/10/19 20:01:09 roy 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(const struct inpcb *inp, struct sockaddr_in *sin,
278     kauth_cred_t cred)
279 {
280 	int error = EADDRNOTAVAIL;
281 	struct ifaddr *ifa = NULL;
282 	int s;
283 
284 	if (sin->sin_family != AF_INET)
285 		return (EAFNOSUPPORT);
286 
287 	s = pserialize_read_enter();
288 	if (IN_MULTICAST(sin->sin_addr.s_addr)) {
289 		/* Always succeed; port reuse handled in in_pcbbind_port(). */
290 	} else if (!in_nullhost(sin->sin_addr)) {
291 		struct in_ifaddr *ia;
292 
293 		ia = in_get_ia(sin->sin_addr);
294 		/* check for broadcast addresses */
295 		if (ia == NULL) {
296 			ifa = ifa_ifwithaddr(sintosa(sin));
297 			if (ifa != NULL)
298 				ia = ifatoia(ifa);
299 			else if ((inp->inp_flags & INP_BINDANY) != 0) {
300 				error = 0;
301 				goto error;
302 			}
303 		}
304 		if (ia == NULL)
305 			goto error;
306 		if (ia->ia4_flags & IN_IFF_DUPLICATED)
307 			goto error;
308 	}
309 	error = 0;
310  error:
311 	pserialize_read_exit(s);
312 	return error;
313 }
314 
315 static int
316 in_pcbbind_addr(struct inpcb *inp, struct sockaddr_in *sin, kauth_cred_t cred)
317 {
318 	int error;
319 
320 	error = in_pcbbindableaddr(inp, sin, cred);
321 	if (error == 0)
322 		inp->inp_laddr = sin->sin_addr;
323 	return error;
324 }
325 
326 static int
327 in_pcbbind_port(struct inpcb *inp, struct sockaddr_in *sin, kauth_cred_t cred)
328 {
329 	struct inpcbtable *table = inp->inp_table;
330 	struct socket *so = inp->inp_socket;
331 	int reuseport = (so->so_options & SO_REUSEPORT);
332 	int wild = 0, error;
333 
334 	if (IN_MULTICAST(sin->sin_addr.s_addr)) {
335 		/*
336 		 * Treat SO_REUSEADDR as SO_REUSEPORT for multicast;
337 		 * allow complete duplication of binding if
338 		 * SO_REUSEPORT is set, or if SO_REUSEADDR is set
339 		 * and a multicast address is bound on both
340 		 * new and duplicated sockets.
341 		 */
342 		if (so->so_options & (SO_REUSEADDR | SO_REUSEPORT))
343 			reuseport = SO_REUSEADDR|SO_REUSEPORT;
344 	}
345 
346 	if (sin->sin_port == 0) {
347 		error = in_pcbsetport(sin, inp, cred);
348 		if (error)
349 			return (error);
350 	} else {
351 		struct inpcb *t;
352 		vestigial_inpcb_t vestige;
353 #ifdef INET6
354 		struct in6pcb *t6;
355 		struct in6_addr mapped;
356 #endif
357 		enum kauth_network_req req;
358 
359 		if ((so->so_options & (SO_REUSEADDR|SO_REUSEPORT)) == 0)
360 			wild = 1;
361 
362 #ifndef IPNOPRIVPORTS
363 		if (ntohs(sin->sin_port) < IPPORT_RESERVED)
364 			req = KAUTH_REQ_NETWORK_BIND_PRIVPORT;
365 		else
366 #endif /* !IPNOPRIVPORTS */
367 			req = KAUTH_REQ_NETWORK_BIND_PORT;
368 
369 		error = kauth_authorize_network(cred, KAUTH_NETWORK_BIND, req,
370 		    so, sin, NULL);
371 		if (error)
372 			return (EACCES);
373 
374 #ifdef INET6
375 		in6_in_2_v4mapin6(&sin->sin_addr, &mapped);
376 		t6 = in6_pcblookup_port(table, &mapped, sin->sin_port, wild, &vestige);
377 		if (t6 && (reuseport & t6->in6p_socket->so_options) == 0)
378 			return (EADDRINUSE);
379 		if (!t6 && vestige.valid) {
380 		    if (!!reuseport != !!vestige.reuse_port) {
381 			return EADDRINUSE;
382 		    }
383 		}
384 #endif
385 
386 		/* XXX-kauth */
387 		if (so->so_uidinfo->ui_uid && !IN_MULTICAST(sin->sin_addr.s_addr)) {
388 			t = in_pcblookup_port(table, sin->sin_addr, sin->sin_port, 1, &vestige);
389 			/*
390 			 * XXX:	investigate ramifications of loosening this
391 			 *	restriction so that as long as both ports have
392 			 *	SO_REUSEPORT allow the bind
393 			 */
394 			if (t &&
395 			    (!in_nullhost(sin->sin_addr) ||
396 			     !in_nullhost(t->inp_laddr) ||
397 			     (t->inp_socket->so_options & SO_REUSEPORT) == 0)
398 			    && (so->so_uidinfo->ui_uid != t->inp_socket->so_uidinfo->ui_uid)) {
399 				return (EADDRINUSE);
400 			}
401 			if (!t && vestige.valid) {
402 				if ((!in_nullhost(sin->sin_addr)
403 				     || !in_nullhost(vestige.laddr.v4)
404 				     || !vestige.reuse_port)
405 				    && so->so_uidinfo->ui_uid != vestige.uid) {
406 					return EADDRINUSE;
407 				}
408 			}
409 		}
410 		t = in_pcblookup_port(table, sin->sin_addr, sin->sin_port, wild, &vestige);
411 		if (t && (reuseport & t->inp_socket->so_options) == 0)
412 			return (EADDRINUSE);
413 		if (!t
414 		    && vestige.valid
415 		    && !(reuseport && vestige.reuse_port))
416 			return EADDRINUSE;
417 
418 		inp->inp_lport = sin->sin_port;
419 		in_pcbstate(inp, INP_BOUND);
420 	}
421 
422 	LIST_REMOVE(&inp->inp_head, inph_lhash);
423 	LIST_INSERT_HEAD(INPCBHASH_PORT(table, inp->inp_lport), &inp->inp_head,
424 	    inph_lhash);
425 
426 	return (0);
427 }
428 
429 int
430 in_pcbbind(void *v, struct sockaddr_in *sin, struct lwp *l)
431 {
432 	struct inpcb *inp = v;
433 	struct sockaddr_in lsin;
434 	int error;
435 
436 	if (inp->inp_af != AF_INET)
437 		return (EINVAL);
438 
439 	if (inp->inp_lport || !in_nullhost(inp->inp_laddr))
440 		return (EINVAL);
441 
442 	if (NULL != sin) {
443 		if (sin->sin_len != sizeof(*sin))
444 			return (EINVAL);
445 	} else {
446 		lsin = *((const struct sockaddr_in *)
447 		    inp->inp_socket->so_proto->pr_domain->dom_sa_any);
448 		sin = &lsin;
449 	}
450 
451 	/* Bind address. */
452 	error = in_pcbbind_addr(inp, sin, l->l_cred);
453 	if (error)
454 		return (error);
455 
456 	/* Bind port. */
457 	error = in_pcbbind_port(inp, sin, l->l_cred);
458 	if (error) {
459 		inp->inp_laddr.s_addr = INADDR_ANY;
460 
461 		return (error);
462 	}
463 
464 	return (0);
465 }
466 
467 /*
468  * Connect from a socket to a specified address.
469  * Both address and port must be specified in argument sin.
470  * If don't have a local address for this socket yet,
471  * then pick one.
472  */
473 int
474 in_pcbconnect(void *v, struct sockaddr_in *sin, struct lwp *l)
475 {
476 	struct inpcb *inp = v;
477 	vestigial_inpcb_t vestige;
478 	int error;
479 	struct in_addr laddr;
480 
481 	if (inp->inp_af != AF_INET)
482 		return (EINVAL);
483 
484 	if (sin->sin_len != sizeof (*sin))
485 		return (EINVAL);
486 	if (sin->sin_family != AF_INET)
487 		return (EAFNOSUPPORT);
488 	if (sin->sin_port == 0)
489 		return (EADDRNOTAVAIL);
490 
491 	if (IN_MULTICAST(sin->sin_addr.s_addr) &&
492 	    inp->inp_socket->so_type == SOCK_STREAM)
493 		return EADDRNOTAVAIL;
494 
495 	if (!IN_ADDRLIST_READER_EMPTY()) {
496 		/*
497 		 * If the destination address is INADDR_ANY,
498 		 * use any local address (likely loopback).
499 		 * If the supplied address is INADDR_BROADCAST,
500 		 * use the broadcast address of an interface
501 		 * which supports broadcast. (loopback does not)
502 		 */
503 
504 		if (in_nullhost(sin->sin_addr)) {
505 			/* XXX racy */
506 			sin->sin_addr =
507 			    IN_ADDRLIST_READER_FIRST()->ia_addr.sin_addr;
508 		} else if (sin->sin_addr.s_addr == INADDR_BROADCAST) {
509 			struct in_ifaddr *ia;
510 			int s = pserialize_read_enter();
511 			IN_ADDRLIST_READER_FOREACH(ia) {
512 				if (ia->ia_ifp->if_flags & IFF_BROADCAST) {
513 					sin->sin_addr =
514 					    ia->ia_broadaddr.sin_addr;
515 					break;
516 				}
517 			}
518 			pserialize_read_exit(s);
519 		}
520 	}
521 	/*
522 	 * If we haven't bound which network number to use as ours,
523 	 * we will use the number of the outgoing interface.
524 	 * This depends on having done a routing lookup, which
525 	 * we will probably have to do anyway, so we might
526 	 * as well do it now.  On the other hand if we are
527 	 * sending to multiple destinations we may have already
528 	 * done the lookup, so see if we can use the route
529 	 * from before.  In any case, we only
530 	 * chose a port number once, even if sending to multiple
531 	 * destinations.
532 	 */
533 	if (in_nullhost(inp->inp_laddr)) {
534 		int xerror;
535 		struct in_ifaddr *ia, *_ia;
536 		int s;
537 		struct psref psref;
538 		int bound;
539 
540 		bound = curlwp_bind();
541 		ia = in_selectsrc(sin, &inp->inp_route,
542 		    inp->inp_socket->so_options, inp->inp_moptions, &xerror,
543 		    &psref);
544 		if (ia == NULL) {
545 			curlwp_bindx(bound);
546 			if (xerror == 0)
547 				xerror = EADDRNOTAVAIL;
548 			return xerror;
549 		}
550 		s = pserialize_read_enter();
551 		_ia = in_get_ia(IA_SIN(ia)->sin_addr);
552 		if (_ia == NULL && (inp->inp_flags & INP_BINDANY) == 0) {
553 			pserialize_read_exit(s);
554 			ia4_release(ia, &psref);
555 			curlwp_bindx(bound);
556 			return (EADDRNOTAVAIL);
557 		}
558 		pserialize_read_exit(s);
559 		laddr = IA_SIN(ia)->sin_addr;
560 		ia4_release(ia, &psref);
561 		curlwp_bindx(bound);
562 	} else
563 		laddr = inp->inp_laddr;
564 	if (in_pcblookup_connect(inp->inp_table, sin->sin_addr, sin->sin_port,
565 	                         laddr, inp->inp_lport, &vestige) != NULL ||
566 	    vestige.valid) {
567 		return (EADDRINUSE);
568 	}
569 	if (in_nullhost(inp->inp_laddr)) {
570 		if (inp->inp_lport == 0) {
571 			error = in_pcbbind(inp, NULL, l);
572 			/*
573 			 * This used to ignore the return value
574 			 * completely, but we need to check for
575 			 * ephemeral port shortage.
576 			 * And attempts to request low ports if not root.
577 			 */
578 			if (error != 0)
579 				return (error);
580 		}
581 		inp->inp_laddr = laddr;
582 	}
583 	inp->inp_faddr = sin->sin_addr;
584 	inp->inp_fport = sin->sin_port;
585 
586         /* Late bind, if needed */
587 	if (inp->inp_bindportonsend) {
588                struct sockaddr_in lsin = *((const struct sockaddr_in *)
589 		    inp->inp_socket->so_proto->pr_domain->dom_sa_any);
590 		lsin.sin_addr = inp->inp_laddr;
591 		lsin.sin_port = 0;
592 
593 		if ((error = in_pcbbind_port(inp, &lsin, l->l_cred)) != 0)
594                        return error;
595 	}
596 
597 	in_pcbstate(inp, INP_CONNECTED);
598 #if defined(IPSEC)
599 	if (ipsec_enabled && inp->inp_socket->so_type == SOCK_STREAM)
600 		ipsec_pcbconn(inp->inp_sp);
601 #endif
602 	return (0);
603 }
604 
605 void
606 in_pcbdisconnect(void *v)
607 {
608 	struct inpcb *inp = v;
609 
610 	if (inp->inp_af != AF_INET)
611 		return;
612 
613 	inp->inp_faddr = zeroin_addr;
614 	inp->inp_fport = 0;
615 	in_pcbstate(inp, INP_BOUND);
616 #if defined(IPSEC)
617 	if (ipsec_enabled)
618 		ipsec_pcbdisconn(inp->inp_sp);
619 #endif
620 	if (inp->inp_socket->so_state & SS_NOFDREF)
621 		in_pcbdetach(inp);
622 }
623 
624 void
625 in_pcbdetach(void *v)
626 {
627 	struct inpcb *inp = v;
628 	struct socket *so = inp->inp_socket;
629 	int s;
630 
631 	if (inp->inp_af != AF_INET)
632 		return;
633 
634 #if defined(IPSEC)
635 	if (ipsec_enabled)
636 		ipsec_delete_pcbpolicy(inp);
637 #endif
638 	so->so_pcb = NULL;
639 
640 	s = splsoftnet();
641 	in_pcbstate(inp, INP_ATTACHED);
642 	LIST_REMOVE(&inp->inp_head, inph_lhash);
643 	TAILQ_REMOVE(&inp->inp_table->inpt_queue, &inp->inp_head, inph_queue);
644 	splx(s);
645 
646 	if (inp->inp_options) {
647 		m_free(inp->inp_options);
648 	}
649 	rtcache_free(&inp->inp_route);
650 	ip_freemoptions(inp->inp_moptions);
651 	sofree(so);			/* drops the socket's lock */
652 
653 	pool_put(&inpcb_pool, inp);
654 	mutex_enter(softnet_lock);	/* reacquire the softnet_lock */
655 }
656 
657 void
658 in_setsockaddr(struct inpcb *inp, struct sockaddr_in *sin)
659 {
660 
661 	if (inp->inp_af != AF_INET)
662 		return;
663 
664 	sockaddr_in_init(sin, &inp->inp_laddr, inp->inp_lport);
665 }
666 
667 void
668 in_setpeeraddr(struct inpcb *inp, struct sockaddr_in *sin)
669 {
670 
671 	if (inp->inp_af != AF_INET)
672 		return;
673 
674 	sockaddr_in_init(sin, &inp->inp_faddr, inp->inp_fport);
675 }
676 
677 /*
678  * Pass some notification to all connections of a protocol
679  * associated with address dst.  The local address and/or port numbers
680  * may be specified to limit the search.  The "usual action" will be
681  * taken, depending on the ctlinput cmd.  The caller must filter any
682  * cmds that are uninteresting (e.g., no error in the map).
683  * Call the protocol specific routine (if any) to report
684  * any errors for each matching socket.
685  *
686  * Must be called at splsoftnet.
687  */
688 int
689 in_pcbnotify(struct inpcbtable *table, struct in_addr faddr, u_int fport_arg,
690     struct in_addr laddr, u_int lport_arg, int errno,
691     void (*notify)(struct inpcb *, int))
692 {
693 	struct inpcbhead *head;
694 	struct inpcb *inp, *ninp;
695 	u_int16_t fport = fport_arg, lport = lport_arg;
696 	int nmatch;
697 
698 	if (in_nullhost(faddr) || notify == 0)
699 		return (0);
700 
701 	nmatch = 0;
702 	head = INPCBHASH_CONNECT(table, faddr, fport, laddr, lport);
703 	for (inp = (struct inpcb *)LIST_FIRST(head); inp != NULL; inp = ninp) {
704 		ninp = (struct inpcb *)LIST_NEXT(inp, inp_hash);
705 		if (inp->inp_af != AF_INET)
706 			continue;
707 		if (in_hosteq(inp->inp_faddr, faddr) &&
708 		    inp->inp_fport == fport &&
709 		    inp->inp_lport == lport &&
710 		    in_hosteq(inp->inp_laddr, laddr)) {
711 			(*notify)(inp, errno);
712 			nmatch++;
713 		}
714 	}
715 	return (nmatch);
716 }
717 
718 void
719 in_pcbnotifyall(struct inpcbtable *table, struct in_addr faddr, int errno,
720     void (*notify)(struct inpcb *, int))
721 {
722 	struct inpcb_hdr *inph, *ninph;
723 
724 	if (in_nullhost(faddr) || notify == 0)
725 		return;
726 
727 	TAILQ_FOREACH_SAFE(inph, &table->inpt_queue, inph_queue, ninph) {
728 		struct inpcb *inp = (struct inpcb *)inph;
729 		if (inp->inp_af != AF_INET)
730 			continue;
731 		if (in_hosteq(inp->inp_faddr, faddr))
732 			(*notify)(inp, errno);
733 	}
734 }
735 
736 void
737 in_purgeifmcast(struct ip_moptions *imo, struct ifnet *ifp)
738 {
739 	int i, gap;
740 
741 	/* The owner of imo should be protected by solock */
742 	KASSERT(ifp != NULL);
743 
744 	if (imo == NULL)
745 		return;
746 
747 	/*
748 	 * Unselect the outgoing interface if it is being
749 	 * detached.
750 	 */
751 	if (imo->imo_multicast_if_index == ifp->if_index)
752 		imo->imo_multicast_if_index = 0;
753 
754 	/*
755 	 * Drop multicast group membership if we joined
756 	 * through the interface being detached.
757 	 */
758 	for (i = 0, gap = 0; i < imo->imo_num_memberships; i++) {
759 		if (imo->imo_membership[i]->inm_ifp == ifp) {
760 			in_delmulti(imo->imo_membership[i]);
761 			gap++;
762 		} else if (gap != 0)
763 			imo->imo_membership[i - gap] = imo->imo_membership[i];
764 	}
765 	imo->imo_num_memberships -= gap;
766 }
767 
768 void
769 in_pcbpurgeif0(struct inpcbtable *table, struct ifnet *ifp)
770 {
771 	struct inpcb_hdr *inph, *ninph;
772 
773 	TAILQ_FOREACH_SAFE(inph, &table->inpt_queue, inph_queue, ninph) {
774 		struct inpcb *inp = (struct inpcb *)inph;
775 		bool need_unlock = false;
776 
777 		if (inp->inp_af != AF_INET)
778 			continue;
779 
780 		/* The caller holds either one of inps' lock */
781 		if (!inp_locked(inp)) {
782 			inp_lock(inp);
783 			need_unlock = true;
784 		}
785 
786 		/* IFNET_LOCK must be taken after solock */
787 		in_purgeifmcast(inp->inp_moptions, ifp);
788 
789 		if (need_unlock)
790 			inp_unlock(inp);
791 	}
792 }
793 
794 void
795 in_pcbpurgeif(struct inpcbtable *table, struct ifnet *ifp)
796 {
797 	struct rtentry *rt;
798 	struct inpcb_hdr *inph, *ninph;
799 
800 	TAILQ_FOREACH_SAFE(inph, &table->inpt_queue, inph_queue, ninph) {
801 		struct inpcb *inp = (struct inpcb *)inph;
802 		if (inp->inp_af != AF_INET)
803 			continue;
804 		if ((rt = rtcache_validate(&inp->inp_route)) != NULL &&
805 		    rt->rt_ifp == ifp) {
806 			rtcache_unref(rt, &inp->inp_route);
807 			in_rtchange(inp, 0);
808 		} else
809 			rtcache_unref(rt, &inp->inp_route);
810 	}
811 }
812 
813 /*
814  * Check for alternatives when higher level complains
815  * about service problems.  For now, invalidate cached
816  * routing information.  If the route was created dynamically
817  * (by a redirect), time to try a default gateway again.
818  */
819 void
820 in_losing(struct inpcb *inp)
821 {
822 	struct rtentry *rt;
823 	struct rt_addrinfo info;
824 
825 	if (inp->inp_af != AF_INET)
826 		return;
827 
828 	if ((rt = rtcache_validate(&inp->inp_route)) == NULL)
829 		return;
830 
831 	memset(&info, 0, sizeof(info));
832 	info.rti_info[RTAX_DST] = rtcache_getdst(&inp->inp_route);
833 	info.rti_info[RTAX_GATEWAY] = rt->rt_gateway;
834 	info.rti_info[RTAX_NETMASK] = rt_mask(rt);
835 	rt_missmsg(RTM_LOSING, &info, rt->rt_flags, 0);
836 	if (rt->rt_flags & RTF_DYNAMIC) {
837 		int error;
838 		struct rtentry *nrt;
839 
840 		error = rtrequest(RTM_DELETE, rt_getkey(rt),
841 		    rt->rt_gateway, rt_mask(rt), rt->rt_flags, &nrt);
842 		rtcache_unref(rt, &inp->inp_route);
843 		if (error == 0)
844 			rt_free(nrt);
845 	} else
846 		rtcache_unref(rt, &inp->inp_route);
847 	/*
848 	 * A new route can be allocated
849 	 * the next time output is attempted.
850 	 */
851 	rtcache_free(&inp->inp_route);
852 }
853 
854 /*
855  * After a routing change, flush old routing.  A new route can be
856  * allocated the next time output is attempted.
857  */
858 void
859 in_rtchange(struct inpcb *inp, int errno)
860 {
861 
862 	if (inp->inp_af != AF_INET)
863 		return;
864 
865 	rtcache_free(&inp->inp_route);
866 
867 	/* XXX SHOULD NOTIFY HIGHER-LEVEL PROTOCOLS */
868 }
869 
870 struct inpcb *
871 in_pcblookup_port(struct inpcbtable *table, struct in_addr laddr,
872 		  u_int lport_arg, int lookup_wildcard, vestigial_inpcb_t *vp)
873 {
874 	struct inpcbhead *head;
875 	struct inpcb_hdr *inph;
876 	struct inpcb *match = NULL;
877 	int matchwild = 3;
878 	int wildcard;
879 	u_int16_t lport = lport_arg;
880 
881 	if (vp)
882 		vp->valid = 0;
883 
884 	head = INPCBHASH_PORT(table, lport);
885 	LIST_FOREACH(inph, head, inph_lhash) {
886 		struct inpcb * const inp = (struct inpcb *)inph;
887 
888 		if (inp->inp_af != AF_INET)
889 			continue;
890 		if (inp->inp_lport != lport)
891 			continue;
892 		/*
893 		 * check if inp's faddr and laddr match with ours.
894 		 * our faddr is considered null.
895 		 * count the number of wildcard matches. (0 - 2)
896 		 *
897 		 *	null	null	match
898 		 *	A	null	wildcard match
899 		 *	null	B	wildcard match
900 		 *	A	B	non match
901 		 *	A	A	match
902 		 */
903 		wildcard = 0;
904 		if (!in_nullhost(inp->inp_faddr))
905 			wildcard++;
906 		if (in_nullhost(inp->inp_laddr)) {
907 			if (!in_nullhost(laddr))
908 				wildcard++;
909 		} else {
910 			if (in_nullhost(laddr))
911 				wildcard++;
912 			else {
913 				if (!in_hosteq(inp->inp_laddr, laddr))
914 					continue;
915 			}
916 		}
917 		if (wildcard && !lookup_wildcard)
918 			continue;
919 		/*
920 		 * prefer an address with less wildcards.
921 		 */
922 		if (wildcard < matchwild) {
923 			match = inp;
924 			matchwild = wildcard;
925 			if (matchwild == 0)
926 				break;
927 		}
928 	}
929 	if (match && matchwild == 0)
930 		return match;
931 
932 	if (vp && table->vestige) {
933 		void	*state = (*table->vestige->init_ports4)(laddr, lport_arg, lookup_wildcard);
934 		vestigial_inpcb_t better;
935 
936 		while (table->vestige
937 		       && (*table->vestige->next_port4)(state, vp)) {
938 
939 			if (vp->lport != lport)
940 				continue;
941 			wildcard = 0;
942 			if (!in_nullhost(vp->faddr.v4))
943 				wildcard++;
944 			if (in_nullhost(vp->laddr.v4)) {
945 				if (!in_nullhost(laddr))
946 					wildcard++;
947 			} else {
948 				if (in_nullhost(laddr))
949 					wildcard++;
950 				else {
951 					if (!in_hosteq(vp->laddr.v4, laddr))
952 						continue;
953 				}
954 			}
955 			if (wildcard && !lookup_wildcard)
956 				continue;
957 			if (wildcard < matchwild) {
958 				better = *vp;
959 				match  = (void*)&better;
960 
961 				matchwild = wildcard;
962 				if (matchwild == 0)
963 					break;
964 			}
965 		}
966 
967 		if (match) {
968 			if (match != (void*)&better)
969 				return match;
970 			else {
971 				*vp = better;
972 				return 0;
973 			}
974 		}
975 	}
976 
977 	return (match);
978 }
979 
980 #ifdef DIAGNOSTIC
981 int	in_pcbnotifymiss = 0;
982 #endif
983 
984 struct inpcb *
985 in_pcblookup_connect(struct inpcbtable *table,
986     struct in_addr faddr, u_int fport_arg,
987     struct in_addr laddr, u_int lport_arg,
988     vestigial_inpcb_t *vp)
989 {
990 	struct inpcbhead *head;
991 	struct inpcb_hdr *inph;
992 	struct inpcb *inp;
993 	u_int16_t fport = fport_arg, lport = lport_arg;
994 
995 	if (vp)
996 		vp->valid = 0;
997 
998 	head = INPCBHASH_CONNECT(table, faddr, fport, laddr, lport);
999 	LIST_FOREACH(inph, head, inph_hash) {
1000 		inp = (struct inpcb *)inph;
1001 		if (inp->inp_af != AF_INET)
1002 			continue;
1003 
1004 		if (in_hosteq(inp->inp_faddr, faddr) &&
1005 		    inp->inp_fport == fport &&
1006 		    inp->inp_lport == lport &&
1007 		    in_hosteq(inp->inp_laddr, laddr))
1008 			goto out;
1009 	}
1010 	if (vp && table->vestige) {
1011 		if ((*table->vestige->lookup4)(faddr, fport_arg,
1012 					       laddr, lport_arg, vp))
1013 			return 0;
1014 	}
1015 
1016 #ifdef DIAGNOSTIC
1017 	if (in_pcbnotifymiss) {
1018 		printf("in_pcblookup_connect: faddr=%08x fport=%d laddr=%08x lport=%d\n",
1019 		    ntohl(faddr.s_addr), ntohs(fport),
1020 		    ntohl(laddr.s_addr), ntohs(lport));
1021 	}
1022 #endif
1023 	return (0);
1024 
1025 out:
1026 	/* Move this PCB to the head of hash chain. */
1027 	inph = &inp->inp_head;
1028 	if (inph != LIST_FIRST(head)) {
1029 		LIST_REMOVE(inph, inph_hash);
1030 		LIST_INSERT_HEAD(head, inph, inph_hash);
1031 	}
1032 	return (inp);
1033 }
1034 
1035 struct inpcb *
1036 in_pcblookup_bind(struct inpcbtable *table,
1037     struct in_addr laddr, u_int lport_arg)
1038 {
1039 	struct inpcbhead *head;
1040 	struct inpcb_hdr *inph;
1041 	struct inpcb *inp;
1042 	u_int16_t lport = lport_arg;
1043 
1044 	head = INPCBHASH_BIND(table, laddr, lport);
1045 	LIST_FOREACH(inph, head, inph_hash) {
1046 		inp = (struct inpcb *)inph;
1047 		if (inp->inp_af != AF_INET)
1048 			continue;
1049 
1050 		if (inp->inp_lport == lport &&
1051 		    in_hosteq(inp->inp_laddr, laddr))
1052 			goto out;
1053 	}
1054 	head = INPCBHASH_BIND(table, zeroin_addr, lport);
1055 	LIST_FOREACH(inph, head, inph_hash) {
1056 		inp = (struct inpcb *)inph;
1057 		if (inp->inp_af != AF_INET)
1058 			continue;
1059 
1060 		if (inp->inp_lport == lport &&
1061 		    in_hosteq(inp->inp_laddr, zeroin_addr))
1062 			goto out;
1063 	}
1064 #ifdef DIAGNOSTIC
1065 	if (in_pcbnotifymiss) {
1066 		printf("in_pcblookup_bind: laddr=%08x lport=%d\n",
1067 		    ntohl(laddr.s_addr), ntohs(lport));
1068 	}
1069 #endif
1070 	return (0);
1071 
1072 out:
1073 	/* Move this PCB to the head of hash chain. */
1074 	inph = &inp->inp_head;
1075 	if (inph != LIST_FIRST(head)) {
1076 		LIST_REMOVE(inph, inph_hash);
1077 		LIST_INSERT_HEAD(head, inph, inph_hash);
1078 	}
1079 	return (inp);
1080 }
1081 
1082 void
1083 in_pcbstate(struct inpcb *inp, int state)
1084 {
1085 
1086 	if (inp->inp_af != AF_INET)
1087 		return;
1088 
1089 	if (inp->inp_state > INP_ATTACHED)
1090 		LIST_REMOVE(&inp->inp_head, inph_hash);
1091 
1092 	switch (state) {
1093 	case INP_BOUND:
1094 		LIST_INSERT_HEAD(INPCBHASH_BIND(inp->inp_table,
1095 		    inp->inp_laddr, inp->inp_lport), &inp->inp_head,
1096 		    inph_hash);
1097 		break;
1098 	case INP_CONNECTED:
1099 		LIST_INSERT_HEAD(INPCBHASH_CONNECT(inp->inp_table,
1100 		    inp->inp_faddr, inp->inp_fport,
1101 		    inp->inp_laddr, inp->inp_lport), &inp->inp_head,
1102 		    inph_hash);
1103 		break;
1104 	}
1105 
1106 	inp->inp_state = state;
1107 }
1108 
1109 struct rtentry *
1110 in_pcbrtentry(struct inpcb *inp)
1111 {
1112 	struct route *ro;
1113 	union {
1114 		struct sockaddr		dst;
1115 		struct sockaddr_in	dst4;
1116 	} u;
1117 
1118 	if (inp->inp_af != AF_INET)
1119 		return (NULL);
1120 
1121 	ro = &inp->inp_route;
1122 
1123 	sockaddr_in_init(&u.dst4, &inp->inp_faddr, 0);
1124 	return rtcache_lookup(ro, &u.dst);
1125 }
1126 
1127 void
1128 in_pcbrtentry_unref(struct rtentry *rt, struct inpcb *inp)
1129 {
1130 
1131 	rtcache_unref(rt, &inp->inp_route);
1132 }
1133