/*********************************************************************************
 * PROJECT: MiMic
 * --------------------------------------------------------------------------------
 *
 * This file is part of MiMic
 * Copyright (C)2011 Ryo Iizuka
 *
 * MiMic is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Lesser General Public License as published
 * by　the Free Software Foundation, either version 3 of the　License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public License
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
 *
 * For further information please contact.
 *	http://nyatla.jp/
 *	<airmail(at)ebony.plala.or.jp> or <nyatla(at)nyatla.jp>
 *
 *
 * Parts of this file were leveraged from uIP:
 *
 * Copyright (c) 2001-2003, Adam Dunkels.
 * All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions
 * are met:
 * 1. Redistributions of source code must retain the above copyright
 *    notice, this list of conditions and the following disclaimer.
 * 2. Redistributions in binary form must reproduce the above copyright
 *    notice, this list of conditions and the following disclaimer in the
 *    documentation and/or other materials provided with the distribution.
 * 3. The name of the author may not be used to endorse or promote
 *    products derived from this software without specific prior
 *    written permission.
 *
 * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS
 * OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
 * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
 * ARE DISCLAIMED.  IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY
 * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE
 * GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
 * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
 * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
 * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
 * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 */
#include "NyLPC_uip.h"
#include "NyLPC_cIPv4Payload_protected.h"




static NyLPC_TUInt16 ipv4id=39;




static void writeTxIpHeader(
	struct NyLPC_TIPv4Header* i_struct,
	NyLPC_TUInt8 i_proto);



/**
 * IPヘッダを送信パケット用に設定する。
 * ipcecksumには0を設定する。
 * この関数は、パケットサイズ,ローカルIP/リモートIPの設定はしない。
 */
static void writeTxIpHeader(
	struct NyLPC_TIPv4Header* i_struct,
	NyLPC_TUInt8 i_proto)
{
	//IPパケットのセット
	i_struct->proto=i_proto;
	i_struct->ttl = UIP_DEFAULT_IP_TTL;
	++ipv4id;//パケットidのインクリメント
	i_struct->tos = 0;
	i_struct->ipoffset=NyLPC_htons(0);
	i_struct->ipid16= NyLPC_htons(ipv4id);
	i_struct->ipchksum = 0;
}
/**
 * TCPヘッダに値をセットする。checksum,wndは0初期化する。
 */
static void setTcpTxHeader(struct NyLPC_TTcpHeader* i_struct,NyLPC_TUInt8 i_flag,const struct uip_conn* i_conn)
{
	i_struct->flags    = i_flag;
	//sorce & destination port
	i_struct->srcport  = i_conn->lport;
	i_struct->destport = i_conn->rport;
	//ACK number
	i_struct->ackno32  = NyLPC_htonl(i_conn->rcv_nxt32);
	//Seq Number
	i_struct->seqno32  = NyLPC_htonl(i_conn->snd_nxt32);
	//uip_func_tcp_send_noconn(BUF);
	i_struct->urgp[0]  = i_struct->urgp[1] = 0;
	i_struct->tcpchksum= 0;
}



/*********************************************************************************
 * public 関数
 *********************************************************************************/




void NyLPC_cIPv4Payload_initialize(NyLPC_TcIPv4Payload_t* i_inst)
{
	return;
}

/**
 * IPパケットを格納したバッファをセットして、ペイロードのポインタを返します。
 * 失敗時はFALSE
 */
NyLPC_TBool NyLPC_cIPv4Payload_setRxBuf(NyLPC_TcIPv4Payload_t* i_inst,void* i_buf,NyLPC_TUInt16 i_flagment_size)
{
	i_inst->header=(struct NyLPC_TIPv4Header*)i_buf;
	i_inst->payload.rawbuf=(NyLPC_TUInt8*)i_buf+(i_inst->header->vhl & 0x0f)*4;
	//IPパケットのバージョンチェック
	if((i_inst->header->vhl & 0xf0)!=0x40){
		NyLPC_OnErrorGoto(Error);
	}
	//IPフレームサイズの調整
	if(NyLPC_ntohs(i_inst->header->len16)>i_flagment_size){
		NyLPC_OnErrorGoto(Error);
	}
	//フラグメントは許可しない。
	if ((NyLPC_ntohs(i_inst->header->ipoffset) & 0x3fff) != 0){
		NyLPC_OnErrorGoto(Error);
	}
	//IPv4ヘッダのチェックサムを確認
	if(!NyLPC_TIPv4Header_isCorrectIpCheckSum(i_inst->header))
	{
		NyLPC_OnErrorGoto(Error);
	}
	return NyLPC_TBool_TRUE;
Error:
	return NyLPC_TBool_FALSE;
}

