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 $
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.
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_get_port */
124 static inline int udp_lport_inuse(u16 num)
127 struct hlist_node *node;
129 sk_for_each(sk, node, &udp_hash[num & (UDP_HTABLE_SIZE - 1)])
130 if (inet_sk(sk)->num == num)
136 * udp_get_port - common port lookup for IPv4 and IPv6
138 * @sk: socket struct in question
139 * @snum: port number to look up
140 * @saddr_comp: AF-dependent comparison of bound local IP addresses
142 int udp_get_port(struct sock *sk, unsigned short snum,
143 int (*saddr_cmp)(struct sock *sk1, struct sock *sk2))
145 struct hlist_node *node;
146 struct hlist_head *head;
150 write_lock_bh(&udp_hash_lock);
152 int best_size_so_far, best, result, i;
154 if (udp_port_rover > sysctl_local_port_range[1] ||
155 udp_port_rover < sysctl_local_port_range[0])
156 udp_port_rover = sysctl_local_port_range[0];
157 best_size_so_far = 32767;
158 best = result = udp_port_rover;
159 for (i = 0; i < UDP_HTABLE_SIZE; i++, result++) {
162 head = &udp_hash[result & (UDP_HTABLE_SIZE - 1)];
163 if (hlist_empty(head)) {
164 if (result > sysctl_local_port_range[1])
165 result = sysctl_local_port_range[0] +
166 ((result - sysctl_local_port_range[0]) &
167 (UDP_HTABLE_SIZE - 1));
171 sk_for_each(sk2, node, head)
172 if (++size < best_size_so_far) {
173 best_size_so_far = size;
178 for(i = 0; i < (1 << 16) / UDP_HTABLE_SIZE; i++, result += UDP_HTABLE_SIZE) {
179 if (result > sysctl_local_port_range[1])
180 result = sysctl_local_port_range[0]
181 + ((result - sysctl_local_port_range[0]) &
182 (UDP_HTABLE_SIZE - 1));
183 if (!udp_lport_inuse(result))
186 if (i >= (1 << 16) / UDP_HTABLE_SIZE)
189 udp_port_rover = snum = result;
191 head = &udp_hash[snum & (UDP_HTABLE_SIZE - 1)];
193 sk_for_each(sk2, node, head)
194 if (inet_sk(sk2)->num == snum &&
196 (!sk2->sk_reuse || !sk->sk_reuse) &&
197 (!sk2->sk_bound_dev_if || !sk->sk_bound_dev_if
198 || sk2->sk_bound_dev_if == sk->sk_bound_dev_if) &&
199 (*saddr_cmp)(sk, sk2) )
202 inet_sk(sk)->num = snum;
203 if (sk_unhashed(sk)) {
204 head = &udp_hash[snum & (UDP_HTABLE_SIZE - 1)];
205 sk_add_node(sk, head);
206 sock_prot_inc_use(sk->sk_prot);
210 write_unlock_bh(&udp_hash_lock);
214 static inline int ipv4_rcv_saddr_equal(struct sock *sk1, struct sock *sk2)
216 struct inet_sock *inet1 = inet_sk(sk1), *inet2 = inet_sk(sk2);
218 return ( !ipv6_only_sock(sk2) &&
219 (!inet1->rcv_saddr || !inet2->rcv_saddr ||
220 inet1->rcv_saddr == inet2->rcv_saddr ));
223 static inline int udp_v4_get_port(struct sock *sk, unsigned short snum)
225 return udp_get_port(sk, snum, ipv4_rcv_saddr_equal);
229 static void udp_v4_hash(struct sock *sk)
234 static void udp_v4_unhash(struct sock *sk)
236 write_lock_bh(&udp_hash_lock);
237 if (sk_del_node_init(sk)) {
238 inet_sk(sk)->num = 0;
239 sock_prot_dec_use(sk->sk_prot);
241 write_unlock_bh(&udp_hash_lock);
244 /* UDP is nearly always wildcards out the wazoo, it makes no sense to try
245 * harder than this. -DaveM
247 static struct sock *udp_v4_lookup_longway(u32 saddr, u16 sport,
248 u32 daddr, u16 dport, int dif)
250 struct sock *sk, *result = NULL;
251 struct hlist_node *node;
252 unsigned short hnum = ntohs(dport);
255 sk_for_each(sk, node, &udp_hash[hnum & (UDP_HTABLE_SIZE - 1)]) {
256 struct inet_sock *inet = inet_sk(sk);
258 if (inet->num == hnum && !ipv6_only_sock(sk)) {
259 int score = (sk->sk_family == PF_INET ? 1 : 0);
260 if (inet->rcv_saddr) {
261 if (inet->rcv_saddr != daddr)
266 if (inet->daddr != saddr)
271 if (inet->dport != sport)
275 if (sk->sk_bound_dev_if) {
276 if (sk->sk_bound_dev_if != dif)
283 } else if(score > badness) {
292 static __inline__ struct sock *udp_v4_lookup(u32 saddr, u16 sport,
293 u32 daddr, u16 dport, int dif)
297 read_lock(&udp_hash_lock);
298 sk = udp_v4_lookup_longway(saddr, sport, daddr, dport, dif);
301 read_unlock(&udp_hash_lock);
305 static inline struct sock *udp_v4_mcast_next(struct sock *sk,
306 u16 loc_port, u32 loc_addr,
307 u16 rmt_port, u32 rmt_addr,
310 struct hlist_node *node;
312 unsigned short hnum = ntohs(loc_port);
314 sk_for_each_from(s, node) {
315 struct inet_sock *inet = inet_sk(s);
317 if (inet->num != hnum ||
318 (inet->daddr && inet->daddr != rmt_addr) ||
319 (inet->dport != rmt_port && inet->dport) ||
320 (inet->rcv_saddr && inet->rcv_saddr != loc_addr) ||
322 (s->sk_bound_dev_if && s->sk_bound_dev_if != dif))
324 if (!ip_mc_sf_allow(s, loc_addr, rmt_addr, dif))
334 * This routine is called by the ICMP module when it gets some
335 * sort of error condition. If err < 0 then the socket should
336 * be closed and the error returned to the user. If err > 0
337 * it's just the icmp type << 8 | icmp code.
338 * Header points to the ip header of the error packet. We move
339 * on past this. Then (as it used to claim before adjustment)
340 * header points to the first 8 bytes of the udp header. We need
341 * to find the appropriate port.
344 void udp_err(struct sk_buff *skb, u32 info)
346 struct inet_sock *inet;
347 struct iphdr *iph = (struct iphdr*)skb->data;
348 struct udphdr *uh = (struct udphdr*)(skb->data+(iph->ihl<<2));
349 int type = skb->h.icmph->type;
350 int code = skb->h.icmph->code;
355 sk = udp_v4_lookup(iph->daddr, uh->dest, iph->saddr, uh->source, skb->dev->ifindex);
357 ICMP_INC_STATS_BH(ICMP_MIB_INERRORS);
358 return; /* No socket for error */
367 case ICMP_TIME_EXCEEDED:
370 case ICMP_SOURCE_QUENCH:
372 case ICMP_PARAMETERPROB:
376 case ICMP_DEST_UNREACH:
377 if (code == ICMP_FRAG_NEEDED) { /* Path MTU discovery */
378 if (inet->pmtudisc != IP_PMTUDISC_DONT) {
386 if (code <= NR_ICMP_UNREACH) {
387 harderr = icmp_err_convert[code].fatal;
388 err = icmp_err_convert[code].errno;
394 * RFC1122: OK. Passes ICMP errors back to application, as per
397 if (!inet->recverr) {
398 if (!harderr || sk->sk_state != TCP_ESTABLISHED)
401 ip_icmp_error(sk, skb, err, uh->dest, info, (u8*)(uh+1));
404 sk->sk_error_report(sk);
410 * Throw away all pending data and cancel the corking. Socket is locked.
412 static void udp_flush_pending_frames(struct sock *sk)
414 struct udp_sock *up = udp_sk(sk);
419 ip_flush_pending_frames(sk);
424 * Push out all pending data as one UDP datagram. Socket is locked.
426 static int udp_push_pending_frames(struct sock *sk, struct udp_sock *up)
428 struct inet_sock *inet = inet_sk(sk);
429 struct flowi *fl = &inet->cork.fl;
434 /* Grab the skbuff where UDP header space exists. */
435 if ((skb = skb_peek(&sk->sk_write_queue)) == NULL)
439 * Create a UDP header
442 uh->source = fl->fl_ip_sport;
443 uh->dest = fl->fl_ip_dport;
444 uh->len = htons(up->len);
447 if (sk->sk_no_check == UDP_CSUM_NOXMIT) {
448 skb->ip_summed = CHECKSUM_NONE;
452 if (skb_queue_len(&sk->sk_write_queue) == 1) {
454 * Only one fragment on the socket.
456 if (skb->ip_summed == CHECKSUM_PARTIAL) {
457 skb->csum = offsetof(struct udphdr, check);
458 uh->check = ~csum_tcpudp_magic(fl->fl4_src, fl->fl4_dst,
459 up->len, IPPROTO_UDP, 0);
461 skb->csum = csum_partial((char *)uh,
462 sizeof(struct udphdr), skb->csum);
463 uh->check = csum_tcpudp_magic(fl->fl4_src, fl->fl4_dst,
464 up->len, IPPROTO_UDP, skb->csum);
469 unsigned int csum = 0;
471 * HW-checksum won't work as there are two or more
472 * fragments on the socket so that all csums of sk_buffs
473 * should be together.
475 if (skb->ip_summed == CHECKSUM_PARTIAL) {
476 int offset = (unsigned char *)uh - skb->data;
477 skb->csum = skb_checksum(skb, offset, skb->len - offset, 0);
479 skb->ip_summed = CHECKSUM_NONE;
481 skb->csum = csum_partial((char *)uh,
482 sizeof(struct udphdr), skb->csum);
485 skb_queue_walk(&sk->sk_write_queue, skb) {
486 csum = csum_add(csum, skb->csum);
488 uh->check = csum_tcpudp_magic(fl->fl4_src, fl->fl4_dst,
489 up->len, IPPROTO_UDP, csum);
494 err = ip_push_pending_frames(sk);
502 static unsigned short udp_check(struct udphdr *uh, int len, unsigned long saddr, unsigned long daddr, unsigned long base)
504 return(csum_tcpudp_magic(saddr, daddr, len, IPPROTO_UDP, base));
507 int udp_sendmsg(struct kiocb *iocb, struct sock *sk, struct msghdr *msg,
510 struct inet_sock *inet = inet_sk(sk);
511 struct udp_sock *up = udp_sk(sk);
513 struct ipcm_cookie ipc;
514 struct rtable *rt = NULL;
517 u32 daddr, faddr, saddr;
521 int corkreq = up->corkflag || msg->msg_flags&MSG_MORE;
530 if (msg->msg_flags&MSG_OOB) /* Mirror BSD error message compatibility */
537 * There are pending frames.
538 * The socket lock must be held while it's corked.
541 if (likely(up->pending)) {
542 if (unlikely(up->pending != AF_INET)) {
550 ulen += sizeof(struct udphdr);
553 * Get and verify the address.
556 struct sockaddr_in * usin = (struct sockaddr_in*)msg->msg_name;
557 if (msg->msg_namelen < sizeof(*usin))
559 if (usin->sin_family != AF_INET) {
560 if (usin->sin_family != AF_UNSPEC)
561 return -EAFNOSUPPORT;
564 daddr = usin->sin_addr.s_addr;
565 dport = usin->sin_port;
569 if (sk->sk_state != TCP_ESTABLISHED)
570 return -EDESTADDRREQ;
573 /* Open fast path for connected socket.
574 Route will not be used, if at least one option is set.
578 ipc.addr = inet->saddr;
580 ipc.oif = sk->sk_bound_dev_if;
581 if (msg->msg_controllen) {
582 err = ip_cmsg_send(msg, &ipc);
593 ipc.addr = faddr = daddr;
595 if (ipc.opt && ipc.opt->srr) {
598 faddr = ipc.opt->faddr;
601 tos = RT_TOS(inet->tos);
602 if (sock_flag(sk, SOCK_LOCALROUTE) ||
603 (msg->msg_flags & MSG_DONTROUTE) ||
604 (ipc.opt && ipc.opt->is_strictroute)) {
609 if (MULTICAST(daddr)) {
611 ipc.oif = inet->mc_index;
613 saddr = inet->mc_addr;
618 rt = (struct rtable*)sk_dst_check(sk, 0);
621 struct flowi fl = { .oif = ipc.oif,
626 .proto = IPPROTO_UDP,
628 { .sport = inet->sport,
629 .dport = dport } } };
630 security_sk_classify_flow(sk, &fl);
631 err = ip_route_output_flow(&rt, &fl, sk, !(msg->msg_flags&MSG_DONTWAIT));
636 if ((rt->rt_flags & RTCF_BROADCAST) &&
637 !sock_flag(sk, SOCK_BROADCAST))
640 sk_dst_set(sk, dst_clone(&rt->u.dst));
643 if (msg->msg_flags&MSG_CONFIRM)
649 daddr = ipc.addr = rt->rt_dst;
652 if (unlikely(up->pending)) {
653 /* The socket is already corked while preparing it. */
654 /* ... which is an evident application bug. --ANK */
657 LIMIT_NETDEBUG(KERN_DEBUG "udp cork app bug 2\n");
662 * Now cork the socket to pend data.
664 inet->cork.fl.fl4_dst = daddr;
665 inet->cork.fl.fl_ip_dport = dport;
666 inet->cork.fl.fl4_src = saddr;
667 inet->cork.fl.fl_ip_sport = inet->sport;
668 up->pending = AF_INET;
672 err = ip_append_data(sk, ip_generic_getfrag, msg->msg_iov, ulen,
673 sizeof(struct udphdr), &ipc, rt,
674 corkreq ? msg->msg_flags|MSG_MORE : msg->msg_flags);
676 udp_flush_pending_frames(sk);
678 err = udp_push_pending_frames(sk, up);
686 UDP_INC_STATS_USER(UDP_MIB_OUTDATAGRAMS);
690 * ENOBUFS = no kernel mem, SOCK_NOSPACE = no sndbuf space. Reporting
691 * ENOBUFS might not be good (it's not tunable per se), but otherwise
692 * we don't have a good statistic (IpOutDiscards but it can be too many
693 * things). We could add another new stat but at least for now that
694 * seems like overkill.
696 if (err == -ENOBUFS || test_bit(SOCK_NOSPACE, &sk->sk_socket->flags)) {
697 UDP_INC_STATS_USER(UDP_MIB_SNDBUFERRORS);
702 dst_confirm(&rt->u.dst);
703 if (!(msg->msg_flags&MSG_PROBE) || len)
704 goto back_from_confirm;
709 static int udp_sendpage(struct sock *sk, struct page *page, int offset,
710 size_t size, int flags)
712 struct udp_sock *up = udp_sk(sk);
716 struct msghdr msg = { .msg_flags = flags|MSG_MORE };
718 /* Call udp_sendmsg to specify destination address which
719 * sendpage interface can't pass.
720 * This will succeed only when the socket is connected.
722 ret = udp_sendmsg(NULL, sk, &msg, 0);
729 if (unlikely(!up->pending)) {
732 LIMIT_NETDEBUG(KERN_DEBUG "udp cork app bug 3\n");
736 ret = ip_append_page(sk, page, offset, size, flags);
737 if (ret == -EOPNOTSUPP) {
739 return sock_no_sendpage(sk->sk_socket, page, offset,
743 udp_flush_pending_frames(sk);
748 if (!(up->corkflag || (flags&MSG_MORE)))
749 ret = udp_push_pending_frames(sk, up);
758 * IOCTL requests applicable to the UDP protocol
761 int udp_ioctl(struct sock *sk, int cmd, unsigned long arg)
767 int amount = atomic_read(&sk->sk_wmem_alloc);
768 return put_user(amount, (int __user *)arg);
774 unsigned long amount;
777 spin_lock_bh(&sk->sk_receive_queue.lock);
778 skb = skb_peek(&sk->sk_receive_queue);
781 * We will only return the amount
782 * of this packet since that is all
785 amount = skb->len - sizeof(struct udphdr);
787 spin_unlock_bh(&sk->sk_receive_queue.lock);
788 return put_user(amount, (int __user *)arg);
797 static __inline__ int __udp_checksum_complete(struct sk_buff *skb)
799 return __skb_checksum_complete(skb);
802 static __inline__ int udp_checksum_complete(struct sk_buff *skb)
804 return skb->ip_summed != CHECKSUM_UNNECESSARY &&
805 __udp_checksum_complete(skb);
809 * This should be easy, if there is something there we
810 * return it, otherwise we block.
813 static int udp_recvmsg(struct kiocb *iocb, struct sock *sk, struct msghdr *msg,
814 size_t len, int noblock, int flags, int *addr_len)
816 struct inet_sock *inet = inet_sk(sk);
817 struct sockaddr_in *sin = (struct sockaddr_in *)msg->msg_name;
822 * Check any passed addresses
825 *addr_len=sizeof(*sin);
827 if (flags & MSG_ERRQUEUE)
828 return ip_recv_error(sk, msg, len);
831 skb = skb_recv_datagram(sk, flags, noblock, &err);
835 copied = skb->len - sizeof(struct udphdr);
838 msg->msg_flags |= MSG_TRUNC;
841 if (skb->ip_summed==CHECKSUM_UNNECESSARY) {
842 err = skb_copy_datagram_iovec(skb, sizeof(struct udphdr), msg->msg_iov,
844 } else if (msg->msg_flags&MSG_TRUNC) {
845 if (__udp_checksum_complete(skb))
847 err = skb_copy_datagram_iovec(skb, sizeof(struct udphdr), msg->msg_iov,
850 err = skb_copy_and_csum_datagram_iovec(skb, sizeof(struct udphdr), msg->msg_iov);
859 sock_recv_timestamp(msg, sk, skb);
861 /* Copy the address. */
864 sin->sin_family = AF_INET;
865 sin->sin_port = skb->h.uh->source;
866 sin->sin_addr.s_addr = skb->nh.iph->saddr;
867 memset(sin->sin_zero, 0, sizeof(sin->sin_zero));
869 if (inet->cmsg_flags)
870 ip_cmsg_recv(msg, skb);
873 if (flags & MSG_TRUNC)
874 err = skb->len - sizeof(struct udphdr);
877 skb_free_datagram(sk, skb);
882 UDP_INC_STATS_BH(UDP_MIB_INERRORS);
884 skb_kill_datagram(sk, skb, flags);
892 int udp_disconnect(struct sock *sk, int flags)
894 struct inet_sock *inet = inet_sk(sk);
896 * 1003.1g - break association.
899 sk->sk_state = TCP_CLOSE;
902 sk->sk_bound_dev_if = 0;
903 if (!(sk->sk_userlocks & SOCK_BINDADDR_LOCK))
904 inet_reset_saddr(sk);
906 if (!(sk->sk_userlocks & SOCK_BINDPORT_LOCK)) {
907 sk->sk_prot->unhash(sk);
914 static void udp_close(struct sock *sk, long timeout)
916 sk_common_release(sk);
920 * 1 if the the UDP system should process it
921 * 0 if we should drop this packet
922 * -1 if it should get processed by xfrm4_rcv_encap
924 static int udp_encap_rcv(struct sock * sk, struct sk_buff *skb)
929 struct udp_sock *up = udp_sk(sk);
930 struct udphdr *uh = skb->h.uh;
934 __u8 *udpdata = (__u8 *)uh + sizeof(struct udphdr);
935 __u32 *udpdata32 = (__u32 *)udpdata;
936 __u16 encap_type = up->encap_type;
938 /* if we're overly short, let UDP handle it */
939 if (udpdata > skb->tail)
942 /* if this is not encapsulated socket, then just return now */
946 len = skb->tail - udpdata;
948 switch (encap_type) {
950 case UDP_ENCAP_ESPINUDP:
951 /* Check if this is a keepalive packet. If so, eat it. */
952 if (len == 1 && udpdata[0] == 0xff) {
954 } else if (len > sizeof(struct ip_esp_hdr) && udpdata32[0] != 0 ) {
955 /* ESP Packet without Non-ESP header */
956 len = sizeof(struct udphdr);
958 /* Must be an IKE packet.. pass it through */
961 case UDP_ENCAP_ESPINUDP_NON_IKE:
962 /* Check if this is a keepalive packet. If so, eat it. */
963 if (len == 1 && udpdata[0] == 0xff) {
965 } else if (len > 2 * sizeof(u32) + sizeof(struct ip_esp_hdr) &&
966 udpdata32[0] == 0 && udpdata32[1] == 0) {
968 /* ESP Packet with Non-IKE marker */
969 len = sizeof(struct udphdr) + 2 * sizeof(u32);
971 /* Must be an IKE packet.. pass it through */
976 /* At this point we are sure that this is an ESPinUDP packet,
977 * so we need to remove 'len' bytes from the packet (the UDP
978 * header and optional ESP marker bytes) and then modify the
979 * protocol to ESP, and then call into the transform receiver.
981 if (skb_cloned(skb) && pskb_expand_head(skb, 0, 0, GFP_ATOMIC))
984 /* Now we can update and verify the packet length... */
986 iphlen = iph->ihl << 2;
987 iph->tot_len = htons(ntohs(iph->tot_len) - len);
988 if (skb->len < iphlen + len) {
989 /* packet is too small!?! */
993 /* pull the data buffer up to the ESP header and set the
994 * transport header to point to ESP. Keep UDP on the stack
997 skb->h.raw = skb_pull(skb, len);
999 /* modify the protocol (it's ESP!) */
1000 iph->protocol = IPPROTO_ESP;
1002 /* and let the caller know to send this into the ESP processor... */
1010 * >0: "udp encap" protocol resubmission
1012 * Note that in the success and error cases, the skb is assumed to
1013 * have either been requeued or freed.
1015 static int udp_queue_rcv_skb(struct sock * sk, struct sk_buff *skb)
1017 struct udp_sock *up = udp_sk(sk);
1021 * Charge it to the socket, dropping if the queue is full.
1023 if (!xfrm4_policy_check(sk, XFRM_POLICY_IN, skb)) {
1029 if (up->encap_type) {
1031 * This is an encapsulation socket, so let's see if this is
1032 * an encapsulated packet.
1033 * If it's a keepalive packet, then just eat it.
1034 * If it's an encapsulateed packet, then pass it to the
1035 * IPsec xfrm input and return the response
1036 * appropriately. Otherwise, just fall through and
1037 * pass this up the UDP socket.
1041 ret = udp_encap_rcv(sk, skb);
1043 /* Eat the packet .. */
1048 /* process the ESP packet */
1049 ret = xfrm4_rcv_encap(skb, up->encap_type);
1050 UDP_INC_STATS_BH(UDP_MIB_INDATAGRAMS);
1053 /* FALLTHROUGH -- it's a UDP Packet */
1056 if (sk->sk_filter && skb->ip_summed != CHECKSUM_UNNECESSARY) {
1057 if (__udp_checksum_complete(skb)) {
1058 UDP_INC_STATS_BH(UDP_MIB_INERRORS);
1062 skb->ip_summed = CHECKSUM_UNNECESSARY;
1065 if ((rc = sock_queue_rcv_skb(sk,skb)) < 0) {
1066 /* Note that an ENOMEM error is charged twice */
1068 UDP_INC_STATS_BH(UDP_MIB_RCVBUFERRORS);
1069 UDP_INC_STATS_BH(UDP_MIB_INERRORS);
1073 UDP_INC_STATS_BH(UDP_MIB_INDATAGRAMS);
1078 * Multicasts and broadcasts go to each listener.
1080 * Note: called only from the BH handler context,
1081 * so we don't need to lock the hashes.
1083 static int udp_v4_mcast_deliver(struct sk_buff *skb, struct udphdr *uh,
1084 u32 saddr, u32 daddr)
1089 read_lock(&udp_hash_lock);
1090 sk = sk_head(&udp_hash[ntohs(uh->dest) & (UDP_HTABLE_SIZE - 1)]);
1091 dif = skb->dev->ifindex;
1092 sk = udp_v4_mcast_next(sk, uh->dest, daddr, uh->source, saddr, dif);
1094 struct sock *sknext = NULL;
1097 struct sk_buff *skb1 = skb;
1099 sknext = udp_v4_mcast_next(sk_next(sk), uh->dest, daddr,
1100 uh->source, saddr, dif);
1102 skb1 = skb_clone(skb, GFP_ATOMIC);
1105 int ret = udp_queue_rcv_skb(sk, skb1);
1107 /* we should probably re-process instead
1108 * of dropping packets here. */
1115 read_unlock(&udp_hash_lock);
1119 /* Initialize UDP checksum. If exited with zero value (success),
1120 * CHECKSUM_UNNECESSARY means, that no more checks are required.
1121 * Otherwise, csum completion requires chacksumming packet body,
1122 * including udp header and folding it to skb->csum.
1124 static void udp_checksum_init(struct sk_buff *skb, struct udphdr *uh,
1125 unsigned short ulen, u32 saddr, u32 daddr)
1127 if (uh->check == 0) {
1128 skb->ip_summed = CHECKSUM_UNNECESSARY;
1129 } else if (skb->ip_summed == CHECKSUM_COMPLETE) {
1130 if (!udp_check(uh, ulen, saddr, daddr, skb->csum))
1131 skb->ip_summed = CHECKSUM_UNNECESSARY;
1133 if (skb->ip_summed != CHECKSUM_UNNECESSARY)
1134 skb->csum = csum_tcpudp_nofold(saddr, daddr, ulen, IPPROTO_UDP, 0);
1135 /* Probably, we should checksum udp header (it should be in cache
1136 * in any case) and data in tiny packets (< rx copybreak).
1141 * All we need to do is get the socket, and then do a checksum.
1144 int udp_rcv(struct sk_buff *skb)
1148 unsigned short ulen;
1149 struct rtable *rt = (struct rtable*)skb->dst;
1150 u32 saddr = skb->nh.iph->saddr;
1151 u32 daddr = skb->nh.iph->daddr;
1155 * Validate the packet and the UDP length.
1157 if (!pskb_may_pull(skb, sizeof(struct udphdr)))
1162 ulen = ntohs(uh->len);
1164 if (ulen > len || ulen < sizeof(*uh))
1167 if (pskb_trim_rcsum(skb, ulen))
1170 udp_checksum_init(skb, uh, ulen, saddr, daddr);
1172 if(rt->rt_flags & (RTCF_BROADCAST|RTCF_MULTICAST))
1173 return udp_v4_mcast_deliver(skb, uh, saddr, daddr);
1175 sk = udp_v4_lookup(saddr, uh->source, daddr, uh->dest, skb->dev->ifindex);
1178 int ret = udp_queue_rcv_skb(sk, skb);
1181 /* a return value > 0 means to resubmit the input, but
1182 * it it wants the return to be -protocol, or 0
1189 if (!xfrm4_policy_check(NULL, XFRM_POLICY_IN, skb))
1193 /* No socket. Drop packet silently, if checksum is wrong */
1194 if (udp_checksum_complete(skb))
1197 UDP_INC_STATS_BH(UDP_MIB_NOPORTS);
1198 icmp_send(skb, ICMP_DEST_UNREACH, ICMP_PORT_UNREACH, 0);
1201 * Hmm. We got an UDP packet to a port to which we
1202 * don't wanna listen. Ignore it.
1208 LIMIT_NETDEBUG(KERN_DEBUG "UDP: short packet: From %u.%u.%u.%u:%u %d/%d to %u.%u.%u.%u:%u\n",
1216 UDP_INC_STATS_BH(UDP_MIB_INERRORS);
1222 * RFC1122: OK. Discards the bad packet silently (as far as
1223 * the network is concerned, anyway) as per 4.1.3.4 (MUST).
1225 LIMIT_NETDEBUG(KERN_DEBUG "UDP: bad checksum. From %d.%d.%d.%d:%d to %d.%d.%d.%d:%d ulen %d\n",
1232 UDP_INC_STATS_BH(UDP_MIB_INERRORS);
1237 static int udp_destroy_sock(struct sock *sk)
1240 udp_flush_pending_frames(sk);
1246 * Socket option code for UDP
1248 static int do_udp_setsockopt(struct sock *sk, int level, int optname,
1249 char __user *optval, int optlen)
1251 struct udp_sock *up = udp_sk(sk);
1255 if(optlen<sizeof(int))
1258 if (get_user(val, (int __user *)optval))
1268 udp_push_pending_frames(sk, up);
1276 case UDP_ENCAP_ESPINUDP:
1277 case UDP_ENCAP_ESPINUDP_NON_IKE:
1278 up->encap_type = val;
1294 static int udp_setsockopt(struct sock *sk, int level, int optname,
1295 char __user *optval, int optlen)
1297 if (level != SOL_UDP)
1298 return ip_setsockopt(sk, level, optname, optval, optlen);
1299 return do_udp_setsockopt(sk, level, optname, optval, optlen);
1302 #ifdef CONFIG_COMPAT
1303 static int compat_udp_setsockopt(struct sock *sk, int level, int optname,
1304 char __user *optval, int optlen)
1306 if (level != SOL_UDP)
1307 return compat_ip_setsockopt(sk, level, optname, optval, optlen);
1308 return do_udp_setsockopt(sk, level, optname, optval, optlen);
1312 static int do_udp_getsockopt(struct sock *sk, int level, int optname,
1313 char __user *optval, int __user *optlen)
1315 struct udp_sock *up = udp_sk(sk);
1318 if(get_user(len,optlen))
1321 len = min_t(unsigned int, len, sizeof(int));
1332 val = up->encap_type;
1336 return -ENOPROTOOPT;
1339 if(put_user(len, optlen))
1341 if(copy_to_user(optval, &val,len))
1346 static int udp_getsockopt(struct sock *sk, int level, int optname,
1347 char __user *optval, int __user *optlen)
1349 if (level != SOL_UDP)
1350 return ip_getsockopt(sk, level, optname, optval, optlen);
1351 return do_udp_getsockopt(sk, level, optname, optval, optlen);
1354 #ifdef CONFIG_COMPAT
1355 static int compat_udp_getsockopt(struct sock *sk, int level, int optname,
1356 char __user *optval, int __user *optlen)
1358 if (level != SOL_UDP)
1359 return compat_ip_getsockopt(sk, level, optname, optval, optlen);
1360 return do_udp_getsockopt(sk, level, optname, optval, optlen);
1364 * udp_poll - wait for a UDP event.
1365 * @file - file struct
1367 * @wait - poll table
1369 * This is same as datagram poll, except for the special case of
1370 * blocking sockets. If application is using a blocking fd
1371 * and a packet with checksum error is in the queue;
1372 * then it could get return from select indicating data available
1373 * but then block when reading it. Add special case code
1374 * to work around these arguably broken applications.
1376 unsigned int udp_poll(struct file *file, struct socket *sock, poll_table *wait)
1378 unsigned int mask = datagram_poll(file, sock, wait);
1379 struct sock *sk = sock->sk;
1381 /* Check for false positives due to checksum errors */
1382 if ( (mask & POLLRDNORM) &&
1383 !(file->f_flags & O_NONBLOCK) &&
1384 !(sk->sk_shutdown & RCV_SHUTDOWN)){
1385 struct sk_buff_head *rcvq = &sk->sk_receive_queue;
1386 struct sk_buff *skb;
1388 spin_lock_bh(&rcvq->lock);
1389 while ((skb = skb_peek(rcvq)) != NULL) {
1390 if (udp_checksum_complete(skb)) {
1391 UDP_INC_STATS_BH(UDP_MIB_INERRORS);
1392 __skb_unlink(skb, rcvq);
1395 skb->ip_summed = CHECKSUM_UNNECESSARY;
1399 spin_unlock_bh(&rcvq->lock);
1401 /* nothing to see, move along */
1403 mask &= ~(POLLIN | POLLRDNORM);
1410 struct proto udp_prot = {
1412 .owner = THIS_MODULE,
1414 .connect = ip4_datagram_connect,
1415 .disconnect = udp_disconnect,
1417 .destroy = udp_destroy_sock,
1418 .setsockopt = udp_setsockopt,
1419 .getsockopt = udp_getsockopt,
1420 .sendmsg = udp_sendmsg,
1421 .recvmsg = udp_recvmsg,
1422 .sendpage = udp_sendpage,
1423 .backlog_rcv = udp_queue_rcv_skb,
1424 .hash = udp_v4_hash,
1425 .unhash = udp_v4_unhash,
1426 .get_port = udp_v4_get_port,
1427 .obj_size = sizeof(struct udp_sock),
1428 #ifdef CONFIG_COMPAT
1429 .compat_setsockopt = compat_udp_setsockopt,
1430 .compat_getsockopt = compat_udp_getsockopt,
1434 /* ------------------------------------------------------------------------ */
1435 #ifdef CONFIG_PROC_FS
1437 static struct sock *udp_get_first(struct seq_file *seq)
1440 struct udp_iter_state *state = seq->private;
1442 for (state->bucket = 0; state->bucket < UDP_HTABLE_SIZE; ++state->bucket) {
1443 struct hlist_node *node;
1444 sk_for_each(sk, node, &udp_hash[state->bucket]) {
1445 if (sk->sk_family == state->family)
1454 static struct sock *udp_get_next(struct seq_file *seq, struct sock *sk)
1456 struct udp_iter_state *state = seq->private;
1462 } while (sk && sk->sk_family != state->family);
1464 if (!sk && ++state->bucket < UDP_HTABLE_SIZE) {
1465 sk = sk_head(&udp_hash[state->bucket]);
1471 static struct sock *udp_get_idx(struct seq_file *seq, loff_t pos)
1473 struct sock *sk = udp_get_first(seq);
1476 while(pos && (sk = udp_get_next(seq, sk)) != NULL)
1478 return pos ? NULL : sk;
1481 static void *udp_seq_start(struct seq_file *seq, loff_t *pos)
1483 read_lock(&udp_hash_lock);
1484 return *pos ? udp_get_idx(seq, *pos-1) : (void *)1;
1487 static void *udp_seq_next(struct seq_file *seq, void *v, loff_t *pos)
1492 sk = udp_get_idx(seq, 0);
1494 sk = udp_get_next(seq, v);
1500 static void udp_seq_stop(struct seq_file *seq, void *v)
1502 read_unlock(&udp_hash_lock);
1505 static int udp_seq_open(struct inode *inode, struct file *file)
1507 struct udp_seq_afinfo *afinfo = PDE(inode)->data;
1508 struct seq_file *seq;
1510 struct udp_iter_state *s = kzalloc(sizeof(*s), GFP_KERNEL);
1514 s->family = afinfo->family;
1515 s->seq_ops.start = udp_seq_start;
1516 s->seq_ops.next = udp_seq_next;
1517 s->seq_ops.show = afinfo->seq_show;
1518 s->seq_ops.stop = udp_seq_stop;
1520 rc = seq_open(file, &s->seq_ops);
1524 seq = file->private_data;
1533 /* ------------------------------------------------------------------------ */
1534 int udp_proc_register(struct udp_seq_afinfo *afinfo)
1536 struct proc_dir_entry *p;
1541 afinfo->seq_fops->owner = afinfo->owner;
1542 afinfo->seq_fops->open = udp_seq_open;
1543 afinfo->seq_fops->read = seq_read;
1544 afinfo->seq_fops->llseek = seq_lseek;
1545 afinfo->seq_fops->release = seq_release_private;
1547 p = proc_net_fops_create(afinfo->name, S_IRUGO, afinfo->seq_fops);
1555 void udp_proc_unregister(struct udp_seq_afinfo *afinfo)
1559 proc_net_remove(afinfo->name);
1560 memset(afinfo->seq_fops, 0, sizeof(*afinfo->seq_fops));
1563 /* ------------------------------------------------------------------------ */
1564 static void udp4_format_sock(struct sock *sp, char *tmpbuf, int bucket)
1566 struct inet_sock *inet = inet_sk(sp);
1567 unsigned int dest = inet->daddr;
1568 unsigned int src = inet->rcv_saddr;
1569 __u16 destp = ntohs(inet->dport);
1570 __u16 srcp = ntohs(inet->sport);
1572 sprintf(tmpbuf, "%4d: %08X:%04X %08X:%04X"
1573 " %02X %08X:%08X %02X:%08lX %08X %5d %8d %lu %d %p",
1574 bucket, src, srcp, dest, destp, sp->sk_state,
1575 atomic_read(&sp->sk_wmem_alloc),
1576 atomic_read(&sp->sk_rmem_alloc),
1577 0, 0L, 0, sock_i_uid(sp), 0, sock_i_ino(sp),
1578 atomic_read(&sp->sk_refcnt), sp);
1581 static int udp4_seq_show(struct seq_file *seq, void *v)
1583 if (v == SEQ_START_TOKEN)
1584 seq_printf(seq, "%-127s\n",
1585 " sl local_address rem_address st tx_queue "
1586 "rx_queue tr tm->when retrnsmt uid timeout "
1590 struct udp_iter_state *state = seq->private;
1592 udp4_format_sock(v, tmpbuf, state->bucket);
1593 seq_printf(seq, "%-127s\n", tmpbuf);
1598 /* ------------------------------------------------------------------------ */
1599 static struct file_operations udp4_seq_fops;
1600 static struct udp_seq_afinfo udp4_seq_afinfo = {
1601 .owner = THIS_MODULE,
1604 .seq_show = udp4_seq_show,
1605 .seq_fops = &udp4_seq_fops,
1608 int __init udp4_proc_init(void)
1610 return udp_proc_register(&udp4_seq_afinfo);
1613 void udp4_proc_exit(void)
1615 udp_proc_unregister(&udp4_seq_afinfo);
1617 #endif /* CONFIG_PROC_FS */
1619 EXPORT_SYMBOL(udp_disconnect);
1620 EXPORT_SYMBOL(udp_hash);
1621 EXPORT_SYMBOL(udp_hash_lock);
1622 EXPORT_SYMBOL(udp_ioctl);
1623 EXPORT_SYMBOL(udp_get_port);
1624 EXPORT_SYMBOL(udp_prot);
1625 EXPORT_SYMBOL(udp_sendmsg);
1626 EXPORT_SYMBOL(udp_poll);
1628 #ifdef CONFIG_PROC_FS
1629 EXPORT_SYMBOL(udp_proc_register);
1630 EXPORT_SYMBOL(udp_proc_unregister);