2 * Copyright (c) 1999, 2000
3 * Politecnico di Torino. All rights reserved.
5 * Redistribution and use in source and binary forms, with or without
6 * modification, are permitted provided that: (1) source code distributions
7 * retain the above copyright notice and this paragraph in its entirety, (2)
8 * distributions including binary code include the above copyright notice and
9 * this paragraph in its entirety in the documentation or other materials
10 * provided with the distribution, and (3) all advertising materials mentioning
11 * features or use of this software display the following acknowledgement:
12 * ``This product includes software developed by the Politecnico
13 * di Torino, and its contributors.'' Neither the name of
14 * the University nor the names of its contributors may be used to endorse
15 * or promote products derived from this software without specific prior
17 * THIS SOFTWARE IS PROVIDED ``AS IS'' AND WITHOUT ANY EXPRESS OR IMPLIED
18 * WARRANTIES, INCLUDING, WITHOUT LIMITATION, THE IMPLIED WARRANTIES OF
19 * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE.
28 #include <ddk/ntddk.h>
37 #include "win_bpf_filter_init.h"
42 // Declare the global debug flag for this driver.
43 //ULONG PacketDebugFlag = PACKET_DEBUG_LOUD;
44 ULONG PacketDebugFlag
= PACKET_DEBUG_LOUD
+ PACKET_DEBUG_VERY_LOUD
+ PACKET_DEBUG_INIT
;
48 PDEVICE_EXTENSION GlobalDeviceExtension
;
50 ////////////////////////////////////////////////////////////////////////////////
54 #define NDIS_STRING_CONST(x) {sizeof(L##x)-2, sizeof(L##x), L##x}
56 //void __moddi3(void) {}
57 //void __divdi3(void) {}
59 #endif // ROBERTS_PATCH
60 ////////////////////////////////////////////////////////////////////////////////
64 NDIS_STRING NPF_Prefix
= NDIS_STRING_CONST("NPF_");
65 NDIS_STRING devicePrefix
= NDIS_STRING_CONST("\\Device\\");
66 NDIS_STRING symbolicLinkPrefix
= NDIS_STRING_CONST("\\DosDevices\\");
67 NDIS_STRING tcpLinkageKeyName
= NDIS_STRING_CONST("\\Registry\\Machine\\System"
68 L
"\\CurrentControlSet\\Services\\Tcpip\\Linkage");
69 NDIS_STRING AdapterListKey
= NDIS_STRING_CONST("\\Registry\\Machine\\System"
70 L
"\\CurrentControlSet\\Control\\Class\\{4D36E972-E325-11CE-BFC1-08002BE10318}");
71 NDIS_STRING bindValueName
= NDIS_STRING_CONST("Bind");
74 /// Global variable that points to the names of the bound adapters
77 extern struct time_conv G_Start_Time
; // from openclos.c
79 extern NDIS_SPIN_LOCK Opened_Instances_Lock
;
82 // Packet Driver's entry routine.
89 IN PDRIVER_OBJECT DriverObject
,
90 IN PUNICODE_STRING RegistryPath
94 NDIS_PROTOCOL_CHARACTERISTICS ProtocolChar
;
95 NDIS_STATUS Status
= NDIS_STATUS_SUCCESS
;
96 NDIS_STRING ProtoName
= NDIS_STRING_CONST("PacketDriver");
97 NDIS_HANDLE NdisProtocolHandle
;
99 PKEY_VALUE_PARTIAL_INFORMATION tcpBindingsP
;
100 UNICODE_STRING macName
;
102 // This driver at the moment works only on single processor machines
103 if(NdisSystemProcessorCount() != 1){
104 return STATUS_IMAGE_MP_UP_MISMATCH
;
107 IF_LOUD(DbgPrint("Packet: DriverEntry\n");)
109 RtlZeroMemory(&ProtocolChar
,sizeof(NDIS_PROTOCOL_CHARACTERISTICS
));
112 ProtocolChar
.MajorNdisVersion
= 5;
114 ProtocolChar
.MajorNdisVersion
= 3;
116 ProtocolChar
.MinorNdisVersion
= 0;
118 ProtocolChar
.Reserved
= 0;
120 ProtocolChar
.u1
.Reserved
= 0;
122 ProtocolChar
.OpenAdapterCompleteHandler
= NPF_OpenAdapterComplete
;
123 ProtocolChar
.CloseAdapterCompleteHandler
= NPF_CloseAdapterComplete
;
125 ProtocolChar
.SendCompleteHandler
= NPF_SendComplete
;
126 ProtocolChar
.TransferDataCompleteHandler
= NPF_TransferDataComplete
;
128 ProtocolChar
.u2
.SendCompleteHandler
= NPF_SendComplete
;
129 ProtocolChar
.u3
.TransferDataCompleteHandler
= NPF_TransferDataComplete
;
131 ProtocolChar
.ResetCompleteHandler
= NPF_ResetComplete
;
132 ProtocolChar
.RequestCompleteHandler
= NPF_RequestComplete
;
134 ProtocolChar
.ReceiveHandler
= NPF_tap
;
136 ProtocolChar
.u4
.ReceiveHandler
= NPF_tap
;
138 ProtocolChar
.ReceiveCompleteHandler
= NPF_ReceiveComplete
;
139 ProtocolChar
.StatusHandler
= NPF_Status
;
140 ProtocolChar
.StatusCompleteHandler
= NPF_StatusComplete
;
142 ProtocolChar
.BindAdapterHandler
= NPF_BindAdapter
;
143 ProtocolChar
.UnbindAdapterHandler
= NPF_UnbindAdapter
;
144 ProtocolChar
.PnPEventHandler
= NPF_PowerChange
;
145 ProtocolChar
.ReceivePacketHandler
= NULL
;
147 ProtocolChar
.Name
= ProtoName
;
149 NdisRegisterProtocol(
153 sizeof(NDIS_PROTOCOL_CHARACTERISTICS
));
155 if (Status
!= NDIS_STATUS_SUCCESS
) {
157 IF_LOUD(DbgPrint("NPF: Failed to register protocol with NDIS\n");)
163 NdisAllocateSpinLock(&Opened_Instances_Lock
);
165 // Set up the device driver entry points.
166 DriverObject
->MajorFunction
[IRP_MJ_CREATE
] = (PDRIVER_DISPATCH
)NPF_Open
;
167 DriverObject
->MajorFunction
[IRP_MJ_CLOSE
] = (PDRIVER_DISPATCH
)NPF_Close
;
168 DriverObject
->MajorFunction
[IRP_MJ_READ
] = (PDRIVER_DISPATCH
)NPF_Read
;
169 DriverObject
->MajorFunction
[IRP_MJ_WRITE
] = (PDRIVER_DISPATCH
)NPF_Write
;
170 DriverObject
->MajorFunction
[IRP_MJ_DEVICE_CONTROL
] = (PDRIVER_DISPATCH
)NPF_IoControl
;
171 DriverObject
->DriverUnload
= NPF_Unload
;
174 // Get the name of the Packet driver and the name of the NIC driver
175 // to bind to from the registry
176 Status=NPF_ReadRegistry(
182 if (Status != STATUS_SUCCESS) {
184 IF_LOUD(DbgPrint("Trying dynamic binding\n");)
186 bindP
= getAdaptersList();
189 IF_LOUD(DbgPrint("Adapters not found in the registry, try to copy the bindings of TCP-IP.\n");)
191 tcpBindingsP
= getTcpBindings();
193 if (tcpBindingsP
== NULL
){
194 IF_LOUD(DbgPrint("TCP-IP not found, quitting.\n");)
198 bindP
= (WCHAR
*)tcpBindingsP
;
199 bindT
= (WCHAR
*)(tcpBindingsP
->Data
);
204 for (; *bindT
!= UNICODE_NULL
; bindT
+= (macName
.Length
+ sizeof(UNICODE_NULL
)) / sizeof(WCHAR
)) {
205 RtlInitUnicodeString(&macName
, bindT
);
206 createDevice(DriverObject
, &macName
, NdisProtocolHandle
);
209 return STATUS_SUCCESS
;
212 BindStringSave = BindString;
213 ExportStringSave = ExportString;
215 // create a device object for each entry
217 while (*BindString!= UNICODE_NULL && *ExportString!= UNICODE_NULL) {
219 // Create a counted unicode string for both null terminated strings
221 RtlInitUnicodeString(
224 RtlInitUnicodeString(
228 // Advance to the next string of the MULTI_SZ string
230 BindString += (MacDriverName.Length+sizeof(UNICODE_NULL))/sizeof(WCHAR);
231 ExportString += (UnicodeDeviceName.Length+sizeof(UNICODE_NULL))/sizeof(WCHAR);
232 IF_LOUD(DbgPrint("NPF: DeviceName=%ws MacName=%ws\n",UnicodeDeviceName.Buffer,MacDriverName.Buffer);)
234 // Create the device object
236 Status = IoCreateDevice(
238 sizeof(DEVICE_EXTENSION),
240 FILE_DEVICE_PROTOCOL,
244 if (Status != STATUS_SUCCESS) {
245 IF_LOUD(DbgPrint("NPF: IoCreateDevice() failed:\n");)
249 DeviceObject->Flags |= DO_DIRECT_IO;
250 DeviceExtension = (PDEVICE_EXTENSION) DeviceObject->DeviceExtension;
251 DeviceExtension->DeviceObject = DeviceObject;
253 // Save the the name of the MAC driver to open in the Device Extension
255 DeviceExtension->AdapterName=MacDriverName;
256 if (DevicesCreated == 1) {
257 DeviceExtension->BindString = NULL;
258 DeviceExtension->ExportString = NULL;
260 DeviceExtension->NdisProtocolHandle=NdisProtocolHandle;
262 if (DevicesCreated > 0) {
264 // Managed to create at least one device.
266 IF_LOUD(DbgPrint("NPF: Managed to create at least one device.\n");)
267 return STATUS_SUCCESS;
269 ExFreePool(BindStringSave);
270 ExFreePool(ExportStringSave);
274 IF_LOUD(DbgPrint("NPF: RegistryError: calling NdisDeregisterProtocol()\n");)
275 NdisDeregisterProtocol(
280 Status
=STATUS_UNSUCCESSFUL
;
286 //-------------------------------------------------------------------
288 PWCHAR
getAdaptersList(void)
290 OBJECT_ATTRIBUTES objAttrs
;
295 #define NPF_TAG_DEVICENAME TAG('0', 'P', 'W', 'A')
296 PWCHAR DeviceNames
= (PWCHAR
) ExAllocatePoolWithTag(PagedPool
, 4096, NPF_TAG_DEVICENAME
);
298 if (DeviceNames
== NULL
) {
299 IF_LOUD(DbgPrint("Unable the allocate the buffer for the list of the network adapters\n");)
303 InitializeObjectAttributes(&objAttrs
, &AdapterListKey
,
304 OBJ_CASE_INSENSITIVE
, NULL
, NULL
);
305 status
= ZwOpenKey(&keyHandle
, KEY_READ
, &objAttrs
);
306 if (!NT_SUCCESS(status
)) {
308 //IF_LOUD(DbgPrint("Status of %x opening %ws\n", status, tcpLinkageKeyName.Buffer);)
309 IF_LOUD(DbgPrint("Status of %x opening %ws\n", status
, AdapterListKey
.Buffer
);)
316 IF_LOUD(DbgPrint("getAdaptersList: scanning the list of the adapters in the registry, DeviceNames=%x\n",DeviceNames
);)
318 // Scan the list of the devices
319 while((status
=ZwEnumerateKey(keyHandle
,i
,KeyBasicInformation
,AdapInfo
,sizeof(AdapInfo
),&resultLength
))==STATUS_SUCCESS
) {
320 WCHAR ExportKeyName
[512];
321 PWCHAR ExportKeyPrefix
= L
"\\Registry\\Machine\\System\\CurrentControlSet\\Control\\Class\\{4D36E972-E325-11CE-BFC1-08002BE10318}\\";
322 UINT ExportKeyPrefixSize
= sizeof(L
"\\Registry\\Machine\\System\\CurrentControlSet\\Control\\Class\\{4D36E972-E325-11CE-BFC1-08002BE10318}");
323 PWCHAR LinkageKeyPrefix
= L
"\\Linkage";
324 UINT LinkageKeyPrefixSize
= sizeof(L
"\\Linkage");
325 NDIS_STRING FinalExportKey
= NDIS_STRING_CONST("Export");
326 PKEY_BASIC_INFORMATION tInfo
= (PKEY_BASIC_INFORMATION
)AdapInfo
;
327 UNICODE_STRING AdapterKeyName
;
328 HANDLE ExportKeyHandle
;
329 KEY_VALUE_PARTIAL_INFORMATION valueInfo
;
332 RtlCopyMemory(ExportKeyName
,
334 ExportKeyPrefixSize
);
336 RtlCopyMemory((PCHAR
)ExportKeyName
+ExportKeyPrefixSize
,
338 tInfo
->NameLength
+2);
340 RtlCopyMemory((PCHAR
)ExportKeyName
+ExportKeyPrefixSize
+tInfo
->NameLength
,
342 LinkageKeyPrefixSize
);
344 IF_LOUD(DbgPrint("Key name=%ws\n", ExportKeyName
);)
346 RtlInitUnicodeString(&AdapterKeyName
, ExportKeyName
);
348 InitializeObjectAttributes(&objAttrs
, &AdapterKeyName
,
349 OBJ_CASE_INSENSITIVE
, NULL
, NULL
);
351 status
=ZwOpenKey(&ExportKeyHandle
,KEY_READ
,&objAttrs
);
353 if (!NT_SUCCESS(status
)) {
354 DbgPrint("OpenKey Failed, %d!\n",status
);
359 status
= ZwQueryValueKey(ExportKeyHandle
, &FinalExportKey
,
360 KeyValuePartialInformation
, &valueInfo
,
361 sizeof(valueInfo
), &resultLength
);
363 if (!NT_SUCCESS(status
) && (status
!= STATUS_BUFFER_OVERFLOW
)) {
364 IF_LOUD(DbgPrint("\n\nStatus of %x querying key value for size\n", status
);)
365 } else { // We know how big it needs to be.
366 ULONG valueInfoLength
= valueInfo
.DataLength
+ FIELD_OFFSET(KEY_VALUE_PARTIAL_INFORMATION
, Data
[0]);
367 #define NPF_TAG_KEYVALUE TAG('1', 'P', 'W', 'A')
368 PKEY_VALUE_PARTIAL_INFORMATION valueInfoP
= (PKEY_VALUE_PARTIAL_INFORMATION
) ExAllocatePoolWithTag(PagedPool
, valueInfoLength
, NPF_TAG_KEYVALUE
);
369 if (valueInfoP
!= NULL
) {
370 status
= ZwQueryValueKey(ExportKeyHandle
, &FinalExportKey
,
371 KeyValuePartialInformation
,
373 valueInfoLength
, &resultLength
);
374 if (!NT_SUCCESS(status
)) {
375 IF_LOUD(DbgPrint("Status of %x querying key value\n", status
);)
377 IF_LOUD(DbgPrint("Device %d = %ws\n", i
, valueInfoP
->Data
);)
378 RtlCopyMemory((PCHAR
)DeviceNames
+BufPos
,
380 valueInfoP
->DataLength
);
381 BufPos
+=valueInfoP
->DataLength
-2;
384 ExFreePool(valueInfoP
);
386 IF_LOUD(DbgPrint("Error Allocating the buffer for the device name\n");)
391 // terminate the buffer
392 DeviceNames
[BufPos
/2]=0;
393 DeviceNames
[BufPos
/2+1]=0;
395 ZwClose (ExportKeyHandle
);
404 ExFreePool(DeviceNames
);
410 //-------------------------------------------------------------------
412 PKEY_VALUE_PARTIAL_INFORMATION
getTcpBindings(void)
414 PKEY_VALUE_PARTIAL_INFORMATION result
= NULL
;
415 OBJECT_ATTRIBUTES objAttrs
;
419 InitializeObjectAttributes(&objAttrs
, &tcpLinkageKeyName
,
420 OBJ_CASE_INSENSITIVE
, NULL
, NULL
);
421 status
= ZwOpenKey(&keyHandle
, KEY_READ
, &objAttrs
);
422 if (!NT_SUCCESS(status
)) {
423 IF_LOUD(DbgPrint("\n\nStatus of %x opening %ws\n", status
, tcpLinkageKeyName
.Buffer
);)
426 KEY_VALUE_PARTIAL_INFORMATION valueInfo
;
428 IF_LOUD(DbgPrint("\n\nOpened %ws\n", tcpLinkageKeyName
.Buffer
);)
430 status
= ZwQueryValueKey(keyHandle
, &bindValueName
,
431 KeyValuePartialInformation
, &valueInfo
,
432 sizeof(valueInfo
), &resultLength
);
433 if (!NT_SUCCESS(status
) && (status
!= STATUS_BUFFER_OVERFLOW
)) {
434 IF_LOUD(DbgPrint("\n\nStatus of %x querying key value for size\n", status
);)
435 } else { // We know how big it needs to be.
436 ULONG valueInfoLength
= valueInfo
.DataLength
+ FIELD_OFFSET(KEY_VALUE_PARTIAL_INFORMATION
, Data
[0]);
437 #define NPF_TAG_KEYVALUE2 TAG('2', 'P', 'W', 'A')
438 PKEY_VALUE_PARTIAL_INFORMATION valueInfoP
=
439 (PKEY_VALUE_PARTIAL_INFORMATION
)ExAllocatePoolWithTag(PagedPool
, valueInfoLength
, NPF_TAG_KEYVALUE2
);
441 if (valueInfoP
!= NULL
) {
442 status
= ZwQueryValueKey(keyHandle
, &bindValueName
,
443 KeyValuePartialInformation
,
445 valueInfoLength
, &resultLength
);
447 if (!NT_SUCCESS(status
)) {
448 IF_LOUD(DbgPrint("\n\nStatus of %x querying key value\n", status
);)
450 else if (valueInfoLength
!= resultLength
) {
451 IF_LOUD(DbgPrint("\n\nQuerying key value result len = %u "
452 "but previous len = %u\n",
453 resultLength
, valueInfoLength
);)
455 else if (valueInfoP
->Type
!= REG_MULTI_SZ
) {
456 IF_LOUD(DbgPrint("\n\nTcpip bind value not REG_MULTI_SZ but %u\n",
462 WCHAR
* dataP
= (WCHAR
*)(&valueInfoP
->Data
[0]);
463 IF_LOUD(DbgPrint("\n\nBind value:\n");)
464 for (i
= 0; *dataP
!= UNICODE_NULL
; i
++) {
465 UNICODE_STRING macName
;
466 RtlInitUnicodeString(&macName
, dataP
);
467 IF_LOUD(DbgPrint("\n\nMac %u = %ws\n", i
, macName
.Buffer
);)
469 (macName
.Length
+ sizeof(UNICODE_NULL
)) / sizeof(WCHAR
);
481 //-------------------------------------------------------------------
483 BOOLEAN
createDevice(IN OUT PDRIVER_OBJECT adriverObjectP
,
484 IN PUNICODE_STRING amacNameP
, NDIS_HANDLE aProtoHandle
)
487 PDEVICE_OBJECT devObjP
;
488 UNICODE_STRING deviceName
;
489 UNICODE_STRING deviceSymLink
;
491 IF_LOUD(DbgPrint("\n\ncreateDevice for MAC %ws\n", amacNameP
->Buffer
););
492 if (RtlCompareMemory(amacNameP
->Buffer
, devicePrefix
.Buffer
,
493 devicePrefix
.Length
) < devicePrefix
.Length
) {
497 deviceName
.Length
= 0;
498 deviceName
.MaximumLength
= (USHORT
)(amacNameP
->Length
+ NPF_Prefix
.Length
+ sizeof(UNICODE_NULL
));
499 #define NPF_TAG_DEVICENAMEBUF TAG('3', 'P', 'W', 'A')
500 deviceName
.Buffer
= ExAllocatePoolWithTag(PagedPool
, deviceName
.MaximumLength
, NPF_TAG_DEVICENAMEBUF
);
502 if (deviceName
.Buffer
== NULL
)
505 deviceSymLink
.Length
= 0;
506 deviceSymLink
.MaximumLength
=(USHORT
)(amacNameP
->Length
-devicePrefix
.Length
507 + symbolicLinkPrefix
.Length
509 + sizeof(UNICODE_NULL
));
511 #define NPF_TAG_SYMLINKBUF TAG('3', 'P', 'W', 'A')
512 deviceSymLink
.Buffer
= ExAllocatePoolWithTag(NonPagedPool
, deviceSymLink
.MaximumLength
, NPF_TAG_SYMLINKBUF
);
514 if (deviceSymLink
.Buffer
== NULL
)
516 ExFreePool(deviceName
.Buffer
);
520 RtlAppendUnicodeStringToString(&deviceName
, &devicePrefix
);
521 RtlAppendUnicodeStringToString(&deviceName
, &NPF_Prefix
);
522 RtlAppendUnicodeToString(&deviceName
, amacNameP
->Buffer
+
523 devicePrefix
.Length
/ sizeof(WCHAR
));
525 RtlAppendUnicodeStringToString(&deviceSymLink
, &symbolicLinkPrefix
);
526 RtlAppendUnicodeStringToString(&deviceSymLink
, &NPF_Prefix
);
527 RtlAppendUnicodeToString(&deviceSymLink
, amacNameP
->Buffer
+
528 devicePrefix
.Length
/ sizeof(WCHAR
));
530 IF_LOUD(DbgPrint("Creating device name: %ws\n", deviceName
.Buffer
);)
532 status
= IoCreateDevice(adriverObjectP
,
533 sizeof(PDEVICE_EXTENSION
),
535 FILE_DEVICE_TRANSPORT
,
540 if (NT_SUCCESS(status
)) {
541 PDEVICE_EXTENSION devExtP
= (PDEVICE_EXTENSION
)devObjP
->DeviceExtension
;
543 IF_LOUD(DbgPrint("Device created successfully\n"););
545 devObjP
->Flags
|= DO_DIRECT_IO
;
546 RtlInitUnicodeString(&devExtP
->AdapterName
,amacNameP
->Buffer
);
547 devExtP
->NdisProtocolHandle
=aProtoHandle
;
549 IF_LOUD(DbgPrint("Trying to create SymLink %ws\n",deviceSymLink
.Buffer
););
551 if (IoCreateSymbolicLink(&deviceSymLink
,&deviceName
) != STATUS_SUCCESS
) {
552 IF_LOUD(DbgPrint("\n\nError creating SymLink %ws\nn", deviceSymLink
.Buffer
););
554 ExFreePool(deviceName
.Buffer
);
555 ExFreePool(deviceSymLink
.Buffer
);
557 devExtP
->ExportString
= NULL
;
562 IF_LOUD(DbgPrint("SymLink %ws successfully created.\n\n", deviceSymLink
.Buffer
););
564 devExtP
->ExportString
= deviceSymLink
.Buffer
;
566 ExFreePool(deviceName
.Buffer
);
573 IF_LOUD(DbgPrint("\n\nIoCreateDevice status = %x\n", status
););
575 ExFreePool(deviceName
.Buffer
);
576 ExFreePool(deviceSymLink
.Buffer
);
582 //-------------------------------------------------------------------
585 NPF_Unload(IN PDRIVER_OBJECT DriverObject
)
587 PDEVICE_OBJECT DeviceObject
;
588 PDEVICE_OBJECT OldDeviceObject
;
589 PDEVICE_EXTENSION DeviceExtension
;
591 NDIS_HANDLE NdisProtocolHandle
;
596 IF_LOUD(DbgPrint("NPF: Unload\n"););
598 DeviceObject
= DriverObject
->DeviceObject
;
600 while (DeviceObject
!= NULL
) {
601 OldDeviceObject
=DeviceObject
;
603 DeviceObject
=DeviceObject
->NextDevice
;
605 DeviceExtension
= OldDeviceObject
->DeviceExtension
;
607 NdisProtocolHandle
=DeviceExtension
->NdisProtocolHandle
;
609 IF_LOUD(DbgPrint("Deleting Adapter %ws, Protocol Handle=%x, Device Obj=%x (%x)\n",
610 DeviceExtension
->AdapterName
.Buffer
,
615 if (DeviceExtension
->ExportString
)
617 RtlInitUnicodeString(&SymLink
, DeviceExtension
->ExportString
);
619 IF_LOUD(DbgPrint("Deleting SymLink at %p\n", SymLink
.Buffer
););
621 IoDeleteSymbolicLink(&SymLink
);
622 ExFreePool(DeviceExtension
->ExportString
);
625 IoDeleteDevice(OldDeviceObject
);
627 NdisDeregisterProtocol(
633 // Free the adapters names
637 //-------------------------------------------------------------------
640 NPF_IoControl(IN PDEVICE_OBJECT DeviceObject
,IN PIRP Irp
)
643 PIO_STACK_LOCATION IrpSp
;
644 PLIST_ENTRY RequestListEntry
;
645 PINTERNAL_REQUEST pRequest
;
651 PPACKET_OID_DATA OidData
;
654 PUCHAR TmpBPFProgram
;
656 BOOLEAN SyncWrite
= FALSE
;
657 struct bpf_insn
*initprogram
;
660 BOOLEAN IsExtendedFilter
=FALSE
;
662 IF_LOUD(DbgPrint("NPF: IoControl\n");)
664 IrpSp
= IoGetCurrentIrpStackLocation(Irp
);
665 FunctionCode
=IrpSp
->Parameters
.DeviceIoControl
.IoControlCode
;
666 Open
=IrpSp
->FileObject
->FsContext
;
668 Irp
->IoStatus
.Status
= STATUS_SUCCESS
;
670 IF_LOUD(DbgPrint("NPF: Function code is %08lx buff size=%08lx %08lx\n",FunctionCode
,IrpSp
->Parameters
.DeviceIoControl
.InputBufferLength
,IrpSp
->Parameters
.DeviceIoControl
.OutputBufferLength
);)
673 switch (FunctionCode
){
675 case BIOCGSTATS
: //function to get the capture stats
677 if(IrpSp
->Parameters
.DeviceIoControl
.OutputBufferLength
< 4*sizeof(INT
)){
681 *(((PUINT
)Irp
->UserBuffer
)+3) = Open
->Accepted
;
682 *(((PUINT
)Irp
->UserBuffer
)) = Open
->Received
;
683 *(((PUINT
)Irp
->UserBuffer
)+1) = Open
->Dropped
;
684 *(((PUINT
)Irp
->UserBuffer
)+2) = 0; // Not yet supported
686 EXIT_SUCCESS(4*sizeof(INT
));
690 case BIOCGEVNAME
: //function to get the name of the event associated with the current instance
692 if(IrpSp
->Parameters
.DeviceIoControl
.OutputBufferLength
<26){
696 RtlCopyMemory(Irp
->UserBuffer
,(Open
->ReadEventName
.Buffer
)+18,26);
702 case BIOCSENDPACKETSSYNC
:
706 case BIOCSENDPACKETSNOSYNC
:
708 WriteRes
= NPF_BufferedWrite(Irp
,
709 (PCHAR
)Irp
->AssociatedIrp
.SystemBuffer
,
710 IrpSp
->Parameters
.DeviceIoControl
.InputBufferLength
,
715 EXIT_SUCCESS(WriteRes
);
718 EXIT_FAILURE(WriteRes
);
724 // Free the previous buffer if it was present
725 if(Open
->bpfprogram
!=NULL
){
726 TmpBPFProgram
=Open
->bpfprogram
;
727 Open
->bpfprogram
= NULL
;
728 ExFreePool(TmpBPFProgram
);
731 if (Open
->Filter
!=NULL
)
733 JIT_BPF_Filter
*OldFilter
=Open
->Filter
;
735 BPF_Destroy_JIT_Filter(OldFilter
);
738 // Get the pointer to the new program
739 prog
=(PUCHAR
)Irp
->AssociatedIrp
.SystemBuffer
;
742 IF_LOUD(DbgPrint("0001");)
747 insns
=(IrpSp
->Parameters
.DeviceIoControl
.InputBufferLength
)/sizeof(struct bpf_insn
);
749 //count the number of operative instructions
750 for (cnt
=0;(cnt
<insns
) &&(((struct bpf_insn
*)prog
)[cnt
].code
!=BPF_SEPARATION
); cnt
++);
752 IF_LOUD(DbgPrint("Operative instructions=%u\n",cnt
);)
754 if (((struct bpf_insn
*)prog
)[cnt
].code
==BPF_SEPARATION
&& (insns
-cnt
-1)!=0)
756 IF_LOUD(DbgPrint("Initialization instructions=%u\n",insns
-cnt
-1);)
758 IsExtendedFilter
=TRUE
;
760 initprogram
=&((struct bpf_insn
*)prog
)[cnt
+1];
762 if(bpf_filter_init(initprogram
,&(Open
->mem_ex
),&(Open
->tme
), &G_Start_Time
)!=INIT_OK
)
765 IF_LOUD(DbgPrint("Error initializing NPF machine (bpf_filter_init)\n");)
771 //the NPF processor has been initialized, we have to validate the operative instructions
774 if(bpf_validate((struct bpf_insn
*)prog
,cnt
,Open
->mem_ex
.size
)==0)
776 IF_LOUD(DbgPrint("Error validating program");)
777 //FIXME: the machine has been initialized(?), but the operative code is wrong.
778 //we have to reset the machine!
779 //something like: reallocate the mem_ex, and reset the tme_core
783 // Allocate the memory to contain the new filter program
784 // We could need the original BPF binary if we are forced to use bpf_filter_with_2_buffers()
785 #define NPF_TAG_BPFPROG TAG('4', 'P', 'W', 'A')
786 TmpBPFProgram
=(PUCHAR
)ExAllocatePoolWithTag(NonPagedPool
, cnt
*sizeof(struct bpf_insn
), NPF_TAG_BPFPROG
);
787 if (TmpBPFProgram
==NULL
){
788 IF_LOUD(DbgPrint("Error - No memory for filter");)
793 //copy the program in the new buffer
794 RtlCopyMemory(TmpBPFProgram
,prog
,cnt
*sizeof(struct bpf_insn
));
795 Open
->bpfprogram
=TmpBPFProgram
;
797 // Create the new JIT filter function
798 if(!IsExtendedFilter
)
799 if((Open
->Filter
=BPF_jitter((struct bpf_insn
*)Open
->bpfprogram
,cnt
)) == NULL
) {
800 IF_LOUD(DbgPrint("Error jittering filter");)
807 Open
->BLastByte
= (UINT
) -1;
812 EXIT_SUCCESS(IrpSp
->Parameters
.DeviceIoControl
.InputBufferLength
);
816 case BIOCSMODE
: //set the capture mode
818 mode
=*((PULONG
)Irp
->AssociatedIrp
.SystemBuffer
);
820 if(mode
== MODE_CAPT
){
821 Open
->mode
=MODE_CAPT
;
825 else if (mode
==MODE_MON
){
831 if(mode
& MODE_STAT
){
832 Open
->mode
= MODE_STAT
;
833 Open
->Nbytes
.QuadPart
=0;
834 Open
->Npackets
.QuadPart
=0;
836 if(Open
->TimeOut
.QuadPart
==0)Open
->TimeOut
.QuadPart
=-10000000;
840 if(mode
& MODE_DUMP
){
842 Open
->mode
|= MODE_DUMP
;
843 Open
->MinToCopy
=(Open
->BufSize
<2000000)?Open
->BufSize
/2:1000000;
853 case BIOCSETDUMPFILENAME
:
855 if(Open
->mode
& MODE_DUMP
)
858 // Close current dump file
859 if(Open
->DumpFileHandle
!= NULL
){
860 NPF_CloseDumpFile(Open
);
861 Open
->DumpFileHandle
= NULL
;
864 if(IrpSp
->Parameters
.DeviceIoControl
.InputBufferLength
== 0){
868 // Allocate the buffer that will contain the string
869 #define NPF_TAG_DUMPNAMEBUF TAG('5', 'P', 'W', 'A')
870 DumpNameBuff
=ExAllocatePoolWithTag(NonPagedPool
, IrpSp
->Parameters
.DeviceIoControl
.InputBufferLength
, NPF_TAG_DUMPNAMEBUF
);
871 if(DumpNameBuff
==NULL
|| Open
->DumpFileName
.Buffer
!=NULL
){
872 IF_LOUD(DbgPrint("NPF: unable to allocate the dump filename: not enough memory or name already set\n");)
877 RtlCopyBytes((PVOID
)DumpNameBuff
,
878 Irp
->AssociatedIrp
.SystemBuffer
,
879 IrpSp
->Parameters
.DeviceIoControl
.InputBufferLength
);
881 // Force a \0 at the end of the filename to avoid that malformed strings cause RtlInitUnicodeString to crash the system
882 ((SHORT
*)DumpNameBuff
)[IrpSp
->Parameters
.DeviceIoControl
.InputBufferLength
/2-1]=0;
884 // Create the unicode string
885 RtlInitUnicodeString(&Open
->DumpFileName
, DumpNameBuff
);
887 IF_LOUD(DbgPrint("NPF: dump file name set to %ws, len=%d\n",
888 Open
->DumpFileName
.Buffer
,
889 IrpSp
->Parameters
.DeviceIoControl
.InputBufferLength
);)
891 // Try to create the file
892 if ( NT_SUCCESS( NPF_OpenDumpFile(Open
,&Open
->DumpFileName
,FALSE
)) &&
893 NT_SUCCESS( NPF_StartDump(Open
))){
903 case BIOCSETDUMPLIMITS
:
905 Open
->MaxDumpBytes
= *(PULONG
)Irp
->AssociatedIrp
.SystemBuffer
;
906 Open
->MaxDumpPacks
= *((PULONG
)Irp
->AssociatedIrp
.SystemBuffer
+ 1);
908 IF_LOUD(DbgPrint("NPF: Set dump limits to %u bytes, %u packs\n", Open
->MaxDumpBytes
, Open
->MaxDumpPacks
);)
914 case BIOCISDUMPENDED
:
915 if(IrpSp
->Parameters
.DeviceIoControl
.OutputBufferLength
< 4){
919 *((UINT
*)Irp
->UserBuffer
) = (Open
->DumpLimitReached
)?1:0;
925 case BIOCSETBUFFERSIZE
:
927 // Get the number of bytes to allocate
928 dim
= *((PULONG
)Irp
->AssociatedIrp
.SystemBuffer
);
930 // Free the old buffer
931 tpointer
= Open
->Buffer
;
932 if(tpointer
!= NULL
){
935 ExFreePool(tpointer
);
937 // Allocate the new buffer
939 #define NPF_TAG_TPOINTER TAG('6', 'P', 'W', 'A')
940 tpointer
= ExAllocatePoolWithTag(NonPagedPool
, dim
, NPF_TAG_TPOINTER
);
941 if (tpointer
==NULL
) {
951 Open
->Buffer
= tpointer
;
954 Open
->BLastByte
= (UINT
) -1;
956 Open
->BufSize
= (UINT
)dim
;
961 case BIOCSRTIMEOUT
: //set the timeout on the read calls
963 timeout
= *((PULONG
)Irp
->AssociatedIrp
.SystemBuffer
);
965 Open
->TimeOut
.QuadPart
=(LONGLONG
)IMMEDIATE
;
967 Open
->TimeOut
.QuadPart
=(LONGLONG
)timeout
;
968 Open
->TimeOut
.QuadPart
*=10000;
969 Open
->TimeOut
.QuadPart
=-Open
->TimeOut
.QuadPart
;
972 //IF_LOUD(DbgPrint("NPF: read timeout set to %d:%d\n",Open->TimeOut.HighPart,Open->TimeOut.LowPart);)
973 EXIT_SUCCESS(timeout
);
977 case BIOCSWRITEREP
: //set the writes repetition number
979 Open
->Nwrites
= *((PULONG
)Irp
->AssociatedIrp
.SystemBuffer
);
981 EXIT_SUCCESS(Open
->Nwrites
);
985 case BIOCSMINTOCOPY
: //set the minimum buffer's size to copy to the application
987 Open
->MinToCopy
= *((PULONG
)Irp
->AssociatedIrp
.SystemBuffer
);
989 EXIT_SUCCESS(Open
->MinToCopy
);
993 case IOCTL_PROTOCOL_RESET
:
995 IF_LOUD(DbgPrint("NPF: IoControl - Reset request\n");)
997 IoMarkIrpPending(Irp
);
998 Irp
->IoStatus
.Status
= STATUS_SUCCESS
;
1000 ExInterlockedInsertTailList(&Open
->ResetIrpList
,&Irp
->Tail
.Overlay
.ListEntry
,&Open
->RequestSpinLock
);
1001 NdisReset(&Status
,Open
->AdapterHandle
);
1002 if (Status
!= NDIS_STATUS_PENDING
) {
1003 IF_LOUD(DbgPrint("NPF: IoControl - ResetComplete being called\n");)
1004 NPF_ResetComplete(Open
,Status
);
1013 // Extract a request from the list of free ones
1014 RequestListEntry
=ExInterlockedRemoveHeadList(&Open
->RequestList
,&Open
->RequestSpinLock
);
1015 if (RequestListEntry
== NULL
)
1020 pRequest
=CONTAINING_RECORD(RequestListEntry
,INTERNAL_REQUEST
,ListElement
);
1022 pRequest
->Internal
= FALSE
;
1026 // See if it is an Ndis request
1028 OidData
=Irp
->AssociatedIrp
.SystemBuffer
;
1030 if (((FunctionCode
== BIOCSETOID
) || (FunctionCode
== BIOCQUERYOID
))
1032 (IrpSp
->Parameters
.DeviceIoControl
.InputBufferLength
== IrpSp
->Parameters
.DeviceIoControl
.OutputBufferLength
)
1034 (IrpSp
->Parameters
.DeviceIoControl
.InputBufferLength
>= sizeof(PACKET_OID_DATA
))
1036 (IrpSp
->Parameters
.DeviceIoControl
.InputBufferLength
>= sizeof(PACKET_OID_DATA
)-1+OidData
->Length
)) {
1038 IF_LOUD(DbgPrint("NPF: IoControl: Request: Oid=%08lx, Length=%08lx\n",OidData
->Oid
,OidData
->Length
);)
1041 // The buffer is valid
1043 if (FunctionCode
== BIOCSETOID
){
1045 pRequest
->Request
.RequestType
=NdisRequestSetInformation
;
1046 pRequest
->Request
.DATA
.SET_INFORMATION
.Oid
=OidData
->Oid
;
1048 pRequest
->Request
.DATA
.SET_INFORMATION
.InformationBuffer
=OidData
->Data
;
1049 pRequest
->Request
.DATA
.SET_INFORMATION
.InformationBufferLength
=OidData
->Length
;
1051 pRequest
->Request
.RequestType
=NdisRequestQueryInformation
;
1052 pRequest
->Request
.DATA
.QUERY_INFORMATION
.Oid
=OidData
->Oid
;
1054 pRequest
->Request
.DATA
.QUERY_INFORMATION
.InformationBuffer
=OidData
->Data
;
1055 pRequest
->Request
.DATA
.QUERY_INFORMATION
.InformationBufferLength
=OidData
->Length
;
1059 NdisResetEvent(&Open
->IOEvent
);
1061 // submit the request
1065 Open
->AdapterHandle
,
1073 Status
=NDIS_STATUS_FAILURE
;
1074 pRequest
->Request
.DATA
.SET_INFORMATION
.BytesRead
=0;
1075 pRequest
->Request
.DATA
.QUERY_INFORMATION
.BytesWritten
=0;
1079 if (Status
!= NDIS_STATUS_PENDING
) {
1080 IF_LOUD(DbgPrint("NPF: Calling RequestCompleteHandler\n");)
1082 NPF_RequestComplete(Open
, &pRequest
->Request
, Status
);
1087 NdisWaitEvent(&Open
->IOEvent
, 5000);
1089 return(Open
->IOStatus
);
1102 //-------------------------------------------------------------------
1105 NPF_RequestComplete(
1106 IN NDIS_HANDLE ProtocolBindingContext
,
1107 IN PNDIS_REQUEST NdisRequest
,
1108 IN NDIS_STATUS Status
1112 POPEN_INSTANCE Open
;
1113 PIO_STACK_LOCATION IrpSp
;
1115 PINTERNAL_REQUEST pRequest
;
1118 PPACKET_OID_DATA OidData
;
1120 IF_LOUD(DbgPrint("NPF: RequestComplete\n");)
1122 Open
= (POPEN_INSTANCE
)ProtocolBindingContext
;
1124 pRequest
=CONTAINING_RECORD(NdisRequest
,INTERNAL_REQUEST
,Request
);
1127 if(pRequest
->Internal
== TRUE
){
1129 // Put the request in the list of the free ones
1130 ExInterlockedInsertTailList(&Open
->RequestList
, &pRequest
->ListElement
, &Open
->RequestSpinLock
);
1132 if(Status
!= NDIS_STATUS_SUCCESS
)
1133 Open
->MaxFrameSize
= 1514; // Assume Ethernet
1135 // We always return success, because the adapter has been already opened
1136 Irp
->IoStatus
.Status
= NDIS_STATUS_SUCCESS
;
1137 Irp
->IoStatus
.Information
= 0;
1138 IoCompleteRequest(Irp
, IO_NO_INCREMENT
);
1142 IrpSp
= IoGetCurrentIrpStackLocation(Irp
);
1144 FunctionCode
=IrpSp
->Parameters
.DeviceIoControl
.IoControlCode
;
1146 OidData
=Irp
->AssociatedIrp
.SystemBuffer
;
1148 if (FunctionCode
== BIOCSETOID
) {
1150 OidData
->Length
=pRequest
->Request
.DATA
.SET_INFORMATION
.BytesRead
;
1154 if (FunctionCode
== BIOCQUERYOID
) {
1156 OidData
->Length
=pRequest
->Request
.DATA
.QUERY_INFORMATION
.BytesWritten
;
1158 IF_LOUD(DbgPrint("RequestComplete: BytesWritten=%d\n",pRequest
->Request
.DATA
.QUERY_INFORMATION
.BytesWritten
);)
1163 Irp
->IoStatus
.Information
=IrpSp
->Parameters
.DeviceIoControl
.InputBufferLength
;
1165 IF_LOUD(DbgPrint("RequestComplete: BytesReturned=%d\n",IrpSp
->Parameters
.DeviceIoControl
.InputBufferLength
);)
1167 ExInterlockedInsertTailList(
1169 &pRequest
->ListElement
,
1170 &Open
->RequestSpinLock
);
1172 Irp
->IoStatus
.Status
= Status
;
1174 Open
->IOStatus
= Status
;
1176 IoCompleteRequest(Irp
, IO_NO_INCREMENT
);
1178 // Unlock the caller
1179 NdisSetEvent(&Open
->IOEvent
);
1186 //-------------------------------------------------------------------
1190 IN NDIS_HANDLE ProtocolBindingContext
,
1191 IN NDIS_STATUS Status
,
1192 IN PVOID StatusBuffer
,
1193 IN UINT StatusBufferSize
1198 IF_LOUD(DbgPrint("NPF: Status Indication\n");)
1204 //-------------------------------------------------------------------
1208 IN NDIS_HANDLE ProtocolBindingContext
1213 IF_LOUD(DbgPrint("NPF: StatusIndicationComplete\n");)
1219 //-------------------------------------------------------------------
1223 IN PWSTR
*MacDriverName
,
1224 IN PWSTR
*PacketDriverName
,
1225 IN PUNICODE_STRING RegistryPath
1231 RTL_QUERY_REGISTRY_TABLE ParamTable
[4];
1233 PWSTR Bind
= L
"Bind";
1234 PWSTR Export
= L
"Export";
1235 PWSTR Linkage
= L
"Linkage";
1239 #define NPF_TAG_PATH TAG('7', 'P', 'W', 'A')
1240 Path
=ExAllocatePoolWithTag(PagedPool
, RegistryPath
->Length
+sizeof(WCHAR
), NPF_TAG_PATH
);
1243 IF_LOUD(DbgPrint("\nPacketReadRegistry: returing STATUS_INSUFFICIENT_RESOURCES\n");)
1244 return STATUS_INSUFFICIENT_RESOURCES
;
1249 RegistryPath
->Length
+sizeof(WCHAR
)
1254 RegistryPath
->Buffer
,
1255 RegistryPath
->Length
1258 IF_LOUD(DbgPrint("NPF: Reg path is %ws\n",RegistryPath
->Buffer
);)
1268 // change to the linkage key
1270 //ParamTable[0].QueryRoutine = NULL;
1271 ParamTable
[0].QueryRoutine
= NPF_QueryRegistryRoutine
;
1272 ParamTable
[0].Flags
= RTL_QUERY_REGISTRY_SUBKEY
;
1273 ParamTable
[0].Name
= Linkage
;
1277 // Get the name of the mac driver we should bind to
1280 ParamTable
[1].QueryRoutine
= NPF_QueryRegistryRoutine
;
1281 ParamTable
[1].Flags
= RTL_QUERY_REGISTRY_REQUIRED
|
1282 RTL_QUERY_REGISTRY_NOEXPAND
;
1284 ParamTable
[1].Name
= Bind
;
1285 ParamTable
[1].EntryContext
= (PVOID
)MacDriverName
;
1286 ParamTable
[1].DefaultType
= REG_MULTI_SZ
;
1289 // Get the name that we should use for the driver object
1292 ParamTable
[2].QueryRoutine
= NPF_QueryRegistryRoutine
;
1293 ParamTable
[2].Flags
= RTL_QUERY_REGISTRY_REQUIRED
|
1294 RTL_QUERY_REGISTRY_NOEXPAND
;
1296 ParamTable
[2].Name
= Export
;
1297 ParamTable
[2].EntryContext
= (PVOID
)PacketDriverName
;
1298 ParamTable
[2].DefaultType
= REG_MULTI_SZ
;
1301 Status
=RtlQueryRegistryValues(
1302 RTL_REGISTRY_ABSOLUTE
,
1309 if (Status
!= STATUS_SUCCESS
) {
1310 // insert hard coded parameters here while registry on ROS is not working...
1311 IF_LOUD(DbgPrint("PacketReadRegistry() RtlQueryRegistryValues failed - returing fixed parameters\n");)
1313 *MacDriverName
= ExAllocatePool(PagedPool
, 50 * sizeof(WCHAR
));
1314 //memcpy(*MacDriverName, L"\\Device\\ne2000", 15 * sizeof(WCHAR));
1315 memcpy(*MacDriverName
, L
"\\Device\\ne2000", 15 * sizeof(WCHAR
));
1317 *PacketDriverName
= ExAllocatePool(PagedPool
, 50 * sizeof(WCHAR
));
1318 memcpy(*PacketDriverName
, L
"\\Device\\NPF_ne2000", 19 * sizeof(WCHAR
));
1319 Status
= STATUS_SUCCESS
;
1327 //-------------------------------------------------------------------
1330 NPF_QueryRegistryRoutine(
1334 IN ULONG ValueLength
,
1336 IN PVOID EntryContext
1343 IF_LOUD(DbgPrint("Perf: QueryRegistryRoutine\n");)
1345 if (ValueType
!= REG_MULTI_SZ
) {
1347 return STATUS_OBJECT_NAME_NOT_FOUND
;
1351 #define NPF_TAG_REGBUF TAG('8', 'P', 'W', 'A')
1352 Buffer
=ExAllocatePoolWithTag(NonPagedPool
, ValueLength
, NPF_TAG_REGBUF
);
1356 return STATUS_INSUFFICIENT_RESOURCES
;
1366 *((PUCHAR
*)EntryContext
)=Buffer
;
1368 return STATUS_SUCCESS
;