network - Completely revamp the netisr / dispatch code
[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) 1982, 1986, 1988, 1990, 1993, 1995
36  *      The Regents of the University of California.  All rights reserved.
37  *
38  * Redistribution and use in source and binary forms, with or without
39  * modification, are permitted provided that the following conditions
40  * are met:
41  * 1. Redistributions of source code must retain the above copyright
42  *    notice, this list of conditions and the following disclaimer.
43  * 2. Redistributions in binary form must reproduce the above copyright
44  *    notice, this list of conditions and the following disclaimer in the
45  *    documentation and/or other materials provided with the distribution.
46  * 3. All advertising materials mentioning features or use of this software
47  *    must display the following acknowledgement:
48  *      This product includes software developed by the University of
49  *      California, Berkeley and its contributors.
50  * 4. Neither the name of the University nor the names of its contributors
51  *    may be used to endorse or promote products derived from this software
52  *    without specific prior written permission.
53  *
54  * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
55  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
56  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
57  * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
58  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
59  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
60  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
61  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
62  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
63  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
64  * SUCH DAMAGE.
65  *
66  *      @(#)udp_usrreq.c        8.6 (Berkeley) 5/23/95
67  * $FreeBSD: src/sys/netinet/udp_usrreq.c,v 1.64.2.18 2003/01/24 05:11:34 sam Exp $
68  * $DragonFly: src/sys/netinet/udp_usrreq.c,v 1.47 2008/11/11 10:46:58 sephe Exp $
69  */
70
71 #include "opt_ipsec.h"
72 #include "opt_inet6.h"
73
74 #include <sys/param.h>
75 #include <sys/systm.h>
76 #include <sys/kernel.h>
77 #include <sys/malloc.h>
78 #include <sys/mbuf.h>
79 #include <sys/domain.h>
80 #include <sys/proc.h>
81 #include <sys/priv.h>
82 #include <sys/protosw.h>
83 #include <sys/socket.h>
84 #include <sys/socketvar.h>
85 #include <sys/sysctl.h>
86 #include <sys/syslog.h>
87 #include <sys/thread2.h>
88 #include <sys/in_cksum.h>
89
90 #include <machine/stdarg.h>
91
92 #include <net/if.h>
93 #include <net/route.h>
94 #include <net/netmsg2.h>
95
96 #include <netinet/in.h>
97 #include <netinet/in_systm.h>
98 #include <netinet/ip.h>
99 #ifdef INET6
100 #include <netinet/ip6.h>
101 #endif
102 #include <netinet/in_pcb.h>
103 #include <netinet/in_var.h>
104 #include <netinet/ip_var.h>
105 #ifdef INET6
106 #include <netinet6/ip6_var.h>
107 #endif
108 #include <netinet/ip_icmp.h>
109 #include <netinet/icmp_var.h>
110 #include <netinet/udp.h>
111 #include <netinet/udp_var.h>
112
113 #ifdef FAST_IPSEC
114 #include <netproto/ipsec/ipsec.h>
115 #endif
116
117 #ifdef IPSEC
118 #include <netinet6/ipsec.h>
119 #endif
120
121 /*
122  * UDP protocol implementation.
123  * Per RFC 768, August, 1980.
124  */
125 #ifndef COMPAT_42
126 static int      udpcksum = 1;
127 #else
128 static int      udpcksum = 0;           /* XXX */
129 #endif
130 SYSCTL_INT(_net_inet_udp, UDPCTL_CHECKSUM, checksum, CTLFLAG_RW,
131                 &udpcksum, 0, "");
132
133 int     log_in_vain = 0;
134 SYSCTL_INT(_net_inet_udp, OID_AUTO, log_in_vain, CTLFLAG_RW,
135     &log_in_vain, 0, "Log all incoming UDP packets");
136
137 static int      blackhole = 0;
138 SYSCTL_INT(_net_inet_udp, OID_AUTO, blackhole, CTLFLAG_RW,
139         &blackhole, 0, "Do not send port unreachables for refused connects");
140
141 static int      strict_mcast_mship = 1;
142 SYSCTL_INT(_net_inet_udp, OID_AUTO, strict_mcast_mship, CTLFLAG_RW,
143         &strict_mcast_mship, 0, "Only send multicast to member sockets");
144
145 struct  inpcbinfo udbinfo;
146
147 #ifndef UDBHASHSIZE
148 #define UDBHASHSIZE 16
149 #endif
150
151 struct  udpstat udpstat;        /* from udp_var.h */
152 SYSCTL_STRUCT(_net_inet_udp, UDPCTL_STATS, stats, CTLFLAG_RW,
153     &udpstat, udpstat, "UDP statistics (struct udpstat, netinet/udp_var.h)");
154
155 static struct   sockaddr_in udp_in = { sizeof udp_in, AF_INET };
156 #ifdef INET6
157 struct udp_in6 {
158         struct sockaddr_in6     uin6_sin;
159         u_char                  uin6_init_done : 1;
160 } udp_in6 = {
161         { sizeof udp_in6.uin6_sin, AF_INET6 },
162         0
163 };
164 struct udp_ip6 {
165         struct ip6_hdr          uip6_ip6;
166         u_char                  uip6_init_done : 1;
167 } udp_ip6;
168 #endif /* INET6 */
169
170 static void udp_append (struct inpcb *last, struct ip *ip,
171                             struct mbuf *n, int off);
172 #ifdef INET6
173 static void ip_2_ip6_hdr (struct ip6_hdr *ip6, struct ip *ip);
174 #endif
175
176 static int udp_connect_oncpu(struct socket *so, struct thread *td,
177                         struct sockaddr_in *sin, struct sockaddr_in *if_sin);
178 static int udp_detach (struct socket *so);
179 static  int udp_output (struct inpcb *, struct mbuf *, struct sockaddr *,
180                             struct mbuf *, struct thread *);
181
182 void
183 udp_init(void)
184 {
185         in_pcbinfo_init(&udbinfo);
186         udbinfo.hashbase = hashinit(UDBHASHSIZE, M_PCB, &udbinfo.hashmask);
187         udbinfo.porthashbase = hashinit(UDBHASHSIZE, M_PCB,
188                                         &udbinfo.porthashmask);
189         udbinfo.wildcardhashbase = hashinit(UDBHASHSIZE, M_PCB,
190                                             &udbinfo.wildcardhashmask);
191         udbinfo.ipi_size = sizeof(struct inpcb);
192 }
193
194 /*
195  * Check multicast packets to make sure they are only sent to sockets with
196  * multicast memberships for the packet's destination address and arrival
197  * interface.  Multicast packets to multicast-unaware sockets are also
198  * disallowed.
199  *
200  * Returns 0 if the packet is acceptable, -1 if it is not.
201  */
202 static __inline int
203 check_multicast_membership(struct ip *ip, struct inpcb *inp, struct mbuf *m)
204 {
205         int mshipno;
206         struct ip_moptions *mopt;
207
208         if (strict_mcast_mship == 0 ||
209             !IN_MULTICAST(ntohl(ip->ip_dst.s_addr))) {
210                 return (0);
211         }
212         mopt = inp->inp_moptions;
213         if (mopt == NULL)
214                 return (-1);
215         for (mshipno = 0; mshipno <= mopt->imo_num_memberships; ++mshipno) {
216                 struct in_multi *maddr = mopt->imo_membership[mshipno];
217
218                 if (ip->ip_dst.s_addr == maddr->inm_addr.s_addr &&
219                     m->m_pkthdr.rcvif == maddr->inm_ifp) {
220                         return (0);
221                 }
222         }
223         return (-1);
224 }
225
226 void
227 udp_input(struct mbuf *m, ...)
228 {
229         int iphlen;
230         struct ip *ip;
231         struct udphdr *uh;
232         struct inpcb *inp;
233         struct mbuf *opts = NULL;
234         int len, off, proto;
235         struct ip save_ip;
236         struct sockaddr *append_sa;
237         __va_list ap;
238
239         __va_start(ap, m);
240         off = __va_arg(ap, int);
241         proto = __va_arg(ap, int);
242         __va_end(ap);
243
244         iphlen = off;
245         udpstat.udps_ipackets++;
246
247         /*
248          * Strip IP options, if any; should skip this,
249          * make available to user, and use on returned packets,
250          * but we don't yet have a way to check the checksum
251          * with options still present.
252          */
253         if (iphlen > sizeof(struct ip)) {
254                 ip_stripoptions(m);
255                 iphlen = sizeof(struct ip);
256         }
257
258         /*
259          * IP and UDP headers are together in first mbuf.
260          * Already checked and pulled up in ip_demux().
261          */
262         KASSERT(m->m_len >= iphlen + sizeof(struct udphdr),
263             ("UDP header not in one mbuf"));
264
265         ip = mtod(m, struct ip *);
266         uh = (struct udphdr *)((caddr_t)ip + iphlen);
267
268         /* destination port of 0 is illegal, based on RFC768. */
269         if (uh->uh_dport == 0)
270                 goto bad;
271
272         /*
273          * Make mbuf data length reflect UDP length.
274          * If not enough data to reflect UDP length, drop.
275          */
276         len = ntohs((u_short)uh->uh_ulen);
277         if (ip->ip_len != len) {
278                 if (len > ip->ip_len || len < sizeof(struct udphdr)) {
279                         udpstat.udps_badlen++;
280                         goto bad;
281                 }
282                 m_adj(m, len - ip->ip_len);
283                 /* ip->ip_len = len; */
284         }
285         /*
286          * Save a copy of the IP header in case we want restore it
287          * for sending an ICMP error message in response.
288          */
289         save_ip = *ip;
290
291         /*
292          * Checksum extended UDP header and data.
293          */
294         if (uh->uh_sum) {
295                 if (m->m_pkthdr.csum_flags & CSUM_DATA_VALID) {
296                         if (m->m_pkthdr.csum_flags & CSUM_PSEUDO_HDR)
297                                 uh->uh_sum = m->m_pkthdr.csum_data;
298                         else
299                                 uh->uh_sum = in_pseudo(ip->ip_src.s_addr,
300                                     ip->ip_dst.s_addr, htonl((u_short)len +
301                                     m->m_pkthdr.csum_data + IPPROTO_UDP));
302                         uh->uh_sum ^= 0xffff;
303                 } else {
304                         char b[9];
305
306                         bcopy(((struct ipovly *)ip)->ih_x1, b, 9);
307                         bzero(((struct ipovly *)ip)->ih_x1, 9);
308                         ((struct ipovly *)ip)->ih_len = uh->uh_ulen;
309                         uh->uh_sum = in_cksum(m, len + sizeof(struct ip));
310                         bcopy(b, ((struct ipovly *)ip)->ih_x1, 9);
311                 }
312                 if (uh->uh_sum) {
313                         udpstat.udps_badsum++;
314                         m_freem(m);
315                         return;
316                 }
317         } else
318                 udpstat.udps_nosum++;
319
320         if (IN_MULTICAST(ntohl(ip->ip_dst.s_addr)) ||
321             in_broadcast(ip->ip_dst, m->m_pkthdr.rcvif)) {
322                 struct inpcb *last;
323
324                 /*
325                  * Deliver a multicast or broadcast datagram to *all* sockets
326                  * for which the local and remote addresses and ports match
327                  * those of the incoming datagram.  This allows more than
328                  * one process to receive multi/broadcasts on the same port.
329                  * (This really ought to be done for unicast datagrams as
330                  * well, but that would cause problems with existing
331                  * applications that open both address-specific sockets and
332                  * a wildcard socket listening to the same port -- they would
333                  * end up receiving duplicates of every unicast datagram.
334                  * Those applications open the multiple sockets to overcome an
335                  * inadequacy of the UDP socket interface, but for backwards
336                  * compatibility we avoid the problem here rather than
337                  * fixing the interface.  Maybe 4.5BSD will remedy this?)
338                  */
339
340                 /*
341                  * Construct sockaddr format source address.
342                  */
343                 udp_in.sin_port = uh->uh_sport;
344                 udp_in.sin_addr = ip->ip_src;
345                 /*
346                  * Locate pcb(s) for datagram.
347                  * (Algorithm copied from raw_intr().)
348                  */
349                 last = NULL;
350 #ifdef INET6
351                 udp_in6.uin6_init_done = udp_ip6.uip6_init_done = 0;
352 #endif
353                 LIST_FOREACH(inp, &udbinfo.pcblisthead, inp_list) {
354                         if (inp->inp_flags & INP_PLACEMARKER)
355                                 continue;
356 #ifdef INET6
357                         if (!(inp->inp_vflag & INP_IPV4))
358                                 continue;
359 #endif
360                         if (inp->inp_lport != uh->uh_dport)
361                                 continue;
362                         if (inp->inp_laddr.s_addr != INADDR_ANY) {
363                                 if (inp->inp_laddr.s_addr !=
364                                     ip->ip_dst.s_addr)
365                                         continue;
366                         }
367                         if (inp->inp_faddr.s_addr != INADDR_ANY) {
368                                 if (inp->inp_faddr.s_addr !=
369                                     ip->ip_src.s_addr ||
370                                     inp->inp_fport != uh->uh_sport)
371                                         continue;
372                         }
373
374                         if (check_multicast_membership(ip, inp, m) < 0)
375                                 continue;
376
377                         if (last != NULL) {
378                                 struct mbuf *n;
379
380 #ifdef IPSEC
381                                 /* check AH/ESP integrity. */
382                                 if (ipsec4_in_reject_so(m, last->inp_socket))
383                                         ipsecstat.in_polvio++;
384                                         /* do not inject data to pcb */
385                                 else
386 #endif /*IPSEC*/
387 #ifdef FAST_IPSEC
388                                 /* check AH/ESP integrity. */
389                                 if (ipsec4_in_reject(m, last))
390                                         ;
391                                 else
392 #endif /*FAST_IPSEC*/
393                                 if ((n = m_copypacket(m, MB_DONTWAIT)) != NULL)
394                                         udp_append(last, ip, n,
395                                                    iphlen +
396                                                    sizeof(struct udphdr));
397                         }
398                         last = inp;
399                         /*
400                          * Don't look for additional matches if this one does
401                          * not have either the SO_REUSEPORT or SO_REUSEADDR
402                          * socket options set.  This heuristic avoids searching
403                          * through all pcbs in the common case of a non-shared
404                          * port.  It * assumes that an application will never
405                          * clear these options after setting them.
406                          */
407                         if (!(last->inp_socket->so_options &
408                             (SO_REUSEPORT | SO_REUSEADDR)))
409                                 break;
410                 }
411
412                 if (last == NULL) {
413                         /*
414                          * No matching pcb found; discard datagram.
415                          * (No need to send an ICMP Port Unreachable
416                          * for a broadcast or multicast datgram.)
417                          */
418                         udpstat.udps_noportbcast++;
419                         goto bad;
420                 }
421 #ifdef IPSEC
422                 /* check AH/ESP integrity. */
423                 if (ipsec4_in_reject_so(m, last->inp_socket)) {
424                         ipsecstat.in_polvio++;
425                         goto bad;
426                 }
427 #endif /*IPSEC*/
428 #ifdef FAST_IPSEC
429                 /* check AH/ESP integrity. */
430                 if (ipsec4_in_reject(m, last))
431                         goto bad;
432 #endif /*FAST_IPSEC*/
433                 udp_append(last, ip, m, iphlen + sizeof(struct udphdr));
434                 return;
435         }
436         /*
437          * Locate pcb for datagram.
438          */
439         inp = in_pcblookup_hash(&udbinfo, ip->ip_src, uh->uh_sport,
440             ip->ip_dst, uh->uh_dport, 1, m->m_pkthdr.rcvif);
441         if (inp == NULL) {
442                 if (log_in_vain) {
443                         char buf[sizeof "aaa.bbb.ccc.ddd"];
444
445                         strcpy(buf, inet_ntoa(ip->ip_dst));
446                         log(LOG_INFO,
447                             "Connection attempt to UDP %s:%d from %s:%d\n",
448                             buf, ntohs(uh->uh_dport), inet_ntoa(ip->ip_src),
449                             ntohs(uh->uh_sport));
450                 }
451                 udpstat.udps_noport++;
452                 if (m->m_flags & (M_BCAST | M_MCAST)) {
453                         udpstat.udps_noportbcast++;
454                         goto bad;
455                 }
456                 if (blackhole)
457                         goto bad;
458 #ifdef ICMP_BANDLIM
459                 if (badport_bandlim(BANDLIM_ICMP_UNREACH) < 0)
460                         goto bad;
461 #endif
462                 *ip = save_ip;
463                 ip->ip_len += iphlen;
464                 icmp_error(m, ICMP_UNREACH, ICMP_UNREACH_PORT, 0, 0);
465                 return;
466         }
467 #ifdef IPSEC
468         if (ipsec4_in_reject_so(m, inp->inp_socket)) {
469                 ipsecstat.in_polvio++;
470                 goto bad;
471         }
472 #endif /*IPSEC*/
473 #ifdef FAST_IPSEC
474         if (ipsec4_in_reject(m, inp))
475                 goto bad;
476 #endif /*FAST_IPSEC*/
477         /*
478          * Check the minimum TTL for socket.
479          */
480         if (ip->ip_ttl < inp->inp_ip_minttl)
481                 goto bad;
482
483         /*
484          * Construct sockaddr format source address.
485          * Stuff source address and datagram in user buffer.
486          */
487         udp_in.sin_port = uh->uh_sport;
488         udp_in.sin_addr = ip->ip_src;
489         if ((inp->inp_flags & INP_CONTROLOPTS) ||
490             (inp->inp_socket->so_options & SO_TIMESTAMP)) {
491 #ifdef INET6
492                 if (inp->inp_vflag & INP_IPV6) {
493                         int savedflags;
494
495                         ip_2_ip6_hdr(&udp_ip6.uip6_ip6, ip);
496                         savedflags = inp->inp_flags;
497                         inp->inp_flags &= ~INP_UNMAPPABLEOPTS;
498                         ip6_savecontrol(inp, &opts, &udp_ip6.uip6_ip6, m);
499                         inp->inp_flags = savedflags;
500                 } else
501 #endif
502                 ip_savecontrol(inp, &opts, ip, m);
503         }
504         m_adj(m, iphlen + sizeof(struct udphdr));
505 #ifdef INET6
506         if (inp->inp_vflag & INP_IPV6) {
507                 in6_sin_2_v4mapsin6(&udp_in, &udp_in6.uin6_sin);
508                 append_sa = (struct sockaddr *)&udp_in6;
509         } else
510 #endif
511                 append_sa = (struct sockaddr *)&udp_in;
512         if (ssb_appendaddr(&inp->inp_socket->so_rcv, append_sa, m, opts) == 0) {
513                 udpstat.udps_fullsock++;
514                 goto bad;
515         }
516         sorwakeup(inp->inp_socket);
517         return;
518 bad:
519         m_freem(m);
520         if (opts)
521                 m_freem(opts);
522         return;
523 }
524
525 #ifdef INET6
526 static void
527 ip_2_ip6_hdr(struct ip6_hdr *ip6, struct ip *ip)
528 {
529         bzero(ip6, sizeof *ip6);
530
531         ip6->ip6_vfc = IPV6_VERSION;
532         ip6->ip6_plen = ip->ip_len;
533         ip6->ip6_nxt = ip->ip_p;
534         ip6->ip6_hlim = ip->ip_ttl;
535         ip6->ip6_src.s6_addr32[2] = ip6->ip6_dst.s6_addr32[2] =
536                 IPV6_ADDR_INT32_SMP;
537         ip6->ip6_src.s6_addr32[3] = ip->ip_src.s_addr;
538         ip6->ip6_dst.s6_addr32[3] = ip->ip_dst.s_addr;
539 }
540 #endif
541
542 /*
543  * subroutine of udp_input(), mainly for source code readability.
544  * caller must properly init udp_ip6 and udp_in6 beforehand.
545  */
546 static void
547 udp_append(struct inpcb *last, struct ip *ip, struct mbuf *n, int off)
548 {
549         struct sockaddr *append_sa;
550         struct mbuf *opts = NULL;
551
552         if (last->inp_flags & INP_CONTROLOPTS ||
553             last->inp_socket->so_options & SO_TIMESTAMP) {
554 #ifdef INET6
555                 if (last->inp_vflag & INP_IPV6) {
556                         int savedflags;
557
558                         if (udp_ip6.uip6_init_done == 0) {
559                                 ip_2_ip6_hdr(&udp_ip6.uip6_ip6, ip);
560                                 udp_ip6.uip6_init_done = 1;
561                         }
562                         savedflags = last->inp_flags;
563                         last->inp_flags &= ~INP_UNMAPPABLEOPTS;
564                         ip6_savecontrol(last, &opts, &udp_ip6.uip6_ip6, n);
565                         last->inp_flags = savedflags;
566                 } else
567 #endif
568                 ip_savecontrol(last, &opts, ip, n);
569         }
570 #ifdef INET6
571         if (last->inp_vflag & INP_IPV6) {
572                 if (udp_in6.uin6_init_done == 0) {
573                         in6_sin_2_v4mapsin6(&udp_in, &udp_in6.uin6_sin);
574                         udp_in6.uin6_init_done = 1;
575                 }
576                 append_sa = (struct sockaddr *)&udp_in6.uin6_sin;
577         } else
578 #endif
579                 append_sa = (struct sockaddr *)&udp_in;
580         m_adj(n, off);
581         if (ssb_appendaddr(&last->inp_socket->so_rcv, append_sa, n, opts) == 0) {
582                 m_freem(n);
583                 if (opts)
584                         m_freem(opts);
585                 udpstat.udps_fullsock++;
586         } else
587                 sorwakeup(last->inp_socket);
588 }
589
590 /*
591  * Notify a udp user of an asynchronous error;
592  * just wake up so that he can collect error status.
593  */
594 void
595 udp_notify(struct inpcb *inp, int error)
596 {
597         inp->inp_socket->so_error = error;
598         sorwakeup(inp->inp_socket);
599         sowwakeup(inp->inp_socket);
600 }
601
602 struct netmsg_udp_notify {
603         struct netmsg   nm_nmsg;
604         void            (*nm_notify)(struct inpcb *, int);
605         struct in_addr  nm_faddr;
606         int             nm_arg;
607 };
608
609 static void
610 udp_notifyall_oncpu(struct netmsg *netmsg)
611 {
612         struct netmsg_udp_notify *nmsg = (struct netmsg_udp_notify *)netmsg;
613         int nextcpu;
614
615         in_pcbnotifyall(&udbinfo.pcblisthead, nmsg->nm_faddr, nmsg->nm_arg,
616                         nmsg->nm_notify);
617
618         nextcpu = mycpuid + 1;
619         if (nextcpu < ncpus2)
620                 lwkt_forwardmsg(cpu_portfn(nextcpu), &netmsg->nm_lmsg);
621         else
622                 lwkt_replymsg(&netmsg->nm_lmsg, 0);
623 }
624
625 static void
626 udp_rtchange(struct inpcb *inp, int err)
627 {
628 #ifdef SMP
629         /* XXX Nuke this, once UDP inpcbs are CPU localized */
630         if (inp->inp_route.ro_rt && inp->inp_route.ro_rt->rt_cpuid == mycpuid) {
631                 rtfree(inp->inp_route.ro_rt);
632                 inp->inp_route.ro_rt = NULL;
633                 /*
634                  * A new route can be allocated the next time
635                  * output is attempted.
636                  */
637         }
638 #else
639         in_rtchange(inp, err);
640 #endif
641 }
642
643 void
644 udp_ctlinput(int cmd, struct sockaddr *sa, void *vip)
645 {
646         struct ip *ip = vip;
647         struct udphdr *uh;
648         void (*notify) (struct inpcb *, int) = udp_notify;
649         struct in_addr faddr;
650         struct inpcb *inp;
651
652         faddr = ((struct sockaddr_in *)sa)->sin_addr;
653         if (sa->sa_family != AF_INET || faddr.s_addr == INADDR_ANY)
654                 return;
655
656         if (PRC_IS_REDIRECT(cmd)) {
657                 ip = NULL;
658                 notify = udp_rtchange;
659         } else if (cmd == PRC_HOSTDEAD)
660                 ip = NULL;
661         else if ((unsigned)cmd >= PRC_NCMDS || inetctlerrmap[cmd] == 0)
662                 return;
663         if (ip) {
664                 crit_enter();
665                 uh = (struct udphdr *)((caddr_t)ip + (ip->ip_hl << 2));
666                 inp = in_pcblookup_hash(&udbinfo, faddr, uh->uh_dport,
667                                         ip->ip_src, uh->uh_sport, 0, NULL);
668                 if (inp != NULL && inp->inp_socket != NULL)
669                         (*notify)(inp, inetctlerrmap[cmd]);
670                 crit_exit();
671         } else if (PRC_IS_REDIRECT(cmd)) {
672                 struct netmsg_udp_notify nmsg;
673
674                 KKASSERT(&curthread->td_msgport == cpu_portfn(0));
675                 netmsg_init(&nmsg.nm_nmsg, NULL, &curthread->td_msgport,
676                             0, udp_notifyall_oncpu);
677                 nmsg.nm_faddr = faddr;
678                 nmsg.nm_arg = inetctlerrmap[cmd];
679                 nmsg.nm_notify = notify;
680
681                 lwkt_domsg(cpu_portfn(0), &nmsg.nm_nmsg.nm_lmsg, 0);
682         } else {
683                 /*
684                  * XXX We should forward msg upon PRC_HOSTHEAD and ip == NULL,
685                  * once UDP inpcbs are CPU localized
686                  */
687                 KKASSERT(&curthread->td_msgport == cpu_portfn(0));
688                 in_pcbnotifyall(&udbinfo.pcblisthead, faddr, inetctlerrmap[cmd],
689                                 notify);
690         }
691 }
692
693 SYSCTL_PROC(_net_inet_udp, UDPCTL_PCBLIST, pcblist, CTLFLAG_RD, &udbinfo, 0,
694             in_pcblist_global, "S,xinpcb", "List of active UDP sockets");
695
696 static int
697 udp_getcred(SYSCTL_HANDLER_ARGS)
698 {
699         struct sockaddr_in addrs[2];
700         struct inpcb *inp;
701         int error;
702
703         error = priv_check(req->td, PRIV_ROOT);
704         if (error)
705                 return (error);
706         error = SYSCTL_IN(req, addrs, sizeof addrs);
707         if (error)
708                 return (error);
709         crit_enter();
710         inp = in_pcblookup_hash(&udbinfo, addrs[1].sin_addr, addrs[1].sin_port,
711                                 addrs[0].sin_addr, addrs[0].sin_port, 1, NULL);
712         if (inp == NULL || inp->inp_socket == NULL) {
713                 error = ENOENT;
714                 goto out;
715         }
716         error = SYSCTL_OUT(req, inp->inp_socket->so_cred, sizeof(struct ucred));
717 out:
718         crit_exit();
719         return (error);
720 }
721
722 SYSCTL_PROC(_net_inet_udp, OID_AUTO, getcred, CTLTYPE_OPAQUE|CTLFLAG_RW,
723     0, 0, udp_getcred, "S,ucred", "Get the ucred of a UDP connection");
724
725 static int
726 udp_output(struct inpcb *inp, struct mbuf *m, struct sockaddr *dstaddr,
727            struct mbuf *control, struct thread *td)
728 {
729         struct udpiphdr *ui;
730         int len = m->m_pkthdr.len;
731         struct sockaddr_in *sin;        /* really is initialized before use */
732         int error = 0, lport_any = 0;
733
734         if (len + sizeof(struct udpiphdr) > IP_MAXPACKET) {
735                 error = EMSGSIZE;
736                 goto release;
737         }
738
739         if (inp->inp_lport == 0) {      /* unbound socket */
740                 error = in_pcbbind(inp, NULL, td);
741                 if (error)
742                         goto release;
743                 in_pcbinswildcardhash(inp);
744                 lport_any = 1;
745         }
746
747         if (dstaddr != NULL) {          /* destination address specified */
748                 if (inp->inp_faddr.s_addr != INADDR_ANY) {
749                         /* already connected */
750                         error = EISCONN;
751                         goto release;
752                 }
753                 sin = (struct sockaddr_in *)dstaddr;
754                 if (!prison_remote_ip(td, (struct sockaddr *)&sin)) {
755                         error = EAFNOSUPPORT; /* IPv6 only jail */
756                         goto release;
757                 }
758         } else {
759                 if (inp->inp_faddr.s_addr == INADDR_ANY) {
760                         /* no destination specified and not already connected */
761                         error = ENOTCONN;
762                         goto release;
763                 }
764                 sin = NULL;
765         }
766
767         /*
768          * Calculate data length and get a mbuf
769          * for UDP and IP headers.
770          */
771         M_PREPEND(m, sizeof(struct udpiphdr), MB_DONTWAIT);
772         if (m == NULL) {
773                 error = ENOBUFS;
774                 goto release;
775         }
776
777         /*
778          * Fill in mbuf with extended UDP header
779          * and addresses and length put into network format.
780          */
781         ui = mtod(m, struct udpiphdr *);
782         bzero(ui->ui_x1, sizeof ui->ui_x1);     /* XXX still needed? */
783         ui->ui_pr = IPPROTO_UDP;
784
785         /*
786          * Set destination address.
787          */
788         if (dstaddr != NULL) {                  /* use specified destination */
789                 ui->ui_dst = sin->sin_addr;
790                 ui->ui_dport = sin->sin_port;
791         } else {                                /* use connected destination */
792                 ui->ui_dst = inp->inp_faddr;
793                 ui->ui_dport = inp->inp_fport;
794         }
795
796         /*
797          * Set source address.
798          */
799         if (inp->inp_laddr.s_addr == INADDR_ANY) {
800                 struct sockaddr_in *if_sin;
801
802                 if (dstaddr == NULL) {  
803                         /*
804                          * connect() had (or should have) failed because
805                          * the interface had no IP address, but the
806                          * application proceeded to call send() anyways.
807                          */
808                         error = ENOTCONN;
809                         goto release;
810                 }
811
812                 /* Look up outgoing interface. */
813                 if ((error = in_pcbladdr(inp, dstaddr, &if_sin, td)))
814                         goto release;
815                 ui->ui_src = if_sin->sin_addr;  /* use address of interface */
816         } else {
817                 ui->ui_src = inp->inp_laddr;    /* use non-null bound address */
818         }
819         ui->ui_sport = inp->inp_lport;
820         KASSERT(inp->inp_lport != 0, ("inp lport should have been bound"));
821
822         ui->ui_ulen = htons((u_short)len + sizeof(struct udphdr));
823
824         /*
825          * Set up checksum and output datagram.
826          */
827         if (udpcksum) {
828                 ui->ui_sum = in_pseudo(ui->ui_src.s_addr, ui->ui_dst.s_addr,
829                     htons((u_short)len + sizeof(struct udphdr) + IPPROTO_UDP));
830                 m->m_pkthdr.csum_flags = CSUM_UDP;
831                 m->m_pkthdr.csum_data = offsetof(struct udphdr, uh_sum);
832         } else {
833                 ui->ui_sum = 0;
834         }
835         ((struct ip *)ui)->ip_len = sizeof(struct udpiphdr) + len;
836         ((struct ip *)ui)->ip_ttl = inp->inp_ip_ttl;    /* XXX */
837         ((struct ip *)ui)->ip_tos = inp->inp_ip_tos;    /* XXX */
838         udpstat.udps_opackets++;
839
840         error = ip_output(m, inp->inp_options, &inp->inp_route,
841             (inp->inp_socket->so_options & (SO_DONTROUTE | SO_BROADCAST)) |
842             IP_DEBUGROUTE,
843             inp->inp_moptions, inp);
844
845         /*
846          * If this is the first data gram sent on an unbound and unconnected
847          * UDP socket, lport will be changed in this function.  If target
848          * CPU after this lport changing is no longer the current CPU, then
849          * free the route entry allocated on the current CPU.
850          */
851         if (lport_any) {
852                 if (udp_addrcpu(inp->inp_faddr.s_addr, inp->inp_fport,
853                     inp->inp_laddr.s_addr, inp->inp_lport) != mycpuid) {
854                         struct route *ro = &inp->inp_route;
855
856                         if (ro->ro_rt != NULL)
857                                 RTFREE(ro->ro_rt);
858                         bzero(ro, sizeof(*ro));
859                 }
860         }
861         return (error);
862
863 release:
864         m_freem(m);
865         return (error);
866 }
867
868 u_long  udp_sendspace = 9216;           /* really max datagram size */
869                                         /* 40 1K datagrams */
870 SYSCTL_INT(_net_inet_udp, UDPCTL_MAXDGRAM, maxdgram, CTLFLAG_RW,
871     &udp_sendspace, 0, "Maximum outgoing UDP datagram size");
872
873 u_long  udp_recvspace = 40 * (1024 +
874 #ifdef INET6
875                                       sizeof(struct sockaddr_in6)
876 #else
877                                       sizeof(struct sockaddr_in)
878 #endif
879                                       );
880 SYSCTL_INT(_net_inet_udp, UDPCTL_RECVSPACE, recvspace, CTLFLAG_RW,
881     &udp_recvspace, 0, "Maximum incoming UDP datagram size");
882
883 static int
884 udp_abort(struct socket *so)
885 {
886         struct inpcb *inp;
887
888         inp = so->so_pcb;
889         if (inp == NULL)
890                 return EINVAL;  /* ??? possible? panic instead? */
891         soisdisconnected(so);
892         crit_enter();
893         in_pcbdetach(inp);
894         crit_exit();
895         return 0;
896 }
897
898 static int
899 udp_attach(struct socket *so, int proto, struct pru_attach_info *ai)
900 {
901         struct inpcb *inp;
902         int error;
903
904         inp = so->so_pcb;
905         if (inp != NULL)
906                 return EINVAL;
907
908         error = soreserve(so, udp_sendspace, udp_recvspace, ai->sb_rlimit);
909         if (error)
910                 return error;
911         crit_enter();
912         error = in_pcballoc(so, &udbinfo);
913         crit_exit();
914         if (error)
915                 return error;
916         so->so_port = udp_soport_attach(so);
917
918         inp = (struct inpcb *)so->so_pcb;
919         inp->inp_vflag |= INP_IPV4;
920         inp->inp_ip_ttl = ip_defttl;
921         return 0;
922 }
923
924 static int
925 udp_bind(struct socket *so, struct sockaddr *nam, struct thread *td)
926 {
927         struct sockaddr_in *sin = (struct sockaddr_in *)nam;
928         struct inpcb *inp;
929         int error;
930
931         inp = so->so_pcb;
932         if (inp == NULL)
933                 return EINVAL;
934         crit_enter();
935         error = in_pcbbind(inp, nam, td);
936         crit_exit();
937         if (error == 0) {
938                 if (sin->sin_addr.s_addr != INADDR_ANY)
939                         inp->inp_flags |= INP_WASBOUND_NOTANY;
940                 in_pcbinswildcardhash(inp);
941         }
942         return error;
943 }
944
945 #ifdef SMP
946
947 struct netmsg_udp_connect {
948         struct netmsg           nm_netmsg;
949         struct socket           *nm_so;
950         struct sockaddr_in      *nm_sin;
951         struct sockaddr_in      *nm_ifsin;
952         struct thread           *nm_td;
953 };
954
955 static void
956 udp_connect_handler(netmsg_t netmsg)
957 {
958         struct netmsg_udp_connect *msg = (void *)netmsg;
959         int error;
960
961         error = udp_connect_oncpu(msg->nm_so, msg->nm_td,
962                                   msg->nm_sin, msg->nm_ifsin);
963         lwkt_replymsg(&msg->nm_netmsg.nm_lmsg, error);
964 }
965
966 #endif
967
968 static int
969 udp_connect(struct socket *so, struct sockaddr *nam, struct thread *td)
970 {
971         struct inpcb *inp;
972         struct sockaddr_in *sin = (struct sockaddr_in *)nam;
973         struct sockaddr_in *if_sin;
974         lwkt_port_t port;
975         int error;
976
977         inp = so->so_pcb;
978         if (inp == NULL)
979                 return EINVAL;
980         if (inp->inp_faddr.s_addr != INADDR_ANY)
981                 return EISCONN;
982         error = 0;
983
984         /*
985          * Bind if we have to
986          */
987         if (td->td_proc && td->td_proc->p_ucred->cr_prison != NULL &&
988             inp->inp_laddr.s_addr == INADDR_ANY) {
989                 error = in_pcbbind(inp, NULL, td);
990                 if (error)
991                         return (error);
992         }
993
994         /*
995          * Calculate the correct protocol processing thread.  The connect
996          * operation must run there.
997          */
998         error = in_pcbladdr(inp, nam, &if_sin, td);
999         if (error)
1000                 return(error);
1001         if (!prison_remote_ip(td, nam))
1002                 return(EAFNOSUPPORT); /* IPv6 only jail */
1003
1004         port = udp_addrport(sin->sin_addr.s_addr, sin->sin_port,
1005                             inp->inp_laddr.s_addr, inp->inp_lport);
1006 #ifdef SMP
1007         if (port != &curthread->td_msgport) {
1008                 struct netmsg_udp_connect msg;
1009                 struct route *ro = &inp->inp_route;
1010
1011                 /*
1012                  * in_pcbladdr() may have allocated a route entry for us
1013                  * on the current CPU, but we need a route entry on the
1014                  * inpcb's owner CPU, so free it here.
1015                  */
1016                 if (ro->ro_rt != NULL)
1017                         RTFREE(ro->ro_rt);
1018                 bzero(ro, sizeof(*ro));
1019
1020                 /*
1021                  * NOTE: We haven't set so->so_port yet do not pass so
1022                  *       to netmsg_init() or it will be improperly forwarded.
1023                  */
1024                 netmsg_init(&msg.nm_netmsg, NULL, &curthread->td_msgport,
1025                             0, udp_connect_handler);
1026                 msg.nm_so = so;
1027                 msg.nm_sin = sin;
1028                 msg.nm_ifsin = if_sin;
1029                 msg.nm_td = td;
1030                 error = lwkt_domsg(port, &msg.nm_netmsg.nm_lmsg, 0);
1031         } else {
1032                 error = udp_connect_oncpu(so, td, sin, if_sin);
1033         }
1034 #else
1035         error = udp_connect_oncpu(so, td, sin, if_sin);
1036 #endif
1037         return (error);
1038 }
1039
1040 static int
1041 udp_connect_oncpu(struct socket *so, struct thread *td,
1042                   struct sockaddr_in *sin, struct sockaddr_in *if_sin)
1043 {
1044         struct inpcb *inp;
1045         int error;
1046
1047         inp = so->so_pcb;
1048         if (inp->inp_flags & INP_WILDCARD)
1049                 in_pcbremwildcardhash(inp);
1050         error = in_pcbconnect(inp, (struct sockaddr *)sin, td);
1051
1052         if (error == 0) {
1053                 /*
1054                  * No more errors can occur, finish adjusting the socket
1055                  * and change the processing port to reflect the connected
1056                  * socket.  Once set we can no longer safely mess with the
1057                  * socket.
1058                  */
1059                 soisconnected(so);
1060                 sosetport(so, &curthread->td_msgport);
1061         } else if (error == EAFNOSUPPORT) {     /* connection dissolved */
1062                 /*
1063                  * Follow traditional BSD behavior and retain
1064                  * the local port binding.  But, fix the old misbehavior
1065                  * of overwriting any previously bound local address.
1066                  */
1067                 if (!(inp->inp_flags & INP_WASBOUND_NOTANY))
1068                         inp->inp_laddr.s_addr = INADDR_ANY;
1069                 in_pcbinswildcardhash(inp);
1070         }
1071         return error;
1072 }
1073
1074 static int
1075 udp_detach(struct socket *so)
1076 {
1077         struct inpcb *inp;
1078
1079         inp = so->so_pcb;
1080         if (inp == NULL)
1081                 return EINVAL;
1082         crit_enter();
1083         in_pcbdetach(inp);
1084         crit_exit();
1085         return 0;
1086 }
1087
1088 static int
1089 udp_disconnect(struct socket *so)
1090 {
1091         struct route *ro;
1092         struct inpcb *inp;
1093
1094         inp = so->so_pcb;
1095         if (inp == NULL)
1096                 return EINVAL;
1097         if (inp->inp_faddr.s_addr == INADDR_ANY)
1098                 return ENOTCONN;
1099
1100         crit_enter();
1101         in_pcbdisconnect(inp);
1102         crit_exit();
1103         so->so_state &= ~SS_ISCONNECTED;                /* XXX */
1104
1105         ro = &inp->inp_route;
1106         if (ro->ro_rt != NULL)
1107                 RTFREE(ro->ro_rt);
1108         bzero(ro, sizeof(*ro));
1109
1110         return 0;
1111 }
1112
1113 static int
1114 udp_send(struct socket *so, int flags, struct mbuf *m, struct sockaddr *addr,
1115             struct mbuf *control, struct thread *td)
1116 {
1117         struct inpcb *inp;
1118
1119         inp = so->so_pcb;
1120         if (inp == NULL) {
1121                 m_freem(m);
1122                 return EINVAL;
1123         }
1124         return udp_output(inp, m, addr, control, td);
1125 }
1126
1127 int
1128 udp_shutdown(struct socket *so)
1129 {
1130         struct inpcb *inp;
1131
1132         inp = so->so_pcb;
1133         if (inp == NULL)
1134                 return EINVAL;
1135         socantsendmore(so);
1136         return 0;
1137 }
1138
1139 struct pr_usrreqs udp_usrreqs = {
1140         .pru_abort = udp_abort,
1141         .pru_accept = pru_accept_notsupp,
1142         .pru_attach = udp_attach,
1143         .pru_bind = udp_bind,
1144         .pru_connect = udp_connect,
1145         .pru_connect2 = pru_connect2_notsupp,
1146         .pru_control = in_control,
1147         .pru_detach = udp_detach,
1148         .pru_disconnect = udp_disconnect,
1149         .pru_listen = pru_listen_notsupp,
1150         .pru_peeraddr = in_setpeeraddr,
1151         .pru_rcvd = pru_rcvd_notsupp,
1152         .pru_rcvoob = pru_rcvoob_notsupp,
1153         .pru_send = udp_send,
1154         .pru_sense = pru_sense_null,
1155         .pru_shutdown = udp_shutdown,
1156         .pru_sockaddr = in_setsockaddr,
1157         .pru_sosend = sosendudp,
1158         .pru_soreceive = soreceive
1159 };
1160