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