⭐ 欢迎来到虫虫下载站! | 📦 资源下载 📁 资源专辑 ℹ️ 关于我们
⭐ 虫虫下载站

📄 iocps.h

📁 提供加密的c/s 聊天程序。用到对称加密算法和非对称加密算法
💻 H
字号:
// IOCPS.h: interface for the IOCPS class. V 1.13
//
//////////////////////////////////////////////////////////////////////

#if !defined(AFX_IOCPS_H__4D63F25E_B852_46D7_9A42_CF060F5E544D__INCLUDED_)
#define AFX_IOCPS_H__4D63F25E_B852_46D7_9A42_CF060F5E544D__INCLUDED_

#if _MSC_VER > 1000
#pragma once
#endif // _MSC_VER > 1000


// Determines the size of the first bytes who tells you how big the message are. (pakage heap)  
#define MINIMUMPACKAGESIZE sizeof(UINT)
#define MAXIMUMPACKAGESIZE 512
#define MAXIMUMSEQUENSENUMBER 5001
#define MAXIMUMPAYLOADSIZE MAXIMUMPACKAGESIZE-MINIMUMPACKAGESIZE


#define IOCPSERVERVERSION "IOCP Server/Client system written by meijusan.2007"
//#define TRANSFERFILEFUNCTIONALITY  // to use filetransfer (transmitfile function) 

/*
*  Add this if you whant to be able to block sertain IP address or
*  just allow one connection per IP.
*/
//#define SIMPLESECURITY


// Winsock 2. Works only under Win XP and Win NT2k. 
#include <winsock2.h>
#pragma comment(lib,"ws2_32.lib")
#include "mswsock.h"

#include "IOCPBuffer.h"


#include "afxmt.h" // CCritical section.. 
#include "Rijndael.h"
#include "MyCryptLib.h"
// CMAP 
#include <afxtempl.h>



class CIOCPBuffer;
struct ClientContext;


template<>
inline UINT AFXAPI HashKey(unsigned int& key)
{
	// default identity hash - works for most primitive values
	return ((UINT)(void*)(unsigned int)key) >> 4;
}

typedef CMap<unsigned int, unsigned int&, ClientContext*, ClientContext* > ContextMap;
typedef CMap<unsigned int, unsigned int&, CIOCPBuffer *, CIOCPBuffer * > BufferMap;

/*
* Type of operations. 
*
*/
enum IOType 
{
	IOInitialize, // The client just connected
	IORead, // Read from the client. 
	IOReadCompleted, // Read completed
	IOWrite, // Write to the Client
	IOWriteCompleted, // Write Completed.
	IOZeroByteRead, // Read zero Byte from client (dummy for avoiding The System Blocking error) 
	IOZeroReadCompleted, // Read Zero Byte  completed. (se IOZeroByteRead)
	IOTransmitFileCompleted, //TransmitFileCompleted.
	IOPostedPackage, // Used to post Packages into IOCP port. 
};




enum JobType
{
	Job_SendText2Client,
	Job_SendFileInfo,
	Job_StartFileTransfer,
	Job_AbortFileTransfer
};


/*
* This is what We put in the JobQueue
*
*
*/

struct JobItem
{
	JobType m_command;
	unsigned int m_ClientID;
	CString m_Data;
};



#define _PRIVATEKEYSIZE_ 16
#define _HASHSIZE_ 20
#define _MINPUBLICKEYPSIZE_ 1024 // 1024 bits is accepted (2005) should be increased in future.  


enum PackageTypes
{
	PKG_ERRORMSG, // Used to send error msg to client. 
	// Key exchange Pkg
	PKG_PUBLIC_KEYP,
	PKG_PUBLIC_KEYA,
	PKG_PUBLIC_KEYB,
	PKG_SIGNATURE,
	// Chat pkg. 
	PKG_ENCRYPTED,
	PKG_USERNAME_PASSWORD,
	PKG_TEXT_TO_ALL,
};




/*
* This struct is used to past around some information about the 
* client. 
*
*/
struct ClientContext
{
	SOCKET				m_Socket; // The Connection socket. 
	CCriticalSection m_ContextLock; // The lock used to update and read variabels. 
	unsigned int			m_ID; // Reserved for DisconnectClient if needed. 
	int					m_nNumberOfPendlingIO; // Very Important variable used with ReleaseClientContext. (Avoids Access Violation)
	//
	// Send in order variables. 
	//
	unsigned int					m_SendSequenceNumber;
	unsigned int					m_CurrentSendSequenceNumber;
	BufferMap						m_SendBufferMap;
	//
	// Read in order variables
	//
	unsigned int					m_ReadSequenceNumber;
	unsigned int					m_CurrentReadSequenceNumber;
	BufferMap						m_ReadBufferMap;
	//
	// File transfer stuff. 
	//
#ifdef TRANSFERFILEFUNCTIONALITY	
	CFile m_File;
	unsigned int m_iMaxFileBytes;
	unsigned int m_iFileBytes; 
	BOOL m_bFileSendMode;
	BOOL m_bFileReceivedMode;
#endif

