//this file is part of eMule
//Copyright (C)2002 Merkur ( devs@emule-project.net / http://www.emule-project.net )
//
//This program is free software; you can redistribute it and/or
//modify it under the terms of the GNU General Public License
//as published by the Free Software Foundation; either
//version 2 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 General Public License
//along with this program; if not, write to the Free Software
//Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
#pragma once
#include "EMSocket.h"

class CUpDownClient;
class CPacket;
class CTimerWnd;
enum EDebugLogPriority;
#ifdef ISPBYPASS // NEO: MP - [MultiPort] -- Xanatos -->
struct SSecretPort;
#endif // ISPBYPASS // NEO: MP END <-- Xanatos --

enum SocketState 
{
	SS_Other,		//These are sockets we created that may or may not be used.. Or incoming connections.
	SS_Half,		//These are sockets that we called ->connect(..) and waiting for some kind of response.
	SS_Complete	//These are sockets that have responded with either a connection or error.
};

class CClientReqSocket : public CEMSocket
{
#ifdef ISPBYPASS // NEO: MP - [MultiPort] -- Xanatos -->
	friend class CPortListener;
#endif // ISPBYPASS // NEO: MP END <-- Xanatos --
	friend class CListenSocket;
#ifdef NATTUNNELING // NEO: UTCP - [UserModeTCP] -- Xanatos -->
	friend class	CClientUDPSocket;
#endif //NATTUNNELING // NEO: UTCP END <-- Xanatos --
	DECLARE_DYNCREATE(CClientReqSocket)

public:
#ifdef NATTUNNELING // NEO: UTCP - [UserModeTCP] -- Xanatos -->
	CClientReqSocket(CUpDownClient* in_client = NULL, bool bNatSocket = false);
#else
	CClientReqSocket(CUpDownClient* in_client = NULL);
#endif //NATTUNNELING // NEO: UTCP END <-- Xanatos --

	void	SetClient(CUpDownClient* pClient);
	void	Disconnect(LPCTSTR pszReason);
	void	WaitForOnConnect();
	void	ResetTimeOutTimer();
	bool	CheckTimeOut();
	virtual UINT GetTimeOut();
	virtual void Safe_Delete();
	
	bool	Create();
	virtual void SendPacket(Packet* packet, bool delpacket = true, bool controlpacket = true, uint32 actualPayloadSize = 0);
#ifdef NEO_UBT // NEO: NUBT - [NeoUploadBandwidthThrottler] -- Xanatos -->
    virtual SocketSentBytes Send(uint32 maxNumberOfBytesToSend, uint32 minFragSize, bool onlyAllowedToSendControlPacket = false, uint16 maxNumberOfPacketsToSend = 0xFFFF);
	virtual	int	Receive(uint32 size);
#else
    virtual SocketSentBytes SendControlData(uint32 maxNumberOfBytesToSend, uint32 overchargeMaxBytesToSend);
    virtual SocketSentBytes SendFileAndControlData(uint32 maxNumberOfBytesToSend, uint32 overchargeMaxBytesToSend);
#endif // NEO_UBT // NEO: NUBT END <-- Xanatos --

	void	DbgAppendClientInfo(CString& str);
	CString DbgGetClientInfo();

	CUpDownClient*	client;

#ifdef LANCAST // NEO: NLC - [NeoLanCast] -- Xanatos -->
	void		SetOnLan();
	bool		IsLanSocket() { return isLanSocket; }
#endif //LANCAST // NEO: NLC END <-- Xanatos --

protected:
	virtual ~CClientReqSocket();
	void	Delete_Timed();

	virtual void OnConnect(int nErrorCode);
	void		 OnClose(int nErrorCode);
	void		 OnSend(int nErrorCode);
	void		 OnReceive(int nErrorCode);
	void		 OnError(int nErrorCode);

	virtual bool PacketReceived(Packet* packet);
	int			 PacketReceivedSEH(Packet* packet);
	bool		 PacketReceivedCppEH(Packet* packet);

	bool	ProcessPacket(const BYTE* packet, uint32 size,UINT opcode);
	bool	ProcessExtPacket(const BYTE* packet, uint32 size, UINT opcode, UINT uRawSize);
	bool	ProcessModPacket(const BYTE* packet, uint32 size, UINT opcode, UINT uRawSize); // NEO: NMP - [NeoModProt] <-- Xanatos --
	void	PacketToDebugLogLine(LPCTSTR protocol, const uchar* packet, uint32 size, UINT opcode);
	void	SetConState(SocketState val);

	uint32	timeout_timer;
	bool	deletethis;
	uint32	deltimer;
	bool	m_bPortTestCon;
	uint32	m_nOnConnect;
#ifdef LANCAST // NEO: NLC - [NeoLanCast] -- Xanatos -->
	bool		isLanSocket;
#endif //LANCAST // NEO: NLC END <-- Xanatos --
};

#ifdef ISPBYPASS // NEO: MP - [MultiPort] -- Xanatos -->
class CPortListener : public CAsyncSocketEx
{
	friend class CListenSocket;

public:
	CPortListener();
	virtual ~CPortListener();

	void	SetCustomDH(); // NEO: SCC - [SecureClinetConnection]

	bool	StartListening(uint16 port, BOOL Secure = FALSE); // NEO: SCC - [SecureClinetConnection]
	void	StopListening();
	void	ReStartListening();

	bool	IsListening()				{ return bListening; }
	uint16	GetConnectedPort()			{ return m_port; } 

protected:
	virtual void OnAccept(int nErrorCode);

