2 * INET An implementation of the TCP/IP protocol suite for the LINUX
3 * operating system. INET is implemented using the BSD Socket
4 * interface as the means of communication with the user level.
6 * The User Datagram Protocol (UDP).
8 * Version: $Id: udp.c,v 1.102 2002/02/01 22:01:04 davem Exp $
11 * Fred N. van Kempen, <waltje@uWalt.NL.Mugnet.ORG>
12 * Arnt Gulbrandsen, <agulbra@nvg.unit.no>
13 * Alan Cox, <Alan.Cox@linux.org>
14 * Hirokazu Takahashi, <taka@valinux.co.jp>
17 * Alan Cox : verify_area() calls
18 * Alan Cox : stopped close while in use off icmp
19 * messages. Not a fix but a botch that
20 * for udp at least is 'valid'.
21 * Alan Cox : Fixed icmp handling properly
22 * Alan Cox : Correct error for oversized datagrams
23 * Alan Cox : Tidied select() semantics.
24 * Alan Cox : udp_err() fixed properly, also now
25 * select and read wake correctly on errors
26 * Alan Cox : udp_send verify_area moved to avoid mem leak
27 * Alan Cox : UDP can count its memory
28 * Alan Cox : send to an unknown connection causes
29 * an ECONNREFUSED off the icmp, but
31 * Alan Cox : Switched to new sk_buff handlers. No more backlog!
32 * Alan Cox : Using generic datagram code. Even smaller and the PEEK
33 * bug no longer crashes it.
34 * Fred Van Kempen : Net2e support for sk->broadcast.
35 * Alan Cox : Uses skb_free_datagram
36 * Alan Cox : Added get/set sockopt support.
37 * Alan Cox : Broadcasting without option set returns EACCES.
38 * Alan Cox : No wakeup calls. Instead we now use the callbacks.
39 * Alan Cox : Use ip_tos and ip_ttl
40 * Alan Cox : SNMP Mibs
41 * Alan Cox : MSG_DONTROUTE, and 0.0.0.0 support.
42 * Matt Dillon : UDP length checks.
43 * Alan Cox : Smarter af_inet used properly.
44 * Alan Cox : Use new kernel side addressing.
45 * Alan Cox : Incorrect return on truncated datagram receive.
46 * Arnt Gulbrandsen : New udp_send and stuff
47 * Alan Cox : Cache last socket
48 * Alan Cox : Route cache
49 * Jon Peatfield : Minor efficiency fix to sendto().
50 * Mike Shaver : RFC1122 checks.
51 * Alan Cox : Nonblocking error fix.
52 * Willy Konynenberg : Transparent proxying support.
53 * Mike McLagan : Routing by source
54 * David S. Miller : New socket lookup architecture.
55 * Last socket cache retained as it
56 * does have a high hit rate.
57 * Olaf Kirch : Don't linearise iovec on sendmsg.
58 * Andi Kleen : Some cleanups, cache destination entry
60 * Vitaly E. Lavrov : Transparent proxy revived after year coma.
61 * Melvin Smith : Check msg_name not msg_namelen in sendto(),
62 * return ENOTCONN for unconnected sockets (POSIX)
63 * Janos Farkas : don't deliver multi/broadcasts to a different
64 * bound-to-device socket
65 * Hirokazu Takahashi : HW checksumming for outgoing UDP
67 * Hirokazu Takahashi : sendfile() on UDP works now.
68 * Arnaldo C. Melo : convert /proc/net/udp to seq_file
69 * YOSHIFUJI Hideaki @USAGI and: Support IPV6_V6ONLY socket option, which
70 * Alexey Kuznetsov: allow both IPv4 and IPv6 sockets to bind
71 * a single port at the same time.
72 * Derek Atkins <derek@ihtfp.com>: Add Encapulation Support
75 * This program is free software; you can redistribute it and/or
76 * modify it under the terms of the GNU General Public License
77 * as published by the Free Software Foundation; either version
78 * 2 of the License, or (at your option) any later version.
81 #include <asm/system.h>
82 #include <asm/uaccess.h>
83 #include <asm/ioctls.h>
84 #include <linux/types.h>
85 #include <linux/fcntl.h>
86 #include <linux/module.h>
87 #include <linux/socket.h>
88 #include <linux/sockios.h>
89 #include <linux/igmp.h>
91 #include <linux/errno.h>
92 #include <linux/timer.h>
94 #include <linux/inet.h>
95 #include <linux/ipv6.h>
96 #include <linux/netdevice.h>
99 #include <net/tcp_states.h>
100 #include <net/protocol.h>
101 #include <linux/skbuff.h>
102 #include <linux/proc_fs.h>
103 #include <linux/seq_file.h>
104 #include <net/sock.h>
106 #include <net/icmp.h>
107 #include <net/route.h>
108 #include <net/inet_common.h>
109 #include <net/checksum.h>
110 #include <net/xfrm.h>
113 * Snmp MIB for the UDP layer
116 DEFINE_SNMP_STAT(struct udp_mib, udp_statistics) __read_mostly;
118 struct hlist_head udp_hash[UDP_HTABLE_SIZE];
119 DEFINE_RWLOCK(udp_hash_lock);
121 static int udp_port_rover;
123 static inline int udp_lport_inuse(u16 num)
126 struct hlist_node *node;
128 sk_for_each(sk, node, &udp_hash[num & (UDP_HTABLE_SIZE - 1)])
129 if (inet_sk(sk)->num == num)
135 * udp_get_port - common port lookup for IPv4 and IPv6
137 * @sk: socket struct in question
138 * @snum: port number to look up
139 * @saddr_comp: AF-dependent comparison of bound local IP addresses
141 int udp_get_port(struct sock *sk, unsigned short snum,
142 int (*saddr_cmp)(const struct sock *sk1, const struct sock *sk2))
144 struct hlist_node *node;
145 struct hlist_head *head;
149 write_lock_bh(&udp_hash_lock);
151 int best_size_so_far, best, result, i;
153 if (udp_port_rover > sysctl_local_port_range[1] ||
154 udp_port_rover < sysctl_local_port_range[0])
155 udp_port_rover = sysctl_local_port_range[0];
156 best_size_so_far = 32767;
157 best = result = udp_port_rover;
158 for (i = 0; i < UDP_HTABLE_SIZE; i++, result++) {
161 head = &udp_hash[result & (UDP_HTABLE_SIZE - 1)];
162 if (hlist_empty(head)) {
163 if (result > sysctl_local_port_range[1])
164 result = sysctl_local_port_range[0] +
165 ((result - sysctl_local_port_range[0]) &
166 (UDP_HTABLE_SIZE - 1));
170 sk_for_each(sk2, node, head)
171 if (++size < best_size_so_far) {
172 best_size_so_far = size;
177 for(i = 0; i < (1 << 16) / UDP_HTABLE_SIZE; i++, result += UDP_HTABLE_SIZE) {
178 if (result > sysctl_local_port_range[1])
179 result = sysctl_local_port_range[0]
180 + ((result - sysctl_local_port_range[0]) &
181 (UDP_HTABLE_SIZE - 1));
182 if (!udp_lport_inuse(result))
185 if (i >= (1 << 16) / UDP_HTABLE_SIZE)
188 udp_port_rover = snum = result;
190 head = &udp_hash[snum & (UDP_HTABLE_SIZE - 1)];
192 sk_for_each(sk2, node, head)
193 if (inet_sk(sk2)->num == snum &&
195 (!sk2->sk_reuse || !sk->sk_reuse) &&
196 (!sk2->sk_bound_dev_if || !sk->sk_bound_dev_if
197 || sk2->sk_bound_dev_if == sk->sk_bound_dev_if) &&
198 (*saddr_cmp)(sk, sk2) )
201 inet_sk(sk)->num = snum;
202 if (sk_unhashed(sk)) {
203 head = &udp_hash[snum & (UDP_HTABLE_SIZE - 1)];
204 sk_add_node(sk, head);
205 sock_prot_inc_use(sk->sk_prot);
209 write_unlock_bh(&udp_hash_lock);
213 static inline int ipv4_rcv_saddr_equal(const struct sock *sk1, const struct sock *sk2)
215 struct inet_sock *inet1 = inet_sk(sk1), *inet2 = inet_sk(sk2);
217 return ( !ipv6_only_sock(sk2) &&
218 (!inet1->rcv_saddr || !inet2->rcv_saddr ||
219 inet1->rcv_saddr == inet2->rcv_saddr ));
222 static inline int udp_v4_get_port(struct sock *sk, unsigned short snum)
224 return udp_get_port(sk, snum, ipv4_rcv_saddr_equal);
228 static void udp_v4_hash(struct sock *sk)
233 static void udp_v4_unhash(struct sock *sk)
235 write_lock_bh(&udp_hash_lock);
236 if (sk_del_node_init(sk)) {
237 inet_sk(sk)->num = 0;
238 sock_prot_dec_use(sk->sk_prot);
240 write_unlock_bh(&udp_hash_lock);
243 /* UDP is nearly always wildcards out the wazoo, it makes no sense to try
244 * harder than this. -DaveM
246 static struct sock *udp_v4_lookup_longway(__be32 saddr, __be16 sport,
247 __be32 daddr, __be16 dport, int dif)
249 struct sock *sk, *result = NULL;
250 struct hlist_node *node;
251 unsigned short hnum = ntohs(dport);
254 sk_for_each(sk, node, &udp_hash[hnum & (UDP_HTABLE_SIZE - 1)]) {
255 struct inet_sock *inet = inet_sk(sk);
257 if (inet->num == hnum && !ipv6_only_sock(sk)) {
258 int score = (sk->sk_family == PF_INET ? 1 : 0);
259 if (inet->rcv_saddr) {
260 if (inet->rcv_saddr != daddr)
265 if (inet->daddr != saddr)
270 if (inet->dport != sport)
274 if (sk->sk_bound_dev_if) {
275 if (sk->sk_bound_dev_if != dif)
282 } else if(score > badness) {
291 static __inline__ struct sock *udp_v4_lookup(__be32 saddr, __be16 sport,
292 __be32 daddr, __be16 dport, int dif)
296 read_lock(&udp_hash_lock);
297 sk = udp_v4_lookup_longway(saddr, sport, daddr, dport, dif);
300 read_unlock(&udp_hash_lock);
304 static inline struct sock *udp_v4_mcast_next(struct sock *sk,
305 __be16 loc_port, __be32 loc_addr,
306 __be16 rmt_port, __be32 rmt_addr,
309 struct hlist_node *node;
311 unsigned short hnum = ntohs(loc_port);
313 sk_for_each_from(s, node) {
314 struct inet_sock *inet = inet_sk(s);
316 if (inet->num != hnum ||
317 (inet->daddr && inet->daddr != rmt_addr) ||
318 (inet->dport != rmt_port && inet->dport) ||
319 (inet->rcv_saddr && inet->rcv_saddr != loc_addr) ||
321 (s->sk_bound_dev_if && s->sk_bound_dev_if != dif))
323 if (!ip_mc_sf_allow(s, loc_addr, rmt_addr, dif))
333 * This routine is called by the ICMP module when it gets some
334 * sort of error condition. If err < 0 then the socket should
335 * be closed and the error returned to the user. If err > 0
336 * it's just the icmp type << 8 | icmp code.
337 * Header points to the ip header of the error packet. We move
338 * on past this. Then (as it used to claim before adjustment)
339 * header points to the first 8 bytes of the udp header. We need
340 * to find the appropriate port.
343 void udp_err(struct sk_buff *skb, u32 info)
345 struct inet_sock *inet;
346 struct iphdr *iph = (struct iphdr*)skb->data;
347 struct udphdr *uh = (struct udphdr*)(skb->data+(iph->ihl<<2));
348 int type = skb->h.icmph->type;
349 int code = skb->h.icmph->code;
354 sk = udp_v4_lookup(iph->daddr, uh->dest, iph->saddr, uh->source, skb->dev->ifindex);
356 ICMP_INC_STATS_BH(ICMP_MIB_INERRORS);
357 return; /* No socket for error */
366 case ICMP_TIME_EXCEEDED:
369 case ICMP_SOURCE_QUENCH:
371 case ICMP_PARAMETERPROB:
375 case ICMP_DEST_UNREACH:
376 if (code == ICMP_FRAG_NEEDED) { /* Path MTU discovery */
377 if (inet->pmtudisc != IP_PMTUDISC_DONT) {
385 if (code <= NR_ICMP_UNREACH) {
386 harderr = icmp_err_convert[code].fatal;
387 err = icmp_err_convert[code].errno;
393 * RFC1122: OK. Passes ICMP errors back to application, as per
396 if (!inet->recverr) {
397 if (!harderr || sk->sk_state != TCP_ESTABLISHED)
400 ip_icmp_error(sk, skb, err, uh->dest, info, (u8*)(uh+1));
403 sk->sk_error_report(sk);
409 * Throw away all pending data and cancel the corking. Socket is locked.
411 static void udp_flush_pending_frames(struct sock *sk)
413 struct udp_sock *up = udp_sk(sk);
418 ip_flush_pending_frames(sk);
423 * Push out all pending data as one UDP datagram. Socket is locked.
425 static int udp_push_pending_frames(struct sock *sk, struct udp_sock *up)
427 struct inet_sock *inet = inet_sk(sk);
428 struct flowi *fl = &inet->cork.fl;
433 /* Grab the skbuff where UDP header space exists. */
434 if ((skb = skb_peek(&sk->sk_write_queue)) == NULL)
438 * Create a UDP header
441 uh->source = fl->fl_ip_sport;
442 uh->dest = fl->fl_ip_dport;
443 uh->len = htons(up->len);
446 if (sk->sk_no_check == UDP_CSUM_NOXMIT) {
447 skb->ip_summed = CHECKSUM_NONE;
451 if (skb_queue_len(&sk->sk_write_queue) == 1) {
453 * Only one fragment on the socket.
455 if (skb->ip_summed == CHECKSUM_PARTIAL) {
456 skb->csum = offsetof(struct udphdr, check);
457 uh->check = ~csum_tcpudp_magic(fl->fl4_src, fl->fl4_dst,
458 up->len, IPPROTO_UDP, 0);
460 skb->csum = csum_partial((char *)uh,
461 sizeof(struct udphdr), skb->csum);
462 uh->check = csum_tcpudp_magic(fl->fl4_src, fl->fl4_dst,
463 up->len, IPPROTO_UDP, skb->csum);
468 unsigned int csum = 0;
470 * HW-checksum won't work as there are two or more
471 * fragments on the socket so that all csums of sk_buffs
472 * should be together.
474 if (skb->ip_summed == CHECKSUM_PARTIAL) {
475 int offset = (unsigned char *)uh - skb->data;
476 skb->csum = skb_checksum(skb, offset, skb->len - offset, 0);
478 skb->ip_summed = CHECKSUM_NONE;
480 skb->csum = csum_partial((char *)uh,
481 sizeof(struct udphdr), skb->csum);
484 skb_queue_walk(&sk->sk_write_queue, skb) {
485 csum = csum_add(csum, skb->csum);
487 uh->check = csum_tcpudp_magic(fl->fl4_src, fl->fl4_dst,
488 up->len, IPPROTO_UDP, csum);
493 err = ip_push_pending_frames(sk);
501 static unsigned short udp_check(struct udphdr *uh, int len, __be32 saddr, __be32 daddr, unsigned long base)
503 return(csum_tcpudp_magic(saddr, daddr, len, IPPROTO_UDP, base));
506 int udp_sendmsg(struct kiocb *iocb, struct sock *sk, struct msghdr *msg,
509 struct inet_sock *inet = inet_sk(sk);
510 struct udp_sock *up = udp_sk(sk);
512 struct ipcm_cookie ipc;
513 struct rtable *rt = NULL;
516 __be32 daddr, faddr, saddr;
520 int corkreq = up->corkflag || msg->msg_flags&MSG_MORE;
529 if (msg->msg_flags&MSG_OOB) /* Mirror BSD error message compatibility */
536 * There are pending frames.
537 * The socket lock must be held while it's corked.
540 if (likely(up->pending)) {
541 if (unlikely(up->pending != AF_INET)) {
549 ulen += sizeof(struct udphdr);
552 * Get and verify the address.
555 struct sockaddr_in * usin = (struct sockaddr_in*)msg->msg_name;
556 if (msg->msg_namelen < sizeof(*usin))
558 if (usin->sin_family != AF_INET) {
559 if (usin->sin_family != AF_UNSPEC)
560 return -EAFNOSUPPORT;
563 daddr = usin->sin_addr.s_addr;
564 dport = usin->sin_port;
568 if (sk->sk_state != TCP_ESTABLISHED)
569 return -EDESTADDRREQ;
572 /* Open fast path for connected socket.
573 Route will not be used, if at least one option is set.
577 ipc.addr = inet->saddr;
579 ipc.oif = sk->sk_bound_dev_if;
580 if (msg->msg_controllen) {
581 err = ip_cmsg_send(msg, &ipc);
592 ipc.addr = faddr = daddr;
594 if (ipc.opt && ipc.opt->srr) {
597 faddr = ipc.opt->faddr;
600 tos = RT_TOS(inet->tos);
601 if (sock_flag(sk, SOCK_LOCALROUTE) ||
602 (msg->msg_flags & MSG_DONTROUTE) ||
603 (ipc.opt && ipc.opt->is_strictroute)) {
608 if (MULTICAST(daddr)) {
610 ipc.oif = inet->mc_index;
612 saddr = inet->mc_addr;
617 rt = (struct rtable*)sk_dst_check(sk, 0);
620 struct flowi fl = { .oif = ipc.oif,
625 .proto = IPPROTO_UDP,
627 { .sport = inet->sport,
628 .dport = dport } } };
629 security_sk_classify_flow(sk, &fl);
630 err = ip_route_output_flow(&rt, &fl, sk, !(msg->msg_flags&MSG_DONTWAIT));
635 if ((rt->rt_flags & RTCF_BROADCAST) &&
636 !sock_flag(sk, SOCK_BROADCAST))
639 sk_dst_set(sk, dst_clone(&rt->u.dst));
642 if (msg->msg_flags&MSG_CONFIRM)
648 daddr = ipc.addr = rt->rt_dst;
651 if (unlikely(up->pending)) {
652 /* The socket is already corked while preparing it. */
653 /* ... which is an evident application bug. --ANK */
656 LIMIT_NETDEBUG(KERN_DEBUG "udp cork app bug 2\n");
661 * Now cork the socket to pend data.
663 inet->cork.fl.fl4_dst = daddr;
664 inet->cork.fl.fl_ip_dport = dport;
665 inet->cork.fl.fl4_src = saddr;
666 inet->cork.fl.fl_ip_sport = inet->sport;
667 up->pending = AF_INET;
671 err = ip_append_data(sk, ip_generic_getfrag, msg->msg_iov, ulen,
672 sizeof(struct udphdr), &ipc, rt,
673 corkreq ? msg->msg_flags|MSG_MORE : msg->msg_flags);
675 udp_flush_pending_frames(sk);
677 err = udp_push_pending_frames(sk, up);
678 else if (unlikely(skb_queue_empty(&sk->sk_write_queue)))
687 UDP_INC_STATS_USER(UDP_MIB_OUTDATAGRAMS);
691 * ENOBUFS = no kernel mem, SOCK_NOSPACE = no sndbuf space. Reporting
692 * ENOBUFS might not be good (it's not tunable per se), but otherwise
693 * we don't have a good statistic (IpOutDiscards but it can be too many
694 * things). We could add another new stat but at least for now that
695 * seems like overkill.
697 if (err == -ENOBUFS || test_bit(SOCK_NOSPACE, &sk->sk_socket->flags)) {
698 UDP_INC_STATS_USER(UDP_MIB_SNDBUFERRORS);
703 dst_confirm(&rt->u.dst);
704 if (!(msg->msg_flags&MSG_PROBE) || len)
705 goto back_from_confirm;
710 static int udp_sendpage(struct sock *sk, struct page *page, int offset,
711 size_t size, int flags)
713 struct udp_sock *up = udp_sk(sk);
717 struct msghdr msg = { .msg_flags = flags|MSG_MORE };
719 /* Call udp_sendmsg to specify destination address which
720 * sendpage interface can't pass.
721 * This will succeed only when the socket is connected.
723 ret = udp_sendmsg(NULL, sk, &msg, 0);
730 if (unlikely(!up->pending)) {
733 LIMIT_NETDEBUG(KERN_DEBUG "udp cork app bug 3\n");
737 ret = ip_append_page(sk, page, offset, size, flags);
738 if (ret == -EOPNOTSUPP) {
740 return sock_no_sendpage(sk->sk_socket, page, offset,
744 udp_flush_pending_frames(sk);
749 if (!(up->corkflag || (flags&MSG_MORE)))
750 ret = udp_push_pending_frames(sk, up);
759 * IOCTL requests applicable to the UDP protocol
762 int udp_ioctl(struct sock *sk, int cmd, unsigned long arg)
768 int amount = atomic_read(&sk->sk_wmem_alloc);
769 return put_user(amount, (int __user *)arg);
775 unsigned long amount;
778 spin_lock_bh(&sk->sk_receive_queue.lock);
779 skb = skb_peek(&sk->sk_receive_queue);
782 * We will only return the amount
783 * of this packet since that is all
786 amount = skb->len - sizeof(struct udphdr);
788 spin_unlock_bh(&sk->sk_receive_queue.lock);
789 return put_user(amount, (int __user *)arg);
798 static __inline__ int __udp_checksum_complete(struct sk_buff *skb)
800 return __skb_checksum_complete(skb);
803 static __inline__ int udp_checksum_complete(struct sk_buff *skb)
805 return skb->ip_summed != CHECKSUM_UNNECESSARY &&
806 __udp_checksum_complete(skb);
810 * This should be easy, if there is something there we
811 * return it, otherwise we block.
814 static int udp_recvmsg(struct kiocb *iocb, struct sock *sk, struct msghdr *msg,
815 size_t len, int noblock, int flags, int *addr_len)
817 struct inet_sock *inet = inet_sk(sk);
818 struct sockaddr_in *sin = (struct sockaddr_in *)msg->msg_name;
823 * Check any passed addresses
826 *addr_len=sizeof(*sin);
828 if (flags & MSG_ERRQUEUE)
829 return ip_recv_error(sk, msg, len);
832 skb = skb_recv_datagram(sk, flags, noblock, &err);
836 copied = skb->len - sizeof(struct udphdr);
839 msg->msg_flags |= MSG_TRUNC;
842 if (skb->ip_summed==CHECKSUM_UNNECESSARY) {
843 err = skb_copy_datagram_iovec(skb, sizeof(struct udphdr), msg->msg_iov,
845 } else if (msg->msg_flags&MSG_TRUNC) {
846 if (__udp_checksum_complete(skb))
848 err = skb_copy_datagram_iovec(skb, sizeof(struct udphdr), msg->msg_iov,
851 err = skb_copy_and_csum_datagram_iovec(skb, sizeof(struct udphdr), msg->msg_iov);
860 sock_recv_timestamp(msg, sk, skb);
862 /* Copy the address. */
865 sin->sin_family = AF_INET;
866 sin->sin_port = skb->h.uh->source;
867 sin->sin_addr.s_addr = skb->nh.iph->saddr;
868 memset(sin->sin_zero, 0, sizeof(sin->sin_zero));
870 if (inet->cmsg_flags)
871 ip_cmsg_recv(msg, skb);
874 if (flags & MSG_TRUNC)
875 err = skb->len - sizeof(struct udphdr);
878 skb_free_datagram(sk, skb);
883 UDP_INC_STATS_BH(UDP_MIB_INERRORS);
885 skb_kill_datagram(sk, skb, flags);
893 int udp_disconnect(struct sock *sk, int flags)
895 struct inet_sock *inet = inet_sk(sk);
897 * 1003.1g - break association.
900 sk->sk_state = TCP_CLOSE;
903 sk->sk_bound_dev_if = 0;
904 if (!(sk->sk_userlocks & SOCK_BINDADDR_LOCK))
905 inet_reset_saddr(sk);
907 if (!(sk->sk_userlocks & SOCK_BINDPORT_LOCK)) {
908 sk->sk_prot->unhash(sk);
915 static void udp_close(struct sock *sk, long timeout)
917 sk_common_release(sk);
921 * 1 if the the UDP system should process it
922 * 0 if we should drop this packet
923 * -1 if it should get processed by xfrm4_rcv_encap
925 static int udp_encap_rcv(struct sock * sk, struct sk_buff *skb)
930 struct udp_sock *up = udp_sk(sk);
937 __u16 encap_type = up->encap_type;
939 /* if we're overly short, let UDP handle it */
940 len = skb->len - sizeof(struct udphdr);
944 /* if this is not encapsulated socket, then just return now */
948 /* If this is a paged skb, make sure we pull up
949 * whatever data we need to look at. */
950 if (!pskb_may_pull(skb, sizeof(struct udphdr) + min(len, 8)))
953 /* Now we can get the pointers */
955 udpdata = (__u8 *)uh + sizeof(struct udphdr);
956 udpdata32 = (__be32 *)udpdata;
958 switch (encap_type) {
960 case UDP_ENCAP_ESPINUDP:
961 /* Check if this is a keepalive packet. If so, eat it. */
962 if (len == 1 && udpdata[0] == 0xff) {
964 } else if (len > sizeof(struct ip_esp_hdr) && udpdata32[0] != 0 ) {
965 /* ESP Packet without Non-ESP header */
966 len = sizeof(struct udphdr);
968 /* Must be an IKE packet.. pass it through */
971 case UDP_ENCAP_ESPINUDP_NON_IKE:
972 /* Check if this is a keepalive packet. If so, eat it. */
973 if (len == 1 && udpdata[0] == 0xff) {
975 } else if (len > 2 * sizeof(u32) + sizeof(struct ip_esp_hdr) &&
976 udpdata32[0] == 0 && udpdata32[1] == 0) {
978 /* ESP Packet with Non-IKE marker */
979 len = sizeof(struct udphdr) + 2 * sizeof(u32);
981 /* Must be an IKE packet.. pass it through */
986 /* At this point we are sure that this is an ESPinUDP packet,
987 * so we need to remove 'len' bytes from the packet (the UDP
988 * header and optional ESP marker bytes) and then modify the
989 * protocol to ESP, and then call into the transform receiver.
991 if (skb_cloned(skb) && pskb_expand_head(skb, 0, 0, GFP_ATOMIC))
994 /* Now we can update and verify the packet length... */
996 iphlen = iph->ihl << 2;
997 iph->tot_len = htons(ntohs(iph->tot_len) - len);
998 if (skb->len < iphlen + len) {
999 /* packet is too small!?! */
1003 /* pull the data buffer up to the ESP header and set the
1004 * transport header to point to ESP. Keep UDP on the stack
1007 skb->h.raw = skb_pull(skb, len);
1009 /* modify the protocol (it's ESP!) */
1010 iph->protocol = IPPROTO_ESP;
1012 /* and let the caller know to send this into the ESP processor... */
1020 * >0: "udp encap" protocol resubmission
1022 * Note that in the success and error cases, the skb is assumed to
1023 * have either been requeued or freed.
1025 static int udp_queue_rcv_skb(struct sock * sk, struct sk_buff *skb)
1027 struct udp_sock *up = udp_sk(sk);
1031 * Charge it to the socket, dropping if the queue is full.
1033 if (!xfrm4_policy_check(sk, XFRM_POLICY_IN, skb)) {
1039 if (up->encap_type) {
1041 * This is an encapsulation socket, so let's see if this is
1042 * an encapsulated packet.
1043 * If it's a keepalive packet, then just eat it.
1044 * If it's an encapsulateed packet, then pass it to the
1045 * IPsec xfrm input and return the response
1046 * appropriately. Otherwise, just fall through and
1047 * pass this up the UDP socket.
1051 ret = udp_encap_rcv(sk, skb);
1053 /* Eat the packet .. */
1058 /* process the ESP packet */
1059 ret = xfrm4_rcv_encap(skb, up->encap_type);
1060 UDP_INC_STATS_BH(UDP_MIB_INDATAGRAMS);
1063 /* FALLTHROUGH -- it's a UDP Packet */
1066 if (sk->sk_filter && skb->ip_summed != CHECKSUM_UNNECESSARY) {
1067 if (__udp_checksum_complete(skb)) {
1068 UDP_INC_STATS_BH(UDP_MIB_INERRORS);
1072 skb->ip_summed = CHECKSUM_UNNECESSARY;
1075 if ((rc = sock_queue_rcv_skb(sk,skb)) < 0) {
1076 /* Note that an ENOMEM error is charged twice */
1078 UDP_INC_STATS_BH(UDP_MIB_RCVBUFERRORS);
1079 UDP_INC_STATS_BH(UDP_MIB_INERRORS);
1083 UDP_INC_STATS_BH(UDP_MIB_INDATAGRAMS);
1088 * Multicasts and broadcasts go to each listener.
1090 * Note: called only from the BH handler context,
1091 * so we don't need to lock the hashes.
1093 static int udp_v4_mcast_deliver(struct sk_buff *skb, struct udphdr *uh,
1094 __be32 saddr, __be32 daddr)
1099 read_lock(&udp_hash_lock);
1100 sk = sk_head(&udp_hash[ntohs(uh->dest) & (UDP_HTABLE_SIZE - 1)]);
1101 dif = skb->dev->ifindex;
1102 sk = udp_v4_mcast_next(sk, uh->dest, daddr, uh->source, saddr, dif);
1104 struct sock *sknext = NULL;
1107 struct sk_buff *skb1 = skb;
1109 sknext = udp_v4_mcast_next(sk_next(sk), uh->dest, daddr,
1110 uh->source, saddr, dif);
1112 skb1 = skb_clone(skb, GFP_ATOMIC);
1115 int ret = udp_queue_rcv_skb(sk, skb1);
1117 /* we should probably re-process instead
1118 * of dropping packets here. */
1125 read_unlock(&udp_hash_lock);
1129 /* Initialize UDP checksum. If exited with zero value (success),
1130 * CHECKSUM_UNNECESSARY means, that no more checks are required.
1131 * Otherwise, csum completion requires chacksumming packet body,
1132 * including udp header and folding it to skb->csum.
1134 static void udp_checksum_init(struct sk_buff *skb, struct udphdr *uh,
1135 unsigned short ulen, __be32 saddr, __be32 daddr)
1137 if (uh->check == 0) {
1138 skb->ip_summed = CHECKSUM_UNNECESSARY;
1139 } else if (skb->ip_summed == CHECKSUM_COMPLETE) {
1140 if (!udp_check(uh, ulen, saddr, daddr, skb->csum))
1141 skb->ip_summed = CHECKSUM_UNNECESSARY;
1143 if (skb->ip_summed != CHECKSUM_UNNECESSARY)
1144 skb->csum = csum_tcpudp_nofold(saddr, daddr, ulen, IPPROTO_UDP, 0);
1145 /* Probably, we should checksum udp header (it should be in cache
1146 * in any case) and data in tiny packets (< rx copybreak).
1151 * All we need to do is get the socket, and then do a checksum.
1154 int udp_rcv(struct sk_buff *skb)
1158 unsigned short ulen;
1159 struct rtable *rt = (struct rtable*)skb->dst;
1160 __be32 saddr = skb->nh.iph->saddr;
1161 __be32 daddr = skb->nh.iph->daddr;
1165 * Validate the packet and the UDP length.
1167 if (!pskb_may_pull(skb, sizeof(struct udphdr)))
1172 ulen = ntohs(uh->len);
1174 if (ulen > len || ulen < sizeof(*uh))
1177 if (pskb_trim_rcsum(skb, ulen))
1180 udp_checksum_init(skb, uh, ulen, saddr, daddr);
1182 if(rt->rt_flags & (RTCF_BROADCAST|RTCF_MULTICAST))
1183 return udp_v4_mcast_deliver(skb, uh, saddr, daddr);
1185 sk = udp_v4_lookup(saddr, uh->source, daddr, uh->dest, skb->dev->ifindex);
1188 int ret = udp_queue_rcv_skb(sk, skb);
1191 /* a return value > 0 means to resubmit the input, but
1192 * it it wants the return to be -protocol, or 0
1199 if (!xfrm4_policy_check(NULL, XFRM_POLICY_IN, skb))
1203 /* No socket. Drop packet silently, if checksum is wrong */
1204 if (udp_checksum_complete(skb))
1207 UDP_INC_STATS_BH(UDP_MIB_NOPORTS);
1208 icmp_send(skb, ICMP_DEST_UNREACH, ICMP_PORT_UNREACH, 0);
1211 * Hmm. We got an UDP packet to a port to which we
1212 * don't wanna listen. Ignore it.
1218 LIMIT_NETDEBUG(KERN_DEBUG "UDP: short packet: From %u.%u.%u.%u:%u %d/%d to %u.%u.%u.%u:%u\n",
1226 UDP_INC_STATS_BH(UDP_MIB_INERRORS);
1232 * RFC1122: OK. Discards the bad packet silently (as far as
1233 * the network is concerned, anyway) as per 4.1.3.4 (MUST).
1235 LIMIT_NETDEBUG(KERN_DEBUG "UDP: bad checksum. From %d.%d.%d.%d:%d to %d.%d.%d.%d:%d ulen %d\n",
1242 UDP_INC_STATS_BH(UDP_MIB_INERRORS);
1247 static int udp_destroy_sock(struct sock *sk)
1250 udp_flush_pending_frames(sk);
1256 * Socket option code for UDP
1258 static int do_udp_setsockopt(struct sock *sk, int level, int optname,
1259 char __user *optval, int optlen)
1261 struct udp_sock *up = udp_sk(sk);
1265 if(optlen<sizeof(int))
1268 if (get_user(val, (int __user *)optval))
1278 udp_push_pending_frames(sk, up);
1286 case UDP_ENCAP_ESPINUDP:
1287 case UDP_ENCAP_ESPINUDP_NON_IKE:
1288 up->encap_type = val;
1304 static int udp_setsockopt(struct sock *sk, int level, int optname,
1305 char __user *optval, int optlen)
1307 if (level != SOL_UDP)
1308 return ip_setsockopt(sk, level, optname, optval, optlen);
1309 return do_udp_setsockopt(sk, level, optname, optval, optlen);
1312 #ifdef CONFIG_COMPAT
1313 static int compat_udp_setsockopt(struct sock *sk, int level, int optname,
1314 char __user *optval, int optlen)
1316 if (level != SOL_UDP)
1317 return compat_ip_setsockopt(sk, level, optname, optval, optlen);
1318 return do_udp_setsockopt(sk, level, optname, optval, optlen);
1322 static int do_udp_getsockopt(struct sock *sk, int level, int optname,
1323 char __user *optval, int __user *optlen)
1325 struct udp_sock *up = udp_sk(sk);
1328 if(get_user(len,optlen))
1331 len = min_t(unsigned int, len, sizeof(int));
1342 val = up->encap_type;
1346 return -ENOPROTOOPT;
1349 if(put_user(len, optlen))
1351 if(copy_to_user(optval, &val,len))
1356 static int udp_getsockopt(struct sock *sk, int level, int optname,
1357 char __user *optval, int __user *optlen)
1359 if (level != SOL_UDP)
1360 return ip_getsockopt(sk, level, optname, optval, optlen);
1361 return do_udp_getsockopt(sk, level, optname, optval, optlen);
1364 #ifdef CONFIG_COMPAT
1365 static int compat_udp_getsockopt(struct sock *sk, int level, int optname,
1366 char __user *optval, int __user *optlen)
1368 if (level != SOL_UDP)
1369 return compat_ip_getsockopt(sk, level, optname, optval, optlen);
1370 return do_udp_getsockopt(sk, level, optname, optval, optlen);
1374 * udp_poll - wait for a UDP event.
1375 * @file - file struct
1377 * @wait - poll table
1379 * This is same as datagram poll, except for the special case of
1380 * blocking sockets. If application is using a blocking fd
1381 * and a packet with checksum error is in the queue;
1382 * then it could get return from select indicating data available
1383 * but then block when reading it. Add special case code
1384 * to work around these arguably broken applications.
1386 unsigned int udp_poll(struct file *file, struct socket *sock, poll_table *wait)
1388 unsigned int mask = datagram_poll(file, sock, wait);
1389 struct sock *sk = sock->sk;
1391 /* Check for false positives due to checksum errors */
1392 if ( (mask & POLLRDNORM) &&
1393 !(file->f_flags & O_NONBLOCK) &&
1394 !(sk->sk_shutdown & RCV_SHUTDOWN)){
1395 struct sk_buff_head *rcvq = &sk->sk_receive_queue;
1396 struct sk_buff *skb;
1398 spin_lock_bh(&rcvq->lock);
1399 while ((skb = skb_peek(rcvq)) != NULL) {
1400 if (udp_checksum_complete(skb)) {
1401 UDP_INC_STATS_BH(UDP_MIB_INERRORS);
1402 __skb_unlink(skb, rcvq);
1405 skb->ip_summed = CHECKSUM_UNNECESSARY;
1409 spin_unlock_bh(&rcvq->lock);
1411 /* nothing to see, move along */
1413 mask &= ~(POLLIN | POLLRDNORM);
1420 struct proto udp_prot = {
1422 .owner = THIS_MODULE,
1424 .connect = ip4_datagram_connect,
1425 .disconnect = udp_disconnect,
1427 .destroy = udp_destroy_sock,
1428 .setsockopt = udp_setsockopt,
1429 .getsockopt = udp_getsockopt,
1430 .sendmsg = udp_sendmsg,
1431 .recvmsg = udp_recvmsg,
1432 .sendpage = udp_sendpage,
1433 .backlog_rcv = udp_queue_rcv_skb,
1434 .hash = udp_v4_hash,
1435 .unhash = udp_v4_unhash,
1436 .get_port = udp_v4_get_port,
1437 .obj_size = sizeof(struct udp_sock),
1438 #ifdef CONFIG_COMPAT
1439 .compat_setsockopt = compat_udp_setsockopt,
1440 .compat_getsockopt = compat_udp_getsockopt,
1444 /* ------------------------------------------------------------------------ */
1445 #ifdef CONFIG_PROC_FS
1447 static struct sock *udp_get_first(struct seq_file *seq)
1450 struct udp_iter_state *state = seq->private;
1452 for (state->bucket = 0; state->bucket < UDP_HTABLE_SIZE; ++state->bucket) {
1453 struct hlist_node *node;
1454 sk_for_each(sk, node, &udp_hash[state->bucket]) {
1455 if (sk->sk_family == state->family)
1464 static struct sock *udp_get_next(struct seq_file *seq, struct sock *sk)
1466 struct udp_iter_state *state = seq->private;
1472 } while (sk && sk->sk_family != state->family);
1474 if (!sk && ++state->bucket < UDP_HTABLE_SIZE) {
1475 sk = sk_head(&udp_hash[state->bucket]);
1481 static struct sock *udp_get_idx(struct seq_file *seq, loff_t pos)
1483 struct sock *sk = udp_get_first(seq);
1486 while(pos && (sk = udp_get_next(seq, sk)) != NULL)
1488 return pos ? NULL : sk;
1491 static void *udp_seq_start(struct seq_file *seq, loff_t *pos)
1493 read_lock(&udp_hash_lock);
1494 return *pos ? udp_get_idx(seq, *pos-1) : (void *)1;
1497 static void *udp_seq_next(struct seq_file *seq, void *v, loff_t *pos)
1502 sk = udp_get_idx(seq, 0);
1504 sk = udp_get_next(seq, v);
1510 static void udp_seq_stop(struct seq_file *seq, void *v)
1512 read_unlock(&udp_hash_lock);
1515 static int udp_seq_open(struct inode *inode, struct file *file)
1517 struct udp_seq_afinfo *afinfo = PDE(inode)->data;
1518 struct seq_file *seq;
1520 struct udp_iter_state *s = kzalloc(sizeof(*s), GFP_KERNEL);
1524 s->family = afinfo->family;
1525 s->seq_ops.start = udp_seq_start;
1526 s->seq_ops.next = udp_seq_next;
1527 s->seq_ops.show = afinfo->seq_show;
1528 s->seq_ops.stop = udp_seq_stop;
1530 rc = seq_open(file, &s->seq_ops);
1534 seq = file->private_data;
1543 /* ------------------------------------------------------------------------ */
1544 int udp_proc_register(struct udp_seq_afinfo *afinfo)
1546 struct proc_dir_entry *p;
1551 afinfo->seq_fops->owner = afinfo->owner;
1552 afinfo->seq_fops->open = udp_seq_open;
1553 afinfo->seq_fops->read = seq_read;
1554 afinfo->seq_fops->llseek = seq_lseek;
1555 afinfo->seq_fops->release = seq_release_private;
1557 p = proc_net_fops_create(afinfo->name, S_IRUGO, afinfo->seq_fops);
1565 void udp_proc_unregister(struct udp_seq_afinfo *afinfo)
1569 proc_net_remove(afinfo->name);
1570 memset(afinfo->seq_fops, 0, sizeof(*afinfo->seq_fops));
1573 /* ------------------------------------------------------------------------ */
1574 static void udp4_format_sock(struct sock *sp, char *tmpbuf, int bucket)
1576 struct inet_sock *inet = inet_sk(sp);
1577 __be32 dest = inet->daddr;
1578 __be32 src = inet->rcv_saddr;
1579 __u16 destp = ntohs(inet->dport);
1580 __u16 srcp = ntohs(inet->sport);
1582 sprintf(tmpbuf, "%4d: %08X:%04X %08X:%04X"
1583 " %02X %08X:%08X %02X:%08lX %08X %5d %8d %lu %d %p",
1584 bucket, src, srcp, dest, destp, sp->sk_state,
1585 atomic_read(&sp->sk_wmem_alloc),
1586 atomic_read(&sp->sk_rmem_alloc),
1587 0, 0L, 0, sock_i_uid(sp), 0, sock_i_ino(sp),
1588 atomic_read(&sp->sk_refcnt), sp);
1591 static int udp4_seq_show(struct seq_file *seq, void *v)
1593 if (v == SEQ_START_TOKEN)
1594 seq_printf(seq, "%-127s\n",
1595 " sl local_address rem_address st tx_queue "
1596 "rx_queue tr tm->when retrnsmt uid timeout "
1600 struct udp_iter_state *state = seq->private;
1602 udp4_format_sock(v, tmpbuf, state->bucket);
1603 seq_printf(seq, "%-127s\n", tmpbuf);
1608 /* ------------------------------------------------------------------------ */
1609 static struct file_operations udp4_seq_fops;
1610 static struct udp_seq_afinfo udp4_seq_afinfo = {
1611 .owner = THIS_MODULE,
1614 .seq_show = udp4_seq_show,
1615 .seq_fops = &udp4_seq_fops,
1618 int __init udp4_proc_init(void)
1620 return udp_proc_register(&udp4_seq_afinfo);
1623 void udp4_proc_exit(void)
1625 udp_proc_unregister(&udp4_seq_afinfo);
1627 #endif /* CONFIG_PROC_FS */
1629 EXPORT_SYMBOL(udp_disconnect);
1630 EXPORT_SYMBOL(udp_hash);
1631 EXPORT_SYMBOL(udp_hash_lock);
1632 EXPORT_SYMBOL(udp_ioctl);
1633 EXPORT_SYMBOL(udp_get_port);
1634 EXPORT_SYMBOL(udp_prot);
1635 EXPORT_SYMBOL(udp_sendmsg);
1636 EXPORT_SYMBOL(udp_poll);
1638 #ifdef CONFIG_PROC_FS
1639 EXPORT_SYMBOL(udp_proc_register);
1640 EXPORT_SYMBOL(udp_proc_unregister);