	// Package Overlapped Buffer..
	// Used to get a complete package when we have several pending reads. 
	CIOCPBuffer* m_pBuffOverlappedPackage;	

	// Extra info you can put what ever you whant here.. 
	CString m_sUsername; // The name of the  User. 


	// Key exchange data. 
	BOOL m_bGotSessionKey; // TRUE if we have a secure session key
	DWORD m_Privatekey[_PRIVATEKEYSIZE_];
	SHA1_STATETYPE m_csha1Hash;
	DWORD* m_pPublickey;
	UINT m_nPublicKeySize;


	CRijndael m_cCryptor;
	MyCryptLib m_cCryptLib;

	// list control data. 
	BOOL m_bUpdateList;


};

class IOCPS  
{

private:
	// Aborts A socket without removing it from contextmap.	
	inline void AbortiveClose(ClientContext *mp);
	// Adds nSize bytes to buffer and flush the other buffer. 
	inline BOOL AddAndFlush(CIOCPBuffer *pFromBuff, CIOCPBuffer *pToBuff, UINT nSize);
	// Add a client Context to hashMap,.
	inline BOOL AddClientContext(ClientContext* mp);
	// Allocates a ClientContext and return a pointer ot it. 
	inline ClientContext* AllocateContext();
	// Do a Asyncorn Read.
	inline BOOL ARead(ClientContext *pContext,CIOCPBuffer *pOverlapBuff=NULL);
	// Used to bin sockets to Completionport. 
	inline BOOL AssociateSocketWithCompletionPort(SOCKET socket, HANDLE hCompletionPort, DWORD dwCompletionKey);
	// Makes tha last peperation for an connection so IOWORKER can start to work with it. 
	inline BOOL AssociateIncomingClientWithContext(SOCKET clientSocket);
	// Unlocks the memory used by the overlapped IO, to avoid WSAENOBUFS problem. 
	inline BOOL AZeroByteRead(ClientContext *pContext,CIOCPBuffer *pOverlapBuff);
	// Creates a CreateCompletionPort
	inline BOOL CreateCompletionPort();
	// Functions used to post request into IOCP (simulate received packages)
	BOOL PostPackage(ClientContext *pContext,CIOCPBuffer *pOverlapBuff);

#if defined TRANSFERFILEFUNCTIONALITY	
	inline void AddToFile(ClientContext *pContext, DWORD dwIoSize, CIOCPBuffer *pOverlapBuff);
	inline void OnTransmitFileCompleted(ClientContext *pContext, CIOCPBuffer *pOverlapBuff);
	// DO an Transmitfile.
	inline BOOL StartSendFile(ClientContext *pContext);
	// Perpares for file receive
	inline BOOL PrepareReceiveFile(ClientContext *pContext, LPCTSTR lpszFilename,DWORD dwFileSize);
	// Perpared for file send
	inline BOOL PrepareSendFile(ClientContext *pContext, LPCTSTR lpszFilename);
	// Disables file send
	inline BOOL DisableSendFile(ClientContext *pContext);
	// Disables file receive. 
	inline BOOL DisableReceiveFile(ClientContext *pContext);
#endif	


#ifdef SIMPLESECURITY	
public:
	void OneIPPerConnection(BOOL bVal=TRUE);
protected: 
	CCriticalSection m_OneIPPerConnectionLock;
	CPtrList m_OneIPPerConnectionList;
	CCriticalSection m_BanIPLock;
	CPtrList m_BanIPList;

	static int CALLBACK ConnectAcceptCondition(IN LPWSABUF lpCallerId,
		IN LPWSABUF lpCallerData,
		IN OUT LPQOS lpSQOS,
		IN OUT LPQOS lpGQOS,
		IN LPWSABUF lpCalleeId, 
		OUT LPWSABUF lpCalleeData,
		OUT GROUP FAR *g,
		IN DWORD dwCallbackData);

	void ClearBanList();
	//inline void DisconnectIfBanned(SOCKET &Socket);
	inline BOOL IsInBannedList(sockaddr_in* pCaller);
	inline BOOL IsAlreadyConnected(sockaddr_in* pCaller);

