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