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