Updated
This commit is contained in:
1 parent
2c5b69bf2c
commit
22dee59f47
132 files changed
+19653
-7192
No files matched your search
@@ -0,0 +1,25 @@
|
||||
<Project Sdk="Microsoft.NET.Sdk">
|
||||
|
||||
<PropertyGroup>
|
||||
<TargetFramework>net8.0</TargetFramework>
|
||||
<LangVersion>latest</LangVersion>
|
||||
<ImplicitUsings>enable</ImplicitUsings>
|
||||
<Nullable>enable</Nullable>
|
||||
<GeneratePackageOnBuild>True</GeneratePackageOnBuild>
|
||||
<Title>EonaCat.Connections.Quic</Title>
|
||||
<Company>EonaCat</Company>
|
||||
<Copyright>Jeroen Saey</Copyright>
|
||||
<PackageId>EonaCat.Connections.Quic</PackageId>
|
||||
<Version>1.0.0</Version>
|
||||
<Authors>Jeroen Saey</Authors>
|
||||
<Description>EonaCat.Connections.Quic for QUIC client/servers</Description>
|
||||
</PropertyGroup>
|
||||
|
||||
<PropertyGroup>
|
||||
<EnablePreviewFeatures>true</EnablePreviewFeatures>
|
||||
</PropertyGroup>
|
||||
<ItemGroup>
|
||||
<ProjectReference Include="..\EonaCat.Connections\EonaCat.Connections.csproj" />
|
||||
</ItemGroup>
|
||||
|
||||
</Project>
|
||||
@@ -0,0 +1,37 @@
|
||||
using System.Net;
|
||||
using System.Net.Quic;
|
||||
using System.Runtime.Versioning;
|
||||
|
||||
namespace EonaCat.Connections.Quic
|
||||
{
|
||||
[SupportedOSPlatform("windows")]
|
||||
[SupportedOSPlatform("linux")]
|
||||
[SupportedOSPlatform("macos")]
|
||||
[RequiresPreviewFeatures]
|
||||
public class QuicClientConnection
|
||||
{
|
||||
public string Id { get; set; } = string.Empty;
|
||||
public QuicConnection? Connection { get; set; }
|
||||
public QuicStream? Stream { get; set; }
|
||||
public IPEndPoint? RemoteEndPoint { get; set; }
|
||||
public SemaphoreSlim WriteLock { get; } = new(1, 1);
|
||||
public DateTime ConnectedAt { get; set; }
|
||||
public DateTime LastActive { get; set; }
|
||||
public DateTime LastDataSent { get; set; }
|
||||
public DateTime LastDataReceived { get; set; }
|
||||
|
||||
public long BytesSent { get; set; }
|
||||
public long BytesReceived { get; set; }
|
||||
public long MessagesSent { get; set; }
|
||||
public long MessagesReceived { get; set; }
|
||||
|
||||
private string? _nickname;
|
||||
public string Nickname
|
||||
{
|
||||
get => string.IsNullOrWhiteSpace(_nickname) ? Id : _nickname;
|
||||
set => _nickname = string.IsNullOrWhiteSpace(value) ? Id : value;
|
||||
}
|
||||
|
||||
public bool HasNickname => !string.IsNullOrWhiteSpace(_nickname) && _nickname != Id;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,554 @@
|
||||
using EonaCat.Connections.EventArguments;
|
||||
using EonaCat.Connections.Models;
|
||||
using EonaCat.Connections.ConnectionDiagnostics;
|
||||
using EonaCat.Connections.Helpers;
|
||||
using System.Buffers;
|
||||
using System.Net;
|
||||
using System.Net.Quic;
|
||||
using System.Net.Security;
|
||||
using System.Runtime.Versioning;
|
||||
using System.Text;
|
||||
using ErrorEventArgs = EonaCat.Connections.EventArguments.ErrorEventArgs;
|
||||
|
||||
namespace EonaCat.Connections.Quic
|
||||
{
|
||||
[SupportedOSPlatform("windows")]
|
||||
[SupportedOSPlatform("linux")]
|
||||
[SupportedOSPlatform("macos")]
|
||||
[RequiresPreviewFeatures]
|
||||
public class QuicNetworkClient : IAsyncDisposable, IDisposable
|
||||
{
|
||||
public static event EventHandler<LogMessage> OnLog;
|
||||
private readonly Configuration _config;
|
||||
private QuicConnection? _connection;
|
||||
private QuicStream? _stream;
|
||||
private Task? _receiveTask;
|
||||
private Task? _autoReconnectTask;
|
||||
private CancellationTokenSource? _clientCts;
|
||||
private CancellationTokenSource? _connectionCts;
|
||||
private CancellationTokenSource? _autoReconnectSource;
|
||||
private bool _disposed;
|
||||
private bool _stopAutoReconnecting;
|
||||
private bool _wasConnected;
|
||||
private DisconnectReason _reason;
|
||||
|
||||
private readonly SemaphoreSlim _connectLock = new(1, 1);
|
||||
private readonly SemaphoreSlim _streamWriteLock = new(1, 1);
|
||||
|
||||
public bool IsConnected { get; private set; }
|
||||
public string? Nickname { get; private set; }
|
||||
public DateTime ConnectionTime { get; private set; }
|
||||
public TimeSpan Uptime => DateTime.UtcNow - ConnectionTime;
|
||||
public DateTime LastActive { get; internal set; }
|
||||
public DateTime LastDataSent { get; private set; }
|
||||
public DateTime LastDataReceived { get; private set; }
|
||||
public DateTime DisconnectionTime { get; private set; }
|
||||
public bool IsAutoConnectStarted => _autoReconnectTask != null && !_autoReconnectTask.IsCompleted;
|
||||
|
||||
public long BytesSent { get; private set; }
|
||||
public long BytesReceived { get; private set; }
|
||||
public long MessagesSent { get; private set; }
|
||||
public long MessagesReceived { get; private set; }
|
||||
|
||||
public int DEFAULT_STREAM_ERROR_CODE { get; set; } = 0;
|
||||
public int DEFAULT_CLOSE_ERROR_CODE { get; set; } = 0;
|
||||
public int MAX_INBOUND_BIDIRECTIONAL_STREAMS { get; set; } = 10;
|
||||
public int MAX_INBOUND_UNIDIRECTIONAL_STREAMS { get; set; } = 10;
|
||||
public string PROTOCOL_CONNECTION_NAME { get; set; } = "EonaCat-connector";
|
||||
|
||||
public event EventHandler<ConnectionEventArgs>? OnConnected;
|
||||
public event EventHandler<ConnectionEventArgs>? OnNicknameSend;
|
||||
public event EventHandler<DataReceivedEventArgs>? OnDataReceived;
|
||||
public event EventHandler<ConnectionEventArgs>? OnDisconnected;
|
||||
public event EventHandler<ErrorEventArgs>? OnGeneralError;
|
||||
|
||||
public QuicNetworkClient(Configuration config)
|
||||
{
|
||||
_config = config ?? throw new ArgumentNullException(nameof(config));
|
||||
_clientCts = new CancellationTokenSource();
|
||||
}
|
||||
|
||||
public async Task<bool> ConnectAsync()
|
||||
{
|
||||
if (!QuicConnection.IsSupported)
|
||||
{
|
||||
HandlingHelpers.SafeInvokeEventHandler(
|
||||
OnGeneralError,
|
||||
this,
|
||||
new ErrorEventArgs
|
||||
{
|
||||
Message = "QUIC is not supported on this platform."
|
||||
},
|
||||
nameof(OnGeneralError));
|
||||
return false;
|
||||
}
|
||||
|
||||
await _connectLock.WaitAsync().ConfigureAwait(false);
|
||||
|
||||
try
|
||||
{
|
||||
if (_clientCts == null || _clientCts.IsCancellationRequested)
|
||||
{
|
||||
_clientCts?.Dispose();
|
||||
_clientCts = new CancellationTokenSource();
|
||||
}
|
||||
|
||||
if (IsConnected)
|
||||
{
|
||||
return true;
|
||||
}
|
||||
|
||||
_connectionCts?.Cancel();
|
||||
_connectionCts?.Dispose();
|
||||
_connectionCts = new CancellationTokenSource();
|
||||
|
||||
var clientOptions = new QuicClientConnectionOptions
|
||||
{
|
||||
RemoteEndPoint = new IPEndPoint(IPAddress.Parse(_config.Host), _config.Port),
|
||||
DefaultStreamErrorCode = DEFAULT_STREAM_ERROR_CODE,
|
||||
DefaultCloseErrorCode = DEFAULT_CLOSE_ERROR_CODE,
|
||||
MaxInboundBidirectionalStreams = MAX_INBOUND_BIDIRECTIONAL_STREAMS,
|
||||
MaxInboundUnidirectionalStreams = MAX_INBOUND_UNIDIRECTIONAL_STREAMS,
|
||||
ClientAuthenticationOptions = new SslClientAuthenticationOptions
|
||||
{
|
||||
ApplicationProtocols = new List<SslApplicationProtocol>
|
||||
{
|
||||
new SslApplicationProtocol(PROTOCOL_CONNECTION_NAME)
|
||||
},
|
||||
RemoteCertificateValidationCallback = (sender, certificate, chain, errors) =>
|
||||
{
|
||||
if (_config.IsSelfSignedEnabled)
|
||||
{
|
||||
return true;
|
||||
}
|
||||
return errors == SslPolicyErrors.None;
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
_connection = await QuicConnection.ConnectAsync(clientOptions, _connectionCts.Token).ConfigureAwait(false);
|
||||
_stream = await _connection.OpenOutboundStreamAsync(QuicStreamType.Bidirectional, _connectionCts.Token).ConfigureAwait(false);
|
||||
|
||||
IsConnected = true;
|
||||
ConnectionTime = DateTime.UtcNow;
|
||||
LastActive = DateTime.UtcNow;
|
||||
|
||||
_receiveTask = Task.Run(() => ReceiveLoopAsync(_connectionCts.Token), _connectionCts.Token);
|
||||
|
||||
if (!string.IsNullOrEmpty(Nickname))
|
||||
{
|
||||
await SendNicknameAsync(Nickname).ConfigureAwait(false);
|
||||
}
|
||||
|
||||
if (_config.EnableAutoReconnect &&
|
||||
(_autoReconnectTask == null || _autoReconnectTask.IsCompleted))
|
||||
{
|
||||
if (_autoReconnectSource == null || _autoReconnectSource.IsCancellationRequested)
|
||||
{
|
||||
_autoReconnectSource?.Dispose();
|
||||
_autoReconnectSource = new CancellationTokenSource();
|
||||
}
|
||||
_autoReconnectTask = Task.Run(() => AutoReconnectAsync(_autoReconnectSource.Token), _autoReconnectSource.Token);
|
||||
}
|
||||
|
||||
_wasConnected = true;
|
||||
|
||||
HandlingHelpers.SafeInvokeEventHandler(
|
||||
OnConnected,
|
||||
this,
|
||||
new ConnectionEventArgs
|
||||
{
|
||||
ClientId = Nickname ?? "self",
|
||||
RemoteEndPoint = new IPEndPoint(IPAddress.Parse(_config.Host), _config.Port)
|
||||
},
|
||||
nameof(OnConnected));
|
||||
|
||||
return true;
|
||||
}
|
||||
catch (Exception exception)
|
||||
{
|
||||
HandlingHelpers.SafeInvokeEventHandler(
|
||||
OnGeneralError,
|
||||
this,
|
||||
new ErrorEventArgs
|
||||
{
|
||||
Exception = exception,
|
||||
Message = "QUIC connection error"
|
||||
},
|
||||
nameof(OnGeneralError));
|
||||
return false;
|
||||
}
|
||||
finally
|
||||
{
|
||||
try
|
||||
{
|
||||
_connectLock.Release();
|
||||
}
|
||||
catch
|
||||
{
|
||||
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private async Task ReceiveLoopAsync(CancellationToken token)
|
||||
{
|
||||
byte[] buffer = ArrayPool<byte>.Shared.Rent(_config.BufferSize);
|
||||
try
|
||||
{
|
||||
while (!token.IsCancellationRequested && _stream != null)
|
||||
{
|
||||
int bytesRead = await _stream.ReadAsync(buffer, 0, buffer.Length, token).ConfigureAwait(false);
|
||||
if (bytesRead == 0)
|
||||
{
|
||||
await DisconnectAsync(DisconnectReason.RemoteClosed).ConfigureAwait(false);
|
||||
return;
|
||||
}
|
||||
|
||||
LastActive = DateTime.UtcNow;
|
||||
LastDataReceived = DateTime.UtcNow;
|
||||
BytesReceived += bytesRead;
|
||||
MessagesReceived++;
|
||||
|
||||
var data = new byte[bytesRead];
|
||||
Buffer.BlockCopy(buffer, 0, data, 0, bytesRead);
|
||||
|
||||
HandlingHelpers.SafeInvokeEventHandler(
|
||||
OnDataReceived,
|
||||
this,
|
||||
new DataReceivedEventArgs
|
||||
{
|
||||
ClientId = Nickname ?? "self",
|
||||
Data = data,
|
||||
RemoteEndPoint = _connection?.RemoteEndPoint as IPEndPoint,
|
||||
Nickname = Nickname
|
||||
},
|
||||
nameof(OnDataReceived));
|
||||
}
|
||||
}
|
||||
catch (OperationCanceledException)
|
||||
{
|
||||
|
||||
}
|
||||
catch (QuicException ex) when (ex.QuicError == QuicError.ConnectionAborted)
|
||||
{
|
||||
await DisconnectAsync(DisconnectReason.RemoteClosed).ConfigureAwait(false);
|
||||
}
|
||||
catch (Exception exception)
|
||||
{
|
||||
HandlingHelpers.SafeInvokeEventHandler(
|
||||
OnGeneralError,
|
||||
this,
|
||||
new ErrorEventArgs
|
||||
{
|
||||
Exception = exception,
|
||||
Message = "Error receiving QUIC data"
|
||||
},
|
||||
nameof(OnGeneralError));
|
||||
await DisconnectAsync(DisconnectReason.Error, exception).ConfigureAwait(false);
|
||||
}
|
||||
finally
|
||||
{
|
||||
ArrayPool<byte>.Shared.Return(buffer);
|
||||
}
|
||||
}
|
||||
|
||||
public async Task<bool> SendAsync(byte[] data)
|
||||
{
|
||||
if (!IsConnected || _stream == null || data == null || data.Length == 0)
|
||||
{
|
||||
return false;
|
||||
}
|
||||
|
||||
try
|
||||
{
|
||||
await _streamWriteLock.WaitAsync().ConfigureAwait(false);
|
||||
|
||||
try
|
||||
{
|
||||
await _stream.WriteAsync(data, _connectionCts?.Token ?? CancellationToken.None).ConfigureAwait(false);
|
||||
await _stream.FlushAsync(_connectionCts?.Token ?? CancellationToken.None).ConfigureAwait(false);
|
||||
}
|
||||
finally
|
||||
{
|
||||
_streamWriteLock.Release();
|
||||
}
|
||||
|
||||
LastActive = DateTime.UtcNow;
|
||||
LastDataSent = DateTime.UtcNow;
|
||||
BytesSent += data.Length;
|
||||
MessagesSent++;
|
||||
return true;
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
await DisconnectAsync(DisconnectReason.Error, ex).ConfigureAwait(false);
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
public async Task<bool> SendAsync(string message) => await SendAsync(Encoding.UTF8.GetBytes(message)).ConfigureAwait(false);
|
||||
|
||||
public async Task SendNicknameAsync(string nickname)
|
||||
{
|
||||
Nickname = nickname;
|
||||
if (IsConnected)
|
||||
{
|
||||
await SendAsync($"NICK:{nickname}").ConfigureAwait(false);
|
||||
OnNicknameSend?.Invoke(this, new ConnectionEventArgs
|
||||
{
|
||||
ClientId = nickname,
|
||||
Nickname = nickname
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
public async Task DisconnectAsync(DisconnectReason reason = DisconnectReason.ClientRequested, Exception? exception = null)
|
||||
{
|
||||
if (!IsConnected && _connection == null)
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
IsConnected = false;
|
||||
DisconnectionTime = DateTime.UtcNow;
|
||||
_reason = reason;
|
||||
|
||||
_connectionCts?.Cancel();
|
||||
|
||||
try
|
||||
{
|
||||
if (_stream != null)
|
||||
{
|
||||
_stream.Abort(QuicAbortDirection.Both, 0);
|
||||
await _stream.DisposeAsync().ConfigureAwait(false);
|
||||
_stream = null;
|
||||
}
|
||||
}
|
||||
catch
|
||||
{
|
||||
|
||||
}
|
||||
|
||||
try
|
||||
{
|
||||
if (_connection != null)
|
||||
{
|
||||
await _connection.CloseAsync(0).ConfigureAwait(false);
|
||||
await _connection.DisposeAsync().ConfigureAwait(false);
|
||||
_connection = null;
|
||||
}
|
||||
}
|
||||
catch
|
||||
{
|
||||
|
||||
}
|
||||
|
||||
var determinedReason = ConnectionEventArgs.Determine(reason, exception);
|
||||
var initiator = DisconnectionDiagnostics.DetermineInitiator(determinedReason, exception);
|
||||
var reasonDetails = DisconnectionDiagnostics.GetDetailedReasonDescription(determinedReason, exception);
|
||||
|
||||
var diagnosticContext = new Dictionary<string, string>();
|
||||
if (exception is System.Net.Sockets.SocketException socketEx)
|
||||
{
|
||||
var socketContext = DisconnectionDiagnostics.AnalyzeSocketException(socketEx);
|
||||
foreach (var kvp in socketContext)
|
||||
{
|
||||
diagnosticContext[$"Socket_{kvp.Key}"] = kvp.Value;
|
||||
}
|
||||
}
|
||||
|
||||
diagnosticContext["IsLocalInitiated"] = initiator == "Local" ? "true" : "false";
|
||||
|
||||
var remoteEndPoint = new IPEndPoint(IPAddress.Parse(_config.Host), _config.Port);
|
||||
var connectionEventArgs = new ConnectionEventArgs
|
||||
{
|
||||
ClientId = Nickname ?? "self",
|
||||
Reason = determinedReason,
|
||||
Exception = exception,
|
||||
RemoteEndPoint = remoteEndPoint,
|
||||
Initiator = initiator,
|
||||
ReasonDetails = reasonDetails,
|
||||
DiagnosticContext = diagnosticContext
|
||||
};
|
||||
|
||||
try
|
||||
{
|
||||
var clientLogger = ConnectionLogManager.GetClientLogger();
|
||||
var localEndPoint = _connection?.LocalEndPoint?.ToString() ?? "[Unknown]";
|
||||
clientLogger.LogDisconnection(
|
||||
Nickname ?? "self",
|
||||
"[QUIC Client]",
|
||||
remoteEndPoint.ToString(),
|
||||
localEndPoint,
|
||||
determinedReason.ToString(),
|
||||
initiator,
|
||||
exception,
|
||||
diagnosticContext
|
||||
);
|
||||
}
|
||||
catch (Exception logEx)
|
||||
{
|
||||
|
||||
System.Diagnostics.Debug.WriteLine($"Failed to log disconnection: {logEx.Message}");
|
||||
}
|
||||
|
||||
HandlingHelpers.SafeInvokeEventHandler(
|
||||
OnDisconnected,
|
||||
this,
|
||||
connectionEventArgs,
|
||||
nameof(OnDisconnected));
|
||||
}
|
||||
|
||||
private async Task AutoReconnectAsync(CancellationToken token)
|
||||
{
|
||||
while (!token.IsCancellationRequested && !_stopAutoReconnecting)
|
||||
{
|
||||
try
|
||||
{
|
||||
await Task.Delay(TimeSpan.FromSeconds(_config.ReconnectDelayInSeconds), token).ConfigureAwait(false);
|
||||
|
||||
if (!IsConnected && _wasConnected)
|
||||
{
|
||||
OnLog?.Invoke(this, new LogMessage { Type = LogType.Debug, Message = "QUIC auto-reconnect: attempting reconnection..." });
|
||||
await ConnectAsync().ConfigureAwait(false);
|
||||
}
|
||||
}
|
||||
catch (OperationCanceledException)
|
||||
{
|
||||
break;
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
OnLog?.Invoke(this, new LogMessage { Type = LogType.Error, Message = $"QUIC auto-reconnect error: {ex.Message}" });
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
public void StopAutoReconnect()
|
||||
{
|
||||
_stopAutoReconnecting = true;
|
||||
_autoReconnectSource?.Cancel();
|
||||
}
|
||||
|
||||
public void Dispose()
|
||||
{
|
||||
if (_disposed)
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
_disposed = true;
|
||||
|
||||
try
|
||||
{
|
||||
_clientCts?.Cancel();
|
||||
_clientCts?.Dispose();
|
||||
}
|
||||
catch
|
||||
{
|
||||
|
||||
}
|
||||
|
||||
try
|
||||
{
|
||||
_connectionCts?.Cancel();
|
||||
_connectionCts?.Dispose();
|
||||
}
|
||||
catch
|
||||
{
|
||||
|
||||
}
|
||||
|
||||
try
|
||||
{
|
||||
_autoReconnectSource?.Cancel();
|
||||
_autoReconnectSource?.Dispose();
|
||||
}
|
||||
catch
|
||||
{
|
||||
|
||||
}
|
||||
|
||||
try
|
||||
{
|
||||
_stream?.Dispose();
|
||||
}
|
||||
catch
|
||||
{
|
||||
|
||||
}
|
||||
|
||||
_connectLock.Dispose();
|
||||
_streamWriteLock.Dispose();
|
||||
|
||||
GC.SuppressFinalize(this);
|
||||
}
|
||||
|
||||
public async ValueTask DisposeAsync()
|
||||
{
|
||||
if (_disposed)
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
_disposed = true;
|
||||
|
||||
try
|
||||
{
|
||||
_clientCts?.Cancel();
|
||||
_clientCts?.Dispose();
|
||||
}
|
||||
catch
|
||||
{
|
||||
|
||||
}
|
||||
|
||||
try
|
||||
{
|
||||
_connectionCts?.Cancel();
|
||||
_connectionCts?.Dispose();
|
||||
}
|
||||
catch
|
||||
{
|
||||
|
||||
}
|
||||
|
||||
try
|
||||
{
|
||||
_autoReconnectSource?.Cancel();
|
||||
_autoReconnectSource?.Dispose();
|
||||
}
|
||||
catch
|
||||
{
|
||||
|
||||
}
|
||||
|
||||
try
|
||||
{
|
||||
_stream?.Dispose();
|
||||
}
|
||||
catch
|
||||
{
|
||||
|
||||
}
|
||||
|
||||
try
|
||||
{
|
||||
if (_connection is not null)
|
||||
{
|
||||
await _connection.DisposeAsync().ConfigureAwait(false);
|
||||
}
|
||||
}
|
||||
catch
|
||||
{
|
||||
|
||||
}
|
||||
|
||||
_connectLock.Dispose();
|
||||
_streamWriteLock.Dispose();
|
||||
|
||||
GC.SuppressFinalize(this);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,634 @@
|
||||
using EonaCat.Connections.EventArguments;
|
||||
using EonaCat.Connections.Models;
|
||||
using EonaCat.Connections.ConnectionDiagnostics;
|
||||
using EonaCat.Connections.Helpers;
|
||||
using System.Buffers;
|
||||
using System.Collections.Concurrent;
|
||||
using System.Net;
|
||||
using System.Net.Quic;
|
||||
using System.Net.Security;
|
||||
using System.Runtime.Versioning;
|
||||
using System.Text;
|
||||
using ErrorEventArgs = EonaCat.Connections.EventArguments.ErrorEventArgs;
|
||||
|
||||
namespace EonaCat.Connections.Quic
|
||||
{
|
||||
[SupportedOSPlatform("windows")]
|
||||
[SupportedOSPlatform("linux")]
|
||||
[SupportedOSPlatform("macos")]
|
||||
[RequiresPreviewFeatures]
|
||||
public class QuicNetworkServer : IDisposable
|
||||
{
|
||||
public static event EventHandler<LogMessage> OnLog;
|
||||
public int DEFAULT_STREAM_ERROR_CODE { get; set; } = 0;
|
||||
public int DEFAULT_CLOSE_ERROR_CODE { get; set; } = 0;
|
||||
public int MAX_INBOUND_BIDIRECTIONAL_STREAMS { get; set; } = 10;
|
||||
public int MAX_INBOUND_UNIDIRECTIONAL_STREAMS { get; set; } = 10;
|
||||
public string PROTOCOL_CONNECTION_NAME { get; set; } = "EonaCat-connector";
|
||||
|
||||
private readonly Configuration _config;
|
||||
private readonly Stats _stats;
|
||||
private readonly ConcurrentDictionary<string, QuicClientConnection> _clients = new();
|
||||
private QuicListener? _listener;
|
||||
private CancellationTokenSource? _serverCts;
|
||||
private Task? _acceptTask;
|
||||
private bool _disposed;
|
||||
|
||||
public bool IsStarted => _serverCts != null && !_serverCts.IsCancellationRequested;
|
||||
public int ActiveConnections => GetActiveConnectionCount();
|
||||
public int MaxConnections => _config.MaxConnections;
|
||||
public string IpAddress => _config.Host;
|
||||
public int Port => _config.Port;
|
||||
public long BytesSent => _stats.BytesSent;
|
||||
public long BytesReceived => _stats.BytesReceived;
|
||||
public long MessagesSent => _stats.MessagesSent;
|
||||
public long MessagesReceived => _stats.MessagesReceived;
|
||||
public double MessagesPerSecond => _stats.MessagesPerSecond;
|
||||
public long TotalConnections => _stats.TotalConnections;
|
||||
public long DroppedConnections => _stats.DroppedConnections;
|
||||
public TimeSpan Uptime => _stats.Uptime;
|
||||
public DateTime StartTime => _stats.StartTime;
|
||||
|
||||
public event EventHandler<ConnectionEventArgs>? OnConnected;
|
||||
public event EventHandler<DataReceivedEventArgs>? OnDataReceived;
|
||||
public event EventHandler<ConnectionEventArgs>? OnDisconnected;
|
||||
public event EventHandler<ErrorEventArgs>? OnGeneralError;
|
||||
|
||||
public QuicNetworkServer(Configuration config)
|
||||
{
|
||||
_config = config ?? throw new ArgumentNullException(nameof(config));
|
||||
_stats = new Stats { StartTime = DateTime.UtcNow };
|
||||
|
||||
if (_config.Certificate == null)
|
||||
{
|
||||
throw new ArgumentException("A TLS certificate is required for QUIC. Set Configuration.Certificate.", nameof(config));
|
||||
}
|
||||
}
|
||||
|
||||
public Stats GetStats()
|
||||
{
|
||||
_stats.ActiveConnections = GetActiveConnectionCount();
|
||||
return _stats;
|
||||
}
|
||||
|
||||
private int GetActiveConnectionCount()
|
||||
{
|
||||
if (_clients.IsEmpty)
|
||||
{
|
||||
return 0;
|
||||
}
|
||||
|
||||
int activeCount = 0;
|
||||
foreach (var client in _clients.Values)
|
||||
{
|
||||
if (client?.Connection != null)
|
||||
{
|
||||
activeCount++;
|
||||
}
|
||||
}
|
||||
|
||||
return activeCount;
|
||||
}
|
||||
|
||||
private bool CanAcceptConnection()
|
||||
{
|
||||
return _config.MaxConnections <= 0 || GetActiveConnectionCount() < _config.MaxConnections;
|
||||
}
|
||||
|
||||
private void TrackDisconnect(DisconnectReason reason)
|
||||
{
|
||||
if (reason == DisconnectReason.Error
|
||||
|| reason == DisconnectReason.Timeout
|
||||
|| reason == DisconnectReason.SSLError
|
||||
|| reason == DisconnectReason.NoPongReceived
|
||||
|| reason == DisconnectReason.ProtocolError)
|
||||
{
|
||||
_stats.IncrementDroppedConnections();
|
||||
}
|
||||
}
|
||||
|
||||
public async Task StartAsync()
|
||||
{
|
||||
if (!QuicListener.IsSupported)
|
||||
{
|
||||
HandlingHelpers.SafeInvokeEventHandler(
|
||||
OnGeneralError,
|
||||
this,
|
||||
new ErrorEventArgs
|
||||
{
|
||||
Message = "QUIC is not supported on this platform."
|
||||
},
|
||||
nameof(OnGeneralError));
|
||||
return;
|
||||
}
|
||||
|
||||
_serverCts?.Dispose();
|
||||
_serverCts = new CancellationTokenSource();
|
||||
|
||||
var listenerOptions = new QuicListenerOptions
|
||||
{
|
||||
ListenEndPoint = new IPEndPoint(IPAddress.Parse(_config.Host), _config.Port),
|
||||
ApplicationProtocols = new List<SslApplicationProtocol>
|
||||
{
|
||||
new SslApplicationProtocol(PROTOCOL_CONNECTION_NAME)
|
||||
},
|
||||
ConnectionOptionsCallback = (connection, clientHello, token) =>
|
||||
{
|
||||
var serverOptions = new QuicServerConnectionOptions
|
||||
{
|
||||
DefaultStreamErrorCode = DEFAULT_STREAM_ERROR_CODE,
|
||||
DefaultCloseErrorCode = DEFAULT_CLOSE_ERROR_CODE,
|
||||
MaxInboundBidirectionalStreams = MAX_INBOUND_BIDIRECTIONAL_STREAMS,
|
||||
MaxInboundUnidirectionalStreams = MAX_INBOUND_UNIDIRECTIONAL_STREAMS,
|
||||
ServerAuthenticationOptions = new SslServerAuthenticationOptions
|
||||
{
|
||||
ApplicationProtocols = new List<SslApplicationProtocol>
|
||||
{
|
||||
new SslApplicationProtocol(PROTOCOL_CONNECTION_NAME)
|
||||
},
|
||||
ServerCertificateContext = SslStreamCertificateContext.Create(_config.Certificate, additionalCertificates: _config.AdditionalCertificates)
|
||||
}
|
||||
};
|
||||
return ValueTask.FromResult(serverOptions);
|
||||
}
|
||||
};
|
||||
|
||||
_listener = await QuicListener.ListenAsync(listenerOptions, _serverCts.Token).ConfigureAwait(false);
|
||||
_acceptTask = Task.Run(() => AcceptClientsAsync(_serverCts.Token), _serverCts.Token);
|
||||
|
||||
OnLog?.Invoke(this, new LogMessage { Type = LogType.Trace, Message = $"EonaCat QUIC server started on {_config.Host}:{_config.Port}" });
|
||||
}
|
||||
|
||||
private async Task AcceptClientsAsync(CancellationToken token)
|
||||
{
|
||||
while (!token.IsCancellationRequested && _listener != null)
|
||||
{
|
||||
try
|
||||
{
|
||||
var connection = await _listener.AcceptConnectionAsync(token).ConfigureAwait(false);
|
||||
|
||||
if (!CanAcceptConnection())
|
||||
{
|
||||
_stats.IncrementDroppedConnections();
|
||||
try
|
||||
{
|
||||
await connection.CloseAsync(0).ConfigureAwait(false);
|
||||
await connection.DisposeAsync().ConfigureAwait(false);
|
||||
}
|
||||
catch
|
||||
{
|
||||
|
||||
}
|
||||
continue;
|
||||
}
|
||||
|
||||
_ = Task.Run(() => HandleConnectionAsync(connection, token), token);
|
||||
}
|
||||
catch (OperationCanceledException)
|
||||
{
|
||||
break;
|
||||
}
|
||||
catch (QuicException ex) when (ex.QuicError == QuicError.OperationAborted)
|
||||
{
|
||||
break;
|
||||
}
|
||||
catch (Exception exception)
|
||||
{
|
||||
OnGeneralError?.Invoke(this, new ErrorEventArgs
|
||||
{
|
||||
Exception = exception,
|
||||
Message = "Error accepting QUIC connection"
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private async Task HandleConnectionAsync(QuicConnection connection, CancellationToken token)
|
||||
{
|
||||
var clientId = Guid.NewGuid().ToString("N");
|
||||
var remoteEndPoint = connection.RemoteEndPoint;
|
||||
QuicStream? stream = null;
|
||||
|
||||
var clientConnection = new QuicClientConnection
|
||||
{
|
||||
Id = clientId,
|
||||
Connection = connection,
|
||||
RemoteEndPoint = remoteEndPoint,
|
||||
ConnectedAt = DateTime.UtcNow
|
||||
};
|
||||
|
||||
if (!_clients.TryAdd(clientId, clientConnection))
|
||||
{
|
||||
_stats.IncrementDroppedConnections();
|
||||
try
|
||||
{
|
||||
await connection.CloseAsync(0).ConfigureAwait(false);
|
||||
await connection.DisposeAsync().ConfigureAwait(false);
|
||||
}
|
||||
catch
|
||||
{
|
||||
|
||||
}
|
||||
return;
|
||||
}
|
||||
|
||||
_stats.IncrementTotalConnections();
|
||||
|
||||
HandlingHelpers.SafeInvokeEventHandler(
|
||||
OnConnected,
|
||||
this,
|
||||
new ConnectionEventArgs
|
||||
{
|
||||
ClientId = clientId,
|
||||
RemoteEndPoint = remoteEndPoint
|
||||
},
|
||||
nameof(OnConnected));
|
||||
|
||||
byte[]? buffer = null;
|
||||
try
|
||||
{
|
||||
stream = await connection.AcceptInboundStreamAsync(token).ConfigureAwait(false);
|
||||
clientConnection.Stream = stream;
|
||||
|
||||
buffer = ArrayPool<byte>.Shared.Rent(_config.BufferSize);
|
||||
|
||||
while (!token.IsCancellationRequested)
|
||||
{
|
||||
int bytesRead = await stream.ReadAsync(buffer, 0, buffer.Length, token).ConfigureAwait(false);
|
||||
if (bytesRead == 0)
|
||||
{
|
||||
break;
|
||||
}
|
||||
|
||||
clientConnection.LastActive = DateTime.UtcNow;
|
||||
clientConnection.LastDataReceived = DateTime.UtcNow;
|
||||
clientConnection.BytesReceived += bytesRead;
|
||||
clientConnection.MessagesReceived++;
|
||||
_stats.AddBytesReceived(bytesRead);
|
||||
_stats.IncrementMessagesReceived();
|
||||
|
||||
var data = new byte[bytesRead];
|
||||
Buffer.BlockCopy(buffer, 0, data, 0, bytesRead);
|
||||
|
||||
var text = Encoding.UTF8.GetString(data);
|
||||
if (text.StartsWith("NICK:", StringComparison.Ordinal))
|
||||
{
|
||||
clientConnection.Nickname = text.Substring(5);
|
||||
continue;
|
||||
}
|
||||
|
||||
HandlingHelpers.SafeInvokeEventHandler(
|
||||
OnDataReceived,
|
||||
this,
|
||||
new DataReceivedEventArgs
|
||||
{
|
||||
ClientId = clientId,
|
||||
Data = data,
|
||||
RemoteEndPoint = remoteEndPoint,
|
||||
Nickname = clientConnection.Nickname
|
||||
},
|
||||
nameof(OnDataReceived));
|
||||
}
|
||||
}
|
||||
catch (OperationCanceledException)
|
||||
{
|
||||
|
||||
}
|
||||
catch (QuicException ex) when (ex.QuicError == QuicError.ConnectionAborted)
|
||||
{
|
||||
|
||||
}
|
||||
catch (Exception exception)
|
||||
{
|
||||
HandlingHelpers.SafeInvokeEventHandler(
|
||||
OnGeneralError,
|
||||
this,
|
||||
new ErrorEventArgs
|
||||
{
|
||||
ClientId = clientId,
|
||||
Nickname = clientConnection.Nickname,
|
||||
Exception = exception,
|
||||
Message = "Error handling QUIC client"
|
||||
},
|
||||
nameof(OnGeneralError));
|
||||
}
|
||||
finally
|
||||
{
|
||||
if (buffer != null)
|
||||
{
|
||||
ArrayPool<byte>.Shared.Return(buffer);
|
||||
}
|
||||
|
||||
_clients.TryRemove(clientId, out _);
|
||||
|
||||
try
|
||||
{
|
||||
if (stream != null)
|
||||
{
|
||||
stream.Abort(QuicAbortDirection.Both, 0);
|
||||
await stream.DisposeAsync().ConfigureAwait(false);
|
||||
}
|
||||
}
|
||||
catch
|
||||
{
|
||||
|
||||
}
|
||||
|
||||
try
|
||||
{
|
||||
await connection.CloseAsync(0).ConfigureAwait(false);
|
||||
await connection.DisposeAsync().ConfigureAwait(false);
|
||||
}
|
||||
catch
|
||||
{
|
||||
|
||||
}
|
||||
|
||||
var initiator = DisconnectionDiagnostics.DetermineInitiator(DisconnectReason.RemoteClosed, null);
|
||||
var reasonDetails = DisconnectionDiagnostics.GetDetailedReasonDescription(DisconnectReason.RemoteClosed, null);
|
||||
|
||||
var diagnosticContext = new Dictionary<string, string>
|
||||
{
|
||||
{ "IsLocalInitiated", initiator == "Local" ? "true" : "false" }
|
||||
};
|
||||
|
||||
var connectionEventArgs = new ConnectionEventArgs
|
||||
{
|
||||
ClientId = clientId,
|
||||
Nickname = clientConnection.Nickname,
|
||||
RemoteEndPoint = remoteEndPoint,
|
||||
Reason = DisconnectReason.RemoteClosed,
|
||||
Initiator = initiator,
|
||||
ReasonDetails = reasonDetails,
|
||||
DiagnosticContext = diagnosticContext
|
||||
};
|
||||
|
||||
try
|
||||
{
|
||||
var serverLogger = ConnectionLogManager.GetServerLogger();
|
||||
var localEndPoint = clientConnection.Connection?.LocalEndPoint?.ToString() ?? "[Unknown]";
|
||||
serverLogger.LogDisconnection(
|
||||
clientId,
|
||||
clientConnection.Nickname,
|
||||
remoteEndPoint?.ToString() ?? "[Unknown]",
|
||||
localEndPoint,
|
||||
DisconnectReason.RemoteClosed.ToString(),
|
||||
initiator,
|
||||
null,
|
||||
diagnosticContext
|
||||
);
|
||||
}
|
||||
catch (Exception logEx)
|
||||
{
|
||||
|
||||
System.Diagnostics.Debug.WriteLine($"Failed to log disconnection: {logEx.Message}");
|
||||
}
|
||||
|
||||
HandlingHelpers.SafeInvokeEventHandler(
|
||||
OnDisconnected,
|
||||
this,
|
||||
connectionEventArgs,
|
||||
nameof(OnDisconnected));
|
||||
}
|
||||
}
|
||||
|
||||
public async Task<bool> SendToClientAsync(string clientId, byte[] data)
|
||||
{
|
||||
if (!_clients.TryGetValue(clientId, out var client) || client.Stream == null)
|
||||
{
|
||||
return false;
|
||||
}
|
||||
|
||||
try
|
||||
{
|
||||
await client.WriteLock.WaitAsync().ConfigureAwait(false);
|
||||
try
|
||||
{
|
||||
await client.Stream.WriteAsync(data).ConfigureAwait(false);
|
||||
await client.Stream.FlushAsync().ConfigureAwait(false);
|
||||
}
|
||||
finally
|
||||
{
|
||||
client.WriteLock.Release();
|
||||
}
|
||||
|
||||
client.LastActive = DateTime.UtcNow;
|
||||
client.LastDataSent = DateTime.UtcNow;
|
||||
client.BytesSent += data.Length;
|
||||
client.MessagesSent++;
|
||||
_stats.AddBytesSent(data.Length);
|
||||
_stats.IncrementMessagesSent();
|
||||
return true;
|
||||
}
|
||||
catch (Exception exception)
|
||||
{
|
||||
OnGeneralError?.Invoke(this, new ErrorEventArgs
|
||||
{
|
||||
ClientId = clientId,
|
||||
Nickname = client.Nickname,
|
||||
Exception = exception,
|
||||
Message = "Error sending data to QUIC client"
|
||||
});
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
public async Task<bool> SendToClientAsync(string clientId, string message)
|
||||
=> await SendToClientAsync(clientId, Encoding.UTF8.GetBytes(message)).ConfigureAwait(false);
|
||||
|
||||
public async Task<bool> BroadcastAsync(byte[] data)
|
||||
{
|
||||
if (data == null || data.Length == 0)
|
||||
{
|
||||
return false;
|
||||
}
|
||||
|
||||
bool any = false;
|
||||
foreach (var client in _clients)
|
||||
{
|
||||
if (await SendToClientAsync(client.Key, data).ConfigureAwait(false))
|
||||
{
|
||||
any = true;
|
||||
}
|
||||
}
|
||||
return any;
|
||||
}
|
||||
|
||||
public async Task<bool> BroadcastAsync(string message)
|
||||
=> await BroadcastAsync(Encoding.UTF8.GetBytes(message)).ConfigureAwait(false);
|
||||
|
||||
public ConcurrentDictionary<string, QuicClientConnection> GetClients() => _clients;
|
||||
|
||||
public async Task DisconnectClientAsync(string clientId, DisconnectReason reason = DisconnectReason.ServerShutdown)
|
||||
{
|
||||
if (!_clients.TryRemove(clientId, out var client))
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
try
|
||||
{
|
||||
if (client.Stream != null)
|
||||
{
|
||||
client.Stream.Abort(QuicAbortDirection.Both, 0);
|
||||
await client.Stream.DisposeAsync().ConfigureAwait(false);
|
||||
}
|
||||
}
|
||||
catch
|
||||
{
|
||||
|
||||
}
|
||||
|
||||
try
|
||||
{
|
||||
if (client.Connection != null)
|
||||
{
|
||||
await client.Connection.CloseAsync(0).ConfigureAwait(false);
|
||||
await client.Connection.DisposeAsync().ConfigureAwait(false);
|
||||
}
|
||||
}
|
||||
catch
|
||||
{
|
||||
|
||||
}
|
||||
|
||||
TrackDisconnect(reason);
|
||||
|
||||
var initiator = DisconnectionDiagnostics.DetermineInitiator(reason, null);
|
||||
var reasonDetails = DisconnectionDiagnostics.GetDetailedReasonDescription(reason, null);
|
||||
|
||||
var diagnosticContext = new Dictionary<string, string>
|
||||
{
|
||||
{ "IsLocalInitiated", initiator == "Local" ? "true" : "false" }
|
||||
};
|
||||
|
||||
var connectionEventArgs = new ConnectionEventArgs
|
||||
{
|
||||
ClientId = clientId,
|
||||
Nickname = client.Nickname,
|
||||
RemoteEndPoint = client.RemoteEndPoint,
|
||||
Reason = reason,
|
||||
Initiator = initiator,
|
||||
ReasonDetails = reasonDetails,
|
||||
DiagnosticContext = diagnosticContext
|
||||
};
|
||||
|
||||
try
|
||||
{
|
||||
var serverLogger = ConnectionLogManager.GetServerLogger();
|
||||
var localEndPoint = client.Connection?.LocalEndPoint?.ToString() ?? "[Unknown]";
|
||||
serverLogger.LogDisconnection(
|
||||
clientId,
|
||||
client.Nickname,
|
||||
client.RemoteEndPoint?.ToString() ?? "[Unknown]",
|
||||
localEndPoint,
|
||||
reason.ToString(),
|
||||
initiator,
|
||||
null,
|
||||
diagnosticContext
|
||||
);
|
||||
}
|
||||
catch (Exception logEx)
|
||||
{
|
||||
|
||||
System.Diagnostics.Debug.WriteLine($"Failed to log disconnection: {logEx.Message}");
|
||||
}
|
||||
|
||||
HandlingHelpers.SafeInvokeEventHandler(
|
||||
OnDisconnected,
|
||||
this,
|
||||
connectionEventArgs,
|
||||
nameof(OnDisconnected));
|
||||
}
|
||||
|
||||
public void Stop()
|
||||
{
|
||||
_serverCts?.Cancel();
|
||||
|
||||
try
|
||||
{
|
||||
if (_listener != null)
|
||||
{
|
||||
_listener.DisposeAsync().AsTask().Wait();
|
||||
}
|
||||
}
|
||||
catch
|
||||
{
|
||||
|
||||
}
|
||||
|
||||
_listener = null;
|
||||
|
||||
foreach (var client in _clients.Keys.ToList())
|
||||
{
|
||||
try
|
||||
{
|
||||
DisconnectClientAsync(client, DisconnectReason.ServerShutdown).Wait();
|
||||
}
|
||||
catch
|
||||
{
|
||||
|
||||
}
|
||||
}
|
||||
|
||||
_clients.Clear();
|
||||
}
|
||||
|
||||
public async Task StopAsync()
|
||||
{
|
||||
_serverCts?.Cancel();
|
||||
|
||||
try
|
||||
{
|
||||
if (_listener != null)
|
||||
{
|
||||
await _listener.DisposeAsync().ConfigureAwait(false);
|
||||
}
|
||||
}
|
||||
catch
|
||||
{
|
||||
|
||||
}
|
||||
|
||||
_listener = null;
|
||||
|
||||
foreach (var client in _clients.Keys.ToList())
|
||||
{
|
||||
await DisconnectClientAsync(client, DisconnectReason.ServerShutdown).ConfigureAwait(false);
|
||||
}
|
||||
|
||||
_clients.Clear();
|
||||
|
||||
if (_acceptTask != null)
|
||||
{
|
||||
try
|
||||
{
|
||||
await _acceptTask.ConfigureAwait(false);
|
||||
}
|
||||
catch
|
||||
{
|
||||
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
public void Dispose()
|
||||
{
|
||||
if (_disposed)
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
_disposed = true;
|
||||
|
||||
Stop();
|
||||
|
||||
_serverCts?.Dispose();
|
||||
|
||||
OnConnected = null;
|
||||
OnDisconnected = null;
|
||||
OnDataReceived = null;
|
||||
OnGeneralError = null;
|
||||
}
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user