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