patch-2_6_7-vs1_9_1_12
[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 void inet_sock_release(struct sock *sk)
176 {
177         if (sk->sk_prot->destroy)
178                 sk->sk_prot->destroy(sk);
179
180         /* Observation: when inet_sock_release is called, processes have
181          * no access to socket. But net still has.
182          * Step one, detach it from networking:
183          *
184          * A. Remove from hash tables.
185          */
186
187         sk->sk_prot->unhash(sk);
188
189         /* In this point socket cannot receive new packets,
190          * but it is possible that some packets are in flight
191          * because some CPU runs receiver and did hash table lookup
192          * before we unhashed socket. They will achieve receive queue
193          * and will be purged by socket destructor.
194          *
195          * Also we still have packets pending on receive
196          * queue and probably, our own packets waiting in device queues.
197          * sock_destroy will drain receive queue, but transmitted
198          * packets will delay socket destruction until the last reference
199          * will be released.
200          */
201
202         sock_orphan(sk);
203
204         xfrm_sk_free_policy(sk);
205
206 #ifdef INET_REFCNT_DEBUG
207         if (atomic_read(&sk->sk_refcnt) != 1)
208                 printk(KERN_DEBUG "Destruction inet %p delayed, c=%d\n",
209                        sk, atomic_read(&sk->sk_refcnt));
210 #endif
211         sock_put(sk);
212 }
213
214
215 /*
216  *      The routines beyond this point handle the behaviour of an AF_INET
217  *      socket object. Mostly it punts to the subprotocols of IP to do
218  *      the work.
219  */
220
221 /*
222  *      Set socket options on an inet socket.
223  */
224 int inet_setsockopt(struct socket *sock, int level, int optname,
225                     char __user *optval, int optlen)
226 {
227         struct sock *sk = sock->sk;
228
229         return sk->sk_prot->setsockopt(sk, level, optname, optval, optlen);
230 }
231
232 /*
233  *      Get a socket option on an AF_INET socket.
234  *
235  *      FIX: POSIX 1003.1g is very ambiguous here. It states that
236  *      asynchronous errors should be reported by getsockopt. We assume
237  *      this means if you specify SO_ERROR (otherwise whats the point of it).
238  */
239
240 int inet_getsockopt(struct socket *sock, int level, int optname,
241                     char __user *optval, int __user *optlen)
242 {
243         struct sock *sk = sock->sk;
244
245         return sk->sk_prot->getsockopt(sk, level, optname, optval, optlen);
246 }
247
248 /*
249  *      Automatically bind an unbound socket.
250  */
251
252 static int inet_autobind(struct sock *sk)
253 {
254         struct inet_opt *inet;
255         /* We may need to bind the socket. */
256         lock_sock(sk);
257         inet = inet_sk(sk);
258         if (!inet->num) {
259                 if (sk->sk_prot->get_port(sk, 0)) {
260                         release_sock(sk);
261                         return -EAGAIN;
262                 }
263                 inet->sport = htons(inet->num);
264         }
265         release_sock(sk);
266         return 0;
267 }
268
269 /*
270  *      Move a socket into listening state.
271  */
272 int inet_listen(struct socket *sock, int backlog)
273 {
274         struct sock *sk = sock->sk;
275         unsigned char old_state;
276         int err;
277
278         lock_sock(sk);
279
280         err = -EINVAL;
281         if (sock->state != SS_UNCONNECTED || sock->type != SOCK_STREAM)
282                 goto out;
283
284         old_state = sk->sk_state;
285         if (!((1 << old_state) & (TCPF_CLOSE | TCPF_LISTEN)))
286                 goto out;
287
288         /* Really, if the socket is already in listen state
289          * we can only allow the backlog to be adjusted.
290          */
291         if (old_state != TCP_LISTEN) {
292                 err = tcp_listen_start(sk);
293                 if (err)
294                         goto out;
295         }
296         sk->sk_max_ack_backlog = backlog;
297         err = 0;
298
299 out:
300         release_sock(sk);
301         return err;
302 }
303
304 static __inline__ kmem_cache_t *inet_sk_slab(int protocol)
305 {
306         kmem_cache_t* rc = tcp_sk_cachep;
307
308         if (protocol == IPPROTO_UDP)
309                 rc = udp_sk_cachep;
310         else if (protocol == IPPROTO_RAW)
311                 rc = raw4_sk_cachep;
312         return rc;
313 }
314
315 static __inline__ int inet_sk_size(int protocol)
316 {
317         int rc = sizeof(struct tcp_sock);
318
319         if (protocol == IPPROTO_UDP)
320                 rc = sizeof(struct udp_sock);
321         else if (protocol == IPPROTO_RAW)
322                 rc = sizeof(struct raw_sock);
323         return rc;
324 }
325
326 /*
327  *      Create an inet socket.
328  */
329
330 static int inet_create(struct socket *sock, int protocol)
331 {
332         struct sock *sk;
333         struct list_head *p;
334         struct inet_protosw *answer;
335         struct inet_opt *inet;
336         int err = -ENOBUFS;
337
338         sock->state = SS_UNCONNECTED;
339         sk = sk_alloc(PF_INET, GFP_KERNEL, inet_sk_size(protocol),
340                       inet_sk_slab(protocol));
341         if (!sk)
342                 goto out;
343
344         /* Look for the requested type/protocol pair. */
345         answer = NULL;
346         rcu_read_lock();
347         list_for_each_rcu(p, &inetsw[sock->type]) {
348                 answer = list_entry(p, struct inet_protosw, list);
349
350                 /* Check the non-wild match. */
351                 if (protocol == answer->protocol) {
352                         if (protocol != IPPROTO_IP)
353                                 break;
354                 } else {
355                         /* Check for the two wild cases. */
356                         if (IPPROTO_IP == protocol) {
357                                 protocol = answer->protocol;
358                                 break;
359                         }
360                         if (IPPROTO_IP == answer->protocol)
361                                 break;
362                 }
363                 answer = NULL;
364         }
365
366         err = -ESOCKTNOSUPPORT;
367         if (!answer)
368                 goto out_sk_free;
369         err = -EPERM;
370         if ((protocol == IPPROTO_ICMP) && vx_ccaps(VXC_RAW_ICMP))
371                 goto override;
372         if (answer->capability > 0 && !capable(answer->capability))
373                 goto out_sk_free;
374 override:
375         err = -EPROTONOSUPPORT;
376         if (!protocol)
377                 goto out_sk_free;
378         err = 0;
379         sock->ops = answer->ops;
380         sk->sk_prot = answer->prot;
381         sk->sk_no_check = answer->no_check;
382         if (INET_PROTOSW_REUSE & answer->flags)
383                 sk->sk_reuse = 1;
384         rcu_read_unlock();
385
386         inet = inet_sk(sk);
387
388         if (SOCK_RAW == sock->type) {
389                 inet->num = protocol;
390                 if (IPPROTO_RAW == protocol)
391                         inet->hdrincl = 1;
392         }
393
394         if (ipv4_config.no_pmtu_disc)
395                 inet->pmtudisc = IP_PMTUDISC_DONT;
396         else
397                 inet->pmtudisc = IP_PMTUDISC_WANT;
398
399         inet->id = 0;
400
401         sock_init_data(sock, sk);
402         sk_set_owner(sk, THIS_MODULE);
403
404         sk->sk_destruct    = inet_sock_destruct;
405         sk->sk_zapped      = 0;
406         sk->sk_family      = PF_INET;
407         sk->sk_protocol    = protocol;
408         sk->sk_backlog_rcv = sk->sk_prot->backlog_rcv;
409         
410         set_vx_info(&sk->sk_vx_info, current->vx_info);
411         sk->sk_xid = vx_current_xid();
412         set_nx_info(&sk->sk_nx_info, current->nx_info);
413         sk->sk_nid = nx_current_nid();
414
415         inet->uc_ttl    = -1;
416         inet->mc_loop   = 1;
417         inet->mc_ttl    = 1;
418         inet->mc_index  = 0;
419         inet->mc_list   = NULL;
420
421 #ifdef INET_REFCNT_DEBUG
422         atomic_inc(&inet_sock_nr);
423 #endif
424
425         if (inet->num) {
426                 /* It assumes that any protocol which allows
427                  * the user to assign a number at socket
428                  * creation time automatically
429                  * shares.
430                  */
431                 inet->sport = htons(inet->num);
432                 /* Add to protocol hash chains. */
433                 sk->sk_prot->hash(sk);
434         }
435
436         if (sk->sk_prot->init) {
437                 err = sk->sk_prot->init(sk);
438                 if (err)
439                         inet_sock_release(sk);
440         }
441 out:
442         return err;
443 out_sk_free:
444         rcu_read_unlock();
445         sk_free(sk);
446         goto out;
447 }
448
449
450 /*
451  *      The peer socket should always be NULL (or else). When we call this
452  *      function we are destroying the object and from then on nobody
453  *      should refer to it.
454  */
455 int inet_release(struct socket *sock)
456 {
457         struct sock *sk = sock->sk;
458
459         if (sk) {
460                 long timeout;
461
462                 /* Applications forget to leave groups before exiting */
463                 ip_mc_drop_socket(sk);
464
465                 /* If linger is set, we don't return until the close
466                  * is complete.  Otherwise we return immediately. The
467                  * actually closing is done the same either way.
468                  *
469                  * If the close is due to the process exiting, we never
470                  * linger..
471                  */
472                 timeout = 0;
473                 if (sock_flag(sk, SOCK_LINGER) &&
474                     !(current->flags & PF_EXITING))
475                         timeout = sk->sk_lingertime;
476                 sock->sk = NULL;
477                 clr_vx_info(&sk->sk_vx_info);
478         sk->sk_xid = -1;
479                 clr_nx_info(&sk->sk_nx_info);
480         sk->sk_nid = -1;
481                 sk->sk_prot->close(sk, timeout);
482         }
483         return 0;
484 }
485
486 /* It is off by default, see below. */
487 int sysctl_ip_nonlocal_bind;
488
489 int inet_bind(struct socket *sock, struct sockaddr *uaddr, int addr_len)
490 {
491         struct sockaddr_in *addr = (struct sockaddr_in *)uaddr;
492         struct sock *sk = sock->sk;
493         struct inet_opt *inet = inet_sk(sk);
494         unsigned short snum;
495         int chk_addr_ret;
496         int err;
497         __u32 s_addr;   /* Address used for validation */
498         __u32 s_addr1;
499         __u32 s_addr2 = 0xffffffffl;    /* Optional address of the socket */
500         struct nx_info *nxi = sk->sk_nx_info;
501
502         /* If the socket has its own bind function then use it. (RAW) */
503         if (sk->sk_prot->bind) {
504                 err = sk->sk_prot->bind(sk, uaddr, addr_len);
505                 goto out;
506         }
507         err = -EINVAL;
508         if (addr_len < sizeof(struct sockaddr_in))
509                 goto out;
510
511         s_addr = s_addr1 = addr->sin_addr.s_addr;
512         nxdprintk("inet_bind(%p) %p,%p;%lx\n",
513                 sk, nx_info, sk->sk_socket,
514                 (sk->sk_socket?sk->sk_socket->flags:0));
515         if (nxi) {
516                 __u32 v4_bcast = nxi->v4_bcast;
517                 __u32 ipv4root = nxi->ipv4[0];
518                 int nbipv4 = nxi->nbipv4;
519                 if (s_addr == 0) {
520                         s_addr = ipv4root;
521                         if (nbipv4 > 1)
522                                 s_addr1 = 0;
523                         else {
524                                 s_addr1 = ipv4root;
525                         }
526                         s_addr2 = v4_bcast;
527                 } else if (s_addr == 0x0100007f) {
528                         s_addr = s_addr1 = ipv4root;
529                 } else if (s_addr != v4_bcast) {
530                         int i;
531                         for (i=0; i<nbipv4; i++) {
532                                 if (s_addr == nxi->ipv4[i])
533                                         break;
534                         }
535                         if (i == nbipv4) {
536                                 return -EADDRNOTAVAIL;
537                         }
538                 }
539         }
540         chk_addr_ret = inet_addr_type(s_addr);
541
542         /* Not specified by any standard per-se, however it breaks too
543          * many applications when removed.  It is unfortunate since
544          * allowing applications to make a non-local bind solves
545          * several problems with systems using dynamic addressing.
546          * (ie. your servers still start up even if your ISDN link
547          *  is temporarily down)
548          */
549         err = -EADDRNOTAVAIL;
550         if (!sysctl_ip_nonlocal_bind &&
551             !inet->freebind &&
552             s_addr != INADDR_ANY &&
553             chk_addr_ret != RTN_LOCAL &&
554             chk_addr_ret != RTN_MULTICAST &&
555             chk_addr_ret != RTN_BROADCAST)
556                 goto out;
557
558         snum = ntohs(addr->sin_port);
559         err = -EACCES;
560         if (snum && snum < PROT_SOCK && !capable(CAP_NET_BIND_SERVICE))
561                 goto out;
562
563         /*      We keep a pair of addresses. rcv_saddr is the one
564          *      used by hash lookups, and saddr is used for transmit.
565          *
566          *      In the BSD API these are the same except where it
567          *      would be illegal to use them (multicast/broadcast) in
568          *      which case the sending device address is used.
569          */
570         lock_sock(sk);
571
572         /* Check these errors (active socket, double bind). */
573         err = -EINVAL;
574         if (sk->sk_state != TCP_CLOSE || inet->num)
575                 goto out_release_sock;
576
577         inet->rcv_saddr = inet->saddr = s_addr1;
578         inet->rcv_saddr2 = s_addr2;
579         if (chk_addr_ret == RTN_MULTICAST || chk_addr_ret == RTN_BROADCAST)
580                 inet->saddr = 0;  /* Use device */
581
582         /* Make sure we are allowed to bind here. */
583         if (sk->sk_prot->get_port(sk, snum)) {
584                 inet->saddr = inet->rcv_saddr = 0;
585                 err = -EADDRINUSE;
586                 goto out_release_sock;
587         }
588
589         if (inet->rcv_saddr)
590                 sk->sk_userlocks |= SOCK_BINDADDR_LOCK;
591         if (snum)
592                 sk->sk_userlocks |= SOCK_BINDPORT_LOCK;
593         inet->sport = htons(inet->num);
594         inet->daddr = 0;
595         inet->dport = 0;
596         sk_dst_reset(sk);
597         err = 0;
598 out_release_sock:
599         release_sock(sk);
600 out:
601         return err;
602 }
603
604 int inet_dgram_connect(struct socket *sock, struct sockaddr * uaddr,
605                        int addr_len, int flags)
606 {
607         struct sock *sk = sock->sk;
608
609         if (uaddr->sa_family == AF_UNSPEC)
610                 return sk->sk_prot->disconnect(sk, flags);
611
612         if (!inet_sk(sk)->num && inet_autobind(sk))
613                 return -EAGAIN;
614         return sk->sk_prot->connect(sk, (struct sockaddr *)uaddr, addr_len);
615 }
616
617 static long inet_wait_for_connect(struct sock *sk, long timeo)
618 {
619         DEFINE_WAIT(wait);
620
621         prepare_to_wait(sk->sk_sleep, &wait, TASK_INTERRUPTIBLE);
622
623         /* Basic assumption: if someone sets sk->sk_err, he _must_
624          * change state of the socket from TCP_SYN_*.
625          * Connect() does not allow to get error notifications
626          * without closing the socket.
627          */
628         while ((1 << sk->sk_state) & (TCPF_SYN_SENT | TCPF_SYN_RECV)) {
629                 release_sock(sk);
630                 timeo = schedule_timeout(timeo);
631                 lock_sock(sk);
632                 if (signal_pending(current) || !timeo)
633                         break;
634                 prepare_to_wait(sk->sk_sleep, &wait, TASK_INTERRUPTIBLE);
635         }
636         finish_wait(sk->sk_sleep, &wait);
637         return timeo;
638 }
639
640 /*
641  *      Connect to a remote host. There is regrettably still a little
642  *      TCP 'magic' in here.
643  */
644 int inet_stream_connect(struct socket *sock, struct sockaddr *uaddr,
645                         int addr_len, int flags)
646 {
647         struct sock *sk = sock->sk;
648         int err;
649         long timeo;
650
651         lock_sock(sk);
652
653         if (uaddr->sa_family == AF_UNSPEC) {
654                 err = sk->sk_prot->disconnect(sk, flags);
655                 sock->state = err ? SS_DISCONNECTING : SS_UNCONNECTED;
656                 goto out;
657         }
658
659         switch (sock->state) {
660         default:
661                 err = -EINVAL;
662                 goto out;
663         case SS_CONNECTED:
664                 err = -EISCONN;
665                 goto out;
666         case SS_CONNECTING:
667                 err = -EALREADY;
668                 /* Fall out of switch with err, set for this state */
669                 break;
670         case SS_UNCONNECTED:
671                 err = -EISCONN;
672                 if (sk->sk_state != TCP_CLOSE)
673                         goto out;
674
675                 err = sk->sk_prot->connect(sk, uaddr, addr_len);
676                 if (err < 0)
677                         goto out;
678
679                 sock->state = SS_CONNECTING;
680
681                 /* Just entered SS_CONNECTING state; the only
682                  * difference is that return value in non-blocking
683                  * case is EINPROGRESS, rather than EALREADY.
684                  */
685                 err = -EINPROGRESS;
686                 break;
687         }
688
689         timeo = sock_sndtimeo(sk, flags & O_NONBLOCK);
690
691         if ((1 << sk->sk_state) & (TCPF_SYN_SENT | TCPF_SYN_RECV)) {
692                 /* Error code is set above */
693                 if (!timeo || !inet_wait_for_connect(sk, timeo))
694                         goto out;
695
696                 err = sock_intr_errno(timeo);
697                 if (signal_pending(current))
698                         goto out;
699         }
700
701         /* Connection was closed by RST, timeout, ICMP error
702          * or another process disconnected us.
703          */
704         if (sk->sk_state == TCP_CLOSE)
705                 goto sock_error;
706
707         /* sk->sk_err may be not zero now, if RECVERR was ordered by user
708          * and error was received after socket entered established state.
709          * Hence, it is handled normally after connect() return successfully.
710          */
711
712         sock->state = SS_CONNECTED;
713         err = 0;
714 out:
715         release_sock(sk);
716         return err;
717
718 sock_error:
719         err = sock_error(sk) ? : -ECONNABORTED;
720         sock->state = SS_UNCONNECTED;
721         if (sk->sk_prot->disconnect(sk, flags))
722                 sock->state = SS_DISCONNECTING;
723         goto out;
724 }
725
726 /*
727  *      Accept a pending connection. The TCP layer now gives BSD semantics.
728  */
729
730 int inet_accept(struct socket *sock, struct socket *newsock, int flags)
731 {
732         struct sock *sk1 = sock->sk;
733         int err = -EINVAL;
734         struct sock *sk2 = sk1->sk_prot->accept(sk1, flags, &err);
735
736         if (!sk2)
737                 goto do_err;
738
739         lock_sock(sk2);
740
741         BUG_TRAP((1 << sk2->sk_state) &
742                  (TCPF_ESTABLISHED | TCPF_CLOSE_WAIT | TCPF_CLOSE));
743
744         sock_graft(sk2, newsock);
745
746         newsock->state = SS_CONNECTED;
747         err = 0;
748         release_sock(sk2);
749 do_err:
750         return err;
751 }
752
753
754 /*
755  *      This does both peername and sockname.
756  */
757 int inet_getname(struct socket *sock, struct sockaddr *uaddr,
758                         int *uaddr_len, int peer)
759 {
760         struct sock *sk         = sock->sk;
761         struct inet_opt *inet   = inet_sk(sk);
762         struct sockaddr_in *sin = (struct sockaddr_in *)uaddr;
763
764         sin->sin_family = AF_INET;
765         if (peer) {
766                 if (!inet->dport ||
767                     (((1 << sk->sk_state) & (TCPF_CLOSE | TCPF_SYN_SENT)) &&
768                      peer == 1))
769                         return -ENOTCONN;
770                 sin->sin_port = inet->dport;
771                 sin->sin_addr.s_addr = inet->daddr;
772         } else {
773                 __u32 addr = inet->rcv_saddr;
774                 if (!addr)
775                         addr = inet->saddr;
776                 sin->sin_port = inet->sport;
777                 sin->sin_addr.s_addr = addr;
778         }
779         memset(sin->sin_zero, 0, sizeof(sin->sin_zero));
780         *uaddr_len = sizeof(*sin);
781         return 0;
782 }
783
784
785 int inet_recvmsg(struct kiocb *iocb, struct socket *sock, struct msghdr *msg,
786                  size_t size, int flags)
787 {
788         struct sock *sk = sock->sk;
789         int addr_len = 0;
790         int err;
791
792         err = sk->sk_prot->recvmsg(iocb, sk, msg, size, flags & MSG_DONTWAIT,
793                                    flags & ~MSG_DONTWAIT, &addr_len);
794         if (err >= 0)
795                 msg->msg_namelen = addr_len;
796         return err;
797 }
798
799
800 int inet_sendmsg(struct kiocb *iocb, struct socket *sock, struct msghdr *msg,
801                  size_t size)
802 {
803         struct sock *sk = sock->sk;
804
805         /* We may need to bind the socket. */
806         if (!inet_sk(sk)->num && inet_autobind(sk))
807                 return -EAGAIN;
808
809         return sk->sk_prot->sendmsg(iocb, sk, msg, size);
810 }
811
812
813 ssize_t inet_sendpage(struct socket *sock, struct page *page, int offset, size_t size, int flags)
814 {
815         struct sock *sk = sock->sk;
816
817         /* We may need to bind the socket. */
818         if (!inet_sk(sk)->num && inet_autobind(sk))
819                 return -EAGAIN;
820
821         if (sk->sk_prot->sendpage)
822                 return sk->sk_prot->sendpage(sk, page, offset, size, flags);
823         return sock_no_sendpage(sock, page, offset, size, flags);
824 }
825
826
827 int inet_shutdown(struct socket *sock, int how)
828 {
829         struct sock *sk = sock->sk;
830         int err = 0;
831
832         /* This should really check to make sure
833          * the socket is a TCP socket. (WHY AC...)
834          */
835         how++; /* maps 0->1 has the advantage of making bit 1 rcvs and
836                        1->2 bit 2 snds.
837                        2->3 */
838         if ((how & ~SHUTDOWN_MASK) || !how)     /* MAXINT->0 */
839                 return -EINVAL;
840
841         lock_sock(sk);
842         if (sock->state == SS_CONNECTING) {
843                 if ((1 << sk->sk_state) &
844                     (TCPF_SYN_SENT | TCPF_SYN_RECV | TCPF_CLOSE))
845                         sock->state = SS_DISCONNECTING;
846                 else
847                         sock->state = SS_CONNECTED;
848         }
849
850         switch (sk->sk_state) {
851         case TCP_CLOSE:
852                 err = -ENOTCONN;
853                 /* Hack to wake up other listeners, who can poll for
854                    POLLHUP, even on eg. unconnected UDP sockets -- RR */
855         default:
856                 sk->sk_shutdown |= how;
857                 if (sk->sk_prot->shutdown)
858                         sk->sk_prot->shutdown(sk, how);
859                 break;
860
861         /* Remaining two branches are temporary solution for missing
862          * close() in multithreaded environment. It is _not_ a good idea,
863          * but we have no choice until close() is repaired at VFS level.
864          */
865         case TCP_LISTEN:
866                 if (!(how & RCV_SHUTDOWN))
867                         break;
868                 /* Fall through */
869         case TCP_SYN_SENT:
870                 err = sk->sk_prot->disconnect(sk, O_NONBLOCK);
871                 sock->state = err ? SS_DISCONNECTING : SS_UNCONNECTED;
872                 break;
873         }
874
875         /* Wake up anyone sleeping in poll. */
876         sk->sk_state_change(sk);
877         release_sock(sk);
878         return err;
879 }
880
881 /*
882  *      ioctl() calls you can issue on an INET socket. Most of these are
883  *      device configuration and stuff and very rarely used. Some ioctls
884  *      pass on to the socket itself.
885  *
886  *      NOTE: I like the idea of a module for the config stuff. ie ifconfig
887  *      loads the devconfigure module does its configuring and unloads it.
888  *      There's a good 20K of config code hanging around the kernel.
889  */
890
891 int inet_ioctl(struct socket *sock, unsigned int cmd, unsigned long arg)
892 {
893         struct sock *sk = sock->sk;
894         int err = 0;
895
896         switch (cmd) {
897                 case SIOCGSTAMP:
898                         err = sock_get_timestamp(sk, (struct timeval __user *)arg);
899                         break;
900                 case SIOCADDRT:
901                 case SIOCDELRT:
902                 case SIOCRTMSG:
903                         err = ip_rt_ioctl(cmd, (void *)arg);
904                         break;
905                 case SIOCDARP:
906                 case SIOCGARP:
907                 case SIOCSARP:
908                         err = arp_ioctl(cmd, (void __user *)arg);
909                         break;
910                 case SIOCGIFADDR:
911                 case SIOCSIFADDR:
912                 case SIOCGIFBRDADDR:
913                 case SIOCSIFBRDADDR:
914                 case SIOCGIFNETMASK:
915                 case SIOCSIFNETMASK:
916                 case SIOCGIFDSTADDR:
917                 case SIOCSIFDSTADDR:
918                 case SIOCSIFPFLAGS:
919                 case SIOCGIFPFLAGS:
920                 case SIOCSIFFLAGS:
921                         err = devinet_ioctl(cmd, (void __user *)arg);
922                         break;
923                 default:
924                         if (!sk->sk_prot->ioctl ||
925                             (err = sk->sk_prot->ioctl(sk, cmd, arg)) ==
926                                                                 -ENOIOCTLCMD)
927                                 err = dev_ioctl(cmd, (void __user *)arg);
928                         break;
929         }
930         return err;
931 }
932
933 struct proto_ops inet_stream_ops = {
934         .family =       PF_INET,
935         .owner =        THIS_MODULE,
936         .release =      inet_release,
937         .bind =         inet_bind,
938         .connect =      inet_stream_connect,
939         .socketpair =   sock_no_socketpair,
940         .accept =       inet_accept,
941         .getname =      inet_getname,
942         .poll =         tcp_poll,
943         .ioctl =        inet_ioctl,
944         .listen =       inet_listen,
945         .shutdown =     inet_shutdown,
946         .setsockopt =   inet_setsockopt,
947         .getsockopt =   inet_getsockopt,
948         .sendmsg =      inet_sendmsg,
949         .recvmsg =      inet_recvmsg,
950         .mmap =         sock_no_mmap,
951         .sendpage =     tcp_sendpage
952 };
953
954 struct proto_ops inet_dgram_ops = {
955         .family =       PF_INET,
956         .owner =        THIS_MODULE,
957         .release =      inet_release,
958         .bind =         inet_bind,
959         .connect =      inet_dgram_connect,
960         .socketpair =   sock_no_socketpair,
961         .accept =       sock_no_accept,
962         .getname =      inet_getname,
963         .poll =         datagram_poll,
964         .ioctl =        inet_ioctl,
965         .listen =       sock_no_listen,
966         .shutdown =     inet_shutdown,
967         .setsockopt =   inet_setsockopt,
968         .getsockopt =   inet_getsockopt,
969         .sendmsg =      inet_sendmsg,
970         .recvmsg =      inet_recvmsg,
971         .mmap =         sock_no_mmap,
972         .sendpage =     inet_sendpage,
973 };
974
975 struct net_proto_family inet_family_ops = {
976         .family = PF_INET,
977         .create = inet_create,
978         .owner  = THIS_MODULE,
979 };
980
981
982 extern void tcp_init(void);
983 extern void tcp_v4_init(struct net_proto_family *);
984
985 /* Upon startup we insert all the elements in inetsw_array[] into
986  * the linked list inetsw.
987  */
988 static struct inet_protosw inetsw_array[] =
989 {
990         {
991                 .type =       SOCK_STREAM,
992                 .protocol =   IPPROTO_TCP,
993                 .prot =       &tcp_prot,
994                 .ops =        &inet_stream_ops,
995                 .capability = -1,
996                 .no_check =   0,
997                 .flags =      INET_PROTOSW_PERMANENT,
998         },
999
1000         {
1001                 .type =       SOCK_DGRAM,
1002                 .protocol =   IPPROTO_UDP,
1003                 .prot =       &udp_prot,
1004                 .ops =        &inet_dgram_ops,
1005                 .capability = -1,
1006                 .no_check =   UDP_CSUM_DEFAULT,
1007                 .flags =      INET_PROTOSW_PERMANENT,
1008        },
1009         
1010
1011        {
1012                .type =       SOCK_RAW,
1013                .protocol =   IPPROTO_IP,        /* wild card */
1014                .prot =       &raw_prot,
1015                .ops =        &inet_dgram_ops,
1016                .capability = CAP_NET_RAW,
1017                .no_check =   UDP_CSUM_DEFAULT,
1018                .flags =      INET_PROTOSW_REUSE,
1019        }
1020 };
1021
1022 #define INETSW_ARRAY_LEN (sizeof(inetsw_array) / sizeof(struct inet_protosw))
1023
1024 void inet_register_protosw(struct inet_protosw *p)
1025 {
1026         struct list_head *lh;
1027         struct inet_protosw *answer;
1028         int protocol = p->protocol;
1029         struct list_head *last_perm;
1030
1031         spin_lock_bh(&inetsw_lock);
1032
1033         if (p->type >= SOCK_MAX)
1034                 goto out_illegal;
1035
1036         /* If we are trying to override a permanent protocol, bail. */
1037         answer = NULL;
1038         last_perm = &inetsw[p->type];
1039         list_for_each(lh, &inetsw[p->type]) {
1040                 answer = list_entry(lh, struct inet_protosw, list);
1041
1042                 /* Check only the non-wild match. */
1043                 if (INET_PROTOSW_PERMANENT & answer->flags) {
1044                         if (protocol == answer->protocol)
1045                                 break;
1046                         last_perm = lh;
1047                 }
1048
1049                 answer = NULL;
1050         }
1051         if (answer)
1052                 goto out_permanent;
1053
1054         /* Add the new entry after the last permanent entry if any, so that
1055          * the new entry does not override a permanent entry when matched with
1056          * a wild-card protocol. But it is allowed to override any existing
1057          * non-permanent entry.  This means that when we remove this entry, the 
1058          * system automatically returns to the old behavior.
1059          */
1060         list_add_rcu(&p->list, last_perm);
1061 out:
1062         spin_unlock_bh(&inetsw_lock);
1063
1064         synchronize_net();
1065
1066         return;
1067
1068 out_permanent:
1069         printk(KERN_ERR "Attempt to override permanent protocol %d.\n",
1070                protocol);
1071         goto out;
1072
1073 out_illegal:
1074         printk(KERN_ERR
1075                "Ignoring attempt to register invalid socket type %d.\n",
1076                p->type);
1077         goto out;
1078 }
1079
1080 void inet_unregister_protosw(struct inet_protosw *p)
1081 {
1082         if (INET_PROTOSW_PERMANENT & p->flags) {
1083                 printk(KERN_ERR
1084                        "Attempt to unregister permanent protocol %d.\n",
1085                        p->protocol);
1086         } else {
1087                 spin_lock_bh(&inetsw_lock);
1088                 list_del_rcu(&p->list);
1089                 spin_unlock_bh(&inetsw_lock);
1090
1091                 synchronize_net();
1092         }
1093 }
1094
1095 #ifdef CONFIG_IP_MULTICAST
1096 static struct inet_protocol igmp_protocol = {
1097         .handler =      igmp_rcv,
1098 };
1099 #endif
1100
1101 static struct inet_protocol tcp_protocol = {
1102         .handler =      tcp_v4_rcv,
1103         .err_handler =  tcp_v4_err,
1104         .no_policy =    1,
1105 };
1106
1107 static struct inet_protocol udp_protocol = {
1108         .handler =      udp_rcv,
1109         .err_handler =  udp_err,
1110         .no_policy =    1,
1111 };
1112
1113 static struct inet_protocol icmp_protocol = {
1114         .handler =      icmp_rcv,
1115 };
1116
1117 static int __init init_ipv4_mibs(void)
1118 {
1119         net_statistics[0] = alloc_percpu(struct linux_mib);
1120         net_statistics[1] = alloc_percpu(struct linux_mib);
1121         ip_statistics[0] = alloc_percpu(struct ipstats_mib);
1122         ip_statistics[1] = alloc_percpu(struct ipstats_mib);
1123         icmp_statistics[0] = alloc_percpu(struct icmp_mib);
1124         icmp_statistics[1] = alloc_percpu(struct icmp_mib);
1125         tcp_statistics[0] = alloc_percpu(struct tcp_mib);
1126         tcp_statistics[1] = alloc_percpu(struct tcp_mib);
1127         udp_statistics[0] = alloc_percpu(struct udp_mib);
1128         udp_statistics[1] = alloc_percpu(struct udp_mib);
1129         if (!
1130             (net_statistics[0] && net_statistics[1] && ip_statistics[0]
1131              && ip_statistics[1] && tcp_statistics[0] && tcp_statistics[1]
1132              && udp_statistics[0] && udp_statistics[1]))
1133                 return -ENOMEM;
1134
1135         (void) tcp_mib_init();
1136
1137         return 0;
1138 }
1139
1140 int ipv4_proc_init(void);
1141 extern void ipfrag_init(void);
1142
1143 static int __init inet_init(void)
1144 {
1145         struct sk_buff *dummy_skb;
1146         struct inet_protosw *q;
1147         struct list_head *r;
1148
1149         if (sizeof(struct inet_skb_parm) > sizeof(dummy_skb->cb)) {
1150                 printk(KERN_CRIT "%s: panic\n", __FUNCTION__);
1151                 return -EINVAL;
1152         }
1153
1154         tcp_sk_cachep = kmem_cache_create("tcp_sock",
1155                                           sizeof(struct tcp_sock), 0,
1156                                           SLAB_HWCACHE_ALIGN, 0, 0);
1157         udp_sk_cachep = kmem_cache_create("udp_sock",
1158                                           sizeof(struct udp_sock), 0,
1159                                           SLAB_HWCACHE_ALIGN, 0, 0);
1160         raw4_sk_cachep = kmem_cache_create("raw4_sock",
1161                                            sizeof(struct raw_sock), 0,
1162                                            SLAB_HWCACHE_ALIGN, 0, 0);
1163         if (!tcp_sk_cachep || !udp_sk_cachep || !raw4_sk_cachep)
1164                 printk(KERN_CRIT
1165                        "inet_init: Can't create protocol sock SLAB caches!\n");
1166         /*
1167          *      Tell SOCKET that we are alive... 
1168          */
1169
1170         (void)sock_register(&inet_family_ops);
1171
1172         /*
1173          *      Add all the base protocols.
1174          */
1175
1176         if (inet_add_protocol(&icmp_protocol, IPPROTO_ICMP) < 0)
1177                 printk(KERN_CRIT "inet_init: Cannot add ICMP protocol\n");
1178         if (inet_add_protocol(&udp_protocol, IPPROTO_UDP) < 0)
1179                 printk(KERN_CRIT "inet_init: Cannot add UDP protocol\n");
1180         if (inet_add_protocol(&tcp_protocol, IPPROTO_TCP) < 0)
1181                 printk(KERN_CRIT "inet_init: Cannot add TCP protocol\n");
1182 #ifdef CONFIG_IP_MULTICAST
1183         if (inet_add_protocol(&igmp_protocol, IPPROTO_IGMP) < 0)
1184                 printk(KERN_CRIT "inet_init: Cannot add IGMP protocol\n");
1185 #endif
1186
1187         /* Register the socket-side information for inet_create. */
1188         for (r = &inetsw[0]; r < &inetsw[SOCK_MAX]; ++r)
1189                 INIT_LIST_HEAD(r);
1190
1191         for (q = inetsw_array; q < &inetsw_array[INETSW_ARRAY_LEN]; ++q)
1192                 inet_register_protosw(q);
1193
1194         /*
1195          *      Set the ARP module up
1196          */
1197
1198         arp_init();
1199
1200         /*
1201          *      Set the IP module up
1202          */
1203
1204         ip_init();
1205
1206         tcp_v4_init(&inet_family_ops);
1207
1208         /* Setup TCP slab cache for open requests. */
1209         tcp_init();
1210
1211
1212         /*
1213          *      Set the ICMP layer up
1214          */
1215
1216         icmp_init(&inet_family_ops);
1217
1218         /*
1219          *      Initialise the multicast router
1220          */
1221 #if defined(CONFIG_IP_MROUTE)
1222         ip_mr_init();
1223 #endif
1224         /*
1225          *      Initialise per-cpu ipv4 mibs
1226          */ 
1227
1228         if(init_ipv4_mibs())
1229                 printk(KERN_CRIT "inet_init: Cannot init ipv4 mibs\n"); ;
1230         
1231         ipv4_proc_init();
1232
1233         ipfrag_init();
1234
1235         return 0;
1236 }
1237
1238 module_init(inet_init);
1239
1240 /* ------------------------------------------------------------------------ */
1241
1242 #ifdef CONFIG_PROC_FS
1243 extern int  fib_proc_init(void);
1244 extern void fib_proc_exit(void);
1245 extern int  ip_misc_proc_init(void);
1246 extern int  raw_proc_init(void);
1247 extern void raw_proc_exit(void);
1248 extern int  tcp4_proc_init(void);
1249 extern void tcp4_proc_exit(void);
1250 extern int  udp4_proc_init(void);
1251 extern void udp4_proc_exit(void);
1252
1253 int __init ipv4_proc_init(void)
1254 {
1255         int rc = 0;
1256
1257         if (raw_proc_init())
1258                 goto out_raw;
1259         if (tcp4_proc_init())
1260                 goto out_tcp;
1261         if (udp4_proc_init())
1262                 goto out_udp;
1263         if (fib_proc_init())
1264                 goto out_fib;
1265         if (ip_misc_proc_init())
1266                 goto out_misc;
1267 out:
1268         return rc;
1269 out_misc:
1270         fib_proc_exit();
1271 out_fib:
1272         udp4_proc_exit();
1273 out_udp:
1274         tcp4_proc_exit();
1275 out_tcp:
1276         raw_proc_exit();
1277 out_raw:
1278         rc = -ENOMEM;
1279         goto out;
1280 }
1281
1282 #else /* CONFIG_PROC_FS */
1283 int __init ipv4_proc_init(void)
1284 {
1285         return 0;
1286 }
1287 #endif /* CONFIG_PROC_FS */
1288
1289 MODULE_ALIAS_NETPROTO(PF_INET);
1290
1291 EXPORT_SYMBOL(inet_accept);
1292 EXPORT_SYMBOL(inet_bind);
1293 EXPORT_SYMBOL(inet_dgram_connect);
1294 EXPORT_SYMBOL(inet_dgram_ops);
1295 EXPORT_SYMBOL(inet_family_ops);
1296 EXPORT_SYMBOL(inet_getname);
1297 EXPORT_SYMBOL(inet_getsockopt);
1298 EXPORT_SYMBOL(inet_ioctl);
1299 EXPORT_SYMBOL(inet_listen);
1300 EXPORT_SYMBOL(inet_recvmsg);
1301 EXPORT_SYMBOL(inet_register_protosw);
1302 EXPORT_SYMBOL(inet_release);
1303 EXPORT_SYMBOL(inet_sendmsg);
1304 EXPORT_SYMBOL(inet_setsockopt);
1305 EXPORT_SYMBOL(inet_shutdown);
1306 EXPORT_SYMBOL(inet_sock_destruct);
1307 EXPORT_SYMBOL(inet_sock_release);
1308 EXPORT_SYMBOL(inet_stream_connect);
1309 EXPORT_SYMBOL(inet_stream_ops);
1310 EXPORT_SYMBOL(inet_unregister_protosw);
1311 EXPORT_SYMBOL(net_statistics);
1312 EXPORT_SYMBOL(tcp_protocol);
1313 EXPORT_SYMBOL(udp_protocol);
1314
1315 #ifdef INET_REFCNT_DEBUG
1316 EXPORT_SYMBOL(inet_sock_nr);
1317 #endif