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

📄 packet32.c

📁 用来监视网络通信数据的源代码和应用程序,方便网络程序底层开发.
💻 C
📖 第 1 页 / 共 5 页
字号:
/*
 * Copyright (c) 1999 - 2003
 *	Politecnico di Torino.  All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that: (1) source code distributions
 * retain the above copyright notice and this paragraph in its entirety, (2)
 * distributions including binary code include the above copyright notice and
 * this paragraph in its entirety in the documentation or other materials
 * provided with the distribution, and (3) all advertising materials mentioning
 * features or use of this software display the following acknowledgement:
 * ``This product includes software developed by the Politecnico
 * di Torino, and its contributors.'' Neither the name of
 * the University 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 ``AS IS'' AND WITHOUT ANY EXPRESS OR IMPLIED
 * WARRANTIES, INCLUDING, WITHOUT LIMITATION, THE IMPLIED WARRANTIES OF
 * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE.
 */

#define UNICODE 1

#include <stdio.h>
#include <packet32.h>
#include "wanpacket/wanpacket.h"


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

#include <ntddndis.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]; 

//service handles
SC_HANDLE scmHandle = NULL;
SC_HANDLE srvHandle = NULL;
LPCTSTR NPFServiceName = TEXT("NPF");
LPCTSTR NPFServiceDesc = TEXT("Netgroup Packet Filter");
LPCTSTR NPFRegistryLocation = TEXT("SYSTEM\\CurrentControlSet\\Services\\NPF");
LPCTSTR NPFDriverPath = TEXT("system32\\drivers\\npf.sys");

extern PADAPTER_INFO AdaptersInfoList;
extern HANDLE AdaptersInfoMutex;
#ifndef _WINNT4
typedef VOID (*GAAHandler)(
  ULONG,
  DWORD,
  PVOID,
  PIP_ADAPTER_ADDRESSES,
  PULONG);
GAAHandler GetAdaptersAddressesPointer = NULL;
#endif // _WINNT4

#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 p_dagc_open = NULL;
dagc_close_handler p_dagc_close = NULL;
dagc_getlinktype_handler p_dagc_getlinktype = NULL;
dagc_getlinkspeed_handler p_dagc_getlinkspeed = NULL;
dagc_getfcslen_handler p_dagc_getfcslen = NULL;
dagc_receive_handler p_dagc_receive = NULL;
dagc_wait_handler p_dagc_wait = NULL;
dagc_stats_handler p_dagc_stats = NULL;
dagc_setsnaplen_handler p_dagc_setsnaplen = NULL;
dagc_finddevs_handler p_dagc_finddevs = NULL;
dagc_freedevs_handler p_dagc_freedevs = NULL;
#endif /* HAVE_DAG_API */

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

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

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

