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