	// Disconnect immediately  if the incoming IP already exist. 
	//inline void DisconnectIfIPExist(SOCKET &Socket);
	inline void AddToBanList(SOCKET &Socket);
private: 

#endif
	// Clears the memory of the ClientContext (Also disconnects) 
	inline void FreeClientContext();
	// Disconnects A client. 
	inline void DisconnectClient(ClientContext* pContext, BOOL bGraceful=FALSE);
	// Used to avoid access violation..
	inline int ExitIOLoop(ClientContext *pContext);
	// Used to avoid access violation..
	inline void EnterIOLoop(ClientContext *pContext);
	// clear the memory of the buffers. Should only be called when no pendling operations are in use. 
	inline void FreeBuffers();
	// Used to  avoid inorder packages (if you are useing more than one I/O Worker Thread)  
	inline CIOCPBuffer * GetNextReadBuffer(ClientContext *pContext,CIOCPBuffer *pBuff=NULL);
	// Used to  avoid inorder packages (if you are useing more than one I/O Worker Thread)  
	inline CIOCPBuffer* GetNextSendBuffer(ClientContext *pContext,CIOCPBuffer *pBuff=NULL);
	inline void IncreaseSendSequenceNumber(ClientContext *pContext);
	inline void IncreaseReadSequenceNumber(ClientContext *pContext);
	// Used to avoid inorder Read packages
	inline void MakeOrderdRead(ClientContext *pContext,CIOCPBuffer *pBuff);


	// Used by IO Workers. 
	inline void OnWriteCompleted(ClientContext *pContext, DWORD dwIoSize,CIOCPBuffer *pOverlapBuff);
	inline void OnWrite(ClientContext *pContext, DWORD dwIoSize,CIOCPBuffer *pOverlapBuff);
	inline void OnReadCompleted(ClientContext *pContext, DWORD dwIoSize,CIOCPBuffer *pOverlapBuff=NULL);
	inline void OnRead(ClientContext *pContext,CIOCPBuffer *pOverlapBuff=NULL);
	inline void OnInitialize(ClientContext* pContext, DWORD dwIoSize,CIOCPBuffer *pOverlapBuff=NULL);
	inline void OnPostedPackage(ClientContext *pContext,CIOCPBuffer *pOverlapBuff);


	// Used to avoid SYSTEM Blocking Bugg. 
	inline void OnZeroByteReadCompleted(ClientContext *pContext, DWORD dwIoSize,CIOCPBuffer *pOverlapBuff=NULL);
	inline void OnZeroByteRead(ClientContext *pContext,CIOCPBuffer *pOverlapBuff=NULL);
	// Process the internal messages. 
	inline void ProcessIOMessage(CIOCPBuffer *pOverlapBuff, ClientContext* pContext, DWORD dwSize);	
	// Process received Packages 
	inline void ProcessPackage(ClientContext *pContext, DWORD dwIoSize,CIOCPBuffer *pOverlapBuff);
	// Used to clean up the Send and receive hash map. 
	// Deletes the ClientContext or just put it in the FreeClientContext list. 
	inline BOOL ReleaseClientContext(ClientContext *pContext);
	// Release buffers. 
	inline void ReleaseBufferMap(BufferMap *map);
	//Closes The Worker Threads
	inline void ShutDownWorkers();
	// Closes The IO Workers
	inline void ShutDownIOWorkers();
	//  Splits a buffer into two. Used to handle halffinished received messages. 
	inline CIOCPBuffer * SplitBuffer(CIOCPBuffer * pBuff,UINT nSize);
	// Used to avoid inorder package.
	inline void SetSendSequenceNumber(ClientContext *pContext,CIOCPBuffer *pBuff);
	// Worker, Listener, IOWorker.  
	static UINT WorkerThreadProc(LPVOID pParam);
	static UINT IOWorkerThreadProc(LPVOID pParam);
	static UINT ListnerThreadProc(LPVOID pParam);
	//Signals No more Accepting Connections.. 
	BOOL m_bServerStarted;

	//Signals ShutDown
	volatile BOOL m_bShutDown;
	//Signals No more Accepting Connections.. 
	volatile BOOL m_bAcceptConnections;
	// Signals No more Jobs. 
	volatile BOOL m_bAcceptJobs;
	// Anv鋘ds f鰎 att binda alla socets till GetQueuedCompletionStatus
	HANDLE					m_hCompletionPort;
	// Om vi f錼 en connecction request.. 
	HANDLE					m_hEvent; 
	// Socket som vi anv鋘der f鰎 att lyssna... 
	SOCKET					m_socListen;   
	// Tr錮en som lyssnar p

⌨️ 快捷键说明

复制代码 Ctrl + C
搜索代码 Ctrl + F
全屏模式 F11
切换主题 Ctrl + Shift + D
显示快捷键 ?
增大字号 Ctrl + =
减小字号 Ctrl + -