819dcef10cff481bd4e8f3936d0870182f07805b
[dragonfly.git] / sys / netinet / in_pcb.c
1 /*
2  * Copyright (c) 2004 Jeffrey M. Hsu.  All rights reserved.
3  * Copyright (c) 2004 The DragonFly Project.  All rights reserved.
4  *
5  * This code is derived from software contributed to The DragonFly Project
6  * by Jeffrey M. Hsu.
7  *
8  * Redistribution and use in source and binary forms, with or without
9  * modification, are permitted provided that the following conditions
10  * are met:
11  * 1. Redistributions of source code must retain the above copyright
12  *    notice, this list of conditions and the following disclaimer.
13  * 2. Redistributions in binary form must reproduce the above copyright
14  *    notice, this list of conditions and the following disclaimer in the
15  *    documentation and/or other materials provided with the distribution.
16  * 3. Neither the name of The DragonFly Project nor the names of its
17  *    contributors may be used to endorse or promote products derived
18  *    from this software without specific, prior written permission.
19  *
20  * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
21  * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
22  * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
23  * FOR A PARTICULAR PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL THE
24  * COPYRIGHT HOLDERS OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
25  * INCIDENTAL, SPECIAL, EXEMPLARY OR CONSEQUENTIAL DAMAGES (INCLUDING,
26  * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
27  * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED
28  * AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
29  * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
30  * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
31  * SUCH DAMAGE.
32  */
33
34 /*
35  * Copyright (c) 1982, 1986, 1991, 1993, 1995
36  *      The Regents of the University of California.  All rights reserved.
37  *
38  * Redistribution and use in source and binary forms, with or without
39  * modification, are permitted provided that the following conditions
40  * are met:
41  * 1. Redistributions of source code must retain the above copyright
42  *    notice, this list of conditions and the following disclaimer.
43  * 2. Redistributions in binary form must reproduce the above copyright
44  *    notice, this list of conditions and the following disclaimer in the
45  *    documentation and/or other materials provided with the distribution.
46  * 3. All advertising materials mentioning features or use of this software
47  *    must display the following acknowledgement:
48  *      This product includes software developed by the University of
49  *      California, Berkeley and its contributors.
50  * 4. Neither the name of the University nor the names of its contributors
51  *    may be used to endorse or promote products derived from this software
52  *    without specific prior written permission.
53  *
54  * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
55  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
56  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
57  * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
58  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
59  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
60  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
61  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
62  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
63  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
64  * SUCH DAMAGE.
65  *
66  *      @(#)in_pcb.c    8.4 (Berkeley) 5/24/95
67  * $FreeBSD: src/sys/netinet/in_pcb.c,v 1.59.2.27 2004/01/02 04:06:42 ambrisko Exp $
68  * $DragonFly: src/sys/netinet/in_pcb.c,v 1.48 2008/11/08 03:38:23 sephe Exp $
69  */
70
71 #include "opt_ipsec.h"
72 #include "opt_inet6.h"
73
74 #include <sys/param.h>
75 #include <sys/systm.h>
76 #include <sys/malloc.h>
77 #include <sys/mbuf.h>
78 #include <sys/domain.h>
79 #include <sys/protosw.h>
80 #include <sys/socket.h>
81 #include <sys/socketvar.h>
82 #include <sys/proc.h>
83 #include <sys/priv.h>
84 #include <sys/jail.h>
85 #include <sys/kernel.h>
86 #include <sys/sysctl.h>
87
88 #include <sys/thread2.h>
89 #include <sys/socketvar2.h>
90 #include <sys/msgport2.h>
91
92 #include <machine/limits.h>
93
94 #include <net/if.h>
95 #include <net/if_types.h>
96 #include <net/route.h>
97
98 #include <netinet/in.h>
99 #include <netinet/in_pcb.h>
100 #include <netinet/in_var.h>
101 #include <netinet/ip_var.h>
102 #ifdef INET6
103 #include <netinet/ip6.h>
104 #include <netinet6/ip6_var.h>
105 #endif /* INET6 */
106
107 #ifdef IPSEC
108 #include <netinet6/ipsec.h>
109 #include <netproto/key/key.h>
110 #endif
111
112 #ifdef FAST_IPSEC
113 #if defined(IPSEC) || defined(IPSEC_ESP)
114 #error "Bad idea: don't compile with both IPSEC and FAST_IPSEC!"
115 #endif
116
117 #include <netproto/ipsec/ipsec.h>
118 #include <netproto/ipsec/key.h>
119 #define IPSEC
120 #endif /* FAST_IPSEC */
121
122 struct in_addr zeroin_addr;
123
124 /*
125  * These configure the range of local port addresses assigned to
126  * "unspecified" outgoing connections/packets/whatever.
127  */
128 int ipport_lowfirstauto = IPPORT_RESERVED - 1;  /* 1023 */
129 int ipport_lowlastauto = IPPORT_RESERVEDSTART;  /* 600 */
130
131 int ipport_firstauto = IPPORT_RESERVED;         /* 1024 */
132 int ipport_lastauto = IPPORT_USERRESERVED;      /* 5000 */
133
134 int ipport_hifirstauto = IPPORT_HIFIRSTAUTO;    /* 49152 */
135 int ipport_hilastauto = IPPORT_HILASTAUTO;      /* 65535 */
136
137 #define RANGECHK(var, min, max) \
138         if ((var) < (min)) { (var) = (min); } \
139         else if ((var) > (max)) { (var) = (max); }
140
141 static int
142 sysctl_net_ipport_check(SYSCTL_HANDLER_ARGS)
143 {
144         int error;
145
146         error = sysctl_handle_int(oidp, oidp->oid_arg1, oidp->oid_arg2, req);
147         if (!error) {
148                 RANGECHK(ipport_lowfirstauto, 1, IPPORT_RESERVED - 1);
149                 RANGECHK(ipport_lowlastauto, 1, IPPORT_RESERVED - 1);
150
151                 RANGECHK(ipport_firstauto, IPPORT_RESERVED, USHRT_MAX);
152                 RANGECHK(ipport_lastauto, IPPORT_RESERVED, USHRT_MAX);
153
154                 RANGECHK(ipport_hifirstauto, IPPORT_RESERVED, USHRT_MAX);
155                 RANGECHK(ipport_hilastauto, IPPORT_RESERVED, USHRT_MAX);
156         }
157         return (error);
158 }
159
160 #undef RANGECHK
161
162 SYSCTL_NODE(_net_inet_ip, IPPROTO_IP, portrange, CTLFLAG_RW, 0, "IP Ports");
163
164 SYSCTL_PROC(_net_inet_ip_portrange, OID_AUTO, lowfirst, CTLTYPE_INT|CTLFLAG_RW,
165            &ipport_lowfirstauto, 0, &sysctl_net_ipport_check, "I", "");
166 SYSCTL_PROC(_net_inet_ip_portrange, OID_AUTO, lowlast, CTLTYPE_INT|CTLFLAG_RW,
167            &ipport_lowlastauto, 0, &sysctl_net_ipport_check, "I", "");
168 SYSCTL_PROC(_net_inet_ip_portrange, OID_AUTO, first, CTLTYPE_INT|CTLFLAG_RW,
169            &ipport_firstauto, 0, &sysctl_net_ipport_check, "I", "");
170 SYSCTL_PROC(_net_inet_ip_portrange, OID_AUTO, last, CTLTYPE_INT|CTLFLAG_RW,
171            &ipport_lastauto, 0, &sysctl_net_ipport_check, "I", "");
172 SYSCTL_PROC(_net_inet_ip_portrange, OID_AUTO, hifirst, CTLTYPE_INT|CTLFLAG_RW,
173            &ipport_hifirstauto, 0, &sysctl_net_ipport_check, "I", "");
174 SYSCTL_PROC(_net_inet_ip_portrange, OID_AUTO, hilast, CTLTYPE_INT|CTLFLAG_RW,
175            &ipport_hilastauto, 0, &sysctl_net_ipport_check, "I", "");
176
177 /*
178  * in_pcb.c: manage the Protocol Control Blocks.
179  *
180  * NOTE: It is assumed that most of these functions will be called from
181  * a critical section.  XXX - There are, unfortunately, a few exceptions
182  * to this rule that should be fixed.
183  *
184  * NOTE: The caller should initialize the cpu field to the cpu running the
185  * protocol stack associated with this inpcbinfo.
186  */
187
188 void
189 in_pcbinfo_init(struct inpcbinfo *pcbinfo)
190 {
191         LIST_INIT(&pcbinfo->pcblisthead);
192         pcbinfo->cpu = -1;
193         pcbinfo->portsave = kmalloc(sizeof(*pcbinfo->portsave), M_PCB,
194                                     M_WAITOK | M_ZERO);
195 }
196
197 /*
198  * Allocate a PCB and associate it with the socket.
199  */
200 int
201 in_pcballoc(struct socket *so, struct inpcbinfo *pcbinfo)
202 {
203         struct inpcb *inp;
204 #ifdef IPSEC
205         int error;
206 #endif
207
208         inp = kmalloc(pcbinfo->ipi_size, M_PCB, M_WAITOK|M_ZERO);
209         inp->inp_gencnt = ++pcbinfo->ipi_gencnt;
210         inp->inp_pcbinfo = inp->inp_cpcbinfo = pcbinfo;
211         inp->inp_socket = so;
212 #ifdef IPSEC
213         error = ipsec_init_policy(so, &inp->inp_sp);
214         if (error != 0) {
215                 kfree(inp, M_PCB);
216                 return (error);
217         }
218 #endif
219 #ifdef INET6
220         if (INP_SOCKAF(so) == AF_INET6 && ip6_v6only)
221                 inp->inp_flags |= IN6P_IPV6_V6ONLY;
222         if (ip6_auto_flowlabel)
223                 inp->inp_flags |= IN6P_AUTOFLOWLABEL;
224 #endif
225         soreference(so);
226         so->so_pcb = inp;
227         LIST_INSERT_HEAD(&pcbinfo->pcblisthead, inp, inp_list);
228         pcbinfo->ipi_count++;
229         return (0);
230 }
231
232 /*
233  * Unlink a pcb with the intention of moving it to another cpu with a
234  * different pcbinfo.  While unlinked nothing should attempt to dereference
235  * inp_pcbinfo, NULL it out so we assert if it does.
236  */
237 void
238 in_pcbunlink(struct inpcb *inp, struct inpcbinfo *pcbinfo)
239 {
240         KKASSERT(inp->inp_pcbinfo == pcbinfo);
241
242         LIST_REMOVE(inp, inp_list);
243         pcbinfo->ipi_count--;
244         inp->inp_pcbinfo = NULL;
245 }
246
247 /*
248  * Relink a pcb into a new pcbinfo.
249  */
250 void
251 in_pcblink(struct inpcb *inp, struct inpcbinfo *pcbinfo)
252 {
253         KKASSERT(inp->inp_pcbinfo == NULL);
254         inp->inp_pcbinfo = pcbinfo;
255         LIST_INSERT_HEAD(&pcbinfo->pcblisthead, inp, inp_list);
256         pcbinfo->ipi_count++;
257 }
258
259 int
260 in_pcbbind(struct inpcb *inp, struct sockaddr *nam, struct thread *td)
261 {
262         struct socket *so = inp->inp_socket;
263         struct proc *p = td->td_proc;
264         unsigned short *lastport;
265         struct sockaddr_in *sin;
266         struct sockaddr_in jsin;
267         struct inpcbinfo *pcbinfo = inp->inp_pcbinfo;
268         struct ucred *cred = NULL;
269         u_short lport = 0;
270         int wild = 0, reuseport = (so->so_options & SO_REUSEPORT);
271         int error;
272
273         KKASSERT(p);
274
275         if (TAILQ_EMPTY(&in_ifaddrheads[mycpuid])) /* XXX broken! */
276                 return (EADDRNOTAVAIL);
277         if (inp->inp_lport != 0 || inp->inp_laddr.s_addr != INADDR_ANY)
278                 return (EINVAL);        /* already bound */
279
280         if (!(so->so_options & (SO_REUSEADDR|SO_REUSEPORT)))
281                 wild = 1;    /* neither SO_REUSEADDR nor SO_REUSEPORT is set */
282         if (p)
283                 cred = p->p_ucred;
284
285         /*
286          * This has to be atomic.  If the porthash is shared across multiple
287          * protocol threads (aka tcp) then the token will be non-NULL.
288          */
289         if (pcbinfo->porttoken)
290                 lwkt_gettoken(pcbinfo->porttoken);
291
292         if (nam != NULL) {
293                 sin = (struct sockaddr_in *)nam;
294                 if (nam->sa_len != sizeof *sin) {
295                         error = EINVAL;
296                         goto done;
297                 }
298 #ifdef notdef
299                 /*
300                  * We should check the family, but old programs
301                  * incorrectly fail to initialize it.
302                  */
303                 if (sin->sin_family != AF_INET) {
304                         error = EAFNOSUPPORT;
305                         goto done;
306                 }
307 #endif
308                 if (!prison_replace_wildcards(td, nam)) {
309                         error = EINVAL;
310                         goto done;
311                 }
312                 lport = sin->sin_port;
313                 if (IN_MULTICAST(ntohl(sin->sin_addr.s_addr))) {
314                         /*
315                          * Treat SO_REUSEADDR as SO_REUSEPORT for multicast;
316                          * allow complete duplication of binding if
317                          * SO_REUSEPORT is set, or if SO_REUSEADDR is set
318                          * and a multicast address is bound on both
319                          * new and duplicated sockets.
320                          */
321                         if (so->so_options & SO_REUSEADDR)
322                                 reuseport = SO_REUSEADDR | SO_REUSEPORT;
323                 } else if (sin->sin_addr.s_addr != INADDR_ANY) {
324                         sin->sin_port = 0;              /* yech... */
325                         bzero(&sin->sin_zero, sizeof sin->sin_zero);
326                         if (ifa_ifwithaddr((struct sockaddr *)sin) == NULL) {
327                                 error = EADDRNOTAVAIL;
328                                 goto done;
329                         }
330                 }
331                 if (lport != 0) {
332                         struct inpcb *t;
333
334                         /* GROSS */
335                         if (ntohs(lport) < IPPORT_RESERVED &&
336                             cred &&
337                             priv_check_cred(cred, PRIV_NETINET_RESERVEDPORT, 0)) {
338                                 error = EACCES;
339                                 goto done;
340                         }
341                         if (so->so_cred->cr_uid != 0 &&
342                             !IN_MULTICAST(ntohl(sin->sin_addr.s_addr))) {
343                                 t = in_pcblookup_local(pcbinfo,
344                                                        sin->sin_addr,
345                                                        lport,
346                                                        INPLOOKUP_WILDCARD,
347                                                        cred);
348                                 if (t &&
349                                     (!in_nullhost(sin->sin_addr) ||
350                                      !in_nullhost(t->inp_laddr) ||
351                                      (t->inp_socket->so_options &
352                                          SO_REUSEPORT) == 0) &&
353                                     (so->so_cred->cr_uid !=
354                                      t->inp_socket->so_cred->cr_uid)) {
355 #ifdef INET6
356                                         if (!in_nullhost(sin->sin_addr) ||
357                                             !in_nullhost(t->inp_laddr) ||
358                                             INP_SOCKAF(so) ==
359                                             INP_SOCKAF(t->inp_socket))
360 #endif
361                                         {
362                                                 error = EADDRINUSE;
363                                                 goto done;
364                                         }
365                                 }
366                         }
367                         if (cred && !prison_replace_wildcards(td, nam)) {
368                                 error = EADDRNOTAVAIL;
369                                 goto done;
370                         }
371                         t = in_pcblookup_local(pcbinfo, sin->sin_addr, lport,
372                                                wild, cred);
373                         if (t && !(reuseport & t->inp_socket->so_options)) {
374 #ifdef INET6
375                                 if (!in_nullhost(sin->sin_addr) ||
376                                     !in_nullhost(t->inp_laddr) ||
377                                     INP_SOCKAF(so) == INP_SOCKAF(t->inp_socket))
378 #endif
379                                 {
380                                         error = EADDRINUSE;
381                                         goto done;
382                                 }
383                         }
384                 }
385                 inp->inp_laddr = sin->sin_addr;
386         }
387         if (lport == 0) {
388                 ushort first, last;
389                 int count;
390
391                 jsin.sin_family = AF_INET;
392                 jsin.sin_addr.s_addr = inp->inp_laddr.s_addr;
393                 if (!prison_replace_wildcards(td, (struct sockaddr *)&jsin)) {
394                         inp->inp_laddr.s_addr = INADDR_ANY;
395                         error = EINVAL;
396                         goto done;
397                 }
398                 inp->inp_laddr.s_addr = jsin.sin_addr.s_addr;
399
400                 inp->inp_flags |= INP_ANONPORT;
401
402                 if (inp->inp_flags & INP_HIGHPORT) {
403                         first = ipport_hifirstauto;     /* sysctl */
404                         last  = ipport_hilastauto;
405                         lastport = &pcbinfo->lasthi;
406                 } else if (inp->inp_flags & INP_LOWPORT) {
407                         if (cred &&
408                             (error = priv_check_cred(cred, PRIV_NETINET_RESERVEDPORT, 0))) {
409                                 inp->inp_laddr.s_addr = INADDR_ANY;
410                                 goto done;
411                         }
412                         first = ipport_lowfirstauto;    /* 1023 */
413                         last  = ipport_lowlastauto;     /* 600 */
414                         lastport = &pcbinfo->lastlow;
415                 } else {
416                         first = ipport_firstauto;       /* sysctl */
417                         last  = ipport_lastauto;
418                         lastport = &pcbinfo->lastport;
419                 }
420                 /*
421                  * Simple check to ensure all ports are not used up causing
422                  * a deadlock here.
423                  *
424                  * We split the two cases (up and down) so that the direction
425                  * is not being tested on each round of the loop.
426                  */
427                 if (first > last) {
428                         /*
429                          * counting down
430                          */
431                         count = first - last;
432
433                         do {
434                                 if (count-- < 0) {      /* completely used? */
435                                         inp->inp_laddr.s_addr = INADDR_ANY;
436                                         error = EADDRNOTAVAIL;
437                                         goto done;
438                                 }
439                                 --*lastport;
440                                 if (*lastport > first || *lastport < last)
441                                         *lastport = first;
442                                 lport = htons(*lastport);
443                         } while (in_pcblookup_local(pcbinfo, inp->inp_laddr,
444                                                     lport, wild, cred));
445                 } else {
446                         /*
447                          * counting up
448                          */
449                         count = last - first;
450
451                         do {
452                                 if (count-- < 0) {      /* completely used? */
453                                         inp->inp_laddr.s_addr = INADDR_ANY;
454                                         error = EADDRNOTAVAIL;
455                                         goto done;
456                                 }
457                                 ++*lastport;
458                                 if (*lastport < first || *lastport > last)
459                                         *lastport = first;
460                                 lport = htons(*lastport);
461                         } while (in_pcblookup_local(pcbinfo, inp->inp_laddr,
462                                                     lport, wild, cred));
463                 }
464         }
465         inp->inp_lport = lport;
466
467         jsin.sin_family = AF_INET;
468         jsin.sin_addr.s_addr = inp->inp_laddr.s_addr;
469         if (!prison_replace_wildcards(td, (struct sockaddr*)&jsin)) {
470                 inp->inp_laddr.s_addr = INADDR_ANY;
471                 inp->inp_lport = 0;
472                 error = EINVAL;
473                 goto done;
474         }
475         inp->inp_laddr.s_addr = jsin.sin_addr.s_addr;
476
477         if (in_pcbinsporthash(inp) != 0) {
478                 inp->inp_laddr.s_addr = INADDR_ANY;
479                 inp->inp_lport = 0;
480                 error = EAGAIN;
481                 goto done;
482         }
483         error = 0;
484 done:
485         if (pcbinfo->porttoken)
486                 lwkt_reltoken(pcbinfo->porttoken);
487         return error;
488 }
489
490 /*
491  *   Transform old in_pcbconnect() into an inner subroutine for new
492  *   in_pcbconnect(): Do some validity-checking on the remote
493  *   address (in mbuf 'nam') and then determine local host address
494  *   (i.e., which interface) to use to access that remote host.
495  *
496  *   This preserves definition of in_pcbconnect(), while supporting a
497  *   slightly different version for T/TCP.  (This is more than
498  *   a bit of a kludge, but cleaning up the internal interfaces would
499  *   have forced minor changes in every protocol).
500  */
501 int
502 in_pcbladdr(struct inpcb *inp, struct sockaddr *nam,
503         struct sockaddr_in **plocal_sin, struct thread *td)
504 {
505         struct in_ifaddr *ia;
506         struct ucred *cred = NULL;
507         struct sockaddr_in *sin = (struct sockaddr_in *)nam;
508         struct sockaddr *jsin;
509         int jailed = 0, alloc_route = 0;
510
511         if (nam->sa_len != sizeof *sin)
512                 return (EINVAL);
513         if (sin->sin_family != AF_INET)
514                 return (EAFNOSUPPORT);
515         if (sin->sin_port == 0)
516                 return (EADDRNOTAVAIL);
517         if (td && td->td_proc && td->td_proc->p_ucred)
518                 cred = td->td_proc->p_ucred;
519         if (cred && cred->cr_prison)
520                 jailed = 1;
521         if (!TAILQ_EMPTY(&in_ifaddrheads[mycpuid])) {
522                 ia = TAILQ_FIRST(&in_ifaddrheads[mycpuid])->ia;
523                 /*
524                  * If the destination address is INADDR_ANY,
525                  * use the primary local address.
526                  * If the supplied address is INADDR_BROADCAST,
527                  * and the primary interface supports broadcast,
528                  * choose the broadcast address for that interface.
529                  */
530                 if (sin->sin_addr.s_addr == INADDR_ANY)
531                         sin->sin_addr = IA_SIN(ia)->sin_addr;
532                 else if (sin->sin_addr.s_addr == (u_long)INADDR_BROADCAST &&
533                     (ia->ia_ifp->if_flags & IFF_BROADCAST))
534                         sin->sin_addr = satosin(&ia->ia_broadaddr)->sin_addr;
535         }
536         if (inp->inp_laddr.s_addr == INADDR_ANY) {
537                 struct route *ro;
538
539                 ia = NULL;
540                 /*
541                  * If route is known or can be allocated now,
542                  * our src addr is taken from the i/f, else punt.
543                  * Note that we should check the address family of the cached
544                  * destination, in case of sharing the cache with IPv6.
545                  */
546                 ro = &inp->inp_route;
547                 if (ro->ro_rt &&
548                     (!(ro->ro_rt->rt_flags & RTF_UP) ||
549                      ro->ro_dst.sa_family != AF_INET ||
550                      satosin(&ro->ro_dst)->sin_addr.s_addr !=
551                                       sin->sin_addr.s_addr ||
552                      inp->inp_socket->so_options & SO_DONTROUTE)) {
553                         RTFREE(ro->ro_rt);
554                         ro->ro_rt = NULL;
555                 }
556                 if (!(inp->inp_socket->so_options & SO_DONTROUTE) && /*XXX*/
557                     (ro->ro_rt == NULL ||
558                     ro->ro_rt->rt_ifp == NULL)) {
559                         /* No route yet, so try to acquire one */
560                         bzero(&ro->ro_dst, sizeof(struct sockaddr_in));
561                         ro->ro_dst.sa_family = AF_INET;
562                         ro->ro_dst.sa_len = sizeof(struct sockaddr_in);
563                         ((struct sockaddr_in *) &ro->ro_dst)->sin_addr =
564                                 sin->sin_addr;
565                         rtalloc(ro);
566                         alloc_route = 1;
567                 }
568                 /*
569                  * If we found a route, use the address
570                  * corresponding to the outgoing interface
571                  * unless it is the loopback (in case a route
572                  * to our address on another net goes to loopback).
573                  */
574                 if (ro->ro_rt && !(ro->ro_rt->rt_ifp->if_flags & IFF_LOOPBACK)) {
575                         if (jailed) {
576                                 if (jailed_ip(cred->cr_prison, 
577                                     ro->ro_rt->rt_ifa->ifa_addr)) {
578                                         ia = ifatoia(ro->ro_rt->rt_ifa);
579                                 }
580                         } else {
581                                 ia = ifatoia(ro->ro_rt->rt_ifa);
582                         }
583                 }
584                 if (ia == NULL) {
585                         u_short fport = sin->sin_port;
586
587                         sin->sin_port = 0;
588                         ia = ifatoia(ifa_ifwithdstaddr(sintosa(sin)));
589                         if (ia && jailed && !jailed_ip(cred->cr_prison,
590                             sintosa(&ia->ia_addr)))
591                                 ia = NULL;
592                         if (ia == NULL)
593                                 ia = ifatoia(ifa_ifwithnet(sintosa(sin)));
594                         if (ia && jailed && !jailed_ip(cred->cr_prison,
595                             sintosa(&ia->ia_addr)))
596                                 ia = NULL;
597                         sin->sin_port = fport;
598                         if (ia == NULL &&
599                             !TAILQ_EMPTY(&in_ifaddrheads[mycpuid]))
600                                 ia = TAILQ_FIRST(&in_ifaddrheads[mycpuid])->ia;
601                         if (ia && jailed && !jailed_ip(cred->cr_prison,
602                             sintosa(&ia->ia_addr)))
603                                 ia = NULL;
604
605                         if (!jailed && ia == NULL)
606                                 goto fail;
607                 }
608                 /*
609                  * If the destination address is multicast and an outgoing
610                  * interface has been set as a multicast option, use the
611                  * address of that interface as our source address.
612                  */
613                 if (!jailed && IN_MULTICAST(ntohl(sin->sin_addr.s_addr)) &&
614                     inp->inp_moptions != NULL) {
615                         struct ip_moptions *imo;
616                         struct ifnet *ifp;
617
618                         imo = inp->inp_moptions;
619                         if (imo->imo_multicast_ifp != NULL) {
620                                 struct in_ifaddr_container *iac;
621
622                                 ifp = imo->imo_multicast_ifp;
623                                 ia = NULL;
624                                 TAILQ_FOREACH(iac,
625                                 &in_ifaddrheads[mycpuid], ia_link) {
626                                         if (iac->ia->ia_ifp == ifp) {
627                                                 ia = iac->ia;
628                                                 break;
629                                         }
630                                 }
631                                 if (ia == NULL)
632                                         goto fail;
633                         }
634                 }
635                 /*
636                  * Don't do pcblookup call here; return interface in plocal_sin
637                  * and exit to caller, that will do the lookup.
638                  */
639                 if (ia == NULL && jailed) {
640                         if ((jsin = prison_get_nonlocal(cred->cr_prison, AF_INET, NULL)) != NULL ||
641                             (jsin = prison_get_local(cred->cr_prison, AF_INET, NULL)) != NULL) {
642                                 *plocal_sin = satosin(jsin);
643                         } else {
644                                 /* IPv6 only Jail */
645                                 goto fail;
646                         }
647                 } else {
648                         *plocal_sin = &ia->ia_addr;
649                 }
650         }
651         return (0);
652 fail:
653         if (alloc_route) {
654                 struct route *ro = &inp->inp_route;
655
656                 if (ro->ro_rt != NULL)
657                         RTFREE(ro->ro_rt);
658                 bzero(ro, sizeof(*ro));
659         }
660         return (EADDRNOTAVAIL);
661 }
662
663 /*
664  * Outer subroutine:
665  * Connect from a socket to a specified address.
666  * Both address and port must be specified in argument sin.
667  * If don't have a local address for this socket yet,
668  * then pick one.
669  */
670 int
671 in_pcbconnect(struct inpcb *inp, struct sockaddr *nam, struct thread *td)
672 {
673         struct sockaddr_in *if_sin;
674         struct sockaddr_in *sin = (struct sockaddr_in *)nam;
675         int error;
676
677         /* Call inner routine to assign local interface address. */
678         if ((error = in_pcbladdr(inp, nam, &if_sin, td)) != 0)
679                 return (error);
680
681         if (in_pcblookup_hash(inp->inp_cpcbinfo, sin->sin_addr, sin->sin_port,
682                               inp->inp_laddr.s_addr ?
683                                 inp->inp_laddr : if_sin->sin_addr,
684                               inp->inp_lport, FALSE, NULL) != NULL) {
685                 return (EADDRINUSE);
686         }
687         if (inp->inp_laddr.s_addr == INADDR_ANY) {
688                 if (inp->inp_lport == 0) {
689                         error = in_pcbbind(inp, NULL, td);
690                         if (error)
691                                 return (error);
692                 }
693                 inp->inp_laddr = if_sin->sin_addr;
694         }
695         inp->inp_faddr = sin->sin_addr;
696         inp->inp_fport = sin->sin_port;
697         in_pcbinsconnhash(inp);
698         return (0);
699 }
700
701 void
702 in_pcbdisconnect(struct inpcb *inp)
703 {
704
705         inp->inp_faddr.s_addr = INADDR_ANY;
706         inp->inp_fport = 0;
707         in_pcbremconnhash(inp);
708         if (inp->inp_socket->so_state & SS_NOFDREF)
709                 in_pcbdetach(inp);
710 }
711
712 void
713 in_pcbdetach(struct inpcb *inp)
714 {
715         struct socket *so = inp->inp_socket;
716         struct inpcbinfo *ipi = inp->inp_pcbinfo;
717
718 #ifdef IPSEC
719         ipsec4_delete_pcbpolicy(inp);
720 #endif /*IPSEC*/
721         inp->inp_gencnt = ++ipi->ipi_gencnt;
722         KKASSERT((so->so_state & SS_ASSERTINPROG) == 0);
723         in_pcbremlists(inp);
724         so->so_pcb = NULL;
725         sofree(so);                     /* remove pcb ref */
726         if (inp->inp_options)
727                 m_free(inp->inp_options);
728         if (inp->inp_route.ro_rt)
729                 rtfree(inp->inp_route.ro_rt);
730         ip_freemoptions(inp->inp_moptions);
731         inp->inp_vflag = 0;
732         kfree(inp, M_PCB);
733 }
734
735 /*
736  * The calling convention of in_setsockaddr() and in_setpeeraddr() was
737  * modified to match the pru_sockaddr() and pru_peeraddr() entry points
738  * in struct pr_usrreqs, so that protocols can just reference then directly
739  * without the need for a wrapper function.  The socket must have a valid
740  * (i.e., non-nil) PCB, but it should be impossible to get an invalid one
741  * except through a kernel programming error, so it is acceptable to panic
742  * (or in this case trap) if the PCB is invalid.  (Actually, we don't trap
743  * because there actually /is/ a programming error somewhere... XXX)
744  */
745 int
746 in_setsockaddr(struct socket *so, struct sockaddr **nam)
747 {
748         struct inpcb *inp;
749         struct sockaddr_in *sin;
750
751         /*
752          * Do the malloc first in case it blocks.
753          */
754         MALLOC(sin, struct sockaddr_in *, sizeof *sin, M_SONAME,
755                 M_WAITOK | M_ZERO);
756         sin->sin_family = AF_INET;
757         sin->sin_len = sizeof *sin;
758
759         crit_enter();
760         inp = so->so_pcb;
761         if (!inp) {
762                 crit_exit();
763                 kfree(sin, M_SONAME);
764                 return (ECONNRESET);
765         }
766         sin->sin_port = inp->inp_lport;
767         sin->sin_addr = inp->inp_laddr;
768         crit_exit();
769
770         *nam = (struct sockaddr *)sin;
771         return (0);
772 }
773
774 void
775 in_setsockaddr_dispatch(netmsg_t msg)
776 {
777         int error;
778
779         error = in_setsockaddr(msg->base.nm_so, msg->peeraddr.nm_nam);
780         lwkt_replymsg(&msg->lmsg, error);
781 }
782
783 int
784 in_setpeeraddr(struct socket *so, struct sockaddr **nam)
785 {
786         struct inpcb *inp;
787         struct sockaddr_in *sin;
788
789         /*
790          * Do the malloc first in case it blocks.
791          */
792         MALLOC(sin, struct sockaddr_in *, sizeof *sin, M_SONAME,
793                 M_WAITOK | M_ZERO);
794         sin->sin_family = AF_INET;
795         sin->sin_len = sizeof *sin;
796
797         crit_enter();
798         inp = so->so_pcb;
799         if (!inp) {
800                 crit_exit();
801                 kfree(sin, M_SONAME);
802                 return (ECONNRESET);
803         }
804         sin->sin_port = inp->inp_fport;
805         sin->sin_addr = inp->inp_faddr;
806         crit_exit();
807
808         *nam = (struct sockaddr *)sin;
809         return (0);
810 }
811
812 void
813 in_setpeeraddr_dispatch(netmsg_t msg)
814 {
815         int error;
816
817         error = in_setpeeraddr(msg->base.nm_so, msg->peeraddr.nm_nam);
818         lwkt_replymsg(&msg->lmsg, error);
819 }
820
821 void
822 in_pcbnotifyall(struct inpcbhead *head, struct in_addr faddr, int err,
823                 void (*notify)(struct inpcb *, int))
824 {
825         struct inpcb *inp, *ninp;
826
827         /*
828          * note: if INP_PLACEMARKER is set we must ignore the rest of
829          * the structure and skip it.
830          */
831         crit_enter();
832         LIST_FOREACH_MUTABLE(inp, head, inp_list, ninp) {
833                 if (inp->inp_flags & INP_PLACEMARKER)
834                         continue;
835 #ifdef INET6
836                 if (!(inp->inp_vflag & INP_IPV4))
837                         continue;
838 #endif
839                 if (inp->inp_faddr.s_addr != faddr.s_addr ||
840                     inp->inp_socket == NULL)
841                         continue;
842                 (*notify)(inp, err);            /* can remove inp from list! */
843         }
844         crit_exit();
845 }
846
847 void
848 in_pcbpurgeif0(struct inpcb *head, struct ifnet *ifp)
849 {
850         struct inpcb *inp;
851         struct ip_moptions *imo;
852         int i, gap;
853
854         for (inp = head; inp != NULL; inp = LIST_NEXT(inp, inp_list)) {
855                 if (inp->inp_flags & INP_PLACEMARKER)
856                         continue;
857                 imo = inp->inp_moptions;
858                 if ((inp->inp_vflag & INP_IPV4) && imo != NULL) {
859                         /*
860                          * Unselect the outgoing interface if it is being
861                          * detached.
862                          */
863                         if (imo->imo_multicast_ifp == ifp)
864                                 imo->imo_multicast_ifp = NULL;
865
866                         /*
867                          * Drop multicast group membership if we joined
868                          * through the interface being detached.
869                          */
870                         for (i = 0, gap = 0; i < imo->imo_num_memberships;
871                             i++) {
872                                 if (imo->imo_membership[i]->inm_ifp == ifp) {
873                                         in_delmulti(imo->imo_membership[i]);
874                                         gap++;
875                                 } else if (gap != 0)
876                                         imo->imo_membership[i - gap] =
877                                             imo->imo_membership[i];
878                         }
879                         imo->imo_num_memberships -= gap;
880                 }
881         }
882 }
883
884 /*
885  * Check for alternatives when higher level complains
886  * about service problems.  For now, invalidate cached
887  * routing information.  If the route was created dynamically
888  * (by a redirect), time to try a default gateway again.
889  */
890 void
891 in_losing(struct inpcb *inp)
892 {
893         struct rtentry *rt;
894         struct rt_addrinfo rtinfo;
895
896         if ((rt = inp->inp_route.ro_rt)) {
897                 bzero(&rtinfo, sizeof(struct rt_addrinfo));
898                 rtinfo.rti_info[RTAX_DST] = rt_key(rt);
899                 rtinfo.rti_info[RTAX_GATEWAY] = rt->rt_gateway;
900                 rtinfo.rti_info[RTAX_NETMASK] = rt_mask(rt);
901                 rtinfo.rti_flags = rt->rt_flags;
902                 rt_missmsg(RTM_LOSING, &rtinfo, rt->rt_flags, 0);
903                 if (rt->rt_flags & RTF_DYNAMIC)
904                         rtrequest1_global(RTM_DELETE, &rtinfo, NULL, NULL);
905                 inp->inp_route.ro_rt = NULL;
906                 rtfree(rt);
907                 /*
908                  * A new route can be allocated
909                  * the next time output is attempted.
910                  */
911         }
912 }
913
914 /*
915  * After a routing change, flush old routing
916  * and allocate a (hopefully) better one.
917  */
918 void
919 in_rtchange(struct inpcb *inp, int err)
920 {
921         if (inp->inp_route.ro_rt) {
922                 rtfree(inp->inp_route.ro_rt);
923                 inp->inp_route.ro_rt = NULL;
924                 /*
925                  * A new route can be allocated the next time
926                  * output is attempted.
927                  */
928         }
929 }
930
931 /*
932  * Lookup a PCB based on the local address and port.
933  */
934 struct inpcb *
935 in_pcblookup_local(struct inpcbinfo *pcbinfo, struct in_addr laddr,
936                    u_int lport_arg, int wild_okay, struct ucred *cred)
937 {
938         struct inpcb *inp;
939         int matchwild = 3, wildcard;
940         u_short lport = lport_arg;
941         struct inpcbporthead *porthash;
942         struct inpcbport *phd;
943         struct inpcb *match = NULL;
944
945         /*
946          * If the porthashbase is shared across several cpus we need
947          * to lock.
948          */
949         if (pcbinfo->porttoken)
950                 lwkt_gettoken(pcbinfo->porttoken);
951
952         /*
953          * Best fit PCB lookup.
954          *
955          * First see if this local port is in use by looking on the
956          * port hash list.
957          */
958         porthash = &pcbinfo->porthashbase[
959                         INP_PCBPORTHASH(lport, pcbinfo->porthashmask)];
960         LIST_FOREACH(phd, porthash, phd_hash) {
961                 if (phd->phd_port == lport)
962                         break;
963         }
964         if (phd != NULL) {
965                 /*
966                  * Port is in use by one or more PCBs. Look for best
967                  * fit.
968                  */
969                 LIST_FOREACH(inp, &phd->phd_pcblist, inp_portlist) {
970                         wildcard = 0;
971 #ifdef INET6
972                         if ((inp->inp_vflag & INP_IPV4) == 0)
973                                 continue;
974 #endif
975                         if (inp->inp_faddr.s_addr != INADDR_ANY)
976                                 wildcard++;
977                         if (inp->inp_laddr.s_addr != INADDR_ANY) {
978                                 if (laddr.s_addr == INADDR_ANY)
979                                         wildcard++;
980                                 else if (inp->inp_laddr.s_addr != laddr.s_addr)
981                                         continue;
982                         } else {
983                                 if (laddr.s_addr != INADDR_ANY)
984                                         wildcard++;
985                         }
986                         if (wildcard && !wild_okay)
987                                 continue;
988                         if (wildcard < matchwild &&
989                             (cred == NULL ||
990                              cred->cr_prison == 
991                                         inp->inp_socket->so_cred->cr_prison)) {
992                                 match = inp;
993                                 matchwild = wildcard;
994                                 if (matchwild == 0) {
995                                         break;
996                                 }
997                         }
998                 }
999         }
1000         if (pcbinfo->porttoken)
1001                 lwkt_reltoken(pcbinfo->porttoken);
1002         return (match);
1003 }
1004
1005 /*
1006  * Lookup PCB in hash list.
1007  */
1008 struct inpcb *
1009 in_pcblookup_hash(struct inpcbinfo *pcbinfo, struct in_addr faddr,
1010                   u_int fport_arg, struct in_addr laddr, u_int lport_arg,
1011                   boolean_t wildcard, struct ifnet *ifp)
1012 {
1013         struct inpcbhead *head;
1014         struct inpcb *inp, *jinp=NULL;
1015         u_short fport = fport_arg, lport = lport_arg;
1016
1017         /*
1018          * First look for an exact match.
1019          */
1020         head = &pcbinfo->hashbase[INP_PCBCONNHASH(faddr.s_addr, fport,
1021             laddr.s_addr, lport, pcbinfo->hashmask)];
1022         LIST_FOREACH(inp, head, inp_hash) {
1023 #ifdef INET6
1024                 if (!(inp->inp_vflag & INP_IPV4))
1025                         continue;
1026 #endif
1027                 if (in_hosteq(inp->inp_faddr, faddr) &&
1028                     in_hosteq(inp->inp_laddr, laddr) &&
1029                     inp->inp_fport == fport && inp->inp_lport == lport) {
1030                         /* found */
1031                         if (inp->inp_socket == NULL ||
1032                             inp->inp_socket->so_cred->cr_prison == NULL) {
1033                                 return (inp);
1034                         } else {
1035                                 if  (jinp == NULL)
1036                                         jinp = inp;
1037                         }
1038                 }
1039         }
1040         if (jinp != NULL)
1041                 return (jinp);
1042         if (wildcard) {
1043                 struct inpcb *local_wild = NULL;
1044                 struct inpcb *jinp_wild = NULL;
1045 #ifdef INET6
1046                 struct inpcb *local_wild_mapped = NULL;
1047 #endif
1048                 struct inpcontainer *ic;
1049                 struct inpcontainerhead *chead;
1050                 struct sockaddr_in jsin;
1051                 struct ucred *cred;
1052
1053                 /*
1054                  * Order of socket selection:
1055                  * 1. non-jailed, non-wild.
1056                  * 2. non-jailed, wild.
1057                  * 3. jailed, non-wild.
1058                  * 4. jailed, wild.
1059                  */
1060                 jsin.sin_family = AF_INET;
1061                 chead = &pcbinfo->wildcardhashbase[
1062                     INP_PCBWILDCARDHASH(lport, pcbinfo->wildcardhashmask)];
1063                 LIST_FOREACH(ic, chead, ic_list) {
1064                         inp = ic->ic_inp;
1065                         jsin.sin_addr.s_addr = laddr.s_addr;
1066 #ifdef INET6
1067                         if (!(inp->inp_vflag & INP_IPV4))
1068                                 continue;
1069 #endif
1070                         if (inp->inp_socket != NULL)
1071                                 cred = inp->inp_socket->so_cred;
1072                         else
1073                                 cred = NULL;
1074                         if (cred != NULL && jailed(cred)) {
1075                                 if (jinp != NULL)
1076                                         continue;
1077                                 else
1078                                         if (!jailed_ip(cred->cr_prison,
1079                                             (struct sockaddr *)&jsin))
1080                                                 continue;
1081                         }
1082                         if (inp->inp_lport == lport) {
1083                                 if (ifp && ifp->if_type == IFT_FAITH &&
1084                                     !(inp->inp_flags & INP_FAITH))
1085                                         continue;
1086                                 if (inp->inp_laddr.s_addr == laddr.s_addr) {
1087                                         if (cred != NULL && jailed(cred))
1088                                                 jinp = inp;
1089                                         else
1090                                                 return (inp);
1091                                 }
1092                                 if (inp->inp_laddr.s_addr == INADDR_ANY) {
1093 #ifdef INET6
1094                                         if (INP_CHECK_SOCKAF(inp->inp_socket,
1095                                                              AF_INET6))
1096                                                 local_wild_mapped = inp;
1097                                         else
1098 #endif
1099                                                 if (cred != NULL &&
1100                                                     jailed(cred))
1101                                                         jinp_wild = inp;
1102                                                 else
1103                                                         local_wild = inp;
1104                                 }
1105                         }
1106                 }
1107                 if (local_wild != NULL)
1108                         return (local_wild);
1109 #ifdef INET6
1110                 if (local_wild_mapped != NULL)
1111                         return (local_wild_mapped);
1112 #endif
1113                 if (jinp != NULL)
1114                         return (jinp);
1115                 return (jinp_wild);
1116         }
1117
1118         /*
1119          * Not found.
1120          */
1121         return (NULL);
1122 }
1123
1124 /*
1125  * Insert PCB into connection hash table.
1126  */
1127 void
1128 in_pcbinsconnhash(struct inpcb *inp)
1129 {
1130         struct inpcbinfo *pcbinfo = inp->inp_cpcbinfo;
1131         struct inpcbhead *bucket;
1132         u_int32_t hashkey_faddr, hashkey_laddr;
1133
1134 #ifdef INET6
1135         if (inp->inp_vflag & INP_IPV6) {
1136                 hashkey_faddr = inp->in6p_faddr.s6_addr32[3] /* XXX JH */;
1137                 hashkey_laddr = inp->in6p_laddr.s6_addr32[3] /* XXX JH */;
1138         } else {
1139 #endif
1140                 hashkey_faddr = inp->inp_faddr.s_addr;
1141                 hashkey_laddr = inp->inp_laddr.s_addr;
1142 #ifdef INET6
1143         }
1144 #endif
1145
1146         KASSERT(!(inp->inp_flags & INP_CONNECTED), ("already on hash list"));
1147         inp->inp_flags |= INP_CONNECTED;
1148
1149         /*
1150          * Insert into the connection hash table.
1151          */
1152         bucket = &pcbinfo->hashbase[INP_PCBCONNHASH(hashkey_faddr,
1153             inp->inp_fport, hashkey_laddr, inp->inp_lport, pcbinfo->hashmask)];
1154         LIST_INSERT_HEAD(bucket, inp, inp_hash);
1155 }
1156
1157 /*
1158  * Remove PCB from connection hash table.
1159  */
1160 void
1161 in_pcbremconnhash(struct inpcb *inp)
1162 {
1163         KASSERT(inp->inp_flags & INP_CONNECTED, ("inp not connected"));
1164         LIST_REMOVE(inp, inp_hash);
1165         inp->inp_flags &= ~INP_CONNECTED;
1166 }
1167
1168 /*
1169  * Insert PCB into port hash table.
1170  */
1171 int
1172 in_pcbinsporthash(struct inpcb *inp)
1173 {
1174         struct inpcbinfo *pcbinfo = inp->inp_pcbinfo;
1175         struct inpcbporthead *pcbporthash;
1176         struct inpcbport *phd;
1177
1178         /*
1179          * If the porthashbase is shared across several cpus we need
1180          * to lock.
1181          */
1182         if (pcbinfo->porttoken)
1183                 lwkt_gettoken(pcbinfo->porttoken);
1184
1185         /*
1186          * Insert into the port hash table.
1187          */
1188         pcbporthash = &pcbinfo->porthashbase[
1189             INP_PCBPORTHASH(inp->inp_lport, pcbinfo->porthashmask)];
1190
1191         /* Go through port list and look for a head for this lport. */
1192         LIST_FOREACH(phd, pcbporthash, phd_hash) {
1193                 if (phd->phd_port == inp->inp_lport)
1194                         break;
1195         }
1196
1197         /* If none exists, malloc one and tack it on. */
1198         if (phd == NULL) {
1199                 KKASSERT(pcbinfo->portsave != NULL);
1200                 phd = pcbinfo->portsave;
1201                 pcbinfo->portsave = NULL;
1202                 phd->phd_port = inp->inp_lport;
1203                 LIST_INIT(&phd->phd_pcblist);
1204                 LIST_INSERT_HEAD(pcbporthash, phd, phd_hash);
1205         }
1206
1207         inp->inp_phd = phd;
1208         LIST_INSERT_HEAD(&phd->phd_pcblist, inp, inp_portlist);
1209
1210         if (pcbinfo->porttoken)
1211                 lwkt_reltoken(pcbinfo->porttoken);
1212         if (pcbinfo->portsave == NULL) {
1213                 pcbinfo->portsave = kmalloc(sizeof(*pcbinfo->portsave),
1214                                             M_PCB, M_INTWAIT | M_ZERO);
1215         }
1216         return (0);
1217 }
1218
1219 void
1220 in_pcbinswildcardhash_oncpu(struct inpcb *inp, struct inpcbinfo *pcbinfo)
1221 {
1222         struct inpcontainer *ic;
1223         struct inpcontainerhead *bucket;
1224
1225         bucket = &pcbinfo->wildcardhashbase[
1226             INP_PCBWILDCARDHASH(inp->inp_lport, pcbinfo->wildcardhashmask)];
1227
1228         ic = kmalloc(sizeof(struct inpcontainer), M_TEMP, M_INTWAIT);
1229         ic->ic_inp = inp;
1230         LIST_INSERT_HEAD(bucket, ic, ic_list);
1231 }
1232
1233 /*
1234  * Insert PCB into wildcard hash table.
1235  */
1236 void
1237 in_pcbinswildcardhash(struct inpcb *inp)
1238 {
1239         struct inpcbinfo *pcbinfo = inp->inp_pcbinfo;
1240         
1241         KKASSERT(pcbinfo != NULL);
1242
1243         in_pcbinswildcardhash_oncpu(inp, pcbinfo);
1244         inp->inp_flags |= INP_WILDCARD;
1245 }
1246
1247 void
1248 in_pcbremwildcardhash_oncpu(struct inpcb *inp, struct inpcbinfo *pcbinfo)
1249 {
1250         struct inpcontainer *ic;
1251         struct inpcontainerhead *head;
1252
1253         /* find bucket */
1254         head = &pcbinfo->wildcardhashbase[
1255             INP_PCBWILDCARDHASH(inp->inp_lport, pcbinfo->wildcardhashmask)];
1256
1257         LIST_FOREACH(ic, head, ic_list) {
1258                 if (ic->ic_inp == inp)
1259                         goto found;
1260         }
1261         return;                 /* not found! */
1262
1263 found:
1264         LIST_REMOVE(ic, ic_list);       /* remove container from bucket chain */
1265         kfree(ic, M_TEMP);              /* deallocate container */
1266 }
1267
1268 /*
1269  * Remove PCB from wildcard hash table.
1270  */
1271 void
1272 in_pcbremwildcardhash(struct inpcb *inp)
1273 {
1274         struct inpcbinfo *pcbinfo = inp->inp_pcbinfo;
1275
1276         KASSERT(inp->inp_flags & INP_WILDCARD, ("inp not wildcard"));
1277         in_pcbremwildcardhash_oncpu(inp, pcbinfo);
1278         inp->inp_flags &= ~INP_WILDCARD;
1279 }
1280
1281 /*
1282  * Remove PCB from various lists.
1283  */
1284 void
1285 in_pcbremlists(struct inpcb *inp)
1286 {
1287         struct inpcbinfo *pcbinfo;
1288
1289         if (inp->inp_lport) {
1290                 struct inpcbport *phd;
1291
1292                 pcbinfo = inp->inp_pcbinfo;
1293                 if (pcbinfo->porttoken)
1294                         lwkt_gettoken(pcbinfo->porttoken);
1295
1296                 phd = inp->inp_phd;
1297                 LIST_REMOVE(inp, inp_portlist);
1298                 if (LIST_FIRST(&phd->phd_pcblist) == NULL) {
1299                         LIST_REMOVE(phd, phd_hash);
1300                         kfree(phd, M_PCB);
1301                 }
1302                 if (pcbinfo->porttoken)
1303                         lwkt_reltoken(pcbinfo->porttoken);
1304         }
1305         if (inp->inp_flags & INP_WILDCARD) {
1306                 in_pcbremwildcardhash(inp);
1307         } else if (inp->inp_flags & INP_CONNECTED) {
1308                 in_pcbremconnhash(inp);
1309         }
1310         LIST_REMOVE(inp, inp_list);
1311         inp->inp_pcbinfo->ipi_count--;
1312 }
1313
1314 int
1315 prison_xinpcb(struct thread *td, struct inpcb *inp)
1316 {
1317         struct ucred *cr;
1318
1319         if (td->td_proc == NULL)
1320                 return (0);
1321         cr = td->td_proc->p_ucred;
1322         if (cr->cr_prison == NULL)
1323                 return (0);
1324         if (inp->inp_socket && inp->inp_socket->so_cred &&
1325             inp->inp_socket->so_cred->cr_prison &&
1326             cr->cr_prison == inp->inp_socket->so_cred->cr_prison)
1327                 return (0);
1328         return (1);
1329 }
1330
1331 int
1332 in_pcblist_global(SYSCTL_HANDLER_ARGS)
1333 {
1334         struct inpcbinfo *pcbinfo = arg1;
1335         struct inpcb *inp, *marker;
1336         struct xinpcb xi;
1337         int error, i, n;
1338         inp_gen_t gencnt;
1339
1340         /*
1341          * The process of preparing the TCB list is too time-consuming and
1342          * resource-intensive to repeat twice on every request.
1343          */
1344         if (req->oldptr == NULL) {
1345                 n = pcbinfo->ipi_count;
1346                 req->oldidx = (n + n/8 + 10) * sizeof(struct xinpcb);
1347                 return 0;
1348         }
1349
1350         if (req->newptr != NULL)
1351                 return EPERM;
1352
1353         /*
1354          * OK, now we're committed to doing something.  Re-fetch ipi_count
1355          * after obtaining the generation count.
1356          */
1357         gencnt = pcbinfo->ipi_gencnt;
1358         n = pcbinfo->ipi_count;
1359
1360         marker = kmalloc(sizeof(struct inpcb), M_TEMP, M_WAITOK|M_ZERO);
1361         marker->inp_flags |= INP_PLACEMARKER;
1362         LIST_INSERT_HEAD(&pcbinfo->pcblisthead, marker, inp_list);
1363
1364         i = 0;
1365         error = 0;
1366
1367         while ((inp = LIST_NEXT(marker, inp_list)) != NULL && i < n) {
1368                 LIST_REMOVE(marker, inp_list);
1369                 LIST_INSERT_AFTER(inp, marker, inp_list);
1370
1371                 if (inp->inp_flags & INP_PLACEMARKER)
1372                         continue;
1373                 if (inp->inp_gencnt > gencnt)
1374                         continue;
1375                 if (prison_xinpcb(req->td, inp))
1376                         continue;
1377                 bzero(&xi, sizeof xi);
1378                 xi.xi_len = sizeof xi;
1379                 bcopy(inp, &xi.xi_inp, sizeof *inp);
1380                 if (inp->inp_socket)
1381                         sotoxsocket(inp->inp_socket, &xi.xi_socket);
1382                 if ((error = SYSCTL_OUT(req, &xi, sizeof xi)) != 0)
1383                         break;
1384                 ++i;
1385         }
1386         LIST_REMOVE(marker, inp_list);
1387         if (error == 0 && i < n) {
1388                 bzero(&xi, sizeof xi);
1389                 xi.xi_len = sizeof xi;
1390                 while (i < n) {
1391                         error = SYSCTL_OUT(req, &xi, sizeof xi);
1392                         ++i;
1393                 }
1394         }
1395         kfree(marker, M_TEMP);
1396         return(error);
1397 }