diff --git a/FastTunnel.Api/FastTunnel.Api.csproj b/FastTunnel.Api/FastTunnel.Api.csproj index e1b27c2..cbebee6 100644 --- a/FastTunnel.Api/FastTunnel.Api.csproj +++ b/FastTunnel.Api/FastTunnel.Api.csproj @@ -1,7 +1,7 @@  - 1.0.0 + 1.0.1 https://github.com/FastTunnel/FastTunnel/tree/v2/FastTunnel.Api https://github.com/FastTunnel/FastTunnel/tree/v2/FastTunnel.Api diff --git a/FastTunnel.Core/Extensions/ServicesExtensions.cs b/FastTunnel.Core/Extensions/ServicesExtensions.cs index dc04488..55f90ca 100644 --- a/FastTunnel.Core/Extensions/ServicesExtensions.cs +++ b/FastTunnel.Core/Extensions/ServicesExtensions.cs @@ -39,7 +39,6 @@ namespace FastTunnel.Core services.AddTransient() .AddSingleton() .AddSingleton() - .AddTransient() .AddSingleton(); services.AddHostedService(); @@ -57,7 +56,7 @@ namespace FastTunnel.Core services.Configure(configurationSection) .AddSingleton() .AddTransient() - .AddTransient() + .AddSingleton() .AddSingleton() .AddSingleton() .AddSingleton(); diff --git a/FastTunnel.Core/FastTunnel.Core.csproj b/FastTunnel.Core/FastTunnel.Core.csproj index c21cefd..8d4089f 100644 --- a/FastTunnel.Core/FastTunnel.Core.csproj +++ b/FastTunnel.Core/FastTunnel.Core.csproj @@ -30,6 +30,7 @@ + diff --git a/FastTunnel.Core/Forwarder/MiddleWare/FastTunnelClientHandler.cs b/FastTunnel.Core/Forwarder/MiddleWare/FastTunnelClientHandler.cs index 306fc85..10d3a9d 100644 --- a/FastTunnel.Core/Forwarder/MiddleWare/FastTunnelClientHandler.cs +++ b/FastTunnel.Core/Forwarder/MiddleWare/FastTunnelClientHandler.cs @@ -25,11 +25,13 @@ namespace FastTunnel.Core.MiddleWares ILogger logger; FastTunnelServer fastTunnelServer; Version serverVersion; + TunnelClientHandler tunnelClient; - public FastTunnelClientHandler(ILogger logger, FastTunnelServer fastTunnelServer) + public FastTunnelClientHandler(ILogger logger, FastTunnelServer fastTunnelServer, TunnelClientHandler tunnelClient) { this.logger = logger; this.fastTunnelServer = fastTunnelServer; + this.tunnelClient = tunnelClient; serverVersion = System.Reflection.Assembly.GetExecutingAssembly().GetName().Version; } @@ -48,7 +50,6 @@ namespace FastTunnel.Core.MiddleWares private async Task handleClient(HttpContext context, Func next, string clientVersion) { using var webSocket = await context.WebSockets.AcceptWebSocketAsync(); - var tunnelClient = context.RequestServices.GetRequiredService().SetSocket(webSocket); if (Version.Parse(clientVersion).Major != serverVersion.Major) { @@ -66,7 +67,7 @@ namespace FastTunnel.Core.MiddleWares { Interlocked.Increment(ref fastTunnelServer.ConnectedClientCount); logger.LogInformation($"客户端连接 {context.TraceIdentifier}:{context.Connection.RemoteIpAddress} 当前在线数:{fastTunnelServer.ConnectedClientCount}"); - await tunnelClient.ReviceAsync(CancellationToken.None); + await tunnelClient.ReviceAsync(webSocket, CancellationToken.None); logOut(context); } diff --git a/FastTunnel.Core/Forwarder/MiddleWare/FastTunnelSwapHandler.cs b/FastTunnel.Core/Forwarder/MiddleWare/FastTunnelSwapHandler.cs index 1dd289d..256090e 100644 --- a/FastTunnel.Core/Forwarder/MiddleWare/FastTunnelSwapHandler.cs +++ b/FastTunnel.Core/Forwarder/MiddleWare/FastTunnelSwapHandler.cs @@ -31,9 +31,11 @@ namespace FastTunnel.Core.Forwarder.MiddleWare } var requestId = context.Request.Path.Value.Trim('/'); + logger.LogError($"[PROXY]:Start {requestId}"); + if (!fastTunnelServer.ResponseTasks.TryRemove(requestId, out var responseAwaiter)) { - logger.LogError($"requestId不存在:{requestId}"); + logger.LogError($"[PROXY]:RequestId不存在 {requestId}"); return; }; @@ -50,9 +52,13 @@ namespace FastTunnel.Core.Forwarder.MiddleWare responseAwaiter.TrySetResult(reverseConnection); var closedAwaiter = new TaskCompletionSource(); - lifetime.ConnectionClosed.Register((task) => { (task as TaskCompletionSource).SetResult(null); }, closedAwaiter); + lifetime.ConnectionClosed.Register((task) => + { + (task as TaskCompletionSource).SetResult(null); + }, closedAwaiter); await closedAwaiter.Task; + logger.LogError($"[PROXY]:Closed {requestId}"); } } } diff --git a/FastTunnel.Core/Handlers/Client/SwapHandler.cs b/FastTunnel.Core/Handlers/Client/SwapHandler.cs index 60e7cae..38b0e3f 100644 --- a/FastTunnel.Core/Handlers/Client/SwapHandler.cs +++ b/FastTunnel.Core/Handlers/Client/SwapHandler.cs @@ -54,17 +54,14 @@ namespace FastTunnel.Core.Handlers.Client private async Task createLocal(string requestId, string localhost, CancellationToken cancellationToken) { - var localConnecter = new DnsSocket(localhost.Split(":")[0], int.Parse(localhost.Split(":")[1])); - await localConnecter.ConnectAsync(); - - return new NetworkStream(localConnecter.Socket, true); + var socket = await DnsSocketFactory.ConnectAsync(localhost.Split(":")[0], int.Parse(localhost.Split(":")[1])); + return new NetworkStream(socket, true); } private async Task createRemote(string requestId, FastTunnelClient cleint, CancellationToken cancellationToken) { - var connecter = new DnsSocket(cleint.Server.ServerAddr, cleint.Server.ServerPort); - await connecter.ConnectAsync(); - Stream serverStream = new NetworkStream(connecter.Socket, true); + var socket = await DnsSocketFactory.ConnectAsync(cleint.Server.ServerAddr, cleint.Server.ServerPort); + Stream serverStream = new NetworkStream(socket, true); if (cleint.Server.Protocol == "wss") { var sslStream = new SslStream(serverStream, false, delegate { return true; }); diff --git a/FastTunnel.Core/Models/TunnelClient.cs b/FastTunnel.Core/Models/TunnelClientHandler.cs similarity index 82% rename from FastTunnel.Core/Models/TunnelClient.cs rename to FastTunnel.Core/Models/TunnelClientHandler.cs index c44af25..1ef35b6 100644 --- a/FastTunnel.Core/Models/TunnelClient.cs +++ b/FastTunnel.Core/Models/TunnelClientHandler.cs @@ -17,27 +17,20 @@ using Yarp.ReverseProxy.Configuration; namespace FastTunnel.Core.Models { - public class TunnelClient + public class TunnelClientHandler { readonly ILoginHandler _loginHandler; FastTunnelServer fastTunnelServer; ILogger logger; - WebSocket webSocket; - public TunnelClient(ILogger logger, FastTunnelServer fastTunnelServer, ILoginHandler loginHandler) + public TunnelClientHandler(ILogger logger, FastTunnelServer fastTunnelServer, ILoginHandler loginHandler) { this.logger = logger; this.fastTunnelServer = fastTunnelServer; this._loginHandler = loginHandler; } - public TunnelClient SetSocket(WebSocket webSocket) - { - this.webSocket = webSocket; - return this; - } - - public async Task ReviceAsync(CancellationToken cancellationToken) + public async Task ReviceAsync(WebSocket webSocket, CancellationToken cancellationToken) { var buffer = new byte[FastTunnelConst.MAX_CMD_LENGTH]; var tunnelProtocol = new TunnelProtocol(); diff --git a/FastTunnel.Core/Sockets/DnsSocket.cs b/FastTunnel.Core/Sockets/DnsSocket.cs deleted file mode 100644 index 0ea01fe..0000000 --- a/FastTunnel.Core/Sockets/DnsSocket.cs +++ /dev/null @@ -1,34 +0,0 @@ -using FastTunnel.Core.Extensions; -using FastTunnel.Core.Models; -using System; -using System.Collections.Generic; -using System.Net; -using System.Net.Sockets; -using System.Text; -using System.Threading.Tasks; - -namespace FastTunnel.Core.Sockets -{ - public class DnsSocket - { - private string _host; - private int _port; - - public Socket Socket { get; } - - public DnsSocket(string host, int port) - { - this._host = host; - this._port = port; - - Socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp); - Socket.NoDelay = true; - } - - public async Task ConnectAsync() - { - DnsEndPoint dnsEndPoint = new DnsEndPoint(_host, _port); - await Socket.ConnectAsync(dnsEndPoint); - } - } -} diff --git a/FastTunnel.Core/Sockets/DnsSocketFactory.cs b/FastTunnel.Core/Sockets/DnsSocketFactory.cs new file mode 100644 index 0000000..c00f374 --- /dev/null +++ b/FastTunnel.Core/Sockets/DnsSocketFactory.cs @@ -0,0 +1,22 @@ +using FastTunnel.Core.Extensions; +using FastTunnel.Core.Models; +using System; +using System.Collections.Generic; +using System.Net; +using System.Net.Sockets; +using System.Text; +using System.Threading.Tasks; + +namespace FastTunnel.Core.Sockets +{ + public class DnsSocketFactory + { + public static async Task ConnectAsync(string host, int port) + { + var Socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp); + DnsEndPoint dnsEndPoint = new DnsEndPoint(host, port); + await Socket.ConnectAsync(dnsEndPoint); + return Socket; + } + } +} diff --git a/FastTunnel.Core/Sockets/SocketSwap.cs b/FastTunnel.Core/Sockets/SocketSwap.cs deleted file mode 100644 index 6beb7c5..0000000 --- a/FastTunnel.Core/Sockets/SocketSwap.cs +++ /dev/null @@ -1,143 +0,0 @@ -using FastTunnel.Core.Dispatchers; -using FastTunnel.Core.Utility.Extensions; -using Microsoft.Extensions.Logging; -using System; -using System.Buffers; -using System.Collections.Generic; -using System.Diagnostics; -using System.Net.Sockets; -using System.Text; -using System.Threading; -using System.Threading.Tasks; - -namespace FastTunnel.Core.Sockets -{ - public class SocketSwap - { - private readonly Socket m_sockt1; - private readonly Socket m_sockt2; - private readonly string m_msgId = null; - private readonly ILogger m_logger; - - private bool swapeStarted = false; - - private class Channel - { - public Socket Send { get; set; } - - public Socket Receive { get; set; } - } - - public SocketSwap(Socket sockt1, Socket sockt2, ILogger logger, string msgId) - { - //sockt1.NoDelay = true; - //sockt2.NoDelay = true; - m_sockt1 = sockt1; - m_sockt2 = sockt2; - m_msgId = msgId; - m_logger = logger; - } - - public void StartSwap() - { - m_logger?.LogDebug($"[StartSwapStart] {m_msgId}"); - swapeStarted = true; - - ThreadPool.QueueUserWorkItem(swapCallback, new Channel - { - Send = m_sockt1, - Receive = m_sockt2 - }); - - ThreadPool.QueueUserWorkItem(swapCallback, new Channel - { - Send = m_sockt2, - Receive = m_sockt1 - }); - - m_logger?.LogDebug($"[StartSwapEnd] {m_msgId}"); - } - - private void swapCallback(object state) - { - m_logger?.LogDebug($"swapCallback {m_msgId}"); - var chanel = state as Channel; - byte[] result = new byte[512]; - - while (true) - { - int num; - - try - { - try - { - num = chanel.Receive.Receive(result, 0, result.Length, SocketFlags.None); - } - catch (Exception) - { - closeSocket("Revice Fail"); - break; - } - - if (num == 0) - { - closeSocket("Normal Close"); - break; - } - - try - { - chanel.Send.Send(result, 0, num, SocketFlags.None); - } - catch (Exception) - { - closeSocket("Send Fail"); - break; - } - } - catch (Exception ex) - { - m_logger.LogCritical(ex, "致命异常"); - break; - } - } - - if (m_msgId.Contains("_")) - { - var interval = long.Parse(DateTime.Now.GetChinaTicks()) - long.Parse(m_msgId.Split('_')[0]); - m_logger?.LogDebug($"endSwap {m_msgId} 交互时常:{interval}ms"); - } - } - - private void closeSocket(string msg) - { - m_logger.LogDebug($"【closeSocket】:{msg}"); - - try - { - m_sockt1.Shutdown(SocketShutdown.Both); - } - catch (Exception) - { - } - finally - { - m_sockt1.Close(); - } - - try - { - m_sockt2.Shutdown(SocketShutdown.Both); - - } - catch (Exception) - { - } - finally - { - m_sockt2.Close(); - } - } - } -} \ No newline at end of file diff --git a/FastTunnel.Server/Startup.cs b/FastTunnel.Server/Startup.cs index c249e01..5c458f8 100644 --- a/FastTunnel.Server/Startup.cs +++ b/FastTunnel.Server/Startup.cs @@ -1,6 +1,5 @@ using FastTunnel.Core; using FastTunnel.Core.Extensions; -using FastTunnel.Server.Models; using Microsoft.AspNetCore.Authentication.JwtBearer; using Microsoft.AspNetCore.Builder; using Microsoft.AspNetCore.Hosting; @@ -57,9 +56,9 @@ namespace FastTunnel.Server context.Response.ContentType = "application/json;charset=utf-8"; context.Response.StatusCode = StatusCodes.Status200OK; - await context.Response.WriteAsync(new ApiResponse + await context.Response.WriteAsync(new { - errorCode = ErrorCodeEnum.AuthError, + errorCode = 1, errorMessage = context.Error ?? "Token is Required" }.ToJson()); },