/*********************************************************************************
 * 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_cIPv4Payload_protected.h"


/*

void NyLPC_cIPv4Udp_initialize(
	NyLPC_TcIPv4_t* i_inst,
	const NyLPC_TcIPv4Config_t* i_ref_config);

NyLPC_TBool NyLPC_cIPv4Udp_rx(
	NyLPC_TcIPv4Udp_t* i_inst,
	NyLPC_TcIPv4Payload_t* i_ipp);


*/




/**
 * Removed a UDP connection.
 *
 * \param conn A pointer to the uip_udp_conn structure for the connection.
 *
 * \hideinitializer
 */
#define uip_udp_remove(conn) (conn)->lport = 0
/**
 * Bind a UDP connection to a local port.
 *
 * \param conn A pointer to the uip_udp_conn structure for the
 * connection.
 *
 * \param port The local port number, in network byte order.
 *
 * \hideinitializer
 */
#define uip_udp_bind(conn, port) (conn)->lport = port
//#define ICMPBUF ((struct NyLPC_TIPv4Header *)&uip_buf[UIP_LLH_LEN])
#define UDPBUF ((struct NyLPC_TIPv4Header *)&uip_buf[UIP_LLH_LEN])
static NyLPC_TUInt16 lastport=2048;
/**
 * Representation of a uIP UDP connection.
 */
struct uip_udp_conn {
	struct NyLPC_TIPv4Addr ripaddr;   /**< The IP address of the remote peer. */
	NyLPC_TUInt16 lport;        /**< The local port number in network byte order. */
	NyLPC_TUInt16 rport;        /**< The remote port number in network byte order. */
	NyLPC_TUInt8  ttl;          /**< Default time-to-live. */

  /** The application state. */
  void* appstate;
};

#define UIP_UDP_CONNS 40
extern struct uip_udp_conn *uip_udp_conn;
extern struct uip_udp_conn uip_udp_conns[UIP_UDP_CONNS];

struct uip_udp_conn *uip_udp_conn;
struct uip_udp_conn uip_udp_conns[UIP_UDP_CONNS];
#ifdef COMMM
NyLPC_TUInt16 uip_udpchksum(NyLPC_TUInt16 i_len_of_data) {
	return upper_layer_chksum(UIP_PROTO_UDP,i_len_of_data);
}

/**
 * チェックサムは、TCP疑似ヘッダから計算。
 * 送信元IPアドレス+あて先/もどりIPアドレス+ProtocolID+パケット長
 */
static NyLPC_TUInt16 upper_layer_chksum(NyLPC_TUInt8 proto,NyLPC_TUInt16 i_len_of_data)
{
	NyLPC_TUInt16 sum;

#if UIP_CONF_IPV6
	i_len_of_data = i_len_of_data;
#else /* UIP_CONF_IPV6 */
	i_len_of_data = i_len_of_data- UIP_IPH_LEN;
#endif /* UIP_CONF_IPV6 */

	/* First sum pseudoheader. */

	/* IP protocol and length fields. This addition cannot carry. */
	sum = i_len_of_data + proto;
	/* Sum IP source and destination addresses. */
//	sum = chksum(sum, (u8_t *) &(BUF->srcipaddr), 2 * sizeof(uip_ipaddr_t));

	/* Sum TCP header and data. */
//	sum = chksum(sum, &uip_buf[UIP_IPH_LEN + UIP_LLH_LEN], i_len_of_data);

	return (sum == 0) ? 0xffff : NyLPC_htons(sum);
}

#endif
void uip_udp_init(void)
{
	NyLPC_TUInt8 c;
#if UIP_UDP
	for(c = 0; c < UIP_UDP_CONNS; ++c) {
		uip_udp_conns[c].lport = 0;
	}
#endif /* UIP_UDP */

	/* IPv4 initialization. */
#if UIP_FIXEDADDR == 0
	/*  uip_hostaddr[0] = uip_hostaddr[1] = 0;*/
#endif /* UIP_FIXEDADDR */

}

#if UIP_UDP
void uip_func_udp_send(void)
{/*
	u16_t t16;
	if(uip_slen == 0) {
		uip_func_drop();
		return;
	}
	uip_len = uip_slen + UIP_IPUDPH_LEN;

	#if UIP_CONF_IPV6
	// For IPv6, the IP length field does not include the IPv6 IP header length.
	t16 = uip_len - UIP_IPH_LEN;
	#else // UIP_CONF_IPV6
	t16 = uip_len;
	#endif // UIP_CONF_IPV6

	//IPヘッダ
	NyLPC_TIPv4Header_setSendHeader(
		&(UDPBUF->ip),
		uip_hostaddr,
		uip_udp_conn->ripaddr,
		UIP_PROTO_UDP,
		uip_udp_conn->ttl,
		uip_len);

	//UDPヘッダ
	UDPBUF->udplen = NyLPC_HTONS(uip_slen + UIP_UDPH_LEN);
	UDPBUF->srcport = uip_udp_conn->lport;
	UDPBUF->destport = uip_udp_conn->rport;
	UDPBUF->udpchksum = 0;
	uip_appdata = &uip_buf[UIP_LLH_LEN + UIP_IPTCPH_LEN];
	#if UIP_UDP_CHECKSUMS
	// Calculate UDP checksum.
	//ここちゅういしてねー。checksumにIPヘッダの内容使うから、うまいことごまかすんだ。
	UDPBUF->udpchksum = ~(uip_udpchksum(t16));
	if(UDPBUF->udpchksum == 0) {
		UDPBUF->udpchksum = 0xffff;
	}
	#endif // UIP_UDP_CHECKSUMS
	UIP_STAT(++uip_stat.udp.sent);
	// Return and let the caller do the actual transmission.
	uip_flags = 0;
	return;*/
}
#endif


