#include <stdio.h>   
#include <string.h>
#include <stdlib.h>
#include <sys/time.h>

#include "stream.h"
#include "MESA_prof_load.h"
#include "MESA_handle_logger.h"
#include "deliver.h"


extern int g_iThreadNum;


extern "C" char deliver_tcp_entry(const struct streaminfo* pstream,void** pme,int thread_seq,const void* ip_hdr)
{
	char ret=APP_STATE_DROPPKT;

	struct origin_stream_addr addrinfo;
	struct sockaddr_in client_addr;
	struct sockaddr_in server_addr;
		
	if(pstream->opstate==OP_STATE_PENDING)
	{
		client_addr.sin_family=AF_INET;
		client_addr.sin_port=pstream->addr.ipv4->source;
		client_addr.sin_addr.s_addr=pstream->addr.ipv4->saddr;
		
		server_addr.sin_family=AF_INET;
		server_addr.sin_port=pstream->addr.ipv4->dest;
		server_addr.sin_addr.s_addr=pstream->addr.ipv4->daddr;

		memcpy(&addrinfo.client,&client_addr,sizeof(struct sockaddr));
		memcpy(&addrinfo.server,&server_addr,sizeof(struct sockaddr));
	
		mirror_stream_start(thread_seq,&addrinfo,pme);
	}

	if(ip_hdr!=NULL)
	{
		mirror_stream_append(pstream->curdir,thread_seq,pstream->ptcpdetail->datalen,(char*)pstream->ptcpdetail->pdata,pme);
	}
	
	if(pstream->opstate==OP_STATE_CLOSE)
	{
		mirror_stream_end(thread_seq,pme);
	}

	return ret;

}


extern "C" char deliver_tcpall_entry(const struct streaminfo* pstream,void** pme,int thread_seq,const void* ip_hdr)
{
	char ret=APP_STATE_DROPPKT;

	struct origin_stream_addr addrinfo;
	struct sockaddr_in client_addr;
	struct sockaddr_in server_addr;
		
	if(pstream->pktstate==OP_STATE_PENDING)
	{
		client_addr.sin_port=pstream->addr.ipv4->source;
		client_addr.sin_addr.s_addr=pstream->addr.ipv4->saddr;
		server_addr.sin_port=pstream->addr.ipv4->dest;
		server_addr.sin_addr.s_addr=pstream->addr.ipv4->daddr;

		memcpy(&addrinfo.client,&client_addr,sizeof(struct sockaddr));
		memcpy(&addrinfo.server,&server_addr,sizeof(struct sockaddr));
	
		mirror_stream_start(thread_seq,&addrinfo,pme);
	}

	if(ip_hdr!=NULL)
	{
		mirror_stream_append(pstream->curdir,thread_seq,pstream->ptcpdetail->datalen,(char*)pstream->ptcpdetail->pdata,pme);
	}
	
	if(pstream->opstate==OP_STATE_CLOSE)
	{
		mirror_stream_end(thread_seq,pme);
	}

	return ret;

}

extern "C" char test_deliver_init()
{
	int ret=0;
	
	ret=mirro_stream_init(g_iThreadNum,(char*)"./conf/deliver.conf");
	if(ret<0)
	{
		printf("test deliver init error!\n");
		return -1;
	}

	return 0;

}


