📄 tcp.c
字号:
//-----------------------------------------------------------------------------
// Copyright (c) 2002 Jim Brady
// Do not use commercially without author's permission
// Last revised August 2002
// Net TCP.C
//
// This module handles TCP segments
// Refer to RFC 793, 896, 1122, 1323, 2018, 2581
//
// A "connection" is a unique combination of 4 items: His IP address,
// his port number, my IP address, and my port number.
//
// Note that a SYN and a FIN count as a byte of data, but a RST does
// not count. Neither do any of the other flags.
// See "TCP/IP Illustrated, Volume 1" Sect 17.3 for info on flags
//-----------------------------------------------------------------------------
#include <stdlib.h>
#include <ctype.h> // toupper
#include "net.h"
#include "cksum.h"
#include "serial.h"
#include "ip.h"
#include "tcp.h"
#include "tcpserver.h"
#include "utils.h"
// These structures keep track of connection information
CONNECTION conxn[5];
ulong volatile initial_sequence_nr;
uint volatile sender_tcpport;
static ulong sender_ipaddr;
UCHAR just_closed; // Keeps track of when a conxn closed
extern ulong my_ipaddr;
extern UCHAR debug;
extern char text[];
// Options: MSS (4 bytes), NOPS (2 bytes), Selective ACK (2 bytes)
UCHAR opt[10] = {
0x02, 0x04, 0x05, 0xB4,
0x01, 0x01,
0x04, 0x02};
//------------------------------------------------------------------------
// Initialize variables declared in this module
//
//------------------------------------------------------------------------
void init_tcp(void)
{
memset((char*)conxn, 0, sizeof(conxn));
just_closed = FALSE;
initial_sequence_nr = 1;
}
//------------------------------------------------------------------------
// This sends a TCP segments that do not include any data.
// http_send() in the HTTP module is used to send data.
// See "TCP/IP Illustrated, Volume 1" Sect 17.3
//------------------------------------------------------------------------
//输入参数:
//flags: sun,fin,rst,ack等标志以及数据偏移等的设置;
//hdr_len: TCP报文首部长度
//nr: 连接号
//功能:发送不包含任何数据段的TCP报文,比如请求连接或者说释放连接;
//http_send发送包含数据段的TCP报文.
void tcp_send(uint flags, uint hdr_len, UCHAR nr)
{
ulong sum, dest;
uint result;
UCHAR * outbuf;
TCP_HEADER * tcp;
IP_HEADER * ip;
// Allocate memory for entire outgoing message including
// eth & IP headers
//TCP层申请发送缓冲区,包括TCP和IP以及Eth首部
// outbuf = (UCHAR *)malloc(34 + hdr_len); //每次都申请内存,但不释放?
outbuf = TX_BUFF;
if (outbuf == NULL)
{
// if (debug) serial_send("TCP: Oops, out of memory\n");
return;
}
tcp = (TCP_HEADER *)(outbuf + 34); //IP首部20字节
ip = (IP_HEADER *)(outbuf + 14); //ethernet v2首部14字节
// If no connection, then message is probably a reset
// message which goes back to the sender
// Otherwise, use information from the connection.
if (nr == NO_CONNECTION)
{
tcp->source_port = HTTP_PORT;
tcp->dest_port = sender_tcpport;
tcp->sequence = 0;
tcp->ack_number = 0;
dest = sender_ipaddr;
}
else if (nr < 5)
{
// This message is to connected port
tcp->source_port = HTTP_PORT; //源端口
tcp->dest_port = conxn[nr].port; //目的端口
tcp->sequence = conxn[nr].my_sequence; //序号: 本报文段所发数据的第一个字节的序号
tcp->ack_number = conxn[nr].his_sequence; //确认号: 期望收到对方的下一个报文段的数据的第一个字节的序号
dest = conxn[nr].ipaddr;
}
else
{
// if (debug) serial_send("TCP: Oops, sock nr out of range\n");
free(outbuf);
return;
}
// Total segment length = header length
// Insert header len
tcp->flags = (hdr_len << 10) | flags;
tcp->window = 1024; //窗口: 用来控制对方发送的数据量.
tcp->checksum = 0;
tcp->urgent_ptr = 0; //紧急指针:
// Sending SYN with header options
if (hdr_len == 28)
{
memcpy((char*)tcp->options, opt, 8);
}
// Compute checksum including 12 bytes of pseudoheader
// Must pre-fill 2 items in ip header to do this
ip->dest_ipaddr = dest;
ip->source_ipaddr = my_ipaddr;
#ifdef __LITTLEENDIAN__
tcp->flags = ntohs(tcp->flags);
tcp->window = ntohs(tcp->window);
tcp->source_port = ntohs(tcp->source_port);
tcp->sequence = ntohl(tcp->sequence);
tcp->dest_port = ntohs(tcp->dest_port);
tcp->ack_number = ntohl(tcp->ack_number);
ip->source_ipaddr = ntohl(my_ipaddr);
#endif
// Sum source_ipaddr, dest_ipaddr, and entire TCP message
sum = (ulong)cksum(outbuf + 26, 8 + hdr_len);
// Add in the rest of pseudoheader which is
// protocol id and TCP segment length
sum += (ulong)0x0006;
#ifdef __LITTLEENDIAN__
// hdr_len = ntohs(&hdr_len);
#endif
sum += (ulong)hdr_len;
// In case there was a carry, add it back around
result = (uint)(sum + (sum >> 16));
tcp->checksum = ~result;
#ifdef __LITTLEENDIAN__
tcp->checksum = ntohs(tcp->checksum);
dest = ntohl(dest);
// hdr_len = ntohs(&hdr_len);
#endif
// if (debug) serial_send("TCP: Sending msg to IP layer\n");
ip_send(outbuf, dest, TCP_TYPE, hdr_len);
#ifdef __LITTLEENDIAN__
free(outbuf);
#endif
// (Re)start TCP retransmit timer
// conxn[nr].timer = TCP_TIMEOUT; //重发定时器2
conxn[nr].timer = TCP_TIMEOUT*2;
}
//------------------------------------------------------------------------
// This runs every 0.5 seconds. If the other end has not ACK'd
// everyting we have sent, it re-sends it. To save RAM space, we
// regenerate a segment rather than keeping a bunch of segments
// hanging around eating up RAM. A connection should not be in an
// opening or closing state when this timer expires, so we simply
// send a reset.
//
// If a connection is in the ESTABLISHED state when the timer expires
// then we have just sent a web page so re-send the page
//------------------------------------------------------------------------
void tcp_retransmit(void)
{
static UCHAR retries = 0;
UCHAR nr;
// Scan through all active connections
for (nr = 0; nr < 5; nr++)
{
if ((conxn[nr].ipaddr != 0) && (conxn[nr].timer))
{
// Decrement the timer and see if it hit 0
conxn[nr].timer--;
//如果定时器到, 即2秒,
if (conxn[nr].timer == 0)
{
// Socket just timed out. If we are not in ESTABLISHED state
// something is amiss so send reset and close connection
//不在Established阶段,发送rst要求,释放连接;
if (conxn[nr].state != STATE_ESTABLISHED)
{
// Send reset and close connection
// if (debug) serial_send("TCP: Timeout, sending reset\n");
tcp_send(FLG_RST, 20, nr);
conxn[nr].ipaddr = 0;
return;
}
else
{
// Socket is in ESTABLISHED state. First make sure his
// ack number is not bogus.
if (conxn[nr].his_ack > conxn[nr].my_sequence) //如果当前连接的对端确认号大于本端发送号,乱套了,发送rst请求,释放连接;
{
// Send reset and close connection
// if (debug) serial_send("TCP: Timeout, sending reset\n");
tcp_send(FLG_RST, 20, nr);
conxn[nr].ipaddr = 0;
return;
}
// We always increment our sequence number immediately
// after sending, so the ack number from the other end
// should be equal to our sequence number. If it is less,
// it means he lost some of our data.
if (conxn[nr].his_ack < conxn[nr].my_sequence) //如果当前连接的对端确认号小于本端发送号,定时器到了,需要重发; 但重发次数不大于3
{
retries++;
if (retries <= 2)
{
// The only thing we send is a web page, and it looks
// like other end did not get it, so resend
// but do not increase my sequence number
// if (debug) serial_send("TCP: Timeout, resending data\n");
tcp_server_recv((UCHAR *)conxn[nr].query,0, nr, 1, 40);
conxn[nr].inactivity = INACTIVITY_TIME;
}
else
{
// if (debug) serial_send("TCP: Giving up, sending reset\n");
// Send reset and close connection
tcp_send(FLG_RST, 20, nr);
conxn[nr].ipaddr = 0;
}
}
} //end of else
}
}
}
}
//------------------------------------------------------------------------
// This runs every 0.5 seconds. If the connection has had no activity
// it initiates closing the connection.
//
//------------------------------------------------------------------------
//Timer2定时器每隔0.5秒触发一次tcp_inactivity调用, 保活时间INACTIVITY_TIME = 30. 在Established阶段每收到一次正常的TCP报文就给
//inactivity赋初值30. 若调用30次本事件, 连接还未收到正常TCP报文,向对端发出FIN =1和ACK =1请求, 终止连接请求.
void tcp_inactivity(void)
{
UCHAR nr;
// Look for active connections in the established state
for (nr = 0; nr < 5; nr++)
{
if ((conxn[nr].ipaddr != 0) &&
(conxn[nr].state == STATE_ESTABLISHED) &&
(conxn[nr].inactivity)) //在ESTABLISHED阶段以及ID地址未释放,剩余非激活时间不等于0
{
// Decrement the timer and see if it hit 0
conxn[nr].inactivity--;
if (conxn[nr].inactivity == 0)
{
// Inactivity timer has just timed out.
// Initiate close of connection
tcp_send((FLG_ACK | FLG_FIN), 20, nr);
conxn[nr].my_sequence++; // For my FIN
conxn[nr].state = STATE_FIN_WAIT_1;
// if (debug) serial_send("TCP: Entered FIN_WAIT_1 state\n");
}
}
}
}
//------------------------------------------------------------------------
// This handles incoming TCP messages and manages the TCP state machine
// Note - both the SYN and FIN flags consume a sequence number.
// See "TCP/IP Illustrated, Volume 1" Sect 18.6 for info on TCP states
// See "TCP/IP Illustrated, Volume 1" Sect 17.3 for info on flags
//------------------------------------------------------------------------
//inbuf: TCP/IP协议栈共用接收缓冲区头指针;
//len: TCP报文的总长度(包含首部和数据段)
void tcp_rcve(UCHAR * inbuf, uint len)
{
UCHAR i, j, nr;
uint result, header_len, data_len;
TCP_HEADER * tcp;
IP_HEADER * ip;
ulong sum;
// IP header is always 20 bytes so message starts at index 34
tcp = (TCP_HEADER *)(inbuf + 34);
ip = (IP_HEADER *)(inbuf + 14); //Ethernet V2标准:14 = 目的MAC地址6 byte + 源MAC地址6 byte + 类型(2) = 14, 不包括LLC层
//现不支持: 802.3.
// Compute TCP checksum including 12 byte pseudoheader
// Sum source_ipaddr, dest_ipaddr, and entire TCP message
//校验加上12字节伪首部 + 首部 + 数据段
sum = (ulong)cksum(inbuf + 26, 8 + len); //目的和源IP地址8 byte + TCP报文(包括首部和数据段)的校验和
// Add in the rest of pseudoheader which is
// protocol id and TCP segment length
sum += (ulong)0x0006; //校验和加上protocol id: 0x0006;
#ifdef __LITTLEENDIAN__
// len = ntohs(&len);
#endif
sum += (ulong)len; //校验和加上数据段长度;
// In case there was a carry, add it back around
result = (uint)(sum + (sum >> 16));
if (result != 0xFFFF) //校验和不对,返回
{
// if (debug) serial_send("TCP: Error, bad cksum\n");
return;
}
#ifdef __LITTLEENDIAN__
//用新的方法计算checksun
#endif
// if (debug) serial_send("TCP: Msg rcvd with good cksum\n");
// See if message is for http server
#ifdef __LITTLEENDIAN__
tcp->dest_port = ntohs(tcp->dest_port);
tcp->flags = ntohs(tcp->flags);
tcp->sequence = ntohl(tcp->sequence);
tcp->ack_number = ntohl(tcp->ack_number);
tcp->checksum = ntohs(tcp->checksum);
tcp->source_port = ntohs(tcp->source_port);
#endif
if (tcp->dest_port != HTTP_PORT) //端口非指定端口HTTP_PORT,退出
{
if (debug)
{
// serial_send("TCP: Error, msg to port ");
// memset(text, 10);
// itoa(tcp->dest_port, text, 10);
// serial_send(text);
// serial_send("\n");
}
tcp_send(FLG_RST, 20, NO_CONNECTION);
return;
}
// Capture sender's IP address and port number
sender_ipaddr = ip->source_ipaddr; //取发送方的IP地址和端口
sender_tcpport = tcp->source_port;
// See if the TCP segment is from someone we are already
// connected to.
// 本案支持5个TCP连接. 先查询0-4连接,若其中一个连接的IP地址和端口与接收TCP报文的一致,此TCP报文的连接已有为此连接。
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -