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

📄 packet32.c

📁 Windows XP下的抓包程序实现
💻 C
📖 第 1 页 / 共 5 页
字号:
/*
 * Copyright (c) 1999 - 2005 NetGroup, Politecnico di Torino (Italy)
 * Copyright (c) 2005 - 2006 CACE Technologies, Davis (California)
 * 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, CACE Technologies 
 * 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.
 *
 */

#define UNICODE 1

#pragma warning (disable : 4127)  //conditional expression is constant. Used for do{}while(FALSE) loops.

#if (MSC_VER < 1300)
#pragma warning (disable : 4710) // inline function not expanded. used for strsafe functions
#endif


#include <packet32.h>
#include <StrSafe.h>

#include "Packet32-Int.h"

#ifdef HAVE_WANPACKET_API
#include "wanpacket/wanpacket.h"
#endif //HAVE_WANPACKET_API

#include "debug.h"

#ifdef _WINNT4
#if (defined(HAVE_NPFIM_API) || defined(HAVE_WANPACKET_API) || defined (HAVE_AIRPCAP_API) || defined(HAVE_IPHELPER_API))
#error Do not enable _WINNT4 with any other API
#endif
#endif //_WINNT4

#ifdef _WINNT4
#pragma message ("Compiling Packet.dll for WINNT4 only")
#endif

#ifdef HAVE_AIRPCAP_API
#pragma message ("Compiling Packet.dll with support for AirPcap")
#endif

#ifdef HAVE_NPFIM_API
#pragma message ("Compiling Packet.dll with support for NpfIm driver")
#endif

#ifdef HAVE_DAG_API
#pragma message ("Compiling Packet.dll with support for DAG cards")
#endif

#ifdef HAVE_WANPACKET_API
#pragma message ("Compiling Packet.dll with support for WanPacket (aka Dialup thru NetMon)")
#endif

#ifdef HAVE_IPHELPER_API
#pragma message ("Compiling Packet.dll with support from IP helper API for API addresses")
#endif

#ifndef UNUSED
#define UNUSED(_x) (_x)
#endif


#ifdef _DEBUG_TO_FILE
LONG PacketDumpRegistryKey(PCHAR KeyName, PCHAR FileName);
CHAR g_LogFileName[1024] = "winpcap_debug.txt";
#endif //_DEBUG_TO_FILE

#include <windows.h>
#include <windowsx.h>
#include <Iphlpapi.h>
#include <IPIfCons.h>

#include <ntddndis.h>

#include <WpcapNames.h>

//
// Current packet.dll Version. It can be retrieved directly or through the PacketGetVersion() function.
//
char PacketLibraryVersion[64]; 

//
// Current NPF.sys Version. It can be retrieved directly or through the PacketGetVersion() function.
//
char PacketDriverVersion[64]; 

//
// WinPcap global registry key
//
//WCHAR g_WinPcapKeyBuffer[MAX_WINPCAP_KEY_CHARS];
//HKEY g_WinpcapKey = NULL;

//
// Global adapters list related variables
//
extern PADAPTER_INFO g_AdaptersInfoList;
extern HANDLE g_AdaptersInfoMutex;

#ifdef HAVE_IPHELPER_API
typedef VOID (*GAAHandler)(
  ULONG,
  DWORD,
  PVOID,
  PIP_ADAPTER_ADDRESSES,
  PULONG);
GAAHandler g_GetAdaptersAddressesPointer = NULL;
#endif // HAVE_IPHELPER_API

//
// Dynamic dependencies variables and declarations
//
volatile LONG g_DynamicLibrariesLoaded = 0;
HANDLE g_DynamicLibrariesMutex;

#ifdef HAVE_AIRPCAP_API
// We load dinamically the dag library in order link it only when it's present on the system
AirpcapGetLastErrorHandler g_PAirpcapGetLastError;
AirpcapGetDeviceListHandler g_PAirpcapGetDeviceList;
AirpcapFreeDeviceListHandler g_PAirpcapFreeDeviceList;
AirpcapOpenHandler g_PAirpcapOpen;
AirpcapCloseHandler g_PAirpcapClose;
AirpcapGetLinkTypeHandler g_PAirpcapGetLinkType;
AirpcapSetKernelBufferHandler g_PAirpcapSetKernelBuffer;
AirpcapSetFilterHandler g_PAirpcapSetFilter;
AirpcapGetMacAddressHandler g_PAirpcapGetMacAddress;
AirpcapSetMinToCopyHandler g_PAirpcapSetMinToCopy;
AirpcapGetReadEventHandler g_PAirpcapGetReadEvent;
AirpcapReadHandler g_PAirpcapRead;
AirpcapGetStatsHandler g_PAirpcapGetStats;
AirpcapWriteHandler g_PAirpcapWrite;
#endif // HAVE_AIRPCAP_API

