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