void uip_process_UDP(void)
{
#ifdef CM
#if UIP_UDP
	/* UDP input processing. */
	udp_input:
	/* UDP processing is really just a hack. We don't do anything to the
	 UDP/IP headers, but let the UDP application do all the hard
	 work. If the application sets uip_slen, it has a packet to
	 send. */
#if UIP_UDP_CHECKSUMS
	uip_len = uip_len - UIP_IPUDPH_LEN;
	uip_appdata = &uip_buf[UIP_LLH_LEN + UIP_IPUDPH_LEN];
	if(UDPBUF->udpchksum != 0 && uip_udpchksum(uip_len) != 0xffff) {
		UIP_STAT(++uip_stat.udp.drop);
		UIP_STAT(++uip_stat.udp.chkerr);
		UIP_LOG("udp: bad checksum.");
		uip_func_drop();
		return;

	}
#else /* UIP_UDP_CHECKSUMS */
	uip_len = uip_len - UIP_IPUDPH_LEN;
#endif /* UIP_UDP_CHECKSUMS */

	/* Demultiplex this UDP packet between the UDP "connections". */
	for(uip_udp_conn = &uip_udp_conns[0];uip_udp_conn < &uip_udp_conns[UIP_UDP_CONNS];++uip_udp_conn) {
		/* If the local UDP port is non-zero, the connection is considered
		 to be used. If so, the local port number is checked against the
		 destination port number in the received packet. If the two port
		 numbers match, the remote port number is checked if the
		 connection is bound to a remote port. Finally, if the
		 connection is bound to a remote IP address, the source IP
		 address of the packet is checked. */
		if(uip_udp_conn->lport != 0 &&
				UDPBUF->destport == uip_udp_conn->lport &&
				(uip_udp_conn->rport == 0 ||
						UDPBUF->srcport == uip_udp_conn->rport) &&
				(uip_ipaddr_cmp(uip_udp_conn->ripaddr, all_zeroes_addr) ||
						uip_ipaddr_cmp(uip_udp_conn->ripaddr, all_ones_addr) ||
						uip_ipaddr_cmp(BUF->ip.srcipaddr, uip_udp_conn->ripaddr)))
		{
			goto udp_found;
		}
	}
	UIP_LOG("udp: no matching connection found");
	uip_func_drop();
	return;


	udp_found:
	UIP_STAT(++uip_stat.udp.recv);
	uip_conn = NULL;
	uip_flags = UIP_NEWDATA;
	uip_sappdata = uip_appdata = &uip_buf[UIP_LLH_LEN + UIP_IPUDPH_LEN];
	uip_slen = 0;
//	UIP_UDP_APPCALL();
	uip_func_udp_send();
	return;
#endif /* UIP_UDP */
#endif
}





void uip_udp_v4(void)
{
	/* If IP broadcast support is configured, we check for a broadcast
	 UDP packet, which may be destined to us. */
#if UIP_BROADCAST
	DEBUG_PRINTF("UDP IP checksum 0x%04x\n", uip_ipchksum());
	if(BUF->proto == UIP_PROTO_UDP &&
			uip_ipaddr_cmp(BUF->destipaddr, all_ones_addr)
			/*&&
			 uip_ipchksum() == 0xffff*/) {
		goto udp_input;
	}
#endif /* UIP_BROADCAST */

	/* Check if the packet is destined for our IP address. */
/*	if (!uip_ipaddr_cmp(BUF->destipaddr, uip_hostaddr)) {
		UIP_STAT(++uip_stat.ip.drop);
		uip_func_drop();
		return;
	}*/
}


/*
void uip_process_UIP_UDP_SEND_CONN(void)
{
	uip_sappdata = uip_appdata = &uip_buf[UIP_IPTCPH_LEN + UIP_LLH_LEN];
#if UIP_UDP
	uip_func_udp_send();
	return;
#endif // UIP_UDP
}
void uip_process_UIP_UDP_TIMER(void)
{
#if UIP_UDP
	if(uip_udp_conn->lport != 0) {

		uip_sappdata = uip_appdata = &uip_buf[UIP_LLH_LEN + UIP_IPUDPH_LEN];
//		uip_len = uip_slen = 0;
		uip_flags = UIP_POLL;
//			UIP_UDP_APPCALL();
		uip_func_udp_send();
	}else{
//		uip_func_drop();
	}
	return;
#endif
}
*/

#if UIP_UDP_COMOUT
struct uip_udp_conn *
uip_udp_new(uip_ipaddr_t *ripaddr, NyLPC_TUInt16 rport)
{
	NyLPC_TUInt8 c;
	register struct uip_udp_conn *conn;

	/* Find an unused local port. */
	again:
	++lastport;

	if(lastport >= 32000) {
		lastport = 4096;
	}

	for(c = 0; c < UIP_UDP_CONNS; ++c) {
		if(uip_udp_conns[c].lport == NyLPC_htons(lastport)) {
			goto again;
		}
	}

	conn = 0;
	for(c = 0; c < UIP_UDP_CONNS; ++c) {
		if(uip_udp_conns[c].lport == 0) {
			conn = &uip_udp_conns[c];
			break;
		}
	}

	if(conn == 0) {
		return 0;
	}

	conn->lport = NyLPC_HTONS(lastport);
	conn->rport = rport;
	if(ripaddr == NULL) {
		memset(&(conn->ripaddr), 0, sizeof(uip_ipaddr_t));
	} else {
		conn->ripaddr=*ripaddr;
	}
	conn->ttl = UIP_TTL;

	return conn;
}
#endif /* UIP_UDP */







