2 * Copyright (c) 1982, 1986, 1988, 1990, 1993, 1995
3 * The Regents of the University of California.
4 * Copyright (c) 2008 Robert N. M. Watson
7 * Redistribution and use in source and binary forms, with or without
8 * modification, are permitted provided that the following conditions
10 * 1. Redistributions of source code must retain the above copyright
11 * notice, this list of conditions and the following disclaimer.
12 * 2. Redistributions in binary form must reproduce the above copyright
13 * notice, this list of conditions and the following disclaimer in the
14 * documentation and/or other materials provided with the distribution.
15 * 4. Neither the name of the University nor the names of its contributors
16 * may be used to endorse or promote products derived from this software
17 * without specific prior written permission.
19 * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
20 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
21 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
22 * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
23 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
24 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
25 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
26 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
27 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
28 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
31 * @(#)udp_usrreq.c 8.6 (Berkeley) 5/23/95
34 #include <sys/cdefs.h>
35 __FBSDID("$FreeBSD$");
38 #include "opt_inet6.h"
39 #include "opt_ipsec.h"
42 #include <sys/param.h>
43 #include <sys/domain.h>
44 #include <sys/eventhandler.h>
46 #include <sys/kernel.h>
48 #include <sys/malloc.h>
52 #include <sys/protosw.h>
53 #include <sys/signalvar.h>
54 #include <sys/socket.h>
55 #include <sys/socketvar.h>
57 #include <sys/sysctl.h>
58 #include <sys/syslog.h>
59 #include <sys/systm.h>
64 #include <net/route.h>
66 #include <netinet/in.h>
67 #include <netinet/in_pcb.h>
68 #include <netinet/in_systm.h>
69 #include <netinet/in_var.h>
70 #include <netinet/ip.h>
72 #include <netinet/ip6.h>
74 #include <netinet/ip_icmp.h>
75 #include <netinet/icmp_var.h>
76 #include <netinet/ip_var.h>
77 #include <netinet/ip_options.h>
79 #include <netinet6/ip6_var.h>
81 #include <netinet/udp.h>
82 #include <netinet/udp_var.h>
84 #include <netinet6/udp6_var.h>
88 #include <netipsec/ipsec.h>
91 #include <machine/in_cksum.h>
93 #include <security/mac/mac_framework.h>
96 * UDP protocol implementation.
97 * Per RFC 768, August, 1980.
101 * BSD 4.2 defaulted the udp checksum to be off. Turning off udp checksums
102 * removes the only data integrity mechanism for packets and malformed
103 * packets that would otherwise be discarded due to bad checksums, and may
104 * cause problems (especially for NFS data blocks).
106 static int udp_cksum = 1;
107 SYSCTL_INT(_net_inet_udp, UDPCTL_CHECKSUM, checksum, CTLFLAG_RW, &udp_cksum,
110 int udp_log_in_vain = 0;
111 SYSCTL_INT(_net_inet_udp, OID_AUTO, log_in_vain, CTLFLAG_RW,
112 &udp_log_in_vain, 0, "Log all incoming UDP packets");
114 int udp_blackhole = 0;
115 SYSCTL_INT(_net_inet_udp, OID_AUTO, blackhole, CTLFLAG_RW, &udp_blackhole, 0,
116 "Do not send port unreachables for refused connects");
118 u_long udp_sendspace = 9216; /* really max datagram size */
119 /* 40 1K datagrams */
120 SYSCTL_ULONG(_net_inet_udp, UDPCTL_MAXDGRAM, maxdgram, CTLFLAG_RW,
121 &udp_sendspace, 0, "Maximum outgoing UDP datagram size");
123 u_long udp_recvspace = 40 * (1024 +
125 sizeof(struct sockaddr_in6)
127 sizeof(struct sockaddr_in)
131 SYSCTL_ULONG(_net_inet_udp, UDPCTL_RECVSPACE, recvspace, CTLFLAG_RW,
132 &udp_recvspace, 0, "Maximum space for incoming UDP datagrams");
134 static int udp_soreceive_dgram = 1;
135 SYSCTL_INT(_net_inet_udp, OID_AUTO, soreceive_dgram_enabled,
136 CTLFLAG_RD | CTLFLAG_TUN, &udp_soreceive_dgram, 0,
137 "Use experimental optimized datagram receive");
139 struct inpcbhead udb; /* from udp_var.h */
140 struct inpcbinfo udbinfo;
143 #define UDBHASHSIZE 128
146 struct udpstat udpstat; /* from udp_var.h */
147 SYSCTL_STRUCT(_net_inet_udp, UDPCTL_STATS, stats, CTLFLAG_RW, &udpstat,
148 udpstat, "UDP statistics (struct udpstat, netinet/udp_var.h)");
150 static void udp_detach(struct socket *so);
151 static int udp_output(struct inpcb *, struct mbuf *, struct sockaddr *,
152 struct mbuf *, struct thread *);
155 udp_zone_change(void *tag)
158 uma_zone_set_max(udbinfo.ipi_zone, maxsockets);
162 udp_inpcb_init(void *mem, int size, int flags)
167 INP_LOCK_INIT(inp, "inp", "udpinp");
175 INP_INFO_LOCK_INIT(&udbinfo, "udp");
177 udbinfo.ipi_listhead = &udb;
178 udbinfo.ipi_hashbase = hashinit(UDBHASHSIZE, M_PCB,
179 &udbinfo.ipi_hashmask);
180 udbinfo.ipi_porthashbase = hashinit(UDBHASHSIZE, M_PCB,
181 &udbinfo.ipi_porthashmask);
182 udbinfo.ipi_zone = uma_zcreate("udpcb", sizeof(struct inpcb), NULL,
183 NULL, udp_inpcb_init, NULL, UMA_ALIGN_PTR, UMA_ZONE_NOFREE);
184 uma_zone_set_max(udbinfo.ipi_zone, maxsockets);
185 EVENTHANDLER_REGISTER(maxsockets_change, udp_zone_change, NULL,
186 EVENTHANDLER_PRI_ANY);
187 TUNABLE_INT_FETCH("net.inet.udp.soreceive_dgram_enabled",
188 &udp_soreceive_dgram);
189 if (udp_soreceive_dgram) {
190 udp_usrreqs.pru_soreceive = soreceive_dgram;
192 udp6_usrreqs.pru_soreceive = soreceive_dgram;
198 * Subroutine of udp_input(), which appends the provided mbuf chain to the
199 * passed pcb/socket. The caller must provide a sockaddr_in via udp_in that
200 * contains the source address. If the socket ends up being an IPv6 socket,
201 * udp_append() will convert to a sockaddr_in6 before passing the address
202 * into the socket code.
205 udp_append(struct inpcb *inp, struct ip *ip, struct mbuf *n, int off,
206 struct sockaddr_in *udp_in)
208 struct sockaddr *append_sa;
210 struct mbuf *opts = 0;
212 struct sockaddr_in6 udp_in6;
215 INP_RLOCK_ASSERT(inp);
218 /* Check AH/ESP integrity. */
219 if (ipsec4_in_reject(n, inp)) {
221 ipsec4stat.in_polvio++;
226 if (mac_check_inpcb_deliver(inp, n) != 0) {
231 if (inp->inp_flags & INP_CONTROLOPTS ||
232 inp->inp_socket->so_options & (SO_TIMESTAMP | SO_BINTIME)) {
234 if (inp->inp_vflag & INP_IPV6)
235 (void)ip6_savecontrol_v4(inp, n, &opts, NULL);
238 ip_savecontrol(inp, &opts, ip, n);
241 if (inp->inp_vflag & INP_IPV6) {
242 bzero(&udp_in6, sizeof(udp_in6));
243 udp_in6.sin6_len = sizeof(udp_in6);
244 udp_in6.sin6_family = AF_INET6;
245 in6_sin_2_v4mapsin6(udp_in, &udp_in6);
246 append_sa = (struct sockaddr *)&udp_in6;
249 append_sa = (struct sockaddr *)udp_in;
252 so = inp->inp_socket;
253 SOCKBUF_LOCK(&so->so_rcv);
254 if (sbappendaddr_locked(&so->so_rcv, append_sa, n, opts) == 0) {
255 SOCKBUF_UNLOCK(&so->so_rcv);
259 udpstat.udps_fullsock++;
261 sorwakeup_locked(so);
265 udp_input(struct mbuf *m, int off)
274 struct sockaddr_in udp_in;
275 #ifdef IPFIREWALL_FORWARD
276 struct m_tag *fwd_tag;
279 ifp = m->m_pkthdr.rcvif;
280 udpstat.udps_ipackets++;
283 * Strip IP options, if any; should skip this, make available to
284 * user, and use on returned packets, but we don't yet have a way to
285 * check the checksum with options still present.
287 if (iphlen > sizeof (struct ip)) {
288 ip_stripoptions(m, (struct mbuf *)0);
289 iphlen = sizeof(struct ip);
293 * Get IP and UDP header together in first mbuf.
295 ip = mtod(m, struct ip *);
296 if (m->m_len < iphlen + sizeof(struct udphdr)) {
297 if ((m = m_pullup(m, iphlen + sizeof(struct udphdr))) == 0) {
298 udpstat.udps_hdrops++;
301 ip = mtod(m, struct ip *);
303 uh = (struct udphdr *)((caddr_t)ip + iphlen);
306 * Destination port of 0 is illegal, based on RFC768.
308 if (uh->uh_dport == 0)
312 * Construct sockaddr format source address. Stuff source address
313 * and datagram in user buffer.
315 bzero(&udp_in, sizeof(udp_in));
316 udp_in.sin_len = sizeof(udp_in);
317 udp_in.sin_family = AF_INET;
318 udp_in.sin_port = uh->uh_sport;
319 udp_in.sin_addr = ip->ip_src;
322 * Make mbuf data length reflect UDP length. If not enough data to
323 * reflect UDP length, drop.
325 len = ntohs((u_short)uh->uh_ulen);
326 if (ip->ip_len != len) {
327 if (len > ip->ip_len || len < sizeof(struct udphdr)) {
328 udpstat.udps_badlen++;
331 m_adj(m, len - ip->ip_len);
332 /* ip->ip_len = len; */
336 * Save a copy of the IP header in case we want restore it for
337 * sending an ICMP error message in response.
342 memset(&save_ip, 0, sizeof(save_ip));
345 * Checksum extended UDP header and data.
350 if (m->m_pkthdr.csum_flags & CSUM_DATA_VALID) {
351 if (m->m_pkthdr.csum_flags & CSUM_PSEUDO_HDR)
352 uh_sum = m->m_pkthdr.csum_data;
354 uh_sum = in_pseudo(ip->ip_src.s_addr,
355 ip->ip_dst.s_addr, htonl((u_short)len +
356 m->m_pkthdr.csum_data + IPPROTO_UDP));
361 bcopy(((struct ipovly *)ip)->ih_x1, b, 9);
362 bzero(((struct ipovly *)ip)->ih_x1, 9);
363 ((struct ipovly *)ip)->ih_len = uh->uh_ulen;
364 uh_sum = in_cksum(m, len + sizeof (struct ip));
365 bcopy(b, ((struct ipovly *)ip)->ih_x1, 9);
368 udpstat.udps_badsum++;
373 udpstat.udps_nosum++;
375 #ifdef IPFIREWALL_FORWARD
377 * Grab info from PACKET_TAG_IPFORWARD tag prepended to the chain.
379 fwd_tag = m_tag_find(m, PACKET_TAG_IPFORWARD, NULL);
380 if (fwd_tag != NULL) {
381 struct sockaddr_in *next_hop;
386 next_hop = (struct sockaddr_in *)(fwd_tag + 1);
387 ip->ip_dst = next_hop->sin_addr;
388 uh->uh_dport = ntohs(next_hop->sin_port);
391 * Remove the tag from the packet. We don't need it anymore.
393 m_tag_delete(m, fwd_tag);
397 INP_INFO_RLOCK(&udbinfo);
398 if (IN_MULTICAST(ntohl(ip->ip_dst.s_addr)) ||
399 in_broadcast(ip->ip_dst, ifp)) {
401 struct ip_moptions *imo;
404 LIST_FOREACH(inp, &udb, inp_list) {
405 if (inp->inp_lport != uh->uh_dport)
408 if ((inp->inp_vflag & INP_IPV4) == 0)
411 if (inp->inp_laddr.s_addr != INADDR_ANY &&
412 inp->inp_laddr.s_addr != ip->ip_dst.s_addr)
414 if (inp->inp_faddr.s_addr != INADDR_ANY &&
415 inp->inp_faddr.s_addr != ip->ip_src.s_addr)
418 * XXX: Do not check source port of incoming datagram
419 * unless inp_connect() has been called to bind the
420 * fport part of the 4-tuple; the source could be
421 * trying to talk to us with an ephemeral port.
423 if (inp->inp_fport != 0 &&
424 inp->inp_fport != uh->uh_sport)
430 * Handle socket delivery policy for any-source
431 * and source-specific multicast. [RFC3678]
433 imo = inp->inp_moptions;
434 if (IN_MULTICAST(ntohl(ip->ip_dst.s_addr)) &&
436 struct sockaddr_in sin;
437 struct in_msource *ims;
441 bzero(&sin, sizeof(struct sockaddr_in));
442 sin.sin_len = sizeof(struct sockaddr_in);
443 sin.sin_family = AF_INET;
444 sin.sin_addr = ip->ip_dst;
447 idx = imo_match_group(imo, ifp,
448 (struct sockaddr *)&sin);
451 * No group membership for this socket.
452 * Do not bump udps_noportbcast, as
453 * this will happen further down.
458 * Check for a multicast source filter
459 * entry on this socket for this group.
460 * MCAST_EXCLUDE is the default
461 * behaviour. It means default accept;
462 * entries, if present, denote sources
463 * to be excluded from delivery.
465 ims = imo_match_source(imo, idx,
466 (struct sockaddr *)&udp_in);
467 mode = imo->imo_mfilters[idx].imf_fmode;
469 mode == MCAST_EXCLUDE) ||
471 mode == MCAST_INCLUDE)) {
474 printf("%s: blocked by"
479 udpstat.udps_filtermcast++;
491 n = m_copy(m, 0, M_COPYALL);
493 udp_append(last, ip, n, iphlen +
494 sizeof(struct udphdr), &udp_in);
499 * Don't look for additional matches if this one does
500 * not have either the SO_REUSEPORT or SO_REUSEADDR
501 * socket options set. This heuristic avoids
502 * searching through all pcbs in the common case of a
503 * non-shared port. It assumes that an application
504 * will never clear these options after setting them.
506 if ((last->inp_socket->so_options &
507 (SO_REUSEPORT|SO_REUSEADDR)) == 0)
513 * No matching pcb found; discard datagram. (No need
514 * to send an ICMP Port Unreachable for a broadcast
515 * or multicast datgram.)
517 udpstat.udps_noportbcast++;
520 udp_append(last, ip, m, iphlen + sizeof(struct udphdr),
523 INP_INFO_RUNLOCK(&udbinfo);
528 * Locate pcb for datagram.
530 inp = in_pcblookup_hash(&udbinfo, ip->ip_src, uh->uh_sport,
531 ip->ip_dst, uh->uh_dport, 1, ifp);
533 if (udp_log_in_vain) {
534 char buf[4*sizeof "123"];
536 strcpy(buf, inet_ntoa(ip->ip_dst));
538 "Connection attempt to UDP %s:%d from %s:%d\n",
539 buf, ntohs(uh->uh_dport), inet_ntoa(ip->ip_src),
540 ntohs(uh->uh_sport));
542 udpstat.udps_noport++;
543 if (m->m_flags & (M_BCAST | M_MCAST)) {
544 udpstat.udps_noportbcast++;
549 if (badport_bandlim(BANDLIM_ICMP_UNREACH) < 0)
552 ip->ip_len += iphlen;
553 icmp_error(m, ICMP_UNREACH, ICMP_UNREACH_PORT, 0, 0);
554 INP_INFO_RUNLOCK(&udbinfo);
559 * Check the minimum TTL for socket.
562 INP_INFO_RUNLOCK(&udbinfo);
563 if (inp->inp_ip_minttl && inp->inp_ip_minttl > ip->ip_ttl) {
567 udp_append(inp, ip, m, iphlen + sizeof(struct udphdr), &udp_in);
574 INP_INFO_RUNLOCK(&udbinfo);
580 * Notify a udp user of an asynchronous error; just wake up so that they can
581 * collect error status.
584 udp_notify(struct inpcb *inp, int errno)
588 * While udp_ctlinput() always calls udp_notify() with a read lock
589 * when invoking it directly, in_pcbnotifyall() currently uses write
590 * locks due to sharing code with TCP. For now, accept either a read
591 * or a write lock, but a read lock is sufficient.
593 INP_LOCK_ASSERT(inp);
595 inp->inp_socket->so_error = errno;
596 sorwakeup(inp->inp_socket);
597 sowwakeup(inp->inp_socket);
602 udp_ctlinput(int cmd, struct sockaddr *sa, void *vip)
606 struct in_addr faddr;
609 faddr = ((struct sockaddr_in *)sa)->sin_addr;
610 if (sa->sa_family != AF_INET || faddr.s_addr == INADDR_ANY)
614 * Redirects don't need to be handled up here.
616 if (PRC_IS_REDIRECT(cmd))
620 * Hostdead is ugly because it goes linearly through all PCBs.
622 * XXX: We never get this from ICMP, otherwise it makes an excellent
623 * DoS attack on machines with many connections.
625 if (cmd == PRC_HOSTDEAD)
627 else if ((unsigned)cmd >= PRC_NCMDS || inetctlerrmap[cmd] == 0)
630 uh = (struct udphdr *)((caddr_t)ip + (ip->ip_hl << 2));
631 INP_INFO_RLOCK(&udbinfo);
632 inp = in_pcblookup_hash(&udbinfo, faddr, uh->uh_dport,
633 ip->ip_src, uh->uh_sport, 0, NULL);
636 if (inp->inp_socket != NULL) {
637 udp_notify(inp, inetctlerrmap[cmd]);
641 INP_INFO_RUNLOCK(&udbinfo);
643 in_pcbnotifyall(&udbinfo, faddr, inetctlerrmap[cmd],
648 udp_pcblist(SYSCTL_HANDLER_ARGS)
651 struct inpcb *inp, **inp_list;
656 * The process of preparing the PCB list is too time-consuming and
657 * resource-intensive to repeat twice on every request.
659 if (req->oldptr == 0) {
660 n = udbinfo.ipi_count;
661 req->oldidx = 2 * (sizeof xig)
662 + (n + n/8) * sizeof(struct xinpcb);
666 if (req->newptr != 0)
670 * OK, now we're committed to doing something.
672 INP_INFO_RLOCK(&udbinfo);
673 gencnt = udbinfo.ipi_gencnt;
674 n = udbinfo.ipi_count;
675 INP_INFO_RUNLOCK(&udbinfo);
677 error = sysctl_wire_old_buffer(req, 2 * (sizeof xig)
678 + n * sizeof(struct xinpcb));
682 xig.xig_len = sizeof xig;
684 xig.xig_gen = gencnt;
685 xig.xig_sogen = so_gencnt;
686 error = SYSCTL_OUT(req, &xig, sizeof xig);
690 inp_list = malloc(n * sizeof *inp_list, M_TEMP, M_WAITOK);
694 INP_INFO_RLOCK(&udbinfo);
695 for (inp = LIST_FIRST(udbinfo.ipi_listhead), i = 0; inp && i < n;
696 inp = LIST_NEXT(inp, inp_list)) {
698 if (inp->inp_gencnt <= gencnt &&
699 cr_canseeinpcb(req->td->td_ucred, inp) == 0)
703 INP_INFO_RUNLOCK(&udbinfo);
707 for (i = 0; i < n; i++) {
710 if (inp->inp_gencnt <= gencnt) {
712 bzero(&xi, sizeof(xi));
713 xi.xi_len = sizeof xi;
714 /* XXX should avoid extra copy */
715 bcopy(inp, &xi.xi_inp, sizeof *inp);
717 sotoxsocket(inp->inp_socket, &xi.xi_socket);
718 xi.xi_inp.inp_gencnt = inp->inp_gencnt;
720 error = SYSCTL_OUT(req, &xi, sizeof xi);
726 * Give the user an updated idea of our state. If the
727 * generation differs from what we told her before, she knows
728 * that something happened while we were processing this
729 * request, and it might be necessary to retry.
731 INP_INFO_RLOCK(&udbinfo);
732 xig.xig_gen = udbinfo.ipi_gencnt;
733 xig.xig_sogen = so_gencnt;
734 xig.xig_count = udbinfo.ipi_count;
735 INP_INFO_RUNLOCK(&udbinfo);
736 error = SYSCTL_OUT(req, &xig, sizeof xig);
738 free(inp_list, M_TEMP);
742 SYSCTL_PROC(_net_inet_udp, UDPCTL_PCBLIST, pcblist, CTLFLAG_RD, 0, 0,
743 udp_pcblist, "S,xinpcb", "List of active UDP sockets");
746 udp_getcred(SYSCTL_HANDLER_ARGS)
749 struct sockaddr_in addrs[2];
753 error = priv_check(req->td, PRIV_NETINET_GETCRED);
756 error = SYSCTL_IN(req, addrs, sizeof(addrs));
759 INP_INFO_RLOCK(&udbinfo);
760 inp = in_pcblookup_hash(&udbinfo, addrs[1].sin_addr, addrs[1].sin_port,
761 addrs[0].sin_addr, addrs[0].sin_port, 1, NULL);
764 INP_INFO_RUNLOCK(&udbinfo);
765 if (inp->inp_socket == NULL)
768 error = cr_canseeinpcb(req->td->td_ucred, inp);
770 cru2x(inp->inp_cred, &xuc);
773 INP_INFO_RUNLOCK(&udbinfo);
777 error = SYSCTL_OUT(req, &xuc, sizeof(struct xucred));
781 SYSCTL_PROC(_net_inet_udp, OID_AUTO, getcred,
782 CTLTYPE_OPAQUE|CTLFLAG_RW|CTLFLAG_PRISON, 0, 0,
783 udp_getcred, "S,xucred", "Get the xucred of a UDP connection");
786 udp_output(struct inpcb *inp, struct mbuf *m, struct sockaddr *addr,
787 struct mbuf *control, struct thread *td)
790 int len = m->m_pkthdr.len;
791 struct in_addr faddr, laddr;
793 struct sockaddr_in *sin, src;
796 u_short fport, lport;
800 * udp_output() may need to temporarily bind or connect the current
801 * inpcb. As such, we don't know up front whether we will need the
802 * pcbinfo lock or not. Do any work to decide what is needed up
803 * front before acquiring any locks.
805 if (len + sizeof(struct udpiphdr) > IP_MAXPACKET) {
813 if (control != NULL) {
815 * XXX: Currently, we assume all the optional information is
816 * stored in a single mbuf.
818 if (control->m_next) {
823 for (; control->m_len > 0;
824 control->m_data += CMSG_ALIGN(cm->cmsg_len),
825 control->m_len -= CMSG_ALIGN(cm->cmsg_len)) {
826 cm = mtod(control, struct cmsghdr *);
827 if (control->m_len < sizeof(*cm) || cm->cmsg_len == 0
828 || cm->cmsg_len > control->m_len) {
832 if (cm->cmsg_level != IPPROTO_IP)
835 switch (cm->cmsg_type) {
838 CMSG_LEN(sizeof(struct in_addr))) {
842 bzero(&src, sizeof(src));
843 src.sin_family = AF_INET;
844 src.sin_len = sizeof(src);
845 src.sin_port = inp->inp_lport;
847 *(struct in_addr *)CMSG_DATA(cm);
865 * Depending on whether or not the application has bound or connected
866 * the socket, we may have to do varying levels of work. The optimal
867 * case is for a connected UDP socket, as a global lock isn't
870 * In order to decide which we need, we require stability of the
871 * inpcb binding, which we ensure by acquiring a read lock on the
872 * inpcb. This doesn't strictly follow the lock order, so we play
873 * the trylock and retry game; note that we may end up with more
874 * conservative locks than required the second time around, so later
875 * assertions have to accept that. Further analysis of the number of
876 * misses under contention is required.
878 sin = (struct sockaddr_in *)addr;
881 (inp->inp_laddr.s_addr == INADDR_ANY && inp->inp_lport == 0)) {
883 INP_INFO_WLOCK(&udbinfo);
886 } else if ((sin != NULL && (
887 (sin->sin_addr.s_addr == INADDR_ANY) ||
888 (sin->sin_addr.s_addr == INADDR_BROADCAST) ||
889 (inp->inp_laddr.s_addr == INADDR_ANY) ||
890 (inp->inp_lport == 0))) ||
891 (src.sin_family == AF_INET)) {
892 if (!INP_INFO_TRY_RLOCK(&udbinfo)) {
894 INP_INFO_RLOCK(&udbinfo);
902 * If the IP_SENDSRCADDR control message was specified, override the
903 * source address for this datagram. Its use is invalidated if the
904 * address thus specified is incomplete or clobbers other inpcbs.
906 laddr = inp->inp_laddr;
907 lport = inp->inp_lport;
908 if (src.sin_family == AF_INET) {
909 INP_INFO_LOCK_ASSERT(&udbinfo);
911 (laddr.s_addr == INADDR_ANY &&
912 src.sin_addr.s_addr == INADDR_ANY)) {
916 error = in_pcbbind_setup(inp, (struct sockaddr *)&src,
917 &laddr.s_addr, &lport, td->td_ucred);
923 * If a UDP socket has been connected, then a local address/port will
924 * have been selected and bound.
926 * If a UDP socket has not been connected to, then an explicit
927 * destination address must be used, in which case a local
928 * address/port may not have been selected and bound.
931 INP_LOCK_ASSERT(inp);
932 if (inp->inp_faddr.s_addr != INADDR_ANY) {
938 * Jail may rewrite the destination address, so let it do
939 * that before we use it.
941 error = prison_remote_ip4(td->td_ucred, &sin->sin_addr);
946 * If a local address or port hasn't yet been selected, or if
947 * the destination address needs to be rewritten due to using
948 * a special INADDR_ constant, invoke in_pcbconnect_setup()
949 * to do the heavy lifting. Once a port is selected, we
950 * commit the binding back to the socket; we also commit the
951 * binding of the address if in jail.
953 * If we already have a valid binding and we're not
954 * requesting a destination address rewrite, use a fast path.
956 if (inp->inp_laddr.s_addr == INADDR_ANY ||
957 inp->inp_lport == 0 ||
958 sin->sin_addr.s_addr == INADDR_ANY ||
959 sin->sin_addr.s_addr == INADDR_BROADCAST) {
960 INP_INFO_LOCK_ASSERT(&udbinfo);
961 error = in_pcbconnect_setup(inp, addr, &laddr.s_addr,
962 &lport, &faddr.s_addr, &fport, NULL,
968 * XXXRW: Why not commit the port if the address is
971 /* Commit the local port if newly assigned. */
972 if (inp->inp_laddr.s_addr == INADDR_ANY &&
973 inp->inp_lport == 0) {
974 INP_INFO_WLOCK_ASSERT(&udbinfo);
975 INP_WLOCK_ASSERT(inp);
977 * Remember addr if jailed, to prevent
980 if (jailed(td->td_ucred))
981 inp->inp_laddr = laddr;
982 inp->inp_lport = lport;
983 if (in_pcbinshash(inp) != 0) {
988 inp->inp_flags |= INP_ANONPORT;
991 faddr = sin->sin_addr;
992 fport = sin->sin_port;
995 INP_LOCK_ASSERT(inp);
996 faddr = inp->inp_faddr;
997 fport = inp->inp_fport;
998 if (faddr.s_addr == INADDR_ANY) {
1005 * Calculate data length and get a mbuf for UDP, IP, and possible
1006 * link-layer headers. Immediate slide the data pointer back forward
1007 * since we won't use that space at this layer.
1009 M_PREPEND(m, sizeof(struct udpiphdr) + max_linkhdr, M_DONTWAIT);
1014 m->m_data += max_linkhdr;
1015 m->m_len -= max_linkhdr;
1016 m->m_pkthdr.len -= max_linkhdr;
1019 * Fill in mbuf with extended UDP header and addresses and length put
1020 * into network format.
1022 ui = mtod(m, struct udpiphdr *);
1023 bzero(ui->ui_x1, sizeof(ui->ui_x1)); /* XXX still needed? */
1024 ui->ui_pr = IPPROTO_UDP;
1027 ui->ui_sport = lport;
1028 ui->ui_dport = fport;
1029 ui->ui_ulen = htons((u_short)len + sizeof(struct udphdr));
1032 * Set the Don't Fragment bit in the IP header.
1034 if (inp->inp_flags & INP_DONTFRAG) {
1037 ip = (struct ip *)&ui->ui_i;
1038 ip->ip_off |= IP_DF;
1042 if (inp->inp_socket->so_options & SO_DONTROUTE)
1043 ipflags |= IP_ROUTETOIF;
1044 if (inp->inp_socket->so_options & SO_BROADCAST)
1045 ipflags |= IP_ALLOWBROADCAST;
1046 if (inp->inp_flags & INP_ONESBCAST)
1047 ipflags |= IP_SENDONES;
1050 mac_create_mbuf_from_inpcb(inp, m);
1054 * Set up checksum and output datagram.
1057 if (inp->inp_flags & INP_ONESBCAST)
1058 faddr.s_addr = INADDR_BROADCAST;
1059 ui->ui_sum = in_pseudo(ui->ui_src.s_addr, faddr.s_addr,
1060 htons((u_short)len + sizeof(struct udphdr) + IPPROTO_UDP));
1061 m->m_pkthdr.csum_flags = CSUM_UDP;
1062 m->m_pkthdr.csum_data = offsetof(struct udphdr, uh_sum);
1065 ((struct ip *)ui)->ip_len = sizeof (struct udpiphdr) + len;
1066 ((struct ip *)ui)->ip_ttl = inp->inp_ip_ttl; /* XXX */
1067 ((struct ip *)ui)->ip_tos = inp->inp_ip_tos; /* XXX */
1068 udpstat.udps_opackets++;
1070 if (unlock_udbinfo == 2)
1071 INP_INFO_WUNLOCK(&udbinfo);
1072 else if (unlock_udbinfo == 1)
1073 INP_INFO_RUNLOCK(&udbinfo);
1074 error = ip_output(m, inp->inp_options, NULL, ipflags,
1075 inp->inp_moptions, inp);
1076 if (unlock_udbinfo == 2)
1083 if (unlock_udbinfo == 2) {
1085 INP_INFO_WUNLOCK(&udbinfo);
1086 } else if (unlock_udbinfo == 1) {
1088 INP_INFO_RUNLOCK(&udbinfo);
1096 udp_abort(struct socket *so)
1100 inp = sotoinpcb(so);
1101 KASSERT(inp != NULL, ("udp_abort: inp == NULL"));
1102 INP_INFO_WLOCK(&udbinfo);
1104 if (inp->inp_faddr.s_addr != INADDR_ANY) {
1105 in_pcbdisconnect(inp);
1106 inp->inp_laddr.s_addr = INADDR_ANY;
1107 soisdisconnected(so);
1110 INP_INFO_WUNLOCK(&udbinfo);
1114 udp_attach(struct socket *so, int proto, struct thread *td)
1119 inp = sotoinpcb(so);
1120 KASSERT(inp == NULL, ("udp_attach: inp != NULL"));
1121 error = soreserve(so, udp_sendspace, udp_recvspace);
1124 INP_INFO_WLOCK(&udbinfo);
1125 error = in_pcballoc(so, &udbinfo);
1127 INP_INFO_WUNLOCK(&udbinfo);
1131 inp = (struct inpcb *)so->so_pcb;
1132 INP_INFO_WUNLOCK(&udbinfo);
1133 inp->inp_vflag |= INP_IPV4;
1134 inp->inp_ip_ttl = ip_defttl;
1140 udp_bind(struct socket *so, struct sockaddr *nam, struct thread *td)
1145 inp = sotoinpcb(so);
1146 KASSERT(inp != NULL, ("udp_bind: inp == NULL"));
1147 INP_INFO_WLOCK(&udbinfo);
1149 error = in_pcbbind(inp, nam, td->td_ucred);
1151 INP_INFO_WUNLOCK(&udbinfo);
1156 udp_close(struct socket *so)
1160 inp = sotoinpcb(so);
1161 KASSERT(inp != NULL, ("udp_close: inp == NULL"));
1162 INP_INFO_WLOCK(&udbinfo);
1164 if (inp->inp_faddr.s_addr != INADDR_ANY) {
1165 in_pcbdisconnect(inp);
1166 inp->inp_laddr.s_addr = INADDR_ANY;
1167 soisdisconnected(so);
1170 INP_INFO_WUNLOCK(&udbinfo);
1174 udp_connect(struct socket *so, struct sockaddr *nam, struct thread *td)
1178 struct sockaddr_in *sin;
1180 inp = sotoinpcb(so);
1181 KASSERT(inp != NULL, ("udp_connect: inp == NULL"));
1182 INP_INFO_WLOCK(&udbinfo);
1184 if (inp->inp_faddr.s_addr != INADDR_ANY) {
1186 INP_INFO_WUNLOCK(&udbinfo);
1189 sin = (struct sockaddr_in *)nam;
1190 error = prison_remote_ip4(td->td_ucred, &sin->sin_addr);
1193 INP_INFO_WUNLOCK(&udbinfo);
1196 error = in_pcbconnect(inp, nam, td->td_ucred);
1200 INP_INFO_WUNLOCK(&udbinfo);
1205 udp_detach(struct socket *so)
1209 inp = sotoinpcb(so);
1210 KASSERT(inp != NULL, ("udp_detach: inp == NULL"));
1211 KASSERT(inp->inp_faddr.s_addr == INADDR_ANY,
1212 ("udp_detach: not disconnected"));
1213 INP_INFO_WLOCK(&udbinfo);
1217 INP_INFO_WUNLOCK(&udbinfo);
1221 udp_disconnect(struct socket *so)
1225 inp = sotoinpcb(so);
1226 KASSERT(inp != NULL, ("udp_disconnect: inp == NULL"));
1227 INP_INFO_WLOCK(&udbinfo);
1229 if (inp->inp_faddr.s_addr == INADDR_ANY) {
1231 INP_INFO_WUNLOCK(&udbinfo);
1235 in_pcbdisconnect(inp);
1236 inp->inp_laddr.s_addr = INADDR_ANY;
1238 so->so_state &= ~SS_ISCONNECTED; /* XXX */
1241 INP_INFO_WUNLOCK(&udbinfo);
1246 udp_send(struct socket *so, int flags, struct mbuf *m, struct sockaddr *addr,
1247 struct mbuf *control, struct thread *td)
1251 inp = sotoinpcb(so);
1252 KASSERT(inp != NULL, ("udp_send: inp == NULL"));
1253 return (udp_output(inp, m, addr, control, td));
1257 udp_shutdown(struct socket *so)
1261 inp = sotoinpcb(so);
1262 KASSERT(inp != NULL, ("udp_shutdown: inp == NULL"));
1269 struct pr_usrreqs udp_usrreqs = {
1270 .pru_abort = udp_abort,
1271 .pru_attach = udp_attach,
1272 .pru_bind = udp_bind,
1273 .pru_connect = udp_connect,
1274 .pru_control = in_control,
1275 .pru_detach = udp_detach,
1276 .pru_disconnect = udp_disconnect,
1277 .pru_peeraddr = in_getpeeraddr,
1278 .pru_send = udp_send,
1279 .pru_sosend = sosend_dgram,
1280 .pru_shutdown = udp_shutdown,
1281 .pru_sockaddr = in_getsockaddr,
1282 .pru_sosetlabel = in_pcbsosetlabel,
1283 .pru_close = udp_close,