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

📄 packet32.c

📁 Windows XP下的抓包程序实现
💻 C
📖 第 1 页 / 共 3 页
字号:
/*
 * Copyright (c) 1999 - 2003
 * NetGroup, Politecnico di Torino (Italy)
 * All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions
 * are met:
 *
 * 1. Redistributions of source code must retain the above copyright
 * notice, this list of conditions and the following disclaimer.
 * 2. Redistributions in binary form must reproduce the above copyright
 * notice, this list of conditions and the following disclaimer in the
 * documentation and/or other materials provided with the distribution.
 * 3. Neither the name of the Politecnico di Torino nor the names of its
 * contributors may be used to endorse or promote products derived from
 * this software without specific prior written permission.
 *
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
 * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
 * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
 * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
 * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
 * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
 * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
 * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
 * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
 * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 *
 */


#include <packet32.h>
#include <windows.h>
#include <windowsx.h>
#include <ntddndis.h>
#include <sys/timeb.h>
#ifdef __MINGW32__
#ifdef DBG
#include <assert.h>
#define _ASSERTE assert
#else
#define _ASSERTE
#endif /* DBG */
#else
#include <crtdbg.h>
#endif /* __MINGW32__ */

#include "../../version.h"


#ifdef __cplusplus
extern "C"
{		
#endif				

TCHAR szWindowTitle[] = TEXT ("PACKET.DLL");
LPADAPTER lpTheAdapter = NULL;

#if _DBG
#define ODS(_x) OutputDebugString(TEXT(_x))
#define ODSEx(_x, _y)
#else
#ifdef _DEBUG_TO_FILE
#include <stdio.h>
// Macro to print a debug string. The behavior differs depending on the debug level
#define ODS(_x) { \
	FILE *f; \
	f = fopen("winpcap_debug.txt", "a"); \
	fprintf(f, "%s", _x); \
	fclose(f); \
}
// Macro to print debug data with the printf convention. The behavior differs depending on */
#define ODSEx(_x, _y) { \
	FILE *f; \
	f = fopen("winpcap_debug.txt", "a"); \
	fprintf(f, _x, _y); \
	fclose(f); \
}

#else
#define ODS(_x)		
#define ODSEx(_x, _y)
#endif
#endif

typedef DWORD(CALLBACK* OPENVXDHANDLE)(HANDLE);

BOOLEAN StartPacketDriver (LPTSTR ServiceName);
BOOLEAN StopPacketDriver (void);
BOOLEAN PacketSetMaxLookaheadsize (LPADAPTER AdapterObject);

char PacketLibraryVersion[] = WINPCAP_PACKET9x_STRING_VERSION; 

//---------------------------------------------------------------------------

PCHAR PacketGetVersion()
{
	return PacketLibraryVersion;
}

//---------------------------------------------------------------------------

PCHAR PacketGetDriverVersion()
{
	return PacketLibraryVersion;
}

//---------------------------------------------------------------------------
BOOL APIENTRY DllMain (HANDLE hModule,
					DWORD dwReason,
					LPVOID lpReserved)
{
    BOOL Status;

	ODS ("Packet32: DllEntry\n");
    switch (dwReason)
	{
		case DLL_PROCESS_ATTACH:
			Status = StartPacketDriver (TEXT ("PACKET"));
			break;
		case DLL_PROCESS_DETACH:
			Status = StopPacketDriver ();
			break;
		default:
			Status = TRUE;
			break;
	}
	return Status;
}

//---------------------------------------------------------------------------
BOOL PacketDeviceIoControl (LPADAPTER lpAdapterObject,
			      LPPACKET lpPacket,
			      ULONG ulIoctl,
			      BOOLEAN bSync)
{
	BOOLEAN Result;
	DWORD Error;

	ODS ("Packet32: PacketDeviceIoControl\n");
	_ASSERTE (lpAdapterObject != NULL);
	_ASSERTE (lpPacket != NULL);
	lpPacket->OverLapped.Offset = 0;
	lpPacket->OverLapped.OffsetHigh = 0;
	lpPacket->ulBytesReceived		= 0;
	if (!ResetEvent (lpPacket->OverLapped.hEvent))
	{
		lpPacket->bIoComplete = FALSE;
		return FALSE;
	}

    Result = DeviceIoControl (lpAdapterObject->hFile,
				ulIoctl,
				lpPacket->Buffer,
				lpPacket->Length,
				lpPacket->Buffer,
				lpPacket->Length,
				&(lpPacket->ulBytesReceived), 
				&(lpPacket->OverLapped));
	Error=GetLastError () ;
    
	if (!Result && bSync)
	{
		if (Error == ERROR_IO_PENDING)
		{
			Result = GetOverlappedResult (lpAdapterObject->hFile,
					&(lpPacket->OverLapped),
					&(lpPacket->ulBytesReceived), 
					TRUE);
		}
		else
			ODS ("Packet32: unsupported API call return error!\n");
	}

	lpPacket->bIoComplete = Result;

	return Result;
}


