diff --git a/.gitmodules b/.gitmodules index b25c3c6..1db9a60 100644 --- a/.gitmodules +++ b/.gitmodules @@ -8,3 +8,6 @@ [submodule "third/web-sugar"] path = third/web-sugar url = git@github.com:ForNetCode/web-sugar.git +[submodule "third/simple-windows-tun"] + path = third/simple-windows-tun + url = git@github.com:ForNetCode/simple-windows-tun.git diff --git a/client/lib/Cargo.toml b/client/lib/Cargo.toml index 55b9227..d954dca 100644 --- a/client/lib/Cargo.toml +++ b/client/lib/Cargo.toml @@ -71,7 +71,7 @@ path = "../../third/boringtun/boringtun" tun = { version = "0.5", features = ["async"], path = "../../third/rust-tun"} nix = { version = "0.25" } #compatible with boringtun [target.'cfg(windows)'.dependencies] -fortun-cli = {version = "0.0.1", path = "../../win-tun-driver/ForTunCli" } +fortun-cli = {version = "0.0.1", path = "../../third/simple-windows-tun/ForTunCli" } windows = {version = "0.44", features=["Win32_Networking_WinSock"]} cidr-utils = "0.5.10" #winapi = {version = "0.3", features=["ws2def"]} diff --git a/third/simple-windows-tun b/third/simple-windows-tun new file mode 160000 index 0000000..aeb8b3c --- /dev/null +++ b/third/simple-windows-tun @@ -0,0 +1 @@ +Subproject commit aeb8b3c92d8c1c656e5a99b7467076ea897d1ea3 diff --git a/win-tun-driver/.gitignore b/win-tun-driver/.gitignore deleted file mode 100644 index dd952bb..0000000 --- a/win-tun-driver/.gitignore +++ /dev/null @@ -1,33 +0,0 @@ -*.suo -*.user -*.userosscache -*.sln.docstates - -# Build results -[Dd]ebug/ -[Dd]ebugPublic/ -[Rr]elease/ -[Rr]eleases/ -build/ -bld/ -[Bb]in/ -[Oo]bj/ -x64 - - -# Visual C++ cache files -ipch/ -*.aps -*.ncb -*.opensdf -*.sdf -*.cachefile - -# Visual Studio profiler -*.psess -*.vsp -*.vspx - -.vs/ - -README.md \ No newline at end of file diff --git a/win-tun-driver/ForTun/Adapter.c b/win-tun-driver/ForTun/Adapter.c deleted file mode 100644 index a8389d3..0000000 --- a/win-tun-driver/ForTun/Adapter.c +++ /dev/null @@ -1,114 +0,0 @@ -#include "Adapter.h" -#include "rxqueue.h" -#include "txqueue.h" -#include "Adapter.tmh" - -#define FOR_TUN_MEDIA_MAX_SPEED 1'000'000'000 - -#if (NETADAPTER_VERSION_MAJOR>=2) && (NETADAPTER_VERSION_MINOR>=1) -EVT_NET_ADAPTER_OFFLOAD_SET_RX_CHECKSUM AdapterOffloadSetRxCHecksum; - - -VOID -AdapterOffloadSetRxChecksum(NETADAPTER Adapter, NETOFFLOAD offload) { - UNREFERENCED_PARAMETER(Adapter); - UNREFERENCED_PARAMETER(offload); -} -#endif - - -NTSTATUS -ForTunAdapterCreate(PDEVICE_CONTEXT DeviceContext, WDFDEVICE Device) { - - NTSTATUS status = STATUS_SUCCESS; - - TraceEvents(TRACE_LEVEL_INFORMATION, TRACE_ADAPTER, "%!FUNC! Entry"); - - NETADAPTER_INIT* adapterInit = NetAdapterInitAllocate(Device); - - NET_ADAPTER_DATAPATH_CALLBACKS datapathCallbacks; - NET_ADAPTER_DATAPATH_CALLBACKS_INIT(&datapathCallbacks, - ForTunAdapterCreateTXQueue, - ForTunAdapterCreateRXQueue); - NetAdapterInitSetDatapathCallbacks(adapterInit, &datapathCallbacks); - - WDF_OBJECT_ATTRIBUTES adapterAttributes; - WDF_OBJECT_ATTRIBUTES_INIT_CONTEXT_TYPE(&adapterAttributes, ADAPTER_CONTEXT); - - NETADAPTER netAdapter; - status = NetAdapterCreate(adapterInit, &adapterAttributes, &netAdapter); - if (!NT_SUCCESS(status)) { - goto adapterFail; - } - - NetAdapterInitFree(adapterInit); - adapterInit = NULL; - - - DeviceContext->Adapter = netAdapter; - PADAPTER_CONTEXT context = AdapterGetContext(netAdapter); - context->DeviceContext = DeviceContext; - - // Capabilities - // Limit - NET_ADAPTER_RX_CAPABILITIES rxCapabilities; - NET_ADAPTER_RX_CAPABILITIES_INIT_SYSTEM_MANAGED(&rxCapabilities, 65536,1); - NET_ADAPTER_TX_CAPABILITIES txCapabilities; - NET_ADAPTER_TX_CAPABILITIES_INIT(&txCapabilities, 1); - NetAdapterSetDataPathCapabilities(netAdapter, &txCapabilities, &rxCapabilities); - - //linkLayer - NET_ADAPTER_LINK_LAYER_CAPABILITIES linkLayerCapabilities; - NET_ADAPTER_LINK_LAYER_CAPABILITIES_INIT(&linkLayerCapabilities, FOR_TUN_MEDIA_MAX_SPEED, FOR_TUN_MEDIA_MAX_SPEED); - NetAdapterSetLinkLayerCapabilities(netAdapter, &linkLayerCapabilities); - NetAdapterSetLinkLayerMtuSize(netAdapter, 0xFFFF); - - //LinkState - ForTunAdapterSetLinkState(netAdapter, MediaConnectStateDisconnected); - -#if(NETADAPTER_VERSION_MAJOR>=2) && (NETADAPTER_VERSION_MINOR>=1) - AdapterOffloadSetRxChecksum(netAdapter); -#endif - - status = NetAdapterStart(netAdapter); - - goto done; - -adapterFail: - NetAdapterInitFree(adapterInit); - adapterInit = NULL; -done: - return status; -} - - -NTSTATUS ForTunAdapterNotifyRx(NETADAPTER NetAdapter) -{ - if (NetAdapter == WDF_NO_HANDLE) { - TraceEvents(TRACE_LEVEL_ERROR, TRACE_ADAPTER, "Adapter no initialized"); - return STATUS_DEVICE_NOT_READY; - } - - NETPACKETQUEUE rxQueue = AdapterGetContext(NetAdapter)->RxQueue; - PRXQUEUE_CONTEXT rxContext = RxQueueGetContext(rxQueue); - if (InterlockedExchange(&rxContext->NotificationEnabled, FALSE) == TRUE) { - TraceEvents(TRACE_LEVEL_INFORMATION, TRACE_ADAPTER, "begin to notify rxQueue"); - NetRxQueueNotifyMoreReceivedPacketsAvailable(rxQueue); - } - - return STATUS_SUCCESS; -} - -VOID ForTunAdapterSetLinkState(NETADAPTER Adapter, NET_IF_MEDIA_CONNECT_STATE State) -{ - NET_ADAPTER_LINK_STATE linkState; - NET_ADAPTER_LINK_STATE_INIT(&linkState, - FOR_TUN_MEDIA_MAX_SPEED, - State, - MediaDuplexStateFull, - NetAdapterPauseFunctionTypeUnsupported, - NetAdapterAutoNegotiationFlagNone); - NetAdapterSetLinkState(Adapter, &linkState); - - -} diff --git a/win-tun-driver/ForTun/Adapter.h b/win-tun-driver/ForTun/Adapter.h deleted file mode 100644 index 1a74a9e..0000000 --- a/win-tun-driver/ForTun/Adapter.h +++ /dev/null @@ -1,26 +0,0 @@ -#pragma once - - -#include "precomp.h" -#include "Device.h" - -EXTERN_C_START - -typedef struct _ADAPTER_CONTEXT { - NETPACKETQUEUE RxQueue; - PDEVICE_CONTEXT DeviceContext; -} ADAPTER_CONTEXT, *PADAPTER_CONTEXT; - - -WDF_DECLARE_CONTEXT_TYPE_WITH_NAME(ADAPTER_CONTEXT, AdapterGetContext) - - - -NTSTATUS -ForTunAdapterCreate(PDEVICE_CONTEXT DeviceContext, WDFDEVICE Device); - -NTSTATUS ForTunAdapterNotifyRx(NETADAPTER NetAdapter); - -VOID ForTunAdapterSetLinkState(NETADAPTER Adapter, NET_IF_MEDIA_CONNECT_STATE State); - -EXTERN_C_END \ No newline at end of file diff --git a/win-tun-driver/ForTun/Device.c b/win-tun-driver/ForTun/Device.c deleted file mode 100644 index ca1ba56..0000000 --- a/win-tun-driver/ForTun/Device.c +++ /dev/null @@ -1,158 +0,0 @@ -/*++ - -Module Name: - - device.c - Device handling events for example driver. - -Abstract: - - This file contains the device entry points and callbacks. - -Environment: - - Kernel-mode Driver Framework - ---*/ - -#include "Device.h" -#include "Adapter.h" -#include "Queue.h" -#include "Public.h" -#include "device.tmh" - -#ifdef ALLOC_PRAGMA -#pragma alloc_text (PAGE, ForTunCreateDevice) -#endif - -NTSTATUS -ForTunCreateDevice( - _Inout_ PWDFDEVICE_INIT DeviceInit -) -/*++ - -Routine Description: - - Worker routine called to create a device and its software resources. - -Arguments: - - DeviceInit - Pointer to an opaque init structure. Memory for this - structure will be freed by the framework when the WdfDeviceCreate - succeeds. So don't access the structure after that point. - -Return Value: - - NTSTATUS - ---*/ -{ - WDF_OBJECT_ATTRIBUTES deviceAttributes; - PDEVICE_CONTEXT deviceContext; - WDFDEVICE device; - NTSTATUS status; - - - TraceEvents(TRACE_LEVEL_INFORMATION, TRACE_DEVICE, "%!FUNC! Entry"); - - PAGED_CODE(); - - WdfDeviceInitSetExclusive(DeviceInit, TRUE); - - - WDF_FILEOBJECT_CONFIG fileConfig; - WDF_FILEOBJECT_CONFIG_INIT(&fileConfig, WDF_NO_EVENT_CALLBACK, WDF_NO_EVENT_CALLBACK, ForTunFileCleanUp); - WdfDeviceInitSetFileObjectConfig(DeviceInit, &fileConfig, WDF_NO_OBJECT_ATTRIBUTES); - - - status = NetDeviceInitConfig(DeviceInit); - if (!NT_SUCCESS(status)) { - goto done; - } - - WDF_OBJECT_ATTRIBUTES_INIT_CONTEXT_TYPE(&deviceAttributes, DEVICE_CONTEXT); - - - deviceAttributes.EvtCleanupCallback = ForTunDeviceCleanUp; - - status = WdfDeviceCreate(&DeviceInit, &deviceAttributes, &device); - - if (!NT_SUCCESS(status)) { - TraceEvents(TRACE_LEVEL_INFORMATION, TRACE_DEVICE, "WdfDeviceCreate failure: %x", status); - goto done; - } - - - deviceContext = DeviceGetContext(device); - DECLARE_CONST_UNICODE_STRING(symLink, L"\\DosDevices\\ForTun"); - - // - // Create a device interface so that applications can find and talk - // to us. - // - // If the client driver calls WdfDeviceCreateDeviceInterface with the ReferenceString parameter equal to NULL, - // NDIS intercepts I/O requests sent to the device interface. To avoid this behavior, specify any reference string. - - status = WdfDeviceCreateSymbolicLink(device, &symLink); - if (!NT_SUCCESS(status)) { - TraceEvents(TRACE_LEVEL_INFORMATION, TRACE_DEVICE, "create symLink failure: %x", status); - } - - UNICODE_STRING referenceString; - RtlInitUnicodeString(&referenceString, L"ForTun"); - - - status = WdfDeviceCreateDeviceInterface( - device, - &GUID_DEVINTERFACE_ForTun, - &referenceString - ); - - if (!NT_SUCCESS(status)) { - //This would fail if multiple device create.. - TraceEvents(TRACE_LEVEL_INFORMATION, TRACE_DEVICE, "create device interface failure: %x", status); - goto done; - } - // Initialize the I/O Package and any Queues - - status = ForTunQueueInitialize(device); - - if (!NT_SUCCESS(status)) { - TraceEvents(TRACE_LEVEL_INFORMATION, TRACE_DEVICE, "WdfDeviceCreate failure: %x", status); - goto done; - } - - status = ForTunAdapterCreate(deviceContext, device); - - -done: - if (!NT_SUCCESS(status)) { - TraceEvents(TRACE_LEVEL_INFORMATION, TRACE_DEVICE, "create device failure: %x", status); - } - return status; -} - - - -VOID ForTunDeviceCleanUp(WDFOBJECT Obj) { - - UNREFERENCED_PARAMETER(Obj); - TraceEvents(TRACE_LEVEL_INFORMATION, TRACE_DEVICE, "%!FUNC! Entry"); - - PDEVICE_CONTEXT pDeviceContext = DeviceGetContext(Obj); - PoolQueueFree(pDeviceContext->PoolQueue); - //pDeviceContext->Adapter = WDF_NO_HANDLE; - -} - -VOID ForTunFileCleanUp( - _In_ - WDFFILEOBJECT FileObject -) { - TraceEvents(TRACE_LEVEL_INFORMATION, TRACE_DEVICE, "%!FUNC! Entry"); - PDEVICE_CONTEXT context = DeviceGetContext(WdfFileObjectGetDevice(FileObject)); - - if (context->Adapter != NULL) { - ForTunAdapterSetLinkState(context->Adapter, MediaConnectStateDisconnected); - } - -} \ No newline at end of file diff --git a/win-tun-driver/ForTun/Device.h b/win-tun-driver/ForTun/Device.h deleted file mode 100644 index c3593d8..0000000 --- a/win-tun-driver/ForTun/Device.h +++ /dev/null @@ -1,58 +0,0 @@ -/*++ - -Module Name: - - device.h - -Abstract: - - This file contains the device definitions. - -Environment: - - Kernel-mode Driver Framework - ---*/ -#pragma once -#include "precomp.h" -#include "Ringbuffer.h" - -EXTERN_C_START - -// -// The device context performs the same job as -// a WDM device extension in the driver frameworks -// -typedef struct _DEVICE_CONTEXT -{ - - WDFQUEUE PendingWriteQueue; - WDFQUEUE PendingReadQueue; - - PPOOL_QUEUE PoolQueue; - WDFSPINLOCK readLock; - - NETADAPTER Adapter; -} DEVICE_CONTEXT, *PDEVICE_CONTEXT; - -// -// This macro will generate an inline function called DeviceGetContext -// which will be used to get a pointer to the device context memory -// in a type safe manner. -// -WDF_DECLARE_CONTEXT_TYPE_WITH_NAME(DEVICE_CONTEXT, DeviceGetContext) - -// -// Function to initialize the device and its callbacks -// -NTSTATUS -ForTunCreateDevice( - _Inout_ PWDFDEVICE_INIT DeviceInit - ); - - -EVT_WDF_DEVICE_CONTEXT_CLEANUP ForTunDeviceCleanUp; - -EVT_WDF_FILE_CLEANUP ForTunFileCleanUp; - -EXTERN_C_END diff --git a/win-tun-driver/ForTun/Driver.c b/win-tun-driver/ForTun/Driver.c deleted file mode 100644 index 3f571b2..0000000 --- a/win-tun-driver/ForTun/Driver.c +++ /dev/null @@ -1,167 +0,0 @@ -/*++ - -Module Name: - - driver.c - -Abstract: - - This file contains the driver entry points and callbacks. - -Environment: - - Kernel-mode Driver Framework - ---*/ - -#include "driver.h" -#include "Device.h" -#include "driver.tmh" - -#ifdef ALLOC_PRAGMA -#pragma alloc_text (INIT, DriverEntry) -#pragma alloc_text (PAGE, ForTunEvtDeviceAdd) -#pragma alloc_text (PAGE, ForTunEvtDriverContextCleanup) -#endif - -NTSTATUS -DriverEntry( - _In_ PDRIVER_OBJECT DriverObject, - _In_ PUNICODE_STRING RegistryPath - ) -/*++ - -Routine Description: - DriverEntry initializes the driver and is the first routine called by the - system after the driver is loaded. DriverEntry specifies the other entry - points in the function driver, such as EvtDevice and DriverUnload. - -Parameters Description: - - DriverObject - represents the instance of the function driver that is loaded - into memory. DriverEntry must initialize members of DriverObject before it - returns to the caller. DriverObject is allocated by the system before the - driver is loaded, and it is released by the system after the system unloads - the function driver from memory. - - RegistryPath - represents the driver specific path in the Registry. - The function driver can use the path to store driver related data between - reboots. The path does not store hardware instance specific data. - -Return Value: - - STATUS_SUCCESS if successful, - STATUS_UNSUCCESSFUL otherwise. - ---*/ -{ - WDF_DRIVER_CONFIG config; - NTSTATUS status; - WDF_OBJECT_ATTRIBUTES attributes; - // - // Initialize WPP Tracing - // - WPP_INIT_TRACING(DriverObject, RegistryPath); - - - - TraceEvents(TRACE_LEVEL_INFORMATION, TRACE_DRIVER, "%!FUNC! Entry"); - - // - // Register a cleanup callback so that we can call WPP_CLEANUP when - // the framework driver object is deleted during driver unload. - // - WDF_OBJECT_ATTRIBUTES_INIT(&attributes); - attributes.EvtCleanupCallback = ForTunEvtDriverContextCleanup; - - - WDF_DRIVER_CONFIG_INIT(&config, - ForTunEvtDeviceAdd - ); - - status = WdfDriverCreate(DriverObject, - RegistryPath, - &attributes, - &config, - WDF_NO_HANDLE - ); - - if (!NT_SUCCESS(status)) { - TraceEvents(TRACE_LEVEL_ERROR, TRACE_DRIVER, "WdfDriverCreate failed %!STATUS!", status); - WPP_CLEANUP(DriverObject); - return status; - } - - TraceEvents(TRACE_LEVEL_INFORMATION, TRACE_DRIVER, "%!FUNC! Exit"); - - return status; -} - -NTSTATUS -ForTunEvtDeviceAdd( - _In_ WDFDRIVER Driver, - _Inout_ PWDFDEVICE_INIT DeviceInit - ) -/*++ -Routine Description: - - EvtDeviceAdd is called by the framework in response to AddDevice - call from the PnP manager. We create and initialize a device object to - represent a new instance of the device. - -Arguments: - - Driver - Handle to a framework driver object created in DriverEntry - - DeviceInit - Pointer to a framework-allocated WDFDEVICE_INIT structure. - -Return Value: - - NTSTATUS - ---*/ -{ - NTSTATUS status; - - UNREFERENCED_PARAMETER(Driver); - - // PAGED_CODE(); - - TraceEvents(TRACE_LEVEL_INFORMATION, TRACE_DRIVER, "%!FUNC! Entry"); - - - status = ForTunCreateDevice(DeviceInit); - TraceEvents(TRACE_LEVEL_INFORMATION, TRACE_DRIVER, "%!FUNC! Exit"); - return status; -} - -VOID -ForTunEvtDriverContextCleanup( - _In_ WDFOBJECT DriverObject - ) -/*++ -Routine Description: - - Free all the resources allocated in DriverEntry. - -Arguments: - - DriverObject - handle to a WDF Driver object. - -Return Value: - - VOID. - ---*/ -{ - UNREFERENCED_PARAMETER(DriverObject); - - PAGED_CODE(); - - TraceEvents(TRACE_LEVEL_INFORMATION, TRACE_DRIVER, "%!FUNC! Entry"); - - // - // Stop WPP Tracing - // - WPP_CLEANUP(WdfDriverWdmGetDriverObject((WDFDRIVER)DriverObject)); -} diff --git a/win-tun-driver/ForTun/Driver.h b/win-tun-driver/ForTun/Driver.h deleted file mode 100644 index c2736eb..0000000 --- a/win-tun-driver/ForTun/Driver.h +++ /dev/null @@ -1,32 +0,0 @@ -/*++ - -Module Name: - - driver.h - -Abstract: - - This file contains the driver definitions. - -Environment: - - Kernel-mode Driver Framework - ---*/ - -#include "precomp.h" - -#include "device.h" -#include "queue.h" - -EXTERN_C_START - -// -// WDFDRIVER Events -// - -DRIVER_INITIALIZE DriverEntry; -EVT_WDF_DRIVER_DEVICE_ADD ForTunEvtDeviceAdd; -EVT_WDF_OBJECT_CONTEXT_CLEANUP ForTunEvtDriverContextCleanup; - -EXTERN_C_END diff --git a/win-tun-driver/ForTun/ForTun.inf b/win-tun-driver/ForTun/ForTun.inf deleted file mode 100644 index 9aa103c..0000000 --- a/win-tun-driver/ForTun/ForTun.inf +++ /dev/null @@ -1,98 +0,0 @@ -; -; ForTun.inf -; - -[Version] -Signature="$WINDOWS NT$" -Class=Net -ClassGuid={4d36e972-e325-11ce-bfc1-08002be10318} -Provider=%ManufacturerName% -CatalogFile=ForTun.cat -;DriverVer=0.0.1 -PnpLockdown=1 - -[DestinationDirs] -;DefaultDestDir = 12 -Drivers_Dir = 13 -;ForTun_Device_CoInstaller_CopyFiles = 11 - -[SourceDisksNames] -1 = %DiskName% - -[SourceDisksFiles] -ForTun.sys = 1,, -;WdfCoInstaller$KMDFCOINSTALLERVERSION$.dll=1 ; make sure the number matches with SourceDisksNames - -;***************************************** -; Install Section -;***************************************** - -[Manufacturer] -%ManufacturerName%=Standard,NT$ARCH$ - -[Standard.NT$ARCH$] -%ForTun.DeviceDesc%=ForTun_Device, ForTun - -[ForTun_Device.NT] -CopyFiles=Drivers_Dir ;dirid 13 -AddReg=ForTun_AddReg - -Characteristics = 1 ; NCF_VIRTUAL - -*IfType = 53 ; IF_TYPE_PROP_VIRTUAL -*MediaType = 19 ; NdisMediumIP -*PhysicalMediaType = 0 ; NdisPhysicalMediumUnspecified - -*IfConnectorPresent = 0 -*ConnectionType = 1 ; NET_IF_CONNECTION_PASSIVE -*DirectionType = 0 ; NET_IF_DIRECTION_SENDRECEIVE -*AccessType = 2 ; NET_IF_ACCESS_POINT_TO_POINT -*HardwareLoopback = 0 - -[ForTun_AddReg] -; Note that "ndis5" simply means to bind to TCPIP; it is not a version number. -HKR, Ndi\Interfaces, UpperRange, 0, "ndis5" -HKR, Ndi\Interfaces, LowerRange, 0, "nolower" -HKR, Ndi, Service, 0, %ForTun.Name% - -[Drivers_Dir] -ForTun.sys - -;-------------- Service installation -[ForTun_Device.NT.Services] -AddService = ForTun,%SPSVCINST_ASSOCSERVICE%, ForTun_Service_Inst - -; -------------- ForTun driver install sections -[ForTun_Service_Inst] -DisplayName = %ForTun.SVCDESC% -ServiceType = 1 ; SERVICE_KERNEL_DRIVER -StartType = 3 ; SERVICE_DEMAND_START -ErrorControl = 1 ; SERVICE_ERROR_NORMAL -ServiceBinary = %13%\ForTun.sys - -; -;--- ForTun_Device Coinstaller installation ------ -; - -;[ForTun_Device.NT.CoInstallers] -;AddReg=ForTun_Device_CoInstaller_AddReg -;CopyFiles=ForTun_Device_CoInstaller_CopyFiles - -;[ForTun_Device_CoInstaller_AddReg] -;HKR,,CoInstallers32,0x00010000, "WdfCoInstaller$KMDFCOINSTALLERVERSION$.dll,WdfCoInstaller" - -;[ForTun_Device_CoInstaller_CopyFiles] -;WdfCoInstaller$KMDFCOINSTALLERVERSION$.dll - -[ForTun_Device.NT.Wdf] -KmdfService = ForTun, ForTun_wdfsect -[ForTun_wdfsect] -KmdfLibraryVersion = $KMDFVERSION$ - -[Strings] -SPSVCINST_ASSOCSERVICE= 0x00000002 -ManufacturerName= "Timzaak" -DiskName = "ForTun Installation Disk" -ForTun.DeviceDesc = "ForTun Device" -ForTun.SVCDESC = "ForTun Service" -ForTun.Name = "ForTun" diff --git a/win-tun-driver/ForTun/ForTun.sln b/win-tun-driver/ForTun/ForTun.sln deleted file mode 100644 index 0b720fe..0000000 --- a/win-tun-driver/ForTun/ForTun.sln +++ /dev/null @@ -1,35 +0,0 @@ - -Microsoft Visual Studio Solution File, Format Version 12.00 -# Visual Studio Version 17 -VisualStudioVersion = 17.4.33205.214 -MinimumVisualStudioVersion = 10.0.40219.1 -Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "ForTun", "ForTun.vcxproj", "{4EF57910-A75E-48FB-89A0-B4005D9F609B}" -EndProject -Global - GlobalSection(SolutionConfigurationPlatforms) = preSolution - Debug|ARM64 = Debug|ARM64 - Debug|x64 = Debug|x64 - Release|ARM64 = Release|ARM64 - Release|x64 = Release|x64 - EndGlobalSection - GlobalSection(ProjectConfigurationPlatforms) = postSolution - {4EF57910-A75E-48FB-89A0-B4005D9F609B}.Debug|ARM64.ActiveCfg = Debug|ARM64 - {4EF57910-A75E-48FB-89A0-B4005D9F609B}.Debug|ARM64.Build.0 = Debug|ARM64 - {4EF57910-A75E-48FB-89A0-B4005D9F609B}.Debug|ARM64.Deploy.0 = Debug|ARM64 - {4EF57910-A75E-48FB-89A0-B4005D9F609B}.Debug|x64.ActiveCfg = Debug|x64 - {4EF57910-A75E-48FB-89A0-B4005D9F609B}.Debug|x64.Build.0 = Debug|x64 - {4EF57910-A75E-48FB-89A0-B4005D9F609B}.Debug|x64.Deploy.0 = Debug|x64 - {4EF57910-A75E-48FB-89A0-B4005D9F609B}.Release|ARM64.ActiveCfg = Release|ARM64 - {4EF57910-A75E-48FB-89A0-B4005D9F609B}.Release|ARM64.Build.0 = Release|ARM64 - {4EF57910-A75E-48FB-89A0-B4005D9F609B}.Release|ARM64.Deploy.0 = Release|ARM64 - {4EF57910-A75E-48FB-89A0-B4005D9F609B}.Release|x64.ActiveCfg = Release|x64 - {4EF57910-A75E-48FB-89A0-B4005D9F609B}.Release|x64.Build.0 = Release|x64 - {4EF57910-A75E-48FB-89A0-B4005D9F609B}.Release|x64.Deploy.0 = Release|x64 - EndGlobalSection - GlobalSection(SolutionProperties) = preSolution - HideSolutionNode = FALSE - EndGlobalSection - GlobalSection(ExtensibilityGlobals) = postSolution - SolutionGuid = {B60E5DE5-FC15-4A72-8423-4882FBAC5684} - EndGlobalSection -EndGlobal diff --git a/win-tun-driver/ForTun/ForTun.vcxproj b/win-tun-driver/ForTun/ForTun.vcxproj deleted file mode 100644 index e74ca01..0000000 --- a/win-tun-driver/ForTun/ForTun.vcxproj +++ /dev/null @@ -1,172 +0,0 @@ - - - - - Debug - x64 - - - Release - x64 - - - Debug - ARM64 - - - Release - ARM64 - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - {4EF57910-A75E-48FB-89A0-B4005D9F609B} - {497e31cb-056b-4f31-abb8-447fd55ee5a5} - v4.5 - 12.0 - Debug - x64 - ForTun - - - - Windows10 - true - WindowsKernelModeDriver10.0 - Driver - KMDF - Windows Driver - true - 2 - 0 - - - Windows10 - false - WindowsKernelModeDriver10.0 - Driver - KMDF - Universal - - - Windows10 - true - WindowsKernelModeDriver10.0 - Driver - KMDF - Universal - - - Windows10 - false - WindowsKernelModeDriver10.0 - Driver - KMDF - Universal - - - - - - - - - - - - - - - - - DbgengKernelDebugger - true - - - DbgengKernelDebugger - - - DbgengKernelDebugger - - - DbgengKernelDebugger - - - - true - true - trace.h - true - NETADAPTER_VERSION_MAJOR=$(NETADAPTER_VERSION_MAJOR);NETADAPTER_VERSION_MINOR=$(NETADAPTER_VERSION_MINOR);FOR_TUN_VERSION_MAJOR=$(FOR_TUN_VERSION_MAJOR);FOR_TUN_VERSION_MINOR=$(FOR_TUN_VERSION_MINOR);FOR_TUN_VERSION_PATCH=$(FOR_TUN_VERSION_PATCH);FOR_TUN_VERSION_STR=$(FOR_TUN_VERSION_MAJOR).$(FOR_TUN_VERSION_MINOR).$(FOR_TUN_VERSION_PATCH);%(PreprocessorDefinitions) - - - sha256 - - - - - true - true - trace.h - true - - - sha256 - - - - - true - true - trace.h - true - - - sha256 - - - - - true - true - trace.h - true - - - sha256 - - - - - - - - - \ No newline at end of file diff --git a/win-tun-driver/ForTun/ForTun.vcxproj.filters b/win-tun-driver/ForTun/ForTun.vcxproj.filters deleted file mode 100644 index f66c6c3..0000000 --- a/win-tun-driver/ForTun/ForTun.vcxproj.filters +++ /dev/null @@ -1,87 +0,0 @@ - - - - - {4FC737F1-C7A5-4376-A066-2A32D752A2FF} - cpp;c;cc;cxx;def;odl;idl;hpj;bat;asm;asmx - - - {93995380-89BD-4b04-88EB-625FBE52EBFB} - h;hpp;hxx;hm;inl;inc;xsd - - - {67DA6AB6-F800-4c08-8B7A-83BB121AAD01} - rc;ico;cur;bmp;dlg;rc2;rct;bin;rgs;gif;jpg;jpeg;jpe;resx;tiff;tif;png;wav;mfcribbon-ms - - - {8E41214B-6785-4CFE-B992-037D68949A14} - inf;inv;inx;mof;mc; - - - - - - - - Driver Files - - - - - Header Files - - - Header Files - - - Header Files - - - Header Files - - - Header Files - - - Header Files - - - Header Files - - - Header Files - - - Header Files - - - Header Files - - - Header Files - - - - - Source Files - - - Source Files - - - Source Files - - - Source Files - - - Source Files - - - Source Files - - - Source Files - - - \ No newline at end of file diff --git a/win-tun-driver/ForTun/PropertySheet.props b/win-tun-driver/ForTun/PropertySheet.props deleted file mode 100644 index 6cd63a1..0000000 --- a/win-tun-driver/ForTun/PropertySheet.props +++ /dev/null @@ -1,22 +0,0 @@ - - - - - 0 - 1 - 0 - - - - - - $(FOR_TUN_VERSION_MAJOR) - - - $(FOR_TUN_VERSION_MINOR) - - - $(FOR_TUN_VERSION_PATCH) - - - \ No newline at end of file diff --git a/win-tun-driver/ForTun/Public.h b/win-tun-driver/ForTun/Public.h deleted file mode 100644 index 2a034e1..0000000 --- a/win-tun-driver/ForTun/Public.h +++ /dev/null @@ -1,32 +0,0 @@ -/*++ - -Module Name: - - public.h - -Abstract: - - This module contains the common declarations shared by driver - and user applications. - -Environment: - - user and kernel - ---*/ - -// -// Define an Interface Guid so that apps can find the device and talk to it. -// -#pragma once - -#include "initguid.h" - - -#define FOR_TUN_IOCTL_OPEN_ADAPTER CTL_CODE(FILE_DEVICE_UNKNOWN, 0x0801, METHOD_BUFFERED, FILE_ANY_ACCESS) - - - -DEFINE_GUID (GUID_DEVINTERFACE_ForTun, - 0xf579d929,0x6c40,0x4e5a,0x85,0x32,0x18,0x01,0x99,0xa4,0xe3,0x21); -// {f579d929-6c40-4e5a-8532-180199a4e321} diff --git a/win-tun-driver/ForTun/Queue.c b/win-tun-driver/ForTun/Queue.c deleted file mode 100644 index 238962a..0000000 --- a/win-tun-driver/ForTun/Queue.c +++ /dev/null @@ -1,352 +0,0 @@ -/*++ - -Module Name: - - queue.c - -Abstract: - - This file contains the queue entry points and callbacks. - -Environment: - - Kernel-mode Driver Framework - ---*/ - -#include "Queue.h" -#include "Device.h" -#include "Ringbuffer.h" -#include "Adapter.h" -#include "Public.h" -#include "queue.tmh" - -#ifdef ALLOC_PRAGMA -#pragma alloc_text (PAGE, ForTunQueueInitialize) -#endif - - -NTSTATUS -ForTunQueueInitialize( - _In_ WDFDEVICE Device - ) -/*++ - -Routine Description: - - The I/O dispatch callbacks for the frameworks device object - are configured in this function. - - A single default I/O Queue is configured for parallel request - processing, and a driver context memory allocation is created - to hold our structure QUEUE_CONTEXT. - -Arguments: - - Device - Handle to a framework device object. - -Return Value: - - VOID - ---*/ -{ - WDFQUEUE queue; - NTSTATUS status; - WDF_IO_QUEUE_CONFIG queueConfig; - - PAGED_CODE(); - - TraceEvents(TRACE_LEVEL_INFORMATION, TRACE_QUEUE, "%!FUNC! Entry"); - - // - // Configure a default queue so that requests that are not - // configure-fowarded using WdfDeviceConfigureRequestDispatching to goto - // other queues get dispatched here. - // - WDF_IO_QUEUE_CONFIG_INIT_DEFAULT_QUEUE( - &queueConfig, - WdfIoQueueDispatchSequential - ); - - queueConfig.EvtIoDeviceControl = ForTunEvtIoDeviceControl; - queueConfig.EvtIoRead = ForTunEvtIoRead; - queueConfig.EvtIoStop = ForTunEvtIoStop; - queueConfig.EvtIoWrite = ForTunEvtIoWrite; - - status = WdfIoQueueCreate( - Device, - &queueConfig, - WDF_NO_OBJECT_ATTRIBUTES, - &queue - ); - - if(!NT_SUCCESS(status)) { - TraceEvents(TRACE_LEVEL_ERROR, TRACE_QUEUE, "create default queue failed %!STATUS!", status); - return status; - } - - WDF_IO_QUEUE_CONFIG_INIT(&queueConfig, WdfIoQueueDispatchManual); - - WDFQUEUE readQueue; - status = WdfIoQueueCreate(Device, &queueConfig, WDF_NO_OBJECT_ATTRIBUTES, &readQueue); - if (!NT_SUCCESS(status)) { - TraceEvents(TRACE_LEVEL_ERROR, TRACE_QUEUE, "create read queue failed %!STATUS!", status); - return status; - } - //status = WdfDeviceConfigureRequestDispatching(Device, readQueue, WdfRequestTypeRead); - //if (!NT_SUCCESS(status)) { - // goto done; - //} - WDFQUEUE writeQueue; - WDF_IO_QUEUE_CONFIG_INIT(&queueConfig, WdfIoQueueDispatchManual); - status = WdfIoQueueCreate(Device, &queueConfig, WDF_NO_OBJECT_ATTRIBUTES, &writeQueue); - - if (!NT_SUCCESS(status)) { - TraceEvents(TRACE_LEVEL_ERROR, TRACE_QUEUE, "create write queue failed %!STATUS!", status); - return status; - } - //status = WdfDeviceConfigureRequestDispatching(Device, writeQueue, WdfRequestTypeWrite); - PDEVICE_CONTEXT device_context = DeviceGetContext(Device); - - /* - WDF_OBJECT_ATTRIBUTES attr; - WDF_OBJECT_ATTRIBUTES_INIT(&attr); - attr.ParentObject = Device; - WDFMEMORY BufferHandler; - status = WdfMemoryCreate(&attr, NonPagedPool, 'FTun', READ_POOL_SIZE, &BufferHandler, &device_context->PReadBuffer); - if (!NT_SUCCESS(status)) { - TraceEvents(TRACE_LEVEL_ERROR, TRACE_QUEUE, "create ReadBuffer failed %!STATUS!", status); - goto done; - } - RtlZeroMemory(device_context->PReadBuffer, READ_POOL_SIZE); - RingBufferInitialize(&device_context->ReadRingBuffer, device_context->PReadBuffer, READ_POOL_SIZE); - */ - PPOOL_QUEUE poolQueue; - status = PoolQueueCreate(&poolQueue); - if (!NT_SUCCESS(status)) { - TraceEvents(TRACE_LEVEL_ERROR, TRACE_QUEUE, "create PoolQueue failed %!STATUS!", status); - goto done; - } - device_context->PoolQueue = poolQueue; - device_context->PendingReadQueue = readQueue; - device_context->PendingWriteQueue = writeQueue; - - - WDF_OBJECT_ATTRIBUTES attr; - WDF_OBJECT_ATTRIBUTES_INIT(&attr); - attr.ParentObject = Device; - - WdfSpinLockCreate(&attr, &device_context->readLock); - - -done: - return status; -} - -VOID -ForTunEvtIoDeviceControl( - _In_ WDFQUEUE Queue, - _In_ WDFREQUEST Request, - _In_ size_t OutputBufferLength, - _In_ size_t InputBufferLength, - _In_ ULONG IoControlCode - ) -/*++ - -Routine Description: - - This event is invoked when the framework receives IRP_MJ_DEVICE_CONTROL request. - -Arguments: - - Queue - Handle to the framework queue object that is associated with the - I/O request. - - Request - Handle to a framework request object. - - OutputBufferLength - Size of the output buffer in bytes - - InputBufferLength - Size of the input buffer in bytes - - IoControlCode - I/O control code. - -Return Value: - - VOID - ---*/ -{ - TraceEvents(TRACE_LEVEL_INFORMATION, - TRACE_QUEUE, - "%!FUNC! Queue 0x%p, Request 0x%p OutputBufferLength %d InputBufferLength %d IoControlCode %d", - Queue, Request, (int) OutputBufferLength, (int) InputBufferLength, IoControlCode); - - switch (IoControlCode) { - case FOR_TUN_IOCTL_OPEN_ADAPTER: - NETADAPTER adapter = DeviceGetContext(WdfIoQueueGetDevice(Queue))->Adapter; - ForTunAdapterSetLinkState(adapter, MediaConnectStateConnected); - WdfRequestComplete(Request, STATUS_SUCCESS); - break; - - default: - WdfRequestComplete(Request, STATUS_INVALID_DEVICE_REQUEST); - } -} - -VOID -ForTunEvtIoStop( - _In_ WDFQUEUE Queue, - _In_ WDFREQUEST Request, - _In_ ULONG ActionFlags -) -/*++ - -Routine Description: - - This event is invoked for a power-managed queue before the device leaves the working state (D0). - -Arguments: - - Queue - Handle to the framework queue object that is associated with the - I/O request. - - Request - Handle to a framework request object. - - ActionFlags - A bitwise OR of one or more WDF_REQUEST_STOP_ACTION_FLAGS-typed flags - that identify the reason that the callback function is being called - and whether the request is cancelable. - -Return Value: - - VOID - ---*/ -{ - TraceEvents(TRACE_LEVEL_INFORMATION, - TRACE_QUEUE, - "%!FUNC! Queue 0x%p, Request 0x%p ActionFlags %d, trigger IoStop", - Queue, Request, ActionFlags); - - // - // In most cases, the EvtIoStop callback function completes, cancels, or postpones - // further processing of the I/O request. - // - // Typically, the driver uses the following rules: - // - // - If the driver owns the I/O request, it calls WdfRequestUnmarkCancelable - // (if the request is cancelable) and either calls WdfRequestStopAcknowledge - // with a Requeue value of TRUE, or it calls WdfRequestComplete with a - // completion status value of STATUS_SUCCESS or STATUS_CANCELLED. - // - // Before it can call these methods safely, the driver must make sure that - // its implementation of EvtIoStop has exclusive access to the request. - // - // In order to do that, the driver must synchronize access to the request - // to prevent other threads from manipulating the request concurrently. - // The synchronization method you choose will depend on your driver's design. - // - // For example, if the request is held in a shared context, the EvtIoStop callback - // might acquire an internal driver lock, take the request from the shared context, - // and then release the lock. At this point, the EvtIoStop callback owns the request - // and can safely complete or requeue the request. - // - // - If the driver has forwarded the I/O request to an I/O target, it either calls - // WdfRequestCancelSentRequest to attempt to cancel the request, or it postpones - // further processing of the request and calls WdfRequestStopAcknowledge with - // a Requeue value of FALSE. - // - // A driver might choose to take no action in EvtIoStop for requests that are - // guaranteed to complete in a small amount of time. - // - // In this case, the framework waits until the specified request is complete - // before moving the device (or system) to a lower power state or removing the device. - // Potentially, this inaction can prevent a system from entering its hibernation state - // or another low system power state. In extreme cases, it can cause the system - // to crash with bugcheck code 9F. - // - - return; -} - - -VOID -ForTunEvtIoRead( - IN WDFQUEUE Queue, - IN WDFREQUEST Request, - IN size_t Length -) -{ - UNREFERENCED_PARAMETER(Length); - NTSTATUS status; - - PDEVICE_CONTEXT deviceContext = DeviceGetContext(WdfIoQueueGetDevice(Queue)); - - PVOID readBuffer; - status = WdfRequestRetrieveOutputBuffer(Request, sizeof(LONG), &readBuffer, NULL); - if (!NT_SUCCESS(status)) { - goto logErr; - - } - - WdfSpinLockAcquire(deviceContext->readLock); - - PPOOL_QUEUE_ITEM poolQueueItem = PoolQueueGetFromQueue(deviceContext->PoolQueue); - - if (poolQueueItem) { - RtlCopyMemory(readBuffer, &poolQueueItem->Data, poolQueueItem->DataSize); - size_t dataSize = poolQueueItem->DataSize; - PoolQueuePutToPool(deviceContext->PoolQueue, poolQueueItem); - WdfSpinLockRelease(deviceContext->readLock); - WdfRequestCompleteWithInformation(Request, STATUS_SUCCESS, dataSize); - } -/* - status = RingBufferRead(&deviceContext->ReadRingBuffer, (BYTE*)&readBuffer, Length, &bytesCopied); - if (!NT_SUCCESS(status)) { - WdfSpinLockRelease(deviceContext->readLock); - goto logErr; - } - if (bytesCopied > 0) { - WdfSpinLockRelease(deviceContext->readLock); - WdfRequestCompleteWithInformation(Request, status, bytesCopied); - }*/ - else { - status = WdfRequestForwardToIoQueue(Request, deviceContext->PendingReadQueue); - WdfSpinLockRelease(deviceContext->readLock); - if (!NT_SUCCESS(status)) { - goto logErr; - } - } - - return; -logErr: - WdfRequestComplete(Request, status); - TraceEvents(TRACE_LEVEL_ERROR, TRACE_QUEUE, "read occur error:%d", status); -} - -VOID -ForTunEvtIoWrite( - IN WDFQUEUE Queue, - IN WDFREQUEST Request, - IN size_t Length -) -{ - UNREFERENCED_PARAMETER(Length); - - PDEVICE_CONTEXT context = DeviceGetContext(WdfIoQueueGetDevice(Queue)); - - WDFQUEUE PendingQueue = context->PendingWriteQueue; - - NTSTATUS status = WdfRequestForwardToIoQueue(Request, PendingQueue); - if (!NT_SUCCESS(status)) { - WdfRequestComplete(Request, status); - goto logErr; - } - - //this should always be success - ForTunAdapterNotifyRx(context->Adapter); - - return; -logErr: - TraceEvents(TRACE_LEVEL_ERROR, TRACE_QUEUE, "write occur error:%d", status); -} \ No newline at end of file diff --git a/win-tun-driver/ForTun/Queue.h b/win-tun-driver/ForTun/Queue.h deleted file mode 100644 index b6be82c..0000000 --- a/win-tun-driver/ForTun/Queue.h +++ /dev/null @@ -1,34 +0,0 @@ -/*++ - -Module Name: - - queue.h - -Abstract: - - This file contains the queue definitions. - -Environment: - - Kernel-mode Driver Framework - ---*/ -#pragma once -#include "precomp.h" - -EXTERN_C_START - -NTSTATUS -ForTunQueueInitialize( - _In_ WDFDEVICE Device - ); - -// -// Events from the IoQueue object -// -EVT_WDF_IO_QUEUE_IO_DEVICE_CONTROL ForTunEvtIoDeviceControl; -EVT_WDF_IO_QUEUE_IO_STOP ForTunEvtIoStop; -EVT_WDF_IO_QUEUE_IO_READ ForTunEvtIoRead; -EVT_WDF_IO_QUEUE_IO_WRITE ForTunEvtIoWrite; - -EXTERN_C_END diff --git a/win-tun-driver/ForTun/RXQueue.c b/win-tun-driver/ForTun/RXQueue.c deleted file mode 100644 index ba9c3a6..0000000 --- a/win-tun-driver/ForTun/RXQueue.c +++ /dev/null @@ -1,166 +0,0 @@ -#include "RXQueue.h" -#include "Adapter.h" -#include "netringiterator.h" -#include "Ringbuffer.h" -#include -#include -#include "RXQueue.tmh" -#include "netiodef.h" - -UINT8 -GetLayer4Type(const VOID* buf, size_t len) { - UINT8 ret = NetPacketLayer4TypeUnspecified; - if (len < sizeof(IPV4_HEADER)) - return ret; - - IPV4_HEADER* ipv4hdr = (IPV4_HEADER*)buf; - if (ipv4hdr->Version == IPV4_VERSION) { - if (ipv4hdr->Protocol == IPPROTO_TCP) - ret = NetPacketLayer4TypeTcp; - else if (ipv4hdr->Protocol == IPPROTO_UDP) - ret = NetPacketLayer4TypeUdp; - } - else if (ipv4hdr->Version == 6) { - if (len < sizeof(IPV6_HEADER)) - return ret; - - IPV6_HEADER* ipv6hdr = (IPV6_HEADER*)buf; - if (ipv6hdr->NextHeader == IPPROTO_TCP) - ret = NetPacketLayer4TypeTcp; - else if (ipv6hdr->NextHeader == IPPROTO_UDP) - ret = NetPacketLayer4TypeUdp; - } - - return ret; -} - - -NTSTATUS -ForTunAdapterCreateRXQueue(NETADAPTER NetAdapter, _Inout_ NETRXQUEUE_INIT* RxQueueInit) { - - TraceEvents(TRACE_LEVEL_INFORMATION, TRACE_ADAPTER, "%!FUNC! Entry"); - NTSTATUS status = STATUS_SUCCESS; - NET_PACKET_QUEUE_CONFIG config; - - NET_PACKET_QUEUE_CONFIG_INIT(&config, ForTunRxQueueAdvance, ForTunRxQueueSetNotificationEnabled, ForTunRxQueueCancel); - - WDF_OBJECT_ATTRIBUTES attr; - - WDF_OBJECT_ATTRIBUTES_INIT_CONTEXT_TYPE(&attr, RXQUEUE_CONTEXT); - NETPACKETQUEUE packetQueue; - - status = NetRxQueueCreate(RxQueueInit, &attr, &config, &packetQueue); - if (!NT_SUCCESS(status)) { - goto done; - } - PADAPTER_CONTEXT adapterContext = AdapterGetContext(NetAdapter); - adapterContext->RxQueue = packetQueue; - PRXQUEUE_CONTEXT context = RxQueueGetContext(packetQueue); - context->RingCollection = NetRxQueueGetRingCollection(packetQueue); - context->NotificationEnabled = 0; - context->AdapterContext = adapterContext; - - NET_EXTENSION_QUERY extension; - NET_EXTENSION_QUERY_INIT(&extension, - NET_FRAGMENT_EXTENSION_VIRTUAL_ADDRESS_NAME, - NET_FRAGMENT_EXTENSION_VIRTUAL_ADDRESS_VERSION_1, - NetExtensionTypeFragment); - NetRxQueueGetExtension(packetQueue, &extension, &context->VirtualAddressExtension); - NET_EXTENSION_QUERY_INIT(&extension, - NET_PACKET_EXTENSION_CHECKSUM_NAME, NET_PACKET_EXTENSION_CHECKSUM_VERSION_1, NetExtensionTypePacket); - NetRxQueueGetExtension(packetQueue, &extension, &context->ChecksumExtension); - -done: - return status; -} - -VOID -ForTunRxQueueAdvance(_In_ NETPACKETQUEUE PacketQueue) -{ - TraceEvents(TRACE_LEVEL_INFORMATION, TRACE_ADAPTER, "%!FUNC! Entry"); - PRXQUEUE_CONTEXT context = RxQueueGetContext(PacketQueue); - PDEVICE_CONTEXT deviceContext = context->AdapterContext->DeviceContext; - - NET_RING_COLLECTION const* ringCollection = context->RingCollection; - NET_RING_FRAGMENT_ITERATOR fi = NetRingGetAllFragments(ringCollection); - NET_RING_PACKET_ITERATOR pi = NetRingGetAllPackets(ringCollection); - NTSTATUS status; - while (NetFragmentIteratorHasAny(&fi)) { - WDFREQUEST request; - status = WdfIoQueueRetrieveNextRequest(deviceContext->PendingWriteQueue, &request); - if (!NT_SUCCESS(status)) { - break; - } - PVOID buffer; - size_t bufferSize; - status = WdfRequestRetrieveInputBuffer(request, sizeof(ULONG), &buffer, &bufferSize); - if (!NT_SUCCESS(status)) { - WdfRequestComplete(request, status); - break; - } - - NET_FRAGMENT* fragment = NetFragmentIteratorGetFragment(&fi); - fragment->ValidLength = bufferSize; - fragment->Offset = 0; - PVOID* virtualAddress = NetExtensionGetFragmentVirtualAddressOffset( - fragment, - &context->VirtualAddressExtension, - NetFragmentIteratorGetIndex(&fi) - ); - RtlCopyMemory(virtualAddress, buffer, bufferSize); - - NET_PACKET* packet = NetPacketIteratorGetPacket(&pi); - packet->FragmentCount = 1; - packet->FragmentIndex = NetFragmentIteratorGetIndex(&fi); - //packet->Layout = {0}; - NET_PACKET_LAYOUT layout = { 0 }; - packet->Layout = layout; - - NET_PACKET_CHECKSUM* checksum = NetExtensionGetPacketChecksum(&context->ChecksumExtension,NetPacketIteratorGetIndex(&pi)); - // Win11/2022 and newer - if (checksum) { - checksum->Layer3 = NetPacketRxChecksumEvaluationValid; - checksum->Layer4 = NetPacketRxChecksumEvaluationInvalid; - packet->Layout.Layer4Type = GetLayer4Type(virtualAddress, bufferSize); - } - NetFragmentIteratorAdvance(&fi); - NetPacketIteratorAdvance(&pi); - - WdfRequestCompleteWithInformation(request, STATUS_SUCCESS, bufferSize); - - } - NetFragmentIteratorSet(&fi); - NetPacketIteratorSet(&pi); - -} - -VOID -ForTunRxQueueSetNotificationEnabled( - _In_ NETPACKETQUEUE PacketQueue, - _In_ BOOLEAN NotificationEnabled) -{ - TraceEvents(TRACE_LEVEL_INFORMATION, TRACE_ADAPTER, "Notification Enabled:%d", NotificationEnabled); - PRXQUEUE_CONTEXT context = RxQueueGetContext(PacketQueue); - InterlockedExchangeNoFence(&context->NotificationEnabled, NotificationEnabled); -} - -VOID -ForTunRxQueueCancel(_In_ NETPACKETQUEUE PacketQueue) -{ - PRXQUEUE_CONTEXT context = RxQueueGetContext(PacketQueue); - NET_RING_COLLECTION const* ringCollection = context->RingCollection; - NET_RING* packetRing = ringCollection->Rings[NetRingTypePacket]; - NET_RING* fragmentRing = ringCollection->Rings[NetRingTypeFragment]; - UINT32 currentPacketIndex = packetRing->BeginIndex; - UINT32 packetEndIndex = packetRing->EndIndex; - - while (currentPacketIndex != packetEndIndex) { - NET_PACKET* packet = NetRingGetPacketAtIndex(packetRing, currentPacketIndex); - packet->Ignore = 1; - currentPacketIndex = NetRingIncrementIndex(packetRing, currentPacketIndex); - } - - packetRing->BeginIndex = packetRing->EndIndex; - - fragmentRing->BeginIndex = fragmentRing->EndIndex; -} \ No newline at end of file diff --git a/win-tun-driver/ForTun/RXQueue.h b/win-tun-driver/ForTun/RXQueue.h deleted file mode 100644 index 82b2534..0000000 --- a/win-tun-driver/ForTun/RXQueue.h +++ /dev/null @@ -1,26 +0,0 @@ -#pragma once -#include "precomp.h" -#include "Adapter.h" - -EXTERN_C_START - -EVT_NET_ADAPTER_CREATE_RXQUEUE ForTunAdapterCreateRXQueue; - -typedef struct _RXQUEUE_CONTEXT { - NET_RING_COLLECTION const* RingCollection; - _Interlocked_ LONG NotificationEnabled; - - PADAPTER_CONTEXT AdapterContext; - NET_EXTENSION VirtualAddressExtension; - NET_EXTENSION ChecksumExtension; - -} RXQUEUE_CONTEXT, *PRXQUEUE_CONTEXT; - - -WDF_DECLARE_CONTEXT_TYPE_WITH_NAME(RXQUEUE_CONTEXT, RxQueueGetContext) - -EXTERN_C_END - -EVT_PACKET_QUEUE_SET_NOTIFICATION_ENABLED ForTunRxQueueSetNotificationEnabled; -EVT_PACKET_QUEUE_ADVANCE ForTunRxQueueAdvance; -EVT_PACKET_QUEUE_CANCEL ForTunRxQueueCancel; diff --git a/win-tun-driver/ForTun/ReadMe.txt b/win-tun-driver/ForTun/ReadMe.txt deleted file mode 100644 index 2e8601a..0000000 --- a/win-tun-driver/ForTun/ReadMe.txt +++ /dev/null @@ -1,41 +0,0 @@ -======================================================================== - ForTun Project Overview -======================================================================== - -This file contains a summary of what you will find in each of the files that make up your project. - -ForTun.vcxproj - This is the main project file for projects generated using an Application Wizard. - It contains information about the version of the product that generated the file, and - information about the platforms, configurations, and project features selected with the - Application Wizard. - -ForTun.vcxproj.filters - This is the filters file for VC++ projects generated using an Application Wizard. - It contains information about the association between the files in your project - and the filters. This association is used in the IDE to show grouping of files with - similar extensions under a specific node (for e.g. ".cpp" files are associated with the - "Source Files" filter). - -Public.h - Header file to be shared with applications. - -Driver.c & Driver.h - DriverEntry and WDFDRIVER related functionality and callbacks. - -Device.c & Device.h - WDFDEVICE related functionality and callbacks. - -Queue.c & Queue.h - WDFQUEUE related functionality and callbacks. - -Trace.h - Definitions for WPP tracing. - -///////////////////////////////////////////////////////////////////////////// - -Learn more about Kernel Mode Driver Framework here: - -http://msdn.microsoft.com/en-us/library/ff544296(v=VS.85).aspx - -///////////////////////////////////////////////////////////////////////////// diff --git a/win-tun-driver/ForTun/Ringbuffer.c b/win-tun-driver/ForTun/Ringbuffer.c deleted file mode 100644 index 745f023..0000000 --- a/win-tun-driver/ForTun/Ringbuffer.c +++ /dev/null @@ -1,72 +0,0 @@ -#include "ringbuffer.h" - -NTSTATUS -PoolQueueCreate(PPOOL_QUEUE* PoolQueue) { - PPOOL_QUEUE poolQueue = (PPOOL_QUEUE)ExAllocatePool2(POOL_FLAG_NON_PAGED, sizeof(POOL_QUEUE),'pque'); - if (!poolQueue) { - return STATUS_MEMORY_NOT_ALLOCATED; - } - InitializeListHead(&poolQueue->PoolHead); - InitializeListHead(&poolQueue->QueueHead); - - *PoolQueue = poolQueue; - return STATUS_SUCCESS; -} - - -PPOOL_QUEUE_ITEM -PoolQueueGetFromPool(PPOOL_QUEUE PoolQueue) { - if (IsListEmpty(&PoolQueue->PoolHead)) { - return (PPOOL_QUEUE_ITEM)ExAllocatePool2(POOL_FLAG_NON_PAGED, sizeof(POOL_QUEUE_ITEM), 'pque'); - } - else { - return CONTAINING_RECORD(RemoveHeadList(&PoolQueue->PoolHead), POOL_QUEUE_ITEM, PoolEntry); - } -} - -VOID -PoolQueuePutToPool(PPOOL_QUEUE PoolQueue, PPOOL_QUEUE_ITEM Item) { - InsertTailList(&PoolQueue->PoolHead, &Item->PoolEntry); -} - -VOID -PoolQueuePutToQueue(PPOOL_QUEUE PoolQueue, PPOOL_QUEUE_ITEM Item) { - InsertTailList(&PoolQueue->QueueHead, &Item->QueueEntry); -} - - -PPOOL_QUEUE_ITEM -PoolQueueGetFromQueue(PPOOL_QUEUE PoolQueue) { - BOOLEAN isEmpty = IsListEmpty(&PoolQueue->QueueHead); - if (isEmpty) { - return NULL; - } - else { - PLIST_ENTRY entry = RemoveHeadList(&PoolQueue->QueueHead); - return CONTAINING_RECORD(entry, POOL_QUEUE_ITEM, QueueEntry); - } -} - - -VOID -PoolQueueFree(PPOOL_QUEUE PoolQueue) { - if (PoolQueue == NULL) { - return; - } - - - while (!IsListEmpty(&PoolQueue->PoolHead)) { - PLIST_ENTRY entry = RemoveHeadList(&PoolQueue->PoolHead); - PPOOL_QUEUE_ITEM item = CONTAINING_RECORD(entry, POOL_QUEUE_ITEM, PoolEntry); - ExFreePoolWithTag(item, 'pque'); - } - while (!IsListEmpty(&PoolQueue->QueueHead)) { - PLIST_ENTRY entry = RemoveHeadList(&PoolQueue->QueueHead); - PPOOL_QUEUE_ITEM item = CONTAINING_RECORD(entry, POOL_QUEUE_ITEM, QueueEntry); - ExFreePoolWithTag(item, 'pque'); - - } - - ExFreePoolWithTag(PoolQueue, 'pque'); -} - diff --git a/win-tun-driver/ForTun/Ringbuffer.h b/win-tun-driver/ForTun/Ringbuffer.h deleted file mode 100644 index 481e0da..0000000 --- a/win-tun-driver/ForTun/Ringbuffer.h +++ /dev/null @@ -1,38 +0,0 @@ -#pragma once -#include "precomp.h" - - -typedef struct _POOL_QUEUE{ - LIST_ENTRY PoolHead; - LIST_ENTRY QueueHead; -} POOL_QUEUE, *PPOOL_QUEUE; - - -typedef struct _POOL_QUEUE_ITEM { - LIST_ENTRY PoolEntry; - LIST_ENTRY QueueEntry; - size_t DataSize; - UCHAR Data[0xffff]; - -}POOL_QUEUE_ITEM, *PPOOL_QUEUE_ITEM; - -NTSTATUS -PoolQueueCreate(PPOOL_QUEUE* PoolQueue); - -PPOOL_QUEUE_ITEM -PoolQueueGetFromPool(PPOOL_QUEUE PoolQueue); - -VOID -PoolQueuePutToPool(PPOOL_QUEUE PoolQueue, PPOOL_QUEUE_ITEM Item); - -VOID -PoolQueuePutToQueue(PPOOL_QUEUE PoolQueue, PPOOL_QUEUE_ITEM Item); - - -PPOOL_QUEUE_ITEM -PoolQueueGetFromQueue(PPOOL_QUEUE PoolQueue); - - -VOID -PoolQueueFree(PPOOL_QUEUE PoolQueue); - diff --git a/win-tun-driver/ForTun/TXQueue.c b/win-tun-driver/ForTun/TXQueue.c deleted file mode 100644 index a53e45e..0000000 --- a/win-tun-driver/ForTun/TXQueue.c +++ /dev/null @@ -1,190 +0,0 @@ -#include "TXQueue.h" -#include "Device.h" -#include "netringiterator.h" -#include -#include "TXQueue.tmh" - - - -NTSTATUS -ForTunAdapterCreateTXQueue(_In_ NETADAPTER NetAdapter, _Inout_ NETTXQUEUE_INIT* TxQueueInit) { - NTSTATUS status = STATUS_SUCCESS; - - NET_PACKET_QUEUE_CONFIG config; - NETPACKETQUEUE queue; - TraceEvents(TRACE_LEVEL_INFORMATION, TRACE_ADAPTER, "%!FUNC! Entry"); - NET_PACKET_QUEUE_CONFIG_INIT(&config, ForTunTxQueueAdvance, ForTunTxQueueSetNotificationEnabled, ForTunTxQueueCancel); - - WDF_OBJECT_ATTRIBUTES attr; - WDF_OBJECT_ATTRIBUTES_INIT_CONTEXT_TYPE(&attr, TXQUEUE_CONTEXT); - - status = NetTxQueueCreate(TxQueueInit, &attr, &config, &queue); - if (!NT_SUCCESS(status)) { - goto done; - } - PTXQUEUE_CONTEXT context = TxQueueGetContext(queue); - context->RingCollection = NetTxQueueGetRingCollection(queue); - context->AdapterContext = AdapterGetContext(NetAdapter); - - NET_EXTENSION_QUERY extension; - NET_EXTENSION_QUERY_INIT(&extension, - NET_FRAGMENT_EXTENSION_VIRTUAL_ADDRESS_NAME, - NET_FRAGMENT_EXTENSION_VIRTUAL_ADDRESS_VERSION_1, - NetExtensionTypeFragment); - NetTxQueueGetExtension(queue, &extension, &context->VirtualAddressExtension); - -done: - return status; -} - -VOID -ForTunTxQueueSetNotificationEnabled(_In_ NETPACKETQUEUE PacketQueue, _In_ BOOLEAN NotificationEnabled) -{ - UNREFERENCED_PARAMETER(PacketQueue); - UNREFERENCED_PARAMETER(NotificationEnabled); -} - -VOID -ForTunTxQueueAdvance(_In_ NETPACKETQUEUE PacketQueue) -{ - TraceEvents(TRACE_LEVEL_INFORMATION, TRACE_ADAPTER, "%!FUNC! Entry"); - - PTXQUEUE_CONTEXT context = TxQueueGetContext(PacketQueue); - PDEVICE_CONTEXT deviceContext = context->AdapterContext->DeviceContext; - - NET_RING_COLLECTION const* ringCollection = context->RingCollection; - NET_RING_PACKET_ITERATOR pi = NetRingGetAllPackets(ringCollection); - - NTSTATUS status = STATUS_SUCCESS; - // in - while (NetPacketIteratorHasAny(&pi)) { - NET_PACKET* packet = NetPacketIteratorGetPacket(&pi); - if (!packet->Ignore && !packet->Scratch) { - // Process - NET_RING_FRAGMENT_ITERATOR fi = NetPacketIteratorGetFragments(&pi); - WDFREQUEST request; - WdfSpinLockAcquire(deviceContext->readLock); - status = WdfIoQueueRetrieveNextRequest(deviceContext->PendingReadQueue, &request); - UCHAR* buffer = NULL; - - PPOOL_QUEUE_ITEM poolQueueItem = NULL; - - if (NT_SUCCESS(status)) { - status = WdfRequestRetrieveOutputBuffer(request, sizeof(LONG), &buffer, NULL); - if (!NT_SUCCESS(status)) { - //This should never reach - TraceEvents(TRACE_LEVEL_ERROR, TRACE_ADAPTER, "wdf request retrieve buffer fail: %d", status); - WdfRequestComplete(request, status); - } - } - else { - poolQueueItem = PoolQueueGetFromPool(deviceContext->PoolQueue); - if (!poolQueueItem) { - TraceEvents(TRACE_LEVEL_ERROR, TRACE_ADAPTER, "PoolQueue is full"); - status = STATUS_INSUFFICIENT_RESOURCES; - } - else { - status = STATUS_SUCCESS; - } - } - - if (!NT_SUCCESS(status)) { - WdfSpinLockRelease(deviceContext->readLock); - NetFragmentIteratorSet(&fi); - } - else { - SIZE_T length = 0; - while (NetFragmentIteratorHasAny(&fi)) { - NET_FRAGMENT* fragment = NetFragmentIteratorGetFragment(&fi); - BYTE* netBuf = (BYTE *)NetExtensionGetFragmentVirtualAddressOffset(fragment, &context->VirtualAddressExtension, NetFragmentIteratorGetIndex(&fi)); - if (buffer) { - RtlCopyMemory(buffer + length, netBuf, fragment->ValidLength); - } - else if(poolQueueItem) { - RtlCopyMemory(poolQueueItem->Data + length, netBuf, fragment->ValidLength); - } - UINT64 ValidLength = fragment->ValidLength; - length = length + (SIZE_T)ValidLength; - NetFragmentIteratorAdvance(&fi); - } - if (buffer) { - WdfRequestCompleteWithInformation(request, status, length); - } - else if(poolQueueItem){ - poolQueueItem->DataSize = length; - PoolQueuePutToQueue(deviceContext->PoolQueue, poolQueueItem); - } - WdfSpinLockRelease(deviceContext->readLock); - } - - /* - while (NetFragmentIteratorHasAny(&fi)) { - NET_FRAGMENT* fragment = NetFragmentIteratorGetFragment(&fi); - NET_FRAGMENT_VIRTUAL_ADDRESS* virtualAddr = NetExtensionGetFragmentVirtualAddress( - &context->VirtualAddressExtension, NetFragmentIteratorGetIndex(&fi)); - if (fragment->ValidLength > 0) { - WDFREQUEST request; - WdfSpinLockAcquire(deviceContext->readLock); - status = WdfIoQueueRetrieveNextRequest(deviceContext->PendingReadQueue, &request); - if (NT_SUCCESS(status)) { - WdfSpinLockRelease(deviceContext->readLock); - PVOID buffer; - status = WdfRequestRetrieveOutputBuffer(request, sizeof(LONG), &buffer, NULL); - if (!NT_SUCCESS(status)) { - WdfRequestComplete(request, status); - } - else { - RtlCopyMemory(buffer, virtualAddr, fragment->ValidLength); - WdfRequestCompleteWithInformation(request, status, fragment->ValidLength); - } - } - else { - PPOOL_QUEUE_ITEM poolQueueItem = PoolQueueGetFromPool(deviceContext->PoolQueue); - if (!poolQueueItem) { - TraceEvents(TRACE_LEVEL_ERROR, TRACE_ADAPTER, "PoolQueue is full"); - } - else { - RtlCopyMemory(&poolQueueItem->Data, virtualAddr, fragment->ValidLength); - poolQueueItem->DataSize = fragment->ValidLength; - PoolQueuePutToQueue(deviceContext->PoolQueue, poolQueueItem); - } - - WdfSpinLockRelease(deviceContext->readLock); - } - } - NetFragmentIteratorAdvance(&fi); - - } */ - NET_PACKET* p = NetPacketIteratorGetPacket(&pi); - NET_RING* const fragmentRing = NetRingCollectionGetFragmentRing(fi.Iterator.Rings); - UINT32 const lastFragmentIndex = NetRingAdvanceIndex(fragmentRing, p->FragmentIndex, p->FragmentCount); - fragmentRing->BeginIndex = lastFragmentIndex; - - //Process - } - NetPacketIteratorAdvance(&pi); - if (!NT_SUCCESS(status)) { - break; - } - } - NetPacketIteratorSet(&pi); -} - -VOID -ForTunTxQueueCancel(_In_ NETPACKETQUEUE PacketQueue) -{ - PTXQUEUE_CONTEXT queue = TxQueueGetContext(PacketQueue); - NET_RING_COLLECTION const* ringCollection = queue->RingCollection; - NET_RING* packetRing = ringCollection->Rings[NetRingTypePacket]; - UINT32 currentPacketIndex = packetRing->BeginIndex; - UINT32 packetEndIndex = packetRing->EndIndex; - while (currentPacketIndex != packetEndIndex) { - NET_PACKET* packet = NetRingGetPacketAtIndex(packetRing, currentPacketIndex); - packet->Scratch = 1; - currentPacketIndex = NetRingIncrementIndex(packetRing, currentPacketIndex); - } - packetRing->BeginIndex = packetRing->EndIndex; - - NET_RING* fragmentRing = NetRingCollectionGetFragmentRing(ringCollection); - fragmentRing->BeginIndex = fragmentRing->EndIndex; -} \ No newline at end of file diff --git a/win-tun-driver/ForTun/TXQueue.h b/win-tun-driver/ForTun/TXQueue.h deleted file mode 100644 index 24ec0ef..0000000 --- a/win-tun-driver/ForTun/TXQueue.h +++ /dev/null @@ -1,24 +0,0 @@ -#pragma once -#include "precomp.h" -#include "Adapter.h" - -EXTERN_C_START - - -EVT_NET_ADAPTER_CREATE_TXQUEUE ForTunAdapterCreateTXQueue; - - -EXTERN_C_END - -typedef struct _TXQUEUE_CONTEXT { - NET_RING_COLLECTION const* RingCollection; - PADAPTER_CONTEXT AdapterContext; - NET_EXTENSION VirtualAddressExtension; -} TXQUEUE_CONTEXT, *PTXQUEUE_CONTEXT; - - -WDF_DECLARE_CONTEXT_TYPE_WITH_NAME(TXQUEUE_CONTEXT, TxQueueGetContext) - -EVT_PACKET_QUEUE_SET_NOTIFICATION_ENABLED ForTunTxQueueSetNotificationEnabled; -EVT_PACKET_QUEUE_ADVANCE ForTunTxQueueAdvance; -EVT_PACKET_QUEUE_CANCEL ForTunTxQueueCancel; \ No newline at end of file diff --git a/win-tun-driver/ForTun/Trace.h b/win-tun-driver/ForTun/Trace.h deleted file mode 100644 index fba3110..0000000 --- a/win-tun-driver/ForTun/Trace.h +++ /dev/null @@ -1,63 +0,0 @@ -/*++ - -Module Name: - - Trace.h - -Abstract: - - Header file for the debug tracing related function defintions and macros. - -Environment: - - Kernel mode - ---*/ - -// -// Define the tracing flags. -// -// Tracing GUID - d3f27918-5d11-433b-8a85-2808e922783f -// - -#define WPP_CONTROL_GUIDS \ - WPP_DEFINE_CONTROL_GUID( \ - ForTunTraceGuid, (d3f27918,5d11,433b,8a85,2808e922783f), \ - \ - WPP_DEFINE_BIT(MYDRIVER_ALL_INFO) \ - WPP_DEFINE_BIT(TRACE_DRIVER) \ - WPP_DEFINE_BIT(TRACE_DEVICE) \ - WPP_DEFINE_BIT(TRACE_QUEUE) \ - WPP_DEFINE_BIT(TRACE_ADAPTER) \ - ) - -#define WPP_FLAG_LEVEL_LOGGER(flag, level) \ - WPP_LEVEL_LOGGER(flag) - -#define WPP_FLAG_LEVEL_ENABLED(flag, level) \ - (WPP_LEVEL_ENABLED(flag) && \ - WPP_CONTROL(WPP_BIT_ ## flag).Level >= level) - -#define WPP_LEVEL_FLAGS_LOGGER(lvl,flags) \ - WPP_LEVEL_LOGGER(flags) - -#define WPP_LEVEL_FLAGS_ENABLED(lvl, flags) \ - (WPP_LEVEL_ENABLED(flags) && WPP_CONTROL(WPP_BIT_ ## flags).Level >= lvl) - -// -// WPP orders static parameters before dynamic parameters. To support the Trace function -// defined below which sets FLAGS=MYDRIVER_ALL_INFO, a custom macro must be defined to -// reorder the arguments to what the .tpl configuration file expects. -// -#define WPP_RECORDER_FLAGS_LEVEL_ARGS(flags, lvl) WPP_RECORDER_LEVEL_FLAGS_ARGS(lvl, flags) -#define WPP_RECORDER_FLAGS_LEVEL_FILTER(flags, lvl) WPP_RECORDER_LEVEL_FLAGS_FILTER(lvl, flags) - -// -// This comment block is scanned by the trace preprocessor to define our -// Trace function. -// -// begin_wpp config -// FUNC Trace{FLAGS=MYDRIVER_ALL_INFO}(LEVEL, MSG, ...); -// FUNC TraceEvents(LEVEL, FLAGS, MSG, ...); -// end_wpp -// diff --git a/win-tun-driver/ForTun/netringiterator.h b/win-tun-driver/ForTun/netringiterator.h deleted file mode 100644 index afb4b98..0000000 --- a/win-tun-driver/ForTun/netringiterator.h +++ /dev/null @@ -1,282 +0,0 @@ -// Copyright (C) Microsoft Corporation. All rights reserved. -//FROM https://github.com/microsoft/NetAdapter-Cx-Driver-Samples/blob/release_2004/RtEthSample/netringiterator.h -#pragma once - -//#include "netadaptercx.h" -#include - -typedef struct _NET_RING_ITERATOR -{ - - NET_RING_COLLECTION const* - Rings; - - UINT32* const - IndexToSet; - - UINT32 - Index; - - UINT32 const - End; - -} NET_RING_ITERATOR; - -typedef struct _NET_RING_PACKET_ITERATOR -{ - - NET_RING_ITERATOR - Iterator; - -} NET_RING_PACKET_ITERATOR; - -typedef struct _NET_RING_FRAGMENT_ITERATOR -{ - - NET_RING_ITERATOR - Iterator; - -} NET_RING_FRAGMENT_ITERATOR; - - -inline -NET_RING_PACKET_ITERATOR -NetRingGetPostPackets( - _In_ NET_RING_COLLECTION const* Rings -) -{ - NET_RING* ring = Rings->Rings[NetRingTypePacket]; - NET_RING_PACKET_ITERATOR iterator = { - Rings, &ring->NextIndex, ring->NextIndex, ring->EndIndex, - }; - - return iterator; -} - -inline -NET_RING_PACKET_ITERATOR -NetRingGetDrainPackets( - _In_ NET_RING_COLLECTION const* Rings -) -{ - NET_RING* ring = Rings->Rings[NetRingTypePacket]; - NET_RING_PACKET_ITERATOR iterator = { - Rings, &ring->BeginIndex, ring->BeginIndex, ring->NextIndex, - }; - - return iterator; -} - -inline -NET_RING_PACKET_ITERATOR -NetRingGetAllPackets( - _In_ NET_RING_COLLECTION const* Rings -) -{ - NET_RING* ring = Rings->Rings[NetRingTypePacket]; - NET_RING_PACKET_ITERATOR iterator = { - Rings, &ring->BeginIndex, ring->BeginIndex, ring->EndIndex, - }; - - return iterator; -} - -inline -NET_PACKET* -NetPacketIteratorGetPacket( - _In_ NET_RING_PACKET_ITERATOR const* Iterator -) -{ - return NetRingGetPacketAtIndex( - Iterator->Iterator.Rings->Rings[NetRingTypePacket], - Iterator->Iterator.Index); -} - -inline -UINT32 -NetPacketIteratorGetIndex( - _In_ NET_RING_PACKET_ITERATOR const* Iterator -) -{ - return Iterator->Iterator.Index; -} - -inline -BOOLEAN -NetPacketIteratorHasAny( - _In_ NET_RING_PACKET_ITERATOR const* Iterator -) -{ - return Iterator->Iterator.Index != Iterator->Iterator.End; -} - -inline -UINT32 -NetPacketIteratorGetCount( - _In_ NET_RING_PACKET_ITERATOR const* Iterator -) -{ - NET_RING const* ring = Iterator->Iterator.Rings->Rings[NetRingTypePacket]; - - return (Iterator->Iterator.End - Iterator->Iterator.Index) & ring->ElementIndexMask; -} - -inline -void -NetPacketIteratorAdvance( - _In_ NET_RING_PACKET_ITERATOR* Iterator -) -{ - Iterator->Iterator.Index = NetRingIncrementIndex( - Iterator->Iterator.Rings->Rings[NetRingTypePacket], - Iterator->Iterator.Index); -} - -inline -void -NetPacketIteratorAdvanceToTheEnd( - _In_ NET_RING_PACKET_ITERATOR* Iterator -) -{ - Iterator->Iterator.Index = Iterator->Iterator.End; -} - -inline -void -NetPacketIteratorSet( - _In_ NET_RING_PACKET_ITERATOR const* Iterator -) -{ - *Iterator->Iterator.IndexToSet - = Iterator->Iterator.Index; -} - - -inline -NET_RING_FRAGMENT_ITERATOR -NetPacketIteratorGetFragments( - _In_ NET_RING_PACKET_ITERATOR const* Iterator -) -{ - NET_RING const* ring = Iterator->Iterator.Rings->Rings[NetRingTypeFragment]; - NET_PACKET const* packet = NetPacketIteratorGetPacket(Iterator); - UINT32 const end = NetRingIncrementIndex(ring, - packet->FragmentIndex + packet->FragmentCount - 1); - NET_RING_FRAGMENT_ITERATOR iterator = { - Iterator->Iterator.Rings, NULL, packet->FragmentIndex, end, - }; - - return iterator; -} - -inline -NET_RING_FRAGMENT_ITERATOR -NetRingGetPostFragments( - _In_ NET_RING_COLLECTION const* Rings -) -{ - NET_RING* ring = Rings->Rings[NetRingTypeFragment]; - NET_RING_FRAGMENT_ITERATOR iterator = { - Rings, &ring->NextIndex, ring->NextIndex, ring->EndIndex, - }; - - return iterator; -} - -inline -NET_RING_FRAGMENT_ITERATOR -NetRingGetDrainFragments( - _In_ NET_RING_COLLECTION const* Rings -) -{ - NET_RING* ring = Rings->Rings[NetRingTypeFragment]; - NET_RING_FRAGMENT_ITERATOR iterator = { - Rings, &ring->BeginIndex, ring->BeginIndex, ring->NextIndex, - }; - - return iterator; -} - -inline -NET_RING_FRAGMENT_ITERATOR -NetRingGetAllFragments( - _In_ NET_RING_COLLECTION const* Rings -) -{ - NET_RING* ring = Rings->Rings[NetRingTypeFragment]; - NET_RING_FRAGMENT_ITERATOR iterator = { - Rings, &ring->BeginIndex, ring->BeginIndex, ring->EndIndex, - }; - - return iterator; -} - -inline -NET_FRAGMENT* -NetFragmentIteratorGetFragment( - _In_ NET_RING_FRAGMENT_ITERATOR const* Iterator -) -{ - return NetRingGetFragmentAtIndex( - Iterator->Iterator.Rings->Rings[NetRingTypeFragment], - Iterator->Iterator.Index); -} - -inline -UINT32 -NetFragmentIteratorGetIndex( - _In_ NET_RING_FRAGMENT_ITERATOR const* Iterator -) -{ - return Iterator->Iterator.Index; -} - -inline -BOOLEAN -NetFragmentIteratorHasAny( - _In_ NET_RING_FRAGMENT_ITERATOR const* Iterator -) -{ - return Iterator->Iterator.Index != Iterator->Iterator.End; -} - -inline -UINT32 -NetFragmentIteratorGetCount( - _In_ NET_RING_FRAGMENT_ITERATOR const* Iterator -) -{ - NET_RING const* ring = Iterator->Iterator.Rings->Rings[NetRingTypeFragment]; - - return (Iterator->Iterator.End - Iterator->Iterator.Index) & ring->ElementIndexMask; -} - -inline -void -NetFragmentIteratorAdvance( - _In_ NET_RING_FRAGMENT_ITERATOR* Iterator -) -{ - Iterator->Iterator.Index = NetRingIncrementIndex( - Iterator->Iterator.Rings->Rings[NetRingTypeFragment], - Iterator->Iterator.Index); -} - -inline -void -NetFragmentIteratorAdvanceToTheEnd( - _In_ NET_RING_FRAGMENT_ITERATOR* Iterator -) -{ - Iterator->Iterator.Index = Iterator->Iterator.End; -} - -inline -void -NetFragmentIteratorSet( - _In_ NET_RING_FRAGMENT_ITERATOR const* Iterator -) -{ - *(Iterator->Iterator.IndexToSet) - = Iterator->Iterator.Index; -} diff --git a/win-tun-driver/ForTun/precomp.h b/win-tun-driver/ForTun/precomp.h deleted file mode 100644 index 3e46134..0000000 --- a/win-tun-driver/ForTun/precomp.h +++ /dev/null @@ -1,6 +0,0 @@ -#pragma once - -#include -#include -#include -#include "Trace.h" \ No newline at end of file diff --git a/win-tun-driver/ForTunCli/.gitignore b/win-tun-driver/ForTunCli/.gitignore deleted file mode 100644 index 9b567b4..0000000 --- a/win-tun-driver/ForTunCli/.gitignore +++ /dev/null @@ -1,5 +0,0 @@ -/target -.idea -/win11 -/examples -driver \ No newline at end of file diff --git a/win-tun-driver/ForTunCli/Cargo.lock b/win-tun-driver/ForTunCli/Cargo.lock deleted file mode 100644 index 2143177..0000000 --- a/win-tun-driver/ForTunCli/Cargo.lock +++ /dev/null @@ -1,749 +0,0 @@ -# This file is automatically @generated by Cargo. -# It is not intended for manual editing. -version = 3 - -[[package]] -name = "aho-corasick" -version = "0.7.20" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "cc936419f96fa211c1b9166887b38e5e40b19958e5b895be7c1f93adec7071ac" -dependencies = [ - "memchr", -] - -[[package]] -name = "anyhow" -version = "1.0.69" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "224afbd727c3d6e4b90103ece64b8d1b67fbb1973b1046c2281eed3f3803f800" - -[[package]] -name = "autocfg" -version = "1.1.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "d468802bab17cbc0cc575e9b053f41e72aa36bfa6b7f55e3529ffa43161b97fa" - -[[package]] -name = "bitflags" -version = "1.3.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "bef38d45163c2f1dde094a7dfd33ccf595c92905c8f8f4fdc18d06fb1037718a" - -[[package]] -name = "byteorder" -version = "1.4.3" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "14c189c53d098945499cdfa7ecc63567cf3886b3332b312a5b4585d8d3a6a610" - -[[package]] -name = "bytes" -version = "1.4.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "89b2fd2a0dcf38d7971e2194b6b6eebab45ae01067456a7fd93d5547a61b70be" - -[[package]] -name = "cfg-if" -version = "1.0.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "baf1de4339761588bc0619e3cbc0120ee582ebb74b53b4efbf79117bd2da40fd" - -[[package]] -name = "cidr-utils" -version = "0.5.10" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "fdfa36f04861d39453affe1cf084ce2d6554021a84eb6f31ebdeafb6fb92a01c" -dependencies = [ - "debug-helper", - "num-bigint", - "num-traits", - "once_cell", - "regex", -] - -[[package]] -name = "debug-helper" -version = "0.3.13" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "f578e8e2c440e7297e008bb5486a3a8a194775224bbc23729b0dbdfaeebf162e" - -[[package]] -name = "fortun-cli" -version = "0.1.0" -dependencies = [ - "anyhow", - "cidr-utils", - "local-encoding", - "packet", - "scopeguard", - "tokio", - "tracing", - "tracing-subscriber", - "windows", -] - -[[package]] -name = "fuchsia-cprng" -version = "0.1.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "a06f77d526c1a601b7c4cdd98f54b5eaabffc14d5f2f0296febdc7f357c6d3ba" - -[[package]] -name = "getopts" -version = "0.2.21" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "14dbbfd5c71d70241ecf9e6f13737f7b5ce823821063188d7e46c41d371eebd5" -dependencies = [ - "unicode-width", -] - -[[package]] -name = "hermit-abi" -version = "0.2.6" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ee512640fe35acbfb4bb779db6f0d80704c2cacfa2e39b601ef3e3f47d1ae4c7" -dependencies = [ - "libc", -] - -[[package]] -name = "hwaddr" -version = "0.1.7" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "e414433a9e4338f4e87fa29d0670c883a5e73e7955c45f4a49130c0aa992c85b" -dependencies = [ - "phf", -] - -[[package]] -name = "kernel32-sys" -version = "0.2.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "7507624b29483431c0ba2d82aece8ca6cdba9382bff4ddd0f7490560c056098d" -dependencies = [ - "winapi 0.2.8", - "winapi-build", -] - -[[package]] -name = "lazy_static" -version = "1.4.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "e2abad23fbc42b3700f2f279844dc832adb2b2eb069b2df918f455c4e18cc646" - -[[package]] -name = "libc" -version = "0.2.139" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "201de327520df007757c1f0adce6e827fe8562fbc28bfd9c15571c66ca1f5f79" - -[[package]] -name = "local-encoding" -version = "0.2.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "e1ceb20f39ff7ae42f3ff9795f3986b1daad821caaa1e1732a0944103a5a1a66" -dependencies = [ - "kernel32-sys", - "skeptic", - "winapi 0.2.8", -] - -[[package]] -name = "lock_api" -version = "0.4.9" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "435011366fe56583b16cf956f9df0095b405b82d76425bc8981c0e22e60ec4df" -dependencies = [ - "autocfg", - "scopeguard", -] - -[[package]] -name = "log" -version = "0.4.17" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "abb12e687cfb44aa40f41fc3978ef76448f9b6038cad6aef4259d3c095a2382e" -dependencies = [ - "cfg-if", -] - -[[package]] -name = "memchr" -version = "2.5.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "2dffe52ecf27772e601905b7522cb4ef790d2cc203488bbd0e2fe85fcb74566d" - -[[package]] -name = "mio" -version = "0.8.5" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "e5d732bc30207a6423068df043e3d02e0735b155ad7ce1a6f76fe2baa5b158de" -dependencies = [ - "libc", - "log", - "wasi", - "windows-sys 0.42.0", -] - -[[package]] -name = "nu-ansi-term" -version = "0.46.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "77a8165726e8236064dbb45459242600304b42a5ea24ee2948e18e023bf7ba84" -dependencies = [ - "overload", - "winapi 0.3.9", -] - -[[package]] -name = "num-bigint" -version = "0.4.3" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "f93ab6289c7b344a8a9f60f88d80aa20032336fe78da341afc91c8a2341fc75f" -dependencies = [ - "autocfg", - "num-integer", - "num-traits", -] - -[[package]] -name = "num-integer" -version = "0.1.45" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "225d3389fb3509a24c93f5c29eb6bde2586b98d9f016636dff58d7c6f7569cd9" -dependencies = [ - "autocfg", - "num-traits", -] - -[[package]] -name = "num-traits" -version = "0.2.15" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "578ede34cf02f8924ab9447f50c28075b4d3e5b269972345e7e0372b38c6cdcd" -dependencies = [ - "autocfg", -] - -[[package]] -name = "num_cpus" -version = "1.15.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "0fac9e2da13b5eb447a6ce3d392f23a29d8694bff781bf03a16cd9ac8697593b" -dependencies = [ - "hermit-abi", - "libc", -] - -[[package]] -name = "once_cell" -version = "1.17.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "b7e5500299e16ebb147ae15a00a942af264cf3688f47923b8fc2cd5858f23ad3" - -[[package]] -name = "overload" -version = "0.1.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "b15813163c1d831bf4a13c3610c05c0d03b39feb07f7e09fa234dac9b15aaf39" - -[[package]] -name = "packet" -version = "0.1.4" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "c136c7ad0619ed4f88894aecf66ad86c80683e7b5d707996e6a3a7e0e3916944" -dependencies = [ - "bitflags", - "byteorder", - "hwaddr", - "thiserror", -] - -[[package]] -name = "parking_lot" -version = "0.12.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "3742b2c103b9f06bc9fff0a37ff4912935851bee6d36f3c02bcc755bcfec228f" -dependencies = [ - "lock_api", - "parking_lot_core", -] - -[[package]] -name = "parking_lot_core" -version = "0.9.7" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "9069cbb9f99e3a5083476ccb29ceb1de18b9118cafa53e90c9551235de2b9521" -dependencies = [ - "cfg-if", - "libc", - "redox_syscall", - "smallvec", - "windows-sys 0.45.0", -] - -[[package]] -name = "phf" -version = "0.8.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "3dfb61232e34fcb633f43d12c58f83c1df82962dcdfa565a4e866ffc17dafe12" -dependencies = [ - "phf_shared", -] - -[[package]] -name = "phf_shared" -version = "0.8.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "c00cf8b9eafe68dde5e9eaa2cef8ee84a9336a47d566ec55ca16589633b65af7" -dependencies = [ - "siphasher", -] - -[[package]] -name = "pin-project-lite" -version = "0.2.9" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "e0a7ae3ac2f1173085d398531c705756c94a4c56843785df85a60c1a0afac116" - -[[package]] -name = "proc-macro2" -version = "1.0.51" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "5d727cae5b39d21da60fa540906919ad737832fe0b1c165da3a34d6548c849d6" -dependencies = [ - "unicode-ident", -] - -[[package]] -name = "pulldown-cmark" -version = "0.0.3" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "8361e81576d2e02643b04950e487ec172b687180da65c731c03cf336784e6c07" -dependencies = [ - "getopts", -] - -[[package]] -name = "quote" -version = "1.0.23" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "8856d8364d252a14d474036ea1358d63c9e6965c8e5c1885c18f73d70bff9c7b" -dependencies = [ - "proc-macro2", -] - -[[package]] -name = "rand" -version = "0.4.6" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "552840b97013b1a26992c11eac34bdd778e464601a4c2054b5f0bff7c6761293" -dependencies = [ - "fuchsia-cprng", - "libc", - "rand_core 0.3.1", - "rdrand", - "winapi 0.3.9", -] - -[[package]] -name = "rand_core" -version = "0.3.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "7a6fdeb83b075e8266dcc8762c22776f6877a63111121f5f8c7411e5be7eed4b" -dependencies = [ - "rand_core 0.4.2", -] - -[[package]] -name = "rand_core" -version = "0.4.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "9c33a3c44ca05fa6f1807d8e6743f3824e8509beca625669633be0acbdf509dc" - -[[package]] -name = "rdrand" -version = "0.4.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "678054eb77286b51581ba43620cc911abf02758c91f93f479767aed0f90458b2" -dependencies = [ - "rand_core 0.3.1", -] - -[[package]] -name = "redox_syscall" -version = "0.2.16" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "fb5a58c1855b4b6819d59012155603f0b22ad30cad752600aadfcb695265519a" -dependencies = [ - "bitflags", -] - -[[package]] -name = "regex" -version = "1.7.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "48aaa5748ba571fb95cd2c85c09f629215d3a6ece942baa100950af03a34f733" -dependencies = [ - "aho-corasick", - "memchr", - "regex-syntax", -] - -[[package]] -name = "regex-syntax" -version = "0.6.28" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "456c603be3e8d448b072f410900c09faf164fbce2d480456f50eea6e25f9c848" - -[[package]] -name = "remove_dir_all" -version = "0.5.3" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "3acd125665422973a33ac9d3dd2df85edad0f4ae9b00dafb1a05e43a9f5ef8e7" -dependencies = [ - "winapi 0.3.9", -] - -[[package]] -name = "scopeguard" -version = "1.1.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "d29ab0c6d3fc0ee92fe66e2d99f700eab17a8d57d1c1d3b748380fb20baa78cd" - -[[package]] -name = "sharded-slab" -version = "0.1.4" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "900fba806f70c630b0a382d0d825e17a0f19fcd059a2ade1ff237bcddf446b31" -dependencies = [ - "lazy_static", -] - -[[package]] -name = "signal-hook-registry" -version = "1.4.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "d8229b473baa5980ac72ef434c4415e70c4b5e71b423043adb4ba059f89c99a1" -dependencies = [ - "libc", -] - -[[package]] -name = "siphasher" -version = "0.3.10" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "7bd3e3206899af3f8b12af284fafc038cc1dc2b41d1b89dd17297221c5d225de" - -[[package]] -name = "skeptic" -version = "0.4.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "24ebf8a06f5f8bae61ae5bbc7af7aac4ef6907ae975130faba1199e5fe82256a" -dependencies = [ - "pulldown-cmark", - "tempdir", -] - -[[package]] -name = "smallvec" -version = "1.10.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "a507befe795404456341dfab10cef66ead4c041f62b8b11bbb92bffe5d0953e0" - -[[package]] -name = "socket2" -version = "0.4.7" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "02e2d2db9033d13a1567121ddd7a095ee144db4e1ca1b1bda3419bc0da294ebd" -dependencies = [ - "libc", - "winapi 0.3.9", -] - -[[package]] -name = "syn" -version = "1.0.107" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "1f4064b5b16e03ae50984a5a8ed5d4f8803e6bc1fd170a3cda91a1be4b18e3f5" -dependencies = [ - "proc-macro2", - "quote", - "unicode-ident", -] - -[[package]] -name = "tempdir" -version = "0.3.7" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "15f2b5fb00ccdf689e0149d1b1b3c03fead81c2b37735d812fa8bddbbf41b6d8" -dependencies = [ - "rand", - "remove_dir_all", -] - -[[package]] -name = "thiserror" -version = "1.0.38" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "6a9cd18aa97d5c45c6603caea1da6628790b37f7a34b6ca89522331c5180fed0" -dependencies = [ - "thiserror-impl", -] - -[[package]] -name = "thiserror-impl" -version = "1.0.38" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "1fb327af4685e4d03fa8cbcf1716380da910eeb2bb8be417e7f9fd3fb164f36f" -dependencies = [ - "proc-macro2", - "quote", - "syn", -] - -[[package]] -name = "thread_local" -version = "1.1.7" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "3fdd6f064ccff2d6567adcb3873ca630700f00b5ad3f060c25b5dcfd9a4ce152" -dependencies = [ - "cfg-if", - "once_cell", -] - -[[package]] -name = "tokio" -version = "1.25.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "c8e00990ebabbe4c14c08aca901caed183ecd5c09562a12c824bb53d3c3fd3af" -dependencies = [ - "autocfg", - "bytes", - "libc", - "memchr", - "mio", - "num_cpus", - "parking_lot", - "pin-project-lite", - "signal-hook-registry", - "socket2", - "tokio-macros", - "windows-sys 0.42.0", -] - -[[package]] -name = "tokio-macros" -version = "1.8.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "d266c00fde287f55d3f1c3e96c500c362a2b8c695076ec180f27918820bc6df8" -dependencies = [ - "proc-macro2", - "quote", - "syn", -] - -[[package]] -name = "tracing" -version = "0.1.37" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "8ce8c33a8d48bd45d624a6e523445fd21ec13d3653cd51f681abf67418f54eb8" -dependencies = [ - "cfg-if", - "pin-project-lite", - "tracing-attributes", - "tracing-core", -] - -[[package]] -name = "tracing-attributes" -version = "0.1.23" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "4017f8f45139870ca7e672686113917c71c7a6e02d4924eda67186083c03081a" -dependencies = [ - "proc-macro2", - "quote", - "syn", -] - -[[package]] -name = "tracing-core" -version = "0.1.30" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "24eb03ba0eab1fd845050058ce5e616558e8f8d8fca633e6b163fe25c797213a" -dependencies = [ - "once_cell", - "valuable", -] - -[[package]] -name = "tracing-log" -version = "0.1.3" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "78ddad33d2d10b1ed7eb9d1f518a5674713876e97e5bb9b7345a7984fbb4f922" -dependencies = [ - "lazy_static", - "log", - "tracing-core", -] - -[[package]] -name = "tracing-subscriber" -version = "0.3.16" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "a6176eae26dd70d0c919749377897b54a9276bd7061339665dd68777926b5a70" -dependencies = [ - "nu-ansi-term", - "sharded-slab", - "smallvec", - "thread_local", - "tracing-core", - "tracing-log", -] - -[[package]] -name = "unicode-ident" -version = "1.0.6" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "84a22b9f218b40614adcb3f4ff08b703773ad44fa9423e4e0d346d5db86e4ebc" - -[[package]] -name = "unicode-width" -version = "0.1.10" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "c0edd1e5b14653f783770bce4a4dabb4a5108a5370a5f5d8cfe8710c361f6c8b" - -[[package]] -name = "valuable" -version = "0.1.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "830b7e5d4d90034032940e4ace0d9a9a057e7a45cd94e6c007832e39edb82f6d" - -[[package]] -name = "wasi" -version = "0.11.0+wasi-snapshot-preview1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "9c8d87e72b64a3b4db28d11ce29237c246188f4f51057d65a7eab63b7987e423" - -[[package]] -name = "winapi" -version = "0.2.8" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "167dc9d6949a9b857f3451275e911c3f44255842c1f7a76f33c55103a909087a" - -[[package]] -name = "winapi" -version = "0.3.9" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "5c839a674fcd7a98952e593242ea400abe93992746761e38641405d28b00f419" -dependencies = [ - "winapi-i686-pc-windows-gnu", - "winapi-x86_64-pc-windows-gnu", -] - -[[package]] -name = "winapi-build" -version = "0.1.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "2d315eee3b34aca4797b2da6b13ed88266e6d612562a0c46390af8299fc699bc" - -[[package]] -name = "winapi-i686-pc-windows-gnu" -version = "0.4.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ac3b87c63620426dd9b991e5ce0329eff545bccbbb34f3be09ff6fb6ab51b7b6" - -[[package]] -name = "winapi-x86_64-pc-windows-gnu" -version = "0.4.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "712e227841d057c1ee1cd2fb22fa7e5a5461ae8e48fa2ca79ec42cfc1931183f" - -[[package]] -name = "windows" -version = "0.44.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "9e745dab35a0c4c77aa3ce42d595e13d2003d6902d6b08c9ef5fc326d08da12b" -dependencies = [ - "windows-targets", -] - -[[package]] -name = "windows-sys" -version = "0.42.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "5a3e1820f08b8513f676f7ab6c1f99ff312fb97b553d30ff4dd86f9f15728aa7" -dependencies = [ - "windows_aarch64_gnullvm", - "windows_aarch64_msvc", - "windows_i686_gnu", - "windows_i686_msvc", - "windows_x86_64_gnu", - "windows_x86_64_gnullvm", - "windows_x86_64_msvc", -] - -[[package]] -name = "windows-sys" -version = "0.45.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "75283be5efb2831d37ea142365f009c02ec203cd29a3ebecbc093d52315b66d0" -dependencies = [ - "windows-targets", -] - -[[package]] -name = "windows-targets" -version = "0.42.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "8e2522491fbfcd58cc84d47aeb2958948c4b8982e9a2d8a2a35bbaed431390e7" -dependencies = [ - "windows_aarch64_gnullvm", - "windows_aarch64_msvc", - "windows_i686_gnu", - "windows_i686_msvc", - "windows_x86_64_gnu", - "windows_x86_64_gnullvm", - "windows_x86_64_msvc", -] - -[[package]] -name = "windows_aarch64_gnullvm" -version = "0.42.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "8c9864e83243fdec7fc9c5444389dcbbfd258f745e7853198f365e3c4968a608" - -[[package]] -name = "windows_aarch64_msvc" -version = "0.42.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "4c8b1b673ffc16c47a9ff48570a9d85e25d265735c503681332589af6253c6c7" - -[[package]] -name = "windows_i686_gnu" -version = "0.42.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "de3887528ad530ba7bdbb1faa8275ec7a1155a45ffa57c37993960277145d640" - -[[package]] -name = "windows_i686_msvc" -version = "0.42.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "bf4d1122317eddd6ff351aa852118a2418ad4214e6613a50e0191f7004372605" - -[[package]] -name = "windows_x86_64_gnu" -version = "0.42.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "c1040f221285e17ebccbc2591ffdc2d44ee1f9186324dd3e84e99ac68d699c45" - -[[package]] -name = "windows_x86_64_gnullvm" -version = "0.42.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "628bfdf232daa22b0d64fdb62b09fcc36bb01f05a3939e20ab73aaf9470d0463" - -[[package]] -name = "windows_x86_64_msvc" -version = "0.42.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "447660ad36a13288b1db4d4248e857b510e8c3a225c822ba4fb748c0aafecffd" diff --git a/win-tun-driver/ForTunCli/Cargo.toml b/win-tun-driver/ForTunCli/Cargo.toml deleted file mode 100644 index 2995e6e..0000000 --- a/win-tun-driver/ForTunCli/Cargo.toml +++ /dev/null @@ -1,23 +0,0 @@ -[package] -name = "fortun-cli" -version = "0.0.1" -edition = "2021" - -# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html -#[lib] -#name = "fortun-cli" -#path = "src/lib.rs" -#crate-type = ["staticlib", "cdylib", "lib"] - -[dependencies] - -windows = { version = "0.44", features = ["Win32_System_IO", "Win32_Storage_FileSystem", "Win32_Devices_Enumeration_Pnp", "Win32_System_Threading" ,"Win32_Devices_Properties", "Win32_Foundation", "Win32_Security", "Win32_Devices_DeviceAndDriverInstallation", "Win32_System_Registry", "Win32_NetworkManagement_IpHelper"] } -anyhow = "1" -scopeguard = "1" -local-encoding = "*" -tokio = {version = "1", features = ["full"]} -packet = "0.1" -cidr-utils = "0.5" - -tracing-subscriber = "0.3" -tracing = "0.1" diff --git a/win-tun-driver/ForTunCli/src/device_ops.rs b/win-tun-driver/ForTunCli/src/device_ops.rs deleted file mode 100644 index cceb636..0000000 --- a/win-tun-driver/ForTunCli/src/device_ops.rs +++ /dev/null @@ -1,753 +0,0 @@ -use std::ffi::c_void; -use std::mem::{size_of, zeroed}; -use std::net::IpAddr; -use std::process::Command; - -use anyhow::{anyhow, bail, Context}; -use cidr_utils::cidr::IpCidr; -use std::thread::sleep; -use std::time::Duration; -use windows::core::{wcslen, GUID, HRESULT, HSTRING, PCWSTR, PWSTR}; -use windows::w; -use windows::Win32::Devices::DeviceAndDriverInstallation::{ - CM_Get_DevNode_PropertyW, CM_Get_Device_ID_ListW, CM_Get_Device_ID_List_SizeW, - CM_Get_Device_Interface_ListW, CM_Get_Device_Interface_List_SizeW, CM_Locate_DevNodeW, - SetupCopyOEMInfW, SetupDiSetClassInstallParamsW, CM_GETIDLIST_FILTER_CLASS, - CM_GET_DEVICE_INTERFACE_LIST_ALL_DEVICES, CM_LOCATE_DEVINST_NORMAL, CM_LOCATE_DEVNODE_PHANTOM, - CR_NO_SUCH_DEVNODE, CR_SUCCESS, DIF_REMOVE, DI_REMOVEDEVICE_GLOBAL, GUID_DEVCLASS_NET, - HDEVINFO, SPOST_PATH, SP_CLASSINSTALL_HEADER, SP_COPY_NEWER, SP_DEVINFO_DATA, - SP_REMOVEDEVICE_PARAMS, -}; -use windows::Win32::Devices::Enumeration::Pnp::{ - SWDeviceCapabilitiesDriverRequired, SWDeviceCapabilitiesSilentInstall, SwDeviceClose, - SwDeviceCreate, HSWDEVICE, SW_DEVICE_CREATE_INFO, -}; -use windows::Win32::Devices::Properties::{ - DEVPKEY_Device_ClassGuid, DEVPKEY_Device_FriendlyName, DEVPKEY_Device_HardwareIds, - DEVPROPCOMPKEY, DEVPROPERTY, DEVPROP_STORE_SYSTEM, DEVPROP_TYPE_GUID, DEVPROP_TYPE_STRING, -}; -use windows::Win32::Foundation::{ - CloseHandle, GetLastError, ERROR_NO_MORE_ITEMS, HANDLE, NO_ERROR, WAIT_OBJECT_0, -}; -use windows::Win32::NetworkManagement::IpHelper::GetAdapterIndex; -use windows::Win32::Storage::FileSystem::{ - CreateFileW, FILE_ATTRIBUTE_SYSTEM, FILE_FLAG_OVERLAPPED, FILE_GENERIC_READ, - FILE_GENERIC_WRITE, FILE_SHARE_NONE, OPEN_EXISTING, -}; -use windows::Win32::System::Registry::{ - RegCloseKey, RegEnumKeyExW, RegOpenKeyExW, RegQueryValueExW, HKEY, HKEY_LOCAL_MACHINE, - KEY_ENUMERATE_SUB_KEYS, KEY_READ, -}; -use windows::Win32::System::IO::DeviceIoControl; - -macro_rules! ctl_code { - ($DeviceType:expr, $Function:expr, $Method:expr, $Access:expr) => { - ($DeviceType << 16) | ($Access << 14) | ($Function << 2) | $Method - }; -} - -pub const FOR_TUN_IOCTL_OPEN_ADAPTER: u32 = ctl_code!(0x00000022, 0x0801, 0, 0); -pub const FOR_TUN_INTERFACE_GUID: &str = "f579d929-6c40-4e5a-8532-180199a4e321"; -pub const FOR_TUN_HWID: &str = "ForTun"; - -// pub const FOR_TUN_IOCTL_OPEN_ADAPTER: u32 = ctl_code!(0x00000022, 6, 0, 0); -// pub const FOR_TUN_INTERFACE_GUID: &str = "CAC88484-7515-4C03-82E6-71A87ABAC361"; -// pub const FOR_TUN_HWID: &str = "ovpn-dco"; - -//const FOR_TUN_ENUMERATOR:PCWSTR = w!("SWD\\ForTun"); -pub const FOR_TUN_DEV_CLASS: GUID = GUID_DEVCLASS_NET; - -pub struct AdapterDevice { - pub handler: HSWDEVICE, - pub instance_id: String, - pub interface_id: String, -} - -impl AdapterDevice { - pub fn new(handler: HSWDEVICE, instance_id: String, interface_id: String) -> Self { - Self { - handler, - instance_id, - interface_id, - } - } - - pub fn start_adapter(&self) -> anyhow::Result { - //println!("interface_id:{}",self.interface_id); - /* - let file = OpenOptions::new() - .write(true) - .read(true) - .create(false) - //.custom_flags(0x40000000) - //.custom_flags(FILE_FLAG_OVERLAPPED.0|FILE_ATTRIBUTE_SYSTEM.0) - //.share_mode() - .open(self.interface_id.clone())?; - - - let result = unsafe { - DeviceIoControl( - HANDLE(file.as_raw_handle() as _), - FOR_TUN_IOCTL_OPEN_ADAPTER, - None, - 0, - None, - 0, - None, - None, - ) - .as_bool() - }; - if !result { - bail!("init adapter error: {:?}", unsafe { GetLastError() }) - } - - */ - - let file = unsafe { - let name = HSTRING::from(self.interface_id.clone()); - CreateFileW( - PCWSTR(name.as_ptr()), - FILE_GENERIC_READ | FILE_GENERIC_WRITE, - FILE_SHARE_NONE, - None, - OPEN_EXISTING, - FILE_ATTRIBUTE_SYSTEM | FILE_FLAG_OVERLAPPED, - None, - ) - } - .unwrap(); - let result = unsafe { - DeviceIoControl( - file, - FOR_TUN_IOCTL_OPEN_ADAPTER, - None, - 0, - None, - 0, - None, - None, - ) - .as_bool() - }; - - if !result { - unsafe { CloseHandle(file) }; - bail!("init adapter error: {:?}", unsafe { GetLastError() }) - } - - Ok(file) - } -} - -//TODO: inf_path change to compile path -pub fn init_device( - device_guid: &GUID, - name: &str, - inf_path: &str, -) -> anyhow::Result { - //let inf_path = "C:/DriverTest/Drivers/ForTun.inf"; - let devices = enum_device(&FOR_TUN_DEV_CLASS, FOR_TUN_HWID)?; - if devices.is_empty() { - // There is no devices - install_driver(inf_path)?; // TODO: this may install multiple times. need add more exact function to check if driver installed. - } else { - //TODO: compare version, if old exists, stop and remove all devices and reinstall new driver. - } - - let (device_handler, device_instance_id) = - create_device(device_guid, FOR_TUN_HWID, name, &FOR_TUN_DEV_CLASS)?; - // need to wait interface initialize - sleep(Duration::from_millis(500)); - let interfaces = get_device_interface(&GUID::from(FOR_TUN_INTERFACE_GUID), &device_instance_id) - .context("get device interface") - .map_err(|e| { - unsafe { - SwDeviceClose(device_handler); - } - e - })?; - - if interfaces.len() == 0 { - unsafe { - SwDeviceClose(device_handler); - } - bail!("get error count device interfaces: {}", interfaces.len()) - } - - //TODO: interface filter, now the first is ok. - let interface_id = interfaces.into_iter().next().unwrap(); - - let device = AdapterDevice::new(device_handler, device_instance_id, interface_id); - - Ok(device) -} - -fn install_driver(inf_path: &str) -> anyhow::Result<()> { - let inf_path = HSTRING::from(inf_path); - let inf_path = PCWSTR(inf_path.as_ptr()); - - let ret = unsafe { - SetupCopyOEMInfW( - inf_path, - PCWSTR::null(), - SPOST_PATH, - SP_COPY_NEWER.0, - None, - None, - None, - ) - }; - if !ret.as_bool() { - unsafe { - return Err(anyhow!( - "install driver:{} fail, code:{}", - inf_path.display(), - GetLastError().0 - )); - } - } - Ok(()) -} - -// this would copy buf to string -fn get_pcwstr_list(mut buf: Vec) -> Vec { - let mut index = 0; - let mut result = Vec::new(); - - let mut string = PCWSTR::from_raw(buf[index..].as_mut_ptr()); - while buf[index] != 0 && !string.is_null() { - unsafe { - result.push(string.to_string().unwrap()); - } - unsafe { - index += wcslen(string) + 1; - } - if index >= buf.len() - 1 { - break; - } - string = PCWSTR::from_raw(buf[index..].as_mut_ptr()); - } - result -} - -struct CreateDeviceContext { - pub instance_id: String, - pub event: HANDLE, - pub success: bool, -} - -pub fn create_device( - device_id: &GUID, - hwid: &str, - device_name: &str, - device_class_guid: &GUID, -) -> anyhow::Result<(HSWDEVICE, String)> { - let description = HSTRING::from(format!("{device_name} device\0\0")); - let description = PCWSTR(description.as_ptr()); - - let device_id = HSTRING::from(format!("{device_id:?}")); - let device_id = PCWSTR(device_id.as_ptr()); - - let friendly_name = HSTRING::from(format!("{device_name}\0")); - let friendly_name = PCWSTR(friendly_name.as_ptr()); - - let device_name = HSTRING::from(device_name); - let device_name = PCWSTR(device_name.as_ptr()); - - //let enumerator_name = HSTRING::from(format!("{}\0",FOR_TUN_ENUMERATOR)); - //let enumerator_name = PCWSTR::from(&enumerator_name); - - let hwids = HSTRING::from(format!("{hwid}\0")); - let hwids = PCWSTR(hwids.as_ptr()); - - //let hwid = HSTRING::from(hwid); - //let hwid = PCWSTR::from(&hwid); - let mut create_info: SW_DEVICE_CREATE_INFO = unsafe { zeroed() }; - create_info.cbSize = size_of::() as u32; - create_info.pszzHardwareIds = hwids; - create_info.pszInstanceId = device_id; - create_info.pszDeviceDescription = description; - create_info.CapabilityFlags = - (SWDeviceCapabilitiesSilentInstall.0 | SWDeviceCapabilitiesDriverRequired.0) as u32; - - let device_properties = vec![ - DEVPROPERTY { - CompKey: DEVPROPCOMPKEY { - Key: DEVPKEY_Device_ClassGuid, - Store: DEVPROP_STORE_SYSTEM, - LocaleName: PCWSTR::null(), - }, - Type: DEVPROP_TYPE_GUID, - Buffer: &mut device_class_guid.clone() as *mut _ as *mut c_void, - BufferSize: size_of::() as u32, - }, - // could not set it DEVPKEY_Device_EnumeratorName - // DEVPROPERTY { - // CompKey: DEVPROPCOMPKEY { - // Key: , - // Store: DEVPROP_STORE_SYSTEM, - // LocaleName: PCWSTR::null(), - // }, - // Type: DEVPROP_TYPE_STRING, - // Buffer: enumerator_name.as_ptr() as *mut c_void, - // BufferSize: ((unsafe { wcslen(enumerator_name) } + 1 ) * size_of::()) as _, - // }, - DEVPROPERTY { - CompKey: DEVPROPCOMPKEY { - Key: DEVPKEY_Device_FriendlyName, - Store: DEVPROP_STORE_SYSTEM, - LocaleName: PCWSTR::null(), - }, - Type: DEVPROP_TYPE_STRING, - Buffer: friendly_name.as_ptr() as *mut c_void, - BufferSize: ((unsafe { wcslen(friendly_name) } + 1) * size_of::()) as _, - }, - ]; - - let event: HANDLE = unsafe { - windows::Win32::System::Threading::CreateEventW(None, false, false, PCWSTR::null())? - }; - let mut context = CreateDeviceContext { - event, - instance_id: String::new(), - success: false, - }; - - let sw_device = unsafe { - SwDeviceCreate( - device_name, - w!("HTREE\\ROOT\\0"), - &create_info, - Some(&device_properties), - Some(creation_callback), - Some(&mut context as *mut _ as *const c_void), - ) - } - .context("SwDeviceCreate Fail")?; - let wait_result = - unsafe { windows::Win32::System::Threading::WaitForSingleObject(event, 20 * 1000) }; - if wait_result != WAIT_OBJECT_0 { - unsafe { - return Err(anyhow!( - "create sw device error: {}, last_error:{}", - wait_result.0, - GetLastError().0 - )); - } - } - if !context.success { - unsafe { - bail!( - "create sw device error in callback, last error:{}", - GetLastError().0 - ) - } - } - - Ok((HSWDEVICE(sw_device), context.instance_id)) -} - -unsafe extern "system" fn creation_callback( - _device: HSWDEVICE, - _create_result: HRESULT, - context: *const c_void, - _device_instance_id: PCWSTR, -) { - let mut context = &mut *(context as *mut CreateDeviceContext); - if _create_result.is_ok() { - context.instance_id = _device_instance_id.to_string().unwrap(); - context.success = true; - //println!("device creation device_id:{}", _device_instance_id.display()); - } else { - context.success = false; - //println!("device creation device_id error, {}",_create_result); - } - let ret = windows::Win32::System::Threading::SetEvent(context.event); - if !ret.as_bool() { - //println!("set event error, {}", GetLastError().0) - } -} - -pub fn route_set(adapter_index: String, address: &str) -> anyhow::Result<()> { - let ip_cidr = cidr_utils::cidr::IpCidr::from_str(address)?; - let netmask = match ip_cidr { - IpCidr::V4(cidr) => cidr.get_mask_as_ipv4_addr().to_string(), - IpCidr::V6(cidr) => cidr.get_mask_as_ipv6_addr().to_string(), - }; - Command::new("netsh") - .args([ - "interface", - "ip", - "set", - "address", - &adapter_index, - "static", - &ip_cidr.to_string(), - &netmask, - //"1", - ]) - .status()?; - Ok(()) -} - -pub fn mtu_set(adapter_index: String, mtu: u32, is_v4: bool) -> anyhow::Result<()> { - let ip_type = if is_v4 { "ipv4" } else { "ipv6" }; - Command::new("netsh") - .args([ - "interface", - ip_type, - "set", - "subinterface", - &adapter_index, - &format!("mtu={}", mtu), - ]) - .status()?; - Ok(()) -} - -pub fn net_config( - device_instance_id: String, - address: &str, - netmask: &str, - //gateway: str, - mtu: u32, -) -> anyhow::Result<()> { - let index = get_net_index(device_instance_id)?.to_string(); - //netsh interface ip set address 5 static 10.0.0.2 255.255.255.0 10.0.0.1 - tracing::debug!("netsh interface ip set address {index} static {address} {netmask}"); - Command::new("netsh") - .args([ - "interface", - "ip", - "set", - "address", - &index, - "static", - address, - netmask, - //gateway, - ]) - .status()?; - let ip_type = if address.parse::()?.is_ipv4() { - "ipv4" - } else { - "ipv6" - }; - - tracing::debug!("netsh interface {ip_type} set subinterface {index} mtu={mtu}"); - //netsh interface ipv4 set subinterface 5 mtu=1428 - Command::new("netsh") - .args([ - "interface", - ip_type, - "set", - "subinterface", - &index, - &format!("mtu={}", mtu), - ]) - .status()?; - Ok(()) -} - -pub fn get_net_index(device_instance_id: String) -> anyhow::Result { - //key: HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\Class\\ registry key. - - let mut key = HKEY::default(); - - let _display_name_buf: [u16; 1024] = unsafe { zeroed() }; - - let key_path_str = - format!("SYSTEM\\CurrentControlSet\\Control\\Class\\{{{FOR_TUN_DEV_CLASS:?}}}"); - - let key_path = HSTRING::from(key_path_str.clone()); - let key_path = PCWSTR(key_path.as_ptr()); - - if unsafe { - RegOpenKeyExW( - HKEY_LOCAL_MACHINE, - key_path, - 0, - KEY_READ | KEY_ENUMERATE_SUB_KEYS, - &mut key, - ) - } != NO_ERROR - { - unsafe { RegCloseKey(key) }; - bail!("can not open registry key: {}", key_path_str); - } else { - let mut value_buffer = vec![0; 200]; - let mut index = 0; - let mut class_name_buf = [0u16; 256]; - let name_buf = PWSTR::from_raw(class_name_buf.as_mut_ptr()); - - loop { - let mut class_name_length = 256; - let ret = unsafe { - RegEnumKeyExW( - key, - index, - name_buf, - &mut class_name_length, - None, - PWSTR::null(), - None, - None, - ) - }; - - if ret == ERROR_NO_MORE_ITEMS { - break; - } else if ret != NO_ERROR { - bail!( - "can not enum registry key: {}, error:{:?}", - key_path_str, - ret - ) - } - - let instance_name_key = - unsafe { format!("{}\\{}", key_path_str, name_buf.to_string().unwrap()) }; - // println!("instance_name_key:{instance_name_key}"); - let instance_name_key = HSTRING::from(instance_name_key); - let instance_name_key = PCWSTR(instance_name_key.as_ptr()); - let mut instance_key = HKEY::default(); - unsafe { - RegOpenKeyExW( - HKEY_LOCAL_MACHINE, - instance_name_key, - 0, - KEY_READ, - &mut instance_key, - ) - }; - - let mut size = 200; - unsafe { - RegQueryValueExW( - instance_key, - w!("DeviceInstanceID"), - None, - None, - Some(value_buffer.as_mut_ptr()), - Some(&mut size), - ) - }; - - let reg_value = - unsafe { PCWSTR::from_raw(value_buffer.as_mut_ptr().cast::()).to_string() } - .unwrap(); - if reg_value == device_instance_id { - let mut size = 200; - //NetCfgInstanceId - unsafe { - RegQueryValueExW( - instance_key, - w!("NetCfgInstanceId"), - None, - None, - Some(value_buffer.as_mut_ptr()), - Some(&mut size), - ) - }; - let net_cfg_instance_id = unsafe { - PCWSTR::from_raw(value_buffer.as_mut_ptr().cast::()).to_string() - } - .unwrap(); - let adapter_name = HSTRING::from(format!("\\DEVICE_TCPIP_{net_cfg_instance_id}")); - let adapter_name = PCWSTR(adapter_name.as_ptr()); - let mut r = 0; - unsafe { - GetAdapterIndex(adapter_name, &mut r); - } - - unsafe { RegCloseKey(instance_key) }; - return Ok(r); - } else { - unsafe { - RegCloseKey(instance_key); - } - index += 1; - } - } - bail!("could not get device NetCfgInstanceId") - } -} - -pub fn get_device_interface( - interface_class_guid: &GUID, - device_instance_id: &str, -) -> anyhow::Result> { - let device_instance_id = HSTRING::from(device_instance_id); - let device_instance_id = PCWSTR(device_instance_id.as_ptr()); - let mut length = 0; - let flag = CM_GET_DEVICE_INTERFACE_LIST_ALL_DEVICES; - let error_ret = unsafe { - CM_Get_Device_Interface_List_SizeW( - &mut length, - interface_class_guid, - device_instance_id, - flag, - ) - }; - if error_ret != CR_SUCCESS { - return Err(anyhow!( - "get device interface list size error: {}", - error_ret.0 - )); - } - if length == 0 { - println!("device list is empty"); - return Ok(Vec::new()); - } - let mut buffer: Vec = vec![0; length as usize]; - let cr_ret = unsafe { - CM_Get_Device_Interface_ListW(interface_class_guid, device_instance_id, &mut buffer, flag) - }; - if cr_ret != CR_SUCCESS { - return Err(anyhow!("get device interface list error: {}", cr_ret.0)); - } - unsafe { - buffer.set_len(length as usize); - } - let buffer = get_pcwstr_list(buffer); - Ok(buffer) -} - -fn remove_device(dev_info: HDEVINFO, dev_info_data: &SP_DEVINFO_DATA) { - let mut rmd_params = unsafe { zeroed::() }; - rmd_params.ClassInstallHeader.cbSize = size_of::() as u32; - rmd_params.ClassInstallHeader.InstallFunction = DIF_REMOVE; - rmd_params.Scope = DI_REMOVEDEVICE_GLOBAL; - rmd_params.HwProfile = 0; - unsafe { - SetupDiSetClassInstallParamsW( - dev_info, - Some(dev_info_data), - Some(&rmd_params.ClassInstallHeader), - size_of::() as u32, - ) - }; -} - -fn enum_device(device_class_id: &GUID, hwid: &str) -> anyhow::Result> { - let mut device_list_len = 0; - let device_class_id = HSTRING::from(format!("{{{device_class_id:?}}}\0")); - let device_class_id = PCWSTR(device_class_id.as_ptr()); - - let flag = CM_GETIDLIST_FILTER_CLASS; - let cr = unsafe { CM_Get_Device_ID_List_SizeW(&mut device_list_len, device_class_id, flag) }; - - if cr != CR_SUCCESS { - return Err(anyhow!("Fail to get device list size: {:?}", cr)); - } - - //let mut buffer = Vec::with_capacity(device_list_len as usize); - let mut buffer = vec![0; device_list_len as usize]; - - let cr = unsafe { CM_Get_Device_ID_ListW(device_class_id, &mut buffer, flag) }; - if cr != CR_SUCCESS { - return Err(anyhow!("Fail to get device list:{:?}", cr)); - } - - let mut dev_inst: u32 = 0; - let mut property_type: u32 = 0; - - let mut property_value: Vec = Vec::with_capacity(2048); - let mut property_value_length = 0; - - let mut index = 0; - let mut device_id = PCWSTR::from_raw(buffer[index..].as_mut_ptr()); - - let mut result: Vec = Vec::new(); - - while buffer[index] != 0 && !device_id.is_null() { - let cr = unsafe { - CM_Locate_DevNodeW( - &mut dev_inst, - device_id, - CM_LOCATE_DEVINST_NORMAL | CM_LOCATE_DEVNODE_PHANTOM, - ) - }; - - if cr != CR_SUCCESS { - if cr != CR_NO_SUCH_DEVNODE { - unsafe { - return Err(anyhow!( - "Fail to locate dev node: {}, error:{}", - device_id.display(), - cr.0 - )); - } - } - } else { - unsafe { - CM_Get_DevNode_PropertyW( - dev_inst, - &DEVPKEY_Device_HardwareIds, - &mut property_type, - Some(property_value.as_mut_ptr()), - &mut property_value_length, - 0, - ); - } - - if property_value_length > 0 { - unsafe { - property_value.set_len(property_value_length as usize); - }; - - let name = unsafe { - PCWSTR::from_raw(property_value.as_mut_ptr().cast::()).to_string() - }; - - if let Ok(name) = name { - if name == hwid { - unsafe { - if let Ok(device_id) = device_id.to_string() { - result.push(device_id); - } - } - } - } - } - } - - unsafe { - index += wcslen(device_id) + 1; - } - if index >= buffer.len() - 1 { - break; - } - device_id = PCWSTR::from_raw(buffer[index..].as_mut_ptr()); - } - Ok(result) -} - -#[cfg(test)] -mod test { - use windows::core::PCSTR; - use windows::Win32::Storage::FileSystem::{ - CreateFileA, FILE_ATTRIBUTE_SYSTEM, FILE_FLAG_OVERLAPPED, FILE_GENERIC_READ, - FILE_GENERIC_WRITE, FILE_SHARE_MODE, FILE_SHARE_NONE, OPEN_EXISTING, - }; - - #[test] - fn test() { - let a = PCSTR::from_raw("\\\\.\\ovpn-dco\0".as_ptr()); - - let a = unsafe { - CreateFileA( - a, - FILE_GENERIC_READ | FILE_GENERIC_WRITE, - FILE_SHARE_NONE, - None, - OPEN_EXISTING, - FILE_ATTRIBUTE_SYSTEM | FILE_FLAG_OVERLAPPED, - None, - ) - } - .unwrap(); - println!("finish...."); - } -} diff --git a/win-tun-driver/ForTunCli/src/lib.rs b/win-tun-driver/ForTunCli/src/lib.rs deleted file mode 100644 index d32d12e..0000000 --- a/win-tun-driver/ForTunCli/src/lib.rs +++ /dev/null @@ -1,137 +0,0 @@ -mod device_ops; -pub mod overlapped_file; - -use crate::overlapped_file::WinOverlappedFile; -use anyhow::bail; -pub use device_ops::get_net_index; -pub use device_ops::init_device; -pub use device_ops::net_config; -pub use device_ops::AdapterDevice; -use std::sync::Arc; -use tokio::io; -use windows::core::GUID; -use windows::Win32::Foundation::CloseHandle; -use windows::Win32::System::IO::OVERLAPPED; - -pub struct OverlappedWrap { - pub overlapped: OVERLAPPED, -} - -//unsafe impl Send for OverlappedWrap {} - -pub struct ReadFile { - file: Arc, - overlapped: OVERLAPPED, -} - -unsafe impl Send for ReadFile {} - -impl ReadFile { - // this would block... - pub fn read(&mut self, buf: &mut [u8]) -> io::Result { - self.file.read(buf, &mut self.overlapped) - } -} - -impl Drop for ReadFile { - fn drop(&mut self) { - let _ = self.file.cancel_io(&mut self.overlapped); - } -} - -pub struct WriteFile { - file: Arc, - overlapped: OVERLAPPED, -} - -unsafe impl Send for WriteFile {} - -impl WriteFile { - //this would Finish quick - pub fn write(&mut self, buf: &[u8]) -> io::Result { - self.file.write(buf, &mut self.overlapped) - } -} - -impl Drop for WriteFile { - fn drop(&mut self) { - let _ = self.file.cancel_io(&mut self.overlapped); - } -} - -pub type TunSocket = (ReadFile, WriteFile, AdapterDevice); - -pub fn create_async_tun(device_id: &GUID, name: &str) -> anyhow::Result { - let device = init_device(device_id, name, "C:/DriverTest/Drivers/ForTun.inf")?; - let file = device.start_adapter()?; - let file = match WinOverlappedFile::new(file) { - Ok(file) => Arc::new(file), - Err(err) => { - unsafe { CloseHandle(file) }; - bail!("create winOverlappedFile error:{}", err) - } - }; - - Ok(( - ReadFile { - file: file.clone(), - overlapped: OVERLAPPED::default(), - }, - WriteFile { - file: file.clone(), - overlapped: OVERLAPPED::default(), - }, - device, - )) -} - -/* -pub struct TunSocket { - pub file: tokio::fs::File, - pub device: AdapterDevice, -} - -pub fn create_async_tun(device_id: &GUID, name: &str) -> anyhow::Result { - let device = init_device(device_id, name, "C:/DriverTest/Drivers/ForTun.inf")?; - let file = device.start_adapter()?; - - let file = tokio::fs::File::from_std(file); - Ok(TunSocket { file, device }) -} - - -impl AsyncRead for TunSocket { - fn poll_read( - self: Pin<&mut Self>, - cx: &mut Context<'_>, - buf: &mut ReadBuf<'_>, - ) -> Poll> { - Pin::new(&mut self.get_mut().file).poll_read(cx, buf) - } -} - -impl AsyncWrite for TunSocket { - fn poll_write( - self: Pin<&mut Self>, - cx: &mut Context<'_>, - buf: &[u8], - ) -> Poll> { - Pin::new(&mut self.get_mut().file).poll_write(cx, buf) - } - - fn poll_flush(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll> { - Pin::new(&mut self.get_mut().file).poll_flush(cx) - } - - fn poll_shutdown(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll> { - Pin::new(&mut self.get_mut().file).poll_shutdown(cx) - } - fn poll_write_vectored( - self: Pin<&mut Self>, - cx: &mut Context<'_>, - bufs: &[IoSlice<'_>], - ) -> Poll> { - Pin::new(&mut self.get_mut().file).poll_write_vectored(cx, bufs) - } -} -*/ diff --git a/win-tun-driver/ForTunCli/src/overlapped_file.rs b/win-tun-driver/ForTunCli/src/overlapped_file.rs deleted file mode 100644 index dee85b3..0000000 --- a/win-tun-driver/ForTunCli/src/overlapped_file.rs +++ /dev/null @@ -1,143 +0,0 @@ -use std::io; -use windows::Win32::Foundation::{CloseHandle, GetLastError, BOOL, ERROR_IO_PENDING, HANDLE}; -use windows::Win32::Storage::FileSystem::{ReadFile, WriteFile}; -use windows::Win32::System::IO::{CancelIoEx, DeviceIoControl, GetOverlappedResult, OVERLAPPED}; - -pub struct WinOverlappedFile { - pub file: HANDLE, -} - -impl WinOverlappedFile { - pub fn new(file: HANDLE) -> anyhow::Result { - //let mut overlapped = OVERLAPPED::default(); - //overlapped.hEvent = unsafe {CreateEventW(None, false, false, None)}?; - - Ok(Self { - file, - //read_overlapped: overlapped, - }) - } - - pub fn device_io_control_sync( - &mut self, - dwiocontrolcode: u32, - lpinbuffer: Option<*const ::core::ffi::c_void>, - ninbuffersize: u32, - lpoutbuffer: Option<*mut ::core::ffi::c_void>, - noutbuffersize: u32, - lpbytesreturned: Option<*mut u32>, - ) -> BOOL { - unsafe { - DeviceIoControl( - self.file, - dwiocontrolcode, - lpinbuffer, - ninbuffersize, - lpoutbuffer, - noutbuffersize, - lpbytesreturned, - None, - ) - } - } - - // driver would wait - pub fn read(&self, buf: &mut [u8], overlapped: &mut OVERLAPPED) -> io::Result { - let mut size = 0; - let ret = unsafe { - ReadFile( - self.file, - Some(buf.as_mut_ptr() as _), - buf.len() as u32, - Some(&mut size), - Some(overlapped), - ) - }; - return if ret.as_bool() { - //success - Ok(size as usize) - } else { - let last_error = unsafe { GetLastError() }; - if last_error == ERROR_IO_PENDING { - let r = unsafe { GetOverlappedResult(self.file, overlapped, &mut size, true) }; - if r.as_bool() { - Ok(size as usize) - } else { - Err(io::Error::from_raw_os_error(last_error.0 as i32)) - } - } else { - Err(io::Error::from_raw_os_error(last_error.0 as i32)) - } - }; - } - /* - pub fn read_result(&self, overlapped: &mut OVERLAPPED) -> io::Result> { - let mut size = 0; - let r = unsafe { - GetOverlappedResult( - self.file, - overlapped, - &mut size, - false, - ) - }; - if r.as_bool() { - Ok(Some(size as usize)) - } else { - let last_error = unsafe { GetLastError() }; - if last_error == ERROR_IO_PENDING { - Ok(None) - } else { - Err(io::Error::from_raw_os_error(last_error.0 as i32)) - } - } - }*/ - - // this is quick , so block - pub fn write(&self, buf: &[u8], overlapped: &mut OVERLAPPED) -> io::Result { - let mut size = 0; - let r = unsafe { - WriteFile( - self.file, - Some(buf.as_ptr() as _), - buf.len() as u32, - Some(&mut size), - Some(overlapped), - ) - }; - return if r.as_bool() { - Ok(size as usize) - } else { - let last_error = unsafe { GetLastError() }; - if last_error == ERROR_IO_PENDING { - let r = unsafe { GetOverlappedResult(self.file, overlapped, &mut size, true) }; - if r.as_bool() { - Ok(size as usize) - } else { - Err(io::Error::from_raw_os_error(last_error.0 as i32)) - } - } else { - Err(io::Error::from_raw_os_error(last_error.0 as i32)) - } - }; - } - - pub fn cancel_io(&self, overlapped: &mut OVERLAPPED) -> io::Result<()> { - if unsafe { CancelIoEx(self.file, Some(overlapped)) }.as_bool() { - Ok(()) - } else { - Err(io::Error::last_os_error()) - //Err(io::Error::from_raw_os_error(last_error.0 as i32)) - //Err(anyhow!("read file fail:{:?}", last_error)) - //Err(anyhow!("cancel file fail:{:?}", unsafe {GetLastError()})) - } - } -} - -impl Drop for WinOverlappedFile { - fn drop(&mut self) { - if !self.file.is_invalid() { - unsafe { CloseHandle(self.file) }; - } - } -}