vserver 1.9.5.x5
[linux-2.6.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, <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>
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/in.h>
90 #include <linux/errno.h>
91 #include <linux/timer.h>
92 #include <linux/mm.h>
93 #include <linux/config.h>
94 #include <linux/inet.h>
95 #include <linux/ipv6.h>
96 #include <linux/netdevice.h>
97 #include <net/snmp.h>
98 #include <net/tcp.h>
99 #include <net/protocol.h>
100 #include <linux/skbuff.h>
101 #include <linux/proc_fs.h>
102 #include <linux/seq_file.h>
103 #include <net/sock.h>
104 #include <net/udp.h>
105 #include <net/icmp.h>
106 #include <net/route.h>
107 #include <net/inet_common.h>
108 #include <net/checksum.h>
109 #include <net/xfrm.h>
110
111 /*
112  *      Snmp MIB for the UDP layer
113  */
114
115 DEFINE_SNMP_STAT(struct udp_mib, udp_statistics);
116
117 struct hlist_head udp_hash[UDP_HTABLE_SIZE];
118 DEFINE_RWLOCK(udp_hash_lock);
119
120 /* Shared by v4/v6 udp. */
121 int udp_port_rover;
122
123 static int udp_v4_get_port(struct sock *sk, unsigned short snum)
124 {
125         struct hlist_node *node;
126         struct sock *sk2;
127         struct inet_sock *inet = inet_sk(sk);
128
129         write_lock_bh(&udp_hash_lock);
130         if (snum == 0) {
131                 int best_size_so_far, best, result, i;
132
133                 if (udp_port_rover > sysctl_local_port_range[1] ||
134                     udp_port_rover < sysctl_local_port_range[0])
135                         udp_port_rover = sysctl_local_port_range[0];
136                 best_size_so_far = 32767;
137                 best = result = udp_port_rover;
138                 for (i = 0; i < UDP_HTABLE_SIZE; i++, result++) {
139                         struct hlist_head *list;
140                         int size;
141
142                         list = &udp_hash[result & (UDP_HTABLE_SIZE - 1)];
143                         if (hlist_empty(list)) {
144                                 if (result > sysctl_local_port_range[1])
145                                         result = sysctl_local_port_range[0] +
146                                                 ((result - sysctl_local_port_range[0]) &
147                                                  (UDP_HTABLE_SIZE - 1));
148                                 goto gotit;
149                         }
150                         size = 0;
151                         sk_for_each(sk2, node, list)
152                                 if (++size >= best_size_so_far)
153                                         goto next;
154                         best_size_so_far = size;
155                         best = result;
156                 next:;
157                 }
158                 result = best;
159                 for(i = 0; i < (1 << 16) / UDP_HTABLE_SIZE; i++, result += UDP_HTABLE_SIZE) {
160                         if (result > sysctl_local_port_range[1])
161                                 result = sysctl_local_port_range[0]
162                                         + ((result - sysctl_local_port_range[0]) &
163                                            (UDP_HTABLE_SIZE - 1));
164                         if (!udp_lport_inuse(result))
165                                 break;
166                 }
167                 if (i >= (1 << 16) / UDP_HTABLE_SIZE)
168                         goto fail;
169 gotit:
170                 udp_port_rover = snum = result;
171         } else {
172                 sk_for_each(sk2, node,
173                             &udp_hash[snum & (UDP_HTABLE_SIZE - 1)]) {
174                         struct inet_sock *inet2 = inet_sk(sk2);
175
176                         if (inet2->num == snum &&
177                             sk2 != sk && !ipv6_only_sock(sk2) &&
178                             (!sk2->sk_bound_dev_if ||
179                              !sk->sk_bound_dev_if ||
180                              sk2->sk_bound_dev_if == sk->sk_bound_dev_if) &&
181                             nx_addr_conflict(sk->sk_nx_info,
182                              tcp_v4_rcv_saddr(sk), sk2) &&
183                             (!sk2->sk_reuse || !sk->sk_reuse))
184                                 goto fail;
185                 }
186         }
187         inet->num = snum;
188         if (sk_unhashed(sk)) {
189                 struct hlist_head *h = &udp_hash[snum & (UDP_HTABLE_SIZE - 1)];
190
191                 sk_add_node(sk, h);
192                 sock_prot_inc_use(sk->sk_prot);
193         }
194         write_unlock_bh(&udp_hash_lock);
195         return 0;
196
197 fail:
198         write_unlock_bh(&udp_hash_lock);
199         return 1;
200 }
201
202 static void udp_v4_hash(struct sock *sk)
203 {
204         BUG();
205 }
206
207 static void udp_v4_unhash(struct sock *sk)
208 {
209         write_lock_bh(&udp_hash_lock);
210         if (sk_del_node_init(sk)) {
211                 inet_sk(sk)->num = 0;
212                 sock_prot_dec_use(sk->sk_prot);
213         }
214         write_unlock_bh(&udp_hash_lock);
215 }
216
217 static inline int udp_in_list(struct nx_info *nx_info, u32 addr)
218 {
219         int n = nx_info->nbipv4;
220         int i;
221
222         for (i=0; i<n; i++)
223                 if (nx_info->ipv4[i] == addr)
224                         return 1;
225         return 0;
226 }
227
228 /* UDP is nearly always wildcards out the wazoo, it makes no sense to try
229  * harder than this. -DaveM
230  */
231 static struct sock *udp_v4_lookup_longway(u32 saddr, u16 sport,
232                                           u32 daddr, u16 dport, int dif)
233 {
234         struct sock *sk, *result = NULL;
235         struct hlist_node *node;
236         unsigned short hnum = ntohs(dport);
237         int badness = -1;
238
239         sk_for_each(sk, node, &udp_hash[hnum & (UDP_HTABLE_SIZE - 1)]) {
240                 struct inet_sock *inet = inet_sk(sk);
241
242                 if (inet->num == hnum && !ipv6_only_sock(sk)) {
243                         int score = (sk->sk_family == PF_INET ? 1 : 0);
244                         if (inet->rcv_saddr) {
245                                 if (inet->rcv_saddr != daddr)
246                                         continue;
247                                 score+=2;
248                         } else if (sk->sk_nx_info) {
249                                 if (udp_in_list(sk->sk_nx_info, daddr))
250                                         score+=2;
251                                 else
252                                         continue;
253                         }
254                         if (inet->daddr) {
255                                 if (inet->daddr != saddr)
256                                         continue;
257                                 score+=2;
258                         }
259                         if (inet->dport) {
260                                 if (inet->dport != sport)
261                                         continue;
262                                 score+=2;
263                         }
264                         if (sk->sk_bound_dev_if) {
265                                 if (sk->sk_bound_dev_if != dif)
266                                         continue;
267                                 score+=2;
268                         }
269                         if(score == 9) {
270                                 result = sk;
271                                 break;
272                         } else if(score > badness) {
273                                 result = sk;
274                                 badness = score;
275                         }
276                 }
277         }
278         return result;
279 }
280
281 static __inline__ struct sock *udp_v4_lookup(u32 saddr, u16 sport,
282                                              u32 daddr, u16 dport, int dif)
283 {
284         struct sock *sk;
285
286         read_lock(&udp_hash_lock);
287         sk = udp_v4_lookup_longway(saddr, sport, daddr, dport, dif);
288         if (sk)
289                 sock_hold(sk);
290         read_unlock(&udp_hash_lock);
291         return sk;
292 }
293
294 static inline struct sock *udp_v4_mcast_next(struct sock *sk,
295                                              u16 loc_port, u32 loc_addr,
296                                              u16 rmt_port, u32 rmt_addr,
297                                              int dif)
298 {
299         struct hlist_node *node;
300         struct sock *s = sk;
301         unsigned short hnum = ntohs(loc_port);
302
303         sk_for_each_from(s, node) {
304                 struct inet_sock *inet = inet_sk(s);
305
306                 if (inet->num != hnum                                   ||
307                     (inet->daddr && inet->daddr != rmt_addr)            ||
308                     (inet->dport != rmt_port && inet->dport)            ||
309                     (inet->rcv_saddr && inet->rcv_saddr != loc_addr &&
310                      inet->rcv_saddr2 && inet->rcv_saddr2 != loc_addr)  ||
311                     ipv6_only_sock(s)                                   ||
312                     (s->sk_bound_dev_if && s->sk_bound_dev_if != dif))
313                         continue;
314                 if (!ip_mc_sf_allow(s, loc_addr, rmt_addr, dif))
315                         continue;
316                 goto found;
317         }
318         s = NULL;
319 found:
320         return s;
321 }
322
323 /*
324  * This routine is called by the ICMP module when it gets some
325  * sort of error condition.  If err < 0 then the socket should
326  * be closed and the error returned to the user.  If err > 0
327  * it's just the icmp type << 8 | icmp code.  
328  * Header points to the ip header of the error packet. We move
329  * on past this. Then (as it used to claim before adjustment)
330  * header points to the first 8 bytes of the udp header.  We need
331  * to find the appropriate port.
332  */
333
334 void udp_err(struct sk_buff *skb, u32 info)
335 {
336         struct inet_sock *inet;
337         struct iphdr *iph = (struct iphdr*)skb->data;
338         struct udphdr *uh = (struct udphdr*)(skb->data+(iph->ihl<<2));
339         int type = skb->h.icmph->type;
340         int code = skb->h.icmph->code;
341         struct sock *sk;
342         int harderr;
343         int err;
344
345         sk = udp_v4_lookup(iph->daddr, uh->dest, iph->saddr, uh->source, skb->dev->ifindex);
346         if (sk == NULL) {
347                 ICMP_INC_STATS_BH(ICMP_MIB_INERRORS);
348                 return; /* No socket for error */
349         }
350
351         err = 0;
352         harderr = 0;
353         inet = inet_sk(sk);
354
355         switch (type) {
356         default:
357         case ICMP_TIME_EXCEEDED:
358                 err = EHOSTUNREACH;
359                 break;
360         case ICMP_SOURCE_QUENCH:
361                 goto out;
362         case ICMP_PARAMETERPROB:
363                 err = EPROTO;
364                 harderr = 1;
365                 break;
366         case ICMP_DEST_UNREACH:
367                 if (code == ICMP_FRAG_NEEDED) { /* Path MTU discovery */
368                         if (inet->pmtudisc != IP_PMTUDISC_DONT) {
369                                 err = EMSGSIZE;
370                                 harderr = 1;
371                                 break;
372                         }
373                         goto out;
374                 }
375                 err = EHOSTUNREACH;
376                 if (code <= NR_ICMP_UNREACH) {
377                         harderr = icmp_err_convert[code].fatal;
378                         err = icmp_err_convert[code].errno;
379                 }
380                 break;
381         }
382
383         /*
384          *      RFC1122: OK.  Passes ICMP errors back to application, as per 
385          *      4.1.3.3.
386          */
387         if (!inet->recverr) {
388                 if (!harderr || sk->sk_state != TCP_ESTABLISHED)
389                         goto out;
390         } else {
391                 ip_icmp_error(sk, skb, err, uh->dest, info, (u8*)(uh+1));
392         }
393         sk->sk_err = err;
394         sk->sk_error_report(sk);
395 out:
396         sock_put(sk);
397 }
398
399 /*
400  * Throw away all pending data and cancel the corking. Socket is locked.
401  */
402 static void udp_flush_pending_frames(struct sock *sk)
403 {
404         struct udp_sock *up = udp_sk(sk);
405
406         if (up->pending) {
407                 up->len = 0;
408                 up->pending = 0;
409                 ip_flush_pending_frames(sk);
410         }
411 }
412
413 /*
414  * Push out all pending data as one UDP datagram. Socket is locked.
415  */
416 static int udp_push_pending_frames(struct sock *sk, struct udp_sock *up)
417 {
418         struct inet_sock *inet = inet_sk(sk);
419         struct flowi *fl = &inet->cork.fl;
420         struct sk_buff *skb;
421         struct udphdr *uh;
422         int err = 0;
423
424         /* Grab the skbuff where UDP header space exists. */
425         if ((skb = skb_peek(&sk->sk_write_queue)) == NULL)
426                 goto out;
427
428         /*
429          * Create a UDP header
430          */
431         uh = skb->h.uh;
432         uh->source = fl->fl_ip_sport;
433         uh->dest = fl->fl_ip_dport;
434         uh->len = htons(up->len);
435         uh->check = 0;
436
437         if (sk->sk_no_check == UDP_CSUM_NOXMIT) {
438                 skb->ip_summed = CHECKSUM_NONE;
439                 goto send;
440         }
441
442         if (skb_queue_len(&sk->sk_write_queue) == 1) {
443                 /*
444                  * Only one fragment on the socket.
445                  */
446                 if (skb->ip_summed == CHECKSUM_HW) {
447                         skb->csum = offsetof(struct udphdr, check);
448                         uh->check = ~csum_tcpudp_magic(fl->fl4_src, fl->fl4_dst,
449                                         up->len, IPPROTO_UDP, 0);
450                 } else {
451                         skb->csum = csum_partial((char *)uh,
452                                         sizeof(struct udphdr), skb->csum);
453                         uh->check = csum_tcpudp_magic(fl->fl4_src, fl->fl4_dst,
454                                         up->len, IPPROTO_UDP, skb->csum);
455                         if (uh->check == 0)
456                                 uh->check = -1;
457                 }
458         } else {
459                 unsigned int csum = 0;
460                 /*
461                  * HW-checksum won't work as there are two or more 
462                  * fragments on the socket so that all csums of sk_buffs
463                  * should be together.
464                  */
465                 if (skb->ip_summed == CHECKSUM_HW) {
466                         int offset = (unsigned char *)uh - skb->data;
467                         skb->csum = skb_checksum(skb, offset, skb->len - offset, 0);
468
469                         skb->ip_summed = CHECKSUM_NONE;
470                 } else {
471                         skb->csum = csum_partial((char *)uh,
472                                         sizeof(struct udphdr), skb->csum);
473                 }
474
475                 skb_queue_walk(&sk->sk_write_queue, skb) {
476                         csum = csum_add(csum, skb->csum);
477                 }
478                 uh->check = csum_tcpudp_magic(fl->fl4_src, fl->fl4_dst,
479                                 up->len, IPPROTO_UDP, csum);
480                 if (uh->check == 0)
481                         uh->check = -1;
482         }
483 send:
484         err = ip_push_pending_frames(sk);
485 out:
486         up->len = 0;
487         up->pending = 0;
488         return err;
489 }
490
491
492 static unsigned short udp_check(struct udphdr *uh, int len, unsigned long saddr, unsigned long daddr, unsigned long base)
493 {
494         return(csum_tcpudp_magic(saddr, daddr, len, IPPROTO_UDP, base));
495 }
496
497 int udp_sendmsg(struct kiocb *iocb, struct sock *sk, struct msghdr *msg,
498                 size_t len)
499 {
500         struct inet_sock *inet = inet_sk(sk);
501         struct udp_sock *up = udp_sk(sk);
502         int ulen = len;
503         struct ipcm_cookie ipc;
504         struct rtable *rt = NULL;
505         int free = 0;
506         int connected = 0;
507         u32 daddr, faddr, saddr;
508         u16 dport;
509         u8  tos;
510         int err;
511         int corkreq = up->corkflag || msg->msg_flags&MSG_MORE;
512
513         if (len > 0xFFFF)
514                 return -EMSGSIZE;
515
516         /* 
517          *      Check the flags.
518          */
519
520         if (msg->msg_flags&MSG_OOB)     /* Mirror BSD error message compatibility */
521                 return -EOPNOTSUPP;
522
523         ipc.opt = NULL;
524
525         if (up->pending) {
526                 /*
527                  * There are pending frames.
528                  * The socket lock must be held while it's corked.
529                  */
530                 lock_sock(sk);
531                 if (likely(up->pending)) {
532                         if (unlikely(up->pending != AF_INET)) {
533                                 release_sock(sk);
534                                 return -EINVAL;
535                         }
536                         goto do_append_data;
537                 }
538                 release_sock(sk);
539         }
540         ulen += sizeof(struct udphdr);
541
542         /*
543          *      Get and verify the address. 
544          */
545         if (msg->msg_name) {
546                 struct sockaddr_in * usin = (struct sockaddr_in*)msg->msg_name;
547                 if (msg->msg_namelen < sizeof(*usin))
548                         return -EINVAL;
549                 if (usin->sin_family != AF_INET) {
550                         if (usin->sin_family != AF_UNSPEC)
551                                 return -EAFNOSUPPORT;
552                 }
553
554                 daddr = usin->sin_addr.s_addr;
555                 dport = usin->sin_port;
556                 if (dport == 0)
557                         return -EINVAL;
558         } else {
559                 if (sk->sk_state != TCP_ESTABLISHED)
560                         return -EDESTADDRREQ;
561                 daddr = inet->daddr;
562                 dport = inet->dport;
563                 /* Open fast path for connected socket.
564                    Route will not be used, if at least one option is set.
565                  */
566                 connected = 1;
567         }
568         ipc.addr = inet->saddr;
569
570         ipc.oif = sk->sk_bound_dev_if;
571         if (msg->msg_controllen) {
572                 err = ip_cmsg_send(msg, &ipc);
573                 if (err)
574                         return err;
575                 if (ipc.opt)
576                         free = 1;
577                 connected = 0;
578         }
579         if (!ipc.opt)
580                 ipc.opt = inet->opt;
581
582         saddr = ipc.addr;
583         ipc.addr = faddr = daddr;
584
585         if (ipc.opt && ipc.opt->srr) {
586                 if (!daddr)
587                         return -EINVAL;
588                 faddr = ipc.opt->faddr;
589                 connected = 0;
590         }
591         tos = RT_TOS(inet->tos);
592         if (sk->sk_localroute || (msg->msg_flags & MSG_DONTROUTE) || 
593             (ipc.opt && ipc.opt->is_strictroute)) {
594                 tos |= RTO_ONLINK;
595                 connected = 0;
596         }
597
598         if (MULTICAST(daddr)) {
599                 if (!ipc.oif)
600                         ipc.oif = inet->mc_index;
601                 if (!saddr)
602                         saddr = inet->mc_addr;
603                 connected = 0;
604         }
605
606         if (connected)
607                 rt = (struct rtable*)sk_dst_check(sk, 0);
608
609         if (rt == NULL) {
610                 struct flowi fl = { .oif = ipc.oif,
611                                     .nl_u = { .ip4_u =
612                                               { .daddr = faddr,
613                                                 .saddr = saddr,
614                                                 .tos = tos } },
615                                     .proto = IPPROTO_UDP,
616                                     .uli_u = { .ports =
617                                                { .sport = inet->sport,
618                                                  .dport = dport } } };
619                 struct nx_info *nxi = sk->sk_nx_info;
620
621                 if (nxi) {
622                         err = ip_find_src(nxi, &rt, &fl);
623                         if (err)
624                                 goto out;
625                         if (daddr == IPI_LOOPBACK && !vx_check(0, VX_ADMIN))
626                                 daddr = fl.fl4_dst = nxi->ipv4[0];
627                 }
628                 err = ip_route_output_flow(&rt, &fl, sk, !(msg->msg_flags&MSG_DONTWAIT));
629                 if (err)
630                         goto out;
631
632                 err = -EACCES;
633                 if ((rt->rt_flags & RTCF_BROADCAST) &&
634                     !sock_flag(sk, SOCK_BROADCAST))
635                         goto out;
636                 if (connected)
637                         sk_dst_set(sk, dst_clone(&rt->u.dst));
638         }
639
640         if (msg->msg_flags&MSG_CONFIRM)
641                 goto do_confirm;
642 back_from_confirm:
643
644         saddr = rt->rt_src;
645         if (!ipc.addr)
646                 daddr = ipc.addr = rt->rt_dst;
647
648         lock_sock(sk);
649         if (unlikely(up->pending)) {
650                 /* The socket is already corked while preparing it. */
651                 /* ... which is an evident application bug. --ANK */
652                 release_sock(sk);
653
654                 NETDEBUG(if (net_ratelimit()) printk(KERN_DEBUG "udp cork app bug 2\n"));
655                 err = -EINVAL;
656                 goto out;
657         }
658         /*
659          *      Now cork the socket to pend data.
660          */
661         inet->cork.fl.fl4_dst = daddr;
662         inet->cork.fl.fl_ip_dport = dport;
663         inet->cork.fl.fl4_src = saddr;
664         inet->cork.fl.fl_ip_sport = inet->sport;
665         up->pending = AF_INET;
666
667 do_append_data:
668         up->len += ulen;
669         err = ip_append_data(sk, ip_generic_getfrag, msg->msg_iov, ulen, 
670                         sizeof(struct udphdr), &ipc, rt, 
671                         corkreq ? msg->msg_flags|MSG_MORE : msg->msg_flags);
672         if (err)
673                 udp_flush_pending_frames(sk);
674         else if (!corkreq)
675                 err = udp_push_pending_frames(sk, up);
676         release_sock(sk);
677
678 out:
679         ip_rt_put(rt);
680         if (free)
681                 kfree(ipc.opt);
682         if (!err) {
683                 UDP_INC_STATS_USER(UDP_MIB_OUTDATAGRAMS);
684                 return len;
685         }
686         return err;
687
688 do_confirm:
689         dst_confirm(&rt->u.dst);
690         if (!(msg->msg_flags&MSG_PROBE) || len)
691                 goto back_from_confirm;
692         err = 0;
693         goto out;
694 }
695
696 static int udp_sendpage(struct sock *sk, struct page *page, int offset,
697                         size_t size, int flags)
698 {
699         struct udp_sock *up = udp_sk(sk);
700         int ret;
701
702         if (!up->pending) {
703                 struct msghdr msg = {   .msg_flags = flags|MSG_MORE };
704
705                 /* Call udp_sendmsg to specify destination address which
706                  * sendpage interface can't pass.
707                  * This will succeed only when the socket is connected.
708                  */
709                 ret = udp_sendmsg(NULL, sk, &msg, 0);
710                 if (ret < 0)
711                         return ret;
712         }
713
714         lock_sock(sk);
715
716         if (unlikely(!up->pending)) {
717                 release_sock(sk);
718
719                 NETDEBUG(if (net_ratelimit()) printk(KERN_DEBUG "udp cork app bug 3\n"));
720                 return -EINVAL;
721         }
722
723         ret = ip_append_page(sk, page, offset, size, flags);
724         if (ret == -EOPNOTSUPP) {
725                 release_sock(sk);
726                 return sock_no_sendpage(sk->sk_socket, page, offset,
727                                         size, flags);
728         }
729         if (ret < 0) {
730                 udp_flush_pending_frames(sk);
731                 goto out;
732         }
733
734         up->len += size;
735         if (!(up->corkflag || (flags&MSG_MORE)))
736                 ret = udp_push_pending_frames(sk, up);
737         if (!ret)
738                 ret = size;
739 out:
740         release_sock(sk);
741         return ret;
742 }
743
744 /*
745  *      IOCTL requests applicable to the UDP protocol
746  */
747  
748 int udp_ioctl(struct sock *sk, int cmd, unsigned long arg)
749 {
750         switch(cmd) 
751         {
752                 case SIOCOUTQ:
753                 {
754                         int amount = atomic_read(&sk->sk_wmem_alloc);
755                         return put_user(amount, (int __user *)arg);
756                 }
757
758                 case SIOCINQ:
759                 {
760                         struct sk_buff *skb;
761                         unsigned long amount;
762
763                         amount = 0;
764                         spin_lock_irq(&sk->sk_receive_queue.lock);
765                         skb = skb_peek(&sk->sk_receive_queue);
766                         if (skb != NULL) {
767                                 /*
768                                  * We will only return the amount
769                                  * of this packet since that is all
770                                  * that will be read.
771                                  */
772                                 amount = skb->len - sizeof(struct udphdr);
773                         }
774                         spin_unlock_irq(&sk->sk_receive_queue.lock);
775                         return put_user(amount, (int __user *)arg);
776                 }
777
778                 default:
779                         return -ENOIOCTLCMD;
780         }
781         return(0);
782 }
783
784 static __inline__ int __udp_checksum_complete(struct sk_buff *skb)
785 {
786         return (unsigned short)csum_fold(skb_checksum(skb, 0, skb->len, skb->csum));
787 }
788
789 static __inline__ int udp_checksum_complete(struct sk_buff *skb)
790 {
791         return skb->ip_summed != CHECKSUM_UNNECESSARY &&
792                 __udp_checksum_complete(skb);
793 }
794
795 /*
796  *      This should be easy, if there is something there we
797  *      return it, otherwise we block.
798  */
799
800 static int udp_recvmsg(struct kiocb *iocb, struct sock *sk, struct msghdr *msg,
801                        size_t len, int noblock, int flags, int *addr_len)
802 {
803         struct inet_sock *inet = inet_sk(sk);
804         struct sockaddr_in *sin = (struct sockaddr_in *)msg->msg_name;
805         struct sk_buff *skb;
806         int copied, err;
807
808         /*
809          *      Check any passed addresses
810          */
811         if (addr_len)
812                 *addr_len=sizeof(*sin);
813
814         if (flags & MSG_ERRQUEUE)
815                 return ip_recv_error(sk, msg, len);
816
817 try_again:
818         skb = skb_recv_datagram(sk, flags, noblock, &err);
819         if (!skb)
820                 goto out;
821   
822         copied = skb->len - sizeof(struct udphdr);
823         if (copied > len) {
824                 copied = len;
825                 msg->msg_flags |= MSG_TRUNC;
826         }
827
828         if (skb->ip_summed==CHECKSUM_UNNECESSARY) {
829                 err = skb_copy_datagram_iovec(skb, sizeof(struct udphdr), msg->msg_iov,
830                                               copied);
831         } else if (msg->msg_flags&MSG_TRUNC) {
832                 if (__udp_checksum_complete(skb))
833                         goto csum_copy_err;
834                 err = skb_copy_datagram_iovec(skb, sizeof(struct udphdr), msg->msg_iov,
835                                               copied);
836         } else {
837                 err = skb_copy_and_csum_datagram_iovec(skb, sizeof(struct udphdr), msg->msg_iov);
838
839                 if (err == -EINVAL)
840                         goto csum_copy_err;
841         }
842
843         if (err)
844                 goto out_free;
845
846         sock_recv_timestamp(msg, sk, skb);
847
848         /* Copy the address. */
849         if (sin)
850         {
851                 sin->sin_family = AF_INET;
852                 sin->sin_port = skb->h.uh->source;
853                 sin->sin_addr.s_addr = skb->nh.iph->saddr;
854                 memset(sin->sin_zero, 0, sizeof(sin->sin_zero));
855         }
856         if (inet->cmsg_flags)
857                 ip_cmsg_recv(msg, skb);
858
859         err = copied;
860         if (flags & MSG_TRUNC)
861                 err = skb->len - sizeof(struct udphdr);
862   
863 out_free:
864         skb_free_datagram(sk, skb);
865 out:
866         return err;
867
868 csum_copy_err:
869         UDP_INC_STATS_BH(UDP_MIB_INERRORS);
870
871         /* Clear queue. */
872         if (flags&MSG_PEEK) {
873                 int clear = 0;
874                 spin_lock_irq(&sk->sk_receive_queue.lock);
875                 if (skb == skb_peek(&sk->sk_receive_queue)) {
876                         __skb_unlink(skb, &sk->sk_receive_queue);
877                         clear = 1;
878                 }
879                 spin_unlock_irq(&sk->sk_receive_queue.lock);
880                 if (clear)
881                         kfree_skb(skb);
882         }
883
884         skb_free_datagram(sk, skb);
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
982         /* Now we can update and verify the packet length... */
983         iph = skb->nh.iph;
984         iphlen = iph->ihl << 2;
985         iph->tot_len = htons(ntohs(iph->tot_len) - len);
986         if (skb->len < iphlen + len) {
987                 /* packet is too small!?! */
988                 return 0;
989         }
990
991         /* pull the data buffer up to the ESP header and set the
992          * transport header to point to ESP.  Keep UDP on the stack
993          * for later.
994          */
995         skb->h.raw = skb_pull(skb, len);
996
997         /* modify the protocol (it's ESP!) */
998         iph->protocol = IPPROTO_ESP;
999
1000         /* and let the caller know to send this into the ESP processor... */
1001         return -1;
1002 #endif
1003 }
1004
1005 /* returns:
1006  *  -1: error
1007  *   0: success
1008  *  >0: "udp encap" protocol resubmission
1009  *
1010  * Note that in the success and error cases, the skb is assumed to
1011  * have either been requeued or freed.
1012  */
1013 static int udp_queue_rcv_skb(struct sock * sk, struct sk_buff *skb)
1014 {
1015         struct udp_sock *up = udp_sk(sk);
1016
1017         /*
1018          *      Charge it to the socket, dropping if the queue is full.
1019          */
1020         if (!xfrm4_policy_check(sk, XFRM_POLICY_IN, skb)) {
1021                 kfree_skb(skb);
1022                 return -1;
1023         }
1024
1025         if (up->encap_type) {
1026                 /*
1027                  * This is an encapsulation socket, so let's see if this is
1028                  * an encapsulated packet.
1029                  * If it's a keepalive packet, then just eat it.
1030                  * If it's an encapsulateed packet, then pass it to the
1031                  * IPsec xfrm input and return the response
1032                  * appropriately.  Otherwise, just fall through and
1033                  * pass this up the UDP socket.
1034                  */
1035                 int ret;
1036
1037                 ret = udp_encap_rcv(sk, skb);
1038                 if (ret == 0) {
1039                         /* Eat the packet .. */
1040                         kfree_skb(skb);
1041                         return 0;
1042                 }
1043                 if (ret < 0) {
1044                         /* process the ESP packet */
1045                         ret = xfrm4_rcv_encap(skb, up->encap_type);
1046                         UDP_INC_STATS_BH(UDP_MIB_INDATAGRAMS);
1047                         return -ret;
1048                 }
1049                 /* FALLTHROUGH -- it's a UDP Packet */
1050         }
1051
1052         if (sk->sk_filter && skb->ip_summed != CHECKSUM_UNNECESSARY) {
1053                 if (__udp_checksum_complete(skb)) {
1054                         UDP_INC_STATS_BH(UDP_MIB_INERRORS);
1055                         kfree_skb(skb);
1056                         return -1;
1057                 }
1058                 skb->ip_summed = CHECKSUM_UNNECESSARY;
1059         }
1060
1061         if (sock_queue_rcv_skb(sk,skb)<0) {
1062                 UDP_INC_STATS_BH(UDP_MIB_INERRORS);
1063                 kfree_skb(skb);
1064                 return -1;
1065         }
1066         UDP_INC_STATS_BH(UDP_MIB_INDATAGRAMS);
1067         return 0;
1068 }
1069
1070 /*
1071  *      Multicasts and broadcasts go to each listener.
1072  *
1073  *      Note: called only from the BH handler context,
1074  *      so we don't need to lock the hashes.
1075  */
1076 static int udp_v4_mcast_deliver(struct sk_buff *skb, struct udphdr *uh,
1077                                  u32 saddr, u32 daddr)
1078 {
1079         struct sock *sk;
1080         int dif;
1081
1082         read_lock(&udp_hash_lock);
1083         sk = sk_head(&udp_hash[ntohs(uh->dest) & (UDP_HTABLE_SIZE - 1)]);
1084         dif = skb->dev->ifindex;
1085         sk = udp_v4_mcast_next(sk, uh->dest, daddr, uh->source, saddr, dif);
1086         if (sk) {
1087                 struct sock *sknext = NULL;
1088
1089                 do {
1090                         struct sk_buff *skb1 = skb;
1091
1092                         sknext = udp_v4_mcast_next(sk_next(sk), uh->dest, daddr,
1093                                                    uh->source, saddr, dif);
1094                         if(sknext)
1095                                 skb1 = skb_clone(skb, GFP_ATOMIC);
1096
1097                         if(skb1) {
1098                                 int ret = udp_queue_rcv_skb(sk, skb1);
1099                                 if (ret > 0)
1100                                         /* we should probably re-process instead
1101                                          * of dropping packets here. */
1102                                         kfree_skb(skb1);
1103                         }
1104                         sk = sknext;
1105                 } while(sknext);
1106         } else
1107                 kfree_skb(skb);
1108         read_unlock(&udp_hash_lock);
1109         return 0;
1110 }
1111
1112 /* Initialize UDP checksum. If exited with zero value (success),
1113  * CHECKSUM_UNNECESSARY means, that no more checks are required.
1114  * Otherwise, csum completion requires chacksumming packet body,
1115  * including udp header and folding it to skb->csum.
1116  */
1117 static int udp_checksum_init(struct sk_buff *skb, struct udphdr *uh,
1118                              unsigned short ulen, u32 saddr, u32 daddr)
1119 {
1120         if (uh->check == 0) {
1121                 skb->ip_summed = CHECKSUM_UNNECESSARY;
1122         } else if (skb->ip_summed == CHECKSUM_HW) {
1123                 skb->ip_summed = CHECKSUM_UNNECESSARY;
1124                 if (!udp_check(uh, ulen, saddr, daddr, skb->csum))
1125                         return 0;
1126                 NETDEBUG(if (net_ratelimit()) printk(KERN_DEBUG "udp v4 hw csum failure.\n"));
1127                 skb->ip_summed = CHECKSUM_NONE;
1128         }
1129         if (skb->ip_summed != CHECKSUM_UNNECESSARY)
1130                 skb->csum = csum_tcpudp_nofold(saddr, daddr, ulen, IPPROTO_UDP, 0);
1131         /* Probably, we should checksum udp header (it should be in cache
1132          * in any case) and data in tiny packets (< rx copybreak).
1133          */
1134         return 0;
1135 }
1136
1137 /*
1138  *      All we need to do is get the socket, and then do a checksum. 
1139  */
1140  
1141 int udp_rcv(struct sk_buff *skb)
1142 {
1143         struct sock *sk;
1144         struct udphdr *uh;
1145         unsigned short ulen;
1146         struct rtable *rt = (struct rtable*)skb->dst;
1147         u32 saddr = skb->nh.iph->saddr;
1148         u32 daddr = skb->nh.iph->daddr;
1149         int len = skb->len;
1150
1151         /*
1152          *      Validate the packet and the UDP length.
1153          */
1154         if (!pskb_may_pull(skb, sizeof(struct udphdr)))
1155                 goto no_header;
1156
1157         uh = skb->h.uh;
1158
1159         ulen = ntohs(uh->len);
1160
1161         if (ulen > len || ulen < sizeof(*uh))
1162                 goto short_packet;
1163
1164         if (pskb_trim(skb, ulen))
1165                 goto short_packet;
1166
1167         if (udp_checksum_init(skb, uh, ulen, saddr, daddr) < 0)
1168                 goto csum_error;
1169
1170         if(rt->rt_flags & (RTCF_BROADCAST|RTCF_MULTICAST))
1171                 return udp_v4_mcast_deliver(skb, uh, saddr, daddr);
1172
1173         sk = udp_v4_lookup(saddr, uh->source, daddr, uh->dest, skb->dev->ifindex);
1174
1175         if (sk != NULL) {
1176                 int ret = udp_queue_rcv_skb(sk, skb);
1177                 sock_put(sk);
1178
1179                 /* a return value > 0 means to resubmit the input, but
1180                  * it it wants the return to be -protocol, or 0
1181                  */
1182                 if (ret > 0)
1183                         return -ret;
1184                 return 0;
1185         }
1186
1187         if (!xfrm4_policy_check(NULL, XFRM_POLICY_IN, skb))
1188                 goto drop;
1189
1190         /* No socket. Drop packet silently, if checksum is wrong */
1191         if (udp_checksum_complete(skb))
1192                 goto csum_error;
1193
1194         UDP_INC_STATS_BH(UDP_MIB_NOPORTS);
1195         icmp_send(skb, ICMP_DEST_UNREACH, ICMP_PORT_UNREACH, 0);
1196
1197         /*
1198          * Hmm.  We got an UDP packet to a port to which we
1199          * don't wanna listen.  Ignore it.
1200          */
1201         kfree_skb(skb);
1202         return(0);
1203
1204 short_packet:
1205         NETDEBUG(if (net_ratelimit())
1206                 printk(KERN_DEBUG "UDP: short packet: From %u.%u.%u.%u:%u %d/%d to %u.%u.%u.%u:%u\n",
1207                         NIPQUAD(saddr),
1208                         ntohs(uh->source),
1209                         ulen,
1210                         len,
1211                         NIPQUAD(daddr),
1212                         ntohs(uh->dest)));
1213 no_header:
1214         UDP_INC_STATS_BH(UDP_MIB_INERRORS);
1215         kfree_skb(skb);
1216         return(0);
1217
1218 csum_error:
1219         /* 
1220          * RFC1122: OK.  Discards the bad packet silently (as far as 
1221          * the network is concerned, anyway) as per 4.1.3.4 (MUST). 
1222          */
1223         NETDEBUG(if (net_ratelimit())
1224                  printk(KERN_DEBUG "UDP: bad checksum. From %d.%d.%d.%d:%d to %d.%d.%d.%d:%d ulen %d\n",
1225                         NIPQUAD(saddr),
1226                         ntohs(uh->source),
1227                         NIPQUAD(daddr),
1228                         ntohs(uh->dest),
1229                         ulen));
1230 drop:
1231         UDP_INC_STATS_BH(UDP_MIB_INERRORS);
1232         kfree_skb(skb);
1233         return(0);
1234 }
1235
1236 static int udp_destroy_sock(struct sock *sk)
1237 {
1238         lock_sock(sk);
1239         udp_flush_pending_frames(sk);
1240         release_sock(sk);
1241         return 0;
1242 }
1243
1244 /*
1245  *      Socket option code for UDP
1246  */
1247 static int udp_setsockopt(struct sock *sk, int level, int optname, 
1248                           char __user *optval, int optlen)
1249 {
1250         struct udp_sock *up = udp_sk(sk);
1251         int val;
1252         int err = 0;
1253
1254         if (level != SOL_UDP)
1255                 return ip_setsockopt(sk, level, optname, optval, optlen);
1256
1257         if(optlen<sizeof(int))
1258                 return -EINVAL;
1259
1260         if (get_user(val, (int __user *)optval))
1261                 return -EFAULT;
1262
1263         switch(optname) {
1264         case UDP_CORK:
1265                 if (val != 0) {
1266                         up->corkflag = 1;
1267                 } else {
1268                         up->corkflag = 0;
1269                         lock_sock(sk);
1270                         udp_push_pending_frames(sk, up);
1271                         release_sock(sk);
1272                 }
1273                 break;
1274                 
1275         case UDP_ENCAP:
1276                 switch (val) {
1277                 case 0:
1278                 case UDP_ENCAP_ESPINUDP:
1279                 case UDP_ENCAP_ESPINUDP_NON_IKE:
1280                         up->encap_type = val;
1281                         break;
1282                 default:
1283                         err = -ENOPROTOOPT;
1284                         break;
1285                 }
1286                 break;
1287
1288         default:
1289                 err = -ENOPROTOOPT;
1290                 break;
1291         };
1292
1293         return err;
1294 }
1295
1296 static int udp_getsockopt(struct sock *sk, int level, int optname, 
1297                           char __user *optval, int __user *optlen)
1298 {
1299         struct udp_sock *up = udp_sk(sk);
1300         int val, len;
1301
1302         if (level != SOL_UDP)
1303                 return ip_getsockopt(sk, level, optname, optval, optlen);
1304
1305         if(get_user(len,optlen))
1306                 return -EFAULT;
1307
1308         len = min_t(unsigned int, len, sizeof(int));
1309         
1310         if(len < 0)
1311                 return -EINVAL;
1312
1313         switch(optname) {
1314         case UDP_CORK:
1315                 val = up->corkflag;
1316                 break;
1317
1318         case UDP_ENCAP:
1319                 val = up->encap_type;
1320                 break;
1321
1322         default:
1323                 return -ENOPROTOOPT;
1324         };
1325
1326         if(put_user(len, optlen))
1327                 return -EFAULT;
1328         if(copy_to_user(optval, &val,len))
1329                 return -EFAULT;
1330         return 0;
1331 }
1332
1333 /**
1334  *      udp_poll - wait for a UDP event.
1335  *      @file - file struct
1336  *      @sock - socket
1337  *      @wait - poll table
1338  *
1339  *      This is same as datagram poll, except for the special case of 
1340  *      blocking sockets. If application is using a blocking fd
1341  *      and a packet with checksum error is in the queue;
1342  *      then it could get return from select indicating data available
1343  *      but then block when reading it. Add special case code
1344  *      to work around these arguably broken applications.
1345  */
1346 unsigned int udp_poll(struct file *file, struct socket *sock, poll_table *wait)
1347 {
1348         unsigned int mask = datagram_poll(file, sock, wait);
1349         struct sock *sk = sock->sk;
1350         
1351         /* Check for false positives due to checksum errors */
1352         if ( (mask & POLLRDNORM) &&
1353              !(file->f_flags & O_NONBLOCK) &&
1354              !(sk->sk_shutdown & RCV_SHUTDOWN)){
1355                 struct sk_buff_head *rcvq = &sk->sk_receive_queue;
1356                 struct sk_buff *skb;
1357
1358                 spin_lock_irq(&rcvq->lock);
1359                 while ((skb = skb_peek(rcvq)) != NULL) {
1360                         if (udp_checksum_complete(skb)) {
1361                                 UDP_INC_STATS_BH(UDP_MIB_INERRORS);
1362                                 __skb_unlink(skb, rcvq);
1363                                 kfree_skb(skb);
1364                         } else {
1365                                 skb->ip_summed = CHECKSUM_UNNECESSARY;
1366                                 break;
1367                         }
1368                 }
1369                 spin_unlock_irq(&rcvq->lock);
1370
1371                 /* nothing to see, move along */
1372                 if (skb == NULL)
1373                         mask &= ~(POLLIN | POLLRDNORM);
1374         }
1375
1376         return mask;
1377         
1378 }
1379
1380 struct proto udp_prot = {
1381         .name =         "UDP",
1382         .owner =        THIS_MODULE,
1383         .close =        udp_close,
1384         .connect =      ip4_datagram_connect,
1385         .disconnect =   udp_disconnect,
1386         .ioctl =        udp_ioctl,
1387         .destroy =      udp_destroy_sock,
1388         .setsockopt =   udp_setsockopt,
1389         .getsockopt =   udp_getsockopt,
1390         .sendmsg =      udp_sendmsg,
1391         .recvmsg =      udp_recvmsg,
1392         .sendpage =     udp_sendpage,
1393         .backlog_rcv =  udp_queue_rcv_skb,
1394         .hash =         udp_v4_hash,
1395         .unhash =       udp_v4_unhash,
1396         .get_port =     udp_v4_get_port,
1397         .slab_obj_size = sizeof(struct udp_sock),
1398 };
1399
1400 /* ------------------------------------------------------------------------ */
1401 #ifdef CONFIG_PROC_FS
1402
1403 static struct sock *udp_get_first(struct seq_file *seq)
1404 {
1405         struct sock *sk;
1406         struct udp_iter_state *state = seq->private;
1407
1408         for (state->bucket = 0; state->bucket < UDP_HTABLE_SIZE; ++state->bucket) {
1409                 struct hlist_node *node;
1410
1411                 sk_for_each(sk, node, &udp_hash[state->bucket]) {
1412                         if (sk->sk_family == state->family &&
1413                                 vx_check(sk->sk_xid, VX_IDENT|VX_WATCH))
1414                                 goto found;
1415                 }
1416         }
1417         sk = NULL;
1418 found:
1419         return sk;
1420 }
1421
1422 static struct sock *udp_get_next(struct seq_file *seq, struct sock *sk)
1423 {
1424         struct udp_iter_state *state = seq->private;
1425
1426         do {
1427                 sk = sk_next(sk);
1428 try_again:
1429                 ;
1430         } while (sk && (sk->sk_family != state->family ||
1431                 !vx_check(sk->sk_xid, VX_IDENT|VX_WATCH)));
1432
1433         if (!sk && ++state->bucket < UDP_HTABLE_SIZE) {
1434                 sk = sk_head(&udp_hash[state->bucket]);
1435                 goto try_again;
1436         }
1437         return sk;
1438 }
1439
1440 static struct sock *udp_get_idx(struct seq_file *seq, loff_t pos)
1441 {
1442         struct sock *sk = udp_get_first(seq);
1443
1444         if (sk)
1445                 while(pos && (sk = udp_get_next(seq, sk)) != NULL)
1446                         --pos;
1447         return pos ? NULL : sk;
1448 }
1449
1450 static void *udp_seq_start(struct seq_file *seq, loff_t *pos)
1451 {
1452         read_lock(&udp_hash_lock);
1453         return *pos ? udp_get_idx(seq, *pos-1) : (void *)1;
1454 }
1455
1456 static void *udp_seq_next(struct seq_file *seq, void *v, loff_t *pos)
1457 {
1458         struct sock *sk;
1459
1460         if (v == (void *)1)
1461                 sk = udp_get_idx(seq, 0);
1462         else
1463                 sk = udp_get_next(seq, v);
1464
1465         ++*pos;
1466         return sk;
1467 }
1468
1469 static void udp_seq_stop(struct seq_file *seq, void *v)
1470 {
1471         read_unlock(&udp_hash_lock);
1472 }
1473
1474 static int udp_seq_open(struct inode *inode, struct file *file)
1475 {
1476         struct udp_seq_afinfo *afinfo = PDE(inode)->data;
1477         struct seq_file *seq;
1478         int rc = -ENOMEM;
1479         struct udp_iter_state *s = kmalloc(sizeof(*s), GFP_KERNEL);
1480
1481         if (!s)
1482                 goto out;
1483         memset(s, 0, sizeof(*s));
1484         s->family               = afinfo->family;
1485         s->seq_ops.start        = udp_seq_start;
1486         s->seq_ops.next         = udp_seq_next;
1487         s->seq_ops.show         = afinfo->seq_show;
1488         s->seq_ops.stop         = udp_seq_stop;
1489
1490         rc = seq_open(file, &s->seq_ops);
1491         if (rc)
1492                 goto out_kfree;
1493
1494         seq          = file->private_data;
1495         seq->private = s;
1496 out:
1497         return rc;
1498 out_kfree:
1499         kfree(s);
1500         goto out;
1501 }
1502
1503 /* ------------------------------------------------------------------------ */
1504 int udp_proc_register(struct udp_seq_afinfo *afinfo)
1505 {
1506         struct proc_dir_entry *p;
1507         int rc = 0;
1508
1509         if (!afinfo)
1510                 return -EINVAL;
1511         afinfo->seq_fops->owner         = afinfo->owner;
1512         afinfo->seq_fops->open          = udp_seq_open;
1513         afinfo->seq_fops->read          = seq_read;
1514         afinfo->seq_fops->llseek        = seq_lseek;
1515         afinfo->seq_fops->release       = seq_release_private;
1516
1517         p = proc_net_fops_create(afinfo->name, S_IRUGO, afinfo->seq_fops);
1518         if (p)
1519                 p->data = afinfo;
1520         else
1521                 rc = -ENOMEM;
1522         return rc;
1523 }
1524
1525 void udp_proc_unregister(struct udp_seq_afinfo *afinfo)
1526 {
1527         if (!afinfo)
1528                 return;
1529         proc_net_remove(afinfo->name);
1530         memset(afinfo->seq_fops, 0, sizeof(*afinfo->seq_fops));
1531 }
1532
1533 /* ------------------------------------------------------------------------ */
1534 static void udp4_format_sock(struct sock *sp, char *tmpbuf, int bucket)
1535 {
1536         struct inet_sock *inet = inet_sk(sp);
1537         unsigned int dest = inet->daddr;
1538         unsigned int src  = inet->rcv_saddr;
1539         __u16 destp       = ntohs(inet->dport);
1540         __u16 srcp        = ntohs(inet->sport);
1541
1542         sprintf(tmpbuf, "%4d: %08X:%04X %08X:%04X"
1543                 " %02X %08X:%08X %02X:%08lX %08X %5d %8d %lu %d %p",
1544                 bucket, src, srcp, dest, destp, sp->sk_state, 
1545                 atomic_read(&sp->sk_wmem_alloc),
1546                 atomic_read(&sp->sk_rmem_alloc),
1547                 0, 0L, 0, sock_i_uid(sp), 0, sock_i_ino(sp),
1548                 atomic_read(&sp->sk_refcnt), sp);
1549 }
1550
1551 static int udp4_seq_show(struct seq_file *seq, void *v)
1552 {
1553         if (v == SEQ_START_TOKEN)
1554                 seq_printf(seq, "%-127s\n",
1555                            "  sl  local_address rem_address   st tx_queue "
1556                            "rx_queue tr tm->when retrnsmt   uid  timeout "
1557                            "inode");
1558         else {
1559                 char tmpbuf[129];
1560                 struct udp_iter_state *state = seq->private;
1561
1562                 udp4_format_sock(v, tmpbuf, state->bucket);
1563                 seq_printf(seq, "%-127s\n", tmpbuf);
1564         }
1565         return 0;
1566 }
1567
1568 /* ------------------------------------------------------------------------ */
1569 static struct file_operations udp4_seq_fops;
1570 static struct udp_seq_afinfo udp4_seq_afinfo = {
1571         .owner          = THIS_MODULE,
1572         .name           = "udp",
1573         .family         = AF_INET,
1574         .seq_show       = udp4_seq_show,
1575         .seq_fops       = &udp4_seq_fops,
1576 };
1577
1578 int __init udp4_proc_init(void)
1579 {
1580         return udp_proc_register(&udp4_seq_afinfo);
1581 }
1582
1583 void udp4_proc_exit(void)
1584 {
1585         udp_proc_unregister(&udp4_seq_afinfo);
1586 }
1587 #endif /* CONFIG_PROC_FS */
1588
1589 EXPORT_SYMBOL(udp_disconnect);
1590 EXPORT_SYMBOL(udp_hash);
1591 EXPORT_SYMBOL(udp_hash_lock);
1592 EXPORT_SYMBOL(udp_ioctl);
1593 EXPORT_SYMBOL(udp_port_rover);
1594 EXPORT_SYMBOL(udp_prot);
1595 EXPORT_SYMBOL(udp_sendmsg);
1596 EXPORT_SYMBOL(udp_poll);
1597
1598 #ifdef CONFIG_PROC_FS
1599 EXPORT_SYMBOL(udp_proc_register);
1600 EXPORT_SYMBOL(udp_proc_unregister);
1601 #endif