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