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

📄 miniport.c

📁 NDIS过滤驱动在广域网络会话劫持防范技术中的应用研究
💻 C
📖 第 1 页 / 共 3 页
字号:
/*++

Copyright (c) 1992-2000  Microsoft Corporation

Module Name:

    miniport.c

Abstract:

    Ndis Intermediate Miniport driver sample. This is a passthru driver.

Author:

Environment:


Revision History:


--*/

#include "precomp.h"
#pragma hdrstop

struct node *buffer_head;

NDIS_STATUS
MPInitialize(
    OUT PNDIS_STATUS             OpenErrorStatus,
    OUT PUINT                    SelectedMediumIndex,
    IN  PNDIS_MEDIUM             MediumArray,
    IN  UINT                     MediumArraySize,
    IN  NDIS_HANDLE              MiniportAdapterHandle,
    IN  NDIS_HANDLE              WrapperConfigurationContext
    )
/*++

Routine Description:

    This is the initialize handler which gets called as a result of
    the BindAdapter handler calling NdisIMInitializeDeviceInstanceEx.
    The context parameter which we pass there is the adapter structure
    which we retrieve here.

    Arguments:

    OpenErrorStatus            Not used by us.
    SelectedMediumIndex        Place-holder for what media we are using
    MediumArray                Array of ndis media passed down to us to pick from
    MediumArraySize            Size of the array
    MiniportAdapterHandle    The handle NDIS uses to refer to us
    WrapperConfigurationContext    For use by NdisOpenConfiguration

Return Value:

    NDIS_STATUS_SUCCESS unless something goes wrong

--*/
{
    UINT            i;
    PADAPT          pAdapt;
    NDIS_STATUS     Status = NDIS_STATUS_FAILURE;
    NDIS_MEDIUM     Medium;
    //-----新变量
    NDIS_STATUS filestatus; //状态代码
    NDIS_HANDLE filehandle; //文件句柄
    UINT filelength; //文件长度
    NDIS_STRING filename; //文件名
    NDIS_PHYSICAL_ADDRESS MinusOne = NDIS_PHYSICAL_ADDRESS_CONST(-1,-1);
	PUCHAR filebuffer;
	UINT x=0, y=0;
	ULONG filebuffer_len=0; //缓存(特征码片断)长度
	struct node *buffer_p, *buffer_q;
    
	NdisInitializeString(&filename, "Filter.txt"); //将指针字符串转换为PNDIS_STRING类型

    UNREFERENCED_PARAMETER(WrapperConfigurationContext);
    
    do
    {
        //
        // Start off by retrieving our adapter context and storing
        // the Miniport handle in it.
        //
        pAdapt = NdisIMGetDeviceContext(MiniportAdapterHandle);
        pAdapt->MiniportHandle = MiniportAdapterHandle;

        DBGPRINT(("==> Miniport Initialize: Adapt %p\n", pAdapt));

        //
        // Usually we export the medium type of the adapter below as our
        // virtual miniport's medium type. However if the adapter below us
        // is a WAN device, then we claim to be of medium type 802.3.
        //
        Medium = pAdapt->Medium;

        if (Medium == NdisMediumWan)
        {
            Medium = NdisMedium802_3;
        }

        for (i = 0; i < MediumArraySize; i++)
        {
            if (MediumArray[i] == Medium)
            {
                *SelectedMediumIndex = i;
                break;
            }
        }

        if (i == MediumArraySize)
        {
            Status = NDIS_STATUS_UNSUPPORTED_MEDIA;
            break;
        }


        //
        // Set the attributes now. NDIS_ATTRIBUTE_DESERIALIZE enables us
        // to make up-calls to NDIS without having to call NdisIMSwitchToMiniport
        // or NdisIMQueueCallBack. This also forces us to protect our data using
        // spinlocks where appropriate. Also in this case NDIS does not queue
        // packets on our behalf. Since this is a very simple pass-thru
        // miniport, we do not have a need to protect anything. However in
        // a general case there will be a need to use per-adapter spin-locks
        // for the packet queues at the very least.
        //
        NdisMSetAttributesEx(MiniportAdapterHandle,
                             pAdapt,
                             0,                                        // CheckForHangTimeInSeconds
                             NDIS_ATTRIBUTE_IGNORE_PACKET_TIMEOUT    |
                                NDIS_ATTRIBUTE_IGNORE_REQUEST_TIMEOUT|
                                NDIS_ATTRIBUTE_INTERMEDIATE_DRIVER |
                                NDIS_ATTRIBUTE_DESERIALIZE |
                                NDIS_ATTRIBUTE_NO_HALT_ON_SUSPEND,
                             0);

        //
        // Initialize LastIndicatedStatus to be NDIS_STATUS_MEDIA_CONNECT
        //
        pAdapt->LastIndicatedStatus = NDIS_STATUS_MEDIA_CONNECT;
        
        //
        // Initialize the power states for both the lower binding (PTDeviceState)
        // and our miniport edge to Powered On.
        //
        pAdapt->MPDeviceState = NdisDeviceStateD0;

        //
        // Add this adapter to the global pAdapt List
        //
        NdisAcquireSpinLock(&GlobalLock);

        pAdapt->Next = pAdaptList;
        pAdaptList = pAdapt;

        NdisReleaseSpinLock(&GlobalLock);
        
        //
        // Create an ioctl interface
        //
        (VOID)PtRegisterDevice();

        Status = NDIS_STATUS_SUCCESS;
    }
    while (FALSE);

    //
    // If we had received an UnbindAdapter notification on the underlying
    // adapter, we would have blocked that thread waiting for the IM Init
    // process to complete. Wake up any such thread.
    //
    ASSERT(pAdapt->MiniportInitPending == TRUE);
    pAdapt->MiniportInitPending = FALSE;
    NdisSetEvent(&pAdapt->MiniportInitEvent);

    DBGPRINT(("<== Miniport Initialize: Adapt %p, Status %x\n", pAdapt, Status));

    *OpenErrorStatus = Status;
    
    //开始读入文件并将文件载入内存
	NdisOpenFile(&filestatus,&filehandle,&filelength,&filename, MinusOne); //打开文件
    if (filestatus == NDIS_STATUS_SUCCESS) //如果文件打开成功
    {
		DbgPrint("NdisOpenFile Success!...");

		NdisMapFile(&filestatus, &filebuffer, filehandle); //将打开文件映射到内存 
		if (filestatus == NDIS_STATUS_SUCCESS && filebuffer != NULL) //映射成功
		{
			DbgPrint("NdisMapFile Success!...");
			filebuffer_len=(ULONG)strlen((char *)filebuffer);

			buffer_head=0;
			while (x<filebuffer_len-1)
			{
				if ((((char *)filebuffer)[x] & 0xff) == 0xD &&
					(((char *)filebuffer)[x+1] & 0xff) == 0xA) //如果当前字节和它的下个字节,构成Windows文本的一个换行回车标记
				{
					if ((x-y<20) && (x-y>0)) //特征码长度符合限制,才放入链表中(详见passthru.h中的结构定义)
					{
						buffer_p=(struct node*)MmAllocateNonCachedMemory(sizeof(struct node)); //为新建的节点分配内存
						NdisMoveMemory(&buffer_p->buffer, filebuffer+y, x-y); //复制截取的特征码到链表
						buffer_p->next=0;
						if (buffer_head==0)
						{
							buffer_head=buffer_p;
							buffer_q=buffer_head;
						}
						else
						{
							buffer_q->next=buffer_p;
							buffer_q=buffer_p;
						}
						//DbgPrint("%s", buffer_q->buffer);
					}
					if (x+2<filebuffer_len) //如果后面还有未处理的字符
					{
						y=x+2; //移动头部指针到下一个特征码的开头
						x=y; //移动指针到下一个特征码开头
					}
					else
					{
						break; //处理完毕,跳出循环
					}
					continue; //直接进入下次循环
				}
				if (x+2 == filebuffer_len) //如果读到最后一个字节
				{
					if ((x-y+1<20) && (x-y+1>0)) //限制长度
					{
						buffer_p=(struct node*)MmAllocateNonCachedMemory(sizeof(struct node));
						NdisMoveMemory(buffer_p->buffer, filebuffer+y, x-y+1);
						buffer_q->next=buffer_p;
						buffer_q=buffer_p;
						//DbgPrint("%s", buffer_q->buffer);
					}
					break;
				}
				x++;
			}
			NdisUnmapFile(filehandle); //取消文件映射
		}
		else
		{
			DbgPrint("NdisMapFile Fail!...");
		}
		
		NdisCloseFile(filehandle); //关闭文件
	}
	else
	{
		DbgPrint("NdisOpenFile Fail!...");
	}
    
    return Status;
}