#ifdef HAVE_DAG_API
// We load dinamically the dag library in order link it only when it's present on the system
dagc_open_handler g_p_dagc_open = NULL;
dagc_close_handler g_p_dagc_close = NULL;
dagc_getlinktype_handler g_p_dagc_getlinktype = NULL;
dagc_getlinkspeed_handler g_p_dagc_getlinkspeed = NULL;
dagc_getfcslen_handler g_p_dagc_getfcslen = NULL;
dagc_receive_handler g_p_dagc_receive = NULL;
dagc_wait_handler g_p_dagc_wait = NULL;
dagc_stats_handler g_p_dagc_stats = NULL;
dagc_setsnaplen_handler g_p_dagc_setsnaplen = NULL;
dagc_finddevs_handler g_p_dagc_finddevs = NULL;
dagc_freedevs_handler g_p_dagc_freedevs = NULL;
#endif // HAVE_DAG_API

BOOLEAN PacketAddAdapterDag(PCHAR name, PCHAR description, BOOLEAN IsAFile);

//
// Additions for WinPcap OEM
//
#ifdef WPCAP_OEM_UNLOAD_H
typedef BOOL (*WoemLeaveDllHandler)(void);
WoemLeaveDllHandler	g_WoemLeaveDllH = NULL;

__declspec (dllexport) VOID PacketRegWoemLeaveHandler(PVOID Handler)
{
	g_WoemLeaveDllH = Handler;
}
#endif // WPCAP_OEM_UNLOAD_H

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

/*! 
  \brief The main dll function.
*/

BOOL APIENTRY DllMain(HANDLE DllHandle,DWORD Reason,LPVOID lpReserved)
{
    BOOLEAN Status=TRUE;
	PADAPTER_INFO NewAdInfo;
	TCHAR DllFileName[MAX_PATH];

	UNUSED(lpReserved);

    switch(Reason)
    {
	case DLL_PROCESS_ATTACH:

		TRACE_PRINT_DLLMAIN("************Packet32: DllMain************");

#if 0
#ifdef WPCAP_OEM
#ifdef HAVE_WANPACKET_API
		LoadNdisNpp(Reason);
#endif // HAVE_WANPACKET_API
#endif // WPCAP_OEM 
#endif

#ifdef _DEBUG_TO_FILE
		PacketDumpRegistryKey("HKEY_LOCAL_MACHINE\\SYSTEM\\CurrentControlSet\\Services\\" NPF_DRIVER_NAME,"npf.reg");
		
		// dump a bunch of registry keys useful for debug to file
		PacketDumpRegistryKey("HKEY_LOCAL_MACHINE\\SYSTEM\\CurrentControlSet\\Control\\Class\\{4D36E972-E325-11CE-BFC1-08002BE10318}",
			"adapters.reg");
		PacketDumpRegistryKey("HKEY_LOCAL_MACHINE\\SYSTEM\\CurrentControlSet\\Services\\Tcpip",
			"tcpip.reg");
		PacketDumpRegistryKey("HKEY_LOCAL_MACHINE\\SYSTEM\\CurrentControlSet\\Services",
			"services.reg");

#endif

		// Create the mutex that will protect the adapter information list
		g_AdaptersInfoMutex = CreateMutex(NULL, FALSE, NULL);
		
		// Create the mutex that will protect the PacketLoadLibrariesDynamically() function		
		g_DynamicLibrariesMutex = CreateMutex(NULL, FALSE, NULL);

		//
		// Retrieve packet.dll version information from the file
		//
		// XXX We want to replace this with a constant. We leave it out for the moment
		if(GetModuleFileName(DllHandle, DllFileName, sizeof(DllFileName) / sizeof(DllFileName[0])) > 0)
		{
			PacketGetFileVersion(DllFileName, PacketLibraryVersion, sizeof(PacketLibraryVersion));
		}
		//
		// Retrieve NPF.sys version information from the file
		//
		// XXX We want to replace this with a constant. We leave it out for the moment
		// TODO fixme. Those hardcoded strings are terrible...
		PacketGetFileVersion(TEXT("drivers\\") TEXT(NPF_DRIVER_NAME) TEXT(".sys"), PacketDriverVersion, sizeof(PacketDriverVersion));
		
		break;
		
	case DLL_PROCESS_DETACH:

		CloseHandle(g_AdaptersInfoMutex);
		
		g_AdaptersInfoList;
		
		while(g_AdaptersInfoList != NULL)
		{
			
			NewAdInfo = g_AdaptersInfoList->Next;
			if (g_AdaptersInfoList->NetworkAddresses != NULL)
				GlobalFreePtr(g_AdaptersInfoList->NetworkAddresses);
			GlobalFreePtr(g_AdaptersInfoList);
			
			g_AdaptersInfoList = NewAdInfo;
		}

#ifdef WPCAP_OEM_UNLOAD_H 
		if(g_WoemLeaveDllH)
		{
			g_WoemLeaveDllH();
		}
#endif // WPCAP_OEM_UNLOAD_H

		break;
		
	default:
		break;
    }
	
    return Status;
}


