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