	bool	Rebind();

private:
	bool	bListening;
	// NEO: SCC - [SecureClinetConnection]
	bool	bSecure;
	// obtional DH parameters
	byte*	abyPrime;
	byte	abyBase;
	// NEO: SCC END
	uint16  m_port;
	int		m_nPendingConnections;

	MyUPnP::UPNPNAT_MAPPING* mapping; // NEO: UPNP - [UPnPNat]

};
#endif // ISPBYPASS // NEO: MP END <-- Xanatos --

#ifdef ISPBYPASS // NEO: MP - [MultiPort] -- Xanatos -->
class CListenSocket : public CObject
#else
class CListenSocket : public CAsyncSocketEx
#endif // ISPBYPASS // NEO: MP END <-- Xanatos --
{
	friend class CClientReqSocket;

public:
	CListenSocket();
	virtual ~CListenSocket();

	bool	StartListening();
#ifdef ISPBYPASS // NEO: MP - [MultiPort] -- Xanatos -->
	bool	StartListening(uint16 port, BOOL Secure = FALSE); // NEO: SCC - [SecureClinetConnection]
#endif // ISPBYPASS // NEO: MP END <-- Xanatos --
	void	StopListening();
#ifndef ISPBYPASS // NEO: MP -- Xanatos -->
	virtual void OnAccept(int nErrorCode);
#endif // ISPBYPASS // NEO: MP END <-- Xanatos --
	void	Process();
	void	RemoveSocket(CClientReqSocket* todel);
	void	AddSocket(CClientReqSocket* toadd);
	UINT	GetOpenSockets()		{return socket_list.GetCount();}
	void	KillAllSockets();
#ifdef ISPBYPASS // NEO: MP - [MultiPort] -- Xanatos -->
	void	KillAllPorts();
#endif // ISPBYPASS // NEO: MP END <-- Xanatos --
	bool	TooManySockets(bool bIgnoreInterval = false);
	bool	TooManySocketsOCC(); // NEO: OCC - [ObelixConnectionControl] <-- Xanatos --
	uint32	GetMaxConnectionReached()	{return maxconnectionreached;}
#ifdef ISPBYPASS // NEO: MP - [MultiPort] -- Xanatos -->
	void	IncMaxConnectionReached()	{maxconnectionreached++;}
#endif // ISPBYPASS // NEO: MP END <-- Xanatos --
	bool    IsValidSocket(CClientReqSocket* totest);
#ifdef NEO_BC // NEO: NBC - [NeoBandwidthControl] -- Xanatos -->
	void	AddConnection(bool created);
#else
	void	AddConnection();
#endif // NEO_BC // NEO: NBC END <-- Xanatos --
	void	RecalculateStats();
	void	ReStartListening();
	void	Debug_ClientDeleted(CUpDownClient* deleted);
	bool	Rebind();
	bool	SendPortTestReply(char result,bool disconnect=false);

	void	UpdateConnectionsStatus();
	float	GetMaxConperFiveModifier();
	uint32	GetPeakConnections()		{ return peakconnections; }
	uint32	GetTotalConnectionChecks()	{ return totalconnectionchecks; }
	float	GetAverageConnections()		{ return averageconnections; }
	uint32	GetActiveConnections()		{ return activeconnections; }
#ifdef ISPBYPASS // NEO: MP - [MultiPort] -- Xanatos -->
	bool	IsListening(uint16 port = 0);
	uint16	GetSecretPort(bool bPublic = false);
	bool	GetSecretPortDH(uint16 port, byte* &abyPrime, byte &abyBase);
	uint16	GetConnectedPort();
#else
	bool	IsListening()				{ return bListening; }
	uint16	GetConnectedPort()			{ return m_port; } 
#endif // ISPBYPASS // NEO: MP END <-- Xanatos --
	uint32	GetTotalHalfCon()			{ return m_nHalfOpen; }
	uint32	GetTotalComp()				{ return m_nComp; }

#ifdef NEO_BC // NEO: NBC - [NeoBandwidthControl] -- Xanatos -->
	void	SetLimitForConnections();
#endif // NEO_BC // NEO: NBC END <-- Xanatos --

private:
	CTypedPtrList<CPtrList, CClientReqSocket*> socket_list;
#ifdef ISPBYPASS // NEO: MP - [MultiPort] -- Xanatos -->
	CMap<uint16,uint16,CPortListener*,CPortListener*> port_map;
#endif // ISPBYPASS // NEO: MP END <-- Xanatos --
	uint16	m_OpenSocketsInterval;
	uint32	maxconnectionreached;
	uint16	m_ConnectionStates[3];
	uint32	peakconnections;
	uint32	totalconnectionchecks;
	float	averageconnections;
	uint32	activeconnections;
#ifndef ISPBYPASS // NEO: MP -- Xanatos -->
	bool	bListening;
	int		m_nPendingConnections;
	uint16  m_port;
#endif // ISPBYPASS // NEO: MP END <-- Xanatos --
	uint32	m_nHalfOpen;
	uint32	m_nComp;
#ifdef NEO_BC // NEO: NBC - [NeoBandwidthControl] -- Xanatos -->
	int		m_CreateSocketsLimit;	
	int		m_AcceptSocketsLimit;	
	int		m_AllSocketsLimit;	
#endif // NEO_BC // NEO: NBC END <-- Xanatos --
	MyUPnP::UPNPNAT_MAPPING* mapping; // NEO: UPNP - [UPnPNat] <-- Xanatos --
};
