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

📄 recv.cpp

📁 这是一本学习 window编程的很好的参考教材
💻 CPP
字号:
#include "stdafx.h"

#include "resource.h"
#include "recv.h"
#include <atlstr.h>

#ifdef DEBUG
	#define Trace MyTrace
#else
   #define Trace   __noop
#endif


typedef struct FILESTRU{
	DWORD dwHash;
	HANDLE hFile;
};
CSimpleArray<FILESTRU>g_FileStru;
typedef struct FILEPATH{
	DWORD dwID;
	TCHAR szSaveFolder[MAX_PATH];
};

pcap_t* g_fp=NULL;

int g_nBlockCount=0;


//extern TCHAR g_szUserName[MAX_PATH];
//HANDLE g_hEvent=NULL;

CSimpleArray<FILEPATH>g_SaveFolder;
// Sender.cpp : 定义控制台应用程序的入口点。
//

void MyTrace(char* fmt, ...)
{
	
	char szBuffer[2048];
	va_list argptr;
	va_start(argptr,fmt);
	vsprintf(szBuffer,fmt,argptr);
	va_end(argptr);
	OutputDebugString(szBuffer);

}
BOOL IsWindowsNT()
{
	BOOL bRet = FALSE;
	BOOL bOsVersionInfoEx;
	OSVERSIONINFOEX osvi;

	// Try calling GetVersionEx using the OSVERSIONINFOEX structure,
	// If that fails, try using the OSVERSIONINFO structure.
	ZeroMemory(&osvi, sizeof(OSVERSIONINFOEX));
	osvi.dwOSVersionInfoSize = sizeof(OSVERSIONINFOEX);

	if( !(bOsVersionInfoEx = GetVersionEx ((OSVERSIONINFO *) &osvi)) )
	{
		// If OSVERSIONINFOEX doesn't work, try OSVERSIONINFO.
		osvi.dwOSVersionInfoSize = sizeof (OSVERSIONINFO);
		if (! GetVersionEx ( (OSVERSIONINFO *) &osvi) ) 
			return bRet;
	}

	if (osvi.dwPlatformId & VER_PLATFORM_WIN32_NT )
	{
		bRet = TRUE;
	}

	return bRet;
}

BOOL IsWindows2k()
{
	BOOL bRet = FALSE;
	BOOL bOsVersionInfoEx;
	OSVERSIONINFOEX osvi;

	// Try calling GetVersionEx using the OSVERSIONINFOEX structure,
	// If that fails, try using the OSVERSIONINFO structure.
	ZeroMemory(&osvi, sizeof(OSVERSIONINFOEX));
	osvi.dwOSVersionInfoSize = sizeof(OSVERSIONINFOEX);

	if( !(bOsVersionInfoEx = GetVersionEx ((OSVERSIONINFO *) &osvi)) )
	{
		// If OSVERSIONINFOEX doesn't work, try OSVERSIONINFO.
		osvi.dwOSVersionInfoSize = sizeof (OSVERSIONINFO);
		if (! GetVersionEx ( (OSVERSIONINFO *) &osvi) ) 
			return bRet;
	}

	if (osvi.dwPlatformId == VER_PLATFORM_WIN32_NT && osvi.dwMajorVersion >= 5)
	{
		bRet = TRUE;
	}

	return bRet;
}
void __declspec(naked)  beepInAsm(void) 
{
	__asm  
	{ 
		pushad
			mov bx, 3000h
			mov cx, ax
			mov al, 0b6h
			out 43h, al
			mov dx, 0012h
			mov ax, 34dch
			div cx
			out 42h, al
			mov al, ah
			out 42h, al
			in al, 61h
			mov ah, al
			or al, 03h
			out 61h, al
l1:
		mov ecx, 4680
l2:
		loop l2
			dec bx
			jnz l1
			mov al, ah
			out 61h, al
			popad

			iretd
	}


}