/**
 * TcpIpのRxバッファをセットします。
 */
void* NyLPC_cIPv4Payload_setTcpRxBuf(NyLPC_TcIPv4Payload_t* i_inst,void* i_buf,NyLPC_TUInt16 i_flagment_size)
{
	if(!NyLPC_cIPv4Payload_setRxBuf(i_inst,i_buf,i_flagment_size)){
		return NULL;
	}
	i_inst->header=(struct NyLPC_TIPv4Header*)i_buf;
	return i_inst->payload.rawbuf+(i_inst->payload.tcp->tcpoffset>>4)*4;
}

/**
 * セット済みのバッファを、TCPの送信ペイロードへ初期化します。
 */
void* NyLPC_cIPv4Payload_initTcpTx(NyLPC_TcIPv4Payload_t* i_inst,NyLPC_TUInt8 i_iph_word,NyLPC_TUInt8 i_tcph_word,NyLPC_TUInt16 i_tcp_payload_size)
{
	i_inst->header->vhl=0x40|(0x0f&i_iph_word);
	i_inst->payload.rawbuf=((NyLPC_TUInt8*)(i_inst->header))+i_iph_word*4;
	i_inst->payload.tcp->tcpoffset=(i_tcph_word<<4);
	i_inst->header->len16=NyLPC_htons(i_tcp_payload_size+((i_iph_word+i_tcph_word)*4));
	return i_inst->payload.rawbuf+(i_tcph_word*4);
}

/**
 * コネクション情報から、TCPのコントロールヘッダをセットします。
 */
void NyLPC_cIPv4Payload_setTcpTxHeaderByConnection(NyLPC_TcIPv4Payload_t* i_inst,const struct uip_conn* i_conn,NyLPC_TUInt8 i_flag)
{
	//IPv4のTxヘッダを書き込む。
	i_inst->header->destipaddr=i_conn->ripaddr;
	i_inst->header->srcipaddr =*(i_conn->lipaddr);
	writeTxIpHeader(i_inst->header,UIP_PROTO_TCP);
	//TCPのTxヘッダを書き込む
	setTcpTxHeader(i_inst->payload.tcp,i_flag,i_conn);
	return;
}

/**
 * 送信バッファをセットする。
 *
 */
void NyLPC_cIPv4Payload_setTxBuf(NyLPC_TcIPv4Payload_t* i_inst,void* i_buf)
{
	i_inst->header=(struct NyLPC_TIPv4Header*)i_buf;
}
void* NyLPC_cIPv4Payload_detachBuf(NyLPC_TcIPv4Payload_t* i_inst)
{
	void* r=i_inst->header;
	NyLPC_ArgAssert(r!=NULL);
	i_inst->header=NULL;
	return r;
}

/**
 * 入力したTCP/IPペイロードをRSTレスポンスに変換する。
 */
void NyLPC_cIPv4Payload_setTcpReverseRstAck(
	NyLPC_TcIPv4Payload_t* i_inst)
{
	struct NyLPC_TIPv4Addr src_addr,dest_addr;
	NyLPC_TUInt32 ack,seq;
	NyLPC_TUInt16 src_port,dest_port;
	struct NyLPC_TTcpHeader* tcp=i_inst->payload.tcp;

	//送信元IP,Portを退避
	src_addr=i_inst->header->srcipaddr;
	dest_addr=i_inst->header->destipaddr;
	dest_port=tcp->destport;
	src_port=tcp->srcport;
	//送信元sq,ackを退避
	ack=tcp->ackno32;
	seq=tcp->seqno32;
	//パケットマップの設定
	NyLPC_cIPv4Payload_initTcpTx(i_inst,0x05,((UIP_TCPH_LEN) / 4),0);
	//ipの設定
	i_inst->header->destipaddr=src_addr;
	i_inst->header->srcipaddr=dest_addr;
	writeTxIpHeader(i_inst->header,UIP_PROTO_TCP);
	//TCP設定
	tcp->flags = TCP_RST | TCP_ACK;
	tcp->tcpoffset = 5<<4;
	tcp->seqno32=ack;
	tcp->ackno32=NyLPC_htonl(NyLPC_ntohl(seq)+1);
	tcp->srcport=dest_port;
	tcp->destport=src_port;
	tcp->urgp[0] = tcp->urgp[1] = 0;
	tcp->wnd16=0;
	i_inst->header->ipchksum = ~(NyLPC_TIPv4Header_makeIpChecksum(i_inst->header));
	i_inst->payload.tcp->tcpchksum=~(NyLPC_TIPv4Header_makeTcpChecksum(i_inst->header));
	return;
}

