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