BOOL APIENTRY DllMain (HANDLE DllHandle,DWORD Reason,LPVOID lpReserved)
{
    BOOLEAN Status=TRUE;
	HMODULE IPHMod;
	PADAPTER_INFO NewAdInfo;
#ifdef HAVE_DAG_API
	HMODULE DagcLib;
#endif // HAVE_DAG_API

    switch(Reason)
    {
	case DLL_PROCESS_ATTACH:

		ODS("************Packet32: DllMain************\n");
		
#ifdef _DEBUG_TO_FILE
		// 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\\NPF",
			"npf.reg");
		PacketDumpRegistryKey("HKEY_LOCAL_MACHINE\\SYSTEM\\CurrentControlSet\\Services",
			"services.reg");
#endif

		// Create the mutex that will protect the adapter information list
		AdaptersInfoMutex = CreateMutex(NULL, FALSE, NULL);

		//
		// Retrieve packet.dll version information from the file
		//
		PacketGetFileVersion(TEXT("packet.dll"), PacketLibraryVersion, sizeof(PacketLibraryVersion));

		//
		// Retrieve NPF.sys version information from the file
		//
		PacketGetFileVersion(TEXT("drivers\\npf.sys"), PacketDriverVersion, sizeof(PacketDriverVersion));

		//
		// Locate GetAdaptersAddresses dinamically since it is not present in Win2k
		//
		IPHMod = GetModuleHandle(TEXT("Iphlpapi"));
		
#ifndef _WINNT4
		GetAdaptersAddressesPointer = (GAAHandler) GetProcAddress(IPHMod ,"GetAdaptersAddresses");
#endif // _WINNT4

#ifdef HAVE_DAG_API
		/* We load dinamically 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
			ODS("dag capture library not found on this system\n");
			break;
		}

		p_dagc_open = (dagc_open_handler) GetProcAddress(DagcLib, "dagc_open");
		p_dagc_close = (dagc_close_handler) GetProcAddress(DagcLib, "dagc_close");
		p_dagc_setsnaplen = (dagc_setsnaplen_handler) GetProcAddress(DagcLib, "dagc_setsnaplen");
		p_dagc_getlinktype = (dagc_getlinktype_handler) GetProcAddress(DagcLib, "dagc_getlinktype");
		p_dagc_getlinkspeed = (dagc_getlinkspeed_handler) GetProcAddress(DagcLib, "dagc_getlinkspeed");
		p_dagc_getfcslen = (dagc_getfcslen_handler) GetProcAddress(DagcLib, "dagc_getfcslen");
		p_dagc_receive = (dagc_receive_handler) GetProcAddress(DagcLib, "dagc_receive");
		p_dagc_wait = (dagc_wait_handler) GetProcAddress(DagcLib, "dagc_wait");
		p_dagc_stats = (dagc_stats_handler) GetProcAddress(DagcLib, "dagc_stats");
		p_dagc_finddevs = (dagc_finddevs_handler) GetProcAddress(DagcLib, "dagc_finddevs");
		p_dagc_freedevs = (dagc_freedevs_handler) GetProcAddress(DagcLib, "dagc_freedevs");
		
#endif /* HAVE_DAG_API */

		break;

        case DLL_PROCESS_DETACH:

			CloseHandle(AdaptersInfoMutex);

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


			break;

		default:
            break;
    }

    return Status;
}

/*! 
  \brief Convert a Unicode dotted-quad to a 32-bit IP address.
  \param cp A string containing the address.
  \return the converted 32-bit numeric address.

   Doesn't check to make sure the address is valid.
*/

ULONG inet_addrU(const WCHAR *cp)
{
	ULONG val, part;
	WCHAR c;
	int i;

	val = 0;
	for (i = 0; i < 4; i++) {
		part = 0;
		while ((c = *cp++) != '\0' && c != '.') {
			if (c < '0' || c > '9')
				return -1;
			part = part*10 + (c - '0');
		}
		if (part > 255)
			return -1;	
		val = val | (part << i*8);
		if (i == 3) {
			if (c != '\0')
				return -1;	// extra gunk at end of string 
		} else {
			if (c == '\0')
				return -1;	// string ends early 
		}
	}
	return val;
}

/*! 
  \brief Converts an ASCII string to UNICODE. Uses the MultiByteToWideChar() system function.
  \param string The string to convert.
  \return The converted string.
*/

PWCHAR SChar2WChar(PCHAR string)
{
	PWCHAR TmpStr;
	TmpStr = (WCHAR*) GlobalAllocPtr(GMEM_MOVEABLE | GMEM_ZEROINIT, (strlen(string)+2)*sizeof(WCHAR));

	MultiByteToWideChar(CP_ACP, 0, string, -1, TmpStr, (strlen(string)+2));

	return TmpStr;
}

/*! 
  \brief Converts an UNICODE string to ASCII. Uses the WideCharToMultiByte() system function.
  \param string The string to convert.
  \return The converted string.
*/

PCHAR WChar2SChar(PWCHAR string)
{
	PCHAR TmpStr;
	TmpStr = (CHAR*) GlobalAllocPtr(GMEM_MOVEABLE | GMEM_ZEROINIT, (wcslen(string)+2));

	// Conver to ASCII
	WideCharToMultiByte(
		CP_ACP,
		0,
		string,
		-1,
		TmpStr,
		(wcslen(string)+2),          // size of buffer
		NULL,
		NULL);

	return TmpStr;
}

/*! 
  \brief Sets the maximum possible lookahead buffer for the driver's Packet_tap() function.
  \param AdapterObject Handle to the service control manager.
  \return If the function succeeds, the return value is nonzero.

  The lookahead buffer is the portion of packet that Packet_tap() can access from the NIC driver's memory
  without performing a copy. This function tries to increase the size of that buffer.
*/