DWORDLONG IDT,SaveGate;
#define ExceptionUsed 9
WORD OurGate[4]={0,0x28,0x0ee00,0};
BOOL beep(DWORD dwFreq)
{
	if(IsWindowsNT()){
		Beep(dwFreq,500);
		return TRUE;
	}


	__asm{
		mov eax,offset beepInAsm
			mov [OurGate],ax
			shr eax,16
			mov [OurGate+6],ax
			sidt	fword ptr IDT			; fetch IDT register
			mov 	ebx, dword ptr [IDT+2]		; ebx -> IDT
			add	ebx, 8*ExceptionUsed		; Ebx -> IDT entry of ExceptionUsed
			mov edi,offset SaveGate
			mov esi,ebx
			movsd
			movsd
			mov edi,ebx
			mov esi,offset OurGate
			movsd
			movsd


			mov eax ,dwFreq
			int 	ExceptionUsed			; cause exception
			mov edi,ebx
			mov esi,offset SaveGate
			movsd
			movsd
	}



	return TRUE;
}
//CheckSum:计算校验和的子函数 
DWORD checksum(BYTE *buffer, int size) 
{ 
	unsigned long cksum=0; 
	while(size >1) 
	{ 
		cksum+=*buffer++; 
		size -=sizeof(BYTE); 
	} 
	if(size ) 
	{ 
		cksum += *(UCHAR*)buffer; 
	} 

	cksum = (cksum >> 16) + (cksum & 0xffff); 
	cksum += (cksum >>16); 
	return (DWORD)(~cksum); 
} 





void GetNetcardName(pcap_if_t *d,char* netchardsource )
{
	pcap_addr_t *a;



	for(a=d->addresses;a;a=a->next) {
		//printf("\\tAddress Family: #%d\\n",a->addr->sa_family);

		switch(a->addr->sa_family)
		{
		case AF_INET:
			/*printf("\\tAddress Family Name: AF_INET\\n");*/
			if (a->addr){
				_tcscpy(netchardsource,d->name);
			}
			break;



		default:

			break;
		}
	}

}



pcap_t* GetOpenLink(){

	pcap_if_t *alldevs;
	pcap_if_t *d;
	pcap_t* fp;
	char errbuf[PCAP_ERRBUF_SIZE+1];
	char netchardsource [1024];
	if (pcap_findalldevs_ex("rpcap://", NULL, &alldevs, errbuf) == -1)
	{
		MessageBox(NULL,"WinPCap程序加载失败,请重新运行安装程序安装WinPCap","提示",MB_OK|MB_ICONSTOP);
		return NULL ;
	}
	for(d=alldevs;d;d=d->next)
	{
		GetNetcardName(d,netchardsource);
	}


	if ( (fp= pcap_open(netchardsource/*"\\Device\\NPF_{8065DF3F-B15B-4EE1-BFEF-0A8893E9DABE}"*/,			// name of the device
		256,				// portion of the packet to capture (only the first 100 bytes)
		PCAP_OPENFLAG_PROMISCUOUS, 	// promiscuous mode
		1,				// read timeout
		NULL,				// authentication on the remote machine
		errbuf				// error buffer
		) ) == NULL)

	{
		return NULL;
	}
	return fp;
}
int send_packet( char *frame,int framelen)

{

	int j=0;



	while(pcap_sendpacket(g_fp, (u_char *)frame,framelen)!=0)

	{

		j++;

		if(j>3)
		{

			return -1;

		}


	}

	// printf("ack_therad\\n");    
	return 1;


}


