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

📄 packet.h

📁 Windows XP下的抓包程序实现
💻 H
📖 第 1 页 / 共 3 页
字号:
/*
 * 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.
 *
 */

/** @addtogroup NPF 
 *  @{
 */

/** @defgroup NPF_include NPF structures and definitions 
 *  @{
 */

#ifndef __PACKET_INCLUDE______
#define __PACKET_INCLUDE______

#ifdef __NPF_x86__
#define NTKERNEL	///< Forces the compilation of the jitter with kernel calls 
#include "jitter.h"
#endif

//
// Needed to disable a warning due to the #pragma prefast directives,
// that are ignored by the normal DDK compiler
//
#ifndef _PREFAST_
#pragma warning(disable:4068)
#endif

#include "win_bpf.h"

#define  MAX_REQUESTS   32 ///< Maximum number of simultaneous IOCTL requests.

#define Packet_ALIGNMENT sizeof(int) ///< Alignment macro. Defines the alignment size.
#define Packet_WORDALIGN(x) (((x)+(Packet_ALIGNMENT-1))&~(Packet_ALIGNMENT-1))	///< Alignment macro. Rounds up to the next 
																				///< even multiple of Packet_ALIGNMENT. 

#define KERNEL_EVENT_NAMESPACE L"\\BaseNamedObjects\\"

/***************************/
/*         IOCTLs          */
/***************************/

/*!
  \brief IOCTL code: set kernel buffer size.

  This IOCTL is used to set a new size of the circular buffer associated with an instance of NPF.
  When a BIOCSETBUFFERSIZE command is received, the driver frees the old buffer, allocates the new one 
  and resets all the parameters associated with the buffer in the OPEN_INSTANCE structure. The currently 
  buffered packets are lost.
*/
#define	 BIOCSETBUFFERSIZE 9592

/*!
  \brief IOCTL code: set packet filtering program.

  This IOCTL sets a new packet filter in the driver. Before allocating any memory for the new filter, the 
  bpf_validate() function is called to check the correctness of the filter. If this function returns TRUE, 
  the filter is copied to the driver's memory, its address is stored in the bpfprogram field of the 
  OPEN_INSTANCE structure associated with current instance of the driver, and the filter will be applied to 
  every incoming packet. This command also empties the circular buffer used by current instance 
  to store packets. This is done to avoid the presence in the buffer of packets that do not match the filter.
*/
#define	 BIOCSETF 9030

/*!
  \brief IOCTL code: get the capture stats

  This command returns to the application the number of packets received and the number of packets dropped by 
  an instance of the driver.
*/
#define  BIOCGSTATS 9031

/*!
  \brief IOCTL code: set the read timeout

  This command sets the maximum timeout after which a read is released, also if no data packets were received.
*/
#define	 BIOCSRTIMEOUT 7416

/*!
  \brief IOCTL code: set working mode

  This IOCTL can be used to set the working mode of a NPF instance. The new mode, received by the driver in the
  buffer associated with the IOCTL command, can be #MODE_CAPT for capture mode (the default), #MODE_STAT for
  statistical mode or #MODE_DUMP for dump mode.
*/
#define	 BIOCSMODE 7412

/*!
  \brief IOCTL code: set number of physical repetions of every packet written by the app

  Sets the number of times a single write call must be repeated. This command sets the OPEN_INSTANCE::Nwrites 
  member, and is used to implement the 'multiple write' feature of the driver.
*/
#define	 BIOCSWRITEREP 7413

/*!
  \brief IOCTL code: set minimum amount of data in the kernel buffer that unlocks a read call

  This command sets the OPEN_INSTANCE::MinToCopy member.
*/
#define	 BIOCSMINTOCOPY 7414

/*!
  \brief IOCTL code: set an OID value

  This IOCTL is used to perform an OID set operation on the NIC driver. 
*/
#define	 BIOCSETOID 2147483648

/*!
  \brief IOCTL code: get an OID value

  This IOCTL is used to perform an OID get operation on the NIC driver. 
*/
#define	 BIOCQUERYOID 2147483652

/*!
  \brief IOCTL code: set the name of a the file used by kernel dump mode

  This command opens a file whose name is contained in the IOCTL buffer and associates it with current NPf instance.
  The dump thread uses it to copy the content of the circular buffer to file.
  If a file was already opened, the driver closes it before opening the new one.
*/
#define  BIOCSETDUMPFILENAME 9029

/*!
  \brief IOCTL code: get the name of the event that the driver signals when some data is present in the buffer

  Command used by the application to retrieve the name of the global event associated with a NPF instance.
  The event is signaled by the driver when the kernel buffer contains enough data for a transfer.
*/
#define  BIOCGEVNAME 7415

