diff --git a/src/BD.WTTS.Client.Plugins.Accelerator.ReverseProxy/BD.WTTS.Client.Plugins.Accelerator.ReverseProxy.csproj b/src/BD.WTTS.Client.Plugins.Accelerator.ReverseProxy/BD.WTTS.Client.Plugins.Accelerator.ReverseProxy.csproj index 7350d4985a5..8266c64ac8f 100644 --- a/src/BD.WTTS.Client.Plugins.Accelerator.ReverseProxy/BD.WTTS.Client.Plugins.Accelerator.ReverseProxy.csproj +++ b/src/BD.WTTS.Client.Plugins.Accelerator.ReverseProxy/BD.WTTS.Client.Plugins.Accelerator.ReverseProxy.csproj @@ -106,9 +106,9 @@ - + diff --git a/src/BD.WTTS.Client.Plugins.Accelerator.ReverseProxy/Extensions/ServiceCollectionExtensions.cs b/src/BD.WTTS.Client.Plugins.Accelerator.ReverseProxy/Extensions/ServiceCollectionExtensions.cs index 009d64473d9..e5bde0b55d2 100644 --- a/src/BD.WTTS.Client.Plugins.Accelerator.ReverseProxy/Extensions/ServiceCollectionExtensions.cs +++ b/src/BD.WTTS.Client.Plugins.Accelerator.ReverseProxy/Extensions/ServiceCollectionExtensions.cs @@ -148,28 +148,28 @@ internal static IServiceCollection AddFlowAnalyze(this IServiceCollection servic #if WINDOWS - /// - /// 注册数据包拦截器 - /// - /// - /// - [MethodImpl(MethodImplOptions.AggressiveInlining)] - internal static IServiceCollection AddPacketIntercept(this IServiceCollection services) - { - // https://github.com/dotnetcore/FastGithub/blob/2.1.4/FastGithub.PacketIntercept/ServiceCollectionExtensions.cs#L21 - //services.AddSingleton(); - //services.AddSingleton(); - services.TryAddSingleton(); - services.AddHostedService(); - - services.AddSingleton(); - services.AddSingleton(); - services.AddSingleton(); - services.AddSingleton(); - services.AddHostedService(); - - return services; - } + ///// + ///// 注册数据包拦截器 + ///// + ///// + ///// + //[MethodImpl(MethodImplOptions.AggressiveInlining)] + //internal static IServiceCollection AddPacketIntercept(this IServiceCollection services) + //{ + // // https://github.com/dotnetcore/FastGithub/blob/2.1.4/FastGithub.PacketIntercept/ServiceCollectionExtensions.cs#L21 + // //services.AddSingleton(); + // //services.AddSingleton(); + // services.TryAddSingleton(); + // services.AddHostedService(); + + // services.AddSingleton(); + // services.AddSingleton(); + // services.AddSingleton(); + // services.AddSingleton(); + // services.AddHostedService(); + + // return services; + //} #endif } \ No newline at end of file diff --git a/src/BD.WTTS.Client.Plugins.Accelerator.ReverseProxy/Services.Implementation/PacketIntercept/DnsInterceptor.cs b/src/BD.WTTS.Client.Plugins.Accelerator.ReverseProxy/Services.Implementation/PacketIntercept/DnsInterceptor.cs index 1c7b3576b88..39ddd32b0b4 100644 --- a/src/BD.WTTS.Client.Plugins.Accelerator.ReverseProxy/Services.Implementation/PacketIntercept/DnsInterceptor.cs +++ b/src/BD.WTTS.Client.Plugins.Accelerator.ReverseProxy/Services.Implementation/PacketIntercept/DnsInterceptor.cs @@ -1,203 +1,203 @@ -// https://github.com/dotnetcore/FastGithub/blob/2.1.4/FastGithub.PacketIntercept/Dns/DnsInterceptor.cs - -#if WINDOWS - -using WinDivertSharp; -using DNS.Protocol; -using DNS.Protocol.ResourceRecords; - -// ReSharper disable once CheckNamespace -namespace BD.WTTS.Services.Implementation; - -/// -sealed partial class DnsInterceptor : IDnsInterceptor, IDisposable -{ - const string DNS_FILTER = "udp.DstPort == 53"; - - readonly IReverseProxyConfig reverseProxyConfig; - readonly ILogger logger; - - readonly TimeSpan ttl = TimeSpan.FromMinutes(5d); - bool disposedValue; - - /// - /// 刷新 DNS 缓存 - /// - [LibraryImport("dnsapi.dll", EntryPoint = "DnsFlushResolverCache", SetLastError = true)] - static partial void DnsFlushResolverCache(); - - static DnsInterceptor() - { - // 首次加载驱动往往有异常,所以要提前加载 - var handle = WinDivert.WinDivertOpen("false", WinDivertLayer.Network, 0, WinDivertOpenFlags.None); - WinDivert.WinDivertClose(handle); - } - - public DnsInterceptor( - IReverseProxyConfig reverseProxyConfig, - ILogger logger) - { - this.reverseProxyConfig = reverseProxyConfig; - this.logger = logger; - } - - public async Task InterceptAsync(CancellationToken cancellationToken) - { - await Task.Yield(); - - var handle = WinDivert.WinDivertOpen(DNS_FILTER, WinDivertLayer.Network, 0, WinDivertOpenFlags.None); - if (handle == new IntPtr(unchecked((long)ulong.MaxValue))) - { - throw new Win32Exception(); - } - - cancellationToken.Register(hwnd => - { - WinDivert.WinDivertClose((IntPtr)hwnd!); - DnsFlushResolverCache(); - }, handle); - - var packetLength = 0U; - using WinDivertBuffer winDivertBuffer = new(); - WinDivertAddress winDivertAddress = default; - - DnsFlushResolverCache(); - while (!cancellationToken.IsCancellationRequested) - { - if (WinDivert.WinDivertRecv(handle, winDivertBuffer, ref winDivertAddress, ref packetLength) == false) - { - throw new Win32Exception(); - } - - try - { - ModifyDnsPacket(winDivertBuffer, ref winDivertAddress, ref packetLength); - } - catch (Exception ex) - { - logger.LogWarning(ex.Message); - } - finally - { - WinDivert.WinDivertSend(handle, winDivertBuffer, packetLength, ref winDivertAddress); - } - } - } - - /// - /// 修改 DNS 数据包 - /// - /// - /// - /// - unsafe void ModifyDnsPacket(WinDivertBuffer winDivertBuffer, ref WinDivertAddress winDivertAddress, ref uint packetLength) - { - var packet = WinDivert.WinDivertHelperParsePacket(winDivertBuffer, packetLength); - var requestPayload = new Span(packet.PacketPayload, (int)packet.PacketPayloadLength).ToArray(); - - if (!TryParseRequest(requestPayload, out var request) || - request.OperationCode != OperationCode.Query || - request.Questions.Count == 0) - { - return; - } - - var question = request.Questions.First(); - if (question.Type != RecordType.A && question.Type != RecordType.AAAA) - { - return; - } - - var domain = question.Name; - if (!reverseProxyConfig.IsMatch(question.Name.ToString())) - { - return; - } - - // DNS 响应数据 - var response = Response.FromRequest(request); - var loopback = question.Type == RecordType.A ? IPAddress.Loopback : IPAddress.IPv6Loopback; - var record = new IPAddressResourceRecord(domain, loopback, ttl); - response.AnswerRecords.Add(record); - var responsePayload = response.ToArray(); - - // 修改 payload 和包长 - responsePayload.CopyTo(new Span(packet.PacketPayload, responsePayload.Length)); - packetLength = (uint)((int)packetLength + responsePayload.Length - requestPayload.Length); - - // 修改 IP 包 - IPAddress destAddress; - if (packet.IPv4Header != null) - { - destAddress = packet.IPv4Header->DstAddr; - packet.IPv4Header->DstAddr = packet.IPv4Header->SrcAddr; - packet.IPv4Header->SrcAddr = destAddress; - packet.IPv4Header->Length = (ushort)packetLength; - } - else - { - destAddress = packet.IPv6Header->DstAddr; - packet.IPv6Header->DstAddr = packet.IPv6Header->SrcAddr; - packet.IPv6Header->SrcAddr = destAddress; - packet.IPv6Header->Length = (ushort)(packetLength - sizeof(IPv6Header)); - } - - // 修改 UDP 包 - (packet.UdpHeader->SrcPort, packet.UdpHeader->DstPort) = (packet.UdpHeader->DstPort, packet.UdpHeader->SrcPort); - packet.UdpHeader->Length = (ushort)(sizeof(UdpHeader) + responsePayload.Length); - - winDivertAddress.Impostor = true; - winDivertAddress.Direction = winDivertAddress.Loopback - ? WinDivertDirection.Outbound - : WinDivertDirection.Inbound; - - WinDivert.WinDivertHelperCalcChecksums(winDivertBuffer, packetLength, ref winDivertAddress, WinDivertChecksumHelperParam.All); - - logger.LogInformation($"{domain} -> {loopback}"); - } - - static bool TryParseRequest(byte[] payload, [NotNullWhen(true)] out Request? request) - { - try - { - request = Request.FromArray(payload); - return true; - } - catch (Exception) - { - request = null; - return false; - } - } - - private void Dispose(bool disposing) - { - if (!disposedValue) - { - if (disposing) - { - // TODO: 释放托管状态(托管对象) - using var p = Process.Start(new ProcessStartInfo() - { - UseShellExecute = false, - CreateNoWindow = true, - FileName = "sc", - Arguments = "stop WinDivert1.4", - }); - } - - // TODO: 释放未托管的资源(未托管的对象)并重写终结器 - // TODO: 将大型字段设置为 null - disposedValue = true; - } - } - - public void Dispose() - { - // 不要更改此代码。请将清理代码放入“Dispose(bool disposing)”方法中 - Dispose(disposing: true); - GC.SuppressFinalize(this); - } -} - -#endif \ No newline at end of file +//// https://github.com/dotnetcore/FastGithub/blob/2.1.4/FastGithub.PacketIntercept/Dns/DnsInterceptor.cs + +//#if WINDOWS + +//using WinDivertSharp; +//using DNS.Protocol; +//using DNS.Protocol.ResourceRecords; + +//// ReSharper disable once CheckNamespace +//namespace BD.WTTS.Services.Implementation; + +///// +//sealed partial class DnsInterceptor : IDnsInterceptor, IDisposable +//{ +// const string DNS_FILTER = "udp.DstPort == 53"; + +// readonly IReverseProxyConfig reverseProxyConfig; +// readonly ILogger logger; + +// readonly TimeSpan ttl = TimeSpan.FromMinutes(5d); +// bool disposedValue; + +// /// +// /// 刷新 DNS 缓存 +// /// +// [LibraryImport("dnsapi.dll", EntryPoint = "DnsFlushResolverCache", SetLastError = true)] +// static partial void DnsFlushResolverCache(); + +// static DnsInterceptor() +// { +// // 首次加载驱动往往有异常,所以要提前加载 +// var handle = WinDivert.WinDivertOpen("false", WinDivertLayer.Network, 0, WinDivertOpenFlags.None); +// WinDivert.WinDivertClose(handle); +// } + +// public DnsInterceptor( +// IReverseProxyConfig reverseProxyConfig, +// ILogger logger) +// { +// this.reverseProxyConfig = reverseProxyConfig; +// this.logger = logger; +// } + +// public async Task InterceptAsync(CancellationToken cancellationToken) +// { +// await Task.Yield(); + +// var handle = WinDivert.WinDivertOpen(DNS_FILTER, WinDivertLayer.Network, 0, WinDivertOpenFlags.None); +// if (handle == new IntPtr(unchecked((long)ulong.MaxValue))) +// { +// throw new Win32Exception(); +// } + +// cancellationToken.Register(hwnd => +// { +// WinDivert.WinDivertClose((IntPtr)hwnd!); +// DnsFlushResolverCache(); +// }, handle); + +// var packetLength = 0U; +// using WinDivertBuffer winDivertBuffer = new(); +// WinDivertAddress winDivertAddress = default; + +// DnsFlushResolverCache(); +// while (!cancellationToken.IsCancellationRequested) +// { +// if (WinDivert.WinDivertRecv(handle, winDivertBuffer, ref winDivertAddress, ref packetLength) == false) +// { +// throw new Win32Exception(); +// } + +// try +// { +// ModifyDnsPacket(winDivertBuffer, ref winDivertAddress, ref packetLength); +// } +// catch (Exception ex) +// { +// logger.LogWarning(ex.Message); +// } +// finally +// { +// WinDivert.WinDivertSend(handle, winDivertBuffer, packetLength, ref winDivertAddress); +// } +// } +// } + +// /// +// /// 修改 DNS 数据包 +// /// +// /// +// /// +// /// +// unsafe void ModifyDnsPacket(WinDivertBuffer winDivertBuffer, ref WinDivertAddress winDivertAddress, ref uint packetLength) +// { +// var packet = WinDivert.WinDivertHelperParsePacket(winDivertBuffer, packetLength); +// var requestPayload = new Span(packet.PacketPayload, (int)packet.PacketPayloadLength).ToArray(); + +// if (!TryParseRequest(requestPayload, out var request) || +// request.OperationCode != OperationCode.Query || +// request.Questions.Count == 0) +// { +// return; +// } + +// var question = request.Questions.First(); +// if (question.Type != RecordType.A && question.Type != RecordType.AAAA) +// { +// return; +// } + +// var domain = question.Name; +// if (!reverseProxyConfig.IsMatch(question.Name.ToString())) +// { +// return; +// } + +// // DNS 响应数据 +// var response = Response.FromRequest(request); +// var loopback = question.Type == RecordType.A ? IPAddress.Loopback : IPAddress.IPv6Loopback; +// var record = new IPAddressResourceRecord(domain, loopback, ttl); +// response.AnswerRecords.Add(record); +// var responsePayload = response.ToArray(); + +// // 修改 payload 和包长 +// responsePayload.CopyTo(new Span(packet.PacketPayload, responsePayload.Length)); +// packetLength = (uint)((int)packetLength + responsePayload.Length - requestPayload.Length); + +// // 修改 IP 包 +// IPAddress destAddress; +// if (packet.IPv4Header != null) +// { +// destAddress = packet.IPv4Header->DstAddr; +// packet.IPv4Header->DstAddr = packet.IPv4Header->SrcAddr; +// packet.IPv4Header->SrcAddr = destAddress; +// packet.IPv4Header->Length = (ushort)packetLength; +// } +// else +// { +// destAddress = packet.IPv6Header->DstAddr; +// packet.IPv6Header->DstAddr = packet.IPv6Header->SrcAddr; +// packet.IPv6Header->SrcAddr = destAddress; +// packet.IPv6Header->Length = (ushort)(packetLength - sizeof(IPv6Header)); +// } + +// // 修改 UDP 包 +// (packet.UdpHeader->SrcPort, packet.UdpHeader->DstPort) = (packet.UdpHeader->DstPort, packet.UdpHeader->SrcPort); +// packet.UdpHeader->Length = (ushort)(sizeof(UdpHeader) + responsePayload.Length); + +// winDivertAddress.Impostor = true; +// winDivertAddress.Direction = winDivertAddress.Loopback +// ? WinDivertDirection.Outbound +// : WinDivertDirection.Inbound; + +// WinDivert.WinDivertHelperCalcChecksums(winDivertBuffer, packetLength, ref winDivertAddress, WinDivertChecksumHelperParam.All); + +// logger.LogInformation($"{domain} -> {loopback}"); +// } + +// static bool TryParseRequest(byte[] payload, [NotNullWhen(true)] out Request? request) +// { +// try +// { +// request = Request.FromArray(payload); +// return true; +// } +// catch (Exception) +// { +// request = null; +// return false; +// } +// } + +// private void Dispose(bool disposing) +// { +// if (!disposedValue) +// { +// if (disposing) +// { +// // TODO: 释放托管状态(托管对象) +// using var p = Process.Start(new ProcessStartInfo() +// { +// UseShellExecute = false, +// CreateNoWindow = true, +// FileName = "sc", +// Arguments = "stop WinDivert1.4", +// }); +// } + +// // TODO: 释放未托管的资源(未托管的对象)并重写终结器 +// // TODO: 将大型字段设置为 null +// disposedValue = true; +// } +// } + +// public void Dispose() +// { +// // 不要更改此代码。请将清理代码放入“Dispose(bool disposing)”方法中 +// Dispose(disposing: true); +// GC.SuppressFinalize(this); +// } +//} + +//#endif \ No newline at end of file diff --git a/src/BD.WTTS.Client.Plugins.Accelerator.ReverseProxy/Services.Implementation/PacketIntercept/GitInterceptor.cs b/src/BD.WTTS.Client.Plugins.Accelerator.ReverseProxy/Services.Implementation/PacketIntercept/GitInterceptor.cs index 517ef9a0661..5d4a7ed976c 100644 --- a/src/BD.WTTS.Client.Plugins.Accelerator.ReverseProxy/Services.Implementation/PacketIntercept/GitInterceptor.cs +++ b/src/BD.WTTS.Client.Plugins.Accelerator.ReverseProxy/Services.Implementation/PacketIntercept/GitInterceptor.cs @@ -1,21 +1,21 @@ -// https://github.com/dotnetcore/FastGithub/blob/2.1.4/FastGithub.PacketIntercept/Tcp/GitInterceptor.cs +//// https://github.com/dotnetcore/FastGithub/blob/2.1.4/FastGithub.PacketIntercept/Tcp/GitInterceptor.cs -#if WINDOWS +//#if WINDOWS -using static BD.WTTS.Models.Abstractions.IReverseProxyConfig; +//using static BD.WTTS.Models.Abstractions.IReverseProxyConfig; -// ReSharper disable once CheckNamespace -namespace BD.WTTS.Services.Implementation; +//// ReSharper disable once CheckNamespace +//namespace BD.WTTS.Services.Implementation; -/// -/// Git 拦截器 -/// -sealed class GitInterceptor : TcpInterceptor -{ - public GitInterceptor(ILogger logger) : base(GitHubDesktopPort, GitPort, logger) - { +///// +///// Git 拦截器 +///// +//sealed class GitInterceptor : TcpInterceptor +//{ +// public GitInterceptor(ILogger logger) : base(GitHubDesktopPort, GitPort, logger) +// { - } -} +// } +//} -#endif \ No newline at end of file +//#endif \ No newline at end of file diff --git a/src/BD.WTTS.Client.Plugins.Accelerator.ReverseProxy/Services.Implementation/PacketIntercept/HttpInterceptor.cs b/src/BD.WTTS.Client.Plugins.Accelerator.ReverseProxy/Services.Implementation/PacketIntercept/HttpInterceptor.cs index 3d3871a9116..bcadcbfc4f7 100644 --- a/src/BD.WTTS.Client.Plugins.Accelerator.ReverseProxy/Services.Implementation/PacketIntercept/HttpInterceptor.cs +++ b/src/BD.WTTS.Client.Plugins.Accelerator.ReverseProxy/Services.Implementation/PacketIntercept/HttpInterceptor.cs @@ -1,21 +1,21 @@ -// https://github.com/dotnetcore/FastGithub/blob/2.1.4/FastGithub.PacketIntercept/Tcp/HttpInterceptor.cs +//// https://github.com/dotnetcore/FastGithub/blob/2.1.4/FastGithub.PacketIntercept/Tcp/HttpInterceptor.cs -#if WINDOWS +//#if WINDOWS -using static BD.WTTS.Models.Abstractions.IReverseProxyConfig; +//using static BD.WTTS.Models.Abstractions.IReverseProxyConfig; -// ReSharper disable once CheckNamespace -namespace BD.WTTS.Services.Implementation; +//// ReSharper disable once CheckNamespace +//namespace BD.WTTS.Services.Implementation; -/// -/// Http 拦截器 -/// -sealed class HttpInterceptor : TcpInterceptor -{ - public HttpInterceptor(ILogger logger) : base(HttpPortDefault, HttpPort, logger) - { +///// +///// Http 拦截器 +///// +//sealed class HttpInterceptor : TcpInterceptor +//{ +// public HttpInterceptor(ILogger logger) : base(HttpPortDefault, HttpPort, logger) +// { - } -} +// } +//} -#endif \ No newline at end of file +//#endif \ No newline at end of file diff --git a/src/BD.WTTS.Client.Plugins.Accelerator.ReverseProxy/Services.Implementation/PacketIntercept/HttpsInterceptor.cs b/src/BD.WTTS.Client.Plugins.Accelerator.ReverseProxy/Services.Implementation/PacketIntercept/HttpsInterceptor.cs index 717dbb8bf89..1b0c000b1fd 100644 --- a/src/BD.WTTS.Client.Plugins.Accelerator.ReverseProxy/Services.Implementation/PacketIntercept/HttpsInterceptor.cs +++ b/src/BD.WTTS.Client.Plugins.Accelerator.ReverseProxy/Services.Implementation/PacketIntercept/HttpsInterceptor.cs @@ -1,21 +1,21 @@ -// https://github.com/dotnetcore/FastGithub/blob/2.1.4/FastGithub.PacketIntercept/Tcp/HttpsInterceptor.cs +//// https://github.com/dotnetcore/FastGithub/blob/2.1.4/FastGithub.PacketIntercept/Tcp/HttpsInterceptor.cs -#if WINDOWS +//#if WINDOWS -using static BD.WTTS.Models.Abstractions.IReverseProxyConfig; +//using static BD.WTTS.Models.Abstractions.IReverseProxyConfig; -// ReSharper disable once CheckNamespace -namespace BD.WTTS.Services.Implementation; +//// ReSharper disable once CheckNamespace +//namespace BD.WTTS.Services.Implementation; -/// -/// Https 拦截器 -/// -sealed class HttpsInterceptor : TcpInterceptor -{ - public HttpsInterceptor(ILogger logger) : base(HttpsPortDefault, HttpsPort, logger) - { +///// +///// Https 拦截器 +///// +//sealed class HttpsInterceptor : TcpInterceptor +//{ +// public HttpsInterceptor(ILogger logger) : base(HttpsPortDefault, HttpsPort, logger) +// { - } -} +// } +//} -#endif \ No newline at end of file +//#endif \ No newline at end of file diff --git a/src/BD.WTTS.Client.Plugins.Accelerator.ReverseProxy/Services.Implementation/PacketIntercept/SshInterceptor.cs b/src/BD.WTTS.Client.Plugins.Accelerator.ReverseProxy/Services.Implementation/PacketIntercept/SshInterceptor.cs index b1ae83075bf..cacdcdc5028 100644 --- a/src/BD.WTTS.Client.Plugins.Accelerator.ReverseProxy/Services.Implementation/PacketIntercept/SshInterceptor.cs +++ b/src/BD.WTTS.Client.Plugins.Accelerator.ReverseProxy/Services.Implementation/PacketIntercept/SshInterceptor.cs @@ -1,20 +1,20 @@ -// https://github.com/dotnetcore/FastGithub/blob/2.1.4/FastGithub.PacketIntercept/Tcp/SshInterceptor.cs +//// https://github.com/dotnetcore/FastGithub/blob/2.1.4/FastGithub.PacketIntercept/Tcp/SshInterceptor.cs -#if WINDOWS +//#if WINDOWS -using static BD.WTTS.Models.Abstractions.IReverseProxyConfig; +//using static BD.WTTS.Models.Abstractions.IReverseProxyConfig; -// ReSharper disable once CheckNamespace -namespace BD.WTTS.Services.Implementation; +//// ReSharper disable once CheckNamespace +//namespace BD.WTTS.Services.Implementation; -/// -/// SSH 拦截器 -/// -sealed class SshInterceptor : TcpInterceptor -{ - public SshInterceptor(ILogger logger) : base(SshPortDefault, SshPort, logger) - { +///// +///// SSH 拦截器 +///// +//sealed class SshInterceptor : TcpInterceptor +//{ +// public SshInterceptor(ILogger logger) : base(SshPortDefault, SshPort, logger) +// { - } -} -#endif \ No newline at end of file +// } +//} +//#endif \ No newline at end of file diff --git a/src/BD.WTTS.Client.Plugins.Accelerator.ReverseProxy/Services.Implementation/PacketIntercept/TcpInterceptHostedService.cs b/src/BD.WTTS.Client.Plugins.Accelerator.ReverseProxy/Services.Implementation/PacketIntercept/TcpInterceptHostedService.cs index 3c7293700a9..38b677e0f22 100644 --- a/src/BD.WTTS.Client.Plugins.Accelerator.ReverseProxy/Services.Implementation/PacketIntercept/TcpInterceptHostedService.cs +++ b/src/BD.WTTS.Client.Plugins.Accelerator.ReverseProxy/Services.Implementation/PacketIntercept/TcpInterceptHostedService.cs @@ -1,22 +1,22 @@ -// https://github.com/dotnetcore/FastGithub/blob/2.1.4/FastGithub.PacketIntercept/TcpInterceptHostedService.cs +//// https://github.com/dotnetcore/FastGithub/blob/2.1.4/FastGithub.PacketIntercept/TcpInterceptHostedService.cs -#if WINDOWS +//#if WINDOWS -using static BD.WTTS.Models.Abstractions.IReverseProxyConfig; +//using static BD.WTTS.Models.Abstractions.IReverseProxyConfig; -// ReSharper disable once CheckNamespace -namespace BD.WTTS.Services.Implementation; +//// ReSharper disable once CheckNamespace +//namespace BD.WTTS.Services.Implementation; -/// -/// TCP 拦截后台服务 -/// -sealed class TcpInterceptHostedService : InterceptHostedService -{ - public TcpInterceptHostedService( - IEnumerable tcpInterceptors, - ILogger logger, - IReverseProxyConfig reverseProxyConfig) : base(new Interceptors(tcpInterceptors), logger, reverseProxyConfig) - { - } -} -#endif \ No newline at end of file +///// +///// TCP 拦截后台服务 +///// +//sealed class TcpInterceptHostedService : InterceptHostedService +//{ +// public TcpInterceptHostedService( +// IEnumerable tcpInterceptors, +// ILogger logger, +// IReverseProxyConfig reverseProxyConfig) : base(new Interceptors(tcpInterceptors), logger, reverseProxyConfig) +// { +// } +//} +//#endif \ No newline at end of file diff --git a/src/BD.WTTS.Client.Plugins.Accelerator.ReverseProxy/Services.Implementation/PacketIntercept/TcpInterceptor.cs b/src/BD.WTTS.Client.Plugins.Accelerator.ReverseProxy/Services.Implementation/PacketIntercept/TcpInterceptor.cs index 06af034edb7..5276546930d 100644 --- a/src/BD.WTTS.Client.Plugins.Accelerator.ReverseProxy/Services.Implementation/PacketIntercept/TcpInterceptor.cs +++ b/src/BD.WTTS.Client.Plugins.Accelerator.ReverseProxy/Services.Implementation/PacketIntercept/TcpInterceptor.cs @@ -1,115 +1,115 @@ -// https://github.com/dotnetcore/FastGithub/blob/2.1.4/FastGithub.PacketIntercept/Tcp/TcpInterceptor.cs +//// https://github.com/dotnetcore/FastGithub/blob/2.1.4/FastGithub.PacketIntercept/Tcp/TcpInterceptor.cs -#if WINDOWS +//#if WINDOWS -using WinDivertSharp; +//using WinDivertSharp; -// ReSharper disable once CheckNamespace -namespace BD.WTTS.Services.Implementation; +//// ReSharper disable once CheckNamespace +//namespace BD.WTTS.Services.Implementation; -/// -abstract class TcpInterceptor : ITcpInterceptor -{ - readonly string filter; - readonly ushort oldServerPort; - readonly ushort newServerPort; - readonly ILogger logger; +///// +//abstract class TcpInterceptor : ITcpInterceptor +//{ +// readonly string filter; +// readonly ushort oldServerPort; +// readonly ushort newServerPort; +// readonly ILogger logger; - public TcpInterceptor(int oldServerPort, int newServerPort, ILogger logger) - { - filter = $"loopback and (tcp.DstPort == {oldServerPort} or tcp.SrcPort == {newServerPort})"; - this.oldServerPort = (ushort)oldServerPort; - this.newServerPort = (ushort)newServerPort; - this.logger = logger; - } +// public TcpInterceptor(int oldServerPort, int newServerPort, ILogger logger) +// { +// filter = $"loopback and (tcp.DstPort == {oldServerPort} or tcp.SrcPort == {newServerPort})"; +// this.oldServerPort = (ushort)oldServerPort; +// this.newServerPort = (ushort)newServerPort; +// this.logger = logger; +// } - /// - /// 拦截指定端口的数据包 - /// - /// - /// - /// - public async Task InterceptAsync(CancellationToken cancellationToken) - { - if (oldServerPort == newServerPort) - { - return; - } +// /// +// /// 拦截指定端口的数据包 +// /// +// /// +// /// +// /// +// public async Task InterceptAsync(CancellationToken cancellationToken) +// { +// if (oldServerPort == newServerPort) +// { +// return; +// } - await Task.Yield(); +// await Task.Yield(); - var handle = WinDivert.WinDivertOpen(filter, WinDivertLayer.Network, 0, WinDivertOpenFlags.None); - if (handle == new IntPtr(unchecked((long)ulong.MaxValue))) - { - throw new Win32Exception(); - } +// var handle = WinDivert.WinDivertOpen(filter, WinDivertLayer.Network, 0, WinDivertOpenFlags.None); +// if (handle == new IntPtr(unchecked((long)ulong.MaxValue))) +// { +// throw new Win32Exception(); +// } - if (Socket.OSSupportsIPv4) - { - logger.LogInformation($"{IPAddress.Loopback}:{oldServerPort} <=> {IPAddress.Loopback}:{newServerPort}"); - } - if (Socket.OSSupportsIPv6) - { - logger.LogInformation($"{IPAddress.IPv6Loopback}:{oldServerPort} <=> {IPAddress.IPv6Loopback}:{newServerPort}"); - } - cancellationToken.Register(hwnd => WinDivert.WinDivertClose((IntPtr)hwnd!), handle); +// if (Socket.OSSupportsIPv4) +// { +// logger.LogInformation($"{IPAddress.Loopback}:{oldServerPort} <=> {IPAddress.Loopback}:{newServerPort}"); +// } +// if (Socket.OSSupportsIPv6) +// { +// logger.LogInformation($"{IPAddress.IPv6Loopback}:{oldServerPort} <=> {IPAddress.IPv6Loopback}:{newServerPort}"); +// } +// cancellationToken.Register(hwnd => WinDivert.WinDivertClose((IntPtr)hwnd!), handle); - var packetLength = 0U; - using WinDivertBuffer winDivertBuffer = new(); - WinDivertAddress winDivertAddress = default; +// var packetLength = 0U; +// using WinDivertBuffer winDivertBuffer = new(); +// WinDivertAddress winDivertAddress = default; - while (!cancellationToken.IsCancellationRequested) - { - winDivertAddress.Reset(); - if (WinDivert.WinDivertRecv(handle, winDivertBuffer, ref winDivertAddress, ref packetLength) == false) - { - throw new Win32Exception(); - } +// while (!cancellationToken.IsCancellationRequested) +// { +// winDivertAddress.Reset(); +// if (WinDivert.WinDivertRecv(handle, winDivertBuffer, ref winDivertAddress, ref packetLength) == false) +// { +// throw new Win32Exception(); +// } - try - { - ModifyTcpPacket(winDivertBuffer, ref winDivertAddress, ref packetLength); - } - catch (Exception ex) - { - logger.LogWarning(ex.Message); - } - finally - { - WinDivert.WinDivertSend(handle, winDivertBuffer, packetLength, ref winDivertAddress); - } - } - } +// try +// { +// ModifyTcpPacket(winDivertBuffer, ref winDivertAddress, ref packetLength); +// } +// catch (Exception ex) +// { +// logger.LogWarning(ex.Message); +// } +// finally +// { +// WinDivert.WinDivertSend(handle, winDivertBuffer, packetLength, ref winDivertAddress); +// } +// } +// } - /// - /// 修改 TCP 数据端口的端口 - /// - /// - /// - /// - unsafe void ModifyTcpPacket(WinDivertBuffer winDivertBuffer, ref WinDivertAddress winDivertAddress, ref uint packetLength) - { - var packet = WinDivert.WinDivertHelperParsePacket(winDivertBuffer, packetLength); - if (packet.IPv4Header != null && packet.IPv4Header->SrcAddr.Equals(IPAddress.Loopback) == false) - { - return; - } - if (packet.IPv6Header != null && packet.IPv6Header->SrcAddr.Equals(IPAddress.IPv6Loopback) == false) - { - return; - } +// /// +// /// 修改 TCP 数据端口的端口 +// /// +// /// +// /// +// /// +// unsafe void ModifyTcpPacket(WinDivertBuffer winDivertBuffer, ref WinDivertAddress winDivertAddress, ref uint packetLength) +// { +// var packet = WinDivert.WinDivertHelperParsePacket(winDivertBuffer, packetLength); +// if (packet.IPv4Header != null && packet.IPv4Header->SrcAddr.Equals(IPAddress.Loopback) == false) +// { +// return; +// } +// if (packet.IPv6Header != null && packet.IPv6Header->SrcAddr.Equals(IPAddress.IPv6Loopback) == false) +// { +// return; +// } - if (packet.TcpHeader->DstPort == oldServerPort) - { - packet.TcpHeader->DstPort = newServerPort; - } - else - { - packet.TcpHeader->SrcPort = oldServerPort; - } - winDivertAddress.Impostor = true; - WinDivert.WinDivertHelperCalcChecksums(winDivertBuffer, packetLength, ref winDivertAddress, WinDivertChecksumHelperParam.All); - } -} +// if (packet.TcpHeader->DstPort == oldServerPort) +// { +// packet.TcpHeader->DstPort = newServerPort; +// } +// else +// { +// packet.TcpHeader->SrcPort = oldServerPort; +// } +// winDivertAddress.Impostor = true; +// WinDivert.WinDivertHelperCalcChecksums(winDivertBuffer, packetLength, ref winDivertAddress, WinDivertChecksumHelperParam.All); +// } +//} -#endif \ No newline at end of file +//#endif \ No newline at end of file diff --git a/src/BD.WTTS.Client.Plugins.Accelerator.ReverseProxy/Services.Implementation/YarpReverseProxyServiceImpl.Startup.cs b/src/BD.WTTS.Client.Plugins.Accelerator.ReverseProxy/Services.Implementation/YarpReverseProxyServiceImpl.Startup.cs index b12c6b76d03..ac9871570fd 100644 --- a/src/BD.WTTS.Client.Plugins.Accelerator.ReverseProxy/Services.Implementation/YarpReverseProxyServiceImpl.Startup.cs +++ b/src/BD.WTTS.Client.Plugins.Accelerator.ReverseProxy/Services.Implementation/YarpReverseProxyServiceImpl.Startup.cs @@ -23,12 +23,12 @@ void StartupConfigureServices(IServiceCollection services) services.AddReverseProxyServer(); services.AddFlowAnalyze(); -#if WINDOWS - if (ProxyMode == ProxyMode.DNSIntercept) - { - services.AddPacketIntercept(); - } -#endif + //#if WINDOWS + // if (ProxyMode == ProxyMode.DNSIntercept) + // { + // services.AddPacketIntercept(); + // } + //#endif // !!! 不可将 IPCSubProcessService ipc 添加到 YarpHost 的 DI 容器中,因停止加速时执行释放会导致进程退出 //services.AddSingleton(_ => ipc); diff --git a/src/BD.WTTS.Client.Plugins.Accelerator/BD.WTTS.Client.Plugins.Accelerator.csproj b/src/BD.WTTS.Client.Plugins.Accelerator/BD.WTTS.Client.Plugins.Accelerator.csproj index e451ccba342..04237a6f05a 100644 --- a/src/BD.WTTS.Client.Plugins.Accelerator/BD.WTTS.Client.Plugins.Accelerator.csproj +++ b/src/BD.WTTS.Client.Plugins.Accelerator/BD.WTTS.Client.Plugins.Accelerator.csproj @@ -124,7 +124,7 @@ - + - + diff --git a/src/BD.WTTS.Client.Plugins.Accelerator/Helpers/WinDivertInitHelper.cs b/src/BD.WTTS.Client.Plugins.Accelerator/Helpers/WinDivertInitHelper.cs index 5b9fd1f1c16..eaac47b3be7 100644 --- a/src/BD.WTTS.Client.Plugins.Accelerator/Helpers/WinDivertInitHelper.cs +++ b/src/BD.WTTS.Client.Plugins.Accelerator/Helpers/WinDivertInitHelper.cs @@ -1,152 +1,152 @@ -#if WINDOWS -using WinDivertBinRes = BD.WTTS.Properties.WinDivertResource; +//#if WINDOWS +//using WinDivertBinRes = BD.WTTS.Properties.WinDivertResource; -namespace Mobius.Helpers; +//namespace Mobius.Helpers; -/// -/// 初始化 WinDivert 助手类 -/// -static class WinDivertInitHelper -{ - const string libraryName = "WinDivert.dll"; +///// +///// 初始化 WinDivert 助手类 +///// +//static class WinDivertInitHelper +//{ +// const string libraryName = "WinDivert.dll"; - static readonly string? libraryPath; - static readonly string? libraryDirPath; - //static nint libraryIntPtr; +// static readonly string? libraryPath; +// static readonly string? libraryDirPath; +// //static nint libraryIntPtr; - ///// - ///// 配置本机库路径解析 - ///// - ///// - ///// - ///// - ///// - //public static nint DllImportResolver(string libraryName, - // Assembly assembly, - // DllImportSearchPath? searchPath) - //{ - // switch (libraryName) - // { - // case WinDivertInitHelper.libraryName: - // if (libraryIntPtr != default) - // return libraryIntPtr; - // break; - // } - // return default; - //} +// ///// +// ///// 配置本机库路径解析 +// ///// +// ///// +// ///// +// ///// +// ///// +// //public static nint DllImportResolver(string libraryName, +// // Assembly assembly, +// // DllImportSearchPath? searchPath) +// //{ +// // switch (libraryName) +// // { +// // case WinDivertInitHelper.libraryName: +// // if (libraryIntPtr != default) +// // return libraryIntPtr; +// // break; +// // } +// // return default; +// //} - static bool isInitialize = false; +// static bool isInitialize = false; - /// - /// 初始化 WinDivert - /// - public static async Task InitializeAsync() - { - (byte[] WinDivert_dll, byte[] WinDivert64_sys) data = default; +// /// +// /// 初始化 WinDivert +// /// +// public static async Task InitializeAsync() +// { +// (byte[] WinDivert_dll, byte[] WinDivert64_sys) data = default; - void GetData() - { - if (data != default) - data = GetWinDivertBinRes(); - } +// void GetData() +// { +// if (data != default) +// data = GetWinDivertBinRes(); +// } - if (libraryPath != null && libraryDirPath != null) - { - bool isWrite; - var libraryFileInfo = new FileInfo(libraryPath); - if (libraryFileInfo.Exists) - { - if (libraryFileInfo.Length > 20000000L) // 文件不可能大于 20 MB - { - libraryFileInfo.Delete(); - isWrite = true; - } - else - { - GetData(); - var libraryBytes = await File.ReadAllBytesAsync(libraryPath); - var libraryHash = SHA256.HashData(libraryBytes); - var libraryHashRes = SHA256.HashData(data.WinDivert_dll!); - if (libraryHash.SequenceEqual(libraryHashRes)) // 哈希值相同,不写入 - { - isWrite = false; - } - else - { - libraryFileInfo.Delete(); - isWrite = true; - } - } - } - else - { - isWrite = true; - } +// if (libraryPath != null && libraryDirPath != null) +// { +// bool isWrite; +// var libraryFileInfo = new FileInfo(libraryPath); +// if (libraryFileInfo.Exists) +// { +// if (libraryFileInfo.Length > 20000000L) // 文件不可能大于 20 MB +// { +// libraryFileInfo.Delete(); +// isWrite = true; +// } +// else +// { +// GetData(); +// var libraryBytes = await File.ReadAllBytesAsync(libraryPath); +// var libraryHash = SHA256.HashData(libraryBytes); +// var libraryHashRes = SHA256.HashData(data.WinDivert_dll!); +// if (libraryHash.SequenceEqual(libraryHashRes)) // 哈希值相同,不写入 +// { +// isWrite = false; +// } +// else +// { +// libraryFileInfo.Delete(); +// isWrite = true; +// } +// } +// } +// else +// { +// isWrite = true; +// } - if (isWrite) // 检查文件不存在时写入 - { - GetData(); - switch (RuntimeInformation.ProcessArchitecture) - { - //case Architecture.X86: - // break; - case Architecture.X64: - IOPath.DirCreateByNotExists(libraryDirPath); - var task1 = File.WriteAllBytesAsync(Path.Combine(libraryDirPath, "WinDivert64.sys"), data.WinDivert64_sys!); - var task2 = File.WriteAllBytesAsync(libraryPath, data.WinDivert_dll!); - await Task.WhenAll(task1, task2); - break; - } - } - } +// if (isWrite) // 检查文件不存在时写入 +// { +// GetData(); +// switch (RuntimeInformation.ProcessArchitecture) +// { +// //case Architecture.X86: +// // break; +// case Architecture.X64: +// IOPath.DirCreateByNotExists(libraryDirPath); +// var task1 = File.WriteAllBytesAsync(Path.Combine(libraryDirPath, "WinDivert64.sys"), data.WinDivert64_sys!); +// var task2 = File.WriteAllBytesAsync(libraryPath, data.WinDivert_dll!); +// await Task.WhenAll(task1, task2); +// break; +// } +// } +// } - if (isInitialize) - return; - isInitialize = true; - //if (IsSupported && libraryPath != null) - //{ - // try - // { - // libraryIntPtr = NativeLibrary.Load(libraryPath); - // } - // catch - // { - // } - // if (libraryIntPtr != default) - // { - // NativeLibrary.SetDllImportResolver(typeof(WinDivertSharp.WinDivert).Assembly, DllImportResolver); - // return; - // } - //} - IsSupported = false; - } +// if (isInitialize) +// return; +// isInitialize = true; +// //if (IsSupported && libraryPath != null) +// //{ +// // try +// // { +// // libraryIntPtr = NativeLibrary.Load(libraryPath); +// // } +// // catch +// // { +// // } +// // if (libraryIntPtr != default) +// // { +// // NativeLibrary.SetDllImportResolver(typeof(WinDivertSharp.WinDivert).Assembly, DllImportResolver); +// // return; +// // } +// //} +// IsSupported = false; +// } - /// - /// 当前运行环境是否支持使用 WinDivert - /// - public static bool IsSupported { get; private set; } +// /// +// /// 当前运行环境是否支持使用 WinDivert +// /// +// public static bool IsSupported { get; private set; } - static WinDivertInitHelper() - { - switch (RuntimeInformation.OSArchitecture) - { - //case Architecture.X86: - case Architecture.X64: - IsSupported = true; - libraryPath = GlobalDllImportResolver.GetLibraryPath("WinDivert.dll"); - libraryDirPath = Path.GetDirectoryName(libraryPath); - break; - } - } +// static WinDivertInitHelper() +// { +// switch (RuntimeInformation.OSArchitecture) +// { +// //case Architecture.X86: +// case Architecture.X64: +// IsSupported = true; +// libraryPath = GlobalDllImportResolver.GetLibraryPath("WinDivert.dll"); +// libraryDirPath = Path.GetDirectoryName(libraryPath); +// break; +// } +// } - static (byte[] WinDivert_dll, byte[] WinDivert64_sys) GetWinDivertBinRes() - { - byte[] bytes = WinDivertBinRes.WinDivert_mpo; - bytes.AsSpan().Reverse(); +// static (byte[] WinDivert_dll, byte[] WinDivert64_sys) GetWinDivertBinRes() +// { +// byte[] bytes = WinDivertBinRes.WinDivert_mpo; +// bytes.AsSpan().Reverse(); - var data = MemoryPackSerializer.Deserialize(bytes)!; +// var data = MemoryPackSerializer.Deserialize(bytes)!; - return (data[0], data[1]); - } -} -#endif \ No newline at end of file +// return (data[0], data[1]); +// } +//} +//#endif \ No newline at end of file diff --git a/src/BD.WTTS.Client.Plugins.Accelerator/Services/Mvvm/ProxyService.Operate.cs b/src/BD.WTTS.Client.Plugins.Accelerator/Services/Mvvm/ProxyService.Operate.cs index a790bf1b942..ec719bc736d 100644 --- a/src/BD.WTTS.Client.Plugins.Accelerator/Services/Mvvm/ProxyService.Operate.cs +++ b/src/BD.WTTS.Client.Plugins.Accelerator/Services/Mvvm/ProxyService.Operate.cs @@ -120,6 +120,7 @@ await EnableProxyScripts.ContinueWith(e => switch (proxyMode) { + case ProxyMode.DNSIntercept: case ProxyMode.Hosts: var inUsePort = SocketHelper.IsUsePort(proxyIp_.Value, httpsPort); if (inUsePort) @@ -186,13 +187,13 @@ await EnableProxyScripts.ContinueWith(e => return Strings.CommunityFix_SetAsSystemPACProxyFail; } break; -#if WINDOWS - case ProxyMode.DNSIntercept: - { - await Mobius.Helpers.WinDivertInitHelper.InitializeAsync(); - } - break; -#endif + //#if WINDOWS + // case ProxyMode.DNSIntercept: + // { + // await Mobius.Helpers.WinDivertInitHelper.InitializeAsync(); + // } + // break; + //#endif } if (!OperatingSystem.IsWindows()) @@ -315,6 +316,7 @@ async Task StopProxyServiceCoreAsync(bool isExit) #endif switch (proxyMode) // 先停止接入代理流量 { + case ProxyMode.DNSIntercept: case ProxyMode.Hosts: var needClear = hostsFileService.ContainsHostsByTag(); if (needClear) @@ -351,14 +353,14 @@ async Task StopProxyServiceCoreAsync(bool isExit) await platformService.SetAsSystemPACProxyAsync(false); } break; -#if WINDOWS - case ProxyMode.DNSIntercept: - { - // 停止时也调用初始化 - await Mobius.Helpers.WinDivertInitHelper.InitializeAsync(); - } - break; -#endif + //#if WINDOWS + // case ProxyMode.DNSIntercept: + // { + // // 停止时也调用初始化 + // await Mobius.Helpers.WinDivertInitHelper.InitializeAsync(); + // } + // break; + //#endif } StopTimer(); // 停止 UI 计时器 #if MACOS diff --git a/src/BD.WTTS.Client.Plugins.Accelerator/Settings/ProxySettings.ProxyMode.cs b/src/BD.WTTS.Client.Plugins.Accelerator/Settings/ProxySettings.ProxyMode.cs index ad566038c9c..21d7171a64e 100644 --- a/src/BD.WTTS.Client.Plugins.Accelerator/Settings/ProxySettings.ProxyMode.cs +++ b/src/BD.WTTS.Client.Plugins.Accelerator/Settings/ProxySettings.ProxyMode.cs @@ -11,7 +11,7 @@ static IEnumerable GetProxyModes() { #if WINDOWS yield return EProxyMode.Hosts; - yield return EProxyMode.DNSIntercept; + //yield return EProxyMode.DNSIntercept; yield return EProxyMode.PAC; yield return EProxyMode.System; #elif ANDROID