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