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