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