/*!
  \brief IOCTL code: Send a buffer containing multiple packets to the network, ignoring the timestamps.

  Command used to send a buffer of packets in a single system call. Every packet in the buffer is preceded by
  a sf_pkthdr structure. The timestamps of the packets are ignored, i.e. the packets are sent as fast as 
  possible. The NPF_BufferedWrite() function is invoked to send the packets.
*/
#define  BIOCSENDPACKETSNOSYNC 9032

/*!
  \brief IOCTL code: Send a buffer containing multiple packets to the network, considering the timestamps.

  Command used to send a buffer of packets in a single system call. Every packet in the buffer is preceded by
  a sf_pkthdr structure. The timestamps of the packets are used to synchronize the write, i.e. the packets 
  are sent to the network respecting the intervals specified in the sf_pkthdr structure assiciated with each
  packet. NPF_BufferedWrite() function is invoked to send the packets. 
*/
#define  BIOCSENDPACKETSSYNC 9033

/*!
  \brief IOCTL code: Set the dump file limits.

  This IOCTL sets the limits (maximum size and maximum number of packets) of the dump file created when the
  driver works in dump mode.
*/
#define  BIOCSETDUMPLIMITS 9034

/*!
  \brief IOCTL code: Get the status of the kernel dump process.

  This command returns TRUE if the kernel dump is ended, i.e if one of the limits set with BIOCSETDUMPLIMITS
  (amount of bytes or number of packets) has been reached.
*/
#define BIOCISDUMPENDED 7411

/*!
  \brief IOCTL code: set the loopback behavior.

  This IOCTL sets the loopback behavior of the driver with packets sent by itself: capture or drop.
*/
#define  BIOCISETLOBBEH 7410			

/*!
	\brief This IOCTL passes the read event HANDLE allocated by the user (packet.dll) to kernel level

	Parameter: HANDLE
	Parameter size: sizeof(HANDLE). If the caller is 32 bit, the parameter size is 4 bytes, even if sizeof(HANDLE) at kernel level
		is 8 bytes. That's why in this IOCTL code handler we detect a 32bit calling process and do the necessary thunking.

	TODO GV:I will go to hell for this ugly IOCTL definition. We should use CTL_CODE!!
*/
#define BIOCSETEVENTHANDLE 7920

// Working modes
#define MODE_CAPT 0x0		///< Capture working mode
#define MODE_STAT 0x1		///< Statistical working mode
#define MODE_MON  0x2		///< Kernel monitoring mode
#define MODE_DUMP 0x10		///< Kernel dump working mode


#define IMMEDIATE 1			///< Immediate timeout. Forces a read call to return immediately.

#define NDIS_FLAGS_SKIP_LOOPBACK_W2K    0x400 ///< This is an undocumented flag for NdisSetPacketFlags() that allows to disable loopback reception.

// The following definitions are used to provide compatibility 
// of the dump files with the ones of libpcap
#define TCPDUMP_MAGIC 0xa1b2c3d4	///< Libpcap magic number. Used by programs like tcpdump to recognize a driver's generated dump file.
#define PCAP_VERSION_MAJOR 2		///< Major libpcap version of the dump file. Used by programs like tcpdump to recognize a driver's generated dump file.
#define PCAP_VERSION_MINOR 4		///< Minor libpcap version of the dump file. Used by programs like tcpdump to recognize a driver's generated dump file.

// Loopback behaviour definitions
#define NPF_DISABLE_LOOPBACK	1	///< Tells the driver to drop the packets sent by itself. This is usefult when building applications like bridges.
#define NPF_ENABLE_LOOPBACK		2	///< Tells the driver to capture the packets sent by itself.

/*!
  \brief Header of a libpcap dump file.

  Used when a driver instance is set in dump mode to create a libpcap-compatible file.
*/
struct packet_file_header 
{
	UINT magic;				///< Libpcap magic number
	USHORT version_major;	///< Libpcap major version
	USHORT version_minor;	///< Libpcap minor version
	UINT thiszone;			///< Gmt to local correction
	UINT sigfigs;			///< Accuracy of timestamps
	UINT snaplen;			///< Length of the max saved portion of each packet
	UINT linktype;			///< Data link type (DLT_*). See win_bpf.h for details.
};

/*!
  \brief Header associated to a packet in the driver's buffer when the driver is in dump mode.
  Similar to the bpf_hdr structure, but simpler.
*/
struct sf_pkthdr {
    struct timeval	ts;			///< time stamp
    UINT			caplen;		///< Length of captured portion. The captured portion can be different from 
								///< the original packet, because it is possible (with a proper filter) to 
								///< instruct the driver to capture only a portion of the packets. 
    UINT			len;		///< Length of the original packet (off wire).
};

