⭐ 欢迎来到虫虫下载站! | 📦 资源下载 📁 资源专辑 ℹ️ 关于我们
⭐ 虫虫下载站

📄 tcp_ipv4.c

📁 linux 内核源代码
💻 C
📖 第 1 页 / 共 5 页
字号:
/* * INET		An implementation of the TCP/IP protocol suite for the LINUX *		operating system.  INET is implemented using the  BSD Socket *		interface as the means of communication with the user level. * *		Implementation of the Transmission Control Protocol(TCP). * * Version:	$Id: tcp_ipv4.c,v 1.240 2002/02/01 22:01:04 davem Exp $ * *		IPv4 specific functions * * *		code split from: *		linux/ipv4/tcp.c *		linux/ipv4/tcp_input.c *		linux/ipv4/tcp_output.c * *		See tcp.c for author information * *	This program is free software; you can redistribute it and/or *      modify it under the terms of the GNU General Public License *      as published by the Free Software Foundation; either version *      2 of the License, or (at your option) any later version. *//* * Changes: *		David S. Miller	:	New socket lookup architecture. *					This code is dedicated to John Dyson. *		David S. Miller :	Change semantics of established hash, *					half is devoted to TIME_WAIT sockets *					and the rest go in the other half. *		Andi Kleen :		Add support for syncookies and fixed *					some bugs: ip options weren't passed to *					the TCP layer, missed a check for an *					ACK bit. *		Andi Kleen :		Implemented fast path mtu discovery. *	     				Fixed many serious bugs in the *					request_sock handling and moved *					most of it into the af independent code. *					Added tail drop and some other bugfixes. *					Added new listen semantics. *		Mike McLagan	:	Routing by source *	Juan Jose Ciarlante:		ip_dynaddr bits *		Andi Kleen:		various fixes. *	Vitaly E. Lavrov	:	Transparent proxy revived after year *					coma. *	Andi Kleen		:	Fix new listen. *	Andi Kleen		:	Fix accept error reporting. *	YOSHIFUJI Hideaki @USAGI and:	Support IPV6_V6ONLY socket option, which *	Alexey Kuznetsov		allow both IPv4 and IPv6 sockets to bind *					a single port at the same time. */#include <linux/types.h>#include <linux/fcntl.h>#include <linux/module.h>#include <linux/random.h>#include <linux/cache.h>#include <linux/jhash.h>#include <linux/init.h>#include <linux/times.h>#include <net/net_namespace.h>#include <net/icmp.h>#include <net/inet_hashtables.h>#include <net/tcp.h>#include <net/transp_v6.h>#include <net/ipv6.h>#include <net/inet_common.h>#include <net/timewait_sock.h>#include <net/xfrm.h>#include <net/netdma.h>#include <linux/inet.h>#include <linux/ipv6.h>#include <linux/stddef.h>#include <linux/proc_fs.h>#include <linux/seq_file.h>#include <linux/crypto.h>#include <linux/scatterlist.h>int sysctl_tcp_tw_reuse __read_mostly;int sysctl_tcp_low_latency __read_mostly;/* Check TCP sequence numbers in ICMP packets. */#define ICMP_MIN_LENGTH 8/* Socket used for sending RSTs */static struct socket *tcp_socket __read_mostly;void tcp_v4_send_check(struct sock *sk, int len, struct sk_buff *skb);#ifdef CONFIG_TCP_MD5SIGstatic struct tcp_md5sig_key *tcp_v4_md5_do_lookup(struct sock *sk,						   __be32 addr);static int tcp_v4_do_calc_md5_hash(char *md5_hash, struct tcp_md5sig_key *key,				   __be32 saddr, __be32 daddr,				   struct tcphdr *th, int protocol,				   int tcplen);#endifstruct inet_hashinfo __cacheline_aligned tcp_hashinfo = {	.lhash_lock  = __RW_LOCK_UNLOCKED(tcp_hashinfo.lhash_lock),	.lhash_users = ATOMIC_INIT(0),	.lhash_wait  = __WAIT_QUEUE_HEAD_INITIALIZER(tcp_hashinfo.lhash_wait),};static int tcp_v4_get_port(struct sock *sk, unsigned short snum){	return inet_csk_get_port(&tcp_hashinfo, sk, snum,				 inet_csk_bind_conflict);}static void tcp_v4_hash(struct sock *sk){	inet_hash(&tcp_hashinfo, sk);}void tcp_unhash(struct sock *sk){	inet_unhash(&tcp_hashinfo, sk);}static inline __u32 tcp_v4_init_sequence(struct sk_buff *skb){	return secure_tcp_sequence_number(ip_hdr(skb)->daddr,					  ip_hdr(skb)->saddr,					  tcp_hdr(skb)->dest,					  tcp_hdr(skb)->source);}int tcp_twsk_unique(struct sock *sk, struct sock *sktw, void *twp){	const struct tcp_timewait_sock *tcptw = tcp_twsk(sktw);	struct tcp_sock *tp = tcp_sk(sk);	/* With PAWS, it is safe from the viewpoint	   of data integrity. Even without PAWS it is safe provided sequence	   spaces do not overlap i.e. at data rates <= 80Mbit/sec.	   Actually, the idea is close to VJ's one, only timestamp cache is	   held not per host, but per port pair and TW bucket is used as state	   holder.	   If TW bucket has been already destroyed we fall back to VJ's scheme	   and use initial timestamp retrieved from peer table.	 */	if (tcptw->tw_ts_recent_stamp &&	    (twp == NULL || (sysctl_tcp_tw_reuse &&			     get_seconds() - tcptw->tw_ts_recent_stamp > 1))) {		tp->write_seq = tcptw->tw_snd_nxt + 65535 + 2;		if (tp->write_seq == 0)			tp->write_seq = 1;		tp->rx_opt.ts_recent	   = tcptw->tw_ts_recent;		tp->rx_opt.ts_recent_stamp = tcptw->tw_ts_recent_stamp;		sock_hold(sktw);		return 1;	}	return 0;}EXPORT_SYMBOL_GPL(tcp_twsk_unique);/* This will initiate an outgoing connection. */int tcp_v4_connect(struct sock *sk, struct sockaddr *uaddr, int addr_len){	struct inet_sock *inet = inet_sk(sk);	struct tcp_sock *tp = tcp_sk(sk);	struct sockaddr_in *usin = (struct sockaddr_in *)uaddr;	struct rtable *rt;	__be32 daddr, nexthop;	int tmp;	int err;	if (addr_len < sizeof(struct sockaddr_in))		return -EINVAL;	if (usin->sin_family != AF_INET)		return -EAFNOSUPPORT;	nexthop = daddr = usin->sin_addr.s_addr;	if (inet->opt && inet->opt->srr) {		if (!daddr)			return -EINVAL;		nexthop = inet->opt->faddr;	}	tmp = ip_route_connect(&rt, nexthop, inet->saddr,			       RT_CONN_FLAGS(sk), sk->sk_bound_dev_if,			       IPPROTO_TCP,			       inet->sport, usin->sin_port, sk, 1);	if (tmp < 0) {		if (tmp == -ENETUNREACH)			IP_INC_STATS_BH(IPSTATS_MIB_OUTNOROUTES);		return tmp;	}	if (rt->rt_flags & (RTCF_MULTICAST | RTCF_BROADCAST)) {		ip_rt_put(rt);		return -ENETUNREACH;	}	if (!inet->opt || !inet->opt->srr)		daddr = rt->rt_dst;	if (!inet->saddr)		inet->saddr = rt->rt_src;	inet->rcv_saddr = inet->saddr;	if (tp->rx_opt.ts_recent_stamp && inet->daddr != daddr) {		/* Reset inherited state */		tp->rx_opt.ts_recent	   = 0;		tp->rx_opt.ts_recent_stamp = 0;		tp->write_seq		   = 0;	}	if (tcp_death_row.sysctl_tw_recycle &&	    !tp->rx_opt.ts_recent_stamp && rt->rt_dst == daddr) {		struct inet_peer *peer = rt_get_peer(rt);		/*		 * VJ's idea. We save last timestamp seen from		 * the destination in peer table, when entering state		 * TIME-WAIT * and initialize rx_opt.ts_recent from it,		 * when trying new connection.		 */		if (peer != NULL &&		    peer->tcp_ts_stamp + TCP_PAWS_MSL >= get_seconds()) {			tp->rx_opt.ts_recent_stamp = peer->tcp_ts_stamp;			tp->rx_opt.ts_recent = peer->tcp_ts;		}	}	inet->dport = usin->sin_port;	inet->daddr = daddr;	inet_csk(sk)->icsk_ext_hdr_len = 0;	if (inet->opt)		inet_csk(sk)->icsk_ext_hdr_len = inet->opt->optlen;	tp->rx_opt.mss_clamp = 536;	/* Socket identity is still unknown (sport may be zero).	 * However we set state to SYN-SENT and not releasing socket	 * lock select source port, enter ourselves into the hash tables and	 * complete initialization after this.	 */	tcp_set_state(sk, TCP_SYN_SENT);	err = inet_hash_connect(&tcp_death_row, sk);	if (err)		goto failure;	err = ip_route_newports(&rt, IPPROTO_TCP,				inet->sport, inet->dport, sk);	if (err)		goto failure;	/* OK, now commit destination to socket.  */	sk->sk_gso_type = SKB_GSO_TCPV4;	sk_setup_caps(sk, &rt->u.dst);	if (!tp->write_seq)		tp->write_seq = secure_tcp_sequence_number(inet->saddr,							   inet->daddr,							   inet->sport,							   usin->sin_port);	inet->id = tp->write_seq ^ jiffies;	err = tcp_connect(sk);	rt = NULL;	if (err)		goto failure;	return 0;failure:	/*	 * This unhashes the socket and releases the local port,	 * if necessary.	 */	tcp_set_state(sk, TCP_CLOSE);	ip_rt_put(rt);	sk->sk_route_caps = 0;	inet->dport = 0;	return err;}/* * This routine does path mtu discovery as defined in RFC1191. */static void do_pmtu_discovery(struct sock *sk, struct iphdr *iph, u32 mtu){	struct dst_entry *dst;	struct inet_sock *inet = inet_sk(sk);	/* We are not interested in TCP_LISTEN and open_requests (SYN-ACKs	 * send out by Linux are always <576bytes so they should go through	 * unfragmented).	 */	if (sk->sk_state == TCP_LISTEN)		return;	/* We don't check in the destentry if pmtu discovery is forbidden	 * on this route. We just assume that no packet_to_big packets	 * are send back when pmtu discovery is not active.	 * There is a small race when the user changes this flag in the	 * route, but I think that's acceptable.	 */	if ((dst = __sk_dst_check(sk, 0)) == NULL)		return;	dst->ops->update_pmtu(dst, mtu);	/* Something is about to be wrong... Remember soft error	 * for the case, if this connection will not able to recover.	 */	if (mtu < dst_mtu(dst) && ip_dont_fragment(sk, dst))		sk->sk_err_soft = EMSGSIZE;	mtu = dst_mtu(dst);	if (inet->pmtudisc != IP_PMTUDISC_DONT &&	    inet_csk(sk)->icsk_pmtu_cookie > mtu) {		tcp_sync_mss(sk, mtu);		/* Resend the TCP packet because it's		 * clear that the old packet has been		 * dropped. This is the new "fast" path mtu		 * discovery.		 */		tcp_simple_retransmit(sk);	} /* else let the usual retransmit timer handle it */}/* * This routine is called by the ICMP module when it gets some * sort of error condition.  If err < 0 then the socket should * be closed and the error returned to the user.  If err > 0 * it's just the icmp type << 8 | icmp code.  After adjustment * header points to the first 8 bytes of the tcp header.  We need * to find the appropriate port. * * The locking strategy used here is very "optimistic". When * someone else accesses the socket the ICMP is just dropped * and for some paths there is no check at all. * A more general error queue to queue errors for later handling * is probably better. * */void tcp_v4_err(struct sk_buff *skb, u32 info){	struct iphdr *iph = (struct iphdr *)skb->data;	struct tcphdr *th = (struct tcphdr *)(skb->data + (iph->ihl << 2));	struct tcp_sock *tp;	struct inet_sock *inet;	const int type = icmp_hdr(skb)->type;	const int code = icmp_hdr(skb)->code;	struct sock *sk;	__u32 seq;	int err;	if (skb->len < (iph->ihl << 2) + 8) {		ICMP_INC_STATS_BH(ICMP_MIB_INERRORS);		return;	}	sk = inet_lookup(&tcp_hashinfo, iph->daddr, th->dest, iph->saddr,			 th->source, inet_iif(skb));	if (!sk) {		ICMP_INC_STATS_BH(ICMP_MIB_INERRORS);		return;	}	if (sk->sk_state == TCP_TIME_WAIT) {		inet_twsk_put(inet_twsk(sk));		return;	}	bh_lock_sock(sk);	/* If too many ICMPs get dropped on busy	 * servers this needs to be solved differently.	 */	if (sock_owned_by_user(sk))		NET_INC_STATS_BH(LINUX_MIB_LOCKDROPPEDICMPS);	if (sk->sk_state == TCP_CLOSE)		goto out;	tp = tcp_sk(sk);	seq = ntohl(th->seq);	if (sk->sk_state != TCP_LISTEN &&	    !between(seq, tp->snd_una, tp->snd_nxt)) {		NET_INC_STATS_BH(LINUX_MIB_OUTOFWINDOWICMPS);		goto out;	}	switch (type) {	case ICMP_SOURCE_QUENCH:		/* Just silently ignore these. */		goto out;	case ICMP_PARAMETERPROB:		err = EPROTO;		break;	case ICMP_DEST_UNREACH:		if (code > NR_ICMP_UNREACH)			goto out;		if (code == ICMP_FRAG_NEEDED) { /* PMTU discovery (RFC1191) */			if (!sock_owned_by_user(sk))				do_pmtu_discovery(sk, iph, info);			goto out;		}		err = icmp_err_convert[code].errno;		break;	case ICMP_TIME_EXCEEDED:		err = EHOSTUNREACH;		break;	default:		goto out;	}	switch (sk->sk_state) {		struct request_sock *req, **prev;	case TCP_LISTEN:		if (sock_owned_by_user(sk))			goto out;		req = inet_csk_search_req(sk, &prev, th->dest,					  iph->daddr, iph->saddr);		if (!req)			goto out;		/* ICMPs are not backlogged, hence we cannot get		   an established socket here.		 */		BUG_TRAP(!req->sk);		if (seq != tcp_rsk(req)->snt_isn) {			NET_INC_STATS_BH(LINUX_MIB_OUTOFWINDOWICMPS);			goto out;		}		/*		 * Still in SYN_RECV, just remove it silently.		 * There is no good way to pass the error to the newly		 * created socket, and POSIX does not want network		 * errors returned from accept().		 */		inet_csk_reqsk_queue_drop(sk, req, prev);		goto out;	case TCP_SYN_SENT:	case TCP_SYN_RECV:  /* Cannot happen.			       It can f.e. if SYNs crossed.			     */		if (!sock_owned_by_user(sk)) {			sk->sk_err = err;			sk->sk_error_report(sk);			tcp_done(sk);		} else {			sk->sk_err_soft = err;		}		goto out;	}	/* If we've already connected we will keep trying	 * until we time out, or the user gives up.	 *	 * rfc1122 4.2.3.9 allows to consider as hard errors	 * only PROTO_UNREACH and PORT_UNREACH (well, FRAG_FAILED too,	 * but it is obsoleted by pmtu discovery).	 *	 * Note, that in modern internet, where routing is unreliable	 * and in each dark corner broken firewalls sit, sending random	 * errors ordered by their masters even this two messages finally lose	 * their original sense (even Linux sends invalid PORT_UNREACHs)	 *	 * Now we are in compliance with RFCs.	 *							--ANK (980905)	 */	inet = inet_sk(sk);	if (!sock_owned_by_user(sk) && inet->recverr) {		sk->sk_err = err;		sk->sk_error_report(sk);	} else	{ /* Only an error on timeout */		sk->sk_err_soft = err;	}out:

⌨️ 快捷键说明

复制代码 Ctrl + C
搜索代码 Ctrl + F
全屏模式 F11
切换主题 Ctrl + Shift + D
显示快捷键 ?
增大字号 Ctrl + =
减小字号 Ctrl + -