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

📄 tcp.c

📁 51avr tcpip http协议
💻 C
📖 第 1 页 / 共 2 页
字号:
//-----------------------------------------------------------------------------
// 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 <string.h>
#include <stdlib.h>
#include <ctype.h>		// toupper
#include "net.h"
#include "cksum.h"
#include "ip.h"
#include "http.h"
#include "tcp.h"
#include "timer.h"
#include "general.h"
#include "serial.h"
#include <avr/pgmspace.h>
#include <avr/io.h>


extern ULONG my_ipaddr;
extern char text[];

// These structures keep track of connection information
CONNECTION conxn[5];
ULONG initial_sequence_nr;
UINT sender_tcpport;
static ULONG sender_ipaddr;
UCHAR just_closed; // Keeps track of when a conxn closed
// Options: MSS (4 bytes), NOPS (2 bytes), Selective ACK (2 bytes) 
UCHAR FLASHDATA opt[10] = {0x02, 0x04, 0x05, 0xB4, 0x01, 0x01, 0x04, 0x02};


//------------------------------------------------------------------------
//  Initialize variables declared in this module
//
//------------------------------------------------------------------------
void init_tcp(void)
{
   memset(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
//------------------------------------------------------------------------
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 
   outbuf = (UCHAR *)malloc(34 + hdr_len);
   if (outbuf == NULL)
   {
#ifdef DEBUG
      PrintStr("TCP: Oops, out of memory\n");
#endif
      return;
   }

	   
   tcp = (TCP_HEADER *)(outbuf + 34);
   ip = (IP_HEADER *)(outbuf + 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 = swapint(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 = swapint(HTTP_PORT);
      tcp->dest_port = conxn[nr].port;
      tcp->sequence = swaplong(conxn[nr].my_sequence);
      tcp->ack_number = swaplong(conxn[nr].his_sequence);
      dest = conxn[nr].ipaddr;
   }
   else
   {
#ifdef DEBUG
    	PrintStr("TCP: Oops, sock nr out of range\n");
#endif
		free(outbuf);
		return;
	}

   // Total segment length = header length
      
   // Insert header len
   tcp->flags = swapint((hdr_len << 10) | flags);
   tcp->window = swapint(1024);
   tcp->checksum = 0;
   tcp->urgent_ptr = 0;
   
   // Sending SYN with header options
   if (hdr_len == 28)
   {
      memcpy_P(&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;
		
	// Sum source_ipaddr, dest_ipaddr, and entire TCP message 
	sum = (UINT)cksum(outbuf + 26, 8 + hdr_len);
				
	// Add in the rest of pseudoheader which is
	// protocol id and TCP segment length
	sum += (UINT)0x0600;/////!!!!
	sum += (UINT)swapint(hdr_len);

	// In case there was a carry, add it back around
	result = (UINT)(sum + (sum >> 16));
	tcp->checksum = ~result;
#ifdef DEBUG   
   PrintStr("TCP: Sending msg to IP layer\n");
#endif
	ip_send(outbuf, dest, TCP_TYPE, hdr_len);

   // (Re)start TCP retransmit timer
   conxn[nr].timer = TCP_TIMEOUT;
}




//------------------------------------------------------------------------
// 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--;
         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
            if (conxn[nr].state != STATE_ESTABLISHED)
            {
               // Send reset and close connection
#ifdef DEBUG
               PrintStr("TCP: Timeout, sending reset\n");
#endif
               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 (swaplong(conxn[nr].his_ack) > conxn[nr].my_sequence)
               {
                  // Send reset and close connection
#ifdef DEBUG
                  PrintStr("TCP: Timeout, sending reset\n");
#endif
                  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 (swaplong(conxn[nr].his_ack) < conxn[nr].my_sequence)
			   {
                  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
#ifdef DEBUG
                  	PrintStr("TCP: Timeout, resending data\n");
#endif
                  	http_server(conxn[nr].query, 0, nr, 1);
			        conxn[nr].inactivity = INACTIVITY_TIME;
                  }
				  else
				  {
#ifdef DEBUG
					PrintStr("TCP: Giving up, sending reset\n");
#endif
					// Send reset and close connection
               		tcp_send(FLG_RST, 20, nr);
               		conxn[nr].ipaddr = 0;
               	  }
               }
            }
         }
      }
   }
}




//------------------------------------------------------------------------
// This runs every 0.5 seconds.  If the connection has had no activity
// it initiates closing the connection.
//
//------------------------------------------------------------------------
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))
      {
         // 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;
#ifdef DEBUG
            PrintStr("TCP: Entered FIN_WAIT_1 state\n");	
#endif
         }
      }
   }
}



//------------------------------------------------------------------------
// 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
//------------------------------------------------------------------------
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);
				   
	// Compute TCP checksum including 12 byte pseudoheader
	// Sum source_ipaddr, dest_ipaddr, and entire TCP message 
	sum = (UINT)cksum(inbuf + 26, 8 + len);

	// Add in the rest of pseudoheader which is
	// protocol id and TCP segment length
	sum += (UINT)0x600;////!!!!
	sum += (UINT)swapint(len);

	// In case there was a carry, add it back around
	result = (UINT)(sum + (sum >> 16));

	if (result != 0xFFFF)
	{
#ifdef DEBUG
		PrintStr("TCP: Error, bad cksum\n");
#endif
        return;
    }
#ifdef DEBUG
	PrintStr("TCP: Msg rcvd with good cksum\n");
#endif
   
	// See if message is for http server
	if (swapint(tcp->dest_port) != HTTP_PORT)	
   {
#ifdef DEBUG
      
         PrintStr("TCP: Error, msg to port\n ");
         memset(text, 0, 10);
         itoa(tcp->dest_port, text, 10);
         PrintStr(text);
		 PrintStr("\n");
#endif
      tcp_send(FLG_RST, 20, NO_CONNECTION);
      return;
   }
   
   // Capture sender's IP address and port number
   sender_ipaddr = ip->source_ipaddr;
   sender_tcpport = tcp->source_port;
   
   // See if the TCP segment is from someone we are already
   // connected to. 
   for (i=0; i < 5; i++)
   {
      if ((ip->source_ipaddr == conxn[i].ipaddr) &&
         (tcp->source_port == conxn[i].port))
      {   
         nr = i;
#ifdef DEBUG
         PrintStr("TCP: Rcvd msg from existing conxn\n");
#endif
         break;
      }       
   }
   
   // If i = 5, we are not connected. If it is a SYN then assign
   // a temporary conection  to it for processing
   if (i == 5)
   {
      if (swapint(tcp->flags) & FLG_SYN)
      {
         // Find first unused connection (one with IP = 0) 
         for (j=0; j < 5; j++)
         {
            if (conxn[j].ipaddr == 0)
            {

⌨️ 快捷键说明

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