void NyLPC_cIPv4Payload_setTcpWnd(
	NyLPC_TcIPv4Payload_t* i_inst,
	NyLPC_TUInt16 i_wnd)
{
	i_inst->payload.tcp->wnd16=NyLPC_htons(i_wnd);
}
/**
 * パケットを閉じで完成させる。
 */
void NyLPC_cIPv4Payload_closeTcpTxPacket(
	NyLPC_TcIPv4Payload_t* i_inst)
{
	i_inst->payload.tcp->tcpchksum=~(NyLPC_TIPv4Header_makeTcpChecksum(i_inst->header));
	i_inst->header->ipchksum = ~(NyLPC_TIPv4Header_makeIpChecksum(i_inst->header));
}
/* なんだっけっこれ？
//1の補数v1にv2を加算する。
static NyLPC_TUInt16 add16c(NyLPC_TUInt16 i_v1,NyLPC_TUInt16 i_v2)
{
	NyLPC_TUInt16 t;
	t=i_v1+i_v2;
	return (t>i_v1)?t:t+1;
}
//1の補数v1から、v2を減算する。
static NyLPC_TUInt16 sub16c(NyLPC_TUInt16 i_v1,NyLPC_TUInt16 i_v2)
{
	NyLPC_TUInt16 t;
	t=i_v1-i_v2;
	return (t<i_v1)?t:t-1;
}
*/
/**
 * o_instに、同一なバッファを参照するインスタンスを生成します。
 */
void NyLPC_cIPv4Payload_copyTo(
	const NyLPC_TcIPv4Payload_t* i_inst,
	NyLPC_TcIPv4Payload_t* o_inst)
{
	o_inst->buf_len=i_inst->buf_len;
	o_inst->header=i_inst->header;
	o_inst->payload=i_inst->payload;
}

/**
 * ACK番号を更新する。
 * @param i_ackno
 * ネットワークオーダーのACK番号
 */
void NyLPC_cIPv4Payload_updateAckNo(
	NyLPC_TcIPv4Payload_t* i_inst,
	NyLPC_TUInt32 i_ackno)
{
	NyLPC_Assert(i_inst->header!=NULL);


/*	union{
		NyLPC_TUInt32 l;
		NyLPC_TUInt8 b[4];
	}old_ack,new_ack;
	NyLPC_TUInt16 v1;
	//checksumの計算
	old_ack.l=i_inst->payload.tcp->ackno32;//古いACK番号
	new_ack.l=i_ackno;//新しいACK番号
	v1=NyLPC_ntohs(~(i_inst->payload.tcp->tcpchksum));//1の補数を取って、ホストオーダーに戻す。
	//減算
	v1=sub16c(v1,(old_ack.b[0]<<8)+old_ack.b[1]);
	v1=sub16c(v1,(old_ack.b[2]<<8)+old_ack.b[3]);
	//加算
	v1=add16c(v1,(new_ack.b[0]<<8)+new_ack.b[1]);
	v1=add16c(v1,(new_ack.b[2]<<8)+new_ack.b[3]);
	v1=~NyLPC_htons(v1);*/
NyLPC_Trace();
	i_inst->payload.tcp->ackno32=i_ackno;
NyLPC_Trace();
	i_inst->payload.tcp->tcpchksum = 0;
NyLPC_Trace();
	i_inst->payload.tcp->tcpchksum = ~(NyLPC_TIPv4Header_makeTcpChecksum(i_inst->header));
NyLPC_Trace();

/*
	if((i_inst->payload.tcp->tcpchksum!=v1)){
		NyLPC_Warning();
	}*/
}