//---------------------------------------------------------------------------

LPADAPTER PacketOpenAdapter (LPTSTR AdapterName)
{
    LPPACKET	lpSupport;
	LPADAPTER	nAdapter;
	DWORD		error;
	BOOL		res;
	OPENVXDHANDLE OpenVxDHandle;
	DWORD		KernEvent;
	UINT		BytesReturned;
	struct _timeb time;

    ODSEx ("Packet32: PacketOpenAdapter, opening %s\n", AdapterName);
	
	nAdapter = (LPADAPTER) GlobalAllocPtr (GMEM_MOVEABLE | GMEM_ZEROINIT,sizeof (ADAPTER));
	if (nAdapter == NULL)
	{
		error=GetLastError();
		ODS ("Packet32: PacketOpenAdapter GlobalAlloc Failed\n");
		ODSEx("Error=%d\n",error);
		//set the error to the one on which we failed
		SetLastError(error);
		return NULL;
	}
	wsprintf (nAdapter->SymbolicLink,
		TEXT ("\\\\.\\%s"),
		TEXT ("NPF.VXD"));
	nAdapter->hFile = CreateFile (nAdapter->SymbolicLink,
		GENERIC_WRITE | GENERIC_READ,
		0,
		NULL,
		OPEN_EXISTING,
		FILE_FLAG_OVERLAPPED | FILE_FLAG_DELETE_ON_CLOSE, 
		0);

	if (nAdapter->hFile == INVALID_HANDLE_VALUE)
	{
		error=GetLastError();
		ODS ("Packet32: PacketOpenAdapter Could not open adapter, 1\n");
		ODSEx("Error=%d\n",error);
		GlobalFreePtr (nAdapter);
		//set the error to the one on which we failed
		SetLastError(error);
		return NULL;
	}
	
	lpSupport=PacketAllocatePacket();
	
	PacketInitPacket(lpSupport,AdapterName,strlen(AdapterName));
	if (nAdapter && (nAdapter->hFile != INVALID_HANDLE_VALUE))
	{
		res=PacketDeviceIoControl(nAdapter,
			lpSupport,
			(ULONG) IOCTL_OPEN,
			TRUE);
		if (res==FALSE || ((char*)lpSupport->Buffer)[0]=='\0'){
			SetLastError(ERROR_FILE_NOT_FOUND);
			goto err;
		}
		PacketFreePacket(lpSupport);

		// Set the time zone
		_ftime(&time);
		if(DeviceIoControl(nAdapter->hFile,pBIOCSTIMEZONE,&time.timezone,2,NULL,0,&BytesReturned,NULL)==FALSE){
			error=GetLastError();
			ODS ("Packet32: PacketOpenAdapter Could not open adapter, 2\n");
			ODSEx("Error=%d\n",error);
			GlobalFreePtr (nAdapter);
			//set the error to the one on which we failed
			SetLastError(error);
			return NULL;	
		}
		
		// create the read event
		nAdapter->ReadEvent=CreateEvent(NULL, TRUE, FALSE, NULL);
		// obtain the pointer of OpenVxDHandle in KERNEL32.DLL.
		// It is not possible to reference statically this function, because it is present only in Win9x
		OpenVxDHandle = (OPENVXDHANDLE) GetProcAddress(GetModuleHandle("KERNEL32"),"OpenVxDHandle");
		// map the event to kernel mode
		KernEvent=(DWORD)(OpenVxDHandle)(nAdapter->ReadEvent);
		// pass the event to the driver
		if(DeviceIoControl(nAdapter->hFile,pBIOCEVNAME,&KernEvent,4,NULL,0,&BytesReturned,NULL)==FALSE){
			error=GetLastError();
			ODS("Packet32: PacketOpenAdapter Could not open adapter, 3\n");
			ODSEx("Error=%d\n",error);
			GlobalFreePtr (nAdapter);
			//set the error to the one on which we failed
			SetLastError(error);
			return NULL;	
		}

		//set the maximum lookhahead size allowable with this NIC driver
		PacketSetMaxLookaheadsize(nAdapter);

		//set the number of times a single write will be repeated
		PacketSetNumWrites(nAdapter,1);
		
		return nAdapter;
	}
err:
	error=GetLastError();
	ODS ("Packet32: PacketOpenAdapter Could not open adapter, 4\n");
	ODSEx("Error=%d\n",error);
	//set the error to the one on which we failed
	SetLastError(error);
    return NULL;
}