/*!
  \brief Stores an OID request.
  
  This structure is used by the driver to perform OID query or set operations on the underlying NIC driver. 
  The OID operations be performed usually only by network drivers, but NPF exports this mechanism to user-level 
  applications through an IOCTL interface. The driver uses this structure to wrap a NDIS_REQUEST structure.
  This allows to handle correctly the callback structure of NdisRequest(), handling multiple requests and
  maintaining information about the IRPs to complete.
*/
typedef struct _INTERNAL_REQUEST {
    LIST_ENTRY		ListElement;		///< Used to handle lists of requests.
//    PIRP			Irp;				///< Irp that performed the request
//	BOOLEAN			Internal;			///< True if the request is for internal use of npf.sys. False if the request is performed by the user through an IOCTL.
	NDIS_EVENT		InternalRequestCompletedEvent;
    NDIS_REQUEST	Request;			///< The structure with the actual request, that will be passed to NdisRequest().
	NDIS_STATUS		RequestStatus;

} INTERNAL_REQUEST, *PINTERNAL_REQUEST;

/*!
  \brief Contains a NDIS packet.
  
  The driver uses this structure to wrap a NDIS_PACKET  structure.
  This allows to handle correctly the callback structure of NdisTransferData(), handling multiple requests and
  maintaining information about the IRPs to complete.
*/
typedef struct _PACKET_RESERVED {
    LIST_ENTRY		ListElement;		///< Used to handle lists of packets.
    PIRP			Irp;				///< Irp that performed the request
    PMDL			pMdl;				///< MDL mapping the buffer of the packet.
	BOOLEAN			FreeBufAfterWrite;	///< True if the memory buffer associated with the packet must be freed 
										///< after a call to NdisSend().
	ULONG			Cpu;				///< The CPU on which the packet was pulled out of the linked list of free packets
}  PACKET_RESERVED, *PPACKET_RESERVED;

#define RESERVED(_p) ((PPACKET_RESERVED)((_p)->ProtocolReserved)) ///< Macro to obtain a NDIS_PACKET from a PACKET_RESERVED

/*!
  \brief Port device extension.
  
  Structure containing some data relative to every adapter on which NPF is bound.
*/
typedef struct _DEVICE_EXTENSION {
    NDIS_HANDLE    NdisProtocolHandle;	///< NDIS handle of NPF.
    NDIS_STRING    AdapterName;			///< Name of the adapter.
	PWSTR		   ExportString;		///< Name of the exported device, i.e. name that the applications will use 
										///< to open this adapter through WinPcap.
} DEVICE_EXTENSION, *PDEVICE_EXTENSION;

/*!
  \brief Kernel buffer of each CPU.

  Structure containing the kernel buffer (and other CPU related fields) used to capture packets.
*/
typedef struct __CPU_Private_Data
{
	ULONG	P;					///< Zero-based index of the producer in the buffer. It indicates the first free byte to be written.
	ULONG	C;					///< Zero-based index of the consumer in the buffer. It indicates the first free byte to be read.
	ULONG	Free;				///< Number of the free bytes in the buffer
	PUCHAR	Buffer;				///< Pointer to the kernel buffer used to capture packets.
	ULONG	Accepted;			///< Number of packet that current capture instance acepted, from its opening. A packet 
								///< is accepted if it passes the filter and fits in the buffer. Accepted packets are the
								///< ones that reach the application. 
								///< This number is related to the particular CPU this structure is referring to.
	ULONG	Received;			///< Number of packets received by current instance from its opening, i.e. number of 
								///< packet received by the network adapter since the beginning of the 
								///< capture/monitoring/dump session. 
								///< This number is related to the particular CPU this structure is referring to.
	ULONG	Dropped;			///< Number of packet that current instance had to drop, from its opening. A packet 
								///< is dropped if there is no more space to store it in the circular buffer that the 
								///< driver associates to current instance. 
								///< This number is related to the particular CPU this structure is referring to.
	NDIS_SPIN_LOCK BufferLock;	///< It protects the buffer associated with this CPU.
	PMDL    TransferMdl1;		///< MDL used to map the portion of the buffer that will contain an incoming packet. 
	PMDL    TransferMdl2;		///< Second MDL used to map the portion of the buffer that will contain an incoming packet. 
	ULONG	NewP;				///< Used by NdisTransferData() (when we call NdisTransferData, p index must be updated only in the TransferDataComplete.
}
	CpuPrivateData;


⌨️ 快捷键说明

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