in_pcbconn_bind: Remove duplicated prison_replace_wildcards()
[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. Neither the name of the University nor the names of its contributors
47  *    may be used to endorse or promote products derived from this software
48  *    without specific prior written permission.
49  *
50  * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
51  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
52  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
53  * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
54  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
55  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
56  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
57  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
58  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
59  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
60  * SUCH DAMAGE.
61  *
62  *      @(#)in_pcb.c    8.4 (Berkeley) 5/24/95
63  * $FreeBSD: src/sys/netinet/in_pcb.c,v 1.59.2.27 2004/01/02 04:06:42 ambrisko Exp $
64  */
65
66 #include "opt_ipsec.h"
67 #include "opt_inet6.h"
68
69 #include <sys/param.h>
70 #include <sys/systm.h>
71 #include <sys/malloc.h>
72 #include <sys/mbuf.h>
73 #include <sys/domain.h>
74 #include <sys/protosw.h>
75 #include <sys/socket.h>
76 #include <sys/socketvar.h>
77 #include <sys/proc.h>
78 #include <sys/priv.h>
79 #include <sys/jail.h>
80 #include <sys/kernel.h>
81 #include <sys/sysctl.h>
82
83 #include <sys/thread2.h>
84 #include <sys/socketvar2.h>
85 #include <sys/msgport2.h>
86
87 #include <machine/limits.h>
88
89 #include <net/if.h>
90 #include <net/if_types.h>
91 #include <net/route.h>
92
93 #include <netinet/in.h>
94 #include <netinet/in_pcb.h>
95 #include <netinet/in_var.h>
96 #include <netinet/ip_var.h>
97 #ifdef INET6
98 #include <netinet/ip6.h>
99 #include <netinet6/ip6_var.h>
100 #endif /* INET6 */
101
102 #ifdef IPSEC
103 #include <netinet6/ipsec.h>
104 #include <netproto/key/key.h>
105 #include <netproto/ipsec/esp_var.h>
106 #endif
107
108 #ifdef FAST_IPSEC
109 #if defined(IPSEC) || defined(IPSEC_ESP)
110 #error "Bad idea: don't compile with both IPSEC and FAST_IPSEC!"
111 #endif
112
113 #include <netproto/ipsec/ipsec.h>
114 #include <netproto/ipsec/key.h>
115 #define IPSEC
116 #endif /* FAST_IPSEC */
117
118 #define INP_LOCALGROUP_SIZMIN   8
119 #define INP_LOCALGROUP_SIZMAX   256
120
121 struct in_addr zeroin_addr;
122
123 /*
124  * These configure the range of local port addresses assigned to
125  * "unspecified" outgoing connections/packets/whatever.
126  */
127 int ipport_lowfirstauto = IPPORT_RESERVED - 1;  /* 1023 */
128 int ipport_lowlastauto = IPPORT_RESERVEDSTART;  /* 600 */
129
130 int ipport_firstauto = IPPORT_RESERVED;         /* 1024 */
131 int ipport_lastauto = IPPORT_USERRESERVED;      /* 5000 */
132
133 int ipport_hifirstauto = IPPORT_HIFIRSTAUTO;    /* 49152 */
134 int ipport_hilastauto = IPPORT_HILASTAUTO;      /* 65535 */
135
136 #define RANGECHK(var, min, max) \
137         if ((var) < (min)) { (var) = (min); } \
138         else if ((var) > (max)) { (var) = (max); }
139
140 int udpencap_enable = 1;        /* enabled by default */
141 int udpencap_port = 4500;       /* triggers decapsulation */
142
143 static int
144 sysctl_net_ipport_check(SYSCTL_HANDLER_ARGS)
145 {
146         int error;
147
148         error = sysctl_handle_int(oidp, oidp->oid_arg1, oidp->oid_arg2, req);
149         if (!error) {
150                 RANGECHK(ipport_lowfirstauto, 1, IPPORT_RESERVED - 1);
151                 RANGECHK(ipport_lowlastauto, 1, IPPORT_RESERVED - 1);
152
153                 RANGECHK(ipport_firstauto, IPPORT_RESERVED, USHRT_MAX);
154                 RANGECHK(ipport_lastauto, IPPORT_RESERVED, USHRT_MAX);
155
156                 RANGECHK(ipport_hifirstauto, IPPORT_RESERVED, USHRT_MAX);
157                 RANGECHK(ipport_hilastauto, IPPORT_RESERVED, USHRT_MAX);
158         }
159         return (error);
160 }
161
162 #undef RANGECHK
163
164 SYSCTL_NODE(_net_inet_ip, IPPROTO_IP, portrange, CTLFLAG_RW, 0, "IP Ports");
165
166 SYSCTL_PROC(_net_inet_ip_portrange, OID_AUTO, lowfirst, CTLTYPE_INT|CTLFLAG_RW,
167            &ipport_lowfirstauto, 0, &sysctl_net_ipport_check, "I", "");
168 SYSCTL_PROC(_net_inet_ip_portrange, OID_AUTO, lowlast, CTLTYPE_INT|CTLFLAG_RW,
169            &ipport_lowlastauto, 0, &sysctl_net_ipport_check, "I", "");
170 SYSCTL_PROC(_net_inet_ip_portrange, OID_AUTO, first, CTLTYPE_INT|CTLFLAG_RW,
171            &ipport_firstauto, 0, &sysctl_net_ipport_check, "I", "");
172 SYSCTL_PROC(_net_inet_ip_portrange, OID_AUTO, last, CTLTYPE_INT|CTLFLAG_RW,
173            &ipport_lastauto, 0, &sysctl_net_ipport_check, "I", "");
174 SYSCTL_PROC(_net_inet_ip_portrange, OID_AUTO, hifirst, CTLTYPE_INT|CTLFLAG_RW,
175            &ipport_hifirstauto, 0, &sysctl_net_ipport_check, "I", "");
176 SYSCTL_PROC(_net_inet_ip_portrange, OID_AUTO, hilast, CTLTYPE_INT|CTLFLAG_RW,
177            &ipport_hilastauto, 0, &sysctl_net_ipport_check, "I", "");
178
179 /*
180  * in_pcb.c: manage the Protocol Control Blocks.
181  *
182  * NOTE: It is assumed that most of these functions will be called from
183  * a critical section.  XXX - There are, unfortunately, a few exceptions
184  * to this rule that should be fixed.
185  *
186  * NOTE: The caller should initialize the cpu field to the cpu running the
187  * protocol stack associated with this inpcbinfo.
188  */
189
190 void
191 in_pcbinfo_init(struct inpcbinfo *pcbinfo)
192 {
193         LIST_INIT(&pcbinfo->pcblisthead);
194         pcbinfo->cpu = -1;
195         pcbinfo->portsave = kmalloc(sizeof(*pcbinfo->portsave), M_PCB,
196                                     M_WAITOK | M_ZERO);
197 }
198
199 struct baddynamicports baddynamicports;
200
201 /*
202  * Check if the specified port is invalid for dynamic allocation.
203  */
204 int
205 in_baddynamic(u_int16_t port, u_int16_t proto)
206 {
207         switch (proto) {
208         case IPPROTO_TCP:
209                 return (DP_ISSET(baddynamicports.tcp, port));
210         case IPPROTO_UDP:
211 #ifdef IPSEC
212                 /* Cannot preset this as it is a sysctl */
213                 if (port == udpencap_port)
214                         return (1);
215 #endif
216                 return (DP_ISSET(baddynamicports.udp, port));
217         default:
218                 return (0);
219         }
220 }
221
222
223 /*
224  * Allocate a PCB and associate it with the socket.
225  */
226 int
227 in_pcballoc(struct socket *so, struct inpcbinfo *pcbinfo)
228 {
229         struct inpcb *inp;
230 #ifdef IPSEC
231         int error;
232 #endif
233
234         inp = kmalloc(pcbinfo->ipi_size, M_PCB, M_WAITOK|M_ZERO|M_NULLOK);
235         if (inp == NULL)
236                 return (ENOMEM);
237         inp->inp_gencnt = ++pcbinfo->ipi_gencnt;
238         inp->inp_pcbinfo = inp->inp_cpcbinfo = pcbinfo;
239         inp->inp_socket = so;
240 #ifdef IPSEC
241         error = ipsec_init_policy(so, &inp->inp_sp);
242         if (error != 0) {
243                 kfree(inp, M_PCB);
244                 return (error);
245         }
246 #endif
247 #ifdef INET6
248         if (INP_SOCKAF(so) == AF_INET6 && ip6_v6only)
249                 inp->inp_flags |= IN6P_IPV6_V6ONLY;
250         if (ip6_auto_flowlabel)
251                 inp->inp_flags |= IN6P_AUTOFLOWLABEL;
252 #endif
253         soreference(so);
254         so->so_pcb = inp;
255         LIST_INSERT_HEAD(&pcbinfo->pcblisthead, inp, inp_list);
256         pcbinfo->ipi_count++;
257         return (0);
258 }
259
260 /*
261  * Unlink a pcb with the intention of moving it to another cpu with a
262  * different pcbinfo.  While unlinked nothing should attempt to dereference
263  * inp_pcbinfo, NULL it out so we assert if it does.
264  */
265 void
266 in_pcbunlink(struct inpcb *inp, struct inpcbinfo *pcbinfo)
267 {
268         KASSERT(inp->inp_pcbinfo == pcbinfo, ("pcbinfo mismatch"));
269         KASSERT(inp->inp_cpcbinfo == pcbinfo, ("cpcbinfo mismatch"));
270         KASSERT((inp->inp_flags & (INP_WILDCARD | INP_CONNECTED)) == 0,
271             ("already linked"));
272
273         LIST_REMOVE(inp, inp_list);
274         pcbinfo->ipi_count--;
275         inp->inp_pcbinfo = NULL;
276         inp->inp_cpcbinfo = NULL;
277 }
278
279 /*
280  * Relink a pcb into a new pcbinfo.
281  */
282 void
283 in_pcblink(struct inpcb *inp, struct inpcbinfo *pcbinfo)
284 {
285         KASSERT(inp->inp_pcbinfo == NULL, ("has pcbinfo"));
286         KASSERT(inp->inp_cpcbinfo == NULL, ("has cpcbinfo"));
287         KASSERT((inp->inp_flags & (INP_WILDCARD | INP_CONNECTED)) == 0,
288             ("already linked"));
289
290         inp->inp_cpcbinfo = pcbinfo;
291         inp->inp_pcbinfo = pcbinfo;
292         LIST_INSERT_HEAD(&pcbinfo->pcblisthead, inp, inp_list);
293         pcbinfo->ipi_count++;
294 }
295
296 int
297 in_pcbbind(struct inpcb *inp, struct sockaddr *nam, struct thread *td)
298 {
299         struct socket *so = inp->inp_socket;
300         unsigned short *lastport;
301         struct sockaddr_in *sin;
302         struct sockaddr_in jsin;
303         struct inpcbinfo *pcbinfo = inp->inp_pcbinfo;
304         struct ucred *cred = NULL;
305         u_short lport = 0;
306         int wild = 0, reuseport = (so->so_options & SO_REUSEPORT);
307         int error;
308
309         if (TAILQ_EMPTY(&in_ifaddrheads[mycpuid])) /* XXX broken! */
310                 return (EADDRNOTAVAIL);
311         if (inp->inp_lport != 0 || inp->inp_laddr.s_addr != INADDR_ANY)
312                 return (EINVAL);        /* already bound */
313
314         if (!(so->so_options & (SO_REUSEADDR|SO_REUSEPORT)))
315                 wild = 1;    /* neither SO_REUSEADDR nor SO_REUSEPORT is set */
316         if (td->td_proc)
317                 cred = td->td_proc->p_ucred;
318
319         /*
320          * This has to be atomic.  If the porthash is shared across multiple
321          * protocol threads (aka tcp) then the token will be non-NULL.
322          */
323         if (pcbinfo->porttoken)
324                 lwkt_gettoken(pcbinfo->porttoken);
325
326         if (nam != NULL) {
327                 sin = (struct sockaddr_in *)nam;
328                 if (nam->sa_len != sizeof *sin) {
329                         error = EINVAL;
330                         goto done;
331                 }
332 #ifdef notdef
333                 /*
334                  * We should check the family, but old programs
335                  * incorrectly fail to initialize it.
336                  */
337                 if (sin->sin_family != AF_INET) {
338                         error = EAFNOSUPPORT;
339                         goto done;
340                 }
341 #endif
342                 if (!prison_replace_wildcards(td, nam)) {
343                         error = EINVAL;
344                         goto done;
345                 }
346                 lport = sin->sin_port;
347                 if (IN_MULTICAST(ntohl(sin->sin_addr.s_addr))) {
348                         /*
349                          * Treat SO_REUSEADDR as SO_REUSEPORT for multicast;
350                          * allow complete duplication of binding if
351                          * SO_REUSEPORT is set, or if SO_REUSEADDR is set
352                          * and a multicast address is bound on both
353                          * new and duplicated sockets.
354                          */
355                         if (so->so_options & SO_REUSEADDR)
356                                 reuseport = SO_REUSEADDR | SO_REUSEPORT;
357                 } else if (sin->sin_addr.s_addr != INADDR_ANY) {
358                         sin->sin_port = 0;              /* yech... */
359                         bzero(&sin->sin_zero, sizeof sin->sin_zero);
360                         if (ifa_ifwithaddr((struct sockaddr *)sin) == NULL) {
361                                 error = EADDRNOTAVAIL;
362                                 goto done;
363                         }
364                 }
365                 if (lport != 0) {
366                         struct inpcb *t;
367
368                         /* GROSS */
369                         if (ntohs(lport) < IPPORT_RESERVED &&
370                             cred &&
371                             priv_check_cred(cred, PRIV_NETINET_RESERVEDPORT, 0)) {
372                                 error = EACCES;
373                                 goto done;
374                         }
375                         if (so->so_cred->cr_uid != 0 &&
376                             !IN_MULTICAST(ntohl(sin->sin_addr.s_addr))) {
377                                 t = in_pcblookup_local(pcbinfo,
378                                                        sin->sin_addr,
379                                                        lport,
380                                                        INPLOOKUP_WILDCARD,
381                                                        cred);
382                                 if (t &&
383                                     (!in_nullhost(sin->sin_addr) ||
384                                      !in_nullhost(t->inp_laddr) ||
385                                      (t->inp_socket->so_options &
386                                          SO_REUSEPORT) == 0) &&
387                                     (so->so_cred->cr_uid !=
388                                      t->inp_socket->so_cred->cr_uid)) {
389 #ifdef INET6
390                                         if (!in_nullhost(sin->sin_addr) ||
391                                             !in_nullhost(t->inp_laddr) ||
392                                             INP_SOCKAF(so) ==
393                                             INP_SOCKAF(t->inp_socket))
394 #endif
395                                         {
396                                                 error = EADDRINUSE;
397                                                 goto done;
398                                         }
399                                 }
400                         }
401                         if (cred && !prison_replace_wildcards(td, nam)) {
402                                 error = EADDRNOTAVAIL;
403                                 goto done;
404                         }
405                         t = in_pcblookup_local(pcbinfo, sin->sin_addr, lport,
406                                                wild, cred);
407                         if (t && !(reuseport & t->inp_socket->so_options)) {
408 #ifdef INET6
409                                 if (!in_nullhost(sin->sin_addr) ||
410                                     !in_nullhost(t->inp_laddr) ||
411                                     INP_SOCKAF(so) == INP_SOCKAF(t->inp_socket))
412 #endif
413                                 {
414                                         error = EADDRINUSE;
415                                         goto done;
416                                 }
417                         }
418                 }
419                 inp->inp_laddr = sin->sin_addr;
420         }
421
422         jsin.sin_family = AF_INET;
423         jsin.sin_addr.s_addr = inp->inp_laddr.s_addr;
424         if (!prison_replace_wildcards(td, (struct sockaddr *)&jsin)) {
425                 inp->inp_laddr.s_addr = INADDR_ANY;
426                 error = EINVAL;
427                 goto done;
428         }
429         inp->inp_laddr.s_addr = jsin.sin_addr.s_addr;
430
431         if (lport == 0) {
432                 ushort first, last;
433                 int count;
434
435                 inp->inp_flags |= INP_ANONPORT;
436
437                 if (inp->inp_flags & INP_HIGHPORT) {
438                         first = ipport_hifirstauto;     /* sysctl */
439                         last  = ipport_hilastauto;
440                         lastport = &pcbinfo->lasthi;
441                 } else if (inp->inp_flags & INP_LOWPORT) {
442                         if (cred &&
443                             (error = priv_check_cred(cred, PRIV_NETINET_RESERVEDPORT, 0))) {
444                                 inp->inp_laddr.s_addr = INADDR_ANY;
445                                 goto done;
446                         }
447                         first = ipport_lowfirstauto;    /* 1023 */
448                         last  = ipport_lowlastauto;     /* 600 */
449                         lastport = &pcbinfo->lastlow;
450                 } else {
451                         first = ipport_firstauto;       /* sysctl */
452                         last  = ipport_lastauto;
453                         lastport = &pcbinfo->lastport;
454                 }
455                 /*
456                  * Simple check to ensure all ports are not used up causing
457                  * a deadlock here.
458                  *
459                  * We split the two cases (up and down) so that the direction
460                  * is not being tested on each round of the loop.
461                  */
462                 if (first > last) {
463                         /*
464                          * counting down
465                          */
466                         count = first - last;
467
468                         do {
469                                 if (count-- < 0) {      /* completely used? */
470                                         inp->inp_laddr.s_addr = INADDR_ANY;
471                                         error = EADDRNOTAVAIL;
472                                         goto done;
473                                 }
474                                 --*lastport;
475                                 if (*lastport > first || *lastport < last)
476                                         *lastport = first;
477                                 lport = htons(*lastport);
478                         } while (in_pcblookup_local(pcbinfo, inp->inp_laddr,
479                                                     lport, wild, cred));
480                 } else {
481                         /*
482                          * counting up
483                          */
484                         count = last - first;
485
486                         do {
487                                 if (count-- < 0) {      /* completely used? */
488                                         inp->inp_laddr.s_addr = INADDR_ANY;
489                                         error = EADDRNOTAVAIL;
490                                         goto done;
491                                 }
492                                 ++*lastport;
493                                 if (*lastport < first || *lastport > last)
494                                         *lastport = first;
495                                 lport = htons(*lastport);
496                         } while (in_pcblookup_local(pcbinfo, inp->inp_laddr,
497                                                     lport, wild, cred));
498                 }
499         }
500         inp->inp_lport = lport;
501
502         if (in_pcbinsporthash(inp) != 0) {
503                 inp->inp_laddr.s_addr = INADDR_ANY;
504                 inp->inp_lport = 0;
505                 error = EAGAIN;
506                 goto done;
507         }
508         error = 0;
509 done:
510         if (pcbinfo->porttoken)
511                 lwkt_reltoken(pcbinfo->porttoken);
512         return error;
513 }
514
515 static struct inpcb *
516 in_pcblookup_addrport(struct inpcbinfo *pcbinfo, struct in_addr laddr,
517     u_short lport, struct in_addr faddr, u_short fport, struct ucred *cred)
518 {
519         struct inpcb *inp;
520         struct inpcbporthead *porthash;
521         struct inpcbport *phd;
522         struct inpcb *match = NULL;
523
524         /*
525          * If the porthashbase is shared across several cpus we need
526          * to lock.
527          */
528         if (pcbinfo->porttoken)
529                 lwkt_gettoken(pcbinfo->porttoken);
530
531         /*
532          * Best fit PCB lookup.
533          *
534          * First see if this local port is in use by looking on the
535          * port hash list.
536          */
537         porthash = &pcbinfo->porthashbase[
538                         INP_PCBPORTHASH(lport, pcbinfo->porthashmask)];
539         LIST_FOREACH(phd, porthash, phd_hash) {
540                 if (phd->phd_port == lport)
541                         break;
542         }
543         if (phd != NULL) {
544                 LIST_FOREACH(inp, &phd->phd_pcblist, inp_portlist) {
545 #ifdef INET6
546                         if ((inp->inp_vflag & INP_IPV4) == 0)
547                                 continue;
548 #endif
549                         if (inp->inp_laddr.s_addr != INADDR_ANY &&
550                             inp->inp_laddr.s_addr != laddr.s_addr)
551                                 continue;
552
553                         if (inp->inp_faddr.s_addr != INADDR_ANY &&
554                             inp->inp_faddr.s_addr != faddr.s_addr)
555                                 continue;
556
557                         if (inp->inp_fport != 0 && inp->inp_fport != fport)
558                                 continue;
559
560                         if (cred == NULL ||
561                             cred->cr_prison ==
562                             inp->inp_socket->so_cred->cr_prison) {
563                                 match = inp;
564                                 break;
565                         }
566                 }
567         }
568         if (pcbinfo->porttoken)
569                 lwkt_reltoken(pcbinfo->porttoken);
570         return (match);
571 }
572
573 int
574 in_pcbconn_bind(struct inpcb *inp, const struct sockaddr *nam,
575     struct thread *td)
576 {
577         struct proc *p = td->td_proc;
578         unsigned short *lastport;
579         const struct sockaddr_in *sin = (const struct sockaddr_in *)nam;
580         struct sockaddr_in jsin;
581         struct inpcbinfo *pcbinfo = inp->inp_pcbinfo;
582         struct ucred *cred = NULL;
583         u_short lport = 0;
584         ushort first, last;
585         int count, error, dup = 0;
586
587         if (TAILQ_EMPTY(&in_ifaddrheads[mycpuid])) /* XXX broken! */
588                 return (EADDRNOTAVAIL);
589
590         KKASSERT(inp->inp_laddr.s_addr != INADDR_ANY);
591         if (inp->inp_lport != 0)
592                 return (EINVAL);        /* already bound */
593
594         KKASSERT(p);
595         cred = p->p_ucred;
596
597         /*
598          * This has to be atomic.  If the porthash is shared across multiple
599          * protocol threads (aka tcp) then the token will be non-NULL.
600          */
601         if (pcbinfo->porttoken)
602                 lwkt_gettoken(pcbinfo->porttoken);
603
604         jsin.sin_family = AF_INET;
605         jsin.sin_addr.s_addr = inp->inp_laddr.s_addr;
606         if (!prison_replace_wildcards(td, (struct sockaddr *)&jsin)) {
607                 inp->inp_laddr.s_addr = INADDR_ANY;
608                 error = EINVAL;
609                 goto done;
610         }
611         inp->inp_laddr.s_addr = jsin.sin_addr.s_addr;
612
613         inp->inp_flags |= INP_ANONPORT;
614
615         if (inp->inp_flags & INP_HIGHPORT) {
616                 first = ipport_hifirstauto;     /* sysctl */
617                 last  = ipport_hilastauto;
618                 lastport = &pcbinfo->lasthi;
619         } else if (inp->inp_flags & INP_LOWPORT) {
620                 if (cred &&
621                     (error = priv_check_cred(cred, PRIV_NETINET_RESERVEDPORT, 0))) {
622                         inp->inp_laddr.s_addr = INADDR_ANY;
623                         goto done;
624                 }
625                 first = ipport_lowfirstauto;    /* 1023 */
626                 last  = ipport_lowlastauto;     /* 600 */
627                 lastport = &pcbinfo->lastlow;
628         } else {
629                 first = ipport_firstauto;       /* sysctl */
630                 last  = ipport_lastauto;
631                 lastport = &pcbinfo->lastport;
632         }
633
634 again:
635         /*
636          * Simple check to ensure all ports are not used up causing
637          * a deadlock here.
638          *
639          * We split the two cases (up and down) so that the direction
640          * is not being tested on each round of the loop.
641          */
642         if (first > last) {
643                 /*
644                  * counting down
645                  */
646                 count = first - last;
647
648                 do {
649                         if (count-- < 0) {      /* completely used? */
650                                 inp->inp_laddr.s_addr = INADDR_ANY;
651                                 error = EADDRNOTAVAIL;
652                                 goto done;
653                         }
654                         --*lastport;
655                         if (*lastport > first || *lastport < last)
656                                 *lastport = first;
657                         lport = htons(*lastport);
658                 } while (in_pcblookup_addrport(pcbinfo, inp->inp_laddr, lport,
659                                 sin->sin_addr, sin->sin_port, cred));
660         } else {
661                 /*
662                  * counting up
663                  */
664                 count = last - first;
665
666                 do {
667                         if (count-- < 0) {      /* completely used? */
668                                 inp->inp_laddr.s_addr = INADDR_ANY;
669                                 error = EADDRNOTAVAIL;
670                                 goto done;
671                         }
672                         ++*lastport;
673                         if (*lastport < first || *lastport > last)
674                                 *lastport = first;
675                         lport = htons(*lastport);
676                 } while (in_pcblookup_addrport(pcbinfo, inp->inp_laddr, lport,
677                                 sin->sin_addr, sin->sin_port, cred));
678         }
679
680         /* This could happen on loopback interface */
681         if (sin->sin_port == lport &&
682             sin->sin_addr.s_addr == inp->inp_laddr.s_addr) {
683                 if (dup) {
684                         /*
685                          * Duplicate again; give up
686                          */
687                         inp->inp_laddr.s_addr = INADDR_ANY;
688                         error = EADDRNOTAVAIL;
689                         goto done;
690                 }
691                 dup = 1;
692                 goto again;
693         }
694         inp->inp_lport = lport;
695
696         if (in_pcbinsporthash(inp) != 0) {
697                 inp->inp_laddr.s_addr = INADDR_ANY;
698                 inp->inp_lport = 0;
699                 error = EAGAIN;
700                 goto done;
701         }
702         error = 0;
703 done:
704         if (pcbinfo->porttoken)
705                 lwkt_reltoken(pcbinfo->porttoken);
706         return error;
707 }
708
709 /*
710  *   Transform old in_pcbconnect() into an inner subroutine for new
711  *   in_pcbconnect(): Do some validity-checking on the remote
712  *   address (in mbuf 'nam') and then determine local host address
713  *   (i.e., which interface) to use to access that remote host.
714  *
715  *   This preserves definition of in_pcbconnect(), while supporting a
716  *   slightly different version for T/TCP.  (This is more than
717  *   a bit of a kludge, but cleaning up the internal interfaces would
718  *   have forced minor changes in every protocol).
719  */
720 int
721 in_pcbladdr_find(struct inpcb *inp, struct sockaddr *nam,
722     struct sockaddr_in **plocal_sin, struct thread *td, int find)
723 {
724         struct in_ifaddr *ia;
725         struct ucred *cred = NULL;
726         struct sockaddr_in *sin = (struct sockaddr_in *)nam;
727         struct sockaddr *jsin;
728         int jailed = 0, alloc_route = 0;
729
730         if (nam->sa_len != sizeof *sin)
731                 return (EINVAL);
732         if (sin->sin_family != AF_INET)
733                 return (EAFNOSUPPORT);
734         if (sin->sin_port == 0)
735                 return (EADDRNOTAVAIL);
736         if (td && td->td_proc && td->td_proc->p_ucred)
737                 cred = td->td_proc->p_ucred;
738         if (cred && cred->cr_prison)
739                 jailed = 1;
740         if (!TAILQ_EMPTY(&in_ifaddrheads[mycpuid])) {
741                 ia = TAILQ_FIRST(&in_ifaddrheads[mycpuid])->ia;
742                 /*
743                  * If the destination address is INADDR_ANY,
744                  * use the primary local address.
745                  * If the supplied address is INADDR_BROADCAST,
746                  * and the primary interface supports broadcast,
747                  * choose the broadcast address for that interface.
748                  */
749                 if (sin->sin_addr.s_addr == INADDR_ANY)
750                         sin->sin_addr = IA_SIN(ia)->sin_addr;
751                 else if (sin->sin_addr.s_addr == (u_long)INADDR_BROADCAST &&
752                     (ia->ia_ifp->if_flags & IFF_BROADCAST))
753                         sin->sin_addr = satosin(&ia->ia_broadaddr)->sin_addr;
754         }
755         if (find) {
756                 struct route *ro;
757
758                 ia = NULL;
759                 /*
760                  * If route is known or can be allocated now,
761                  * our src addr is taken from the i/f, else punt.
762                  * Note that we should check the address family of the cached
763                  * destination, in case of sharing the cache with IPv6.
764                  */
765                 ro = &inp->inp_route;
766                 if (ro->ro_rt &&
767                     (!(ro->ro_rt->rt_flags & RTF_UP) ||
768                      ro->ro_dst.sa_family != AF_INET ||
769                      satosin(&ro->ro_dst)->sin_addr.s_addr !=
770                                       sin->sin_addr.s_addr ||
771                      inp->inp_socket->so_options & SO_DONTROUTE)) {
772                         RTFREE(ro->ro_rt);
773                         ro->ro_rt = NULL;
774                 }
775                 if (!(inp->inp_socket->so_options & SO_DONTROUTE) && /*XXX*/
776                     (ro->ro_rt == NULL ||
777                     ro->ro_rt->rt_ifp == NULL)) {
778                         /* No route yet, so try to acquire one */
779                         bzero(&ro->ro_dst, sizeof(struct sockaddr_in));
780                         ro->ro_dst.sa_family = AF_INET;
781                         ro->ro_dst.sa_len = sizeof(struct sockaddr_in);
782                         ((struct sockaddr_in *) &ro->ro_dst)->sin_addr =
783                                 sin->sin_addr;
784                         rtalloc(ro);
785                         alloc_route = 1;
786                 }
787                 /*
788                  * If we found a route, use the address
789                  * corresponding to the outgoing interface
790                  * unless it is the loopback (in case a route
791                  * to our address on another net goes to loopback).
792                  */
793                 if (ro->ro_rt && !(ro->ro_rt->rt_ifp->if_flags & IFF_LOOPBACK)) {
794                         if (jailed) {
795                                 if (jailed_ip(cred->cr_prison, 
796                                     ro->ro_rt->rt_ifa->ifa_addr)) {
797                                         ia = ifatoia(ro->ro_rt->rt_ifa);
798                                 }
799                         } else {
800                                 ia = ifatoia(ro->ro_rt->rt_ifa);
801                         }
802                 }
803                 if (ia == NULL) {
804                         u_short fport = sin->sin_port;
805
806                         sin->sin_port = 0;
807                         ia = ifatoia(ifa_ifwithdstaddr(sintosa(sin)));
808                         if (ia && jailed && !jailed_ip(cred->cr_prison,
809                             sintosa(&ia->ia_addr)))
810                                 ia = NULL;
811                         if (ia == NULL)
812                                 ia = ifatoia(ifa_ifwithnet(sintosa(sin)));
813                         if (ia && jailed && !jailed_ip(cred->cr_prison,
814                             sintosa(&ia->ia_addr)))
815                                 ia = NULL;
816                         sin->sin_port = fport;
817                         if (ia == NULL &&
818                             !TAILQ_EMPTY(&in_ifaddrheads[mycpuid]))
819                                 ia = TAILQ_FIRST(&in_ifaddrheads[mycpuid])->ia;
820                         if (ia && jailed && !jailed_ip(cred->cr_prison,
821                             sintosa(&ia->ia_addr)))
822                                 ia = NULL;
823
824                         if (!jailed && ia == NULL)
825                                 goto fail;
826                 }
827                 /*
828                  * If the destination address is multicast and an outgoing
829                  * interface has been set as a multicast option, use the
830                  * address of that interface as our source address.
831                  */
832                 if (!jailed && IN_MULTICAST(ntohl(sin->sin_addr.s_addr)) &&
833                     inp->inp_moptions != NULL) {
834                         struct ip_moptions *imo;
835                         struct ifnet *ifp;
836
837                         imo = inp->inp_moptions;
838                         if (imo->imo_multicast_ifp != NULL) {
839                                 struct in_ifaddr_container *iac;
840
841                                 ifp = imo->imo_multicast_ifp;
842                                 ia = NULL;
843                                 TAILQ_FOREACH(iac,
844                                 &in_ifaddrheads[mycpuid], ia_link) {
845                                         if (iac->ia->ia_ifp == ifp) {
846                                                 ia = iac->ia;
847                                                 break;
848                                         }
849                                 }
850                                 if (ia == NULL)
851                                         goto fail;
852                         }
853                 }
854                 /*
855                  * Don't do pcblookup call here; return interface in plocal_sin
856                  * and exit to caller, that will do the lookup.
857                  */
858                 if (ia == NULL && jailed) {
859                         if ((jsin = prison_get_nonlocal(cred->cr_prison, AF_INET, NULL)) != NULL ||
860                             (jsin = prison_get_local(cred->cr_prison, AF_INET, NULL)) != NULL) {
861                                 *plocal_sin = satosin(jsin);
862                         } else {
863                                 /* IPv6 only Jail */
864                                 goto fail;
865                         }
866                 } else {
867                         *plocal_sin = &ia->ia_addr;
868                 }
869         }
870         return (0);
871 fail:
872         if (alloc_route) {
873                 struct route *ro = &inp->inp_route;
874
875                 if (ro->ro_rt != NULL)
876                         RTFREE(ro->ro_rt);
877                 bzero(ro, sizeof(*ro));
878         }
879         return (EADDRNOTAVAIL);
880 }
881
882 int
883 in_pcbladdr(struct inpcb *inp, struct sockaddr *nam,
884     struct sockaddr_in **plocal_sin, struct thread *td)
885 {
886         return in_pcbladdr_find(inp, nam, plocal_sin, td,
887             (inp->inp_laddr.s_addr == INADDR_ANY));
888 }
889
890 /*
891  * Outer subroutine:
892  * Connect from a socket to a specified address.
893  * Both address and port must be specified in argument sin.
894  * If don't have a local address for this socket yet,
895  * then pick one.
896  */
897 int
898 in_pcbconnect(struct inpcb *inp, struct sockaddr *nam, struct thread *td)
899 {
900         struct sockaddr_in *if_sin;
901         struct sockaddr_in *sin = (struct sockaddr_in *)nam;
902         int error;
903
904         /* Call inner routine to assign local interface address. */
905         if ((error = in_pcbladdr(inp, nam, &if_sin, td)) != 0)
906                 return (error);
907
908         if (in_pcblookup_hash(inp->inp_cpcbinfo, sin->sin_addr, sin->sin_port,
909                               inp->inp_laddr.s_addr ?
910                                 inp->inp_laddr : if_sin->sin_addr,
911                               inp->inp_lport, FALSE, NULL) != NULL) {
912                 return (EADDRINUSE);
913         }
914         if (inp->inp_laddr.s_addr == INADDR_ANY) {
915                 if (inp->inp_lport == 0) {
916                         error = in_pcbbind(inp, NULL, td);
917                         if (error)
918                                 return (error);
919                 }
920                 inp->inp_laddr = if_sin->sin_addr;
921         }
922         inp->inp_faddr = sin->sin_addr;
923         inp->inp_fport = sin->sin_port;
924         in_pcbinsconnhash(inp);
925         return (0);
926 }
927
928 void
929 in_pcbdisconnect(struct inpcb *inp)
930 {
931
932         inp->inp_faddr.s_addr = INADDR_ANY;
933         inp->inp_fport = 0;
934         in_pcbremconnhash(inp);
935         if (inp->inp_socket->so_state & SS_NOFDREF)
936                 in_pcbdetach(inp);
937 }
938
939 void
940 in_pcbdetach(struct inpcb *inp)
941 {
942         struct socket *so = inp->inp_socket;
943         struct inpcbinfo *ipi = inp->inp_pcbinfo;
944
945 #ifdef IPSEC
946         ipsec4_delete_pcbpolicy(inp);
947 #endif /*IPSEC*/
948         inp->inp_gencnt = ++ipi->ipi_gencnt;
949         KKASSERT((so->so_state & SS_ASSERTINPROG) == 0);
950         in_pcbremlists(inp);
951         so->so_pcb = NULL;
952         sofree(so);                     /* remove pcb ref */
953         if (inp->inp_options)
954                 m_free(inp->inp_options);
955         if (inp->inp_route.ro_rt)
956                 rtfree(inp->inp_route.ro_rt);
957         ip_freemoptions(inp->inp_moptions);
958         inp->inp_vflag = 0;
959         kfree(inp, M_PCB);
960 }
961
962 /*
963  * The calling convention of in_setsockaddr() and in_setpeeraddr() was
964  * modified to match the pru_sockaddr() and pru_peeraddr() entry points
965  * in struct pr_usrreqs, so that protocols can just reference then directly
966  * without the need for a wrapper function.  The socket must have a valid
967  * (i.e., non-nil) PCB, but it should be impossible to get an invalid one
968  * except through a kernel programming error, so it is acceptable to panic
969  * (or in this case trap) if the PCB is invalid.  (Actually, we don't trap
970  * because there actually /is/ a programming error somewhere... XXX)
971  */
972 int
973 in_setsockaddr(struct socket *so, struct sockaddr **nam)
974 {
975         struct inpcb *inp;
976         struct sockaddr_in *sin;
977
978         /*
979          * Do the malloc first in case it blocks.
980          */
981         sin = kmalloc(sizeof *sin, M_SONAME, M_WAITOK | M_ZERO);
982         sin->sin_family = AF_INET;
983         sin->sin_len = sizeof *sin;
984
985         crit_enter();
986         inp = so->so_pcb;
987         if (!inp) {
988                 crit_exit();
989                 kfree(sin, M_SONAME);
990                 return (ECONNRESET);
991         }
992         sin->sin_port = inp->inp_lport;
993         sin->sin_addr = inp->inp_laddr;
994         crit_exit();
995
996         *nam = (struct sockaddr *)sin;
997         return (0);
998 }
999
1000 void
1001 in_setsockaddr_dispatch(netmsg_t msg)
1002 {
1003         int error;
1004
1005         error = in_setsockaddr(msg->base.nm_so, msg->peeraddr.nm_nam);
1006         lwkt_replymsg(&msg->lmsg, error);
1007 }
1008
1009 int
1010 in_setpeeraddr(struct socket *so, struct sockaddr **nam)
1011 {
1012         struct inpcb *inp;
1013         struct sockaddr_in *sin;
1014
1015         /*
1016          * Do the malloc first in case it blocks.
1017          */
1018         sin = kmalloc(sizeof *sin, M_SONAME, M_WAITOK | M_ZERO);
1019         sin->sin_family = AF_INET;
1020         sin->sin_len = sizeof *sin;
1021
1022         crit_enter();
1023         inp = so->so_pcb;
1024         if (!inp) {
1025                 crit_exit();
1026                 kfree(sin, M_SONAME);
1027                 return (ECONNRESET);
1028         }
1029         sin->sin_port = inp->inp_fport;
1030         sin->sin_addr = inp->inp_faddr;
1031         crit_exit();
1032
1033         *nam = (struct sockaddr *)sin;
1034         return (0);
1035 }
1036
1037 void
1038 in_setpeeraddr_dispatch(netmsg_t msg)
1039 {
1040         int error;
1041
1042         error = in_setpeeraddr(msg->base.nm_so, msg->peeraddr.nm_nam);
1043         lwkt_replymsg(&msg->lmsg, error);
1044 }
1045
1046 void
1047 in_pcbnotifyall(struct inpcbhead *head, struct in_addr faddr, int err,
1048                 void (*notify)(struct inpcb *, int))
1049 {
1050         struct inpcb *inp, *ninp;
1051
1052         /*
1053          * note: if INP_PLACEMARKER is set we must ignore the rest of
1054          * the structure and skip it.
1055          */
1056         crit_enter();
1057         LIST_FOREACH_MUTABLE(inp, head, inp_list, ninp) {
1058                 if (inp->inp_flags & INP_PLACEMARKER)
1059                         continue;
1060 #ifdef INET6
1061                 if (!(inp->inp_vflag & INP_IPV4))
1062                         continue;
1063 #endif
1064                 if (inp->inp_faddr.s_addr != faddr.s_addr ||
1065                     inp->inp_socket == NULL)
1066                         continue;
1067                 (*notify)(inp, err);            /* can remove inp from list! */
1068         }
1069         crit_exit();
1070 }
1071
1072 void
1073 in_pcbpurgeif0(struct inpcb *head, struct ifnet *ifp)
1074 {
1075         struct inpcb *inp;
1076         struct ip_moptions *imo;
1077         int i, gap;
1078
1079         for (inp = head; inp != NULL; inp = LIST_NEXT(inp, inp_list)) {
1080                 if (inp->inp_flags & INP_PLACEMARKER)
1081                         continue;
1082                 imo = inp->inp_moptions;
1083                 if ((inp->inp_vflag & INP_IPV4) && imo != NULL) {
1084                         /*
1085                          * Unselect the outgoing interface if it is being
1086                          * detached.
1087                          */
1088                         if (imo->imo_multicast_ifp == ifp)
1089                                 imo->imo_multicast_ifp = NULL;
1090
1091                         /*
1092                          * Drop multicast group membership if we joined
1093                          * through the interface being detached.
1094                          */
1095                         for (i = 0, gap = 0; i < imo->imo_num_memberships;
1096                             i++) {
1097                                 if (imo->imo_membership[i]->inm_ifp == ifp) {
1098                                         in_delmulti(imo->imo_membership[i]);
1099                                         gap++;
1100                                 } else if (gap != 0)
1101                                         imo->imo_membership[i - gap] =
1102                                             imo->imo_membership[i];
1103                         }
1104                         imo->imo_num_memberships -= gap;
1105                 }
1106         }
1107 }
1108
1109 /*
1110  * Check for alternatives when higher level complains
1111  * about service problems.  For now, invalidate cached
1112  * routing information.  If the route was created dynamically
1113  * (by a redirect), time to try a default gateway again.
1114  */
1115 void
1116 in_losing(struct inpcb *inp)
1117 {
1118         struct rtentry *rt;
1119         struct rt_addrinfo rtinfo;
1120
1121         if ((rt = inp->inp_route.ro_rt)) {
1122                 bzero(&rtinfo, sizeof(struct rt_addrinfo));
1123                 rtinfo.rti_info[RTAX_DST] = rt_key(rt);
1124                 rtinfo.rti_info[RTAX_GATEWAY] = rt->rt_gateway;
1125                 rtinfo.rti_info[RTAX_NETMASK] = rt_mask(rt);
1126                 rtinfo.rti_flags = rt->rt_flags;
1127                 rt_missmsg(RTM_LOSING, &rtinfo, rt->rt_flags, 0);
1128                 if (rt->rt_flags & RTF_DYNAMIC) {
1129                         rtrequest(RTM_DELETE, rt_key(rt), rt->rt_gateway,
1130                             rt_mask(rt), rt->rt_flags, NULL);
1131                 }
1132                 inp->inp_route.ro_rt = NULL;
1133                 rtfree(rt);
1134                 /*
1135                  * A new route can be allocated
1136                  * the next time output is attempted.
1137                  */
1138         }
1139 }
1140
1141 /*
1142  * After a routing change, flush old routing
1143  * and allocate a (hopefully) better one.
1144  */
1145 void
1146 in_rtchange(struct inpcb *inp, int err)
1147 {
1148         if (inp->inp_route.ro_rt) {
1149                 rtfree(inp->inp_route.ro_rt);
1150                 inp->inp_route.ro_rt = NULL;
1151                 /*
1152                  * A new route can be allocated the next time
1153                  * output is attempted.
1154                  */
1155         }
1156 }
1157
1158 /*
1159  * Lookup a PCB based on the local address and port.
1160  */
1161 struct inpcb *
1162 in_pcblookup_local(struct inpcbinfo *pcbinfo, struct in_addr laddr,
1163                    u_int lport_arg, int wild_okay, struct ucred *cred)
1164 {
1165         struct inpcb *inp;
1166         int matchwild = 3, wildcard;
1167         u_short lport = lport_arg;
1168         struct inpcbporthead *porthash;
1169         struct inpcbport *phd;
1170         struct inpcb *match = NULL;
1171
1172         /*
1173          * If the porthashbase is shared across several cpus we need
1174          * to lock.
1175          */
1176         if (pcbinfo->porttoken)
1177                 lwkt_gettoken(pcbinfo->porttoken);
1178
1179         /*
1180          * Best fit PCB lookup.
1181          *
1182          * First see if this local port is in use by looking on the
1183          * port hash list.
1184          */
1185         porthash = &pcbinfo->porthashbase[
1186                         INP_PCBPORTHASH(lport, pcbinfo->porthashmask)];
1187         LIST_FOREACH(phd, porthash, phd_hash) {
1188                 if (phd->phd_port == lport)
1189                         break;
1190         }
1191         if (phd != NULL) {
1192                 /*
1193                  * Port is in use by one or more PCBs. Look for best
1194                  * fit.
1195                  */
1196                 LIST_FOREACH(inp, &phd->phd_pcblist, inp_portlist) {
1197                         wildcard = 0;
1198 #ifdef INET6
1199                         if ((inp->inp_vflag & INP_IPV4) == 0)
1200                                 continue;
1201 #endif
1202                         if (inp->inp_faddr.s_addr != INADDR_ANY)
1203                                 wildcard++;
1204                         if (inp->inp_laddr.s_addr != INADDR_ANY) {
1205                                 if (laddr.s_addr == INADDR_ANY)
1206                                         wildcard++;
1207                                 else if (inp->inp_laddr.s_addr != laddr.s_addr)
1208                                         continue;
1209                         } else {
1210                                 if (laddr.s_addr != INADDR_ANY)
1211                                         wildcard++;
1212                         }
1213                         if (wildcard && !wild_okay)
1214                                 continue;
1215                         if (wildcard < matchwild &&
1216                             (cred == NULL ||
1217                              cred->cr_prison == 
1218                                         inp->inp_socket->so_cred->cr_prison)) {
1219                                 match = inp;
1220                                 matchwild = wildcard;
1221                                 if (matchwild == 0) {
1222                                         break;
1223                                 }
1224                         }
1225                 }
1226         }
1227         if (pcbinfo->porttoken)
1228                 lwkt_reltoken(pcbinfo->porttoken);
1229         return (match);
1230 }
1231
1232 struct inpcb *
1233 in_pcblocalgroup_last(const struct inpcbinfo *pcbinfo,
1234     const struct inpcb *inp)
1235 {
1236         const struct inp_localgrphead *hdr;
1237         const struct inp_localgroup *grp;
1238         int i;
1239
1240         if (pcbinfo->localgrphashbase == NULL)
1241                 return NULL;
1242
1243         hdr = &pcbinfo->localgrphashbase[
1244             INP_PCBLOCALGRPHASH(inp->inp_lport, pcbinfo->localgrphashmask)];
1245
1246         LIST_FOREACH(grp, hdr, il_list) {
1247                 if (grp->il_vflag == inp->inp_vflag &&
1248                     grp->il_lport == inp->inp_lport &&
1249                     memcmp(&grp->il_dependladdr,
1250                         &inp->inp_inc.inc_ie.ie_dependladdr,
1251                         sizeof(grp->il_dependladdr)) == 0) {
1252                         break;
1253                 }
1254         }
1255         if (grp == NULL || grp->il_inpcnt == 1)
1256                 return NULL;
1257
1258         KASSERT(grp->il_inpcnt >= 2,
1259             ("invalid localgroup inp count %d", grp->il_inpcnt));
1260         for (i = 0; i < grp->il_inpcnt; ++i) {
1261                 if (grp->il_inp[i] == inp) {
1262                         int last = grp->il_inpcnt - 1;
1263
1264                         if (i == last)
1265                                 last = grp->il_inpcnt - 2;
1266                         return grp->il_inp[last];
1267                 }
1268         }
1269         return NULL;
1270 }
1271
1272 static struct inpcb *
1273 inp_localgroup_lookup(const struct inpcbinfo *pcbinfo,
1274     struct in_addr laddr, uint16_t lport, uint32_t pkt_hash)
1275 {
1276         struct inpcb *local_wild = NULL;
1277         const struct inp_localgrphead *hdr;
1278         const struct inp_localgroup *grp;
1279
1280         hdr = &pcbinfo->localgrphashbase[
1281             INP_PCBLOCALGRPHASH(lport, pcbinfo->localgrphashmask)];
1282 #ifdef INP_LOCALGROUP_HASHTHR
1283         pkt_hash >>= ncpus2_shift;
1284 #endif
1285
1286         /*
1287          * Order of socket selection:
1288          * 1. non-wild.
1289          * 2. wild.
1290          *
1291          * NOTE:
1292          * - Local group does not contain jailed sockets
1293          * - Local group does not contain IPv4 mapped INET6 wild sockets
1294          */
1295         LIST_FOREACH(grp, hdr, il_list) {
1296 #ifdef INET6
1297                 if (!(grp->il_vflag & INP_IPV4))
1298                         continue;
1299 #endif
1300                 if (grp->il_lport == lport) {
1301                         int idx;
1302
1303 #ifdef INP_LOCALGROUP_HASHTHR
1304                         idx = pkt_hash / grp->il_factor;
1305                         KASSERT(idx < grp->il_inpcnt && idx >= 0,
1306                             ("invalid hash %04x, cnt %d or fact %d",
1307                              pkt_hash, grp->il_inpcnt, grp->il_factor));
1308 #else
1309                         /*
1310                          * Modulo-N is used here, which greatly reduces
1311                          * completion queue token contention, thus more
1312                          * cpu time is saved.
1313                          */
1314                         idx = pkt_hash % grp->il_inpcnt;
1315 #endif
1316
1317                         if (grp->il_laddr.s_addr == laddr.s_addr)
1318                                 return grp->il_inp[idx];
1319                         else if (grp->il_laddr.s_addr == INADDR_ANY)
1320                                 local_wild = grp->il_inp[idx];
1321                 }
1322         }
1323         if (local_wild != NULL)
1324                 return local_wild;
1325         return NULL;
1326 }
1327
1328 /*
1329  * Lookup PCB in hash list.
1330  */
1331 struct inpcb *
1332 in_pcblookup_pkthash(struct inpcbinfo *pcbinfo, struct in_addr faddr,
1333     u_int fport_arg, struct in_addr laddr, u_int lport_arg,
1334     boolean_t wildcard, struct ifnet *ifp, const struct mbuf *m)
1335 {
1336         struct inpcbhead *head;
1337         struct inpcb *inp, *jinp=NULL;
1338         u_short fport = fport_arg, lport = lport_arg;
1339
1340         /*
1341          * First look for an exact match.
1342          */
1343         head = &pcbinfo->hashbase[INP_PCBCONNHASH(faddr.s_addr, fport,
1344             laddr.s_addr, lport, pcbinfo->hashmask)];
1345         LIST_FOREACH(inp, head, inp_hash) {
1346 #ifdef INET6
1347                 if (!(inp->inp_vflag & INP_IPV4))
1348                         continue;
1349 #endif
1350                 if (in_hosteq(inp->inp_faddr, faddr) &&
1351                     in_hosteq(inp->inp_laddr, laddr) &&
1352                     inp->inp_fport == fport && inp->inp_lport == lport) {
1353                         /* found */
1354                         if (inp->inp_socket == NULL ||
1355                             inp->inp_socket->so_cred->cr_prison == NULL) {
1356                                 return (inp);
1357                         } else {
1358                                 if  (jinp == NULL)
1359                                         jinp = inp;
1360                         }
1361                 }
1362         }
1363         if (jinp != NULL)
1364                 return (jinp);
1365         if (wildcard) {
1366                 struct inpcb *local_wild = NULL;
1367                 struct inpcb *jinp_wild = NULL;
1368 #ifdef INET6
1369                 struct inpcb *local_wild_mapped = NULL;
1370 #endif
1371                 struct inpcontainer *ic;
1372                 struct inpcontainerhead *chead;
1373                 struct sockaddr_in jsin;
1374                 struct ucred *cred;
1375
1376                 /*
1377                  * Check local group first
1378                  */
1379                 if (pcbinfo->localgrphashbase != NULL &&
1380                     m != NULL && (m->m_flags & M_HASH) &&
1381                     !(ifp && ifp->if_type == IFT_FAITH)) {
1382                         inp = inp_localgroup_lookup(pcbinfo,
1383                             laddr, lport, m->m_pkthdr.hash);
1384                         if (inp != NULL)
1385                                 return inp;
1386                 }
1387
1388                 /*
1389                  * Order of socket selection:
1390                  * 1. non-jailed, non-wild.
1391                  * 2. non-jailed, wild.
1392                  * 3. jailed, non-wild.
1393                  * 4. jailed, wild.
1394                  */
1395                 jsin.sin_family = AF_INET;
1396                 chead = &pcbinfo->wildcardhashbase[
1397                     INP_PCBWILDCARDHASH(lport, pcbinfo->wildcardhashmask)];
1398                 LIST_FOREACH(ic, chead, ic_list) {
1399                         inp = ic->ic_inp;
1400                         jsin.sin_addr.s_addr = laddr.s_addr;
1401 #ifdef INET6
1402                         if (!(inp->inp_vflag & INP_IPV4))
1403                                 continue;
1404 #endif
1405                         if (inp->inp_socket != NULL)
1406                                 cred = inp->inp_socket->so_cred;
1407                         else
1408                                 cred = NULL;
1409                         if (cred != NULL && jailed(cred)) {
1410                                 if (jinp != NULL)
1411                                         continue;
1412                                 else
1413                                         if (!jailed_ip(cred->cr_prison,
1414                                             (struct sockaddr *)&jsin))
1415                                                 continue;
1416                         }
1417                         if (inp->inp_lport == lport) {
1418                                 if (ifp && ifp->if_type == IFT_FAITH &&
1419                                     !(inp->inp_flags & INP_FAITH))
1420                                         continue;
1421                                 if (inp->inp_laddr.s_addr == laddr.s_addr) {
1422                                         if (cred != NULL && jailed(cred))
1423                                                 jinp = inp;
1424                                         else
1425                                                 return (inp);
1426                                 }
1427                                 if (inp->inp_laddr.s_addr == INADDR_ANY) {
1428 #ifdef INET6
1429                                         if (INP_CHECK_SOCKAF(inp->inp_socket,
1430                                                              AF_INET6))
1431                                                 local_wild_mapped = inp;
1432                                         else
1433 #endif
1434                                                 if (cred != NULL &&
1435                                                     jailed(cred))
1436                                                         jinp_wild = inp;
1437                                                 else
1438                                                         local_wild = inp;
1439                                 }
1440                         }
1441                 }
1442                 if (local_wild != NULL)
1443                         return (local_wild);
1444 #ifdef INET6
1445                 if (local_wild_mapped != NULL)
1446                         return (local_wild_mapped);
1447 #endif
1448                 if (jinp != NULL)
1449                         return (jinp);
1450                 return (jinp_wild);
1451         }
1452
1453         /*
1454          * Not found.
1455          */
1456         return (NULL);
1457 }
1458
1459 struct inpcb *
1460 in_pcblookup_hash(struct inpcbinfo *pcbinfo, struct in_addr faddr,
1461     u_int fport_arg, struct in_addr laddr, u_int lport_arg,
1462     boolean_t wildcard, struct ifnet *ifp)
1463 {
1464         return in_pcblookup_pkthash(pcbinfo, faddr, fport_arg,
1465             laddr, lport_arg, wildcard, ifp, NULL);
1466 }
1467
1468 /*
1469  * Insert PCB into connection hash table.
1470  */
1471 void
1472 in_pcbinsconnhash(struct inpcb *inp)
1473 {
1474         struct inpcbinfo *pcbinfo = inp->inp_cpcbinfo;
1475         struct inpcbhead *bucket;
1476         u_int32_t hashkey_faddr, hashkey_laddr;
1477
1478 #ifdef INET6
1479         if (inp->inp_vflag & INP_IPV6) {
1480                 hashkey_faddr = inp->in6p_faddr.s6_addr32[3] /* XXX JH */;
1481                 hashkey_laddr = inp->in6p_laddr.s6_addr32[3] /* XXX JH */;
1482         } else {
1483 #endif
1484                 hashkey_faddr = inp->inp_faddr.s_addr;
1485                 hashkey_laddr = inp->inp_laddr.s_addr;
1486 #ifdef INET6
1487         }
1488 #endif
1489
1490         KASSERT(!(inp->inp_flags & INP_WILDCARD),
1491                 ("already on wildcardhash"));
1492         KASSERT(!(inp->inp_flags & INP_CONNECTED),
1493                 ("already on connhash"));
1494         inp->inp_flags |= INP_CONNECTED;
1495
1496         /*
1497          * Insert into the connection hash table.
1498          */
1499         bucket = &pcbinfo->hashbase[INP_PCBCONNHASH(hashkey_faddr,
1500             inp->inp_fport, hashkey_laddr, inp->inp_lport, pcbinfo->hashmask)];
1501         LIST_INSERT_HEAD(bucket, inp, inp_hash);
1502 }
1503
1504 /*
1505  * Remove PCB from connection hash table.
1506  */
1507 void
1508 in_pcbremconnhash(struct inpcb *inp)
1509 {
1510         KASSERT(inp->inp_flags & INP_CONNECTED, ("inp not connected"));
1511         LIST_REMOVE(inp, inp_hash);
1512         inp->inp_flags &= ~INP_CONNECTED;
1513 }
1514
1515 /*
1516  * Insert PCB into port hash table.
1517  */
1518 int
1519 in_pcbinsporthash(struct inpcb *inp)
1520 {
1521         struct inpcbinfo *pcbinfo = inp->inp_pcbinfo;
1522         struct inpcbporthead *pcbporthash;
1523         struct inpcbport *phd;
1524
1525         /*
1526          * If the porthashbase is shared across several cpus we need
1527          * to lock.
1528          */
1529         if (pcbinfo->porttoken)
1530                 lwkt_gettoken(pcbinfo->porttoken);
1531
1532         /*
1533          * Insert into the port hash table.
1534          */
1535         pcbporthash = &pcbinfo->porthashbase[
1536             INP_PCBPORTHASH(inp->inp_lport, pcbinfo->porthashmask)];
1537
1538         /* Go through port list and look for a head for this lport. */
1539         LIST_FOREACH(phd, pcbporthash, phd_hash) {
1540                 if (phd->phd_port == inp->inp_lport)
1541                         break;
1542         }
1543
1544         /* If none exists, malloc one and tack it on. */
1545         if (phd == NULL) {
1546                 KKASSERT(pcbinfo->portsave != NULL);
1547                 phd = pcbinfo->portsave;
1548                 pcbinfo->portsave = NULL;
1549                 phd->phd_port = inp->inp_lport;
1550                 LIST_INIT(&phd->phd_pcblist);
1551                 LIST_INSERT_HEAD(pcbporthash, phd, phd_hash);
1552         }
1553
1554         inp->inp_phd = phd;
1555         LIST_INSERT_HEAD(&phd->phd_pcblist, inp, inp_portlist);
1556
1557         if (pcbinfo->porttoken)
1558                 lwkt_reltoken(pcbinfo->porttoken);
1559         if (pcbinfo->portsave == NULL) {
1560                 pcbinfo->portsave = kmalloc(sizeof(*pcbinfo->portsave),
1561                                             M_PCB, M_INTWAIT | M_ZERO);
1562         }
1563         return (0);
1564 }
1565
1566 static struct inp_localgroup *
1567 inp_localgroup_alloc(struct inp_localgrphead *hdr, u_char vflag,
1568     uint16_t port, const union in_dependaddr *addr, int size)
1569 {
1570         struct inp_localgroup *grp;
1571
1572         grp = kmalloc(__offsetof(struct inp_localgroup, il_inp[size]),
1573             M_TEMP, M_INTWAIT | M_ZERO);
1574         grp->il_vflag = vflag;
1575         grp->il_lport = port;
1576         grp->il_dependladdr = *addr;
1577         grp->il_inpsiz = size;
1578
1579         LIST_INSERT_HEAD(hdr, grp, il_list);
1580
1581         return grp;
1582 }
1583
1584 static void
1585 inp_localgroup_free(struct inp_localgroup *grp)
1586 {
1587         LIST_REMOVE(grp, il_list);
1588         kfree(grp, M_TEMP);
1589 }
1590
1591 static struct inp_localgroup *
1592 inp_localgroup_resize(struct inp_localgrphead *hdr,
1593     struct inp_localgroup *old_grp, int size)
1594 {
1595         struct inp_localgroup *grp;
1596         int i;
1597
1598         grp = inp_localgroup_alloc(hdr, old_grp->il_vflag,
1599             old_grp->il_lport, &old_grp->il_dependladdr, size);
1600
1601         KASSERT(old_grp->il_inpcnt < grp->il_inpsiz,
1602             ("invalid new local group size %d and old local group count %d",
1603              grp->il_inpsiz, old_grp->il_inpcnt));
1604         for (i = 0; i < old_grp->il_inpcnt; ++i)
1605                 grp->il_inp[i] = old_grp->il_inp[i];
1606         grp->il_inpcnt = old_grp->il_inpcnt;
1607         grp->il_factor = old_grp->il_factor;
1608
1609         inp_localgroup_free(old_grp);
1610
1611         return grp;
1612 }
1613
1614 static void
1615 inp_localgroup_factor(struct inp_localgroup *grp)
1616 {
1617         grp->il_factor =
1618             ((uint32_t)(0xffff >> ncpus2_shift) / grp->il_inpcnt) + 1;
1619         KASSERT(grp->il_factor != 0, ("invalid local group factor, "
1620             "ncpus2_shift %d, inpcnt %d", ncpus2_shift, grp->il_inpcnt));
1621 }
1622
1623 static void
1624 in_pcbinslocalgrphash_oncpu(struct inpcb *inp, struct inpcbinfo *pcbinfo)
1625 {
1626         struct inp_localgrphead *hdr;
1627         struct inp_localgroup *grp;
1628         struct ucred *cred;
1629
1630         if (pcbinfo->localgrphashbase == NULL)
1631                 return;
1632
1633         /*
1634          * XXX don't allow jailed socket to join local group
1635          */
1636         if (inp->inp_socket != NULL)
1637                 cred = inp->inp_socket->so_cred;
1638         else
1639                 cred = NULL;
1640         if (cred != NULL && jailed(cred))
1641                 return;
1642
1643 #ifdef INET6
1644         /*
1645          * XXX don't allow IPv4 mapped INET6 wild socket
1646          */
1647         if ((inp->inp_vflag & INP_IPV4) &&
1648             inp->inp_laddr.s_addr == INADDR_ANY &&
1649             INP_CHECK_SOCKAF(inp->inp_socket, AF_INET6))
1650                 return;
1651 #endif
1652
1653         hdr = &pcbinfo->localgrphashbase[
1654             INP_PCBLOCALGRPHASH(inp->inp_lport, pcbinfo->localgrphashmask)];
1655
1656         LIST_FOREACH(grp, hdr, il_list) {
1657                 if (grp->il_vflag == inp->inp_vflag &&
1658                     grp->il_lport == inp->inp_lport &&
1659                     memcmp(&grp->il_dependladdr,
1660                         &inp->inp_inc.inc_ie.ie_dependladdr,
1661                         sizeof(grp->il_dependladdr)) == 0) {
1662                         break;
1663                 }
1664         }
1665         if (grp == NULL) {
1666                 /* Create new local group */
1667                 grp = inp_localgroup_alloc(hdr, inp->inp_vflag,
1668                     inp->inp_lport, &inp->inp_inc.inc_ie.ie_dependladdr,
1669                     INP_LOCALGROUP_SIZMIN);
1670         } else if (grp->il_inpcnt == grp->il_inpsiz) {
1671                 if (grp->il_inpsiz >= INP_LOCALGROUP_SIZMAX) {
1672                         static int limit_logged = 0;
1673
1674                         if (!limit_logged) {
1675                                 limit_logged = 1;
1676                                 kprintf("local group port %d, "
1677                                     "limit reached\n", ntohs(grp->il_lport));
1678                         }
1679                         return;
1680                 }
1681
1682                 /* Expand this local group */
1683                 grp = inp_localgroup_resize(hdr, grp, grp->il_inpsiz * 2);
1684         }
1685
1686         KASSERT(grp->il_inpcnt < grp->il_inpsiz,
1687             ("invalid local group size %d and count %d",
1688              grp->il_inpsiz, grp->il_inpcnt));
1689         grp->il_inp[grp->il_inpcnt] = inp;
1690         grp->il_inpcnt++;
1691         inp_localgroup_factor(grp);
1692 }
1693
1694 void
1695 in_pcbinswildcardhash_oncpu(struct inpcb *inp, struct inpcbinfo *pcbinfo)
1696 {
1697         struct inpcontainer *ic;
1698         struct inpcontainerhead *bucket;
1699
1700         in_pcbinslocalgrphash_oncpu(inp, pcbinfo);
1701
1702         bucket = &pcbinfo->wildcardhashbase[
1703             INP_PCBWILDCARDHASH(inp->inp_lport, pcbinfo->wildcardhashmask)];
1704
1705         ic = kmalloc(sizeof(struct inpcontainer), M_TEMP, M_INTWAIT);
1706         ic->ic_inp = inp;
1707         LIST_INSERT_HEAD(bucket, ic, ic_list);
1708 }
1709
1710 /*
1711  * Insert PCB into wildcard hash table.
1712  */
1713 void
1714 in_pcbinswildcardhash(struct inpcb *inp)
1715 {
1716         struct inpcbinfo *pcbinfo = inp->inp_pcbinfo;
1717
1718         KASSERT(!(inp->inp_flags & INP_CONNECTED),
1719                 ("already on connhash"));
1720         KASSERT(!(inp->inp_flags & INP_WILDCARD),
1721                 ("already on wildcardhash"));
1722         inp->inp_flags |= INP_WILDCARD;
1723
1724         in_pcbinswildcardhash_oncpu(inp, pcbinfo);
1725 }
1726
1727 static void
1728 in_pcbremlocalgrphash_oncpu(struct inpcb *inp, struct inpcbinfo *pcbinfo)
1729 {
1730         struct inp_localgrphead *hdr;
1731         struct inp_localgroup *grp;
1732
1733         if (pcbinfo->localgrphashbase == NULL)
1734                 return;
1735
1736         hdr = &pcbinfo->localgrphashbase[
1737             INP_PCBLOCALGRPHASH(inp->inp_lport, pcbinfo->localgrphashmask)];
1738
1739         LIST_FOREACH(grp, hdr, il_list) {
1740                 int i;
1741
1742                 for (i = 0; i < grp->il_inpcnt; ++i) {
1743                         if (grp->il_inp[i] != inp)
1744                                 continue;
1745
1746                         if (grp->il_inpcnt == 1) {
1747                                 /* Free this local group */
1748                                 inp_localgroup_free(grp);
1749                         } else {
1750                                 /* Pull up inpcbs */
1751                                 for (; i + 1 < grp->il_inpcnt; ++i)
1752                                         grp->il_inp[i] = grp->il_inp[i + 1];
1753                                 grp->il_inpcnt--;
1754                                 inp_localgroup_factor(grp);
1755
1756                                 if (grp->il_inpsiz > INP_LOCALGROUP_SIZMIN &&
1757                                     grp->il_inpcnt <= (grp->il_inpsiz / 4)) {
1758                                         /* Shrink this local group */
1759                                         grp = inp_localgroup_resize(hdr, grp,
1760                                             grp->il_inpsiz / 2);
1761                                 }
1762                         }
1763                         return;
1764                 }
1765         }
1766 }
1767
1768 void
1769 in_pcbremwildcardhash_oncpu(struct inpcb *inp, struct inpcbinfo *pcbinfo)
1770 {
1771         struct inpcontainer *ic;
1772         struct inpcontainerhead *head;
1773
1774         in_pcbremlocalgrphash_oncpu(inp, pcbinfo);
1775
1776         /* find bucket */
1777         head = &pcbinfo->wildcardhashbase[
1778             INP_PCBWILDCARDHASH(inp->inp_lport, pcbinfo->wildcardhashmask)];
1779
1780         LIST_FOREACH(ic, head, ic_list) {
1781                 if (ic->ic_inp == inp)
1782                         goto found;
1783         }
1784         return;                 /* not found! */
1785
1786 found:
1787         LIST_REMOVE(ic, ic_list);       /* remove container from bucket chain */
1788         kfree(ic, M_TEMP);              /* deallocate container */
1789 }
1790
1791 /*
1792  * Remove PCB from wildcard hash table.
1793  */
1794 void
1795 in_pcbremwildcardhash(struct inpcb *inp)
1796 {
1797         struct inpcbinfo *pcbinfo = inp->inp_pcbinfo;
1798
1799         KASSERT(inp->inp_flags & INP_WILDCARD, ("inp not wildcard"));
1800         in_pcbremwildcardhash_oncpu(inp, pcbinfo);
1801         inp->inp_flags &= ~INP_WILDCARD;
1802 }
1803
1804 /*
1805  * Remove PCB from various lists.
1806  */
1807 void
1808 in_pcbremlists(struct inpcb *inp)
1809 {
1810         struct inpcbinfo *pcbinfo;
1811
1812         if (inp->inp_lport) {
1813                 struct inpcbport *phd;
1814
1815                 pcbinfo = inp->inp_pcbinfo;
1816                 if (pcbinfo->porttoken)
1817                         lwkt_gettoken(pcbinfo->porttoken);
1818
1819                 phd = inp->inp_phd;
1820                 LIST_REMOVE(inp, inp_portlist);
1821                 if (LIST_FIRST(&phd->phd_pcblist) == NULL) {
1822                         LIST_REMOVE(phd, phd_hash);
1823                         kfree(phd, M_PCB);
1824                 }
1825                 if (pcbinfo->porttoken)
1826                         lwkt_reltoken(pcbinfo->porttoken);
1827         }
1828         if (inp->inp_flags & INP_WILDCARD) {
1829                 in_pcbremwildcardhash(inp);
1830         } else if (inp->inp_flags & INP_CONNECTED) {
1831                 in_pcbremconnhash(inp);
1832         }
1833         LIST_REMOVE(inp, inp_list);
1834         inp->inp_pcbinfo->ipi_count--;
1835 }
1836
1837 int
1838 prison_xinpcb(struct thread *td, struct inpcb *inp)
1839 {
1840         struct ucred *cr;
1841
1842         if (td->td_proc == NULL)
1843                 return (0);
1844         cr = td->td_proc->p_ucred;
1845         if (cr->cr_prison == NULL)
1846                 return (0);
1847         if (inp->inp_socket && inp->inp_socket->so_cred &&
1848             inp->inp_socket->so_cred->cr_prison &&
1849             cr->cr_prison == inp->inp_socket->so_cred->cr_prison)
1850                 return (0);
1851         return (1);
1852 }
1853
1854 int
1855 in_pcblist_global(SYSCTL_HANDLER_ARGS)
1856 {
1857         struct inpcbinfo *pcbinfo = arg1;
1858         struct inpcb *inp, *marker;
1859         struct xinpcb xi;
1860         int error, i, n;
1861
1862         /*
1863          * The process of preparing the TCB list is too time-consuming and
1864          * resource-intensive to repeat twice on every request.
1865          */
1866         if (req->oldptr == NULL) {
1867                 n = pcbinfo->ipi_count;
1868                 req->oldidx = (n + n/8 + 10) * sizeof(struct xinpcb);
1869                 return 0;
1870         }
1871
1872         if (req->newptr != NULL)
1873                 return EPERM;
1874
1875         /*
1876          * OK, now we're committed to doing something.  Re-fetch ipi_count
1877          * after obtaining the generation count.
1878          */
1879         n = pcbinfo->ipi_count;
1880
1881         marker = kmalloc(sizeof(struct inpcb), M_TEMP, M_WAITOK|M_ZERO);
1882         marker->inp_flags |= INP_PLACEMARKER;
1883         LIST_INSERT_HEAD(&pcbinfo->pcblisthead, marker, inp_list);
1884
1885         i = 0;
1886         error = 0;
1887
1888         while ((inp = LIST_NEXT(marker, inp_list)) != NULL && i < n) {
1889                 LIST_REMOVE(marker, inp_list);
1890                 LIST_INSERT_AFTER(inp, marker, inp_list);
1891
1892                 if (inp->inp_flags & INP_PLACEMARKER)
1893                         continue;
1894                 if (prison_xinpcb(req->td, inp))
1895                         continue;
1896                 bzero(&xi, sizeof xi);
1897                 xi.xi_len = sizeof xi;
1898                 bcopy(inp, &xi.xi_inp, sizeof *inp);
1899                 if (inp->inp_socket)
1900                         sotoxsocket(inp->inp_socket, &xi.xi_socket);
1901                 if ((error = SYSCTL_OUT(req, &xi, sizeof xi)) != 0)
1902                         break;
1903                 ++i;
1904         }
1905         LIST_REMOVE(marker, inp_list);
1906         if (error == 0 && i < n) {
1907                 bzero(&xi, sizeof xi);
1908                 xi.xi_len = sizeof xi;
1909                 while (i < n) {
1910                         error = SYSCTL_OUT(req, &xi, sizeof xi);
1911                         ++i;
1912                 }
1913         }
1914         kfree(marker, M_TEMP);
1915         return(error);
1916 }
1917
1918 int
1919 in_pcblist_global_nomarker(SYSCTL_HANDLER_ARGS, struct xinpcb **xi0, int *nxi0)
1920 {
1921         struct inpcbinfo *pcbinfo = arg1;
1922         struct inpcb *inp;
1923         struct xinpcb *xi;
1924         int nxi;
1925
1926         *nxi0 = 0;
1927         *xi0 = NULL;
1928
1929         /*
1930          * The process of preparing the PCB list is too time-consuming and
1931          * resource-intensive to repeat twice on every request.
1932          */
1933         if (req->oldptr == NULL) {
1934                 int n = pcbinfo->ipi_count;
1935
1936                 req->oldidx = (n + n/8 + 10) * sizeof(struct xinpcb);
1937                 return 0;
1938         }
1939
1940         if (req->newptr != NULL)
1941                 return EPERM;
1942
1943         if (pcbinfo->ipi_count == 0)
1944                 return 0;
1945
1946         nxi = 0;
1947         xi = kmalloc(pcbinfo->ipi_count * sizeof(*xi), M_TEMP,
1948                      M_WAITOK | M_ZERO | M_NULLOK);
1949         if (xi == NULL)
1950                 return ENOMEM;
1951
1952         LIST_FOREACH(inp, &pcbinfo->pcblisthead, inp_list) {
1953                 struct xinpcb *xi_ptr = &xi[nxi];
1954
1955                 if (prison_xinpcb(req->td, inp))
1956                         continue;
1957
1958                 xi_ptr->xi_len = sizeof(*xi_ptr);
1959                 bcopy(inp, &xi_ptr->xi_inp, sizeof(*inp));
1960                 if (inp->inp_socket)
1961                         sotoxsocket(inp->inp_socket, &xi_ptr->xi_socket);
1962                 ++nxi;
1963         }
1964
1965         if (nxi == 0) {
1966                 kfree(xi, M_TEMP);
1967                 return 0;
1968         }
1969
1970         *nxi0 = nxi;
1971         *xi0 = xi;
1972
1973         return 0;
1974 }
1975
1976 void
1977 in_savefaddr(struct socket *so, const struct sockaddr *faddr)
1978 {
1979         struct sockaddr_in *sin;
1980
1981         KASSERT(faddr->sa_family == AF_INET,
1982             ("not AF_INET faddr %d", faddr->sa_family));
1983
1984         sin = kmalloc(sizeof(*sin), M_SONAME, M_WAITOK | M_ZERO);
1985         sin->sin_family = AF_INET;
1986         sin->sin_len = sizeof(*sin);
1987         sin->sin_port = ((const struct sockaddr_in *)faddr)->sin_port;
1988         sin->sin_addr = ((const struct sockaddr_in *)faddr)->sin_addr;
1989
1990         so->so_faddr = (struct sockaddr *)sin;
1991 }