庖丁解牛—winpcap源码彻底解密系列的续集(8)

2024-01-13 01:48

本文主要是介绍庖丁解牛—winpcap源码彻底解密系列的续集(8),希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!

设置超时,设置mintoCopy,设置内核缓冲,设置用户缓冲,设置MTU的大小,这些实现都和设置混合模式相似。讲解如下:

 

如设置内核缓冲区,代码段如下pcap_win32的pcap_activate_win32函数:

          if (p->opt.buffer_size == 0)

              p->opt.buffer_size = WIN32_DEFAULT_KERNEL_BUFFER_SIZE;

 

         if(PacketSetBuff(p->adapter,p->opt.buffer_size)==FALSE)

         {

              snprintf(p->errbuf, PCAP_ERRBUF_SIZE, "driver error: not enough memory to allocate the kernel buffer");

              goto bad;

         }

WIN32_DEFAULT_KERNEL_BUFFER_SIZE为默认的内核缓冲区大小,#define  WIN32_DEFAULT_KERNEL_BUFFER_SIZE 1000000

即winpcap默认的内核缓冲区的大小为1M。PacketSetBuff在Packet.c中定义,

*/

BOOLEAN PacketSetBuff(LPADAPTER AdapterObject,int dim)

{

     DWORD BytesReturned;

     BOOLEAN Result;

 

     TRACE_ENTER("PacketSetBuff");

 

#ifdef HAVE_WANPACKET_API

     if (AdapterObject->Flags == INFO_FLAG_NDISWAN_ADAPTER)

     {

        Result = WanPacketSetBufferSize(AdapterObject->pWanAdapter, dim);

        

         TRACE_EXIT("PacketSetBuff");

         return Result;

     }

#endif

 

#ifdef HAVE_AIRPCAP_API

     if(AdapterObject->Flags == INFO_FLAG_AIRPCAP_CARD)

     {

         Result = (BOOLEAN)g_PAirpcapSetKernelBuffer(AdapterObject->AirpcapAd, dim);

        

         TRACE_EXIT("PacketSetBuff");

         return Result;

     }

#endif // HAVE_AIRPCAP_API

 

#ifdef HAVE_NPFIM_API

     if(AdapterObject->Flags == INFO_FLAG_NPFIM_DEVICE)

     {

         Result = (BOOLEAN)g_NpfImHandlers.NpfImSetCaptureBufferSize(AdapterObject->NpfImHandle, dim);

 

         TRACE_EXIT("PacketSetBuff");

         return Result;

     }

#endif // HAVE_NPFIM_API

 

#ifdef HAVE_DAG_API

     if(AdapterObject->Flags == INFO_FLAG_DAG_CARD)

     {

         // We can't change DAG buffers

         TRACE_EXIT("PacketSetBuff");

         return TRUE;

     }

#endif // HAVE_DAG_API

 

     if (AdapterObject->Flags == INFO_FLAG_NDIS_ADAPTER)

     {

         Result = (BOOLEAN)DeviceIoControl(AdapterObject->hFile,BIOCSETBUFFERSIZE,&dim,sizeof(dim),NULL,0,&BytesReturned,NULL);

     }

     else

     {

         TRACE_PRINT1("Request to set buf size on an unknown device type (%u)", AdapterObject->Flags);

         Result = FALSE;

     }

    

     TRACE_EXIT("PacketSetBuff");

 

     return Result;

}

 

该函数同样是通过DeviceIoControl将缓冲区的size传递给内核的,IOControl码为BIOCSETBUFFERSIZE,在npf.sys中进行搜索:通样在NPF_IoControl中实现。

