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 $
10 * Authors: Ross Biro, <bir7@leland.Stanford.Edu>
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>
90 #include <linux/errno.h>
91 #include <linux/timer.h>
93 #include <linux/config.h>
94 #include <linux/inet.h>
95 #include <linux/ipv6.h>
96 #include <linux/netdevice.h>
99 #include <net/protocol.h>
100 #include <linux/skbuff.h>
101 #include <linux/proc_fs.h>
102 #include <linux/seq_file.h>
103 #include <net/sock.h>
105 #include <net/icmp.h>
106 #include <net/route.h>
107 #include <net/inet_common.h>
108 #include <net/checksum.h>
109 #include <net/xfrm.h>
112 * Snmp MIB for the UDP layer
115 DEFINE_SNMP_STAT(struct udp_mib, udp_statistics);
117 struct hlist_head udp_hash[UDP_HTABLE_SIZE];
118 rwlock_t udp_hash_lock = RW_LOCK_UNLOCKED;
120 /* Shared by v4/v6 udp. */
123 int tcp_ipv4_addr_conflict(struct sock *sk1, struct sock *sk2);
125 static int udp_v4_get_port(struct sock *sk, unsigned short snum)
127 struct hlist_node *node;
129 struct inet_opt *inet = inet_sk(sk);
131 write_lock_bh(&udp_hash_lock);
133 int best_size_so_far, best, result, i;
135 if (udp_port_rover > sysctl_local_port_range[1] ||
136 udp_port_rover < sysctl_local_port_range[0])
137 udp_port_rover = sysctl_local_port_range[0];
138 best_size_so_far = 32767;
139 best = result = udp_port_rover;
140 for (i = 0; i < UDP_HTABLE_SIZE; i++, result++) {
141 struct hlist_head *list;
144 list = &udp_hash[result & (UDP_HTABLE_SIZE - 1)];
145 if (hlist_empty(list)) {
146 if (result > sysctl_local_port_range[1])
147 result = sysctl_local_port_range[0] +
148 ((result - sysctl_local_port_range[0]) &
149 (UDP_HTABLE_SIZE - 1));
153 sk_for_each(sk2, node, list)
154 if (++size >= best_size_so_far)
156 best_size_so_far = size;
161 for(i = 0; i < (1 << 16) / UDP_HTABLE_SIZE; i++, result += UDP_HTABLE_SIZE) {
162 if (result > sysctl_local_port_range[1])
163 result = sysctl_local_port_range[0]
164 + ((result - sysctl_local_port_range[0]) &
165 (UDP_HTABLE_SIZE - 1));
166 if (!udp_lport_inuse(result))
169 if (i >= (1 << 16) / UDP_HTABLE_SIZE)
172 udp_port_rover = snum = result;
174 sk_for_each(sk2, node,
175 &udp_hash[snum & (UDP_HTABLE_SIZE - 1)]) {
176 struct inet_opt *inet2 = inet_sk(sk2);
178 if (inet2->num == snum &&
180 !ipv6_only_sock(sk2) &&
181 (!sk2->sk_bound_dev_if ||
182 !sk->sk_bound_dev_if ||
183 sk2->sk_bound_dev_if == sk->sk_bound_dev_if) &&
184 tcp_ipv4_addr_conflict(sk2, sk) &&
185 (!sk2->sk_reuse || !sk->sk_reuse))
190 if (sk_unhashed(sk)) {
191 struct hlist_head *h = &udp_hash[snum & (UDP_HTABLE_SIZE - 1)];
194 sock_prot_inc_use(sk->sk_prot);
196 write_unlock_bh(&udp_hash_lock);
200 write_unlock_bh(&udp_hash_lock);
204 static void udp_v4_hash(struct sock *sk)
209 static void udp_v4_unhash(struct sock *sk)
211 write_lock_bh(&udp_hash_lock);
212 if (sk_del_node_init(sk)) {
213 inet_sk(sk)->num = 0;
214 sock_prot_dec_use(sk->sk_prot);
216 write_unlock_bh(&udp_hash_lock);
219 static inline int udp_in_list(struct nx_info *nx_info, u32 addr)
221 int n = nx_info->nbipv4;
225 if (nx_info->ipv4[i] == addr)
230 /* UDP is nearly always wildcards out the wazoo, it makes no sense to try
231 * harder than this. -DaveM
233 struct sock *udp_v4_lookup_longway(u32 saddr, u16 sport, u32 daddr, u16 dport, int dif)
235 struct sock *sk, *result = NULL;
236 struct hlist_node *node;
237 unsigned short hnum = ntohs(dport);
240 sk_for_each(sk, node, &udp_hash[hnum & (UDP_HTABLE_SIZE - 1)]) {
241 struct inet_opt *inet = inet_sk(sk);
243 if (inet->num == hnum && !ipv6_only_sock(sk)) {
244 int score = (sk->sk_family == PF_INET ? 1 : 0);
245 if (inet->rcv_saddr) {
246 if (inet->rcv_saddr != daddr)
249 } else if (sk->sk_nx_info) {
250 if (udp_in_list(sk->sk_nx_info, daddr))
256 if (inet->daddr != saddr)
261 if (inet->dport != sport)
265 if (sk->sk_bound_dev_if) {
266 if (sk->sk_bound_dev_if != dif)
273 } else if(score > badness) {
282 __inline__ struct sock *udp_v4_lookup(u32 saddr, u16 sport, u32 daddr, u16 dport, int dif)
286 read_lock(&udp_hash_lock);
287 sk = udp_v4_lookup_longway(saddr, sport, daddr, dport, dif);
290 read_unlock(&udp_hash_lock);
294 static inline struct sock *udp_v4_mcast_next(struct sock *sk,
295 u16 loc_port, u32 loc_addr,
296 u16 rmt_port, u32 rmt_addr,
299 struct hlist_node *node;
301 unsigned short hnum = ntohs(loc_port);
303 sk_for_each_from(s, node) {
304 struct inet_opt *inet = inet_sk(s);
306 if (inet->num != hnum ||
307 (inet->daddr && inet->daddr != rmt_addr) ||
308 (inet->dport != rmt_port && inet->dport) ||
309 (inet->rcv_saddr && inet->rcv_saddr != loc_addr &&
310 inet->rcv_saddr2 && inet->rcv_saddr2 != loc_addr) ||
312 (s->sk_bound_dev_if && s->sk_bound_dev_if != dif))
314 if (!ip_mc_sf_allow(s, loc_addr, rmt_addr, dif))
324 * This routine is called by the ICMP module when it gets some
325 * sort of error condition. If err < 0 then the socket should
326 * be closed and the error returned to the user. If err > 0
327 * it's just the icmp type << 8 | icmp code.
328 * Header points to the ip header of the error packet. We move
329 * on past this. Then (as it used to claim before adjustment)
330 * header points to the first 8 bytes of the udp header. We need
331 * to find the appropriate port.
334 void udp_err(struct sk_buff *skb, u32 info)
336 struct inet_opt *inet;
337 struct iphdr *iph = (struct iphdr*)skb->data;
338 struct udphdr *uh = (struct udphdr*)(skb->data+(iph->ihl<<2));
339 int type = skb->h.icmph->type;
340 int code = skb->h.icmph->code;
345 sk = udp_v4_lookup(iph->daddr, uh->dest, iph->saddr, uh->source, skb->dev->ifindex);
347 ICMP_INC_STATS_BH(IcmpInErrors);
348 return; /* No socket for error */
357 case ICMP_TIME_EXCEEDED:
360 case ICMP_SOURCE_QUENCH:
362 case ICMP_PARAMETERPROB:
366 case ICMP_DEST_UNREACH:
367 if (code == ICMP_FRAG_NEEDED) { /* Path MTU discovery */
368 if (inet->pmtudisc != IP_PMTUDISC_DONT) {
376 if (code <= NR_ICMP_UNREACH) {
377 harderr = icmp_err_convert[code].fatal;
378 err = icmp_err_convert[code].errno;
384 * RFC1122: OK. Passes ICMP errors back to application, as per
387 if (!inet->recverr) {
388 if (!harderr || sk->sk_state != TCP_ESTABLISHED)
391 ip_icmp_error(sk, skb, err, uh->dest, info, (u8*)(uh+1));
394 sk->sk_error_report(sk);
400 * Throw away all pending data and cancel the corking. Socket is locked.
402 static void udp_flush_pending_frames(struct sock *sk)
404 struct udp_opt *up = udp_sk(sk);
409 ip_flush_pending_frames(sk);
414 * Push out all pending data as one UDP datagram. Socket is locked.
416 static int udp_push_pending_frames(struct sock *sk, struct udp_opt *up)
418 struct inet_opt *inet = inet_sk(sk);
419 struct flowi *fl = &inet->cork.fl;
424 /* Grab the skbuff where UDP header space exists. */
425 if ((skb = skb_peek(&sk->sk_write_queue)) == NULL)
429 * Create a UDP header
432 uh->source = fl->fl_ip_sport;
433 uh->dest = fl->fl_ip_dport;
434 uh->len = htons(up->len);
437 if (sk->sk_no_check == UDP_CSUM_NOXMIT) {
438 skb->ip_summed = CHECKSUM_NONE;
442 if (skb_queue_len(&sk->sk_write_queue) == 1) {
444 * Only one fragment on the socket.
446 if (skb->ip_summed == CHECKSUM_HW) {
447 skb->csum = offsetof(struct udphdr, check);
448 uh->check = ~csum_tcpudp_magic(fl->fl4_src, fl->fl4_dst,
449 up->len, IPPROTO_UDP, 0);
451 skb->csum = csum_partial((char *)uh,
452 sizeof(struct udphdr), skb->csum);
453 uh->check = csum_tcpudp_magic(fl->fl4_src, fl->fl4_dst,
454 up->len, IPPROTO_UDP, skb->csum);
459 unsigned int csum = 0;
461 * HW-checksum won't work as there are two or more
462 * fragments on the socket so that all csums of sk_buffs
463 * should be together.
465 if (skb->ip_summed == CHECKSUM_HW) {
466 int offset = (unsigned char *)uh - skb->data;
467 skb->csum = skb_checksum(skb, offset, skb->len - offset, 0);
469 skb->ip_summed = CHECKSUM_NONE;
471 skb->csum = csum_partial((char *)uh,
472 sizeof(struct udphdr), skb->csum);
475 skb_queue_walk(&sk->sk_write_queue, skb) {
476 csum = csum_add(csum, skb->csum);
478 uh->check = csum_tcpudp_magic(fl->fl4_src, fl->fl4_dst,
479 up->len, IPPROTO_UDP, csum);
484 err = ip_push_pending_frames(sk);
492 static unsigned short udp_check(struct udphdr *uh, int len, unsigned long saddr, unsigned long daddr, unsigned long base)
494 return(csum_tcpudp_magic(saddr, daddr, len, IPPROTO_UDP, base));
497 int udp_sendmsg(struct kiocb *iocb, struct sock *sk, struct msghdr *msg,
500 struct inet_opt *inet = inet_sk(sk);
501 struct udp_opt *up = udp_sk(sk);
503 struct ipcm_cookie ipc;
504 struct rtable *rt = NULL;
507 u32 daddr, faddr, saddr;
511 int corkreq = up->corkflag || msg->msg_flags&MSG_MORE;
520 if (msg->msg_flags&MSG_OOB) /* Mirror BSD error message compatibility */
527 * There are pending frames.
528 * The socket lock must be held while it's corked.
531 if (likely(up->pending)) {
532 if (unlikely(up->pending != AF_INET)) {
540 ulen += sizeof(struct udphdr);
543 * Get and verify the address.
546 struct sockaddr_in * usin = (struct sockaddr_in*)msg->msg_name;
547 if (msg->msg_namelen < sizeof(*usin))
549 if (usin->sin_family != AF_INET) {
550 if (usin->sin_family != AF_UNSPEC)
554 daddr = usin->sin_addr.s_addr;
555 dport = usin->sin_port;
559 if (sk->sk_state != TCP_ESTABLISHED)
560 return -EDESTADDRREQ;
563 /* Open fast path for connected socket.
564 Route will not be used, if at least one option is set.
568 ipc.addr = inet->saddr;
570 ipc.oif = sk->sk_bound_dev_if;
571 if (msg->msg_controllen) {
572 err = ip_cmsg_send(msg, &ipc);
583 ipc.addr = faddr = daddr;
585 if (ipc.opt && ipc.opt->srr) {
588 faddr = ipc.opt->faddr;
591 tos = RT_TOS(inet->tos);
592 if (sk->sk_localroute || (msg->msg_flags & MSG_DONTROUTE) ||
593 (ipc.opt && ipc.opt->is_strictroute)) {
598 if (MULTICAST(daddr)) {
600 ipc.oif = inet->mc_index;
602 saddr = inet->mc_addr;
607 rt = (struct rtable*)sk_dst_check(sk, 0);
610 struct flowi fl = { .oif = ipc.oif,
615 .proto = IPPROTO_UDP,
617 { .sport = inet->sport,
618 .dport = dport } } };
619 struct nx_info *nxi = sk->sk_nx_info;
622 err = ip_find_src(nxi, &rt, &fl);
625 if (daddr == IPI_LOOPBACK && !vx_check(0, VX_ADMIN))
626 daddr = fl.fl4_dst = nxi->ipv4[0];
628 err = ip_route_output_flow(&rt, &fl, sk, !(msg->msg_flags&MSG_DONTWAIT));
633 if ((rt->rt_flags & RTCF_BROADCAST) &&
634 !sock_flag(sk, SOCK_BROADCAST))
637 sk_dst_set(sk, dst_clone(&rt->u.dst));
640 if (msg->msg_flags&MSG_CONFIRM)
646 daddr = ipc.addr = rt->rt_dst;
649 if (unlikely(up->pending)) {
650 /* The socket is already corked while preparing it. */
651 /* ... which is an evident application bug. --ANK */
654 NETDEBUG(if (net_ratelimit()) printk(KERN_DEBUG "udp cork app bug 2\n"));
659 * Now cork the socket to pend data.
661 inet->cork.fl.fl4_dst = daddr;
662 inet->cork.fl.fl_ip_dport = dport;
663 inet->cork.fl.fl4_src = saddr;
664 inet->cork.fl.fl_ip_sport = inet->sport;
665 up->pending = AF_INET;
669 err = ip_append_data(sk, ip_generic_getfrag, msg->msg_iov, ulen,
670 sizeof(struct udphdr), &ipc, rt,
671 corkreq ? msg->msg_flags|MSG_MORE : msg->msg_flags);
673 udp_flush_pending_frames(sk);
675 err = udp_push_pending_frames(sk, up);
683 UDP_INC_STATS_USER(UdpOutDatagrams);
689 dst_confirm(&rt->u.dst);
690 if (!(msg->msg_flags&MSG_PROBE) || len)
691 goto back_from_confirm;
696 int udp_sendpage(struct sock *sk, struct page *page, int offset, size_t size, int flags)
698 struct udp_opt *up = udp_sk(sk);
702 struct msghdr msg = { .msg_flags = flags|MSG_MORE };
704 /* Call udp_sendmsg to specify destination address which
705 * sendpage interface can't pass.
706 * This will succeed only when the socket is connected.
708 ret = udp_sendmsg(NULL, sk, &msg, 0);
715 if (unlikely(!up->pending)) {
718 NETDEBUG(if (net_ratelimit()) printk(KERN_DEBUG "udp cork app bug 3\n"));
722 ret = ip_append_page(sk, page, offset, size, flags);
723 if (ret == -EOPNOTSUPP) {
725 return sock_no_sendpage(sk->sk_socket, page, offset,
729 udp_flush_pending_frames(sk);
734 if (!(up->corkflag || (flags&MSG_MORE)))
735 ret = udp_push_pending_frames(sk, up);
744 * IOCTL requests applicable to the UDP protocol
747 int udp_ioctl(struct sock *sk, int cmd, unsigned long arg)
753 int amount = atomic_read(&sk->sk_wmem_alloc);
754 return put_user(amount, (int __user *)arg);
760 unsigned long amount;
763 spin_lock_irq(&sk->sk_receive_queue.lock);
764 skb = skb_peek(&sk->sk_receive_queue);
767 * We will only return the amount
768 * of this packet since that is all
771 amount = skb->len - sizeof(struct udphdr);
773 spin_unlock_irq(&sk->sk_receive_queue.lock);
774 return put_user(amount, (int __user *)arg);
783 static __inline__ int __udp_checksum_complete(struct sk_buff *skb)
785 return (unsigned short)csum_fold(skb_checksum(skb, 0, skb->len, skb->csum));
788 static __inline__ int udp_checksum_complete(struct sk_buff *skb)
790 return skb->ip_summed != CHECKSUM_UNNECESSARY &&
791 __udp_checksum_complete(skb);
795 * This should be easy, if there is something there we
796 * return it, otherwise we block.
799 int udp_recvmsg(struct kiocb *iocb, struct sock *sk, struct msghdr *msg,
800 size_t len, int noblock, int flags, int *addr_len)
802 struct inet_opt *inet = inet_sk(sk);
803 struct sockaddr_in *sin = (struct sockaddr_in *)msg->msg_name;
808 * Check any passed addresses
811 *addr_len=sizeof(*sin);
813 if (flags & MSG_ERRQUEUE)
814 return ip_recv_error(sk, msg, len);
817 skb = skb_recv_datagram(sk, flags, noblock, &err);
821 copied = skb->len - sizeof(struct udphdr);
824 msg->msg_flags |= MSG_TRUNC;
827 if (skb->ip_summed==CHECKSUM_UNNECESSARY) {
828 err = skb_copy_datagram_iovec(skb, sizeof(struct udphdr), msg->msg_iov,
830 } else if (msg->msg_flags&MSG_TRUNC) {
831 if (__udp_checksum_complete(skb))
833 err = skb_copy_datagram_iovec(skb, sizeof(struct udphdr), msg->msg_iov,
836 err = skb_copy_and_csum_datagram_iovec(skb, sizeof(struct udphdr), msg->msg_iov);
845 sock_recv_timestamp(msg, sk, skb);
847 /* Copy the address. */
850 sin->sin_family = AF_INET;
851 sin->sin_port = skb->h.uh->source;
852 sin->sin_addr.s_addr = skb->nh.iph->saddr;
853 memset(sin->sin_zero, 0, sizeof(sin->sin_zero));
855 if (inet->cmsg_flags)
856 ip_cmsg_recv(msg, skb);
860 skb_free_datagram(sk, skb);
865 UDP_INC_STATS_BH(UdpInErrors);
868 if (flags&MSG_PEEK) {
870 spin_lock_irq(&sk->sk_receive_queue.lock);
871 if (skb == skb_peek(&sk->sk_receive_queue)) {
872 __skb_unlink(skb, &sk->sk_receive_queue);
875 spin_unlock_irq(&sk->sk_receive_queue.lock);
880 skb_free_datagram(sk, skb);
887 int udp_connect(struct sock *sk, struct sockaddr *uaddr, int addr_len)
889 struct inet_opt *inet = inet_sk(sk);
890 struct sockaddr_in *usin = (struct sockaddr_in *) uaddr;
897 if (addr_len < sizeof(*usin))
900 if (usin->sin_family != AF_INET)
901 return -EAFNOSUPPORT;
905 oif = sk->sk_bound_dev_if;
907 if (MULTICAST(usin->sin_addr.s_addr)) {
909 oif = inet->mc_index;
911 saddr = inet->mc_addr;
913 err = ip_route_connect(&rt, usin->sin_addr.s_addr, saddr,
914 RT_CONN_FLAGS(sk), oif,
916 inet->sport, usin->sin_port, sk);
919 if ((rt->rt_flags & RTCF_BROADCAST) && !sock_flag(sk, SOCK_BROADCAST)) {
924 inet->saddr = rt->rt_src; /* Update source address */
925 if (!inet->rcv_saddr)
926 inet->rcv_saddr = rt->rt_src;
927 inet->daddr = rt->rt_dst;
928 inet->dport = usin->sin_port;
929 sk->sk_state = TCP_ESTABLISHED;
932 sk_dst_set(sk, &rt->u.dst);
936 int udp_disconnect(struct sock *sk, int flags)
938 struct inet_opt *inet = inet_sk(sk);
940 * 1003.1g - break association.
943 sk->sk_state = TCP_CLOSE;
946 sk->sk_bound_dev_if = 0;
947 if (!(sk->sk_userlocks & SOCK_BINDADDR_LOCK))
948 inet_reset_saddr(sk);
950 if (!(sk->sk_userlocks & SOCK_BINDPORT_LOCK)) {
951 sk->sk_prot->unhash(sk);
958 static void udp_close(struct sock *sk, long timeout)
960 sk_common_release(sk);
964 * 1 if the the UDP system should process it
965 * 0 if we should drop this packet
966 * -1 if it should get processed by xfrm4_rcv_encap
968 static int udp_encap_rcv(struct sock * sk, struct sk_buff *skb)
973 struct udp_opt *up = udp_sk(sk);
974 struct udphdr *uh = skb->h.uh;
978 __u8 *udpdata = (__u8 *)uh + sizeof(struct udphdr);
979 __u32 *udpdata32 = (__u32 *)udpdata;
980 __u16 encap_type = up->encap_type;
982 /* if we're overly short, let UDP handle it */
983 if (udpdata > skb->tail)
986 /* if this is not encapsulated socket, then just return now */
990 len = skb->tail - udpdata;
992 switch (encap_type) {
994 case UDP_ENCAP_ESPINUDP:
995 /* Check if this is a keepalive packet. If so, eat it. */
996 if (len == 1 && udpdata[0] == 0xff) {
998 } else if (len > sizeof(struct ip_esp_hdr) && udpdata32[0] != 0 ) {
999 /* ESP Packet without Non-ESP header */
1000 len = sizeof(struct udphdr);
1002 /* Must be an IKE packet.. pass it through */
1005 case UDP_ENCAP_ESPINUDP_NON_IKE:
1006 /* Check if this is a keepalive packet. If so, eat it. */
1007 if (len == 1 && udpdata[0] == 0xff) {
1009 } else if (len > 2 * sizeof(u32) + sizeof(struct ip_esp_hdr) &&
1010 udpdata32[0] == 0 && udpdata32[1] == 0) {
1012 /* ESP Packet with Non-IKE marker */
1013 len = sizeof(struct udphdr) + 2 * sizeof(u32);
1015 /* Must be an IKE packet.. pass it through */
1019 /* At this point we are sure that this is an ESPinUDP packet,
1020 * so we need to remove 'len' bytes from the packet (the UDP
1021 * header and optional ESP marker bytes) and then modify the
1022 * protocol to ESP, and then call into the transform receiver.
1025 /* Now we can update and verify the packet length... */
1027 iphlen = iph->ihl << 2;
1028 iph->tot_len = htons(ntohs(iph->tot_len) - len);
1029 if (skb->len < iphlen + len) {
1030 /* packet is too small!?! */
1034 /* pull the data buffer up to the ESP header and set the
1035 * transport header to point to ESP. Keep UDP on the stack
1038 skb->h.raw = skb_pull(skb, len);
1040 /* modify the protocol (it's ESP!) */
1041 iph->protocol = IPPROTO_ESP;
1043 /* and let the caller know to send this into the ESP processor... */
1051 * >0: "udp encap" protocol resubmission
1053 * Note that in the success and error cases, the skb is assumed to
1054 * have either been requeued or freed.
1056 static int udp_queue_rcv_skb(struct sock * sk, struct sk_buff *skb)
1058 struct udp_opt *up = udp_sk(sk);
1061 * Charge it to the socket, dropping if the queue is full.
1063 if (!xfrm4_policy_check(sk, XFRM_POLICY_IN, skb)) {
1068 if (up->encap_type) {
1070 * This is an encapsulation socket, so let's see if this is
1071 * an encapsulated packet.
1072 * If it's a keepalive packet, then just eat it.
1073 * If it's an encapsulateed packet, then pass it to the
1074 * IPsec xfrm input and return the response
1075 * appropriately. Otherwise, just fall through and
1076 * pass this up the UDP socket.
1080 ret = udp_encap_rcv(sk, skb);
1082 /* Eat the packet .. */
1087 /* process the ESP packet */
1088 ret = xfrm4_rcv_encap(skb, up->encap_type);
1089 UDP_INC_STATS_BH(UdpInDatagrams);
1092 /* FALLTHROUGH -- it's a UDP Packet */
1095 if (sk->sk_filter && skb->ip_summed != CHECKSUM_UNNECESSARY) {
1096 if (__udp_checksum_complete(skb)) {
1097 UDP_INC_STATS_BH(UdpInErrors);
1101 skb->ip_summed = CHECKSUM_UNNECESSARY;
1104 if (sock_queue_rcv_skb(sk,skb)<0) {
1105 UDP_INC_STATS_BH(UdpInErrors);
1109 UDP_INC_STATS_BH(UdpInDatagrams);
1114 * Multicasts and broadcasts go to each listener.
1116 * Note: called only from the BH handler context,
1117 * so we don't need to lock the hashes.
1119 static int udp_v4_mcast_deliver(struct sk_buff *skb, struct udphdr *uh,
1120 u32 saddr, u32 daddr)
1125 read_lock(&udp_hash_lock);
1126 sk = sk_head(&udp_hash[ntohs(uh->dest) & (UDP_HTABLE_SIZE - 1)]);
1127 dif = skb->dev->ifindex;
1128 sk = udp_v4_mcast_next(sk, uh->dest, daddr, uh->source, saddr, dif);
1130 struct sock *sknext = NULL;
1133 struct sk_buff *skb1 = skb;
1135 sknext = udp_v4_mcast_next(sk_next(sk), uh->dest, daddr,
1136 uh->source, saddr, dif);
1138 skb1 = skb_clone(skb, GFP_ATOMIC);
1141 int ret = udp_queue_rcv_skb(sk, skb1);
1143 /* we should probably re-process instead
1144 * of dropping packets here. */
1151 read_unlock(&udp_hash_lock);
1155 /* Initialize UDP checksum. If exited with zero value (success),
1156 * CHECKSUM_UNNECESSARY means, that no more checks are required.
1157 * Otherwise, csum completion requires chacksumming packet body,
1158 * including udp header and folding it to skb->csum.
1160 static int udp_checksum_init(struct sk_buff *skb, struct udphdr *uh,
1161 unsigned short ulen, u32 saddr, u32 daddr)
1163 if (uh->check == 0) {
1164 skb->ip_summed = CHECKSUM_UNNECESSARY;
1165 } else if (skb->ip_summed == CHECKSUM_HW) {
1166 skb->ip_summed = CHECKSUM_UNNECESSARY;
1167 if (!udp_check(uh, ulen, saddr, daddr, skb->csum))
1169 NETDEBUG(if (net_ratelimit()) printk(KERN_DEBUG "udp v4 hw csum failure.\n"));
1170 skb->ip_summed = CHECKSUM_NONE;
1172 if (skb->ip_summed != CHECKSUM_UNNECESSARY)
1173 skb->csum = csum_tcpudp_nofold(saddr, daddr, ulen, IPPROTO_UDP, 0);
1174 /* Probably, we should checksum udp header (it should be in cache
1175 * in any case) and data in tiny packets (< rx copybreak).
1181 * All we need to do is get the socket, and then do a checksum.
1184 int udp_rcv(struct sk_buff *skb)
1188 unsigned short ulen;
1189 struct rtable *rt = (struct rtable*)skb->dst;
1190 u32 saddr = skb->nh.iph->saddr;
1191 u32 daddr = skb->nh.iph->daddr;
1195 * Validate the packet and the UDP length.
1197 if (!pskb_may_pull(skb, sizeof(struct udphdr)))
1202 ulen = ntohs(uh->len);
1204 if (ulen > len || ulen < sizeof(*uh))
1207 if (pskb_trim(skb, ulen))
1210 if (udp_checksum_init(skb, uh, ulen, saddr, daddr) < 0)
1213 if(rt->rt_flags & (RTCF_BROADCAST|RTCF_MULTICAST))
1214 return udp_v4_mcast_deliver(skb, uh, saddr, daddr);
1216 sk = udp_v4_lookup(saddr, uh->source, daddr, uh->dest, skb->dev->ifindex);
1219 int ret = udp_queue_rcv_skb(sk, skb);
1222 /* a return value > 0 means to resubmit the input, but
1223 * it it wants the return to be -protocol, or 0
1230 if (!xfrm4_policy_check(NULL, XFRM_POLICY_IN, skb))
1233 /* No socket. Drop packet silently, if checksum is wrong */
1234 if (udp_checksum_complete(skb))
1237 UDP_INC_STATS_BH(UdpNoPorts);
1238 icmp_send(skb, ICMP_DEST_UNREACH, ICMP_PORT_UNREACH, 0);
1241 * Hmm. We got an UDP packet to a port to which we
1242 * don't wanna listen. Ignore it.
1248 NETDEBUG(if (net_ratelimit())
1249 printk(KERN_DEBUG "UDP: short packet: From %u.%u.%u.%u:%u %d/%d to %u.%u.%u.%u:%u\n",
1257 UDP_INC_STATS_BH(UdpInErrors);
1263 * RFC1122: OK. Discards the bad packet silently (as far as
1264 * the network is concerned, anyway) as per 4.1.3.4 (MUST).
1266 NETDEBUG(if (net_ratelimit())
1267 printk(KERN_DEBUG "UDP: bad checksum. From %d.%d.%d.%d:%d to %d.%d.%d.%d:%d ulen %d\n",
1274 UDP_INC_STATS_BH(UdpInErrors);
1279 static int udp_destroy_sock(struct sock *sk)
1282 udp_flush_pending_frames(sk);
1288 * Socket option code for UDP
1290 static int udp_setsockopt(struct sock *sk, int level, int optname,
1291 char __user *optval, int optlen)
1293 struct udp_opt *up = udp_sk(sk);
1297 if (level != SOL_UDP)
1298 return ip_setsockopt(sk, level, optname, optval, optlen);
1300 if(optlen<sizeof(int))
1303 if (get_user(val, (int __user *)optval))
1313 udp_push_pending_frames(sk, up);
1321 case UDP_ENCAP_ESPINUDP:
1322 case UDP_ENCAP_ESPINUDP_NON_IKE:
1323 up->encap_type = val;
1339 static int udp_getsockopt(struct sock *sk, int level, int optname,
1340 char __user *optval, int __user *optlen)
1342 struct udp_opt *up = udp_sk(sk);
1345 if (level != SOL_UDP)
1346 return ip_getsockopt(sk, level, optname, optval, optlen);
1348 if(get_user(len,optlen))
1351 len = min_t(unsigned int, len, sizeof(int));
1362 val = up->encap_type;
1366 return -ENOPROTOOPT;
1369 if(put_user(len, optlen))
1371 if(copy_to_user(optval, &val,len))
1377 struct proto udp_prot = {
1380 .connect = udp_connect,
1381 .disconnect = udp_disconnect,
1383 .destroy = udp_destroy_sock,
1384 .setsockopt = udp_setsockopt,
1385 .getsockopt = udp_getsockopt,
1386 .sendmsg = udp_sendmsg,
1387 .recvmsg = udp_recvmsg,
1388 .sendpage = udp_sendpage,
1389 .backlog_rcv = udp_queue_rcv_skb,
1390 .hash = udp_v4_hash,
1391 .unhash = udp_v4_unhash,
1392 .get_port = udp_v4_get_port,
1395 /* ------------------------------------------------------------------------ */
1396 #ifdef CONFIG_PROC_FS
1398 static struct sock *udp_get_first(struct seq_file *seq)
1401 struct udp_iter_state *state = seq->private;
1403 for (state->bucket = 0; state->bucket < UDP_HTABLE_SIZE; ++state->bucket) {
1404 struct hlist_node *node;
1406 sk_for_each(sk, node, &udp_hash[state->bucket]) {
1407 if (sk->sk_family == state->family &&
1408 vx_check(sk->sk_xid, VX_WATCH|VX_IDENT))
1417 static struct sock *udp_get_next(struct seq_file *seq, struct sock *sk)
1419 struct udp_iter_state *state = seq->private;
1425 } while (sk && (sk->sk_family != state->family ||
1426 !vx_check(sk->sk_xid, VX_WATCH|VX_IDENT)));
1428 if (!sk && ++state->bucket < UDP_HTABLE_SIZE) {
1429 sk = sk_head(&udp_hash[state->bucket]);
1435 static struct sock *udp_get_idx(struct seq_file *seq, loff_t pos)
1437 struct sock *sk = udp_get_first(seq);
1440 while(pos && (sk = udp_get_next(seq, sk)) != NULL)
1442 return pos ? NULL : sk;
1445 static void *udp_seq_start(struct seq_file *seq, loff_t *pos)
1447 read_lock(&udp_hash_lock);
1448 return *pos ? udp_get_idx(seq, *pos-1) : (void *)1;
1451 static void *udp_seq_next(struct seq_file *seq, void *v, loff_t *pos)
1456 sk = udp_get_idx(seq, 0);
1458 sk = udp_get_next(seq, v);
1464 static void udp_seq_stop(struct seq_file *seq, void *v)
1466 read_unlock(&udp_hash_lock);
1469 static int udp_seq_open(struct inode *inode, struct file *file)
1471 struct udp_seq_afinfo *afinfo = PDE(inode)->data;
1472 struct seq_file *seq;
1474 struct udp_iter_state *s = kmalloc(sizeof(*s), GFP_KERNEL);
1478 memset(s, 0, sizeof(*s));
1479 s->family = afinfo->family;
1480 s->seq_ops.start = udp_seq_start;
1481 s->seq_ops.next = udp_seq_next;
1482 s->seq_ops.show = afinfo->seq_show;
1483 s->seq_ops.stop = udp_seq_stop;
1485 rc = seq_open(file, &s->seq_ops);
1489 seq = file->private_data;
1498 /* ------------------------------------------------------------------------ */
1499 int udp_proc_register(struct udp_seq_afinfo *afinfo)
1501 struct proc_dir_entry *p;
1506 afinfo->seq_fops->owner = afinfo->owner;
1507 afinfo->seq_fops->open = udp_seq_open;
1508 afinfo->seq_fops->read = seq_read;
1509 afinfo->seq_fops->llseek = seq_lseek;
1510 afinfo->seq_fops->release = seq_release_private;
1512 p = proc_net_fops_create(afinfo->name, S_IRUGO, afinfo->seq_fops);
1520 void udp_proc_unregister(struct udp_seq_afinfo *afinfo)
1524 proc_net_remove(afinfo->name);
1525 memset(afinfo->seq_fops, 0, sizeof(*afinfo->seq_fops));
1528 /* ------------------------------------------------------------------------ */
1529 static void udp4_format_sock(struct sock *sp, char *tmpbuf, int bucket)
1531 struct inet_opt *inet = inet_sk(sp);
1532 unsigned int dest = inet->daddr;
1533 unsigned int src = inet->rcv_saddr;
1534 __u16 destp = ntohs(inet->dport);
1535 __u16 srcp = ntohs(inet->sport);
1537 sprintf(tmpbuf, "%4d: %08X:%04X %08X:%04X"
1538 " %02X %08X:%08X %02X:%08lX %08X %5d %8d %lu %d %p",
1539 bucket, src, srcp, dest, destp, sp->sk_state,
1540 atomic_read(&sp->sk_wmem_alloc),
1541 atomic_read(&sp->sk_rmem_alloc),
1542 0, 0L, 0, sock_i_uid(sp), 0, sock_i_ino(sp),
1543 atomic_read(&sp->sk_refcnt), sp);
1546 static int udp4_seq_show(struct seq_file *seq, void *v)
1548 if (v == SEQ_START_TOKEN)
1549 seq_printf(seq, "%-127s\n",
1550 " sl local_address rem_address st tx_queue "
1551 "rx_queue tr tm->when retrnsmt uid timeout "
1555 struct udp_iter_state *state = seq->private;
1557 udp4_format_sock(v, tmpbuf, state->bucket);
1558 seq_printf(seq, "%-127s\n", tmpbuf);
1563 /* ------------------------------------------------------------------------ */
1564 static struct file_operations udp4_seq_fops;
1565 static struct udp_seq_afinfo udp4_seq_afinfo = {
1566 .owner = THIS_MODULE,
1569 .seq_show = udp4_seq_show,
1570 .seq_fops = &udp4_seq_fops,
1573 int __init udp4_proc_init(void)
1575 return udp_proc_register(&udp4_seq_afinfo);
1578 void udp4_proc_exit(void)
1580 udp_proc_unregister(&udp4_seq_afinfo);
1582 #endif /* CONFIG_PROC_FS */
1584 EXPORT_SYMBOL(udp_connect);
1585 EXPORT_SYMBOL(udp_disconnect);
1586 EXPORT_SYMBOL(udp_hash);
1587 EXPORT_SYMBOL(udp_hash_lock);
1588 EXPORT_SYMBOL(udp_ioctl);
1589 EXPORT_SYMBOL(udp_port_rover);
1590 EXPORT_SYMBOL(udp_prot);
1591 EXPORT_SYMBOL(udp_sendmsg);
1593 #ifdef CONFIG_PROC_FS
1594 EXPORT_SYMBOL(udp_proc_register);
1595 EXPORT_SYMBOL(udp_proc_unregister);