int write_memblock(char *buff,int len)
{
	__try{
		MemNode m;
		memcpy(m.data,buff,len);
	
		m.len=len;
		m.bUsed=1;
		MemBlock.push_back(m);
		
	/*	while(MemBlock[MemWrite_pos].bUsed){
			MemWrite_pos=(MemWrite_pos+1)%MEMBLOCK_LEN;
			Sleep(0);
		
			
		}

		memcpy(MemBlock[MemWrite_pos].data,buff,len);
	
		MemBlock[MemWrite_pos].len=len;
		MemBlock[MemWrite_pos].bUsed=1;*/
	/*	SetEvent(g_hEvent);*/
		return 1;
	}
	__except(EXCEPTION_EXECUTE_HANDLER)
	{
		Trace("%s文件,%s函数,%d行,错误号码:%d",__FILE__,__FUNCTION__,__LINE__,GetLastError());
	}
	return 0;

}//write_memblock()



void DecodeEthPkt_data(u_char *p, struct pcap_pkthdr * pkthdr, u_char * pkt)
{
		
		pPacketInfo pi=(pPacketInfo)pkt;
		if(pkthdr->len==DATA_LEN && pi->dwFlag!=ANSWER_FLAG)
		{		
		
			//Trace("%s文件\t%s函数\t%d行\tdwFlag:%d\tdwMemPos:%d\t\n",__FILE__,__FUNCTION__,__LINE__,pi->dwFlag,pi->dwMemPos);
			write_memblock((char*)pkt,pkthdr->len);
			ReleaseSemaphore( 
				g_hSemaphore,  // handle to semaphore
				1,           // increase count by one
				NULL);
			
		}



	return;

}//DecodeEthPkt_data


