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