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