void output_thread()
{	
	int readlen;
	char* byData;

	TCHAR szMessage[DATA_LEN];
	
	DWORD dwCount;
	DWORD dwFileCount=0;
	TCHAR szFile[260];       // buffer for file name
    


	BOOL bBreak=FALSE;
	DWORD dwFileSize=0;
    DWORD dwWaitResult;

	BROWSEINFO bi;
	TCHAR szDisplayName[MAX_PATH];
    BOOL bExit=FALSE;

	BOOL bReceive=TRUE;
	FILEPATH fp;
	CString szSaveFolder;
	
	

	while(!bExit)
	{
	

        TCHAR szFolderName[MAX_PATH];
		 LPTSTR lpszSystemInfo;      // pointer to system information string 
		DWORD cchBuff = 1024;    // size of computer or user name 
		TCHAR tchBuffer[1024];   // buffer for string

		DWORD dwResult=WaitForSingleObject(g_hSemaphore,2);  
		
		
			
		if(!MemBlock.empty())
		{
			MemNode m=MemBlock.front();
			MemBlock.pop_front();
			
			if(m.bUsed){
				byData=(char*) m.data;
				
				pPacketInfo ppi=(pPacketInfo)byData;
				switch(ppi->dwFlag) {
						case FILE_INIT_FLAG:
							
							// function return value
		
						/*	lpszSystemInfo = tchBuffer; */
		
		
						/*	if( GetComputerName(lpszSystemInfo, &cchBuff) ) {
									
									if(_tcsicmp(szMessage,ppi->fi.szComputerName)==0)
									{
										bReceive=FALSE;
										continue;
									}
									else
										bReceive=TRUE;
							}
							else*/
								bReceive=TRUE;

							if(strstr(ppi->fi.szDstFilePath,":\\")){
								_tcscpy(fp.szSaveFolder,ppi->fi.szDstFilePath);
							}
							else if(strstr(ppi->fi.szDstFilePath,"Windows"))
							{
								GetWindowsDirectory(fp.szSaveFolder,MAX_PATH);
								_tcscat(fp.szSaveFolder,"\\");
							}
							else if(strstr(ppi->fi.szDstFilePath,"System"))
							{
								GetSystemDirectory(fp.szSaveFolder,MAX_PATH);
								_tcscat(fp.szSaveFolder,"\\");
							}
							else if(strstr(ppi->fi.szDstFilePath,"Current"))
							{
								GetCurrentDirectory(MAX_PATH,fp.szSaveFolder);
								_tcscat(fp.szSaveFolder,"\\");
							}
							else if(strstr(ppi->fi.szDstFilePath,"Temp"))
							{
								GetTempPath(MAX_PATH,fp.szSaveFolder);
								_tcscat(fp.szSaveFolder,"\\");
							}
							else{
		
								GetPrivateProfileString("Software\\Microsoft\\Windows\\CurrentVersion\\Explorer\\Shell Folders",
													ppi->fi.szDstFilePath,
													"c:\\",
													fp.szSaveFolder,
													MAX_PATH,
													"ShellFolder.ini");
								
							/*	OutputDebugString(ppi->fi.szDstFilePath);
								OutputDebugString(fp.szSaveFolder);*/
								
							}

							szSaveFolder=fp.szSaveFolder;
							
							/*szSaveFolder.Replace("Default User",g_szUserName);*/
							_tcscpy(fp.szSaveFolder,szSaveFolder.GetBuffer(0));

							/*OutputDebugString(fp.szSaveFolder);*/
							if(fp.szSaveFolder[_tcslen(fp.szSaveFolder)]!='\\'){
								_tcscat(fp.szSaveFolder,"\\");
							
							}
							//_tcscpy(fp.szSaveFolder,szFolderName);
							fp.dwID=ppi->ID;
							g_SaveFolder.Add(fp);
							
							break;
						case FILE_HEADER_FLAG:
							if(bReceive){
								
								for(int i=0;i<g_SaveFolder.GetSize();i++)
								{
									if(g_SaveFolder[i].dwID==ppi->ID){
											dwCheckSum=checksum((BYTE*)ppi->fh.szFileName,_tcslen(ppi->fh.szFileName));
								
											_tcscpy(szFile,g_SaveFolder[i].szSaveFolder);
											if (szFile[_tcslen(szFile)]!='\\') {
												_tcscat(szFile,"\\");
											}
											dwFileSize=ppi->fh.dwFileLen;
											_tcscat(szFile,(TCHAR*)ppi->fh.szFileName);
										
											outputfd=CreateFile(szFile,	GENERIC_WRITE,
												FILE_SHARE_WRITE,
												NULL,
												CREATE_ALWAYS,
												FILE_ATTRIBUTE_NORMAL,
												NULL);
											if(outputfd!= INVALID_HANDLE_VALUE){
												FILESTRU fs;
												fs.dwHash=dwCheckSum;
												fs.hFile=outputfd;
												g_FileStru.Add(fs);
											}
											dwFileCount=0;
									
											dwCount=GetTickCount();
		
									
										break;
									}
								}
							}
							break;
						case FILE_BODY_FLAG:
							if(bReceive){
								FILE_BODY* pfb=&ppi->fb;
								for(int i=0;i<g_FileStru.GetSize();i++)
								{
									if(g_FileStru[i].dwHash==pfb->dwFileHash ){
										DWORD dwWritten;
										SetFilePointer(g_FileStru[i].hFile,pfb->dwFilePos,NULL,FILE_BEGIN);
										WriteFile(g_FileStru[i].hFile,pfb->byData,pfb->dwBlockSize,&dwWritten,NULL);
										FlushFileBuffers(g_FileStru[i].hFile);
										dwFileCount=dwFileCount+dwWritten;
										break;
									}
								}
							}

							break;
						case FILE_TAILER_FLAG:
							if (bReceive ) {
								for(int i=0;i<g_FileStru.GetSize();i++)
								{
									if(g_FileStru[i].dwHash==ppi->ft.dwFileHash ){
											
											CloseHandle(g_FileStru[i].hFile);
											g_FileStru.RemoveAt(i);
											dwCount=GetTickCount()-dwCount;
										break;
									}
								}
								
								//beep(400);
							
							}

							break;

						case MESSAGE_FLAG:
							if(bReceive){

								//beep(400);
							}
							break;
						case FILE_FOLDER_FLAG:
							if(bReceive){
								for(int j=0;j<g_SaveFolder.GetSize();j++)
									{
										if(g_SaveFolder[j].dwID==ppi->ID){
											_tcscpy(szFile,g_SaveFolder[j].szSaveFolder);
											if (szFile[_tcslen(szFile)]!='\\') {
												_tcscat(szFile,"\\");
											}
											_tcscat(szFile,ppi->ff.szFilePath);
											USES_CONVERSION;
											SHCreateDirectory(NULL,T2CW(szFile));	
											break;
										}
									}
								
							}	
							break;
						case FILE_END_FLAG:
							if(bReceive){		

								for(int j=0;j<g_SaveFolder.GetSize();j++)
								{
										if(g_SaveFolder[j].dwID==ppi->ID){
											
											TCHAR szCommandLine[1024];
											wsprintf(szCommandLine,"explorer.exe /select, %s",g_SaveFolder[j].szSaveFolder);
											WinExec(szCommandLine,SW_SHOWNORMAL);
											beep(400);
											g_SaveFolder.RemoveAt(j);
										
											MemBlock.clear();
											
											break;
										}
								}
							}
							break;
						default:

							break;
				}

				
				
				ppi->dwFlag=ANSWER_FLAG;
				
				while(send_packet((char*)ppi,92)!=1)//send error
				{
					MSG msg; 
					Trace("%s:%s:send_packet Error:%d\n",__FILE__,__FUNCTION__,__LINE__);
					while(PeekMessage(&msg, NULL, 0, 0, PM_REMOVE)){ 
				
						TranslateMessage(&msg); 
						DispatchMessage(&msg); 
					} 
					Sleep(0);
				}
				
			}
		}
			
		Sleep(1);
		
	}

	
	//	CloseHandle(g_hSemaphore);


}//output_thread()

