Once we distribute socket protocol processing requests to different
[dragonfly.git] / sys / netinet / udp_usrreq.c
1 /*
2  * Copyright (c) 1982, 1986, 1988, 1990, 1993, 1995
3  *      The Regents of the University of California.  All rights reserved.
4  *
5  * Redistribution and use in source and binary forms, with or without
6  * modification, are permitted provided that the following conditions
7  * are met:
8  * 1. Redistributions of source code must retain the above copyright
9  *    notice, this list of conditions and the following disclaimer.
10  * 2. Redistributions in binary form must reproduce the above copyright
11  *    notice, this list of conditions and the following disclaimer in the
12  *    documentation and/or other materials provided with the distribution.
13  * 3. All advertising materials mentioning features or use of this software
14  *    must display the following acknowledgement:
15  *      This product includes software developed by the University of
16  *      California, Berkeley and its contributors.
17  * 4. Neither the name of the University nor the names of its contributors
18  *    may be used to endorse or promote products derived from this software
19  *    without specific prior written permission.
20  *
21  * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
22  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
23  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
24  * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
25  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
26  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
27  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
28  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
29  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
30  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
31  * SUCH DAMAGE.
32  *
33  *      @(#)udp_usrreq.c        8.6 (Berkeley) 5/23/95
34  * $FreeBSD: src/sys/netinet/udp_usrreq.c,v 1.64.2.18 2003/01/24 05:11:34 sam Exp $
35  * $DragonFly: src/sys/netinet/udp_usrreq.c,v 1.12 2004/03/05 16:57:15 hsu Exp $
36  */
37
38 #include "opt_ipsec.h"
39 #include "opt_inet6.h"
40
41 #include <sys/param.h>
42 #include <sys/systm.h>
43 #include <sys/kernel.h>
44 #include <sys/malloc.h>
45 #include <sys/mbuf.h>
46 #include <sys/domain.h>
47 #include <sys/proc.h>
48 #include <sys/protosw.h>
49 #include <sys/socket.h>
50 #include <sys/socketvar.h>
51 #include <sys/sysctl.h>
52 #include <sys/syslog.h>
53 #include <sys/in_cksum.h>
54
55 #include <vm/vm_zone.h>
56
57 #include <net/if.h>
58 #include <net/route.h>
59
60 #include <netinet/in.h>
61 #include <netinet/in_systm.h>
62 #include <netinet/ip.h>
63 #ifdef INET6
64 #include <netinet/ip6.h>
65 #endif
66 #include <netinet/in_pcb.h>
67 #include <netinet/in_var.h>
68 #include <netinet/ip_var.h>
69 #ifdef INET6
70 #include <netinet6/ip6_var.h>
71 #endif
72 #include <netinet/ip_icmp.h>
73 #include <netinet/icmp_var.h>
74 #include <netinet/udp.h>
75 #include <netinet/udp_var.h>
76
77 #ifdef FAST_IPSEC
78 #include <netipsec/ipsec.h>
79 #endif /*FAST_IPSEC*/
80
81 #ifdef IPSEC
82 #include <netinet6/ipsec.h>
83 #endif /*IPSEC*/
84
85 /*
86  * UDP protocol implementation.
87  * Per RFC 768, August, 1980.
88  */
89 #ifndef COMPAT_42
90 static int      udpcksum = 1;
91 #else
92 static int      udpcksum = 0;           /* XXX */
93 #endif
94 SYSCTL_INT(_net_inet_udp, UDPCTL_CHECKSUM, checksum, CTLFLAG_RW,
95                 &udpcksum, 0, "");
96
97 int     log_in_vain = 0;
98 SYSCTL_INT(_net_inet_udp, OID_AUTO, log_in_vain, CTLFLAG_RW, 
99     &log_in_vain, 0, "Log all incoming UDP packets");
100
101 static int      blackhole = 0;
102 SYSCTL_INT(_net_inet_udp, OID_AUTO, blackhole, CTLFLAG_RW,
103         &blackhole, 0, "Do not send port unreachables for refused connects");
104
105 static int      strict_mcast_mship = 1;
106 SYSCTL_INT(_net_inet_udp, OID_AUTO, strict_mcast_mship, CTLFLAG_RW,
107         &strict_mcast_mship, 0, "Only send multicast to member sockets");
108
109 struct  inpcbhead udb;          /* from udp_var.h */
110 #define udb6    udb  /* for KAME src sync over BSD*'s */
111 struct  inpcbinfo udbinfo;
112
113 #ifndef UDBHASHSIZE
114 #define UDBHASHSIZE 16
115 #endif
116
117 struct  udpstat udpstat;        /* from udp_var.h */
118 SYSCTL_STRUCT(_net_inet_udp, UDPCTL_STATS, stats, CTLFLAG_RW,
119     &udpstat, udpstat, "UDP statistics (struct udpstat, netinet/udp_var.h)");
120
121 static struct   sockaddr_in udp_in = { sizeof(udp_in), AF_INET };
122 #ifdef INET6
123 struct udp_in6 {
124         struct sockaddr_in6     uin6_sin;
125         u_char                  uin6_init_done : 1;
126 } udp_in6 = {
127         { sizeof(udp_in6.uin6_sin), AF_INET6 },
128         0
129 };
130 struct udp_ip6 {
131         struct ip6_hdr          uip6_ip6;
132         u_char                  uip6_init_done : 1;
133 } udp_ip6;
134 #endif /* INET6 */
135
136 static void udp_append (struct inpcb *last, struct ip *ip,
137                             struct mbuf *n, int off);
138 #ifdef INET6
139 static void ip_2_ip6_hdr (struct ip6_hdr *ip6, struct ip *ip);
140 #endif
141
142 static int udp_detach (struct socket *so);
143 static  int udp_output (struct inpcb *, struct mbuf *, struct sockaddr *,
144                             struct mbuf *, struct thread *);
145
146 void
147 udp_init()
148 {
149         LIST_INIT(&udb);
150         udbinfo.listhead = &udb;
151         udbinfo.hashbase = hashinit(UDBHASHSIZE, M_PCB, &udbinfo.hashmask);
152         udbinfo.porthashbase = hashinit(UDBHASHSIZE, M_PCB,
153                                         &udbinfo.porthashmask);
154         udbinfo.bindhashbase = hashinit(UDBHASHSIZE, M_PCB,
155                                         &udbinfo.bindhashmask);
156         udbinfo.ipi_zone = zinit("udpcb", sizeof(struct inpcb), maxsockets,
157                                  ZONE_INTERRUPT, 0);
158         udp_thread_init();
159 }
160
161 /*
162  * Check multicast packets to make sure they are only sent to sockets with
163  * multicast memberships for the packet's destination address and arrival
164  * interface.  Multicast packets to multicast-unaware sockets are also
165  * disallowed.
166  *
167  * Returns 0 if the packet is acceptable, -1 if it is not.
168  */
169 static __inline
170 int
171 check_multicast_membership(struct ip *ip, struct inpcb *inp, struct mbuf *m)
172 {
173         int mshipno;
174         struct ip_moptions *mopt;
175
176         if (strict_mcast_mship == 0 ||
177             !IN_MULTICAST(ntohl(ip->ip_dst.s_addr))) {
178                 return(0);
179         }
180         mopt = inp->inp_moptions;
181         if (mopt == NULL)
182                 return(-1);
183         for (mshipno = 0; mshipno <= mopt->imo_num_memberships; ++mshipno) {
184                 if (ip->ip_dst.s_addr == mopt->imo_membership[mshipno]->inm_addr.s_addr &&
185                     m->m_pkthdr.rcvif == mopt->imo_membership[mshipno]->inm_ifp) {
186                         return(0);
187                 }
188         }
189         return(-1);
190 }
191
192 void
193 udp_input(m, off, proto)
194         struct mbuf *m;
195         int off, proto;
196 {
197         int iphlen = off;
198         struct ip *ip;
199         struct udphdr *uh;
200         struct inpcb *inp;
201         struct mbuf *opts = 0;
202         int len;
203         struct ip save_ip;
204         struct sockaddr *append_sa;
205
206         udpstat.udps_ipackets++;
207
208         /*
209          * Strip IP options, if any; should skip this,
210          * make available to user, and use on returned packets,
211          * but we don't yet have a way to check the checksum
212          * with options still present.
213          */
214         if (iphlen > sizeof (struct ip)) {
215                 ip_stripoptions(m, (struct mbuf *)0);
216                 iphlen = sizeof(struct ip);
217         }
218
219         /*
220          * Get IP and UDP header together in first mbuf.
221          */
222         ip = mtod(m, struct ip *);
223         if (m->m_len < iphlen + sizeof(struct udphdr)) {
224                 if ((m = m_pullup(m, iphlen + sizeof(struct udphdr))) == 0) {
225                         udpstat.udps_hdrops++;
226                         return;
227                 }
228                 ip = mtod(m, struct ip *);
229         }
230         uh = (struct udphdr *)((caddr_t)ip + iphlen);
231
232         /* destination port of 0 is illegal, based on RFC768. */
233         if (uh->uh_dport == 0)
234                 goto bad;
235
236         /*
237          * Make mbuf data length reflect UDP length.
238          * If not enough data to reflect UDP length, drop.
239          */
240         len = ntohs((u_short)uh->uh_ulen);
241         if (ip->ip_len != len) {
242                 if (len > ip->ip_len || len < sizeof(struct udphdr)) {
243                         udpstat.udps_badlen++;
244                         goto bad;
245                 }
246                 m_adj(m, len - ip->ip_len);
247                 /* ip->ip_len = len; */
248         }
249         /*
250          * Save a copy of the IP header in case we want restore it
251          * for sending an ICMP error message in response.
252          */
253         save_ip = *ip;
254
255         /*
256          * Checksum extended UDP header and data.
257          */
258         if (uh->uh_sum) {
259                 if (m->m_pkthdr.csum_flags & CSUM_DATA_VALID) {
260                         if (m->m_pkthdr.csum_flags & CSUM_PSEUDO_HDR)
261                                 uh->uh_sum = m->m_pkthdr.csum_data;
262                         else
263                                 uh->uh_sum = in_pseudo(ip->ip_src.s_addr,
264                                     ip->ip_dst.s_addr, htonl((u_short)len +
265                                     m->m_pkthdr.csum_data + IPPROTO_UDP));
266                         uh->uh_sum ^= 0xffff;
267                 } else {
268                         char b[9];
269                         bcopy(((struct ipovly *)ip)->ih_x1, b, 9);
270                         bzero(((struct ipovly *)ip)->ih_x1, 9);
271                         ((struct ipovly *)ip)->ih_len = uh->uh_ulen;
272                         uh->uh_sum = in_cksum(m, len + sizeof (struct ip));
273                         bcopy(b, ((struct ipovly *)ip)->ih_x1, 9);
274                 }
275                 if (uh->uh_sum) {
276                         udpstat.udps_badsum++;
277                         m_freem(m);
278                         return;
279                 }
280         } else
281                 udpstat.udps_nosum++;
282
283         if (IN_MULTICAST(ntohl(ip->ip_dst.s_addr)) ||
284             in_broadcast(ip->ip_dst, m->m_pkthdr.rcvif)) {
285                 struct inpcb *last;
286                 /*
287                  * Deliver a multicast or broadcast datagram to *all* sockets
288                  * for which the local and remote addresses and ports match
289                  * those of the incoming datagram.  This allows more than
290                  * one process to receive multi/broadcasts on the same port.
291                  * (This really ought to be done for unicast datagrams as
292                  * well, but that would cause problems with existing
293                  * applications that open both address-specific sockets and
294                  * a wildcard socket listening to the same port -- they would
295                  * end up receiving duplicates of every unicast datagram.
296                  * Those applications open the multiple sockets to overcome an
297                  * inadequacy of the UDP socket interface, but for backwards
298                  * compatibility we avoid the problem here rather than
299                  * fixing the interface.  Maybe 4.5BSD will remedy this?)
300                  */
301
302                 /*
303                  * Construct sockaddr format source address.
304                  */
305                 udp_in.sin_port = uh->uh_sport;
306                 udp_in.sin_addr = ip->ip_src;
307                 /*
308                  * Locate pcb(s) for datagram.
309                  * (Algorithm copied from raw_intr().)
310                  */
311                 last = NULL;
312 #ifdef INET6
313                 udp_in6.uin6_init_done = udp_ip6.uip6_init_done = 0;
314 #endif
315                 LIST_FOREACH(inp, &udb, inp_list) {
316 #ifdef INET6
317                         if ((inp->inp_vflag & INP_IPV4) == 0)
318                                 continue;
319 #endif
320                         if (inp->inp_lport != uh->uh_dport)
321                                 continue;
322                         if (inp->inp_laddr.s_addr != INADDR_ANY) {
323                                 if (inp->inp_laddr.s_addr !=
324                                     ip->ip_dst.s_addr)
325                                         continue;
326                         }
327                         if (inp->inp_faddr.s_addr != INADDR_ANY) {
328                                 if (inp->inp_faddr.s_addr !=
329                                     ip->ip_src.s_addr ||
330                                     inp->inp_fport != uh->uh_sport)
331                                         continue;
332                         }
333
334                         if (check_multicast_membership(ip, inp, m) < 0)
335                                 continue;
336
337                         if (last != NULL) {
338                                 struct mbuf *n;
339
340 #ifdef IPSEC
341                                 /* check AH/ESP integrity. */
342                                 if (ipsec4_in_reject_so(m, last->inp_socket))
343                                         ipsecstat.in_polvio++;
344                                         /* do not inject data to pcb */
345                                 else
346 #endif /*IPSEC*/
347 #ifdef FAST_IPSEC
348                                 /* check AH/ESP integrity. */
349                                 if (ipsec4_in_reject(m, last))
350                                         ;
351                                 else
352 #endif /*FAST_IPSEC*/
353                                 if ((n = m_copy(m, 0, M_COPYALL)) != NULL)
354                                         udp_append(last, ip, n,
355                                                    iphlen +
356                                                    sizeof(struct udphdr));
357                         }
358                         last = inp;
359                         /*
360                          * Don't look for additional matches if this one does
361                          * not have either the SO_REUSEPORT or SO_REUSEADDR
362                          * socket options set.  This heuristic avoids searching
363                          * through all pcbs in the common case of a non-shared
364                          * port.  It * assumes that an application will never
365                          * clear these options after setting them.
366                          */
367                         if ((last->inp_socket->so_options&(SO_REUSEPORT|SO_REUSEADDR)) == 0)
368                                 break;
369                 }
370
371                 if (last == NULL) {
372                         /*
373                          * No matching pcb found; discard datagram.
374                          * (No need to send an ICMP Port Unreachable
375                          * for a broadcast or multicast datgram.)
376                          */
377                         udpstat.udps_noportbcast++;
378                         goto bad;
379                 }
380 #ifdef IPSEC
381                 /* check AH/ESP integrity. */
382                 if (ipsec4_in_reject_so(m, last->inp_socket)) {
383                         ipsecstat.in_polvio++;
384                         goto bad;
385                 }
386 #endif /*IPSEC*/
387 #ifdef FAST_IPSEC
388                 /* check AH/ESP integrity. */
389                 if (ipsec4_in_reject(m, last))
390                         goto bad;
391 #endif /*FAST_IPSEC*/
392                 udp_append(last, ip, m, iphlen + sizeof(struct udphdr));
393                 return;
394         }
395         /*
396          * Locate pcb for datagram.
397          */
398         inp = in_pcblookup_hash(&udbinfo, ip->ip_src, uh->uh_sport,
399             ip->ip_dst, uh->uh_dport, 1, m->m_pkthdr.rcvif);
400         if (inp == NULL) {
401                 if (log_in_vain) {
402                         char buf[4*sizeof "123"];
403
404                         strcpy(buf, inet_ntoa(ip->ip_dst));
405                         log(LOG_INFO,
406                             "Connection attempt to UDP %s:%d from %s:%d\n",
407                             buf, ntohs(uh->uh_dport), inet_ntoa(ip->ip_src),
408                             ntohs(uh->uh_sport));
409                 }
410                 udpstat.udps_noport++;
411                 if (m->m_flags & (M_BCAST | M_MCAST)) {
412                         udpstat.udps_noportbcast++;
413                         goto bad;
414                 }
415                 if (blackhole)
416                         goto bad;
417 #ifdef ICMP_BANDLIM
418                 if (badport_bandlim(BANDLIM_ICMP_UNREACH) < 0)
419                         goto bad;
420 #endif
421                 *ip = save_ip;
422                 ip->ip_len += iphlen;
423                 icmp_error(m, ICMP_UNREACH, ICMP_UNREACH_PORT, 0, 0);
424                 return;
425         }
426 #ifdef IPSEC
427         if (ipsec4_in_reject_so(m, inp->inp_socket)) {
428                 ipsecstat.in_polvio++;
429                 goto bad;
430         }
431 #endif /*IPSEC*/
432 #ifdef FAST_IPSEC
433         if (ipsec4_in_reject(m, inp))
434                 goto bad;
435 #endif /*FAST_IPSEC*/
436
437         /*
438          * Construct sockaddr format source address.
439          * Stuff source address and datagram in user buffer.
440          */
441         udp_in.sin_port = uh->uh_sport;
442         udp_in.sin_addr = ip->ip_src;
443         if (inp->inp_flags & INP_CONTROLOPTS
444             || inp->inp_socket->so_options & SO_TIMESTAMP) {
445 #ifdef INET6
446                 if (inp->inp_vflag & INP_IPV6) {
447                         int savedflags;
448
449                         ip_2_ip6_hdr(&udp_ip6.uip6_ip6, ip);
450                         savedflags = inp->inp_flags;
451                         inp->inp_flags &= ~INP_UNMAPPABLEOPTS;
452                         ip6_savecontrol(inp, &opts, &udp_ip6.uip6_ip6, m);
453                         inp->inp_flags = savedflags;
454                 } else
455 #endif
456                 ip_savecontrol(inp, &opts, ip, m);
457         }
458         m_adj(m, iphlen + sizeof(struct udphdr));
459 #ifdef INET6
460         if (inp->inp_vflag & INP_IPV6) {
461                 in6_sin_2_v4mapsin6(&udp_in, &udp_in6.uin6_sin);
462                 append_sa = (struct sockaddr *)&udp_in6;
463         } else
464 #endif
465         append_sa = (struct sockaddr *)&udp_in;
466         if (sbappendaddr(&inp->inp_socket->so_rcv, append_sa, m, opts) == 0) {
467                 udpstat.udps_fullsock++;
468                 goto bad;
469         }
470         sorwakeup(inp->inp_socket);
471         return;
472 bad:
473         m_freem(m);
474         if (opts)
475                 m_freem(opts);
476         return;
477 }
478
479 #ifdef INET6
480 static void
481 ip_2_ip6_hdr(ip6, ip)
482         struct ip6_hdr *ip6;
483         struct ip *ip;
484 {
485         bzero(ip6, sizeof(*ip6));
486
487         ip6->ip6_vfc = IPV6_VERSION;
488         ip6->ip6_plen = ip->ip_len;
489         ip6->ip6_nxt = ip->ip_p;
490         ip6->ip6_hlim = ip->ip_ttl;
491         ip6->ip6_src.s6_addr32[2] = ip6->ip6_dst.s6_addr32[2] =
492                 IPV6_ADDR_INT32_SMP;
493         ip6->ip6_src.s6_addr32[3] = ip->ip_src.s_addr;
494         ip6->ip6_dst.s6_addr32[3] = ip->ip_dst.s_addr;
495 }
496 #endif
497
498 /*
499  * subroutine of udp_input(), mainly for source code readability.
500  * caller must properly init udp_ip6 and udp_in6 beforehand.
501  */
502 static void
503 udp_append(last, ip, n, off)
504         struct inpcb *last;
505         struct ip *ip;
506         struct mbuf *n;
507         int off;
508 {
509         struct sockaddr *append_sa;
510         struct mbuf *opts = 0;
511
512         if (last->inp_flags & INP_CONTROLOPTS ||
513             last->inp_socket->so_options & SO_TIMESTAMP) {
514 #ifdef INET6
515                 if (last->inp_vflag & INP_IPV6) {
516                         int savedflags;
517
518                         if (udp_ip6.uip6_init_done == 0) {
519                                 ip_2_ip6_hdr(&udp_ip6.uip6_ip6, ip);
520                                 udp_ip6.uip6_init_done = 1;
521                         }
522                         savedflags = last->inp_flags;
523                         last->inp_flags &= ~INP_UNMAPPABLEOPTS;
524                         ip6_savecontrol(last, &opts, &udp_ip6.uip6_ip6, n);
525                         last->inp_flags = savedflags;
526                 } else
527 #endif
528                 ip_savecontrol(last, &opts, ip, n);
529         }
530 #ifdef INET6
531         if (last->inp_vflag & INP_IPV6) {
532                 if (udp_in6.uin6_init_done == 0) {
533                         in6_sin_2_v4mapsin6(&udp_in, &udp_in6.uin6_sin);
534                         udp_in6.uin6_init_done = 1;
535                 }
536                 append_sa = (struct sockaddr *)&udp_in6.uin6_sin;
537         } else
538 #endif
539         append_sa = (struct sockaddr *)&udp_in;
540         m_adj(n, off);
541         if (sbappendaddr(&last->inp_socket->so_rcv, append_sa, n, opts) == 0) {
542                 m_freem(n);
543                 if (opts)
544                         m_freem(opts);
545                 udpstat.udps_fullsock++;
546         } else
547                 sorwakeup(last->inp_socket);
548 }
549
550 /*
551  * Notify a udp user of an asynchronous error;
552  * just wake up so that he can collect error status.
553  */
554 void
555 udp_notify(inp, errno)
556         struct inpcb *inp;
557         int errno;
558 {
559         inp->inp_socket->so_error = errno;
560         sorwakeup(inp->inp_socket);
561         sowwakeup(inp->inp_socket);
562 }
563
564 void
565 udp_ctlinput(cmd, sa, vip)
566         int cmd;
567         struct sockaddr *sa;
568         void *vip;
569 {
570         struct ip *ip = vip;
571         struct udphdr *uh;
572         void (*notify) (struct inpcb *, int) = udp_notify;
573         struct in_addr faddr;
574         struct inpcb *inp;
575         int s;
576
577         faddr = ((struct sockaddr_in *)sa)->sin_addr;
578         if (sa->sa_family != AF_INET || faddr.s_addr == INADDR_ANY)
579                 return;
580
581         if (PRC_IS_REDIRECT(cmd)) {
582                 ip = 0;
583                 notify = in_rtchange;
584         } else if (cmd == PRC_HOSTDEAD)
585                 ip = 0;
586         else if ((unsigned)cmd >= PRC_NCMDS || inetctlerrmap[cmd] == 0)
587                 return;
588         if (ip) {
589                 s = splnet();
590                 uh = (struct udphdr *)((caddr_t)ip + (ip->ip_hl << 2));
591                 inp = in_pcblookup_hash(&udbinfo, faddr, uh->uh_dport,
592                     ip->ip_src, uh->uh_sport, 0, NULL);
593                 if (inp != NULL && inp->inp_socket != NULL)
594                         (*notify)(inp, inetctlerrmap[cmd]);
595                 splx(s);
596         } else
597                 in_pcbnotifyall(&udb, faddr, inetctlerrmap[cmd], notify);
598 }
599
600 static int
601 udp_pcblist(SYSCTL_HANDLER_ARGS)
602 {
603         int error, i, n, s;
604         struct inpcb *inp, **inp_list;
605         inp_gen_t gencnt;
606         struct xinpgen xig;
607
608         /*
609          * The process of preparing the TCB list is too time-consuming and
610          * resource-intensive to repeat twice on every request.
611          */
612         if (req->oldptr == 0) {
613                 n = udbinfo.ipi_count;
614                 req->oldidx = 2 * (sizeof xig)
615                         + (n + n/8) * sizeof(struct xinpcb);
616                 return 0;
617         }
618
619         if (req->newptr != 0)
620                 return EPERM;
621
622         /*
623          * OK, now we're committed to doing something.
624          */
625         s = splnet();
626         gencnt = udbinfo.ipi_gencnt;
627         n = udbinfo.ipi_count;
628         splx(s);
629
630         xig.xig_len = sizeof xig;
631         xig.xig_count = n;
632         xig.xig_gen = gencnt;
633         xig.xig_sogen = so_gencnt;
634         error = SYSCTL_OUT(req, &xig, sizeof xig);
635         if (error)
636                 return error;
637
638         inp_list = malloc(n * sizeof *inp_list, M_TEMP, M_WAITOK);
639         if (inp_list == 0)
640                 return ENOMEM;
641         
642         s = splnet();
643         for (inp = LIST_FIRST(udbinfo.listhead), i = 0; inp && i < n;
644              inp = LIST_NEXT(inp, inp_list)) {
645                 if (inp->inp_gencnt <= gencnt && !prison_xinpcb(req->td, inp))
646                         inp_list[i++] = inp;
647         }
648         splx(s);
649         n = i;
650
651         error = 0;
652         for (i = 0; i < n; i++) {
653                 inp = inp_list[i];
654                 if (inp->inp_gencnt <= gencnt) {
655                         struct xinpcb xi;
656                         xi.xi_len = sizeof xi;
657                         /* XXX should avoid extra copy */
658                         bcopy(inp, &xi.xi_inp, sizeof *inp);
659                         if (inp->inp_socket)
660                                 sotoxsocket(inp->inp_socket, &xi.xi_socket);
661                         error = SYSCTL_OUT(req, &xi, sizeof xi);
662                 }
663         }
664         if (!error) {
665                 /*
666                  * Give the user an updated idea of our state.
667                  * If the generation differs from what we told
668                  * her before, she knows that something happened
669                  * while we were processing this request, and it
670                  * might be necessary to retry.
671                  */
672                 s = splnet();
673                 xig.xig_gen = udbinfo.ipi_gencnt;
674                 xig.xig_sogen = so_gencnt;
675                 xig.xig_count = udbinfo.ipi_count;
676                 splx(s);
677                 error = SYSCTL_OUT(req, &xig, sizeof xig);
678         }
679         free(inp_list, M_TEMP);
680         return error;
681 }
682
683 SYSCTL_PROC(_net_inet_udp, UDPCTL_PCBLIST, pcblist, CTLFLAG_RD, 0, 0,
684             udp_pcblist, "S,xinpcb", "List of active UDP sockets");
685
686 static int
687 udp_getcred(SYSCTL_HANDLER_ARGS)
688 {
689         struct sockaddr_in addrs[2];
690         struct inpcb *inp;
691         int error, s;
692
693         error = suser(req->td);
694         if (error)
695                 return (error);
696         error = SYSCTL_IN(req, addrs, sizeof(addrs));
697         if (error)
698                 return (error);
699         s = splnet();
700         inp = in_pcblookup_hash(&udbinfo, addrs[1].sin_addr, addrs[1].sin_port,
701                                 addrs[0].sin_addr, addrs[0].sin_port, 1, NULL);
702         if (inp == NULL || inp->inp_socket == NULL) {
703                 error = ENOENT;
704                 goto out;
705         }
706         error = SYSCTL_OUT(req, inp->inp_socket->so_cred, sizeof(struct ucred));
707 out:
708         splx(s);
709         return (error);
710 }
711
712 SYSCTL_PROC(_net_inet_udp, OID_AUTO, getcred, CTLTYPE_OPAQUE|CTLFLAG_RW,
713     0, 0, udp_getcred, "S,ucred", "Get the ucred of a UDP connection");
714
715 static int
716 udp_output(inp, m, addr, control, td)
717         struct inpcb *inp;
718         struct mbuf *m;
719         struct sockaddr *addr;
720         struct mbuf *control;
721         struct thread *td;
722 {
723         struct udpiphdr *ui;
724         int len = m->m_pkthdr.len;
725         struct in_addr laddr;
726         struct sockaddr_in *sin;
727         int s = 0, error = 0;
728
729         if (control)
730                 m_freem(control);               /* XXX */
731
732         if (len + sizeof(struct udpiphdr) > IP_MAXPACKET) {
733                 error = EMSGSIZE;
734                 goto release;
735         }
736
737         if (addr) {
738                 sin = (struct sockaddr_in *)addr;
739                 prison_remote_ip(td, 0, &sin->sin_addr.s_addr);
740                 laddr = inp->inp_laddr;
741                 if (inp->inp_faddr.s_addr != INADDR_ANY) {
742                         error = EISCONN;
743                         goto release;
744                 }
745                 /*
746                  * Must block input while temporarily connected.
747                  */
748                 s = splnet();
749                 error = in_pcbconnect(inp, addr, td);
750                 if (error) {
751                         splx(s);
752                         goto release;
753                 }
754         } else {
755                 if (inp->inp_faddr.s_addr == INADDR_ANY) {
756                         error = ENOTCONN;
757                         goto release;
758                 }
759         }
760         /*
761          * Calculate data length and get a mbuf
762          * for UDP and IP headers.
763          */
764         M_PREPEND(m, sizeof(struct udpiphdr), M_DONTWAIT);
765         if (m == 0) {
766                 error = ENOBUFS;
767                 if (addr)
768                         splx(s);
769                 goto release;
770         }
771
772         /*
773          * Fill in mbuf with extended UDP header
774          * and addresses and length put into network format.
775          */
776         ui = mtod(m, struct udpiphdr *);
777         bzero(ui->ui_x1, sizeof(ui->ui_x1));    /* XXX still needed? */
778         ui->ui_pr = IPPROTO_UDP;
779         ui->ui_src = inp->inp_laddr;
780         ui->ui_dst = inp->inp_faddr;
781         ui->ui_sport = inp->inp_lport;
782         ui->ui_dport = inp->inp_fport;
783         ui->ui_ulen = htons((u_short)len + sizeof(struct udphdr));
784
785         /*
786          * Set up checksum and output datagram.
787          */
788         if (udpcksum) {
789                 ui->ui_sum = in_pseudo(ui->ui_src.s_addr, ui->ui_dst.s_addr,
790                     htons((u_short)len + sizeof(struct udphdr) + IPPROTO_UDP));
791                 m->m_pkthdr.csum_flags = CSUM_UDP;
792                 m->m_pkthdr.csum_data = offsetof(struct udphdr, uh_sum);
793         } else {
794                 ui->ui_sum = 0;
795         }
796         ((struct ip *)ui)->ip_len = sizeof (struct udpiphdr) + len;
797         ((struct ip *)ui)->ip_ttl = inp->inp_ip_ttl;    /* XXX */
798         ((struct ip *)ui)->ip_tos = inp->inp_ip_tos;    /* XXX */
799         udpstat.udps_opackets++;
800
801         error = ip_output(m, inp->inp_options, &inp->inp_route,
802             (inp->inp_socket->so_options & (SO_DONTROUTE | SO_BROADCAST)),
803             inp->inp_moptions, inp);
804
805         if (addr) {
806                 in_pcbdisconnect(inp);
807                 inp->inp_laddr = laddr;
808                 in_pcbinsbindhash(inp);
809                 splx(s);
810         }
811         return (error);
812
813 release:
814         m_freem(m);
815         return (error);
816 }
817
818 u_long  udp_sendspace = 9216;           /* really max datagram size */
819                                         /* 40 1K datagrams */
820 SYSCTL_INT(_net_inet_udp, UDPCTL_MAXDGRAM, maxdgram, CTLFLAG_RW,
821     &udp_sendspace, 0, "Maximum outgoing UDP datagram size");
822
823 u_long  udp_recvspace = 40 * (1024 +
824 #ifdef INET6
825                                       sizeof(struct sockaddr_in6)
826 #else
827                                       sizeof(struct sockaddr_in)
828 #endif
829                                       );
830 SYSCTL_INT(_net_inet_udp, UDPCTL_RECVSPACE, recvspace, CTLFLAG_RW,
831     &udp_recvspace, 0, "Maximum incoming UDP datagram size");
832
833 static int
834 udp_abort(struct socket *so)
835 {
836         struct inpcb *inp;
837         int s;
838
839         inp = sotoinpcb(so);
840         if (inp == 0)
841                 return EINVAL;  /* ??? possible? panic instead? */
842         soisdisconnected(so);
843         s = splnet();
844         in_pcbdetach(inp);
845         splx(s);
846         return 0;
847 }
848
849 static int
850 udp_attach(struct socket *so, int proto, struct pru_attach_info *ai)
851 {
852         struct inpcb *inp;
853         int s, error;
854
855         inp = sotoinpcb(so);
856         if (inp != 0)
857                 return EINVAL;
858
859         error = soreserve(so, udp_sendspace, udp_recvspace, ai->sb_rlimit);
860         if (error)
861                 return error;
862         s = splnet();
863         error = in_pcballoc(so, &udbinfo);
864         splx(s);
865         if (error)
866                 return error;
867
868         inp = (struct inpcb *)so->so_pcb;
869         inp->inp_vflag |= INP_IPV4;
870         inp->inp_ip_ttl = ip_defttl;
871         return 0;
872 }
873
874 static int
875 udp_bind(struct socket *so, struct sockaddr *nam, struct thread *td)
876 {
877         struct inpcb *inp;
878         int s, error;
879
880         inp = sotoinpcb(so);
881         if (inp == 0)
882                 return EINVAL;
883         s = splnet();
884         error = in_pcbbind(inp, nam, td);
885         splx(s);
886         return error;
887 }
888
889 static int
890 udp_connect(struct socket *so, struct sockaddr *nam, struct thread *td)
891 {
892         struct inpcb *inp;
893         int s, error;
894         struct sockaddr_in *sin;
895
896         inp = sotoinpcb(so);
897         if (inp == 0)
898                 return EINVAL;
899         if (inp->inp_faddr.s_addr != INADDR_ANY)
900                 return EISCONN;
901         error = 0;
902         s = splnet();
903         if (inp->inp_laddr.s_addr == INADDR_ANY && 
904             td->td_proc &&
905             td->td_proc->p_ucred->cr_prison != NULL) {
906                 error = in_pcbbind(inp, NULL, td);
907         }
908         if (error == 0) {
909                 sin = (struct sockaddr_in *)nam;
910                 prison_remote_ip(td, 0, &sin->sin_addr.s_addr);
911                 error = in_pcbconnect(inp, nam, td);
912         }
913         splx(s);
914         if (error == 0)
915                 soisconnected(so);
916         return error;
917 }
918
919 static int
920 udp_detach(struct socket *so)
921 {
922         struct inpcb *inp;
923         int s;
924
925         inp = sotoinpcb(so);
926         if (inp == 0)
927                 return EINVAL;
928         s = splnet();
929         in_pcbdetach(inp);
930         splx(s);
931         return 0;
932 }
933
934 static int
935 udp_disconnect(struct socket *so)
936 {
937         struct inpcb *inp;
938         int s;
939
940         inp = sotoinpcb(so);
941         if (inp == 0)
942                 return EINVAL;
943         if (inp->inp_faddr.s_addr == INADDR_ANY)
944                 return ENOTCONN;
945
946         s = splnet();
947         in_pcbdisconnect(inp);
948         inp->inp_laddr.s_addr = INADDR_ANY;
949         in_pcbinsbindhash(inp);
950         splx(s);
951         so->so_state &= ~SS_ISCONNECTED;                /* XXX */
952         return 0;
953 }
954
955 static int
956 udp_send(struct socket *so, int flags, struct mbuf *m, struct sockaddr *addr,
957             struct mbuf *control, struct thread *td)
958 {
959         struct inpcb *inp;
960
961         inp = sotoinpcb(so);
962         if (inp == 0) {
963                 m_freem(m);
964                 return EINVAL;
965         }
966         return udp_output(inp, m, addr, control, td);
967 }
968
969 int
970 udp_shutdown(struct socket *so)
971 {
972         struct inpcb *inp;
973
974         inp = sotoinpcb(so);
975         if (inp == 0)
976                 return EINVAL;
977         socantsendmore(so);
978         return 0;
979 }
980
981 struct pr_usrreqs udp_usrreqs = {
982         udp_abort, pru_accept_notsupp, udp_attach, udp_bind, udp_connect, 
983         pru_connect2_notsupp, in_control, udp_detach, udp_disconnect, 
984         pru_listen_notsupp, in_setpeeraddr, pru_rcvd_notsupp, 
985         pru_rcvoob_notsupp, udp_send, pru_sense_null, udp_shutdown,
986         in_setsockaddr, sosend, soreceive, sopoll
987 };
988