Get rid of arch/mips64/kernel. 9116 lines of code gone.
[linux-2.6/linux-mips.git] / net / ipv4 / udp.c
blob6049b4853a65ddf51c38f68caaa2d78df304e52c
1 /*
2 * INET An implementation of the TCP/IP protocol suite for the LINUX
3 * operating system. INET is implemented using the BSD Socket
4 * interface as the means of communication with the user level.
6 * The User Datagram Protocol (UDP).
8 * Version: $Id: udp.c,v 1.102 2002/02/01 22:01:04 davem Exp $
10 * Authors: Ross Biro, <bir7@leland.Stanford.Edu>
11 * Fred N. van Kempen, <waltje@uWalt.NL.Mugnet.ORG>
12 * Arnt Gulbrandsen, <agulbra@nvg.unit.no>
13 * Alan Cox, <Alan.Cox@linux.org>
14 * Hirokazu Takahashi, <taka@valinux.co.jp>
16 * Fixes:
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
30 * does NOT close.
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
59 * for connect.
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
66 * datagrams.
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/socket.h>
87 #include <linux/sockios.h>
88 #include <linux/in.h>
89 #include <linux/errno.h>
90 #include <linux/timer.h>
91 #include <linux/mm.h>
92 #include <linux/config.h>
93 #include <linux/inet.h>
94 #include <linux/ipv6.h>
95 #include <linux/netdevice.h>
96 #include <net/snmp.h>
97 #include <net/tcp.h>
98 #include <net/protocol.h>
99 #include <linux/skbuff.h>
100 #include <linux/proc_fs.h>
101 #include <linux/seq_file.h>
102 #include <net/sock.h>
103 #include <net/udp.h>
104 #include <net/icmp.h>
105 #include <net/route.h>
106 #include <net/inet_common.h>
107 #include <net/checksum.h>
108 #include <net/xfrm.h>
111 * Snmp MIB for the UDP layer
114 DEFINE_SNMP_STAT(struct udp_mib, udp_statistics);
116 struct hlist_head udp_hash[UDP_HTABLE_SIZE];
117 rwlock_t udp_hash_lock = RW_LOCK_UNLOCKED;
119 /* Shared by v4/v6 udp. */
120 int udp_port_rover;
122 static int udp_v4_get_port(struct sock *sk, unsigned short snum)
124 struct hlist_node *node;
125 struct sock *sk2;
126 struct inet_opt *inet = inet_sk(sk);
128 write_lock_bh(&udp_hash_lock);
129 if (snum == 0) {
130 int best_size_so_far, best, result, i;
132 if (udp_port_rover > sysctl_local_port_range[1] ||
133 udp_port_rover < sysctl_local_port_range[0])
134 udp_port_rover = sysctl_local_port_range[0];
135 best_size_so_far = 32767;
136 best = result = udp_port_rover;
137 for (i = 0; i < UDP_HTABLE_SIZE; i++, result++) {
138 struct hlist_head *list;
139 int size;
141 list = &udp_hash[result & (UDP_HTABLE_SIZE - 1)];
142 if (hlist_empty(list)) {
143 if (result > sysctl_local_port_range[1])
144 result = sysctl_local_port_range[0] +
145 ((result - sysctl_local_port_range[0]) &
146 (UDP_HTABLE_SIZE - 1));
147 goto gotit;
149 size = 0;
150 sk_for_each(sk2, node, list)
151 if (++size >= best_size_so_far)
152 goto next;
153 best_size_so_far = size;
154 best = result;
155 next:;
157 result = best;
158 for(i = 0; i < (1 << 16) / UDP_HTABLE_SIZE; i++, result += UDP_HTABLE_SIZE) {
159 if (result > sysctl_local_port_range[1])
160 result = sysctl_local_port_range[0]
161 + ((result - sysctl_local_port_range[0]) &
162 (UDP_HTABLE_SIZE - 1));
163 if (!udp_lport_inuse(result))
164 break;
166 if (i >= (1 << 16) / UDP_HTABLE_SIZE)
167 goto fail;
168 gotit:
169 udp_port_rover = snum = result;
170 } else {
171 sk_for_each(sk2, node,
172 &udp_hash[snum & (UDP_HTABLE_SIZE - 1)]) {
173 struct inet_opt *inet2 = inet_sk(sk2);
175 if (inet2->num == snum &&
176 sk2 != sk &&
177 !ipv6_only_sock(sk2) &&
178 sk2->sk_bound_dev_if == sk->sk_bound_dev_if &&
179 (!inet2->rcv_saddr ||
180 !inet->rcv_saddr ||
181 inet2->rcv_saddr == inet->rcv_saddr) &&
182 (!sk2->sk_reuse || !sk->sk_reuse))
183 goto fail;
186 inet->num = snum;
187 if (sk_unhashed(sk)) {
188 struct hlist_head *h = &udp_hash[snum & (UDP_HTABLE_SIZE - 1)];
190 sk_add_node(sk, h);
191 sock_prot_inc_use(sk->sk_prot);
193 write_unlock_bh(&udp_hash_lock);
194 return 0;
196 fail:
197 write_unlock_bh(&udp_hash_lock);
198 return 1;
201 static void udp_v4_hash(struct sock *sk)
203 BUG();
206 static void udp_v4_unhash(struct sock *sk)
208 write_lock_bh(&udp_hash_lock);
209 if (sk_del_node_init(sk)) {
210 inet_sk(sk)->num = 0;
211 sock_prot_dec_use(sk->sk_prot);
213 write_unlock_bh(&udp_hash_lock);
216 /* UDP is nearly always wildcards out the wazoo, it makes no sense to try
217 * harder than this. -DaveM
219 struct sock *udp_v4_lookup_longway(u32 saddr, u16 sport, u32 daddr, u16 dport, int dif)
221 struct sock *sk, *result = NULL;
222 struct hlist_node *node;
223 unsigned short hnum = ntohs(dport);
224 int badness = -1;
226 sk_for_each(sk, node, &udp_hash[hnum & (UDP_HTABLE_SIZE - 1)]) {
227 struct inet_opt *inet = inet_sk(sk);
229 if (inet->num == hnum && !ipv6_only_sock(sk)) {
230 int score = (sk->sk_family == PF_INET ? 1 : 0);
231 if (inet->rcv_saddr) {
232 if (inet->rcv_saddr != daddr)
233 continue;
234 score+=2;
236 if (inet->daddr) {
237 if (inet->daddr != saddr)
238 continue;
239 score+=2;
241 if (inet->dport) {
242 if (inet->dport != sport)
243 continue;
244 score+=2;
246 if (sk->sk_bound_dev_if) {
247 if (sk->sk_bound_dev_if != dif)
248 continue;
249 score+=2;
251 if(score == 9) {
252 result = sk;
253 break;
254 } else if(score > badness) {
255 result = sk;
256 badness = score;
260 return result;
263 __inline__ struct sock *udp_v4_lookup(u32 saddr, u16 sport, u32 daddr, u16 dport, int dif)
265 struct sock *sk;
267 read_lock(&udp_hash_lock);
268 sk = udp_v4_lookup_longway(saddr, sport, daddr, dport, dif);
269 if (sk)
270 sock_hold(sk);
271 read_unlock(&udp_hash_lock);
272 return sk;
275 static inline struct sock *udp_v4_mcast_next(struct sock *sk,
276 u16 loc_port, u32 loc_addr,
277 u16 rmt_port, u32 rmt_addr,
278 int dif)
280 struct hlist_node *node;
281 struct sock *s = sk;
282 unsigned short hnum = ntohs(loc_port);
284 sk_for_each_from(s, node) {
285 struct inet_opt *inet = inet_sk(s);
287 if (inet->num != hnum ||
288 (inet->daddr && inet->daddr != rmt_addr) ||
289 (inet->dport != rmt_port && inet->dport) ||
290 (inet->rcv_saddr && inet->rcv_saddr != loc_addr) ||
291 ipv6_only_sock(s) ||
292 (s->sk_bound_dev_if && s->sk_bound_dev_if != dif))
293 continue;
294 if (!ip_mc_sf_allow(sk, loc_addr, rmt_addr, dif))
295 continue;
296 goto found;
298 s = NULL;
299 found:
300 return s;
304 * This routine is called by the ICMP module when it gets some
305 * sort of error condition. If err < 0 then the socket should
306 * be closed and the error returned to the user. If err > 0
307 * it's just the icmp type << 8 | icmp code.
308 * Header points to the ip header of the error packet. We move
309 * on past this. Then (as it used to claim before adjustment)
310 * header points to the first 8 bytes of the udp header. We need
311 * to find the appropriate port.
314 void udp_err(struct sk_buff *skb, u32 info)
316 struct inet_opt *inet;
317 struct iphdr *iph = (struct iphdr*)skb->data;
318 struct udphdr *uh = (struct udphdr*)(skb->data+(iph->ihl<<2));
319 int type = skb->h.icmph->type;
320 int code = skb->h.icmph->code;
321 struct sock *sk;
322 int harderr;
323 int err;
325 sk = udp_v4_lookup(iph->daddr, uh->dest, iph->saddr, uh->source, skb->dev->ifindex);
326 if (sk == NULL) {
327 ICMP_INC_STATS_BH(IcmpInErrors);
328 return; /* No socket for error */
331 err = 0;
332 harderr = 0;
333 inet = inet_sk(sk);
335 switch (type) {
336 default:
337 case ICMP_TIME_EXCEEDED:
338 err = EHOSTUNREACH;
339 break;
340 case ICMP_SOURCE_QUENCH:
341 goto out;
342 case ICMP_PARAMETERPROB:
343 err = EPROTO;
344 harderr = 1;
345 break;
346 case ICMP_DEST_UNREACH:
347 if (code == ICMP_FRAG_NEEDED) { /* Path MTU discovery */
348 if (inet->pmtudisc != IP_PMTUDISC_DONT) {
349 err = EMSGSIZE;
350 harderr = 1;
351 break;
353 goto out;
355 err = EHOSTUNREACH;
356 if (code <= NR_ICMP_UNREACH) {
357 harderr = icmp_err_convert[code].fatal;
358 err = icmp_err_convert[code].errno;
360 break;
364 * RFC1122: OK. Passes ICMP errors back to application, as per
365 * 4.1.3.3.
367 if (!inet->recverr) {
368 if (!harderr || sk->sk_state != TCP_ESTABLISHED)
369 goto out;
370 } else {
371 ip_icmp_error(sk, skb, err, uh->dest, info, (u8*)(uh+1));
373 sk->sk_err = err;
374 sk->sk_error_report(sk);
375 out:
376 sock_put(sk);
380 * Throw away all pending data and cancel the corking. Socket is locked.
382 static void udp_flush_pending_frames(struct sock *sk)
384 struct udp_opt *up = udp_sk(sk);
386 if (up->pending) {
387 up->pending = 0;
388 ip_flush_pending_frames(sk);
393 * Push out all pending data as one UDP datagram. Socket is locked.
395 static int udp_push_pending_frames(struct sock *sk, struct udp_opt *up)
397 struct sk_buff *skb;
398 struct udphdr *uh;
399 int err = 0;
401 /* Grab the skbuff where UDP header space exists. */
402 if ((skb = skb_peek(&sk->sk_write_queue)) == NULL)
403 goto out;
406 * Create a UDP header
408 uh = skb->h.uh;
409 uh->source = up->sport;
410 uh->dest = up->dport;
411 uh->len = htons(up->len);
412 uh->check = 0;
414 if (sk->sk_no_check == UDP_CSUM_NOXMIT) {
415 skb->ip_summed = CHECKSUM_NONE;
416 goto send;
419 if (skb_queue_len(&sk->sk_write_queue) == 1) {
421 * Only one fragment on the socket.
423 if (skb->ip_summed == CHECKSUM_HW) {
424 skb->csum = offsetof(struct udphdr, check);
425 uh->check = ~csum_tcpudp_magic(up->saddr, up->daddr,
426 up->len, IPPROTO_UDP, 0);
427 } else {
428 skb->csum = csum_partial((char *)uh,
429 sizeof(struct udphdr), skb->csum);
430 uh->check = csum_tcpudp_magic(up->saddr, up->daddr,
431 up->len, IPPROTO_UDP, skb->csum);
432 if (uh->check == 0)
433 uh->check = -1;
435 } else {
436 unsigned int csum = 0;
438 * HW-checksum won't work as there are two or more
439 * fragments on the socket so that all csums of sk_buffs
440 * should be together.
442 if (skb->ip_summed == CHECKSUM_HW) {
443 int offset = (unsigned char *)uh - skb->data;
444 skb->csum = skb_checksum(skb, offset, skb->len - offset, 0);
446 skb->ip_summed = CHECKSUM_NONE;
447 } else {
448 skb->csum = csum_partial((char *)uh,
449 sizeof(struct udphdr), skb->csum);
452 skb_queue_walk(&sk->sk_write_queue, skb) {
453 csum = csum_add(csum, skb->csum);
455 uh->check = csum_tcpudp_magic(up->saddr, up->daddr,
456 up->len, IPPROTO_UDP, csum);
457 if (uh->check == 0)
458 uh->check = -1;
460 send:
461 err = ip_push_pending_frames(sk);
462 out:
463 up->len = 0;
464 up->pending = 0;
465 return err;
469 static unsigned short udp_check(struct udphdr *uh, int len, unsigned long saddr, unsigned long daddr, unsigned long base)
471 return(csum_tcpudp_magic(saddr, daddr, len, IPPROTO_UDP, base));
474 int udp_sendmsg(struct kiocb *iocb, struct sock *sk, struct msghdr *msg,
475 int len)
477 struct inet_opt *inet = inet_sk(sk);
478 struct udp_opt *up = udp_sk(sk);
479 int ulen = len;
480 struct ipcm_cookie ipc;
481 struct rtable *rt = NULL;
482 int free = 0;
483 int connected = 0;
484 u32 daddr, faddr, saddr;
485 u16 dport;
486 u8 tos;
487 int err;
488 int corkreq = up->corkflag || msg->msg_flags&MSG_MORE;
490 /* This check is ONLY to check for arithmetic overflow
491 on integer(!) len. Not more! Real check will be made
492 in ip_append_* --ANK
494 BTW socket.c -> af_*.c -> ... make multiple
495 invalid conversions size_t -> int. We MUST repair it f.e.
496 by replacing all of them with size_t and revise all
497 the places sort of len += sizeof(struct iphdr)
498 If len was ULONG_MAX-10 it would be cathastrophe --ANK
501 if (len < 0 || len > 0xFFFF)
502 return -EMSGSIZE;
505 * Check the flags.
508 if (msg->msg_flags&MSG_OOB) /* Mirror BSD error message compatibility */
509 return -EOPNOTSUPP;
511 ipc.opt = NULL;
513 if (up->pending) {
515 * There are pending frames.
516 * The socket lock must be held while it's corked.
518 lock_sock(sk);
519 if (likely(up->pending))
520 goto do_append_data;
521 release_sock(sk);
523 ulen += sizeof(struct udphdr);
526 * Get and verify the address.
528 if (msg->msg_name) {
529 struct sockaddr_in * usin = (struct sockaddr_in*)msg->msg_name;
530 if (msg->msg_namelen < sizeof(*usin))
531 return -EINVAL;
532 if (usin->sin_family != AF_INET) {
533 if (usin->sin_family != AF_UNSPEC)
534 return -EINVAL;
537 daddr = usin->sin_addr.s_addr;
538 dport = usin->sin_port;
539 if (dport == 0)
540 return -EINVAL;
541 } else {
542 if (sk->sk_state != TCP_ESTABLISHED)
543 return -EDESTADDRREQ;
544 daddr = inet->daddr;
545 dport = inet->dport;
546 /* Open fast path for connected socket.
547 Route will not be used, if at least one option is set.
549 connected = 1;
551 ipc.addr = inet->saddr;
553 ipc.oif = sk->sk_bound_dev_if;
554 if (msg->msg_controllen) {
555 err = ip_cmsg_send(msg, &ipc);
556 if (err)
557 return err;
558 if (ipc.opt)
559 free = 1;
560 connected = 0;
562 if (!ipc.opt)
563 ipc.opt = inet->opt;
565 saddr = ipc.addr;
566 ipc.addr = faddr = daddr;
568 if (ipc.opt && ipc.opt->srr) {
569 if (!daddr)
570 return -EINVAL;
571 faddr = ipc.opt->faddr;
572 connected = 0;
574 tos = RT_TOS(inet->tos);
575 if (sk->sk_localroute || (msg->msg_flags & MSG_DONTROUTE) ||
576 (ipc.opt && ipc.opt->is_strictroute)) {
577 tos |= RTO_ONLINK;
578 connected = 0;
581 if (MULTICAST(daddr)) {
582 if (!ipc.oif)
583 ipc.oif = inet->mc_index;
584 if (!saddr)
585 saddr = inet->mc_addr;
586 connected = 0;
589 if (connected)
590 rt = (struct rtable*)sk_dst_check(sk, 0);
592 if (rt == NULL) {
593 struct flowi fl = { .oif = ipc.oif,
594 .nl_u = { .ip4_u =
595 { .daddr = faddr,
596 .saddr = saddr,
597 .tos = tos } },
598 .proto = IPPROTO_UDP,
599 .uli_u = { .ports =
600 { .sport = inet->sport,
601 .dport = dport } } };
602 err = ip_route_output_flow(&rt, &fl, sk, !(msg->msg_flags&MSG_DONTWAIT));
603 if (err)
604 goto out;
606 err = -EACCES;
607 if ((rt->rt_flags & RTCF_BROADCAST) &&
608 !sock_flag(sk, SOCK_BROADCAST))
609 goto out;
610 if (connected)
611 sk_dst_set(sk, dst_clone(&rt->u.dst));
614 if (msg->msg_flags&MSG_CONFIRM)
615 goto do_confirm;
616 back_from_confirm:
618 saddr = rt->rt_src;
619 if (!ipc.addr)
620 daddr = ipc.addr = rt->rt_dst;
622 lock_sock(sk);
623 if (unlikely(up->pending)) {
624 /* The socket is already corked while preparing it. */
625 /* ... which is an evident application bug. --ANK */
626 release_sock(sk);
628 NETDEBUG(if (net_ratelimit()) printk(KERN_DEBUG "udp cork app bug 2\n"));
629 err = -EINVAL;
630 goto out;
633 * Now cork the socket to pend data.
635 up->daddr = daddr;
636 up->dport = dport;
637 up->saddr = saddr;
638 up->sport = inet->sport;
639 up->pending = 1;
641 do_append_data:
642 up->len += ulen;
643 err = ip_append_data(sk, ip_generic_getfrag, msg->msg_iov, ulen,
644 sizeof(struct udphdr), &ipc, rt,
645 corkreq ? msg->msg_flags|MSG_MORE : msg->msg_flags);
646 if (err)
647 udp_flush_pending_frames(sk);
648 else if (!corkreq)
649 err = udp_push_pending_frames(sk, up);
650 release_sock(sk);
652 out:
653 ip_rt_put(rt);
654 if (free)
655 kfree(ipc.opt);
656 if (!err) {
657 UDP_INC_STATS_USER(UdpOutDatagrams);
658 return len;
660 return err;
662 do_confirm:
663 dst_confirm(&rt->u.dst);
664 if (!(msg->msg_flags&MSG_PROBE) || len)
665 goto back_from_confirm;
666 err = 0;
667 goto out;
670 int udp_sendpage(struct sock *sk, struct page *page, int offset, size_t size, int flags)
672 struct udp_opt *up = udp_sk(sk);
673 int ret;
675 if (!up->pending) {
676 struct msghdr msg = { .msg_flags = flags|MSG_MORE };
678 /* Call udp_sendmsg to specify destination address which
679 * sendpage interface can't pass.
680 * This will succeed only when the socket is connected.
682 ret = udp_sendmsg(NULL, sk, &msg, 0);
683 if (ret < 0)
684 return ret;
687 lock_sock(sk);
689 if (unlikely(!up->pending)) {
690 release_sock(sk);
692 NETDEBUG(if (net_ratelimit()) printk(KERN_DEBUG "udp cork app bug 3\n"));
693 return -EINVAL;
696 ret = ip_append_page(sk, page, offset, size, flags);
697 if (ret == -EOPNOTSUPP) {
698 release_sock(sk);
699 return sock_no_sendpage(sk->sk_socket, page, offset,
700 size, flags);
702 if (ret < 0) {
703 udp_flush_pending_frames(sk);
704 goto out;
707 up->len += size;
708 if (!(up->corkflag || (flags&MSG_MORE)))
709 ret = udp_push_pending_frames(sk, up);
710 if (!ret)
711 ret = size;
712 out:
713 release_sock(sk);
714 return ret;
718 * IOCTL requests applicable to the UDP protocol
721 int udp_ioctl(struct sock *sk, int cmd, unsigned long arg)
723 switch(cmd)
725 case SIOCOUTQ:
727 int amount = atomic_read(&sk->sk_wmem_alloc);
728 return put_user(amount, (int *)arg);
731 case SIOCINQ:
733 struct sk_buff *skb;
734 unsigned long amount;
736 amount = 0;
737 spin_lock_irq(&sk->sk_receive_queue.lock);
738 skb = skb_peek(&sk->sk_receive_queue);
739 if (skb != NULL) {
741 * We will only return the amount
742 * of this packet since that is all
743 * that will be read.
745 amount = skb->len - sizeof(struct udphdr);
747 spin_unlock_irq(&sk->sk_receive_queue.lock);
748 return put_user(amount, (int *)arg);
751 default:
752 return -ENOIOCTLCMD;
754 return(0);
757 static __inline__ int __udp_checksum_complete(struct sk_buff *skb)
759 return (unsigned short)csum_fold(skb_checksum(skb, 0, skb->len, skb->csum));
762 static __inline__ int udp_checksum_complete(struct sk_buff *skb)
764 return skb->ip_summed != CHECKSUM_UNNECESSARY &&
765 __udp_checksum_complete(skb);
769 * This should be easy, if there is something there we
770 * return it, otherwise we block.
773 int udp_recvmsg(struct kiocb *iocb, struct sock *sk, struct msghdr *msg,
774 int len, int noblock, int flags, int *addr_len)
776 struct inet_opt *inet = inet_sk(sk);
777 struct sockaddr_in *sin = (struct sockaddr_in *)msg->msg_name;
778 struct sk_buff *skb;
779 int copied, err;
782 * Check any passed addresses
784 if (addr_len)
785 *addr_len=sizeof(*sin);
787 if (flags & MSG_ERRQUEUE)
788 return ip_recv_error(sk, msg, len);
790 skb = skb_recv_datagram(sk, flags, noblock, &err);
791 if (!skb)
792 goto out;
794 copied = skb->len - sizeof(struct udphdr);
795 if (copied > len) {
796 copied = len;
797 msg->msg_flags |= MSG_TRUNC;
800 if (skb->ip_summed==CHECKSUM_UNNECESSARY) {
801 err = skb_copy_datagram_iovec(skb, sizeof(struct udphdr), msg->msg_iov,
802 copied);
803 } else if (msg->msg_flags&MSG_TRUNC) {
804 if (__udp_checksum_complete(skb))
805 goto csum_copy_err;
806 err = skb_copy_datagram_iovec(skb, sizeof(struct udphdr), msg->msg_iov,
807 copied);
808 } else {
809 err = skb_copy_and_csum_datagram_iovec(skb, sizeof(struct udphdr), msg->msg_iov);
811 if (err == -EINVAL)
812 goto csum_copy_err;
815 if (err)
816 goto out_free;
818 sock_recv_timestamp(msg, sk, skb);
820 /* Copy the address. */
821 if (sin)
823 sin->sin_family = AF_INET;
824 sin->sin_port = skb->h.uh->source;
825 sin->sin_addr.s_addr = skb->nh.iph->saddr;
826 memset(sin->sin_zero, 0, sizeof(sin->sin_zero));
828 if (inet->cmsg_flags)
829 ip_cmsg_recv(msg, skb);
830 err = copied;
832 out_free:
833 skb_free_datagram(sk, skb);
834 out:
835 return err;
837 csum_copy_err:
838 UDP_INC_STATS_BH(UdpInErrors);
840 /* Clear queue. */
841 if (flags&MSG_PEEK) {
842 int clear = 0;
843 spin_lock_irq(&sk->sk_receive_queue.lock);
844 if (skb == skb_peek(&sk->sk_receive_queue)) {
845 __skb_unlink(skb, &sk->sk_receive_queue);
846 clear = 1;
848 spin_unlock_irq(&sk->sk_receive_queue.lock);
849 if (clear)
850 kfree_skb(skb);
853 skb_free_datagram(sk, skb);
855 return -EAGAIN;
858 int udp_connect(struct sock *sk, struct sockaddr *uaddr, int addr_len)
860 struct inet_opt *inet = inet_sk(sk);
861 struct sockaddr_in *usin = (struct sockaddr_in *) uaddr;
862 struct rtable *rt;
863 u32 saddr;
864 int oif;
865 int err;
868 if (addr_len < sizeof(*usin))
869 return -EINVAL;
871 if (usin->sin_family != AF_INET)
872 return -EAFNOSUPPORT;
874 sk_dst_reset(sk);
876 oif = sk->sk_bound_dev_if;
877 saddr = inet->saddr;
878 if (MULTICAST(usin->sin_addr.s_addr)) {
879 if (!oif)
880 oif = inet->mc_index;
881 if (!saddr)
882 saddr = inet->mc_addr;
884 err = ip_route_connect(&rt, usin->sin_addr.s_addr, saddr,
885 RT_CONN_FLAGS(sk), oif,
886 IPPROTO_UDP,
887 inet->sport, usin->sin_port, sk);
888 if (err)
889 return err;
890 if ((rt->rt_flags & RTCF_BROADCAST) && !sock_flag(sk, SOCK_BROADCAST)) {
891 ip_rt_put(rt);
892 return -EACCES;
894 if (!inet->saddr)
895 inet->saddr = rt->rt_src; /* Update source address */
896 if (!inet->rcv_saddr)
897 inet->rcv_saddr = rt->rt_src;
898 inet->daddr = rt->rt_dst;
899 inet->dport = usin->sin_port;
900 sk->sk_state = TCP_ESTABLISHED;
901 inet->id = jiffies;
903 sk_dst_set(sk, &rt->u.dst);
904 return(0);
907 int udp_disconnect(struct sock *sk, int flags)
909 struct inet_opt *inet = inet_sk(sk);
911 * 1003.1g - break association.
914 sk->sk_state = TCP_CLOSE;
915 inet->daddr = 0;
916 inet->dport = 0;
917 sk->sk_bound_dev_if = 0;
918 if (!(sk->sk_userlocks & SOCK_BINDADDR_LOCK))
919 inet_reset_saddr(sk);
921 if (!(sk->sk_userlocks & SOCK_BINDPORT_LOCK)) {
922 sk->sk_prot->unhash(sk);
923 inet->sport = 0;
925 sk_dst_reset(sk);
926 return 0;
929 static void udp_close(struct sock *sk, long timeout)
931 inet_sock_release(sk);
934 /* return:
935 * 1 if the the UDP system should process it
936 * 0 if we should drop this packet
937 * -1 if it should get processed by xfrm4_rcv_encap
939 static int udp_encap_rcv(struct sock * sk, struct sk_buff *skb)
941 struct udp_opt *up = udp_sk(sk);
942 struct udphdr *uh = skb->h.uh;
943 struct iphdr *iph;
944 int iphlen, len;
946 __u8 *udpdata = (__u8 *)uh + sizeof(struct udphdr);
947 __u32 *udpdata32 = (__u32 *)udpdata;
948 __u16 encap_type = up->encap_type;
950 /* if we're overly short, let UDP handle it */
951 if (udpdata > skb->tail)
952 return 1;
954 /* if this is not encapsulated socket, then just return now */
955 if (!encap_type)
956 return 1;
958 len = skb->tail - udpdata;
960 switch (encap_type) {
961 case UDP_ENCAP_ESPINUDP:
962 /* Check if this is a keepalive packet. If so, eat it. */
963 if (len == 1 && udpdata[0] == 0xff) {
964 return 0;
965 } else if (len > sizeof(struct ip_esp_hdr) && udpdata32[0] != 0 ) {
966 /* ESP Packet without Non-ESP header */
967 len = sizeof(struct udphdr);
968 } else
969 /* Must be an IKE packet.. pass it through */
970 return 1;
972 /* At this point we are sure that this is an ESPinUDP packet,
973 * so we need to remove 'len' bytes from the packet (the UDP
974 * header and optional ESP marker bytes) and then modify the
975 * protocol to ESP, and then call into the transform receiver.
978 /* Now we can update and verify the packet length... */
979 iph = skb->nh.iph;
980 iphlen = iph->ihl << 2;
981 iph->tot_len = htons(ntohs(iph->tot_len) - len);
982 if (skb->len < iphlen + len) {
983 /* packet is too small!?! */
984 return 0;
987 /* pull the data buffer up to the ESP header and set the
988 * transport header to point to ESP. Keep UDP on the stack
989 * for later.
991 skb->h.raw = skb_pull(skb, len);
993 /* modify the protocol (it's ESP!) */
994 iph->protocol = IPPROTO_ESP;
996 /* and let the caller know to send this into the ESP processor... */
997 return -1;
999 default:
1000 printk(KERN_INFO "udp_encap_rcv(): Unhandled UDP encap type: %u\n",
1001 encap_type);
1002 return 1;
1006 /* returns:
1007 * -1: error
1008 * 0: success
1009 * >0: "udp encap" protocol resubmission
1011 * Note that in the success and error cases, the skb is assumed to
1012 * have either been requeued or freed.
1014 static int udp_queue_rcv_skb(struct sock * sk, struct sk_buff *skb)
1016 struct udp_opt *up = udp_sk(sk);
1019 * Charge it to the socket, dropping if the queue is full.
1021 if (!xfrm4_policy_check(sk, XFRM_POLICY_IN, skb)) {
1022 kfree_skb(skb);
1023 return -1;
1026 if (up->encap_type) {
1028 * This is an encapsulation socket, so let's see if this is
1029 * an encapsulated packet.
1030 * If it's a keepalive packet, then just eat it.
1031 * If it's an encapsulateed packet, then pass it to the
1032 * IPsec xfrm input and return the response
1033 * appropriately. Otherwise, just fall through and
1034 * pass this up the UDP socket.
1036 int ret;
1038 ret = udp_encap_rcv(sk, skb);
1039 if (ret == 0) {
1040 /* Eat the packet .. */
1041 kfree_skb(skb);
1042 return 0;
1044 if (ret < 0) {
1045 /* process the ESP packet */
1046 ret = xfrm4_rcv_encap(skb, up->encap_type);
1047 UDP_INC_STATS_BH(UdpInDatagrams);
1048 return -ret;
1050 /* FALLTHROUGH -- it's a UDP Packet */
1053 if (sk->sk_filter && skb->ip_summed != CHECKSUM_UNNECESSARY) {
1054 if (__udp_checksum_complete(skb)) {
1055 UDP_INC_STATS_BH(UdpInErrors);
1056 kfree_skb(skb);
1057 return -1;
1059 skb->ip_summed = CHECKSUM_UNNECESSARY;
1062 if (sock_queue_rcv_skb(sk,skb)<0) {
1063 UDP_INC_STATS_BH(UdpInErrors);
1064 kfree_skb(skb);
1065 return -1;
1067 UDP_INC_STATS_BH(UdpInDatagrams);
1068 return 0;
1072 * Multicasts and broadcasts go to each listener.
1074 * Note: called only from the BH handler context,
1075 * so we don't need to lock the hashes.
1077 static int udp_v4_mcast_deliver(struct sk_buff *skb, struct udphdr *uh,
1078 u32 saddr, u32 daddr)
1080 struct sock *sk;
1081 int dif;
1083 read_lock(&udp_hash_lock);
1084 sk = sk_head(&udp_hash[ntohs(uh->dest) & (UDP_HTABLE_SIZE - 1)]);
1085 dif = skb->dev->ifindex;
1086 sk = udp_v4_mcast_next(sk, uh->dest, daddr, uh->source, saddr, dif);
1087 if (sk) {
1088 struct sock *sknext = NULL;
1090 do {
1091 struct sk_buff *skb1 = skb;
1093 sknext = udp_v4_mcast_next(sk_next(sk), uh->dest, daddr,
1094 uh->source, saddr, dif);
1095 if(sknext)
1096 skb1 = skb_clone(skb, GFP_ATOMIC);
1098 if(skb1) {
1099 int ret = udp_queue_rcv_skb(sk, skb1);
1100 if (ret > 0)
1101 /* we should probably re-process instead
1102 * of dropping packets here. */
1103 kfree_skb(skb1);
1105 sk = sknext;
1106 } while(sknext);
1107 } else
1108 kfree_skb(skb);
1109 read_unlock(&udp_hash_lock);
1110 return 0;
1113 /* Initialize UDP checksum. If exited with zero value (success),
1114 * CHECKSUM_UNNECESSARY means, that no more checks are required.
1115 * Otherwise, csum completion requires chacksumming packet body,
1116 * including udp header and folding it to skb->csum.
1118 static int udp_checksum_init(struct sk_buff *skb, struct udphdr *uh,
1119 unsigned short ulen, u32 saddr, u32 daddr)
1121 if (uh->check == 0) {
1122 skb->ip_summed = CHECKSUM_UNNECESSARY;
1123 } else if (skb->ip_summed == CHECKSUM_HW) {
1124 skb->ip_summed = CHECKSUM_UNNECESSARY;
1125 if (!udp_check(uh, ulen, saddr, daddr, skb->csum))
1126 return 0;
1127 NETDEBUG(if (net_ratelimit()) printk(KERN_DEBUG "udp v4 hw csum failure.\n"));
1128 skb->ip_summed = CHECKSUM_NONE;
1130 if (skb->ip_summed != CHECKSUM_UNNECESSARY)
1131 skb->csum = csum_tcpudp_nofold(saddr, daddr, ulen, IPPROTO_UDP, 0);
1132 /* Probably, we should checksum udp header (it should be in cache
1133 * in any case) and data in tiny packets (< rx copybreak).
1135 return 0;
1139 * All we need to do is get the socket, and then do a checksum.
1142 int udp_rcv(struct sk_buff *skb)
1144 struct sock *sk;
1145 struct udphdr *uh;
1146 unsigned short ulen;
1147 struct rtable *rt = (struct rtable*)skb->dst;
1148 u32 saddr = skb->nh.iph->saddr;
1149 u32 daddr = skb->nh.iph->daddr;
1150 int len = skb->len;
1153 * Validate the packet and the UDP length.
1155 if (!pskb_may_pull(skb, sizeof(struct udphdr)))
1156 goto no_header;
1158 uh = skb->h.uh;
1160 ulen = ntohs(uh->len);
1162 if (ulen > len || ulen < sizeof(*uh))
1163 goto short_packet;
1165 if (pskb_trim(skb, ulen))
1166 goto short_packet;
1168 if (udp_checksum_init(skb, uh, ulen, saddr, daddr) < 0)
1169 goto csum_error;
1171 if(rt->rt_flags & (RTCF_BROADCAST|RTCF_MULTICAST))
1172 return udp_v4_mcast_deliver(skb, uh, saddr, daddr);
1174 sk = udp_v4_lookup(saddr, uh->source, daddr, uh->dest, skb->dev->ifindex);
1176 if (sk != NULL) {
1177 int ret = udp_queue_rcv_skb(sk, skb);
1178 sock_put(sk);
1180 /* a return value > 0 means to resubmit the input, but
1181 * it it wants the return to be -protocol, or 0
1183 if (ret > 0)
1184 return -ret;
1185 return 0;
1188 if (!xfrm4_policy_check(NULL, XFRM_POLICY_IN, skb))
1189 goto drop;
1191 /* No socket. Drop packet silently, if checksum is wrong */
1192 if (udp_checksum_complete(skb))
1193 goto csum_error;
1195 UDP_INC_STATS_BH(UdpNoPorts);
1196 icmp_send(skb, ICMP_DEST_UNREACH, ICMP_PORT_UNREACH, 0);
1199 * Hmm. We got an UDP packet to a port to which we
1200 * don't wanna listen. Ignore it.
1202 kfree_skb(skb);
1203 return(0);
1205 short_packet:
1206 NETDEBUG(if (net_ratelimit())
1207 printk(KERN_DEBUG "UDP: short packet: From %u.%u.%u.%u:%u %d/%d to %u.%u.%u.%u:%u\n",
1208 NIPQUAD(saddr),
1209 ntohs(uh->source),
1210 ulen,
1211 len,
1212 NIPQUAD(daddr),
1213 ntohs(uh->dest)));
1214 no_header:
1215 UDP_INC_STATS_BH(UdpInErrors);
1216 kfree_skb(skb);
1217 return(0);
1219 csum_error:
1221 * RFC1122: OK. Discards the bad packet silently (as far as
1222 * the network is concerned, anyway) as per 4.1.3.4 (MUST).
1224 NETDEBUG(if (net_ratelimit())
1225 printk(KERN_DEBUG "UDP: bad checksum. From %d.%d.%d.%d:%d to %d.%d.%d.%d:%d ulen %d\n",
1226 NIPQUAD(saddr),
1227 ntohs(uh->source),
1228 NIPQUAD(daddr),
1229 ntohs(uh->dest),
1230 ulen));
1231 drop:
1232 UDP_INC_STATS_BH(UdpInErrors);
1233 kfree_skb(skb);
1234 return(0);
1237 static int udp_destroy_sock(struct sock *sk)
1239 lock_sock(sk);
1240 udp_flush_pending_frames(sk);
1241 release_sock(sk);
1242 return 0;
1246 * Socket option code for UDP
1248 static int udp_setsockopt(struct sock *sk, int level, int optname,
1249 char *optval, int optlen)
1251 struct udp_opt *up = udp_sk(sk);
1252 int val;
1253 int err = 0;
1255 if (level != SOL_UDP)
1256 return ip_setsockopt(sk, level, optname, optval, optlen);
1258 if(optlen<sizeof(int))
1259 return -EINVAL;
1261 if (get_user(val, (int *)optval))
1262 return -EFAULT;
1264 switch(optname) {
1265 case UDP_CORK:
1266 if (val != 0) {
1267 up->corkflag = 1;
1268 } else {
1269 up->corkflag = 0;
1270 lock_sock(sk);
1271 udp_push_pending_frames(sk, up);
1272 release_sock(sk);
1274 break;
1276 case UDP_ENCAP:
1277 up->encap_type = val;
1278 break;
1280 default:
1281 err = -ENOPROTOOPT;
1282 break;
1285 return err;
1288 static int udp_getsockopt(struct sock *sk, int level, int optname,
1289 char *optval, int *optlen)
1291 struct udp_opt *up = udp_sk(sk);
1292 int val, len;
1294 if (level != SOL_UDP)
1295 return ip_getsockopt(sk, level, optname, optval, optlen);
1297 if(get_user(len,optlen))
1298 return -EFAULT;
1300 len = min_t(unsigned int, len, sizeof(int));
1302 if(len < 0)
1303 return -EINVAL;
1305 switch(optname) {
1306 case UDP_CORK:
1307 val = up->corkflag;
1308 break;
1310 case UDP_ENCAP:
1311 val = up->encap_type;
1312 break;
1314 default:
1315 return -ENOPROTOOPT;
1318 if(put_user(len, optlen))
1319 return -EFAULT;
1320 if(copy_to_user(optval, &val,len))
1321 return -EFAULT;
1322 return 0;
1326 struct proto udp_prot = {
1327 .name = "UDP",
1328 .close = udp_close,
1329 .connect = udp_connect,
1330 .disconnect = udp_disconnect,
1331 .ioctl = udp_ioctl,
1332 .destroy = udp_destroy_sock,
1333 .setsockopt = udp_setsockopt,
1334 .getsockopt = udp_getsockopt,
1335 .sendmsg = udp_sendmsg,
1336 .recvmsg = udp_recvmsg,
1337 .sendpage = udp_sendpage,
1338 .backlog_rcv = udp_queue_rcv_skb,
1339 .hash = udp_v4_hash,
1340 .unhash = udp_v4_unhash,
1341 .get_port = udp_v4_get_port,
1344 /* ------------------------------------------------------------------------ */
1345 #ifdef CONFIG_PROC_FS
1347 static __inline__ struct sock *udp_get_bucket(struct seq_file *seq, loff_t *pos)
1349 int i;
1350 struct sock *sk;
1351 struct hlist_node *node;
1352 loff_t l = *pos;
1353 struct udp_iter_state *state = seq->private;
1355 for (; state->bucket < UDP_HTABLE_SIZE; ++state->bucket) {
1356 i = 0;
1357 sk_for_each(sk, node, &udp_hash[state->bucket]) {
1358 if (sk->sk_family != state->family) {
1359 ++i;
1360 continue;
1362 if (l--) {
1363 ++i;
1364 continue;
1366 *pos = i;
1367 goto out;
1370 sk = NULL;
1371 out:
1372 return sk;
1375 static void *udp_seq_start(struct seq_file *seq, loff_t *pos)
1377 read_lock(&udp_hash_lock);
1378 return *pos ? udp_get_bucket(seq, pos) : (void *)1;
1381 static void *udp_seq_next(struct seq_file *seq, void *v, loff_t *pos)
1383 struct sock *sk;
1384 struct hlist_node *node;
1385 struct udp_iter_state *state;
1387 if (v == (void *)1) {
1388 sk = udp_get_bucket(seq, pos);
1389 goto out;
1392 state = seq->private;
1394 sk = v;
1395 sk_for_each_continue(sk, node)
1396 if (sk->sk_family == state->family)
1397 goto out;
1399 if (++state->bucket >= UDP_HTABLE_SIZE)
1400 goto out;
1402 *pos = 0;
1403 sk = udp_get_bucket(seq, pos);
1404 out:
1405 ++*pos;
1406 return sk;
1409 static void udp_seq_stop(struct seq_file *seq, void *v)
1411 read_unlock(&udp_hash_lock);
1414 static int udp_seq_open(struct inode *inode, struct file *file)
1416 struct udp_seq_afinfo *afinfo = PDE(inode)->data;
1417 struct seq_file *seq;
1418 int rc = -ENOMEM;
1419 struct udp_iter_state *s = kmalloc(sizeof(*s), GFP_KERNEL);
1421 if (!s)
1422 goto out;
1423 memset(s, 0, sizeof(*s));
1424 s->family = afinfo->family;
1425 s->seq_ops.start = udp_seq_start;
1426 s->seq_ops.next = udp_seq_next;
1427 s->seq_ops.show = afinfo->seq_show;
1428 s->seq_ops.stop = udp_seq_stop;
1430 rc = seq_open(file, &s->seq_ops);
1431 if (rc)
1432 goto out_kfree;
1434 seq = file->private_data;
1435 seq->private = s;
1436 out:
1437 return rc;
1438 out_kfree:
1439 kfree(s);
1440 goto out;
1443 /* ------------------------------------------------------------------------ */
1444 int udp_proc_register(struct udp_seq_afinfo *afinfo)
1446 struct proc_dir_entry *p;
1447 int rc = 0;
1449 if (!afinfo)
1450 return -EINVAL;
1451 afinfo->seq_fops->owner = afinfo->owner;
1452 afinfo->seq_fops->open = udp_seq_open;
1453 afinfo->seq_fops->read = seq_read;
1454 afinfo->seq_fops->llseek = seq_lseek;
1455 afinfo->seq_fops->release = seq_release_private;
1457 p = create_proc_entry(afinfo->name, S_IRUGO, proc_net);
1458 if (p) {
1459 p->data = afinfo;
1460 p->proc_fops = afinfo->seq_fops;
1461 } else
1462 rc = -ENOMEM;
1463 return rc;
1466 void udp_proc_unregister(struct udp_seq_afinfo *afinfo)
1468 if (!afinfo)
1469 return;
1470 remove_proc_entry(afinfo->name, proc_net);
1471 memset(afinfo->seq_fops, 0, sizeof(*afinfo->seq_fops));
1474 /* ------------------------------------------------------------------------ */
1475 static void udp4_format_sock(struct sock *sp, char *tmpbuf, int bucket)
1477 struct inet_opt *inet = inet_sk(sp);
1478 unsigned int dest = inet->daddr;
1479 unsigned int src = inet->rcv_saddr;
1480 __u16 destp = ntohs(inet->dport);
1481 __u16 srcp = ntohs(inet->sport);
1483 sprintf(tmpbuf, "%4d: %08X:%04X %08X:%04X"
1484 " %02X %08X:%08X %02X:%08lX %08X %5d %8d %lu %d %p",
1485 bucket, src, srcp, dest, destp, sp->sk_state,
1486 atomic_read(&sp->sk_wmem_alloc),
1487 atomic_read(&sp->sk_rmem_alloc),
1488 0, 0L, 0, sock_i_uid(sp), 0, sock_i_ino(sp),
1489 atomic_read(&sp->sk_refcnt), sp);
1492 static int udp4_seq_show(struct seq_file *seq, void *v)
1494 if (v == (void *)1)
1495 seq_printf(seq, "%-127s\n",
1496 " sl local_address rem_address st tx_queue "
1497 "rx_queue tr tm->when retrnsmt uid timeout "
1498 "inode");
1499 else {
1500 char tmpbuf[129];
1501 struct udp_iter_state *state = seq->private;
1503 udp4_format_sock(v, tmpbuf, state->bucket);
1504 seq_printf(seq, "%-127s\n", tmpbuf);
1506 return 0;
1509 /* ------------------------------------------------------------------------ */
1510 static struct file_operations udp4_seq_fops;
1511 static struct udp_seq_afinfo udp4_seq_afinfo = {
1512 .owner = THIS_MODULE,
1513 .name = "udp",
1514 .family = AF_INET,
1515 .seq_show = udp4_seq_show,
1516 .seq_fops = &udp4_seq_fops,
1519 int __init udp4_proc_init(void)
1521 return udp_proc_register(&udp4_seq_afinfo);
1524 void udp4_proc_exit(void)
1526 udp_proc_unregister(&udp4_seq_afinfo);
1528 #endif /* CONFIG_PROC_FS */