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