/*! 
  \brief This function is used to dynamically load some of the libraries winpcap depends on, 
   and that are not guaranteed to be in the system
  \param cp A string containing the address.
  \return the converted 32-bit numeric address.

   Doesn't check to make sure the address is valid.
*/
VOID PacketLoadLibrariesDynamically()
{
#ifdef HAVE_IPHELPER_API
	HMODULE IPHMod;
#endif // HAVE_IPHELPER_API

#ifdef HAVE_AIRPCAP_API
	HMODULE AirpcapLib;
#endif // HAVE_DAG_API	

#ifdef HAVE_DAG_API
	HMODULE DagcLib;
#endif // HAVE_DAG_API

	TRACE_ENTER("PacketLoadLibrariesDynamically");

	//
	// Acquire the global mutex, so we wait until other threads are done
	//
	WaitForSingleObject(g_DynamicLibrariesMutex, INFINITE);

	//
	// Only the first thread should do the initialization
	//
	g_DynamicLibrariesLoaded++;

	if(g_DynamicLibrariesLoaded != 1)
	{
		ReleaseMutex(g_DynamicLibrariesMutex);
		TRACE_EXIT("PacketLoadLibrariesDynamically");
		return;
	}

	//
	// Locate GetAdaptersAddresses dinamically since it is not present in Win2k
	//

#ifdef HAVE_IPHELPER_API
	IPHMod = GetModuleHandle(TEXT("Iphlpapi"));
	if (IPHMod != NULL)
	{
		g_GetAdaptersAddressesPointer = (GAAHandler) GetProcAddress(IPHMod ,"GetAdaptersAddresses");
	}
#endif // HAVE_IPHELPER_API
	
#ifdef HAVE_AIRPCAP_API
	/* We dinamically load the airpcap library in order link it only when it's present on the system */
	if((AirpcapLib =  LoadLibrary(TEXT("airpcap.dll"))) == NULL)
	{
		// Report the error but go on
		TRACE_PRINT("AirPcap library not found on this system");
	}
	else
	{
		//
		// Find the exports
		//
		g_PAirpcapGetLastError = (AirpcapGetLastErrorHandler) GetProcAddress(AirpcapLib, "AirpcapGetLastError");
		g_PAirpcapGetDeviceList = (AirpcapGetDeviceListHandler) GetProcAddress(AirpcapLib, "AirpcapGetDeviceList");
		g_PAirpcapFreeDeviceList = (AirpcapFreeDeviceListHandler) GetProcAddress(AirpcapLib, "AirpcapFreeDeviceList");
		g_PAirpcapOpen = (AirpcapOpenHandler) GetProcAddress(AirpcapLib, "AirpcapOpen");
		g_PAirpcapClose = (AirpcapCloseHandler) GetProcAddress(AirpcapLib, "AirpcapClose");
		g_PAirpcapGetLinkType = (AirpcapGetLinkTypeHandler) GetProcAddress(AirpcapLib, "AirpcapGetLinkType");
		g_PAirpcapSetKernelBuffer = (AirpcapSetKernelBufferHandler) GetProcAddress(AirpcapLib, "AirpcapSetKernelBuffer");
		g_PAirpcapSetFilter = (AirpcapSetFilterHandler) GetProcAddress(AirpcapLib, "AirpcapSetFilter");
		g_PAirpcapGetMacAddress = (AirpcapGetMacAddressHandler) GetProcAddress(AirpcapLib, "AirpcapGetMacAddress");
		g_PAirpcapSetMinToCopy = (AirpcapSetMinToCopyHandler) GetProcAddress(AirpcapLib, "AirpcapSetMinToCopy");
		g_PAirpcapGetReadEvent = (AirpcapGetReadEventHandler) GetProcAddress(AirpcapLib, "AirpcapGetReadEvent");
		g_PAirpcapRead = (AirpcapReadHandler) GetProcAddress(AirpcapLib, "AirpcapRead");
		g_PAirpcapGetStats = (AirpcapGetStatsHandler) GetProcAddress(AirpcapLib, "AirpcapGetStats");
		g_PAirpcapWrite = (AirpcapWriteHandler) GetProcAddress(AirpcapLib, "AirpcapWrite");

		//
		// Make sure that we found everything
		//
		if(g_PAirpcapGetLastError == NULL ||
			g_PAirpcapGetDeviceList == NULL ||
			g_PAirpcapFreeDeviceList == NULL ||
			g_PAirpcapClose == NULL ||
			g_PAirpcapGetLinkType == NULL ||
			g_PAirpcapSetKernelBuffer == NULL ||
			g_PAirpcapSetFilter == NULL ||
			g_PAirpcapGetMacAddress == NULL ||
			g_PAirpcapSetMinToCopy == NULL ||
			g_PAirpcapGetReadEvent == NULL ||
			g_PAirpcapRead == NULL ||
			g_PAirpcapGetStats == NULL)
		{
			// No, something missing. A NULL g_PAirpcapOpen will disable airpcap adapters check
			g_PAirpcapOpen = NULL;
		}
	}
#endif // HAVE_DAG_API
	
#ifdef HAVE_DAG_API
	/* We dinamically load the dag library in order link it only when it's present on the system */
	if((DagcLib =  LoadLibrary(TEXT("dagc.dll"))) == NULL)
	{
		// Report the error but go on
		TRACE_PRINT("dag capture library not found on this system");
	}
	else
	{
		g_p_dagc_open = (dagc_open_handler) GetProcAddress(DagcLib, "dagc_open");
		g_p_dagc_close = (dagc_close_handler) GetProcAddress(DagcLib, "dagc_close");
		g_p_dagc_setsnaplen = (dagc_setsnaplen_handler) GetProcAddress(DagcLib, "dagc_setsnaplen");
		g_p_dagc_getlinktype = (dagc_getlinktype_handler) GetProcAddress(DagcLib, "dagc_getlinktype");
		g_p_dagc_getlinkspeed = (dagc_getlinkspeed_handler) GetProcAddress(DagcLib, "dagc_getlinkspeed");
		g_p_dagc_getfcslen = (dagc_getfcslen_handler) GetProcAddress(DagcLib, "dagc_getfcslen");
		g_p_dagc_receive = (dagc_receive_handler) GetProcAddress(DagcLib, "dagc_receive");
		g_p_dagc_wait = (dagc_wait_handler) GetProcAddress(DagcLib, "dagc_wait");
		g_p_dagc_stats = (dagc_stats_handler) GetProcAddress(DagcLib, "dagc_stats");
		g_p_dagc_finddevs = (dagc_finddevs_handler) GetProcAddress(DagcLib, "dagc_finddevs");
		g_p_dagc_freedevs = (dagc_freedevs_handler) GetProcAddress(DagcLib, "dagc_freedevs");
	}
#endif /* HAVE_DAG_API */

#ifdef HAVE_NPFIM_API
	if (LoadNpfImDll() == FALSE)
	{
		TRACE_PRINT("Failed loading NpfIm extension");
	}
#endif //HAVE_NPFIM_API


	//
	// Done. Release the mutex and return
	//
	ReleaseMutex(g_DynamicLibrariesMutex);

	TRACE_EXIT("PacketLoadLibrariesDynamically");
	return;
}

/*
BOOLEAN QueryWinPcapRegistryStringA(CHAR *SubKeyName,
								 CHAR *Value,
								 UINT *pValueLen,
								 CHAR *DefaultVal)
{
#ifdef WPCAP_OEM
	DWORD Type;
	LONG QveRes;
	HKEY hWinPcapKey;
	
	if (QveRes = RegOpenKeyExA(HKEY_LOCAL_MACHINE, 
			WINPCAP_INSTANCE_KEY,
			0,
			KEY_ALL_ACCESS,
			&hWinPcapKey) != ERROR_SUCCESS)
	{
		*pValueLen = 0;
		
		SetLastError(QveRes);

		return FALSE;
	}

	//
	// Query the requested value
	//
	QveRes = RegQueryValueExA(hWinPcapKey,
		SubKeyName,
		NULL,
		&Type,
		Value,
		pValueLen);

	RegCloseKey(hWinPcapKey);

	if (QveRes == ERROR_SUCCESS)
	{
		//let's check that the key is text

⌨️ 快捷键说明

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