This commit was manufactured by cvs2svn to create tag
[linux-2.6.git] / net / ipv4 / af_inet.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  *              PF_INET protocol family socket handler.
7  *
8  * Version:     $Id: af_inet.c,v 1.137 2002/02/01 22:01:03 davem Exp $
9  *
10  * Authors:     Ross Biro, <bir7@leland.Stanford.Edu>
11  *              Fred N. van Kempen, <waltje@uWalt.NL.Mugnet.ORG>
12  *              Florian La Roche, <flla@stud.uni-sb.de>
13  *              Alan Cox, <A.Cox@swansea.ac.uk>
14  *
15  * Changes (see also sock.c)
16  *
17  *              piggy,
18  *              Karl Knutson    :       Socket protocol table
19  *              A.N.Kuznetsov   :       Socket death error in accept().
20  *              John Richardson :       Fix non blocking error in connect()
21  *                                      so sockets that fail to connect
22  *                                      don't return -EINPROGRESS.
23  *              Alan Cox        :       Asynchronous I/O support
24  *              Alan Cox        :       Keep correct socket pointer on sock
25  *                                      structures
26  *                                      when accept() ed
27  *              Alan Cox        :       Semantics of SO_LINGER aren't state
28  *                                      moved to close when you look carefully.
29  *                                      With this fixed and the accept bug fixed
30  *                                      some RPC stuff seems happier.
31  *              Niibe Yutaka    :       4.4BSD style write async I/O
32  *              Alan Cox,
33  *              Tony Gale       :       Fixed reuse semantics.
34  *              Alan Cox        :       bind() shouldn't abort existing but dead
35  *                                      sockets. Stops FTP netin:.. I hope.
36  *              Alan Cox        :       bind() works correctly for RAW sockets.
37  *                                      Note that FreeBSD at least was broken
38  *                                      in this respect so be careful with
39  *                                      compatibility tests...
40  *              Alan Cox        :       routing cache support
41  *              Alan Cox        :       memzero the socket structure for
42  *                                      compactness.
43  *              Matt Day        :       nonblock connect error handler
44  *              Alan Cox        :       Allow large numbers of pending sockets
45  *                                      (eg for big web sites), but only if
46  *                                      specifically application requested.
47  *              Alan Cox        :       New buffering throughout IP. Used
48  *                                      dumbly.
49  *              Alan Cox        :       New buffering now used smartly.
50  *              Alan Cox        :       BSD rather than common sense
51  *                                      interpretation of listen.
52  *              Germano Caronni :       Assorted small races.
53  *              Alan Cox        :       sendmsg/recvmsg basic support.
54  *              Alan Cox        :       Only sendmsg/recvmsg now supported.
55  *              Alan Cox        :       Locked down bind (see security list).
56  *              Alan Cox        :       Loosened bind a little.
57  *              Mike McLagan    :       ADD/DEL DLCI Ioctls
58  *      Willy Konynenberg       :       Transparent proxying support.
59  *              David S. Miller :       New socket lookup architecture.
60  *                                      Some other random speedups.
61  *              Cyrus Durgin    :       Cleaned up file for kmod hacks.
62  *              Andi Kleen      :       Fix inet_stream_connect TCP race.
63  *
64  *              This program is free software; you can redistribute it and/or
65  *              modify it under the terms of the GNU General Public License
66  *              as published by the Free Software Foundation; either version
67  *              2 of the License, or (at your option) any later version.
68  */
69
70 #include <linux/config.h>
71 #include <linux/errno.h>
72 #include <linux/types.h>
73 #include <linux/socket.h>
74 #include <linux/in.h>
75 #include <linux/kernel.h>
76 #include <linux/major.h>
77 #include <linux/module.h>
78 #include <linux/sched.h>
79 #include <linux/timer.h>
80 #include <linux/string.h>
81 #include <linux/sockios.h>
82 #include <linux/net.h>
83 #include <linux/fcntl.h>
84 #include <linux/mm.h>
85 #include <linux/interrupt.h>
86 #include <linux/stat.h>
87 #include <linux/init.h>
88 #include <linux/poll.h>
89 #include <linux/netfilter_ipv4.h>
90
91 #include <asm/uaccess.h>
92 #include <asm/system.h>
93
94 #include <linux/smp_lock.h>
95 #include <linux/inet.h>
96 #include <linux/igmp.h>
97 #include <linux/netdevice.h>
98 #include <net/ip.h>
99 #include <net/protocol.h>
100 #include <net/arp.h>
101 #include <net/route.h>
102 #include <net/ip_fib.h>
103 #include <net/tcp.h>
104 #include <net/udp.h>
105 #include <linux/skbuff.h>
106 #include <net/sock.h>
107 #include <net/raw.h>
108 #include <net/icmp.h>
109 #include <net/ipip.h>
110 #include <net/inet_common.h>
111 #include <net/xfrm.h>
112 #ifdef CONFIG_IP_MROUTE
113 #include <linux/mroute.h>
114 #endif
115
116 DEFINE_SNMP_STAT(struct linux_mib, net_statistics);
117
118 #ifdef INET_REFCNT_DEBUG
119 atomic_t inet_sock_nr;
120 #endif
121
122 extern void ip_mc_drop_socket(struct sock *sk);
123
124 /* Per protocol sock slabcache */
125 kmem_cache_t *tcp_sk_cachep;
126 static kmem_cache_t *udp_sk_cachep;
127 static kmem_cache_t *raw4_sk_cachep;
128
129 /* The inetsw table contains everything that inet_create needs to
130  * build a new socket.
131  */
132 static struct list_head inetsw[SOCK_MAX];
133 static spinlock_t inetsw_lock = SPIN_LOCK_UNLOCKED;
134
135 /* New destruction routine */
136
137 void inet_sock_destruct(struct sock *sk)
138 {
139         struct inet_opt *inet = inet_sk(sk);
140
141         __skb_queue_purge(&sk->sk_receive_queue);
142         __skb_queue_purge(&sk->sk_error_queue);
143
144         if (sk->sk_type == SOCK_STREAM && sk->sk_state != TCP_CLOSE) {
145                 printk("Attempt to release TCP socket in state %d %p\n",
146                        sk->sk_state, sk);
147                 return;
148         }
149         if (!sock_flag(sk, SOCK_DEAD)) {
150                 printk("Attempt to release alive inet socket %p\n", sk);
151                 return;
152         }
153
154         BUG_TRAP(!atomic_read(&sk->sk_rmem_alloc));
155         BUG_TRAP(!atomic_read(&sk->sk_wmem_alloc));
156         BUG_TRAP(!sk->sk_wmem_queued);
157         BUG_TRAP(!sk->sk_forward_alloc);
158
159         if (inet->opt)
160                 kfree(inet->opt);
161         
162         clr_vx_info(&sk->sk_vx_info);
163         sk->sk_xid = -1;
164         clr_nx_info(&sk->sk_nx_info);
165         sk->sk_nid = -1;
166
167         dst_release(sk->sk_dst_cache);
168 #ifdef INET_REFCNT_DEBUG
169         atomic_dec(&inet_sock_nr);
170         printk(KERN_DEBUG "INET socket %p released, %d are still alive\n",
171                sk, atomic_read(&inet_sock_nr));
172 #endif
173 }
174
175 /*
176  *      The routines beyond this point handle the behaviour of an AF_INET
177  *      socket object. Mostly it punts to the subprotocols of IP to do
178  *      the work.
179  */
180
181 /*
182  *      Automatically bind an unbound socket.
183  */
184
185 static int inet_autobind(struct sock *sk)
186 {
187         struct inet_opt *inet;
188         /* We may need to bind the socket. */
189         lock_sock(sk);
190         inet = inet_sk(sk);
191         if (!inet->num) {
192                 if (sk->sk_prot->get_port(sk, 0)) {
193                         release_sock(sk);
194                         return -EAGAIN;
195                 }
196                 inet->sport = htons(inet->num);
197         }
198         release_sock(sk);
199         return 0;
200 }
201
202 /*
203  *      Move a socket into listening state.
204  */
205 int inet_listen(struct socket *sock, int backlog)
206 {
207         struct sock *sk = sock->sk;
208         unsigned char old_state;
209         int err;
210
211         lock_sock(sk);
212
213         err = -EINVAL;
214         if (sock->state != SS_UNCONNECTED || sock->type != SOCK_STREAM)
215                 goto out;
216
217         old_state = sk->sk_state;
218         if (!((1 << old_state) & (TCPF_CLOSE | TCPF_LISTEN)))
219                 goto out;
220
221         /* Really, if the socket is already in listen state
222          * we can only allow the backlog to be adjusted.
223          */
224         if (old_state != TCP_LISTEN) {
225                 err = tcp_listen_start(sk);
226                 if (err)
227                         goto out;
228         }
229         sk->sk_max_ack_backlog = backlog;
230         err = 0;
231
232 out:
233         release_sock(sk);
234         return err;
235 }
236
237 static __inline__ kmem_cache_t *inet_sk_slab(int protocol)
238 {
239         kmem_cache_t* rc = tcp_sk_cachep;
240
241         if (protocol == IPPROTO_UDP)
242                 rc = udp_sk_cachep;
243         else if (protocol == IPPROTO_RAW)
244                 rc = raw4_sk_cachep;
245         return rc;
246 }
247
248 static __inline__ int inet_sk_size(int protocol)
249 {
250         int rc = sizeof(struct tcp_sock);
251
252         if (protocol == IPPROTO_UDP)
253                 rc = sizeof(struct udp_sock);
254         else if (protocol == IPPROTO_RAW)
255                 rc = sizeof(struct raw_sock);
256         return rc;
257 }
258
259 /*
260  *      Create an inet socket.
261  */
262
263 static int inet_create(struct socket *sock, int protocol)
264 {
265         struct sock *sk;
266         struct list_head *p;
267         struct inet_protosw *answer;
268         struct inet_opt *inet;
269         int err = -ENOBUFS;
270
271         sock->state = SS_UNCONNECTED;
272         sk = sk_alloc(PF_INET, GFP_KERNEL, inet_sk_size(protocol),
273                       inet_sk_slab(protocol));
274         if (!sk)
275                 goto out;
276
277         /* Look for the requested type/protocol pair. */
278         answer = NULL;
279         rcu_read_lock();
280         list_for_each_rcu(p, &inetsw[sock->type]) {
281                 answer = list_entry(p, struct inet_protosw, list);
282
283                 /* Check the non-wild match. */
284                 if (protocol == answer->protocol) {
285                         if (protocol != IPPROTO_IP)
286                                 break;
287                 } else {
288                         /* Check for the two wild cases. */
289                         if (IPPROTO_IP == protocol) {
290                                 protocol = answer->protocol;
291                                 break;
292                         }
293                         if (IPPROTO_IP == answer->protocol)
294                                 break;
295                 }
296                 answer = NULL;
297         }
298
299         err = -ESOCKTNOSUPPORT;
300         if (!answer)
301                 goto out_sk_free;
302         err = -EPERM;
303         if ((protocol == IPPROTO_ICMP) && vx_ccaps(VXC_RAW_ICMP))
304                 goto override;
305         if (answer->capability > 0 && !capable(answer->capability))
306                 goto out_sk_free;
307 override:
308         err = -EPROTONOSUPPORT;
309         if (!protocol)
310                 goto out_sk_free;
311         err = 0;
312         sock->ops = answer->ops;
313         sk->sk_prot = answer->prot;
314         sk->sk_no_check = answer->no_check;
315         if (INET_PROTOSW_REUSE & answer->flags)
316                 sk->sk_reuse = 1;
317         rcu_read_unlock();
318
319         inet = inet_sk(sk);
320
321         if (SOCK_RAW == sock->type) {
322                 inet->num = protocol;
323                 if (IPPROTO_RAW == protocol)
324                         inet->hdrincl = 1;
325         }
326
327         if (ipv4_config.no_pmtu_disc)
328                 inet->pmtudisc = IP_PMTUDISC_DONT;
329         else
330                 inet->pmtudisc = IP_PMTUDISC_WANT;
331
332         inet->id = 0;
333
334         sock_init_data(sock, sk);
335         sk_set_owner(sk, THIS_MODULE);
336
337         sk->sk_destruct    = inet_sock_destruct;
338         sk->sk_zapped      = 0;
339         sk->sk_family      = PF_INET;
340         sk->sk_protocol    = protocol;
341         sk->sk_backlog_rcv = sk->sk_prot->backlog_rcv;
342         
343         set_vx_info(&sk->sk_vx_info, current->vx_info);
344         sk->sk_xid = vx_current_xid();
345         set_nx_info(&sk->sk_nx_info, current->nx_info);
346         sk->sk_nid = nx_current_nid();
347
348         inet->uc_ttl    = -1;
349         inet->mc_loop   = 1;
350         inet->mc_ttl    = 1;
351         inet->mc_index  = 0;
352         inet->mc_list   = NULL;
353
354 #ifdef INET_REFCNT_DEBUG
355         atomic_inc(&inet_sock_nr);
356 #endif
357
358         if (inet->num) {
359                 /* It assumes that any protocol which allows
360                  * the user to assign a number at socket
361                  * creation time automatically
362                  * shares.
363                  */
364                 inet->sport = htons(inet->num);
365                 /* Add to protocol hash chains. */
366                 sk->sk_prot->hash(sk);
367         }
368
369         if (sk->sk_prot->init) {
370                 err = sk->sk_prot->init(sk);
371                 if (err)
372                         sk_common_release(sk);
373         }
374 out:
375         return err;
376 out_sk_free:
377         rcu_read_unlock();
378         sk_free(sk);
379         goto out;
380 }
381
382
383 /*
384  *      The peer socket should always be NULL (or else). When we call this
385  *      function we are destroying the object and from then on nobody
386  *      should refer to it.
387  */
388 int inet_release(struct socket *sock)
389 {
390         struct sock *sk = sock->sk;
391
392         if (sk) {
393                 long timeout;
394
395                 /* Applications forget to leave groups before exiting */
396                 ip_mc_drop_socket(sk);
397
398                 /* If linger is set, we don't return until the close
399                  * is complete.  Otherwise we return immediately. The
400                  * actually closing is done the same either way.
401                  *
402                  * If the close is due to the process exiting, we never
403                  * linger..
404                  */
405                 timeout = 0;
406                 if (sock_flag(sk, SOCK_LINGER) &&
407                     !(current->flags & PF_EXITING))
408                         timeout = sk->sk_lingertime;
409                 sock->sk = NULL;
410                 clr_vx_info(&sk->sk_vx_info);
411         sk->sk_xid = -1;
412                 clr_nx_info(&sk->sk_nx_info);
413         sk->sk_nid = -1;
414                 sk->sk_prot->close(sk, timeout);
415         }
416         return 0;
417 }
418
419 /* It is off by default, see below. */
420 int sysctl_ip_nonlocal_bind;
421
422 int inet_bind(struct socket *sock, struct sockaddr *uaddr, int addr_len)
423 {
424         struct sockaddr_in *addr = (struct sockaddr_in *)uaddr;
425         struct sock *sk = sock->sk;
426         struct inet_opt *inet = inet_sk(sk);
427         unsigned short snum;
428         int chk_addr_ret;
429         int err;
430         __u32 s_addr;   /* Address used for validation */
431         __u32 s_addr1;
432         __u32 s_addr2 = 0xffffffffl;    /* Optional address of the socket */
433         struct nx_info *nxi = sk->sk_nx_info;
434
435         /* If the socket has its own bind function then use it. (RAW) */
436         if (sk->sk_prot->bind) {
437                 err = sk->sk_prot->bind(sk, uaddr, addr_len);
438                 goto out;
439         }
440         err = -EINVAL;
441         if (addr_len < sizeof(struct sockaddr_in))
442                 goto out;
443
444         s_addr = s_addr1 = addr->sin_addr.s_addr;
445         nxdprintk("inet_bind(%p) %p,%p;%lx\n",
446                 sk, nx_info, sk->sk_socket,
447                 (sk->sk_socket?sk->sk_socket->flags:0));
448         if (nxi) {
449                 __u32 v4_bcast = nxi->v4_bcast;
450                 __u32 ipv4root = nxi->ipv4[0];
451                 int nbipv4 = nxi->nbipv4;
452                 if (s_addr == 0) {
453                         s_addr = ipv4root;
454                         if (nbipv4 > 1)
455                                 s_addr1 = 0;
456                         else {
457                                 s_addr1 = ipv4root;
458                         }
459                         s_addr2 = v4_bcast;
460                 } else if (s_addr == 0x0100007f) {
461                         s_addr = s_addr1 = ipv4root;
462                 } else if (s_addr != v4_bcast) {
463                         int i;
464                         for (i=0; i<nbipv4; i++) {
465                                 if (s_addr == nxi->ipv4[i])
466                                         break;
467                         }
468                         if (i == nbipv4) {
469                                 return -EADDRNOTAVAIL;
470                         }
471                 }
472         }
473         chk_addr_ret = inet_addr_type(s_addr);
474
475         /* Not specified by any standard per-se, however it breaks too
476          * many applications when removed.  It is unfortunate since
477          * allowing applications to make a non-local bind solves
478          * several problems with systems using dynamic addressing.
479          * (ie. your servers still start up even if your ISDN link
480          *  is temporarily down)
481          */
482         err = -EADDRNOTAVAIL;
483         if (!sysctl_ip_nonlocal_bind &&
484             !inet->freebind &&
485             s_addr != INADDR_ANY &&
486             chk_addr_ret != RTN_LOCAL &&
487             chk_addr_ret != RTN_MULTICAST &&
488             chk_addr_ret != RTN_BROADCAST)
489                 goto out;
490
491         snum = ntohs(addr->sin_port);
492         err = -EACCES;
493         if (snum && snum < PROT_SOCK && !capable(CAP_NET_BIND_SERVICE))
494                 goto out;
495
496         /*      We keep a pair of addresses. rcv_saddr is the one
497          *      used by hash lookups, and saddr is used for transmit.
498          *
499          *      In the BSD API these are the same except where it
500          *      would be illegal to use them (multicast/broadcast) in
501          *      which case the sending device address is used.
502          */
503         lock_sock(sk);
504
505         /* Check these errors (active socket, double bind). */
506         err = -EINVAL;
507         if (sk->sk_state != TCP_CLOSE || inet->num)
508                 goto out_release_sock;
509
510         inet->rcv_saddr = inet->saddr = s_addr1;
511         inet->rcv_saddr2 = s_addr2;
512         if (chk_addr_ret == RTN_MULTICAST || chk_addr_ret == RTN_BROADCAST)
513                 inet->saddr = 0;  /* Use device */
514
515         /* Make sure we are allowed to bind here. */
516         if (sk->sk_prot->get_port(sk, snum)) {
517                 inet->saddr = inet->rcv_saddr = 0;
518                 err = -EADDRINUSE;
519                 goto out_release_sock;
520         }
521
522         if (inet->rcv_saddr)
523                 sk->sk_userlocks |= SOCK_BINDADDR_LOCK;
524         if (snum)
525                 sk->sk_userlocks |= SOCK_BINDPORT_LOCK;
526         inet->sport = htons(inet->num);
527         inet->daddr = 0;
528         inet->dport = 0;
529         sk_dst_reset(sk);
530         err = 0;
531 out_release_sock:
532         release_sock(sk);
533 out:
534         return err;
535 }
536
537 int inet_dgram_connect(struct socket *sock, struct sockaddr * uaddr,
538                        int addr_len, int flags)
539 {
540         struct sock *sk = sock->sk;
541
542         if (uaddr->sa_family == AF_UNSPEC)
543                 return sk->sk_prot->disconnect(sk, flags);
544
545         if (!inet_sk(sk)->num && inet_autobind(sk))
546                 return -EAGAIN;
547         return sk->sk_prot->connect(sk, (struct sockaddr *)uaddr, addr_len);
548 }
549
550 static long inet_wait_for_connect(struct sock *sk, long timeo)
551 {
552         DEFINE_WAIT(wait);
553
554         prepare_to_wait(sk->sk_sleep, &wait, TASK_INTERRUPTIBLE);
555
556         /* Basic assumption: if someone sets sk->sk_err, he _must_
557          * change state of the socket from TCP_SYN_*.
558          * Connect() does not allow to get error notifications
559          * without closing the socket.
560          */
561         while ((1 << sk->sk_state) & (TCPF_SYN_SENT | TCPF_SYN_RECV)) {
562                 release_sock(sk);
563                 timeo = schedule_timeout(timeo);
564                 lock_sock(sk);
565                 if (signal_pending(current) || !timeo)
566                         break;
567                 prepare_to_wait(sk->sk_sleep, &wait, TASK_INTERRUPTIBLE);
568         }
569         finish_wait(sk->sk_sleep, &wait);
570         return timeo;
571 }
572
573 /*
574  *      Connect to a remote host. There is regrettably still a little
575  *      TCP 'magic' in here.
576  */
577 int inet_stream_connect(struct socket *sock, struct sockaddr *uaddr,
578                         int addr_len, int flags)
579 {
580         struct sock *sk = sock->sk;
581         int err;
582         long timeo;
583
584         lock_sock(sk);
585
586         if (uaddr->sa_family == AF_UNSPEC) {
587                 err = sk->sk_prot->disconnect(sk, flags);
588                 sock->state = err ? SS_DISCONNECTING : SS_UNCONNECTED;
589                 goto out;
590         }
591
592         switch (sock->state) {
593         default:
594                 err = -EINVAL;
595                 goto out;
596         case SS_CONNECTED:
597                 err = -EISCONN;
598                 goto out;
599         case SS_CONNECTING:
600                 err = -EALREADY;
601                 /* Fall out of switch with err, set for this state */
602                 break;
603         case SS_UNCONNECTED:
604                 err = -EISCONN;
605                 if (sk->sk_state != TCP_CLOSE)
606                         goto out;
607
608                 err = sk->sk_prot->connect(sk, uaddr, addr_len);
609                 if (err < 0)
610                         goto out;
611
612                 sock->state = SS_CONNECTING;
613
614                 /* Just entered SS_CONNECTING state; the only
615                  * difference is that return value in non-blocking
616                  * case is EINPROGRESS, rather than EALREADY.
617                  */
618                 err = -EINPROGRESS;
619                 break;
620         }
621
622         timeo = sock_sndtimeo(sk, flags & O_NONBLOCK);
623
624         if ((1 << sk->sk_state) & (TCPF_SYN_SENT | TCPF_SYN_RECV)) {
625                 /* Error code is set above */
626                 if (!timeo || !inet_wait_for_connect(sk, timeo))
627                         goto out;
628
629                 err = sock_intr_errno(timeo);
630                 if (signal_pending(current))
631                         goto out;
632         }
633
634         /* Connection was closed by RST, timeout, ICMP error
635          * or another process disconnected us.
636          */
637         if (sk->sk_state == TCP_CLOSE)
638                 goto sock_error;
639
640         /* sk->sk_err may be not zero now, if RECVERR was ordered by user
641          * and error was received after socket entered established state.
642          * Hence, it is handled normally after connect() return successfully.
643          */
644
645         sock->state = SS_CONNECTED;
646         err = 0;
647 out:
648         release_sock(sk);
649         return err;
650
651 sock_error:
652         err = sock_error(sk) ? : -ECONNABORTED;
653         sock->state = SS_UNCONNECTED;
654         if (sk->sk_prot->disconnect(sk, flags))
655                 sock->state = SS_DISCONNECTING;
656         goto out;
657 }
658
659 /*
660  *      Accept a pending connection. The TCP layer now gives BSD semantics.
661  */
662
663 int inet_accept(struct socket *sock, struct socket *newsock, int flags)
664 {
665         struct sock *sk1 = sock->sk;
666         int err = -EINVAL;
667         struct sock *sk2 = sk1->sk_prot->accept(sk1, flags, &err);
668
669         if (!sk2)
670                 goto do_err;
671
672         lock_sock(sk2);
673
674         BUG_TRAP((1 << sk2->sk_state) &
675                  (TCPF_ESTABLISHED | TCPF_CLOSE_WAIT | TCPF_CLOSE));
676
677         sock_graft(sk2, newsock);
678
679         newsock->state = SS_CONNECTED;
680         err = 0;
681         release_sock(sk2);
682 do_err:
683         return err;
684 }
685
686
687 /*
688  *      This does both peername and sockname.
689  */
690 int inet_getname(struct socket *sock, struct sockaddr *uaddr,
691                         int *uaddr_len, int peer)
692 {
693         struct sock *sk         = sock->sk;
694         struct inet_opt *inet   = inet_sk(sk);
695         struct sockaddr_in *sin = (struct sockaddr_in *)uaddr;
696
697         sin->sin_family = AF_INET;
698         if (peer) {
699                 if (!inet->dport ||
700                     (((1 << sk->sk_state) & (TCPF_CLOSE | TCPF_SYN_SENT)) &&
701                      peer == 1))
702                         return -ENOTCONN;
703                 sin->sin_port = inet->dport;
704                 sin->sin_addr.s_addr = inet->daddr;
705         } else {
706                 __u32 addr = inet->rcv_saddr;
707                 if (!addr)
708                         addr = inet->saddr;
709                 sin->sin_port = inet->sport;
710                 sin->sin_addr.s_addr = addr;
711         }
712         memset(sin->sin_zero, 0, sizeof(sin->sin_zero));
713         *uaddr_len = sizeof(*sin);
714         return 0;
715 }
716
717 int inet_sendmsg(struct kiocb *iocb, struct socket *sock, struct msghdr *msg,
718                  size_t size)
719 {
720         struct sock *sk = sock->sk;
721
722         /* We may need to bind the socket. */
723         if (!inet_sk(sk)->num && inet_autobind(sk))
724                 return -EAGAIN;
725
726         return sk->sk_prot->sendmsg(iocb, sk, msg, size);
727 }
728
729
730 ssize_t inet_sendpage(struct socket *sock, struct page *page, int offset, size_t size, int flags)
731 {
732         struct sock *sk = sock->sk;
733
734         /* We may need to bind the socket. */
735         if (!inet_sk(sk)->num && inet_autobind(sk))
736                 return -EAGAIN;
737
738         if (sk->sk_prot->sendpage)
739                 return sk->sk_prot->sendpage(sk, page, offset, size, flags);
740         return sock_no_sendpage(sock, page, offset, size, flags);
741 }
742
743
744 int inet_shutdown(struct socket *sock, int how)
745 {
746         struct sock *sk = sock->sk;
747         int err = 0;
748
749         /* This should really check to make sure
750          * the socket is a TCP socket. (WHY AC...)
751          */
752         how++; /* maps 0->1 has the advantage of making bit 1 rcvs and
753                        1->2 bit 2 snds.
754                        2->3 */
755         if ((how & ~SHUTDOWN_MASK) || !how)     /* MAXINT->0 */
756                 return -EINVAL;
757
758         lock_sock(sk);
759         if (sock->state == SS_CONNECTING) {
760                 if ((1 << sk->sk_state) &
761                     (TCPF_SYN_SENT | TCPF_SYN_RECV | TCPF_CLOSE))
762                         sock->state = SS_DISCONNECTING;
763                 else
764                         sock->state = SS_CONNECTED;
765         }
766
767         switch (sk->sk_state) {
768         case TCP_CLOSE:
769                 err = -ENOTCONN;
770                 /* Hack to wake up other listeners, who can poll for
771                    POLLHUP, even on eg. unconnected UDP sockets -- RR */
772         default:
773                 sk->sk_shutdown |= how;
774                 if (sk->sk_prot->shutdown)
775                         sk->sk_prot->shutdown(sk, how);
776                 break;
777
778         /* Remaining two branches are temporary solution for missing
779          * close() in multithreaded environment. It is _not_ a good idea,
780          * but we have no choice until close() is repaired at VFS level.
781          */
782         case TCP_LISTEN:
783                 if (!(how & RCV_SHUTDOWN))
784                         break;
785                 /* Fall through */
786         case TCP_SYN_SENT:
787                 err = sk->sk_prot->disconnect(sk, O_NONBLOCK);
788                 sock->state = err ? SS_DISCONNECTING : SS_UNCONNECTED;
789                 break;
790         }
791
792         /* Wake up anyone sleeping in poll. */
793         sk->sk_state_change(sk);
794         release_sock(sk);
795         return err;
796 }
797
798 /*
799  *      ioctl() calls you can issue on an INET socket. Most of these are
800  *      device configuration and stuff and very rarely used. Some ioctls
801  *      pass on to the socket itself.
802  *
803  *      NOTE: I like the idea of a module for the config stuff. ie ifconfig
804  *      loads the devconfigure module does its configuring and unloads it.
805  *      There's a good 20K of config code hanging around the kernel.
806  */
807
808 int inet_ioctl(struct socket *sock, unsigned int cmd, unsigned long arg)
809 {
810         struct sock *sk = sock->sk;
811         int err = 0;
812
813         switch (cmd) {
814                 case SIOCGSTAMP:
815                         err = sock_get_timestamp(sk, (struct timeval __user *)arg);
816                         break;
817                 case SIOCADDRT:
818                 case SIOCDELRT:
819                 case SIOCRTMSG:
820                         err = ip_rt_ioctl(cmd, (void __user *)arg);
821                         break;
822                 case SIOCDARP:
823                 case SIOCGARP:
824                 case SIOCSARP:
825                         err = arp_ioctl(cmd, (void __user *)arg);
826                         break;
827                 case SIOCGIFADDR:
828                 case SIOCSIFADDR:
829                 case SIOCGIFBRDADDR:
830                 case SIOCSIFBRDADDR:
831                 case SIOCGIFNETMASK:
832                 case SIOCSIFNETMASK:
833                 case SIOCGIFDSTADDR:
834                 case SIOCSIFDSTADDR:
835                 case SIOCSIFPFLAGS:
836                 case SIOCGIFPFLAGS:
837                 case SIOCSIFFLAGS:
838                         err = devinet_ioctl(cmd, (void __user *)arg);
839                         break;
840                 default:
841                         if (!sk->sk_prot->ioctl ||
842                             (err = sk->sk_prot->ioctl(sk, cmd, arg)) ==
843                                                                 -ENOIOCTLCMD)
844                                 err = dev_ioctl(cmd, (void __user *)arg);
845                         break;
846         }
847         return err;
848 }
849
850 struct proto_ops inet_stream_ops = {
851         .family =       PF_INET,
852         .owner =        THIS_MODULE,
853         .release =      inet_release,
854         .bind =         inet_bind,
855         .connect =      inet_stream_connect,
856         .socketpair =   sock_no_socketpair,
857         .accept =       inet_accept,
858         .getname =      inet_getname,
859         .poll =         tcp_poll,
860         .ioctl =        inet_ioctl,
861         .listen =       inet_listen,
862         .shutdown =     inet_shutdown,
863         .setsockopt =   sock_common_setsockopt,
864         .getsockopt =   sock_common_getsockopt,
865         .sendmsg =      inet_sendmsg,
866         .recvmsg =      sock_common_recvmsg,
867         .mmap =         sock_no_mmap,
868         .sendpage =     tcp_sendpage
869 };
870
871 struct proto_ops inet_dgram_ops = {
872         .family =       PF_INET,
873         .owner =        THIS_MODULE,
874         .release =      inet_release,
875         .bind =         inet_bind,
876         .connect =      inet_dgram_connect,
877         .socketpair =   sock_no_socketpair,
878         .accept =       sock_no_accept,
879         .getname =      inet_getname,
880         .poll =         datagram_poll,
881         .ioctl =        inet_ioctl,
882         .listen =       sock_no_listen,
883         .shutdown =     inet_shutdown,
884         .setsockopt =   sock_common_setsockopt,
885         .getsockopt =   sock_common_getsockopt,
886         .sendmsg =      inet_sendmsg,
887         .recvmsg =      sock_common_recvmsg,
888         .mmap =         sock_no_mmap,
889         .sendpage =     inet_sendpage,
890 };
891
892 struct net_proto_family inet_family_ops = {
893         .family = PF_INET,
894         .create = inet_create,
895         .owner  = THIS_MODULE,
896 };
897
898
899 extern void tcp_init(void);
900 extern void tcp_v4_init(struct net_proto_family *);
901
902 /* Upon startup we insert all the elements in inetsw_array[] into
903  * the linked list inetsw.
904  */
905 static struct inet_protosw inetsw_array[] =
906 {
907         {
908                 .type =       SOCK_STREAM,
909                 .protocol =   IPPROTO_TCP,
910                 .prot =       &tcp_prot,
911                 .ops =        &inet_stream_ops,
912                 .capability = -1,
913                 .no_check =   0,
914                 .flags =      INET_PROTOSW_PERMANENT,
915         },
916
917         {
918                 .type =       SOCK_DGRAM,
919                 .protocol =   IPPROTO_UDP,
920                 .prot =       &udp_prot,
921                 .ops =        &inet_dgram_ops,
922                 .capability = -1,
923                 .no_check =   UDP_CSUM_DEFAULT,
924                 .flags =      INET_PROTOSW_PERMANENT,
925        },
926         
927
928        {
929                .type =       SOCK_RAW,
930                .protocol =   IPPROTO_IP,        /* wild card */
931                .prot =       &raw_prot,
932                .ops =        &inet_dgram_ops,
933                .capability = CAP_NET_RAW,
934                .no_check =   UDP_CSUM_DEFAULT,
935                .flags =      INET_PROTOSW_REUSE,
936        }
937 };
938
939 #define INETSW_ARRAY_LEN (sizeof(inetsw_array) / sizeof(struct inet_protosw))
940
941 void inet_register_protosw(struct inet_protosw *p)
942 {
943         struct list_head *lh;
944         struct inet_protosw *answer;
945         int protocol = p->protocol;
946         struct list_head *last_perm;
947
948         spin_lock_bh(&inetsw_lock);
949
950         if (p->type >= SOCK_MAX)
951                 goto out_illegal;
952
953         /* If we are trying to override a permanent protocol, bail. */
954         answer = NULL;
955         last_perm = &inetsw[p->type];
956         list_for_each(lh, &inetsw[p->type]) {
957                 answer = list_entry(lh, struct inet_protosw, list);
958
959                 /* Check only the non-wild match. */
960                 if (INET_PROTOSW_PERMANENT & answer->flags) {
961                         if (protocol == answer->protocol)
962                                 break;
963                         last_perm = lh;
964                 }
965
966                 answer = NULL;
967         }
968         if (answer)
969                 goto out_permanent;
970
971         /* Add the new entry after the last permanent entry if any, so that
972          * the new entry does not override a permanent entry when matched with
973          * a wild-card protocol. But it is allowed to override any existing
974          * non-permanent entry.  This means that when we remove this entry, the 
975          * system automatically returns to the old behavior.
976          */
977         list_add_rcu(&p->list, last_perm);
978 out:
979         spin_unlock_bh(&inetsw_lock);
980
981         synchronize_net();
982
983         return;
984
985 out_permanent:
986         printk(KERN_ERR "Attempt to override permanent protocol %d.\n",
987                protocol);
988         goto out;
989
990 out_illegal:
991         printk(KERN_ERR
992                "Ignoring attempt to register invalid socket type %d.\n",
993                p->type);
994         goto out;
995 }
996
997 void inet_unregister_protosw(struct inet_protosw *p)
998 {
999         if (INET_PROTOSW_PERMANENT & p->flags) {
1000                 printk(KERN_ERR
1001                        "Attempt to unregister permanent protocol %d.\n",
1002                        p->protocol);
1003         } else {
1004                 spin_lock_bh(&inetsw_lock);
1005                 list_del_rcu(&p->list);
1006                 spin_unlock_bh(&inetsw_lock);
1007
1008                 synchronize_net();
1009         }
1010 }
1011
1012 #ifdef CONFIG_IP_MULTICAST
1013 static struct net_protocol igmp_protocol = {
1014         .handler =      igmp_rcv,
1015 };
1016 #endif
1017
1018 static struct net_protocol tcp_protocol = {
1019         .handler =      tcp_v4_rcv,
1020         .err_handler =  tcp_v4_err,
1021         .no_policy =    1,
1022 };
1023
1024 static struct net_protocol udp_protocol = {
1025         .handler =      udp_rcv,
1026         .err_handler =  udp_err,
1027         .no_policy =    1,
1028 };
1029
1030 static struct net_protocol icmp_protocol = {
1031         .handler =      icmp_rcv,
1032 };
1033
1034 static int __init init_ipv4_mibs(void)
1035 {
1036         net_statistics[0] = alloc_percpu(struct linux_mib);
1037         net_statistics[1] = alloc_percpu(struct linux_mib);
1038         ip_statistics[0] = alloc_percpu(struct ipstats_mib);
1039         ip_statistics[1] = alloc_percpu(struct ipstats_mib);
1040         icmp_statistics[0] = alloc_percpu(struct icmp_mib);
1041         icmp_statistics[1] = alloc_percpu(struct icmp_mib);
1042         tcp_statistics[0] = alloc_percpu(struct tcp_mib);
1043         tcp_statistics[1] = alloc_percpu(struct tcp_mib);
1044         udp_statistics[0] = alloc_percpu(struct udp_mib);
1045         udp_statistics[1] = alloc_percpu(struct udp_mib);
1046         if (!
1047             (net_statistics[0] && net_statistics[1] && ip_statistics[0]
1048              && ip_statistics[1] && tcp_statistics[0] && tcp_statistics[1]
1049              && udp_statistics[0] && udp_statistics[1]))
1050                 return -ENOMEM;
1051
1052         (void) tcp_mib_init();
1053
1054         return 0;
1055 }
1056
1057 int ipv4_proc_init(void);
1058 extern void ipfrag_init(void);
1059
1060 static int __init inet_init(void)
1061 {
1062         struct sk_buff *dummy_skb;
1063         struct inet_protosw *q;
1064         struct list_head *r;
1065
1066         if (sizeof(struct inet_skb_parm) > sizeof(dummy_skb->cb)) {
1067                 printk(KERN_CRIT "%s: panic\n", __FUNCTION__);
1068                 return -EINVAL;
1069         }
1070
1071         tcp_sk_cachep = kmem_cache_create("tcp_sock",
1072                                           sizeof(struct tcp_sock), 0,
1073                                           SLAB_HWCACHE_ALIGN, NULL, NULL);
1074         udp_sk_cachep = kmem_cache_create("udp_sock",
1075                                           sizeof(struct udp_sock), 0,
1076                                           SLAB_HWCACHE_ALIGN, NULL, NULL);
1077         raw4_sk_cachep = kmem_cache_create("raw4_sock",
1078                                            sizeof(struct raw_sock), 0,
1079                                            SLAB_HWCACHE_ALIGN, NULL, NULL);
1080         if (!tcp_sk_cachep || !udp_sk_cachep || !raw4_sk_cachep)
1081                 printk(KERN_CRIT
1082                        "inet_init: Can't create protocol sock SLAB caches!\n");
1083         /*
1084          *      Tell SOCKET that we are alive... 
1085          */
1086
1087         (void)sock_register(&inet_family_ops);
1088
1089         /*
1090          *      Add all the base protocols.
1091          */
1092
1093         if (inet_add_protocol(&icmp_protocol, IPPROTO_ICMP) < 0)
1094                 printk(KERN_CRIT "inet_init: Cannot add ICMP protocol\n");
1095         if (inet_add_protocol(&udp_protocol, IPPROTO_UDP) < 0)
1096                 printk(KERN_CRIT "inet_init: Cannot add UDP protocol\n");
1097         if (inet_add_protocol(&tcp_protocol, IPPROTO_TCP) < 0)
1098                 printk(KERN_CRIT "inet_init: Cannot add TCP protocol\n");
1099 #ifdef CONFIG_IP_MULTICAST
1100         if (inet_add_protocol(&igmp_protocol, IPPROTO_IGMP) < 0)
1101                 printk(KERN_CRIT "inet_init: Cannot add IGMP protocol\n");
1102 #endif
1103
1104         /* Register the socket-side information for inet_create. */
1105         for (r = &inetsw[0]; r < &inetsw[SOCK_MAX]; ++r)
1106                 INIT_LIST_HEAD(r);
1107
1108         for (q = inetsw_array; q < &inetsw_array[INETSW_ARRAY_LEN]; ++q)
1109                 inet_register_protosw(q);
1110
1111         /*
1112          *      Set the ARP module up
1113          */
1114
1115         arp_init();
1116
1117         /*
1118          *      Set the IP module up
1119          */
1120
1121         ip_init();
1122
1123         tcp_v4_init(&inet_family_ops);
1124
1125         /* Setup TCP slab cache for open requests. */
1126         tcp_init();
1127
1128
1129         /*
1130          *      Set the ICMP layer up
1131          */
1132
1133         icmp_init(&inet_family_ops);
1134
1135         /*
1136          *      Initialise the multicast router
1137          */
1138 #if defined(CONFIG_IP_MROUTE)
1139         ip_mr_init();
1140 #endif
1141         /*
1142          *      Initialise per-cpu ipv4 mibs
1143          */ 
1144
1145         if(init_ipv4_mibs())
1146                 printk(KERN_CRIT "inet_init: Cannot init ipv4 mibs\n"); ;
1147         
1148         ipv4_proc_init();
1149
1150         ipfrag_init();
1151
1152         return 0;
1153 }
1154
1155 module_init(inet_init);
1156
1157 /* ------------------------------------------------------------------------ */
1158
1159 #ifdef CONFIG_PROC_FS
1160 extern int  fib_proc_init(void);
1161 extern void fib_proc_exit(void);
1162 extern int  ip_misc_proc_init(void);
1163 extern int  raw_proc_init(void);
1164 extern void raw_proc_exit(void);
1165 extern int  tcp4_proc_init(void);
1166 extern void tcp4_proc_exit(void);
1167 extern int  udp4_proc_init(void);
1168 extern void udp4_proc_exit(void);
1169
1170 int __init ipv4_proc_init(void)
1171 {
1172         int rc = 0;
1173
1174         if (raw_proc_init())
1175                 goto out_raw;
1176         if (tcp4_proc_init())
1177                 goto out_tcp;
1178         if (udp4_proc_init())
1179                 goto out_udp;
1180         if (fib_proc_init())
1181                 goto out_fib;
1182         if (ip_misc_proc_init())
1183                 goto out_misc;
1184 out:
1185         return rc;
1186 out_misc:
1187         fib_proc_exit();
1188 out_fib:
1189         udp4_proc_exit();
1190 out_udp:
1191         tcp4_proc_exit();
1192 out_tcp:
1193         raw_proc_exit();
1194 out_raw:
1195         rc = -ENOMEM;
1196         goto out;
1197 }
1198
1199 #else /* CONFIG_PROC_FS */
1200 int __init ipv4_proc_init(void)
1201 {
1202         return 0;
1203 }
1204 #endif /* CONFIG_PROC_FS */
1205
1206 MODULE_ALIAS_NETPROTO(PF_INET);
1207
1208 EXPORT_SYMBOL(inet_accept);
1209 EXPORT_SYMBOL(inet_bind);
1210 EXPORT_SYMBOL(inet_dgram_connect);
1211 EXPORT_SYMBOL(inet_dgram_ops);
1212 EXPORT_SYMBOL(inet_family_ops);
1213 EXPORT_SYMBOL(inet_getname);
1214 EXPORT_SYMBOL(inet_ioctl);
1215 EXPORT_SYMBOL(inet_listen);
1216 EXPORT_SYMBOL(inet_register_protosw);
1217 EXPORT_SYMBOL(inet_release);
1218 EXPORT_SYMBOL(inet_sendmsg);
1219 EXPORT_SYMBOL(inet_shutdown);
1220 EXPORT_SYMBOL(inet_sock_destruct);
1221 EXPORT_SYMBOL(inet_stream_connect);
1222 EXPORT_SYMBOL(inet_stream_ops);
1223 EXPORT_SYMBOL(inet_unregister_protosw);
1224 EXPORT_SYMBOL(net_statistics);
1225 EXPORT_SYMBOL(tcp_protocol);
1226 EXPORT_SYMBOL(udp_protocol);
1227
1228 #ifdef INET_REFCNT_DEBUG
1229 EXPORT_SYMBOL(inet_sock_nr);
1230 #endif