This commit is contained in:
SpringHgui 2021-08-07 23:54:48 +08:00
parent e07bcf171e
commit 6e0d00bed5
18 changed files with 85 additions and 503 deletions

View File

@ -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
{
@ -32,10 +31,14 @@ namespace FastTunnel.Client
// -------------------FastTunnel EDN--------------------
})
.ConfigureLogging((HostBuilderContext context, ILoggingBuilder logging) =>
{
var enableFileLog = (bool)(context.Configuration.GetSection("EnableFileLog")?.Get(typeof(bool)) ?? false);
if (enableFileLog)
{
logging.ClearProviders();
logging.SetMinimumLevel(LogLevel.Trace);
logging.AddLog4Net();
}
});
}
}

View File

@ -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, // windows3389
"RemotePort": 1274 // 访 ip:1274 window
}

View File

@ -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<FastTunnelClient> _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<LogInMassage> loginMsg;
protected readonly IOptionsMonitor<DefaultClientConfig> _configuration;
private readonly CancellationTokenSource cancellationTokenSource = new();
public SuiDaoServer Server { get; protected set; }
public FastTunnelClient(
ILogger<FastTunnelClient> logger,
HttpRequestHandler newCustomerHandler,
NewForwardHandler newSSHHandler, LogHandler logHandler,
IOptionsMonitor<DefaultClientConfig> 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<HeartMassage> { MessageType = MessageType.Heart, Content = null }, cancellationTokenSource.Token).Wait();
}
catch (Exception)
{
// 与服务端断开连接
await reConnAsync();
}
finally
{
timer_heart.Enabled = true;
}
}
/// <summary>
/// 启动客户端
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="customLoginMsg">自定义登录信息,可进行扩展业务</param>
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<IFastTunnelClientSocket> 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<LogInMassage>
{
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<NewCustomerMassage>(cmds[1]);
break;
case "S_NewSSH":
handler = _newSSHHandler;
msg = JsonSerializer.Deserialize<NewForwardMessage>(cmds[1]);
break;
case "Log":
handler = _logHandler;
msg = JsonSerializer.Deserialize<LogMassage>(cmds[1]);
break;
default:
throw new Exception($"未处理的消息:{lineCmd}");
}
await handler.HandlerMsgAsync(this, msg);
}
}
}

View File

@ -22,14 +22,12 @@ namespace FastTunnel.Core.Client
public class FastTunnelClient : IFastTunnelClient
{
private ClientWebSocket socket;
protected ILogger<FastTunnelClient> _logger;
public DateTime lastHeart;
SwapHandler _newCustomerHandler;
LogHandler _logHandler;
protected readonly ILogger<FastTunnelClient> _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);
}
}
}

View File

@ -10,5 +10,7 @@ namespace FastTunnel.Core.Client
public interface IFastTunnelClient
{
void StartAsync(CancellationToken cancellationToken);
void Stop(CancellationToken cancellationToken);
}
}

View File

@ -26,7 +26,7 @@ namespace FastTunnel.Core
{
services.Configure<DefaultClientConfig>(configurationSection);
services.AddSingleton<IFastTunnelClient, FastTunnelClient>()
services.AddTransient<IFastTunnelClient, FastTunnelClient>()
.AddSingleton<IExceptionFilter, FastTunnelExceptionFilter>()
.AddSingleton<LogHandler>()
.AddSingleton<SwapHandler>();
@ -44,7 +44,6 @@ namespace FastTunnel.Core
services.AddSingleton<IForwarderHttpClientFactory, FastTunnelForwarderHttpClientFactory>();
services.Configure<DefaultServerConfig>(configurationSection)
.AddSingleton<TunnelClient>()
.AddSingleton<IExceptionFilter, FastTunnelExceptionFilter>()
.AddSingleton<FastTunnelClientHandler, FastTunnelClientHandler>()
.AddSingleton<FastTunnelSwapHandler, FastTunnelSwapHandler>()

View File

@ -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<RouteConfig> routes, IReadOnlyList<ClusterConfig> clusters)
{
@ -55,8 +56,14 @@ namespace Yarp.Sample
}
public void AddWeb(string hostName)
{
lock (locker)
{
var oldConfig = _config;
if (oldConfig.Routes.Any(x => x.ClusterId == hostName))
{
return;
}
var newRoutes = oldConfig.Routes.ToList();
newRoutes.Add(new RouteConfig
@ -79,6 +86,7 @@ namespace Yarp.Sample
_config = new InMemoryConfig(newRoutes, newClusters);
oldConfig.SignalChange();
}
}
/// <summary>
/// Implementation of IProxyConfig which is a snapshot of the current config state. The data for this class should be immutable.

View File

@ -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<FastTunnelClientHandler> logger;
FastTunnelServer fastTunnelServer;
TunnelClient tunnelClient;
public FastTunnelClientHandler(
ILogger<FastTunnelClientHandler> logger,
FastTunnelServer fastTunnelServer, TunnelClient tunnelClient)
public FastTunnelClientHandler(ILogger<FastTunnelClientHandler> logger, FastTunnelServer fastTunnelServer)
{
this.logger = logger;
this.fastTunnelServer = fastTunnelServer;
this.tunnelClient = tunnelClient;
}
public async Task Handle(HttpContext context, Func<Task> 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}");
}
}
}

View File

@ -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<Stream> 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);

View File

@ -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<Stream>();

View File

@ -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;

View File

@ -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<JObject> msg)
{
var SwapMsg = msg.Content.ToObject<SwapMassage>();
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<LogMassage> { MessageType = MessageType.Log, Content = new LogMassage(LogMsgType.Debug, $"未找到请求:{SwapMsg.msgId}") });
try
{
client.Shutdown(SocketShutdown.Both);
}
catch (Exception)
{
}
client.Close();
}
}
public Task<bool> HandlerMsg(FastTunnelServer server, WebSocket client, Message<JObject> msg)
{
throw new NotImplementedException();
}
}
}

View File

@ -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<JObject> msg;
try
{
msg = JsonConvert.DeserializeObject<Message<JObject>>(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()
{
}
}
}

View File

@ -23,16 +23,17 @@ namespace FastTunnel.Core.Models
ILogger logger;
WebSocket webSocket;
public TunnelClient(ILogger<TunnelClient> 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<LogInMassage>(lineCmd.Substring(1));
return await _loginHandler.HandlerMsg(fastTunnelServer, webSocket, msg);

View File

@ -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】");
}
}
}
}

View File

@ -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);
});
})
@ -33,10 +33,14 @@ namespace FastTunnel.Server
webBuilder.UseStartup<Startup>();
})
.ConfigureLogging((HostBuilderContext context, ILoggingBuilder logging) =>
{
var enableFileLog = (bool)context.Configuration.GetSection("EnableFileLog").Get(typeof(bool));
if (enableFileLog)
{
logging.ClearProviders();
logging.SetMinimumLevel(LogLevel.Trace);
logging.AddLog4Net();
}
});
}
}

View File

@ -1,9 +1,12 @@
{
"Logging": {
"LogLevel": {
"Default": "Information",
// Trace Debug Information Warning Error
"Default": "Debug",
"Microsoft": "Warning",
"Microsoft.Hosting.Lifetime": "Information"
}
}
},
"AllowedHosts": "*",
"EnableFileLog": true
}

View File

@ -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" ],