]> pilppa.org Git - linux-2.6-omap-h63xx.git/blob - net/ipv4/udp.c
[UDP]: Unify UDPv4 and UDPv6 ->get_port()
[linux-2.6-omap-h63xx.git] / net / ipv4 / udp.c
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.
5  *
6  *              The User Datagram Protocol (UDP).
7  *
8  * Version:     $Id: udp.c,v 1.102 2002/02/01 22:01:04 davem Exp $
9  *
10  * Authors:     Ross Biro
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>
15  *
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
73  *
74  *
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.
79  */
80  
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>
90 #include <linux/in.h>
91 #include <linux/errno.h>
92 #include <linux/timer.h>
93 #include <linux/mm.h>
94 #include <linux/inet.h>
95 #include <linux/ipv6.h>
96 #include <linux/netdevice.h>
97 #include <net/snmp.h>
98 #include <net/ip.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>
105 #include <net/udp.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>
111
112 /*
113  *      Snmp MIB for the UDP layer
114  */
115
116 DEFINE_SNMP_STAT(struct udp_mib, udp_statistics) __read_mostly;
117
118 struct hlist_head udp_hash[UDP_HTABLE_SIZE];
119 DEFINE_RWLOCK(udp_hash_lock);
120
121 /* Shared by v4/v6 udp_get_port */
122 int udp_port_rover;
123
124 static inline int udp_lport_inuse(u16 num)
125 {
126         struct sock *sk;
127         struct hlist_node *node;
128
129         sk_for_each(sk, node, &udp_hash[num & (UDP_HTABLE_SIZE - 1)])
130                 if (inet_sk(sk)->num == num)
131                         return 1;
132         return 0;
133 }
134
135 /**
136  *  udp_get_port  -  common port lookup for IPv4 and IPv6
137  *
138  *  @sk:          socket struct in question
139  *  @snum:        port number to look up
140  *  @saddr_comp:  AF-dependent comparison of bound local IP addresses
141  */
142 int udp_get_port(struct sock *sk, unsigned short snum,
143                  int (*saddr_cmp)(struct sock *sk1, struct sock *sk2))
144 {
145         struct hlist_node *node;
146         struct hlist_head *head;
147         struct sock *sk2;
148         int    error = 1;
149
150         write_lock_bh(&udp_hash_lock);
151         if (snum == 0) {
152                 int best_size_so_far, best, result, i;
153
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++) {
160                         int size;
161
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));
168                                 goto gotit;
169                         }
170                         size = 0;
171                         sk_for_each(sk2, node, head)
172                                 if (++size < best_size_so_far) {
173                                         best_size_so_far = size;
174                                         best = result;
175                                 }
176                 }
177                 result = best;
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))
184                                 break;
185                 }
186                 if (i >= (1 << 16) / UDP_HTABLE_SIZE)
187                         goto fail;
188 gotit:
189                 udp_port_rover = snum = result;
190         } else {
191                 head = &udp_hash[snum & (UDP_HTABLE_SIZE - 1)];
192
193                 sk_for_each(sk2, node, head)
194                         if (inet_sk(sk2)->num == snum                        &&
195                             sk2 != sk                                        &&
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)                              )
200                                 goto fail;
201         }
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);
207         }
208         error = 0;
209 fail:
210         write_unlock_bh(&udp_hash_lock);
211         return error;
212 }
213
214 static inline int  ipv4_rcv_saddr_equal(struct sock *sk1, struct sock *sk2)
215 {
216         struct inet_sock *inet1 = inet_sk(sk1), *inet2 = inet_sk(sk2);
217
218         return  ( !ipv6_only_sock(sk2)  &&
219                   (!inet1->rcv_saddr || !inet2->rcv_saddr ||
220                    inet1->rcv_saddr == inet2->rcv_saddr      ));
221 }
222
223 static inline int udp_v4_get_port(struct sock *sk, unsigned short snum)
224 {
225         return udp_get_port(sk, snum, ipv4_rcv_saddr_equal);
226 }
227
228
229 static void udp_v4_hash(struct sock *sk)
230 {
231         BUG();
232 }
233
234 static void udp_v4_unhash(struct sock *sk)
235 {
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);
240         }
241         write_unlock_bh(&udp_hash_lock);
242 }
243
244 /* UDP is nearly always wildcards out the wazoo, it makes no sense to try
245  * harder than this. -DaveM
246  */
247 static struct sock *udp_v4_lookup_longway(u32 saddr, u16 sport,
248                                           u32 daddr, u16 dport, int dif)
249 {
250         struct sock *sk, *result = NULL;
251         struct hlist_node *node;
252         unsigned short hnum = ntohs(dport);
253         int badness = -1;
254
255         sk_for_each(sk, node, &udp_hash[hnum & (UDP_HTABLE_SIZE - 1)]) {
256                 struct inet_sock *inet = inet_sk(sk);
257
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)
262                                         continue;
263                                 score+=2;
264                         }
265                         if (inet->daddr) {
266                                 if (inet->daddr != saddr)
267                                         continue;
268                                 score+=2;
269                         }
270                         if (inet->dport) {
271                                 if (inet->dport != sport)
272                                         continue;
273                                 score+=2;
274                         }
275                         if (sk->sk_bound_dev_if) {
276                                 if (sk->sk_bound_dev_if != dif)
277                                         continue;
278                                 score+=2;
279                         }
280                         if(score == 9) {
281                                 result = sk;
282                                 break;
283                         } else if(score > badness) {
284                                 result = sk;
285                                 badness = score;
286                         }
287                 }
288         }
289         return result;
290 }
291
292 static __inline__ struct sock *udp_v4_lookup(u32 saddr, u16 sport,
293                                              u32 daddr, u16 dport, int dif)
294 {
295         struct sock *sk;
296
297         read_lock(&udp_hash_lock);
298         sk = udp_v4_lookup_longway(saddr, sport, daddr, dport, dif);
299         if (sk)
300                 sock_hold(sk);
301         read_unlock(&udp_hash_lock);
302         return sk;
303 }
304
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,
308                                              int dif)
309 {
310         struct hlist_node *node;
311         struct sock *s = sk;
312         unsigned short hnum = ntohs(loc_port);
313
314         sk_for_each_from(s, node) {
315                 struct inet_sock *inet = inet_sk(s);
316
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)    ||
321                     ipv6_only_sock(s)                                   ||
322                     (s->sk_bound_dev_if && s->sk_bound_dev_if != dif))
323                         continue;
324                 if (!ip_mc_sf_allow(s, loc_addr, rmt_addr, dif))
325                         continue;
326                 goto found;
327         }
328         s = NULL;
329 found:
330         return s;
331 }
332
333 /*
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.
342  */
343
344 void udp_err(struct sk_buff *skb, u32 info)
345 {
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;
351         struct sock *sk;
352         int harderr;
353         int err;
354
355         sk = udp_v4_lookup(iph->daddr, uh->dest, iph->saddr, uh->source, skb->dev->ifindex);
356         if (sk == NULL) {
357                 ICMP_INC_STATS_BH(ICMP_MIB_INERRORS);
358                 return; /* No socket for error */
359         }
360
361         err = 0;
362         harderr = 0;
363         inet = inet_sk(sk);
364
365         switch (type) {
366         default:
367         case ICMP_TIME_EXCEEDED:
368                 err = EHOSTUNREACH;
369                 break;
370         case ICMP_SOURCE_QUENCH:
371                 goto out;
372         case ICMP_PARAMETERPROB:
373                 err = EPROTO;
374                 harderr = 1;
375                 break;
376         case ICMP_DEST_UNREACH:
377                 if (code == ICMP_FRAG_NEEDED) { /* Path MTU discovery */
378                         if (inet->pmtudisc != IP_PMTUDISC_DONT) {
379                                 err = EMSGSIZE;
380                                 harderr = 1;
381                                 break;
382                         }
383                         goto out;
384                 }
385                 err = EHOSTUNREACH;
386                 if (code <= NR_ICMP_UNREACH) {
387                         harderr = icmp_err_convert[code].fatal;
388                         err = icmp_err_convert[code].errno;
389                 }
390                 break;
391         }
392
393         /*
394          *      RFC1122: OK.  Passes ICMP errors back to application, as per 
395          *      4.1.3.3.
396          */
397         if (!inet->recverr) {
398                 if (!harderr || sk->sk_state != TCP_ESTABLISHED)
399                         goto out;
400         } else {
401                 ip_icmp_error(sk, skb, err, uh->dest, info, (u8*)(uh+1));
402         }
403         sk->sk_err = err;
404         sk->sk_error_report(sk);
405 out:
406         sock_put(sk);
407 }
408
409 /*
410  * Throw away all pending data and cancel the corking. Socket is locked.
411  */
412 static void udp_flush_pending_frames(struct sock *sk)
413 {
414         struct udp_sock *up = udp_sk(sk);
415
416         if (up->pending) {
417                 up->len = 0;
418                 up->pending = 0;
419                 ip_flush_pending_frames(sk);
420         }
421 }
422
423 /*
424  * Push out all pending data as one UDP datagram. Socket is locked.
425  */
426 static int udp_push_pending_frames(struct sock *sk, struct udp_sock *up)
427 {
428         struct inet_sock *inet = inet_sk(sk);
429         struct flowi *fl = &inet->cork.fl;
430         struct sk_buff *skb;
431         struct udphdr *uh;
432         int err = 0;
433
434         /* Grab the skbuff where UDP header space exists. */
435         if ((skb = skb_peek(&sk->sk_write_queue)) == NULL)
436                 goto out;
437
438         /*
439          * Create a UDP header
440          */
441         uh = skb->h.uh;
442         uh->source = fl->fl_ip_sport;
443         uh->dest = fl->fl_ip_dport;
444         uh->len = htons(up->len);
445         uh->check = 0;
446
447         if (sk->sk_no_check == UDP_CSUM_NOXMIT) {
448                 skb->ip_summed = CHECKSUM_NONE;
449                 goto send;
450         }
451
452         if (skb_queue_len(&sk->sk_write_queue) == 1) {
453                 /*
454                  * Only one fragment on the socket.
455                  */
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);
460                 } else {
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);
465                         if (uh->check == 0)
466                                 uh->check = -1;
467                 }
468         } else {
469                 unsigned int csum = 0;
470                 /*
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.
474                  */
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);
478
479                         skb->ip_summed = CHECKSUM_NONE;
480                 } else {
481                         skb->csum = csum_partial((char *)uh,
482                                         sizeof(struct udphdr), skb->csum);
483                 }
484
485                 skb_queue_walk(&sk->sk_write_queue, skb) {
486                         csum = csum_add(csum, skb->csum);
487                 }
488                 uh->check = csum_tcpudp_magic(fl->fl4_src, fl->fl4_dst,
489                                 up->len, IPPROTO_UDP, csum);
490                 if (uh->check == 0)
491                         uh->check = -1;
492         }
493 send:
494         err = ip_push_pending_frames(sk);
495 out:
496         up->len = 0;
497         up->pending = 0;
498         return err;
499 }
500
501
502 static unsigned short udp_check(struct udphdr *uh, int len, unsigned long saddr, unsigned long daddr, unsigned long base)
503 {
504         return(csum_tcpudp_magic(saddr, daddr, len, IPPROTO_UDP, base));
505 }
506
507 int udp_sendmsg(struct kiocb *iocb, struct sock *sk, struct msghdr *msg,
508                 size_t len)
509 {
510         struct inet_sock *inet = inet_sk(sk);
511         struct udp_sock *up = udp_sk(sk);
512         int ulen = len;
513         struct ipcm_cookie ipc;
514         struct rtable *rt = NULL;
515         int free = 0;
516         int connected = 0;
517         u32 daddr, faddr, saddr;
518         u16 dport;
519         u8  tos;
520         int err;
521         int corkreq = up->corkflag || msg->msg_flags&MSG_MORE;
522
523         if (len > 0xFFFF)
524                 return -EMSGSIZE;
525
526         /* 
527          *      Check the flags.
528          */
529
530         if (msg->msg_flags&MSG_OOB)     /* Mirror BSD error message compatibility */
531                 return -EOPNOTSUPP;
532
533         ipc.opt = NULL;
534
535         if (up->pending) {
536                 /*
537                  * There are pending frames.
538                  * The socket lock must be held while it's corked.
539                  */
540                 lock_sock(sk);
541                 if (likely(up->pending)) {
542                         if (unlikely(up->pending != AF_INET)) {
543                                 release_sock(sk);
544                                 return -EINVAL;
545                         }
546                         goto do_append_data;
547                 }
548                 release_sock(sk);
549         }
550         ulen += sizeof(struct udphdr);
551
552         /*
553          *      Get and verify the address. 
554          */
555         if (msg->msg_name) {
556                 struct sockaddr_in * usin = (struct sockaddr_in*)msg->msg_name;
557                 if (msg->msg_namelen < sizeof(*usin))
558                         return -EINVAL;
559                 if (usin->sin_family != AF_INET) {
560                         if (usin->sin_family != AF_UNSPEC)
561                                 return -EAFNOSUPPORT;
562                 }
563
564                 daddr = usin->sin_addr.s_addr;
565                 dport = usin->sin_port;
566                 if (dport == 0)
567                         return -EINVAL;
568         } else {
569                 if (sk->sk_state != TCP_ESTABLISHED)
570                         return -EDESTADDRREQ;
571                 daddr = inet->daddr;
572                 dport = inet->dport;
573                 /* Open fast path for connected socket.
574                    Route will not be used, if at least one option is set.
575                  */
576                 connected = 1;
577         }
578         ipc.addr = inet->saddr;
579
580         ipc.oif = sk->sk_bound_dev_if;
581         if (msg->msg_controllen) {
582                 err = ip_cmsg_send(msg, &ipc);
583                 if (err)
584                         return err;
585                 if (ipc.opt)
586                         free = 1;
587                 connected = 0;
588         }
589         if (!ipc.opt)
590                 ipc.opt = inet->opt;
591
592         saddr = ipc.addr;
593         ipc.addr = faddr = daddr;
594
595         if (ipc.opt && ipc.opt->srr) {
596                 if (!daddr)
597                         return -EINVAL;
598                 faddr = ipc.opt->faddr;
599                 connected = 0;
600         }
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)) {
605                 tos |= RTO_ONLINK;
606                 connected = 0;
607         }
608
609         if (MULTICAST(daddr)) {
610                 if (!ipc.oif)
611                         ipc.oif = inet->mc_index;
612                 if (!saddr)
613                         saddr = inet->mc_addr;
614                 connected = 0;
615         }
616
617         if (connected)
618                 rt = (struct rtable*)sk_dst_check(sk, 0);
619
620         if (rt == NULL) {
621                 struct flowi fl = { .oif = ipc.oif,
622                                     .nl_u = { .ip4_u =
623                                               { .daddr = faddr,
624                                                 .saddr = saddr,
625                                                 .tos = tos } },
626                                     .proto = IPPROTO_UDP,
627                                     .uli_u = { .ports =
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));
632                 if (err)
633                         goto out;
634
635                 err = -EACCES;
636                 if ((rt->rt_flags & RTCF_BROADCAST) &&
637                     !sock_flag(sk, SOCK_BROADCAST))
638                         goto out;
639                 if (connected)
640                         sk_dst_set(sk, dst_clone(&rt->u.dst));
641         }
642
643         if (msg->msg_flags&MSG_CONFIRM)
644                 goto do_confirm;
645 back_from_confirm:
646
647         saddr = rt->rt_src;
648         if (!ipc.addr)
649                 daddr = ipc.addr = rt->rt_dst;
650
651         lock_sock(sk);
652         if (unlikely(up->pending)) {
653                 /* The socket is already corked while preparing it. */
654                 /* ... which is an evident application bug. --ANK */
655                 release_sock(sk);
656
657                 LIMIT_NETDEBUG(KERN_DEBUG "udp cork app bug 2\n");
658                 err = -EINVAL;
659                 goto out;
660         }
661         /*
662          *      Now cork the socket to pend data.
663          */
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;
669
670 do_append_data:
671         up->len += ulen;
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);
675         if (err)
676                 udp_flush_pending_frames(sk);
677         else if (!corkreq)
678                 err = udp_push_pending_frames(sk, up);
679         release_sock(sk);
680
681 out:
682         ip_rt_put(rt);
683         if (free)
684                 kfree(ipc.opt);
685         if (!err) {
686                 UDP_INC_STATS_USER(UDP_MIB_OUTDATAGRAMS);
687                 return len;
688         }
689         /*
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.
695          */
696         if (err == -ENOBUFS || test_bit(SOCK_NOSPACE, &sk->sk_socket->flags)) {
697                 UDP_INC_STATS_USER(UDP_MIB_SNDBUFERRORS);
698         }
699         return err;
700
701 do_confirm:
702         dst_confirm(&rt->u.dst);
703         if (!(msg->msg_flags&MSG_PROBE) || len)
704                 goto back_from_confirm;
705         err = 0;
706         goto out;
707 }
708
709 static int udp_sendpage(struct sock *sk, struct page *page, int offset,
710                         size_t size, int flags)
711 {
712         struct udp_sock *up = udp_sk(sk);
713         int ret;
714
715         if (!up->pending) {
716                 struct msghdr msg = {   .msg_flags = flags|MSG_MORE };
717
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.
721                  */
722                 ret = udp_sendmsg(NULL, sk, &msg, 0);
723                 if (ret < 0)
724                         return ret;
725         }
726
727         lock_sock(sk);
728
729         if (unlikely(!up->pending)) {
730                 release_sock(sk);
731
732                 LIMIT_NETDEBUG(KERN_DEBUG "udp cork app bug 3\n");
733                 return -EINVAL;
734         }
735
736         ret = ip_append_page(sk, page, offset, size, flags);
737         if (ret == -EOPNOTSUPP) {
738                 release_sock(sk);
739                 return sock_no_sendpage(sk->sk_socket, page, offset,
740                                         size, flags);
741         }
742         if (ret < 0) {
743                 udp_flush_pending_frames(sk);
744                 goto out;
745         }
746
747         up->len += size;
748         if (!(up->corkflag || (flags&MSG_MORE)))
749                 ret = udp_push_pending_frames(sk, up);
750         if (!ret)
751                 ret = size;
752 out:
753         release_sock(sk);
754         return ret;
755 }
756
757 /*
758  *      IOCTL requests applicable to the UDP protocol
759  */
760  
761 int udp_ioctl(struct sock *sk, int cmd, unsigned long arg)
762 {
763         switch(cmd) 
764         {
765                 case SIOCOUTQ:
766                 {
767                         int amount = atomic_read(&sk->sk_wmem_alloc);
768                         return put_user(amount, (int __user *)arg);
769                 }
770
771                 case SIOCINQ:
772                 {
773                         struct sk_buff *skb;
774                         unsigned long amount;
775
776                         amount = 0;
777                         spin_lock_bh(&sk->sk_receive_queue.lock);
778                         skb = skb_peek(&sk->sk_receive_queue);
779                         if (skb != NULL) {
780                                 /*
781                                  * We will only return the amount
782                                  * of this packet since that is all
783                                  * that will be read.
784                                  */
785                                 amount = skb->len - sizeof(struct udphdr);
786                         }
787                         spin_unlock_bh(&sk->sk_receive_queue.lock);
788                         return put_user(amount, (int __user *)arg);
789                 }
790
791                 default:
792                         return -ENOIOCTLCMD;
793         }
794         return(0);
795 }
796
797 static __inline__ int __udp_checksum_complete(struct sk_buff *skb)
798 {
799         return __skb_checksum_complete(skb);
800 }
801
802 static __inline__ int udp_checksum_complete(struct sk_buff *skb)
803 {
804         return skb->ip_summed != CHECKSUM_UNNECESSARY &&
805                 __udp_checksum_complete(skb);
806 }
807
808 /*
809  *      This should be easy, if there is something there we
810  *      return it, otherwise we block.
811  */
812
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)
815 {
816         struct inet_sock *inet = inet_sk(sk);
817         struct sockaddr_in *sin = (struct sockaddr_in *)msg->msg_name;
818         struct sk_buff *skb;
819         int copied, err;
820
821         /*
822          *      Check any passed addresses
823          */
824         if (addr_len)
825                 *addr_len=sizeof(*sin);
826
827         if (flags & MSG_ERRQUEUE)
828                 return ip_recv_error(sk, msg, len);
829
830 try_again:
831         skb = skb_recv_datagram(sk, flags, noblock, &err);
832         if (!skb)
833                 goto out;
834   
835         copied = skb->len - sizeof(struct udphdr);
836         if (copied > len) {
837                 copied = len;
838                 msg->msg_flags |= MSG_TRUNC;
839         }
840
841         if (skb->ip_summed==CHECKSUM_UNNECESSARY) {
842                 err = skb_copy_datagram_iovec(skb, sizeof(struct udphdr), msg->msg_iov,
843                                               copied);
844         } else if (msg->msg_flags&MSG_TRUNC) {
845                 if (__udp_checksum_complete(skb))
846                         goto csum_copy_err;
847                 err = skb_copy_datagram_iovec(skb, sizeof(struct udphdr), msg->msg_iov,
848                                               copied);
849         } else {
850                 err = skb_copy_and_csum_datagram_iovec(skb, sizeof(struct udphdr), msg->msg_iov);
851
852                 if (err == -EINVAL)
853                         goto csum_copy_err;
854         }
855
856         if (err)
857                 goto out_free;
858
859         sock_recv_timestamp(msg, sk, skb);
860
861         /* Copy the address. */
862         if (sin)
863         {
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));
868         }
869         if (inet->cmsg_flags)
870                 ip_cmsg_recv(msg, skb);
871
872         err = copied;
873         if (flags & MSG_TRUNC)
874                 err = skb->len - sizeof(struct udphdr);
875   
876 out_free:
877         skb_free_datagram(sk, skb);
878 out:
879         return err;
880
881 csum_copy_err:
882         UDP_INC_STATS_BH(UDP_MIB_INERRORS);
883
884         skb_kill_datagram(sk, skb, flags);
885
886         if (noblock)
887                 return -EAGAIN; 
888         goto try_again;
889 }
890
891
892 int udp_disconnect(struct sock *sk, int flags)
893 {
894         struct inet_sock *inet = inet_sk(sk);
895         /*
896          *      1003.1g - break association.
897          */
898          
899         sk->sk_state = TCP_CLOSE;
900         inet->daddr = 0;
901         inet->dport = 0;
902         sk->sk_bound_dev_if = 0;
903         if (!(sk->sk_userlocks & SOCK_BINDADDR_LOCK))
904                 inet_reset_saddr(sk);
905
906         if (!(sk->sk_userlocks & SOCK_BINDPORT_LOCK)) {
907                 sk->sk_prot->unhash(sk);
908                 inet->sport = 0;
909         }
910         sk_dst_reset(sk);
911         return 0;
912 }
913
914 static void udp_close(struct sock *sk, long timeout)
915 {
916         sk_common_release(sk);
917 }
918
919 /* return:
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
923  */
924 static int udp_encap_rcv(struct sock * sk, struct sk_buff *skb)
925 {
926 #ifndef CONFIG_XFRM
927         return 1; 
928 #else
929         struct udp_sock *up = udp_sk(sk);
930         struct udphdr *uh = skb->h.uh;
931         struct iphdr *iph;
932         int iphlen, len;
933   
934         __u8 *udpdata = (__u8 *)uh + sizeof(struct udphdr);
935         __u32 *udpdata32 = (__u32 *)udpdata;
936         __u16 encap_type = up->encap_type;
937
938         /* if we're overly short, let UDP handle it */
939         if (udpdata > skb->tail)
940                 return 1;
941
942         /* if this is not encapsulated socket, then just return now */
943         if (!encap_type)
944                 return 1;
945
946         len = skb->tail - udpdata;
947
948         switch (encap_type) {
949         default:
950         case UDP_ENCAP_ESPINUDP:
951                 /* Check if this is a keepalive packet.  If so, eat it. */
952                 if (len == 1 && udpdata[0] == 0xff) {
953                         return 0;
954                 } else if (len > sizeof(struct ip_esp_hdr) && udpdata32[0] != 0 ) {
955                         /* ESP Packet without Non-ESP header */
956                         len = sizeof(struct udphdr);
957                 } else
958                         /* Must be an IKE packet.. pass it through */
959                         return 1;
960                 break;
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) {
964                         return 0;
965                 } else if (len > 2 * sizeof(u32) + sizeof(struct ip_esp_hdr) &&
966                            udpdata32[0] == 0 && udpdata32[1] == 0) {
967                         
968                         /* ESP Packet with Non-IKE marker */
969                         len = sizeof(struct udphdr) + 2 * sizeof(u32);
970                 } else
971                         /* Must be an IKE packet.. pass it through */
972                         return 1;
973                 break;
974         }
975
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.
980          */
981         if (skb_cloned(skb) && pskb_expand_head(skb, 0, 0, GFP_ATOMIC))
982                 return 0;
983
984         /* Now we can update and verify the packet length... */
985         iph = skb->nh.iph;
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!?! */
990                 return 0;
991         }
992
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
995          * for later.
996          */
997         skb->h.raw = skb_pull(skb, len);
998
999         /* modify the protocol (it's ESP!) */
1000         iph->protocol = IPPROTO_ESP;
1001
1002         /* and let the caller know to send this into the ESP processor... */
1003         return -1;
1004 #endif
1005 }
1006
1007 /* returns:
1008  *  -1: error
1009  *   0: success
1010  *  >0: "udp encap" protocol resubmission
1011  *
1012  * Note that in the success and error cases, the skb is assumed to
1013  * have either been requeued or freed.
1014  */
1015 static int udp_queue_rcv_skb(struct sock * sk, struct sk_buff *skb)
1016 {
1017         struct udp_sock *up = udp_sk(sk);
1018         int rc;
1019
1020         /*
1021          *      Charge it to the socket, dropping if the queue is full.
1022          */
1023         if (!xfrm4_policy_check(sk, XFRM_POLICY_IN, skb)) {
1024                 kfree_skb(skb);
1025                 return -1;
1026         }
1027         nf_reset(skb);
1028
1029         if (up->encap_type) {
1030                 /*
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.
1038                  */
1039                 int ret;
1040
1041                 ret = udp_encap_rcv(sk, skb);
1042                 if (ret == 0) {
1043                         /* Eat the packet .. */
1044                         kfree_skb(skb);
1045                         return 0;
1046                 }
1047                 if (ret < 0) {
1048                         /* process the ESP packet */
1049                         ret = xfrm4_rcv_encap(skb, up->encap_type);
1050                         UDP_INC_STATS_BH(UDP_MIB_INDATAGRAMS);
1051                         return -ret;
1052                 }
1053                 /* FALLTHROUGH -- it's a UDP Packet */
1054         }
1055
1056         if (sk->sk_filter && skb->ip_summed != CHECKSUM_UNNECESSARY) {
1057                 if (__udp_checksum_complete(skb)) {
1058                         UDP_INC_STATS_BH(UDP_MIB_INERRORS);
1059                         kfree_skb(skb);
1060                         return -1;
1061                 }
1062                 skb->ip_summed = CHECKSUM_UNNECESSARY;
1063         }
1064
1065         if ((rc = sock_queue_rcv_skb(sk,skb)) < 0) {
1066                 /* Note that an ENOMEM error is charged twice */
1067                 if (rc == -ENOMEM)
1068                         UDP_INC_STATS_BH(UDP_MIB_RCVBUFERRORS);
1069                 UDP_INC_STATS_BH(UDP_MIB_INERRORS);
1070                 kfree_skb(skb);
1071                 return -1;
1072         }
1073         UDP_INC_STATS_BH(UDP_MIB_INDATAGRAMS);
1074         return 0;
1075 }
1076
1077 /*
1078  *      Multicasts and broadcasts go to each listener.
1079  *
1080  *      Note: called only from the BH handler context,
1081  *      so we don't need to lock the hashes.
1082  */
1083 static int udp_v4_mcast_deliver(struct sk_buff *skb, struct udphdr *uh,
1084                                  u32 saddr, u32 daddr)
1085 {
1086         struct sock *sk;
1087         int dif;
1088
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);
1093         if (sk) {
1094                 struct sock *sknext = NULL;
1095
1096                 do {
1097                         struct sk_buff *skb1 = skb;
1098
1099                         sknext = udp_v4_mcast_next(sk_next(sk), uh->dest, daddr,
1100                                                    uh->source, saddr, dif);
1101                         if(sknext)
1102                                 skb1 = skb_clone(skb, GFP_ATOMIC);
1103
1104                         if(skb1) {
1105                                 int ret = udp_queue_rcv_skb(sk, skb1);
1106                                 if (ret > 0)
1107                                         /* we should probably re-process instead
1108                                          * of dropping packets here. */
1109                                         kfree_skb(skb1);
1110                         }
1111                         sk = sknext;
1112                 } while(sknext);
1113         } else
1114                 kfree_skb(skb);
1115         read_unlock(&udp_hash_lock);
1116         return 0;
1117 }
1118
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.
1123  */
1124 static void udp_checksum_init(struct sk_buff *skb, struct udphdr *uh,
1125                              unsigned short ulen, u32 saddr, u32 daddr)
1126 {
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;
1132         }
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).
1137          */
1138 }
1139
1140 /*
1141  *      All we need to do is get the socket, and then do a checksum. 
1142  */
1143  
1144 int udp_rcv(struct sk_buff *skb)
1145 {
1146         struct sock *sk;
1147         struct udphdr *uh;
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;
1152         int len = skb->len;
1153
1154         /*
1155          *      Validate the packet and the UDP length.
1156          */
1157         if (!pskb_may_pull(skb, sizeof(struct udphdr)))
1158                 goto no_header;
1159
1160         uh = skb->h.uh;
1161
1162         ulen = ntohs(uh->len);
1163
1164         if (ulen > len || ulen < sizeof(*uh))
1165                 goto short_packet;
1166
1167         if (pskb_trim_rcsum(skb, ulen))
1168                 goto short_packet;
1169
1170         udp_checksum_init(skb, uh, ulen, saddr, daddr);
1171
1172         if(rt->rt_flags & (RTCF_BROADCAST|RTCF_MULTICAST))
1173                 return udp_v4_mcast_deliver(skb, uh, saddr, daddr);
1174
1175         sk = udp_v4_lookup(saddr, uh->source, daddr, uh->dest, skb->dev->ifindex);
1176
1177         if (sk != NULL) {
1178                 int ret = udp_queue_rcv_skb(sk, skb);
1179                 sock_put(sk);
1180
1181                 /* a return value > 0 means to resubmit the input, but
1182                  * it it wants the return to be -protocol, or 0
1183                  */
1184                 if (ret > 0)
1185                         return -ret;
1186                 return 0;
1187         }
1188
1189         if (!xfrm4_policy_check(NULL, XFRM_POLICY_IN, skb))
1190                 goto drop;
1191         nf_reset(skb);
1192
1193         /* No socket. Drop packet silently, if checksum is wrong */
1194         if (udp_checksum_complete(skb))
1195                 goto csum_error;
1196
1197         UDP_INC_STATS_BH(UDP_MIB_NOPORTS);
1198         icmp_send(skb, ICMP_DEST_UNREACH, ICMP_PORT_UNREACH, 0);
1199
1200         /*
1201          * Hmm.  We got an UDP packet to a port to which we
1202          * don't wanna listen.  Ignore it.
1203          */
1204         kfree_skb(skb);
1205         return(0);
1206
1207 short_packet:
1208         LIMIT_NETDEBUG(KERN_DEBUG "UDP: short packet: From %u.%u.%u.%u:%u %d/%d to %u.%u.%u.%u:%u\n",
1209                        NIPQUAD(saddr),
1210                        ntohs(uh->source),
1211                        ulen,
1212                        len,
1213                        NIPQUAD(daddr),
1214                        ntohs(uh->dest));
1215 no_header:
1216         UDP_INC_STATS_BH(UDP_MIB_INERRORS);
1217         kfree_skb(skb);
1218         return(0);
1219
1220 csum_error:
1221         /* 
1222          * RFC1122: OK.  Discards the bad packet silently (as far as 
1223          * the network is concerned, anyway) as per 4.1.3.4 (MUST). 
1224          */
1225         LIMIT_NETDEBUG(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(UDP_MIB_INERRORS);
1233         kfree_skb(skb);
1234         return(0);
1235 }
1236
1237 static int udp_destroy_sock(struct sock *sk)
1238 {
1239         lock_sock(sk);
1240         udp_flush_pending_frames(sk);
1241         release_sock(sk);
1242         return 0;
1243 }
1244
1245 /*
1246  *      Socket option code for UDP
1247  */
1248 static int do_udp_setsockopt(struct sock *sk, int level, int optname,
1249                           char __user *optval, int optlen)
1250 {
1251         struct udp_sock *up = udp_sk(sk);
1252         int val;
1253         int err = 0;
1254
1255         if(optlen<sizeof(int))
1256                 return -EINVAL;
1257
1258         if (get_user(val, (int __user *)optval))
1259                 return -EFAULT;
1260
1261         switch(optname) {
1262         case UDP_CORK:
1263                 if (val != 0) {
1264                         up->corkflag = 1;
1265                 } else {
1266                         up->corkflag = 0;
1267                         lock_sock(sk);
1268                         udp_push_pending_frames(sk, up);
1269                         release_sock(sk);
1270                 }
1271                 break;
1272                 
1273         case UDP_ENCAP:
1274                 switch (val) {
1275                 case 0:
1276                 case UDP_ENCAP_ESPINUDP:
1277                 case UDP_ENCAP_ESPINUDP_NON_IKE:
1278                         up->encap_type = val;
1279                         break;
1280                 default:
1281                         err = -ENOPROTOOPT;
1282                         break;
1283                 }
1284                 break;
1285
1286         default:
1287                 err = -ENOPROTOOPT;
1288                 break;
1289         };
1290
1291         return err;
1292 }
1293
1294 static int udp_setsockopt(struct sock *sk, int level, int optname,
1295                           char __user *optval, int optlen)
1296 {
1297         if (level != SOL_UDP)
1298                 return ip_setsockopt(sk, level, optname, optval, optlen);
1299         return do_udp_setsockopt(sk, level, optname, optval, optlen);
1300 }
1301
1302 #ifdef CONFIG_COMPAT
1303 static int compat_udp_setsockopt(struct sock *sk, int level, int optname,
1304                                  char __user *optval, int optlen)
1305 {
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);
1309 }
1310 #endif
1311
1312 static int do_udp_getsockopt(struct sock *sk, int level, int optname,
1313                           char __user *optval, int __user *optlen)
1314 {
1315         struct udp_sock *up = udp_sk(sk);
1316         int val, len;
1317
1318         if(get_user(len,optlen))
1319                 return -EFAULT;
1320
1321         len = min_t(unsigned int, len, sizeof(int));
1322         
1323         if(len < 0)
1324                 return -EINVAL;
1325
1326         switch(optname) {
1327         case UDP_CORK:
1328                 val = up->corkflag;
1329                 break;
1330
1331         case UDP_ENCAP:
1332                 val = up->encap_type;
1333                 break;
1334
1335         default:
1336                 return -ENOPROTOOPT;
1337         };
1338
1339         if(put_user(len, optlen))
1340                 return -EFAULT;
1341         if(copy_to_user(optval, &val,len))
1342                 return -EFAULT;
1343         return 0;
1344 }
1345
1346 static int udp_getsockopt(struct sock *sk, int level, int optname,
1347                           char __user *optval, int __user *optlen)
1348 {
1349         if (level != SOL_UDP)
1350                 return ip_getsockopt(sk, level, optname, optval, optlen);
1351         return do_udp_getsockopt(sk, level, optname, optval, optlen);
1352 }
1353
1354 #ifdef CONFIG_COMPAT
1355 static int compat_udp_getsockopt(struct sock *sk, int level, int optname,
1356                                  char __user *optval, int __user *optlen)
1357 {
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);
1361 }
1362 #endif
1363 /**
1364  *      udp_poll - wait for a UDP event.
1365  *      @file - file struct
1366  *      @sock - socket
1367  *      @wait - poll table
1368  *
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.
1375  */
1376 unsigned int udp_poll(struct file *file, struct socket *sock, poll_table *wait)
1377 {
1378         unsigned int mask = datagram_poll(file, sock, wait);
1379         struct sock *sk = sock->sk;
1380         
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;
1387
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);
1393                                 kfree_skb(skb);
1394                         } else {
1395                                 skb->ip_summed = CHECKSUM_UNNECESSARY;
1396                                 break;
1397                         }
1398                 }
1399                 spin_unlock_bh(&rcvq->lock);
1400
1401                 /* nothing to see, move along */
1402                 if (skb == NULL)
1403                         mask &= ~(POLLIN | POLLRDNORM);
1404         }
1405
1406         return mask;
1407         
1408 }
1409
1410 struct proto udp_prot = {
1411         .name              = "UDP",
1412         .owner             = THIS_MODULE,
1413         .close             = udp_close,
1414         .connect           = ip4_datagram_connect,
1415         .disconnect        = udp_disconnect,
1416         .ioctl             = udp_ioctl,
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,
1431 #endif
1432 };
1433
1434 /* ------------------------------------------------------------------------ */
1435 #ifdef CONFIG_PROC_FS
1436
1437 static struct sock *udp_get_first(struct seq_file *seq)
1438 {
1439         struct sock *sk;
1440         struct udp_iter_state *state = seq->private;
1441
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)
1446                                 goto found;
1447                 }
1448         }
1449         sk = NULL;
1450 found:
1451         return sk;
1452 }
1453
1454 static struct sock *udp_get_next(struct seq_file *seq, struct sock *sk)
1455 {
1456         struct udp_iter_state *state = seq->private;
1457
1458         do {
1459                 sk = sk_next(sk);
1460 try_again:
1461                 ;
1462         } while (sk && sk->sk_family != state->family);
1463
1464         if (!sk && ++state->bucket < UDP_HTABLE_SIZE) {
1465                 sk = sk_head(&udp_hash[state->bucket]);
1466                 goto try_again;
1467         }
1468         return sk;
1469 }
1470
1471 static struct sock *udp_get_idx(struct seq_file *seq, loff_t pos)
1472 {
1473         struct sock *sk = udp_get_first(seq);
1474
1475         if (sk)
1476                 while(pos && (sk = udp_get_next(seq, sk)) != NULL)
1477                         --pos;
1478         return pos ? NULL : sk;
1479 }
1480
1481 static void *udp_seq_start(struct seq_file *seq, loff_t *pos)
1482 {
1483         read_lock(&udp_hash_lock);
1484         return *pos ? udp_get_idx(seq, *pos-1) : (void *)1;
1485 }
1486
1487 static void *udp_seq_next(struct seq_file *seq, void *v, loff_t *pos)
1488 {
1489         struct sock *sk;
1490
1491         if (v == (void *)1)
1492                 sk = udp_get_idx(seq, 0);
1493         else
1494                 sk = udp_get_next(seq, v);
1495
1496         ++*pos;
1497         return sk;
1498 }
1499
1500 static void udp_seq_stop(struct seq_file *seq, void *v)
1501 {
1502         read_unlock(&udp_hash_lock);
1503 }
1504
1505 static int udp_seq_open(struct inode *inode, struct file *file)
1506 {
1507         struct udp_seq_afinfo *afinfo = PDE(inode)->data;
1508         struct seq_file *seq;
1509         int rc = -ENOMEM;
1510         struct udp_iter_state *s = kzalloc(sizeof(*s), GFP_KERNEL);
1511
1512         if (!s)
1513                 goto out;
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;
1519
1520         rc = seq_open(file, &s->seq_ops);
1521         if (rc)
1522                 goto out_kfree;
1523
1524         seq          = file->private_data;
1525         seq->private = s;
1526 out:
1527         return rc;
1528 out_kfree:
1529         kfree(s);
1530         goto out;
1531 }
1532
1533 /* ------------------------------------------------------------------------ */
1534 int udp_proc_register(struct udp_seq_afinfo *afinfo)
1535 {
1536         struct proc_dir_entry *p;
1537         int rc = 0;
1538
1539         if (!afinfo)
1540                 return -EINVAL;
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;
1546
1547         p = proc_net_fops_create(afinfo->name, S_IRUGO, afinfo->seq_fops);
1548         if (p)
1549                 p->data = afinfo;
1550         else
1551                 rc = -ENOMEM;
1552         return rc;
1553 }
1554
1555 void udp_proc_unregister(struct udp_seq_afinfo *afinfo)
1556 {
1557         if (!afinfo)
1558                 return;
1559         proc_net_remove(afinfo->name);
1560         memset(afinfo->seq_fops, 0, sizeof(*afinfo->seq_fops));
1561 }
1562
1563 /* ------------------------------------------------------------------------ */
1564 static void udp4_format_sock(struct sock *sp, char *tmpbuf, int bucket)
1565 {
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);
1571
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);
1579 }
1580
1581 static int udp4_seq_show(struct seq_file *seq, void *v)
1582 {
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 "
1587                            "inode");
1588         else {
1589                 char tmpbuf[129];
1590                 struct udp_iter_state *state = seq->private;
1591
1592                 udp4_format_sock(v, tmpbuf, state->bucket);
1593                 seq_printf(seq, "%-127s\n", tmpbuf);
1594         }
1595         return 0;
1596 }
1597
1598 /* ------------------------------------------------------------------------ */
1599 static struct file_operations udp4_seq_fops;
1600 static struct udp_seq_afinfo udp4_seq_afinfo = {
1601         .owner          = THIS_MODULE,
1602         .name           = "udp",
1603         .family         = AF_INET,
1604         .seq_show       = udp4_seq_show,
1605         .seq_fops       = &udp4_seq_fops,
1606 };
1607
1608 int __init udp4_proc_init(void)
1609 {
1610         return udp_proc_register(&udp4_seq_afinfo);
1611 }
1612
1613 void udp4_proc_exit(void)
1614 {
1615         udp_proc_unregister(&udp4_seq_afinfo);
1616 }
1617 #endif /* CONFIG_PROC_FS */
1618
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);
1627
1628 #ifdef CONFIG_PROC_FS
1629 EXPORT_SYMBOL(udp_proc_register);
1630 EXPORT_SYMBOL(udp_proc_unregister);
1631 #endif