xref: /netbsd-src/sys/netinet/in_pcb.c (revision 46f5119e40af2e51998f686b2fdcc76b5488f7f3)
1 /*	$NetBSD: in_pcb.c,v 1.138 2011/05/03 18:28:45 dyoung 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.138 2011/05/03 18:28:45 dyoung Exp $");
97 
98 #include "opt_inet.h"
99 #include "opt_ipsec.h"
100 
101 #include <sys/param.h>
102 #include <sys/systm.h>
103 #include <sys/malloc.h>
104 #include <sys/mbuf.h>
105 #include <sys/protosw.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 
128 #ifdef INET6
129 #include <netinet/ip6.h>
130 #include <netinet6/ip6_var.h>
131 #include <netinet6/in6_pcb.h>
132 #endif
133 
134 #ifdef IPSEC
135 #include <netinet6/ipsec.h>
136 #include <netkey/key.h>
137 #elif FAST_IPSEC
138 #include <netipsec/ipsec.h>
139 #include <netipsec/key.h>
140 #endif /* IPSEC */
141 
142 #include <netinet/tcp_vtw.h>
143 
144 struct	in_addr zeroin_addr;
145 
146 #define	INPCBHASH_PORT(table, lport) \
147 	&(table)->inpt_porthashtbl[ntohs(lport) & (table)->inpt_porthash]
148 #define	INPCBHASH_BIND(table, laddr, lport) \
149 	&(table)->inpt_bindhashtbl[ \
150 	    ((ntohl((laddr).s_addr) + ntohs(lport))) & (table)->inpt_bindhash]
151 #define	INPCBHASH_CONNECT(table, faddr, fport, laddr, lport) \
152 	&(table)->inpt_connecthashtbl[ \
153 	    ((ntohl((faddr).s_addr) + ntohs(fport)) + \
154 	     (ntohl((laddr).s_addr) + ntohs(lport))) & (table)->inpt_connecthash]
155 
156 int	anonportmin = IPPORT_ANONMIN;
157 int	anonportmax = IPPORT_ANONMAX;
158 int	lowportmin  = IPPORT_RESERVEDMIN;
159 int	lowportmax  = IPPORT_RESERVEDMAX;
160 
161 static struct pool inpcb_pool;
162 
163 static int
164 inpcb_poolinit(void)
165 {
166 
167 	pool_init(&inpcb_pool, sizeof(struct inpcb), 0, 0, 0, "inpcbpl", NULL,
168 	    IPL_NET);
169 	return 0;
170 }
171 
172 void
173 in_pcbinit(struct inpcbtable *table, int bindhashsize, int connecthashsize)
174 {
175 	static ONCE_DECL(control);
176 
177 	CIRCLEQ_INIT(&table->inpt_queue);
178 	table->inpt_porthashtbl = hashinit(bindhashsize, HASH_LIST, true,
179 	    &table->inpt_porthash);
180 	table->inpt_bindhashtbl = hashinit(bindhashsize, HASH_LIST, true,
181 	    &table->inpt_bindhash);
182 	table->inpt_connecthashtbl = hashinit(connecthashsize, HASH_LIST, true,
183 	    &table->inpt_connecthash);
184 	table->inpt_lastlow = IPPORT_RESERVEDMAX;
185 	table->inpt_lastport = (u_int16_t)anonportmax;
186 
187 	RUN_ONCE(&control, inpcb_poolinit);
188 }
189 
190 int
191 in_pcballoc(struct socket *so, void *v)
192 {
193 	struct inpcbtable *table = v;
194 	struct inpcb *inp;
195 	int s;
196 #if defined(IPSEC) || defined(FAST_IPSEC)
197 	int error;
198 #endif
199 
200 	s = splnet();
201 	inp = pool_get(&inpcb_pool, PR_NOWAIT);
202 	splx(s);
203 	if (inp == NULL)
204 		return (ENOBUFS);
205 	memset((void *)inp, 0, sizeof(*inp));
206 	inp->inp_af = AF_INET;
207 	inp->inp_table = table;
208 	inp->inp_socket = so;
209 	inp->inp_errormtu = -1;
210 #if defined(IPSEC) || defined(FAST_IPSEC)
211 	error = ipsec_init_pcbpolicy(so, &inp->inp_sp);
212 	if (error != 0) {
213 		s = splnet();
214 		pool_put(&inpcb_pool, inp);
215 		splx(s);
216 		return error;
217 	}
218 #endif
219 	so->so_pcb = inp;
220 	s = splnet();
221 	CIRCLEQ_INSERT_HEAD(&table->inpt_queue, &inp->inp_head,
222 	    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 	int	   cnt;
236 	u_int16_t  mymin, mymax;
237 	u_int16_t *lastport;
238 	u_int16_t lport = 0;
239 	enum kauth_network_req req;
240 	int error;
241 
242 	if (inp->inp_flags & INP_LOWPORT) {
243 #ifndef IPNOPRIVPORTS
244 		req = KAUTH_REQ_NETWORK_BIND_PRIVPORT;
245 #else
246 		req = KAUTH_REQ_NETWORK_BIND_PORT;
247 #endif
248 
249 		mymin = lowportmin;
250 		mymax = lowportmax;
251 		lastport = &table->inpt_lastlow;
252 	} else {
253 		req = KAUTH_REQ_NETWORK_BIND_PORT;
254 
255 		mymin = anonportmin;
256 		mymax = anonportmax;
257 		lastport = &table->inpt_lastport;
258 	}
259 
260 	/* XXX-kauth: KAUTH_REQ_NETWORK_BIND_AUTOASSIGN_{,PRIV}PORT */
261 	error = kauth_authorize_network(cred, KAUTH_NETWORK_BIND, req, so, sin,
262 	    NULL);
263 	if (error)
264 		return (EACCES);
265 
266 	if (mymin > mymax) {	/* sanity check */
267 		u_int16_t swp;
268 
269 		swp = mymin;
270 		mymin = mymax;
271 		mymax = swp;
272 	}
273 
274 	lport = *lastport - 1;
275 	for (cnt = mymax - mymin + 1; cnt; cnt--, lport--) {
276 		vestigial_inpcb_t vestigial;
277 
278 		if (lport < mymin || lport > mymax)
279 			lport = mymax;
280 		if (!in_pcblookup_port(table, sin->sin_addr, htons(lport), 1,
281 		                       &vestigial) && !vestigial.valid) {
282 			/* We have a free port, check with the secmodel(s). */
283 			sin->sin_port = lport;
284 			error = kauth_authorize_network(cred,
285 			    KAUTH_NETWORK_BIND, req, so, sin, NULL);
286 			if (error) {
287 				/* Secmodel says no. Keep looking. */
288 				continue;
289 			}
290 
291 			goto found;
292 		}
293 	}
294 
295 	return (EAGAIN);
296 
297  found:
298 	inp->inp_flags |= INP_ANONPORT;
299 	*lastport = lport;
300 	lport = htons(lport);
301 	inp->inp_lport = lport;
302 	in_pcbstate(inp, INP_BOUND);
303 
304 	return (0);
305 }
306 
307 static int
308 in_pcbbind_addr(struct inpcb *inp, struct sockaddr_in *sin, kauth_cred_t cred)
309 {
310 	if (sin->sin_family != AF_INET)
311 		return (EAFNOSUPPORT);
312 
313 	if (IN_MULTICAST(sin->sin_addr.s_addr)) {
314 		/* Always succeed; port reuse handled in in_pcbbind_port(). */
315 	} else if (!in_nullhost(sin->sin_addr)) {
316 		struct in_ifaddr *ia = NULL;
317 
318 		INADDR_TO_IA(sin->sin_addr, ia);
319 		/* check for broadcast addresses */
320 		if (ia == NULL)
321 			ia = ifatoia(ifa_ifwithaddr(sintosa(sin)));
322 		if (ia == NULL)
323 			return (EADDRNOTAVAIL);
324 	}
325 
326 	inp->inp_laddr = sin->sin_addr;
327 
328 	return (0);
329 }
330 
331 static int
332 in_pcbbind_port(struct inpcb *inp, struct sockaddr_in *sin, kauth_cred_t cred)
333 {
334 	struct inpcbtable *table = inp->inp_table;
335 	struct socket *so = inp->inp_socket;
336 	int reuseport = (so->so_options & SO_REUSEPORT);
337 	int wild = 0, error;
338 
339 	if (IN_MULTICAST(sin->sin_addr.s_addr)) {
340 		/*
341 		 * Treat SO_REUSEADDR as SO_REUSEPORT for multicast;
342 		 * allow complete duplication of binding if
343 		 * SO_REUSEPORT is set, or if SO_REUSEADDR is set
344 		 * and a multicast address is bound on both
345 		 * new and duplicated sockets.
346 		 */
347 		if (so->so_options & SO_REUSEADDR)
348 			reuseport = SO_REUSEADDR|SO_REUSEPORT;
349 	}
350 
351 	if (sin->sin_port == 0) {
352 		error = in_pcbsetport(sin, inp, cred);
353 		if (error)
354 			return (error);
355 	} else {
356 		struct inpcb *t;
357 		vestigial_inpcb_t vestige;
358 #ifdef INET6
359 		struct in6pcb *t6;
360 		struct in6_addr mapped;
361 #endif
362 		enum kauth_network_req req;
363 
364 		if ((so->so_options & (SO_REUSEADDR|SO_REUSEPORT)) == 0)
365 			wild = 1;
366 
367 #ifndef IPNOPRIVPORTS
368 		if (ntohs(sin->sin_port) < IPPORT_RESERVED)
369 			req = KAUTH_REQ_NETWORK_BIND_PRIVPORT;
370 		else
371 #endif /* !IPNOPRIVPORTS */
372 			req = KAUTH_REQ_NETWORK_BIND_PORT;
373 
374 		error = kauth_authorize_network(cred, KAUTH_NETWORK_BIND, req,
375 		    so, sin, NULL);
376 		if (error)
377 			return (EACCES);
378 
379 #ifdef INET6
380 		memset(&mapped, 0, sizeof(mapped));
381 		mapped.s6_addr16[5] = 0xffff;
382 		memcpy(&mapped.s6_addr32[3], &sin->sin_addr,
383 		    sizeof(mapped.s6_addr32[3]));
384 		t6 = in6_pcblookup_port(table, &mapped, sin->sin_port, wild, &vestige);
385 		if (t6 && (reuseport & t6->in6p_socket->so_options) == 0)
386 			return (EADDRINUSE);
387 		if (!t6 && vestige.valid) {
388 		    if (!!reuseport != !!vestige.reuse_port) {
389 			return EADDRINUSE;
390 		    }
391 		}
392 #endif
393 
394 		/* XXX-kauth */
395 		if (so->so_uidinfo->ui_uid && !IN_MULTICAST(sin->sin_addr.s_addr)) {
396 			t = in_pcblookup_port(table, sin->sin_addr, sin->sin_port, 1, &vestige);
397 			/*
398 			 * XXX:	investigate ramifications of loosening this
399 			 *	restriction so that as long as both ports have
400 			 *	SO_REUSEPORT allow the bind
401 			 */
402 			if (t &&
403 			    (!in_nullhost(sin->sin_addr) ||
404 			     !in_nullhost(t->inp_laddr) ||
405 			     (t->inp_socket->so_options & SO_REUSEPORT) == 0)
406 			    && (so->so_uidinfo->ui_uid != t->inp_socket->so_uidinfo->ui_uid)) {
407 				return (EADDRINUSE);
408 			}
409 			if (!t && vestige.valid) {
410 				if ((!in_nullhost(sin->sin_addr)
411 				     || !in_nullhost(vestige.laddr.v4)
412 				     || !vestige.reuse_port)
413 				    && so->so_uidinfo->ui_uid != vestige.uid) {
414 					return EADDRINUSE;
415 				}
416 			}
417 		}
418 		t = in_pcblookup_port(table, sin->sin_addr, sin->sin_port, wild, &vestige);
419 		if (t && (reuseport & t->inp_socket->so_options) == 0)
420 			return (EADDRINUSE);
421 		if (!t
422 		    && vestige.valid
423 		    && !(reuseport && vestige.reuse_port))
424 			return EADDRINUSE;
425 
426 		inp->inp_lport = sin->sin_port;
427 		in_pcbstate(inp, INP_BOUND);
428 	}
429 
430 	LIST_REMOVE(&inp->inp_head, inph_lhash);
431 	LIST_INSERT_HEAD(INPCBHASH_PORT(table, inp->inp_lport), &inp->inp_head,
432 	    inph_lhash);
433 
434 	return (0);
435 }
436 
437 int
438 in_pcbbind(void *v, struct mbuf *nam, struct lwp *l)
439 {
440 	struct inpcb *inp = v;
441 	struct sockaddr_in *sin = NULL; /* XXXGCC */
442 	struct sockaddr_in lsin;
443 	int error;
444 
445 	if (inp->inp_af != AF_INET)
446 		return (EINVAL);
447 
448 	if (TAILQ_FIRST(&in_ifaddrhead) == 0)
449 		return (EADDRNOTAVAIL);
450 	if (inp->inp_lport || !in_nullhost(inp->inp_laddr))
451 		return (EINVAL);
452 
453 	if (nam != NULL) {
454 		sin = mtod(nam, struct sockaddr_in *);
455 		if (nam->m_len != sizeof (*sin))
456 			return (EINVAL);
457 	} else {
458 		lsin = *((const struct sockaddr_in *)
459 		    inp->inp_socket->so_proto->pr_domain->dom_sa_any);
460 		sin = &lsin;
461 	}
462 
463 	/* Bind address. */
464 	error = in_pcbbind_addr(inp, sin, l->l_cred);
465 	if (error)
466 		return (error);
467 
468 	/* Bind port. */
469 	error = in_pcbbind_port(inp, sin, l->l_cred);
470 	if (error) {
471 		inp->inp_laddr.s_addr = INADDR_ANY;
472 
473 		return (error);
474 	}
475 
476 	return (0);
477 }
478 
479 /*
480  * Connect from a socket to a specified address.
481  * Both address and port must be specified in argument sin.
482  * If don't have a local address for this socket yet,
483  * then pick one.
484  */
485 int
486 in_pcbconnect(void *v, struct mbuf *nam, struct lwp *l)
487 {
488 	struct inpcb *inp = v;
489 	struct in_ifaddr *ia = NULL;
490 	struct sockaddr_in *ifaddr = NULL;
491 	struct sockaddr_in *sin = mtod(nam, struct sockaddr_in *);
492 	vestigial_inpcb_t vestige;
493 	int error;
494 
495 	if (inp->inp_af != AF_INET)
496 		return (EINVAL);
497 
498 	if (nam->m_len != sizeof (*sin))
499 		return (EINVAL);
500 	if (sin->sin_family != AF_INET)
501 		return (EAFNOSUPPORT);
502 	if (sin->sin_port == 0)
503 		return (EADDRNOTAVAIL);
504 	if (TAILQ_FIRST(&in_ifaddrhead) != 0) {
505 		/*
506 		 * If the destination address is INADDR_ANY,
507 		 * use any local address (likely loopback).
508 		 * If the supplied address is INADDR_BROADCAST,
509 		 * use the broadcast address of an interface
510 		 * which supports broadcast. (loopback does not)
511 		 */
512 
513 		if (in_nullhost(sin->sin_addr)) {
514 			sin->sin_addr =
515 			    TAILQ_FIRST(&in_ifaddrhead)->ia_addr.sin_addr;
516 		} else if (sin->sin_addr.s_addr == INADDR_BROADCAST) {
517 			TAILQ_FOREACH(ia, &in_ifaddrhead, ia_list) {
518 				if (ia->ia_ifp->if_flags & IFF_BROADCAST) {
519 					sin->sin_addr =
520 					    ia->ia_broadaddr.sin_addr;
521 					break;
522 				}
523 			}
524 		}
525 	}
526 	/*
527 	 * If we haven't bound which network number to use as ours,
528 	 * we will use the number of the outgoing interface.
529 	 * This depends on having done a routing lookup, which
530 	 * we will probably have to do anyway, so we might
531 	 * as well do it now.  On the other hand if we are
532 	 * sending to multiple destinations we may have already
533 	 * done the lookup, so see if we can use the route
534 	 * from before.  In any case, we only
535 	 * chose a port number once, even if sending to multiple
536 	 * destinations.
537 	 */
538 	if (in_nullhost(inp->inp_laddr)) {
539 		int xerror;
540 		ifaddr = in_selectsrc(sin, &inp->inp_route,
541 		    inp->inp_socket->so_options, inp->inp_moptions, &xerror);
542 		if (ifaddr == NULL) {
543 			if (xerror == 0)
544 				xerror = EADDRNOTAVAIL;
545 			return xerror;
546 		}
547 		INADDR_TO_IA(ifaddr->sin_addr, ia);
548 		if (ia == NULL)
549 			return (EADDRNOTAVAIL);
550 	}
551 	if (in_pcblookup_connect(inp->inp_table, sin->sin_addr, sin->sin_port,
552 	    !in_nullhost(inp->inp_laddr) ? inp->inp_laddr : ifaddr->sin_addr,
553 				 inp->inp_lport, &vestige) != 0
554 	    || vestige.valid)
555 		return (EADDRINUSE);
556 	if (in_nullhost(inp->inp_laddr)) {
557 		if (inp->inp_lport == 0) {
558 			error = in_pcbbind(inp, NULL, l);
559 			/*
560 			 * This used to ignore the return value
561 			 * completely, but we need to check for
562 			 * ephemeral port shortage.
563 			 * And attempts to request low ports if not root.
564 			 */
565 			if (error != 0)
566 				return (error);
567 		}
568 		inp->inp_laddr = ifaddr->sin_addr;
569 	}
570 	inp->inp_faddr = sin->sin_addr;
571 	inp->inp_fport = sin->sin_port;
572 	in_pcbstate(inp, INP_CONNECTED);
573 #if defined(IPSEC) || defined(FAST_IPSEC)
574 	if (inp->inp_socket->so_type == SOCK_STREAM)
575 		ipsec_pcbconn(inp->inp_sp);
576 #endif
577 	return (0);
578 }
579 
580 void
581 in_pcbdisconnect(void *v)
582 {
583 	struct inpcb *inp = v;
584 
585 	if (inp->inp_af != AF_INET)
586 		return;
587 
588 	inp->inp_faddr = zeroin_addr;
589 	inp->inp_fport = 0;
590 	in_pcbstate(inp, INP_BOUND);
591 #if defined(IPSEC) || defined(FAST_IPSEC)
592 	ipsec_pcbdisconn(inp->inp_sp);
593 #endif
594 	if (inp->inp_socket->so_state & SS_NOFDREF)
595 		in_pcbdetach(inp);
596 }
597 
598 void
599 in_pcbdetach(void *v)
600 {
601 	struct inpcb *inp = v;
602 	struct socket *so = inp->inp_socket;
603 	int s;
604 
605 	if (inp->inp_af != AF_INET)
606 		return;
607 
608 #if defined(IPSEC) || defined(FAST_IPSEC)
609 	ipsec4_delete_pcbpolicy(inp);
610 #endif /*IPSEC*/
611 	so->so_pcb = 0;
612 	if (inp->inp_options)
613 		(void)m_free(inp->inp_options);
614 	rtcache_free(&inp->inp_route);
615 	ip_freemoptions(inp->inp_moptions);
616 	s = splnet();
617 	in_pcbstate(inp, INP_ATTACHED);
618 	LIST_REMOVE(&inp->inp_head, inph_lhash);
619 	CIRCLEQ_REMOVE(&inp->inp_table->inpt_queue, &inp->inp_head,
620 	    inph_queue);
621 	pool_put(&inpcb_pool, inp);
622 	splx(s);
623 	sofree(so);			/* drops the socket's lock */
624 	mutex_enter(softnet_lock);	/* reacquire the softnet_lock */
625 }
626 
627 void
628 in_setsockaddr(struct inpcb *inp, struct mbuf *nam)
629 {
630 	struct sockaddr_in *sin;
631 
632 	if (inp->inp_af != AF_INET)
633 		return;
634 
635 	sin = mtod(nam, struct sockaddr_in *);
636 	sockaddr_in_init(sin, &inp->inp_laddr, inp->inp_lport);
637 	nam->m_len = sin->sin_len;
638 }
639 
640 void
641 in_setpeeraddr(struct inpcb *inp, struct mbuf *nam)
642 {
643 	struct sockaddr_in *sin;
644 
645 	if (inp->inp_af != AF_INET)
646 		return;
647 
648 	sin = mtod(nam, struct sockaddr_in *);
649 	sockaddr_in_init(sin, &inp->inp_faddr, inp->inp_fport);
650 	nam->m_len = sin->sin_len;
651 }
652 
653 /*
654  * Pass some notification to all connections of a protocol
655  * associated with address dst.  The local address and/or port numbers
656  * may be specified to limit the search.  The "usual action" will be
657  * taken, depending on the ctlinput cmd.  The caller must filter any
658  * cmds that are uninteresting (e.g., no error in the map).
659  * Call the protocol specific routine (if any) to report
660  * any errors for each matching socket.
661  *
662  * Must be called at splsoftnet.
663  */
664 int
665 in_pcbnotify(struct inpcbtable *table, struct in_addr faddr, u_int fport_arg,
666     struct in_addr laddr, u_int lport_arg, int errno,
667     void (*notify)(struct inpcb *, int))
668 {
669 	struct inpcbhead *head;
670 	struct inpcb *inp, *ninp;
671 	u_int16_t fport = fport_arg, lport = lport_arg;
672 	int nmatch;
673 
674 	if (in_nullhost(faddr) || notify == 0)
675 		return (0);
676 
677 	nmatch = 0;
678 	head = INPCBHASH_CONNECT(table, faddr, fport, laddr, lport);
679 	for (inp = (struct inpcb *)LIST_FIRST(head); inp != NULL; inp = ninp) {
680 		ninp = (struct inpcb *)LIST_NEXT(inp, inp_hash);
681 		if (inp->inp_af != AF_INET)
682 			continue;
683 		if (in_hosteq(inp->inp_faddr, faddr) &&
684 		    inp->inp_fport == fport &&
685 		    inp->inp_lport == lport &&
686 		    in_hosteq(inp->inp_laddr, laddr)) {
687 			(*notify)(inp, errno);
688 			nmatch++;
689 		}
690 	}
691 	return (nmatch);
692 }
693 
694 void
695 in_pcbnotifyall(struct inpcbtable *table, struct in_addr faddr, int errno,
696     void (*notify)(struct inpcb *, int))
697 {
698 	struct inpcb *inp, *ninp;
699 
700 	if (in_nullhost(faddr) || notify == 0)
701 		return;
702 
703 	for (inp = (struct inpcb *)CIRCLEQ_FIRST(&table->inpt_queue);
704 	    inp != (void *)&table->inpt_queue;
705 	    inp = ninp) {
706 		ninp = (struct inpcb *)CIRCLEQ_NEXT(inp, inp_queue);
707 		if (inp->inp_af != AF_INET)
708 			continue;
709 		if (in_hosteq(inp->inp_faddr, faddr))
710 			(*notify)(inp, errno);
711 	}
712 }
713 
714 void
715 in_pcbpurgeif0(struct inpcbtable *table, struct ifnet *ifp)
716 {
717 	struct inpcb *inp, *ninp;
718 	struct ip_moptions *imo;
719 	int i, gap;
720 
721 	for (inp = (struct inpcb *)CIRCLEQ_FIRST(&table->inpt_queue);
722 	    inp != (void *)&table->inpt_queue;
723 	    inp = ninp) {
724 		ninp = (struct inpcb *)CIRCLEQ_NEXT(inp, inp_queue);
725 		if (inp->inp_af != AF_INET)
726 			continue;
727 		imo = inp->inp_moptions;
728 		if (imo != NULL) {
729 			/*
730 			 * Unselect the outgoing interface if it is being
731 			 * detached.
732 			 */
733 			if (imo->imo_multicast_ifp == ifp)
734 				imo->imo_multicast_ifp = NULL;
735 
736 			/*
737 			 * Drop multicast group membership if we joined
738 			 * through the interface being detached.
739 			 */
740 			for (i = 0, gap = 0; i < imo->imo_num_memberships;
741 			    i++) {
742 				if (imo->imo_membership[i]->inm_ifp == ifp) {
743 					in_delmulti(imo->imo_membership[i]);
744 					gap++;
745 				} else if (gap != 0)
746 					imo->imo_membership[i - gap] =
747 					    imo->imo_membership[i];
748 			}
749 			imo->imo_num_memberships -= gap;
750 		}
751 	}
752 }
753 
754 void
755 in_pcbpurgeif(struct inpcbtable *table, struct ifnet *ifp)
756 {
757 	struct rtentry *rt;
758 	struct inpcb *inp, *ninp;
759 
760 	for (inp = (struct inpcb *)CIRCLEQ_FIRST(&table->inpt_queue);
761 	    inp != (void *)&table->inpt_queue;
762 	    inp = ninp) {
763 		ninp = (struct inpcb *)CIRCLEQ_NEXT(inp, inp_queue);
764 		if (inp->inp_af != AF_INET)
765 			continue;
766 		if ((rt = rtcache_validate(&inp->inp_route)) != NULL &&
767 		    rt->rt_ifp == ifp)
768 			in_rtchange(inp, 0);
769 	}
770 }
771 
772 /*
773  * Check for alternatives when higher level complains
774  * about service problems.  For now, invalidate cached
775  * routing information.  If the route was created dynamically
776  * (by a redirect), time to try a default gateway again.
777  */
778 void
779 in_losing(struct inpcb *inp)
780 {
781 	struct rtentry *rt;
782 	struct rt_addrinfo info;
783 
784 	if (inp->inp_af != AF_INET)
785 		return;
786 
787 	if ((rt = rtcache_validate(&inp->inp_route)) == NULL)
788 		return;
789 
790 	memset(&info, 0, sizeof(info));
791 	info.rti_info[RTAX_DST] = rtcache_getdst(&inp->inp_route);
792 	info.rti_info[RTAX_GATEWAY] = rt->rt_gateway;
793 	info.rti_info[RTAX_NETMASK] = rt_mask(rt);
794 	rt_missmsg(RTM_LOSING, &info, rt->rt_flags, 0);
795 	if (rt->rt_flags & RTF_DYNAMIC)
796 		(void) rtrequest(RTM_DELETE, rt_getkey(rt),
797 			rt->rt_gateway, rt_mask(rt), rt->rt_flags,
798 			NULL);
799 	/*
800 	 * A new route can be allocated
801 	 * the next time output is attempted.
802 	 */
803 	rtcache_free(&inp->inp_route);
804 }
805 
806 /*
807  * After a routing change, flush old routing.  A new route can be
808  * allocated the next time output is attempted.
809  */
810 void
811 in_rtchange(struct inpcb *inp, int errno)
812 {
813 
814 	if (inp->inp_af != AF_INET)
815 		return;
816 
817 	rtcache_free(&inp->inp_route);
818 
819 	/* XXX SHOULD NOTIFY HIGHER-LEVEL PROTOCOLS */
820 }
821 
822 struct inpcb *
823 in_pcblookup_port(struct inpcbtable *table, struct in_addr laddr,
824 		  u_int lport_arg, int lookup_wildcard, vestigial_inpcb_t *vp)
825 {
826 	struct inpcbhead *head;
827 	struct inpcb_hdr *inph;
828 	struct inpcb *inp, *match = 0;
829 	int matchwild = 3, wildcard;
830 	u_int16_t lport = lport_arg;
831 
832 	if (vp)
833 		vp->valid = 0;
834 
835 	head = INPCBHASH_PORT(table, lport);
836 	LIST_FOREACH(inph, head, inph_lhash) {
837 		inp = (struct inpcb *)inph;
838 		if (inp->inp_af != AF_INET)
839 			continue;
840 
841 		if (inp->inp_lport != lport)
842 			continue;
843 		wildcard = 0;
844 		if (!in_nullhost(inp->inp_faddr))
845 			wildcard++;
846 		if (in_nullhost(inp->inp_laddr)) {
847 			if (!in_nullhost(laddr))
848 				wildcard++;
849 		} else {
850 			if (in_nullhost(laddr))
851 				wildcard++;
852 			else {
853 				if (!in_hosteq(inp->inp_laddr, laddr))
854 					continue;
855 			}
856 		}
857 		if (wildcard && !lookup_wildcard)
858 			continue;
859 		if (wildcard < matchwild) {
860 			match = inp;
861 			matchwild = wildcard;
862 			if (matchwild == 0)
863 				break;
864 		}
865 	}
866 	if (match && matchwild == 0)
867 		return match;
868 
869 	if (vp && table->vestige) {
870 		void	*state = (*table->vestige->init_ports4)(laddr, lport_arg, lookup_wildcard);
871 		vestigial_inpcb_t better;
872 
873 		while (table->vestige
874 		       && (*table->vestige->next_port4)(state, vp)) {
875 
876 			if (vp->lport != lport)
877 				continue;
878 			wildcard = 0;
879 			if (!in_nullhost(vp->faddr.v4))
880 				wildcard++;
881 			if (in_nullhost(vp->laddr.v4)) {
882 				if (!in_nullhost(laddr))
883 					wildcard++;
884 			} else {
885 				if (in_nullhost(laddr))
886 					wildcard++;
887 				else {
888 					if (!in_hosteq(vp->laddr.v4, laddr))
889 						continue;
890 				}
891 			}
892 			if (wildcard && !lookup_wildcard)
893 				continue;
894 			if (wildcard < matchwild) {
895 				better = *vp;
896 				match  = (void*)&better;
897 
898 				matchwild = wildcard;
899 				if (matchwild == 0)
900 					break;
901 			}
902 		}
903 
904 		if (match) {
905 			if (match != (void*)&better)
906 				return match;
907 			else {
908 				*vp = better;
909 				return 0;
910 			}
911 		}
912 	}
913 
914 	return (match);
915 }
916 
917 #ifdef DIAGNOSTIC
918 int	in_pcbnotifymiss = 0;
919 #endif
920 
921 struct inpcb *
922 in_pcblookup_connect(struct inpcbtable *table,
923     struct in_addr faddr, u_int fport_arg,
924     struct in_addr laddr, u_int lport_arg,
925     vestigial_inpcb_t *vp)
926 {
927 	struct inpcbhead *head;
928 	struct inpcb_hdr *inph;
929 	struct inpcb *inp;
930 	u_int16_t fport = fport_arg, lport = lport_arg;
931 
932 	if (vp)
933 		vp->valid = 0;
934 
935 	head = INPCBHASH_CONNECT(table, faddr, fport, laddr, lport);
936 	LIST_FOREACH(inph, head, inph_hash) {
937 		inp = (struct inpcb *)inph;
938 		if (inp->inp_af != AF_INET)
939 			continue;
940 
941 		if (in_hosteq(inp->inp_faddr, faddr) &&
942 		    inp->inp_fport == fport &&
943 		    inp->inp_lport == lport &&
944 		    in_hosteq(inp->inp_laddr, laddr))
945 			goto out;
946 	}
947 	if (vp && table->vestige) {
948 		if ((*table->vestige->lookup4)(faddr, fport_arg,
949 					       laddr, lport_arg, vp))
950 			return 0;
951 	}
952 
953 #ifdef DIAGNOSTIC
954 	if (in_pcbnotifymiss) {
955 		printf("in_pcblookup_connect: faddr=%08x fport=%d laddr=%08x lport=%d\n",
956 		    ntohl(faddr.s_addr), ntohs(fport),
957 		    ntohl(laddr.s_addr), ntohs(lport));
958 	}
959 #endif
960 	return (0);
961 
962 out:
963 	/* Move this PCB to the head of hash chain. */
964 	inph = &inp->inp_head;
965 	if (inph != LIST_FIRST(head)) {
966 		LIST_REMOVE(inph, inph_hash);
967 		LIST_INSERT_HEAD(head, inph, inph_hash);
968 	}
969 	return (inp);
970 }
971 
972 struct inpcb *
973 in_pcblookup_bind(struct inpcbtable *table,
974     struct in_addr laddr, u_int lport_arg)
975 {
976 	struct inpcbhead *head;
977 	struct inpcb_hdr *inph;
978 	struct inpcb *inp;
979 	u_int16_t lport = lport_arg;
980 
981 	head = INPCBHASH_BIND(table, laddr, lport);
982 	LIST_FOREACH(inph, head, inph_hash) {
983 		inp = (struct inpcb *)inph;
984 		if (inp->inp_af != AF_INET)
985 			continue;
986 
987 		if (inp->inp_lport == lport &&
988 		    in_hosteq(inp->inp_laddr, laddr))
989 			goto out;
990 	}
991 	head = INPCBHASH_BIND(table, zeroin_addr, lport);
992 	LIST_FOREACH(inph, head, inph_hash) {
993 		inp = (struct inpcb *)inph;
994 		if (inp->inp_af != AF_INET)
995 			continue;
996 
997 		if (inp->inp_lport == lport &&
998 		    in_hosteq(inp->inp_laddr, zeroin_addr))
999 			goto out;
1000 	}
1001 #ifdef DIAGNOSTIC
1002 	if (in_pcbnotifymiss) {
1003 		printf("in_pcblookup_bind: laddr=%08x lport=%d\n",
1004 		    ntohl(laddr.s_addr), ntohs(lport));
1005 	}
1006 #endif
1007 	return (0);
1008 
1009 out:
1010 	/* Move this PCB to the head of hash chain. */
1011 	inph = &inp->inp_head;
1012 	if (inph != LIST_FIRST(head)) {
1013 		LIST_REMOVE(inph, inph_hash);
1014 		LIST_INSERT_HEAD(head, inph, inph_hash);
1015 	}
1016 	return (inp);
1017 }
1018 
1019 void
1020 in_pcbstate(struct inpcb *inp, int state)
1021 {
1022 
1023 	if (inp->inp_af != AF_INET)
1024 		return;
1025 
1026 	if (inp->inp_state > INP_ATTACHED)
1027 		LIST_REMOVE(&inp->inp_head, inph_hash);
1028 
1029 	switch (state) {
1030 	case INP_BOUND:
1031 		LIST_INSERT_HEAD(INPCBHASH_BIND(inp->inp_table,
1032 		    inp->inp_laddr, inp->inp_lport), &inp->inp_head,
1033 		    inph_hash);
1034 		break;
1035 	case INP_CONNECTED:
1036 		LIST_INSERT_HEAD(INPCBHASH_CONNECT(inp->inp_table,
1037 		    inp->inp_faddr, inp->inp_fport,
1038 		    inp->inp_laddr, inp->inp_lport), &inp->inp_head,
1039 		    inph_hash);
1040 		break;
1041 	}
1042 
1043 	inp->inp_state = state;
1044 }
1045 
1046 struct rtentry *
1047 in_pcbrtentry(struct inpcb *inp)
1048 {
1049 	struct route *ro;
1050 	union {
1051 		struct sockaddr		dst;
1052 		struct sockaddr_in	dst4;
1053 	} u;
1054 
1055 	if (inp->inp_af != AF_INET)
1056 		return (NULL);
1057 
1058 	ro = &inp->inp_route;
1059 
1060 	sockaddr_in_init(&u.dst4, &inp->inp_faddr, 0);
1061 	return rtcache_lookup(ro, &u.dst);
1062 }
1063 
1064 struct sockaddr_in *
1065 in_selectsrc(struct sockaddr_in *sin, struct route *ro,
1066     int soopts, struct ip_moptions *mopts, int *errorp)
1067 {
1068 	struct rtentry *rt = NULL;
1069 	struct in_ifaddr *ia = NULL;
1070 
1071 	/*
1072          * If route is known or can be allocated now, take the
1073          * source address from the interface.  Otherwise, punt.
1074 	 */
1075 	if ((soopts & SO_DONTROUTE) != 0)
1076 		rtcache_free(ro);
1077 	else {
1078 		union {
1079 			struct sockaddr		dst;
1080 			struct sockaddr_in	dst4;
1081 		} u;
1082 
1083 		sockaddr_in_init(&u.dst4, &sin->sin_addr, 0);
1084 		rt = rtcache_lookup(ro, &u.dst);
1085 	}
1086 	/*
1087 	 * If we found a route, use the address
1088 	 * corresponding to the outgoing interface
1089 	 * unless it is the loopback (in case a route
1090 	 * to our address on another net goes to loopback).
1091 	 *
1092 	 * XXX Is this still true?  Do we care?
1093 	 */
1094 	if (rt != NULL && (rt->rt_ifp->if_flags & IFF_LOOPBACK) == 0)
1095 		ia = ifatoia(rt->rt_ifa);
1096 	if (ia == NULL) {
1097 		u_int16_t fport = sin->sin_port;
1098 
1099 		sin->sin_port = 0;
1100 		ia = ifatoia(ifa_ifwithladdr(sintosa(sin)));
1101 		sin->sin_port = fport;
1102 		if (ia == NULL) {
1103 			/* Find 1st non-loopback AF_INET address */
1104 			TAILQ_FOREACH(ia, &in_ifaddrhead, ia_list) {
1105 				if (!(ia->ia_ifp->if_flags & IFF_LOOPBACK))
1106 					break;
1107 			}
1108 		}
1109 		if (ia == NULL) {
1110 			*errorp = EADDRNOTAVAIL;
1111 			return NULL;
1112 		}
1113 	}
1114 	/*
1115 	 * If the destination address is multicast and an outgoing
1116 	 * interface has been set as a multicast option, use the
1117 	 * address of that interface as our source address.
1118 	 */
1119 	if (IN_MULTICAST(sin->sin_addr.s_addr) && mopts != NULL) {
1120 		struct ip_moptions *imo;
1121 		struct ifnet *ifp;
1122 
1123 		imo = mopts;
1124 		if (imo->imo_multicast_ifp != NULL) {
1125 			ifp = imo->imo_multicast_ifp;
1126 			IFP_TO_IA(ifp, ia);		/* XXX */
1127 			if (ia == 0) {
1128 				*errorp = EADDRNOTAVAIL;
1129 				return NULL;
1130 			}
1131 		}
1132 	}
1133 	if (ia->ia_ifa.ifa_getifa != NULL) {
1134 		ia = ifatoia((*ia->ia_ifa.ifa_getifa)(&ia->ia_ifa,
1135 		                                      sintosa(sin)));
1136 	}
1137 #ifdef GETIFA_DEBUG
1138 	else
1139 		printf("%s: missing ifa_getifa\n", __func__);
1140 #endif
1141 	return satosin(&ia->ia_addr);
1142 }
1143