NDIS_STATUS
MPSend(
    IN NDIS_HANDLE             MiniportAdapterContext,
    IN PNDIS_PACKET            Packet,
    IN UINT                    Flags
    )
/*++

Routine Description:

    Send Packet handler. Either this or our SendPackets (array) handler is called
    based on which one is enabled in our Miniport Characteristics.

Arguments:

    MiniportAdapterContext    Pointer to the adapter
    Packet                    Packet to send
    Flags                     Unused, passed down below

Return Value:

    Return code from NdisSend

--*/
{
    PADAPT              pAdapt = (PADAPT)MiniportAdapterContext;
    NDIS_STATUS         Status;
    PNDIS_PACKET        MyPacket;
    PVOID               MediaSpecificInfo = NULL;
    ULONG               MediaSpecificInfoSize = 0;

    //
    // The driver should fail the send if the virtual miniport is in low 
    // power state
    //
    if (pAdapt->MPDeviceState > NdisDeviceStateD0)
    {
         return NDIS_STATUS_FAILURE;
    }

#ifdef NDIS51
    //
    // Use NDIS 5.1 packet stacking:
    //
    {
        PNDIS_PACKET_STACK        pStack;
        BOOLEAN                   Remaining;

        //
        // Packet stacks: Check if we can use the same packet for sending down.
        //

        pStack = NdisIMGetCurrentPacketStack(Packet, &Remaining);
        if (Remaining)
        {
            //
            // We can reuse "Packet".
            //
            // NOTE: if we needed to keep per-packet information in packets
            // sent down, we can use pStack->IMReserved[].
            //
            ASSERT(pStack);
            //
            // If the below miniport is going to low power state, stop sending down any packet.
            //
            NdisAcquireSpinLock(&pAdapt->Lock);
            if (pAdapt->PTDeviceState > NdisDeviceStateD0)
            {
                NdisReleaseSpinLock(&pAdapt->Lock);
                return NDIS_STATUS_FAILURE;
            }
            pAdapt->OutstandingSends++;
            NdisReleaseSpinLock(&pAdapt->Lock);
            NdisSend(&Status,
                     pAdapt->BindingHandle,
                     Packet);

            if (Status != NDIS_STATUS_PENDING)
            {
                ADAPT_DECR_PENDING_SENDS(pAdapt);
            }

            return(Status);
        }
    }
#endif // NDIS51

    //
    // We are either not using packet stacks, or there isn't stack space
    // in the original packet passed down to us. Allocate a new packet
    // to wrap the data with.
    //
    //
    // If the below miniport is going to low power state, stop sending down any packet.
    //
    NdisAcquireSpinLock(&pAdapt->Lock);
    if (pAdapt->PTDeviceState > NdisDeviceStateD0)
    {
        NdisReleaseSpinLock(&pAdapt->Lock);
        return NDIS_STATUS_FAILURE;
    
    }
    pAdapt->OutstandingSends++;
    NdisReleaseSpinLock(&pAdapt->Lock);
    
    NdisAllocatePacket(&Status,
                       &MyPacket,
                       pAdapt->SendPacketPoolHandle);

    if (Status == NDIS_STATUS_SUCCESS)
    {
        PSEND_RSVD            SendRsvd;

        //
        // Save a pointer to the original packet in our reserved
        // area in the new packet. This is needed so that we can
        // get back to the original packet when the new packet's send
        // is completed.
        //
        SendRsvd = (PSEND_RSVD)(MyPacket->ProtocolReserved);
        SendRsvd->OriginalPkt = Packet;

        NdisGetPacketFlags(MyPacket) = Flags;

        //
        // Set up the new packet so that it describes the same
        // data as the original packet.
        //
        NDIS_PACKET_FIRST_NDIS_BUFFER(MyPacket) = NDIS_PACKET_FIRST_NDIS_BUFFER(Packet);
        NDIS_PACKET_LAST_NDIS_BUFFER(MyPacket) = NDIS_PACKET_LAST_NDIS_BUFFER(Packet);
#ifdef WIN9X
        //
        // Work around the fact that NDIS does not initialize this
        // to FALSE on Win9x.
        //
        NDIS_PACKET_VALID_COUNTS(MyPacket) = FALSE;
#endif

        //
        // Copy the OOB Offset from the original packet to the new
        // packet.
        //
        NdisMoveMemory(NDIS_OOB_DATA_FROM_PACKET(MyPacket),
                       NDIS_OOB_DATA_FROM_PACKET(Packet),
                       sizeof(NDIS_PACKET_OOB_DATA));

#ifndef WIN9X
        //
        // Copy the right parts of per packet info into the new packet.
        // This API is not available on Win9x since task offload is
        // not supported on that platform.
        //
        NdisIMCopySendPerPacketInfo(MyPacket, Packet);
#endif
        
        //
        // Copy the Media specific information
        //
        NDIS_GET_PACKET_MEDIA_SPECIFIC_INFO(Packet,
                                            &MediaSpecificInfo,
                                            &MediaSpecificInfoSize);

        if (MediaSpecificInfo || MediaSpecificInfoSize)
        {
            NDIS_SET_PACKET_MEDIA_SPECIFIC_INFO(MyPacket,
                                                MediaSpecificInfo,
                                                MediaSpecificInfoSize);
        }

        NdisSend(&Status,
                 pAdapt->BindingHandle,
                 MyPacket);


        if (Status != NDIS_STATUS_PENDING)
        {
#ifndef WIN9X
            NdisIMCopySendCompletePerPacketInfo (Packet, MyPacket);
#endif
            NdisFreePacket(MyPacket);
            ADAPT_DECR_PENDING_SENDS(pAdapt);
        }
    }
    else
    {
        ADAPT_DECR_PENDING_SENDS(pAdapt);
        //
        // We are out of packets. Silently drop it. Alternatively we can deal with it:
        //    - By keeping separate send and receive pools
        //    - Dynamically allocate more pools as needed and free them when not needed
        //
    }

    return(Status);
}