case BIOCSETBUFFERSIZE:

        

         TRACE_MESSAGE(PACKET_DEBUG_LOUD, "BIOCSETBUFFERSIZE");

 

 

         if(IrpSp->Parameters.DeviceIoControl.InputBufferLength < sizeof(ULONG))

         {            

              SET_FAILURE_BUFFER_SMALL();

              break;

         }

 

         // Get the number of bytes to allocate

          dim = *((PULONG)Irp->AssociatedIrp.SystemBuffer);

         //dim为获取的SystemBuffer,其值为内核缓冲区的大小;

 

         if (dim / g_NCpu < sizeof(struct PacketHeader))

         {

              dim = 0; //如果dim的size分到每个cpu后都比包头的size小,且dim=0

         }

         else

         {

              tpointer = ExAllocatePoolWithTag(NonPagedPool, dim, '6PWA'); //分配内存

              if (tpointer == NULL)

              {

                   // no memory  内存分配失败

                   SET_FAILURE_NOMEM();

                   break;

              }

         }

 

         //

         // acquire the locks for all the buffers

         //

         for (i = 0; i < g_NCpu ; i++)

         {

#pragma prefast(suppress:8103, "There's no Spinlock leak here, as it's released some lines below.")

              NdisAcquireSpinLock(&Open->CpuData[i].BufferLock); //获取每个cpu的锁

         }

 

         //

         // free the old buffer, if any

         //

         if (Open->CpuData[0].Buffer != NULL)

         {

              ExFreePool(Open->CpuData[0].Buffer); //释放原有内存

         }

 

         for (i = 0 ; i < g_NCpu ; i++)

         {

              if (dim > 0)

                   Open->CpuData[i].Buffer=(PUCHAR)tpointer + (dim/g_NCpu)*i;  //对每个cpu平均分配缓冲

              else

                   Open->CpuData[i].Buffer = NULL;

              Open->CpuData[i].Free = dim/g_NCpu;       //剩余缓冲

              Open->CpuData[i].P = 0;               //生产者

              Open->CpuData[i].C = 0;              //消费者

              Open->CpuData[i].Accepted = 0;

              Open->CpuData[i].Dropped = 0;

              Open->CpuData[i].Received = 0;

          }

 

         Open->ReaderSN=0;                    //读序列号

         Open->WriterSN=0;                     //写序列号

 

         Open->Size = dim/g_NCpu;             //open上下文的size

 

         //

         // acquire the locks for all the buffers  释放锁

         //

         i = g_NCpu;

 

         do

         {

              i--;

 

#pragma prefast(suppress:8107, "There's no Spinlock leak here, as it's acquired some lines above.")

              NdisReleaseSpinLock(&Open->CpuData[i].BufferLock);

         }while(i != 0);

 

         SET_RESULT_SUCCESS(0);

         break;

 

该函数将内核缓冲区的size平均到每一个cpu,并将它们保存在Open上下文中;open上下文的结构如下:

typedef struct _OPEN_INSTANCE

