/* IP vrstva komunikacniho modulu pro Ethernet */

#include "stdint.h"
#include "ip.h"
#include "eth.h"
#include "net.h"
#include "net_checksum.h"

extern unsigned char my_MAC[MAC_ADR_SIZE];					// MAC adresa HTTP serveru
extern unsigned char my_IP[IP_ADR_SIZE];					// IP adresa HTTP serveru

/* --------------------------------------------------------------
 Vyplni IP hlavicku a zapise ji do lokalniho paket bufferu
 ------------------------------------------------------------- */
void IP_Set_IP_Header(uint8_t *buffer, uint16_t TotalLen, uint16_t Identification, uint8_t IP_Flags, 
					  uint8_t TTL, uint8_t IP_Protokol, uint8_t *Source_IP, uint8_t *Dest_IP)
{
	unsigned int tmp = 0;
	unsigned char i;
	buffer[OFFSER_IP_Version] = 0xF0&IPv4;							// Verze IP = 0x04 v horni casti byte => 0x40
	buffer[OFFSET_IP_Header_Length] |= 0x0F&(IP_Header_len/4);		// Delka IP hlavicky = pocet 32bitu => 20/4 = 5 (x32bit)
	buffer[OFFSET_IP_ServiceCode] = 0x3F&SC_IP_InternetworkControl;	
	buffer[OFFSET_IP_TotalLength+0] = (0xFF00&TotalLen)>>8;			// Total len = IP header len + TCP header len (plain) + data len
	buffer[OFFSET_IP_TotalLength+1] = (0x00FF&TotalLen);
	buffer[OFFSET_IP_Identification+0] = (0xFF00&Identification)>>8;// Identification byte - nepouzito
	buffer[OFFSET_IP_Identification+1] = (0x00FF&Identification);
	buffer[OFFSET_IP_Flags] = 0xE0&IP_Flags;
	buffer[OFFSET_IP_FragmentOffset+0] = (0x1FFF&0x0000)>>8;		// Fragment offset = 0x0000
	buffer[OFFSET_IP_FragmentOffset+1] = (0x00FF&0x0000);			// Low byte of fragment offset
	buffer[OFFSET_IP_TTL] = TTL;
	buffer[OFFSET_IP_Protokol] = IP_Protokol;						// ICMP/TCP/UDP
	buffer[OFFSET_IP_HeaderChecksum+0] = 0x00;						// Vynulovani IP checksumu
	buffer[OFFSET_IP_HeaderChecksum+1] = 0x00;	
	for(i=0;i<IP_ADR_SIZE;i++)
	{
		buffer[OFFSET_IP_SourceIP+i] = Source_IP[i];				// Source IP
		buffer[OFFSET_IP_DestIP+i] = Dest_IP[i];					// Dest. IP
	}
	tmp = NET_checksum(&buffer[OFFSET_IP_Header], IP_Header_len, IP_TYPE);
	buffer[OFFSET_IP_HeaderChecksum+0] = (0xFF00&tmp)>>8;
	buffer[OFFSET_IP_HeaderChecksum+1] = (0x00FF&tmp);
}

/* ------------------------------------------------------------------
 Zkopiruje TTL z prichoziho paketu (RX) do odchoziho (TX)
 ----------------------------------------------------------------- */
void IP_CopyTTL(unsigned char *RX_buffer, unsigned char *TX_buffer)
{
	TX_buffer[OFFSET_IP_TTL] = RX_buffer[OFFSET_IP_TTL];
}

/* ------------------------------------------------------------------
 Vrati ukazatel na IP adresu zdroje z predaneho bufferu (RX) 
 ----------------------------------------------------------------- */
uint8_t *IP_Get_SourceIP(uint8_t *buffer)
{
	static uint8_t SourceIP[IP_ADR_SIZE];
	uint8_t i;
	
	for(i=0;i<IP_ADR_SIZE;i++)
	{
		SourceIP[i] = buffer[OFFSET_IP_SourceIP+i];
	}
	return(SourceIP);
}
/* Konec souboru */
