in_pcbconn_bind: Reduce port token cover range
[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         jsin.sin_family = AF_INET;
598         jsin.sin_addr.s_addr = inp->inp_laddr.s_addr;
599         if (!prison_replace_wildcards(td, (struct sockaddr *)&jsin)) {
600                 inp->inp_laddr.s_addr = INADDR_ANY;
601                 return (EINVAL);
602         }
603         inp->inp_laddr.s_addr = jsin.sin_addr.s_addr;
604
605         inp->inp_flags |= INP_ANONPORT;
606
607         if (inp->inp_flags & INP_HIGHPORT) {
608                 first = ipport_hifirstauto;     /* sysctl */
609                 last  = ipport_hilastauto;
610                 lastport = &pcbinfo->lasthi;
611         } else if (inp->inp_flags & INP_LOWPORT) {
612                 if (cred &&
613                     (error = priv_check_cred(cred, PRIV_NETINET_RESERVEDPORT, 0))) {
614                         inp->inp_laddr.s_addr = INADDR_ANY;
615                         return (error);
616                 }
617                 first = ipport_lowfirstauto;    /* 1023 */
618                 last  = ipport_lowlastauto;     /* 600 */
619                 lastport = &pcbinfo->lastlow;
620         } else {
621                 first = ipport_firstauto;       /* sysctl */
622                 last  = ipport_lastauto;
623                 lastport = &pcbinfo->lastport;
624         }
625
626         /*
627          * This has to be atomic.  If the porthash is shared across multiple
628          * protocol threads (aka tcp) then the token will be non-NULL.
629          */
630         if (pcbinfo->porttoken)
631                 lwkt_gettoken(pcbinfo->porttoken);
632
633 again:
634         /*
635          * Simple check to ensure all ports are not used up causing
636          * a deadlock here.
637          *
638          * We split the two cases (up and down) so that the direction
639          * is not being tested on each round of the loop.
640          */
641         if (first > last) {
642                 /*
643                  * counting down
644                  */
645                 count = first - last;
646
647                 do {
648                         if (count-- < 0) {      /* completely used? */
649                                 inp->inp_laddr.s_addr = INADDR_ANY;
650                                 error = EADDRNOTAVAIL;
651                                 goto done;
652                         }
653                         --*lastport;
654                         if (*lastport > first || *lastport < last)
655                                 *lastport = first;
656                         lport = htons(*lastport);
657                 } while (in_pcblookup_addrport(pcbinfo, inp->inp_laddr, lport,
658                                 sin->sin_addr, sin->sin_port, cred));
659         } else {
660                 /*
661                  * counting up
662                  */
663                 count = last - first;
664
665                 do {
666                         if (count-- < 0) {      /* completely used? */
667                                 inp->inp_laddr.s_addr = INADDR_ANY;
668                                 error = EADDRNOTAVAIL;
669                                 goto done;
670                         }
671                         ++*lastport;
672                         if (*lastport < first || *lastport > last)
673                                 *lastport = first;
674                         lport = htons(*lastport);
675                 } while (in_pcblookup_addrport(pcbinfo, inp->inp_laddr, lport,
676                                 sin->sin_addr, sin->sin_port, cred));
677         }
678
679         /* This could happen on loopback interface */
680         if (sin->sin_port == lport &&
681             sin->sin_addr.s_addr == inp->inp_laddr.s_addr) {
682                 if (dup) {
683                         /*
684                          * Duplicate again; give up
685                          */
686                         inp->inp_laddr.s_addr = INADDR_ANY;
687                         error = EADDRNOTAVAIL;
688                         goto done;
689                 }
690                 dup = 1;
691                 goto again;
692         }
693         inp->inp_lport = lport;
694
695         if (in_pcbinsporthash(inp) != 0) {
696                 inp->inp_laddr.s_addr = INADDR_ANY;
697                 inp->inp_lport = 0;
698                 error = EAGAIN;
699                 goto done;
700         }
701         error = 0;
702 done:
703         if (pcbinfo->porttoken)
704                 lwkt_reltoken(pcbinfo->porttoken);
705         return error;
706 }
707
708 /*
709  *   Transform old in_pcbconnect() into an inner subroutine for new
710  *   in_pcbconnect(): Do some validity-checking on the remote
711  *   address (in mbuf 'nam') and then determine local host address
712  *   (i.e., which interface) to use to access that remote host.
713  *
714  *   This preserves definition of in_pcbconnect(), while supporting a
715  *   slightly different version for T/TCP.  (This is more than
716  *   a bit of a kludge, but cleaning up the internal interfaces would
717  *   have forced minor changes in every protocol).
718  */
719 int
720 in_pcbladdr_find(struct inpcb *inp, struct sockaddr *nam,
721     struct sockaddr_in **plocal_sin, struct thread *td, int find)
722 {
723         struct in_ifaddr *ia;
724         struct ucred *cred = NULL;
725         struct sockaddr_in *sin = (struct sockaddr_in *)nam;
726         struct sockaddr *jsin;
727         int jailed = 0, alloc_route = 0;
728
729         if (nam->sa_len != sizeof *sin)
730                 return (EINVAL);
731         if (sin->sin_family != AF_INET)
732                 return (EAFNOSUPPORT);
733         if (sin->sin_port == 0)
734                 return (EADDRNOTAVAIL);
735         if (td && td->td_proc && td->td_proc->p_ucred)
736                 cred = td->td_proc->p_ucred;
737         if (cred && cred->cr_prison)
738                 jailed = 1;
739         if (!TAILQ_EMPTY(&in_ifaddrheads[mycpuid])) {
740                 ia = TAILQ_FIRST(&in_ifaddrheads[mycpuid])->ia;
741                 /*
742                  * If the destination address is INADDR_ANY,
743                  * use the primary local address.
744                  * If the supplied address is INADDR_BROADCAST,
745                  * and the primary interface supports broadcast,
746                  * choose the broadcast address for that interface.
747                  */
748                 if (sin->sin_addr.s_addr == INADDR_ANY)
749                         sin->sin_addr = IA_SIN(ia)->sin_addr;
750                 else if (sin->sin_addr.s_addr == (u_long)INADDR_BROADCAST &&
751                     (ia->ia_ifp->if_flags & IFF_BROADCAST))
752                         sin->sin_addr = satosin(&ia->ia_broadaddr)->sin_addr;
753         }
754         if (find) {
755                 struct route *ro;
756
757                 ia = NULL;
758                 /*
759                  * If route is known or can be allocated now,
760                  * our src addr is taken from the i/f, else punt.
761                  * Note that we should check the address family of the cached
762                  * destination, in case of sharing the cache with IPv6.
763                  */
764                 ro = &inp->inp_route;
765                 if (ro->ro_rt &&
766                     (!(ro->ro_rt->rt_flags & RTF_UP) ||
767                      ro->ro_dst.sa_family != AF_INET ||
768                      satosin(&ro->ro_dst)->sin_addr.s_addr !=
769                                       sin->sin_addr.s_addr ||
770                      inp->inp_socket->so_options & SO_DONTROUTE)) {
771                         RTFREE(ro->ro_rt);
772                         ro->ro_rt = NULL;
773                 }
774                 if (!(inp->inp_socket->so_options & SO_DONTROUTE) && /*XXX*/
775                     (ro->ro_rt == NULL ||
776                     ro->ro_rt->rt_ifp == NULL)) {
777                         /* No route yet, so try to acquire one */
778                         bzero(&ro->ro_dst, sizeof(struct sockaddr_in));
779                         ro->ro_dst.sa_family = AF_INET;
780                         ro->ro_dst.sa_len = sizeof(struct sockaddr_in);
781                         ((struct sockaddr_in *) &ro->ro_dst)->sin_addr =
782                                 sin->sin_addr;
783                         rtalloc(ro);
784                         alloc_route = 1;
785                 }
786                 /*
787                  * If we found a route, use the address
788                  * corresponding to the outgoing interface
789                  * unless it is the loopback (in case a route
790                  * to our address on another net goes to loopback).
791                  */
792                 if (ro->ro_rt && !(ro->ro_rt->rt_ifp->if_flags & IFF_LOOPBACK)) {
793                         if (jailed) {
794                                 if (jailed_ip(cred->cr_prison, 
795                                     ro->ro_rt->rt_ifa->ifa_addr)) {
796                                         ia = ifatoia(ro->ro_rt->rt_ifa);
797                                 }
798                         } else {
799                                 ia = ifatoia(ro->ro_rt->rt_ifa);
800                         }
801                 }
802                 if (ia == NULL) {
803                         u_short fport = sin->sin_port;
804
805                         sin->sin_port = 0;
806                         ia = ifatoia(ifa_ifwithdstaddr(sintosa(sin)));
807                         if (ia && jailed && !jailed_ip(cred->cr_prison,
808                             sintosa(&ia->ia_addr)))
809                                 ia = NULL;
810                         if (ia == NULL)
811                                 ia = ifatoia(ifa_ifwithnet(sintosa(sin)));
812                         if (ia && jailed && !jailed_ip(cred->cr_prison,
813                             sintosa(&ia->ia_addr)))
814                                 ia = NULL;
815                         sin->sin_port = fport;
816                         if (ia == NULL &&
817                             !TAILQ_EMPTY(&in_ifaddrheads[mycpuid]))
818                                 ia = TAILQ_FIRST(&in_ifaddrheads[mycpuid])->ia;
819                         if (ia && jailed && !jailed_ip(cred->cr_prison,
820                             sintosa(&ia->ia_addr)))
821                                 ia = NULL;
822
823                         if (!jailed && ia == NULL)
824                                 goto fail;
825                 }
826                 /*
827                  * If the destination address is multicast and an outgoing
828                  * interface has been set as a multicast option, use the
829                  * address of that interface as our source address.
830                  */
831                 if (!jailed && IN_MULTICAST(ntohl(sin->sin_addr.s_addr)) &&
832                     inp->inp_moptions != NULL) {
833                         struct ip_moptions *imo;
834                         struct ifnet *ifp;
835
836                         imo = inp->inp_moptions;
837                         if (imo->imo_multicast_ifp != NULL) {
838                                 struct in_ifaddr_container *iac;
839
840                                 ifp = imo->imo_multicast_ifp;
841                                 ia = NULL;
842                                 TAILQ_FOREACH(iac,
843                                 &in_ifaddrheads[mycpuid], ia_link) {
844                                         if (iac->ia->ia_ifp == ifp) {
845                                                 ia = iac->ia;
846                                                 break;
847                                         }
848                                 }
849                                 if (ia == NULL)
850                                         goto fail;
851                         }
852                 }
853                 /*
854                  * Don't do pcblookup call here; return interface in plocal_sin
855                  * and exit to caller, that will do the lookup.
856                  */
857                 if (ia == NULL && jailed) {
858                         if ((jsin = prison_get_nonlocal(cred->cr_prison, AF_INET, NULL)) != NULL ||
859                             (jsin = prison_get_local(cred->cr_prison, AF_INET, NULL)) != NULL) {
860                                 *plocal_sin = satosin(jsin);
861                         } else {
862                                 /* IPv6 only Jail */
863                                 goto fail;
864                         }
865                 } else {
866                         *plocal_sin = &ia->ia_addr;
867                 }
868         }
869         return (0);
870 fail:
871         if (alloc_route) {
872                 struct route *ro = &inp->inp_route;
873
874                 if (ro->ro_rt != NULL)
875                         RTFREE(ro->ro_rt);
876                 bzero(ro, sizeof(*ro));
877         }
878         return (EADDRNOTAVAIL);
879 }
880
881 int
882 in_pcbladdr(struct inpcb *inp, struct sockaddr *nam,
883     struct sockaddr_in **plocal_sin, struct thread *td)
884 {
885         return in_pcbladdr_find(inp, nam, plocal_sin, td,
886             (inp->inp_laddr.s_addr == INADDR_ANY));
887 }
888
889 /*
890  * Outer subroutine:
891  * Connect from a socket to a specified address.
892  * Both address and port must be specified in argument sin.
893  * If don't have a local address for this socket yet,
894  * then pick one.
895  */
896 int
897 in_pcbconnect(struct inpcb *inp, struct sockaddr *nam, struct thread *td)
898 {
899         struct sockaddr_in *if_sin;
900         struct sockaddr_in *sin = (struct sockaddr_in *)nam;
901         int error;
902
903         /* Call inner routine to assign local interface address. */
904         if ((error = in_pcbladdr(inp, nam, &if_sin, td)) != 0)
905                 return (error);
906
907         if (in_pcblookup_hash(inp->inp_cpcbinfo, sin->sin_addr, sin->sin_port,
908                               inp->inp_laddr.s_addr ?
909                                 inp->inp_laddr : if_sin->sin_addr,
910                               inp->inp_lport, FALSE, NULL) != NULL) {
911                 return (EADDRINUSE);
912         }
913         if (inp->inp_laddr.s_addr == INADDR_ANY) {
914                 if (inp->inp_lport == 0) {
915                         error = in_pcbbind(inp, NULL, td);
916                         if (error)
917                                 return (error);
918                 }
919                 inp->inp_laddr = if_sin->sin_addr;
920         }
921         inp->inp_faddr = sin->sin_addr;
922         inp->inp_fport = sin->sin_port;
923         in_pcbinsconnhash(inp);
924         return (0);
925 }
926
927 void
928 in_pcbdisconnect(struct inpcb *inp)
929 {
930
931         inp->inp_faddr.s_addr = INADDR_ANY;
932         inp->inp_fport = 0;
933         in_pcbremconnhash(inp);
934         if (inp->inp_socket->so_state & SS_NOFDREF)
935                 in_pcbdetach(inp);
936 }
937
938 void
939 in_pcbdetach(struct inpcb *inp)
940 {
941         struct socket *so = inp->inp_socket;
942         struct inpcbinfo *ipi = inp->inp_pcbinfo;
943
944 #ifdef IPSEC
945         ipsec4_delete_pcbpolicy(inp);
946 #endif /*IPSEC*/
947         inp->inp_gencnt = ++ipi->ipi_gencnt;
948         KKASSERT((so->so_state & SS_ASSERTINPROG) == 0);
949         in_pcbremlists(inp);
950         so->so_pcb = NULL;
951         sofree(so);                     /* remove pcb ref */
952         if (inp->inp_options)
953                 m_free(inp->inp_options);
954         if (inp->inp_route.ro_rt)
955                 rtfree(inp->inp_route.ro_rt);
956         ip_freemoptions(inp->inp_moptions);
957         inp->inp_vflag = 0;
958         kfree(inp, M_PCB);
959 }
960
961 /*
962  * The calling convention of in_setsockaddr() and in_setpeeraddr() was
963  * modified to match the pru_sockaddr() and pru_peeraddr() entry points
964  * in struct pr_usrreqs, so that protocols can just reference then directly
965  * without the need for a wrapper function.  The socket must have a valid
966  * (i.e., non-nil) PCB, but it should be impossible to get an invalid one
967  * except through a kernel programming error, so it is acceptable to panic
968  * (or in this case trap) if the PCB is invalid.  (Actually, we don't trap
969  * because there actually /is/ a programming error somewhere... XXX)
970  */
971 int
972 in_setsockaddr(struct socket *so, struct sockaddr **nam)
973 {
974         struct inpcb *inp;
975         struct sockaddr_in *sin;
976
977         /*
978          * Do the malloc first in case it blocks.
979          */
980         sin = kmalloc(sizeof *sin, M_SONAME, M_WAITOK | M_ZERO);
981         sin->sin_family = AF_INET;
982         sin->sin_len = sizeof *sin;
983
984         crit_enter();
985         inp = so->so_pcb;
986         if (!inp) {
987                 crit_exit();
988                 kfree(sin, M_SONAME);
989                 return (ECONNRESET);
990         }
991         sin->sin_port = inp->inp_lport;
992         sin->sin_addr = inp->inp_laddr;
993         crit_exit();
994
995         *nam = (struct sockaddr *)sin;
996         return (0);
997 }
998
999 void
1000 in_setsockaddr_dispatch(netmsg_t msg)
1001 {
1002         int error;
1003
1004         error = in_setsockaddr(msg->base.nm_so, msg->peeraddr.nm_nam);
1005         lwkt_replymsg(&msg->lmsg, error);
1006 }
1007
1008 int
1009 in_setpeeraddr(struct socket *so, struct sockaddr **nam)
1010 {
1011         struct inpcb *inp;
1012         struct sockaddr_in *sin;
1013
1014         /*
1015          * Do the malloc first in case it blocks.
1016          */
1017         sin = kmalloc(sizeof *sin, M_SONAME, M_WAITOK | M_ZERO);
1018         sin->sin_family = AF_INET;
1019         sin->sin_len = sizeof *sin;
1020
1021         crit_enter();
1022         inp = so->so_pcb;
1023         if (!inp) {
1024                 crit_exit();
1025                 kfree(sin, M_SONAME);
1026                 return (ECONNRESET);
1027         }
1028         sin->sin_port = inp->inp_fport;
1029         sin->sin_addr = inp->inp_faddr;
1030         crit_exit();
1031
1032         *nam = (struct sockaddr *)sin;
1033         return (0);
1034 }
1035
1036 void
1037 in_setpeeraddr_dispatch(netmsg_t msg)
1038 {
1039         int error;
1040
1041         error = in_setpeeraddr(msg->base.nm_so, msg->peeraddr.nm_nam);
1042         lwkt_replymsg(&msg->lmsg, error);
1043 }
1044
1045 void
1046 in_pcbnotifyall(struct inpcbhead *head, struct in_addr faddr, int err,
1047                 void (*notify)(struct inpcb *, int))
1048 {
1049         struct inpcb *inp, *ninp;
1050
1051         /*
1052          * note: if INP_PLACEMARKER is set we must ignore the rest of
1053          * the structure and skip it.
1054          */
1055         crit_enter();
1056         LIST_FOREACH_MUTABLE(inp, head, inp_list, ninp) {
1057                 if (inp->inp_flags & INP_PLACEMARKER)
1058                         continue;
1059 #ifdef INET6
1060                 if (!(inp->inp_vflag & INP_IPV4))
1061                         continue;
1062 #endif
1063                 if (inp->inp_faddr.s_addr != faddr.s_addr ||
1064                     inp->inp_socket == NULL)
1065                         continue;
1066                 (*notify)(inp, err);            /* can remove inp from list! */
1067         }
1068         crit_exit();
1069 }
1070
1071 void
1072 in_pcbpurgeif0(struct inpcb *head, struct ifnet *ifp)
1073 {
1074         struct inpcb *inp;
1075         struct ip_moptions *imo;
1076         int i, gap;
1077
1078         for (inp = head; inp != NULL; inp = LIST_NEXT(inp, inp_list)) {
1079                 if (inp->inp_flags & INP_PLACEMARKER)
1080                         continue;
1081                 imo = inp->inp_moptions;
1082                 if ((inp->inp_vflag & INP_IPV4) && imo != NULL) {
1083                         /*
1084                          * Unselect the outgoing interface if it is being
1085                          * detached.
1086                          */
1087                         if (imo->imo_multicast_ifp == ifp)
1088                                 imo->imo_multicast_ifp = NULL;
1089
1090                         /*
1091                          * Drop multicast group membership if we joined
1092                          * through the interface being detached.
1093                          */
1094                         for (i = 0, gap = 0; i < imo->imo_num_memberships;
1095                             i++) {
1096                                 if (imo->imo_membership[i]->inm_ifp == ifp) {
1097                                         in_delmulti(imo->imo_membership[i]);
1098                                         gap++;
1099                                 } else if (gap != 0)
1100                                         imo->imo_membership[i - gap] =
1101                                             imo->imo_membership[i];
1102                         }
1103                         imo->imo_num_memberships -= gap;
1104                 }
1105         }
1106 }
1107
1108 /*
1109  * Check for alternatives when higher level complains
1110  * about service problems.  For now, invalidate cached
1111  * routing information.  If the route was created dynamically
1112  * (by a redirect), time to try a default gateway again.
1113  */
1114 void
1115 in_losing(struct inpcb *inp)
1116 {
1117         struct rtentry *rt;
1118         struct rt_addrinfo rtinfo;
1119
1120         if ((rt = inp->inp_route.ro_rt)) {
1121                 bzero(&rtinfo, sizeof(struct rt_addrinfo));
1122                 rtinfo.rti_info[RTAX_DST] = rt_key(rt);
1123                 rtinfo.rti_info[RTAX_GATEWAY] = rt->rt_gateway;
1124                 rtinfo.rti_info[RTAX_NETMASK] = rt_mask(rt);
1125                 rtinfo.rti_flags = rt->rt_flags;
1126                 rt_missmsg(RTM_LOSING, &rtinfo, rt->rt_flags, 0);
1127                 if (rt->rt_flags & RTF_DYNAMIC) {
1128                         rtrequest(RTM_DELETE, rt_key(rt), rt->rt_gateway,
1129                             rt_mask(rt), rt->rt_flags, NULL);
1130                 }
1131                 inp->inp_route.ro_rt = NULL;
1132                 rtfree(rt);
1133                 /*
1134                  * A new route can be allocated
1135                  * the next time output is attempted.
1136                  */
1137         }
1138 }
1139
1140 /*
1141  * After a routing change, flush old routing
1142  * and allocate a (hopefully) better one.
1143  */
1144 void
1145 in_rtchange(struct inpcb *inp, int err)
1146 {
1147         if (inp->inp_route.ro_rt) {
1148                 rtfree(inp->inp_route.ro_rt);
1149                 inp->inp_route.ro_rt = NULL;
1150                 /*
1151                  * A new route can be allocated the next time
1152                  * output is attempted.
1153                  */
1154         }
1155 }
1156
1157 /*
1158  * Lookup a PCB based on the local address and port.
1159  */
1160 struct inpcb *
1161 in_pcblookup_local(struct inpcbinfo *pcbinfo, struct in_addr laddr,
1162                    u_int lport_arg, int wild_okay, struct ucred *cred)
1163 {
1164         struct inpcb *inp;
1165         int matchwild = 3, wildcard;
1166         u_short lport = lport_arg;
1167         struct inpcbporthead *porthash;
1168         struct inpcbport *phd;
1169         struct inpcb *match = NULL;
1170
1171         /*
1172          * If the porthashbase is shared across several cpus we need
1173          * to lock.
1174          */
1175         if (pcbinfo->porttoken)
1176                 lwkt_gettoken(pcbinfo->porttoken);
1177
1178         /*
1179          * Best fit PCB lookup.
1180          *
1181          * First see if this local port is in use by looking on the
1182          * port hash list.
1183          */
1184         porthash = &pcbinfo->porthashbase[
1185                         INP_PCBPORTHASH(lport, pcbinfo->porthashmask)];
1186         LIST_FOREACH(phd, porthash, phd_hash) {
1187                 if (phd->phd_port == lport)
1188                         break;
1189         }
1190         if (phd != NULL) {
1191                 /*
1192                  * Port is in use by one or more PCBs. Look for best
1193                  * fit.
1194                  */
1195                 LIST_FOREACH(inp, &phd->phd_pcblist, inp_portlist) {
1196                         wildcard = 0;
1197 #ifdef INET6
1198                         if ((inp->inp_vflag & INP_IPV4) == 0)
1199                                 continue;
1200 #endif
1201                         if (inp->inp_faddr.s_addr != INADDR_ANY)
1202                                 wildcard++;
1203                         if (inp->inp_laddr.s_addr != INADDR_ANY) {
1204                                 if (laddr.s_addr == INADDR_ANY)
1205                                         wildcard++;
1206                                 else if (inp->inp_laddr.s_addr != laddr.s_addr)
1207                                         continue;
1208                         } else {
1209                                 if (laddr.s_addr != INADDR_ANY)
1210                                         wildcard++;
1211                         }
1212                         if (wildcard && !wild_okay)
1213                                 continue;
1214                         if (wildcard < matchwild &&
1215                             (cred == NULL ||
1216                              cred->cr_prison == 
1217                                         inp->inp_socket->so_cred->cr_prison)) {
1218                                 match = inp;
1219                                 matchwild = wildcard;
1220                                 if (matchwild == 0) {
1221                                         break;
1222                                 }
1223                         }
1224                 }
1225         }
1226         if (pcbinfo->porttoken)
1227                 lwkt_reltoken(pcbinfo->porttoken);
1228         return (match);
1229 }
1230
1231 struct inpcb *
1232 in_pcblocalgroup_last(const struct inpcbinfo *pcbinfo,
1233     const struct inpcb *inp)
1234 {
1235         const struct inp_localgrphead *hdr;
1236         const struct inp_localgroup *grp;
1237         int i;
1238
1239         if (pcbinfo->localgrphashbase == NULL)
1240                 return NULL;
1241
1242         hdr = &pcbinfo->localgrphashbase[
1243             INP_PCBLOCALGRPHASH(inp->inp_lport, pcbinfo->localgrphashmask)];
1244
1245         LIST_FOREACH(grp, hdr, il_list) {
1246                 if (grp->il_vflag == inp->inp_vflag &&
1247                     grp->il_lport == inp->inp_lport &&
1248                     memcmp(&grp->il_dependladdr,
1249                         &inp->inp_inc.inc_ie.ie_dependladdr,
1250                         sizeof(grp->il_dependladdr)) == 0) {
1251                         break;
1252                 }
1253         }
1254         if (grp == NULL || grp->il_inpcnt == 1)
1255                 return NULL;
1256
1257         KASSERT(grp->il_inpcnt >= 2,
1258             ("invalid localgroup inp count %d", grp->il_inpcnt));
1259         for (i = 0; i < grp->il_inpcnt; ++i) {
1260                 if (grp->il_inp[i] == inp) {
1261                         int last = grp->il_inpcnt - 1;
1262
1263                         if (i == last)
1264                                 last = grp->il_inpcnt - 2;
1265                         return grp->il_inp[last];
1266                 }
1267         }
1268         return NULL;
1269 }
1270
1271 static struct inpcb *
1272 inp_localgroup_lookup(const struct inpcbinfo *pcbinfo,
1273     struct in_addr laddr, uint16_t lport, uint32_t pkt_hash)
1274 {
1275         struct inpcb *local_wild = NULL;
1276         const struct inp_localgrphead *hdr;
1277         const struct inp_localgroup *grp;
1278
1279         hdr = &pcbinfo->localgrphashbase[
1280             INP_PCBLOCALGRPHASH(lport, pcbinfo->localgrphashmask)];
1281 #ifdef INP_LOCALGROUP_HASHTHR
1282         pkt_hash >>= ncpus2_shift;
1283 #endif
1284
1285         /*
1286          * Order of socket selection:
1287          * 1. non-wild.
1288          * 2. wild.
1289          *
1290          * NOTE:
1291          * - Local group does not contain jailed sockets
1292          * - Local group does not contain IPv4 mapped INET6 wild sockets
1293          */
1294         LIST_FOREACH(grp, hdr, il_list) {
1295 #ifdef INET6
1296                 if (!(grp->il_vflag & INP_IPV4))
1297                         continue;
1298 #endif
1299                 if (grp->il_lport == lport) {
1300                         int idx;
1301
1302 #ifdef INP_LOCALGROUP_HASHTHR
1303                         idx = pkt_hash / grp->il_factor;
1304                         KASSERT(idx < grp->il_inpcnt && idx >= 0,
1305                             ("invalid hash %04x, cnt %d or fact %d",
1306                              pkt_hash, grp->il_inpcnt, grp->il_factor));
1307 #else
1308                         /*
1309                          * Modulo-N is used here, which greatly reduces
1310                          * completion queue token contention, thus more
1311                          * cpu time is saved.
1312                          */
1313                         idx = pkt_hash % grp->il_inpcnt;
1314 #endif
1315
1316                         if (grp->il_laddr.s_addr == laddr.s_addr)
1317                                 return grp->il_inp[idx];
1318                         else if (grp->il_laddr.s_addr == INADDR_ANY)
1319                                 local_wild = grp->il_inp[idx];
1320                 }
1321         }
1322         if (local_wild != NULL)
1323                 return local_wild;
1324         return NULL;
1325 }
1326
1327 /*
1328  * Lookup PCB in hash list.
1329  */
1330 struct inpcb *
1331 in_pcblookup_pkthash(struct inpcbinfo *pcbinfo, struct in_addr faddr,
1332     u_int fport_arg, struct in_addr laddr, u_int lport_arg,
1333     boolean_t wildcard, struct ifnet *ifp, const struct mbuf *m)
1334 {
1335         struct inpcbhead *head;
1336         struct inpcb *inp, *jinp=NULL;
1337         u_short fport = fport_arg, lport = lport_arg;
1338
1339         /*
1340          * First look for an exact match.
1341          */
1342         head = &pcbinfo->hashbase[INP_PCBCONNHASH(faddr.s_addr, fport,
1343             laddr.s_addr, lport, pcbinfo->hashmask)];
1344         LIST_FOREACH(inp, head, inp_hash) {
1345 #ifdef INET6
1346                 if (!(inp->inp_vflag & INP_IPV4))
1347                         continue;
1348 #endif
1349                 if (in_hosteq(inp->inp_faddr, faddr) &&
1350                     in_hosteq(inp->inp_laddr, laddr) &&
1351                     inp->inp_fport == fport && inp->inp_lport == lport) {
1352                         /* found */
1353                         if (inp->inp_socket == NULL ||
1354                             inp->inp_socket->so_cred->cr_prison == NULL) {
1355                                 return (inp);
1356                         } else {
1357                                 if  (jinp == NULL)
1358                                         jinp = inp;
1359                         }
1360                 }
1361         }
1362         if (jinp != NULL)
1363                 return (jinp);
1364         if (wildcard) {
1365                 struct inpcb *local_wild = NULL;
1366                 struct inpcb *jinp_wild = NULL;
1367 #ifdef INET6
1368                 struct inpcb *local_wild_mapped = NULL;
1369 #endif
1370                 struct inpcontainer *ic;
1371                 struct inpcontainerhead *chead;
1372                 struct sockaddr_in jsin;
1373                 struct ucred *cred;
1374
1375                 /*
1376                  * Check local group first
1377                  */
1378                 if (pcbinfo->localgrphashbase != NULL &&
1379                     m != NULL && (m->m_flags & M_HASH) &&
1380                     !(ifp && ifp->if_type == IFT_FAITH)) {
1381                         inp = inp_localgroup_lookup(pcbinfo,
1382                             laddr, lport, m->m_pkthdr.hash);
1383                         if (inp != NULL)
1384                                 return inp;
1385                 }
1386
1387                 /*
1388                  * Order of socket selection:
1389                  * 1. non-jailed, non-wild.
1390                  * 2. non-jailed, wild.
1391                  * 3. jailed, non-wild.
1392                  * 4. jailed, wild.
1393                  */
1394                 jsin.sin_family = AF_INET;
1395                 chead = &pcbinfo->wildcardhashbase[
1396                     INP_PCBWILDCARDHASH(lport, pcbinfo->wildcardhashmask)];
1397                 LIST_FOREACH(ic, chead, ic_list) {
1398                         inp = ic->ic_inp;
1399                         jsin.sin_addr.s_addr = laddr.s_addr;
1400 #ifdef INET6
1401                         if (!(inp->inp_vflag & INP_IPV4))
1402                                 continue;
1403 #endif
1404                         if (inp->inp_socket != NULL)
1405                                 cred = inp->inp_socket->so_cred;
1406                         else
1407                                 cred = NULL;
1408                         if (cred != NULL && jailed(cred)) {
1409                                 if (jinp != NULL)
1410                                         continue;
1411                                 else
1412                                         if (!jailed_ip(cred->cr_prison,
1413                                             (struct sockaddr *)&jsin))
1414                                                 continue;
1415                         }
1416                         if (inp->inp_lport == lport) {
1417                                 if (ifp && ifp->if_type == IFT_FAITH &&
1418                                     !(inp->inp_flags & INP_FAITH))
1419                                         continue;
1420                                 if (inp->inp_laddr.s_addr == laddr.s_addr) {
1421                                         if (cred != NULL && jailed(cred))
1422                                                 jinp = inp;
1423                                         else
1424                                                 return (inp);
1425                                 }
1426                                 if (inp->inp_laddr.s_addr == INADDR_ANY) {
1427 #ifdef INET6
1428                                         if (INP_CHECK_SOCKAF(inp->inp_socket,
1429                                                              AF_INET6))
1430                                                 local_wild_mapped = inp;
1431                                         else
1432 #endif
1433                                                 if (cred != NULL &&
1434                                                     jailed(cred))
1435                                                         jinp_wild = inp;
1436                                                 else
1437                                                         local_wild = inp;
1438                                 }
1439                         }
1440                 }
1441                 if (local_wild != NULL)
1442                         return (local_wild);
1443 #ifdef INET6
1444                 if (local_wild_mapped != NULL)
1445                         return (local_wild_mapped);
1446 #endif
1447                 if (jinp != NULL)
1448                         return (jinp);
1449                 return (jinp_wild);
1450         }
1451
1452         /*
1453          * Not found.
1454          */
1455         return (NULL);
1456 }
1457
1458 struct inpcb *
1459 in_pcblookup_hash(struct inpcbinfo *pcbinfo, struct in_addr faddr,
1460     u_int fport_arg, struct in_addr laddr, u_int lport_arg,
1461     boolean_t wildcard, struct ifnet *ifp)
1462 {
1463         return in_pcblookup_pkthash(pcbinfo, faddr, fport_arg,
1464             laddr, lport_arg, wildcard, ifp, NULL);
1465 }
1466
1467 /*
1468  * Insert PCB into connection hash table.
1469  */
1470 void
1471 in_pcbinsconnhash(struct inpcb *inp)
1472 {
1473         struct inpcbinfo *pcbinfo = inp->inp_cpcbinfo;
1474         struct inpcbhead *bucket;
1475         u_int32_t hashkey_faddr, hashkey_laddr;
1476
1477 #ifdef INET6
1478         if (inp->inp_vflag & INP_IPV6) {
1479                 hashkey_faddr = inp->in6p_faddr.s6_addr32[3] /* XXX JH */;
1480                 hashkey_laddr = inp->in6p_laddr.s6_addr32[3] /* XXX JH */;
1481         } else {
1482 #endif
1483                 hashkey_faddr = inp->inp_faddr.s_addr;
1484                 hashkey_laddr = inp->inp_laddr.s_addr;
1485 #ifdef INET6
1486         }
1487 #endif
1488
1489         KASSERT(!(inp->inp_flags & INP_WILDCARD),
1490                 ("already on wildcardhash"));
1491         KASSERT(!(inp->inp_flags & INP_CONNECTED),
1492                 ("already on connhash"));
1493         inp->inp_flags |= INP_CONNECTED;
1494
1495         /*
1496          * Insert into the connection hash table.
1497          */
1498         bucket = &pcbinfo->hashbase[INP_PCBCONNHASH(hashkey_faddr,
1499             inp->inp_fport, hashkey_laddr, inp->inp_lport, pcbinfo->hashmask)];
1500         LIST_INSERT_HEAD(bucket, inp, inp_hash);
1501 }
1502
1503 /*
1504  * Remove PCB from connection hash table.
1505  */
1506 void
1507 in_pcbremconnhash(struct inpcb *inp)
1508 {
1509         KASSERT(inp->inp_flags & INP_CONNECTED, ("inp not connected"));
1510         LIST_REMOVE(inp, inp_hash);
1511         inp->inp_flags &= ~INP_CONNECTED;
1512 }
1513
1514 /*
1515  * Insert PCB into port hash table.
1516  */
1517 int
1518 in_pcbinsporthash(struct inpcb *inp)
1519 {
1520         struct inpcbinfo *pcbinfo = inp->inp_pcbinfo;
1521         struct inpcbporthead *pcbporthash;
1522         struct inpcbport *phd;
1523
1524         /*
1525          * If the porthashbase is shared across several cpus we need
1526          * to lock.
1527          */
1528         if (pcbinfo->porttoken)
1529                 lwkt_gettoken(pcbinfo->porttoken);
1530
1531         /*
1532          * Insert into the port hash table.
1533          */
1534         pcbporthash = &pcbinfo->porthashbase[
1535             INP_PCBPORTHASH(inp->inp_lport, pcbinfo->porthashmask)];
1536
1537         /* Go through port list and look for a head for this lport. */
1538         LIST_FOREACH(phd, pcbporthash, phd_hash) {
1539                 if (phd->phd_port == inp->inp_lport)
1540                         break;
1541         }
1542
1543         /* If none exists, malloc one and tack it on. */
1544         if (phd == NULL) {
1545                 KKASSERT(pcbinfo->portsave != NULL);
1546                 phd = pcbinfo->portsave;
1547                 pcbinfo->portsave = NULL;
1548                 phd->phd_port = inp->inp_lport;
1549                 LIST_INIT(&phd->phd_pcblist);
1550                 LIST_INSERT_HEAD(pcbporthash, phd, phd_hash);
1551         }
1552
1553         inp->inp_phd = phd;
1554         LIST_INSERT_HEAD(&phd->phd_pcblist, inp, inp_portlist);
1555
1556         if (pcbinfo->porttoken)
1557                 lwkt_reltoken(pcbinfo->porttoken);
1558         if (pcbinfo->portsave == NULL) {
1559                 pcbinfo->portsave = kmalloc(sizeof(*pcbinfo->portsave),
1560                                             M_PCB, M_INTWAIT | M_ZERO);
1561         }
1562         return (0);
1563 }
1564
1565 static struct inp_localgroup *
1566 inp_localgroup_alloc(struct inp_localgrphead *hdr, u_char vflag,
1567     uint16_t port, const union in_dependaddr *addr, int size)
1568 {
1569         struct inp_localgroup *grp;
1570
1571         grp = kmalloc(__offsetof(struct inp_localgroup, il_inp[size]),
1572             M_TEMP, M_INTWAIT | M_ZERO);
1573         grp->il_vflag = vflag;
1574         grp->il_lport = port;
1575         grp->il_dependladdr = *addr;
1576         grp->il_inpsiz = size;
1577
1578         LIST_INSERT_HEAD(hdr, grp, il_list);
1579
1580         return grp;
1581 }
1582
1583 static void
1584 inp_localgroup_free(struct inp_localgroup *grp)
1585 {
1586         LIST_REMOVE(grp, il_list);
1587         kfree(grp, M_TEMP);
1588 }
1589
1590 static struct inp_localgroup *
1591 inp_localgroup_resize(struct inp_localgrphead *hdr,
1592     struct inp_localgroup *old_grp, int size)
1593 {
1594         struct inp_localgroup *grp;
1595         int i;
1596
1597         grp = inp_localgroup_alloc(hdr, old_grp->il_vflag,
1598             old_grp->il_lport, &old_grp->il_dependladdr, size);
1599
1600         KASSERT(old_grp->il_inpcnt < grp->il_inpsiz,
1601             ("invalid new local group size %d and old local group count %d",
1602              grp->il_inpsiz, old_grp->il_inpcnt));
1603         for (i = 0; i < old_grp->il_inpcnt; ++i)
1604                 grp->il_inp[i] = old_grp->il_inp[i];
1605         grp->il_inpcnt = old_grp->il_inpcnt;
1606         grp->il_factor = old_grp->il_factor;
1607
1608         inp_localgroup_free(old_grp);
1609
1610         return grp;
1611 }
1612
1613 static void
1614 inp_localgroup_factor(struct inp_localgroup *grp)
1615 {
1616         grp->il_factor =
1617             ((uint32_t)(0xffff >> ncpus2_shift) / grp->il_inpcnt) + 1;
1618         KASSERT(grp->il_factor != 0, ("invalid local group factor, "
1619             "ncpus2_shift %d, inpcnt %d", ncpus2_shift, grp->il_inpcnt));
1620 }
1621
1622 static void
1623 in_pcbinslocalgrphash_oncpu(struct inpcb *inp, struct inpcbinfo *pcbinfo)
1624 {
1625         struct inp_localgrphead *hdr;
1626         struct inp_localgroup *grp;
1627         struct ucred *cred;
1628
1629         if (pcbinfo->localgrphashbase == NULL)
1630                 return;
1631
1632         /*
1633          * XXX don't allow jailed socket to join local group
1634          */
1635         if (inp->inp_socket != NULL)
1636                 cred = inp->inp_socket->so_cred;
1637         else
1638                 cred = NULL;
1639         if (cred != NULL && jailed(cred))
1640                 return;
1641
1642 #ifdef INET6
1643         /*
1644          * XXX don't allow IPv4 mapped INET6 wild socket
1645          */
1646         if ((inp->inp_vflag & INP_IPV4) &&
1647             inp->inp_laddr.s_addr == INADDR_ANY &&
1648             INP_CHECK_SOCKAF(inp->inp_socket, AF_INET6))
1649                 return;
1650 #endif
1651
1652         hdr = &pcbinfo->localgrphashbase[
1653             INP_PCBLOCALGRPHASH(inp->inp_lport, pcbinfo->localgrphashmask)];
1654
1655         LIST_FOREACH(grp, hdr, il_list) {
1656                 if (grp->il_vflag == inp->inp_vflag &&
1657                     grp->il_lport == inp->inp_lport &&
1658                     memcmp(&grp->il_dependladdr,
1659                         &inp->inp_inc.inc_ie.ie_dependladdr,
1660                         sizeof(grp->il_dependladdr)) == 0) {
1661                         break;
1662                 }
1663         }
1664         if (grp == NULL) {
1665                 /* Create new local group */
1666                 grp = inp_localgroup_alloc(hdr, inp->inp_vflag,
1667                     inp->inp_lport, &inp->inp_inc.inc_ie.ie_dependladdr,
1668                     INP_LOCALGROUP_SIZMIN);
1669         } else if (grp->il_inpcnt == grp->il_inpsiz) {
1670                 if (grp->il_inpsiz >= INP_LOCALGROUP_SIZMAX) {
1671                         static int limit_logged = 0;
1672
1673                         if (!limit_logged) {
1674                                 limit_logged = 1;
1675                                 kprintf("local group port %d, "
1676                                     "limit reached\n", ntohs(grp->il_lport));
1677                         }
1678                         return;
1679                 }
1680
1681                 /* Expand this local group */
1682                 grp = inp_localgroup_resize(hdr, grp, grp->il_inpsiz * 2);
1683         }
1684
1685         KASSERT(grp->il_inpcnt < grp->il_inpsiz,
1686             ("invalid local group size %d and count %d",
1687              grp->il_inpsiz, grp->il_inpcnt));
1688         grp->il_inp[grp->il_inpcnt] = inp;
1689         grp->il_inpcnt++;
1690         inp_localgroup_factor(grp);
1691 }
1692
1693 void
1694 in_pcbinswildcardhash_oncpu(struct inpcb *inp, struct inpcbinfo *pcbinfo)
1695 {
1696         struct inpcontainer *ic;
1697         struct inpcontainerhead *bucket;
1698
1699         in_pcbinslocalgrphash_oncpu(inp, pcbinfo);
1700
1701         bucket = &pcbinfo->wildcardhashbase[
1702             INP_PCBWILDCARDHASH(inp->inp_lport, pcbinfo->wildcardhashmask)];
1703
1704         ic = kmalloc(sizeof(struct inpcontainer), M_TEMP, M_INTWAIT);
1705         ic->ic_inp = inp;
1706         LIST_INSERT_HEAD(bucket, ic, ic_list);
1707 }
1708
1709 /*
1710  * Insert PCB into wildcard hash table.
1711  */
1712 void
1713 in_pcbinswildcardhash(struct inpcb *inp)
1714 {
1715         struct inpcbinfo *pcbinfo = inp->inp_pcbinfo;
1716
1717         KASSERT(!(inp->inp_flags & INP_CONNECTED),
1718                 ("already on connhash"));
1719         KASSERT(!(inp->inp_flags & INP_WILDCARD),
1720                 ("already on wildcardhash"));
1721         inp->inp_flags |= INP_WILDCARD;
1722
1723         in_pcbinswildcardhash_oncpu(inp, pcbinfo);
1724 }
1725
1726 static void
1727 in_pcbremlocalgrphash_oncpu(struct inpcb *inp, struct inpcbinfo *pcbinfo)
1728 {
1729         struct inp_localgrphead *hdr;
1730         struct inp_localgroup *grp;
1731
1732         if (pcbinfo->localgrphashbase == NULL)
1733                 return;
1734
1735         hdr = &pcbinfo->localgrphashbase[
1736             INP_PCBLOCALGRPHASH(inp->inp_lport, pcbinfo->localgrphashmask)];
1737
1738         LIST_FOREACH(grp, hdr, il_list) {
1739                 int i;
1740
1741                 for (i = 0; i < grp->il_inpcnt; ++i) {
1742                         if (grp->il_inp[i] != inp)
1743                                 continue;
1744
1745                         if (grp->il_inpcnt == 1) {
1746                                 /* Free this local group */
1747                                 inp_localgroup_free(grp);
1748                         } else {
1749                                 /* Pull up inpcbs */
1750                                 for (; i + 1 < grp->il_inpcnt; ++i)
1751                                         grp->il_inp[i] = grp->il_inp[i + 1];
1752                                 grp->il_inpcnt--;
1753                                 inp_localgroup_factor(grp);
1754
1755                                 if (grp->il_inpsiz > INP_LOCALGROUP_SIZMIN &&
1756                                     grp->il_inpcnt <= (grp->il_inpsiz / 4)) {
1757                                         /* Shrink this local group */
1758                                         grp = inp_localgroup_resize(hdr, grp,
1759                                             grp->il_inpsiz / 2);
1760                                 }
1761                         }
1762                         return;
1763                 }
1764         }
1765 }
1766
1767 void
1768 in_pcbremwildcardhash_oncpu(struct inpcb *inp, struct inpcbinfo *pcbinfo)
1769 {
1770         struct inpcontainer *ic;
1771         struct inpcontainerhead *head;
1772
1773         in_pcbremlocalgrphash_oncpu(inp, pcbinfo);
1774
1775         /* find bucket */
1776         head = &pcbinfo->wildcardhashbase[
1777             INP_PCBWILDCARDHASH(inp->inp_lport, pcbinfo->wildcardhashmask)];
1778
1779         LIST_FOREACH(ic, head, ic_list) {
1780                 if (ic->ic_inp == inp)
1781                         goto found;
1782         }
1783         return;                 /* not found! */
1784
1785 found:
1786         LIST_REMOVE(ic, ic_list);       /* remove container from bucket chain */
1787         kfree(ic, M_TEMP);              /* deallocate container */
1788 }
1789
1790 /*
1791  * Remove PCB from wildcard hash table.
1792  */
1793 void
1794 in_pcbremwildcardhash(struct inpcb *inp)
1795 {
1796         struct inpcbinfo *pcbinfo = inp->inp_pcbinfo;
1797
1798         KASSERT(inp->inp_flags & INP_WILDCARD, ("inp not wildcard"));
1799         in_pcbremwildcardhash_oncpu(inp, pcbinfo);
1800         inp->inp_flags &= ~INP_WILDCARD;
1801 }
1802
1803 /*
1804  * Remove PCB from various lists.
1805  */
1806 void
1807 in_pcbremlists(struct inpcb *inp)
1808 {
1809         struct inpcbinfo *pcbinfo;
1810
1811         if (inp->inp_lport) {
1812                 struct inpcbport *phd;
1813
1814                 pcbinfo = inp->inp_pcbinfo;
1815                 if (pcbinfo->porttoken)
1816                         lwkt_gettoken(pcbinfo->porttoken);
1817
1818                 phd = inp->inp_phd;
1819                 LIST_REMOVE(inp, inp_portlist);
1820                 if (LIST_FIRST(&phd->phd_pcblist) == NULL) {
1821                         LIST_REMOVE(phd, phd_hash);
1822                         kfree(phd, M_PCB);
1823                 }
1824                 if (pcbinfo->porttoken)
1825                         lwkt_reltoken(pcbinfo->porttoken);
1826         }
1827         if (inp->inp_flags & INP_WILDCARD) {
1828                 in_pcbremwildcardhash(inp);
1829         } else if (inp->inp_flags & INP_CONNECTED) {
1830                 in_pcbremconnhash(inp);
1831         }
1832         LIST_REMOVE(inp, inp_list);
1833         inp->inp_pcbinfo->ipi_count--;
1834 }
1835
1836 int
1837 prison_xinpcb(struct thread *td, struct inpcb *inp)
1838 {
1839         struct ucred *cr;
1840
1841         if (td->td_proc == NULL)
1842                 return (0);
1843         cr = td->td_proc->p_ucred;
1844         if (cr->cr_prison == NULL)
1845                 return (0);
1846         if (inp->inp_socket && inp->inp_socket->so_cred &&
1847             inp->inp_socket->so_cred->cr_prison &&
1848             cr->cr_prison == inp->inp_socket->so_cred->cr_prison)
1849                 return (0);
1850         return (1);
1851 }
1852
1853 int
1854 in_pcblist_global(SYSCTL_HANDLER_ARGS)
1855 {
1856         struct inpcbinfo *pcbinfo = arg1;
1857         struct inpcb *inp, *marker;
1858         struct xinpcb xi;
1859         int error, i, n;
1860
1861         /*
1862          * The process of preparing the TCB list is too time-consuming and
1863          * resource-intensive to repeat twice on every request.
1864          */
1865         if (req->oldptr == NULL) {
1866                 n = pcbinfo->ipi_count;
1867                 req->oldidx = (n + n/8 + 10) * sizeof(struct xinpcb);
1868                 return 0;
1869         }
1870
1871         if (req->newptr != NULL)
1872                 return EPERM;
1873
1874         /*
1875          * OK, now we're committed to doing something.  Re-fetch ipi_count
1876          * after obtaining the generation count.
1877          */
1878         n = pcbinfo->ipi_count;
1879
1880         marker = kmalloc(sizeof(struct inpcb), M_TEMP, M_WAITOK|M_ZERO);
1881         marker->inp_flags |= INP_PLACEMARKER;
1882         LIST_INSERT_HEAD(&pcbinfo->pcblisthead, marker, inp_list);
1883
1884         i = 0;
1885         error = 0;
1886
1887         while ((inp = LIST_NEXT(marker, inp_list)) != NULL && i < n) {
1888                 LIST_REMOVE(marker, inp_list);
1889                 LIST_INSERT_AFTER(inp, marker, inp_list);
1890
1891                 if (inp->inp_flags & INP_PLACEMARKER)
1892                         continue;
1893                 if (prison_xinpcb(req->td, inp))
1894                         continue;
1895                 bzero(&xi, sizeof xi);
1896                 xi.xi_len = sizeof xi;
1897                 bcopy(inp, &xi.xi_inp, sizeof *inp);
1898                 if (inp->inp_socket)
1899                         sotoxsocket(inp->inp_socket, &xi.xi_socket);
1900                 if ((error = SYSCTL_OUT(req, &xi, sizeof xi)) != 0)
1901                         break;
1902                 ++i;
1903         }
1904         LIST_REMOVE(marker, inp_list);
1905         if (error == 0 && i < n) {
1906                 bzero(&xi, sizeof xi);
1907                 xi.xi_len = sizeof xi;
1908                 while (i < n) {
1909                         error = SYSCTL_OUT(req, &xi, sizeof xi);
1910                         ++i;
1911                 }
1912         }
1913         kfree(marker, M_TEMP);
1914         return(error);
1915 }
1916
1917 int
1918 in_pcblist_global_nomarker(SYSCTL_HANDLER_ARGS, struct xinpcb **xi0, int *nxi0)
1919 {
1920         struct inpcbinfo *pcbinfo = arg1;
1921         struct inpcb *inp;
1922         struct xinpcb *xi;
1923         int nxi;
1924
1925         *nxi0 = 0;
1926         *xi0 = NULL;
1927
1928         /*
1929          * The process of preparing the PCB list is too time-consuming and
1930          * resource-intensive to repeat twice on every request.
1931          */
1932         if (req->oldptr == NULL) {
1933                 int n = pcbinfo->ipi_count;
1934
1935                 req->oldidx = (n + n/8 + 10) * sizeof(struct xinpcb);
1936                 return 0;
1937         }
1938
1939         if (req->newptr != NULL)
1940                 return EPERM;
1941
1942         if (pcbinfo->ipi_count == 0)
1943                 return 0;
1944
1945         nxi = 0;
1946         xi = kmalloc(pcbinfo->ipi_count * sizeof(*xi), M_TEMP,
1947                      M_WAITOK | M_ZERO | M_NULLOK);
1948         if (xi == NULL)
1949                 return ENOMEM;
1950
1951         LIST_FOREACH(inp, &pcbinfo->pcblisthead, inp_list) {
1952                 struct xinpcb *xi_ptr = &xi[nxi];
1953
1954                 if (prison_xinpcb(req->td, inp))
1955                         continue;
1956
1957                 xi_ptr->xi_len = sizeof(*xi_ptr);
1958                 bcopy(inp, &xi_ptr->xi_inp, sizeof(*inp));
1959                 if (inp->inp_socket)
1960                         sotoxsocket(inp->inp_socket, &xi_ptr->xi_socket);
1961                 ++nxi;
1962         }
1963
1964         if (nxi == 0) {
1965                 kfree(xi, M_TEMP);
1966                 return 0;
1967         }
1968
1969         *nxi0 = nxi;
1970         *xi0 = xi;
1971
1972         return 0;
1973 }
1974
1975 void
1976 in_savefaddr(struct socket *so, const struct sockaddr *faddr)
1977 {
1978         struct sockaddr_in *sin;
1979
1980         KASSERT(faddr->sa_family == AF_INET,
1981             ("not AF_INET faddr %d", faddr->sa_family));
1982
1983         sin = kmalloc(sizeof(*sin), M_SONAME, M_WAITOK | M_ZERO);
1984         sin->sin_family = AF_INET;
1985         sin->sin_len = sizeof(*sin);
1986         sin->sin_port = ((const struct sockaddr_in *)faddr)->sin_port;
1987         sin->sin_addr = ((const struct sockaddr_in *)faddr)->sin_addr;
1988
1989         so->so_faddr = (struct sockaddr *)sin;
1990 }