#include "IpFilter.h"
#include "Capture/TcpipDefs.h"

IpFilter::IpFilter() : 
	m_nAddr(0)
{
}

IpFilter::IpFilter(const IpFilter & src) :
	Filter(src),
	m_nAddr(src.m_nAddr),
	m_sAddr(src.m_sAddr)
{
}

IpFilter::~IpFilter()
{
}

Filter * IpFilter::Clone() const
{
	return new IpFilter(*this);
}

bool IpFilter::SetAddress(const std::string sAddr)
{	
	std::clog << ">>> IpFilter::SetAddress: " << sAddr << std::endl;

	struct sockaddr_in tgtAddr;
	memset(&tgtAddr, 0, sizeof tgtAddr);

	struct hostent * host;
	host = gethostbyname(sAddr.c_str());
	if (!host)
		return false;
	m_sAddr = sAddr;
	m_nAddr = ((struct in_addr *)(host->h_addr))->s_addr;
	return true;
}

bool IpFilter::Match(const ProtocolInfoElement * pProtocolInfo)
{
	std::clog << ">>> IpFilter::Match: " << pProtocolInfo->ToString() << std::endl;

	if (pProtocolInfo->GetId() != EProtocolType_IPv4)
		return false;
	if (AreAllPacketsAccepted())
		return true;
	const IPv4Info * pIPv4 = dynamic_cast<const IPv4Info *>(pProtocolInfo);
	EFilterMatch matchType = GetMatchType();
	if (matchType == EFilterMatch_Receiver)
		return m_nAddr == pIPv4->GetDestinationAddress();
	else if (matchType == EFilterMatch_Sender)
		return m_nAddr == pIPv4->GetSourceAddress();
	else
	{
		if (m_nAddr == pIPv4->GetDestinationAddress())
			SetMatchType(EFilterMatch_Receiver);
		else if (m_nAddr == pIPv4->GetSourceAddress())
			SetMatchType(EFilterMatch_Sender);
		return matchType != GetMatchType();
	}
}

std::string IpFilter::GetSourcePcapFilter() const
{
	std::string sRes = "src host ";
	sRes += m_sAddr;
	return sRes;
}

std::string IpFilter::GetDestinationPcapFilter() const
{
	std::string sRes = "dst host ";
	sRes += m_sAddr;
	return sRes;
}


