635 lines
21 KiB
C#
635 lines
21 KiB
C#
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;
|
|
}
|
|
}
|
|
}
|