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