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);
685 UDP_INC_STATS_USER(UDP_MIB_OUTDATAGRAMS);
689 * ENOBUFS = no kernel mem, SOCK_NOSPACE = no sndbuf space. Reporting
690 * ENOBUFS might not be good (it's not tunable per se), but otherwise
691 * we don't have a good statistic (IpOutDiscards but it can be too many
692 * things). We could add another new stat but at least for now that
693 * seems like overkill.
695 if (err == -ENOBUFS || test_bit(SOCK_NOSPACE, &sk->sk_socket->flags)) {
696 UDP_INC_STATS_USER(UDP_MIB_SNDBUFERRORS);
701 dst_confirm(&rt->u.dst);
702 if (!(msg->msg_flags&MSG_PROBE) || len)
703 goto back_from_confirm;
708 static int udp_sendpage(struct sock *sk, struct page *page, int offset,
709 size_t size, int flags)
711 struct udp_sock *up = udp_sk(sk);
715 struct msghdr msg = { .msg_flags = flags|MSG_MORE };
717 /* Call udp_sendmsg to specify destination address which
718 * sendpage interface can't pass.
719 * This will succeed only when the socket is connected.
721 ret = udp_sendmsg(NULL, sk, &msg, 0);
728 if (unlikely(!up->pending)) {
731 LIMIT_NETDEBUG(KERN_DEBUG "udp cork app bug 3\n");
735 ret = ip_append_page(sk, page, offset, size, flags);
736 if (ret == -EOPNOTSUPP) {
738 return sock_no_sendpage(sk->sk_socket, page, offset,
742 udp_flush_pending_frames(sk);
747 if (!(up->corkflag || (flags&MSG_MORE)))
748 ret = udp_push_pending_frames(sk, up);
757 * IOCTL requests applicable to the UDP protocol
760 int udp_ioctl(struct sock *sk, int cmd, unsigned long arg)
766 int amount = atomic_read(&sk->sk_wmem_alloc);
767 return put_user(amount, (int __user *)arg);
773 unsigned long amount;
776 spin_lock_bh(&sk->sk_receive_queue.lock);
777 skb = skb_peek(&sk->sk_receive_queue);
780 * We will only return the amount
781 * of this packet since that is all
784 amount = skb->len - sizeof(struct udphdr);
786 spin_unlock_bh(&sk->sk_receive_queue.lock);
787 return put_user(amount, (int __user *)arg);
796 static __inline__ int __udp_checksum_complete(struct sk_buff *skb)
798 return __skb_checksum_complete(skb);
801 static __inline__ int udp_checksum_complete(struct sk_buff *skb)
803 return skb->ip_summed != CHECKSUM_UNNECESSARY &&
804 __udp_checksum_complete(skb);
808 * This should be easy, if there is something there we
809 * return it, otherwise we block.
812 static int udp_recvmsg(struct kiocb *iocb, struct sock *sk, struct msghdr *msg,
813 size_t len, int noblock, int flags, int *addr_len)
815 struct inet_sock *inet = inet_sk(sk);
816 struct sockaddr_in *sin = (struct sockaddr_in *)msg->msg_name;
821 * Check any passed addresses
824 *addr_len=sizeof(*sin);
826 if (flags & MSG_ERRQUEUE)
827 return ip_recv_error(sk, msg, len);
830 skb = skb_recv_datagram(sk, flags, noblock, &err);
834 copied = skb->len - sizeof(struct udphdr);
837 msg->msg_flags |= MSG_TRUNC;
840 if (skb->ip_summed==CHECKSUM_UNNECESSARY) {
841 err = skb_copy_datagram_iovec(skb, sizeof(struct udphdr), msg->msg_iov,
843 } else if (msg->msg_flags&MSG_TRUNC) {
844 if (__udp_checksum_complete(skb))
846 err = skb_copy_datagram_iovec(skb, sizeof(struct udphdr), msg->msg_iov,
849 err = skb_copy_and_csum_datagram_iovec(skb, sizeof(struct udphdr), msg->msg_iov);
858 sock_recv_timestamp(msg, sk, skb);
860 /* Copy the address. */
863 sin->sin_family = AF_INET;
864 sin->sin_port = skb->h.uh->source;
865 sin->sin_addr.s_addr = skb->nh.iph->saddr;
866 memset(sin->sin_zero, 0, sizeof(sin->sin_zero));
868 if (inet->cmsg_flags)
869 ip_cmsg_recv(msg, skb);
872 if (flags & MSG_TRUNC)
873 err = skb->len - sizeof(struct udphdr);
876 skb_free_datagram(sk, skb);
881 UDP_INC_STATS_BH(UDP_MIB_INERRORS);
883 skb_kill_datagram(sk, skb, flags);
891 int udp_disconnect(struct sock *sk, int flags)
893 struct inet_sock *inet = inet_sk(sk);
895 * 1003.1g - break association.
898 sk->sk_state = TCP_CLOSE;
901 sk->sk_bound_dev_if = 0;
902 if (!(sk->sk_userlocks & SOCK_BINDADDR_LOCK))
903 inet_reset_saddr(sk);
905 if (!(sk->sk_userlocks & SOCK_BINDPORT_LOCK)) {
906 sk->sk_prot->unhash(sk);
913 static void udp_close(struct sock *sk, long timeout)
915 sk_common_release(sk);
919 * 1 if the the UDP system should process it
920 * 0 if we should drop this packet
921 * -1 if it should get processed by xfrm4_rcv_encap
923 static int udp_encap_rcv(struct sock * sk, struct sk_buff *skb)
928 struct udp_sock *up = udp_sk(sk);
929 struct udphdr *uh = skb->h.uh;
933 __u8 *udpdata = (__u8 *)uh + sizeof(struct udphdr);
934 __be32 *udpdata32 = (__be32 *)udpdata;
935 __u16 encap_type = up->encap_type;
937 /* if we're overly short, let UDP handle it */
938 if (udpdata > skb->tail)
941 /* if this is not encapsulated socket, then just return now */
945 len = skb->tail - udpdata;
947 switch (encap_type) {
949 case UDP_ENCAP_ESPINUDP:
950 /* Check if this is a keepalive packet. If so, eat it. */
951 if (len == 1 && udpdata[0] == 0xff) {
953 } else if (len > sizeof(struct ip_esp_hdr) && udpdata32[0] != 0 ) {
954 /* ESP Packet without Non-ESP header */
955 len = sizeof(struct udphdr);
957 /* Must be an IKE packet.. pass it through */
960 case UDP_ENCAP_ESPINUDP_NON_IKE:
961 /* Check if this is a keepalive packet. If so, eat it. */
962 if (len == 1 && udpdata[0] == 0xff) {
964 } else if (len > 2 * sizeof(u32) + sizeof(struct ip_esp_hdr) &&
965 udpdata32[0] == 0 && udpdata32[1] == 0) {
967 /* ESP Packet with Non-IKE marker */
968 len = sizeof(struct udphdr) + 2 * sizeof(u32);
970 /* Must be an IKE packet.. pass it through */
975 /* At this point we are sure that this is an ESPinUDP packet,
976 * so we need to remove 'len' bytes from the packet (the UDP
977 * header and optional ESP marker bytes) and then modify the
978 * protocol to ESP, and then call into the transform receiver.
980 if (skb_cloned(skb) && pskb_expand_head(skb, 0, 0, GFP_ATOMIC))
983 /* Now we can update and verify the packet length... */
985 iphlen = iph->ihl << 2;
986 iph->tot_len = htons(ntohs(iph->tot_len) - len);
987 if (skb->len < iphlen + len) {
988 /* packet is too small!?! */
992 /* pull the data buffer up to the ESP header and set the
993 * transport header to point to ESP. Keep UDP on the stack
996 skb->h.raw = skb_pull(skb, len);
998 /* modify the protocol (it's ESP!) */
999 iph->protocol = IPPROTO_ESP;
1001 /* and let the caller know to send this into the ESP processor... */
1009 * >0: "udp encap" protocol resubmission
1011 * Note that in the success and error cases, the skb is assumed to
1012 * have either been requeued or freed.
1014 static int udp_queue_rcv_skb(struct sock * sk, struct sk_buff *skb)
1016 struct udp_sock *up = udp_sk(sk);
1020 * Charge it to the socket, dropping if the queue is full.
1022 if (!xfrm4_policy_check(sk, XFRM_POLICY_IN, skb)) {
1028 if (up->encap_type) {
1030 * This is an encapsulation socket, so let's see if this is
1031 * an encapsulated packet.
1032 * If it's a keepalive packet, then just eat it.
1033 * If it's an encapsulateed packet, then pass it to the
1034 * IPsec xfrm input and return the response
1035 * appropriately. Otherwise, just fall through and
1036 * pass this up the UDP socket.
1040 ret = udp_encap_rcv(sk, skb);
1042 /* Eat the packet .. */
1047 /* process the ESP packet */
1048 ret = xfrm4_rcv_encap(skb, up->encap_type);
1049 UDP_INC_STATS_BH(UDP_MIB_INDATAGRAMS);
1052 /* FALLTHROUGH -- it's a UDP Packet */
1055 if (sk->sk_filter && skb->ip_summed != CHECKSUM_UNNECESSARY) {
1056 if (__udp_checksum_complete(skb)) {
1057 UDP_INC_STATS_BH(UDP_MIB_INERRORS);
1061 skb->ip_summed = CHECKSUM_UNNECESSARY;
1064 if ((rc = sock_queue_rcv_skb(sk,skb)) < 0) {
1065 /* Note that an ENOMEM error is charged twice */
1067 UDP_INC_STATS_BH(UDP_MIB_RCVBUFERRORS);
1068 UDP_INC_STATS_BH(UDP_MIB_INERRORS);
1072 UDP_INC_STATS_BH(UDP_MIB_INDATAGRAMS);
1077 * Multicasts and broadcasts go to each listener.
1079 * Note: called only from the BH handler context,
1080 * so we don't need to lock the hashes.
1082 static int udp_v4_mcast_deliver(struct sk_buff *skb, struct udphdr *uh,
1083 __be32 saddr, __be32 daddr)
1088 read_lock(&udp_hash_lock);
1089 sk = sk_head(&udp_hash[ntohs(uh->dest) & (UDP_HTABLE_SIZE - 1)]);
1090 dif = skb->dev->ifindex;
1091 sk = udp_v4_mcast_next(sk, uh->dest, daddr, uh->source, saddr, dif);
1093 struct sock *sknext = NULL;
1096 struct sk_buff *skb1 = skb;
1098 sknext = udp_v4_mcast_next(sk_next(sk), uh->dest, daddr,
1099 uh->source, saddr, dif);
1101 skb1 = skb_clone(skb, GFP_ATOMIC);
1104 int ret = udp_queue_rcv_skb(sk, skb1);
1106 /* we should probably re-process instead
1107 * of dropping packets here. */
1114 read_unlock(&udp_hash_lock);
1118 /* Initialize UDP checksum. If exited with zero value (success),
1119 * CHECKSUM_UNNECESSARY means, that no more checks are required.
1120 * Otherwise, csum completion requires chacksumming packet body,
1121 * including udp header and folding it to skb->csum.
1123 static void udp_checksum_init(struct sk_buff *skb, struct udphdr *uh,
1124 unsigned short ulen, __be32 saddr, __be32 daddr)
1126 if (uh->check == 0) {
1127 skb->ip_summed = CHECKSUM_UNNECESSARY;
1128 } else if (skb->ip_summed == CHECKSUM_COMPLETE) {
1129 if (!udp_check(uh, ulen, saddr, daddr, skb->csum))
1130 skb->ip_summed = CHECKSUM_UNNECESSARY;
1132 if (skb->ip_summed != CHECKSUM_UNNECESSARY)
1133 skb->csum = csum_tcpudp_nofold(saddr, daddr, ulen, IPPROTO_UDP, 0);
1134 /* Probably, we should checksum udp header (it should be in cache
1135 * in any case) and data in tiny packets (< rx copybreak).
1140 * All we need to do is get the socket, and then do a checksum.
1143 int udp_rcv(struct sk_buff *skb)
1147 unsigned short ulen;
1148 struct rtable *rt = (struct rtable*)skb->dst;
1149 __be32 saddr = skb->nh.iph->saddr;
1150 __be32 daddr = skb->nh.iph->daddr;
1154 * Validate the packet and the UDP length.
1156 if (!pskb_may_pull(skb, sizeof(struct udphdr)))
1161 ulen = ntohs(uh->len);
1163 if (ulen > len || ulen < sizeof(*uh))
1166 if (pskb_trim_rcsum(skb, ulen))
1169 udp_checksum_init(skb, uh, ulen, saddr, daddr);
1171 if(rt->rt_flags & (RTCF_BROADCAST|RTCF_MULTICAST))
1172 return udp_v4_mcast_deliver(skb, uh, saddr, daddr);
1174 sk = udp_v4_lookup(saddr, uh->source, daddr, uh->dest, skb->dev->ifindex);
1177 int ret = udp_queue_rcv_skb(sk, skb);
1180 /* a return value > 0 means to resubmit the input, but
1181 * it it wants the return to be -protocol, or 0
1188 if (!xfrm4_policy_check(NULL, XFRM_POLICY_IN, skb))
1192 /* No socket. Drop packet silently, if checksum is wrong */
1193 if (udp_checksum_complete(skb))
1196 UDP_INC_STATS_BH(UDP_MIB_NOPORTS);
1197 icmp_send(skb, ICMP_DEST_UNREACH, ICMP_PORT_UNREACH, 0);
1200 * Hmm. We got an UDP packet to a port to which we
1201 * don't wanna listen. Ignore it.
1207 LIMIT_NETDEBUG(KERN_DEBUG "UDP: short packet: From %u.%u.%u.%u:%u %d/%d to %u.%u.%u.%u:%u\n",
1215 UDP_INC_STATS_BH(UDP_MIB_INERRORS);
1221 * RFC1122: OK. Discards the bad packet silently (as far as
1222 * the network is concerned, anyway) as per 4.1.3.4 (MUST).
1224 LIMIT_NETDEBUG(KERN_DEBUG "UDP: bad checksum. From %d.%d.%d.%d:%d to %d.%d.%d.%d:%d ulen %d\n",
1231 UDP_INC_STATS_BH(UDP_MIB_INERRORS);
1236 static int udp_destroy_sock(struct sock *sk)
1239 udp_flush_pending_frames(sk);
1245 * Socket option code for UDP
1247 static int do_udp_setsockopt(struct sock *sk, int level, int optname,
1248 char __user *optval, int optlen)
1250 struct udp_sock *up = udp_sk(sk);
1254 if(optlen<sizeof(int))
1257 if (get_user(val, (int __user *)optval))
1267 udp_push_pending_frames(sk, up);
1275 case UDP_ENCAP_ESPINUDP:
1276 case UDP_ENCAP_ESPINUDP_NON_IKE:
1277 up->encap_type = val;
1293 static int udp_setsockopt(struct sock *sk, int level, int optname,
1294 char __user *optval, int optlen)
1296 if (level != SOL_UDP)
1297 return ip_setsockopt(sk, level, optname, optval, optlen);
1298 return do_udp_setsockopt(sk, level, optname, optval, optlen);
1301 #ifdef CONFIG_COMPAT
1302 static int compat_udp_setsockopt(struct sock *sk, int level, int optname,
1303 char __user *optval, int optlen)
1305 if (level != SOL_UDP)
1306 return compat_ip_setsockopt(sk, level, optname, optval, optlen);
1307 return do_udp_setsockopt(sk, level, optname, optval, optlen);
1311 static int do_udp_getsockopt(struct sock *sk, int level, int optname,
1312 char __user *optval, int __user *optlen)
1314 struct udp_sock *up = udp_sk(sk);
1317 if(get_user(len,optlen))
1320 len = min_t(unsigned int, len, sizeof(int));
1331 val = up->encap_type;
1335 return -ENOPROTOOPT;
1338 if(put_user(len, optlen))
1340 if(copy_to_user(optval, &val,len))
1345 static int udp_getsockopt(struct sock *sk, int level, int optname,
1346 char __user *optval, int __user *optlen)
1348 if (level != SOL_UDP)
1349 return ip_getsockopt(sk, level, optname, optval, optlen);
1350 return do_udp_getsockopt(sk, level, optname, optval, optlen);
1353 #ifdef CONFIG_COMPAT
1354 static int compat_udp_getsockopt(struct sock *sk, int level, int optname,
1355 char __user *optval, int __user *optlen)
1357 if (level != SOL_UDP)
1358 return compat_ip_getsockopt(sk, level, optname, optval, optlen);
1359 return do_udp_getsockopt(sk, level, optname, optval, optlen);
1363 * udp_poll - wait for a UDP event.
1364 * @file - file struct
1366 * @wait - poll table
1368 * This is same as datagram poll, except for the special case of
1369 * blocking sockets. If application is using a blocking fd
1370 * and a packet with checksum error is in the queue;
1371 * then it could get return from select indicating data available
1372 * but then block when reading it. Add special case code
1373 * to work around these arguably broken applications.
1375 unsigned int udp_poll(struct file *file, struct socket *sock, poll_table *wait)
1377 unsigned int mask = datagram_poll(file, sock, wait);
1378 struct sock *sk = sock->sk;
1380 /* Check for false positives due to checksum errors */
1381 if ( (mask & POLLRDNORM) &&
1382 !(file->f_flags & O_NONBLOCK) &&
1383 !(sk->sk_shutdown & RCV_SHUTDOWN)){
1384 struct sk_buff_head *rcvq = &sk->sk_receive_queue;
1385 struct sk_buff *skb;
1387 spin_lock_bh(&rcvq->lock);
1388 while ((skb = skb_peek(rcvq)) != NULL) {
1389 if (udp_checksum_complete(skb)) {
1390 UDP_INC_STATS_BH(UDP_MIB_INERRORS);
1391 __skb_unlink(skb, rcvq);
1394 skb->ip_summed = CHECKSUM_UNNECESSARY;
1398 spin_unlock_bh(&rcvq->lock);
1400 /* nothing to see, move along */
1402 mask &= ~(POLLIN | POLLRDNORM);
1409 struct proto udp_prot = {
1411 .owner = THIS_MODULE,
1413 .connect = ip4_datagram_connect,
1414 .disconnect = udp_disconnect,
1416 .destroy = udp_destroy_sock,
1417 .setsockopt = udp_setsockopt,
1418 .getsockopt = udp_getsockopt,
1419 .sendmsg = udp_sendmsg,
1420 .recvmsg = udp_recvmsg,
1421 .sendpage = udp_sendpage,
1422 .backlog_rcv = udp_queue_rcv_skb,
1423 .hash = udp_v4_hash,
1424 .unhash = udp_v4_unhash,
1425 .get_port = udp_v4_get_port,
1426 .obj_size = sizeof(struct udp_sock),
1427 #ifdef CONFIG_COMPAT
1428 .compat_setsockopt = compat_udp_setsockopt,
1429 .compat_getsockopt = compat_udp_getsockopt,
1433 /* ------------------------------------------------------------------------ */
1434 #ifdef CONFIG_PROC_FS
1436 static struct sock *udp_get_first(struct seq_file *seq)
1439 struct udp_iter_state *state = seq->private;
1441 for (state->bucket = 0; state->bucket < UDP_HTABLE_SIZE; ++state->bucket) {
1442 struct hlist_node *node;
1443 sk_for_each(sk, node, &udp_hash[state->bucket]) {
1444 if (sk->sk_family == state->family)
1453 static struct sock *udp_get_next(struct seq_file *seq, struct sock *sk)
1455 struct udp_iter_state *state = seq->private;
1461 } while (sk && sk->sk_family != state->family);
1463 if (!sk && ++state->bucket < UDP_HTABLE_SIZE) {
1464 sk = sk_head(&udp_hash[state->bucket]);
1470 static struct sock *udp_get_idx(struct seq_file *seq, loff_t pos)
1472 struct sock *sk = udp_get_first(seq);
1475 while(pos && (sk = udp_get_next(seq, sk)) != NULL)
1477 return pos ? NULL : sk;
1480 static void *udp_seq_start(struct seq_file *seq, loff_t *pos)
1482 read_lock(&udp_hash_lock);
1483 return *pos ? udp_get_idx(seq, *pos-1) : (void *)1;
1486 static void *udp_seq_next(struct seq_file *seq, void *v, loff_t *pos)
1491 sk = udp_get_idx(seq, 0);
1493 sk = udp_get_next(seq, v);
1499 static void udp_seq_stop(struct seq_file *seq, void *v)
1501 read_unlock(&udp_hash_lock);
1504 static int udp_seq_open(struct inode *inode, struct file *file)
1506 struct udp_seq_afinfo *afinfo = PDE(inode)->data;
1507 struct seq_file *seq;
1509 struct udp_iter_state *s = kzalloc(sizeof(*s), GFP_KERNEL);
1513 s->family = afinfo->family;
1514 s->seq_ops.start = udp_seq_start;
1515 s->seq_ops.next = udp_seq_next;
1516 s->seq_ops.show = afinfo->seq_show;
1517 s->seq_ops.stop = udp_seq_stop;
1519 rc = seq_open(file, &s->seq_ops);
1523 seq = file->private_data;
1532 /* ------------------------------------------------------------------------ */
1533 int udp_proc_register(struct udp_seq_afinfo *afinfo)
1535 struct proc_dir_entry *p;
1540 afinfo->seq_fops->owner = afinfo->owner;
1541 afinfo->seq_fops->open = udp_seq_open;
1542 afinfo->seq_fops->read = seq_read;
1543 afinfo->seq_fops->llseek = seq_lseek;
1544 afinfo->seq_fops->release = seq_release_private;
1546 p = proc_net_fops_create(afinfo->name, S_IRUGO, afinfo->seq_fops);
1554 void udp_proc_unregister(struct udp_seq_afinfo *afinfo)
1558 proc_net_remove(afinfo->name);
1559 memset(afinfo->seq_fops, 0, sizeof(*afinfo->seq_fops));
1562 /* ------------------------------------------------------------------------ */
1563 static void udp4_format_sock(struct sock *sp, char *tmpbuf, int bucket)
1565 struct inet_sock *inet = inet_sk(sp);
1566 __be32 dest = inet->daddr;
1567 __be32 src = inet->rcv_saddr;
1568 __u16 destp = ntohs(inet->dport);
1569 __u16 srcp = ntohs(inet->sport);
1571 sprintf(tmpbuf, "%4d: %08X:%04X %08X:%04X"
1572 " %02X %08X:%08X %02X:%08lX %08X %5d %8d %lu %d %p",
1573 bucket, src, srcp, dest, destp, sp->sk_state,
1574 atomic_read(&sp->sk_wmem_alloc),
1575 atomic_read(&sp->sk_rmem_alloc),
1576 0, 0L, 0, sock_i_uid(sp), 0, sock_i_ino(sp),
1577 atomic_read(&sp->sk_refcnt), sp);
1580 static int udp4_seq_show(struct seq_file *seq, void *v)
1582 if (v == SEQ_START_TOKEN)
1583 seq_printf(seq, "%-127s\n",
1584 " sl local_address rem_address st tx_queue "
1585 "rx_queue tr tm->when retrnsmt uid timeout "
1589 struct udp_iter_state *state = seq->private;
1591 udp4_format_sock(v, tmpbuf, state->bucket);
1592 seq_printf(seq, "%-127s\n", tmpbuf);
1597 /* ------------------------------------------------------------------------ */
1598 static struct file_operations udp4_seq_fops;
1599 static struct udp_seq_afinfo udp4_seq_afinfo = {
1600 .owner = THIS_MODULE,
1603 .seq_show = udp4_seq_show,
1604 .seq_fops = &udp4_seq_fops,
1607 int __init udp4_proc_init(void)
1609 return udp_proc_register(&udp4_seq_afinfo);
1612 void udp4_proc_exit(void)
1614 udp_proc_unregister(&udp4_seq_afinfo);
1616 #endif /* CONFIG_PROC_FS */
1618 EXPORT_SYMBOL(udp_disconnect);
1619 EXPORT_SYMBOL(udp_hash);
1620 EXPORT_SYMBOL(udp_hash_lock);
1621 EXPORT_SYMBOL(udp_ioctl);
1622 EXPORT_SYMBOL(udp_get_port);
1623 EXPORT_SYMBOL(udp_prot);
1624 EXPORT_SYMBOL(udp_sendmsg);
1625 EXPORT_SYMBOL(udp_poll);
1627 #ifdef CONFIG_PROC_FS
1628 EXPORT_SYMBOL(udp_proc_register);
1629 EXPORT_SYMBOL(udp_proc_unregister);