udp: Factor out function to reset inpcb route cache
[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. 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 #include <sys/ktr.h>
84
85 #include <sys/thread2.h>
86 #include <sys/socketvar2.h>
87 #include <sys/serialize.h>
88
89 #include <machine/stdarg.h>
90
91 #include <net/if.h>
92 #include <net/route.h>
93 #include <net/netmsg2.h>
94 #include <net/netisr2.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 #define MSGF_UDP_SEND           MSGF_PROTO1
122
123 #define UDP_KTR_STRING          "inp=%p"
124 #define UDP_KTR_ARGS            struct inpcb *inp
125
126 #ifndef KTR_UDP
127 #define KTR_UDP                 KTR_ALL
128 #endif
129
130 KTR_INFO_MASTER(udp);
131 KTR_INFO(KTR_UDP, udp, send_beg, 0, UDP_KTR_STRING, UDP_KTR_ARGS);
132 KTR_INFO(KTR_UDP, udp, send_end, 1, UDP_KTR_STRING, UDP_KTR_ARGS);
133 KTR_INFO(KTR_UDP, udp, send_ipout, 2, UDP_KTR_STRING, UDP_KTR_ARGS);
134 KTR_INFO(KTR_UDP, udp, redisp_ipout_beg, 3, UDP_KTR_STRING, UDP_KTR_ARGS);
135 KTR_INFO(KTR_UDP, udp, redisp_ipout_end, 4, UDP_KTR_STRING, UDP_KTR_ARGS);
136 KTR_INFO(KTR_UDP, udp, send_redisp, 5, UDP_KTR_STRING, UDP_KTR_ARGS);
137 KTR_INFO(KTR_UDP, udp, send_inswildcard, 6, UDP_KTR_STRING, UDP_KTR_ARGS);
138
139 #define logudp(name, inp)       KTR_LOG(udp_##name, inp)
140
141 /*
142  * UDP protocol implementation.
143  * Per RFC 768, August, 1980.
144  */
145 #ifndef COMPAT_42
146 static int      udpcksum = 1;
147 #else
148 static int      udpcksum = 0;           /* XXX */
149 #endif
150 SYSCTL_INT(_net_inet_udp, UDPCTL_CHECKSUM, checksum, CTLFLAG_RW,
151     &udpcksum, 0, "Enable checksumming of UDP packets");
152
153 int     log_in_vain = 0;
154 SYSCTL_INT(_net_inet_udp, OID_AUTO, log_in_vain, CTLFLAG_RW,
155     &log_in_vain, 0, "Log all incoming UDP packets");
156
157 static int      blackhole = 0;
158 SYSCTL_INT(_net_inet_udp, OID_AUTO, blackhole, CTLFLAG_RW,
159         &blackhole, 0, "Do not send port unreachables for refused connects");
160
161 static int      strict_mcast_mship = 1;
162 SYSCTL_INT(_net_inet_udp, OID_AUTO, strict_mcast_mship, CTLFLAG_RW,
163         &strict_mcast_mship, 0, "Only send multicast to member sockets");
164
165 int     udp_sosend_async = 1;
166 SYSCTL_INT(_net_inet_udp, OID_AUTO, sosend_async, CTLFLAG_RW,
167         &udp_sosend_async, 0, "UDP asynchronized pru_send");
168
169 int     udp_sosend_prepend = 1;
170 SYSCTL_INT(_net_inet_udp, OID_AUTO, sosend_prepend, CTLFLAG_RW,
171         &udp_sosend_prepend, 0,
172         "Prepend enough space for proto and link header in pru_send");
173
174 static int udp_reuseport_ext = 1;
175 SYSCTL_INT(_net_inet_udp, OID_AUTO, reuseport_ext, CTLFLAG_RW,
176         &udp_reuseport_ext, 0, "SO_REUSEPORT extension");
177
178 struct  inpcbinfo udbinfo[MAXCPU];
179
180 #ifndef UDBHASHSIZE
181 #define UDBHASHSIZE 16
182 #endif
183
184 struct  udpstat udpstat_percpu[MAXCPU] __cachealign;
185
186 #ifdef INET6
187 struct udp_in6 {
188         struct sockaddr_in6     uin6_sin;
189         u_char                  uin6_init_done : 1;
190 };
191 struct udp_ip6 {
192         struct ip6_hdr          uip6_ip6;
193         u_char                  uip6_init_done : 1;
194 };
195 #else
196 struct udp_in6;
197 struct udp_ip6;
198 #endif /* INET6 */
199
200 static void udp_append (struct inpcb *last, struct ip *ip,
201     struct mbuf *n, int off, struct sockaddr_in *udp_in,
202     struct udp_in6 *, struct udp_ip6 *);
203 #ifdef INET6
204 static void ip_2_ip6_hdr (struct ip6_hdr *ip6, struct ip *ip);
205 #endif
206
207 static int udp_connect_oncpu(struct inpcb *inp, struct sockaddr_in *sin,
208     struct sockaddr_in *if_sin);
209
210 static boolean_t udp_inswildcardhash(struct inpcb *inp,
211     struct netmsg_base *msg, int error);
212 static void udp_remwildcardhash(struct inpcb *inp);
213
214 static void
215 udp_reset_route(struct inpcb *inp)
216 {
217         struct route *ro = &inp->inp_route;
218
219         if (ro->ro_rt != NULL)
220                 RTFREE(ro->ro_rt);
221         bzero(ro, sizeof(*ro));
222 }
223
224 void
225 udp_init(void)
226 {
227         struct inpcbportinfo *portinfo;
228         int cpu;
229
230         portinfo = kmalloc_cachealign(sizeof(*portinfo) * ncpus2, M_PCB,
231             M_WAITOK);
232
233         for (cpu = 0; cpu < ncpus2; cpu++) {
234                 struct inpcbinfo *uicb = &udbinfo[cpu];
235
236                 /*
237                  * NOTE:
238                  * UDP pcb list, wildcard hash table and localgroup hash
239                  * table are shared.
240                  */
241                 in_pcbinfo_init(uicb, cpu, TRUE);
242                 uicb->hashbase = hashinit(UDBHASHSIZE, M_PCB, &uicb->hashmask);
243
244                 in_pcbportinfo_init(&portinfo[cpu], UDBHASHSIZE, TRUE, cpu);
245                 uicb->portinfo = portinfo;
246                 uicb->portinfo_mask = ncpus2_mask;
247
248                 uicb->wildcardhashbase = hashinit(UDBHASHSIZE, M_PCB,
249                     &uicb->wildcardhashmask);
250                 uicb->localgrphashbase = hashinit(UDBHASHSIZE, M_PCB,
251                     &uicb->localgrphashmask);
252
253                 uicb->ipi_size = sizeof(struct inpcb);
254         }
255
256         /*
257          * Initialize UDP statistics counters for each CPU.
258          */
259         for (cpu = 0; cpu < ncpus; ++cpu)
260                 bzero(&udpstat_percpu[cpu], sizeof(struct udpstat));
261 }
262
263 static int
264 sysctl_udpstat(SYSCTL_HANDLER_ARGS)
265 {
266         int cpu, error = 0;
267
268         for (cpu = 0; cpu < ncpus; ++cpu) {
269                 if ((error = SYSCTL_OUT(req, &udpstat_percpu[cpu],
270                                         sizeof(struct udpstat))))
271                         break;
272                 if ((error = SYSCTL_IN(req, &udpstat_percpu[cpu],
273                                        sizeof(struct udpstat))))
274                         break;
275         }
276
277         return (error);
278 }
279 SYSCTL_PROC(_net_inet_udp, UDPCTL_STATS, stats, (CTLTYPE_OPAQUE | CTLFLAG_RW),
280     0, 0, sysctl_udpstat, "S,udpstat", "UDP statistics");
281
282 /*
283  * Check multicast packets to make sure they are only sent to sockets with
284  * multicast memberships for the packet's destination address and arrival
285  * interface.  Multicast packets to multicast-unaware sockets are also
286  * disallowed.
287  *
288  * Returns 0 if the packet is acceptable, -1 if it is not.
289  */
290 static __inline int
291 check_multicast_membership(const struct ip *ip, const struct inpcb *inp,
292     const struct mbuf *m)
293 {
294         const struct ip_moptions *mopt;
295         int mshipno;
296
297         if (strict_mcast_mship == 0 ||
298             !IN_MULTICAST(ntohl(ip->ip_dst.s_addr))) {
299                 return (0);
300         }
301
302         KASSERT(&curthread->td_msgport == netisr_cpuport(0),
303             ("multicast input not in netisr0"));
304
305         mopt = inp->inp_moptions;
306         if (mopt == NULL)
307                 return (-1);
308         for (mshipno = 0; mshipno < mopt->imo_num_memberships; ++mshipno) {
309                 const struct in_multi *maddr = mopt->imo_membership[mshipno];
310
311                 if (ip->ip_dst.s_addr == maddr->inm_addr.s_addr &&
312                     m->m_pkthdr.rcvif == maddr->inm_ifp) {
313                         return (0);
314                 }
315         }
316         return (-1);
317 }
318
319 struct udp_mcast_arg {
320         struct inpcb    *inp;
321         struct inpcb    *last;
322         struct ip       *ip;
323         struct mbuf     *m;
324         int             iphlen;
325         struct sockaddr_in *udp_in;
326 #ifdef INET6
327         struct udp_in6  *udp_in6;
328         struct udp_ip6  *udp_ip6;
329 #endif
330 };
331
332 static int
333 udp_mcast_input(struct udp_mcast_arg *arg)
334 {
335         struct inpcb *inp = arg->inp;
336         struct inpcb *last = arg->last;
337         struct ip *ip = arg->ip;
338         struct mbuf *m = arg->m;
339
340         if (check_multicast_membership(ip, inp, m) < 0)
341                 return ERESTART; /* caller continue */
342
343         if (last != NULL) {
344                 struct mbuf *n;
345
346 #ifdef IPSEC
347                 /* check AH/ESP integrity. */
348                 if (ipsec4_in_reject_so(m, last->inp_socket))
349                         ipsecstat.in_polvio++;
350                         /* do not inject data to pcb */
351                 else
352 #endif /*IPSEC*/
353 #ifdef FAST_IPSEC
354                 /* check AH/ESP integrity. */
355                 if (ipsec4_in_reject(m, last))
356                         ;
357                 else
358 #endif /*FAST_IPSEC*/
359                 if ((n = m_copypacket(m, MB_DONTWAIT)) != NULL)
360                         udp_append(last, ip, n,
361                             arg->iphlen + sizeof(struct udphdr),
362                             arg->udp_in,
363 #ifdef INET6
364                             arg->udp_in6, arg->udp_ip6
365 #else
366                             NULL, NULL
367 #endif
368                             );
369         }
370         arg->last = last = inp;
371
372         /*
373          * Don't look for additional matches if this one does
374          * not have either the SO_REUSEPORT or SO_REUSEADDR
375          * socket options set.  This heuristic avoids searching
376          * through all pcbs in the common case of a non-shared
377          * port.  It * assumes that an application will never
378          * clear these options after setting them.
379          */
380         if (!(last->inp_socket->so_options &
381             (SO_REUSEPORT | SO_REUSEADDR)))
382                 return EJUSTRETURN; /* caller stop */
383         return 0;
384 }
385
386 int
387 udp_input(struct mbuf **mp, int *offp, int proto)
388 {
389         struct sockaddr_in udp_in = { sizeof udp_in, AF_INET };
390 #ifdef INET6
391         struct udp_in6 udp_in6 = {
392                 { sizeof udp_in6.uin6_sin, AF_INET6 }, 0
393         };
394         struct udp_ip6 udp_ip6;
395 #endif
396
397         int iphlen;
398         struct ip *ip;
399         struct udphdr *uh;
400         struct inpcb *inp;
401         struct mbuf *m;
402         struct mbuf *opts = NULL;
403         int len, off;
404         struct ip save_ip;
405         struct sockaddr *append_sa;
406         struct inpcbinfo *pcbinfo = &udbinfo[mycpuid];
407
408         off = *offp;
409         m = *mp;
410         *mp = NULL;
411
412         iphlen = off;
413         udp_stat.udps_ipackets++;
414
415         /*
416          * Strip IP options, if any; should skip this,
417          * make available to user, and use on returned packets,
418          * but we don't yet have a way to check the checksum
419          * with options still present.
420          */
421         if (iphlen > sizeof(struct ip)) {
422                 ip_stripoptions(m);
423                 iphlen = sizeof(struct ip);
424         }
425
426         /*
427          * IP and UDP headers are together in first mbuf.
428          * Already checked and pulled up in ip_demux().
429          */
430         KASSERT(m->m_len >= iphlen + sizeof(struct udphdr),
431             ("UDP header not in one mbuf"));
432
433         ip = mtod(m, struct ip *);
434         uh = (struct udphdr *)((caddr_t)ip + iphlen);
435
436         /* destination port of 0 is illegal, based on RFC768. */
437         if (uh->uh_dport == 0)
438                 goto bad;
439
440         /*
441          * Make mbuf data length reflect UDP length.
442          * If not enough data to reflect UDP length, drop.
443          */
444         len = ntohs((u_short)uh->uh_ulen);
445         if (ip->ip_len != len) {
446                 if (len > ip->ip_len || len < sizeof(struct udphdr)) {
447                         udp_stat.udps_badlen++;
448                         goto bad;
449                 }
450                 m_adj(m, len - ip->ip_len);
451                 /* ip->ip_len = len; */
452         }
453         /*
454          * Save a copy of the IP header in case we want restore it
455          * for sending an ICMP error message in response.
456          */
457         save_ip = *ip;
458
459         /*
460          * Checksum extended UDP header and data.
461          */
462         if (uh->uh_sum) {
463                 if (m->m_pkthdr.csum_flags & CSUM_DATA_VALID) {
464                         if (m->m_pkthdr.csum_flags & CSUM_PSEUDO_HDR)
465                                 uh->uh_sum = m->m_pkthdr.csum_data;
466                         else
467                                 uh->uh_sum = in_pseudo(ip->ip_src.s_addr,
468                                     ip->ip_dst.s_addr, htonl((u_short)len +
469                                     m->m_pkthdr.csum_data + IPPROTO_UDP));
470                         uh->uh_sum ^= 0xffff;
471                 } else {
472                         char b[9];
473
474                         bcopy(((struct ipovly *)ip)->ih_x1, b, 9);
475                         bzero(((struct ipovly *)ip)->ih_x1, 9);
476                         ((struct ipovly *)ip)->ih_len = uh->uh_ulen;
477                         uh->uh_sum = in_cksum(m, len + sizeof(struct ip));
478                         bcopy(b, ((struct ipovly *)ip)->ih_x1, 9);
479                 }
480                 if (uh->uh_sum) {
481                         udp_stat.udps_badsum++;
482                         m_freem(m);
483                         return(IPPROTO_DONE);
484                 }
485         } else
486                 udp_stat.udps_nosum++;
487
488         if (IN_MULTICAST(ntohl(ip->ip_dst.s_addr)) ||
489             in_broadcast(ip->ip_dst, m->m_pkthdr.rcvif)) {
490                 struct inpcbhead *connhead;
491                 struct inpcontainer *ic, *ic_marker;
492                 struct inpcontainerhead *ichead;
493                 struct udp_mcast_arg arg;
494                 struct inpcb *last;
495                 int error;
496
497                 /*
498                  * Deliver a multicast or broadcast datagram to *all* sockets
499                  * for which the local and remote addresses and ports match
500                  * those of the incoming datagram.  This allows more than
501                  * one process to receive multi/broadcasts on the same port.
502                  * (This really ought to be done for unicast datagrams as
503                  * well, but that would cause problems with existing
504                  * applications that open both address-specific sockets and
505                  * a wildcard socket listening to the same port -- they would
506                  * end up receiving duplicates of every unicast datagram.
507                  * Those applications open the multiple sockets to overcome an
508                  * inadequacy of the UDP socket interface, but for backwards
509                  * compatibility we avoid the problem here rather than
510                  * fixing the interface.  Maybe 4.5BSD will remedy this?)
511                  */
512
513                 /*
514                  * Construct sockaddr format source address.
515                  */
516                 udp_in.sin_port = uh->uh_sport;
517                 udp_in.sin_addr = ip->ip_src;
518                 arg.udp_in = &udp_in;
519                 /*
520                  * Locate pcb(s) for datagram.
521                  * (Algorithm copied from raw_intr().)
522                  */
523                 last = NULL;
524 #ifdef INET6
525                 udp_in6.uin6_init_done = udp_ip6.uip6_init_done = 0;
526                 arg.udp_in6 = &udp_in6;
527                 arg.udp_ip6 = &udp_ip6;
528 #endif
529                 arg.iphlen = iphlen;
530
531                 connhead = &pcbinfo->hashbase[
532                     INP_PCBCONNHASH(ip->ip_src.s_addr, uh->uh_sport,
533                     ip->ip_dst.s_addr, uh->uh_dport, pcbinfo->hashmask)];
534                 LIST_FOREACH(inp, connhead, inp_hash) {
535 #ifdef INET6
536                         if (!(inp->inp_vflag & INP_IPV4))
537                                 continue;
538 #endif
539                         if (!in_hosteq(inp->inp_faddr, ip->ip_src) ||
540                             !in_hosteq(inp->inp_laddr, ip->ip_dst) ||
541                             inp->inp_fport != uh->uh_sport ||
542                             inp->inp_lport != uh->uh_dport)
543                                 continue;
544
545                         arg.inp = inp;
546                         arg.last = last;
547                         arg.ip = ip;
548                         arg.m = m;
549
550                         error = udp_mcast_input(&arg);
551                         if (error == ERESTART)
552                                 continue;
553                         last = arg.last;
554
555                         if (error == EJUSTRETURN)
556                                 goto done;
557                 }
558
559                 ichead = &pcbinfo->wildcardhashbase[
560                     INP_PCBWILDCARDHASH(uh->uh_dport,
561                     pcbinfo->wildcardhashmask)];
562                 ic_marker = in_pcbcontainer_marker(mycpuid);
563
564                 GET_PCBINFO_TOKEN(pcbinfo);
565                 LIST_INSERT_HEAD(ichead, ic_marker, ic_list);
566                 while ((ic = LIST_NEXT(ic_marker, ic_list)) != NULL) {
567                         LIST_REMOVE(ic_marker, ic_list);
568                         LIST_INSERT_AFTER(ic, ic_marker, ic_list);
569
570                         inp = ic->ic_inp;
571                         if (inp->inp_flags & INP_PLACEMARKER)
572                                 continue;
573 #ifdef INET6
574                         if (!(inp->inp_vflag & INP_IPV4))
575                                 continue;
576 #endif
577                         if (inp->inp_lport != uh->uh_dport)
578                                 continue;
579                         if (inp->inp_laddr.s_addr != INADDR_ANY &&
580                             inp->inp_laddr.s_addr != ip->ip_dst.s_addr)
581                                 continue;
582
583                         arg.inp = inp;
584                         arg.last = last;
585                         arg.ip = ip;
586                         arg.m = m;
587
588                         error = udp_mcast_input(&arg);
589                         if (error == ERESTART)
590                                 continue;
591                         last = arg.last;
592
593                         if (error == EJUSTRETURN)
594                                 break;
595                 }
596                 LIST_REMOVE(ic_marker, ic_list);
597                 REL_PCBINFO_TOKEN(pcbinfo);
598 done:
599                 if (last == NULL) {
600                         /*
601                          * No matching pcb found; discard datagram.
602                          * (No need to send an ICMP Port Unreachable
603                          * for a broadcast or multicast datgram.)
604                          */
605                         udp_stat.udps_noportbcast++;
606                         goto bad;
607                 }
608 #ifdef IPSEC
609                 /* check AH/ESP integrity. */
610                 if (ipsec4_in_reject_so(m, last->inp_socket)) {
611                         ipsecstat.in_polvio++;
612                         goto bad;
613                 }
614 #endif /*IPSEC*/
615 #ifdef FAST_IPSEC
616                 /* check AH/ESP integrity. */
617                 if (ipsec4_in_reject(m, last))
618                         goto bad;
619 #endif /*FAST_IPSEC*/
620                 udp_append(last, ip, m, iphlen + sizeof(struct udphdr),
621                     &udp_in,
622 #ifdef INET6
623                     &udp_in6, &udp_ip6
624 #else
625                     NULL, NULL
626 #endif
627                     );
628                 return(IPPROTO_DONE);
629         }
630         /*
631          * Locate pcb for datagram.
632          */
633         inp = in_pcblookup_pkthash(pcbinfo, ip->ip_src, uh->uh_sport,
634             ip->ip_dst, uh->uh_dport, TRUE, m->m_pkthdr.rcvif,
635             udp_reuseport_ext ? m : NULL);
636         if (inp == NULL) {
637                 if (log_in_vain) {
638                         char buf[sizeof "aaa.bbb.ccc.ddd"];
639
640                         strcpy(buf, inet_ntoa(ip->ip_dst));
641                         log(LOG_INFO,
642                             "Connection attempt to UDP %s:%d from %s:%d\n",
643                             buf, ntohs(uh->uh_dport), inet_ntoa(ip->ip_src),
644                             ntohs(uh->uh_sport));
645                 }
646                 udp_stat.udps_noport++;
647                 if (m->m_flags & (M_BCAST | M_MCAST)) {
648                         udp_stat.udps_noportbcast++;
649                         goto bad;
650                 }
651                 if (blackhole)
652                         goto bad;
653 #ifdef ICMP_BANDLIM
654                 if (badport_bandlim(BANDLIM_ICMP_UNREACH) < 0)
655                         goto bad;
656 #endif
657                 *ip = save_ip;
658                 ip->ip_len += iphlen;
659                 icmp_error(m, ICMP_UNREACH, ICMP_UNREACH_PORT, 0, 0);
660                 return(IPPROTO_DONE);
661         }
662 #ifdef IPSEC
663         if (ipsec4_in_reject_so(m, inp->inp_socket)) {
664                 ipsecstat.in_polvio++;
665                 goto bad;
666         }
667 #endif /*IPSEC*/
668 #ifdef FAST_IPSEC
669         if (ipsec4_in_reject(m, inp))
670                 goto bad;
671 #endif /*FAST_IPSEC*/
672         /*
673          * Check the minimum TTL for socket.
674          */
675         if (ip->ip_ttl < inp->inp_ip_minttl)
676                 goto bad;
677
678         /*
679          * Construct sockaddr format source address.
680          * Stuff source address and datagram in user buffer.
681          */
682         udp_in.sin_port = uh->uh_sport;
683         udp_in.sin_addr = ip->ip_src;
684         if ((inp->inp_flags & INP_CONTROLOPTS) ||
685             (inp->inp_socket->so_options & SO_TIMESTAMP)) {
686 #ifdef INET6
687                 if (inp->inp_vflag & INP_IPV6) {
688                         int savedflags;
689
690                         ip_2_ip6_hdr(&udp_ip6.uip6_ip6, ip);
691                         savedflags = inp->inp_flags;
692                         inp->inp_flags &= ~INP_UNMAPPABLEOPTS;
693                         ip6_savecontrol(inp, &opts, &udp_ip6.uip6_ip6, m);
694                         inp->inp_flags = savedflags;
695                 } else
696 #endif
697                 ip_savecontrol(inp, &opts, ip, m);
698         }
699         m_adj(m, iphlen + sizeof(struct udphdr));
700 #ifdef INET6
701         if (inp->inp_vflag & INP_IPV6) {
702                 in6_sin_2_v4mapsin6(&udp_in, &udp_in6.uin6_sin);
703                 append_sa = (struct sockaddr *)&udp_in6;
704         } else
705 #endif
706                 append_sa = (struct sockaddr *)&udp_in;
707
708         lwkt_gettoken(&inp->inp_socket->so_rcv.ssb_token);
709         if (ssb_appendaddr(&inp->inp_socket->so_rcv, append_sa, m, opts) == 0) {
710                 lwkt_reltoken(&inp->inp_socket->so_rcv.ssb_token);
711                 udp_stat.udps_fullsock++;
712                 goto bad;
713         }
714         lwkt_reltoken(&inp->inp_socket->so_rcv.ssb_token);
715         sorwakeup(inp->inp_socket);
716         return(IPPROTO_DONE);
717 bad:
718         m_freem(m);
719         if (opts)
720                 m_freem(opts);
721         return(IPPROTO_DONE);
722 }
723
724 #ifdef INET6
725 static void
726 ip_2_ip6_hdr(struct ip6_hdr *ip6, struct ip *ip)
727 {
728         bzero(ip6, sizeof *ip6);
729
730         ip6->ip6_vfc = IPV6_VERSION;
731         ip6->ip6_plen = ip->ip_len;
732         ip6->ip6_nxt = ip->ip_p;
733         ip6->ip6_hlim = ip->ip_ttl;
734         ip6->ip6_src.s6_addr32[2] = ip6->ip6_dst.s6_addr32[2] =
735                 IPV6_ADDR_INT32_SMP;
736         ip6->ip6_src.s6_addr32[3] = ip->ip_src.s_addr;
737         ip6->ip6_dst.s6_addr32[3] = ip->ip_dst.s_addr;
738 }
739 #endif
740
741 /*
742  * subroutine of udp_input(), mainly for source code readability.
743  * caller must properly init udp_ip6 and udp_in6 beforehand.
744  */
745 static void
746 udp_append(struct inpcb *last, struct ip *ip, struct mbuf *n, int off,
747     struct sockaddr_in *udp_in,
748     struct udp_in6 *udp_in6, struct udp_ip6 *udp_ip6)
749 {
750         struct sockaddr *append_sa;
751         struct mbuf *opts = NULL;
752         int ret;
753
754         if (last->inp_flags & INP_CONTROLOPTS ||
755             last->inp_socket->so_options & SO_TIMESTAMP) {
756 #ifdef INET6
757                 if (last->inp_vflag & INP_IPV6) {
758                         int savedflags;
759
760                         if (udp_ip6->uip6_init_done == 0) {
761                                 ip_2_ip6_hdr(&udp_ip6->uip6_ip6, ip);
762                                 udp_ip6->uip6_init_done = 1;
763                         }
764                         savedflags = last->inp_flags;
765                         last->inp_flags &= ~INP_UNMAPPABLEOPTS;
766                         ip6_savecontrol(last, &opts, &udp_ip6->uip6_ip6, n);
767                         last->inp_flags = savedflags;
768                 } else
769 #endif
770                 ip_savecontrol(last, &opts, ip, n);
771         }
772 #ifdef INET6
773         if (last->inp_vflag & INP_IPV6) {
774                 if (udp_in6->uin6_init_done == 0) {
775                         in6_sin_2_v4mapsin6(udp_in, &udp_in6->uin6_sin);
776                         udp_in6->uin6_init_done = 1;
777                 }
778                 append_sa = (struct sockaddr *)&udp_in6->uin6_sin;
779         } else
780 #endif
781                 append_sa = (struct sockaddr *)udp_in;
782         m_adj(n, off);
783
784         lwkt_gettoken(&last->inp_socket->so_rcv.ssb_token);
785         ret = ssb_appendaddr(&last->inp_socket->so_rcv, append_sa, n, opts);
786         lwkt_reltoken(&last->inp_socket->so_rcv.ssb_token);
787         if (ret == 0) {
788                 m_freem(n);
789                 if (opts)
790                         m_freem(opts);
791                 udp_stat.udps_fullsock++;
792         } else {
793                 sorwakeup(last->inp_socket);
794         }
795 }
796
797 /*
798  * Notify a udp user of an asynchronous error;
799  * just wake up so that he can collect error status.
800  */
801 void
802 udp_notify(struct inpcb *inp, int error)
803 {
804         inp->inp_socket->so_error = error;
805         sorwakeup(inp->inp_socket);
806         sowwakeup(inp->inp_socket);
807 }
808
809 struct netmsg_udp_notify {
810         struct netmsg_base base;
811         void            (*nm_notify)(struct inpcb *, int);
812         struct in_addr  nm_faddr;
813         int             nm_arg;
814 };
815
816 static void
817 udp_notifyall_oncpu(netmsg_t msg)
818 {
819         struct netmsg_udp_notify *nm = (struct netmsg_udp_notify *)msg;
820         int nextcpu, cpu = mycpuid;
821
822         in_pcbnotifyall(&udbinfo[cpu], nm->nm_faddr, nm->nm_arg, nm->nm_notify);
823
824         nextcpu = cpu + 1;
825         if (nextcpu < ncpus2)
826                 lwkt_forwardmsg(netisr_cpuport(nextcpu), &nm->base.lmsg);
827         else
828                 lwkt_replymsg(&nm->base.lmsg, 0);
829 }
830
831 void
832 udp_ctlinput(netmsg_t msg)
833 {
834         struct sockaddr *sa = msg->ctlinput.nm_arg;
835         struct ip *ip = msg->ctlinput.nm_extra;
836         int cmd = msg->ctlinput.nm_cmd;
837         struct udphdr *uh;
838         void (*notify) (struct inpcb *, int) = udp_notify;
839         struct in_addr faddr;
840         struct inpcb *inp;
841
842         faddr = ((struct sockaddr_in *)sa)->sin_addr;
843         if (sa->sa_family != AF_INET || faddr.s_addr == INADDR_ANY)
844                 goto done;
845
846         if (PRC_IS_REDIRECT(cmd)) {
847                 ip = NULL;
848                 notify = in_rtchange;
849         } else if (cmd == PRC_HOSTDEAD) {
850                 ip = NULL;
851         } else if ((unsigned)cmd >= PRC_NCMDS || inetctlerrmap[cmd] == 0) {
852                 goto done;
853         }
854
855         if (ip) {
856                 uh = (struct udphdr *)((caddr_t)ip + (ip->ip_hl << 2));
857                 inp = in_pcblookup_hash(&udbinfo[mycpuid], faddr, uh->uh_dport,
858                                         ip->ip_src, uh->uh_sport, 0, NULL);
859                 if (inp != NULL && inp->inp_socket != NULL)
860                         (*notify)(inp, inetctlerrmap[cmd]);
861         } else {
862                 struct netmsg_udp_notify *nm;
863
864                 KKASSERT(&curthread->td_msgport == netisr_cpuport(0));
865                 nm = kmalloc(sizeof(*nm), M_LWKTMSG, M_INTWAIT);
866                 netmsg_init(&nm->base, NULL, &netisr_afree_rport,
867                             0, udp_notifyall_oncpu);
868                 nm->nm_faddr = faddr;
869                 nm->nm_arg = inetctlerrmap[cmd];
870                 nm->nm_notify = notify;
871                 lwkt_sendmsg(netisr_cpuport(0), &nm->base.lmsg);
872         }
873 done:
874         lwkt_replymsg(&msg->lmsg, 0);
875 }
876
877 SYSCTL_PROC(_net_inet_udp, UDPCTL_PCBLIST, pcblist, CTLFLAG_RD, udbinfo, 0,
878             in_pcblist_global_ncpus2, "S,xinpcb", "List of active UDP sockets");
879
880 static int
881 udp_getcred(SYSCTL_HANDLER_ARGS)
882 {
883         struct sockaddr_in addrs[2];
884         struct ucred cred0, *cred = NULL;
885         struct inpcb *inp;
886         int error, cpu, origcpu;
887
888         error = priv_check(req->td, PRIV_ROOT);
889         if (error)
890                 return (error);
891         error = SYSCTL_IN(req, addrs, sizeof addrs);
892         if (error)
893                 return (error);
894
895         origcpu = mycpuid;
896         cpu = udp_addrcpu(addrs[1].sin_addr.s_addr, addrs[1].sin_port,
897             addrs[0].sin_addr.s_addr, addrs[0].sin_port);
898
899         lwkt_migratecpu(cpu);
900
901         inp = in_pcblookup_hash(&udbinfo[cpu],
902             addrs[1].sin_addr, addrs[1].sin_port,
903             addrs[0].sin_addr, addrs[0].sin_port, TRUE, NULL);
904         if (inp == NULL || inp->inp_socket == NULL) {
905                 error = ENOENT;
906         } else if (inp->inp_socket->so_cred != NULL) {
907                 cred0 = *(inp->inp_socket->so_cred);
908                 cred = &cred0;
909         }
910
911         lwkt_migratecpu(origcpu);
912
913         if (error)
914                 return error;
915
916         return SYSCTL_OUT(req, cred, sizeof(struct ucred));
917 }
918 SYSCTL_PROC(_net_inet_udp, OID_AUTO, getcred, CTLTYPE_OPAQUE|CTLFLAG_RW,
919     0, 0, udp_getcred, "S,ucred", "Get the ucred of a UDP connection");
920
921 static void
922 udp_send_redispatch(netmsg_t msg)
923 {
924         struct mbuf *m = msg->send.nm_m;
925         int pru_flags = msg->send.nm_flags;
926         struct inpcb *inp = msg->send.base.nm_so->so_pcb;
927         struct mbuf *m_opt = msg->send.nm_control; /* XXX save ipopt */
928         int flags = msg->send.nm_priv; /* ip_output flags */
929         int error;
930
931         logudp(redisp_ipout_beg, inp);
932
933         /*
934          * - Don't use inp route cache.  It should only be used in the
935          *   inp owner netisr.
936          * - Access to inp_moptions should be safe, since multicast UDP
937          *   datagrams are redispatched to netisr0 and inp_moptions is
938          *   changed only in netisr0.
939          */
940         error = ip_output(m, m_opt, NULL, flags, inp->inp_moptions, inp);
941         if ((pru_flags & PRUS_NOREPLY) == 0)
942                 lwkt_replymsg(&msg->send.base.lmsg, error);
943
944         if (m_opt != NULL) {
945                 /* Free saved ip options, if any */
946                 m_freem(m_opt);
947         }
948
949         logudp(redisp_ipout_end, inp);
950 }
951
952 static void
953 udp_send(netmsg_t msg)
954 {
955         struct socket *so = msg->send.base.nm_so;
956         struct mbuf *m = msg->send.nm_m;
957         struct sockaddr *dstaddr = msg->send.nm_addr;
958         int pru_flags = msg->send.nm_flags;
959         struct inpcb *inp = so->so_pcb;
960         struct thread *td = msg->send.nm_td;
961         int flags;
962
963         struct udpiphdr *ui;
964         int len = m->m_pkthdr.len;
965         struct sockaddr_in *sin;        /* really is initialized before use */
966         int error = 0, cpu;
967
968         KKASSERT(msg->send.nm_control == NULL);
969
970         logudp(send_beg, inp);
971
972         if (inp == NULL) {
973                 error = EINVAL;
974                 goto release;
975         }
976
977         if (len + sizeof(struct udpiphdr) > IP_MAXPACKET) {
978                 error = EMSGSIZE;
979                 goto release;
980         }
981
982         if (inp->inp_lport == 0) {      /* unbound socket */
983                 boolean_t forwarded;
984
985                 error = in_pcbbind(inp, NULL, td);
986                 if (error)
987                         goto release;
988
989                 /*
990                  * Need to call udp_send again, after this inpcb is
991                  * inserted into wildcard hash table.
992                  */
993                 msg->send.base.lmsg.ms_flags |= MSGF_UDP_SEND;
994                 forwarded = udp_inswildcardhash(inp, &msg->send.base, 0);
995                 if (forwarded) {
996                         /*
997                          * The message is further forwarded, so we are
998                          * done here.
999                          */
1000                         logudp(send_inswildcard, inp);
1001                         return;
1002                 }
1003         }
1004
1005         if (dstaddr != NULL) {          /* destination address specified */
1006                 if (inp->inp_faddr.s_addr != INADDR_ANY) {
1007                         /* already connected */
1008                         error = EISCONN;
1009                         goto release;
1010                 }
1011                 sin = (struct sockaddr_in *)dstaddr;
1012                 if (!prison_remote_ip(td, (struct sockaddr *)&sin)) {
1013                         error = EAFNOSUPPORT; /* IPv6 only jail */
1014                         goto release;
1015                 }
1016         } else {
1017                 if (inp->inp_faddr.s_addr == INADDR_ANY) {
1018                         /* no destination specified and not already connected */
1019                         error = ENOTCONN;
1020                         goto release;
1021                 }
1022                 sin = NULL;
1023         }
1024
1025         /*
1026          * Calculate data length and get a mbuf
1027          * for UDP and IP headers.
1028          */
1029         M_PREPEND(m, sizeof(struct udpiphdr), MB_DONTWAIT);
1030         if (m == NULL) {
1031                 error = ENOBUFS;
1032                 goto release;
1033         }
1034
1035         /*
1036          * Fill in mbuf with extended UDP header
1037          * and addresses and length put into network format.
1038          */
1039         ui = mtod(m, struct udpiphdr *);
1040         bzero(ui->ui_x1, sizeof ui->ui_x1);     /* XXX still needed? */
1041         ui->ui_pr = IPPROTO_UDP;
1042
1043         /*
1044          * Set destination address.
1045          */
1046         if (dstaddr != NULL) {                  /* use specified destination */
1047                 ui->ui_dst = sin->sin_addr;
1048                 ui->ui_dport = sin->sin_port;
1049         } else {                                /* use connected destination */
1050                 ui->ui_dst = inp->inp_faddr;
1051                 ui->ui_dport = inp->inp_fport;
1052         }
1053
1054         /*
1055          * Set source address.
1056          */
1057         if (inp->inp_laddr.s_addr == INADDR_ANY ||
1058             IN_MULTICAST(ntohl(inp->inp_laddr.s_addr))) {
1059                 struct sockaddr_in *if_sin;
1060
1061                 if (dstaddr == NULL) {  
1062                         /*
1063                          * connect() had (or should have) failed because
1064                          * the interface had no IP address, but the
1065                          * application proceeded to call send() anyways.
1066                          */
1067                         error = ENOTCONN;
1068                         goto release;
1069                 }
1070
1071                 /* Look up outgoing interface. */
1072                 error = in_pcbladdr_find(inp, dstaddr, &if_sin, td, 1);
1073                 if (error)
1074                         goto release;
1075                 ui->ui_src = if_sin->sin_addr;  /* use address of interface */
1076         } else {
1077                 ui->ui_src = inp->inp_laddr;    /* use non-null bound address */
1078         }
1079         ui->ui_sport = inp->inp_lport;
1080         KASSERT(inp->inp_lport != 0, ("inp lport should have been bound"));
1081
1082         /*
1083          * Release the original thread, since it is no longer used
1084          */
1085         if (pru_flags & PRUS_HELDTD) {
1086                 lwkt_rele(td);
1087                 pru_flags &= ~PRUS_HELDTD;
1088         }
1089         /*
1090          * Free the dest address, since it is no longer needed
1091          */
1092         if (pru_flags & PRUS_FREEADDR) {
1093                 kfree(dstaddr, M_SONAME);
1094                 pru_flags &= ~PRUS_FREEADDR;
1095         }
1096
1097         ui->ui_ulen = htons((u_short)len + sizeof(struct udphdr));
1098
1099         /*
1100          * Set up checksum and output datagram.
1101          */
1102         if (udpcksum) {
1103                 ui->ui_sum = in_pseudo(ui->ui_src.s_addr, ui->ui_dst.s_addr,
1104                     htons((u_short)len + sizeof(struct udphdr) + IPPROTO_UDP));
1105                 m->m_pkthdr.csum_flags = CSUM_UDP;
1106                 m->m_pkthdr.csum_data = offsetof(struct udphdr, uh_sum);
1107                 m->m_pkthdr.csum_thlen = sizeof(struct udphdr);
1108         } else {
1109                 ui->ui_sum = 0;
1110         }
1111         ((struct ip *)ui)->ip_len = sizeof(struct udpiphdr) + len;
1112         ((struct ip *)ui)->ip_ttl = inp->inp_ip_ttl;    /* XXX */
1113         ((struct ip *)ui)->ip_tos = inp->inp_ip_tos;    /* XXX */
1114         udp_stat.udps_opackets++;
1115
1116         flags = IP_DEBUGROUTE |
1117             (inp->inp_socket->so_options & (SO_DONTROUTE | SO_BROADCAST));
1118         if (pru_flags & PRUS_DONTROUTE)
1119                 flags |= SO_DONTROUTE;
1120
1121         if (inp->inp_flags & INP_CONNECTED) {
1122                 /*
1123                  * For connected socket, this datagram has already
1124                  * been in the correct netisr; no need to rehash.
1125                  */
1126                 goto sendit;
1127         }
1128
1129         cpu = udp_addrcpu(ui->ui_dst.s_addr, ui->ui_dport,
1130             ui->ui_src.s_addr, ui->ui_sport);
1131         if (cpu != mycpuid) {
1132                 struct mbuf *m_opt = NULL;
1133                 struct netmsg_pru_send *smsg;
1134                 struct lwkt_port *port = netisr_cpuport(cpu);
1135
1136                 /*
1137                  * Not on the CPU that matches this UDP datagram hash;
1138                  * redispatch to the correct CPU to do the ip_output().
1139                  */
1140                 if (inp->inp_options != NULL) {
1141                         /*
1142                          * If there are ip options, then save a copy,
1143                          * since accessing inp_options on other CPUs'
1144                          * is not safe.
1145                          *
1146                          * XXX optimize this?
1147                          */
1148                         m_opt = m_copym(inp->inp_options, 0, M_COPYALL,
1149                             MB_WAIT);
1150                 }
1151                 if ((pru_flags & PRUS_NOREPLY) == 0) {
1152                         /*
1153                          * Change some parts of the original netmsg and
1154                          * forward it to the target netisr.
1155                          *
1156                          * NOTE: so_port MUST NOT be checked in the target
1157                          * netisr.
1158                          */
1159                         smsg = &msg->send;
1160                         smsg->nm_priv = flags; /* ip_output flags */
1161                         smsg->nm_m = m;
1162                         smsg->nm_control = m_opt; /* XXX save ipopt */
1163                         smsg->base.lmsg.ms_flags |= MSGF_IGNSOPORT;
1164                         smsg->base.nm_dispatch = udp_send_redispatch;
1165                         lwkt_forwardmsg(port, &smsg->base.lmsg);
1166                 } else {
1167                         /*
1168                          * Recreate the netmsg, since the original mbuf
1169                          * could have been changed.  And send it to the
1170                          * target netisr.
1171                          *
1172                          * NOTE: so_port MUST NOT be checked in the target
1173                          * netisr.
1174                          */
1175                         smsg = &m->m_hdr.mh_sndmsg;
1176                         netmsg_init(&smsg->base, so, &netisr_apanic_rport,
1177                             MSGF_IGNSOPORT, udp_send_redispatch);
1178                         smsg->nm_priv = flags; /* ip_output flags */
1179                         smsg->nm_flags = pru_flags;
1180                         smsg->nm_m = m;
1181                         smsg->nm_control = m_opt; /* XXX save ipopt */
1182                         lwkt_sendmsg(port, &smsg->base.lmsg);
1183                 }
1184
1185                 /* This UDP datagram is redispatched; done */
1186                 logudp(send_redisp, inp);
1187                 return;
1188         }
1189
1190 sendit:
1191         logudp(send_ipout, inp);
1192         error = ip_output(m, inp->inp_options, &inp->inp_route, flags,
1193             inp->inp_moptions, inp);
1194         m = NULL;
1195
1196 release:
1197         if (m != NULL)
1198                 m_freem(m);
1199
1200         if (pru_flags & PRUS_HELDTD)
1201                 lwkt_rele(td);
1202         if (pru_flags & PRUS_FREEADDR)
1203                 kfree(dstaddr, M_SONAME);
1204         if ((pru_flags & PRUS_NOREPLY) == 0)
1205                 lwkt_replymsg(&msg->send.base.lmsg, error);
1206
1207         logudp(send_end, inp);
1208 }
1209
1210 u_long  udp_sendspace = 9216;           /* really max datagram size */
1211                                         /* 40 1K datagrams */
1212 SYSCTL_INT(_net_inet_udp, UDPCTL_MAXDGRAM, maxdgram, CTLFLAG_RW,
1213     &udp_sendspace, 0, "Maximum outgoing UDP datagram size");
1214
1215 u_long  udp_recvspace = 40 * (1024 +
1216 #ifdef INET6
1217                                       sizeof(struct sockaddr_in6)
1218 #else
1219                                       sizeof(struct sockaddr_in)
1220 #endif
1221                                       );
1222 SYSCTL_INT(_net_inet_udp, UDPCTL_RECVSPACE, recvspace, CTLFLAG_RW,
1223     &udp_recvspace, 0, "Maximum incoming UDP datagram size");
1224
1225 /*
1226  * This should never happen, since UDP socket does not support
1227  * connection acception (SO_ACCEPTCONN, i.e. listen(2)).
1228  */
1229 static void
1230 udp_abort(netmsg_t msg __unused)
1231 {
1232         panic("udp_abort is called");
1233 }
1234
1235 static void
1236 udp_attach(netmsg_t msg)
1237 {
1238         struct socket *so = msg->attach.base.nm_so;
1239         struct pru_attach_info *ai = msg->attach.nm_ai;
1240         struct inpcb *inp;
1241         int error;
1242
1243         inp = so->so_pcb;
1244         if (inp != NULL) {
1245                 error = EINVAL;
1246                 goto out;
1247         }
1248         error = soreserve(so, udp_sendspace, udp_recvspace, ai->sb_rlimit);
1249         if (error)
1250                 goto out;
1251
1252         error = in_pcballoc(so, &udbinfo[mycpuid]);
1253         if (error)
1254                 goto out;
1255
1256         inp = (struct inpcb *)so->so_pcb;
1257         inp->inp_vflag |= INP_IPV4;
1258         inp->inp_ip_ttl = ip_defttl;
1259         error = 0;
1260 out:
1261         lwkt_replymsg(&msg->attach.base.lmsg, error);
1262 }
1263
1264 static boolean_t
1265 udp_inswildcardhash_oncpu(struct inpcb *inp)
1266 {
1267         int cpu;
1268
1269         KASSERT(inp->inp_pcbinfo == &udbinfo[mycpuid],
1270             ("not on owner cpu"));
1271
1272         in_pcbinswildcardhash(inp);
1273         for (cpu = 0; cpu < ncpus2; ++cpu) {
1274                 if (cpu == mycpuid) {
1275                         /*
1276                          * This inpcb has been inserted by the above
1277                          * in_pcbinswildcardhash().
1278                          */
1279                         continue;
1280                 }
1281                 in_pcbinswildcardhash_oncpu(inp, &udbinfo[cpu]);
1282         }
1283
1284         /* TODO need to change port again, if SO_REUSEPORT */
1285         return FALSE;
1286 }
1287
1288 static void
1289 udp_inswildcardhash_dispatch(netmsg_t msg)
1290 {
1291         struct inpcb *inp = msg->base.nm_so->so_pcb;
1292         lwkt_msg_t lmsg = &msg->base.lmsg;
1293         boolean_t forwarded;
1294
1295         KASSERT(inp->inp_lport != 0, ("local port not set yet"));
1296         KASSERT((ntohs(inp->inp_lport) & ncpus2_mask) == mycpuid,
1297             ("not target cpu"));
1298
1299         in_pcblink(inp, &udbinfo[mycpuid]);
1300
1301         forwarded = udp_inswildcardhash_oncpu(inp);
1302         if (forwarded) {
1303                 /* The message is further forwarded, so we are done here. */
1304                 return;
1305         }
1306
1307         if (lmsg->ms_flags & MSGF_UDP_SEND) {
1308                 udp_send(msg);
1309                 /* msg is replied by udp_send() */
1310         } else {
1311                 lwkt_replymsg(lmsg, lmsg->ms_error);
1312         }
1313 }
1314
1315 static void
1316 udp_sosetport(struct lwkt_msg *msg, lwkt_port_t port)
1317 {
1318         sosetport(((struct netmsg_base *)msg)->nm_so, port);
1319 }
1320
1321 static boolean_t
1322 udp_inswildcardhash(struct inpcb *inp, struct netmsg_base *msg, int error)
1323 {
1324         lwkt_msg_t lmsg = &msg->lmsg;
1325         int cpu;
1326
1327         /*
1328          * Always clear the route cache, so we don't need to
1329          * worry about any owner CPU changes later.
1330          */
1331         udp_reset_route(inp);
1332
1333         KASSERT(inp->inp_lport != 0, ("local port not set yet"));
1334         cpu = ntohs(inp->inp_lport) & ncpus2_mask;
1335
1336         lmsg->ms_error = error;
1337         if (cpu != mycpuid) {
1338                 struct lwkt_port *port = netisr_cpuport(cpu);
1339
1340                 /*
1341                  * We are moving the protocol processing port the socket
1342                  * is on, we have to unlink here and re-link on the
1343                  * target cpu.
1344                  */
1345                 in_pcbunlink(inp, &udbinfo[mycpuid]);
1346                 msg->nm_dispatch = udp_inswildcardhash_dispatch;
1347
1348                 /* See the related comment in tcp_usrreq.c tcp_connect() */
1349                 lwkt_setmsg_receipt(lmsg, udp_sosetport);
1350                 lwkt_forwardmsg(port, lmsg);
1351                 return TRUE; /* forwarded */
1352         }
1353
1354         return udp_inswildcardhash_oncpu(inp);
1355 }
1356
1357 static void
1358 udp_bind(netmsg_t msg)
1359 {
1360         struct socket *so = msg->bind.base.nm_so;
1361         struct inpcb *inp;
1362         int error;
1363
1364         inp = so->so_pcb;
1365         if (inp) {
1366                 struct sockaddr *nam = msg->bind.nm_nam;
1367                 struct thread *td = msg->bind.nm_td;
1368
1369                 error = in_pcbbind(inp, nam, td);
1370                 if (error == 0) {
1371                         struct sockaddr_in *sin = (struct sockaddr_in *)nam;
1372                         boolean_t forwarded;
1373
1374                         if (sin->sin_addr.s_addr != INADDR_ANY)
1375                                 inp->inp_flags |= INP_WASBOUND_NOTANY;
1376
1377                         forwarded = udp_inswildcardhash(inp,
1378                             &msg->bind.base, 0);
1379                         if (forwarded) {
1380                                 /*
1381                                  * The message is further forwarded, so
1382                                  * we are done here.
1383                                  */
1384                                 return;
1385                         }
1386                 }
1387         } else {
1388                 error = EINVAL;
1389         }
1390         lwkt_replymsg(&msg->bind.base.lmsg, error);
1391 }
1392
1393 static void
1394 udp_connect(netmsg_t msg)
1395 {
1396         struct socket *so = msg->connect.base.nm_so;
1397         struct sockaddr *nam = msg->connect.nm_nam;
1398         struct thread *td = msg->connect.nm_td;
1399         struct inpcb *inp;
1400         struct sockaddr_in *sin = (struct sockaddr_in *)nam;
1401         struct sockaddr_in *if_sin;
1402         struct lwkt_port *port;
1403         int error;
1404
1405         KKASSERT(msg->connect.nm_m == NULL);
1406
1407         inp = so->so_pcb;
1408         if (inp == NULL) {
1409                 error = EINVAL;
1410                 goto out;
1411         }
1412
1413         if (msg->connect.nm_flags & PRUC_RECONNECT) {
1414                 msg->connect.nm_flags &= ~PRUC_RECONNECT;
1415                 in_pcblink(inp, &udbinfo[mycpuid]);
1416         }
1417
1418         if (inp->inp_faddr.s_addr != INADDR_ANY) {
1419                 error = EISCONN;
1420                 goto out;
1421         }
1422         error = 0;
1423
1424         /*
1425          * Bind if we have to
1426          */
1427         if (inp->inp_lport == 0 ||
1428             (td->td_proc && td->td_proc->p_ucred->cr_prison != NULL &&
1429              inp->inp_laddr.s_addr == INADDR_ANY)) {
1430                 error = in_pcbbind(inp, NULL, td);
1431                 if (error)
1432                         goto out;
1433         }
1434
1435         /*
1436          * Calculate the correct protocol processing thread.  The connect
1437          * operation must run there.
1438          */
1439         error = in_pcbladdr(inp, nam, &if_sin, td);
1440         if (error)
1441                 goto out;
1442         if (!prison_remote_ip(td, nam)) {
1443                 error = EAFNOSUPPORT; /* IPv6 only jail */
1444                 goto out;
1445         }
1446
1447         port = udp_addrport(sin->sin_addr.s_addr, sin->sin_port,
1448             inp->inp_laddr.s_addr != INADDR_ANY ?
1449             inp->inp_laddr.s_addr : if_sin->sin_addr.s_addr, inp->inp_lport);
1450         if (port != &curthread->td_msgport) {
1451                 lwkt_msg_t lmsg = &msg->connect.base.lmsg;
1452                 int nm_flags = PRUC_RECONNECT;
1453
1454                 /*
1455                  * in_pcbladdr() may have allocated a route entry for us
1456                  * on the current CPU, but we need a route entry on the
1457                  * inpcb's owner CPU, so free it here.
1458                  */
1459                 udp_reset_route(inp);
1460
1461                 if (inp->inp_flags & INP_WILDCARD) {
1462                         /*
1463                          * Remove this inpcb from the wildcard hash before
1464                          * the socket's msgport changes.
1465                          */
1466                         udp_remwildcardhash(inp);
1467                 }
1468
1469                 /*
1470                  * We are moving the protocol processing port the socket
1471                  * is on, we have to unlink here and re-link on the
1472                  * target cpu.
1473                  */
1474                 in_pcbunlink(inp, &udbinfo[mycpuid]);
1475                 msg->connect.nm_flags |= nm_flags;
1476
1477                 /* See the related comment in tcp_usrreq.c tcp_connect() */
1478                 lwkt_setmsg_receipt(lmsg, udp_sosetport);
1479                 lwkt_forwardmsg(port, lmsg);
1480                 /* msg invalid now */
1481                 return;
1482         }
1483         error = udp_connect_oncpu(inp, sin, if_sin);
1484 out:
1485         if (error && inp != NULL && inp->inp_lport != 0 &&
1486             (inp->inp_flags & INP_WILDCARD) == 0) {
1487                 boolean_t forwarded;
1488
1489                 /* Connect failed; put it to wildcard hash. */
1490                 forwarded = udp_inswildcardhash(inp, &msg->connect.base,
1491                     error);
1492                 if (forwarded) {
1493                         /*
1494                          * The message is further forwarded, so we are done
1495                          * here.
1496                          */
1497                         return;
1498                 }
1499         }
1500         lwkt_replymsg(&msg->connect.base.lmsg, error);
1501 }
1502
1503 static void
1504 udp_remwildcardhash(struct inpcb *inp)
1505 {
1506         int cpu;
1507
1508         KASSERT(inp->inp_pcbinfo == &udbinfo[mycpuid],
1509             ("not on owner cpu"));
1510
1511         for (cpu = 0; cpu < ncpus2; ++cpu) {
1512                 if (cpu == mycpuid) {
1513                         /*
1514                          * This inpcb will be removed by the later
1515                          * in_pcbremwildcardhash().
1516                          */
1517                         continue;
1518                 }
1519                 in_pcbremwildcardhash_oncpu(inp, &udbinfo[cpu]);
1520         }
1521         in_pcbremwildcardhash(inp);
1522 }
1523
1524 static int
1525 udp_connect_oncpu(struct inpcb *inp, struct sockaddr_in *sin,
1526     struct sockaddr_in *if_sin)
1527 {
1528         struct socket *so = inp->inp_socket;
1529         struct inpcb *oinp;
1530
1531         oinp = in_pcblookup_hash(inp->inp_pcbinfo,
1532             sin->sin_addr, sin->sin_port,
1533             inp->inp_laddr.s_addr != INADDR_ANY ?
1534             inp->inp_laddr : if_sin->sin_addr, inp->inp_lport, FALSE, NULL);
1535         if (oinp != NULL)
1536                 return EADDRINUSE;
1537
1538         /*
1539          * No more errors can occur, finish adjusting the socket
1540          * and change the processing port to reflect the connected
1541          * socket.  Once set we can no longer safely mess with the
1542          * socket.
1543          */
1544
1545         if (inp->inp_flags & INP_WILDCARD)
1546                 udp_remwildcardhash(inp);
1547
1548         if (inp->inp_laddr.s_addr == INADDR_ANY)
1549                 inp->inp_laddr = if_sin->sin_addr;
1550         inp->inp_faddr = sin->sin_addr;
1551         inp->inp_fport = sin->sin_port;
1552         in_pcbinsconnhash(inp);
1553
1554         soisconnected(so);
1555
1556         return 0;
1557 }
1558
1559 static void
1560 udp_detach2(struct socket *so)
1561 {
1562         in_pcbdetach(so->so_pcb);
1563         sodiscard(so);
1564         sofree(so);
1565 }
1566
1567 static void
1568 udp_detach_final_dispatch(netmsg_t msg)
1569 {
1570         udp_detach2(msg->base.nm_so);
1571 }
1572
1573 static void
1574 udp_detach_oncpu_dispatch(netmsg_t msg)
1575 {
1576         struct netmsg_base *clomsg = &msg->base;
1577         struct socket *so = clomsg->nm_so;
1578         struct inpcb *inp = so->so_pcb;
1579         struct thread *td = curthread;
1580         int nextcpu, cpuid = mycpuid;
1581
1582         KASSERT(td->td_type == TD_TYPE_NETISR, ("not in netisr"));
1583
1584         if (inp->inp_flags & INP_WILDCARD) {
1585                 /*
1586                  * This inp will be removed on the inp's
1587                  * owner CPU later, so don't do it now.
1588                  */
1589                 if (&td->td_msgport != so->so_port)
1590                         in_pcbremwildcardhash_oncpu(inp, &udbinfo[cpuid]);
1591         }
1592
1593         if (cpuid == 0) {
1594                 /*
1595                  * Free and clear multicast socket option,
1596                  * which is only accessed in netisr0.
1597                  */
1598                 ip_freemoptions(inp->inp_moptions);
1599                 inp->inp_moptions = NULL;
1600         }
1601
1602         nextcpu = cpuid + 1;
1603         if (nextcpu < ncpus2) {
1604                 lwkt_forwardmsg(netisr_cpuport(nextcpu), &clomsg->lmsg);
1605         } else {
1606                 /*
1607                  * No one could see this inpcb now; destroy this
1608                  * inpcb in its owner netisr.
1609                  */
1610                 netmsg_init(clomsg, so, &netisr_apanic_rport, 0,
1611                     udp_detach_final_dispatch);
1612                 lwkt_sendmsg(so->so_port, &clomsg->lmsg);
1613         }
1614 }
1615
1616 static void
1617 udp_detach(netmsg_t msg)
1618 {
1619         struct socket *so = msg->detach.base.nm_so;
1620         struct netmsg_base *clomsg;
1621         struct inpcb *inp;
1622
1623         inp = so->so_pcb;
1624         if (inp == NULL) {
1625                 lwkt_replymsg(&msg->detach.base.lmsg, EINVAL);
1626                 return;
1627         }
1628
1629         /*
1630          * Reply EJUSTRETURN ASAP, we will call sodiscard() and
1631          * sofree() later.
1632          */
1633         lwkt_replymsg(&msg->detach.base.lmsg, EJUSTRETURN);
1634
1635         if (ncpus == 1) {
1636                 /* Only one CPU, detach the inpcb directly. */
1637                 udp_detach2(so);
1638                 return;
1639         }
1640
1641         /*
1642          * Remove this inpcb from the inpcb list first, so that
1643          * no one could find this inpcb from the inpcb list.
1644          */
1645         in_pcbofflist(inp);
1646
1647         /*
1648          * Go through netisrs which process UDP to make sure
1649          * no one could find this inpcb anymore.
1650          */
1651         clomsg = &so->so_clomsg;
1652         netmsg_init(clomsg, so, &netisr_apanic_rport, MSGF_IGNSOPORT,
1653             udp_detach_oncpu_dispatch);
1654         lwkt_sendmsg(netisr_cpuport(0), &clomsg->lmsg);
1655 }
1656
1657 static void
1658 udp_disconnect(netmsg_t msg)
1659 {
1660         struct socket *so = msg->disconnect.base.nm_so;
1661         struct inpcb *inp;
1662         boolean_t forwarded;
1663         int error = 0;
1664
1665         inp = so->so_pcb;
1666         if (inp == NULL) {
1667                 error = EINVAL;
1668                 goto out;
1669         }
1670         if (inp->inp_faddr.s_addr == INADDR_ANY) {
1671                 error = ENOTCONN;
1672                 goto out;
1673         }
1674
1675         soclrstate(so, SS_ISCONNECTED);         /* XXX */
1676
1677         in_pcbdisconnect(inp);
1678
1679         /*
1680          * Follow traditional BSD behavior and retain the local port
1681          * binding.  But, fix the old misbehavior of overwriting any
1682          * previously bound local address.
1683          */
1684         if (!(inp->inp_flags & INP_WASBOUND_NOTANY))
1685                 inp->inp_laddr.s_addr = INADDR_ANY;
1686
1687         if (so->so_state & SS_ISCLOSING) {
1688                 /*
1689                  * If this socket is being closed, there is no need
1690                  * to put this socket back into wildcard hash table.
1691                  */
1692                 error = 0;
1693                 goto out;
1694         }
1695
1696         forwarded = udp_inswildcardhash(inp, &msg->disconnect.base, 0);
1697         if (forwarded) {
1698                 /*
1699                  * The message is further forwarded, so we are done
1700                  * here.
1701                  */
1702                 return;
1703         }
1704 out:
1705         lwkt_replymsg(&msg->disconnect.base.lmsg, error);
1706 }
1707
1708 void
1709 udp_shutdown(netmsg_t msg)
1710 {
1711         struct socket *so = msg->shutdown.base.nm_so;
1712         struct inpcb *inp;
1713         int error;
1714
1715         inp = so->so_pcb;
1716         if (inp) {
1717                 socantsendmore(so);
1718                 error = 0;
1719         } else {
1720                 error = EINVAL;
1721         }
1722         lwkt_replymsg(&msg->shutdown.base.lmsg, error);
1723 }
1724
1725 struct pr_usrreqs udp_usrreqs = {
1726         .pru_abort = udp_abort,
1727         .pru_accept = pr_generic_notsupp,
1728         .pru_attach = udp_attach,
1729         .pru_bind = udp_bind,
1730         .pru_connect = udp_connect,
1731         .pru_connect2 = pr_generic_notsupp,
1732         .pru_control = in_control_dispatch,
1733         .pru_detach = udp_detach,
1734         .pru_disconnect = udp_disconnect,
1735         .pru_listen = pr_generic_notsupp,
1736         .pru_peeraddr = in_setpeeraddr_dispatch,
1737         .pru_rcvd = pr_generic_notsupp,
1738         .pru_rcvoob = pr_generic_notsupp,
1739         .pru_send = udp_send,
1740         .pru_sense = pru_sense_null,
1741         .pru_shutdown = udp_shutdown,
1742         .pru_sockaddr = in_setsockaddr_dispatch,
1743         .pru_sosend = sosendudp,
1744         .pru_soreceive = soreceive
1745 };