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 /* Shared by v4/v6 udp. */
124 static int udp_v4_get_port(struct sock *sk, unsigned short snum)
126 struct hlist_node *node;
128 struct inet_sock *inet = inet_sk(sk);
130 write_lock_bh(&udp_hash_lock);
132 int best_size_so_far, best, result, i;
134 if (udp_port_rover > sysctl_local_port_range[1] ||
135 udp_port_rover < sysctl_local_port_range[0])
136 udp_port_rover = sysctl_local_port_range[0];
137 best_size_so_far = 32767;
138 best = result = udp_port_rover;
139 for (i = 0; i < UDP_HTABLE_SIZE; i++, result++) {
140 struct hlist_head *list;
143 list = &udp_hash[result & (UDP_HTABLE_SIZE - 1)];
144 if (hlist_empty(list)) {
145 if (result > sysctl_local_port_range[1])
146 result = sysctl_local_port_range[0] +
147 ((result - sysctl_local_port_range[0]) &
148 (UDP_HTABLE_SIZE - 1));
152 sk_for_each(sk2, node, list)
153 if (++size >= best_size_so_far)
155 best_size_so_far = size;
160 for(i = 0; i < (1 << 16) / UDP_HTABLE_SIZE; i++, result += UDP_HTABLE_SIZE) {
161 if (result > sysctl_local_port_range[1])
162 result = sysctl_local_port_range[0]
163 + ((result - sysctl_local_port_range[0]) &
164 (UDP_HTABLE_SIZE - 1));
165 if (!udp_lport_inuse(result))
168 if (i >= (1 << 16) / UDP_HTABLE_SIZE)
171 udp_port_rover = snum = result;
173 sk_for_each(sk2, node,
174 &udp_hash[snum & (UDP_HTABLE_SIZE - 1)]) {
175 struct inet_sock *inet2 = inet_sk(sk2);
177 if (inet2->num == snum &&
178 sk2 != sk && !ipv6_only_sock(sk2) &&
179 (!sk2->sk_bound_dev_if ||
180 !sk->sk_bound_dev_if ||
181 sk2->sk_bound_dev_if == sk->sk_bound_dev_if) &&
182 nx_addr_conflict(sk->sk_nx_info,
183 inet_rcv_saddr(sk), sk2) &&
184 (!sk2->sk_reuse || !sk->sk_reuse))
189 if (sk_unhashed(sk)) {
190 struct hlist_head *h = &udp_hash[snum & (UDP_HTABLE_SIZE - 1)];
193 sock_prot_inc_use(sk->sk_prot);
195 write_unlock_bh(&udp_hash_lock);
199 write_unlock_bh(&udp_hash_lock);
203 static void udp_v4_hash(struct sock *sk)
208 static void udp_v4_unhash(struct sock *sk)
210 write_lock_bh(&udp_hash_lock);
211 if (sk_del_node_init(sk)) {
212 inet_sk(sk)->num = 0;
213 sock_prot_dec_use(sk->sk_prot);
215 write_unlock_bh(&udp_hash_lock);
218 /* UDP is nearly always wildcards out the wazoo, it makes no sense to try
219 * harder than this. -DaveM
221 static struct sock *udp_v4_lookup_longway(u32 saddr, u16 sport,
222 u32 daddr, u16 dport, int dif)
224 struct sock *sk, *result = NULL;
225 struct hlist_node *node;
226 unsigned short hnum = ntohs(dport);
229 sk_for_each(sk, node, &udp_hash[hnum & (UDP_HTABLE_SIZE - 1)]) {
230 struct inet_sock *inet = inet_sk(sk);
232 if (inet->num == hnum && !ipv6_only_sock(sk)) {
233 int score = (sk->sk_family == PF_INET ? 1 : 0);
234 if (inet->rcv_saddr) {
235 if (inet->rcv_saddr != daddr)
238 } else if (sk->sk_nx_info) {
239 if (addr_in_nx_info(sk->sk_nx_info, daddr))
245 if (inet->daddr != saddr)
250 if (inet->dport != sport)
254 if (sk->sk_bound_dev_if) {
255 if (sk->sk_bound_dev_if != dif)
262 } else if(score > badness) {
271 static __inline__ struct sock *udp_v4_lookup(u32 saddr, u16 sport,
272 u32 daddr, u16 dport, int dif)
276 read_lock(&udp_hash_lock);
277 sk = udp_v4_lookup_longway(saddr, sport, daddr, dport, dif);
280 read_unlock(&udp_hash_lock);
284 static inline struct sock *udp_v4_mcast_next(struct sock *sk,
285 u16 loc_port, u32 loc_addr,
286 u16 rmt_port, u32 rmt_addr,
289 struct hlist_node *node;
291 unsigned short hnum = ntohs(loc_port);
293 sk_for_each_from(s, node) {
294 struct inet_sock *inet = inet_sk(s);
296 if (inet->num != hnum ||
297 (inet->daddr && inet->daddr != rmt_addr) ||
298 (inet->dport != rmt_port && inet->dport) ||
299 (inet->rcv_saddr && inet->rcv_saddr != loc_addr &&
300 inet->rcv_saddr2 && inet->rcv_saddr2 != loc_addr) ||
302 (s->sk_bound_dev_if && s->sk_bound_dev_if != dif))
304 if (!ip_mc_sf_allow(s, loc_addr, rmt_addr, dif))
314 * This routine is called by the ICMP module when it gets some
315 * sort of error condition. If err < 0 then the socket should
316 * be closed and the error returned to the user. If err > 0
317 * it's just the icmp type << 8 | icmp code.
318 * Header points to the ip header of the error packet. We move
319 * on past this. Then (as it used to claim before adjustment)
320 * header points to the first 8 bytes of the udp header. We need
321 * to find the appropriate port.
324 void udp_err(struct sk_buff *skb, u32 info)
326 struct inet_sock *inet;
327 struct iphdr *iph = (struct iphdr*)skb->data;
328 struct udphdr *uh = (struct udphdr*)(skb->data+(iph->ihl<<2));
329 int type = skb->h.icmph->type;
330 int code = skb->h.icmph->code;
335 sk = udp_v4_lookup(iph->daddr, uh->dest, iph->saddr, uh->source, skb->dev->ifindex);
337 ICMP_INC_STATS_BH(ICMP_MIB_INERRORS);
338 return; /* No socket for error */
347 case ICMP_TIME_EXCEEDED:
350 case ICMP_SOURCE_QUENCH:
352 case ICMP_PARAMETERPROB:
356 case ICMP_DEST_UNREACH:
357 if (code == ICMP_FRAG_NEEDED) { /* Path MTU discovery */
358 if (inet->pmtudisc != IP_PMTUDISC_DONT) {
366 if (code <= NR_ICMP_UNREACH) {
367 harderr = icmp_err_convert[code].fatal;
368 err = icmp_err_convert[code].errno;
374 * RFC1122: OK. Passes ICMP errors back to application, as per
377 if (!inet->recverr) {
378 if (!harderr || sk->sk_state != TCP_ESTABLISHED)
381 ip_icmp_error(sk, skb, err, uh->dest, info, (u8*)(uh+1));
384 sk->sk_error_report(sk);
390 * Throw away all pending data and cancel the corking. Socket is locked.
392 static void udp_flush_pending_frames(struct sock *sk)
394 struct udp_sock *up = udp_sk(sk);
399 ip_flush_pending_frames(sk);
404 * Push out all pending data as one UDP datagram. Socket is locked.
406 static int udp_push_pending_frames(struct sock *sk, struct udp_sock *up)
408 struct inet_sock *inet = inet_sk(sk);
409 struct flowi *fl = &inet->cork.fl;
414 /* Grab the skbuff where UDP header space exists. */
415 if ((skb = skb_peek(&sk->sk_write_queue)) == NULL)
419 * Create a UDP header
422 uh->source = fl->fl_ip_sport;
423 uh->dest = fl->fl_ip_dport;
424 uh->len = htons(up->len);
427 if (sk->sk_no_check == UDP_CSUM_NOXMIT) {
428 skb->ip_summed = CHECKSUM_NONE;
432 if (skb_queue_len(&sk->sk_write_queue) == 1) {
434 * Only one fragment on the socket.
436 if (skb->ip_summed == CHECKSUM_HW) {
437 skb->csum = offsetof(struct udphdr, check);
438 uh->check = ~csum_tcpudp_magic(fl->fl4_src, fl->fl4_dst,
439 up->len, IPPROTO_UDP, 0);
441 skb->csum = csum_partial((char *)uh,
442 sizeof(struct udphdr), skb->csum);
443 uh->check = csum_tcpudp_magic(fl->fl4_src, fl->fl4_dst,
444 up->len, IPPROTO_UDP, skb->csum);
449 unsigned int csum = 0;
451 * HW-checksum won't work as there are two or more
452 * fragments on the socket so that all csums of sk_buffs
453 * should be together.
455 if (skb->ip_summed == CHECKSUM_HW) {
456 int offset = (unsigned char *)uh - skb->data;
457 skb->csum = skb_checksum(skb, offset, skb->len - offset, 0);
459 skb->ip_summed = CHECKSUM_NONE;
461 skb->csum = csum_partial((char *)uh,
462 sizeof(struct udphdr), skb->csum);
465 skb_queue_walk(&sk->sk_write_queue, skb) {
466 csum = csum_add(csum, skb->csum);
468 uh->check = csum_tcpudp_magic(fl->fl4_src, fl->fl4_dst,
469 up->len, IPPROTO_UDP, csum);
474 err = ip_push_pending_frames(sk);
482 static unsigned short udp_check(struct udphdr *uh, int len, unsigned long saddr, unsigned long daddr, unsigned long base)
484 return(csum_tcpudp_magic(saddr, daddr, len, IPPROTO_UDP, base));
487 int udp_sendmsg(struct kiocb *iocb, struct sock *sk, struct msghdr *msg,
490 struct inet_sock *inet = inet_sk(sk);
491 struct udp_sock *up = udp_sk(sk);
493 struct ipcm_cookie ipc;
494 struct rtable *rt = NULL;
497 u32 daddr, faddr, saddr;
501 int corkreq = up->corkflag || msg->msg_flags&MSG_MORE;
510 if (msg->msg_flags&MSG_OOB) /* Mirror BSD error message compatibility */
517 * There are pending frames.
518 * The socket lock must be held while it's corked.
521 if (likely(up->pending)) {
522 if (unlikely(up->pending != AF_INET)) {
530 ulen += sizeof(struct udphdr);
533 * Get and verify the address.
536 struct sockaddr_in * usin = (struct sockaddr_in*)msg->msg_name;
537 if (msg->msg_namelen < sizeof(*usin))
539 if (usin->sin_family != AF_INET) {
540 if (usin->sin_family != AF_UNSPEC)
541 return -EAFNOSUPPORT;
544 daddr = usin->sin_addr.s_addr;
545 dport = usin->sin_port;
549 if (sk->sk_state != TCP_ESTABLISHED)
550 return -EDESTADDRREQ;
553 /* Open fast path for connected socket.
554 Route will not be used, if at least one option is set.
558 ipc.addr = inet->saddr;
560 ipc.oif = sk->sk_bound_dev_if;
561 if (msg->msg_controllen) {
562 err = ip_cmsg_send(msg, &ipc);
573 ipc.addr = faddr = daddr;
575 if (ipc.opt && ipc.opt->srr) {
578 faddr = ipc.opt->faddr;
581 tos = RT_TOS(inet->tos);
582 if (sock_flag(sk, SOCK_LOCALROUTE) ||
583 (msg->msg_flags & MSG_DONTROUTE) ||
584 (ipc.opt && ipc.opt->is_strictroute)) {
589 if (MULTICAST(daddr)) {
591 ipc.oif = inet->mc_index;
593 saddr = inet->mc_addr;
598 rt = (struct rtable*)sk_dst_check(sk, 0);
601 struct flowi fl = { .oif = ipc.oif,
606 .proto = IPPROTO_UDP,
608 { .sport = inet->sport,
609 .dport = dport } } };
610 struct nx_info *nxi = sk->sk_nx_info;
613 err = ip_find_src(nxi, &rt, &fl);
616 if (daddr == IPI_LOOPBACK && !vx_check(0, VX_ADMIN))
617 daddr = fl.fl4_dst = nxi->ipv4[0];
618 #ifdef CONFIG_VSERVER_REMAP_SADDR
619 if (saddr == IPI_LOOPBACK && !vx_check(0, VX_ADMIN))
620 saddr = fl.fl4_src = nxi->ipv4[0];
623 err = ip_route_output_flow(&rt, &fl, sk, !(msg->msg_flags&MSG_DONTWAIT));
628 if ((rt->rt_flags & RTCF_BROADCAST) &&
629 !sock_flag(sk, SOCK_BROADCAST))
632 sk_dst_set(sk, dst_clone(&rt->u.dst));
635 if (msg->msg_flags&MSG_CONFIRM)
641 daddr = ipc.addr = rt->rt_dst;
644 if (unlikely(up->pending)) {
645 /* The socket is already corked while preparing it. */
646 /* ... which is an evident application bug. --ANK */
649 LIMIT_NETDEBUG(KERN_DEBUG "udp cork app bug 2\n");
654 * Now cork the socket to pend data.
656 inet->cork.fl.fl4_dst = daddr;
657 inet->cork.fl.fl_ip_dport = dport;
658 inet->cork.fl.fl4_src = saddr;
659 inet->cork.fl.fl_ip_sport = inet->sport;
660 up->pending = AF_INET;
664 err = ip_append_data(sk, ip_generic_getfrag, msg->msg_iov, ulen,
665 sizeof(struct udphdr), &ipc, rt,
666 corkreq ? msg->msg_flags|MSG_MORE : msg->msg_flags);
668 udp_flush_pending_frames(sk);
670 err = udp_push_pending_frames(sk, up);
678 UDP_INC_STATS_USER(UDP_MIB_OUTDATAGRAMS);
684 dst_confirm(&rt->u.dst);
685 if (!(msg->msg_flags&MSG_PROBE) || len)
686 goto back_from_confirm;
691 static int udp_sendpage(struct sock *sk, struct page *page, int offset,
692 size_t size, int flags)
694 struct udp_sock *up = udp_sk(sk);
698 struct msghdr msg = { .msg_flags = flags|MSG_MORE };
700 /* Call udp_sendmsg to specify destination address which
701 * sendpage interface can't pass.
702 * This will succeed only when the socket is connected.
704 ret = udp_sendmsg(NULL, sk, &msg, 0);
711 if (unlikely(!up->pending)) {
714 LIMIT_NETDEBUG(KERN_DEBUG "udp cork app bug 3\n");
718 ret = ip_append_page(sk, page, offset, size, flags);
719 if (ret == -EOPNOTSUPP) {
721 return sock_no_sendpage(sk->sk_socket, page, offset,
725 udp_flush_pending_frames(sk);
730 if (!(up->corkflag || (flags&MSG_MORE)))
731 ret = udp_push_pending_frames(sk, up);
740 * IOCTL requests applicable to the UDP protocol
743 int udp_ioctl(struct sock *sk, int cmd, unsigned long arg)
749 int amount = atomic_read(&sk->sk_wmem_alloc);
750 return put_user(amount, (int __user *)arg);
756 unsigned long amount;
759 spin_lock_bh(&sk->sk_receive_queue.lock);
760 skb = skb_peek(&sk->sk_receive_queue);
763 * We will only return the amount
764 * of this packet since that is all
767 amount = skb->len - sizeof(struct udphdr);
769 spin_unlock_bh(&sk->sk_receive_queue.lock);
770 return put_user(amount, (int __user *)arg);
779 static __inline__ int __udp_checksum_complete(struct sk_buff *skb)
781 return __skb_checksum_complete(skb);
784 static __inline__ int udp_checksum_complete(struct sk_buff *skb)
786 return skb->ip_summed != CHECKSUM_UNNECESSARY &&
787 __udp_checksum_complete(skb);
791 * This should be easy, if there is something there we
792 * return it, otherwise we block.
795 static int udp_recvmsg(struct kiocb *iocb, struct sock *sk, struct msghdr *msg,
796 size_t len, int noblock, int flags, int *addr_len)
798 struct inet_sock *inet = inet_sk(sk);
799 struct sockaddr_in *sin = (struct sockaddr_in *)msg->msg_name;
804 * Check any passed addresses
807 *addr_len=sizeof(*sin);
809 if (flags & MSG_ERRQUEUE)
810 return ip_recv_error(sk, msg, len);
813 skb = skb_recv_datagram(sk, flags, noblock, &err);
817 copied = skb->len - sizeof(struct udphdr);
820 msg->msg_flags |= MSG_TRUNC;
823 if (skb->ip_summed==CHECKSUM_UNNECESSARY) {
824 err = skb_copy_datagram_iovec(skb, sizeof(struct udphdr), msg->msg_iov,
826 } else if (msg->msg_flags&MSG_TRUNC) {
827 if (__udp_checksum_complete(skb))
829 err = skb_copy_datagram_iovec(skb, sizeof(struct udphdr), msg->msg_iov,
832 err = skb_copy_and_csum_datagram_iovec(skb, sizeof(struct udphdr), msg->msg_iov);
841 sock_recv_timestamp(msg, sk, skb);
843 /* Copy the address. */
846 sin->sin_family = AF_INET;
847 sin->sin_port = skb->h.uh->source;
848 sin->sin_addr.s_addr = skb->nh.iph->saddr;
849 memset(sin->sin_zero, 0, sizeof(sin->sin_zero));
851 if (inet->cmsg_flags)
852 ip_cmsg_recv(msg, skb);
855 if (flags & MSG_TRUNC)
856 err = skb->len - sizeof(struct udphdr);
859 skb_free_datagram(sk, skb);
864 UDP_INC_STATS_BH(UDP_MIB_INERRORS);
866 skb_kill_datagram(sk, skb, flags);
874 int udp_disconnect(struct sock *sk, int flags)
876 struct inet_sock *inet = inet_sk(sk);
878 * 1003.1g - break association.
881 sk->sk_state = TCP_CLOSE;
884 sk->sk_bound_dev_if = 0;
885 if (!(sk->sk_userlocks & SOCK_BINDADDR_LOCK))
886 inet_reset_saddr(sk);
888 if (!(sk->sk_userlocks & SOCK_BINDPORT_LOCK)) {
889 sk->sk_prot->unhash(sk);
896 static void udp_close(struct sock *sk, long timeout)
898 sk_common_release(sk);
902 * 1 if the the UDP system should process it
903 * 0 if we should drop this packet
904 * -1 if it should get processed by xfrm4_rcv_encap
906 static int udp_encap_rcv(struct sock * sk, struct sk_buff *skb)
911 struct udp_sock *up = udp_sk(sk);
912 struct udphdr *uh = skb->h.uh;
916 __u8 *udpdata = (__u8 *)uh + sizeof(struct udphdr);
917 __u32 *udpdata32 = (__u32 *)udpdata;
918 __u16 encap_type = up->encap_type;
920 /* if we're overly short, let UDP handle it */
921 if (udpdata > skb->tail)
924 /* if this is not encapsulated socket, then just return now */
928 len = skb->tail - udpdata;
930 switch (encap_type) {
932 case UDP_ENCAP_ESPINUDP:
933 /* Check if this is a keepalive packet. If so, eat it. */
934 if (len == 1 && udpdata[0] == 0xff) {
936 } else if (len > sizeof(struct ip_esp_hdr) && udpdata32[0] != 0 ) {
937 /* ESP Packet without Non-ESP header */
938 len = sizeof(struct udphdr);
940 /* Must be an IKE packet.. pass it through */
943 case UDP_ENCAP_ESPINUDP_NON_IKE:
944 /* Check if this is a keepalive packet. If so, eat it. */
945 if (len == 1 && udpdata[0] == 0xff) {
947 } else if (len > 2 * sizeof(u32) + sizeof(struct ip_esp_hdr) &&
948 udpdata32[0] == 0 && udpdata32[1] == 0) {
950 /* ESP Packet with Non-IKE marker */
951 len = sizeof(struct udphdr) + 2 * sizeof(u32);
953 /* Must be an IKE packet.. pass it through */
958 /* At this point we are sure that this is an ESPinUDP packet,
959 * so we need to remove 'len' bytes from the packet (the UDP
960 * header and optional ESP marker bytes) and then modify the
961 * protocol to ESP, and then call into the transform receiver.
963 if (skb_cloned(skb) && pskb_expand_head(skb, 0, 0, GFP_ATOMIC))
966 /* Now we can update and verify the packet length... */
968 iphlen = iph->ihl << 2;
969 iph->tot_len = htons(ntohs(iph->tot_len) - len);
970 if (skb->len < iphlen + len) {
971 /* packet is too small!?! */
975 /* pull the data buffer up to the ESP header and set the
976 * transport header to point to ESP. Keep UDP on the stack
979 skb->h.raw = skb_pull(skb, len);
981 /* modify the protocol (it's ESP!) */
982 iph->protocol = IPPROTO_ESP;
984 /* and let the caller know to send this into the ESP processor... */
992 * >0: "udp encap" protocol resubmission
994 * Note that in the success and error cases, the skb is assumed to
995 * have either been requeued or freed.
997 static int udp_queue_rcv_skb(struct sock * sk, struct sk_buff *skb)
999 struct udp_sock *up = udp_sk(sk);
1002 * Charge it to the socket, dropping if the queue is full.
1004 if (!xfrm4_policy_check(sk, XFRM_POLICY_IN, skb)) {
1010 if (up->encap_type) {
1012 * This is an encapsulation socket, so let's see if this is
1013 * an encapsulated packet.
1014 * If it's a keepalive packet, then just eat it.
1015 * If it's an encapsulateed packet, then pass it to the
1016 * IPsec xfrm input and return the response
1017 * appropriately. Otherwise, just fall through and
1018 * pass this up the UDP socket.
1022 ret = udp_encap_rcv(sk, skb);
1024 /* Eat the packet .. */
1029 /* process the ESP packet */
1030 ret = xfrm4_rcv_encap(skb, up->encap_type);
1031 UDP_INC_STATS_BH(UDP_MIB_INDATAGRAMS);
1034 /* FALLTHROUGH -- it's a UDP Packet */
1037 if (sk->sk_filter && skb->ip_summed != CHECKSUM_UNNECESSARY) {
1038 if (__udp_checksum_complete(skb)) {
1039 UDP_INC_STATS_BH(UDP_MIB_INERRORS);
1043 skb->ip_summed = CHECKSUM_UNNECESSARY;
1046 if (sock_queue_rcv_skb(sk,skb)<0) {
1047 UDP_INC_STATS_BH(UDP_MIB_INERRORS);
1051 UDP_INC_STATS_BH(UDP_MIB_INDATAGRAMS);
1056 * Multicasts and broadcasts go to each listener.
1058 * Note: called only from the BH handler context,
1059 * so we don't need to lock the hashes.
1061 static int udp_v4_mcast_deliver(struct sk_buff *skb, struct udphdr *uh,
1062 u32 saddr, u32 daddr)
1067 read_lock(&udp_hash_lock);
1068 sk = sk_head(&udp_hash[ntohs(uh->dest) & (UDP_HTABLE_SIZE - 1)]);
1069 dif = skb->dev->ifindex;
1070 sk = udp_v4_mcast_next(sk, uh->dest, daddr, uh->source, saddr, dif);
1072 struct sock *sknext = NULL;
1075 struct sk_buff *skb1 = skb;
1077 sknext = udp_v4_mcast_next(sk_next(sk), uh->dest, daddr,
1078 uh->source, saddr, dif);
1080 skb1 = skb_clone(skb, GFP_ATOMIC);
1083 int ret = udp_queue_rcv_skb(sk, skb1);
1085 /* we should probably re-process instead
1086 * of dropping packets here. */
1093 read_unlock(&udp_hash_lock);
1097 /* Initialize UDP checksum. If exited with zero value (success),
1098 * CHECKSUM_UNNECESSARY means, that no more checks are required.
1099 * Otherwise, csum completion requires chacksumming packet body,
1100 * including udp header and folding it to skb->csum.
1102 static void udp_checksum_init(struct sk_buff *skb, struct udphdr *uh,
1103 unsigned short ulen, u32 saddr, u32 daddr)
1105 if (uh->check == 0) {
1106 skb->ip_summed = CHECKSUM_UNNECESSARY;
1107 } else if (skb->ip_summed == CHECKSUM_HW) {
1108 if (!udp_check(uh, ulen, saddr, daddr, skb->csum))
1109 skb->ip_summed = CHECKSUM_UNNECESSARY;
1111 if (skb->ip_summed != CHECKSUM_UNNECESSARY)
1112 skb->csum = csum_tcpudp_nofold(saddr, daddr, ulen, IPPROTO_UDP, 0);
1113 /* Probably, we should checksum udp header (it should be in cache
1114 * in any case) and data in tiny packets (< rx copybreak).
1118 /* XXX (mef) need to generalize the IPOD stuff. Right now I am borrowing
1119 from the ICMP infrastructure. */
1120 #ifdef CONFIG_ICMP_IPOD
1121 #include <linux/reboot.h>
1123 extern int sysctl_icmp_ipod_version;
1124 extern int sysctl_icmp_ipod_enabled;
1125 extern u32 sysctl_icmp_ipod_host;
1126 extern u32 sysctl_icmp_ipod_mask;
1127 extern char sysctl_icmp_ipod_key[32+1];
1128 #define IPOD_CHECK_KEY \
1129 (sysctl_icmp_ipod_key[0] != 0)
1130 #define IPOD_VALID_KEY(d) \
1131 (strncmp(sysctl_icmp_ipod_key, (char *)(d), strlen(sysctl_icmp_ipod_key)) == 0)
1133 static void udp_ping_of_death(struct sk_buff *skb, struct udphdr *uh, u32 saddr)
1138 * If IPOD not enabled or wrong UDP IPOD port, ignore.
1140 if (!sysctl_icmp_ipod_enabled || (ntohs(uh->dest) != 664))
1144 printk(KERN_INFO "IPOD: got udp pod request, host=%u.%u.%u.%u\n", NIPQUAD(saddr));
1149 * First check the source address info.
1150 * If host not set, ignore.
1152 if (sysctl_icmp_ipod_host != 0xffffffff &&
1153 (ntohl(saddr) & sysctl_icmp_ipod_mask) == sysctl_icmp_ipod_host) {
1155 * Now check the key if enabled.
1156 * If packet doesn't contain enough data or key
1157 * is otherwise invalid, ignore.
1159 if (IPOD_CHECK_KEY) {
1160 if (pskb_may_pull(skb, sizeof(sysctl_icmp_ipod_key)+sizeof(struct udphdr)-1)){
1163 for (i=0;i<32+1;i++){
1164 printk("%c",((char*)skb->data)[i+sizeof(struct udphdr)]);
1168 if (IPOD_VALID_KEY(skb->data+sizeof(struct udphdr)))
1176 sysctl_icmp_ipod_enabled = 0;
1177 printk(KERN_CRIT "IPOD: reboot forced by %u.%u.%u.%u...\n",
1179 machine_restart(NULL);
1181 printk(KERN_WARNING "IPOD: from %u.%u.%u.%u rejected\n",
1188 * All we need to do is get the socket, and then do a checksum.
1191 int udp_rcv(struct sk_buff *skb)
1195 unsigned short ulen;
1196 struct rtable *rt = (struct rtable*)skb->dst;
1197 u32 saddr = skb->nh.iph->saddr;
1198 u32 daddr = skb->nh.iph->daddr;
1202 * Validate the packet and the UDP length.
1204 if (!pskb_may_pull(skb, sizeof(struct udphdr)))
1209 ulen = ntohs(uh->len);
1211 if (ulen > len || ulen < sizeof(*uh))
1214 if (pskb_trim_rcsum(skb, ulen))
1217 udp_checksum_init(skb, uh, ulen, saddr, daddr);
1219 if(rt->rt_flags & (RTCF_BROADCAST|RTCF_MULTICAST))
1220 return udp_v4_mcast_deliver(skb, uh, saddr, daddr);
1222 #ifdef CONFIG_ICMP_IPOD
1223 udp_ping_of_death(skb, uh, saddr);
1226 sk = udp_v4_lookup(saddr, uh->source, daddr, uh->dest, skb->dev->ifindex);
1229 int ret = udp_queue_rcv_skb(sk, skb);
1232 /* a return value > 0 means to resubmit the input, but
1233 * it it wants the return to be -protocol, or 0
1240 if (!xfrm4_policy_check(NULL, XFRM_POLICY_IN, skb))
1244 /* No socket. Drop packet silently, if checksum is wrong */
1245 if (udp_checksum_complete(skb))
1248 #if defined(CONFIG_VNET) || defined(CONFIG_VNET_MODULE)
1249 if (vnet_active && skb->sk) {
1250 /* VNET: Suppress ICMP Unreachable if the port was bound to a (presumably raw) socket */
1256 UDP_INC_STATS_BH(UDP_MIB_NOPORTS);
1257 icmp_send(skb, ICMP_DEST_UNREACH, ICMP_PORT_UNREACH, 0);
1260 * Hmm. We got an UDP packet to a port to which we
1261 * don't wanna listen. Ignore it.
1267 LIMIT_NETDEBUG(KERN_DEBUG "UDP: short packet: From %u.%u.%u.%u:%u %d/%d to %u.%u.%u.%u:%u\n",
1275 UDP_INC_STATS_BH(UDP_MIB_INERRORS);
1281 * RFC1122: OK. Discards the bad packet silently (as far as
1282 * the network is concerned, anyway) as per 4.1.3.4 (MUST).
1284 LIMIT_NETDEBUG(KERN_DEBUG "UDP: bad checksum. From %d.%d.%d.%d:%d to %d.%d.%d.%d:%d ulen %d\n",
1291 UDP_INC_STATS_BH(UDP_MIB_INERRORS);
1296 static int udp_destroy_sock(struct sock *sk)
1299 udp_flush_pending_frames(sk);
1305 * Socket option code for UDP
1307 static int do_udp_setsockopt(struct sock *sk, int level, int optname,
1308 char __user *optval, int optlen)
1310 struct udp_sock *up = udp_sk(sk);
1314 if(optlen<sizeof(int))
1317 if (get_user(val, (int __user *)optval))
1327 udp_push_pending_frames(sk, up);
1335 case UDP_ENCAP_ESPINUDP:
1336 case UDP_ENCAP_ESPINUDP_NON_IKE:
1337 up->encap_type = val;
1353 static int udp_setsockopt(struct sock *sk, int level, int optname,
1354 char __user *optval, int optlen)
1356 if (level != SOL_UDP)
1357 return ip_setsockopt(sk, level, optname, optval, optlen);
1358 return do_udp_setsockopt(sk, level, optname, optval, optlen);
1361 #ifdef CONFIG_COMPAT
1362 static int compat_udp_setsockopt(struct sock *sk, int level, int optname,
1363 char __user *optval, int optlen)
1365 if (level != SOL_UDP)
1366 return compat_ip_setsockopt(sk, level, optname, optval, optlen);
1367 return do_udp_setsockopt(sk, level, optname, optval, optlen);
1371 static int do_udp_getsockopt(struct sock *sk, int level, int optname,
1372 char __user *optval, int __user *optlen)
1374 struct udp_sock *up = udp_sk(sk);
1377 if(get_user(len,optlen))
1380 len = min_t(unsigned int, len, sizeof(int));
1391 val = up->encap_type;
1395 return -ENOPROTOOPT;
1398 if(put_user(len, optlen))
1400 if(copy_to_user(optval, &val,len))
1405 static int udp_getsockopt(struct sock *sk, int level, int optname,
1406 char __user *optval, int __user *optlen)
1408 if (level != SOL_UDP)
1409 return ip_getsockopt(sk, level, optname, optval, optlen);
1410 return do_udp_getsockopt(sk, level, optname, optval, optlen);
1413 #ifdef CONFIG_COMPAT
1414 static int compat_udp_getsockopt(struct sock *sk, int level, int optname,
1415 char __user *optval, int __user *optlen)
1417 if (level != SOL_UDP)
1418 return compat_ip_getsockopt(sk, level, optname, optval, optlen);
1419 return do_udp_getsockopt(sk, level, optname, optval, optlen);
1423 * udp_poll - wait for a UDP event.
1424 * @file - file struct
1426 * @wait - poll table
1428 * This is same as datagram poll, except for the special case of
1429 * blocking sockets. If application is using a blocking fd
1430 * and a packet with checksum error is in the queue;
1431 * then it could get return from select indicating data available
1432 * but then block when reading it. Add special case code
1433 * to work around these arguably broken applications.
1435 unsigned int udp_poll(struct file *file, struct socket *sock, poll_table *wait)
1437 unsigned int mask = datagram_poll(file, sock, wait);
1438 struct sock *sk = sock->sk;
1440 /* Check for false positives due to checksum errors */
1441 if ( (mask & POLLRDNORM) &&
1442 !(file->f_flags & O_NONBLOCK) &&
1443 !(sk->sk_shutdown & RCV_SHUTDOWN)){
1444 struct sk_buff_head *rcvq = &sk->sk_receive_queue;
1445 struct sk_buff *skb;
1447 spin_lock_bh(&rcvq->lock);
1448 while ((skb = skb_peek(rcvq)) != NULL) {
1449 if (udp_checksum_complete(skb)) {
1450 UDP_INC_STATS_BH(UDP_MIB_INERRORS);
1451 __skb_unlink(skb, rcvq);
1454 skb->ip_summed = CHECKSUM_UNNECESSARY;
1458 spin_unlock_bh(&rcvq->lock);
1460 /* nothing to see, move along */
1462 mask &= ~(POLLIN | POLLRDNORM);
1469 struct proto udp_prot = {
1471 .owner = THIS_MODULE,
1473 .connect = ip4_datagram_connect,
1474 .disconnect = udp_disconnect,
1476 .destroy = udp_destroy_sock,
1477 .setsockopt = udp_setsockopt,
1478 .getsockopt = udp_getsockopt,
1479 .sendmsg = udp_sendmsg,
1480 .recvmsg = udp_recvmsg,
1481 .sendpage = udp_sendpage,
1482 .backlog_rcv = udp_queue_rcv_skb,
1483 .hash = udp_v4_hash,
1484 .unhash = udp_v4_unhash,
1485 .get_port = udp_v4_get_port,
1486 .obj_size = sizeof(struct udp_sock),
1487 #ifdef CONFIG_COMPAT
1488 .compat_setsockopt = compat_udp_setsockopt,
1489 .compat_getsockopt = compat_udp_getsockopt,
1493 /* ------------------------------------------------------------------------ */
1494 #ifdef CONFIG_PROC_FS
1496 static struct sock *udp_get_first(struct seq_file *seq)
1499 struct udp_iter_state *state = seq->private;
1501 for (state->bucket = 0; state->bucket < UDP_HTABLE_SIZE; ++state->bucket) {
1502 struct hlist_node *node;
1504 sk_for_each(sk, node, &udp_hash[state->bucket]) {
1505 if (sk->sk_family == state->family &&
1506 vx_check(sk->sk_xid, VX_IDENT|VX_WATCH))
1515 static struct sock *udp_get_next(struct seq_file *seq, struct sock *sk)
1517 struct udp_iter_state *state = seq->private;
1523 } while (sk && (sk->sk_family != state->family ||
1524 !vx_check(sk->sk_xid, VX_IDENT|VX_WATCH)));
1526 if (!sk && ++state->bucket < UDP_HTABLE_SIZE) {
1527 sk = sk_head(&udp_hash[state->bucket]);
1533 static struct sock *udp_get_idx(struct seq_file *seq, loff_t pos)
1535 struct sock *sk = udp_get_first(seq);
1538 while(pos && (sk = udp_get_next(seq, sk)) != NULL)
1540 return pos ? NULL : sk;
1543 static void *udp_seq_start(struct seq_file *seq, loff_t *pos)
1545 read_lock(&udp_hash_lock);
1546 return *pos ? udp_get_idx(seq, *pos-1) : (void *)1;
1549 static void *udp_seq_next(struct seq_file *seq, void *v, loff_t *pos)
1554 sk = udp_get_idx(seq, 0);
1556 sk = udp_get_next(seq, v);
1562 static void udp_seq_stop(struct seq_file *seq, void *v)
1564 read_unlock(&udp_hash_lock);
1567 static int udp_seq_open(struct inode *inode, struct file *file)
1569 struct udp_seq_afinfo *afinfo = PDE(inode)->data;
1570 struct seq_file *seq;
1572 struct udp_iter_state *s = kzalloc(sizeof(*s), GFP_KERNEL);
1576 s->family = afinfo->family;
1577 s->seq_ops.start = udp_seq_start;
1578 s->seq_ops.next = udp_seq_next;
1579 s->seq_ops.show = afinfo->seq_show;
1580 s->seq_ops.stop = udp_seq_stop;
1582 rc = seq_open(file, &s->seq_ops);
1586 seq = file->private_data;
1595 /* ------------------------------------------------------------------------ */
1596 int udp_proc_register(struct udp_seq_afinfo *afinfo)
1598 struct proc_dir_entry *p;
1603 afinfo->seq_fops->owner = afinfo->owner;
1604 afinfo->seq_fops->open = udp_seq_open;
1605 afinfo->seq_fops->read = seq_read;
1606 afinfo->seq_fops->llseek = seq_lseek;
1607 afinfo->seq_fops->release = seq_release_private;
1609 p = proc_net_fops_create(afinfo->name, S_IRUGO, afinfo->seq_fops);
1617 void udp_proc_unregister(struct udp_seq_afinfo *afinfo)
1621 proc_net_remove(afinfo->name);
1622 memset(afinfo->seq_fops, 0, sizeof(*afinfo->seq_fops));
1625 /* ------------------------------------------------------------------------ */
1626 static void udp4_format_sock(struct sock *sp, char *tmpbuf, int bucket)
1628 struct inet_sock *inet = inet_sk(sp);
1629 unsigned int dest = inet->daddr;
1630 unsigned int src = inet->rcv_saddr;
1631 __u16 destp = ntohs(inet->dport);
1632 __u16 srcp = ntohs(inet->sport);
1634 sprintf(tmpbuf, "%4d: %08X:%04X %08X:%04X"
1635 " %02X %08X:%08X %02X:%08lX %08X %5d %8d %lu %d %p",
1636 bucket, src, srcp, dest, destp, sp->sk_state,
1637 atomic_read(&sp->sk_wmem_alloc),
1638 atomic_read(&sp->sk_rmem_alloc),
1639 0, 0L, 0, sock_i_uid(sp), 0, sock_i_ino(sp),
1640 atomic_read(&sp->sk_refcnt), sp);
1643 static int udp4_seq_show(struct seq_file *seq, void *v)
1645 if (v == SEQ_START_TOKEN)
1646 seq_printf(seq, "%-127s\n",
1647 " sl local_address rem_address st tx_queue "
1648 "rx_queue tr tm->when retrnsmt uid timeout "
1652 struct udp_iter_state *state = seq->private;
1654 udp4_format_sock(v, tmpbuf, state->bucket);
1655 seq_printf(seq, "%-127s\n", tmpbuf);
1660 /* ------------------------------------------------------------------------ */
1661 static struct file_operations udp4_seq_fops;
1662 static struct udp_seq_afinfo udp4_seq_afinfo = {
1663 .owner = THIS_MODULE,
1666 .seq_show = udp4_seq_show,
1667 .seq_fops = &udp4_seq_fops,
1670 int __init udp4_proc_init(void)
1672 return udp_proc_register(&udp4_seq_afinfo);
1675 void udp4_proc_exit(void)
1677 udp_proc_unregister(&udp4_seq_afinfo);
1679 #endif /* CONFIG_PROC_FS */
1681 EXPORT_SYMBOL(udp_disconnect);
1682 EXPORT_SYMBOL(udp_hash);
1683 EXPORT_SYMBOL(udp_hash_lock);
1684 EXPORT_SYMBOL(udp_ioctl);
1685 EXPORT_SYMBOL(udp_port_rover);
1686 EXPORT_SYMBOL(udp_prot);
1687 EXPORT_SYMBOL(udp_sendmsg);
1688 EXPORT_SYMBOL(udp_poll);
1690 #ifdef CONFIG_PROC_FS
1691 EXPORT_SYMBOL(udp_proc_register);
1692 EXPORT_SYMBOL(udp_proc_unregister);