{

     PDEVICE_EXTENSION   DeviceExtension; ///< Pointer to the _DEVICE_EXTENSION structure of the device on which

                                                   ///< the instance is bound.

     NDIS_HANDLE         AdapterHandle;        ///< NDIS idetifier of the adapter used by this instance.

     UINT               Medium;                ///< Type of physical medium the underlying NDIS driver uses. See the

                                               ///< documentation of NdisOpenAdapter in the MS DDK for details.

     NDIS_HANDLE         PacketPool;           ///< Pool of NDIS_PACKET structures used to transfer the packets from and to the NIC driver.

     KSPIN_LOCK             RequestSpinLock;   ///< SpinLock used to synchronize the OID requests.

     LIST_ENTRY          RequestList;     ///< List of pending OID requests.

     LIST_ENTRY          ResetIrpList;         ///< List of pending adapter reset requests.

    INTERNAL_REQUEST    Requests[MAX_REQUESTS]; ///< Array of structures that wrap every single OID request.

     PMDL               BufferMdl;             ///< Pointer to a Memory descriptor list (MDL) that maps the circular buffer's memory.

     PKEVENT                ReadEvent;             ///< Pointer to the event on which the read calls on this instance must wait.

     PUCHAR                 bpfprogram;            ///< Pointer to the filtering pseudo-code associated with current instance of the driver.

                                                   ///< This code is used only in particular situations (for example when the packet received

                                                   ///< from the NIC driver is stored in two non-consecutive buffers. In normal situations

                                                   ///< the filtering routine created by the JIT compiler and pointed by the next field

                                                   ///< is used. See \ref NPF for details on the filtering process.

#ifdef _X86_

     JIT_BPF_Filter         *Filter;           ///< Pointer to the native filtering function created by the jitter.

                                                   ///< See BPF_jitter() for details.

#endif //_X86_

     UINT               MinToCopy;             ///< Minimum amount of data in the circular buffer that unlocks a read. Set with the

                                                   ///< BIOCSMINTOCOPY IOCTL.

     LARGE_INTEGER      TimeOut;           ///< Timeout after which a read is released, also if the amount of data in the buffer is

                                                   ///< less than MinToCopy. Set with the BIOCSRTIMEOUT IOCTL.

                                                  

     int                    mode;                  ///< Working mode of the driver. See PacketSetMode() for details.

     LARGE_INTEGER      Nbytes;                ///< Amount of bytes accepted by the filter when this instance is in statistical mode.

     LARGE_INTEGER      Npackets;          ///< Number of packets accepted by the filter when this instance is in statistical mode.

     NDIS_SPIN_LOCK         CountersLock;      ///< SpinLock that protects the statistical mode counters.

     UINT               Nwrites;           ///< Number of times a single write must be physically repeated. See \ref NPF for an

                                                   ///< explanation

     ULONG                  Multiple_Write_Counter; ///< Counts the number of times a single write has already physically repeated.

     NDIS_EVENT             WriteEvent;            ///< Event used to synchronize the multiple write process.

     BOOLEAN                WriteInProgress;   ///< True if a write is currently in progress. NPF currently allows a single wite on

                                                   ///< the same open instance.

     NDIS_SPIN_LOCK         WriteLock;             ///< SpinLock that protects the WriteInProgress variable.

     NDIS_EVENT             NdisRequestEvent;  ///< Event used to synchronize I/O requests with the callback structure of NDIS.

     BOOLEAN                SkipSentPackets;   ///< True if this instance should not capture back the packets that it transmits.

     NDIS_STATUS            IOStatus;          ///< Maintains the status of and OID request call, that will be passed to the application.

     HANDLE                 DumpFileHandle;        ///< Handle of the file used in dump mode.

     PFILE_OBJECT       DumpFileObject;        ///< Pointer to the object of the file used in dump mode.

     PKTHREAD           DumpThreadObject;  ///< Pointer to the object of the thread used in dump mode.

     HANDLE                 DumpThreadHandle;  ///< Handle of the thread created by dump mode to asynchronously move the buffer to disk.

     NDIS_EVENT             DumpEvent;             ///< Event used to synchronize the dump thread with the tap when the instance is in dump mode.

     LARGE_INTEGER      DumpOffset;            ///< Current offset in the dump file.

     UNICODE_STRING      DumpFileName;         ///< String containing the name of the dump file.

     UINT               MaxDumpBytes;      ///< Maximum dimension in bytes of the dump file. If the dump file reaches this size it

                                                   ///< will be closed. A value of 0 means unlimited size.

     UINT               MaxDumpPacks;      ///< Maximum number of packets that will be saved in the dump file. If this number of

                                                   ///< packets is reached the dump will be closed. A value of 0 means unlimited number of

                                                   ///< packets.

     BOOLEAN                DumpLimitReached;  ///< TRUE if the maximum dimension of the dump file (MaxDumpBytes or MaxDumpPacks) is

                                                   ///< reached.

#ifdef HAVE_BUGGY_TME_SUPPORT

     MEM_TYPE           mem_ex;                ///< Memory used by the TME virtual co-processor

     TME_CORE           tme;               ///< Data structure containing the virtualization of the TME co-processor

#endif //HAVE_BUGGY_TME_SUPPORT

 

     NDIS_SPIN_LOCK         MachineLock;       ///< SpinLock that protects the BPF filter and the TME engine, if in use.

     UINT               MaxFrameSize;      ///< Maximum frame size that the underlying MAC acceptes. Used to perform a check on the

                                                   ///< size of the frames sent with NPF_Write() or NPF_BufferedWrite().

     //

     // KAFFINITY is used as a bit mask for the affinity in the system. So on every supported OS is big enough for all the CPUs on the system (32 bits on x86, 64 on x64?).

     // We use its size to compute the max number of CPUs.

     //

     CpuPrivateData         CpuData[sizeof(KAFFINITY) * 8];      ///< Pool of kernel buffer structures, one for each CPU.

     ULONG                  ReaderSN;          ///< Sequence number of the next packet to be read from the pool of kernel buffers.

     ULONG                  WriterSN;          ///< Sequence number of the next packet to be written in the pool of kernel buffers.

                                                   ///< These two sequence numbers are unique for each capture instance.

     ULONG                  Size;                  ///< Size of each kernel buffer contained in the CpuData field.

     ULONG                 AdapterHandleUsageCounter;

     NDIS_SPIN_LOCK        AdapterHandleLock;

     ULONG                 AdapterBindingStatus;    ///< Specifies if NPF is still bound to the adapter used by this instance, it's unbinding or it's not bound.   

 

     NDIS_EVENT            NdisOpenCloseCompleteEvent;

     NDIS_EVENT            NdisWriteCompleteEvent;  ///< Event that is signalled when all the packets have been successfully sent by NdisSend (and corresponfing sendComplete has been called)

     NTSTATUS         OpenCloseStatus;

     ULONG                 TransmitPendingPackets;  ///< Specifies the number of packets that are pending to be transmitted, i.e. have been submitted to NdisSendXXX but the SendComplete has not been called yet.

     ULONG                 NumPendingIrps;

     BOOLEAN               ClosePending;

     NDIS_SPIN_LOCK        OpenInUseLock;

}

OPEN_INSTANCE, *POPEN_INSTANCE;

 

设置mintoCopy的方法和设置内核缓冲区类似,不在进行讲解。