BOOLEAN PacketSetMaxLookaheadsize (LPADAPTER AdapterObject)
{
    BOOLEAN    Status;
    ULONG      IoCtlBufferLength=(sizeof(PACKET_OID_DATA)+sizeof(ULONG)-1);
    PPACKET_OID_DATA  OidData;

    OidData = GlobalAllocPtr(GMEM_MOVEABLE | GMEM_ZEROINIT,IoCtlBufferLength);
    if (OidData == NULL) {
        ODS("PacketSetMaxLookaheadsize failed\n");
        return FALSE;
    }

	//set the size of the lookahead buffer to the maximum available by the the NIC driver
    OidData->Oid=OID_GEN_MAXIMUM_LOOKAHEAD;
    OidData->Length=sizeof(ULONG);
    Status=PacketRequest(AdapterObject,FALSE,OidData);
    OidData->Oid=OID_GEN_CURRENT_LOOKAHEAD;
    Status=PacketRequest(AdapterObject,TRUE,OidData);
    GlobalFreePtr(OidData);
    return Status;
}

/*! 
  \brief Retrieves the event associated in the driver with a capture instance and stores it in an 
   _ADAPTER structure.
  \param AdapterObject Handle to the service control manager.
  \return If the function succeeds, the return value is nonzero.

  This function is used by PacketOpenAdapter() to retrieve the read event from the driver by means of an ioctl
  call and set it in the _ADAPTER structure pointed by AdapterObject.
*/

BOOLEAN PacketSetReadEvt(LPADAPTER AdapterObject)
{
	DWORD BytesReturned;
	TCHAR EventName[39];

 	if (LOWORD(GetVersion()) == 4)
	{
		// retrieve the name of the shared event from the driver without the "Global\\" prefix
		if(DeviceIoControl(AdapterObject->hFile,pBIOCEVNAME,NULL,0,EventName,13*sizeof(TCHAR),&BytesReturned,NULL)==FALSE) 
			return FALSE;

		EventName[BytesReturned/sizeof(TCHAR)]=0; // terminate the string
	}
	else
	{
		// this tells the terminal service to retrieve the event from the global namespace
		wcsncpy(EventName,L"Global\\",sizeof(L"Global\\"));
		// retrieve the name of the shared event from the driver with the "Global\\" prefix
		if(DeviceIoControl(AdapterObject->hFile,pBIOCEVNAME,NULL,0,EventName + 7,13*sizeof(TCHAR),&BytesReturned,NULL)==FALSE) 
			return FALSE;

		EventName[BytesReturned/sizeof(TCHAR) + 7]=0; // terminate the string
	}

	// open the shared event
	AdapterObject->ReadEvent=CreateEvent(NULL,
										 TRUE,
										 FALSE,
										 EventName);

	if(AdapterObject->ReadEvent==NULL || GetLastError()!=ERROR_ALREADY_EXISTS){
        ODS("PacketSetReadEvt: error retrieving the event from the kernel\n");
		return FALSE;
	}

	AdapterObject->ReadTimeOut=0;

	return TRUE;
}

/*! 
  \brief Installs the NPF device driver.
  \param ascmHandle Handle to the service control manager.
  \param ascmHandle A pointer to a handle that will receive the pointer to the driver's service.
  \return If the function succeeds, the return value is nonzero.

  This function installs the driver's service in the system using the CreateService function.
*/

BOOL PacketInstallDriver(SC_HANDLE ascmHandle,SC_HANDLE *srvHandle)
{
	BOOL result = FALSE;
	ULONG err = 0;
	
	ODS("installdriver\n");
	
	*srvHandle = CreateService(ascmHandle, 
		NPFServiceName,
		NPFServiceDesc,
		SERVICE_ALL_ACCESS,
		SERVICE_KERNEL_DRIVER,
		SERVICE_DEMAND_START,
		SERVICE_ERROR_NORMAL,
		NPFDriverPath,
		NULL, NULL, NULL, NULL, NULL);
	if (*srvHandle == NULL) 
	{
		if (GetLastError() == ERROR_SERVICE_EXISTS) 
		{
			//npf.sys already existed
			result = TRUE;
		}
	}
	else 
	{
		//Created service for npf.sys
		result = TRUE;
	}
	if (result == TRUE) 
		if (*srvHandle != NULL)
			CloseServiceHandle(*srvHandle);

	if(result == FALSE){
		err = GetLastError();
		if(err != 2)
			ODSEx("PacketInstallDriver failed, Error=%d\n",err);

⌨️ 快捷键说明

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