//---------------------------------------------------------------------------
/* Function to set the working mode of the driver
mode	working mode
*/

BOOLEAN PacketSetMode(LPADAPTER AdapterObject,int mode)
{
	int BytesReturned;
		
    return DeviceIoControl(AdapterObject->hFile,pBIOCSMODE,&mode,4,NULL,0,&BytesReturned,NULL);
}

//---------------------------------------------------------------------------
/* Function to get the the read event*/

HANDLE PacketGetReadEvent(LPADAPTER AdapterObject)
{
    return AdapterObject->ReadEvent;
}

//---------------------------------------------------------------------------
/* Function to set the the number of times a write will be repeated*/

BOOLEAN PacketSetNumWrites(LPADAPTER AdapterObject,int nwrites)
{
	AdapterObject->NumWrites=nwrites;
	return TRUE;
}

//---------------------------------------------------------------------------
/* This function is used to set the read timeout
timeout		value of timeout(milliseconds). 0 means infinite.
*/

BOOLEAN PacketSetReadTimeout(LPADAPTER AdapterObject,int timeout)
{
	int BytesReturned;
    return DeviceIoControl(AdapterObject->hFile,pBIOCSRTIMEOUT,&timeout,4,NULL,0,&BytesReturned,NULL);
}

//---------------------------------------------------------------------------
/* This function allows to set the dimension of the packet buffer in the driver
parameters:
dim		dimension of the buffer (kilobytes)
*/

BOOLEAN PacketSetBuff(LPADAPTER AdapterObject,int dim)
{
	int BytesReturned;
    return DeviceIoControl(AdapterObject->hFile,pBIOCSETBUFFERSIZE,&dim,4,NULL,0,&BytesReturned,NULL);
}

//---------------------------------------------------------------------------
/* Function to set the minimum amount of bytes that will be copied by the driver*/

BOOLEAN PacketSetMinToCopy(LPADAPTER AdapterObject,int nbytes)
{
	// not yet implemented in Windows 9x
    return TRUE;
}

//---------------------------------------------------------------------------
/* Function to set a bpf filter in the driver
parameters:
fp		the pointer to the beginning of the filtering program
*/

BOOLEAN PacketSetBpf(LPADAPTER AdapterObject,struct bpf_program *fp)
{
	int BytesReturned;

    return DeviceIoControl(AdapterObject->hFile,pBIOCSETF,(char*)fp->bf_insns,fp->bf_len*sizeof(struct bpf_insn),NULL,0,&BytesReturned,NULL);
}



//---------------------------------------------------------------------------

BOOLEAN PacketGetStats(LPADAPTER AdapterObject,struct bpf_stat *s)
{
	int BytesReturned;

    return DeviceIoControl(AdapterObject->hFile,pBIOCGSTATS,NULL,0,s,sizeof(struct bpf_stat),&BytesReturned,NULL);
}

//---------------------------------------------------------------------------

BOOLEAN PacketGetStatsEx(LPADAPTER AdapterObject,struct bpf_stat *s)
{
	int BytesReturned;

    return DeviceIoControl(AdapterObject->hFile,pBIOCGSTATS,NULL,0,s,sizeof(struct bpf_stat),&BytesReturned,NULL);
}

//---------------------------------------------------------------------------
VOID PacketCloseAdapter (LPADAPTER lpAdapter)
{

	ODS ("Packet32: PacketCloseAdapter\n");

	// close the capture handle
	CloseHandle (lpAdapter->hFile);

	// close the read event
	CloseHandle (lpAdapter->ReadEvent);

	GlobalFreePtr (lpAdapter);
	lpAdapter = NULL;

}

//---------------------------------------------------------------------------
LPPACKET PacketAllocatePacket (void)
{
	LPPACKET lpPacket;

    lpPacket = (LPPACKET) GlobalAllocPtr (
					   GMEM_MOVEABLE | GMEM_ZEROINIT,
					   sizeof (PACKET));
    if (lpPacket == NULL)
	{

⌨️ 快捷键说明

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