这篇关于庖丁解牛—winpcap源码彻底解密系列的续集(8)的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!



http://www.chinasem.cn/article/599856

相关文章

Java中使用Hutool进行AES加密解密的方法举例

《Java中使用Hutool进行AES加密解密的方法举例》AES是一种对称加密,所谓对称加密就是加密与解密使用的秘钥是一个,下面:本文主要介绍Java中使用Hutool进行AES加密解密的相关资料... 目录前言一、Hutool简介与引入1.1 Hutool简介1.2 引入Hutool二、AES加密解密基础

Java调用C++动态库超详细步骤讲解(附源码)

《Java调用C++动态库超详细步骤讲解(附源码)》C语言因其高效和接近硬件的特性,时常会被用在性能要求较高或者需要直接操作硬件的场合,:本文主要介绍Java调用C++动态库的相关资料,文中通过代... 目录一、直接调用C++库第一步:动态库生成(vs2017+qt5.12.10)第二步:Java调用C++

Python实现无痛修改第三方库源码的方法详解

《Python实现无痛修改第三方库源码的方法详解》很多时候,我们下载的第三方库是不会有需求不满足的情况,但也有极少的情况,第三方库没有兼顾到需求,本文将介绍几个修改源码的操作,大家可以根据需求进行选择... 目录需求不符合模拟示例 1. 修改源文件2. 继承修改3. 猴子补丁4. 追踪局部变量需求不符合很

Spring 中 BeanFactoryPostProcessor 的作用和示例源码分析

《Spring中BeanFactoryPostProcessor的作用和示例源码分析》Spring的BeanFactoryPostProcessor是容器初始化的扩展接口,允许在Bean实例化前... 目录一、概览1. 核心定位2. 核心功能详解3. 关键特性二、Spring 内置的 BeanFactory

Go中sync.Once源码的深度讲解

《Go中sync.Once源码的深度讲解》sync.Once是Go语言标准库中的一个同步原语,用于确保某个操作只执行一次,本文将从源码出发为大家详细介绍一下sync.Once的具体使用,x希望对大家有... 目录概念简单示例源码解读总结概念sync.Once是Go语言标准库中的一个同步原语,用于确保某个操

Java汇编源码如何查看环境搭建

《Java汇编源码如何查看环境搭建》:本文主要介绍如何在IntelliJIDEA开发环境中搭建字节码和汇编环境,以便更好地进行代码调优和JVM学习,首先,介绍了如何配置IntelliJIDEA以方... 目录一、简介二、在IDEA开发环境中搭建汇编环境2.1 在IDEA中搭建字节码查看环境2.1.1 搭建步

Spring Security 从入门到进阶系列教程

Spring Security 入门系列 《保护 Web 应用的安全》 《Spring-Security-入门(一):登录与退出》 《Spring-Security-入门(二):基于数据库验证》 《Spring-Security-入门(三):密码加密》 《Spring-Security-入门(四):自定义-Filter》 《Spring-Security-入门(五):在 Sprin

JAVA智听未来一站式有声阅读平台听书系统小程序源码

智听未来,一站式有声阅读平台听书系统 🌟&nbsp;开篇:遇见未来,从“智听”开始 在这个快节奏的时代,你是否渴望在忙碌的间隙,找到一片属于自己的宁静角落?是否梦想着能随时随地,沉浸在知识的海洋,或是故事的奇幻世界里?今天,就让我带你一起探索“智听未来”——这一站式有声阅读平台听书系统,它正悄悄改变着我们的阅读方式,让未来触手可及! 📚&nbsp;第一站:海量资源,应有尽有 走进“智听

科研绘图系列:R语言扩展物种堆积图(Extended Stacked Barplot)

介绍 R语言的扩展物种堆积图是一种数据可视化工具,它不仅展示了物种的堆积结果,还整合了不同样本分组之间的差异性分析结果。这种图形表示方法能够直观地比较不同物种在各个分组中的显著性差异,为研究者提供了一种有效的数据解读方式。 加载R包 knitr::opts_chunk$set(warning = F, message = F)library(tidyverse)library(phyl

【生成模型系列(初级)】嵌入(Embedding)方程——自然语言处理的数学灵魂【通俗理解】

【通俗理解】嵌入(Embedding)方程——自然语言处理的数学灵魂 关键词提炼 #嵌入方程 #自然语言处理 #词向量 #机器学习 #神经网络 #向量空间模型 #Siri #Google翻译 #AlexNet 第一节:嵌入方程的类比与核心概念【尽可能通俗】 嵌入方程可以被看作是自然语言处理中的“翻译机”,它将文本中的单词或短语转换成计算机能够理解的数学形式,即向量。 正如翻译机将一种语言