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