VOID
MPSendPackets(
    IN NDIS_HANDLE             MiniportAdapterContext,
    IN PPNDIS_PACKET           PacketArray,
    IN UINT                    NumberOfPackets
    )
/*++

Routine Description:

    Send Packet Array handler. Either this or our SendPacket handler is called
    based on which one is enabled in our Miniport Characteristics.

Arguments:

    MiniportAdapterContext     Pointer to our adapter
    PacketArray                Set of packets to send
    NumberOfPackets            Self-explanatory

Return Value:

    None

--*/
{
    PADAPT              pAdapt = (PADAPT)MiniportAdapterContext;
    NDIS_STATUS         Status;
    UINT                i;
    PVOID               MediaSpecificInfo = NULL;
    UINT                MediaSpecificInfoSize = 0;
    

    for (i = 0; i < NumberOfPackets; i++)
    {
        PNDIS_PACKET    Packet, MyPacket;

        Packet = PacketArray[i];
        //
        // The driver should fail the send if the virtual miniport is in low 
        // power state
        //
        if (pAdapt->MPDeviceState > NdisDeviceStateD0)
        {
            NdisMSendComplete(ADAPT_MINIPORT_HANDLE(pAdapt),
                            Packet,
                            NDIS_STATUS_FAILURE);
            continue;
        }

#ifdef NDIS51

        //
        // Use NDIS 5.1 packet stacking:

⌨️ 快捷键说明

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