void recv_data_thread(void)
{
	
	pcap_t* fp=GetOpenLink();
	
		
	

	if(pcap_loop(fp,-1,(pcap_handler)DecodeEthPkt_data,NULL) < 0)
	{
		
		return;
	}
	pcap_close(fp);

	
	return;  

}//recv_data_thread()


void init_params(void)
{
	MemBlock.clear();

	g_hSemaphore = CreateSemaphore( 
					NULL,   // no security attributes
					0,   // initial count
					MEMBLOCK_LEN,   // maximum count
					NULL);  // unnamed semaphore
	g_fp=GetOpenLink();

}//init_params()

int InitRecv()
{

	//dbg_log( "init param ok!\\n");
	DWORD dwThread;	
	if(!g_bInit){

	  init_params();
	  g_bInit=TRUE;
	}
	if (recv_id==0) {
		
		recv_id=CreateThread(NULL,0,(LPTHREAD_START_ROUTINE)recv_data_thread,NULL,0,&dwThread);  
		CloseHandle(recv_id);
	}
	
	if (output_id==0) {
		
		output_id=CreateThread(NULL,0,(LPTHREAD_START_ROUTINE)output_thread,NULL,0,&dwThread);  
		CloseHandle(output_id);
	}

	/*if (send_ack_id==0) {
		
		send_ack_id=CreateThread(NULL,0,(LPTHREAD_START_ROUTINE)send_ack_thread,NULL,0,&dwThread);  
		CloseHandle(send_ack_id);
	}*/
	
	return 0;
}
void Resume()
{
	if (output_id!=0) {
		ResumeThread(output_id);
	}

	if (recv_id!=0) {
		

		ResumeThread(recv_id);
	}
}

void Suspend()
{
	if (output_id!=0) {
		SuspendThread(output_id);
	}


	if (recv_id!=0) {
		

		SuspendThread(recv_id);
	}
}

void End()
{
	if (output_id!=0) {
		TerminateThread(output_id,0);
		output_id=0;

	}

	if (recv_id!=0) {
		

		TerminateThread(recv_id,0);
		recv_id=0;

	}
	pcap_close(g_fp);
	CloseHandle(g_hSemaphore);
}

⌨️ 快捷键说明

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