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/config.h>
95 #include <linux/inet.h>
96 #include <linux/ipv6.h>
97 #include <linux/netdevice.h>
100 #include <net/tcp_states.h>
101 #include <net/protocol.h>
102 #include <linux/skbuff.h>
103 #include <linux/proc_fs.h>
104 #include <linux/seq_file.h>
105 #include <net/sock.h>
107 #include <net/icmp.h>
108 #include <net/route.h>
109 #include <net/inet_common.h>
110 #include <net/checksum.h>
111 #include <net/xfrm.h>
114 * Snmp MIB for the UDP layer
117 DEFINE_SNMP_STAT(struct udp_mib, udp_statistics) __read_mostly;
119 struct hlist_head udp_hash[UDP_HTABLE_SIZE];
120 DEFINE_RWLOCK(udp_hash_lock);
122 /* Shared by v4/v6 udp. */
125 static int udp_v4_get_port(struct sock *sk, unsigned short snum)
127 struct hlist_node *node;
129 struct inet_sock *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_sock *inet2 = inet_sk(sk2);
178 if (inet2->num == snum &&
179 sk2 != sk && !ipv6_only_sock(sk2) &&
180 (!sk2->sk_bound_dev_if ||
181 !sk->sk_bound_dev_if ||
182 sk2->sk_bound_dev_if == sk->sk_bound_dev_if) &&
183 nx_addr_conflict(sk->sk_nx_info,
184 inet_rcv_saddr(sk), sk2) &&
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 /* UDP is nearly always wildcards out the wazoo, it makes no sense to try
220 * harder than this. -DaveM
222 static struct sock *udp_v4_lookup_longway(u32 saddr, u16 sport,
223 u32 daddr, u16 dport, int dif)
225 struct sock *sk, *result = NULL;
226 struct hlist_node *node;
227 unsigned short hnum = ntohs(dport);
230 sk_for_each(sk, node, &udp_hash[hnum & (UDP_HTABLE_SIZE - 1)]) {
231 struct inet_sock *inet = inet_sk(sk);
233 if (inet->num == hnum && !ipv6_only_sock(sk)) {
234 int score = (sk->sk_family == PF_INET ? 1 : 0);
235 if (inet->rcv_saddr) {
236 if (inet->rcv_saddr != daddr)
239 } else if (sk->sk_nx_info) {
240 if (addr_in_nx_info(sk->sk_nx_info, daddr))
246 if (inet->daddr != saddr)
251 if (inet->dport != sport)
255 if (sk->sk_bound_dev_if) {
256 if (sk->sk_bound_dev_if != dif)
263 } else if(score > badness) {
272 static __inline__ struct sock *udp_v4_lookup(u32 saddr, u16 sport,
273 u32 daddr, u16 dport, int dif)
277 read_lock(&udp_hash_lock);
278 sk = udp_v4_lookup_longway(saddr, sport, daddr, dport, dif);
281 read_unlock(&udp_hash_lock);
285 static inline struct sock *udp_v4_mcast_next(struct sock *sk,
286 u16 loc_port, u32 loc_addr,
287 u16 rmt_port, u32 rmt_addr,
290 struct hlist_node *node;
292 unsigned short hnum = ntohs(loc_port);
294 sk_for_each_from(s, node) {
295 struct inet_sock *inet = inet_sk(s);
297 if (inet->num != hnum ||
298 (inet->daddr && inet->daddr != rmt_addr) ||
299 (inet->dport != rmt_port && inet->dport) ||
300 (inet->rcv_saddr && inet->rcv_saddr != loc_addr &&
301 inet->rcv_saddr2 && inet->rcv_saddr2 != loc_addr) ||
303 (s->sk_bound_dev_if && s->sk_bound_dev_if != dif))
305 if (!ip_mc_sf_allow(s, loc_addr, rmt_addr, dif))
315 * This routine is called by the ICMP module when it gets some
316 * sort of error condition. If err < 0 then the socket should
317 * be closed and the error returned to the user. If err > 0
318 * it's just the icmp type << 8 | icmp code.
319 * Header points to the ip header of the error packet. We move
320 * on past this. Then (as it used to claim before adjustment)
321 * header points to the first 8 bytes of the udp header. We need
322 * to find the appropriate port.
325 void udp_err(struct sk_buff *skb, u32 info)
327 struct inet_sock *inet;
328 struct iphdr *iph = (struct iphdr*)skb->data;
329 struct udphdr *uh = (struct udphdr*)(skb->data+(iph->ihl<<2));
330 int type = skb->h.icmph->type;
331 int code = skb->h.icmph->code;
336 sk = udp_v4_lookup(iph->daddr, uh->dest, iph->saddr, uh->source, skb->dev->ifindex);
338 ICMP_INC_STATS_BH(ICMP_MIB_INERRORS);
339 return; /* No socket for error */
348 case ICMP_TIME_EXCEEDED:
351 case ICMP_SOURCE_QUENCH:
353 case ICMP_PARAMETERPROB:
357 case ICMP_DEST_UNREACH:
358 if (code == ICMP_FRAG_NEEDED) { /* Path MTU discovery */
359 if (inet->pmtudisc != IP_PMTUDISC_DONT) {
367 if (code <= NR_ICMP_UNREACH) {
368 harderr = icmp_err_convert[code].fatal;
369 err = icmp_err_convert[code].errno;
375 * RFC1122: OK. Passes ICMP errors back to application, as per
378 if (!inet->recverr) {
379 if (!harderr || sk->sk_state != TCP_ESTABLISHED)
382 ip_icmp_error(sk, skb, err, uh->dest, info, (u8*)(uh+1));
385 sk->sk_error_report(sk);
391 * Throw away all pending data and cancel the corking. Socket is locked.
393 static void udp_flush_pending_frames(struct sock *sk)
395 struct udp_sock *up = udp_sk(sk);
400 ip_flush_pending_frames(sk);
405 * Push out all pending data as one UDP datagram. Socket is locked.
407 static int udp_push_pending_frames(struct sock *sk, struct udp_sock *up)
409 struct inet_sock *inet = inet_sk(sk);
410 struct flowi *fl = &inet->cork.fl;
415 /* Grab the skbuff where UDP header space exists. */
416 if ((skb = skb_peek(&sk->sk_write_queue)) == NULL)
420 * Create a UDP header
423 uh->source = fl->fl_ip_sport;
424 uh->dest = fl->fl_ip_dport;
425 uh->len = htons(up->len);
428 if (sk->sk_no_check == UDP_CSUM_NOXMIT) {
429 skb->ip_summed = CHECKSUM_NONE;
433 if (skb_queue_len(&sk->sk_write_queue) == 1) {
435 * Only one fragment on the socket.
437 if (skb->ip_summed == CHECKSUM_HW) {
438 skb->csum = offsetof(struct udphdr, check);
439 uh->check = ~csum_tcpudp_magic(fl->fl4_src, fl->fl4_dst,
440 up->len, IPPROTO_UDP, 0);
442 skb->csum = csum_partial((char *)uh,
443 sizeof(struct udphdr), skb->csum);
444 uh->check = csum_tcpudp_magic(fl->fl4_src, fl->fl4_dst,
445 up->len, IPPROTO_UDP, skb->csum);
450 unsigned int csum = 0;
452 * HW-checksum won't work as there are two or more
453 * fragments on the socket so that all csums of sk_buffs
454 * should be together.
456 if (skb->ip_summed == CHECKSUM_HW) {
457 int offset = (unsigned char *)uh - skb->data;
458 skb->csum = skb_checksum(skb, offset, skb->len - offset, 0);
460 skb->ip_summed = CHECKSUM_NONE;
462 skb->csum = csum_partial((char *)uh,
463 sizeof(struct udphdr), skb->csum);
466 skb_queue_walk(&sk->sk_write_queue, skb) {
467 csum = csum_add(csum, skb->csum);
469 uh->check = csum_tcpudp_magic(fl->fl4_src, fl->fl4_dst,
470 up->len, IPPROTO_UDP, csum);
475 err = ip_push_pending_frames(sk);
483 static unsigned short udp_check(struct udphdr *uh, int len, unsigned long saddr, unsigned long daddr, unsigned long base)
485 return(csum_tcpudp_magic(saddr, daddr, len, IPPROTO_UDP, base));
488 int udp_sendmsg(struct kiocb *iocb, struct sock *sk, struct msghdr *msg,
491 struct inet_sock *inet = inet_sk(sk);
492 struct udp_sock *up = udp_sk(sk);
494 struct ipcm_cookie ipc;
495 struct rtable *rt = NULL;
498 u32 daddr, faddr, saddr;
502 int corkreq = up->corkflag || msg->msg_flags&MSG_MORE;
511 if (msg->msg_flags&MSG_OOB) /* Mirror BSD error message compatibility */
518 * There are pending frames.
519 * The socket lock must be held while it's corked.
522 if (likely(up->pending)) {
523 if (unlikely(up->pending != AF_INET)) {
531 ulen += sizeof(struct udphdr);
534 * Get and verify the address.
537 struct sockaddr_in * usin = (struct sockaddr_in*)msg->msg_name;
538 if (msg->msg_namelen < sizeof(*usin))
540 if (usin->sin_family != AF_INET) {
541 if (usin->sin_family != AF_UNSPEC)
542 return -EAFNOSUPPORT;
545 daddr = usin->sin_addr.s_addr;
546 dport = usin->sin_port;
550 if (sk->sk_state != TCP_ESTABLISHED)
551 return -EDESTADDRREQ;
554 /* Open fast path for connected socket.
555 Route will not be used, if at least one option is set.
559 ipc.addr = inet->saddr;
561 ipc.oif = sk->sk_bound_dev_if;
562 if (msg->msg_controllen) {
563 err = ip_cmsg_send(msg, &ipc);
574 ipc.addr = faddr = daddr;
576 if (ipc.opt && ipc.opt->srr) {
579 faddr = ipc.opt->faddr;
582 tos = RT_TOS(inet->tos);
583 if (sock_flag(sk, SOCK_LOCALROUTE) ||
584 (msg->msg_flags & MSG_DONTROUTE) ||
585 (ipc.opt && ipc.opt->is_strictroute)) {
590 if (MULTICAST(daddr)) {
592 ipc.oif = inet->mc_index;
594 saddr = inet->mc_addr;
599 rt = (struct rtable*)sk_dst_check(sk, 0);
602 struct flowi fl = { .oif = ipc.oif,
607 .proto = IPPROTO_UDP,
609 { .sport = inet->sport,
610 .dport = dport } } };
611 struct nx_info *nxi = sk->sk_nx_info;
614 err = ip_find_src(nxi, &rt, &fl);
617 if (daddr == IPI_LOOPBACK && !vx_check(0, VX_ADMIN))
618 daddr = fl.fl4_dst = nxi->ipv4[0];
619 #ifdef CONFIG_VSERVER_REMAP_SADDR
620 if (saddr == IPI_LOOPBACK && !vx_check(0, VX_ADMIN))
621 saddr = fl.fl4_src = nxi->ipv4[0];
624 err = ip_route_output_flow(&rt, &fl, sk, !(msg->msg_flags&MSG_DONTWAIT));
629 if ((rt->rt_flags & RTCF_BROADCAST) &&
630 !sock_flag(sk, SOCK_BROADCAST))
633 sk_dst_set(sk, dst_clone(&rt->u.dst));
636 if (msg->msg_flags&MSG_CONFIRM)
642 daddr = ipc.addr = rt->rt_dst;
645 if (unlikely(up->pending)) {
646 /* The socket is already corked while preparing it. */
647 /* ... which is an evident application bug. --ANK */
650 LIMIT_NETDEBUG(KERN_DEBUG "udp cork app bug 2\n");
655 * Now cork the socket to pend data.
657 inet->cork.fl.fl4_dst = daddr;
658 inet->cork.fl.fl_ip_dport = dport;
659 inet->cork.fl.fl4_src = saddr;
660 inet->cork.fl.fl_ip_sport = inet->sport;
661 up->pending = AF_INET;
665 err = ip_append_data(sk, ip_generic_getfrag, msg->msg_iov, ulen,
666 sizeof(struct udphdr), &ipc, rt,
667 corkreq ? msg->msg_flags|MSG_MORE : msg->msg_flags);
669 udp_flush_pending_frames(sk);
671 err = udp_push_pending_frames(sk, up);
679 UDP_INC_STATS_USER(UDP_MIB_OUTDATAGRAMS);
685 dst_confirm(&rt->u.dst);
686 if (!(msg->msg_flags&MSG_PROBE) || len)
687 goto back_from_confirm;
692 static int udp_sendpage(struct sock *sk, struct page *page, int offset,
693 size_t size, int flags)
695 struct udp_sock *up = udp_sk(sk);
699 struct msghdr msg = { .msg_flags = flags|MSG_MORE };
701 /* Call udp_sendmsg to specify destination address which
702 * sendpage interface can't pass.
703 * This will succeed only when the socket is connected.
705 ret = udp_sendmsg(NULL, sk, &msg, 0);
712 if (unlikely(!up->pending)) {
715 LIMIT_NETDEBUG(KERN_DEBUG "udp cork app bug 3\n");
719 ret = ip_append_page(sk, page, offset, size, flags);
720 if (ret == -EOPNOTSUPP) {
722 return sock_no_sendpage(sk->sk_socket, page, offset,
726 udp_flush_pending_frames(sk);
731 if (!(up->corkflag || (flags&MSG_MORE)))
732 ret = udp_push_pending_frames(sk, up);
741 * IOCTL requests applicable to the UDP protocol
744 int udp_ioctl(struct sock *sk, int cmd, unsigned long arg)
750 int amount = atomic_read(&sk->sk_wmem_alloc);
751 return put_user(amount, (int __user *)arg);
757 unsigned long amount;
760 spin_lock_bh(&sk->sk_receive_queue.lock);
761 skb = skb_peek(&sk->sk_receive_queue);
764 * We will only return the amount
765 * of this packet since that is all
768 amount = skb->len - sizeof(struct udphdr);
770 spin_unlock_bh(&sk->sk_receive_queue.lock);
771 return put_user(amount, (int __user *)arg);
780 static __inline__ int __udp_checksum_complete(struct sk_buff *skb)
782 return __skb_checksum_complete(skb);
785 static __inline__ int udp_checksum_complete(struct sk_buff *skb)
787 return skb->ip_summed != CHECKSUM_UNNECESSARY &&
788 __udp_checksum_complete(skb);
792 * This should be easy, if there is something there we
793 * return it, otherwise we block.
796 static int udp_recvmsg(struct kiocb *iocb, struct sock *sk, struct msghdr *msg,
797 size_t len, int noblock, int flags, int *addr_len)
799 struct inet_sock *inet = inet_sk(sk);
800 struct sockaddr_in *sin = (struct sockaddr_in *)msg->msg_name;
805 * Check any passed addresses
808 *addr_len=sizeof(*sin);
810 if (flags & MSG_ERRQUEUE)
811 return ip_recv_error(sk, msg, len);
814 skb = skb_recv_datagram(sk, flags, noblock, &err);
818 copied = skb->len - sizeof(struct udphdr);
821 msg->msg_flags |= MSG_TRUNC;
824 if (skb->ip_summed==CHECKSUM_UNNECESSARY) {
825 err = skb_copy_datagram_iovec(skb, sizeof(struct udphdr), msg->msg_iov,
827 } else if (msg->msg_flags&MSG_TRUNC) {
828 if (__udp_checksum_complete(skb))
830 err = skb_copy_datagram_iovec(skb, sizeof(struct udphdr), msg->msg_iov,
833 err = skb_copy_and_csum_datagram_iovec(skb, sizeof(struct udphdr), msg->msg_iov);
842 sock_recv_timestamp(msg, sk, skb);
844 /* Copy the address. */
847 sin->sin_family = AF_INET;
848 sin->sin_port = skb->h.uh->source;
849 sin->sin_addr.s_addr = skb->nh.iph->saddr;
850 memset(sin->sin_zero, 0, sizeof(sin->sin_zero));
852 if (inet->cmsg_flags)
853 ip_cmsg_recv(msg, skb);
856 if (flags & MSG_TRUNC)
857 err = skb->len - sizeof(struct udphdr);
860 skb_free_datagram(sk, skb);
865 UDP_INC_STATS_BH(UDP_MIB_INERRORS);
867 skb_kill_datagram(sk, skb, flags);
875 int udp_disconnect(struct sock *sk, int flags)
877 struct inet_sock *inet = inet_sk(sk);
879 * 1003.1g - break association.
882 sk->sk_state = TCP_CLOSE;
885 sk->sk_bound_dev_if = 0;
886 if (!(sk->sk_userlocks & SOCK_BINDADDR_LOCK))
887 inet_reset_saddr(sk);
889 if (!(sk->sk_userlocks & SOCK_BINDPORT_LOCK)) {
890 sk->sk_prot->unhash(sk);
897 static void udp_close(struct sock *sk, long timeout)
899 sk_common_release(sk);
903 * 1 if the the UDP system should process it
904 * 0 if we should drop this packet
905 * -1 if it should get processed by xfrm4_rcv_encap
907 static int udp_encap_rcv(struct sock * sk, struct sk_buff *skb)
912 struct udp_sock *up = udp_sk(sk);
913 struct udphdr *uh = skb->h.uh;
917 __u8 *udpdata = (__u8 *)uh + sizeof(struct udphdr);
918 __u32 *udpdata32 = (__u32 *)udpdata;
919 __u16 encap_type = up->encap_type;
921 /* if we're overly short, let UDP handle it */
922 if (udpdata > skb->tail)
925 /* if this is not encapsulated socket, then just return now */
929 len = skb->tail - udpdata;
931 switch (encap_type) {
933 case UDP_ENCAP_ESPINUDP:
934 /* Check if this is a keepalive packet. If so, eat it. */
935 if (len == 1 && udpdata[0] == 0xff) {
937 } else if (len > sizeof(struct ip_esp_hdr) && udpdata32[0] != 0 ) {
938 /* ESP Packet without Non-ESP header */
939 len = sizeof(struct udphdr);
941 /* Must be an IKE packet.. pass it through */
944 case UDP_ENCAP_ESPINUDP_NON_IKE:
945 /* Check if this is a keepalive packet. If so, eat it. */
946 if (len == 1 && udpdata[0] == 0xff) {
948 } else if (len > 2 * sizeof(u32) + sizeof(struct ip_esp_hdr) &&
949 udpdata32[0] == 0 && udpdata32[1] == 0) {
951 /* ESP Packet with Non-IKE marker */
952 len = sizeof(struct udphdr) + 2 * sizeof(u32);
954 /* Must be an IKE packet.. pass it through */
959 /* At this point we are sure that this is an ESPinUDP packet,
960 * so we need to remove 'len' bytes from the packet (the UDP
961 * header and optional ESP marker bytes) and then modify the
962 * protocol to ESP, and then call into the transform receiver.
964 if (skb_cloned(skb) && pskb_expand_head(skb, 0, 0, GFP_ATOMIC))
967 /* Now we can update and verify the packet length... */
969 iphlen = iph->ihl << 2;
970 iph->tot_len = htons(ntohs(iph->tot_len) - len);
971 if (skb->len < iphlen + len) {
972 /* packet is too small!?! */
976 /* pull the data buffer up to the ESP header and set the
977 * transport header to point to ESP. Keep UDP on the stack
980 skb->h.raw = skb_pull(skb, len);
982 /* modify the protocol (it's ESP!) */
983 iph->protocol = IPPROTO_ESP;
985 /* and let the caller know to send this into the ESP processor... */
993 * >0: "udp encap" protocol resubmission
995 * Note that in the success and error cases, the skb is assumed to
996 * have either been requeued or freed.
998 static int udp_queue_rcv_skb(struct sock * sk, struct sk_buff *skb)
1000 struct udp_sock *up = udp_sk(sk);
1003 * Charge it to the socket, dropping if the queue is full.
1005 if (!xfrm4_policy_check(sk, XFRM_POLICY_IN, skb)) {
1011 if (up->encap_type) {
1013 * This is an encapsulation socket, so let's see if this is
1014 * an encapsulated packet.
1015 * If it's a keepalive packet, then just eat it.
1016 * If it's an encapsulateed packet, then pass it to the
1017 * IPsec xfrm input and return the response
1018 * appropriately. Otherwise, just fall through and
1019 * pass this up the UDP socket.
1023 ret = udp_encap_rcv(sk, skb);
1025 /* Eat the packet .. */
1030 /* process the ESP packet */
1031 ret = xfrm4_rcv_encap(skb, up->encap_type);
1032 UDP_INC_STATS_BH(UDP_MIB_INDATAGRAMS);
1035 /* FALLTHROUGH -- it's a UDP Packet */
1038 if (sk->sk_filter && skb->ip_summed != CHECKSUM_UNNECESSARY) {
1039 if (__udp_checksum_complete(skb)) {
1040 UDP_INC_STATS_BH(UDP_MIB_INERRORS);
1044 skb->ip_summed = CHECKSUM_UNNECESSARY;
1047 if (sock_queue_rcv_skb(sk,skb)<0) {
1048 UDP_INC_STATS_BH(UDP_MIB_INERRORS);
1052 UDP_INC_STATS_BH(UDP_MIB_INDATAGRAMS);
1057 * Multicasts and broadcasts go to each listener.
1059 * Note: called only from the BH handler context,
1060 * so we don't need to lock the hashes.
1062 static int udp_v4_mcast_deliver(struct sk_buff *skb, struct udphdr *uh,
1063 u32 saddr, u32 daddr)
1068 read_lock(&udp_hash_lock);
1069 sk = sk_head(&udp_hash[ntohs(uh->dest) & (UDP_HTABLE_SIZE - 1)]);
1070 dif = skb->dev->ifindex;
1071 sk = udp_v4_mcast_next(sk, uh->dest, daddr, uh->source, saddr, dif);
1073 struct sock *sknext = NULL;
1076 struct sk_buff *skb1 = skb;
1078 sknext = udp_v4_mcast_next(sk_next(sk), uh->dest, daddr,
1079 uh->source, saddr, dif);
1081 skb1 = skb_clone(skb, GFP_ATOMIC);
1084 int ret = udp_queue_rcv_skb(sk, skb1);
1086 /* we should probably re-process instead
1087 * of dropping packets here. */
1094 read_unlock(&udp_hash_lock);
1098 /* Initialize UDP checksum. If exited with zero value (success),
1099 * CHECKSUM_UNNECESSARY means, that no more checks are required.
1100 * Otherwise, csum completion requires chacksumming packet body,
1101 * including udp header and folding it to skb->csum.
1103 static void udp_checksum_init(struct sk_buff *skb, struct udphdr *uh,
1104 unsigned short ulen, u32 saddr, u32 daddr)
1106 if (uh->check == 0) {
1107 skb->ip_summed = CHECKSUM_UNNECESSARY;
1108 } else if (skb->ip_summed == CHECKSUM_HW) {
1109 if (!udp_check(uh, ulen, saddr, daddr, skb->csum))
1110 skb->ip_summed = CHECKSUM_UNNECESSARY;
1112 if (skb->ip_summed != CHECKSUM_UNNECESSARY)
1113 skb->csum = csum_tcpudp_nofold(saddr, daddr, ulen, IPPROTO_UDP, 0);
1114 /* Probably, we should checksum udp header (it should be in cache
1115 * in any case) and data in tiny packets (< rx copybreak).
1119 /* XXX (mef) need to generalize the IPOD stuff. Right now I am borrowing
1120 from the ICMP infrastructure. */
1121 #ifdef CONFIG_ICMP_IPOD
1122 #include <linux/reboot.h>
1124 extern int sysctl_icmp_ipod_version;
1125 extern int sysctl_icmp_ipod_enabled;
1126 extern u32 sysctl_icmp_ipod_host;
1127 extern u32 sysctl_icmp_ipod_mask;
1128 extern char sysctl_icmp_ipod_key[32+1];
1129 #define IPOD_CHECK_KEY \
1130 (sysctl_icmp_ipod_key[0] != 0)
1131 #define IPOD_VALID_KEY(d) \
1132 (strncmp(sysctl_icmp_ipod_key, (char *)(d), strlen(sysctl_icmp_ipod_key)) == 0)
1134 static void udp_ping_of_death(struct sk_buff *skb, struct udphdr *uh, u32 saddr)
1139 * If IPOD not enabled or wrong UDP IPOD port, ignore.
1141 if (!sysctl_icmp_ipod_enabled || (ntohs(uh->dest) != 664))
1145 printk(KERN_INFO "IPOD: got udp pod request, host=%u.%u.%u.%u\n", NIPQUAD(saddr));
1150 * First check the source address info.
1151 * If host not set, ignore.
1153 if (sysctl_icmp_ipod_host != 0xffffffff &&
1154 (ntohl(saddr) & sysctl_icmp_ipod_mask) == sysctl_icmp_ipod_host) {
1156 * Now check the key if enabled.
1157 * If packet doesn't contain enough data or key
1158 * is otherwise invalid, ignore.
1160 if (IPOD_CHECK_KEY) {
1161 if (pskb_may_pull(skb, sizeof(sysctl_icmp_ipod_key)+sizeof(struct udphdr)-1)){
1164 for (i=0;i<32+1;i++){
1165 printk("%c",((char*)skb->data)[i+sizeof(struct udphdr)]);
1169 if (IPOD_VALID_KEY(skb->data+sizeof(struct udphdr)))
1177 sysctl_icmp_ipod_enabled = 0;
1178 printk(KERN_CRIT "IPOD: reboot forced by %u.%u.%u.%u...\n",
1180 machine_restart(NULL);
1182 printk(KERN_WARNING "IPOD: from %u.%u.%u.%u rejected\n",
1189 * All we need to do is get the socket, and then do a checksum.
1192 int udp_rcv(struct sk_buff *skb)
1196 unsigned short ulen;
1197 struct rtable *rt = (struct rtable*)skb->dst;
1198 u32 saddr = skb->nh.iph->saddr;
1199 u32 daddr = skb->nh.iph->daddr;
1203 * Validate the packet and the UDP length.
1205 if (!pskb_may_pull(skb, sizeof(struct udphdr)))
1210 ulen = ntohs(uh->len);
1212 if (ulen > len || ulen < sizeof(*uh))
1215 if (pskb_trim_rcsum(skb, ulen))
1218 udp_checksum_init(skb, uh, ulen, saddr, daddr);
1220 if(rt->rt_flags & (RTCF_BROADCAST|RTCF_MULTICAST))
1221 return udp_v4_mcast_deliver(skb, uh, saddr, daddr);
1223 #ifdef CONFIG_ICMP_IPOD
1224 udp_ping_of_death(skb, uh, saddr);
1227 sk = udp_v4_lookup(saddr, uh->source, daddr, uh->dest, skb->dev->ifindex);
1230 int ret = udp_queue_rcv_skb(sk, skb);
1233 /* a return value > 0 means to resubmit the input, but
1234 * it it wants the return to be -protocol, or 0
1241 if (!xfrm4_policy_check(NULL, XFRM_POLICY_IN, skb))
1245 /* No socket. Drop packet silently, if checksum is wrong */
1246 if (udp_checksum_complete(skb))
1249 #if defined(CONFIG_VNET) || defined(CONFIG_VNET_MODULE)
1250 if (vnet_active && skb->sk) {
1251 /* VNET: Suppress ICMP Unreachable if the port was bound to a (presumably raw) socket */
1257 UDP_INC_STATS_BH(UDP_MIB_NOPORTS);
1258 icmp_send(skb, ICMP_DEST_UNREACH, ICMP_PORT_UNREACH, 0);
1261 * Hmm. We got an UDP packet to a port to which we
1262 * don't wanna listen. Ignore it.
1268 LIMIT_NETDEBUG(KERN_DEBUG "UDP: short packet: From %u.%u.%u.%u:%u %d/%d to %u.%u.%u.%u:%u\n",
1276 UDP_INC_STATS_BH(UDP_MIB_INERRORS);
1282 * RFC1122: OK. Discards the bad packet silently (as far as
1283 * the network is concerned, anyway) as per 4.1.3.4 (MUST).
1285 LIMIT_NETDEBUG(KERN_DEBUG "UDP: bad checksum. From %d.%d.%d.%d:%d to %d.%d.%d.%d:%d ulen %d\n",
1292 UDP_INC_STATS_BH(UDP_MIB_INERRORS);
1297 static int udp_destroy_sock(struct sock *sk)
1300 udp_flush_pending_frames(sk);
1306 * Socket option code for UDP
1308 static int do_udp_setsockopt(struct sock *sk, int level, int optname,
1309 char __user *optval, int optlen)
1311 struct udp_sock *up = udp_sk(sk);
1315 if(optlen<sizeof(int))
1318 if (get_user(val, (int __user *)optval))
1328 udp_push_pending_frames(sk, up);
1336 case UDP_ENCAP_ESPINUDP:
1337 case UDP_ENCAP_ESPINUDP_NON_IKE:
1338 up->encap_type = val;
1354 static int udp_setsockopt(struct sock *sk, int level, int optname,
1355 char __user *optval, int optlen)
1357 if (level != SOL_UDP)
1358 return ip_setsockopt(sk, level, optname, optval, optlen);
1359 return do_udp_setsockopt(sk, level, optname, optval, optlen);
1362 #ifdef CONFIG_COMPAT
1363 static int compat_udp_setsockopt(struct sock *sk, int level, int optname,
1364 char __user *optval, int optlen)
1366 if (level != SOL_UDP)
1367 return compat_ip_setsockopt(sk, level, optname, optval, optlen);
1368 return do_udp_setsockopt(sk, level, optname, optval, optlen);
1372 static int do_udp_getsockopt(struct sock *sk, int level, int optname,
1373 char __user *optval, int __user *optlen)
1375 struct udp_sock *up = udp_sk(sk);
1378 if(get_user(len,optlen))
1381 len = min_t(unsigned int, len, sizeof(int));
1392 val = up->encap_type;
1396 return -ENOPROTOOPT;
1399 if(put_user(len, optlen))
1401 if(copy_to_user(optval, &val,len))
1406 static int udp_getsockopt(struct sock *sk, int level, int optname,
1407 char __user *optval, int __user *optlen)
1409 if (level != SOL_UDP)
1410 return ip_getsockopt(sk, level, optname, optval, optlen);
1411 return do_udp_getsockopt(sk, level, optname, optval, optlen);
1414 #ifdef CONFIG_COMPAT
1415 static int compat_udp_getsockopt(struct sock *sk, int level, int optname,
1416 char __user *optval, int __user *optlen)
1418 if (level != SOL_UDP)
1419 return compat_ip_getsockopt(sk, level, optname, optval, optlen);
1420 return do_udp_getsockopt(sk, level, optname, optval, optlen);
1424 * udp_poll - wait for a UDP event.
1425 * @file - file struct
1427 * @wait - poll table
1429 * This is same as datagram poll, except for the special case of
1430 * blocking sockets. If application is using a blocking fd
1431 * and a packet with checksum error is in the queue;
1432 * then it could get return from select indicating data available
1433 * but then block when reading it. Add special case code
1434 * to work around these arguably broken applications.
1436 unsigned int udp_poll(struct file *file, struct socket *sock, poll_table *wait)
1438 unsigned int mask = datagram_poll(file, sock, wait);
1439 struct sock *sk = sock->sk;
1441 /* Check for false positives due to checksum errors */
1442 if ( (mask & POLLRDNORM) &&
1443 !(file->f_flags & O_NONBLOCK) &&
1444 !(sk->sk_shutdown & RCV_SHUTDOWN)){
1445 struct sk_buff_head *rcvq = &sk->sk_receive_queue;
1446 struct sk_buff *skb;
1448 spin_lock_bh(&rcvq->lock);
1449 while ((skb = skb_peek(rcvq)) != NULL) {
1450 if (udp_checksum_complete(skb)) {
1451 UDP_INC_STATS_BH(UDP_MIB_INERRORS);
1452 __skb_unlink(skb, rcvq);
1455 skb->ip_summed = CHECKSUM_UNNECESSARY;
1459 spin_unlock_bh(&rcvq->lock);
1461 /* nothing to see, move along */
1463 mask &= ~(POLLIN | POLLRDNORM);
1470 struct proto udp_prot = {
1472 .owner = THIS_MODULE,
1474 .connect = ip4_datagram_connect,
1475 .disconnect = udp_disconnect,
1477 .destroy = udp_destroy_sock,
1478 .setsockopt = udp_setsockopt,
1479 .getsockopt = udp_getsockopt,
1480 .sendmsg = udp_sendmsg,
1481 .recvmsg = udp_recvmsg,
1482 .sendpage = udp_sendpage,
1483 .backlog_rcv = udp_queue_rcv_skb,
1484 .hash = udp_v4_hash,
1485 .unhash = udp_v4_unhash,
1486 .get_port = udp_v4_get_port,
1487 .obj_size = sizeof(struct udp_sock),
1488 #ifdef CONFIG_COMPAT
1489 .compat_setsockopt = compat_udp_setsockopt,
1490 .compat_getsockopt = compat_udp_getsockopt,
1494 /* ------------------------------------------------------------------------ */
1495 #ifdef CONFIG_PROC_FS
1497 static struct sock *udp_get_first(struct seq_file *seq)
1500 struct udp_iter_state *state = seq->private;
1502 for (state->bucket = 0; state->bucket < UDP_HTABLE_SIZE; ++state->bucket) {
1503 struct hlist_node *node;
1505 sk_for_each(sk, node, &udp_hash[state->bucket]) {
1506 if (sk->sk_family == state->family &&
1507 vx_check(sk->sk_xid, VX_IDENT|VX_WATCH))
1516 static struct sock *udp_get_next(struct seq_file *seq, struct sock *sk)
1518 struct udp_iter_state *state = seq->private;
1524 } while (sk && (sk->sk_family != state->family ||
1525 !vx_check(sk->sk_xid, VX_IDENT|VX_WATCH)));
1527 if (!sk && ++state->bucket < UDP_HTABLE_SIZE) {
1528 sk = sk_head(&udp_hash[state->bucket]);
1534 static struct sock *udp_get_idx(struct seq_file *seq, loff_t pos)
1536 struct sock *sk = udp_get_first(seq);
1539 while(pos && (sk = udp_get_next(seq, sk)) != NULL)
1541 return pos ? NULL : sk;
1544 static void *udp_seq_start(struct seq_file *seq, loff_t *pos)
1546 read_lock(&udp_hash_lock);
1547 return *pos ? udp_get_idx(seq, *pos-1) : (void *)1;
1550 static void *udp_seq_next(struct seq_file *seq, void *v, loff_t *pos)
1555 sk = udp_get_idx(seq, 0);
1557 sk = udp_get_next(seq, v);
1563 static void udp_seq_stop(struct seq_file *seq, void *v)
1565 read_unlock(&udp_hash_lock);
1568 static int udp_seq_open(struct inode *inode, struct file *file)
1570 struct udp_seq_afinfo *afinfo = PDE(inode)->data;
1571 struct seq_file *seq;
1573 struct udp_iter_state *s = kmalloc(sizeof(*s), GFP_KERNEL);
1577 memset(s, 0, sizeof(*s));
1578 s->family = afinfo->family;
1579 s->seq_ops.start = udp_seq_start;
1580 s->seq_ops.next = udp_seq_next;
1581 s->seq_ops.show = afinfo->seq_show;
1582 s->seq_ops.stop = udp_seq_stop;
1584 rc = seq_open(file, &s->seq_ops);
1588 seq = file->private_data;
1597 /* ------------------------------------------------------------------------ */
1598 int udp_proc_register(struct udp_seq_afinfo *afinfo)
1600 struct proc_dir_entry *p;
1605 afinfo->seq_fops->owner = afinfo->owner;
1606 afinfo->seq_fops->open = udp_seq_open;
1607 afinfo->seq_fops->read = seq_read;
1608 afinfo->seq_fops->llseek = seq_lseek;
1609 afinfo->seq_fops->release = seq_release_private;
1611 p = proc_net_fops_create(afinfo->name, S_IRUGO, afinfo->seq_fops);
1619 void udp_proc_unregister(struct udp_seq_afinfo *afinfo)
1623 proc_net_remove(afinfo->name);
1624 memset(afinfo->seq_fops, 0, sizeof(*afinfo->seq_fops));
1627 /* ------------------------------------------------------------------------ */
1628 static void udp4_format_sock(struct sock *sp, char *tmpbuf, int bucket)
1630 struct inet_sock *inet = inet_sk(sp);
1631 unsigned int dest = inet->daddr;
1632 unsigned int src = inet->rcv_saddr;
1633 __u16 destp = ntohs(inet->dport);
1634 __u16 srcp = ntohs(inet->sport);
1636 sprintf(tmpbuf, "%4d: %08X:%04X %08X:%04X"
1637 " %02X %08X:%08X %02X:%08lX %08X %5d %8d %lu %d %p",
1638 bucket, src, srcp, dest, destp, sp->sk_state,
1639 atomic_read(&sp->sk_wmem_alloc),
1640 atomic_read(&sp->sk_rmem_alloc),
1641 0, 0L, 0, sock_i_uid(sp), 0, sock_i_ino(sp),
1642 atomic_read(&sp->sk_refcnt), sp);
1645 static int udp4_seq_show(struct seq_file *seq, void *v)
1647 if (v == SEQ_START_TOKEN)
1648 seq_printf(seq, "%-127s\n",
1649 " sl local_address rem_address st tx_queue "
1650 "rx_queue tr tm->when retrnsmt uid timeout "
1654 struct udp_iter_state *state = seq->private;
1656 udp4_format_sock(v, tmpbuf, state->bucket);
1657 seq_printf(seq, "%-127s\n", tmpbuf);
1662 /* ------------------------------------------------------------------------ */
1663 static struct file_operations udp4_seq_fops;
1664 static struct udp_seq_afinfo udp4_seq_afinfo = {
1665 .owner = THIS_MODULE,
1668 .seq_show = udp4_seq_show,
1669 .seq_fops = &udp4_seq_fops,
1672 int __init udp4_proc_init(void)
1674 return udp_proc_register(&udp4_seq_afinfo);
1677 void udp4_proc_exit(void)
1679 udp_proc_unregister(&udp4_seq_afinfo);
1681 #endif /* CONFIG_PROC_FS */
1683 EXPORT_SYMBOL(udp_disconnect);
1684 EXPORT_SYMBOL(udp_hash);
1685 EXPORT_SYMBOL(udp_hash_lock);
1686 EXPORT_SYMBOL(udp_ioctl);
1687 EXPORT_SYMBOL(udp_port_rover);
1688 EXPORT_SYMBOL(udp_prot);
1689 EXPORT_SYMBOL(udp_sendmsg);
1690 EXPORT_SYMBOL(udp_poll);
1692 #ifdef CONFIG_PROC_FS
1693 EXPORT_SYMBOL(udp_proc_register);
1694 EXPORT_SYMBOL(udp_proc_unregister);