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