diff --git a/FastTunnel.Client/Program.cs b/FastTunnel.Client/Program.cs index afbcf2a..c273f1d 100644 --- a/FastTunnel.Client/Program.cs +++ b/FastTunnel.Client/Program.cs @@ -1,10 +1,9 @@ using Microsoft.Extensions.Hosting; using Microsoft.Extensions.Logging; -using Microsoft.Extensions.DependencyInjection; -using FastTunnel.Core.Client; using System; using Microsoft.AspNetCore.Builder; using FastTunnel.Core; +using Microsoft.Extensions.Configuration; namespace FastTunnel.Client { @@ -33,9 +32,13 @@ namespace FastTunnel.Client }) .ConfigureLogging((HostBuilderContext context, ILoggingBuilder logging) => { - logging.ClearProviders(); - logging.SetMinimumLevel(LogLevel.Trace); - logging.AddLog4Net(); + var enableFileLog = (bool)(context.Configuration.GetSection("EnableFileLog")?.Get(typeof(bool)) ?? false); + if (enableFileLog) + { + logging.ClearProviders(); + logging.SetMinimumLevel(LogLevel.Trace); + logging.AddLog4Net(); + } }); } } diff --git a/FastTunnel.Client/appsettings.json b/FastTunnel.Client/appsettings.json index dffbbb5..46bd569 100644 --- a/FastTunnel.Client/appsettings.json +++ b/FastTunnel.Client/appsettings.json @@ -2,11 +2,12 @@ "Logging": { "LogLevel": { // Trace Debug Information Warning Error - "Default": "Debug", + "Default": "Information", "Microsoft": "Warning", "Microsoft.Hosting.Lifetime": "Information" } }, + "EnableFileLog": false, "ClientSettings": { "Server": { // 服务端ip/域名 @@ -58,7 +59,7 @@ "RemotePort": 7091 }, { - "LocalIp": "192.168.0.91", + "LocalIp": "10.70.250.17", "LocalPort": 3389, // windows远程桌面端口为3389 "RemotePort": 1274 // 访问 服务端ip:1274 即可实现远程window桌面 } diff --git a/FastTunnel.Core/Client/FastTunnelClient - Copy.cs b/FastTunnel.Core/Client/FastTunnelClient - Copy.cs deleted file mode 100644 index 4c5a036..0000000 --- a/FastTunnel.Core/Client/FastTunnelClient - Copy.cs +++ /dev/null @@ -1,244 +0,0 @@ -using FastTunnel.Core.Config; -using FastTunnel.Core.Models; -using System; -using System.Net.Sockets; -using System.Text; -using System.Threading.Tasks; -using FastTunnel.Core.Extensions; -using System.Timers; -using System.Threading; -using Microsoft.Extensions.Logging; -using FastTunnel.Core.Handlers.Client; -using Microsoft.Extensions.Configuration; -using FastTunnel.Core.Server; -using FastTunnel.Core.Sockets; -using Microsoft.Extensions.Options; -using System.Net.WebSockets; -using System.Text.Json; -using FastTunnel.Core.Protocol; - -namespace FastTunnel.Core.Client -{ - public class FastTunnelClient : IFastTunnelClient - { - //Socket _client; - private IFastTunnelClientSocket socket; - - protected ILogger _logger; - - System.Timers.Timer timer_heart; - - double heartInterval = 10 * 1000; // 10 秒心跳 - public DateTime lastHeart; - - int reTrySpan = 10 * 1000; // 登陆失败后重试间隔 - HttpRequestHandler _newCustomerHandler; - NewForwardHandler _newSSHHandler; - LogHandler _logHandler; - ClientHeartHandler _clientHeartHandler; - Message loginMsg; - protected readonly IOptionsMonitor _configuration; - private readonly CancellationTokenSource cancellationTokenSource = new(); - - public SuiDaoServer Server { get; protected set; } - - public FastTunnelClient( - ILogger logger, - HttpRequestHandler newCustomerHandler, - NewForwardHandler newSSHHandler, LogHandler logHandler, - IOptionsMonitor configuration, - ClientHeartHandler clientHeartHandler) - { - _logger = logger; - _newCustomerHandler = newCustomerHandler; - _newSSHHandler = newSSHHandler; - _logHandler = logHandler; - _clientHeartHandler = clientHeartHandler; - _configuration = configuration; - - timer_heart = new System.Timers.Timer(); - timer_heart.AutoReset = false; - timer_heart.Interval = heartInterval; - timer_heart.Elapsed += HeartElapsed; - } - - private async Task reConnAsync() - { - Close(); - - do - { - try - { - Thread.Sleep(reTrySpan); - - _logger.LogInformation("登录重试..."); - socket = await loginAsync(CancellationToken.None); - - break; - } - catch (Exception ex) - { - _logger.LogError(ex.Message); - } - } while (true); - - await connSuccessAsync(); - } - - private async void HeartElapsed(object sender, ElapsedEventArgs e) - { - timer_heart.Enabled = false; - - try - { - socket.SendAsync(new Message { MessageType = MessageType.Heart, Content = null }, cancellationTokenSource.Token).Wait(); - } - catch (Exception) - { - // 与服务端断开连接 - await reConnAsync(); - } - finally - { - timer_heart.Enabled = true; - } - } - - /// - /// 启动客户端 - /// - /// - /// 自定义登录信息,可进行扩展业务 - public async Task StartAsync(CancellationToken cancellationToken) - { - CancellationTokenSource.CreateLinkedTokenSource(cancellationToken, this.cancellationTokenSource.Token); - - _logger.LogInformation("===== FastTunnel Client Start ====="); - - try - { - socket = await loginAsync(cancellationToken); - } - catch (Exception ex) - { - _logger.LogError(ex.Message); - - await reConnAsync(); - return; - } - - _ = connSuccessAsync(); - } - - protected virtual async Task loginAsync(CancellationToken cancellationToken) - { - Server = _configuration.CurrentValue.Server; - _logger.LogInformation($"正在连接服务端 {Server.ServerAddr}:{Server.ServerPort}"); - - try - { - // 连接到的目标IP - socket = new DefultClientSocket(); - - await socket.ConnectAsync( - new Uri($"ws://{_configuration.CurrentValue.Server.ServerAddr}:{_configuration.CurrentValue.Server.ServerPort}"), cancellationToken); - - _logger.LogInformation("连接成功"); - } - catch (Exception) - { - throw; - } - - loginMsg = new Message - { - MessageType = MessageType.C_LogIn, - Content = new LogInMassage - { - Webs = _configuration.CurrentValue.Webs, - SSH = _configuration.CurrentValue.Forwards, - }, - }; - - // 登录 - await socket.SendAsync(loginMsg, cancellationToken); - return socket; - } - - void Close() - { - timer_heart.Stop(); - socket.CloseAsync(); - } - - private async Task connSuccessAsync() - { - _logger.LogDebug("通信已建立"); - - // 心跳开始 - timer_heart.Start(); - - await ReceiveServerAsync(socket); - // await new PipeHepler(_client, ProceccLine).ProcessLinesAsync(); - } - - private async Task ReceiveServerAsync(IFastTunnelClientSocket client) - { - var tunnelProtocol = new TunnelProtocol(); - byte[] buffer = new byte[512]; - int n = 0; - - try - { - while (true) - { - n = await client.ReceiveAsync(buffer, cancellationTokenSource.Token); - var cmds = tunnelProtocol.HandleBuffer(buffer, 0, n); - - foreach (var item in cmds) - { - await HandleServerRequestAsync(item); - } - } - } - catch (Exception ex) - { - - throw; - } - } - - private async Task HandleServerRequestAsync(string lineCmd) - { - _logger.LogInformation($"服务端指令 {lineCmd}"); - var cmds = lineCmd.Split("||"); - var type = cmds[0]; - - TunnelMassage msg = null; - IClientHandler handler; - switch (type) - { - case "Heart": - handler = _clientHeartHandler; - break; - case "S_NewCustomer": - handler = _newCustomerHandler; - msg = JsonSerializer.Deserialize(cmds[1]); - break; - case "S_NewSSH": - handler = _newSSHHandler; - msg = JsonSerializer.Deserialize(cmds[1]); - break; - case "Log": - handler = _logHandler; - msg = JsonSerializer.Deserialize(cmds[1]); - break; - default: - throw new Exception($"未处理的消息:{lineCmd}"); - } - - await handler.HandlerMsgAsync(this, msg); - } - } -} diff --git a/FastTunnel.Core/Client/FastTunnelClient.cs b/FastTunnel.Core/Client/FastTunnelClient.cs index 00270a8..3667dfc 100644 --- a/FastTunnel.Core/Client/FastTunnelClient.cs +++ b/FastTunnel.Core/Client/FastTunnelClient.cs @@ -22,14 +22,12 @@ namespace FastTunnel.Core.Client public class FastTunnelClient : IFastTunnelClient { private ClientWebSocket socket; - protected ILogger _logger; - public DateTime lastHeart; - SwapHandler _newCustomerHandler; - LogHandler _logHandler; + protected readonly ILogger _logger; + private readonly SwapHandler _newCustomerHandler; + private readonly LogHandler _logHandler; public DefaultClientConfig ClientConfig { get; private set; } - private readonly CancellationTokenSource cancellationTokenSource = new(); public SuiDaoServer Server { get; protected set; } @@ -142,5 +140,14 @@ namespace FastTunnel.Core.Client _logger.LogError(ex); } } + + public void Stop(CancellationToken cancellationToken) + { + _logger.LogInformation("===== FastTunnel Client Stoping ====="); + if (socket.State == WebSocketState.Connecting) + return; + + socket.CloseAsync(WebSocketCloseStatus.Empty, "客户端主动关闭", cancellationToken); + } } } diff --git a/FastTunnel.Core/Client/IFastTunnelClient.cs b/FastTunnel.Core/Client/IFastTunnelClient.cs index 884886f..422f8e4 100644 --- a/FastTunnel.Core/Client/IFastTunnelClient.cs +++ b/FastTunnel.Core/Client/IFastTunnelClient.cs @@ -10,5 +10,7 @@ namespace FastTunnel.Core.Client public interface IFastTunnelClient { void StartAsync(CancellationToken cancellationToken); + + void Stop(CancellationToken cancellationToken); } } diff --git a/FastTunnel.Core/Extensions/ServicesExtensions.cs b/FastTunnel.Core/Extensions/ServicesExtensions.cs index de6dc14..38cb697 100644 --- a/FastTunnel.Core/Extensions/ServicesExtensions.cs +++ b/FastTunnel.Core/Extensions/ServicesExtensions.cs @@ -26,7 +26,7 @@ namespace FastTunnel.Core { services.Configure(configurationSection); - services.AddSingleton() + services.AddTransient() .AddSingleton() .AddSingleton() .AddSingleton(); @@ -44,7 +44,6 @@ namespace FastTunnel.Core services.AddSingleton(); services.Configure(configurationSection) - .AddSingleton() .AddSingleton() .AddSingleton() .AddSingleton() diff --git a/FastTunnel.Core/Forwarder/InMemoryConfigProvider.cs b/FastTunnel.Core/Forwarder/InMemoryConfigProvider.cs index 6c215b8..903f3a5 100644 --- a/FastTunnel.Core/Forwarder/InMemoryConfigProvider.cs +++ b/FastTunnel.Core/Forwarder/InMemoryConfigProvider.cs @@ -32,6 +32,7 @@ namespace Yarp.Sample { // Marked as volatile so that updates are atomic private volatile InMemoryConfig _config; + private object locker = new object(); public InMemoryConfigProvider(IReadOnlyList routes, IReadOnlyList clusters) { @@ -56,28 +57,35 @@ namespace Yarp.Sample public void AddWeb(string hostName) { - var oldConfig = _config; - - var newRoutes = oldConfig.Routes.ToList(); - newRoutes.Add(new RouteConfig + lock (locker) { - ClusterId = hostName, - RouteId = hostName, - Match = new RouteMatch { Hosts = new string[] { hostName } } - }); - - var newClusters = oldConfig.Clusters.ToList(); - newClusters.Add(new ClusterConfig - { - ClusterId = hostName, - Destinations = new Dictionary(StringComparer.OrdinalIgnoreCase) + var oldConfig = _config; + if (oldConfig.Routes.Any(x => x.ClusterId == hostName)) { - { "default", new DestinationConfig() {Address = $"http://{hostName}",} } + return; } - }); - _config = new InMemoryConfig(newRoutes, newClusters); - oldConfig.SignalChange(); + var newRoutes = oldConfig.Routes.ToList(); + newRoutes.Add(new RouteConfig + { + ClusterId = hostName, + RouteId = hostName, + Match = new RouteMatch { Hosts = new string[] { hostName } } + }); + + var newClusters = oldConfig.Clusters.ToList(); + newClusters.Add(new ClusterConfig + { + ClusterId = hostName, + Destinations = new Dictionary(StringComparer.OrdinalIgnoreCase) + { + { "default", new DestinationConfig() {Address = $"http://{hostName}",} } + } + }); + + _config = new InMemoryConfig(newRoutes, newClusters); + oldConfig.SignalChange(); + } } /// diff --git a/FastTunnel.Core/Forwarder/MiddleWare/FastTunnelClientHandler.cs b/FastTunnel.Core/Forwarder/MiddleWare/FastTunnelClientHandler.cs index 5257196..84a5d5a 100644 --- a/FastTunnel.Core/Forwarder/MiddleWare/FastTunnelClientHandler.cs +++ b/FastTunnel.Core/Forwarder/MiddleWare/FastTunnelClientHandler.cs @@ -1,8 +1,11 @@ using FastTunnel.Core.Client; using FastTunnel.Core.Forwarder; +using FastTunnel.Core.Forwarder.MiddleWare; using FastTunnel.Core.Models; +using Microsoft.AspNetCore.Builder; using Microsoft.AspNetCore.Connections.Features; using Microsoft.AspNetCore.Http; +using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Logging; using System; using System.Collections.Concurrent; @@ -20,15 +23,11 @@ namespace FastTunnel.Core.MiddleWares { ILogger logger; FastTunnelServer fastTunnelServer; - TunnelClient tunnelClient; - public FastTunnelClientHandler( - ILogger logger, - FastTunnelServer fastTunnelServer, TunnelClient tunnelClient) + public FastTunnelClientHandler(ILogger logger, FastTunnelServer fastTunnelServer) { this.logger = logger; this.fastTunnelServer = fastTunnelServer; - this.tunnelClient = tunnelClient; } public async Task Handle(HttpContext context, Func next) @@ -48,15 +47,16 @@ namespace FastTunnel.Core.MiddleWares { using var webSocket = await context.WebSockets.AcceptWebSocketAsync(); - tunnelClient.SetSocket(webSocket); + var tunnelClient = new TunnelClient(logger, fastTunnelServer).SetSocket(webSocket); try { + logger.LogInformation($"客户端连接 {context.TraceIdentifier}:{context.Connection.RemoteIpAddress}"); await tunnelClient.ReviceAsync(CancellationToken.None); } - catch (Exception ex) + catch (Exception) { - logger.LogError(ex, "通信异常"); + logger.LogInformation($"客户端关闭 {context.TraceIdentifier}:{context.Connection.RemoteIpAddress}"); } } } diff --git a/FastTunnel.Core/Handlers/Client/SwapHandler.cs b/FastTunnel.Core/Handlers/Client/SwapHandler.cs index 0ad4de6..398711d 100644 --- a/FastTunnel.Core/Handlers/Client/SwapHandler.cs +++ b/FastTunnel.Core/Handlers/Client/SwapHandler.cs @@ -57,7 +57,7 @@ namespace FastTunnel.Core.Handlers.Client var localConnecter = new DnsSocket(localhost.Split(":")[0], int.Parse(localhost.Split(":")[1])); await localConnecter.ConnectAsync(); - return new NetworkStream(localConnecter.Socket, ownsSocket: true); + return new NetworkStream(localConnecter.Socket, true); } private async Task createRemote(string requestId, FastTunnelClient cleint, CancellationToken cancellationToken) @@ -65,7 +65,7 @@ namespace FastTunnel.Core.Handlers.Client var connecter = new DnsSocket(cleint.Server.ServerAddr, cleint.Server.ServerPort); await connecter.ConnectAsync(); - Stream serverConn = new NetworkStream(connecter.Socket, ownsSocket: true); + Stream serverConn = new NetworkStream(connecter.Socket, true); var reverse = $"PROXY /{requestId} HTTP/1.1\r\nHost: {cleint.Server.ServerAddr}:{cleint.Server.ServerPort}\r\nConnection: keep-alive\r\n\r\n"; var requestMsg = Encoding.ASCII.GetBytes(reverse); diff --git a/FastTunnel.Core/Handlers/Client/ForwardDispatcher.cs b/FastTunnel.Core/Handlers/Server/ForwardDispatcher.cs similarity index 95% rename from FastTunnel.Core/Handlers/Client/ForwardDispatcher.cs rename to FastTunnel.Core/Handlers/Server/ForwardDispatcher.cs index 800eda1..afbcf37 100644 --- a/FastTunnel.Core/Handlers/Client/ForwardDispatcher.cs +++ b/FastTunnel.Core/Handlers/Server/ForwardDispatcher.cs @@ -37,7 +37,7 @@ namespace FastTunnel.Core.Dispatchers { await Task.Yield(); - var msgid = Guid.NewGuid().ToString(); + var msgid = Guid.NewGuid().ToString().Replace("-", ""); await _client.SendCmdAsync(MessageType.Forward, $"{msgid}|{_config.LocalIp}:{_config.LocalPort}", CancellationToken.None); var tcs = new TaskCompletionSource(); diff --git a/FastTunnel.Core/Handlers/Server/LoginHandler.cs b/FastTunnel.Core/Handlers/Server/LoginHandler.cs index 9208942..13fa8cd 100644 --- a/FastTunnel.Core/Handlers/Server/LoginHandler.cs +++ b/FastTunnel.Core/Handlers/Server/LoginHandler.cs @@ -35,7 +35,7 @@ namespace FastTunnel.Core.Handlers { bool hasTunnel = false; - await client.SendCmdAsync(MessageType.Log, $"穿透协议 | 映射关系(公网=>内网){Environment.NewLine}", CancellationToken.None); + await client.SendCmdAsync(MessageType.Log, $"穿透协议 | 映射关系(公网=>内网)", CancellationToken.None); if (requet.Webs != null && requet.Webs.Count() > 0) { hasTunnel = true; diff --git a/FastTunnel.Core/Handlers/Server/SwapMessageHandler.cs b/FastTunnel.Core/Handlers/Server/SwapMessageHandler.cs deleted file mode 100644 index cbc255a..0000000 --- a/FastTunnel.Core/Handlers/Server/SwapMessageHandler.cs +++ /dev/null @@ -1,68 +0,0 @@ -using FastTunnel.Core.Client; -using FastTunnel.Core.Extensions; -using FastTunnel.Core.Models; -using FastTunnel.Core.Sockets; -using FastTunnel.Core.Utility.Extensions; -using Microsoft.Extensions.Logging; -using Newtonsoft.Json.Linq; -using System; -using System.Collections.Generic; -using System.Net.Sockets; -using System.Net.WebSockets; -using System.Text; -using System.Threading.Tasks; - -namespace FastTunnel.Core.Handlers.Server -{ - public class SwapMessageHandler : IClientMessageHandler - { - public bool NeedRecive => false; - - ILogger _logger; - - public SwapMessageHandler(ILogger logger) - { - _logger = logger; - } - - public void HandlerMsg(FastTunnelServer server, Socket client, Message msg) - { - var SwapMsg = msg.Content.ToObject(); - if (SwapMsg.msgId.Contains("_")) - { - var interval = long.Parse(DateTime.Now.GetChinaTicks()) - long.Parse(SwapMsg.msgId.Split('_')[0]); - _logger.LogDebug($"[开始转发HTTP]:{SwapMsg.msgId} 客户端耗时:{interval}ms"); - } - - if (!string.IsNullOrEmpty(SwapMsg.msgId) && server.ResponseTasks.TryGetValue(SwapMsg.msgId, out var response)) - { - server.ResponseTasks.TryRemove(SwapMsg.msgId, out _); - - _logger.LogDebug($"SwapMassage:{SwapMsg.msgId}"); - response.SetResult(new NetworkStream(client, true)); - } - else - { - // 未找到,关闭连接 - _logger.LogError($"未找到请求:{SwapMsg.msgId}"); - - client.SendCmd(new Message { MessageType = MessageType.Log, Content = new LogMassage(LogMsgType.Debug, $"未找到请求:{SwapMsg.msgId}") }); - - try - { - client.Shutdown(SocketShutdown.Both); - } - catch (Exception) - { - } - - client.Close(); - } - } - - public Task HandlerMsg(FastTunnelServer server, WebSocket client, Message msg) - { - throw new NotImplementedException(); - } - } -} diff --git a/FastTunnel.Core/Listener/ClientListenerV2.cs b/FastTunnel.Core/Listener/ClientListenerV2.cs deleted file mode 100644 index 1207a33..0000000 --- a/FastTunnel.Core/Listener/ClientListenerV2.cs +++ /dev/null @@ -1,111 +0,0 @@ -using FastTunnel.Core.Client; -using FastTunnel.Core.Dispatchers; -using FastTunnel.Core.Extensions; -using FastTunnel.Core.Handlers; -using FastTunnel.Core.Handlers.Server; -using FastTunnel.Core.Models; -using FastTunnel.Core.Server; -using Microsoft.Extensions.Logging; -using Newtonsoft.Json; -using Newtonsoft.Json.Linq; -using System; -using System.Collections.Generic; -using System.Net; -using System.Net.Sockets; -using System.Threading; -using Yarp.ReverseProxy.Configuration; - -namespace FastTunnel.Core.Listener -{ - public class ClientListenerV2 - { - ILogger _logger; - - public string ListenIp { get; set; } - - public int ListenPort { get; set; } - - FastTunnelServer _fastTunnelServer; - Server.Server server; - - readonly LoginHandler _loginHandler; - readonly HeartMessageHandler _heartHandler; - readonly SwapMessageHandler _swapMsgHandler; - - public ClientListenerV2(FastTunnelServer fastTunnelServer, IProxyConfigProvider proxyConfig, string ip, int port, ILogger logerr) - { - _fastTunnelServer = fastTunnelServer; - _logger = logerr; - this.ListenIp = ip; - this.ListenPort = port; - - _loginHandler = new LoginHandler(_logger, proxyConfig); - _heartHandler = new HeartMessageHandler(); - _swapMsgHandler = new SwapMessageHandler(_logger); - - server = new Server.Server(10000, 100, false, _logger); - } - - public void Start() - { - IPAddress ipa = IPAddress.Parse(ListenIp); - IPEndPoint localEndPoint = new IPEndPoint(ipa, ListenPort); - - server.Init(); - server.Start(localEndPoint, "\n", handle); - _logger.LogInformation($"监听客户端 -> {ListenIp}:{ListenPort}"); - } - - private bool handle(AsyncUserToken token, string words) - { - Message msg; - - try - { - msg = JsonConvert.DeserializeObject>(words); - } - catch (Exception ex) - { - _logger.LogCritical(ex, $"【异常的指令】{words}"); - token.Socket.Close(); - return false; - } - - try - { - IClientMessageHandler handler = null; - switch (msg.MessageType) - { - case MessageType.C_LogIn: // 登录 - handler = _loginHandler; - break; - case MessageType.Heart: // 心跳 - handler = _heartHandler; - break; - case MessageType.C_SwapMsg: // 交换数据 - handler = _swapMsgHandler; - break; - default: - throw new Exception($"未知的通讯指令 {msg.MessageType}"); - } - - handler.HandlerMsg(this._fastTunnelServer, token.Socket, msg); - return handler.NeedRecive; - } - catch (Exception ex) - { - _logger.LogError(ex, $"处理客户端消息失败:msg={msg?.ToJson()}"); - token.Socket.Close(); - return false; - } - } - - public void Stop() - { - } - - public void Close() - { - } - } -} diff --git a/FastTunnel.Core/Models/TunnelClient.cs b/FastTunnel.Core/Models/TunnelClient.cs index 1822f35..c16c138 100644 --- a/FastTunnel.Core/Models/TunnelClient.cs +++ b/FastTunnel.Core/Models/TunnelClient.cs @@ -23,16 +23,17 @@ namespace FastTunnel.Core.Models ILogger logger; WebSocket webSocket; - public TunnelClient(ILogger logger, FastTunnelServer fastTunnelServer) + public TunnelClient(ILogger logger, FastTunnelServer fastTunnelServer) { this.logger = logger; this.fastTunnelServer = fastTunnelServer; this._loginHandler = new LoginHandler(logger, fastTunnelServer.proxyConfig); } - public void SetSocket(WebSocket webSocket) + public TunnelClient SetSocket(WebSocket webSocket) { this.webSocket = webSocket; + return this; } public async Task ReviceAsync(CancellationToken cancellationToken) @@ -60,7 +61,7 @@ namespace FastTunnel.Core.Models { try { - logger.LogInformation($"client:{lineCmd}"); + logger.LogDebug($"client:{lineCmd}"); var msg = JsonSerializer.Deserialize(lineCmd.Substring(1)); return await _loginHandler.HandlerMsg(fastTunnelServer, webSocket, msg); diff --git a/FastTunnel.Core/Services/ServiceFastTunnelClient.cs b/FastTunnel.Core/Services/ServiceFastTunnelClient.cs index f5fcba7..02bc75b 100644 --- a/FastTunnel.Core/Services/ServiceFastTunnelClient.cs +++ b/FastTunnel.Core/Services/ServiceFastTunnelClient.cs @@ -21,9 +21,7 @@ namespace FastTunnel.Core.Services { _logger = logger; _fastTunnelClient = fastTunnelClient; -#if DEBUG - AppDomain.CurrentDomain.FirstChanceException += CurrentDomain_FirstChanceException; -#endif + AppDomain.CurrentDomain.UnhandledException += CurrentDomain_UnhandledException; } @@ -35,7 +33,7 @@ namespace FastTunnel.Core.Services public Task StopAsync(CancellationToken cancellationToken) { - _logger.LogInformation("===== FastTunnel Client Stoping ====="); + _fastTunnelClient.Stop(cancellationToken); return Task.CompletedTask; } @@ -51,24 +49,5 @@ namespace FastTunnel.Core.Services { } } - - private void CurrentDomain_FirstChanceException(object sender, FirstChanceExceptionEventArgs e) - { - if (e.Exception is DirectoryNotFoundException) - { - // nlog第一次找不到文件的错误,跳过 - } - else if (e.Exception is PlatformNotSupportedException) - { - // log4net - } - else if (e.Exception is IOException && e.Exception.Source == "System.Net.Security") - { - } - else - { - _logger.LogError(e.Exception, "【FirstChanceException】"); - } - } } } diff --git a/FastTunnel.Server/Program.cs b/FastTunnel.Server/Program.cs index b1c94b9..52c9a10 100644 --- a/FastTunnel.Server/Program.cs +++ b/FastTunnel.Server/Program.cs @@ -24,7 +24,7 @@ namespace FastTunnel.Server webHostBuilder.ConfigureAppConfiguration((hostingContext, config) => { var env = hostingContext.HostingEnvironment; - config.AddJsonFile("config/appsettings.json", optional: true, reloadOnChange: true) + config.AddJsonFile("config/appsettings.json", optional: false, reloadOnChange: true) .AddJsonFile($"config/appsettings.{env.EnvironmentName}.json", optional: true, reloadOnChange: true); }); }) @@ -34,9 +34,13 @@ namespace FastTunnel.Server }) .ConfigureLogging((HostBuilderContext context, ILoggingBuilder logging) => { - logging.ClearProviders(); - logging.SetMinimumLevel(LogLevel.Trace); - logging.AddLog4Net(); + var enableFileLog = (bool)context.Configuration.GetSection("EnableFileLog").Get(typeof(bool)); + if (enableFileLog) + { + logging.ClearProviders(); + logging.SetMinimumLevel(LogLevel.Trace); + logging.AddLog4Net(); + } }); } } diff --git a/FastTunnel.Server/config/appsettings.Development.json b/FastTunnel.Server/config/appsettings.Development.json index 8983e0f..7819f3c 100644 --- a/FastTunnel.Server/config/appsettings.Development.json +++ b/FastTunnel.Server/config/appsettings.Development.json @@ -1,9 +1,12 @@ { "Logging": { "LogLevel": { - "Default": "Information", + // Trace Debug Information Warning Error + "Default": "Debug", "Microsoft": "Warning", "Microsoft.Hosting.Lifetime": "Information" } - } + }, + "AllowedHosts": "*", + "EnableFileLog": true } diff --git a/FastTunnel.Server/config/appsettings.json b/FastTunnel.Server/config/appsettings.json index f78ad0f..c510a27 100644 --- a/FastTunnel.Server/config/appsettings.json +++ b/FastTunnel.Server/config/appsettings.json @@ -2,20 +2,18 @@ "Logging": { "LogLevel": { // Trace Debug Information Warning Error - "Default": "Debug", + "Default": "Information", "Microsoft": "Warning", "Microsoft.Hosting.Lifetime": "Information" } }, "AllowedHosts": "*", "urls": "http://*:1270;", // Http&ͻͨѶ˿ + "EnableFileLog": false, "ServerSettings": { // 󶨵ĸ "WebDomain": "test.cc", - // ѡngixnʡĶ˿ںŽз - "WebHasNginxProxy": false, - // ѡʰڰipܾΪʱȨ޷ "WebAllowAccessIps": [ "192.168.0.101" ],