]> CyberLeo.Net >> Repos - FreeBSD/FreeBSD.git/blob - sys/netinet/udp_usrreq.c
MFH r338661 through r339200.
[FreeBSD/FreeBSD.git] / sys / netinet / udp_usrreq.c
1 /*-
2  * SPDX-License-Identifier: BSD-3-Clause
3  *
4  * Copyright (c) 1982, 1986, 1988, 1990, 1993, 1995
5  *      The Regents of the University of California.
6  * Copyright (c) 2008 Robert N. M. Watson
7  * Copyright (c) 2010-2011 Juniper Networks, Inc.
8  * Copyright (c) 2014 Kevin Lo
9  * All rights reserved.
10  *
11  * Portions of this software were developed by Robert N. M. Watson under
12  * contract to Juniper Networks, Inc.
13  *
14  * Redistribution and use in source and binary forms, with or without
15  * modification, are permitted provided that the following conditions
16  * are met:
17  * 1. Redistributions of source code must retain the above copyright
18  *    notice, this list of conditions and the following disclaimer.
19  * 2. Redistributions in binary form must reproduce the above copyright
20  *    notice, this list of conditions and the following disclaimer in the
21  *    documentation and/or other materials provided with the distribution.
22  * 3. Neither the name of the University nor the names of its contributors
23  *    may be used to endorse or promote products derived from this software
24  *    without specific prior written permission.
25  *
26  * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
27  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
28  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
29  * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
30  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
31  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
32  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
33  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
34  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
35  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
36  * SUCH DAMAGE.
37  *
38  *      @(#)udp_usrreq.c        8.6 (Berkeley) 5/23/95
39  */
40
41 #include <sys/cdefs.h>
42 __FBSDID("$FreeBSD$");
43
44 #include "opt_inet.h"
45 #include "opt_inet6.h"
46 #include "opt_ipsec.h"
47 #include "opt_rss.h"
48
49 #include <sys/param.h>
50 #include <sys/domain.h>
51 #include <sys/eventhandler.h>
52 #include <sys/jail.h>
53 #include <sys/kernel.h>
54 #include <sys/lock.h>
55 #include <sys/malloc.h>
56 #include <sys/mbuf.h>
57 #include <sys/priv.h>
58 #include <sys/proc.h>
59 #include <sys/protosw.h>
60 #include <sys/sdt.h>
61 #include <sys/signalvar.h>
62 #include <sys/socket.h>
63 #include <sys/socketvar.h>
64 #include <sys/sx.h>
65 #include <sys/sysctl.h>
66 #include <sys/syslog.h>
67 #include <sys/systm.h>
68
69 #include <vm/uma.h>
70
71 #include <net/if.h>
72 #include <net/if_var.h>
73 #include <net/route.h>
74 #include <net/rss_config.h>
75
76 #include <netinet/in.h>
77 #include <netinet/in_kdtrace.h>
78 #include <netinet/in_pcb.h>
79 #include <netinet/in_systm.h>
80 #include <netinet/in_var.h>
81 #include <netinet/ip.h>
82 #ifdef INET6
83 #include <netinet/ip6.h>
84 #endif
85 #include <netinet/ip_icmp.h>
86 #include <netinet/icmp_var.h>
87 #include <netinet/ip_var.h>
88 #include <netinet/ip_options.h>
89 #ifdef INET6
90 #include <netinet6/ip6_var.h>
91 #endif
92 #include <netinet/udp.h>
93 #include <netinet/udp_var.h>
94 #include <netinet/udplite.h>
95 #include <netinet/in_rss.h>
96
97 #include <netipsec/ipsec_support.h>
98
99 #include <machine/in_cksum.h>
100
101 #include <security/mac/mac_framework.h>
102
103 /*
104  * UDP and UDP-Lite protocols implementation.
105  * Per RFC 768, August, 1980.
106  * Per RFC 3828, July, 2004.
107  */
108
109 /*
110  * BSD 4.2 defaulted the udp checksum to be off.  Turning off udp checksums
111  * removes the only data integrity mechanism for packets and malformed
112  * packets that would otherwise be discarded due to bad checksums, and may
113  * cause problems (especially for NFS data blocks).
114  */
115 VNET_DEFINE(int, udp_cksum) = 1;
116 SYSCTL_INT(_net_inet_udp, UDPCTL_CHECKSUM, checksum, CTLFLAG_VNET | CTLFLAG_RW,
117     &VNET_NAME(udp_cksum), 0, "compute udp checksum");
118
119 int     udp_log_in_vain = 0;
120 SYSCTL_INT(_net_inet_udp, OID_AUTO, log_in_vain, CTLFLAG_RW,
121     &udp_log_in_vain, 0, "Log all incoming UDP packets");
122
123 VNET_DEFINE(int, udp_blackhole) = 0;
124 SYSCTL_INT(_net_inet_udp, OID_AUTO, blackhole, CTLFLAG_VNET | CTLFLAG_RW,
125     &VNET_NAME(udp_blackhole), 0,
126     "Do not send port unreachables for refused connects");
127
128 u_long  udp_sendspace = 9216;           /* really max datagram size */
129 SYSCTL_ULONG(_net_inet_udp, UDPCTL_MAXDGRAM, maxdgram, CTLFLAG_RW,
130     &udp_sendspace, 0, "Maximum outgoing UDP datagram size");
131
132 u_long  udp_recvspace = 40 * (1024 +
133 #ifdef INET6
134                                       sizeof(struct sockaddr_in6)
135 #else
136                                       sizeof(struct sockaddr_in)
137 #endif
138                                       );        /* 40 1K datagrams */
139
140 SYSCTL_ULONG(_net_inet_udp, UDPCTL_RECVSPACE, recvspace, CTLFLAG_RW,
141     &udp_recvspace, 0, "Maximum space for incoming UDP datagrams");
142
143 VNET_DEFINE(struct inpcbhead, udb);             /* from udp_var.h */
144 VNET_DEFINE(struct inpcbinfo, udbinfo);
145 VNET_DEFINE(struct inpcbhead, ulitecb);
146 VNET_DEFINE(struct inpcbinfo, ulitecbinfo);
147 VNET_DEFINE_STATIC(uma_zone_t, udpcb_zone);
148 #define V_udpcb_zone                    VNET(udpcb_zone)
149
150 #ifndef UDBHASHSIZE
151 #define UDBHASHSIZE     128
152 #endif
153
154 VNET_PCPUSTAT_DEFINE(struct udpstat, udpstat);          /* from udp_var.h */
155 VNET_PCPUSTAT_SYSINIT(udpstat);
156 SYSCTL_VNET_PCPUSTAT(_net_inet_udp, UDPCTL_STATS, stats, struct udpstat,
157     udpstat, "UDP statistics (struct udpstat, netinet/udp_var.h)");
158
159 #ifdef VIMAGE
160 VNET_PCPUSTAT_SYSUNINIT(udpstat);
161 #endif /* VIMAGE */
162 #ifdef INET
163 static void     udp_detach(struct socket *so);
164 static int      udp_output(struct inpcb *, struct mbuf *, struct sockaddr *,
165                     struct mbuf *, struct thread *);
166 #endif
167
168 static void
169 udp_zone_change(void *tag)
170 {
171
172         uma_zone_set_max(V_udbinfo.ipi_zone, maxsockets);
173         uma_zone_set_max(V_udpcb_zone, maxsockets);
174 }
175
176 static int
177 udp_inpcb_init(void *mem, int size, int flags)
178 {
179         struct inpcb *inp;
180
181         inp = mem;
182         INP_LOCK_INIT(inp, "inp", "udpinp");
183         return (0);
184 }
185
186 static int
187 udplite_inpcb_init(void *mem, int size, int flags)
188 {
189         struct inpcb *inp;
190
191         inp = mem;
192         INP_LOCK_INIT(inp, "inp", "udpliteinp");
193         return (0);
194 }
195
196 void
197 udp_init(void)
198 {
199
200         /*
201          * For now default to 2-tuple UDP hashing - until the fragment
202          * reassembly code can also update the flowid.
203          *
204          * Once we can calculate the flowid that way and re-establish
205          * a 4-tuple, flip this to 4-tuple.
206          */
207         in_pcbinfo_init(&V_udbinfo, "udp", &V_udb, UDBHASHSIZE, UDBHASHSIZE,
208             "udp_inpcb", udp_inpcb_init, IPI_HASHFIELDS_2TUPLE);
209         V_udpcb_zone = uma_zcreate("udpcb", sizeof(struct udpcb),
210             NULL, NULL, NULL, NULL, UMA_ALIGN_PTR, 0);
211         uma_zone_set_max(V_udpcb_zone, maxsockets);
212         uma_zone_set_warning(V_udpcb_zone, "kern.ipc.maxsockets limit reached");
213         EVENTHANDLER_REGISTER(maxsockets_change, udp_zone_change, NULL,
214             EVENTHANDLER_PRI_ANY);
215 }
216
217 void
218 udplite_init(void)
219 {
220
221         in_pcbinfo_init(&V_ulitecbinfo, "udplite", &V_ulitecb, UDBHASHSIZE,
222             UDBHASHSIZE, "udplite_inpcb", udplite_inpcb_init,
223             IPI_HASHFIELDS_2TUPLE);
224 }
225
226 /*
227  * Kernel module interface for updating udpstat.  The argument is an index
228  * into udpstat treated as an array of u_long.  While this encodes the
229  * general layout of udpstat into the caller, it doesn't encode its location,
230  * so that future changes to add, for example, per-CPU stats support won't
231  * cause binary compatibility problems for kernel modules.
232  */
233 void
234 kmod_udpstat_inc(int statnum)
235 {
236
237         counter_u64_add(VNET(udpstat)[statnum], 1);
238 }
239
240 int
241 udp_newudpcb(struct inpcb *inp)
242 {
243         struct udpcb *up;
244
245         up = uma_zalloc(V_udpcb_zone, M_NOWAIT | M_ZERO);
246         if (up == NULL)
247                 return (ENOBUFS);
248         inp->inp_ppcb = up;
249         return (0);
250 }
251
252 void
253 udp_discardcb(struct udpcb *up)
254 {
255
256         uma_zfree(V_udpcb_zone, up);
257 }
258
259 #ifdef VIMAGE
260 static void
261 udp_destroy(void *unused __unused)
262 {
263
264         in_pcbinfo_destroy(&V_udbinfo);
265         uma_zdestroy(V_udpcb_zone);
266 }
267 VNET_SYSUNINIT(udp, SI_SUB_PROTO_DOMAIN, SI_ORDER_FOURTH, udp_destroy, NULL);
268
269 static void
270 udplite_destroy(void *unused __unused)
271 {
272
273         in_pcbinfo_destroy(&V_ulitecbinfo);
274 }
275 VNET_SYSUNINIT(udplite, SI_SUB_PROTO_DOMAIN, SI_ORDER_FOURTH, udplite_destroy,
276     NULL);
277 #endif
278
279 #ifdef INET
280 /*
281  * Subroutine of udp_input(), which appends the provided mbuf chain to the
282  * passed pcb/socket.  The caller must provide a sockaddr_in via udp_in that
283  * contains the source address.  If the socket ends up being an IPv6 socket,
284  * udp_append() will convert to a sockaddr_in6 before passing the address
285  * into the socket code.
286  *
287  * In the normal case udp_append() will return 0, indicating that you
288  * must unlock the inp. However if a tunneling protocol is in place we increment
289  * the inpcb refcnt and unlock the inp, on return from the tunneling protocol we
290  * then decrement the reference count. If the inp_rele returns 1, indicating the
291  * inp is gone, we return that to the caller to tell them *not* to unlock
292  * the inp. In the case of multi-cast this will cause the distribution
293  * to stop (though most tunneling protocols known currently do *not* use
294  * multicast).
295  */
296 static int
297 udp_append(struct inpcb *inp, struct ip *ip, struct mbuf *n, int off,
298     struct sockaddr_in *udp_in)
299 {
300         struct sockaddr *append_sa;
301         struct socket *so;
302         struct mbuf *tmpopts, *opts = NULL;
303 #ifdef INET6
304         struct sockaddr_in6 udp_in6;
305 #endif
306         struct udpcb *up;
307
308         INP_LOCK_ASSERT(inp);
309
310         /*
311          * Engage the tunneling protocol.
312          */
313         up = intoudpcb(inp);
314         if (up->u_tun_func != NULL) {
315                 in_pcbref(inp);
316                 INP_RUNLOCK(inp);
317                 (*up->u_tun_func)(n, off, inp, (struct sockaddr *)&udp_in[0],
318                     up->u_tun_ctx);
319                 INP_RLOCK(inp);
320                 return (in_pcbrele_rlocked(inp));
321         }
322
323         off += sizeof(struct udphdr);
324
325 #if defined(IPSEC) || defined(IPSEC_SUPPORT)
326         /* Check AH/ESP integrity. */
327         if (IPSEC_ENABLED(ipv4) &&
328             IPSEC_CHECK_POLICY(ipv4, n, inp) != 0) {
329                 m_freem(n);
330                 return (0);
331         }
332         if (up->u_flags & UF_ESPINUDP) {/* IPSec UDP encaps. */
333                 if (IPSEC_ENABLED(ipv4) &&
334                     UDPENCAP_INPUT(n, off, AF_INET) != 0)
335                         return (0);     /* Consumed. */
336         }
337 #endif /* IPSEC */
338 #ifdef MAC
339         if (mac_inpcb_check_deliver(inp, n) != 0) {
340                 m_freem(n);
341                 return (0);
342         }
343 #endif /* MAC */
344         if (inp->inp_flags & INP_CONTROLOPTS ||
345             inp->inp_socket->so_options & (SO_TIMESTAMP | SO_BINTIME)) {
346 #ifdef INET6
347                 if (inp->inp_vflag & INP_IPV6)
348                         (void)ip6_savecontrol_v4(inp, n, &opts, NULL);
349                 else
350 #endif /* INET6 */
351                         ip_savecontrol(inp, &opts, ip, n);
352         }
353         if ((inp->inp_vflag & INP_IPV4) && (inp->inp_flags2 & INP_ORIGDSTADDR)) {
354                 tmpopts = sbcreatecontrol((caddr_t)&udp_in[1],
355                         sizeof(struct sockaddr_in), IP_ORIGDSTADDR, IPPROTO_IP);
356                 if (tmpopts) {
357                         if (opts) {
358                                 tmpopts->m_next = opts;
359                                 opts = tmpopts;
360                         } else
361                                 opts = tmpopts;
362                 }
363         }
364 #ifdef INET6
365         if (inp->inp_vflag & INP_IPV6) {
366                 bzero(&udp_in6, sizeof(udp_in6));
367                 udp_in6.sin6_len = sizeof(udp_in6);
368                 udp_in6.sin6_family = AF_INET6;
369                 in6_sin_2_v4mapsin6(&udp_in[0], &udp_in6);
370                 append_sa = (struct sockaddr *)&udp_in6;
371         } else
372 #endif /* INET6 */
373                 append_sa = (struct sockaddr *)&udp_in[0];
374         m_adj(n, off);
375
376         so = inp->inp_socket;
377         SOCKBUF_LOCK(&so->so_rcv);
378         if (sbappendaddr_locked(&so->so_rcv, append_sa, n, opts) == 0) {
379                 SOCKBUF_UNLOCK(&so->so_rcv);
380                 m_freem(n);
381                 if (opts)
382                         m_freem(opts);
383                 UDPSTAT_INC(udps_fullsock);
384         } else
385                 sorwakeup_locked(so);
386         return (0);
387 }
388
389 int
390 udp_input(struct mbuf **mp, int *offp, int proto)
391 {
392         struct ip *ip;
393         struct udphdr *uh;
394         struct ifnet *ifp;
395         struct inpcb *inp;
396         uint16_t len, ip_len;
397         struct inpcbinfo *pcbinfo;
398         struct ip save_ip;
399         struct sockaddr_in udp_in[2];
400         struct mbuf *m;
401         struct m_tag *fwd_tag;
402         struct epoch_tracker et;
403         int cscov_partial, iphlen;
404
405         m = *mp;
406         iphlen = *offp;
407         ifp = m->m_pkthdr.rcvif;
408         *mp = NULL;
409         UDPSTAT_INC(udps_ipackets);
410
411         /*
412          * Strip IP options, if any; should skip this, make available to
413          * user, and use on returned packets, but we don't yet have a way to
414          * check the checksum with options still present.
415          */
416         if (iphlen > sizeof (struct ip)) {
417                 ip_stripoptions(m);
418                 iphlen = sizeof(struct ip);
419         }
420
421         /*
422          * Get IP and UDP header together in first mbuf.
423          */
424         ip = mtod(m, struct ip *);
425         if (m->m_len < iphlen + sizeof(struct udphdr)) {
426                 if ((m = m_pullup(m, iphlen + sizeof(struct udphdr))) == NULL) {
427                         UDPSTAT_INC(udps_hdrops);
428                         return (IPPROTO_DONE);
429                 }
430                 ip = mtod(m, struct ip *);
431         }
432         uh = (struct udphdr *)((caddr_t)ip + iphlen);
433         cscov_partial = (proto == IPPROTO_UDPLITE) ? 1 : 0;
434
435         /*
436          * Destination port of 0 is illegal, based on RFC768.
437          */
438         if (uh->uh_dport == 0)
439                 goto badunlocked;
440
441         /*
442          * Construct sockaddr format source address.  Stuff source address
443          * and datagram in user buffer.
444          */
445         bzero(&udp_in[0], sizeof(struct sockaddr_in) * 2);
446         udp_in[0].sin_len = sizeof(struct sockaddr_in);
447         udp_in[0].sin_family = AF_INET;
448         udp_in[0].sin_port = uh->uh_sport;
449         udp_in[0].sin_addr = ip->ip_src;
450         udp_in[1].sin_len = sizeof(struct sockaddr_in);
451         udp_in[1].sin_family = AF_INET;
452         udp_in[1].sin_port = uh->uh_dport;
453         udp_in[1].sin_addr = ip->ip_dst;
454
455         /*
456          * Make mbuf data length reflect UDP length.  If not enough data to
457          * reflect UDP length, drop.
458          */
459         len = ntohs((u_short)uh->uh_ulen);
460         ip_len = ntohs(ip->ip_len) - iphlen;
461         if (proto == IPPROTO_UDPLITE && (len == 0 || len == ip_len)) {
462                 /* Zero means checksum over the complete packet. */
463                 if (len == 0)
464                         len = ip_len;
465                 cscov_partial = 0;
466         }
467         if (ip_len != len) {
468                 if (len > ip_len || len < sizeof(struct udphdr)) {
469                         UDPSTAT_INC(udps_badlen);
470                         goto badunlocked;
471                 }
472                 if (proto == IPPROTO_UDP)
473                         m_adj(m, len - ip_len);
474         }
475
476         /*
477          * Save a copy of the IP header in case we want restore it for
478          * sending an ICMP error message in response.
479          */
480         if (!V_udp_blackhole)
481                 save_ip = *ip;
482         else
483                 memset(&save_ip, 0, sizeof(save_ip));
484
485         /*
486          * Checksum extended UDP header and data.
487          */
488         if (uh->uh_sum) {
489                 u_short uh_sum;
490
491                 if ((m->m_pkthdr.csum_flags & CSUM_DATA_VALID) &&
492                     !cscov_partial) {
493                         if (m->m_pkthdr.csum_flags & CSUM_PSEUDO_HDR)
494                                 uh_sum = m->m_pkthdr.csum_data;
495                         else
496                                 uh_sum = in_pseudo(ip->ip_src.s_addr,
497                                     ip->ip_dst.s_addr, htonl((u_short)len +
498                                     m->m_pkthdr.csum_data + proto));
499                         uh_sum ^= 0xffff;
500                 } else {
501                         char b[9];
502
503                         bcopy(((struct ipovly *)ip)->ih_x1, b, 9);
504                         bzero(((struct ipovly *)ip)->ih_x1, 9);
505                         ((struct ipovly *)ip)->ih_len = (proto == IPPROTO_UDP) ?
506                             uh->uh_ulen : htons(ip_len);
507                         uh_sum = in_cksum(m, len + sizeof (struct ip));
508                         bcopy(b, ((struct ipovly *)ip)->ih_x1, 9);
509                 }
510                 if (uh_sum) {
511                         UDPSTAT_INC(udps_badsum);
512                         m_freem(m);
513                         return (IPPROTO_DONE);
514                 }
515         } else {
516                 if (proto == IPPROTO_UDP) {
517                         UDPSTAT_INC(udps_nosum);
518                 } else {
519                         /* UDPLite requires a checksum */
520                         /* XXX: What is the right UDPLite MIB counter here? */
521                         m_freem(m);
522                         return (IPPROTO_DONE);
523                 }
524         }
525
526         pcbinfo = udp_get_inpcbinfo(proto);
527         if (IN_MULTICAST(ntohl(ip->ip_dst.s_addr)) ||
528             in_broadcast(ip->ip_dst, ifp)) {
529                 struct inpcb *last;
530                 struct inpcbhead *pcblist;
531                 struct ip_moptions *imo;
532
533                 INP_INFO_RLOCK_ET(pcbinfo, et);
534                 pcblist = udp_get_pcblist(proto);
535                 last = NULL;
536                 CK_LIST_FOREACH(inp, pcblist, inp_list) {
537                         if (inp->inp_lport != uh->uh_dport)
538                                 continue;
539 #ifdef INET6
540                         if ((inp->inp_vflag & INP_IPV4) == 0)
541                                 continue;
542 #endif
543                         if (inp->inp_laddr.s_addr != INADDR_ANY &&
544                             inp->inp_laddr.s_addr != ip->ip_dst.s_addr)
545                                 continue;
546                         if (inp->inp_faddr.s_addr != INADDR_ANY &&
547                             inp->inp_faddr.s_addr != ip->ip_src.s_addr)
548                                 continue;
549                         if (inp->inp_fport != 0 &&
550                             inp->inp_fport != uh->uh_sport)
551                                 continue;
552
553                         INP_RLOCK(inp);
554
555                         /*
556                          * XXXRW: Because we weren't holding either the inpcb
557                          * or the hash lock when we checked for a match
558                          * before, we should probably recheck now that the
559                          * inpcb lock is held.
560                          */
561
562                         /*
563                          * Handle socket delivery policy for any-source
564                          * and source-specific multicast. [RFC3678]
565                          */
566                         imo = inp->inp_moptions;
567                         if (IN_MULTICAST(ntohl(ip->ip_dst.s_addr))) {
568                                 struct sockaddr_in       group;
569                                 int                      blocked;
570                                 if (imo == NULL) {
571                                         INP_RUNLOCK(inp);
572                                         continue;
573                                 }
574                                 bzero(&group, sizeof(struct sockaddr_in));
575                                 group.sin_len = sizeof(struct sockaddr_in);
576                                 group.sin_family = AF_INET;
577                                 group.sin_addr = ip->ip_dst;
578
579                                 blocked = imo_multi_filter(imo, ifp,
580                                         (struct sockaddr *)&group,
581                                         (struct sockaddr *)&udp_in[0]);
582                                 if (blocked != MCAST_PASS) {
583                                         if (blocked == MCAST_NOTGMEMBER)
584                                                 IPSTAT_INC(ips_notmember);
585                                         if (blocked == MCAST_NOTSMEMBER ||
586                                             blocked == MCAST_MUTED)
587                                                 UDPSTAT_INC(udps_filtermcast);
588                                         INP_RUNLOCK(inp);
589                                         continue;
590                                 }
591                         }
592                         if (last != NULL) {
593                                 struct mbuf *n;
594
595                                 if ((n = m_copym(m, 0, M_COPYALL, M_NOWAIT)) !=
596                                     NULL) {
597                                         if (proto == IPPROTO_UDPLITE)
598                                                 UDPLITE_PROBE(receive, NULL, last, ip,
599                                                     last, uh);
600                                         else
601                                                 UDP_PROBE(receive, NULL, last, ip, last,
602                                                     uh);
603                                         if (udp_append(last, ip, n, iphlen,
604                                                 udp_in)) {
605                                                 goto inp_lost;
606                                         }
607                                 }
608                                 INP_RUNLOCK(last);
609                         }
610                         last = inp;
611                         /*
612                          * Don't look for additional matches if this one does
613                          * not have either the SO_REUSEPORT or SO_REUSEADDR
614                          * socket options set.  This heuristic avoids
615                          * searching through all pcbs in the common case of a
616                          * non-shared port.  It assumes that an application
617                          * will never clear these options after setting them.
618                          */
619                         if ((last->inp_socket->so_options &
620                             (SO_REUSEPORT|SO_REUSEPORT_LB|SO_REUSEADDR)) == 0)
621                                 break;
622                 }
623
624                 if (last == NULL) {
625                         /*
626                          * No matching pcb found; discard datagram.  (No need
627                          * to send an ICMP Port Unreachable for a broadcast
628                          * or multicast datgram.)
629                          */
630                         UDPSTAT_INC(udps_noportbcast);
631                         if (inp)
632                                 INP_RUNLOCK(inp);
633                         INP_INFO_RUNLOCK_ET(pcbinfo, et);
634                         goto badunlocked;
635                 }
636                 if (proto == IPPROTO_UDPLITE)
637                         UDPLITE_PROBE(receive, NULL, last, ip, last, uh);
638                 else
639                         UDP_PROBE(receive, NULL, last, ip, last, uh);
640                 if (udp_append(last, ip, m, iphlen, udp_in) == 0) 
641                         INP_RUNLOCK(last);
642         inp_lost:
643                 INP_INFO_RUNLOCK_ET(pcbinfo, et);
644                 return (IPPROTO_DONE);
645         }
646
647         /*
648          * Locate pcb for datagram.
649          */
650
651         /*
652          * Grab info from PACKET_TAG_IPFORWARD tag prepended to the chain.
653          */
654         if ((m->m_flags & M_IP_NEXTHOP) &&
655             (fwd_tag = m_tag_find(m, PACKET_TAG_IPFORWARD, NULL)) != NULL) {
656                 struct sockaddr_in *next_hop;
657
658                 next_hop = (struct sockaddr_in *)(fwd_tag + 1);
659
660                 /*
661                  * Transparently forwarded. Pretend to be the destination.
662                  * Already got one like this?
663                  */
664                 inp = in_pcblookup_mbuf(pcbinfo, ip->ip_src, uh->uh_sport,
665                     ip->ip_dst, uh->uh_dport, INPLOOKUP_RLOCKPCB, ifp, m);
666                 if (!inp) {
667                         /*
668                          * It's new.  Try to find the ambushing socket.
669                          * Because we've rewritten the destination address,
670                          * any hardware-generated hash is ignored.
671                          */
672                         inp = in_pcblookup(pcbinfo, ip->ip_src,
673                             uh->uh_sport, next_hop->sin_addr,
674                             next_hop->sin_port ? htons(next_hop->sin_port) :
675                             uh->uh_dport, INPLOOKUP_WILDCARD |
676                             INPLOOKUP_RLOCKPCB, ifp);
677                 }
678                 /* Remove the tag from the packet. We don't need it anymore. */
679                 m_tag_delete(m, fwd_tag);
680                 m->m_flags &= ~M_IP_NEXTHOP;
681         } else
682                 inp = in_pcblookup_mbuf(pcbinfo, ip->ip_src, uh->uh_sport,
683                     ip->ip_dst, uh->uh_dport, INPLOOKUP_WILDCARD |
684                     INPLOOKUP_RLOCKPCB, ifp, m);
685         if (inp == NULL) {
686                 if (udp_log_in_vain) {
687                         char src[INET_ADDRSTRLEN];
688                         char dst[INET_ADDRSTRLEN];
689
690                         log(LOG_INFO,
691                             "Connection attempt to UDP %s:%d from %s:%d\n",
692                             inet_ntoa_r(ip->ip_dst, dst), ntohs(uh->uh_dport),
693                             inet_ntoa_r(ip->ip_src, src), ntohs(uh->uh_sport));
694                 }
695                 if (proto == IPPROTO_UDPLITE)
696                         UDPLITE_PROBE(receive, NULL, NULL, ip, NULL, uh);
697                 else
698                         UDP_PROBE(receive, NULL, NULL, ip, NULL, uh);
699                 UDPSTAT_INC(udps_noport);
700                 if (m->m_flags & (M_BCAST | M_MCAST)) {
701                         UDPSTAT_INC(udps_noportbcast);
702                         goto badunlocked;
703                 }
704                 if (V_udp_blackhole)
705                         goto badunlocked;
706                 if (badport_bandlim(BANDLIM_ICMP_UNREACH) < 0)
707                         goto badunlocked;
708                 *ip = save_ip;
709                 icmp_error(m, ICMP_UNREACH, ICMP_UNREACH_PORT, 0, 0);
710                 return (IPPROTO_DONE);
711         }
712
713         /*
714          * Check the minimum TTL for socket.
715          */
716         INP_RLOCK_ASSERT(inp);
717         if (inp->inp_ip_minttl && inp->inp_ip_minttl > ip->ip_ttl) {
718                 if (proto == IPPROTO_UDPLITE)
719                         UDPLITE_PROBE(receive, NULL, inp, ip, inp, uh);
720                 else
721                         UDP_PROBE(receive, NULL, inp, ip, inp, uh);
722                 INP_RUNLOCK(inp);
723                 m_freem(m);
724                 return (IPPROTO_DONE);
725         }
726         if (cscov_partial) {
727                 struct udpcb *up;
728
729                 up = intoudpcb(inp);
730                 if (up->u_rxcslen == 0 || up->u_rxcslen > len) {
731                         INP_RUNLOCK(inp);
732                         m_freem(m);
733                         return (IPPROTO_DONE);
734                 }
735         }
736
737         if (proto == IPPROTO_UDPLITE)
738                 UDPLITE_PROBE(receive, NULL, inp, ip, inp, uh);
739         else
740                 UDP_PROBE(receive, NULL, inp, ip, inp, uh);
741         if (udp_append(inp, ip, m, iphlen, udp_in) == 0) 
742                 INP_RUNLOCK(inp);
743         return (IPPROTO_DONE);
744
745 badunlocked:
746         m_freem(m);
747         return (IPPROTO_DONE);
748 }
749 #endif /* INET */
750
751 /*
752  * Notify a udp user of an asynchronous error; just wake up so that they can
753  * collect error status.
754  */
755 struct inpcb *
756 udp_notify(struct inpcb *inp, int errno)
757 {
758
759         INP_WLOCK_ASSERT(inp);
760         if ((errno == EHOSTUNREACH || errno == ENETUNREACH ||
761              errno == EHOSTDOWN) && inp->inp_route.ro_rt) {
762                 RTFREE(inp->inp_route.ro_rt);
763                 inp->inp_route.ro_rt = (struct rtentry *)NULL;
764         }
765
766         inp->inp_socket->so_error = errno;
767         sorwakeup(inp->inp_socket);
768         sowwakeup(inp->inp_socket);
769         return (inp);
770 }
771
772 #ifdef INET
773 static void
774 udp_common_ctlinput(int cmd, struct sockaddr *sa, void *vip,
775     struct inpcbinfo *pcbinfo)
776 {
777         struct ip *ip = vip;
778         struct udphdr *uh;
779         struct in_addr faddr;
780         struct inpcb *inp;
781
782         faddr = ((struct sockaddr_in *)sa)->sin_addr;
783         if (sa->sa_family != AF_INET || faddr.s_addr == INADDR_ANY)
784                 return;
785
786         if (PRC_IS_REDIRECT(cmd)) {
787                 /* signal EHOSTDOWN, as it flushes the cached route */
788                 in_pcbnotifyall(&V_udbinfo, faddr, EHOSTDOWN, udp_notify);
789                 return;
790         }
791
792         /*
793          * Hostdead is ugly because it goes linearly through all PCBs.
794          *
795          * XXX: We never get this from ICMP, otherwise it makes an excellent
796          * DoS attack on machines with many connections.
797          */
798         if (cmd == PRC_HOSTDEAD)
799                 ip = NULL;
800         else if ((unsigned)cmd >= PRC_NCMDS || inetctlerrmap[cmd] == 0)
801                 return;
802         if (ip != NULL) {
803                 uh = (struct udphdr *)((caddr_t)ip + (ip->ip_hl << 2));
804                 inp = in_pcblookup(pcbinfo, faddr, uh->uh_dport,
805                     ip->ip_src, uh->uh_sport, INPLOOKUP_WLOCKPCB, NULL);
806                 if (inp != NULL) {
807                         INP_WLOCK_ASSERT(inp);
808                         if (inp->inp_socket != NULL) {
809                                 udp_notify(inp, inetctlerrmap[cmd]);
810                         }
811                         INP_WUNLOCK(inp);
812                 } else {
813                         inp = in_pcblookup(pcbinfo, faddr, uh->uh_dport,
814                                            ip->ip_src, uh->uh_sport,
815                                            INPLOOKUP_WILDCARD | INPLOOKUP_RLOCKPCB, NULL);
816                         if (inp != NULL) {
817                                 struct udpcb *up;
818                                 void *ctx;
819                                 udp_tun_icmp_t func;
820
821                                 up = intoudpcb(inp);
822                                 ctx = up->u_tun_ctx;
823                                 func = up->u_icmp_func;
824                                 INP_RUNLOCK(inp);
825                                 if (func != NULL)
826                                         (*func)(cmd, sa, vip, ctx);
827                         }
828                 }
829         } else
830                 in_pcbnotifyall(pcbinfo, faddr, inetctlerrmap[cmd],
831                     udp_notify);
832 }
833 void
834 udp_ctlinput(int cmd, struct sockaddr *sa, void *vip)
835 {
836
837         return (udp_common_ctlinput(cmd, sa, vip, &V_udbinfo));
838 }
839
840 void
841 udplite_ctlinput(int cmd, struct sockaddr *sa, void *vip)
842 {
843
844         return (udp_common_ctlinput(cmd, sa, vip, &V_ulitecbinfo));
845 }
846 #endif /* INET */
847
848 static int
849 udp_pcblist(SYSCTL_HANDLER_ARGS)
850 {
851         int error, i, n;
852         struct inpcb *inp, **inp_list;
853         inp_gen_t gencnt;
854         struct xinpgen xig;
855         struct epoch_tracker et;
856
857         /*
858          * The process of preparing the PCB list is too time-consuming and
859          * resource-intensive to repeat twice on every request.
860          */
861         if (req->oldptr == 0) {
862                 n = V_udbinfo.ipi_count;
863                 n += imax(n / 8, 10);
864                 req->oldidx = 2 * (sizeof xig) + n * sizeof(struct xinpcb);
865                 return (0);
866         }
867
868         if (req->newptr != 0)
869                 return (EPERM);
870
871         /*
872          * OK, now we're committed to doing something.
873          */
874         INP_INFO_RLOCK_ET(&V_udbinfo, et);
875         gencnt = V_udbinfo.ipi_gencnt;
876         n = V_udbinfo.ipi_count;
877         INP_INFO_RUNLOCK_ET(&V_udbinfo, et);
878
879         error = sysctl_wire_old_buffer(req, 2 * (sizeof xig)
880                 + n * sizeof(struct xinpcb));
881         if (error != 0)
882                 return (error);
883
884         xig.xig_len = sizeof xig;
885         xig.xig_count = n;
886         xig.xig_gen = gencnt;
887         xig.xig_sogen = so_gencnt;
888         error = SYSCTL_OUT(req, &xig, sizeof xig);
889         if (error)
890                 return (error);
891
892         inp_list = malloc(n * sizeof *inp_list, M_TEMP, M_WAITOK);
893         if (inp_list == NULL)
894                 return (ENOMEM);
895
896         INP_INFO_RLOCK_ET(&V_udbinfo, et);
897         for (inp = CK_LIST_FIRST(V_udbinfo.ipi_listhead), i = 0; inp && i < n;
898              inp = CK_LIST_NEXT(inp, inp_list)) {
899                 INP_WLOCK(inp);
900                 if (inp->inp_gencnt <= gencnt &&
901                     cr_canseeinpcb(req->td->td_ucred, inp) == 0) {
902                         in_pcbref(inp);
903                         inp_list[i++] = inp;
904                 }
905                 INP_WUNLOCK(inp);
906         }
907         INP_INFO_RUNLOCK_ET(&V_udbinfo, et);
908         n = i;
909
910         error = 0;
911         for (i = 0; i < n; i++) {
912                 inp = inp_list[i];
913                 INP_RLOCK(inp);
914                 if (inp->inp_gencnt <= gencnt) {
915                         struct xinpcb xi;
916
917                         in_pcbtoxinpcb(inp, &xi);
918                         INP_RUNLOCK(inp);
919                         error = SYSCTL_OUT(req, &xi, sizeof xi);
920                 } else
921                         INP_RUNLOCK(inp);
922         }
923         INP_INFO_WLOCK(&V_udbinfo);
924         for (i = 0; i < n; i++) {
925                 inp = inp_list[i];
926                 INP_RLOCK(inp);
927                 if (!in_pcbrele_rlocked(inp))
928                         INP_RUNLOCK(inp);
929         }
930         INP_INFO_WUNLOCK(&V_udbinfo);
931
932         if (!error) {
933                 /*
934                  * Give the user an updated idea of our state.  If the
935                  * generation differs from what we told her before, she knows
936                  * that something happened while we were processing this
937                  * request, and it might be necessary to retry.
938                  */
939                 INP_INFO_RLOCK_ET(&V_udbinfo, et);
940                 xig.xig_gen = V_udbinfo.ipi_gencnt;
941                 xig.xig_sogen = so_gencnt;
942                 xig.xig_count = V_udbinfo.ipi_count;
943                 INP_INFO_RUNLOCK_ET(&V_udbinfo, et);
944                 error = SYSCTL_OUT(req, &xig, sizeof xig);
945         }
946         free(inp_list, M_TEMP);
947         return (error);
948 }
949
950 SYSCTL_PROC(_net_inet_udp, UDPCTL_PCBLIST, pcblist,
951     CTLTYPE_OPAQUE | CTLFLAG_RD, NULL, 0,
952     udp_pcblist, "S,xinpcb", "List of active UDP sockets");
953
954 #ifdef INET
955 static int
956 udp_getcred(SYSCTL_HANDLER_ARGS)
957 {
958         struct xucred xuc;
959         struct sockaddr_in addrs[2];
960         struct inpcb *inp;
961         int error;
962
963         error = priv_check(req->td, PRIV_NETINET_GETCRED);
964         if (error)
965                 return (error);
966         error = SYSCTL_IN(req, addrs, sizeof(addrs));
967         if (error)
968                 return (error);
969         inp = in_pcblookup(&V_udbinfo, addrs[1].sin_addr, addrs[1].sin_port,
970             addrs[0].sin_addr, addrs[0].sin_port,
971             INPLOOKUP_WILDCARD | INPLOOKUP_RLOCKPCB, NULL);
972         if (inp != NULL) {
973                 INP_RLOCK_ASSERT(inp);
974                 if (inp->inp_socket == NULL)
975                         error = ENOENT;
976                 if (error == 0)
977                         error = cr_canseeinpcb(req->td->td_ucred, inp);
978                 if (error == 0)
979                         cru2x(inp->inp_cred, &xuc);
980                 INP_RUNLOCK(inp);
981         } else
982                 error = ENOENT;
983         if (error == 0)
984                 error = SYSCTL_OUT(req, &xuc, sizeof(struct xucred));
985         return (error);
986 }
987
988 SYSCTL_PROC(_net_inet_udp, OID_AUTO, getcred,
989     CTLTYPE_OPAQUE|CTLFLAG_RW|CTLFLAG_PRISON, 0, 0,
990     udp_getcred, "S,xucred", "Get the xucred of a UDP connection");
991 #endif /* INET */
992
993 int
994 udp_ctloutput(struct socket *so, struct sockopt *sopt)
995 {
996         struct inpcb *inp;
997         struct udpcb *up;
998         int isudplite, error, optval;
999
1000         error = 0;
1001         isudplite = (so->so_proto->pr_protocol == IPPROTO_UDPLITE) ? 1 : 0;
1002         inp = sotoinpcb(so);
1003         KASSERT(inp != NULL, ("%s: inp == NULL", __func__));
1004         INP_WLOCK(inp);
1005         if (sopt->sopt_level != so->so_proto->pr_protocol) {
1006 #ifdef INET6
1007                 if (INP_CHECK_SOCKAF(so, AF_INET6)) {
1008                         INP_WUNLOCK(inp);
1009                         error = ip6_ctloutput(so, sopt);
1010                 }
1011 #endif
1012 #if defined(INET) && defined(INET6)
1013                 else
1014 #endif
1015 #ifdef INET
1016                 {
1017                         INP_WUNLOCK(inp);
1018                         error = ip_ctloutput(so, sopt);
1019                 }
1020 #endif
1021                 return (error);
1022         }
1023
1024         switch (sopt->sopt_dir) {
1025         case SOPT_SET:
1026                 switch (sopt->sopt_name) {
1027 #if defined(IPSEC) || defined(IPSEC_SUPPORT)
1028 #ifdef INET
1029                 case UDP_ENCAP:
1030                         if (!IPSEC_ENABLED(ipv4)) {
1031                                 INP_WUNLOCK(inp);
1032                                 return (ENOPROTOOPT);
1033                         }
1034                         error = UDPENCAP_PCBCTL(inp, sopt);
1035                         break;
1036 #endif /* INET */
1037 #endif /* IPSEC */
1038                 case UDPLITE_SEND_CSCOV:
1039                 case UDPLITE_RECV_CSCOV:
1040                         if (!isudplite) {
1041                                 INP_WUNLOCK(inp);
1042                                 error = ENOPROTOOPT;
1043                                 break;
1044                         }
1045                         INP_WUNLOCK(inp);
1046                         error = sooptcopyin(sopt, &optval, sizeof(optval),
1047                             sizeof(optval));
1048                         if (error != 0)
1049                                 break;
1050                         inp = sotoinpcb(so);
1051                         KASSERT(inp != NULL, ("%s: inp == NULL", __func__));
1052                         INP_WLOCK(inp);
1053                         up = intoudpcb(inp);
1054                         KASSERT(up != NULL, ("%s: up == NULL", __func__));
1055                         if ((optval != 0 && optval < 8) || (optval > 65535)) {
1056                                 INP_WUNLOCK(inp);
1057                                 error = EINVAL;
1058                                 break;
1059                         }
1060                         if (sopt->sopt_name == UDPLITE_SEND_CSCOV)
1061                                 up->u_txcslen = optval;
1062                         else
1063                                 up->u_rxcslen = optval;
1064                         INP_WUNLOCK(inp);
1065                         break;
1066                 default:
1067                         INP_WUNLOCK(inp);
1068                         error = ENOPROTOOPT;
1069                         break;
1070                 }
1071                 break;
1072         case SOPT_GET:
1073                 switch (sopt->sopt_name) {
1074 #if defined(IPSEC) || defined(IPSEC_SUPPORT)
1075 #ifdef INET
1076                 case UDP_ENCAP:
1077                         if (!IPSEC_ENABLED(ipv4)) {
1078                                 INP_WUNLOCK(inp);
1079                                 return (ENOPROTOOPT);
1080                         }
1081                         error = UDPENCAP_PCBCTL(inp, sopt);
1082                         break;
1083 #endif /* INET */
1084 #endif /* IPSEC */
1085                 case UDPLITE_SEND_CSCOV:
1086                 case UDPLITE_RECV_CSCOV:
1087                         if (!isudplite) {
1088                                 INP_WUNLOCK(inp);
1089                                 error = ENOPROTOOPT;
1090                                 break;
1091                         }
1092                         up = intoudpcb(inp);
1093                         KASSERT(up != NULL, ("%s: up == NULL", __func__));
1094                         if (sopt->sopt_name == UDPLITE_SEND_CSCOV)
1095                                 optval = up->u_txcslen;
1096                         else
1097                                 optval = up->u_rxcslen;
1098                         INP_WUNLOCK(inp);
1099                         error = sooptcopyout(sopt, &optval, sizeof(optval));
1100                         break;
1101                 default:
1102                         INP_WUNLOCK(inp);
1103                         error = ENOPROTOOPT;
1104                         break;
1105                 }
1106                 break;
1107         }       
1108         return (error);
1109 }
1110
1111 #ifdef INET
1112 #define UH_WLOCKED      2
1113 #define UH_RLOCKED      1
1114 #define UH_UNLOCKED     0
1115 static int
1116 udp_output(struct inpcb *inp, struct mbuf *m, struct sockaddr *addr,
1117     struct mbuf *control, struct thread *td)
1118 {
1119         struct udpiphdr *ui;
1120         int len = m->m_pkthdr.len;
1121         struct in_addr faddr, laddr;
1122         struct cmsghdr *cm;
1123         struct inpcbinfo *pcbinfo;
1124         struct sockaddr_in *sin, src;
1125         struct epoch_tracker et;
1126         int cscov_partial = 0;
1127         int error = 0;
1128         int ipflags;
1129         u_short fport, lport;
1130         int unlock_udbinfo, unlock_inp;
1131         u_char tos;
1132         uint8_t pr;
1133         uint16_t cscov = 0;
1134         uint32_t flowid = 0;
1135         uint8_t flowtype = M_HASHTYPE_NONE;
1136
1137         /*
1138          * udp_output() may need to temporarily bind or connect the current
1139          * inpcb.  As such, we don't know up front whether we will need the
1140          * pcbinfo lock or not.  Do any work to decide what is needed up
1141          * front before acquiring any locks.
1142          */
1143         if (len + sizeof(struct udpiphdr) > IP_MAXPACKET) {
1144                 if (control)
1145                         m_freem(control);
1146                 m_freem(m);
1147                 return (EMSGSIZE);
1148         }
1149
1150         src.sin_family = 0;
1151         sin = (struct sockaddr_in *)addr;
1152         if (sin == NULL ||
1153             (inp->inp_laddr.s_addr == INADDR_ANY && inp->inp_lport == 0)) {
1154                 INP_WLOCK(inp);
1155                 unlock_inp = UH_WLOCKED;
1156         } else {
1157                 INP_RLOCK(inp);
1158                 unlock_inp = UH_RLOCKED;
1159         }
1160         tos = inp->inp_ip_tos;
1161         if (control != NULL) {
1162                 /*
1163                  * XXX: Currently, we assume all the optional information is
1164                  * stored in a single mbuf.
1165                  */
1166                 if (control->m_next) {
1167                         if (unlock_inp == UH_WLOCKED)
1168                                 INP_WUNLOCK(inp);
1169                         else
1170                                 INP_RUNLOCK(inp);
1171                         m_freem(control);
1172                         m_freem(m);
1173                         return (EINVAL);
1174                 }
1175                 for (; control->m_len > 0;
1176                     control->m_data += CMSG_ALIGN(cm->cmsg_len),
1177                     control->m_len -= CMSG_ALIGN(cm->cmsg_len)) {
1178                         cm = mtod(control, struct cmsghdr *);
1179                         if (control->m_len < sizeof(*cm) || cm->cmsg_len == 0
1180                             || cm->cmsg_len > control->m_len) {
1181                                 error = EINVAL;
1182                                 break;
1183                         }
1184                         if (cm->cmsg_level != IPPROTO_IP)
1185                                 continue;
1186
1187                         switch (cm->cmsg_type) {
1188                         case IP_SENDSRCADDR:
1189                                 if (cm->cmsg_len !=
1190                                     CMSG_LEN(sizeof(struct in_addr))) {
1191                                         error = EINVAL;
1192                                         break;
1193                                 }
1194                                 bzero(&src, sizeof(src));
1195                                 src.sin_family = AF_INET;
1196                                 src.sin_len = sizeof(src);
1197                                 src.sin_port = inp->inp_lport;
1198                                 src.sin_addr =
1199                                     *(struct in_addr *)CMSG_DATA(cm);
1200                                 break;
1201
1202                         case IP_TOS:
1203                                 if (cm->cmsg_len != CMSG_LEN(sizeof(u_char))) {
1204                                         error = EINVAL;
1205                                         break;
1206                                 }
1207                                 tos = *(u_char *)CMSG_DATA(cm);
1208                                 break;
1209
1210                         case IP_FLOWID:
1211                                 if (cm->cmsg_len != CMSG_LEN(sizeof(uint32_t))) {
1212                                         error = EINVAL;
1213                                         break;
1214                                 }
1215                                 flowid = *(uint32_t *) CMSG_DATA(cm);
1216                                 break;
1217
1218                         case IP_FLOWTYPE:
1219                                 if (cm->cmsg_len != CMSG_LEN(sizeof(uint32_t))) {
1220                                         error = EINVAL;
1221                                         break;
1222                                 }
1223                                 flowtype = *(uint32_t *) CMSG_DATA(cm);
1224                                 break;
1225
1226 #ifdef  RSS
1227                         case IP_RSSBUCKETID:
1228                                 if (cm->cmsg_len != CMSG_LEN(sizeof(uint32_t))) {
1229                                         error = EINVAL;
1230                                         break;
1231                                 }
1232                                 /* This is just a placeholder for now */
1233                                 break;
1234 #endif  /* RSS */
1235                         default:
1236                                 error = ENOPROTOOPT;
1237                                 break;
1238                         }
1239                         if (error)
1240                                 break;
1241                 }
1242                 m_freem(control);
1243         }
1244         if (error) {
1245                 if (unlock_inp == UH_WLOCKED)
1246                         INP_WUNLOCK(inp);
1247                 else
1248                         INP_RUNLOCK(inp);
1249                 m_freem(m);
1250                 return (error);
1251         }
1252
1253         /*
1254          * Depending on whether or not the application has bound or connected
1255          * the socket, we may have to do varying levels of work.  The optimal
1256          * case is for a connected UDP socket, as a global lock isn't
1257          * required at all.
1258          *
1259          * In order to decide which we need, we require stability of the
1260          * inpcb binding, which we ensure by acquiring a read lock on the
1261          * inpcb.  This doesn't strictly follow the lock order, so we play
1262          * the trylock and retry game; note that we may end up with more
1263          * conservative locks than required the second time around, so later
1264          * assertions have to accept that.  Further analysis of the number of
1265          * misses under contention is required.
1266          *
1267          * XXXRW: Check that hash locking update here is correct.
1268          */
1269         pr = inp->inp_socket->so_proto->pr_protocol;
1270         pcbinfo = udp_get_inpcbinfo(pr);
1271         sin = (struct sockaddr_in *)addr;
1272         if (sin != NULL &&
1273             (inp->inp_laddr.s_addr == INADDR_ANY && inp->inp_lport == 0)) {
1274                 INP_HASH_WLOCK(pcbinfo);
1275                 unlock_udbinfo = UH_WLOCKED;
1276         } else if ((sin != NULL && (
1277             (sin->sin_addr.s_addr == INADDR_ANY) ||
1278             (sin->sin_addr.s_addr == INADDR_BROADCAST) ||
1279             (inp->inp_laddr.s_addr == INADDR_ANY) ||
1280             (inp->inp_lport == 0))) ||
1281             (src.sin_family == AF_INET)) {
1282                 INP_HASH_RLOCK_ET(pcbinfo, et);
1283                 unlock_udbinfo = UH_RLOCKED;
1284         } else
1285                 unlock_udbinfo = UH_UNLOCKED;
1286
1287         /*
1288          * If the IP_SENDSRCADDR control message was specified, override the
1289          * source address for this datagram.  Its use is invalidated if the
1290          * address thus specified is incomplete or clobbers other inpcbs.
1291          */
1292         laddr = inp->inp_laddr;
1293         lport = inp->inp_lport;
1294         if (src.sin_family == AF_INET) {
1295                 INP_HASH_LOCK_ASSERT(pcbinfo);
1296                 if ((lport == 0) ||
1297                     (laddr.s_addr == INADDR_ANY &&
1298                      src.sin_addr.s_addr == INADDR_ANY)) {
1299                         error = EINVAL;
1300                         goto release;
1301                 }
1302                 error = in_pcbbind_setup(inp, (struct sockaddr *)&src,
1303                     &laddr.s_addr, &lport, td->td_ucred);
1304                 if (error)
1305                         goto release;
1306         }
1307
1308         /*
1309          * If a UDP socket has been connected, then a local address/port will
1310          * have been selected and bound.
1311          *
1312          * If a UDP socket has not been connected to, then an explicit
1313          * destination address must be used, in which case a local
1314          * address/port may not have been selected and bound.
1315          */
1316         if (sin != NULL) {
1317                 INP_LOCK_ASSERT(inp);
1318                 if (inp->inp_faddr.s_addr != INADDR_ANY) {
1319                         error = EISCONN;
1320                         goto release;
1321                 }
1322
1323                 /*
1324                  * Jail may rewrite the destination address, so let it do
1325                  * that before we use it.
1326                  */
1327                 error = prison_remote_ip4(td->td_ucred, &sin->sin_addr);
1328                 if (error)
1329                         goto release;
1330
1331                 /*
1332                  * If a local address or port hasn't yet been selected, or if
1333                  * the destination address needs to be rewritten due to using
1334                  * a special INADDR_ constant, invoke in_pcbconnect_setup()
1335                  * to do the heavy lifting.  Once a port is selected, we
1336                  * commit the binding back to the socket; we also commit the
1337                  * binding of the address if in jail.
1338                  *
1339                  * If we already have a valid binding and we're not
1340                  * requesting a destination address rewrite, use a fast path.
1341                  */
1342                 if (inp->inp_laddr.s_addr == INADDR_ANY ||
1343                     inp->inp_lport == 0 ||
1344                     sin->sin_addr.s_addr == INADDR_ANY ||
1345                     sin->sin_addr.s_addr == INADDR_BROADCAST) {
1346                         INP_HASH_LOCK_ASSERT(pcbinfo);
1347                         error = in_pcbconnect_setup(inp, addr, &laddr.s_addr,
1348                             &lport, &faddr.s_addr, &fport, NULL,
1349                             td->td_ucred);
1350                         if (error)
1351                                 goto release;
1352
1353                         /*
1354                          * XXXRW: Why not commit the port if the address is
1355                          * !INADDR_ANY?
1356                          */
1357                         /* Commit the local port if newly assigned. */
1358                         if (inp->inp_laddr.s_addr == INADDR_ANY &&
1359                             inp->inp_lport == 0) {
1360                                 INP_WLOCK_ASSERT(inp);
1361                                 INP_HASH_WLOCK_ASSERT(pcbinfo);
1362                                 /*
1363                                  * Remember addr if jailed, to prevent
1364                                  * rebinding.
1365                                  */
1366                                 if (prison_flag(td->td_ucred, PR_IP4))
1367                                         inp->inp_laddr = laddr;
1368                                 inp->inp_lport = lport;
1369                                 if (in_pcbinshash(inp) != 0) {
1370                                         inp->inp_lport = 0;
1371                                         error = EAGAIN;
1372                                         goto release;
1373                                 }
1374                                 inp->inp_flags |= INP_ANONPORT;
1375                         }
1376                 } else {
1377                         faddr = sin->sin_addr;
1378                         fport = sin->sin_port;
1379                 }
1380         } else {
1381                 INP_LOCK_ASSERT(inp);
1382                 faddr = inp->inp_faddr;
1383                 fport = inp->inp_fport;
1384                 if (faddr.s_addr == INADDR_ANY) {
1385                         error = ENOTCONN;
1386                         goto release;
1387                 }
1388         }
1389
1390         /*
1391          * Calculate data length and get a mbuf for UDP, IP, and possible
1392          * link-layer headers.  Immediate slide the data pointer back forward
1393          * since we won't use that space at this layer.
1394          */
1395         M_PREPEND(m, sizeof(struct udpiphdr) + max_linkhdr, M_NOWAIT);
1396         if (m == NULL) {
1397                 error = ENOBUFS;
1398                 goto release;
1399         }
1400         m->m_data += max_linkhdr;
1401         m->m_len -= max_linkhdr;
1402         m->m_pkthdr.len -= max_linkhdr;
1403
1404         /*
1405          * Fill in mbuf with extended UDP header and addresses and length put
1406          * into network format.
1407          */
1408         ui = mtod(m, struct udpiphdr *);
1409         bzero(ui->ui_x1, sizeof(ui->ui_x1));    /* XXX still needed? */
1410         ui->ui_v = IPVERSION << 4;
1411         ui->ui_pr = pr;
1412         ui->ui_src = laddr;
1413         ui->ui_dst = faddr;
1414         ui->ui_sport = lport;
1415         ui->ui_dport = fport;
1416         ui->ui_ulen = htons((u_short)len + sizeof(struct udphdr));
1417         if (pr == IPPROTO_UDPLITE) {
1418                 struct udpcb *up;
1419                 uint16_t plen;
1420
1421                 up = intoudpcb(inp);
1422                 cscov = up->u_txcslen;
1423                 plen = (u_short)len + sizeof(struct udphdr);
1424                 if (cscov >= plen)
1425                         cscov = 0;
1426                 ui->ui_len = htons(plen);
1427                 ui->ui_ulen = htons(cscov);
1428                 /*
1429                  * For UDP-Lite, checksum coverage length of zero means
1430                  * the entire UDPLite packet is covered by the checksum.
1431                  */
1432                 cscov_partial = (cscov == 0) ? 0 : 1;
1433         }
1434
1435         /*
1436          * Set the Don't Fragment bit in the IP header.
1437          */
1438         if (inp->inp_flags & INP_DONTFRAG) {
1439                 struct ip *ip;
1440
1441                 ip = (struct ip *)&ui->ui_i;
1442                 ip->ip_off |= htons(IP_DF);
1443         }
1444
1445         ipflags = 0;
1446         if (inp->inp_socket->so_options & SO_DONTROUTE)
1447                 ipflags |= IP_ROUTETOIF;
1448         if (inp->inp_socket->so_options & SO_BROADCAST)
1449                 ipflags |= IP_ALLOWBROADCAST;
1450         if (inp->inp_flags & INP_ONESBCAST)
1451                 ipflags |= IP_SENDONES;
1452
1453 #ifdef MAC
1454         mac_inpcb_create_mbuf(inp, m);
1455 #endif
1456
1457         /*
1458          * Set up checksum and output datagram.
1459          */
1460         ui->ui_sum = 0;
1461         if (pr == IPPROTO_UDPLITE) {
1462                 if (inp->inp_flags & INP_ONESBCAST)
1463                         faddr.s_addr = INADDR_BROADCAST;
1464                 if (cscov_partial) {
1465                         if ((ui->ui_sum = in_cksum(m, sizeof(struct ip) + cscov)) == 0)
1466                                 ui->ui_sum = 0xffff;
1467                 } else {
1468                         if ((ui->ui_sum = in_cksum(m, sizeof(struct udpiphdr) + len)) == 0)
1469                                 ui->ui_sum = 0xffff;
1470                 }
1471         } else if (V_udp_cksum) {
1472                 if (inp->inp_flags & INP_ONESBCAST)
1473                         faddr.s_addr = INADDR_BROADCAST;
1474                 ui->ui_sum = in_pseudo(ui->ui_src.s_addr, faddr.s_addr,
1475                     htons((u_short)len + sizeof(struct udphdr) + pr));
1476                 m->m_pkthdr.csum_flags = CSUM_UDP;
1477                 m->m_pkthdr.csum_data = offsetof(struct udphdr, uh_sum);
1478         }
1479         ((struct ip *)ui)->ip_len = htons(sizeof(struct udpiphdr) + len);
1480         ((struct ip *)ui)->ip_ttl = inp->inp_ip_ttl;    /* XXX */
1481         ((struct ip *)ui)->ip_tos = tos;                /* XXX */
1482         UDPSTAT_INC(udps_opackets);
1483
1484         /*
1485          * Setup flowid / RSS information for outbound socket.
1486          *
1487          * Once the UDP code decides to set a flowid some other way,
1488          * this allows the flowid to be overridden by userland.
1489          */
1490         if (flowtype != M_HASHTYPE_NONE) {
1491                 m->m_pkthdr.flowid = flowid;
1492                 M_HASHTYPE_SET(m, flowtype);
1493 #ifdef  RSS
1494         } else {
1495                 uint32_t hash_val, hash_type;
1496                 /*
1497                  * Calculate an appropriate RSS hash for UDP and
1498                  * UDP Lite.
1499                  *
1500                  * The called function will take care of figuring out
1501                  * whether a 2-tuple or 4-tuple hash is required based
1502                  * on the currently configured scheme.
1503                  *
1504                  * Later later on connected socket values should be
1505                  * cached in the inpcb and reused, rather than constantly
1506                  * re-calculating it.
1507                  *
1508                  * UDP Lite is a different protocol number and will
1509                  * likely end up being hashed as a 2-tuple until
1510                  * RSS / NICs grow UDP Lite protocol awareness.
1511                  */
1512                 if (rss_proto_software_hash_v4(faddr, laddr, fport, lport,
1513                     pr, &hash_val, &hash_type) == 0) {
1514                         m->m_pkthdr.flowid = hash_val;
1515                         M_HASHTYPE_SET(m, hash_type);
1516                 }
1517 #endif
1518         }
1519
1520 #ifdef  RSS
1521         /*
1522          * Don't override with the inp cached flowid value.
1523          *
1524          * Depending upon the kind of send being done, the inp
1525          * flowid/flowtype values may actually not be appropriate
1526          * for this particular socket send.
1527          *
1528          * We should either leave the flowid at zero (which is what is
1529          * currently done) or set it to some software generated
1530          * hash value based on the packet contents.
1531          */
1532         ipflags |= IP_NODEFAULTFLOWID;
1533 #endif  /* RSS */
1534
1535         if (unlock_udbinfo == UH_WLOCKED)
1536                 INP_HASH_WUNLOCK(pcbinfo);
1537         else if (unlock_udbinfo == UH_RLOCKED)
1538                 INP_HASH_RUNLOCK_ET(pcbinfo, et);
1539         if (pr == IPPROTO_UDPLITE)
1540                 UDPLITE_PROBE(send, NULL, inp, &ui->ui_i, inp, &ui->ui_u);
1541         else
1542                 UDP_PROBE(send, NULL, inp, &ui->ui_i, inp, &ui->ui_u);
1543         error = ip_output(m, inp->inp_options,
1544             (unlock_inp == UH_WLOCKED ? &inp->inp_route : NULL), ipflags,
1545             inp->inp_moptions, inp);
1546         if (unlock_inp == UH_WLOCKED)
1547                 INP_WUNLOCK(inp);
1548         else
1549                 INP_RUNLOCK(inp);
1550         return (error);
1551
1552 release:
1553         if (unlock_udbinfo == UH_WLOCKED) {
1554                 KASSERT(unlock_inp == UH_WLOCKED,
1555                     ("%s: excl udbinfo lock, shared inp lock", __func__));
1556                 INP_HASH_WUNLOCK(pcbinfo);
1557                 INP_WUNLOCK(inp);
1558         } else if (unlock_udbinfo == UH_RLOCKED) {
1559                 KASSERT(unlock_inp == UH_RLOCKED,
1560                     ("%s: shared udbinfo lock, excl inp lock", __func__));
1561                 INP_HASH_RUNLOCK_ET(pcbinfo, et);
1562                 INP_RUNLOCK(inp);
1563         } else if (unlock_inp == UH_WLOCKED)
1564                 INP_WUNLOCK(inp);
1565         else
1566                 INP_RUNLOCK(inp);
1567         m_freem(m);
1568         return (error);
1569 }
1570
1571 static void
1572 udp_abort(struct socket *so)
1573 {
1574         struct inpcb *inp;
1575         struct inpcbinfo *pcbinfo;
1576
1577         pcbinfo = udp_get_inpcbinfo(so->so_proto->pr_protocol);
1578         inp = sotoinpcb(so);
1579         KASSERT(inp != NULL, ("udp_abort: inp == NULL"));
1580         INP_WLOCK(inp);
1581         if (inp->inp_faddr.s_addr != INADDR_ANY) {
1582                 INP_HASH_WLOCK(pcbinfo);
1583                 in_pcbdisconnect(inp);
1584                 inp->inp_laddr.s_addr = INADDR_ANY;
1585                 INP_HASH_WUNLOCK(pcbinfo);
1586                 soisdisconnected(so);
1587         }
1588         INP_WUNLOCK(inp);
1589 }
1590
1591 static int
1592 udp_attach(struct socket *so, int proto, struct thread *td)
1593 {
1594         static uint32_t udp_flowid;
1595         struct inpcb *inp;
1596         struct inpcbinfo *pcbinfo;
1597         int error;
1598
1599         pcbinfo = udp_get_inpcbinfo(so->so_proto->pr_protocol);
1600         inp = sotoinpcb(so);
1601         KASSERT(inp == NULL, ("udp_attach: inp != NULL"));
1602         error = soreserve(so, udp_sendspace, udp_recvspace);
1603         if (error)
1604                 return (error);
1605         INP_INFO_WLOCK(pcbinfo);
1606         error = in_pcballoc(so, pcbinfo);
1607         if (error) {
1608                 INP_INFO_WUNLOCK(pcbinfo);
1609                 return (error);
1610         }
1611
1612         inp = sotoinpcb(so);
1613         inp->inp_vflag |= INP_IPV4;
1614         inp->inp_ip_ttl = V_ip_defttl;
1615         inp->inp_flowid = atomic_fetchadd_int(&udp_flowid, 1);
1616         inp->inp_flowtype = M_HASHTYPE_OPAQUE;
1617
1618         error = udp_newudpcb(inp);
1619         if (error) {
1620                 in_pcbdetach(inp);
1621                 in_pcbfree(inp);
1622                 INP_INFO_WUNLOCK(pcbinfo);
1623                 return (error);
1624         }
1625
1626         INP_WUNLOCK(inp);
1627         INP_INFO_WUNLOCK(pcbinfo);
1628         return (0);
1629 }
1630 #endif /* INET */
1631
1632 int
1633 udp_set_kernel_tunneling(struct socket *so, udp_tun_func_t f, udp_tun_icmp_t i, void *ctx)
1634 {
1635         struct inpcb *inp;
1636         struct udpcb *up;
1637
1638         KASSERT(so->so_type == SOCK_DGRAM,
1639             ("udp_set_kernel_tunneling: !dgram"));
1640         inp = sotoinpcb(so);
1641         KASSERT(inp != NULL, ("udp_set_kernel_tunneling: inp == NULL"));
1642         INP_WLOCK(inp);
1643         up = intoudpcb(inp);
1644         if ((up->u_tun_func != NULL) ||
1645             (up->u_icmp_func != NULL)) {
1646                 INP_WUNLOCK(inp);
1647                 return (EBUSY);
1648         }
1649         up->u_tun_func = f;
1650         up->u_icmp_func = i;
1651         up->u_tun_ctx = ctx;
1652         INP_WUNLOCK(inp);
1653         return (0);
1654 }
1655
1656 #ifdef INET
1657 static int
1658 udp_bind(struct socket *so, struct sockaddr *nam, struct thread *td)
1659 {
1660         struct inpcb *inp;
1661         struct inpcbinfo *pcbinfo;
1662         int error;
1663
1664         pcbinfo = udp_get_inpcbinfo(so->so_proto->pr_protocol);
1665         inp = sotoinpcb(so);
1666         KASSERT(inp != NULL, ("udp_bind: inp == NULL"));
1667         INP_WLOCK(inp);
1668         INP_HASH_WLOCK(pcbinfo);
1669         error = in_pcbbind(inp, nam, td->td_ucred);
1670         INP_HASH_WUNLOCK(pcbinfo);
1671         INP_WUNLOCK(inp);
1672         return (error);
1673 }
1674
1675 static void
1676 udp_close(struct socket *so)
1677 {
1678         struct inpcb *inp;
1679         struct inpcbinfo *pcbinfo;
1680
1681         pcbinfo = udp_get_inpcbinfo(so->so_proto->pr_protocol);
1682         inp = sotoinpcb(so);
1683         KASSERT(inp != NULL, ("udp_close: inp == NULL"));
1684         INP_WLOCK(inp);
1685         if (inp->inp_faddr.s_addr != INADDR_ANY) {
1686                 INP_HASH_WLOCK(pcbinfo);
1687                 in_pcbdisconnect(inp);
1688                 inp->inp_laddr.s_addr = INADDR_ANY;
1689                 INP_HASH_WUNLOCK(pcbinfo);
1690                 soisdisconnected(so);
1691         }
1692         INP_WUNLOCK(inp);
1693 }
1694
1695 static int
1696 udp_connect(struct socket *so, struct sockaddr *nam, struct thread *td)
1697 {
1698         struct inpcb *inp;
1699         struct inpcbinfo *pcbinfo;
1700         struct sockaddr_in *sin;
1701         int error;
1702
1703         pcbinfo = udp_get_inpcbinfo(so->so_proto->pr_protocol);
1704         inp = sotoinpcb(so);
1705         KASSERT(inp != NULL, ("udp_connect: inp == NULL"));
1706         INP_WLOCK(inp);
1707         if (inp->inp_faddr.s_addr != INADDR_ANY) {
1708                 INP_WUNLOCK(inp);
1709                 return (EISCONN);
1710         }
1711         sin = (struct sockaddr_in *)nam;
1712         error = prison_remote_ip4(td->td_ucred, &sin->sin_addr);
1713         if (error != 0) {
1714                 INP_WUNLOCK(inp);
1715                 return (error);
1716         }
1717         INP_HASH_WLOCK(pcbinfo);
1718         error = in_pcbconnect(inp, nam, td->td_ucred);
1719         INP_HASH_WUNLOCK(pcbinfo);
1720         if (error == 0)
1721                 soisconnected(so);
1722         INP_WUNLOCK(inp);
1723         return (error);
1724 }
1725
1726 static void
1727 udp_detach(struct socket *so)
1728 {
1729         struct inpcb *inp;
1730         struct inpcbinfo *pcbinfo;
1731         struct udpcb *up;
1732
1733         pcbinfo = udp_get_inpcbinfo(so->so_proto->pr_protocol);
1734         inp = sotoinpcb(so);
1735         KASSERT(inp != NULL, ("udp_detach: inp == NULL"));
1736         KASSERT(inp->inp_faddr.s_addr == INADDR_ANY,
1737             ("udp_detach: not disconnected"));
1738         INP_INFO_WLOCK(pcbinfo);
1739         INP_WLOCK(inp);
1740         up = intoudpcb(inp);
1741         KASSERT(up != NULL, ("%s: up == NULL", __func__));
1742         inp->inp_ppcb = NULL;
1743         in_pcbdetach(inp);
1744         in_pcbfree(inp);
1745         INP_INFO_WUNLOCK(pcbinfo);
1746         udp_discardcb(up);
1747 }
1748
1749 static int
1750 udp_disconnect(struct socket *so)
1751 {
1752         struct inpcb *inp;
1753         struct inpcbinfo *pcbinfo;
1754
1755         pcbinfo = udp_get_inpcbinfo(so->so_proto->pr_protocol);
1756         inp = sotoinpcb(so);
1757         KASSERT(inp != NULL, ("udp_disconnect: inp == NULL"));
1758         INP_WLOCK(inp);
1759         if (inp->inp_faddr.s_addr == INADDR_ANY) {
1760                 INP_WUNLOCK(inp);
1761                 return (ENOTCONN);
1762         }
1763         INP_HASH_WLOCK(pcbinfo);
1764         in_pcbdisconnect(inp);
1765         inp->inp_laddr.s_addr = INADDR_ANY;
1766         INP_HASH_WUNLOCK(pcbinfo);
1767         SOCK_LOCK(so);
1768         so->so_state &= ~SS_ISCONNECTED;                /* XXX */
1769         SOCK_UNLOCK(so);
1770         INP_WUNLOCK(inp);
1771         return (0);
1772 }
1773
1774 static int
1775 udp_send(struct socket *so, int flags, struct mbuf *m, struct sockaddr *addr,
1776     struct mbuf *control, struct thread *td)
1777 {
1778         struct inpcb *inp;
1779
1780         inp = sotoinpcb(so);
1781         KASSERT(inp != NULL, ("udp_send: inp == NULL"));
1782         return (udp_output(inp, m, addr, control, td));
1783 }
1784 #endif /* INET */
1785
1786 int
1787 udp_shutdown(struct socket *so)
1788 {
1789         struct inpcb *inp;
1790
1791         inp = sotoinpcb(so);
1792         KASSERT(inp != NULL, ("udp_shutdown: inp == NULL"));
1793         INP_WLOCK(inp);
1794         socantsendmore(so);
1795         INP_WUNLOCK(inp);
1796         return (0);
1797 }
1798
1799 #ifdef INET
1800 struct pr_usrreqs udp_usrreqs = {
1801         .pru_abort =            udp_abort,
1802         .pru_attach =           udp_attach,
1803         .pru_bind =             udp_bind,
1804         .pru_connect =          udp_connect,
1805         .pru_control =          in_control,
1806         .pru_detach =           udp_detach,
1807         .pru_disconnect =       udp_disconnect,
1808         .pru_peeraddr =         in_getpeeraddr,
1809         .pru_send =             udp_send,
1810         .pru_soreceive =        soreceive_dgram,
1811         .pru_sosend =           sosend_dgram,
1812         .pru_shutdown =         udp_shutdown,
1813         .pru_sockaddr =         in_getsockaddr,
1814         .pru_sosetlabel =       in_pcbsosetlabel,
1815         .pru_close =            udp_close,
1816 };
1817 #endif /* INET */