From 22dee59f476d43d1d015c6a57a8fb99bb52e53a8 Mon Sep 17 00:00:00 2001 From: EonaCat Date: Wed, 4 Nov 2026 07:53:40 +0100 Subject: [PATCH] Updated --- .dockerignore | 25 + Custom Crap/CUSTOMPROTOCOLS.md | 401 +++ Custom Crap/PROTOCOLSUPPORT.md | 105 + .../EonaCat.Connections.Client.csproj | 2 +- EonaCat.Connections.Client/JsonTest.cs | 72 - EonaCat.Connections.Client/Program.cs | 676 ++++- .../EonaCat.Connections.OpcUa.Client.csproj | 14 + EonaCat.Connections.OpcUa.Client/Program.cs | 41 + .../EonaCat.Connections.OpcUa.Server.csproj | 14 + EonaCat.Connections.OpcUa.Server/Program.cs | 39 + .../Client/OpcUaNetworkClient.cs | 309 ++ .../Client/OpcUaSubscription.cs | 30 + .../Configuration/OpcUaClientOptions.cs | 20 + .../Configuration/OpcUaServerOptions.cs | 19 + .../EonaCat.Connections.OpcUa.csproj | 26 + .../OpcUaApplicationConfigurationFactory.cs | 158 + .../Infrastructure/OpcUaRuntime.cs | 12 + .../Models/OpcUaConnectionEventArgs.cs | 7 + .../Models/OpcUaMethodDefinition.cs | 13 + .../Models/OpcUaNodeDefinition.cs | 11 + .../Models/OpcUaValueChangedEventArgs.cs | 11 + .../Server/HeijmansOpcUaServer.cs | 44 + .../Server/OpcUaAddressSpace.cs | 197 ++ .../Server/OpcUaNetworkServer.cs | 170 ++ .../EonaCat.Connections.Quic.Client.csproj | 14 + EonaCat.Connections.Quic.Client/Program.cs | 75 + .../EonaCat.Connections.Quic.Server.csproj | 14 + EonaCat.Connections.Quic.Server/Program.cs | 117 + .../EonaCat.Connections.Quic.csproj | 25 + .../QuicClientConnection.cs | 37 + EonaCat.Connections.Quic/QuicNetworkClient.cs | 554 ++++ EonaCat.Connections.Quic/QuicNetworkServer.cs | 634 ++++ .../EonaCat.Connections.REST.Client.csproj | 14 + EonaCat.Connections.REST.Client/Program.cs | 91 + .../EonaCat.Connections.REST.Server.csproj | 14 + EonaCat.Connections.REST.Server/Program.cs | 114 + .../EonaCat.Connections.REST.csproj | 30 + .../RestClientConnection.cs | 50 + EonaCat.Connections.REST/RestNetworkClient.cs | 859 ++++++ EonaCat.Connections.REST/RestNetworkServer.cs | 732 +++++ EonaCat.Connections.REST/WebhookManager.cs | 91 + .../EonaCat.Connections.Server.csproj | 2 +- EonaCat.Connections.Server/Program.cs | 197 +- .../EonaCat.Connections.gRPC.Client.csproj | 14 + EonaCat.Connections.gRPC.Client/Program.cs | 73 + .../EonaCat.Connections.gRPC.Server.csproj | 14 + EonaCat.Connections.gRPC.Server/Program.cs | 115 + .../ConnectorServiceImplementation.cs | 163 ++ .../EonaCat.Connections.gRPC.csproj | 35 + .../GrpcChannelFactory.cs | 77 + .../GrpcClientConnection.cs | 40 + EonaCat.Connections.gRPC/GrpcNetworkClient.cs | 599 ++++ EonaCat.Connections.gRPC/GrpcNetworkServer.cs | 698 +++++ .../Protos/connector.proto | 23 + EonaCat.Connections.sln | 198 +- EonaCat.Connections/BufferSize.cs | 24 +- EonaCat.Connections/Client/LogType.cs | 18 + .../Client/NetworkClient.Connection.cs | 1116 +++++++ .../Client/NetworkClient.Diagnostics.cs | 73 + .../Client/NetworkClient.Heartbeat.cs | 225 ++ .../Client/NetworkClient.Receiving.cs | 679 +++++ .../Client/NetworkClient.Reconnect.cs | 163 ++ .../Client/NetworkClient.Sending.cs | 418 +++ .../Client/NetworkClient.Status.cs | 163 ++ .../ConnectionDiagnostics/ConnectionLogger.cs | 282 ++ .../ConnectionTimeFormatter.cs | 43 + .../DisconnectionDiagnostics.cs | 276 ++ EonaCat.Connections/ConnectionLogManager.cs | 53 + .../Contracts/IConnectorClient.cs | 54 + .../Contracts/IConnectorServer.cs | 46 + EonaCat.Connections/DisconnectReason.cs | 20 +- .../EonaCat.Connections.csproj | 52 +- EonaCat.Connections/EonaCat.ico | Bin 254014 -> 0 bytes EonaCat.Connections/EonaCat.png | Bin 89562 -> 0 bytes .../EventArguments/ClientMissingEventArgs.cs | 9 + .../EventArguments/ConnectionEventArgs.cs | 34 +- .../EventArguments/DataReceivedEventArgs.cs | 7 +- .../EventArguments/ErrorEventArgs.cs | 25 +- .../EventArguments/IdleClientEventArgs.cs | 30 - .../EventArguments/IdleEventArgs.cs | 24 - .../EventArguments/PingEventArgs.cs | 5 +- .../Framing/MessageFrameDecoder.cs | 128 + .../Framing/MessageFrameEncoder.cs | 109 + EonaCat.Connections/Helpers/AesKeyExchange.cs | 23 +- .../Helpers/CertificateHelper.cs | 270 ++ .../Helpers/HandlingHelpers.cs | 169 ++ .../Helpers/HealthApiServer.cs | 256 +- EonaCat.Connections/Helpers/LoadTester.cs | 261 ++ EonaCat.Connections/Helpers/NetworkMonitor.cs | 29 +- .../Helpers/ProtocolProbeStream.cs | 97 + .../Helpers/SecurityValidator.cs | 253 -- .../Helpers/SslHandshakeDiagnostics.cs | 40 +- EonaCat.Connections/Helpers/SslMetrics.cs | 66 +- EonaCat.Connections/Helpers/StringHelper.cs | 88 +- EonaCat.Connections/Helpers/TcpSeparators.cs | 5 +- .../Helpers/TrafficDashboard.html | 196 ++ .../SocketKeepAliveConfigurator.cs | 46 + .../Messaging/ResponseAwaiter.cs | 108 + EonaCat.Connections/Models/Configuration.cs | 309 +- EonaCat.Connections/Models/Connection.cs | 114 +- EonaCat.Connections/Models/FramingMode.cs | 5 +- .../Models/ProcessedMessage.cs | 5 +- .../Models/ProcessedTextMessage.cs | 7 +- EonaCat.Connections/Models/ProtocolType.cs | 17 +- EonaCat.Connections/Models/SecurityOptions.cs | 82 + .../Models/ServerStatusPage.cs | 107 +- .../Models/SocketErrorEntry.cs | 3 - .../Models/SocketStatusPage.cs | 28 +- EonaCat.Connections/Models/Stats.cs | 11 +- EonaCat.Connections/NetworkClient.cs | 2559 +---------------- EonaCat.Connections/NetworkServer.cs | 2435 +--------------- .../Processors/JsonDataProcessor.cs | 7 +- .../Protocols/INetworkProtocol.cs | 50 + .../Protocols/ProtocolFactory.cs | 83 + EonaCat.Connections/Protocols/TcpProtocol.cs | 422 +++ EonaCat.Connections/Protocols/UdpProtocol.cs | 243 ++ EonaCat.Connections/Security/DDoSDetector.cs | 264 ++ EonaCat.Connections/Security/IPBlocklist.cs | 260 ++ .../Security/PayloadValidator.cs | 359 +++ EonaCat.Connections/Security/RateLimiter.cs | 216 ++ .../Server/NetworkServer.ClientRegistry.cs | 217 ++ .../Server/NetworkServer.Diagnostics.cs | 55 + .../Server/NetworkServer.Heartbeat.cs | 141 + .../Server/NetworkServer.Lifecycle.cs | 525 ++++ .../Server/NetworkServer.Listeners.cs | 903 ++++++ .../Server/NetworkServer.Receiving.cs | 601 ++++ .../Server/NetworkServer.Sending.cs | 392 +++ .../Server/NetworkServer.Status.cs | 328 +++ EonaCat.Connections/Testing/StressTest.cs | 448 +++ EonaCat.Connections/icon.ico | Bin 254014 -> 7406 bytes README.md | 1512 ++++------ docker/Dockerfile | 25 + 132 files changed, 19653 insertions(+), 7192 deletions(-) create mode 100644 .dockerignore create mode 100644 Custom Crap/CUSTOMPROTOCOLS.md create mode 100644 Custom Crap/PROTOCOLSUPPORT.md delete mode 100644 EonaCat.Connections.Client/JsonTest.cs create mode 100644 EonaCat.Connections.OpcUa.Client/EonaCat.Connections.OpcUa.Client.csproj create mode 100644 EonaCat.Connections.OpcUa.Client/Program.cs create mode 100644 EonaCat.Connections.OpcUa.Server/EonaCat.Connections.OpcUa.Server.csproj create mode 100644 EonaCat.Connections.OpcUa.Server/Program.cs create mode 100644 EonaCat.Connections.OpcUa/Client/OpcUaNetworkClient.cs create mode 100644 EonaCat.Connections.OpcUa/Client/OpcUaSubscription.cs create mode 100644 EonaCat.Connections.OpcUa/Configuration/OpcUaClientOptions.cs create mode 100644 EonaCat.Connections.OpcUa/Configuration/OpcUaServerOptions.cs create mode 100644 EonaCat.Connections.OpcUa/EonaCat.Connections.OpcUa.csproj create mode 100644 EonaCat.Connections.OpcUa/Infrastructure/OpcUaApplicationConfigurationFactory.cs create mode 100644 EonaCat.Connections.OpcUa/Infrastructure/OpcUaRuntime.cs create mode 100644 EonaCat.Connections.OpcUa/Models/OpcUaConnectionEventArgs.cs create mode 100644 EonaCat.Connections.OpcUa/Models/OpcUaMethodDefinition.cs create mode 100644 EonaCat.Connections.OpcUa/Models/OpcUaNodeDefinition.cs create mode 100644 EonaCat.Connections.OpcUa/Models/OpcUaValueChangedEventArgs.cs create mode 100644 EonaCat.Connections.OpcUa/Server/HeijmansOpcUaServer.cs create mode 100644 EonaCat.Connections.OpcUa/Server/OpcUaAddressSpace.cs create mode 100644 EonaCat.Connections.OpcUa/Server/OpcUaNetworkServer.cs create mode 100644 EonaCat.Connections.Quic.Client/EonaCat.Connections.Quic.Client.csproj create mode 100644 EonaCat.Connections.Quic.Client/Program.cs create mode 100644 EonaCat.Connections.Quic.Server/EonaCat.Connections.Quic.Server.csproj create mode 100644 EonaCat.Connections.Quic.Server/Program.cs create mode 100644 EonaCat.Connections.Quic/EonaCat.Connections.Quic.csproj create mode 100644 EonaCat.Connections.Quic/QuicClientConnection.cs create mode 100644 EonaCat.Connections.Quic/QuicNetworkClient.cs create mode 100644 EonaCat.Connections.Quic/QuicNetworkServer.cs create mode 100644 EonaCat.Connections.REST.Client/EonaCat.Connections.REST.Client.csproj create mode 100644 EonaCat.Connections.REST.Client/Program.cs create mode 100644 EonaCat.Connections.REST.Server/EonaCat.Connections.REST.Server.csproj create mode 100644 EonaCat.Connections.REST.Server/Program.cs create mode 100644 EonaCat.Connections.REST/EonaCat.Connections.REST.csproj create mode 100644 EonaCat.Connections.REST/RestClientConnection.cs create mode 100644 EonaCat.Connections.REST/RestNetworkClient.cs create mode 100644 EonaCat.Connections.REST/RestNetworkServer.cs create mode 100644 EonaCat.Connections.REST/WebhookManager.cs create mode 100644 EonaCat.Connections.gRPC.Client/EonaCat.Connections.gRPC.Client.csproj create mode 100644 EonaCat.Connections.gRPC.Client/Program.cs create mode 100644 EonaCat.Connections.gRPC.Server/EonaCat.Connections.gRPC.Server.csproj create mode 100644 EonaCat.Connections.gRPC.Server/Program.cs create mode 100644 EonaCat.Connections.gRPC/ConnectorServiceImplementation.cs create mode 100644 EonaCat.Connections.gRPC/EonaCat.Connections.gRPC.csproj create mode 100644 EonaCat.Connections.gRPC/GrpcChannelFactory.cs create mode 100644 EonaCat.Connections.gRPC/GrpcClientConnection.cs create mode 100644 EonaCat.Connections.gRPC/GrpcNetworkClient.cs create mode 100644 EonaCat.Connections.gRPC/GrpcNetworkServer.cs create mode 100644 EonaCat.Connections.gRPC/Protos/connector.proto create mode 100644 EonaCat.Connections/Client/LogType.cs create mode 100644 EonaCat.Connections/Client/NetworkClient.Connection.cs create mode 100644 EonaCat.Connections/Client/NetworkClient.Diagnostics.cs create mode 100644 EonaCat.Connections/Client/NetworkClient.Heartbeat.cs create mode 100644 EonaCat.Connections/Client/NetworkClient.Receiving.cs create mode 100644 EonaCat.Connections/Client/NetworkClient.Reconnect.cs create mode 100644 EonaCat.Connections/Client/NetworkClient.Sending.cs create mode 100644 EonaCat.Connections/Client/NetworkClient.Status.cs create mode 100644 EonaCat.Connections/ConnectionDiagnostics/ConnectionLogger.cs create mode 100644 EonaCat.Connections/ConnectionDiagnostics/ConnectionTimeFormatter.cs create mode 100644 EonaCat.Connections/ConnectionDiagnostics/DisconnectionDiagnostics.cs create mode 100644 EonaCat.Connections/ConnectionLogManager.cs create mode 100644 EonaCat.Connections/Contracts/IConnectorClient.cs create mode 100644 EonaCat.Connections/Contracts/IConnectorServer.cs delete mode 100644 EonaCat.Connections/EonaCat.ico delete mode 100644 EonaCat.Connections/EonaCat.png create mode 100644 EonaCat.Connections/EventArguments/ClientMissingEventArgs.cs delete mode 100644 EonaCat.Connections/EventArguments/IdleClientEventArgs.cs delete mode 100644 EonaCat.Connections/EventArguments/IdleEventArgs.cs create mode 100644 EonaCat.Connections/Framing/MessageFrameDecoder.cs create mode 100644 EonaCat.Connections/Framing/MessageFrameEncoder.cs create mode 100644 EonaCat.Connections/Helpers/CertificateHelper.cs create mode 100644 EonaCat.Connections/Helpers/HandlingHelpers.cs create mode 100644 EonaCat.Connections/Helpers/LoadTester.cs create mode 100644 EonaCat.Connections/Helpers/ProtocolProbeStream.cs delete mode 100644 EonaCat.Connections/Helpers/SecurityValidator.cs create mode 100644 EonaCat.Connections/Helpers/TrafficDashboard.html create mode 100644 EonaCat.Connections/Infrastructure/SocketKeepAliveConfigurator.cs create mode 100644 EonaCat.Connections/Messaging/ResponseAwaiter.cs create mode 100644 EonaCat.Connections/Models/SecurityOptions.cs create mode 100644 EonaCat.Connections/Protocols/INetworkProtocol.cs create mode 100644 EonaCat.Connections/Protocols/ProtocolFactory.cs create mode 100644 EonaCat.Connections/Protocols/TcpProtocol.cs create mode 100644 EonaCat.Connections/Protocols/UdpProtocol.cs create mode 100644 EonaCat.Connections/Security/DDoSDetector.cs create mode 100644 EonaCat.Connections/Security/IPBlocklist.cs create mode 100644 EonaCat.Connections/Security/PayloadValidator.cs create mode 100644 EonaCat.Connections/Security/RateLimiter.cs create mode 100644 EonaCat.Connections/Server/NetworkServer.ClientRegistry.cs create mode 100644 EonaCat.Connections/Server/NetworkServer.Diagnostics.cs create mode 100644 EonaCat.Connections/Server/NetworkServer.Heartbeat.cs create mode 100644 EonaCat.Connections/Server/NetworkServer.Lifecycle.cs create mode 100644 EonaCat.Connections/Server/NetworkServer.Listeners.cs create mode 100644 EonaCat.Connections/Server/NetworkServer.Receiving.cs create mode 100644 EonaCat.Connections/Server/NetworkServer.Sending.cs create mode 100644 EonaCat.Connections/Server/NetworkServer.Status.cs create mode 100644 EonaCat.Connections/Testing/StressTest.cs create mode 100644 docker/Dockerfile diff --git a/.dockerignore b/.dockerignore new file mode 100644 index 0000000..e7b690f --- /dev/null +++ b/.dockerignore @@ -0,0 +1,25 @@ +**/.classpath +**/.dockerignore +**/.env +**/.git +**/.gitignore +**/.project +**/.settings +**/.toolstarget +**/.vs +**/.vscode +**/*.*proj.user +**/*.dbmdl +**/*.jfm +**/azds.yaml +**/bin +**/charts +**/docker-compose* +**/Dockerfile* +**/node_modules +**/npm-debug.log +**/obj +**/secrets.dev.yaml +**/values.dev.yaml +LICENSE +README.md diff --git a/Custom Crap/CUSTOMPROTOCOLS.md b/Custom Crap/CUSTOMPROTOCOLS.md new file mode 100644 index 0000000..2226691 --- /dev/null +++ b/Custom Crap/CUSTOMPROTOCOLS.md @@ -0,0 +1,401 @@ +# Custom Protocol Support in EonaCat.Connections + +Custom protocol implementations, allowing you to easily integrate your own protocols (QUIC, HTTP/2, WebSocket, custom binary protocols, etc.) without modifying the core library. + +## Quick Start + +### Step 1: Implement INetworkProtocol + +Create a class that implements the `INetworkProtocol` interface: + +```csharp +using System.Net.Sockets; +using EonaCat.Connections.Protocols; + +public class CustomProtocol : INetworkProtocol +{ + private Socket? _socket; + + public string ProtocolName => "MyCustomProtocol"; + public bool IsConnected => _socket?.Connected == true; + public bool CanRead => _socket != null; + public bool CanWrite => _socket != null; + + public async Task ConnectAsync(string host, int port, CancellationToken cancellationToken) + { + // Implement connection logic + _socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, + System.Net.Sockets.ProtocolType.Tcp); + + var connectCts = CancellationTokenSource.CreateLinkedTokenSource(cancellationToken); + connectCts.CancelAfter(TimeSpan.FromSeconds(30)); + + await _socket.ConnectAsync(host, port, connectCts.Token); + return true; + } + + public async Task SendAsync(byte[] data, CancellationToken cancellationToken) + { + if (data?.Length == 0 || _socket == null) + return false; + + try + { + // Add custom framing, encryption, compression, etc. + byte[] frame = PrepareFrame(data); + await _socket.SendAsync(new ArraySegment(frame), + SocketFlags.None, cancellationToken); + return true; + } + catch + { + return false; + } + } + + public async Task ReceiveAsync(CancellationToken cancellationToken) + { + if (_socket == null) + return null; + + try + { + var buffer = new byte[4096]; + var received = await _socket.ReceiveAsync( + new ArraySegment(buffer), SocketFlags.None, cancellationToken); + + if (received == 0) + return null; + + // Parse custom framing + return ParseFrame(buffer, received); + } + catch + { + return null; + } + } + + public async Task DisconnectAsync(CancellationToken cancellationToken) + { + await CleanupAsync(cancellationToken); + } + + public async Task CleanupAsync(CancellationToken cancellationToken) + { + try + { + _socket?.Shutdown(SocketShutdown.Both); + _socket?.Close(); + _socket?.Dispose(); + } + catch { } + + _socket = null; + await Task.CompletedTask; + } + + // Implement configuration methods (can be no-ops if not applicable to your protocol) + public void ConfigureKeepAlive(bool keepAliveEnabled, int timeInSeconds, + int intervalInSeconds, int retryCount) { } + + public void ConfigureSsl(bool useSsl, string? serverName, + bool checkCertificateRevocation, bool allowRenegotiation) { } + + public void ConfigureBufferSize(int bufferSize) { } + public void ConfigureNagle(bool enableNagle) { } + public void ConfigureRst(bool enableRst) { } + + public string? GetRemoteEndPoint() => _socket?.RemoteEndPoint?.ToString(); + public string? GetLocalEndPoint() => _socket?.LocalEndPoint?.ToString(); + public Socket? GetUnderlyingSocket() => _socket; + public Stream? GetUnderlyingStream() => null; + + public void Dispose() + { + try { _socket?.Dispose(); } + catch { } + } + + private byte[] PrepareFrame(byte[] data) + { + // Implement your custom frame format + // Example: add length prefix, checksum, headers, etc. + return data; + } + + private byte[]? ParseFrame(byte[] buffer, int length) + { + // Parse your custom frame format + return buffer; + } +} +``` + +### Step 2: Register Your Protocol + +Register your custom protocol with the factory (optional but recommended): + +```csharp +// Register with a factory function +ProtocolFactory.RegisterProtocol("CUSTOM", () => new CustomProtocol()); + +// Or with initialization logic +ProtocolFactory.RegisterProtocol("CUSTOM_WITH_CONFIG", () => +{ + var protocol = new CustomProtocol(); + // Custom initialization + return protocol; +}); +``` + +### Step 3: Use in Configuration + +Create a configuration that uses your custom protocol: + +```csharp +var config = new Configuration +{ + Host = "example.com", + Port = 8080, + // Option 1: Use factory function directly + ProtocolFactory = () => new CustomProtocol() + + // Option 2: Use registered protocol + // ProtocolFactory = () => ProtocolFactory.CreateProtocol("CUSTOM") +}; + +// Use with NetworkClient +var client = new NetworkClient(config); +await client.ConnectAsync(); +// Now communicating via your custom protocol! + +// Or use with NetworkServer +var server = new NetworkServer(config); +await server.StartAsync(); +``` + +### Step 4: Switching Between Protocols + +Easily switch between protocols at runtime: + +```csharp +public Configuration CreateConfig(string protocol) +{ + var config = new Configuration + { + Host = "example.com", + Port = 8080, + }; + + config.ProtocolFactory = protocol.ToUpper() switch + { + "TCP" => () => ProtocolFactory.CreateProtocol("TCP"), + "UDP" => () => ProtocolFactory.CreateProtocol("UDP"), + "CUSTOM" => () => new CustomProtocol(), + _ => () => ProtocolFactory.CreateProtocol("TCP") + }; + + return config; +} +``` + +## INetworkProtocol Interface Reference + +Your custom protocol must implement these members: + +### Properties +- `string ProtocolName` - Returns the name/identifier of your protocol +- `bool IsConnected` - Whether currently connected +- `bool CanRead` - Whether data can be read +- `bool CanWrite` - Whether data can be written + +### Core Methods +- `Task ConnectAsync(string host, int port, CancellationToken cancellationToken)` - Establish connection +- `Task SendAsync(byte[] data, CancellationToken cancellationToken)` - Send data +- `Task ReceiveAsync(CancellationToken cancellationToken)` - Receive data +- `Task DisconnectAsync(CancellationToken cancellationToken)` - Close connection +- `Task CleanupAsync(CancellationToken cancellationToken)` - Release resources + +### Configuration Methods +- `void ConfigureKeepAlive(bool enabled, int timeInSeconds, int intervalInSeconds, int retryCount)` - Configure keep-alive +- `void ConfigureSsl(bool useSsl, string? serverName, bool checkRevocation, bool allowRenegotiation)` - Configure SSL/TLS +- `void ConfigureBufferSize(int bufferSize)` - Set buffer size +- `void ConfigureNagle(bool enableNagle)` - Configure Nagle's algorithm +- `void ConfigureRst(bool enableRst)` - Configure RST on close + +### Utility Methods +- `string? GetRemoteEndPoint()` - Get remote endpoint address +- `string? GetLocalEndPoint()` - Get local endpoint address +- `Socket? GetUnderlyingSocket()` - Get underlying socket (return null if not applicable) +- `Stream? GetUnderlyingStream()` - Get underlying stream (return null if not applicable) + +### Resource Management +- `void Dispose()` - Clean up resources (implement IDisposable) + +## Use Cases + +### Custom Framing Protocol +Add protocol-specific framing (length prefixes, checksums, headers): + +```csharp +public async Task SendAsync(byte[] data, CancellationToken cancellationToken) +{ + // Add 4-byte length prefix + byte[] lengthPrefix = BitConverter.GetBytes(data.Length); + byte[] frame = new byte[lengthPrefix.Length + data.Length]; + Array.Copy(lengthPrefix, frame, lengthPrefix.Length); + Array.Copy(data, 0, frame, lengthPrefix.Length, data.Length); + + await _socket.SendAsync(new ArraySegment(frame), + SocketFlags.None, cancellationToken); + return true; +} +``` + +### Compression Protocol +Implement automatic compression: + +```csharp +public async Task SendAsync(byte[] data, CancellationToken cancellationToken) +{ + // Compress data before sending + byte[] compressed = CompressData(data); + await _stream.WriteAsync(compressed, 0, compressed.Length, cancellationToken); + return true; +} + +public async Task ReceiveAsync(CancellationToken cancellationToken) +{ + byte[] compressed = await ReadCompressedDataAsync(cancellationToken); + // Decompress data after receiving + return DecompressData(compressed); +} +``` + +### Encryption Protocol +Add encryption on top of transport: + +```csharp +private ICryptoTransform? _encryptor; +private ICryptoTransform? _decryptor; + +public async Task SendAsync(byte[] data, CancellationToken cancellationToken) +{ + // Encrypt data before sending + byte[] encrypted = _encryptor.TransformFinalBlock(data, 0, data.Length); + await _socket.SendAsync(new ArraySegment(encrypted), + SocketFlags.None, cancellationToken); + return true; +} +``` + +### WebSocket Protocol +Wrap WebSocket for application-level transport: + +```csharp +private WebSocket? _webSocket; + +public async Task ConnectAsync(string host, int port, CancellationToken cancellationToken) +{ + var uri = new Uri($"ws://{host}:{port}"); + _webSocket = new ClientWebSocket(); + await _webSocket.ConnectAsync(uri, cancellationToken); + return true; +} + +public async Task SendAsync(byte[] data, CancellationToken cancellationToken) +{ + await _webSocket.SendAsync(new ArraySegment(data), + WebSocketMessageType.Binary, endOfMessage: true, cancellationToken); + return true; +} +``` + +## Best Practices + +1. **Handle Cancellation**: Always respect the CancellationToken parameter +2. **Error Handling**: Return false on send errors, null on receive errors or connection closed +3. **Resource Cleanup**: Ensure Dispose and CleanupAsync properly release resources +4. **Thread Safety**: Use locks if needed for concurrent access +5. **Configuration**: Implement configuration methods even if they're no-ops +6. **Testing**: Test with both NetworkClient and NetworkServer +7. **Timeouts**: Implement connection timeouts in ConnectAsync +8. **State Management**: Track connection state accurately in IsConnected property + +## API Reference + +### ProtocolFactory +```csharp +// Register a custom protocol +ProtocolFactory.RegisterProtocol(string name, Func factory); + +// Create a protocol instance +INetworkProtocol protocol = ProtocolFactory.CreateProtocol("PROTOCOL_NAME"); +INetworkProtocol tcpProtocol = ProtocolFactory.CreateProtocol(ProtocolType.TCP); + +// Check if registered +bool registered = ProtocolFactory.IsProtocolRegistered("PROTOCOL_NAME"); + +// Get all registered protocol names +IEnumerable protocolNames = ProtocolFactory.GetRegisteredProtocols(); + +// Unregister a protocol (built-in TCP/UDP cannot be unregistered) +ProtocolFactory.UnregisterProtocol("CUSTOM_PROTOCOL"); +``` + +### Configuration +```csharp +var config = new Configuration +{ + // Use custom protocol via factory + ProtocolFactory = () => new CustomProtocol(), + + // Or use enum for built-in protocols (backward compatible) + // Protocol = ProtocolType.TCP, + + Host = "example.com", + Port = 8080, + BufferSize = 8192, + EnableKeepAlive = true, + EnableNagle = false, + EnableRST = true, + // ... other configuration +}; + +// Configuration automatically applies settings to protocol +// via GetProtocol() method +INetworkProtocol protocol = config.GetProtocol(); +``` + +## Backward Compatibility + +The library maintains full backward compatibility: + +```csharp +// Old way (still works) +var config = new Configuration +{ + Protocol = ProtocolType.TCP // Uses default TCP implementation +}; + +// New way +var config = new Configuration +{ + ProtocolFactory = () => ProtocolFactory.CreateProtocol("TCP") +}; + +// Or with custom protocol +var config = new Configuration +{ + ProtocolFactory = () => new CustomProtocol() +}; +``` + +## Examples + +See [CustomProtocolUsageExample](./CustomProtocolUsageExample.cs) for complete working examples. + +## Questions + +Contact the brasser \ No newline at end of file diff --git a/Custom Crap/PROTOCOLSUPPORT.md b/Custom Crap/PROTOCOLSUPPORT.md new file mode 100644 index 0000000..192f48f --- /dev/null +++ b/Custom Crap/PROTOCOLSUPPORT.md @@ -0,0 +1,105 @@ +# Custom Protocol Support + +The EonaCat.Connections library now provides **extensible protocol support** that allows you to easily integrate custom network protocols without modifying the core library. + +## Key Features + +### 1. **INetworkProtocol Interface** +A clean, well-defined contract that any protocol implementation must follow: +- `ConnectAsync`, `SendAsync`, `ReceiveAsync`, `DisconnectAsync` +- Configuration methods: `ConfigureKeepAlive`, `ConfigureSsl`, `ConfigureBufferSize`, etc. +- Utility methods: `GetRemoteEndPoint`, `GetLocalEndPoint`, `GetUnderlyingSocket`, `GetUnderlyingStream` + +### 2. **ProtocolFactory** +Central registry for managing protocol implementations: +- Register custom protocols: `ProtocolFactory.RegisterProtocol("CUSTOM", () => new CustomProtocol())` +- Create instances: `ProtocolFactory.CreateProtocol("CUSTOM")` +- Query registered protocols: `ProtocolFactory.IsProtocolRegistered("CUSTOM")` +- Get all protocols: `ProtocolFactory.GetRegisteredProtocols()` +- Unregister protocols (except built-in TCP/UDP) + +### 3. **Easy Integration with Configuration** +Use protocols with a single line: +```csharp +var config = new Configuration +{ + ProtocolFactory = () => new MyCustomProtocol() +}; +``` + +### 4. **Built-in Implementations** +TCP and UDP protocols are provided out-of-the-box: +- `TcpProtocol` - Full TCP support with SSL/TLS, keep-alive, socket options +- `UdpProtocol` - UDP connectionless protocols + +### 5. **Backward Compatibility** +Existing code continues to work without changes: +```csharp +// Old way still works +var config = new Configuration { Protocol = ProtocolType.TCP }; + +// New way for custom protocols +var config = new Configuration { ProtocolFactory = () => new CustomProtocol() }; +``` + +## Use Cases + +- **QUIC Protocol** - Modern, low-latency transport +- **HTTP/2 or HTTP/3** - Web-based communication +- **WebSocket** - Browser-compatible real-time communication +- **Custom Binary Protocols** - Application-specific formats +- **Compression Wrappers** - Transparent data compression +- **Encryption Wrappers** - Protocol-level encryption +- **Protocol Composition** - Layered protocol stacks + +## Files Added + +- `EonaCat.Connections/Protocols/INetworkProtocol.cs` - Protocol interface +- `EonaCat.Connections/Protocols/ProtocolFactory.cs` - Protocol registry +- `EonaCat.Connections/Protocols/TcpProtocol.cs` - TCP implementation +- `EonaCat.Connections/Protocols/UdpProtocol.cs` - UDP implementation +- `EonaCat.Connections/Protocols/CUSTOM_PROTOCOLS.md` - Complete documentation + +## Files Modified + +- `EonaCat.Connections/Models/Configuration.cs` + - Added `ProtocolFactory` property (optional custom protocol factory) + - Added `GetProtocol()` method (creates and configures protocol instance) + - Maintains backward compatibility with `Protocol` enum + +## Getting Started + +### 1. Create Your Protocol +Implement `INetworkProtocol`: +```csharp +public class MyProtocol : INetworkProtocol +{ + public string ProtocolName => "MyProtocol"; + public bool IsConnected => /* ... */; + // Implement required methods... +} +``` + +### 2. Register (Optional) +```csharp +ProtocolFactory.RegisterProtocol("MY_PROTO", () => new MyProtocol()); +``` + +### 3. Use in Configuration +```csharp +var config = new Configuration +{ + ProtocolFactory = () => new MyProtocol(), + Host = "example.com", + Port = 8080 +}; + +var client = new NetworkClient(config); +await client.ConnectAsync(); +``` + +That's it! Your custom protocol is now integrated. + +## Questions? + +Please contact the Brasser \ No newline at end of file diff --git a/EonaCat.Connections.Client/EonaCat.Connections.Client.csproj b/EonaCat.Connections.Client/EonaCat.Connections.Client.csproj index 57d906c..af3c1cc 100644 --- a/EonaCat.Connections.Client/EonaCat.Connections.Client.csproj +++ b/EonaCat.Connections.Client/EonaCat.Connections.Client.csproj @@ -12,7 +12,7 @@ - + diff --git a/EonaCat.Connections.Client/JsonTest.cs b/EonaCat.Connections.Client/JsonTest.cs deleted file mode 100644 index 54b068d..0000000 --- a/EonaCat.Connections.Client/JsonTest.cs +++ /dev/null @@ -1,72 +0,0 @@ -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Threading.Tasks; - -namespace EonaCat.Connections.Client -{ - // This file is part of the EonaCat project(s) which is released under the Apache License. - // See the LICENSE file or go to https://EonaCat.com/license for full license details. - - // Root myDeserializedClass = JsonConvert.DeserializeObject>(myJsonResponse); - public class Contact - { - public string email { get; set; } - public string phone { get; set; } - } - - public class Department - { - public string id { get; set; } - public string name { get; set; } - public Manager manager { get; set; } - } - - public class Details - { - public int hoursSpent { get; set; } - public List technologiesUsed { get; set; } - public string completionDate { get; set; } - public string expectedCompletion { get; set; } - } - - public class Employee - { - public string id { get; set; } - public string name { get; set; } - public string position { get; set; } - public Department department { get; set; } - public List projects { get; set; } - } - - public class Manager - { - public string id { get; set; } - public string name { get; set; } - public Contact contact { get; set; } - } - - public class Project - { - public string projectId { get; set; } - public string projectName { get; set; } - public string startDate { get; set; } - public List tasks { get; set; } - } - - public class Root - { - public Employee employee { get; set; } - } - - public class Task - { - public string taskId { get; set; } - public string title { get; set; } - public string status { get; set; } - public Details details { get; set; } - } - - -} diff --git a/EonaCat.Connections.Client/Program.cs b/EonaCat.Connections.Client/Program.cs index 4e4d8d7..76fe599 100644 --- a/EonaCat.Connections.Client/Program.cs +++ b/EonaCat.Connections.Client/Program.cs @@ -1,205 +1,570 @@ -// This file is part of the EonaCat project(s) which is released under the Apache License. -// See the LICENSE file or go to https://EonaCat.com/license for full license details. - +using EonaCat.Connections.Helpers; using EonaCat.Connections.Models; using System.Reflection; using System.Text; namespace EonaCat.Connections.Client.Example { - // This file is part of the EonaCat project(s) which is released under the Apache License. - // See the LICENSE file or go to https://EonaCat.com/license for full license details. - public class Program { - private const bool UseProcessor = true; + private static JsonDataProcessor processor = new JsonDataProcessor(); private const bool IsHeartBeatEnabled = false; + private static int SEND_DELAY_IN_MILLISECONDS = 1000 * 40; private static List _clients = new List(); private static long clientCount = 1; private static long clientsConnected = 0; private static string _jsonContent; - //public static string SERVER_IP = "10.40.11.22"; public static string SERVER_IP = "127.0.0.1"; - private static Dictionary>> _clientsProcessors = new Dictionary>>(); - private static bool testDataProcessor; + static int i = 0; + private static Configuration _configuration; public static bool WaitForMessage { get; private set; } public static bool PressEnterForNextMessage { get; private set; } - public static bool ToConsoleOnly { get; private set; } = true; + public static bool ToConsoleOnly { get; private set; } public static bool UseJson { get; private set; } = true; public static bool TESTBYTES { get; private set; } public static bool UseJsonProcessorTest { get; private set; } = true; + public static bool ShowInConsole { get; private set; } + public static bool UseJsonProcessorInternalTest { get; private set; } = true; + public static bool UseTestJsonFive { get; private set; } = true; + public static bool UseTestJsonTen { get; private set; } + public static bool UseTestJsonTwenty { get; private set; } + public static bool UseTestJsonThirty { get; private set; } + public static bool UseTestJsonOneHundred { get; private set; } + public static bool IgnoreAutoDelay { get; private set; } + public static bool IsConnected { get; private set; } + public static bool CheckJsonPayloadMessage { get; set; } + public static bool EnableStressTest { get; private set; } = false; + public static bool EnableLoadTest { get; private set; } = false; - public static async System.Threading.Tasks.Task Main(string[] args) + public static async Task Main(string[] args) { - for (long i = 0; i < clientCount; i++) + _configuration = new Configuration { - var clientName = $"User {i}"; - var client = await CreateClientAsync().ConfigureAwait(false); - _clients.Add(client); + Protocol = ProtocolType.TCP, + Host = SERVER_IP, + Port = 1111, - if (testDataProcessor) - { - _clientsProcessors[client] = new JsonDataProcessor>(); - } - else - { - _ = StartClientAsync(clientName, client); - } - } + Certificate = CertificateHelper.GetCertificate(certificatePath: @"C:\ProgramData\EonaCat\localhost.pfx", certificatePassword: null), + UseAesEncryption = false, + EnableHeartbeat = IsHeartBeatEnabled, + AesPassword = "itudin ante tempus consequat. Aliquam scelerisque pretium tellus, sed accumsan est ultrices id. Suspendisse sit amet ullamcorper sem.\",\"version\": 9.3},{\"name\": \"Sunil Kapoor\",\"language\": \"Hindi\",\"id\": \"VY2A0APGVHK5NAW2\",\"bio\": \"Proin tempus eu risus nec mattis. Ut dictum, ligula eget sagittis maximus, tellus mi varius ex, a accumsan justo tellus vitae leo. In id elit malesuada, pulvinar mi eu, imperdiet nulla.\",\"version\": 8.04},{\"name\": \"Zamokuhle Zulu\",\"language\": \"isiZulu\",\"id\": \"XU7BX2F8M5PVZ1EF\",\"bio\": \"Etiam congue dignissim volutpat. Phasellus tincidunt sollicitudin posuere. Phasellus tincidunt sollicitudin posuere. Nam tristique feugiat est vitae mollis.\",\"version\": 8.39},{\"name\": \"Bhupesh Menon\",\"language\": \"Hindi\",\"id\": \"0CEPNRDV98KT3ORP\",\"bio\": \"Maecenas tempus neque ut porttitor malesuada. Phasellus massa ligula, hendrerit eget efficitur eget, tincidunt in ligula. Quisque mauris ligula, efficitur porttitor sodales ac, lacinia non ex. Maecenas quis nisi nunc.\",\"version\": 2.69},{\"name\": \"Rohini Vasav\",\"language\": \"Hindi\",\"id\": \"UEFML43TCGS04KWM\",\"bio\": \"Ut accumsan, est vel fringilla varius, purus augue blandit nisl, eu rhoncus ligula purus vel dolor. Ut maximus, libero nec facilisis fringilla, ex sem sollicitudin leo, non congue tortor ligula in eros. Nam rutrum sollicitudin ante tempus consequat. Aliquam scelerisque pretium tellus, sed accumsan est ultrices id. Suspendisse sit amet ullamcorper sem.\",\"version\": 9.3},{\"name\": \"Sunil Kapoor\",\"language\": \"Hindi\",\"id\": \"VY2A0APGVHK5NAW2\",\"bio\": \"Proin tempus eu risus nec mattis. Ut dictum, ligula eget sagittis maximus, tellus mi varius ex, a accumsan justo tellus vitae leo. In id elit malesuada, pulvinar mi eu, imperdiet nulla.\",\"version\": 8.04},{\"name\": \"Zamokuhle Zulu\",\"language\": \"isiZulu\",\"id\": \"XU7BX2F8M5PVZ1EF\",\"bio\": \"Etiam congue dignissim volutpat. Phasellus tinc", - while (true) + EnableConnectionDebugLogs = true, + }; + + AppDomain.CurrentDomain.ProcessExit += (sender, e) => { - string message = string.Empty; + Console.WriteLine("[TCP Client] Application terminating, forcing cleanup..."); + CleanupAllClients(); + }; - if (WaitForMessage) + try + { + + if (!EnableLoadTest && !EnableStressTest) { - Console.Write("Enter message to send (or 'exit' to quit): "); - message = Console.ReadLine(); + for (long i = 0; i < clientCount; i++) + { + var clientName = $"User {i}"; + var client = await CreateClientAsync().ConfigureAwait(false); + _clients.Add(client); + _ = StartClientAsync(clientName, client); + } } - if (!string.IsNullOrEmpty(message) && message.Equals("exit", StringComparison.OrdinalIgnoreCase)) + processor.OnProcessMessage += Processor_OnProcessMessage; + processor.OnProcessTextMessage += Processor_OnProcessTextMessage; + processor.OnError += Processor_OnError; + processor.OnClientRemovedDueToIdle += Processor_OnClientRemovedDueToIdle; + + if (!IgnoreAutoDelay) { - foreach (var client in _clients) - { - await client.DisconnectAsync().ConfigureAwait(false); - } - break; + SetDelay(); } - var jsonUrl = "https://sample.json-format.com/api/download?url=https%3A%2F%2Ffiles.jsons.live%2Femployees%2F5-level%2F20-MB%2Fformatted.json&name=20%20MB%205%20Level%20Formatted.json"; - - try + bool shouldExit = false; + while (!shouldExit) { - if (string.IsNullOrEmpty(_jsonContent) && UseJson) - { - using var httpClient = new HttpClient(); - _jsonContent = await httpClient.GetStringAsync(jsonUrl); + string message = string.Empty; - var jsonSize = Encoding.UTF8.GetByteCount(_jsonContent); - WriteToLog($"Using large JSON file (size: {jsonSize / 1024 / 1024} MB)"); + if (WaitForMessage) + { + Console.Write("Enter message to send (or 'exit' to quit): "); + message = Console.ReadLine(); + + foreach (var client in _clients) + { + await client.DisconnectAsync().ConfigureAwait(false); + } + + Console.WriteLine("Disconnected all clients. Press any key to continue..."); + Console.ReadKey(); + Console.ReadLine(); + foreach (var client in _clients) + { + await client.ConnectAsync().ConfigureAwait(false); + } + Console.WriteLine("Reconnected all clients"); } - if (UseJson) + if (!string.IsNullOrEmpty(message) && message.Equals("exit", StringComparison.OrdinalIgnoreCase)) { - message = _jsonContent; + shouldExit = true; + break; } - if (UseJsonProcessorTest) + if (!string.IsNullOrEmpty(message) && message.Equals("connect", StringComparison.OrdinalIgnoreCase)) { foreach (var client in _clients) { - var processor = _clientsProcessors[client]; - processor.OnProcessTextMessage += (sender, e) => - { - WriteToLog($"Processed message from {e.ClientName}: {e.Text}"); - }; - processor.OnProcessMessage += (sender, e) => - { - WriteToLog($"Processed JSON message from {e.ClientName} ({e.ClientEndpoint}): {e.Data}"); - }; - processor.MaxAllowedBufferSize = 50 * 1024 * 1024; // 10 MB - var json = _jsonContent; + await client.ConnectAsync().ConfigureAwait(false); + } + continue; + } - while (true) - { - json = "TEST1" + _jsonContent + "TEST2"; + if (EnableStressTest) + { + await RunStressTestAsync(); + return; + } + if (EnableLoadTest) + { + await RunLoadTestAsync(10_000, 10, 1000, 10_000); + return; + } + + var jsonUrl = "https://samples.json-format.com/employees/json/employees_500KB.json"; + + try + { + if (string.IsNullOrEmpty(_jsonContent) && UseJson) + { + using var httpClient = new HttpClient(); + _jsonContent = await httpClient.GetStringAsync(jsonUrl); + } + + if (UseJson) + { + message = _jsonContent; + } + + if (UseTestJsonTwenty) + { + message = File.ReadAllText("Z:\\json\\20mb.json"); + } + + if (UseTestJsonThirty) + { + message = File.ReadAllText("Z:\\json\\30mb.json"); + } + + if (UseTestJsonFive) + { + message = File.ReadAllText("Z:\\json\\5mb.json"); + } + + if (UseTestJsonTen) + { + message = File.ReadAllText("Z:\\json\\10mb.json"); + } + + if (UseTestJsonOneHundred) + { + message = File.ReadAllText("Z:\\json\\100mb.json"); + } + + var jsonSize = Encoding.UTF8.GetByteCount(message); + WriteToLog($"Using file (size: {jsonSize / 1024 / 1024} MB)"); + + if (UseJsonProcessorInternalTest) + { + foreach (var client in _clients) + { + var json = message; processor.Process(json, "TestClient"); - await System.Threading.Tasks.Task.Delay(100).ConfigureAwait(false); + await Task.Delay(100).ConfigureAwait(false); } } } - } - catch (Exception exception) - { - WriteToLog($"Failed to download large JSON file: {exception.Message}"); - } - - if (!string.IsNullOrEmpty(message)) - { - foreach (var client in _clients) + catch (Exception exception) { - if (TESTBYTES) + WriteToLog($"Failed to download large JSON file: {exception.Message}"); + } + + if (!string.IsNullOrEmpty(message)) + { + foreach (var client in _clients) { - var bytes = new byte[] { 0x00, 0x04, 0x31, 0x32, 0x30, 0x30 }; - await client.SendAsync(bytes).ConfigureAwait(false); - } - else - { - await client.SendAsync(message).ConfigureAwait(false); + if (TESTBYTES) + { + var bytes = new byte[] { 0x00, 0x04, 0x31, 0x32, 0x30, 0x30 }; + await client.SendAsync(bytes).ConfigureAwait(false); + } + else + { + await client.SendAsync(message).ConfigureAwait(false); + } } } - } - await System.Threading.Tasks.Task.Delay(1000).ConfigureAwait(false); + await Task.Delay(SEND_DELAY_IN_MILLISECONDS).ConfigureAwait(false); + } + } + catch (Exception ex) + { + Console.WriteLine($"[TCP Client] Fatal error: {ex.Message}"); + Console.WriteLine(ex.StackTrace); + } + finally + { + Console.WriteLine("[TCP Client] Stopping all clients..."); + CleanupAllClients(); + Console.WriteLine("[TCP Client] Stopped."); } } - private static async System.Threading.Tasks.Task StartClientAsync(string clientName, NetworkClient client) + private static void CleanupAllClients() + { + foreach (var client in _clients) + { + try + { + client?.Dispose(); + } + catch (Exception ex) + { + Console.WriteLine($"Error disposing client: {ex.Message}"); + } + } + _clients.Clear(); + } + + static long totalKeepAlives = 0; + private static async Task KeepAliveBroadCastTest() + { + var client = _clients.FirstOrDefault(); + client.OnDataReceived += (sender, e) => + { + if (e.StringData.Contains("KeepAlive Test")) + { + Console.Title = $"Received KeepAlive Test response at {DateTime.Now} (total {++totalKeepAlives})"; + Console.WriteLine($"Received KeepAlive Test response: {e.StringData}"); + } + else + { + Console.WriteLine($"Received data: {e.StringData}"); + } + }; + + await client.SendAndWaitForResponseAsync("KeepAliveTest", TimeSpan.FromSeconds(30)).ContinueWith(task => + { + if (task.IsCompletedSuccessfully) + { + var response = task.Result; + Console.WriteLine($"Received response for KeepAliveTest: {response}"); + } + else + { + Console.WriteLine($"KeepAliveTest failed: {task.Exception?.Message}"); + } + }); + } + + private static async Task TimerTest() + { + System.Timers.Timer timer = new System.Timers.Timer(1000); + timer.Elapsed += (sender, e) => + { + Console.WriteLine("IK BEN GEFIRED!"); + }; + timer.Start(); + + while (true) + { + timer.Start(); + Console.WriteLine("JIJ BENT EEN NERD !"); + await Task.Delay(950); + timer.Stop(); + Console.WriteLine("JIJ BENT EEN NERD ! (NA TIMER)"); + await Task.Delay(1000).ConfigureAwait(false); + } + } + + private static void DelayTest() + { + while (true) + { + _clients.FirstOrDefault().SendAsync($"Hello server, this is a delayed message at {DateTime.Now}").ConfigureAwait(false); + Console.WriteLine($"{DateTime.Now} : Sent delayed message"); + Thread.Sleep(30_000); + } + } + + private static async Task DisconnectTest() + { + while (true) + { + var client = new NetworkClient(new Configuration() + { + Host = "127.0.0.1", + Port = 1111, + Certificate = CertificateHelper.GetCertificate(certificateThumbprint: "4e34475f8618f4cbd65a9852b8bf45e740a52fff"), + }); + + client.OnDataReceived += Client_OnDataReceived1; + + while (true) + { + await Task.Delay(10000).ConfigureAwait(false); + await client.ConnectAsync().ConfigureAwait(false); + await Task.Delay(1000).ConfigureAwait(false); + await client.DisconnectAsync().ConfigureAwait(false); + await Task.Delay(1000).ConfigureAwait(false); + await client.ConnectAsync().ConfigureAwait(false); + await Task.Delay(1000).ConfigureAwait(false); + await client.DisconnectAsync().ConfigureAwait(false); + await Task.Delay(1000).ConfigureAwait(false); + await client.ConnectAsync().ConfigureAwait(false); + await client.SendAsync("Hallo ik ben een brasser zie je dat niet;"); + } + } + } + + private static async void Client_OnDataReceived1(object? sender, DataReceivedEventArgs e) + { + var client = (NetworkClient)sender; + if (client == null) + { + return; + } + + Console.WriteLine($"Received data from server: {e.StringData}"); + await client.SendAsync($"Echo: {e.StringData}").ConfigureAwait(false); + await client.DisconnectAsync().ConfigureAwait(false); + await client.ConnectAsync(); + } + + private static async Task RikAsync() + { + var client = new NetworkClient(new Configuration() + { + + Host = "127.0.0.1", + Port = 1111, + + Certificate = CertificateHelper.GetCertificate(certificatePath: @"C:\ProgramData\EonaCat\localhost.pfx", certificatePassword: null), + EnableConnectionDebugLogs = true, + MessageFraming = FramingMode.LengthPrefixed, + }); + + client.OnConnected += Client_OnConnected; + client.OnDisconnected += Client_OnDisconnected; + client.OnDataReceived += Client_OnDataReceived; + client.OnGeneralError += Client_OnGeneralError; + client.OnEncryptionError += Client_OnEncryptionError; + client.OnSslError += Client_OnSslError; + + await client.ConnectAsync().ConfigureAwait(false); + while (true) + { + await client.ConnectAsync(); + await Task.Delay(250); + + } + + } + + private static void Client_OnDataReceived(object? sender, DataReceivedEventArgs e) + { + if (e.Data != null) + { + var dataSize = e.Data.Length; + if (CheckJsonPayloadMessage) + { + Console.WriteLine($"Received JSON from server (size: {dataSize} bytes)"); + } + else + { + Console.WriteLine($"Received data from server (size: {dataSize} bytes) {e.StringData}"); + } + } + else + { + Console.WriteLine("Received data from server (no data)"); + } + } + + private static void Client_OnDisconnected(object? sender, EventArguments.ConnectionEventArgs e) + { + Console.WriteLine($"Disconnected from server at {e.RemoteEndPoint}"); + IsConnected = false; + } + + private static void Client_OnConnected(object? sender, EventArguments.ConnectionEventArgs e) + { + Console.WriteLine($"Connected to server at {e.RemoteEndPoint}"); + IsConnected = true; + SendMessagesContinuously(sender); + } + + private static void SendMessagesContinuously(object? sender) + { + while (IsConnected) + { + var message = $"Hello server, this is message {++i}"; + ((NetworkClient)sender).SendAsync(message).ConfigureAwait(false); + Console.WriteLine($"{DateTime.Now} : Sent message: {message}"); + Thread.Sleep(1); + } + } + + private static void Processor_OnClientRemovedDueToIdle(object? sender, string e) + { + Console.WriteLine($"Client removed due to idle: {e}"); + } + + private static void Processor_OnError(object? sender, Exception e) + { + Console.WriteLine("Error: " + e.Message); + } + + private static void Processor_OnProcessTextMessage(object? sender, ProcessedTextMessage e) + { + if (ShowInConsole) + { + Console.WriteLine("Received text: " + e.Text); + } + else + { + Console.WriteLine("Received text OK"); + } + } + + private static void Processor_OnProcessMessage(object? sender, ProcessedMessage e) + { + if (ShowInConsole) + { + Console.WriteLine("Received JSON message OK: " + e.Data); + } + else + { + Console.WriteLine("Received JSON message OK"); + } + } + + private static void SetDelay() + { + if (UseTestJsonOneHundred) + { + SEND_DELAY_IN_MILLISECONDS = 1000 * 120; + } + else if (UseTestJsonThirty) + { + SEND_DELAY_IN_MILLISECONDS = 1000 * 60; + } + else if (UseTestJsonTwenty) + { + SEND_DELAY_IN_MILLISECONDS = 1000 * 40; + } + else if (UseTestJsonTen) + { + SEND_DELAY_IN_MILLISECONDS = 1000 * 20; + } + } + + private static void SmallMessagesTest() + { + while (true) + { + for (int i = 0; i < 1000; i++) + { + var message = $"{i}"; + _clients.ForEach(async client => + { + await client.SendAsync(message).ConfigureAwait(false); + }); + } + Thread.Sleep(10); + } + } + + private static async Task DanielTestAsync() + { + Console.WriteLine("SocketTest Client started."); + EonaCat.Connections.NetworkClient _networkClient = new EonaCat.Connections.NetworkClient(new Configuration() + { + Host = "127.0.0.1", + Port = 1111, + }); + Console.WriteLine("Connecting to server..."); + _ = _networkClient.ConnectAsync(); + + await Task.Delay(1000); + + Console.WriteLine("Disconnecting from server..."); + + _ = _networkClient.DisconnectAsync(); + _ = _networkClient.DisposeAsync(); + await _networkClient.ConnectAsync(); + _networkClient.Dispose(); + + _networkClient = null; + + while (true) + { + await Task.Delay(1000); + Console.WriteLine("Keeping the process alive..."); + } + Console.WriteLine("DanielTest finished..."); + Console.ReadKey(); + } + + private static async Task StartClientAsync(string clientName, NetworkClient client) { await client.ConnectAsync().ConfigureAwait(false); - // Send nickname - await client.SendNicknameAsync(clientName); - - // Send a message await client.SendAsync($"Hello server, my name is {clientName}!"); } private static async Task CreateClientAsync() { - var config = new Configuration - { - Protocol = ProtocolType.TCP, - Host = SERVER_IP, - Port = 1111, - UseAesEncryption = false, - EnableHeartbeat = IsHeartBeatEnabled, - AesPassword = "EonaCat.Connections.Password", - //Certificate = new System.Security.Cryptography.X509Certificates.X509Certificate2("client.pfx", "p@ss"), - }; + var client = new NetworkClient(_configuration); - var client = new NetworkClient(config); - - // Subscribe to events client.OnConnected += (sender, e) => { + + client.SendNicknameAsync("MYTESTNICKNAME"); + WriteToLog($"Connected to server at {e.RemoteEndPoint}"); Console.WriteLine($"Connected to server at {e.RemoteEndPoint}"); Console.Title = $"Total clients {++clientsConnected}"; - }; + }; ; - if (UseProcessor) + client.OnDataReceived += async (sender, e) => { - _clientsProcessors[client] = new JsonDataProcessor>(); - _clientsProcessors[client].OnError += (sender, e) => + var data = e.Data; + if (Encoding.UTF8.GetString(data).Contains("Server broadcast")) { - Console.WriteLine($"Processor error: {e.Message}"); - }; + var broadcastData = Encoding.UTF8.GetString(data).Split(new[] { "Server broadcast: " }, StringSplitOptions.None).LastOrDefault()?.Trim(); + Console.Title = broadcastData; + return; + } - _clientsProcessors[client].OnProcessTextMessage += (sender, e) => + Console.WriteLine($"Received: {data.Length} bytes"); + if (UseJsonProcessorTest) { - Console.WriteLine($"Processed text message from {e.ClientName}: {e.Text}"); - }; - - _clientsProcessors[client].OnProcessMessage += (sender, e) => - { - ProcessMessage(e.Data, e.ClientName, e.ClientEndpoint ?? "Unknown endpoint"); - }; - } - - client.OnDataReceived += (sender, e) => - { - if (UseProcessor) - { - _clientsProcessors[client].Process(e.StringData, currentClientName: e.Nickname); + processor.Process(e, currentClientName: e.Nickname, e.RemoteEndPoint.ToString()); return; } else { + Console.WriteLine(e.StringData); + return; + WriteToLog($"Server says: {(e.IsBinary ? $"{e.Data.Length} bytes" : "We got a json message")}"); Console.WriteLine($"{e.StringData}"); @@ -235,9 +600,6 @@ namespace EonaCat.Connections.Client.Example message = $"Disconnected from server (remote close). Reason: {e.Reason}"; } } - - WriteToLog(message); - Console.WriteLine(message); Console.Title = $"Total clients {--clientsConnected}"; }; @@ -249,7 +611,15 @@ namespace EonaCat.Connections.Client.Example private static void ProcessMessage(object message, string clientName, string remoteEndpoint) { - WriteToLog($"Processed message from {clientName} ({remoteEndpoint}): {message}"); + if (ShowInConsole) + { + WriteToLog($"Processed message from {clientName} ({remoteEndpoint}): {message}"); + } + else + { + WriteToLog($"Processed message from {clientName} ({remoteEndpoint})"); + } + if (PressEnterForNextMessage) { Console.ReadKey(); @@ -263,12 +633,64 @@ namespace EonaCat.Connections.Client.Example private static void Client_OnGeneralError(object? sender, EventArguments.ErrorEventArgs e) { - WriteToLog($"General error: {e.Message} => {e.Exception?.Message} => {e.Nickname}"); + WriteToLog($"General error: {e.Message} {e.Exception?.Message} {e.Nickname}"); } private static void Client_OnEncryptionError(object? sender, EventArguments.ErrorEventArgs e) { - WriteToLog($"Encryption error: {e.Message} => {e.Exception?.Message} => {e.Nickname}"); + WriteToLog($"Encryption error: {e.Message} {e.Exception?.Message} {e.Nickname}"); + } + + /// + /// Run a stress test with multiple clients and many messages + /// + public static async Task RunStressTestAsync(int totalClients = 1000, int totalMessages = 100) + { + try + { + int clients = totalClients; + int messages = totalMessages; + + // Close existing clients so stress test can use the port + CleanupAllClients(); + await Task.Delay(1000); // Wait for port to be released + + var stressTest = new Tests.StressTest(_configuration, clients, messages); + await stressTest.RunAsync(); + WriteToLog($"Stress test completed. Report:{Environment.NewLine}{stressTest.Result}"); + + // Recreate clients if needed + for (long i = 0; i < clientCount; i++) + { + var clientName = $"User {i}"; + var client = await CreateClientAsync().ConfigureAwait(false); + _clients.Add(client); + _ = StartClientAsync(clientName, client); + } + } + catch (Exception ex) + { + Console.WriteLine($"Error running stress test: {ex.Message}"); + } + finally + { + Console.WriteLine("Stress test completed."); + Console.ReadKey(); + } + } + + private static async Task RunLoadTestAsync(int totalConnections, int durationMinutes, int connectionRatePerSecond, int messageRate) + { + var tester = new LoadTester(_configuration, totalConnections); + var task = tester.RunAsync( + duration: TimeSpan.FromMinutes(durationMinutes), + connectionRatePerSecond: connectionRatePerSecond, // Establish connections/sec + messageRate: messageRate // messages/sec/connection + ); + await task; + var report = tester.GetReport(); + WriteToLog($"Load test completed. Report:{Environment.NewLine}{report}"); + Console.ReadKey(); } public static void WriteToLog(string message) @@ -307,4 +729,4 @@ namespace EonaCat.Connections.Client.Example } } } -} \ No newline at end of file +} diff --git a/EonaCat.Connections.OpcUa.Client/EonaCat.Connections.OpcUa.Client.csproj b/EonaCat.Connections.OpcUa.Client/EonaCat.Connections.OpcUa.Client.csproj new file mode 100644 index 0000000..6bb8017 --- /dev/null +++ b/EonaCat.Connections.OpcUa.Client/EonaCat.Connections.OpcUa.Client.csproj @@ -0,0 +1,14 @@ + + + + Exe + net8.0 + enable + enable + + + + + + + \ No newline at end of file diff --git a/EonaCat.Connections.OpcUa.Client/Program.cs b/EonaCat.Connections.OpcUa.Client/Program.cs new file mode 100644 index 0000000..2c7e020 --- /dev/null +++ b/EonaCat.Connections.OpcUa.Client/Program.cs @@ -0,0 +1,41 @@ +using EonaCat.Connections.OpcUa.Client; +using EonaCat.Connections.OpcUa.Configuration; + +const string endpointUrl = "opc.tcp://localhost:4840/EonaCat/Connector"; +const string namespaceUri = "urn:EonaCat:Connector:OpcUa:Example"; + +await using var client = new OpcUaNetworkClient(new OpcUaClientOptions +{ + EndpointUrl = endpointUrl, + UseSecurity = false, + AutoAcceptUntrustedCertificates = true, + CheckCertificateRevocation = false +}); + +client.Error += (_, exception) => Console.Error.WriteLine(exception); +if (!await client.ConnectAsync()) +{ + return; +} + +var temperatureNode = client.GetNodeId(namespaceUri, "Machine.Temperature"); +var enabledNode = client.GetNodeId(namespaceUri, "Machine.Enabled"); +var addMethod = client.GetNodeId(namespaceUri, "Machine.Add"); +var rootNode = client.GetNodeId(namespaceUri, "EonaCat"); + +await using var subscription = await client.SubscribeAsync([temperatureNode, enabledNode], (_, args) => Console.WriteLine($"Subscription: {args.NodeId} = {args.Value}")); +var temperature = await client.ReadAsync(temperatureNode); +Console.WriteLine($"Temperature: {temperature.Value}"); + +await client.WriteAsync(temperatureNode, 42.0d); +var result = await client.CallAsync(rootNode, addMethod, [2.0d, 3.5d]); +Console.WriteLine($"2 + 3.5 = {result[0]}"); + +var children = await client.BrowseAsync(rootNode); +foreach (var child in children) +{ + Console.WriteLine($"{child.NodeClass}: {child.DisplayName} ({child.NodeId})"); +} + +await Task.Delay(1_500); +Console.ReadKey(); diff --git a/EonaCat.Connections.OpcUa.Server/EonaCat.Connections.OpcUa.Server.csproj b/EonaCat.Connections.OpcUa.Server/EonaCat.Connections.OpcUa.Server.csproj new file mode 100644 index 0000000..6bb8017 --- /dev/null +++ b/EonaCat.Connections.OpcUa.Server/EonaCat.Connections.OpcUa.Server.csproj @@ -0,0 +1,14 @@ + + + + Exe + net8.0 + enable + enable + + + + + + + \ No newline at end of file diff --git a/EonaCat.Connections.OpcUa.Server/Program.cs b/EonaCat.Connections.OpcUa.Server/Program.cs new file mode 100644 index 0000000..a80cb66 --- /dev/null +++ b/EonaCat.Connections.OpcUa.Server/Program.cs @@ -0,0 +1,39 @@ +using EonaCat.Connections.OpcUa.Configuration; +using EonaCat.Connections.OpcUa.Models; +using EonaCat.Connections.OpcUa.Server; +using Opc.Ua; + +const string namespaceUri = "urn:EonaCat:Connector:OpcUa:Example"; + +await using var server = new OpcUaNetworkServer(new OpcUaServerOptions +{ + BaseAddress = "opc.tcp://localhost:4840/EonaCat/Connector", + NamespaceUri = namespaceUri, + AutoAcceptUntrustedCertificates = true, + CheckCertificateRevocation = false +}); + +server.AddVariable(new OpcUaNodeDefinition("Machine.Temperature", "Temperature", DataTypeIds.Double, 1337.0d, Description: "Current machine temperature in degrees Celsius")) + .AddVariable(new OpcUaNodeDefinition("Machine.Enabled", "Enabled", DataTypeIds.Boolean, true)) + .AddMethod(new OpcUaMethodDefinition("Machine.Add", "Add", + [ + new OpcUaMethodArgument("Left", DataTypeIds.Double), + new OpcUaMethodArgument("Right", DataTypeIds.Double) + ], + [new OpcUaMethodArgument("Result", DataTypeIds.Double)], arguments => [Convert.ToDouble(arguments[0]) + Convert.ToDouble(arguments[1])], "Adds two numbers")); + +server.ValueChanged += (_, args) => Console.WriteLine($"Value changed: {args.NodeId} = {args.Value}"); +server.Error += (_, exception) => Console.Error.WriteLine(exception); + +await server.StartAsync(); +Console.WriteLine($"OPC UA server listening on {server.EndpointUrl}"); +Console.WriteLine("Press Ctrl+C to stop."); + +var stopped = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously); +Console.CancelKeyPress += (_, eventArgs) => +{ + eventArgs.Cancel = true; + stopped.TrySetResult(true); +}; + +await stopped.Task; diff --git a/EonaCat.Connections.OpcUa/Client/OpcUaNetworkClient.cs b/EonaCat.Connections.OpcUa/Client/OpcUaNetworkClient.cs new file mode 100644 index 0000000..74df925 --- /dev/null +++ b/EonaCat.Connections.OpcUa/Client/OpcUaNetworkClient.cs @@ -0,0 +1,309 @@ +using EonaCat.Connections.OpcUa.Configuration; +using EonaCat.Connections.OpcUa.Infrastructure; +using EonaCat.Connections.OpcUa.Models; +using Opc.Ua; +using Opc.Ua.Client; +using System.Text; +using OpcUaClientOptions = EonaCat.Connections.OpcUa.Configuration.OpcUaClientOptions; + +namespace EonaCat.Connections.OpcUa.Client; + +public sealed class OpcUaNetworkClient : IAsyncDisposable, IDisposable +{ + private readonly OpcUaClientOptions _options; + private readonly SemaphoreSlim _lifecycleLock = new(1, 1); + private ApplicationConfiguration? _configuration; + private ISession? _session; + private SessionReconnectHandler? _reconnectHandler; + private bool _disposed; + + public OpcUaNetworkClient(OpcUaClientOptions options) + { + _options = options ?? throw new ArgumentNullException(nameof(options)); + } + + public bool IsConnected => _session?.Connected == true; + public ISession? Session => _session; + public string EndpointUrl => _options.EndpointUrl; + + public event EventHandler? Connected; + public event EventHandler? Disconnected; + public event EventHandler? Error; + + public NodeId GetNodeId(string namespaceUri, string identifier) + { + ArgumentException.ThrowIfNullOrWhiteSpace(namespaceUri); + ArgumentException.ThrowIfNullOrWhiteSpace(identifier); + + var namespaceIndex = GetSession().NamespaceUris.GetIndex(namespaceUri); + if (namespaceIndex < 0) + { + throw new ArgumentException($"Namespace '{namespaceUri}' is not registered by the server.", nameof(namespaceUri)); + } + + return new NodeId(identifier, (ushort)namespaceIndex); + } + + public async Task ConnectAsync(CancellationToken cancellationToken = default) + { + await _lifecycleLock.WaitAsync(cancellationToken).ConfigureAwait(false); + + try + { + ObjectDisposedException.ThrowIf(_disposed, this); + if (IsConnected) + { + return true; + } + + _configuration ??= await OpcUaApplicationConfigurationFactory + .CreateClientAsync(_options, cancellationToken) + .ConfigureAwait(false); + + var endpointDescription = await CoreClientUtils.SelectEndpointAsync( + _configuration, + _options.EndpointUrl, + _options.UseSecurity, + _options.OperationTimeoutMilliseconds, + OpcUaRuntime.Telemetry, + cancellationToken).ConfigureAwait(false); + + var endpoint = new ConfiguredEndpoint( + null, + endpointDescription, + EndpointConfiguration.Create(_configuration)); + + var identity = string.IsNullOrWhiteSpace(_options.Username) + ? new UserIdentity() + : new UserIdentity( + _options.Username, + Encoding.UTF8.GetBytes(_options.Password ?? string.Empty)); + + _session = await OpcUaRuntime.SessionFactory.CreateAsync( + _configuration, + endpoint, + false, + _options.SessionName, + (uint)_options.SessionTimeoutMilliseconds, + identity, + default, + cancellationToken).ConfigureAwait(false); + + _session.KeepAlive += HandleKeepAlive; + Connected?.Invoke(this, CreateConnectionEventArgs()); + return true; + } + catch (Exception exception) + { + Error?.Invoke(this, exception); + return false; + } + finally + { + _lifecycleLock.Release(); + } + } + + public async Task> BrowseAsync( + NodeId? nodeId = null, + CancellationToken cancellationToken = default) + { + var session = GetSession(); + var browser = new Browser(session) + { + BrowseDirection = BrowseDirection.Forward, + NodeClassMask = (int)(NodeClass.Object | NodeClass.Variable | NodeClass.Method), + ReferenceTypeId = ReferenceTypeIds.HierarchicalReferences, + IncludeSubtypes = true + }; + + var references = await browser.BrowseAsync(nodeId ?? ObjectIds.ObjectsFolder, cancellationToken).ConfigureAwait(false); + return references.ToArray(); + } + + public async Task ReadAsync(NodeId nodeId, CancellationToken cancellationToken = default) + { + ArgumentNullException.ThrowIfNull(nodeId); + return await GetSession().ReadValueAsync(nodeId, cancellationToken).ConfigureAwait(false); + } + + public async Task WriteAsync(NodeId nodeId, object? value, CancellationToken cancellationToken = default) + { + ArgumentNullException.ThrowIfNull(nodeId); + var values = new[] + { + new WriteValue + { + NodeId = nodeId, + AttributeId = Attributes.Value, + Value = new DataValue(new Variant(value)) + } + }; + + var response = await GetSession().WriteAsync(null, values, cancellationToken).ConfigureAwait(false); + if (StatusCode.IsBad(response.Results[0])) + { + throw new ServiceResultException(response.Results[0]); + } + } + + public async Task> CallAsync( + NodeId objectId, + NodeId methodId, + IEnumerable? arguments = null, + CancellationToken cancellationToken = default) + { + var request = new CallMethodRequest + { + ObjectId = objectId, + MethodId = methodId, + InputArguments = (arguments ?? []).Select(value => new Variant(value)).ToArray() + }; + var methods = new[] { request }; + var response = await GetSession().CallAsync(null, methods, cancellationToken).ConfigureAwait(false); + var result = response.Results[0]; + if (StatusCode.IsBad(result.StatusCode)) + { + throw new ServiceResultException(result.StatusCode); + } + + return result.OutputArguments.ToArray().Select(argument => argument.Value).ToArray(); + } + + public async Task SubscribeAsync( + IEnumerable nodeIds, + EventHandler handler, + int publishingIntervalMilliseconds = 1_000, + int samplingIntervalMilliseconds = 1_000, + CancellationToken cancellationToken = default) + { + ArgumentNullException.ThrowIfNull(nodeIds); + ArgumentNullException.ThrowIfNull(handler); + + var session = GetSession(); + var subscription = new Subscription(session.DefaultSubscription) + { + PublishingInterval = publishingIntervalMilliseconds + }; + + foreach (var nodeId in nodeIds) + { + var item = new MonitoredItem(subscription.DefaultItem) + { + StartNodeId = nodeId, + AttributeId = Attributes.Value, + SamplingInterval = samplingIntervalMilliseconds, + QueueSize = 10, + DiscardOldest = true + }; + item.Notification += (monitoredItem, _) => + { + foreach (var value in monitoredItem.DequeueValues()) + { + handler(this, new OpcUaValueChangedEventArgs + { + NodeId = nodeId, + Value = value.WrappedValue.Value, + StatusCode = value.StatusCode, + SourceTimestamp = value.SourceTimestamp.ToDateTime() + }); + } + }; + subscription.AddItem(item); + } + + session.AddSubscription(subscription); + await subscription.CreateAsync(cancellationToken).ConfigureAwait(false); + return new OpcUaSubscription(subscription); + } + + public async Task DisconnectAsync(CancellationToken cancellationToken = default) + { + await _lifecycleLock.WaitAsync(cancellationToken).ConfigureAwait(false); + try + { + _reconnectHandler?.Dispose(); + _reconnectHandler = null; + + if (_session != null) + { + _session.KeepAlive -= HandleKeepAlive; + await _session.CloseAsync(cancellationToken).ConfigureAwait(false); + _session.Dispose(); + _session = null; + Disconnected?.Invoke(this, CreateConnectionEventArgs()); + } + } + finally + { + _lifecycleLock.Release(); + } + } + + private ISession GetSession() + { + if (_session?.Connected != true) + { + throw new InvalidOperationException("The OPC UA client is not connected."); + } + + return _session; + } + + private void HandleKeepAlive(ISession session, KeepAliveEventArgs args) + { + if (ServiceResult.IsGood(args.Status)) + { + return; + } + + Disconnected?.Invoke(this, CreateConnectionEventArgs()); + if (!_options.AutoReconnect || _reconnectHandler != null) + { + return; + } + + var currentSession = _session; + if (currentSession == null) + { + return; + } + + _reconnectHandler = new SessionReconnectHandler(OpcUaRuntime.Telemetry); + _reconnectHandler.BeginReconnect( + currentSession, + _options.ReconnectPeriodMilliseconds, + (_, _) => + { + if (_reconnectHandler?.Session is ISession reconnectedSession) + { + _session = reconnectedSession; + _session.KeepAlive += HandleKeepAlive; + Connected?.Invoke(this, CreateConnectionEventArgs()); + } + + _reconnectHandler?.Dispose(); + _reconnectHandler = null; + }); + } + + private OpcUaConnectionEventArgs CreateConnectionEventArgs() => new() + { + EndpointUrl = _options.EndpointUrl, + SessionName = _session?.SessionName + }; + + public async ValueTask DisposeAsync() + { + if (_disposed) + { + return; + } + + await DisconnectAsync().ConfigureAwait(false); + _disposed = true; + _lifecycleLock.Dispose(); + } + + public void Dispose() => DisposeAsync().AsTask().GetAwaiter().GetResult(); +} diff --git a/EonaCat.Connections.OpcUa/Client/OpcUaSubscription.cs b/EonaCat.Connections.OpcUa/Client/OpcUaSubscription.cs new file mode 100644 index 0000000..46ecd2c --- /dev/null +++ b/EonaCat.Connections.OpcUa/Client/OpcUaSubscription.cs @@ -0,0 +1,30 @@ +using Opc.Ua.Client; + +namespace EonaCat.Connections.OpcUa.Client; + +public sealed class OpcUaSubscription : IAsyncDisposable, IDisposable +{ + private readonly Subscription _subscription; + private bool _disposed; + + internal OpcUaSubscription(Subscription subscription) + { + _subscription = subscription; + } + + public uint Id => _subscription.Id; + + public async ValueTask DisposeAsync() + { + if (_disposed) + { + return; + } + + _disposed = true; + await _subscription.DeleteAsync(true, CancellationToken.None).ConfigureAwait(false); + _subscription.Dispose(); + } + + public void Dispose() => DisposeAsync().AsTask().GetAwaiter().GetResult(); +} diff --git a/EonaCat.Connections.OpcUa/Configuration/OpcUaClientOptions.cs b/EonaCat.Connections.OpcUa/Configuration/OpcUaClientOptions.cs new file mode 100644 index 0000000..408bb76 --- /dev/null +++ b/EonaCat.Connections.OpcUa/Configuration/OpcUaClientOptions.cs @@ -0,0 +1,20 @@ +using Opc.Ua; + +namespace EonaCat.Connections.OpcUa.Configuration; + +public sealed class OpcUaClientOptions +{ + public required string EndpointUrl { get; init; } + public string ApplicationName { get; init; } = "EonaCat OPC UA Client"; + public string ApplicationUri { get; init; } = $"urn:{Utils.GetHostName()}:EonaCat:OpcUa:Client"; + public string SessionName { get; init; } = "EonaCat OPC UA Session"; + public string? Username { get; init; } + public string? Password { get; init; } + public bool UseSecurity { get; init; } = true; + public bool AutoAcceptUntrustedCertificates { get; init; } + public bool CheckCertificateRevocation { get; init; } = true; + public bool AutoReconnect { get; init; } = true; + public int ReconnectPeriodMilliseconds { get; init; } = 5_000; + public int SessionTimeoutMilliseconds { get; init; } = 60_000; + public int OperationTimeoutMilliseconds { get; init; } = 15_000; +} diff --git a/EonaCat.Connections.OpcUa/Configuration/OpcUaServerOptions.cs b/EonaCat.Connections.OpcUa/Configuration/OpcUaServerOptions.cs new file mode 100644 index 0000000..f5cc705 --- /dev/null +++ b/EonaCat.Connections.OpcUa/Configuration/OpcUaServerOptions.cs @@ -0,0 +1,19 @@ +using Opc.Ua; + +namespace EonaCat.Connections.OpcUa.Configuration; + +public sealed class OpcUaServerOptions +{ + public string ApplicationName { get; init; } = "EonaCat OPC UA Server"; + public string ApplicationUri { get; init; } = $"urn:{Utils.GetHostName()}:EonaCat:OpcUa:Server"; + public string ProductUri { get; init; } = "urn:EonaCat:Connector:OpcUa"; + public string BaseAddress { get; init; } = "opc.tcp://localhost:4840/EonaCat/Connector"; + public string NamespaceUri { get; init; } = "urn:EonaCat:Connector:OpcUa:AddressSpace"; + public bool EnableSecureEndpoint { get; init; } = true; + public bool AllowUnsecuredEndpoint { get; init; } = true; + public bool AutoAcceptUntrustedCertificates { get; init; } + public bool CheckCertificateRevocation { get; init; } = true; + public int OperationTimeoutMilliseconds { get; init; } = 15_000; + public int MaxSessionCount { get; init; } = 100; + public int MaxSubscriptionCount { get; init; } = 1_000; +} diff --git a/EonaCat.Connections.OpcUa/EonaCat.Connections.OpcUa.csproj b/EonaCat.Connections.OpcUa/EonaCat.Connections.OpcUa.csproj new file mode 100644 index 0000000..359e2d2 --- /dev/null +++ b/EonaCat.Connections.OpcUa/EonaCat.Connections.OpcUa.csproj @@ -0,0 +1,26 @@ + + + + net8.0 + latest + enable + enable + True + EonaCat.Connections.OpcUa + EonaCat + EonaCat.Connections.OpcUa + 1.0.0 + Jeroen Saey + OPC UA client and server for EonaCat.Connections + + + + + + + + + + + + \ No newline at end of file diff --git a/EonaCat.Connections.OpcUa/Infrastructure/OpcUaApplicationConfigurationFactory.cs b/EonaCat.Connections.OpcUa/Infrastructure/OpcUaApplicationConfigurationFactory.cs new file mode 100644 index 0000000..30b23a8 --- /dev/null +++ b/EonaCat.Connections.OpcUa/Infrastructure/OpcUaApplicationConfigurationFactory.cs @@ -0,0 +1,158 @@ +using Opc.Ua; +using Opc.Ua.Configuration; + +namespace EonaCat.Connections.OpcUa.Infrastructure; + +internal static class OpcUaApplicationConfigurationFactory +{ + public static async Task CreateClientAsync( + Configuration.OpcUaClientOptions options, + CancellationToken cancellationToken) + { + var configuration = CreateBase( + options.ApplicationName, + options.ApplicationUri, + ApplicationType.Client, + options.AutoAcceptUntrustedCertificates, + options.CheckCertificateRevocation, + options.OperationTimeoutMilliseconds); + + configuration.ClientConfiguration = new ClientConfiguration + { + DefaultSessionTimeout = options.SessionTimeoutMilliseconds + }; + + await ValidateAndCreateCertificateAsync(configuration, cancellationToken).ConfigureAwait(false); + return configuration; + } + + public static async Task CreateServerAsync( + Configuration.OpcUaServerOptions options, + CancellationToken cancellationToken) + { + var configuration = CreateBase( + options.ApplicationName, + options.ApplicationUri, + ApplicationType.Server, + options.AutoAcceptUntrustedCertificates, + options.CheckCertificateRevocation, + options.OperationTimeoutMilliseconds); + + configuration.ServerConfiguration = new ServerConfiguration + { + BaseAddresses = new[] { options.BaseAddress }, + SecurityPolicies = CreateSecurityPolicies(options), + UserTokenPolicies = new[] + { + new UserTokenPolicy(UserTokenType.Anonymous) + }, + MaxSessionCount = options.MaxSessionCount, + MaxSubscriptionCount = options.MaxSubscriptionCount + }; + + await ValidateAndCreateCertificateAsync(configuration, cancellationToken).ConfigureAwait(false); + return configuration; + } + + private static List CreateSecurityPolicies( + Configuration.OpcUaServerOptions options) + { + var policies = new List(); + if (options.AllowUnsecuredEndpoint) + { + policies.Add(new ServerSecurityPolicy + { + SecurityMode = MessageSecurityMode.None, + SecurityPolicyUri = SecurityPolicies.None + }); + } + + if (options.EnableSecureEndpoint) + { + policies.Add(new ServerSecurityPolicy + { + SecurityMode = MessageSecurityMode.SignAndEncrypt, + SecurityPolicyUri = SecurityPolicies.Basic256Sha256 + }); + } + + if (policies.Count == 0) + { + throw new ArgumentException("At least one OPC UA endpoint security policy must be enabled.", nameof(options)); + } + + return policies; + } + + private static ApplicationConfiguration CreateBase( + string applicationName, + string applicationUri, + ApplicationType applicationType, + bool autoAcceptUntrustedCertificates, + bool checkCertificateRevocation, + int operationTimeoutMilliseconds) + { + var certificateRoot = Path.Combine( + Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData), + "EonaCat", + "OpcUa", + applicationType.ToString()); + + return new ApplicationConfiguration(OpcUaRuntime.Telemetry) + { + ApplicationName = applicationName, + ApplicationUri = applicationUri, + ApplicationType = applicationType, + SecurityConfiguration = new SecurityConfiguration + { + ApplicationCertificate = new CertificateIdentifier + { + StoreType = "Directory", + StorePath = Path.Combine(certificateRoot, "own"), + SubjectName = $"CN={applicationName}, DC={Utils.GetHostName()}" + }, + TrustedPeerCertificates = CreateTrustList(certificateRoot, "trusted"), + TrustedIssuerCertificates = CreateTrustList(certificateRoot, "issuers"), + RejectedCertificateStore = new CertificateTrustList + { + StoreType = "Directory", + StorePath = Path.Combine(certificateRoot, "rejected") + }, + AutoAcceptUntrustedCertificates = autoAcceptUntrustedCertificates, + RejectSHA1SignedCertificates = true, + MinimumCertificateKeySize = 2048, + RejectUnknownRevocationStatus = checkCertificateRevocation + }, + TransportConfigurations = Array.Empty(), + TransportQuotas = new TransportQuotas + { + OperationTimeout = operationTimeoutMilliseconds + } + }; + } + + private static CertificateTrustList CreateTrustList(string root, string name) => new() + { + StoreType = "Directory", + StorePath = Path.Combine(root, name) + }; + + private static async Task ValidateAndCreateCertificateAsync( + ApplicationConfiguration configuration, + CancellationToken cancellationToken) + { + await configuration.ValidateAsync(configuration.ApplicationType, cancellationToken).ConfigureAwait(false); + + var application = new ApplicationInstance(OpcUaRuntime.Telemetry) + { + ApplicationName = configuration.ApplicationName, + ApplicationType = configuration.ApplicationType, + ApplicationConfiguration = configuration + }; + + if (!await application.CheckApplicationInstanceCertificatesAsync(false, 2048, cancellationToken).ConfigureAwait(false)) + { + throw new InvalidOperationException("OPC UA application certificate could not be created or validated."); + } + } +} diff --git a/EonaCat.Connections.OpcUa/Infrastructure/OpcUaRuntime.cs b/EonaCat.Connections.OpcUa/Infrastructure/OpcUaRuntime.cs new file mode 100644 index 0000000..1a99cdd --- /dev/null +++ b/EonaCat.Connections.OpcUa/Infrastructure/OpcUaRuntime.cs @@ -0,0 +1,12 @@ +using Opc.Ua; +using Opc.Ua.Client; + +namespace EonaCat.Connections.OpcUa.Infrastructure; + +internal static class OpcUaRuntime +{ + private static readonly ITelemetryContext TelemetryContext = DefaultTelemetry.Create(_ => { }); + + public static DefaultSessionFactory SessionFactory { get; } = new(TelemetryContext); + public static ITelemetryContext Telemetry => SessionFactory.Telemetry; +} diff --git a/EonaCat.Connections.OpcUa/Models/OpcUaConnectionEventArgs.cs b/EonaCat.Connections.OpcUa/Models/OpcUaConnectionEventArgs.cs new file mode 100644 index 0000000..a4b59f3 --- /dev/null +++ b/EonaCat.Connections.OpcUa/Models/OpcUaConnectionEventArgs.cs @@ -0,0 +1,7 @@ +namespace EonaCat.Connections.OpcUa.Models; + +public sealed class OpcUaConnectionEventArgs : EventArgs +{ + public required string EndpointUrl { get; init; } + public string? SessionName { get; init; } +} diff --git a/EonaCat.Connections.OpcUa/Models/OpcUaMethodDefinition.cs b/EonaCat.Connections.OpcUa/Models/OpcUaMethodDefinition.cs new file mode 100644 index 0000000..c498363 --- /dev/null +++ b/EonaCat.Connections.OpcUa/Models/OpcUaMethodDefinition.cs @@ -0,0 +1,13 @@ +using Opc.Ua; + +namespace EonaCat.Connections.OpcUa.Models; + +public sealed record OpcUaMethodArgument(string Name, NodeId DataType, string? Description = null); + +public sealed record OpcUaMethodDefinition( + string Identifier, + string DisplayName, + IReadOnlyList InputArguments, + IReadOnlyList OutputArguments, + Func, IReadOnlyList> Handler, + string? Description = null); diff --git a/EonaCat.Connections.OpcUa/Models/OpcUaNodeDefinition.cs b/EonaCat.Connections.OpcUa/Models/OpcUaNodeDefinition.cs new file mode 100644 index 0000000..066006b --- /dev/null +++ b/EonaCat.Connections.OpcUa/Models/OpcUaNodeDefinition.cs @@ -0,0 +1,11 @@ +using Opc.Ua; + +namespace EonaCat.Connections.OpcUa.Models; + +public sealed record OpcUaNodeDefinition( + string Identifier, + string DisplayName, + NodeId DataType, + object? InitialValue = null, + byte AccessLevel = AccessLevels.CurrentReadOrWrite, + string? Description = null); diff --git a/EonaCat.Connections.OpcUa/Models/OpcUaValueChangedEventArgs.cs b/EonaCat.Connections.OpcUa/Models/OpcUaValueChangedEventArgs.cs new file mode 100644 index 0000000..fcf175a --- /dev/null +++ b/EonaCat.Connections.OpcUa/Models/OpcUaValueChangedEventArgs.cs @@ -0,0 +1,11 @@ +using Opc.Ua; + +namespace EonaCat.Connections.OpcUa.Models; + +public sealed class OpcUaValueChangedEventArgs : EventArgs +{ + public required NodeId NodeId { get; init; } + public object? Value { get; init; } + public StatusCode StatusCode { get; init; } + public DateTime SourceTimestamp { get; init; } +} diff --git a/EonaCat.Connections.OpcUa/Server/HeijmansOpcUaServer.cs b/EonaCat.Connections.OpcUa/Server/HeijmansOpcUaServer.cs new file mode 100644 index 0000000..277dda4 --- /dev/null +++ b/EonaCat.Connections.OpcUa/Server/HeijmansOpcUaServer.cs @@ -0,0 +1,44 @@ +using EonaCat.Connections.OpcUa.Infrastructure; +using EonaCat.Connections.OpcUa.Models; +using Opc.Ua; +using Opc.Ua.Server; + +namespace EonaCat.Connections.OpcUa.Server; + +internal sealed class EonaCatOpcUaServer : StandardServer +{ + private readonly string _namespaceUri; + private readonly IReadOnlyCollection _nodes; + private readonly IReadOnlyCollection _methods; + + public EonaCatOpcUaServer( + string namespaceUri, + IReadOnlyCollection nodes, + IReadOnlyCollection methods) + : base(OpcUaRuntime.Telemetry) + { + _namespaceUri = namespaceUri; + _nodes = nodes; + _methods = methods; + } + + public OpcUaAddressSpace? AddressSpace { get; private set; } + + protected override MasterNodeManager CreateMasterNodeManager( + IServerInternal server, + ApplicationConfiguration configuration) + { + AddressSpace = new OpcUaAddressSpace(server, configuration, _namespaceUri, _nodes, _methods); + return new MasterNodeManager(server, configuration, null, AddressSpace); + } + + protected override ServerProperties LoadServerProperties() => new() + { + ManufacturerName = "EonaCat", + ProductName = "EonaCat Generic OPC UA Server", + ProductUri = "urn:EonaCat:Connector:OpcUa", + SoftwareVersion = Utils.GetAssemblySoftwareVersion(), + BuildNumber = Utils.GetAssemblyBuildNumber(), + BuildDate = Utils.GetAssemblyTimestamp() + }; +} diff --git a/EonaCat.Connections.OpcUa/Server/OpcUaAddressSpace.cs b/EonaCat.Connections.OpcUa/Server/OpcUaAddressSpace.cs new file mode 100644 index 0000000..353f344 --- /dev/null +++ b/EonaCat.Connections.OpcUa/Server/OpcUaAddressSpace.cs @@ -0,0 +1,197 @@ +using EonaCat.Connections.OpcUa.Models; +using Opc.Ua; +using Opc.Ua.Server; +using System.Collections.Concurrent; + +namespace EonaCat.Connections.OpcUa.Server; + +internal sealed class OpcUaAddressSpace : CustomNodeManager2 +{ + private readonly IReadOnlyCollection _nodeDefinitions; + private readonly IReadOnlyCollection _methodDefinitions; + private readonly ConcurrentDictionary _variables = new(StringComparer.Ordinal); + + public OpcUaAddressSpace( + IServerInternal server, + ApplicationConfiguration configuration, + string namespaceUri, + IReadOnlyCollection nodeDefinitions, + IReadOnlyCollection methodDefinitions) + : base(server, configuration, namespaceUri) + { + _nodeDefinitions = nodeDefinitions; + _methodDefinitions = methodDefinitions; + SystemContext.NodeIdFactory = this; + } + + public event EventHandler? ValueChanged; + + public override void CreateAddressSpace(IDictionary> externalReferences) + { + lock (Lock) + { + if (!externalReferences.TryGetValue(ObjectIds.ObjectsFolder, out var references)) + { + references = new List(); + externalReferences[ObjectIds.ObjectsFolder] = references; + } + + var root = new FolderState(null) + { + NodeId = new NodeId("EonaCat", NamespaceIndex), + BrowseName = new QualifiedName("EonaCat", NamespaceIndex), + DisplayName = (LocalizedText)"EonaCat", + TypeDefinitionId = ObjectTypeIds.FolderType, + EventNotifier = EventNotifiers.None + }; + root.AddReference(ReferenceTypeIds.Organizes, true, ObjectIds.ObjectsFolder); + references.Add(new NodeStateReference(ReferenceTypeIds.Organizes, false, root.NodeId)); + + foreach (var definition in _nodeDefinitions) + { + AddVariable(root, definition); + } + + foreach (var definition in _methodDefinitions) + { + AddMethod(root, definition); + } + + AddPredefinedNode(SystemContext, root); + } + } + + public NodeId ResolveNodeId(string identifier) => new(identifier, NamespaceIndex); + + public bool TrySetValue(string identifier, object? value) + { + if (!_variables.TryGetValue(identifier, out var variable)) + { + return false; + } + + lock (Lock) + { + variable.Value = new Variant(value); + variable.StatusCode = StatusCodes.Good; + variable.Timestamp = DateTime.UtcNow; + variable.ClearChangeMasks(SystemContext, false); + } + + RaiseValueChanged(variable); + return true; + } + + private void AddVariable(NodeState parent, OpcUaNodeDefinition definition) + { + var variable = new BaseDataVariableState(parent) + { + NodeId = ResolveNodeId(definition.Identifier), + BrowseName = new QualifiedName(definition.DisplayName, NamespaceIndex), + DisplayName = (LocalizedText)definition.DisplayName, + Description = (LocalizedText)definition.Description, + TypeDefinitionId = VariableTypeIds.BaseDataVariableType, + ReferenceTypeId = ReferenceTypeIds.HasComponent, + DataType = definition.DataType, + ValueRank = ValueRanks.Scalar, + AccessLevel = definition.AccessLevel, + UserAccessLevel = definition.AccessLevel, + Historizing = false, + Value = new Variant(definition.InitialValue), + StatusCode = StatusCodes.Good, + Timestamp = DateTime.UtcNow + }; + variable.OnSimpleWriteValue = HandleWrite; + parent.AddChild(variable); + _variables[definition.Identifier] = variable; + } + + private void AddMethod(NodeState parent, OpcUaMethodDefinition definition) + { + var method = new MethodState(parent) + { + NodeId = ResolveNodeId(definition.Identifier), + BrowseName = new QualifiedName(definition.DisplayName, NamespaceIndex), + DisplayName = (LocalizedText)definition.DisplayName, + Description = (LocalizedText)definition.Description, + ReferenceTypeId = ReferenceTypeIds.HasComponent, + Executable = true, + UserExecutable = true + }; + + method.InputArguments = CreateArguments(method, "InputArguments", definition.InputArguments); + method.OutputArguments = CreateArguments(method, "OutputArguments", definition.OutputArguments); + method.OnCallMethod = (_, _, inputArguments, outputArguments) => + { + try + { + var inputs = new object?[inputArguments.Count]; + for (var index = 0; index < inputs.Length; index++) + { + inputs[index] = inputArguments[index].Value; + } + + var results = definition.Handler(inputs); + for (var index = 0; index < Math.Min(results.Count, outputArguments.Count); index++) + { + outputArguments[index] = new Variant(results[index]); + } + return ServiceResult.Good; + } + catch (Exception exception) + { + return new ServiceResult(exception, StatusCodes.BadUnexpectedError); + } + }; + + parent.AddChild(method); + } + + private PropertyState> CreateArguments( + NodeState parent, + string name, + IReadOnlyList definitions) + { + var property = PropertyState>.With>(parent); + property.NodeId = new NodeId($"{parent.NodeId.Identifier}.{name}", NamespaceIndex); + property.BrowseName = (QualifiedName)(name == "InputArguments" ? BrowseNames.InputArguments : BrowseNames.OutputArguments); + property.DisplayName = (LocalizedText)name; + property.TypeDefinitionId = VariableTypeIds.PropertyType; + property.ReferenceTypeId = ReferenceTypeIds.HasProperty; + property.DataType = DataTypeIds.Argument; + property.ValueRank = ValueRanks.OneDimension; + property.Value = definitions.Select(definition => new Argument + { + Name = definition.Name, + DataType = definition.DataType, + ValueRank = ValueRanks.Scalar, + Description = (LocalizedText)definition.Description + }).ToArray(); + return property; + } + + private ServiceResult HandleWrite(ISystemContext context, NodeState node, ref Variant value) + { + if (node is not BaseDataVariableState variable || (variable.AccessLevel & AccessLevels.CurrentWrite) == 0) + { + return StatusCodes.BadNotWritable; + } + + variable.Value = value; + variable.Timestamp = DateTime.UtcNow; + variable.StatusCode = StatusCodes.Good; + RaiseValueChanged(variable); + return ServiceResult.Good; + } + + private void RaiseValueChanged(BaseDataVariableState variable) + { + ValueChanged?.Invoke(this, new OpcUaValueChangedEventArgs + { + NodeId = variable.NodeId, + Value = variable.Value.Value, + StatusCode = variable.StatusCode, + SourceTimestamp = variable.Timestamp.ToDateTime() + }); + } +} diff --git a/EonaCat.Connections.OpcUa/Server/OpcUaNetworkServer.cs b/EonaCat.Connections.OpcUa/Server/OpcUaNetworkServer.cs new file mode 100644 index 0000000..be1f2c7 --- /dev/null +++ b/EonaCat.Connections.OpcUa/Server/OpcUaNetworkServer.cs @@ -0,0 +1,170 @@ +using EonaCat.Connections.OpcUa.Configuration; +using EonaCat.Connections.OpcUa.Infrastructure; +using EonaCat.Connections.OpcUa.Models; +using Opc.Ua; +using Opc.Ua.Configuration; + +namespace EonaCat.Connections.OpcUa.Server; + +public sealed class OpcUaNetworkServer : IAsyncDisposable, IDisposable +{ + private readonly OpcUaServerOptions _options; + private readonly List _nodes = []; + private readonly List _methods = []; + private readonly SemaphoreSlim _lifecycleLock = new(1, 1); + private ApplicationInstance? _application; + private EonaCatOpcUaServer? _server; + private bool _disposed; + + public OpcUaNetworkServer(OpcUaServerOptions options) + { + _options = options ?? throw new ArgumentNullException(nameof(options)); + } + + public bool IsStarted { get; private set; } + public string EndpointUrl => _options.BaseAddress; + public string NamespaceUri => _options.NamespaceUri; + + public event EventHandler? Started; + public event EventHandler? Stopped; + public event EventHandler? ValueChanged; + public event EventHandler? Error; + + public OpcUaNetworkServer AddVariable(OpcUaNodeDefinition definition) + { + EnsureNotStarted(); + ArgumentNullException.ThrowIfNull(definition); + if (_nodes.Any(node => string.Equals(node.Identifier, definition.Identifier, StringComparison.Ordinal))) + { + throw new ArgumentException($"A node with identifier '{definition.Identifier}' is already registered.", nameof(definition)); + } + + _nodes.Add(definition); + return this; + } + + public OpcUaNetworkServer AddMethod(OpcUaMethodDefinition definition) + { + EnsureNotStarted(); + ArgumentNullException.ThrowIfNull(definition); + if (_methods.Any(method => string.Equals(method.Identifier, definition.Identifier, StringComparison.Ordinal))) + { + throw new ArgumentException($"A method with identifier '{definition.Identifier}' is already registered.", nameof(definition)); + } + + _methods.Add(definition); + return this; + } + + public async Task StartAsync(CancellationToken cancellationToken = default) + { + await _lifecycleLock.WaitAsync(cancellationToken).ConfigureAwait(false); + try + { + ObjectDisposedException.ThrowIf(_disposed, this); + if (IsStarted) + { + return; + } + + var configuration = await OpcUaApplicationConfigurationFactory + .CreateServerAsync(_options, cancellationToken) + .ConfigureAwait(false); + _server = new EonaCatOpcUaServer(_options.NamespaceUri, _nodes.ToArray(), _methods.ToArray()); + _application = new ApplicationInstance(OpcUaRuntime.Telemetry) + { + ApplicationName = _options.ApplicationName, + ApplicationType = ApplicationType.Server, + ApplicationConfiguration = configuration + }; + + await _application.StartAsync(_server).ConfigureAwait(false); + if (_server.AddressSpace != null) + { + _server.AddressSpace.ValueChanged += HandleValueChanged; + } + + IsStarted = true; + Started?.Invoke(this, EventArgs.Empty); + } + catch (Exception exception) + { + Error?.Invoke(this, exception); + throw; + } + finally + { + _lifecycleLock.Release(); + } + } + + public NodeId GetNodeId(string identifier) + { + ArgumentException.ThrowIfNullOrWhiteSpace(identifier); + return _server?.AddressSpace?.ResolveNodeId(identifier) + ?? throw new InvalidOperationException("The OPC UA server has not started."); + } + + public bool TrySetValue(string identifier, object? value) + { + ArgumentException.ThrowIfNullOrWhiteSpace(identifier); + return _server?.AddressSpace?.TrySetValue(identifier, value) == true; + } + + public async Task StopAsync(CancellationToken cancellationToken = default) + { + await _lifecycleLock.WaitAsync(cancellationToken).ConfigureAwait(false); + try + { + if (!IsStarted) + { + return; + } + + if (_server?.AddressSpace != null) + { + _server.AddressSpace.ValueChanged -= HandleValueChanged; + } + + if (_application != null) + { + await _application.StopAsync().ConfigureAwait(false); + } + _server?.Dispose(); + _server = null; + _application = null; + IsStarted = false; + Stopped?.Invoke(this, EventArgs.Empty); + } + finally + { + _lifecycleLock.Release(); + } + } + + private void HandleValueChanged(object? sender, OpcUaValueChangedEventArgs args) => + ValueChanged?.Invoke(this, args); + + private void EnsureNotStarted() + { + ObjectDisposedException.ThrowIf(_disposed, this); + if (IsStarted) + { + throw new InvalidOperationException("Nodes and methods must be registered before the OPC UA server starts."); + } + } + + public async ValueTask DisposeAsync() + { + if (_disposed) + { + return; + } + + await StopAsync().ConfigureAwait(false); + _disposed = true; + _lifecycleLock.Dispose(); + } + + public void Dispose() => DisposeAsync().AsTask().GetAwaiter().GetResult(); +} diff --git a/EonaCat.Connections.Quic.Client/EonaCat.Connections.Quic.Client.csproj b/EonaCat.Connections.Quic.Client/EonaCat.Connections.Quic.Client.csproj new file mode 100644 index 0000000..c2dddc2 --- /dev/null +++ b/EonaCat.Connections.Quic.Client/EonaCat.Connections.Quic.Client.csproj @@ -0,0 +1,14 @@ + + + + Exe + net8.0 + enable + enable + + + + + + + diff --git a/EonaCat.Connections.Quic.Client/Program.cs b/EonaCat.Connections.Quic.Client/Program.cs new file mode 100644 index 0000000..6033ef6 --- /dev/null +++ b/EonaCat.Connections.Quic.Client/Program.cs @@ -0,0 +1,75 @@ +using EonaCat.Connections.Models; +using System.Runtime.Versioning; + +namespace EonaCat.Connections.Quic.Client.Example +{ + [RequiresPreviewFeatures] + public class Program + { + private const string SERVER_IP = "127.0.0.1"; + private const int SERVER_PORT = 8443; + + public static async Task Main(string[] args) + { + var config = new Configuration + { + Host = SERVER_IP, + Port = SERVER_PORT, + IsSelfSignedEnabled = true, + EnableAutoReconnect = true, + ReconnectDelayInSeconds = 5, + }; + + await using var client = new QuicNetworkClient(config); + + client.OnConnected += (sender, e) => + { + Console.WriteLine($"[QUIC Client] Connected to {e.RemoteEndPoint}"); + }; + + client.OnDataReceived += (sender, e) => + { + Console.WriteLine($"[QUIC Client] Received: {e.StringData}"); + }; + + client.OnDisconnected += (sender, e) => + { + Console.WriteLine($"[QUIC Client] Disconnected: {e.Reason}"); + }; + + client.OnGeneralError += (sender, e) => + { + Console.WriteLine($"[QUIC Client] Error: {e.Message} - {e.Exception?.Message}"); + }; + + Console.WriteLine("[QUIC Client] Connecting..."); + var connected = await client.ConnectAsync(); + + if (!connected) + { + Console.WriteLine("[QUIC Client] Failed to connect. Press any key to exit."); + Console.ReadKey(); + return; + } + + await client.SendNicknameAsync("QuicTestClient"); + + while (true) + { + Console.Write("Enter message (or 'exit'): "); + var message = Console.ReadLine(); + + if (string.IsNullOrEmpty(message) || message.Equals("exit", StringComparison.OrdinalIgnoreCase)) + { + break; + } + + await client.SendAsync(message); + } + + await client.DisconnectAsync(); + Console.WriteLine("[QUIC Client] Disconnected. Press any key to exit."); + Console.ReadKey(); + } + } +} diff --git a/EonaCat.Connections.Quic.Server/EonaCat.Connections.Quic.Server.csproj b/EonaCat.Connections.Quic.Server/EonaCat.Connections.Quic.Server.csproj new file mode 100644 index 0000000..c2dddc2 --- /dev/null +++ b/EonaCat.Connections.Quic.Server/EonaCat.Connections.Quic.Server.csproj @@ -0,0 +1,14 @@ + + + + Exe + net8.0 + enable + enable + + + + + + + diff --git a/EonaCat.Connections.Quic.Server/Program.cs b/EonaCat.Connections.Quic.Server/Program.cs new file mode 100644 index 0000000..9d75d06 --- /dev/null +++ b/EonaCat.Connections.Quic.Server/Program.cs @@ -0,0 +1,117 @@ +using EonaCat.Connections.Models; +using System.Runtime.Versioning; +using System.Security.Cryptography; +using System.Security.Cryptography.X509Certificates; + +namespace EonaCat.Connections.Quic.Server.Example +{ + [RequiresPreviewFeatures] + public class Program + { + private const string LISTEN_IP = "127.0.0.1"; + private const int LISTEN_PORT = 8443; + + public static async Task Main(string[] args) + { + + using var certificate = GenerateSelfSignedCertificate(); + + var config = new Configuration + { + Host = LISTEN_IP, + Port = LISTEN_PORT, + Certificate = certificate, + IsSelfSignedEnabled = true, + }; + + using var server = new QuicNetworkServer(config); + + server.OnConnected += (sender, e) => + { + Console.WriteLine($"[QUIC Server] Client connected: {e.ClientId} from {e.RemoteEndPoint}"); + }; + + server.OnDataReceived += async (sender, e) => + { + Console.WriteLine($"[QUIC Server] Received from {e.Nickname ?? e.ClientId}: {e.StringData}"); + + if (sender is QuicNetworkServer srv) + { + await srv.SendToClientAsync(e.ClientId, $"Echo: {e.StringData}"); + } + }; + + server.OnDisconnected += (sender, e) => + { + Console.WriteLine($"[QUIC Server] Client disconnected: {e.Nickname ?? e.ClientId} ({e.Reason})"); + }; + + server.OnGeneralError += (sender, e) => + { + Console.WriteLine($"[QUIC Server] Error: {e.Message} - {e.Exception?.Message}"); + }; + + Console.WriteLine($"[QUIC Server] Starting on {LISTEN_IP}:{LISTEN_PORT}..."); + await server.StartAsync(); + Console.WriteLine("[QUIC Server] Started. Press 'q' to stop."); + + while (true) + { + var key = Console.ReadKey(true); + if (key.KeyChar == 'q') + { + break; + } + + if (key.KeyChar == 'b') + { + Console.Write("Broadcast message: "); + var msg = Console.ReadLine(); + if (!string.IsNullOrEmpty(msg)) + { + await server.BroadcastAsync(msg); + } + } + + if (key.KeyChar == 'c') + { + var clients = server.GetClients(); + Console.WriteLine($"[QUIC Server] Active connections: {server.ActiveConnections}"); + foreach (var client in clients) + { + Console.WriteLine($" - {client.Value.Nickname} ({client.Key}) from {client.Value.RemoteEndPoint}"); + } + } + } + + Console.WriteLine("[QUIC Server] Stopping..."); + await server.StopAsync(); + Console.WriteLine("[QUIC Server] Stopped."); + } + + private static X509Certificate2 GenerateSelfSignedCertificate() + { + + using var ecdsa = ECDsa.Create(ECCurve.NamedCurves.nistP256); + var request = new CertificateRequest("CN=localhost", ecdsa, HashAlgorithmName.SHA256); + + request.CertificateExtensions.Add( + new X509KeyUsageExtension( + X509KeyUsageFlags.DigitalSignature, + critical: false)); + + request.CertificateExtensions.Add( + new X509EnhancedKeyUsageExtension( + new OidCollection { new Oid("1.3.6.1.5.5.7.3.1") }, + critical: false)); + + var sanBuilder = new SubjectAlternativeNameBuilder(); + sanBuilder.AddDnsName("localhost"); + sanBuilder.AddIpAddress(System.Net.IPAddress.Loopback); + request.CertificateExtensions.Add(sanBuilder.Build()); + + using var certificate = request.CreateSelfSigned(DateTimeOffset.UtcNow.AddMinutes(-5), DateTimeOffset.UtcNow.AddYears(200)); + return new X509Certificate2(certificate.Export(X509ContentType.Pfx), (string?)null, X509KeyStorageFlags.Exportable); + } + } +} diff --git a/EonaCat.Connections.Quic/EonaCat.Connections.Quic.csproj b/EonaCat.Connections.Quic/EonaCat.Connections.Quic.csproj new file mode 100644 index 0000000..3b76341 --- /dev/null +++ b/EonaCat.Connections.Quic/EonaCat.Connections.Quic.csproj @@ -0,0 +1,25 @@ + + + + net8.0 + latest + enable + enable + True + EonaCat.Connections.Quic + EonaCat + Jeroen Saey + EonaCat.Connections.Quic + 1.0.0 + Jeroen Saey + EonaCat.Connections.Quic for QUIC client/servers + + + + true + + + + + + diff --git a/EonaCat.Connections.Quic/QuicClientConnection.cs b/EonaCat.Connections.Quic/QuicClientConnection.cs new file mode 100644 index 0000000..fb4ff33 --- /dev/null +++ b/EonaCat.Connections.Quic/QuicClientConnection.cs @@ -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; + } +} diff --git a/EonaCat.Connections.Quic/QuicNetworkClient.cs b/EonaCat.Connections.Quic/QuicNetworkClient.cs new file mode 100644 index 0000000..652be24 --- /dev/null +++ b/EonaCat.Connections.Quic/QuicNetworkClient.cs @@ -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 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? OnConnected; + public event EventHandler? OnNicknameSend; + public event EventHandler? OnDataReceived; + public event EventHandler? OnDisconnected; + public event EventHandler? OnGeneralError; + + public QuicNetworkClient(Configuration config) + { + _config = config ?? throw new ArgumentNullException(nameof(config)); + _clientCts = new CancellationTokenSource(); + } + + public async Task 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 + { + 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.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.Shared.Return(buffer); + } + } + + public async Task 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 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(); + 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); + } + } +} diff --git a/EonaCat.Connections.Quic/QuicNetworkServer.cs b/EonaCat.Connections.Quic/QuicNetworkServer.cs new file mode 100644 index 0000000..c94074a --- /dev/null +++ b/EonaCat.Connections.Quic/QuicNetworkServer.cs @@ -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 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 _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? OnConnected; + public event EventHandler? OnDataReceived; + public event EventHandler? OnDisconnected; + public event EventHandler? 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 + { + 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 + { + 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.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.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 + { + { "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 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 SendToClientAsync(string clientId, string message) + => await SendToClientAsync(clientId, Encoding.UTF8.GetBytes(message)).ConfigureAwait(false); + + public async Task 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 BroadcastAsync(string message) + => await BroadcastAsync(Encoding.UTF8.GetBytes(message)).ConfigureAwait(false); + + public ConcurrentDictionary 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 + { + { "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; + } + } +} diff --git a/EonaCat.Connections.REST.Client/EonaCat.Connections.REST.Client.csproj b/EonaCat.Connections.REST.Client/EonaCat.Connections.REST.Client.csproj new file mode 100644 index 0000000..992ba3c --- /dev/null +++ b/EonaCat.Connections.REST.Client/EonaCat.Connections.REST.Client.csproj @@ -0,0 +1,14 @@ + + + + Exe + net8.0 + enable + enable + + + + + + + diff --git a/EonaCat.Connections.REST.Client/Program.cs b/EonaCat.Connections.REST.Client/Program.cs new file mode 100644 index 0000000..6f62c89 --- /dev/null +++ b/EonaCat.Connections.REST.Client/Program.cs @@ -0,0 +1,91 @@ +using EonaCat.Connections.Models; + +namespace EonaCat.Connections.REST.Client.Example +{ + public class Program + { + private const string SERVER_IP = "127.0.0.1"; + private const int SERVER_PORT = 5580; + private const int WEBHOOK_PORT = 5581; + + public static async Task Main(string[] args) + { + var config = new Configuration + { + Host = SERVER_IP, + Port = SERVER_PORT, + IsSelfSignedEnabled = true, + EnableAutoReconnect = true, + ReconnectDelayInSeconds = 5, + }; + + await using var client = new RestNetworkClient(config); + + client.OnConnected += (sender, e) => + { + Console.WriteLine($"[REST Client] Connected to {e.RemoteEndPoint} (clientId: {e.ClientId})"); + }; + + client.OnDataReceived += (sender, e) => + { + Console.WriteLine($"[REST Client] Received: {e.StringData}"); + }; + + client.OnDisconnected += (sender, e) => + { + Console.WriteLine($"[REST Client] Disconnected: {e.Reason}"); + }; + + client.OnGeneralError += (sender, e) => + { + Console.WriteLine($"[REST Client] Error: {e.Message} - {e.Exception?.Message}"); + }; + + Console.WriteLine("[REST Client] Connecting..."); + var connected = await client.ConnectAsync(); + + if (!connected) + { + Console.WriteLine("[REST Client] Failed to connect. Press any key to exit."); + Console.ReadKey(); + return; + } + + await client.SendNicknameAsync("RestTestClient"); + + Console.WriteLine($"[REST Client] Starting webhook listener on port {WEBHOOK_PORT}..."); + await client.StartWebhookListenerAsync(WEBHOOK_PORT); + await client.RegisterWebhookAsync(); + Console.WriteLine("[REST Client] Webhook registered."); + + Console.WriteLine("[REST Client] Commands: type a message to send, 'broadcast ' to broadcast, 'exit' to quit."); + + while (true) + { + Console.Write("> "); + var input = Console.ReadLine(); + + if (string.IsNullOrEmpty(input) || input.Equals("exit", StringComparison.OrdinalIgnoreCase)) + { + break; + } + + if (input.StartsWith("broadcast ", StringComparison.OrdinalIgnoreCase)) + { + var msg = input.Substring("broadcast ".Length); + await client.BroadcastAsync(msg); + Console.WriteLine("[REST Client] Broadcast sent."); + } + else + { + await client.SendAsync(input); + } + } + + await client.StopWebhookListenerAsync(); + await client.DisconnectAsync(); + Console.WriteLine("[REST Client] Disconnected. Press any key to exit."); + Console.ReadKey(); + } + } +} diff --git a/EonaCat.Connections.REST.Server/EonaCat.Connections.REST.Server.csproj b/EonaCat.Connections.REST.Server/EonaCat.Connections.REST.Server.csproj new file mode 100644 index 0000000..992ba3c --- /dev/null +++ b/EonaCat.Connections.REST.Server/EonaCat.Connections.REST.Server.csproj @@ -0,0 +1,14 @@ + + + + Exe + net8.0 + enable + enable + + + + + + + diff --git a/EonaCat.Connections.REST.Server/Program.cs b/EonaCat.Connections.REST.Server/Program.cs new file mode 100644 index 0000000..a9b7287 --- /dev/null +++ b/EonaCat.Connections.REST.Server/Program.cs @@ -0,0 +1,114 @@ +using EonaCat.Connections.Models; +using System.Security.Cryptography; +using System.Security.Cryptography.X509Certificates; + +namespace EonaCat.Connections.REST.Server.Example +{ + public class Program + { + private const string LISTEN_IP = "127.0.0.1"; + private const int LISTEN_PORT = 5580; + + public static async Task Main(string[] args) + { + using var certificate = GenerateSelfSignedCertificate(); + + var config = new Configuration + { + Host = LISTEN_IP, + Port = LISTEN_PORT, + Certificate = certificate, + IsSelfSignedEnabled = true, + }; + + using var server = new RestNetworkServer(config); + + server.OnConnected += (sender, e) => + { + Console.WriteLine($"[REST Server] Client connected: {e.ClientId} from {e.RemoteEndPoint}"); + }; + + server.OnDataReceived += async (sender, e) => + { + Console.WriteLine($"[REST Server] Received from {e.Nickname ?? e.ClientId}: {e.StringData}"); + + if (sender is RestNetworkServer srv) + { + await srv.SendToClientAsync(e.ClientId, $"Echo: {e.StringData}"); + } + }; + + server.OnDisconnected += (sender, e) => + { + Console.WriteLine($"[REST Server] Client disconnected: {e.Nickname ?? e.ClientId} ({e.Reason})"); + }; + + server.OnGeneralError += (sender, e) => + { + Console.WriteLine($"[REST Server] Error: {e.Message} - {e.Exception?.Message}"); + }; + + Console.WriteLine($"[REST Server] Starting on {LISTEN_IP}:{LISTEN_PORT}..."); + await server.StartAsync(); + Console.WriteLine("[REST Server] Started. Press 'q' to stop."); + + while (true) + { + var key = Console.ReadKey(true); + if (key.KeyChar == 'q') + { + break; + } + + if (key.KeyChar == 'b') + { + Console.Write("Broadcast message: "); + var msg = Console.ReadLine(); + if (!string.IsNullOrEmpty(msg)) + { + await server.BroadcastAsync(msg); + } + } + + if (key.KeyChar == 'c') + { + var clients = server.GetClients(); + Console.WriteLine($"[REST Server] Active connections: {server.ActiveConnections}"); + foreach (var client in clients) + { + Console.WriteLine($" - {client.Value.Nickname} ({client.Key}) from {client.Value.RemoteEndPoint}" + + $"{(client.Value.WebhookUrl != null ? $" [webhook: {client.Value.WebhookUrl}]" : "")}"); + } + } + } + + Console.WriteLine("[REST Server] Stopping..."); + await server.StopAsync(); + Console.WriteLine("[REST Server] Stopped."); + } + + private static X509Certificate2 GenerateSelfSignedCertificate() + { + using var ecdsa = ECDsa.Create(ECCurve.NamedCurves.nistP256); + var request = new CertificateRequest("CN=localhost", ecdsa, HashAlgorithmName.SHA256); + + request.CertificateExtensions.Add( + new X509KeyUsageExtension( + X509KeyUsageFlags.DigitalSignature, + critical: false)); + + request.CertificateExtensions.Add( + new X509EnhancedKeyUsageExtension( + new OidCollection { new Oid("1.3.6.1.5.5.7.3.1") }, + critical: false)); + + var sanBuilder = new SubjectAlternativeNameBuilder(); + sanBuilder.AddDnsName("localhost"); + sanBuilder.AddIpAddress(System.Net.IPAddress.Loopback); + request.CertificateExtensions.Add(sanBuilder.Build()); + + using var certificate = request.CreateSelfSigned(DateTimeOffset.UtcNow.AddMinutes(-5), DateTimeOffset.UtcNow.AddYears(200)); + return new X509Certificate2(certificate.Export(X509ContentType.Pfx), (string?)null, X509KeyStorageFlags.Exportable); + } + } +} diff --git a/EonaCat.Connections.REST/EonaCat.Connections.REST.csproj b/EonaCat.Connections.REST/EonaCat.Connections.REST.csproj new file mode 100644 index 0000000..e93efc6 --- /dev/null +++ b/EonaCat.Connections.REST/EonaCat.Connections.REST.csproj @@ -0,0 +1,30 @@ + + + + net8.0 + latest + enable + enable + True + EonaCat.Connections.REST + EonaCat + Jeroen Saey + EonaCat.Connections.REST + 1.0.0 + Jeroen Saey + EonaCat.Connections.REST for REST client/servers with optional TLS, broadcast, and webhook support + + + + + + + + + + + + + + + diff --git a/EonaCat.Connections.REST/RestClientConnection.cs b/EonaCat.Connections.REST/RestClientConnection.cs new file mode 100644 index 0000000..2333ae1 --- /dev/null +++ b/EonaCat.Connections.REST/RestClientConnection.cs @@ -0,0 +1,50 @@ +using System.Collections.Concurrent; +using System.Net; +using System.Security.Cryptography; + +namespace EonaCat.Connections.REST +{ + public class RestClientConnection : IDisposable + { + public string Id { get; set; } = string.Empty; + public IPEndPoint? RemoteEndPoint { get; set; } + public CancellationTokenSource? CancellationSource { get; set; } + public DateTime ConnectedAt { get; set; } + public DateTime LastActive { get; set; } + public DateTime LastDataSent { get; set; } + public DateTime LastDataReceived { get; set; } + public DateTime LastPingSent { get; set; } + public DateTime LastPongReceived { 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; + + internal ConcurrentQueue PendingMessages { get; } = new(); + + public int PendingMessageCount => PendingMessages.Count; + + public string? WebhookUrl { get; set; } + + public Aes? AesInstance { get; set; } + public byte[]? AesSalt { get; set; } + public byte[]? AesIv { get; set; } + + public void Dispose() + { + AesInstance?.Dispose(); + AesInstance = null; + CancellationSource?.Dispose(); + } + } +} diff --git a/EonaCat.Connections.REST/RestNetworkClient.cs b/EonaCat.Connections.REST/RestNetworkClient.cs new file mode 100644 index 0000000..97b13e8 --- /dev/null +++ b/EonaCat.Connections.REST/RestNetworkClient.cs @@ -0,0 +1,859 @@ +using EonaCat.Json; +using EonaCat.Json.Linq; +using EonaCat.Connections.EventArguments; +using EonaCat.Connections.Helpers; +using EonaCat.Connections.Models; +using EonaCat.Connections.ConnectionDiagnostics; +using Microsoft.AspNetCore.Builder; +using Microsoft.AspNetCore.Hosting; +using Microsoft.AspNetCore.Http; +using Microsoft.AspNetCore.Server.Kestrel.Core; +using System.Net; +using System.Security.Cryptography; +using System.Text; +using ErrorEventArgs = EonaCat.Connections.EventArguments.ErrorEventArgs; + +namespace EonaCat.Connections.REST +{ + public class RestNetworkClient : IAsyncDisposable, IDisposable + { + public static event EventHandler OnLog; + private readonly Configuration _config; + private HttpClient? _httpClient; + private Task? _pollTask; + private Task? _autoReconnectTask; + private Task? _pingTask; + private Task? _pongMonitorTask; + private CancellationTokenSource? _clientCts; + private CancellationTokenSource? _autoReconnectSource; + private bool _disposed; + private bool _stopAutoReconnecting; + private bool _wasConnected; + private DisconnectReason _reason; + private Aes? _aesInstance; + + private WebApplication? _webhookApp; + private CancellationTokenSource? _webhookCts; + private Task? _webhookTask; + private int _webhookPort; + + private readonly SemaphoreSlim _connectLock = new(1, 1); + + public string? ClientId { get; private set; } + 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 LastPingSent { get; private set; } + public DateTime LastPongReceived { get; private set; } + public DateTime DisconnectionTime { get; private set; } + public bool IsAutoConnectStarted => _autoReconnectTask != null && !_autoReconnectTask.IsCompleted; + public bool IsWebhookListenerActive => _webhookApp != null && _webhookCts != null && !_webhookCts.IsCancellationRequested; + + 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 event EventHandler? OnConnected; + public event EventHandler? OnNicknameSend; + public event EventHandler? OnDataReceived; + public event EventHandler? OnDisconnected; + public event EventHandler? OnGeneralError; + public event EventHandler? OnPingResponse; + public event EventHandler? OnPongResponse; + + public WebhookManager Webhooks { get; } = new(); + + public RestNetworkClient(Configuration config) + { + _config = config ?? throw new ArgumentNullException(nameof(config)); + _clientCts = new CancellationTokenSource(); + } + + private string BaseUrl + { + get + { + var scheme = _config.UseSsl ? "https" : "http"; + return $"{scheme}://{_config.Host}:{_config.Port}"; + } + } + + public async Task ConnectAsync() + { + await _connectLock.WaitAsync().ConfigureAwait(false); + + try + { + if (_clientCts == null || _clientCts.IsCancellationRequested) + { + _clientCts?.Dispose(); + _clientCts = new CancellationTokenSource(); + } + + if (IsConnected) + { + return true; + } + + _httpClient?.Dispose(); + + var handler = new HttpClientHandler(); + if (_config.UseSsl && _config.IsSelfSignedEnabled) + { + handler.ServerCertificateCustomValidationCallback = (_, _, _, _) => true; + } + + _httpClient = new HttpClient(handler) + { + BaseAddress = new Uri(BaseUrl), + Timeout = _config.ConnectionTimeout + }; + + var response = await _httpClient.PostAsync("/api/connect", + new StringContent("{}", Encoding.UTF8, "application/json")).ConfigureAwait(false); + + if (!response.IsSuccessStatusCode) + { + return false; + } + + var json = await response.Content.ReadAsStringAsync().ConfigureAwait(false); + var doc = JObject.Parse(json); + ClientId = (string)doc["clientId"]; + + if (string.IsNullOrEmpty(ClientId)) + { + return false; + } + + IsConnected = true; + ConnectionTime = DateTime.UtcNow; + LastActive = DateTime.UtcNow; + LastPongReceived = DateTime.UtcNow; + + if (_config.UseAesEncryption && !string.IsNullOrEmpty(_config.AesPassword)) + { + await InitAesEncryptionAsync().ConfigureAwait(false); + } + + _pollTask = Task.Run(() => PollLoopAsync(_clientCts.Token), _clientCts.Token); + + if (_config.EnableHeartbeat) + { + _pingTask = Task.Run(() => PingLoopAsync(_clientCts.Token), _clientCts.Token); + _pongMonitorTask = Task.Run(() => PongMonitorAsync(_clientCts.Token), _clientCts.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 = ClientId, + 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 = "REST connection error" + }, + nameof(OnGeneralError)); + return false; + } + finally + { + try + { + _connectLock.Release(); + } + catch + { + + } + } + } + + private async Task PollLoopAsync(CancellationToken token) + { + try + { + while (!token.IsCancellationRequested && IsConnected) + { + try + { + if (_httpClient == null || string.IsNullOrEmpty(ClientId)) + { + break; + } + + var response = await _httpClient.GetAsync($"/api/poll/{ClientId}", token).ConfigureAwait(false); + + if (!response.IsSuccessStatusCode) + { + if (response.StatusCode == System.Net.HttpStatusCode.NotFound) + { + await DisconnectAsync(DisconnectReason.RemoteClosed).ConfigureAwait(false); + break; + } + await Task.Delay(1000, token).ConfigureAwait(false); + continue; + } + + var json = await response.Content.ReadAsStringAsync(token).ConfigureAwait(false); + var doc = JObject.Parse(json); + + if (doc.TryGetValue("messages", out var messagesToken) && messagesToken is JArray messagesArray) + { + foreach (var msg in messagesArray) + { + var base64 = (string)msg; + if (string.IsNullOrEmpty(base64)) + { + continue; + } + + var data = Convert.FromBase64String(base64); + + if (_config.UseAesEncryption && _aesInstance != null) + { + data = await AesKeyExchange.DecryptDataAsync(data, data.Length, _aesInstance).ConfigureAwait(false); + } + + LastActive = DateTime.UtcNow; + LastDataReceived = DateTime.UtcNow; + BytesReceived += data.Length; + MessagesReceived++; + + HandlingHelpers.SafeInvokeEventHandler( + OnDataReceived, + this, + new DataReceivedEventArgs + { + ClientId = ClientId ?? "self", + Data = data, + RemoteEndPoint = new IPEndPoint(IPAddress.Parse(_config.Host), _config.Port), + Nickname = Nickname + }, + nameof(OnDataReceived)); + } + } + + await Task.Delay(500, token).ConfigureAwait(false); + } + catch (OperationCanceledException) + { + break; + } + catch (HttpRequestException) + { + await DisconnectAsync(DisconnectReason.RemoteClosed).ConfigureAwait(false); + break; + } + } + } + catch (OperationCanceledException) + { + + } + catch (Exception exception) + { + HandlingHelpers.SafeInvokeEventHandler( + OnGeneralError, + this, + new ErrorEventArgs + { + Exception = exception, + Message = "Error in REST poll loop" + }, + nameof(OnGeneralError)); + await DisconnectAsync(DisconnectReason.Error, exception).ConfigureAwait(false); + } + } + + public async Task SendAsync(byte[] data) + { + if (!IsConnected || _httpClient == null || string.IsNullOrEmpty(ClientId) || data == null || data.Length == 0) + { + return false; + } + + try + { + var sendData = data; + if (_config.UseAesEncryption && _aesInstance != null) + { + sendData = await AesKeyExchange.EncryptDataAsync(data, data.Length, _aesInstance).ConfigureAwait(false); + } + + var payload = JsonHelper.ToJson(new + { + clientId = ClientId, + data = Convert.ToBase64String(sendData) + }); + + var response = await _httpClient.PostAsync("/api/send", + new StringContent(payload, Encoding.UTF8, "application/json")).ConfigureAwait(false); + + LastActive = DateTime.UtcNow; + LastDataSent = DateTime.UtcNow; + BytesSent += data.Length; + MessagesSent++; + return response.IsSuccessStatusCode; + } + catch (Exception ex) + { + await DisconnectAsync(DisconnectReason.Error, ex).ConfigureAwait(false); + return false; + } + } + + public async Task SendAsync(string message) => await SendAsync(Encoding.UTF8.GetBytes(message)).ConfigureAwait(false); + + public async Task BroadcastAsync(byte[] data) + { + if (!IsConnected || _httpClient == null || string.IsNullOrEmpty(ClientId) || data == null || data.Length == 0) + { + return false; + } + + try + { + var broadcast_data = data; + if (_config.UseAesEncryption && _aesInstance != null) + { + broadcast_data = await AesKeyExchange.EncryptDataAsync(data, data.Length, _aesInstance).ConfigureAwait(false); + } + + var payload = JsonHelper.ToJson(new + { + clientId = ClientId, + data = Convert.ToBase64String(broadcast_data) + }); + + var response = await _httpClient.PostAsync("/api/broadcast", + new StringContent(payload, Encoding.UTF8, "application/json")).ConfigureAwait(false); + + return response.IsSuccessStatusCode; + } + catch (Exception ex) + { + HandlingHelpers.SafeInvokeEventHandler( + OnGeneralError, + this, + new ErrorEventArgs + { + Exception = ex, + Message = "Error broadcasting via REST" + }, + nameof(OnGeneralError)); + return false; + } + } + + public async Task BroadcastAsync(string message) => await BroadcastAsync(Encoding.UTF8.GetBytes(message)).ConfigureAwait(false); + + public async Task SendNicknameAsync(string nickname) + { + Nickname = nickname; + if (IsConnected && _httpClient != null && !string.IsNullOrEmpty(ClientId)) + { + var payload = JsonHelper.ToJson(new { clientId = ClientId, nickname }); + await _httpClient.PostAsync("/api/nickname", + new StringContent(payload, Encoding.UTF8, "application/json")).ConfigureAwait(false); + + OnNicknameSend?.Invoke(this, new ConnectionEventArgs + { + ClientId = ClientId, + Nickname = nickname + }); + } + } + + public async Task StartWebhookListenerAsync(int port) + { + _webhookPort = port; + _webhookCts?.Cancel(); + _webhookCts?.Dispose(); + _webhookCts = new CancellationTokenSource(); + + var builder = WebApplication.CreateBuilder(new WebApplicationOptions + { + Args = Array.Empty() + }); + + builder.WebHost.ConfigureKestrel(options => + { + options.Listen(IPAddress.Loopback, port, listenOptions => + { + listenOptions.Protocols = HttpProtocols.Http1AndHttp2; + }); + }); + + _webhookApp = builder.Build(); + + _webhookApp.MapPost("/webhook", async (HttpContext ctx) => + { + try + { + using var reader = new System.IO.StreamReader(ctx.Request.Body); + var json = await reader.ReadToEndAsync().ConfigureAwait(false); + var doc = JObject.Parse(json); + + if (doc.TryGetValue("data", out var dataToken)) + { + var base64 = (string)dataToken; + if (!string.IsNullOrEmpty(base64)) + { + var data = Convert.FromBase64String(base64); + LastActive = DateTime.UtcNow; + LastDataReceived = DateTime.UtcNow; + BytesReceived += data.Length; + MessagesReceived++; + + HandlingHelpers.SafeInvokeEventHandler( + OnDataReceived, + this, + new DataReceivedEventArgs + { + ClientId = ClientId ?? "self", + Data = data, + RemoteEndPoint = new IPEndPoint(IPAddress.Parse(_config.Host), _config.Port), + Nickname = Nickname + }, + nameof(OnDataReceived)); + } + } + } + catch + { + + } + + return Results.Ok(); + }); + + _webhookTask = _webhookApp.RunAsync(); + } + + public async Task RegisterWebhookAsync(string webhookServer = "https://127.0.0.1") + { + if (!IsConnected || _httpClient == null || string.IsNullOrEmpty(ClientId)) + { + return; + } + + var webhookUrl = $"{webhookServer}:{_webhookPort}/webhook"; + var payload = JsonHelper.ToJson(new { clientId = ClientId, url = webhookUrl }); + await _httpClient.PostAsync("/api/webhooks/register", + new StringContent(payload, Encoding.UTF8, "application/json")).ConfigureAwait(false); + } + + public async Task UnregisterWebhookAsync() + { + if (!IsConnected || _httpClient == null || string.IsNullOrEmpty(ClientId)) + { + return; + } + + var payload = JsonHelper.ToJson(new { clientId = ClientId }); + await _httpClient.PostAsync("/api/webhooks/unregister", + new StringContent(payload, Encoding.UTF8, "application/json")).ConfigureAwait(false); + } + + public async Task StopWebhookListenerAsync() + { + await UnregisterWebhookAsync().ConfigureAwait(false); + + _webhookCts?.Cancel(); + + try + { + if (_webhookApp != null) + { + await _webhookApp.StopAsync().ConfigureAwait(false); + await _webhookApp.DisposeAsync().ConfigureAwait(false); + } + } + catch + { + + } + + _webhookApp = null; + } + + public async Task DisconnectAsync(DisconnectReason reason = DisconnectReason.ClientRequested, Exception? exception = null) + { + if (!IsConnected && _httpClient == null) + { + return; + } + + IsConnected = false; + DisconnectionTime = DateTime.UtcNow; + _reason = reason; + + _clientCts?.Cancel(); + + _aesInstance?.Dispose(); + _aesInstance = null; + + try + { + if (_httpClient != null && !string.IsNullOrEmpty(ClientId)) + { + var payload = JsonHelper.ToJson(new { clientId = ClientId }); + await _httpClient.PostAsync("/api/disconnect", + new StringContent(payload, Encoding.UTF8, "application/json")).ConfigureAwait(false); + } + } + catch + { + + } + + try + { + _httpClient?.Dispose(); + _httpClient = null; + } + catch + { + + } + + var determinedReason = ConnectionEventArgs.Determine(reason, exception); + var initiator = DisconnectionDiagnostics.DetermineInitiator(determinedReason, exception); + var reasonDetails = DisconnectionDiagnostics.GetDetailedReasonDescription(determinedReason, exception); + + var diagnosticContext = new Dictionary(); + 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 = ClientId ?? "self", + Reason = determinedReason, + Exception = exception, + RemoteEndPoint = remoteEndPoint, + Initiator = initiator, + ReasonDetails = reasonDetails, + DiagnosticContext = diagnosticContext + }; + + try + { + var clientLogger = ConnectionLogManager.GetClientLogger(); + var localEndPoint = IsWebhookListenerActive ? $"127.0.0.1:{_webhookPort}" : "[Client-Local]"; + clientLogger.LogDisconnection( + ClientId ?? "self", + "[REST 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 PingLoopAsync(CancellationToken token) + { + var interval = TimeSpan.FromSeconds(_config.HeartbeatIntervalSeconds); + + while (!token.IsCancellationRequested && IsConnected) + { + try + { + await Task.Delay(interval, token).ConfigureAwait(false); + + if (_httpClient == null || string.IsNullOrEmpty(ClientId)) + { + break; + } + + var response = await _httpClient.GetAsync($"/api/ping/{ClientId}", token).ConfigureAwait(false); + LastPingSent = DateTime.UtcNow; + + if (response.IsSuccessStatusCode) + { + LastPongReceived = DateTime.UtcNow; + LastActive = DateTime.UtcNow; + + if (_config.EnablePingPongLogs) + { + OnLog?.Invoke(this, new LogMessage { Type = LogType.Trace, Message = $"[REST PING] Pong received at {DateTime.UtcNow:O}" }); + } + + OnPongResponse?.Invoke(this, new PingEventArgs + { + Id = ClientId, + Nickname = Nickname, + ReceivedTime = DateTime.UtcNow, + RemoteEndPoint = new IPEndPoint(IPAddress.Parse(_config.Host), _config.Port) + }); + } + else if (response.StatusCode == HttpStatusCode.NotFound) + { + await DisconnectAsync(DisconnectReason.RemoteClosed).ConfigureAwait(false); + break; + } + } + catch (OperationCanceledException) + { + break; + } + catch (HttpRequestException) + { + await DisconnectAsync(DisconnectReason.RemoteClosed).ConfigureAwait(false); + break; + } + catch (Exception ex) + { + HandlingHelpers.SafeInvokeEventHandler( + OnGeneralError, + this, + new ErrorEventArgs + { + Exception = ex, + Message = "Error in REST ping loop" + }, + nameof(OnGeneralError)); + break; + } + } + } + + private async Task PongMonitorAsync(CancellationToken token) + { + while (!token.IsCancellationRequested && IsConnected) + { + try + { + await Task.Delay(1000, token).ConfigureAwait(false); + + var elapsed = (DateTime.UtcNow - LastPongReceived).TotalSeconds; + + if (LastPongReceived != DateTime.MinValue && + elapsed > _config.HeartbeatIntervalSeconds * 5) + { + if (_config.DisconectOnMissedPong) + { + OnLog?.Invoke(this, new LogMessage { Type = LogType.Trace, Message = $"[REST PONG] No pong for {elapsed:F0}s, disconnecting" }); + await DisconnectAsync(DisconnectReason.NoPongReceived).ConfigureAwait(false); + break; + } + } + } + catch (OperationCanceledException) + { + break; + } + } + } + + private async Task InitAesEncryptionAsync() + { + var salt = new byte[32]; + var iv = new byte[16]; + using (var rng = RandomNumberGenerator.Create()) + { + rng.GetBytes(salt); + rng.GetBytes(iv); + } + + var payload = JsonHelper.ToJson(new + { + salt = Convert.ToBase64String(salt), + iv = Convert.ToBase64String(iv) + }); + + var response = await _httpClient!.PostAsync($"/api/aes/init/{ClientId}", + new StringContent(payload, Encoding.UTF8, "application/json")).ConfigureAwait(false); + + if (!response.IsSuccessStatusCode) + { + throw new InvalidOperationException("Failed to initialize AES encryption with server"); + } + + using var pbkdf2 = new Rfc2898DeriveBytes(_config.AesPassword, salt, 800_000, HashAlgorithmName.SHA256); + var key = pbkdf2.GetBytes(32); + + _aesInstance?.Dispose(); + _aesInstance = Aes.Create(); + _aesInstance.KeySize = 256; + _aesInstance.Mode = CipherMode.CBC; + _aesInstance.Padding = PaddingMode.PKCS7; + _aesInstance.Key = key; + _aesInstance.IV = iv; + } + + 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.Trace, Message = "REST auto-reconnect: attempting reconnection..." }); + await ConnectAsync().ConfigureAwait(false); + } + } + catch (OperationCanceledException) + { + break; + } + catch (Exception ex) + { + OnLog?.Invoke(this, new LogMessage { Type = LogType.Error, Message = $"REST auto-reconnect error: {ex.Message}" }); + } + } + } + + public void StopAutoReconnect() + { + _stopAutoReconnecting = true; + _autoReconnectSource?.Cancel(); + } + + public void Dispose() + { + if (_disposed) + { + return; + } + + _disposed = true; + + _clientCts?.Cancel(); + _clientCts?.Dispose(); + _autoReconnectSource?.Cancel(); + _autoReconnectSource?.Dispose(); + _webhookCts?.Cancel(); + _webhookCts?.Dispose(); + + try + { + _httpClient?.Dispose(); + } + catch + { + + } + + try + { + _webhookApp?.DisposeAsync().AsTask().GetAwaiter().GetResult(); + } + catch + { + + } + + _aesInstance?.Dispose(); + _aesInstance = null; + _connectLock.Dispose(); + Webhooks.Dispose(); + } + + public async ValueTask DisposeAsync() + { + if (_disposed) + { + return; + } + + _disposed = true; + + _clientCts?.Cancel(); + _clientCts?.Dispose(); + _autoReconnectSource?.Cancel(); + _autoReconnectSource?.Dispose(); + _webhookCts?.Cancel(); + _webhookCts?.Dispose(); + + try + { + _httpClient?.Dispose(); + } + catch + { + + } + + try + { + if (_webhookApp != null) + { + await _webhookApp.DisposeAsync().ConfigureAwait(false); + } + } + catch + { + + } + + _aesInstance?.Dispose(); + _aesInstance = null; + + _connectLock.Dispose(); + Webhooks.Dispose(); + } + } +} diff --git a/EonaCat.Connections.REST/RestNetworkServer.cs b/EonaCat.Connections.REST/RestNetworkServer.cs new file mode 100644 index 0000000..a443908 --- /dev/null +++ b/EonaCat.Connections.REST/RestNetworkServer.cs @@ -0,0 +1,732 @@ +using EonaCat.Json; +using EonaCat.Json.Linq; +using EonaCat.Connections.EventArguments; +using EonaCat.Connections.Helpers; +using EonaCat.Connections.Models; +using EonaCat.Connections.ConnectionDiagnostics; +using Microsoft.AspNetCore.Builder; +using Microsoft.AspNetCore.Hosting; +using Microsoft.AspNetCore.Http; +using Microsoft.AspNetCore.Server.Kestrel.Core; +using Microsoft.Extensions.Hosting; +using System.Collections.Concurrent; +using System.Net; +using System.Security.Authentication; +using System.Security.Cryptography; +using System.Text; +using ErrorEventArgs = EonaCat.Connections.EventArguments.ErrorEventArgs; + +namespace EonaCat.Connections.REST +{ + public class RestNetworkServer : IDisposable + { + private readonly Configuration _config; + private readonly Stats _stats; + private readonly ConcurrentDictionary _clients = new(); + private WebApplication? _app; + private CancellationTokenSource? _serverCts; + private Task? _serverTask; + 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? OnConnected; + public event EventHandler? OnDataReceived; + public event EventHandler? OnDisconnected; + public event EventHandler? OnGeneralError; + + public WebhookManager Webhooks { get; } = new(); + + public RestNetworkServer(Configuration config) + { + _config = config ?? throw new ArgumentNullException(nameof(config)); + _stats = new Stats { StartTime = DateTime.UtcNow }; + } + + 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?.CancellationSource != null && !client.CancellationSource.IsCancellationRequested) + { + 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() + { + _serverCts?.Dispose(); + _serverCts = new CancellationTokenSource(); + + var builder = WebApplication.CreateBuilder(new WebApplicationOptions + { + Args = Array.Empty() + }); + + builder.WebHost.ConfigureKestrel(options => + { + options.Listen(IPAddress.Parse(_config.Host), _config.Port, listenOptions => + { + if (_config.Certificate != null && _config.UseSsl) + { + listenOptions.UseHttps(httpsOptions => + { + httpsOptions.ServerCertificate = _config.Certificate; + httpsOptions.SslProtocols = SslProtocols.Tls12 | SslProtocols.Tls13; + }); + } + + listenOptions.Protocols = HttpProtocols.Http1AndHttp2; + }); + }); + + _app = builder.Build(); + MapEndpoints(_app); + + _serverTask = _app.RunAsync(_serverCts.Token); + + Console.WriteLine($"EonaCat REST server started on {_config.Host}:{_config.Port}"); + } + + private void MapEndpoints(WebApplication app) + { + app.MapPost("/api/connect", async (HttpContext ctx) => + { + if (!CanAcceptConnection()) + { + _stats.IncrementDroppedConnections(); + return Results.StatusCode(StatusCodes.Status429TooManyRequests); + } + + var clientId = Guid.NewGuid().ToString("N"); + IPEndPoint? remoteEndPoint = null; + if (ctx.Connection.RemoteIpAddress != null) + { + remoteEndPoint = new IPEndPoint(ctx.Connection.RemoteIpAddress, ctx.Connection.RemotePort); + } + + var clientCts = new CancellationTokenSource(); + var connection = new RestClientConnection + { + Id = clientId, + RemoteEndPoint = remoteEndPoint, + ConnectedAt = DateTime.UtcNow, + LastActive = DateTime.UtcNow, + CancellationSource = clientCts + }; + + if (!_clients.TryAdd(clientId, connection)) + { + _stats.IncrementDroppedConnections(); + return Results.StatusCode(StatusCodes.Status409Conflict); + } + + _stats.IncrementTotalConnections(); + + HandlingHelpers.SafeInvokeEventHandler( + OnConnected, + this, + new ConnectionEventArgs + { + ClientId = clientId, + RemoteEndPoint = remoteEndPoint + }, + nameof(OnConnected)); + + _ = HandlingHelpers.SafeFireAndForgetTaskAsync( + () => Webhooks.FireAsync("connected", new { clientId, remoteEndPoint = remoteEndPoint?.ToString() }), + "WebhookConnected"); + + return Results.Ok(new { clientId }); + }); + + app.MapPost("/api/disconnect", async (HttpContext ctx) => + { + var body = await ReadJsonBodyAsync(ctx); + var clientId = (string)body?["clientId"]; + + if (string.IsNullOrEmpty(clientId)) + { + return Results.BadRequest(new { error = "clientId is required" }); + } + + await DisconnectClientAsync(clientId, DisconnectReason.ClientRequested); + return Results.Ok(new { success = true }); + }); + + app.MapPost("/api/send", async (HttpContext ctx) => + { + var body = await ReadJsonBodyAsync(ctx); + var clientId = (string)body?["clientId"]; + var dataBase64 = (string)body?["data"]; + + if (string.IsNullOrEmpty(clientId) || string.IsNullOrEmpty(dataBase64)) + { + return Results.BadRequest(new { error = "clientId and data are required" }); + } + + if (!_clients.TryGetValue(clientId, out var client)) + { + return Results.NotFound(new { error = "Client not found" }); + } + + byte[] data; + try + { + data = Convert.FromBase64String(dataBase64); + } + catch + { + data = Encoding.UTF8.GetBytes(dataBase64); + } + + if (_config.UseAesEncryption && client.AesInstance != null) + { + data = await AesKeyExchange.DecryptDataAsync(data, data.Length, client.AesInstance).ConfigureAwait(false); + } + + client.LastActive = DateTime.UtcNow; + client.LastDataReceived = DateTime.UtcNow; + client.BytesReceived += data.Length; + client.MessagesReceived++; + _stats.AddBytesReceived(data.Length); + _stats.IncrementMessagesReceived(); + + HandlingHelpers.SafeInvokeEventHandler( + OnDataReceived, + this, + new DataReceivedEventArgs + { + ClientId = clientId, + Data = data, + RemoteEndPoint = client.RemoteEndPoint, + Nickname = client.Nickname + }, + nameof(OnDataReceived)); + + _ = HandlingHelpers.SafeFireAndForgetTaskAsync( + () => Webhooks.FireAsync("data_received", new + { + clientId, + nickname = client.Nickname, + data = Convert.ToBase64String(data) + }), + "WebhookDataReceived"); + + return Results.Ok(new { success = true }); + }); + + app.MapGet("/api/poll/{clientId}", (string clientId) => + { + if (!_clients.TryGetValue(clientId, out var client)) + { + return Results.NotFound(new { error = "Client not found" }); + } + + client.LastActive = DateTime.UtcNow; + + var messages = new List(); + while (client.PendingMessages.TryDequeue(out var msg)) + { + messages.Add(Convert.ToBase64String(msg)); + } + + return Results.Ok(new { messages }); + }); + + app.MapPost("/api/broadcast", async (HttpContext ctx) => + { + var body = await ReadJsonBodyAsync(ctx); + var senderClientId = (string)body?["clientId"]; + var dataBase64 = (string)body?["data"]; + + if (string.IsNullOrEmpty(dataBase64)) + { + return Results.BadRequest(new { error = "data is required" }); + } + + byte[] data; + try + { + data = Convert.FromBase64String(dataBase64); + } + catch + { + data = Encoding.UTF8.GetBytes(dataBase64); + } + + var sent = await BroadcastAsync(data, senderClientId); + return Results.Ok(new { success = sent }); + }); + + app.MapPost("/api/nickname", async (HttpContext ctx) => + { + var body = await ReadJsonBodyAsync(ctx); + var clientId = (string)body?["clientId"]; + var nickname = (string)body?["nickname"]; + + if (string.IsNullOrEmpty(clientId) || string.IsNullOrEmpty(nickname)) + { + return Results.BadRequest(new { error = "clientId and nickname are required" }); + } + + if (!_clients.TryGetValue(clientId, out var client)) + { + return Results.NotFound(new { error = "Client not found" }); + } + + client.Nickname = nickname; + client.LastActive = DateTime.UtcNow; + return Results.Ok(new { success = true }); + }); + + app.MapPost("/api/webhooks/register", async (HttpContext ctx) => + { + var body = await ReadJsonBodyAsync(ctx); + var clientId = (string)body?["clientId"]; + var url = (string)body?["url"]; + + if (string.IsNullOrEmpty(clientId) || string.IsNullOrEmpty(url)) + { + return Results.BadRequest(new { error = "clientId and url are required" }); + } + + if (!_clients.TryGetValue(clientId, out var client)) + { + return Results.NotFound(new { error = "Client not found" }); + } + + client.WebhookUrl = url; + client.LastActive = DateTime.UtcNow; + return Results.Ok(new { success = true }); + }); + + app.MapPost("/api/webhooks/unregister", async (HttpContext ctx) => + { + var body = await ReadJsonBodyAsync(ctx); + var clientId = (string)body?["clientId"]; + + if (string.IsNullOrEmpty(clientId)) + { + return Results.BadRequest(new { error = "clientId is required" }); + } + + if (_clients.TryGetValue(clientId, out var client)) + { + client.WebhookUrl = null; + client.LastActive = DateTime.UtcNow; + } + + return Results.Ok(new { success = true }); + }); + + app.MapGet("/api/ping/{clientId}", (string clientId) => + { + if (!_clients.TryGetValue(clientId, out var client)) + { + return Results.NotFound(new { error = "Client not found" }); + } + + client.LastActive = DateTime.UtcNow; + client.LastPongReceived = DateTime.UtcNow; + return Results.Ok(new { pong = true, time = DateTime.UtcNow }); + }); + + app.MapPost("/api/aes/init/{clientId}", async (string clientId, HttpContext ctx) => + { + if (!_config.UseAesEncryption || string.IsNullOrEmpty(_config.AesPassword)) + { + return Results.BadRequest(new { error = "AES encryption not enabled on server" }); + } + + if (!_clients.TryGetValue(clientId, out var client)) + { + return Results.NotFound(new { error = "Client not found" }); + } + + var body = await ReadJsonBodyAsync(ctx); + var saltBase64 = (string)body?["salt"]; + var ivBase64 = (string)body?["iv"]; + + if (string.IsNullOrEmpty(saltBase64) || string.IsNullOrEmpty(ivBase64)) + { + return Results.BadRequest(new { error = "salt and iv are required" }); + } + + var salt = Convert.FromBase64String(saltBase64); + var iv = Convert.FromBase64String(ivBase64); + + var aes = CreateAesFromPassword(_config.AesPassword, salt, iv); + client.AesInstance?.Dispose(); + client.AesInstance = aes; + client.AesSalt = salt; + client.AesIv = iv; + client.LastActive = DateTime.UtcNow; + + return Results.Ok(new { success = true }); + }); + } + + private static async Task ReadJsonBodyAsync(HttpContext ctx) + { + try + { + using var reader = new System.IO.StreamReader(ctx.Request.Body); + var json = await reader.ReadToEndAsync().ConfigureAwait(false); + return JToken.Parse(json); + } + catch + { + return null; + } + } + + public async Task SendToClientAsync(string clientId, byte[] data) + { + if (!_clients.TryGetValue(clientId, out var client)) + { + return false; + } + + try + { + var payload = data; + if (_config.UseAesEncryption && client.AesInstance != null) + { + payload = await AesKeyExchange.EncryptDataAsync(data, data.Length, client.AesInstance).ConfigureAwait(false); + } + + if (!string.IsNullOrEmpty(client.WebhookUrl)) + { + await DeliverViaWebhookAsync(client, payload).ConfigureAwait(false); + } + else + { + client.PendingMessages.Enqueue(payload); + + int pendingMessageCount = client.PendingMessageCount; + if (pendingMessageCount > 1000) + { + + HandlingHelpers.SafeInvokeEventHandler( + OnGeneralError, + this, + new ErrorEventArgs + { + ClientId = clientId, + Nickname = client.Nickname, + Message = $"WARNING: REST client message queue saturation - {pendingMessageCount} messages pending. Client may be slow to consume messages." + }, + nameof(OnGeneralError)); + } + } + + client.LastActive = DateTime.UtcNow; + client.LastDataSent = DateTime.UtcNow; + client.BytesSent += payload.Length; + client.MessagesSent++; + _stats.AddBytesSent(payload.Length); + _stats.IncrementMessagesSent(); + return true; + } + catch (Exception exception) + { + HandlingHelpers.SafeInvokeEventHandler( + OnGeneralError, + this, + new ErrorEventArgs + { + ClientId = clientId, + Nickname = client.Nickname, + Exception = exception, + Message = "Error sending data to REST client" + }, + nameof(OnGeneralError)); + return false; + } + } + + public async Task SendToClientAsync(string clientId, string message) + => await SendToClientAsync(clientId, Encoding.UTF8.GetBytes(message)).ConfigureAwait(false); + + public async Task BroadcastAsync(byte[] data, string? excludeClientId = null) + { + if (data == null || data.Length == 0) + { + return false; + } + + bool any = false; + foreach (var client in _clients) + { + if (client.Key == excludeClientId) + { + continue; + } + + if (await SendToClientAsync(client.Key, data).ConfigureAwait(false)) + { + any = true; + } + } + + _ = Webhooks.FireAsync("broadcast", new { data = Convert.ToBase64String(data), excludeClientId }); + + return any; + } + + public async Task BroadcastAsync(string message, string? excludeClientId = null) + => await BroadcastAsync(Encoding.UTF8.GetBytes(message), excludeClientId).ConfigureAwait(false); + + public ConcurrentDictionary GetClients() => _clients; + + public async Task DisconnectClientAsync(string clientId, DisconnectReason reason = DisconnectReason.ServerShutdown) + { + if (!_clients.TryRemove(clientId, out var client)) + { + return; + } + + try + { + client.CancellationSource?.Cancel(); + client.CancellationSource?.Dispose(); + } + catch + { + + } + + TrackDisconnect(reason); + + var initiator = DisconnectionDiagnostics.DetermineInitiator(reason, null); + var reasonDetails = DisconnectionDiagnostics.GetDetailedReasonDescription(reason, null); + + var diagnosticContext = new Dictionary + { + { "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 = $"{IpAddress}:{Port}"; + 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)); + + _ = HandlingHelpers.SafeFireAndForgetTaskAsync( + () => Webhooks.FireAsync("disconnected", new { clientId, nickname = client.Nickname, reason = reason.ToString() }), + "WebhookDisconnected"); + } + + private async Task DeliverViaWebhookAsync(RestClientConnection client, byte[] data) + { + using var httpClient = new HttpClient(); + var payload = JsonHelper.ToJson(new + { + clientId = client.Id, + nickname = client.Nickname, + data = Convert.ToBase64String(data) + }); + var content = new StringContent(payload, Encoding.UTF8, "application/json"); + await httpClient.PostAsync(client.WebhookUrl!, content).ConfigureAwait(false); + } + + public void Stop() + { + _serverCts?.Cancel(); + + foreach (var client in _clients.Keys.ToList()) + { + DisconnectClientAsync(client, DisconnectReason.ServerShutdown).GetAwaiter().GetResult(); + } + + _clients.Clear(); + + try + { + _app?.StopAsync().GetAwaiter().GetResult(); + } + catch + { + + } + + try + { + _app?.DisposeAsync().AsTask().GetAwaiter().GetResult(); + } + catch + { + + } + + _app = null; + } + + public async Task StopAsync() + { + _serverCts?.Cancel(); + + foreach (var client in _clients.Keys.ToList()) + { + await DisconnectClientAsync(client, DisconnectReason.ServerShutdown).ConfigureAwait(false); + } + + _clients.Clear(); + + try + { + if (_app != null) + { + await _app.StopAsync().ConfigureAwait(false); + } + } + catch + { + + } + + try + { + if (_app != null) + { + await _app.DisposeAsync().ConfigureAwait(false); + } + } + catch + { + + } + + _app = null; + + if (_serverTask != null) + { + try + { + await _serverTask.ConfigureAwait(false); + } + catch + { + + } + } + } + + private static Aes CreateAesFromPassword(string password, byte[] salt, byte[] iv) + { + using var pbkdf2 = new Rfc2898DeriveBytes(password, salt, 800_000, HashAlgorithmName.SHA256); + var key = pbkdf2.GetBytes(32); + + var aes = Aes.Create(); + aes.KeySize = 256; + aes.Mode = CipherMode.CBC; + aes.Padding = PaddingMode.PKCS7; + aes.Key = key; + aes.IV = iv; + return aes; + } + + public void Dispose() + { + if (_disposed) + { + return; + } + + _disposed = true; + + Stop(); + + foreach (var client in _clients.Values) + { + client.Dispose(); + } + + _serverCts?.Dispose(); + Webhooks.Dispose(); + + OnConnected = null; + OnDisconnected = null; + OnDataReceived = null; + OnGeneralError = null; + } + } +} diff --git a/EonaCat.Connections.REST/WebhookManager.cs b/EonaCat.Connections.REST/WebhookManager.cs new file mode 100644 index 0000000..410982b --- /dev/null +++ b/EonaCat.Connections.REST/WebhookManager.cs @@ -0,0 +1,91 @@ +using EonaCat.Json; +using System.Collections.Concurrent; +using System.Text; + +namespace EonaCat.Connections.REST +{ + public class WebhookManager : IDisposable + { + private readonly ConcurrentDictionary> _webhooks = new(); + private readonly HttpClient _httpClient = new(); + private bool _disposed; + + public void Register(string eventName, string url) + { + var urls = _webhooks.GetOrAdd(eventName, _ => new HashSet(StringComparer.OrdinalIgnoreCase)); + lock (urls) + { + urls.Add(url); + } + } + + public void Unregister(string eventName, string url) + { + if (_webhooks.TryGetValue(eventName, out var urls)) + { + lock (urls) + { + urls.Remove(url); + } + } + } + + public void UnregisterAll(string eventName) + { + _webhooks.TryRemove(eventName, out _); + } + + public async Task FireAsync(string eventName, object payload) + { + if (!_webhooks.TryGetValue(eventName, out var urls)) + { + return; + } + + string[] snapshot; + lock (urls) + { + snapshot = urls.ToArray(); + } + + var json = JsonHelper.ToJson(payload); + + foreach (var url in snapshot) + { + try + { + using var content = new StringContent(json, Encoding.UTF8, "application/json"); + await _httpClient.PostAsync(url, content).ConfigureAwait(false); + } + catch + { + + } + } + } + + public Dictionary GetRegistrations() + { + var result = new Dictionary(); + foreach (var kvp in _webhooks) + { + lock (kvp.Value) + { + result[kvp.Key] = kvp.Value.ToArray(); + } + } + return result; + } + + public void Dispose() + { + if (_disposed) + { + return; + } + + _disposed = true; + _httpClient.Dispose(); + } + } +} diff --git a/EonaCat.Connections.Server/EonaCat.Connections.Server.csproj b/EonaCat.Connections.Server/EonaCat.Connections.Server.csproj index 3f96243..ee2f14d 100644 --- a/EonaCat.Connections.Server/EonaCat.Connections.Server.csproj +++ b/EonaCat.Connections.Server/EonaCat.Connections.Server.csproj @@ -12,7 +12,7 @@ - + diff --git a/EonaCat.Connections.Server/Program.cs b/EonaCat.Connections.Server/Program.cs index 6494c8a..c4e349b 100644 --- a/EonaCat.Connections.Server/Program.cs +++ b/EonaCat.Connections.Server/Program.cs @@ -1,23 +1,35 @@ -using EonaCat.Connections.Models; +using EonaCat.Connections.Helpers; +using EonaCat.Connections.Models; +using System.Net; +using System.Net.Sockets; using System.Reflection; namespace EonaCat.Connections.Server.Example { - // This file is part of the EonaCat project(s) which is released under the Apache License. - // See the LICENSE file or go to https://EonaCat.com/license for full license details. - public class Program { private const bool IsHeartBeatEnabled = false; private static NetworkServer _server; + private static TcpListener _tcpListener; + private static readonly object _tcpLock = new object(); - public static bool WaitForMessage { get; private set; } = true; + public static bool WaitForMessage { get; private set; } public static bool ToConsoleOnly { get; private set; } = true; public static async Task Main(string[] args) { + CreateServerAsync().ConfigureAwait(false); + await BroadCastLoopTest(); + + while (true) + { + await Task.Delay(1000).ConfigureAwait(false); + } + + ConnectedClientsTest(); + while (true) { var message = string.Empty; @@ -27,6 +39,10 @@ namespace EonaCat.Connections.Server.Example Console.Write("Enter message to send (or 'exit' to quit): "); message = Console.ReadLine(); } + else + { + message = $"Server broadcast at {DateTime.Now:HH:mm:ss}"; + } if (!string.IsNullOrEmpty(message) && message.Equals("exit", StringComparison.OrdinalIgnoreCase)) { @@ -45,48 +61,145 @@ namespace EonaCat.Connections.Server.Example } } + private static async Task BroadCastLoopTest() + { + long keepAliveCounter = 0; + while (true) + { + var message = $"KeepAlive Test {++keepAliveCounter}"; + if (_server.GetClients().Any(c => c.Value.IsConnected)) + { + Console.WriteLine($"Broadcasting: {message}"); + await _server.BroadcastAsync(message).ConfigureAwait(false); + } + + await Task.Delay(1000).ConfigureAwait(false); + } + } + + private static void ConnectedClientsTest() + { + foreach (var client in _server.GetClients()) + { + Console.WriteLine($"Connected Client: ID={client.Value.Id}, Nickname={client.Value.Nickname}, RemoteEndPoint={client.Value.RemoteEndPoint}, IsConnected={client.Value.IsConnected}"); + } + + while (true) + { + Console.WriteLine("Press 'c' to check connected clients, 'q' to quit."); + var key = Console.ReadKey(true); + if (key.KeyChar == 'c') + { + foreach (var client in _server.GetClients()) + { + Console.WriteLine($"Connected Client: ID={client.Value.Id}, Nickname={client.Value.Nickname}, RemoteEndPoint={client.Value.RemoteEndPoint}, IsConnected={client.Value.IsConnected}"); + } + + Console.WriteLine("Total clients: " + _server.GetClients().Count); + Console.WriteLine("Total connected clients: " + _server.GetClients().Count(c => c.Value.IsConnected)); + } + else if (key.KeyChar == 'q') + { + break; + } + } + } + + private static async Task DanielTestServer() + { + lock (_tcpLock) + { + try + { + _tcpListener?.Stop(); + _tcpListener?.Server?.Close(); + } + catch (Exception) + { + + } + + _tcpListener = null; + } + + lock (_tcpLock) + { + _tcpListener = new TcpListener(IPAddress.Parse("127.0.0.1"), 1111); + _tcpListener.Start(); + Console.WriteLine("Listener started"); + } + + while (true) + { + var client = await _tcpListener.AcceptTcpClientAsync(); + if (client != null) + { + Console.WriteLine("DanielTestServer: Client connected."); + } + + Console.ReadKey(); + _tcpListener.Stop(); + Console.WriteLine("DanielTestServer: Listener stopped."); + await DanielTestServer(); + break; + } + } + private static async Task CreateServerAsync() { var config = new Configuration { - Protocol = ProtocolType.TCP, + Protocol = Models.ProtocolType.TCP, Host = "0.0.0.0", Port = 1111, + EnableHealthApi = true, + HealthApiBindAddress = System.Net.IPAddress.Loopback, + + Certificate = CertificateHelper.GetCertificate(certificatePath: @"C:\ProgramData\EonaCat\localhost.pfx", certificatePassword: null), UseAesEncryption = false, - MaxConnections = 100000, - AesPassword = "EonaCat.Connections.Password", - //Certificate = new System.Security.Cryptography.X509Certificates.X509Certificate2("server.pfx", "p@ss"), - EnableHeartbeat = IsHeartBeatEnabled + + AesPassword = "itudin ante tempus consequat. Aliquam scelerisque pretium tellus, sed accumsan est ultrices id. Suspendisse sit amet ullamcorper sem.\",\"version\": 9.3},{\"name\": \"Sunil Kapoor\",\"language\": \"Hindi\",\"id\": \"VY2A0APGVHK5NAW2\",\"bio\": \"Proin tempus eu risus nec mattis. Ut dictum, ligula eget sagittis maximus, tellus mi varius ex, a accumsan justo tellus vitae leo. In id elit malesuada, pulvinar mi eu, imperdiet nulla.\",\"version\": 8.04},{\"name\": \"Zamokuhle Zulu\",\"language\": \"isiZulu\",\"id\": \"XU7BX2F8M5PVZ1EF\",\"bio\": \"Etiam congue dignissim volutpat. Phasellus tincidunt sollicitudin posuere. Phasellus tincidunt sollicitudin posuere. Nam tristique feugiat est vitae mollis.\",\"version\": 8.39},{\"name\": \"Bhupesh Menon\",\"language\": \"Hindi\",\"id\": \"0CEPNRDV98KT3ORP\",\"bio\": \"Maecenas tempus neque ut porttitor malesuada. Phasellus massa ligula, hendrerit eget efficitur eget, tincidunt in ligula. Quisque mauris ligula, efficitur porttitor sodales ac, lacinia non ex. Maecenas quis nisi nunc.\",\"version\": 2.69},{\"name\": \"Rohini Vasav\",\"language\": \"Hindi\",\"id\": \"UEFML43TCGS04KWM\",\"bio\": \"Ut accumsan, est vel fringilla varius, purus augue blandit nisl, eu rhoncus ligula purus vel dolor. Ut maximus, libero nec facilisis fringilla, ex sem sollicitudin leo, non congue tortor ligula in eros. Nam rutrum sollicitudin ante tempus consequat. Aliquam scelerisque pretium tellus, sed accumsan est ultrices id. Suspendisse sit amet ullamcorper sem.\",\"version\": 9.3},{\"name\": \"Sunil Kapoor\",\"language\": \"Hindi\",\"id\": \"VY2A0APGVHK5NAW2\",\"bio\": \"Proin tempus eu risus nec mattis. Ut dictum, ligula eget sagittis maximus, tellus mi varius ex, a accumsan justo tellus vitae leo. In id elit malesuada, pulvinar mi eu, imperdiet nulla.\",\"version\": 8.04},{\"name\": \"Zamokuhle Zulu\",\"language\": \"isiZulu\",\"id\": \"XU7BX2F8M5PVZ1EF\",\"bio\": \"Etiam congue dignissim volutpat. Phasellus tinc", + EnableHeartbeat = IsHeartBeatEnabled, + + EnableConnectionDebugLogs = true, }; _server = new NetworkServer(config); - // Subscribe to events _server.OnConnected += (sender, e) => { WriteToLog($"Client {e.ClientId} connected from {e.RemoteEndPoint}"); Console.WriteLine($"New connection from {e.RemoteEndPoint} with Client ID: {e.ClientId}"); }; - _server.OnConnectedWithNickname += (sender, e) => WriteToLog($"Client {e.ClientId} connected with nickname: {e.Nickname}"); - - _server.OnDataReceived += async (sender, e) => - { - WriteToLog($"Received from {e.ClientId} ({e.RemoteEndPoint.ToString()}): {(e.IsBinary ? $"{e.Data.Length} bytes" : "a message")}"); - - // Echo back the message - if (e.IsBinary) - { - await _server.SendToClientAsync(e.ClientId, e.Data); - } - else - { - await _server.SendToClientAsync(e.ClientId, e.StringData); - } - }; - _server.OnDisconnected += (sender, e) => { + WriteToLog($"Client {e.ClientId} disconnected from {e.RemoteEndPoint}"); + Console.WriteLine($"Connection terminated from {e.RemoteEndPoint} with Client ID: {e.ClientId}"); + + Console.WriteLine($" → Reason: {e.Reason}"); + Console.WriteLine($" → Initiated By: {e.Initiator}"); + Console.WriteLine($" → Details: {e.ReasonDetails}"); + + if (e.ConnectionDuration.HasValue) + { + Console.WriteLine($" → Duration: {e.ConnectionDuration.Value.TotalSeconds:F2}s"); + } + + if (e.HasException) + { + Console.WriteLine($" → Exception: {e.Exception.GetType().Name}: {e.Exception.Message}"); + } + + if (e.DiagnosticContext != null && e.DiagnosticContext.Count > 0) + { + Console.WriteLine($" → Diagnostic Context:"); + foreach (var kvp in e.DiagnosticContext) + { + Console.WriteLine($" {kvp.Key}: {kvp.Value}"); + } + } + var message = string.Empty; if (e.Reason == DisconnectReason.LocalClosed) { @@ -103,17 +216,33 @@ namespace EonaCat.Connections.Server.Example { if (e.Exception != null) { - message = $"{e.Nickname} disconnected from server (remote close). Reason: {e.Reason}. Exception: {e.Exception.Message}"; + message = $"{e.Nickname} disconnected from server (remote close). Reason: {e.Reason}. Initiator: {e.Initiator}. Exception: {e.Exception.Message}"; } else { - message = $"{e.Nickname} disconnected from server (remote close). Reason: {e.Reason}"; + message = $"{e.Nickname} disconnected from server (remote close). Reason: {e.Reason}. Initiator: {e.Initiator}"; } } WriteToLog(message); Console.WriteLine(message); }; + _server.OnConnectedWithNickname += (sender, e) => WriteToLog($"Client {e.ClientId} connected with nickname: {e.Nickname}"); + + _server.OnDataReceived += async (sender, e) => + { + WriteToLog($"Received from {e.ClientId} ({e.Nickname ?? "NoNickname"}) ({e.RemoteEndPoint.ToString()}): {(e.IsBinary ? $"{e.Data.Length} bytes" : "a message")}"); + + if (e.IsBinary) + { + await _server.SendToClientAsync(e.ClientId, e.Data); + } + else + { + await _server.SendToClientAsync(e.ClientId, e.StringData); + } + }; + _ = _server.StartAsync(); } @@ -137,7 +266,7 @@ namespace EonaCat.Connections.Server.Example return; } - if (new FileInfo(logFilePath).Length > 5 * 1024 * 1024) // 5 MB + if (new FileInfo(logFilePath).Length > 5 * 1024 * 1024) { var archiveFilePath = Path.Combine(Path.GetDirectoryName(logFilePath) ?? ".", $"server_log{DateTime.Now:yyyyMMdd_HHmmss}.txt"); File.Move(logFilePath, archiveFilePath); @@ -147,10 +276,10 @@ namespace EonaCat.Connections.Server.Example File.AppendAllText(logFilePath, logMessage); } - catch + catch (Exception) { - // Ignore logging errors + } } } -} \ No newline at end of file +} diff --git a/EonaCat.Connections.gRPC.Client/EonaCat.Connections.gRPC.Client.csproj b/EonaCat.Connections.gRPC.Client/EonaCat.Connections.gRPC.Client.csproj new file mode 100644 index 0000000..7413b67 --- /dev/null +++ b/EonaCat.Connections.gRPC.Client/EonaCat.Connections.gRPC.Client.csproj @@ -0,0 +1,14 @@ + + + + Exe + net8.0 + enable + enable + + + + + + + diff --git a/EonaCat.Connections.gRPC.Client/Program.cs b/EonaCat.Connections.gRPC.Client/Program.cs new file mode 100644 index 0000000..dd8445d --- /dev/null +++ b/EonaCat.Connections.gRPC.Client/Program.cs @@ -0,0 +1,73 @@ +using EonaCat.Connections.Models; + +namespace EonaCat.Connections.gRPC.Client.Example +{ + public class Program + { + private const string SERVER_IP = "127.0.0.1"; + private const int SERVER_PORT = 5443; + + public static async Task Main(string[] args) + { + var config = new Configuration + { + Host = SERVER_IP, + Port = SERVER_PORT, + IsSelfSignedEnabled = true, + EnableAutoReconnect = true, + ReconnectDelayInSeconds = 5, + }; + + await using var client = new GrpcNetworkClient(config); + + client.OnConnected += (sender, e) => + { + Console.WriteLine($"[gRPC Client] Connected to {e.RemoteEndPoint}"); + }; + + client.OnDataReceived += (sender, e) => + { + Console.WriteLine($"[gRPC Client] Received: {e.StringData}"); + }; + + client.OnDisconnected += (sender, e) => + { + Console.WriteLine($"[gRPC Client] Disconnected: {e.Reason}"); + }; + + client.OnGeneralError += (sender, e) => + { + Console.WriteLine($"[gRPC Client] Error: {e.Message} - {e.Exception?.Message}"); + }; + + Console.WriteLine("[gRPC Client] Connecting..."); + var connected = await client.ConnectAsync(); + + if (!connected) + { + Console.WriteLine("[gRPC Client] Failed to connect. Press any key to exit."); + Console.ReadKey(); + return; + } + + await client.SendNicknameAsync("GrpcTestClient"); + + while (true) + { + Console.Write("Enter message (or 'exit'): "); + var message = Console.ReadLine(); + + if (string.IsNullOrEmpty(message) || message.Equals("exit", StringComparison.OrdinalIgnoreCase)) + { + break; + } + + await client.SendAsync(message); + } + + await client.DisconnectAsync(); + Console.WriteLine("[gRPC Client] Disconnected. Press any key to exit."); + Console.ReadKey(); + } + } +} diff --git a/EonaCat.Connections.gRPC.Server/EonaCat.Connections.gRPC.Server.csproj b/EonaCat.Connections.gRPC.Server/EonaCat.Connections.gRPC.Server.csproj new file mode 100644 index 0000000..7413b67 --- /dev/null +++ b/EonaCat.Connections.gRPC.Server/EonaCat.Connections.gRPC.Server.csproj @@ -0,0 +1,14 @@ + + + + Exe + net8.0 + enable + enable + + + + + + + diff --git a/EonaCat.Connections.gRPC.Server/Program.cs b/EonaCat.Connections.gRPC.Server/Program.cs new file mode 100644 index 0000000..e94f806 --- /dev/null +++ b/EonaCat.Connections.gRPC.Server/Program.cs @@ -0,0 +1,115 @@ +using EonaCat.Connections.Models; +using System.Security.Cryptography; +using System.Security.Cryptography.X509Certificates; + +namespace EonaCat.Connections.gRPC.Server.Example +{ + public class Program + { + private const string LISTEN_IP = "127.0.0.1"; + private const int LISTEN_PORT = 5443; + + public static async Task Main(string[] args) + { + + using var certificate = GenerateSelfSignedCertificate(); + + var config = new Configuration + { + Host = LISTEN_IP, + Port = LISTEN_PORT, + Certificate = certificate, + IsSelfSignedEnabled = true, + }; + + using var server = new GrpcNetworkServer(config); + + server.OnConnected += (sender, e) => + { + Console.WriteLine($"[gRPC Server] Client connected: {e.ClientId} from {e.RemoteEndPoint}"); + }; + + server.OnDataReceived += async (sender, e) => + { + Console.WriteLine($"[gRPC Server] Received from {e.Nickname ?? e.ClientId}: {e.StringData}"); + + if (sender is GrpcNetworkServer srv) + { + await srv.SendToClientAsync(e.ClientId, $"Echo: {e.StringData}"); + } + }; + + server.OnDisconnected += (sender, e) => + { + Console.WriteLine($"[gRPC Server] Client disconnected: {e.Nickname ?? e.ClientId} ({e.Reason})"); + }; + + server.OnGeneralError += (sender, e) => + { + Console.WriteLine($"[gRPC Server] Error: {e.Message} - {e.Exception?.Message}"); + }; + + Console.WriteLine($"[gRPC Server] Starting on {LISTEN_IP}:{LISTEN_PORT}..."); + await server.StartAsync(); + Console.WriteLine("[gRPC Server] Started. Press 'q' to stop."); + + while (true) + { + var key = Console.ReadKey(true); + if (key.KeyChar == 'q') + { + break; + } + + if (key.KeyChar == 'b') + { + Console.Write("Broadcast message: "); + var msg = Console.ReadLine(); + if (!string.IsNullOrEmpty(msg)) + { + await server.BroadcastAsync(msg); + } + } + + if (key.KeyChar == 'c') + { + var clients = server.GetClients(); + Console.WriteLine($"[gRPC Server] Active connections: {server.ActiveConnections}"); + foreach (var client in clients) + { + Console.WriteLine($" - {client.Value.Nickname} ({client.Key}) from {client.Value.RemoteEndPoint}"); + } + } + } + + Console.WriteLine("[gRPC Server] Stopping..."); + await server.StopAsync(); + Console.WriteLine("[gRPC Server] Stopped."); + } + + private static X509Certificate2 GenerateSelfSignedCertificate() + { + + using var ecdsa = ECDsa.Create(ECCurve.NamedCurves.nistP256); + var request = new CertificateRequest("CN=localhost", ecdsa, HashAlgorithmName.SHA256); + + request.CertificateExtensions.Add( + new X509KeyUsageExtension( + X509KeyUsageFlags.DigitalSignature, + critical: false)); + + request.CertificateExtensions.Add( + new X509EnhancedKeyUsageExtension( + new OidCollection { new Oid("1.3.6.1.5.5.7.3.1") }, + critical: false)); + + var sanBuilder = new SubjectAlternativeNameBuilder(); + sanBuilder.AddDnsName("localhost"); + sanBuilder.AddIpAddress(System.Net.IPAddress.Loopback); + request.CertificateExtensions.Add(sanBuilder.Build()); + + using var certificate = request.CreateSelfSigned(DateTimeOffset.UtcNow.AddMinutes(-5), DateTimeOffset.UtcNow.AddYears(200)); + return new X509Certificate2(certificate.Export(X509ContentType.Pfx), (string?)null, X509KeyStorageFlags.Exportable); + } + } +} diff --git a/EonaCat.Connections.gRPC/ConnectorServiceImplementation.cs b/EonaCat.Connections.gRPC/ConnectorServiceImplementation.cs new file mode 100644 index 0000000..53303b3 --- /dev/null +++ b/EonaCat.Connections.gRPC/ConnectorServiceImplementation.cs @@ -0,0 +1,163 @@ +using Grpc.Core; +using EonaCat.Connections; +using EonaCat.Connections.EventArguments; +using EonaCat.Connections.gRPC.Proto; +using System.Net; +using ErrorEventArgs = EonaCat.Connections.EventArguments.ErrorEventArgs; + +namespace EonaCat.Connections.gRPC +{ + internal class ConnectorServiceImplementation : ConnectorService.ConnectorServiceBase + { + private readonly GrpcNetworkServer _server; + + public ConnectorServiceImplementation(GrpcNetworkServer server) + { + _server = server; + } + + public override async Task Connect( + IAsyncStreamReader requestStream, + IServerStreamWriter responseStream, + ServerCallContext context) + { + if (!_server.CanAcceptConnection()) + { + _server.IncrementDroppedConnection(); + throw new RpcException(new Status(StatusCode.ResourceExhausted, "Max connections reached")); + } + + var clientId = Guid.NewGuid().ToString("N"); + IPEndPoint? remoteEndPoint = null; + + var httpContext = context.GetHttpContext(); + if (httpContext?.Connection.RemoteIpAddress != null) + { + remoteEndPoint = new IPEndPoint( + httpContext.Connection.RemoteIpAddress, + httpContext.Connection.RemotePort); + } + + var clientCts = CancellationTokenSource.CreateLinkedTokenSource(context.CancellationToken); + + var clientConnection = new GrpcClientConnection + { + Id = clientId, + ResponseStream = responseStream, + RemoteEndPoint = remoteEndPoint, + ConnectedAt = DateTime.UtcNow, + CancellationSource = clientCts + }; + + if (!_server.AddClient(clientId, clientConnection)) + { + clientCts.Dispose(); + throw new RpcException(new Status(StatusCode.Aborted, "Failed to register client connection")); + } + + _server.RaiseOnConnected(new ConnectionEventArgs + { + ClientId = clientId, + RemoteEndPoint = remoteEndPoint + }); + + try + { + while (await requestStream.MoveNext(clientCts.Token).ConfigureAwait(false)) + { + if (clientCts.Token.IsCancellationRequested) + { + break; + } + + var message = requestStream.Current; + clientConnection.LastActive = DateTime.UtcNow; + + switch (message.Type) + { + case MessageType.Nickname: + clientConnection.Nickname = message.Text; + continue; + + case MessageType.Pong: + _server.HandlePongReceived(clientId); + continue; + + case MessageType.Ping: + + await clientConnection.WriteLock.WaitAsync(clientCts.Token).ConfigureAwait(false); + try + { + var pongMsg = new ConnectorMessage { Type = MessageType.Pong }; + await responseStream.WriteAsync(pongMsg).ConfigureAwait(false); + } + finally + { + clientConnection.WriteLock.Release(); + } + continue; + + case MessageType.Disconnect: + break; + + case MessageType.Data: + default: + break; + } + + if (message.Type == MessageType.Disconnect) + { + break; + } + + clientConnection.LastDataReceived = DateTime.UtcNow; + var data = message.Data.ToByteArray(); + clientConnection.BytesReceived += data.Length; + clientConnection.MessagesReceived++; + _server.TrackBytesReceived(data.Length); + + _server.RaiseOnDataReceived(new DataReceivedEventArgs + { + ClientId = clientId, + Data = data, + RemoteEndPoint = remoteEndPoint, + Nickname = clientConnection.Nickname + }); + } + } + catch (OperationCanceledException) + { + + } + catch (RpcException ex) when (ex.StatusCode == StatusCode.Cancelled) + { + + } + catch (Exception exception) + { + _server.RaiseOnGeneralError(new ErrorEventArgs + { + ClientId = clientId, + Nickname = clientConnection.Nickname, + Exception = exception, + Message = "Error handling gRPC client" + }); + } + finally + { + if (_server.RemoveClient(clientId, out _)) + { + _server.RaiseOnDisconnected(new ConnectionEventArgs + { + ClientId = clientId, + Nickname = clientConnection.Nickname, + RemoteEndPoint = remoteEndPoint, + Reason = DisconnectReason.RemoteClosed + }); + } + + clientCts.Dispose(); + } + } + } +} diff --git a/EonaCat.Connections.gRPC/EonaCat.Connections.gRPC.csproj b/EonaCat.Connections.gRPC/EonaCat.Connections.gRPC.csproj new file mode 100644 index 0000000..2b5b85c --- /dev/null +++ b/EonaCat.Connections.gRPC/EonaCat.Connections.gRPC.csproj @@ -0,0 +1,35 @@ + + + + net8.0 + latest + enable + enable + True + EonaCat.Connections.gRPC + EonaCat + Jeroen Saey + EonaCat.Connections.gRPC + 1.0.0 + Jeroen Saey + EonaCat.Connections.gRPC for gRPC client/servers with optional TLS 1.2 + + + + + + + + + + + + + + + + + + + + diff --git a/EonaCat.Connections.gRPC/GrpcChannelFactory.cs b/EonaCat.Connections.gRPC/GrpcChannelFactory.cs new file mode 100644 index 0000000..486c78d --- /dev/null +++ b/EonaCat.Connections.gRPC/GrpcChannelFactory.cs @@ -0,0 +1,77 @@ +using Grpc.Net.Client; +using EonaCat.Connections.Models; +using System.Net.Security; +using System.Security.Authentication; + +namespace EonaCat.Connections.gRPC +{ + + public static class GrpcChannelFactory + { + + public static GrpcChannel Create(Configuration config) + { + if (config == null) + { + throw new ArgumentNullException(nameof(config)); + } + + var scheme = config.UseSsl ? "https" : "http"; + var address = $"{scheme}://{config.Host}:{config.Port}"; + return Create(address, config); + } + + public static GrpcChannel Create(string address, Configuration config) + { + if (string.IsNullOrWhiteSpace(address)) + { + throw new ArgumentNullException(nameof(address)); + } + + if (config == null) + { + throw new ArgumentNullException(nameof(config)); + } + + return GrpcChannel.ForAddress(address, BuildChannelOptions(config)); + } + + public static GrpcChannelOptions BuildChannelOptions(Configuration config) + { + if (config == null) + { + throw new ArgumentNullException(nameof(config)); + } + + var options = new GrpcChannelOptions(); + + if (config.UseSsl) + { + options.HttpHandler = new SocketsHttpHandler + { + SslOptions = new SslClientAuthenticationOptions + { + EnabledSslProtocols = SslProtocols.Tls12 | SslProtocols.Tls13, + RemoteCertificateValidationCallback = (sender, certificate, chain, errors) => + { + if (config.IsSelfSignedEnabled) + { + return true; + } + return errors == SslPolicyErrors.None; + } + } + }; + } + else + { + options.HttpHandler = new SocketsHttpHandler + { + EnableMultipleHttp2Connections = true + }; + } + + return options; + } + } +} diff --git a/EonaCat.Connections.gRPC/GrpcClientConnection.cs b/EonaCat.Connections.gRPC/GrpcClientConnection.cs new file mode 100644 index 0000000..108e510 --- /dev/null +++ b/EonaCat.Connections.gRPC/GrpcClientConnection.cs @@ -0,0 +1,40 @@ +using Grpc.Core; +using EonaCat.Connections.gRPC.Proto; +using System.Net; + +namespace EonaCat.Connections.gRPC +{ + public class GrpcClientConnection + { + public string Id { get; set; } = string.Empty; + public IServerStreamWriter? ResponseStream { get; set; } + public IPEndPoint? RemoteEndPoint { get; set; } + public SemaphoreSlim WriteLock { get; } = new(1, 1); + public CancellationTokenSource? CancellationSource { get; set; } + public DateTime ConnectedAt { get; set; } + public DateTime LastActive { get; set; } + public DateTime LastDataSent { get; set; } + public DateTime LastDataReceived { get; set; } + public DateTime LastPingSent { get; set; } + public DateTime LastPongReceived { get; set; } + + public long BytesSent { get; set; } + public long BytesReceived { get; set; } + public long MessagesSent { get; set; } + public long MessagesReceived { get; set; } + + public bool IsConnected => CancellationSource != null && !CancellationSource.IsCancellationRequested; + + public TimeSpan ConnectedTime() => DateTime.UtcNow - ConnectedAt; + public TimeSpan IdleTime() => DateTime.UtcNow - (LastActive == default ? ConnectedAt : LastActive); + + 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; + } +} diff --git a/EonaCat.Connections.gRPC/GrpcNetworkClient.cs b/EonaCat.Connections.gRPC/GrpcNetworkClient.cs new file mode 100644 index 0000000..523f14f --- /dev/null +++ b/EonaCat.Connections.gRPC/GrpcNetworkClient.cs @@ -0,0 +1,599 @@ +using Google.Protobuf; +using Grpc.Core; +using Grpc.Net.Client; +using EonaCat.Connections; +using EonaCat.Connections.EventArguments; +using EonaCat.Connections.Helpers; +using EonaCat.Connections.Models; +using EonaCat.Connections.gRPC.Proto; +using System.Net; +using System.Text; +using ErrorEventArgs = EonaCat.Connections.EventArguments.ErrorEventArgs; + +namespace EonaCat.Connections.gRPC +{ + public class GrpcNetworkClient : IAsyncDisposable, IDisposable + { + public static event EventHandler OnLog; + private readonly Configuration _config; + private GrpcChannel? _channel; + private AsyncDuplexStreamingCall? _call; + private Task? _receiveTask; + private Task? _autoReconnectTask; + private Task? _pingTask; + 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 GrpcChannel? Channel => _channel; + + 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 DateTime LastPingSent { get; private set; } + public DateTime LastPongReceived { 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 HealthApiServer HealthApi { get; } + + public event EventHandler? OnConnected; + public event EventHandler? OnNicknameSend; + public event EventHandler? OnDataReceived; + public event EventHandler? OnDisconnected; + public event EventHandler? OnGeneralError; + public event EventHandler? OnPingReceived; + public event EventHandler? OnPongReceived; + + public GrpcNetworkClient(Configuration config) + { + _config = config ?? throw new ArgumentNullException(nameof(config)); + _clientCts = new CancellationTokenSource(); + HealthApi = new HealthApiServer(BuildHealthJson, BuildStatusJson); + } + + public async Task ConnectAsync() + { + 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 scheme = _config.UseSsl ? "https" : "http"; + var address = $"{scheme}://{_config.Host}:{_config.Port}"; + + _channel = GrpcChannelFactory.Create(address, _config); + + var client = new ConnectorService.ConnectorServiceClient(_channel); + _call = client.Connect(cancellationToken: _connectionCts.Token); + + 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); + } + + if (_config.EnableHeartbeat) + { + _pingTask = Task.Run(() => PingLoopAsync(_connectionCts.Token), _connectionCts.Token); + } + + if (_config.EnableHealthApi) + { + HealthApi.Start(_config.HealthApiPort, _config.HealthApiBindAddress); + } + + _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 = "gRPC connection error" + }, + nameof(OnGeneralError)); + return false; + } + finally + { + try + { + _connectLock.Release(); + } + catch + { + + } + } + } + + private async Task ReceiveLoopAsync(CancellationToken token) + { + try + { + if (_call == null) + { + return; + } + + while (await _call.ResponseStream.MoveNext(token).ConfigureAwait(false)) + { + if (token.IsCancellationRequested) + { + break; + } + + var message = _call.ResponseStream.Current; + LastActive = DateTime.UtcNow; + + switch (message.Type) + { + case MessageType.Ping: + + OnPingReceived?.Invoke(this, new PingEventArgs + { + Id = Nickname ?? "self", + ReceivedTime = DateTime.UtcNow + }); + await SendPongAsync().ConfigureAwait(false); + continue; + + case MessageType.Pong: + LastPongReceived = DateTime.UtcNow; + OnPongReceived?.Invoke(this, new PingEventArgs + { + Id = Nickname ?? "self", + ReceivedTime = DateTime.UtcNow + }); + continue; + + case MessageType.Disconnect: + await DisconnectAsync(DisconnectReason.RemoteClosed).ConfigureAwait(false); + return; + + case MessageType.Data: + default: + break; + } + + LastDataReceived = DateTime.UtcNow; + var data = message.Data.ToByteArray(); + BytesReceived += data.Length; + MessagesReceived++; + + HandlingHelpers.SafeInvokeEventHandler( + OnDataReceived, + this, + new DataReceivedEventArgs + { + ClientId = Nickname ?? "self", + Data = data, + RemoteEndPoint = new IPEndPoint(IPAddress.Parse(_config.Host), _config.Port), + Nickname = Nickname + }, + nameof(OnDataReceived)); + } + + await DisconnectAsync(DisconnectReason.RemoteClosed).ConfigureAwait(false); + } + catch (OperationCanceledException) + { + + } + catch (RpcException ex) when (ex.StatusCode == StatusCode.Cancelled) + { + + } + catch (Exception exception) + { + HandlingHelpers.SafeInvokeEventHandler( + OnGeneralError, + this, + new ErrorEventArgs + { + Exception = exception, + Message = "Error receiving gRPC data" + }, + nameof(OnGeneralError)); + await DisconnectAsync(DisconnectReason.Error, exception).ConfigureAwait(false); + } + } + + private async Task PingLoopAsync(CancellationToken token) + { + while (!token.IsCancellationRequested) + { + try + { + await Task.Delay(TimeSpan.FromSeconds(_config.HeartbeatIntervalSeconds), token).ConfigureAwait(false); + + if (IsConnected && _call != null) + { + await _streamWriteLock.WaitAsync(token).ConfigureAwait(false); + try + { + var pingMsg = new ConnectorMessage { Type = MessageType.Ping }; + await _call.RequestStream.WriteAsync(pingMsg).ConfigureAwait(false); + } + finally + { + _streamWriteLock.Release(); + } + + LastPingSent = DateTime.UtcNow; + } + } + catch (OperationCanceledException) + { + break; + } + catch (Exception ex) + { + OnLog?.Invoke(this, new LogMessage { Type = LogType.Error, Message = $"gRPC ping loop error: {ex.Message}" }); + } + } + } + + private async Task SendPongAsync() + { + if (!IsConnected || _call == null) + { + return; + } + + await _streamWriteLock.WaitAsync().ConfigureAwait(false); + try + { + var pongMsg = new ConnectorMessage { Type = MessageType.Pong }; + await _call.RequestStream.WriteAsync(pongMsg).ConfigureAwait(false); + } + finally + { + _streamWriteLock.Release(); + } + } + + public async Task SendAsync(byte[] data) + { + if (!IsConnected || _call == null || data == null || data.Length == 0) + { + return false; + } + + try + { + await _streamWriteLock.WaitAsync().ConfigureAwait(false); + try + { + var message = new ConnectorMessage + { + Type = MessageType.Data, + Data = ByteString.CopyFrom(data) + }; + await _call.RequestStream.WriteAsync(message).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 SendAsync(string message) => await SendAsync(Encoding.UTF8.GetBytes(message)).ConfigureAwait(false); + + public async Task SendNicknameAsync(string nickname) + { + Nickname = nickname; + if (IsConnected && _call != null) + { + await _streamWriteLock.WaitAsync().ConfigureAwait(false); + try + { + var message = new ConnectorMessage + { + Type = MessageType.Nickname, + Text = nickname + }; + await _call.RequestStream.WriteAsync(message).ConfigureAwait(false); + } + finally + { + _streamWriteLock.Release(); + } + + OnNicknameSend?.Invoke(this, new ConnectionEventArgs + { + ClientId = nickname, + Nickname = nickname + }); + } + } + + public async Task DisconnectAsync(DisconnectReason reason = DisconnectReason.ClientRequested, Exception? exception = null) + { + if (!IsConnected && _channel == null) + { + return; + } + + IsConnected = false; + DisconnectionTime = DateTime.UtcNow; + _reason = reason; + + _connectionCts?.Cancel(); + + try + { + if (_call != null) + { + await _call.RequestStream.CompleteAsync().ConfigureAwait(false); + _call.Dispose(); + _call = null; + } + } + catch + { + + } + + try + { + if (_channel != null) + { + _channel.Dispose(); + _channel = null; + } + } + catch + { + + } + + HealthApi.Stop(); + + HandlingHelpers.SafeInvokeEventHandler( + OnDisconnected, + this, + new ConnectionEventArgs + { + ClientId = Nickname ?? "self", + Reason = reason, + Exception = exception, + RemoteEndPoint = new IPEndPoint(IPAddress.Parse(_config.Host), _config.Port) + }, + 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 = "gRPC auto-reconnect: attempting reconnection..." }); + await ConnectAsync().ConfigureAwait(false); + } + } + catch (OperationCanceledException) + { + break; + } + catch (Exception ex) + { + OnLog?.Invoke(this, new LogMessage { Type = LogType.Error, Message = $"gRPC auto-reconnect error: {ex.Message}" }); + } + } + } + + public void StopAutoReconnect() + { + _stopAutoReconnecting = true; + _autoReconnectSource?.Cancel(); + } + + public TClient CreateClient(Func factory) + { + if (factory == null) + { + throw new ArgumentNullException(nameof(factory)); + } + + if (_channel == null) + { + throw new InvalidOperationException("Not connected. Call ConnectAsync first."); + } + + return factory(_channel); + } + + private string BuildHealthJson() + { + var E = HealthApiServer.JsonEscape; + return "{" + + "\"status\":\"ok\"," + + "\"type\":\"grpc-client\"," + + $"\"serverAddress\":{E(_config.Host + ":" + _config.Port)}," + + $"\"isConnected\":{(IsConnected ? "true" : "false")}," + + $"\"uptimeSeconds\":{Uptime.TotalSeconds:F1}," + + $"\"connectionTimeUtc\":{E(ConnectionTime.ToString("O"))}" + + "}"; + } + + private string BuildStatusJson() + { + var E = HealthApiServer.JsonEscape; + return "{" + + "\"status\":\"ok\"," + + "\"type\":\"grpc-client\"," + + $"\"serverAddress\":{E(_config.Host + ":" + _config.Port)}," + + $"\"isConnected\":{(IsConnected ? "true" : "false")}," + + $"\"nickname\":{E(Nickname ?? "self")}," + + $"\"bytesSent\":{BytesSent}," + + $"\"bytesReceived\":{BytesReceived}," + + $"\"messagesSent\":{MessagesSent}," + + $"\"messagesReceived\":{MessagesReceived}," + + $"\"uptimeSeconds\":{Uptime.TotalSeconds:F1}," + + $"\"connectionTimeUtc\":{E(ConnectionTime.ToString("O"))}," + + $"\"lastDataSentUtc\":{(LastDataSent == default ? "null" : E(LastDataSent.ToString("O")))}," + + $"\"lastDataReceivedUtc\":{(LastDataReceived == default ? "null" : E(LastDataReceived.ToString("O")))}" + + "}"; + } + + public void Dispose() + { + if (_disposed) + { + return; + } + + _disposed = true; + + _clientCts?.Cancel(); + _clientCts?.Dispose(); + _connectionCts?.Cancel(); + _connectionCts?.Dispose(); + _autoReconnectSource?.Cancel(); + _autoReconnectSource?.Dispose(); + + HealthApi.Stop(); + + try + { + _call?.Dispose(); + } + catch + { + + } + + try + { + _channel?.Dispose(); + } + catch + { + + } + + _connectLock.Dispose(); + _streamWriteLock.Dispose(); + } + + public async ValueTask DisposeAsync() + { + if (_disposed) + { + return; + } + + _disposed = true; + + _clientCts?.Cancel(); + _clientCts?.Dispose(); + _connectionCts?.Cancel(); + _connectionCts?.Dispose(); + _autoReconnectSource?.Cancel(); + _autoReconnectSource?.Dispose(); + + HealthApi.Stop(); + + try + { + _call?.Dispose(); + } + catch + { + + } + + try + { + _channel?.Dispose(); + } + catch + { + + } + + _connectLock.Dispose(); + _streamWriteLock.Dispose(); + } + } +} diff --git a/EonaCat.Connections.gRPC/GrpcNetworkServer.cs b/EonaCat.Connections.gRPC/GrpcNetworkServer.cs new file mode 100644 index 0000000..91ce3b1 --- /dev/null +++ b/EonaCat.Connections.gRPC/GrpcNetworkServer.cs @@ -0,0 +1,698 @@ +using EonaCat.Connections; +using EonaCat.Connections.EventArguments; +using EonaCat.Connections.Helpers; +using EonaCat.Connections.Models; +using EonaCat.Connections.gRPC.Proto; +using Microsoft.AspNetCore.Builder; +using Microsoft.AspNetCore.Hosting; +using Microsoft.AspNetCore.Server.Kestrel.Core; +using Microsoft.Extensions.DependencyInjection; +using Microsoft.Extensions.Hosting; +using System.Collections.Concurrent; +using System.Net; +using System.Security.Authentication; +using System.Text; +using ErrorEventArgs = EonaCat.Connections.EventArguments.ErrorEventArgs; + +namespace EonaCat.Connections.gRPC +{ + public class GrpcNetworkServer : IDisposable, IAsyncDisposable + { + public static event EventHandler OnLog; + private readonly Configuration _config; + private readonly Stats _stats; + private readonly ConcurrentDictionary _clients = new(); + private readonly ConcurrentDictionary _lastPingTimes = new(); + private WebApplication? _app; + private CancellationTokenSource? _serverCts; + private Task? _serverTask; + private Task? _pingTask; + private Task? _pongTask; + private Task? _idleTask; + 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 HealthApiServer HealthApi { get; } + + public event EventHandler? OnConnected; + public event EventHandler? OnDataReceived; + public event EventHandler? OnDisconnected; + public event EventHandler? OnGeneralError; + public event EventHandler? OnClientPingResponse; + public event EventHandler? OnPongMissed; + public GrpcNetworkServer(Configuration config) + { + _config = config ?? throw new ArgumentNullException(nameof(config)); + _stats = new Stats { StartTime = DateTime.UtcNow }; + HealthApi = new HealthApiServer(BuildHealthJson, BuildStatusJson); + } + + 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?.IsConnected == true) + { + activeCount++; + } + } + + return activeCount; + } + + internal 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() + { + _serverCts?.Dispose(); + _serverCts = new CancellationTokenSource(); + + var builder = WebApplication.CreateBuilder(new WebApplicationOptions + { + Args = Array.Empty() + }); + + builder.Services.AddSingleton(this); + builder.Services.AddGrpc(options => + { + options.MaxReceiveMessageSize = _config.MAX_MESSAGE_SIZE; + options.MaxSendMessageSize = _config.MAX_MESSAGE_SIZE; + }); + + builder.WebHost.ConfigureKestrel(options => + { + options.Listen(IPAddress.Parse(_config.Host), _config.Port, listenOptions => + { + if (_config.Certificate != null && _config.UseSsl) + { + listenOptions.UseHttps(httpsOptions => + { + httpsOptions.ServerCertificate = _config.Certificate; + httpsOptions.SslProtocols = SslProtocols.Tls12 | SslProtocols.Tls13; + }); + } + + listenOptions.Protocols = HttpProtocols.Http2; + }); + }); + + _app = builder.Build(); + _app.MapGrpcService(); + + _serverTask = _app.RunAsync(_serverCts.Token); + + if (_config.EnableHeartbeat) + { + _pingTask = Task.Run(() => PingLoopAsync(_serverCts.Token), _serverCts.Token); + _pongTask = Task.Run(() => PongMonitorLoopAsync(_serverCts.Token), _serverCts.Token); + } + + if (_config.EnableHealthApi) + { + HealthApi.Start(_config.HealthApiPort, _config.HealthApiBindAddress); + } + + OnLog?.Invoke(this, new LogMessage { Type = LogType.Trace, Message = $"EonaCat gRPC server started on {_config.Host}:{_config.Port}" }); + } + + internal bool CanAcceptConnection() + { + return _config.MaxConnections <= 0 || GetActiveConnectionCount() < _config.MaxConnections; + } + + internal void IncrementDroppedConnection() => _stats.IncrementDroppedConnections(); + + internal bool AddClient(string clientId, GrpcClientConnection connection) + { + if (_clients.TryAdd(clientId, connection)) + { + _stats.IncrementTotalConnections(); + return true; + } + + _stats.IncrementDroppedConnections(); + return false; + } + + internal bool RemoveClient(string clientId, out GrpcClientConnection? client) + { + var removed = _clients.TryRemove(clientId, out client); + _lastPingTimes.TryRemove(clientId, out _); + return removed; + } + + internal void RaiseOnConnected(ConnectionEventArgs args) => + HandlingHelpers.SafeInvokeEventHandler(OnConnected, this, args, nameof(OnConnected)); + + internal void RaiseOnDataReceived(DataReceivedEventArgs args) + { + _stats.IncrementMessagesReceived(); + HandlingHelpers.SafeInvokeEventHandler(OnDataReceived, this, args, nameof(OnDataReceived)); + } + + internal void RaiseOnDisconnected(ConnectionEventArgs args) => + HandlingHelpers.SafeInvokeEventHandler(OnDisconnected, this, args, nameof(OnDisconnected)); + + internal void RaiseOnGeneralError(ErrorEventArgs args) => + HandlingHelpers.SafeInvokeEventHandler(OnGeneralError, this, args, nameof(OnGeneralError)); + + internal void TrackBytesReceived(long bytes) => _stats.AddBytesReceived(bytes); + internal void TrackBytesSent(long bytes) => _stats.AddBytesSent(bytes); + + public async Task SendToClientAsync(string clientId, byte[] data) + { + if (data == null || data.Length == 0) + { + return false; + } + + if (!_clients.TryGetValue(clientId, out var client) || client.ResponseStream == null) + { + return false; + } + + try + { + await client.WriteLock.WaitAsync().ConfigureAwait(false); + try + { + var message = new ConnectorMessage + { + Type = MessageType.Data, + Data = Google.Protobuf.ByteString.CopyFrom(data) + }; + await client.ResponseStream.WriteAsync(message).ConfigureAwait(false); + } + finally + { + client.WriteLock.Release(); + } + + var sentAt = DateTime.UtcNow; + client.LastDataSent = sentAt; + client.LastActive = sentAt; + client.BytesSent += data.Length; + client.MessagesSent++; + _stats.IncrementMessagesSent(); + _stats.AddBytesSent(data.Length); + return true; + } + catch (Exception exception) + { + HandlingHelpers.SafeInvokeEventHandler( + OnGeneralError, + this, + new ErrorEventArgs + { + ClientId = clientId, + Nickname = client.Nickname, + Exception = exception, + Message = "Error sending data to gRPC client" + }, + nameof(OnGeneralError)); + return false; + } + } + + public async Task SendToClientAsync(string clientId, string message) + => await SendToClientAsync(clientId, Encoding.UTF8.GetBytes(message)).ConfigureAwait(false); + + public async Task 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 BroadcastAsync(string message) + => await BroadcastAsync(Encoding.UTF8.GetBytes(message)).ConfigureAwait(false); + + public async Task BroadcastExceptAsync(byte[] data, string excludeClientId) + { + if (data == null || data.Length == 0) + { + return false; + } + + bool any = false; + foreach (var client in _clients) + { + if (client.Key == excludeClientId) + { + continue; + } + + if (await SendToClientAsync(client.Key, data).ConfigureAwait(false)) + { + any = true; + } + } + return any; + } + + public async Task BroadcastExceptAsync(string message, string excludeClientId) + => await BroadcastExceptAsync(Encoding.UTF8.GetBytes(message), excludeClientId).ConfigureAwait(false); + + public ConcurrentDictionary GetClients() => _clients; + + public GrpcClientConnection? GetClient(string clientId) + { + _clients.TryGetValue(clientId, out var client); + return client; + } + + public async Task DisconnectClientAsync(string clientId, DisconnectReason reason = DisconnectReason.ServerShutdown) + { + if (!RemoveClient(clientId, out var client)) + { + return; + } + + try + { + + if (client?.ResponseStream != null) + { + await client.WriteLock.WaitAsync().ConfigureAwait(false); + try + { + var msg = new ConnectorMessage { Type = MessageType.Disconnect }; + await client.ResponseStream.WriteAsync(msg).ConfigureAwait(false); + } + catch + { + + } + finally + { + client.WriteLock.Release(); + } + } + + client?.CancellationSource?.Cancel(); + } + catch + { + + } + + TrackDisconnect(reason); + + HandlingHelpers.SafeInvokeEventHandler( + OnDisconnected, + this, + new ConnectionEventArgs + { + ClientId = clientId, + Nickname = client?.Nickname, + RemoteEndPoint = client?.RemoteEndPoint, + Reason = reason + }, + nameof(OnDisconnected)); + } + + private async Task PingLoopAsync(CancellationToken token) + { + while (!token.IsCancellationRequested) + { + try + { + await Task.Delay(TimeSpan.FromSeconds(_config.HeartbeatIntervalSeconds), token).ConfigureAwait(false); + + foreach (var kvp in _clients) + { + var clientId = kvp.Key; + var client = kvp.Value; + + if (client.ResponseStream == null || !client.IsConnected) + { + continue; + } + + try + { + await client.WriteLock.WaitAsync(token).ConfigureAwait(false); + try + { + var pingMsg = new ConnectorMessage { Type = MessageType.Ping }; + await client.ResponseStream.WriteAsync(pingMsg).ConfigureAwait(false); + } + finally + { + client.WriteLock.Release(); + } + + client.LastPingSent = DateTime.UtcNow; + _lastPingTimes[clientId] = DateTime.UtcNow; + } + catch (Exception ex) + { + OnLog?.Invoke(this, new LogMessage { Type = LogType.Error, Message = $"Error sending ping to {client.Nickname}: {ex.Message}" }); + } + } + } + catch (OperationCanceledException) + { + break; + } + catch (Exception ex) + { + HandlingHelpers.SafeInvokeEventHandler( + OnGeneralError, + this, + new ErrorEventArgs + { + Exception = ex, + Message = "Ping loop error" + }, + nameof(OnGeneralError)); + } + } + } + + private async Task PongMonitorLoopAsync(CancellationToken token) + { + while (!token.IsCancellationRequested) + { + try + { + await Task.Delay(TimeSpan.FromSeconds(1), token).ConfigureAwait(false); + + var now = DateTime.UtcNow; + var timeout = _config.HeartbeatIntervalSeconds * 2; + + foreach (var kvp in _lastPingTimes) + { + var clientId = kvp.Key; + var lastPing = kvp.Value; + + if (!_clients.TryGetValue(clientId, out var client)) + { + _lastPingTimes.TryRemove(clientId, out _); + continue; + } + + var elapsed = (now - client.LastPongReceived).TotalSeconds; + if (client.LastPongReceived == default) + { + elapsed = (now - lastPing).TotalSeconds; + } + + if (elapsed > timeout) + { + OnPongMissed?.Invoke(this, new PingEventArgs + { + Id = client.Id, + Nickname = client.Nickname, + ReceivedTime = now, + RemoteEndPoint = client.RemoteEndPoint + }); + + if (_config.DisconectOnMissedPong) + { + OnLog?.Invoke(this, new LogMessage { Type = LogType.Trace, Message = $"gRPC client '{client.Nickname}' no PONG for {elapsed:F1}s, disconnecting." }); + _ = DisconnectClientAsync(clientId, DisconnectReason.NoPongReceived); + } + } + } + } + catch (OperationCanceledException) + { + break; + } + catch (Exception ex) + { + HandlingHelpers.SafeInvokeEventHandler( + OnGeneralError, + this, + new ErrorEventArgs + { + Exception = ex, + Message = "Pong monitor loop error" + }, + nameof(OnGeneralError)); + } + } + } + + internal void HandlePongReceived(string clientId) + { + if (_clients.TryGetValue(clientId, out var client)) + { + client.LastPongReceived = DateTime.UtcNow; + client.LastActive = DateTime.UtcNow; + + OnClientPingResponse?.Invoke(this, new PingEventArgs + { + Id = clientId, + Nickname = client.Nickname, + ReceivedTime = DateTime.UtcNow, + RemoteEndPoint = client.RemoteEndPoint + }); + } + } + + private string BuildHealthJson() + { + var E = HealthApiServer.JsonEscape; + var stats = GetStats(); + return "{" + + "\"status\":\"ok\"," + + "\"type\":\"grpc-server\"," + + $"\"listenAddress\":{E(_config.Host + ":" + _config.Port)}," + + $"\"isStarted\":{(IsStarted ? "true" : "false")}," + + $"\"activeConnections\":{stats.ActiveConnections}," + + $"\"maxConnections\":{_config.MaxConnections}," + + $"\"uptimeSeconds\":{stats.Uptime.TotalSeconds:F1}," + + $"\"startTimeUtc\":{E(stats.StartTime.ToString("O"))}" + + "}"; + } + + private string BuildStatusJson() + { + var E = HealthApiServer.JsonEscape; + var stats = GetStats(); + var sb = new StringBuilder(); + sb.Append("{"); + sb.Append("\"status\":\"ok\","); + sb.Append("\"type\":\"grpc-server\","); + sb.Append($"\"listenAddress\":{E(_config.Host + ":" + _config.Port)},"); + sb.Append($"\"isStarted\":{(IsStarted ? "true" : "false")},"); + sb.Append($"\"activeConnections\":{stats.ActiveConnections},"); + sb.Append($"\"maxConnections\":{_config.MaxConnections},"); + sb.Append($"\"totalConnections\":{stats.TotalConnections},"); + sb.Append($"\"droppedConnections\":{stats.DroppedConnections},"); + sb.Append($"\"bytesSent\":{stats.BytesSent},"); + sb.Append($"\"bytesReceived\":{stats.BytesReceived},"); + sb.Append($"\"messagesSent\":{stats.MessagesSent},"); + sb.Append($"\"messagesReceived\":{stats.MessagesReceived},"); + sb.Append($"\"messagesPerSecond\":{stats.MessagesPerSecond:F2},"); + sb.Append($"\"uptimeSeconds\":{stats.Uptime.TotalSeconds:F1},"); + sb.Append($"\"startTimeUtc\":{E(stats.StartTime.ToString("O"))},"); + + sb.Append("\"clients\":["); + var clientList = _clients.Values.ToArray(); + for (int i = 0; i < clientList.Length; i++) + { + var c = clientList[i]; + if (i > 0) + { + sb.Append(","); + } + + sb.Append("{"); + sb.Append($"\"id\":{E(c.Id)},"); + sb.Append($"\"nickname\":{E(c.Nickname)},"); + sb.Append($"\"remoteEndPoint\":{E(c.RemoteEndPoint?.ToString())},"); + sb.Append($"\"connectedAtUtc\":{E(c.ConnectedAt.ToString("O"))},"); + sb.Append($"\"connectedTimeSeconds\":{c.ConnectedTime().TotalSeconds:F1},"); + sb.Append($"\"idleTimeSeconds\":{c.IdleTime().TotalSeconds:F1},"); + sb.Append($"\"bytesSent\":{c.BytesSent},"); + sb.Append($"\"bytesReceived\":{c.BytesReceived},"); + sb.Append($"\"messagesSent\":{c.MessagesSent},"); + sb.Append($"\"messagesReceived\":{c.MessagesReceived}"); + sb.Append("}"); + } + sb.Append("]"); + sb.Append("}"); + return sb.ToString(); + } + + public void Stop() + { + _serverCts?.Cancel(); + + foreach (var client in _clients.Keys.ToList()) + { + DisconnectClientAsync(client, DisconnectReason.ServerShutdown).GetAwaiter().GetResult(); + } + + _clients.Clear(); + + HealthApi.Stop(); + + try + { + _app?.StopAsync().GetAwaiter().GetResult(); + } + catch + { + + } + + try + { + _app?.DisposeAsync().AsTask().GetAwaiter().GetResult(); + } + catch + { + + } + + _app = null; + } + + public async Task StopAsync() + { + _serverCts?.Cancel(); + + foreach (var client in _clients.Keys.ToList()) + { + await DisconnectClientAsync(client, DisconnectReason.ServerShutdown).ConfigureAwait(false); + } + + _clients.Clear(); + + HealthApi.Stop(); + + try + { + if (_app != null) + { + await _app.StopAsync().ConfigureAwait(false); + } + } + catch + { + + } + + try + { + if (_app != null) + { + await _app.DisposeAsync().ConfigureAwait(false); + } + } + catch + { + + } + + _app = null; + + if (_serverTask != null) + { + try + { + await _serverTask.ConfigureAwait(false); + } + catch + { + + } + } + } + + public void Dispose() + { + if (_disposed) + { + return; + } + + _disposed = true; + + Stop(); + + _serverCts?.Dispose(); + _stats.Dispose(); + + OnConnected = null; + OnDisconnected = null; + OnDataReceived = null; + OnGeneralError = null; + OnClientPingResponse = null; + OnPongMissed = null; + } + + public async ValueTask DisposeAsync() + { + if (_disposed) + { + return; + } + + _disposed = true; + + await StopAsync().ConfigureAwait(false); + + _serverCts?.Dispose(); + _stats.Dispose(); + + OnConnected = null; + OnDisconnected = null; + OnDataReceived = null; + OnGeneralError = null; + OnClientPingResponse = null; + OnPongMissed = null; + } + } +} diff --git a/EonaCat.Connections.gRPC/Protos/connector.proto b/EonaCat.Connections.gRPC/Protos/connector.proto new file mode 100644 index 0000000..3506e43 --- /dev/null +++ b/EonaCat.Connections.gRPC/Protos/connector.proto @@ -0,0 +1,23 @@ +syntax = "proto3"; + +option csharp_namespace = "EonaCat.Connections.gRPC.Proto"; + +package connector; + +service ConnectorService { + rpc Connect (stream ConnectorMessage) returns (stream ConnectorMessage); +} + +message ConnectorMessage { + MessageType type = 1; + bytes data = 2; + string text = 3; +} + +enum MessageType { + DATA = 0; + NICKNAME = 1; + PING = 2; + PONG = 3; + DISCONNECT = 4; +} diff --git a/EonaCat.Connections.sln b/EonaCat.Connections.sln index 9494a31..1b5ea09 100644 --- a/EonaCat.Connections.sln +++ b/EonaCat.Connections.sln @@ -1,7 +1,7 @@  Microsoft Visual Studio Solution File, Format Version 12.00 # Visual Studio Version 18 -VisualStudioVersion = 18.0.11205.157 d18.0 +VisualStudioVersion = 18.0.11205.157 MinimumVisualStudioVersion = 10.0.40219.1 Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "EonaCat.Connections", "EonaCat.Connections\EonaCat.Connections.csproj", "{D3925D5A-4791-C3BB-93E0-25AC0C0ED425}" EndProject @@ -9,24 +9,220 @@ Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "EonaCat.Connections.Client" EndProject Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "EonaCat.Connections.Server", "EonaCat.Connections.Server\EonaCat.Connections.Server.csproj", "{B0756C21-1D41-041C-D3D7-76A9A01E0009}" EndProject +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "EonaCat.Connections.Quic", "EonaCat.Connections.Quic\EonaCat.Connections.Quic.csproj", "{78997F5F-4278-4817-9F8F-C95AB807A812}" +EndProject +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "EonaCat.Connections.Quic.Client", "EonaCat.Connections.Quic.Client\EonaCat.Connections.Quic.Client.csproj", "{35256C8B-48E2-42DC-977F-E2749D2B0284}" +EndProject +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "EonaCat.Connections.Quic.Server", "EonaCat.Connections.Quic.Server\EonaCat.Connections.Quic.Server.csproj", "{2482D3A6-6312-4892-BD57-927F49D4ACD7}" +EndProject +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "EonaCat.Connections.gRPC", "EonaCat.Connections.gRPC\EonaCat.Connections.gRPC.csproj", "{1DF97457-1582-4218-BC07-706FB23021D0}" +EndProject +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "EonaCat.Connections.gRPC.Server", "EonaCat.Connections.gRPC.Server\EonaCat.Connections.gRPC.Server.csproj", "{EB379332-F5E6-48BD-8114-A59014A1E27C}" +EndProject +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "EonaCat.Connections.gRPC.Client", "EonaCat.Connections.gRPC.Client\EonaCat.Connections.gRPC.Client.csproj", "{D0C18902-A38A-4686-A4D2-2A79143C97E4}" +EndProject +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "EonaCat.Connections.REST", "EonaCat.Connections.REST\EonaCat.Connections.REST.csproj", "{86B741C5-7D96-4AC9-A365-DD93AD4BA53F}" +EndProject +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "EonaCat.Connections.REST.Server", "EonaCat.Connections.REST.Server\EonaCat.Connections.REST.Server.csproj", "{EB638D1B-A2C3-4184-A276-5C903BEABE9E}" +EndProject +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "EonaCat.Connections.REST.Client", "EonaCat.Connections.REST.Client\EonaCat.Connections.REST.Client.csproj", "{17E8D91B-131F-447C-9FF5-BC87094CFB2F}" +EndProject +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "EonaCat.Connections.OpcUa", "EonaCat.Connections.OpcUa\EonaCat.Connections.OpcUa.csproj", "{1DD90B77-24AB-4162-8D7E-BD0EDC16FE62}" +EndProject +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "EonaCat.Connections.OpcUa.Client", "EonaCat.Connections.OpcUa.Client\EonaCat.Connections.OpcUa.Client.csproj", "{55E9200D-DF76-476B-ACB0-99727862F9F8}" +EndProject +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "EonaCat.Connections.OpcUa.Server", "EonaCat.Connections.OpcUa.Server\EonaCat.Connections.OpcUa.Server.csproj", "{33B0EF4A-E66B-4D37-8C77-6018DFE69B9C}" +EndProject Global GlobalSection(SolutionConfigurationPlatforms) = preSolution Debug|Any CPU = Debug|Any CPU + Debug|x64 = Debug|x64 + Debug|x86 = Debug|x86 Release|Any CPU = Release|Any CPU + Release|x64 = Release|x64 + Release|x86 = Release|x86 EndGlobalSection GlobalSection(ProjectConfigurationPlatforms) = postSolution {D3925D5A-4791-C3BB-93E0-25AC0C0ED425}.Debug|Any CPU.ActiveCfg = Debug|Any CPU {D3925D5A-4791-C3BB-93E0-25AC0C0ED425}.Debug|Any CPU.Build.0 = Debug|Any CPU + {D3925D5A-4791-C3BB-93E0-25AC0C0ED425}.Debug|x64.ActiveCfg = Debug|Any CPU + {D3925D5A-4791-C3BB-93E0-25AC0C0ED425}.Debug|x64.Build.0 = Debug|Any CPU + {D3925D5A-4791-C3BB-93E0-25AC0C0ED425}.Debug|x86.ActiveCfg = Debug|Any CPU + {D3925D5A-4791-C3BB-93E0-25AC0C0ED425}.Debug|x86.Build.0 = Debug|Any CPU {D3925D5A-4791-C3BB-93E0-25AC0C0ED425}.Release|Any CPU.ActiveCfg = Release|Any CPU {D3925D5A-4791-C3BB-93E0-25AC0C0ED425}.Release|Any CPU.Build.0 = Release|Any CPU + {D3925D5A-4791-C3BB-93E0-25AC0C0ED425}.Release|x64.ActiveCfg = Release|Any CPU + {D3925D5A-4791-C3BB-93E0-25AC0C0ED425}.Release|x64.Build.0 = Release|Any CPU + {D3925D5A-4791-C3BB-93E0-25AC0C0ED425}.Release|x86.ActiveCfg = Release|Any CPU + {D3925D5A-4791-C3BB-93E0-25AC0C0ED425}.Release|x86.Build.0 = Release|Any CPU {42A5F58D-850A-8272-4CD9-0B1BEFD12A11}.Debug|Any CPU.ActiveCfg = Debug|Any CPU {42A5F58D-850A-8272-4CD9-0B1BEFD12A11}.Debug|Any CPU.Build.0 = Debug|Any CPU + {42A5F58D-850A-8272-4CD9-0B1BEFD12A11}.Debug|x64.ActiveCfg = Debug|Any CPU + {42A5F58D-850A-8272-4CD9-0B1BEFD12A11}.Debug|x64.Build.0 = Debug|Any CPU + {42A5F58D-850A-8272-4CD9-0B1BEFD12A11}.Debug|x86.ActiveCfg = Debug|Any CPU + {42A5F58D-850A-8272-4CD9-0B1BEFD12A11}.Debug|x86.Build.0 = Debug|Any CPU {42A5F58D-850A-8272-4CD9-0B1BEFD12A11}.Release|Any CPU.ActiveCfg = Release|Any CPU {42A5F58D-850A-8272-4CD9-0B1BEFD12A11}.Release|Any CPU.Build.0 = Release|Any CPU + {42A5F58D-850A-8272-4CD9-0B1BEFD12A11}.Release|x64.ActiveCfg = Release|Any CPU + {42A5F58D-850A-8272-4CD9-0B1BEFD12A11}.Release|x64.Build.0 = Release|Any CPU + {42A5F58D-850A-8272-4CD9-0B1BEFD12A11}.Release|x86.ActiveCfg = Release|Any CPU + {42A5F58D-850A-8272-4CD9-0B1BEFD12A11}.Release|x86.Build.0 = Release|Any CPU {B0756C21-1D41-041C-D3D7-76A9A01E0009}.Debug|Any CPU.ActiveCfg = Debug|Any CPU {B0756C21-1D41-041C-D3D7-76A9A01E0009}.Debug|Any CPU.Build.0 = Debug|Any CPU + {B0756C21-1D41-041C-D3D7-76A9A01E0009}.Debug|x64.ActiveCfg = Debug|Any CPU + {B0756C21-1D41-041C-D3D7-76A9A01E0009}.Debug|x64.Build.0 = Debug|Any CPU + {B0756C21-1D41-041C-D3D7-76A9A01E0009}.Debug|x86.ActiveCfg = Debug|Any CPU + {B0756C21-1D41-041C-D3D7-76A9A01E0009}.Debug|x86.Build.0 = Debug|Any CPU {B0756C21-1D41-041C-D3D7-76A9A01E0009}.Release|Any CPU.ActiveCfg = Release|Any CPU {B0756C21-1D41-041C-D3D7-76A9A01E0009}.Release|Any CPU.Build.0 = Release|Any CPU + {B0756C21-1D41-041C-D3D7-76A9A01E0009}.Release|x64.ActiveCfg = Release|Any CPU + {B0756C21-1D41-041C-D3D7-76A9A01E0009}.Release|x64.Build.0 = Release|Any CPU + {B0756C21-1D41-041C-D3D7-76A9A01E0009}.Release|x86.ActiveCfg = Release|Any CPU + {B0756C21-1D41-041C-D3D7-76A9A01E0009}.Release|x86.Build.0 = Release|Any CPU + {78997F5F-4278-4817-9F8F-C95AB807A812}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {78997F5F-4278-4817-9F8F-C95AB807A812}.Debug|Any CPU.Build.0 = Debug|Any CPU + {78997F5F-4278-4817-9F8F-C95AB807A812}.Debug|x64.ActiveCfg = Debug|Any CPU + {78997F5F-4278-4817-9F8F-C95AB807A812}.Debug|x64.Build.0 = Debug|Any CPU + {78997F5F-4278-4817-9F8F-C95AB807A812}.Debug|x86.ActiveCfg = Debug|Any CPU + {78997F5F-4278-4817-9F8F-C95AB807A812}.Debug|x86.Build.0 = Debug|Any CPU + {78997F5F-4278-4817-9F8F-C95AB807A812}.Release|Any CPU.ActiveCfg = Release|Any CPU + {78997F5F-4278-4817-9F8F-C95AB807A812}.Release|Any CPU.Build.0 = Release|Any CPU + {78997F5F-4278-4817-9F8F-C95AB807A812}.Release|x64.ActiveCfg = Release|Any CPU + {78997F5F-4278-4817-9F8F-C95AB807A812}.Release|x64.Build.0 = Release|Any CPU + {78997F5F-4278-4817-9F8F-C95AB807A812}.Release|x86.ActiveCfg = Release|Any CPU + {78997F5F-4278-4817-9F8F-C95AB807A812}.Release|x86.Build.0 = Release|Any CPU + {35256C8B-48E2-42DC-977F-E2749D2B0284}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {35256C8B-48E2-42DC-977F-E2749D2B0284}.Debug|Any CPU.Build.0 = Debug|Any CPU + {35256C8B-48E2-42DC-977F-E2749D2B0284}.Debug|x64.ActiveCfg = Debug|Any CPU + {35256C8B-48E2-42DC-977F-E2749D2B0284}.Debug|x64.Build.0 = Debug|Any CPU + {35256C8B-48E2-42DC-977F-E2749D2B0284}.Debug|x86.ActiveCfg = Debug|Any CPU + {35256C8B-48E2-42DC-977F-E2749D2B0284}.Debug|x86.Build.0 = Debug|Any CPU + {35256C8B-48E2-42DC-977F-E2749D2B0284}.Release|Any CPU.ActiveCfg = Release|Any CPU + {35256C8B-48E2-42DC-977F-E2749D2B0284}.Release|Any CPU.Build.0 = Release|Any CPU + {35256C8B-48E2-42DC-977F-E2749D2B0284}.Release|x64.ActiveCfg = Release|Any CPU + {35256C8B-48E2-42DC-977F-E2749D2B0284}.Release|x64.Build.0 = Release|Any CPU + {35256C8B-48E2-42DC-977F-E2749D2B0284}.Release|x86.ActiveCfg = Release|Any CPU + {35256C8B-48E2-42DC-977F-E2749D2B0284}.Release|x86.Build.0 = Release|Any CPU + {2482D3A6-6312-4892-BD57-927F49D4ACD7}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {2482D3A6-6312-4892-BD57-927F49D4ACD7}.Debug|Any CPU.Build.0 = Debug|Any CPU + {2482D3A6-6312-4892-BD57-927F49D4ACD7}.Debug|x64.ActiveCfg = Debug|Any CPU + {2482D3A6-6312-4892-BD57-927F49D4ACD7}.Debug|x64.Build.0 = Debug|Any CPU + {2482D3A6-6312-4892-BD57-927F49D4ACD7}.Debug|x86.ActiveCfg = Debug|Any CPU + {2482D3A6-6312-4892-BD57-927F49D4ACD7}.Debug|x86.Build.0 = Debug|Any CPU + {2482D3A6-6312-4892-BD57-927F49D4ACD7}.Release|Any CPU.ActiveCfg = Release|Any CPU + {2482D3A6-6312-4892-BD57-927F49D4ACD7}.Release|Any CPU.Build.0 = Release|Any CPU + {2482D3A6-6312-4892-BD57-927F49D4ACD7}.Release|x64.ActiveCfg = Release|Any CPU + {2482D3A6-6312-4892-BD57-927F49D4ACD7}.Release|x64.Build.0 = Release|Any CPU + {2482D3A6-6312-4892-BD57-927F49D4ACD7}.Release|x86.ActiveCfg = Release|Any CPU + {2482D3A6-6312-4892-BD57-927F49D4ACD7}.Release|x86.Build.0 = Release|Any CPU + {1DF97457-1582-4218-BC07-706FB23021D0}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {1DF97457-1582-4218-BC07-706FB23021D0}.Debug|Any CPU.Build.0 = Debug|Any CPU + {1DF97457-1582-4218-BC07-706FB23021D0}.Debug|x64.ActiveCfg = Debug|Any CPU + {1DF97457-1582-4218-BC07-706FB23021D0}.Debug|x64.Build.0 = Debug|Any CPU + {1DF97457-1582-4218-BC07-706FB23021D0}.Debug|x86.ActiveCfg = Debug|Any CPU + {1DF97457-1582-4218-BC07-706FB23021D0}.Debug|x86.Build.0 = Debug|Any CPU + {1DF97457-1582-4218-BC07-706FB23021D0}.Release|Any CPU.ActiveCfg = Release|Any CPU + {1DF97457-1582-4218-BC07-706FB23021D0}.Release|Any CPU.Build.0 = Release|Any CPU + {1DF97457-1582-4218-BC07-706FB23021D0}.Release|x64.ActiveCfg = Release|Any CPU + {1DF97457-1582-4218-BC07-706FB23021D0}.Release|x64.Build.0 = Release|Any CPU + {1DF97457-1582-4218-BC07-706FB23021D0}.Release|x86.ActiveCfg = Release|Any CPU + {1DF97457-1582-4218-BC07-706FB23021D0}.Release|x86.Build.0 = Release|Any CPU + {EB379332-F5E6-48BD-8114-A59014A1E27C}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {EB379332-F5E6-48BD-8114-A59014A1E27C}.Debug|Any CPU.Build.0 = Debug|Any CPU + {EB379332-F5E6-48BD-8114-A59014A1E27C}.Debug|x64.ActiveCfg = Debug|Any CPU + {EB379332-F5E6-48BD-8114-A59014A1E27C}.Debug|x64.Build.0 = Debug|Any CPU + {EB379332-F5E6-48BD-8114-A59014A1E27C}.Debug|x86.ActiveCfg = Debug|Any CPU + {EB379332-F5E6-48BD-8114-A59014A1E27C}.Debug|x86.Build.0 = Debug|Any CPU + {EB379332-F5E6-48BD-8114-A59014A1E27C}.Release|Any CPU.ActiveCfg = Release|Any CPU + {EB379332-F5E6-48BD-8114-A59014A1E27C}.Release|Any CPU.Build.0 = Release|Any CPU + {EB379332-F5E6-48BD-8114-A59014A1E27C}.Release|x64.ActiveCfg = Release|Any CPU + {EB379332-F5E6-48BD-8114-A59014A1E27C}.Release|x64.Build.0 = Release|Any CPU + {EB379332-F5E6-48BD-8114-A59014A1E27C}.Release|x86.ActiveCfg = Release|Any CPU + {EB379332-F5E6-48BD-8114-A59014A1E27C}.Release|x86.Build.0 = Release|Any CPU + {D0C18902-A38A-4686-A4D2-2A79143C97E4}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {D0C18902-A38A-4686-A4D2-2A79143C97E4}.Debug|Any CPU.Build.0 = Debug|Any CPU + {D0C18902-A38A-4686-A4D2-2A79143C97E4}.Debug|x64.ActiveCfg = Debug|Any CPU + {D0C18902-A38A-4686-A4D2-2A79143C97E4}.Debug|x64.Build.0 = Debug|Any CPU + {D0C18902-A38A-4686-A4D2-2A79143C97E4}.Debug|x86.ActiveCfg = Debug|Any CPU + {D0C18902-A38A-4686-A4D2-2A79143C97E4}.Debug|x86.Build.0 = Debug|Any CPU + {D0C18902-A38A-4686-A4D2-2A79143C97E4}.Release|Any CPU.ActiveCfg = Release|Any CPU + {D0C18902-A38A-4686-A4D2-2A79143C97E4}.Release|Any CPU.Build.0 = Release|Any CPU + {D0C18902-A38A-4686-A4D2-2A79143C97E4}.Release|x64.ActiveCfg = Release|Any CPU + {D0C18902-A38A-4686-A4D2-2A79143C97E4}.Release|x64.Build.0 = Release|Any CPU + {D0C18902-A38A-4686-A4D2-2A79143C97E4}.Release|x86.ActiveCfg = Release|Any CPU + {D0C18902-A38A-4686-A4D2-2A79143C97E4}.Release|x86.Build.0 = Release|Any CPU + {86B741C5-7D96-4AC9-A365-DD93AD4BA53F}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {86B741C5-7D96-4AC9-A365-DD93AD4BA53F}.Debug|Any CPU.Build.0 = Debug|Any CPU + {86B741C5-7D96-4AC9-A365-DD93AD4BA53F}.Debug|x64.ActiveCfg = Debug|Any CPU + {86B741C5-7D96-4AC9-A365-DD93AD4BA53F}.Debug|x64.Build.0 = Debug|Any CPU + {86B741C5-7D96-4AC9-A365-DD93AD4BA53F}.Debug|x86.ActiveCfg = Debug|Any CPU + {86B741C5-7D96-4AC9-A365-DD93AD4BA53F}.Debug|x86.Build.0 = Debug|Any CPU + {86B741C5-7D96-4AC9-A365-DD93AD4BA53F}.Release|Any CPU.ActiveCfg = Release|Any CPU + {86B741C5-7D96-4AC9-A365-DD93AD4BA53F}.Release|Any CPU.Build.0 = Release|Any CPU + {86B741C5-7D96-4AC9-A365-DD93AD4BA53F}.Release|x64.ActiveCfg = Release|Any CPU + {86B741C5-7D96-4AC9-A365-DD93AD4BA53F}.Release|x64.Build.0 = Release|Any CPU + {86B741C5-7D96-4AC9-A365-DD93AD4BA53F}.Release|x86.ActiveCfg = Release|Any CPU + {86B741C5-7D96-4AC9-A365-DD93AD4BA53F}.Release|x86.Build.0 = Release|Any CPU + {EB638D1B-A2C3-4184-A276-5C903BEABE9E}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {EB638D1B-A2C3-4184-A276-5C903BEABE9E}.Debug|Any CPU.Build.0 = Debug|Any CPU + {EB638D1B-A2C3-4184-A276-5C903BEABE9E}.Debug|x64.ActiveCfg = Debug|Any CPU + {EB638D1B-A2C3-4184-A276-5C903BEABE9E}.Debug|x64.Build.0 = Debug|Any CPU + {EB638D1B-A2C3-4184-A276-5C903BEABE9E}.Debug|x86.ActiveCfg = Debug|Any CPU + {EB638D1B-A2C3-4184-A276-5C903BEABE9E}.Debug|x86.Build.0 = Debug|Any CPU + {EB638D1B-A2C3-4184-A276-5C903BEABE9E}.Release|Any CPU.ActiveCfg = Release|Any CPU + {EB638D1B-A2C3-4184-A276-5C903BEABE9E}.Release|Any CPU.Build.0 = Release|Any CPU + {EB638D1B-A2C3-4184-A276-5C903BEABE9E}.Release|x64.ActiveCfg = Release|Any CPU + {EB638D1B-A2C3-4184-A276-5C903BEABE9E}.Release|x64.Build.0 = Release|Any CPU + {EB638D1B-A2C3-4184-A276-5C903BEABE9E}.Release|x86.ActiveCfg = Release|Any CPU + {EB638D1B-A2C3-4184-A276-5C903BEABE9E}.Release|x86.Build.0 = Release|Any CPU + {17E8D91B-131F-447C-9FF5-BC87094CFB2F}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {17E8D91B-131F-447C-9FF5-BC87094CFB2F}.Debug|Any CPU.Build.0 = Debug|Any CPU + {17E8D91B-131F-447C-9FF5-BC87094CFB2F}.Debug|x64.ActiveCfg = Debug|Any CPU + {17E8D91B-131F-447C-9FF5-BC87094CFB2F}.Debug|x64.Build.0 = Debug|Any CPU + {17E8D91B-131F-447C-9FF5-BC87094CFB2F}.Debug|x86.ActiveCfg = Debug|Any CPU + {17E8D91B-131F-447C-9FF5-BC87094CFB2F}.Debug|x86.Build.0 = Debug|Any CPU + {17E8D91B-131F-447C-9FF5-BC87094CFB2F}.Release|Any CPU.ActiveCfg = Release|Any CPU + {17E8D91B-131F-447C-9FF5-BC87094CFB2F}.Release|Any CPU.Build.0 = Release|Any CPU + {17E8D91B-131F-447C-9FF5-BC87094CFB2F}.Release|x64.ActiveCfg = Release|Any CPU + {17E8D91B-131F-447C-9FF5-BC87094CFB2F}.Release|x64.Build.0 = Release|Any CPU + {17E8D91B-131F-447C-9FF5-BC87094CFB2F}.Release|x86.ActiveCfg = Release|Any CPU + {17E8D91B-131F-447C-9FF5-BC87094CFB2F}.Release|x86.Build.0 = Release|Any CPU + {1DD90B77-24AB-4162-8D7E-BD0EDC16FE62}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {1DD90B77-24AB-4162-8D7E-BD0EDC16FE62}.Debug|Any CPU.Build.0 = Debug|Any CPU + {1DD90B77-24AB-4162-8D7E-BD0EDC16FE62}.Debug|x64.ActiveCfg = Debug|Any CPU + {1DD90B77-24AB-4162-8D7E-BD0EDC16FE62}.Debug|x64.Build.0 = Debug|Any CPU + {1DD90B77-24AB-4162-8D7E-BD0EDC16FE62}.Debug|x86.ActiveCfg = Debug|Any CPU + {1DD90B77-24AB-4162-8D7E-BD0EDC16FE62}.Debug|x86.Build.0 = Debug|Any CPU + {1DD90B77-24AB-4162-8D7E-BD0EDC16FE62}.Release|Any CPU.ActiveCfg = Release|Any CPU + {1DD90B77-24AB-4162-8D7E-BD0EDC16FE62}.Release|Any CPU.Build.0 = Release|Any CPU + {1DD90B77-24AB-4162-8D7E-BD0EDC16FE62}.Release|x64.ActiveCfg = Release|Any CPU + {1DD90B77-24AB-4162-8D7E-BD0EDC16FE62}.Release|x64.Build.0 = Release|Any CPU + {1DD90B77-24AB-4162-8D7E-BD0EDC16FE62}.Release|x86.ActiveCfg = Release|Any CPU + {1DD90B77-24AB-4162-8D7E-BD0EDC16FE62}.Release|x86.Build.0 = Release|Any CPU + {55E9200D-DF76-476B-ACB0-99727862F9F8}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {55E9200D-DF76-476B-ACB0-99727862F9F8}.Debug|Any CPU.Build.0 = Debug|Any CPU + {55E9200D-DF76-476B-ACB0-99727862F9F8}.Debug|x64.ActiveCfg = Debug|Any CPU + {55E9200D-DF76-476B-ACB0-99727862F9F8}.Debug|x64.Build.0 = Debug|Any CPU + {55E9200D-DF76-476B-ACB0-99727862F9F8}.Debug|x86.ActiveCfg = Debug|Any CPU + {55E9200D-DF76-476B-ACB0-99727862F9F8}.Debug|x86.Build.0 = Debug|Any CPU + {55E9200D-DF76-476B-ACB0-99727862F9F8}.Release|Any CPU.ActiveCfg = Release|Any CPU + {55E9200D-DF76-476B-ACB0-99727862F9F8}.Release|Any CPU.Build.0 = Release|Any CPU + {55E9200D-DF76-476B-ACB0-99727862F9F8}.Release|x64.ActiveCfg = Release|Any CPU + {55E9200D-DF76-476B-ACB0-99727862F9F8}.Release|x64.Build.0 = Release|Any CPU + {55E9200D-DF76-476B-ACB0-99727862F9F8}.Release|x86.ActiveCfg = Release|Any CPU + {55E9200D-DF76-476B-ACB0-99727862F9F8}.Release|x86.Build.0 = Release|Any CPU + {33B0EF4A-E66B-4D37-8C77-6018DFE69B9C}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {33B0EF4A-E66B-4D37-8C77-6018DFE69B9C}.Debug|Any CPU.Build.0 = Debug|Any CPU + {33B0EF4A-E66B-4D37-8C77-6018DFE69B9C}.Debug|x64.ActiveCfg = Debug|Any CPU + {33B0EF4A-E66B-4D37-8C77-6018DFE69B9C}.Debug|x64.Build.0 = Debug|Any CPU + {33B0EF4A-E66B-4D37-8C77-6018DFE69B9C}.Debug|x86.ActiveCfg = Debug|Any CPU + {33B0EF4A-E66B-4D37-8C77-6018DFE69B9C}.Debug|x86.Build.0 = Debug|Any CPU + {33B0EF4A-E66B-4D37-8C77-6018DFE69B9C}.Release|Any CPU.ActiveCfg = Release|Any CPU + {33B0EF4A-E66B-4D37-8C77-6018DFE69B9C}.Release|Any CPU.Build.0 = Release|Any CPU + {33B0EF4A-E66B-4D37-8C77-6018DFE69B9C}.Release|x64.ActiveCfg = Release|Any CPU + {33B0EF4A-E66B-4D37-8C77-6018DFE69B9C}.Release|x64.Build.0 = Release|Any CPU + {33B0EF4A-E66B-4D37-8C77-6018DFE69B9C}.Release|x86.ActiveCfg = Release|Any CPU + {33B0EF4A-E66B-4D37-8C77-6018DFE69B9C}.Release|x86.Build.0 = Release|Any CPU EndGlobalSection GlobalSection(SolutionProperties) = preSolution HideSolutionNode = FALSE diff --git a/EonaCat.Connections/BufferSize.cs b/EonaCat.Connections/BufferSize.cs index 91e0a3e..90de155 100644 --- a/EonaCat.Connections/BufferSize.cs +++ b/EonaCat.Connections/BufferSize.cs @@ -1,13 +1,21 @@ namespace EonaCat.Connections { - // This file is part of the EonaCat project(s) which is released under the Apache License. - // See the LICENSE file or go to https://EonaCat.com/license for full license details. - internal enum BufferSizeMaximum { - Minimal = 8192, - Medium = 65536, - Large = 262144, - ExtraLarge = 1048576, + Small = 32 * 1024, + Medium = 128 * 1024, + Large = 512 * 1024, + ExtraLarge = 1 * 1024 * 1024, + Huge = 8 * 1024 * 1024 } -} \ No newline at end of file + + internal enum MessageSizeMaximum + { + Small = 16 * 1024 * 1024, + Medium = 32 * 1024 * 1024, + Large = 64 * 1024 * 1024, + ExtraLarge = 128 * 1024 * 1024, + Huge = 256 * 1024 * 1024, + Default = 32 * 1024 * 1024 + } +} diff --git a/EonaCat.Connections/Client/LogType.cs b/EonaCat.Connections/Client/LogType.cs new file mode 100644 index 0000000..1b3226c --- /dev/null +++ b/EonaCat.Connections/Client/LogType.cs @@ -0,0 +1,18 @@ +namespace EonaCat.Connections +{ + public enum LogType + { + None = 0, + Info = 1, + Warning = 2, + Error = 3, + Debug = 4, + Trace = 5 + } + + public class LogMessage + { + public LogType Type { get; set; } + public string Message { get; set; } + } +} \ No newline at end of file diff --git a/EonaCat.Connections/Client/NetworkClient.Connection.cs b/EonaCat.Connections/Client/NetworkClient.Connection.cs new file mode 100644 index 0000000..9180272 --- /dev/null +++ b/EonaCat.Connections/Client/NetworkClient.Connection.cs @@ -0,0 +1,1116 @@ +using EonaCat.Connections.EventArguments; +using EonaCat.Connections.Helpers; +using EonaCat.Connections.Infrastructure; +using EonaCat.Connections.Models; +using EonaCat.Connections.ConnectionDiagnostics; +using System.Net; +using System.Net.Security; +using System.Net.Sockets; +using System.Security.Authentication; +using System.Security.Cryptography.X509Certificates; +using System.Text; +using ErrorEventArgs = EonaCat.Connections.EventArguments.ErrorEventArgs; +using ProtocolType = EonaCat.Connections.Models.ProtocolType; + +namespace EonaCat.Connections +{ + public partial class NetworkClient + { + public static event EventHandler OnLog; + + private IPEndPoint GetRemoteEndPoint() + { + try + { + if (_tcpClient?.Client?.RemoteEndPoint is IPEndPoint tcpEndPoint) + { + _resolvedEndPoint = tcpEndPoint; + return tcpEndPoint; + } + + if (_udpClient?.Client?.RemoteEndPoint is IPEndPoint udpEndPoint) + { + _resolvedEndPoint = udpEndPoint; + return udpEndPoint; + } + } + catch (ObjectDisposedException) + { + + } + + if (_resolvedEndPoint != null) + { + return _resolvedEndPoint; + } + + return ResolveRemoteEndPointSafe(); + } + + private IPEndPoint ResolveRemoteEndPointSafe() + { + try + { + if (string.IsNullOrWhiteSpace(_config.Host)) + { + throw new ArgumentException("Host cannot be empty.", nameof(_config.Host)); + } + + if (_config.Port is < 1 or > 65535) + { + throw new ArgumentOutOfRangeException(nameof(_config.Port), "Port must be between 1 and 65535."); + } + + if (IPAddress.TryParse(_config.Host, out var ip)) + { + _resolvedEndPoint = new IPEndPoint(ip, _config.Port); + return _resolvedEndPoint; + } + + var addresses = Dns.GetHostAddresses(_config.Host); + var address = addresses + .OrderBy(a => a.AddressFamily == AddressFamily.InterNetwork ? 0 : 1) + .FirstOrDefault(); + + if (address == null) + { + throw new InvalidOperationException($"DNS lookup for '{_config.Host}' returned no addresses."); + } + + _resolvedEndPoint = new IPEndPoint(address, _config.Port); + return _resolvedEndPoint; + } + catch (Exception ex) + { + DebugConnection($"GetRemoteEndPoint: resolution failed for '{_config?.Host}': {ex.GetType().Name} - {ex.Message}"); + return _resolvedEndPoint ?? new IPEndPoint(IPAddress.None, _config?.Port ?? 0); + } + } + + public async Task WaitForConnectedAsync(TimeSpan? timeout = null, CancellationToken cancellationToken = default) + { + if (cancellationToken.IsCancellationRequested) + { + return false; + } + + if (IsConnected) + { + return true; + } + + var completion = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously); + EventHandler handler = (_, _) => completion.TrySetResult(true); + OnConnected += handler; + + try + { + if (IsConnected) + { + completion.TrySetResult(true); + } + + using var timeoutSource = timeout.HasValue + ? new CancellationTokenSource(timeout.Value) + : new CancellationTokenSource(); + using var linkedSource = CancellationTokenSource.CreateLinkedTokenSource(timeoutSource.Token, cancellationToken); + using var registration = linkedSource.Token.Register(() => completion.TrySetResult(false)); + return await completion.Task.ConfigureAwait(false); + } + finally + { + OnConnected -= handler; + } + } + + public async Task ConnectAsync() + { + DebugConnection($"Attempting to connect to {_config.Host}:{_config.Port} using protocol {_config.Protocol} with SSL: {_config.UseSsl} and AES: {_config.UseAesEncryption}"); + + using var lockCts = CancellationTokenSource.CreateLinkedTokenSource(_clientCts?.Token ?? CancellationToken.None); + lockCts.CancelAfter(TimeSpan.FromSeconds(30)); + + try + { + await _connectLock.WaitAsync(lockCts.Token).ConfigureAwait(false); + } + catch (OperationCanceledException) + { + DebugConnection($"Failed to acquire connection lock within timeout for {_config.Host}:{_config.Port}"); + return false; + } + + DebugConnection($"Acquired connection lock for {_config.Host}:{_config.Port}"); + + try + { + if (_clientCts == null || _clientCts.IsCancellationRequested) + { + _clientCts?.Dispose(); + _clientCts = new CancellationTokenSource(); + } + + if (IsConnected) + { + if (_config.Protocol == ProtocolType.TCP) + { + if (_stream == null || !_stream.CanRead || !_stream.CanWrite) + { + + _connectLock.Release(); + try + { + await DisconnectClientAsync(DisconnectReason.RemoteClosed).ConfigureAwait(false); + } + finally + { + await _connectLock.WaitAsync().ConfigureAwait(false); + } + } + else + { + return true; + } + } + else + { + if (_udpClient == null) + { + IsConnected = false; + } + else + { + return true; + } + } + } + + DebugConnection($"Starting connection process for {_config.Host}:{_config.Port}"); + DebugConnection($"Cleaned up existing connection for {_config.Host}:{_config.Port}"); + _connectionCts?.Cancel(); + _connectionCts?.Dispose(); + + _connectionCts = new CancellationTokenSource(); + + DebugConnection($"Connecting to {_config.Host}:{_config.Port} using protocol {_config.Protocol}"); + bool isConnected = false; + + if (_config.Protocol == ProtocolType.TCP) + { + var result = await ConnectTcpAsync().ConfigureAwait(false); + isConnected = result; + if (!result) + { + throw new Exception("Failed to connect via TCP"); + } + } + else + { + var result = await ConnectUdpAsync().ConfigureAwait(false); + isConnected = result; + if (!result) + { + throw new Exception("Failed to connect via UDP"); + } + } + + if (isConnected) + { + DebugConnection($"Successfully connected to {_config.Host}:{_config.Port}"); + _wasConnected = true; + + if (!string.IsNullOrEmpty(Nickname)) + { + await SendNicknameAsync(Nickname).ConfigureAwait(false); + } + + DebugConnection($"Starting background tasks for {_config.Host}:{_config.Port}"); + if (_config.EnableAutoReconnect && + (_autoReconnectTask == null || _autoReconnectTask.IsCompleted || _autoReconnectTask.IsCanceled || _autoReconnectTask.IsFaulted)) + { + if (_autoReconnectSource == null || _autoReconnectSource.IsCancellationRequested) + { + _autoReconnectSource?.Dispose(); + _autoReconnectSource = new CancellationTokenSource(); + } + + _autoReconnectTask = Task.Run(() => AutoReconnectAsync(_autoReconnectSource.Token), _autoReconnectSource.Token); + } + } + + _reason = DisconnectReason.Unknown; + HandlingHelpers.SafeInvokeEventHandler( + OnConnected, + this, + new ConnectionEventArgs + { + ClientId = Nickname ?? "self", + RemoteEndPoint = GetRemoteEndPoint() + }, + nameof(OnConnected)); + + if (_config.EnableAutoHtmlReports) + { + StatusPage.StartAutoHtmlReport( + _config.HtmlReportOutputDirectory, + _config.HtmlReportIntervalSeconds, + "status-client-errors.html"); + } + + return true; + } + catch (Exception exception) + { + RecordError(exception, "Connection error"); + HandlingHelpers.SafeInvokeEventHandler( + OnGeneralError, + this, + new ErrorEventArgs + { + Exception = exception, + Message = "Connection error" + }, + nameof(OnGeneralError)); + return false; + } + finally + { + try + { + _connectLock?.Release(); + } + catch + { + + } + } + } + + private async Task CleanupExistingConnectionAsync() + { + try + { + _stream?.Close(); + _stream?.Dispose(); + _stream = null; + + if (_tcpClient != null) + { + try + { + _tcpClient?.Client?.Shutdown(SocketShutdown.Both); + } + catch + { + + } + + _tcpClient?.Close(); + _tcpClient?.Dispose(); + _tcpClient = null; + } + + if (_receiveTask != null) + { + await Task.WhenAny(_receiveTask, Task.Delay(3000)); + } + } + catch (Exception ex) + { + DebugConnection($"Error cleaning up existing connection for {_config.Host}:{_config.Port}: {ex.Message}"); + OnLog?.Invoke(this, new LogMessage { Type = LogType.Error, Message = $"Error cleaning up existing connection for {_config.Host}:{_config.Port}: {ex.Message}" }); + } + } + + private async Task ConnectTcpAsync() + { + try + { + if (IsConnected) + { + return true; + } + + int attempt = 0; + + while (_config.SSLMaxRetries == 0 || attempt < _config.SSLMaxRetries) + { + if (_clientCts != null && _clientCts.IsCancellationRequested) + { + break; + } + + attempt++; + + TcpClient tcpClient = null; + SslHandshakeDiagnostics sslDiagnostics = null; + + try + { + tcpClient = new TcpClient + { + NoDelay = !_config.EnableNagle, + ReceiveBufferSize = _config.BufferSize, + SendBufferSize = _config.BufferSize, + LingerState = new LingerOption(_config.EnableRST, 0) + }; + + if (EnableKeepAlive) + { + DebugConnection($"Enabling TCP keep-alive for {_config.Host}:{_config.Port} with KeepAliveTimeSeconds: {_config.KeepAliveTimeSeconds}, KeepAliveIntervalSeconds: {_config.KeepAliveIntervalSeconds}, KeepAliveRetryCount: {_config.KeepAliveRetryCount}"); + SocketKeepAliveConfigurator.Configure(tcpClient.Client, _config.KeepAliveTimeSeconds, _config.KeepAliveIntervalSeconds, _config.KeepAliveRetryCount); + } + + await CleanupExistingConnectionAsync().ConfigureAwait(false); + + if (_clientCts == null) + { + _clientCts = new CancellationTokenSource(); + } + + using var connectCts = CancellationTokenSource.CreateLinkedTokenSource(_clientCts.Token); + + if (_config.ConnectionTimeout.TotalMilliseconds > 0) + { + connectCts.CancelAfter(_config.ConnectionTimeout); + } +#if NET8_0_OR_GREATER + await tcpClient.ConnectAsync(_config.Host, _config.Port, connectCts.Token).ConfigureAwait(false); +#else + var connectTask = tcpClient.ConnectAsync(_config.Host, _config.Port); + var timeoutTask = Task.Delay(Timeout.Infinite, connectCts.Token); + if (await Task.WhenAny(connectTask, timeoutTask).ConfigureAwait(false) != connectTask) + { + throw new OperationCanceledException("TCP connect timed out."); + } + await connectTask.ConfigureAwait(false); +#endif + _tcpClient = tcpClient; + tcpClient = null; + + try + { + if (_tcpClient.Client?.RemoteEndPoint is IPEndPoint connectedEndPoint) + { + _resolvedEndPoint = connectedEndPoint; + } + } + catch + { + + } + + LastPongReceived = DateTime.UtcNow; + DebugConnection($"TCP connection established to {_config.Host}:{_config.Port} on attempt {attempt} using client {_tcpClient.Client.LocalEndPoint}"); + NetworkStream networkStream = _tcpClient.GetStream(); + DebugConnection($"Obtained network stream for {_config.Host}:{_config.Port} on attempt {attempt}, SSL Enabled: {_config.UseSsl}"); + + if (!_config.UseSsl) + { + _stream = networkStream; + break; + } + + var sslStream = new SslStream(networkStream, leaveInnerStreamOpen: true, _config.GetRemoteCertificateValidationCallback()); + sslDiagnostics = _config.EnableSslDiagnostics ? new SslHandshakeDiagnostics() : null; + var remoteEndPoint = _tcpClient?.Client.RemoteEndPoint?.ToString() ?? "unknown"; + sslDiagnostics?.StartHandshake(remoteEndPoint, _config.Certificate != null); + +#if NET8_0_OR_GREATER + var clientOptions = new SslClientAuthenticationOptions + { + TargetHost = _config.Host, + ClientCertificates = _config.Certificate != null ? new X509CertificateCollection { _config.Certificate } : null, + EnabledSslProtocols = SslProtocols.Tls12 | SslProtocols.Tls13, + CertificateRevocationCheckMode = _config.CheckCertificateRevocation ? X509RevocationMode.Online : X509RevocationMode.NoCheck, + AllowRenegotiation = _config.AllowTlsRenegotiation + }; + DebugConnection($"Authenticating SSL connection to {_config.Host}:{_config.Port} with SNI: {_config.Host}, Client Certificate: {(_config.Certificate != null ? "Yes" : "No")}, Enabled Protocols: {clientOptions.EnabledSslProtocols}, Check Certificate Revocation: {_config.CheckCertificateRevocation}"); + sslDiagnostics?.StartStage("ClientAuth"); + await sslStream.AuthenticateAsClientAsync(clientOptions).ConfigureAwait(false); + sslDiagnostics?.EndStage("ClientAuth"); +#else + sslDiagnostics?.StartStage("ClientAuth"); + if (_config.Certificate != null) + { + await sslStream.AuthenticateAsClientAsync(_config.Host, new X509CertificateCollection { _config.Certificate }, SslProtocols.Tls12 | SslProtocols.Tls13, _config.CheckCertificateRevocation).ConfigureAwait(false); + } + else + { + await sslStream.AuthenticateAsClientAsync(_config.Host, null, SslProtocols.Tls12 | SslProtocols.Tls13, _config.CheckCertificateRevocation).ConfigureAwait(false); + } + sslDiagnostics?.EndStage("ClientAuth"); +#endif + + DebugConnection($"SSL authentication successful for {_config.Host}:{_config.Port} using SNI: {_config.Host}, Client Certificate: {(_config.Certificate != null ? "Yes" : "No")}, Enabled Protocols: {(sslStream.SslProtocol)}, Cipher Algorithm: {sslStream.CipherAlgorithm}, Hash Algorithm: {sslStream.HashAlgorithm}, Key Exchange Algorithm: {sslStream.KeyExchangeAlgorithm}"); + sslDiagnostics?.RecordSuccess(sslStream); + if (sslDiagnostics != null) + { + DebugConnection($"[SSL Metrics] {sslDiagnostics}"); + } + _stream = sslStream; + break; + } + catch (SocketException socketEx) + { + var errorMsg = $"Socket error on TCP connect attempt {attempt}: {socketEx.SocketErrorCode} - {socketEx.SocketErrorCode switch { SocketError.ConnectionRefused => "Connection refused - server not listening or firewall blocked", SocketError.HostUnreachable => "Host unreachable - network unreachable or no route to host", SocketError.NetworkUnreachable => "Network unreachable", SocketError.TimedOut => "Connection attempt timed out", _ => "Unknown socket error" }}"; + RecordError(socketEx, errorMsg); + DebugConnection($"[Attempt {attempt}] Socket error: {socketEx.SocketErrorCode} - {socketEx.Message}"); + OnLog?.Invoke(this, new LogMessage { Type = LogType.Error, Message = $"[Attempt {attempt}] TCP connection failed (SocketError={socketEx.SocketErrorCode}): {socketEx.Message}, cannot connect to {_config.Host}:{_config.Port}" }); + if (_config.SSLMaxRetries != 0 && attempt >= _config.SSLMaxRetries) + { + throw; + } + } + catch (IOException ioEx) when (ioEx.InnerException is SocketException innerSocketEx) + { + var errorMsg = $"Socket IO error on TCP connect attempt {attempt}: {innerSocketEx.SocketErrorCode} - {innerSocketEx.SocketErrorCode switch { SocketError.ConnectionRefused => "Connection refused", SocketError.HostUnreachable => "Host unreachable", _ => "Unknown socket error" }}"; + RecordError(ioEx, errorMsg); + DebugConnection($"[Attempt {attempt}] Socket IO error: {innerSocketEx.SocketErrorCode} - {ioEx.Message}"); + OnLog?.Invoke(this, new LogMessage { Type = LogType.Error, Message = $"[Attempt {attempt}] TCP connection failed (SocketError={innerSocketEx.SocketErrorCode}): {ioEx.Message}, cannot connect to {_config.Host}:{_config.Port}" }); + if (_config.SSLMaxRetries != 0 && attempt >= _config.SSLMaxRetries) + { + throw; + } + } + catch (Exception ex) + { + var isRecoverable = _config.UseSsl ? Helpers.SslHandshakeDiagnostics.IsRecoverableFailure(ex) : false; + sslDiagnostics?.RecordFailure(ex, isRecoverable); + + RecordError(ex, $"Connection error on attempt {attempt}: {ex.GetType().Name} - {ex.Message}", isSslError: _config.UseSsl); + if (_config.UseSsl) + { + + string serverSslError = null; + try + { + var rawStream = _tcpClient?.GetStream(); + if (rawStream != null && rawStream.DataAvailable) + { + var buffer = new byte[1024]; + var totalBytes = await rawStream.ReadAsync(buffer, 0, buffer.Length).ConfigureAwait(false); + if (totalBytes > 0) + { + var message = Encoding.UTF8.GetString(buffer, 0, totalBytes); + if (message.Contains(Configuration.SSL_ERROR_PREFIX)) + { + var startIndex = message.IndexOf(Configuration.SSL_ERROR_PREFIX, StringComparison.Ordinal) + Configuration.SSL_ERROR_PREFIX.Length; + var endIndex = message.IndexOf(Configuration.SSL_ERROR_SUFFIX, StringComparison.Ordinal); + if (endIndex > startIndex) + { + serverSslError = message.Substring(startIndex, endIndex - startIndex); + } + } + } + } + } + catch (Exception readEx) + { + DebugConnection($"Unable to read SSL error notification from server: {readEx.GetType().Name}"); + } + + try + { + var rawStream = _tcpClient?.GetStream(); + if (rawStream != null) + { + var notification = Encoding.UTF8.GetBytes($"{Configuration.SSL_ERROR_PREFIX}Client SSL error: {ex.GetType().Name} - {ex.Message}{Configuration.SSL_ERROR_SUFFIX}"); + await rawStream.WriteAsync(notification, 0, notification.Length).ConfigureAwait(false); + await rawStream.FlushAsync().ConfigureAwait(false); + } + } + catch (Exception sendEx) + { + DebugConnection($"Unable to send SSL error notification to server: {sendEx.GetType().Name}"); + } + + HandlingHelpers.SafeInvokeEventHandler( + OnSslError, + this, + new ErrorEventArgs + { + Exception = ex, + Message = serverSslError != null + ? $"SSL connection error on attempt {attempt}. Server reported: {serverSslError}" + : $"SSL connection error on attempt {attempt}: {ex.GetType().Name} - {ex.Message}" + }, + nameof(OnSslError)); + } + else + { + HandlingHelpers.SafeInvokeEventHandler( + OnGeneralError, + this, + new ErrorEventArgs + { + Exception = ex, + Message = $"TCP connection error on attempt {attempt}: {ex.GetType().Name} - {ex.Message}" + }, + nameof(OnGeneralError)); + } + OnLog?.Invoke(this, new LogMessage { Type = LogType.Error, Message = $"[Attempt {attempt}] TCP connection failed: {ex.GetType().Name} - {ex.Message}, cannot connect to {_config.Host}:{_config.Port}" }); + if (_config.SSLMaxRetries != 0 && attempt >= _config.SSLMaxRetries) + { + throw; + } + } + finally + { + try { tcpClient?.Close(); tcpClient?.Dispose(); } catch { } + tcpClient = null; + } + await Task.Delay(_config.SSLRetryDelayInSeconds * 1000).ConfigureAwait(false); + } + + if (_config.UseAesEncryption) + { + _aesEncryption?.Dispose(); + _aesEncryption = await AesKeyExchange.ReceiveAesKeyAsync(_stream, _config.AesPassword).ConfigureAwait(false); + } + + ConnectionTime = DateTime.UtcNow; + LastPongReceived = DateTime.UtcNow; + _hasReceivedPongSinceConnection = false; + UpdateLastActive(); + + IsConnected = true; + + _connectionCts ??= new CancellationTokenSource(); + + _receiveTask = Task.Run(async () => await ReceiveDataAsync(_connectionCts.Token)); + + if (_config.EnableHeartbeat) + { + _pingTask = Task.Run(() => StartPingLoopAsync(_connectionCts.Token)); + _pongTask = Task.Run(() => StartPongLoop(_connectionCts.Token)); + } + return true; + } + catch (Exception ex) + { + DebugConnection($"ConnectTcpAsync: Unexpected error: {ex.GetType().Name} - {ex.Message}"); + RecordError(ex, $"TCP connection error: {ex.Message}"); + return false; + } + } + + private void UpdateLastActive() + { + LastActive = DateTime.UtcNow; + } + + private void MarkDataReceived() + { + var now = DateTime.UtcNow; + LastActive = now; + LastDataReceived = now; + } + + private void MarkDataSent() + { + var now = DateTime.UtcNow; + LastActive = now; + LastDataSent = now; + } + + private async Task CancelAndWaitAsync() + { + _connectionCts?.Cancel(); + _connectionCts?.Dispose(); + _connectionCts = null; + + await Task.WhenAll( + SafeTaskCompletion(_pingTask), + SafeTaskCompletion(_pongTask), + SafeTaskCompletion(_receiveTask) + ); + } + + public async ValueTask DisposeAsync() + { + if (_disposed) + { + return; + } + + _disposed = true; + + try + { + DebugConnection($"DisposeAsync: Starting cleanup for {_config.Host}:{_config.Port}"); + + _clientCts?.Cancel(); + + await SafeTaskCompletion(_autoReconnectTask); + try + { + _autoReconnectTask?.Dispose(); + } + catch (Exception ex) + { + DebugConnection($"DisposeAsync: Error disposing auto reconnect task: {ex.Message}"); + } + + _autoReconnectTask = null; + + await DisconnectClientAsync(); + await CleanupAsync(); + + _clientCts?.Dispose(); + _clientCts = null; + + _autoReconnectSource?.Cancel(); + _autoReconnectSource?.Dispose(); + _autoReconnectSource = null; + + await SafeTaskCompletion(_pingTask); + await SafeTaskCompletion(_pongTask); + + _pingTask?.Dispose(); + _pongTask?.Dispose(); + _pingTask = null; + _pongTask = null; + + try + { + _connectLock?.Dispose(); + _streamWriteLock?.Dispose(); + _disconnectLock?.Dispose(); + _aesEncryption?.Dispose(); + } + catch (Exception ex) + { + DebugConnection($"DisposeAsync: Error disposing locks: {ex.Message}"); + } + + HealthApi?.Dispose(); + + OnConnected = null; + OnDisconnected = null; + OnDataReceived = null; + OnGeneralError = null; + OnPingResponse = null; + OnPongResponse = null; + OnSslError = null; + OnEncryptionError = null; + OnNicknameSend = null; + OnSocketError = null; + + DebugConnection($"DisposeAsync: Cleanup completed for {_config.Host}:{_config.Port}"); + } + catch (Exception ex) + { + DebugConnection($"DisposeAsync: Unexpected error during cleanup: {ex.GetType().Name} - {ex.Message}"); + } + finally + { + GC.SuppressFinalize(this); + } + } + + private async Task CleanupAsync() + { + IsConnected = false; + await CancelAndWaitAsync(); + + if (_pingTask != null) + { + await Task.WhenAny(_pingTask, Task.Delay(3000)); + } + + if (_pongTask != null) + { + await Task.WhenAny(_pongTask, Task.Delay(3000)); + } + + _pingTask?.Dispose(); + _pongTask?.Dispose(); + _receiveTask?.Dispose(); + + _pingTask = null; + _pongTask = null; + _receiveTask = null; + + _tcpClient?.Close(); + _tcpClient?.Dispose(); + _tcpClient = null; + + _udpClient?.Close(); + _udpClient?.Dispose(); + _udpClient = null; + + _stream?.Close(); + _stream?.Dispose(); + _stream = null; + + _utf8Decoder.Reset(); + _aesEncryption?.Dispose(); + _aesEncryption = null; + + _stopAutoReconnecting = false; + } + + public string IpAddress => _config != null ? _config.Host : string.Empty; + public int Port => _config != null ? _config.Port : 0; + public string Nickname { get; private set; } + public bool DEBUG_DATA_SEND { get; set; } + public bool DEBUG_DATA_RECEIVED { get; set; } + public DateTime LastPongReceived { get; private set; } + public DateTime LastPingSent { get; private set; } + public bool DisconnectOnMissedPong { get; set; } + + private long _lastDataSentTicks; + private long _lastDataReceivedTicks; + private long _disconnectionTimeTicks; + + public DateTime LastDataSent + { + get => new DateTime(Interlocked.Read(ref _lastDataSentTicks)); + private set => Interlocked.Exchange(ref _lastDataSentTicks, value.Ticks); + } + + public DateTime LastDataReceived + { + get => new DateTime(Interlocked.Read(ref _lastDataReceivedTicks)); + private set => Interlocked.Exchange(ref _lastDataReceivedTicks, value.Ticks); + } + + public DateTime DisconnectionTime + { + get => new DateTime(Interlocked.Read(ref _disconnectionTimeTicks)); + private set => Interlocked.Exchange(ref _disconnectionTimeTicks, value.Ticks); + } + public bool IsAutoConnectStarted { get; private set; } + private DateTime _lastIdleLogUtc; + private CancellationTokenSource _autoReconnectSource; + private bool _hasReceivedPongSinceConnection; + + public bool EnableKeepAlive { get; set; } = true; + + private async Task ConnectUdpAsync() + { + try + { + DebugConnection($"Attempting UDP connection to {_config.Host}:{_config.Port}"); + + _udpClient = new UdpClient(); + _udpClient.EnableBroadcast = _config.EnableBroadcast; + _udpClient.Client.ReceiveBufferSize = _config.BufferSize; + _udpClient.Client.SendBufferSize = _config.BufferSize; + + try + { + _udpClient.Connect(_config.Host, _config.Port); + } + catch (SocketException socketEx) + { + var errorMsg = $"UDP connection failed: {socketEx.SocketErrorCode} - {socketEx.SocketErrorCode switch { SocketError.ConnectionRefused => "Connection refused - server not listening", SocketError.HostUnreachable => "Host unreachable", SocketError.NetworkUnreachable => "Network unreachable", _ => "Unknown socket error" }}"; + DebugConnection($"UDP connection socket error: {socketEx.SocketErrorCode} - {socketEx.Message}"); + RecordError(socketEx, errorMsg); + HandlingHelpers.SafeInvokeEventHandler( + OnGeneralError, + this, + new ErrorEventArgs { Exception = socketEx, Message = errorMsg }, + nameof(OnGeneralError)); + + try { _udpClient?.Close(); _udpClient?.Dispose(); } catch { } + _udpClient = null; + return false; + } + catch (Exception ex) + { + var errorMsg = $"UDP connection error: {ex.GetType().Name} - {ex.Message}"; + DebugConnection($"UDP connection failed: {ex.GetType().Name} - {ex.Message}"); + RecordError(ex, errorMsg); + HandlingHelpers.SafeInvokeEventHandler( + OnGeneralError, + this, + new ErrorEventArgs { Exception = ex, Message = errorMsg }, + nameof(OnGeneralError)); + + try { _udpClient?.Close(); _udpClient?.Dispose(); } catch { } + _udpClient = null; + return false; + } + + try + { + if (_udpClient.Client?.RemoteEndPoint is IPEndPoint connectedUdpEndPoint) + { + _resolvedEndPoint = connectedUdpEndPoint; + } + } + catch + { + + } + + ConnectionTime = DateTime.UtcNow; + LastPongReceived = DateTime.UtcNow; + _hasReceivedPongSinceConnection = false; + UpdateLastActive(); + + DebugConnection($"UDP connection established to {_config.Host}:{_config.Port}"); + + _ = Task.Run(() => ReceiveUdpDataAsync(), _connectionCts.Token); + + if (_config.EnableHeartbeat) + { + _pingTask = Task.Run(() => StartPingLoopAsync(_connectionCts.Token)); + _pongTask = Task.Run(() => StartPongLoop(_connectionCts.Token)); + } + + IsConnected = true; + HandlingHelpers.SafeInvokeEventHandler( + OnConnected, + this, + new ConnectionEventArgs { ClientId = "self", RemoteEndPoint = GetRemoteEndPoint() }, + nameof(OnConnected)); + return true; + } + catch (Exception exception) + { + DebugConnection($"Unexpected error during UDP connection: {exception.GetType().Name} - {exception.Message}"); + RecordError(exception, $"UDP connection error: {exception.GetType().Name} - {exception.Message}"); + HandlingHelpers.SafeInvokeEventHandler( + OnGeneralError, + this, + new ErrorEventArgs { Exception = exception, Message = $"UDP connection error: {exception.GetType().Name}" }, + nameof(OnGeneralError)); + + try { _udpClient?.Close(); _udpClient?.Dispose(); } catch { } + _udpClient = null; + return false; + } + } + public async Task DisconnectAsync() => await DisconnectClientAsync(DisconnectReason.ClientRequested).ConfigureAwait(false); + + public async Task DisconnectDueTimeoutAsync() => await DisconnectClientAsync(DisconnectReason.Timeout).ConfigureAwait(false); + + private async Task DisconnectClientAsync( + DisconnectReason reason = DisconnectReason.LocalClosed, + Exception exception = null) + { + if (!await _disconnectLock.WaitAsync(0).ConfigureAwait(false)) + { + DebugConnection("DisconnectClientAsync: disconnect already in progress, skipping duplicate call."); + return; + } + + try + { + if (!IsConnected && _stream == null && _tcpClient == null && _udpClient == null) + { + + return; + } + + DisconnectionTime = DateTime.UtcNow; + IsConnected = false; + _reason = reason; + + var disconnectedEndPoint = GetRemoteEndPoint(); + + if (reason == DisconnectReason.ClientRequested || reason == DisconnectReason.LocalClosed) + { + _autoReconnectSource?.Cancel(); + } + + try + { + _connectionCts?.Cancel(); + } + catch + { + + } + + try + { + _connectionCts?.Dispose(); + } + catch + { + + } + _connectionCts = null; + + try + { + _stream?.Close(); + _stream?.Dispose(); + _stream = null; + } + catch + { + + } + + try + { + if (_tcpClient != null) + { + try + { + _tcpClient.Client?.Shutdown(System.Net.Sockets.SocketShutdown.Both); + } + catch + { + + } + + _tcpClient.Close(); + _tcpClient.Dispose(); + _tcpClient = null; + } + } + catch + { + + } + + try + { + _udpClient?.Close(); + _udpClient?.Dispose(); + _udpClient = null; + } + catch + { + + } + + var determinedReason = ConnectionEventArgs.Determine(reason, exception); + var initiator = DisconnectionDiagnostics.DetermineInitiator(determinedReason, exception); + var reasonDetails = DisconnectionDiagnostics.GetDetailedReasonDescription(determinedReason, exception); + + var diagnosticContext = new Dictionary(); + 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 connectionEventArgs = new ConnectionEventArgs + { + ClientId = "self", + RemoteEndPoint = disconnectedEndPoint, + Reason = determinedReason, + Exception = exception, + Initiator = initiator, + ReasonDetails = reasonDetails, + DiagnosticContext = diagnosticContext + }; + + try + { + var clientLogger = ConnectionLogManager.GetClientLogger(); + var localEndPoint = _tcpClient?.Client?.LocalEndPoint?.ToString() ?? + _udpClient?.Client?.LocalEndPoint?.ToString() ?? + "[Unknown]"; + clientLogger.LogDisconnection( + "self", + "[Client]", + disconnectedEndPoint?.ToString() ?? "[Unknown]", + 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)); + + StatusPage.StopAutoHtmlReport(); + HealthApi.Stop(); + } + finally + { + _disconnectLock.Release(); + } + } + + private async Task SafeTaskCompletion(Task task) + { + if (task == null) + { + return; + } + + try + { + await task.ConfigureAwait(false); + } + catch + { + + } + } + public void Dispose() + { + Dispose(true); + GC.SuppressFinalize(this); + } + + protected virtual void Dispose(bool disposing) + { + if (!disposing) + { + return; + } + + try + { + _clientCts?.Cancel(); + _autoReconnectSource?.Cancel(); + _connectionCts?.Cancel(); + } + catch + { + + } + + try { _stream?.Close(); _stream?.Dispose(); _stream = null; } catch { } + try + { + if (_tcpClient != null) + { + try { _tcpClient.Client?.Shutdown(SocketShutdown.Both); } catch { } + _tcpClient.Close(); + _tcpClient.Dispose(); + _tcpClient = null; + } + } + catch { } + try { _udpClient?.Close(); _udpClient?.Dispose(); _udpClient = null; } catch { } + try { _aesEncryption?.Dispose(); _aesEncryption = null; } catch { } + + try { _clientCts?.Dispose(); _clientCts = null; } catch { } + try { _autoReconnectSource?.Dispose(); _autoReconnectSource = null; } catch { } + try { _connectionCts?.Dispose(); _connectionCts = null; } catch { } + + try { _connectLock?.Dispose(); } catch { } + try { _connectionAttemptLock?.Dispose(); } catch { } + try { _streamWriteLock?.Dispose(); } catch { } + try { _disconnectLock?.Dispose(); } catch { } + + HealthApi.Dispose(); + } + + } +} diff --git a/EonaCat.Connections/Client/NetworkClient.Diagnostics.cs b/EonaCat.Connections/Client/NetworkClient.Diagnostics.cs new file mode 100644 index 0000000..3f3a16e --- /dev/null +++ b/EonaCat.Connections/Client/NetworkClient.Diagnostics.cs @@ -0,0 +1,73 @@ +using EonaCat.Connections.Models; +using System.Net.Sockets; +using ErrorEventArgs = EonaCat.Connections.EventArguments.ErrorEventArgs; + +namespace EonaCat.Connections +{ + public partial class NetworkClient + { + private static void FireAndForget(Task task, string context) + { + if (task == null) + { + return; + } + + if (task.IsCompleted) + { + if (task.IsFaulted) + { + OnLog?.Invoke(null, new LogMessage { Type = LogType.Error, Message = $"Unobserved exception in {context}: {task.Exception?.Flatten().Message}" }); + } + return; + } + + _ = task.ContinueWith(t => + { + OnLog?.Invoke(null, new LogMessage { Type = LogType.Error, Message = $"Unobserved exception in {context}: {t.Exception?.Flatten().Message}" }); + }, CancellationToken.None, TaskContinuationOptions.OnlyOnFaulted | TaskContinuationOptions.ExecuteSynchronously, TaskScheduler.Default); + } + private void DebugConnection(string debugText) + { + if (!_config.EnableConnectionDebugLogs) + { + return; + } + OnLog?.Invoke(this, new LogMessage { Type = LogType.Debug, Message = $"[NetworkClient] {debugText}" }); + } + + private void RecordError(Exception exception, string message, string clientId = null, string nickname = null, bool isSslError = false) + { + var socketEx = exception as SocketException + ?? (exception as IOException)?.InnerException as SocketException; + + var entry = new SocketErrorEntry + { + Timestamp = DateTime.UtcNow, + Source = "Client", + ClientId = clientId ?? Nickname ?? "self", + Nickname = nickname ?? Nickname, + SocketErrorCode = socketEx?.SocketErrorCode, + ErrorCode = socketEx != null ? socketEx.SocketErrorCode.ToString() : exception?.GetType().Name, + Message = message, + ExceptionType = exception?.GetType().FullName, + StackTrace = exception?.StackTrace, + Exception = exception, + IsSslError = isSslError + }; + + StatusPage.AddError(entry); + + if (socketEx != null) + { + OnSocketError?.Invoke(this, new ErrorEventArgs + { + ClientId = entry.ClientId, + Nickname = entry.Nickname, + Exception = exception, + Message = $"SocketError {socketEx.SocketErrorCode}: {message}" + }); + } + } + } +} diff --git a/EonaCat.Connections/Client/NetworkClient.Heartbeat.cs b/EonaCat.Connections/Client/NetworkClient.Heartbeat.cs new file mode 100644 index 0000000..d30d9cd --- /dev/null +++ b/EonaCat.Connections/Client/NetworkClient.Heartbeat.cs @@ -0,0 +1,225 @@ +using EonaCat.Connections.EventArguments; +using EonaCat.Connections.Helpers; +using EonaCat.Connections.Models; +using System.Text; +using ErrorEventArgs = EonaCat.Connections.EventArguments.ErrorEventArgs; + +namespace EonaCat.Connections +{ + public partial class NetworkClient + { + private async Task StartPingLoopAsync(CancellationToken token) + { + var interval = TimeSpan.FromSeconds(_config.HeartbeatIntervalSeconds); + var next = DateTime.UtcNow + interval; + + try + { + while (!token.IsCancellationRequested && IsConnected) + { + try + { + if (_stream == null || !_stream.CanWrite) + { + DebugConnection("Ping loop stopping - stream not available for writing"); + break; + } + + var result = await SendInternalAsync(PingBytes, token).ConfigureAwait(false); + + if (result) + { + LastPingSent = DateTime.UtcNow; + if (_config.EnablePingPongLogs) + { + OnLog?.Invoke(this, new LogMessage { Type = LogType.Debug, Message = $"[PING] Sent at {DateTime.UtcNow:O}" }); + } + } + else + { + DebugConnection("Ping loop failed to send ping - will retry on next interval"); + } + + var delay = next - DateTime.UtcNow; + if (delay > TimeSpan.Zero) + { + await Task.Delay(delay, token).ConfigureAwait(false); + } + + next += interval; + } + catch (OperationCanceledException) + { + DebugConnection($"Ping loop: Operation canceled for {_config.Host}:{_config.Port}"); + break; + } + catch (Exception exception) + { + DebugConnection($"Ping loop: Error sending ping to {_config.Host}:{_config.Port}: {exception.GetType().Name} - {exception.Message}"); + RecordError(exception, $"Ping loop error: {exception.GetType().Name} - {exception.Message}"); + OnLog?.Invoke(this, new LogMessage { Type = LogType.Error, Message = $"[PING] Error sending ping: {exception.GetType().Name} - {exception.Message}" }); + break; + } + } + } + catch (Exception ex) + { + DebugConnection($"Ping loop: Unexpected error: {ex.GetType().Name} - {ex.Message}"); + RecordError(ex, $"Ping loop unexpected error: {ex.GetType().Name}"); + } + finally + { + DebugConnection("Ping loop stopped."); + } + } + + private async Task StartPongLoop(CancellationToken token) + { + var interval = TimeSpan.FromSeconds(1); + var next = DateTime.UtcNow + interval; + + try + { + while (!token.IsCancellationRequested) + { + try + { + if (!IsConnected) + { + DebugConnection("Pong loop stopping - client disconnected"); + break; + } + + var elapsed = (DateTime.UtcNow - LastPongReceived).TotalSeconds; + + if (_hasReceivedPongSinceConnection && + elapsed > _config.HeartbeatIntervalSeconds * 5) + { + + var msg = $"No PONG received for {elapsed:F1}s (threshold: {_config.HeartbeatIntervalSeconds * 5}s) - connection is stale"; + DebugConnection($"Pong monitor: {msg}"); + RecordError(null, msg); + + var disconnectReason = DisconnectOnMissedPong ? DisconnectReason.NoPongReceived : DisconnectReason.Timeout; + await DisconnectClientAsync(disconnectReason); + break; + } + + var delay = next - DateTime.UtcNow; + if (delay > TimeSpan.Zero) + { + await Task.Delay(delay, token); + } + + next += interval; + } + catch (OperationCanceledException) + { + DebugConnection($"Pong loop: Operation canceled for {_config.Host}:{_config.Port}"); + break; + } + catch (Exception ex) + { + DebugConnection($"Pong loop: Error monitoring pong for {_config.Host}:{_config.Port}: {ex.GetType().Name} - {ex.Message}"); + RecordError(ex, $"Pong loop error: {ex.GetType().Name} - {ex.Message}"); + await DisconnectClientAsync(DisconnectReason.Error, ex); + break; + } + } + } + catch (Exception ex) + { + DebugConnection($"Pong loop: Unexpected error: {ex.GetType().Name} - {ex.Message}"); + RecordError(ex, $"Pong loop unexpected error: {ex.GetType().Name}"); + } + finally + { + DebugConnection("Pong loop stopped."); + } + } + + + private byte[] HandleHeartbeat(byte[] data, out bool hasHeartbeat) + { + hasHeartbeat = false; + if (!_config.EnableHeartbeat || data == null || data.Length == 0) + { + return data; + } + + string text = null; + + try + { + text = Encoding.UTF8.GetString(data); + } + catch + { + + } + + if (string.IsNullOrEmpty(text)) + { + return data; + } + + if (text.Contains("[DISCONNECT]", StringComparison.OrdinalIgnoreCase)) + { + FireAndForget(DisconnectClientAsync(DisconnectReason.RemoteClosed), "heartbeat DISCONNECT"); + hasHeartbeat = true; + } + if (text.Contains(Configuration.SSL_ERROR_PREFIX, StringComparison.OrdinalIgnoreCase)) + { + string sslError = null; + var startIdx = text.IndexOf(Configuration.SSL_ERROR_PREFIX, StringComparison.Ordinal) + Configuration.SSL_ERROR_PREFIX.Length; + var endIdx = text.IndexOf(Configuration.SSL_ERROR_SUFFIX, StringComparison.Ordinal); + if (endIdx > startIdx) + { + sslError = text.Substring(startIdx, endIdx - startIdx); + } + RecordError(null, $"Server reported SSL error: {sslError ?? text}", isSslError: true); + HandlingHelpers.SafeInvokeEventHandler( + OnSslError, + this, + new ErrorEventArgs + { + Message = $"Server reported SSL error: {sslError ?? text}" + }, + nameof(OnSslError)); + FireAndForget(DisconnectClientAsync(DisconnectReason.SSLError), "heartbeat SSL error disconnect"); + hasHeartbeat = true; + } + if (text.Contains(Configuration.PING_VALUE)) + { + hasHeartbeat = true; + FireAndForget(SendAsync(Configuration.PONG_VALUE), "heartbeat PONG send"); + if (_config.EnablePingPongLogs) + { + OnLog?.Invoke(this, new LogMessage { Type = LogType.Debug, Message = "PING received. Sent PONG response." }); + } + } + if (text.Contains(Configuration.PONG_VALUE)) + { + hasHeartbeat = true; + var now = DateTime.UtcNow; + OnPingResponse?.Invoke(this, new PingEventArgs + { + Id = "server", + Nickname = Nickname, + ReceivedTime = now, + RemoteEndPoint = GetRemoteEndPoint() + }); + if (_config.EnablePingPongLogs) + { + OnLog?.Invoke(this, new LogMessage { Type = LogType.Debug, Message = "PONG received." }); + } + } + if (hasHeartbeat && !string.IsNullOrEmpty(text)) + { + text = text.Replace(Configuration.PING_VALUE, string.Empty).Replace(Configuration.PONG_VALUE, string.Empty).Replace("[DISCONNECT]", string.Empty); + data = Encoding.UTF8.GetBytes(text); + } + return data; + } + } +} diff --git a/EonaCat.Connections/Client/NetworkClient.Receiving.cs b/EonaCat.Connections/Client/NetworkClient.Receiving.cs new file mode 100644 index 0000000..e94b13e --- /dev/null +++ b/EonaCat.Connections/Client/NetworkClient.Receiving.cs @@ -0,0 +1,679 @@ +using EonaCat.Connections.EventArguments; +using EonaCat.Connections.Framing; +using EonaCat.Connections.Helpers; +using EonaCat.Connections.Models; +using System.Buffers; +using System.Net; +using System.Net.Sockets; +using System.Text; +using ErrorEventArgs = EonaCat.Connections.EventArguments.ErrorEventArgs; + +namespace EonaCat.Connections +{ + public partial class NetworkClient + { + private async Task ReceiveDataAsync(CancellationToken token) + { + DebugConnection($"ReceiveDataAsync started for {_config.Host}:{_config.Port} with framing mode {_config.MessageFraming}"); + + try + { + switch (_config.MessageFraming) + { + case FramingMode.LengthPrefixed: + await ReceiveLengthPrefixedAsync(token); + break; + + case FramingMode.Delimiter: + await ReceiveDelimiterAsync(token); + break; + + case FramingMode.None: + await ReceiveNoneAsync(token); + break; + } + } + catch (OperationCanceledException ex) + { + DebugConnection("Receive loop cancelled by cancellation token."); + RecordError(ex, "Receive loop cancellation requested"); + } + catch (SocketException socketEx) + { + var errorMsg = $"Socket error in receive loop: {socketEx.SocketErrorCode} - {socketEx.SocketErrorCode switch { SocketError.ConnectionReset => "Connection reset by remote", SocketError.ConnectionAborted => "Connection aborted", SocketError.TimedOut => "Receive timeout", _ => "Unknown socket error" }}"; + RecordError(socketEx, errorMsg); + DebugConnection($"Receive loop socket error: {socketEx.SocketErrorCode} - {socketEx.Message}"); + var reason = socketEx.SocketErrorCode == SocketError.ConnectionReset || socketEx.SocketErrorCode == SocketError.ConnectionAborted + ? DisconnectReason.RemoteClosed + : DisconnectReason.Error; + await DisconnectClientAsync(reason, socketEx); + } + catch (IOException ioEx) when (ioEx.InnerException is SocketException innerSocketEx) + { + var errorMsg = $"Socket IO error in receive loop: {innerSocketEx.SocketErrorCode} - {innerSocketEx.SocketErrorCode switch { SocketError.ConnectionReset => "Connection reset", SocketError.ConnectionAborted => "Connection aborted", _ => "Unknown socket error" }}"; + RecordError(ioEx, errorMsg); + DebugConnection($"Receive loop socket IO error: {innerSocketEx.SocketErrorCode} - {ioEx.Message}"); + var reason = innerSocketEx.SocketErrorCode == SocketError.ConnectionReset + || innerSocketEx.SocketErrorCode == SocketError.ConnectionAborted + ? DisconnectReason.RemoteClosed + : DisconnectReason.Error; + await DisconnectClientAsync(reason, ioEx); + } + catch (IOException ioEx) + { + DebugConnection($"IO error in receive loop: {ioEx.GetType().Name} - {ioEx.Message}"); + RecordError(ioEx, $"IO error in receive loop: {ioEx.GetType().Name}"); + await DisconnectClientAsync(DisconnectReason.Error, ioEx); + } + catch (Exception ex) + { + DebugConnection($"Unexpected error in receive loop: {ex.GetType().Name} - {ex.Message}"); + RecordError(ex, $"Receive loop error: {ex.GetType().Name} - {ex.Message}"); + await DisconnectClientAsync(DisconnectReason.Error, ex); + } + finally + { + DebugConnection("Receive loop exited."); + } + } + + private async Task ReceiveLengthPrefixedAsync(CancellationToken token) + { + int prefixSize = _config.LengthPrefixedLength; + + if (prefixSize < 1 || prefixSize > 8) + { + throw new InvalidOperationException("LengthPrefixedLength must be between 1 and 8."); + } + + byte[] lengthBuffer = ArrayPool.Shared.Rent(prefixSize); + + try + { + while (!token.IsCancellationRequested && IsConnected) + { + var stream = _stream; + if (stream == null || !stream.CanRead) + { + break; + } + + CancellationToken readToken = token; + using var cts = _config.ReadTimeoutSeconds > 0 + ? CancellationTokenSource.CreateLinkedTokenSource(token) + : null; + if (cts != null) + { + cts.CancelAfter(TimeSpan.FromSeconds(_config.ReadTimeoutSeconds)); + readToken = cts.Token; + } + + await ReadExactAsync(stream, lengthBuffer, 0, prefixSize, readToken).ConfigureAwait(false); + + long length = ParseLengthPrefix(lengthBuffer, prefixSize, _config.UseBigEndian); + + if (length <= 0 || length > _config.MAX_MESSAGE_SIZE) + { + throw new InvalidOperationException($"Invalid message length {length}"); + } + + byte[] buffer = ArrayPool.Shared.Rent((int)length); + + try + { + await ReadExactAsync(stream, buffer, 0, (int)length, readToken).ConfigureAwait(false); + + if (_config.UseAesEncryption && _aesEncryption != null) + { + var decrypted = await AesKeyExchange.DecryptDataAsync(buffer.AsSpan(0, (int)length).ToArray(), (int)length, _aesEncryption).ConfigureAwait(false); + await ProcessReceivedDataAsync(decrypted).ConfigureAwait(false); + } + else + { + await ProcessReceivedDataAsync(buffer.AsMemory(0, (int)length)).ConfigureAwait(false); + } + + MarkDataReceived(); + } + finally + { + ArrayPool.Shared.Return(buffer); + } + } + } + catch (OperationCanceledException ex) + { + DebugConnection($"Length-prefixed read timeout: {ex.Message}"); + RecordError(ex, "Read timeout during length-prefixed receive - stream may have hung"); + await DisconnectClientAsync(DisconnectReason.Timeout, ex); + } + catch (SocketException socketEx) + { + DebugConnection($"Socket error in length-prefixed receive: {socketEx.SocketErrorCode} - {socketEx.Message}"); + RecordError(socketEx, $"Socket error in length-prefixed receive: {socketEx.SocketErrorCode} - {socketEx.SocketErrorCode switch { SocketError.ConnectionReset => "Connection reset by remote", SocketError.ConnectionAborted => "Connection aborted", _ => "Unknown socket error" }}"); + var reason = socketEx.SocketErrorCode == SocketError.ConnectionReset || socketEx.SocketErrorCode == SocketError.ConnectionAborted + ? DisconnectReason.RemoteClosed + : DisconnectReason.Error; + await DisconnectClientAsync(reason, socketEx); + } + catch (IOException ex) when (ex.InnerException is SocketException innerSocketEx) + { + DebugConnection($"Socket IO error in length-prefixed receive: {innerSocketEx.SocketErrorCode} - {ex.Message}"); + RecordError(ex, $"Socket IO error in length-prefixed receive: {innerSocketEx.SocketErrorCode} - {innerSocketEx.SocketErrorCode switch { SocketError.ConnectionReset => "Connection reset", SocketError.ConnectionAborted => "Connection aborted", _ => "Unknown socket error" }}"); + var reason = innerSocketEx.SocketErrorCode == SocketError.ConnectionReset + || innerSocketEx.SocketErrorCode == SocketError.ConnectionAborted + ? DisconnectReason.RemoteClosed + : DisconnectReason.Error; + await DisconnectClientAsync(reason, ex); + } + catch (IOException ex) + { + DebugConnection($"Connection closed during length-prefixed receive: {ex.GetType().Name} - {ex.Message}"); + RecordError(ex, "Connection closed during length-prefixed receive"); + await DisconnectClientAsync(DisconnectReason.RemoteClosed, ex); + } + catch (Exception ex) + { + DebugConnection($"Unexpected error in length-prefixed receive: {ex.GetType().Name} - {ex.Message}"); + RecordError(ex, $"Unexpected error in length-prefixed receive: {ex.GetType().Name} - {ex.Message}"); + await DisconnectClientAsync(DisconnectReason.Error, ex); + } + finally + { + ArrayPool.Shared.Return(lengthBuffer); + } + } + + private long ParseLengthPrefix(byte[] buffer, int length, bool useBigEndian) + { + var value = MessageFrameDecoder.ParseLengthPrefix(buffer, length, useBigEndian); + + if (value > _config.MAX_MESSAGE_SIZE) + { + throw new InvalidOperationException( + $"Parsed message length {value} exceeds maximum allowed {_config.MAX_MESSAGE_SIZE}. Possible malformed or malicious message."); + } + + return value; + } + + private async Task ReceiveNoneAsync(CancellationToken token) + { + byte[] buffer = ArrayPool.Shared.Rent(_config.BufferSize); + + try + { + while (!token.IsCancellationRequested && IsConnected) + { + var stream = _stream; + if (stream == null || !stream.CanRead) + { + break; + } + + CancellationToken readToken = token; + using var cts = _config.ReadTimeoutSeconds > 0 + ? CancellationTokenSource.CreateLinkedTokenSource(token) + : null; + if (cts != null) + { + cts.CancelAfter(TimeSpan.FromSeconds(_config.ReadTimeoutSeconds)); + readToken = cts.Token; + } + + int read = await stream.ReadAsync(buffer, 0, buffer.Length, readToken); + + if (read == 0) + { + DebugConnection("Remote closed connection."); + await DisconnectClientAsync(DisconnectReason.RemoteClosed); + return; + } + + ReadOnlyMemory payload = buffer.AsMemory(0, read); + + if (_config.UseAesEncryption && _aesEncryption != null) + { + try + { + var decrypted = await AesKeyExchange.DecryptDataAsync(payload.ToArray(), read, _aesEncryption); + await ProcessReceivedDataAsync(decrypted); + } + catch (Exception ex) + { + DebugConnection($"Decrypt error: {ex.Message}"); + HandlingHelpers.SafeInvokeEventHandler( + OnEncryptionError, + this, + new ErrorEventArgs + { + Exception = ex, + Message = "Error decrypting data" + }, + nameof(OnEncryptionError)); + } + } + else + { + await ProcessReceivedDataAsync(payload); + } + + MarkDataReceived(); + } + } + catch (OperationCanceledException ex) + { + DebugConnection($"Read timeout during raw receive: {ex.Message}"); + RecordError(ex, "Read timeout in raw receive - stream may be unresponsive"); + await DisconnectClientAsync(DisconnectReason.Timeout, ex); + } + catch (SocketException socketEx) + { + DebugConnection($"Socket error in raw receive: {socketEx.SocketErrorCode} - {socketEx.Message}"); + var errorMsg = $"Socket error in raw receive: {socketEx.SocketErrorCode} - {socketEx.SocketErrorCode switch { SocketError.ConnectionReset => "Connection reset", SocketError.ConnectionAborted => "Connection aborted", _ => "Unknown socket error" }}"; + RecordError(socketEx, errorMsg); + var reason = socketEx.SocketErrorCode == SocketError.ConnectionReset || socketEx.SocketErrorCode == SocketError.ConnectionAborted + ? DisconnectReason.RemoteClosed + : DisconnectReason.Error; + await DisconnectClientAsync(reason, socketEx); + } + catch (IOException ex) when (ex.InnerException is SocketException innerSocketEx) + { + DebugConnection($"Socket IO error in raw receive: {innerSocketEx.SocketErrorCode} - {ex.Message}"); + var errorMsg = $"Socket IO error in raw receive: {innerSocketEx.SocketErrorCode} - {innerSocketEx.SocketErrorCode switch { SocketError.ConnectionReset => "Connection reset", SocketError.ConnectionAborted => "Connection aborted", _ => "Unknown socket error" }}"; + RecordError(ex, errorMsg); + var reason = innerSocketEx.SocketErrorCode == SocketError.ConnectionReset + || innerSocketEx.SocketErrorCode == SocketError.ConnectionAborted + ? DisconnectReason.RemoteClosed + : DisconnectReason.Error; + await DisconnectClientAsync(reason, ex); + } + catch (IOException ex) + { + DebugConnection($"Connection closed during raw receive: {ex.GetType().Name} - {ex.Message}"); + RecordError(ex, "Connection closed during raw receive"); + await DisconnectClientAsync(DisconnectReason.RemoteClosed, ex); + } + catch (Exception ex) + { + DebugConnection($"Unexpected error in raw receive: {ex.GetType().Name} - {ex.Message}"); + RecordError(ex, $"Error in raw receive: {ex.GetType().Name} - {ex.Message}"); + await DisconnectClientAsync(DisconnectReason.Error, ex); + } + finally + { + ArrayPool.Shared.Return(buffer); + } + } + + private async Task ReceiveDelimiterAsync(CancellationToken token) + { + byte[] buffer = ArrayPool.Shared.Rent(_config.BufferSize); + var memory = new MemoryStream(); + + try + { + while (!token.IsCancellationRequested && IsConnected) + { + var stream = _stream; + if (stream == null || !stream.CanRead) + { + break; + } + + CancellationToken readToken = token; + using var cts = _config.ReadTimeoutSeconds > 0 + ? CancellationTokenSource.CreateLinkedTokenSource(token) + : null; + if (cts != null) + { + cts.CancelAfter(TimeSpan.FromSeconds(_config.ReadTimeoutSeconds)); + readToken = cts.Token; + } + + int read = await stream.ReadAsync(buffer, 0, buffer.Length, readToken); + + if (read == 0) + { + DebugConnection("Remote closed connection."); + await DisconnectClientAsync(DisconnectReason.RemoteClosed); + return; + } + + memory.Write(buffer, 0, read); + + while (TryExtractMessage(memory, _config.Delimiter, _config.MAX_MESSAGE_SIZE, out var message)) + { + if (_config.UseAesEncryption && _aesEncryption != null) + { + message = await AesKeyExchange.DecryptDataAsync(message, message.Length, _aesEncryption); + } + + await ProcessReceivedDataAsync(message); + MarkDataReceived(); + } + } + } + catch (ProtocolViolationException ex) + { + DebugConnection($"Protocol violation during delimiter receive: {ex.Message}"); + RecordError(ex, $"Protocol violation during delimiter receive: {ex.Message}"); + await DisconnectClientAsync(DisconnectReason.ProtocolError, ex); + } + catch (OperationCanceledException ex) + { + DebugConnection($"Read timeout during delimiter receive: {ex.Message}"); + RecordError(ex, "Read timeout in delimiter receive - stream may be unresponsive"); + await DisconnectClientAsync(DisconnectReason.Timeout, ex); + } + catch (SocketException socketEx) + { + DebugConnection($"Socket error in delimiter receive: {socketEx.SocketErrorCode} - {socketEx.Message}"); + var errorMsg = $"Socket error in delimiter receive: {socketEx.SocketErrorCode} - {socketEx.SocketErrorCode switch { SocketError.ConnectionReset => "Connection reset", SocketError.ConnectionAborted => "Connection aborted", _ => "Unknown socket error" }}"; + RecordError(socketEx, errorMsg); + var reason = socketEx.SocketErrorCode == SocketError.ConnectionReset || socketEx.SocketErrorCode == SocketError.ConnectionAborted + ? DisconnectReason.RemoteClosed + : DisconnectReason.Error; + await DisconnectClientAsync(reason, socketEx); + } + catch (IOException ex) when (ex.InnerException is SocketException innerSocketEx) + { + DebugConnection($"Socket IO error in delimiter receive: {innerSocketEx.SocketErrorCode} - {ex.Message}"); + var errorMsg = $"Socket IO error in delimiter receive: {innerSocketEx.SocketErrorCode} - {innerSocketEx.SocketErrorCode switch { SocketError.ConnectionReset => "Connection reset", SocketError.ConnectionAborted => "Connection aborted", _ => "Unknown socket error" }}"; + RecordError(ex, errorMsg); + var reason = innerSocketEx.SocketErrorCode == SocketError.ConnectionReset + || innerSocketEx.SocketErrorCode == SocketError.ConnectionAborted + ? DisconnectReason.RemoteClosed + : DisconnectReason.Error; + await DisconnectClientAsync(reason, ex); + } + catch (IOException ex) + { + DebugConnection($"Connection closed during delimiter receive: {ex.GetType().Name} - {ex.Message}"); + RecordError(ex, "Connection closed during delimiter receive"); + await DisconnectClientAsync(DisconnectReason.RemoteClosed, ex); + } + catch (Exception ex) + { + DebugConnection($"Unexpected error in delimiter receive: {ex.GetType().Name} - {ex.Message}"); + RecordError(ex, $"Error in delimiter receive: {ex.GetType().Name} - {ex.Message}"); + await DisconnectClientAsync(DisconnectReason.Error, ex); + } + finally + { + ArrayPool.Shared.Return(buffer); + memory.Dispose(); + } + } + + private static bool TryExtractMessage(MemoryStream stream, byte[] delimiter, double maxMessageBytes, out byte[] message) + { + var hasMessage = MessageFrameDecoder.TryReadDelimited(stream, delimiter, maxMessageBytes, out var decodedMessage); + message = decodedMessage ?? Array.Empty(); + return hasMessage; + } + private async Task ReadExactAsync(Stream stream, byte[] buffer, int offset, int count, CancellationToken token) + { + int totalRead = 0; + + while (totalRead < count && !token.IsCancellationRequested) + { + int bytesRead = await stream.ReadAsync(buffer, offset + totalRead, count - totalRead, token).ConfigureAwait(false); + + if (bytesRead == 0) + { + + DebugConnection($"Unexpected end of stream: expected {count} bytes, got {totalRead}"); + throw new EndOfStreamException($"Unexpected end of stream: expected {count} bytes, got {totalRead}"); + } + + totalRead += bytesRead; + } + + return totalRead; + } + + private async Task ProcessReceivedDataAsync(ReadOnlyMemory data) + { + if (data.IsEmpty) + { + return; + } + + MarkDataReceived(); + Interlocked.Add(ref _bytesReceived, data.Length); + Interlocked.Increment(ref _messagesReceived); + + bool needsText = _config.EnableHeartbeat || OnDataReceived != null; + + string stringData = null; + bool isText = false; + + if (needsText) + { + try + { +#if NET8_0_OR_GREATER + var span = data.Span; + int charCount = Encoding.UTF8.GetCharCount(span); + + if (_charBuffer.Length < charCount) + { + _charBuffer = new char[charCount]; + } + + int written = Encoding.UTF8.GetChars(span, _charBuffer); +#else + byte[] bytes = data.ToArray(); + int charCount = _utf8Decoder.GetCharCount(bytes, 0, bytes.Length); + + if (_charBuffer.Length < charCount) + { + _charBuffer = new char[charCount]; + } + + int written = _utf8Decoder.GetChars(bytes, 0, bytes.Length, _charBuffer, 0); +#endif + if (written > 0) + { + stringData = new string(_charBuffer, 0, written); + isText = true; + } + } + catch + { + isText = false; + } + } + + if (_config.EnableHeartbeat && isText) + { + ProcessPingPong(ref stringData); + + if (string.IsNullOrEmpty(stringData)) + { + return; + } + } + + if (isText && !string.IsNullOrEmpty(stringData) && stringData.Contains(Configuration.SSL_ERROR_PREFIX, StringComparison.OrdinalIgnoreCase)) + { + string sslError = null; + var startIdx = stringData.IndexOf(Configuration.SSL_ERROR_PREFIX, StringComparison.Ordinal) + Configuration.SSL_ERROR_PREFIX.Length; + var endIdx = stringData.IndexOf(Configuration.SSL_ERROR_SUFFIX, StringComparison.Ordinal); + if (endIdx > startIdx) + { + sslError = stringData.Substring(startIdx, endIdx - startIdx); + } + RecordError(null, $"Server reported SSL error: {sslError ?? stringData}", isSslError: true); + HandlingHelpers.SafeInvokeEventHandler( + OnSslError, + this, + new ErrorEventArgs + { + Message = $"Server reported SSL error: {sslError ?? stringData}" + }, + nameof(OnSslError)); + await DisconnectClientAsync(DisconnectReason.SSLError).ConfigureAwait(false); + return; + } + + if (DEBUG_DATA_RECEIVED) + { + OnLog?.Invoke(this, new LogMessage { Type = LogType.Debug, Message = $"[DEBUG DATA] Received {data.Length} bytes" }); + } + + try + { + + byte[] sanitizedData = SanitizeReceivedData(data.ToArray()); + + HandlingHelpers.SafeInvokeEventHandler( + OnDataReceived, + this, + new DataReceivedEventArgs + { + ClientId = "server", + Data = sanitizedData, + IsBinary = !isText, + Timestamp = DateTime.UtcNow, + RemoteEndPoint = GetRemoteEndPoint(), + Nickname = Nickname, + }, + nameof(OnDataReceived)); + } + catch (Exception ex) + { + DebugConnection($"OnDataReceived handler threw: {ex.GetType().Name} - {ex.Message}"); + OnLog?.Invoke(this, new LogMessage { Type = LogType.Error, Message = $"OnDataReceived handler threw: {ex.GetType().Name} - {ex.Message}" }); + } + } + + private void ProcessPingPong(ref string message) + { + if (!_config.EnableHeartbeat || string.IsNullOrEmpty(message)) + { + return; + } + + if (message.Contains(Configuration.PING_VALUE)) + { + LastPingSent = DateTime.UtcNow; + if (_config.EnablePingPongLogs) + { + OnLog?.Invoke(this, new LogMessage { Type = LogType.Debug, Message = "Received PING from server. Sending PONG response." }); + } + + OnPingResponse?.Invoke(this, new PingEventArgs + { + Id = "server", + Nickname = Nickname, + ReceivedTime = DateTime.UtcNow, + RemoteEndPoint = GetRemoteEndPoint() + }); + FireAndForget(SendAsync(Configuration.PONG_VALUE), "PONG send"); + message = message.Replace(Configuration.PING_VALUE, string.Empty); + } + + if (message.Contains(Configuration.PONG_VALUE)) + { + LastPongReceived = DateTime.UtcNow; + _hasReceivedPongSinceConnection = true; + if (_config.EnablePingPongLogs) + { + OnLog?.Invoke(this, new LogMessage { Type = LogType.Debug, Message = "Received PONG from server for PING" }); + } + OnPongResponse?.Invoke(this, new PingEventArgs + { + Id = "server", + Nickname = Nickname, + ReceivedTime = DateTime.UtcNow, + RemoteEndPoint = GetRemoteEndPoint() + }); + message = message.Replace(Configuration.PONG_VALUE, string.Empty); + } + } + + private async Task ReceiveUdpDataAsync() + { + DebugConnection($"UDP receive loop started for {_config.Host}:{_config.Port}"); + + while (_connectionCts != null && !_connectionCts.Token.IsCancellationRequested && IsConnected) + { + try + { + var result = await _udpClient.ReceiveAsync().ConfigureAwait(false); + var buffer = result.Buffer; + + if (_config.EnableHeartbeat) + { + try + { + buffer = HandleHeartbeat(buffer, out bool foundHeartbeat); + if (foundHeartbeat) + { + LastPongReceived = DateTime.UtcNow; + _hasReceivedPongSinceConnection = true; + if (_config.EnablePingPongLogs) + { + OnLog?.Invoke(this, new LogMessage { Type = LogType.Debug, Message = "Received PONG from server for PING (UDP)" }); + } + } + if (buffer == null || buffer.Length == 0) + { + continue; + } + } + catch (Exception exception) + { + DebugConnection($"Heartbeat handling error in UDP: {exception.GetType().Name} - {exception.Message}"); + RecordError(exception, $"Heartbeat handling failed (UDP): {exception.GetType().Name} - {exception.Message}"); + HandlingHelpers.SafeInvokeEventHandler( + OnGeneralError, + this, + new ErrorEventArgs { Exception = exception, Message = "Heartbeat handling failed (UDP)" }, + nameof(OnGeneralError)); + } + } + + MarkDataReceived(); + await ProcessReceivedDataAsync(buffer).ConfigureAwait(false); + } + catch (SocketException socketEx) + { + var errorMsg = $"Socket error in UDP receive: {socketEx.SocketErrorCode} - {socketEx.SocketErrorCode switch { SocketError.ConnectionReset => "Connection reset", SocketError.HostUnreachable => "Host unreachable", _ => "Unknown socket error" }}"; + DebugConnection($"UDP receive socket error: {socketEx.SocketErrorCode} - {socketEx.Message}"); + RecordError(socketEx, errorMsg); + HandlingHelpers.SafeInvokeEventHandler( + OnGeneralError, + this, + new ErrorEventArgs { Exception = socketEx, Message = errorMsg }, + nameof(OnGeneralError)); + ConnectionTime = DateTime.MinValue; + break; + } + catch (ObjectDisposedException ex) + { + DebugConnection("UDP receive loop: UDP client disposed, stopping receive loop."); + RecordError(ex, "UDP client disposed - connection closing"); + break; + } + catch (OperationCanceledException) + { + DebugConnection("UDP receive loop: Operation canceled."); + break; + } + catch (Exception exception) + { + DebugConnection($"UDP receive error: {exception.GetType().Name} - {exception.Message}"); + RecordError(exception, $"Error receiving UDP data: {exception.GetType().Name} - {exception.Message}"); + OnGeneralError?.Invoke(this, new ErrorEventArgs { Exception = exception, Message = $"UDP receive error: {exception.GetType().Name}" }); + ConnectionTime = DateTime.MinValue; + break; + } + } + + DebugConnection("UDP receive loop stopped."); + } + } +} diff --git a/EonaCat.Connections/Client/NetworkClient.Reconnect.cs b/EonaCat.Connections/Client/NetworkClient.Reconnect.cs new file mode 100644 index 0000000..9bf31a4 --- /dev/null +++ b/EonaCat.Connections/Client/NetworkClient.Reconnect.cs @@ -0,0 +1,163 @@ +using ErrorEventArgs = EonaCat.Connections.EventArguments.ErrorEventArgs; + +namespace EonaCat.Connections +{ + public partial class NetworkClient + { + private async Task AutoReconnectAsync(CancellationToken token) + { + IsAutoConnectStarted = true; + int consecutiveFailures = 0; + const int MAX_CONSECUTIVE_FAILURES = 10; + const int MAX_BACKOFF_SECONDS = 300; + + try + { + while (!token.IsCancellationRequested) + { + if (!_config.EnableAutoReconnect || + _reason == DisconnectReason.LocalClosed || + !_wasConnected) + { + DebugConnection("Auto-reconnect disabled or not previously connected; stopping auto-reconnect task."); + break; + } + + if (_reason == DisconnectReason.ClientRequested) + { + + DebugConnection("Client explicitly requested disconnection; stopping auto-reconnect task."); + _autoReconnectSource?.Cancel(); + break; + } + + if (IsConnected) + { + consecutiveFailures = 0; + await Task.Delay(1_000, token).ConfigureAwait(false); + continue; + } + + bool reconnected = await TryReconnectWithRetriesAsync(token).ConfigureAwait(false); + + if (reconnected) + { + consecutiveFailures = 0; + } + else + { + consecutiveFailures++; + + if (consecutiveFailures >= MAX_CONSECUTIVE_FAILURES) + { + var criticalMsg = $"Too many consecutive reconnection failures ({consecutiveFailures}); stopping auto-reconnect task to prevent resource exhaustion."; + DebugConnection(criticalMsg); + RecordError(null, criticalMsg); + break; + } + + int baseBackoffSeconds = Math.Min( + (int)Math.Pow(2, Math.Min(consecutiveFailures - 1, 8)), + MAX_BACKOFF_SECONDS + ); + + var jitter = new Random().Next((int)(baseBackoffSeconds * -0.25), (int)(baseBackoffSeconds * 0.25)); + int finalBackoffSeconds = Math.Max(1, baseBackoffSeconds + jitter); + + DebugConnection($"Reconnection failed (attempt {consecutiveFailures}); waiting {finalBackoffSeconds}s (base: {baseBackoffSeconds}s) before next attempt..."); + + try + { + await Task.Delay(TimeSpan.FromSeconds(finalBackoffSeconds), token).ConfigureAwait(false); + } + catch (OperationCanceledException) + { + break; + } + } + } + } + catch (OperationCanceledException) + { + DebugConnection("Auto-reconnect task canceled."); + } + catch (Exception ex) + { + DebugConnection($"Auto-reconnect task encountered unexpected error: {ex.GetType().Name} - {ex.Message}"); + RecordError(ex, $"Auto-reconnect task failed: {ex.GetType().Name} - {ex.Message}"); + } + finally + { + IsAutoConnectStarted = false; + DebugConnection("Auto-reconnect task stopped."); + } + } + private async Task TryReconnectWithRetriesAsync(CancellationToken token) + { + int attempt = 0; + var maxAttempts = _config.MaxReconnectAttempts; + + while (!token.IsCancellationRequested && (maxAttempts == 0 || attempt < maxAttempts)) + { + if (IsConnected) + { + return true; + } + + attempt++; + + try + { + DebugConnection($"Attempting to reconnect... Attempt {attempt}/{(maxAttempts == 0 ? "unlimited" : maxAttempts.ToString())}"); + var connected = await ConnectAsync().ConfigureAwait(false); + + if (connected && IsConnected) + { + _reason = DisconnectReason.Unknown; + + var successMsg = $"Reconnected successfully after {attempt} attempt(s)"; + DebugConnection(successMsg); + return true; + } + } + catch (OperationCanceledException) + { + DebugConnection($"Reconnection attempt {attempt} canceled."); + throw; + } + catch (Exception ex) + { + var errorMsg = $"Reconnection attempt {attempt} failed: {ex.GetType().Name} - {ex.Message}"; + DebugConnection(errorMsg); + RecordError(ex, errorMsg); + + OnGeneralError?.Invoke( + this, + new ErrorEventArgs + { + Exception = ex, + Message = errorMsg + }); + } + + if (maxAttempts > 0 && attempt >= maxAttempts) + { + DebugConnection($"Maximum reconnection attempts ({maxAttempts}) reached."); + break; + } + + Int32 retryDelayMs = Math.Min(500 * attempt, 2000); + try + { + await Task.Delay(retryDelayMs, token).ConfigureAwait(false); + } + catch (OperationCanceledException) + { + break; + } + } + + return false; + } + } +} diff --git a/EonaCat.Connections/Client/NetworkClient.Sending.cs b/EonaCat.Connections/Client/NetworkClient.Sending.cs new file mode 100644 index 0000000..e9ca638 --- /dev/null +++ b/EonaCat.Connections/Client/NetworkClient.Sending.cs @@ -0,0 +1,418 @@ +using EonaCat.Connections.EventArguments; +using EonaCat.Connections.Framing; +using EonaCat.Connections.Helpers; +using EonaCat.Connections.Messaging; +using EonaCat.Connections.Models; +using System.Net.Sockets; +using System.Text; +using ProtocolType = EonaCat.Connections.Models.ProtocolType; + +namespace EonaCat.Connections +{ + public partial class NetworkClient + { + public async Task SendAsync(byte[] data) + => await SendAsync(data, CancellationToken.None).ConfigureAwait(false); + + public async Task SendAsync(byte[] data, CancellationToken cancellationToken) + { + + if (data == null || data.Length == 0) + { + DebugConnection("SendAsync: Cannot send null or empty data"); + return false; + } + + if (!IsConnected) + { + DebugConnection("SendAsync: Not connected, cannot send"); + return false; + } + + if (_clientCts == null || _clientCts.IsCancellationRequested) + { + DebugConnection("SendAsync: Client cancellation token is invalid"); + return false; + } + + try + { + using var linkedSource = CancellationTokenSource.CreateLinkedTokenSource(_clientCts.Token, cancellationToken); + byte[] payload = data; + + if (_config.UseAesEncryption && _aesEncryption != null) + { + payload = await AesKeyExchange.EncryptDataAsync(data, data.Length, _aesEncryption); + } + + byte[] framed = Frame(payload); + return await SendWithRetryAsync(framed, linkedSource.Token).ConfigureAwait(false); + } + catch (Exception ex) + { + DebugConnection($"SendAsync: Unexpected error in send operation: {ex.GetType().Name} - {ex.Message}"); + await DisconnectClientAsync(DisconnectReason.Error, ex); + return false; + } + } + + private async Task SendWithRetryAsync(byte[] data, CancellationToken token) + { + int retryCount = 0; + int delayMs = SEND_RETRY_INITIAL_DELAY_MS; + + while (retryCount <= SEND_RETRY_MAX_ATTEMPTS) + { + try + { + if (token.IsCancellationRequested) + { + DebugConnection("SendWithRetryAsync: Operation canceled"); + return false; + } + + bool result = await SendInternalAsync(data, token).ConfigureAwait(false); + + if (result) + { + + if (retryCount > 0) + { + DebugConnection($"SendWithRetryAsync: Send succeeded on retry attempt {retryCount}"); + } + return true; + } + + if (token.IsCancellationRequested) + { + return false; + } + + retryCount++; + + if (retryCount <= SEND_RETRY_MAX_ATTEMPTS) + { + + if (!IsConnected) + { + DebugConnection($"SendWithRetryAsync: Not connected, triggering auto-reconnect (attempt {retryCount}/{SEND_RETRY_MAX_ATTEMPTS})"); + + if (_config.EnableAutoReconnect && _autoReconnectTask != null && !_autoReconnectTask.IsCompleted) + { + + await Task.Delay(delayMs, token).ConfigureAwait(false); + } + else if (_config.EnableAutoReconnect) + { + + await ConnectAsync().ConfigureAwait(false); + } + } + else + { + + DebugConnection($"SendWithRetryAsync: Send failed, retrying after {delayMs}ms (attempt {retryCount}/{SEND_RETRY_MAX_ATTEMPTS})"); + await Task.Delay(delayMs, token).ConfigureAwait(false); + } + delayMs = Math.Min(delayMs * 2, SEND_RETRY_MAX_DELAY_MS); + } + } + catch (OperationCanceledException) + { + DebugConnection("SendWithRetryAsync: Operation canceled during retry"); + return false; + } + catch (Exception ex) + { + DebugConnection($"SendWithRetryAsync: Exception during send attempt: {ex.GetType().Name} - {ex.Message}"); + retryCount++; + + if (retryCount <= SEND_RETRY_MAX_ATTEMPTS) + { + DebugConnection($"SendWithRetryAsync: Retrying after exception (attempt {retryCount}/{SEND_RETRY_MAX_ATTEMPTS})"); + + if (!IsConnected && _config.EnableAutoReconnect) + { + DebugConnection("SendWithRetryAsync: Connection lost, triggering auto-reconnect"); + await ConnectAsync().ConfigureAwait(false); + } + + try + { + await Task.Delay(delayMs, token).ConfigureAwait(false); + } + catch (OperationCanceledException) + { + return false; + } + delayMs = Math.Min(delayMs * 2, SEND_RETRY_MAX_DELAY_MS); + } + } + } + + DebugConnection($"SendWithRetryAsync: All {SEND_RETRY_MAX_ATTEMPTS} retry attempts exhausted"); + await DisconnectClientAsync(DisconnectReason.Error); + return false; + } + + private byte[] Frame(byte[] payload) + { + if (payload == null) + { + throw new ArgumentNullException(nameof(payload)); + } + + if (payload.Length > _config.MAX_MESSAGE_SIZE) + { + throw new InvalidOperationException($"Payload size {payload.Length} exceeds maximum message size {_config.MAX_MESSAGE_SIZE}"); + } + + return _config.MessageFraming == FramingMode.None + ? payload + : MessageFrameEncoder.Encode(payload, _config); + } + + private byte[] SanitizeReceivedData(byte[] data) + { + try + { + + if (data == null) + { + return Array.Empty(); + } + + if (data.Length > _config.MAX_MESSAGE_SIZE) + { + throw new InvalidOperationException( + $"Received data size {data.Length} exceeds maximum message size {_config.MAX_MESSAGE_SIZE}"); + } + + return data; + } + catch (Exception ex) + { + DebugConnection($"SanitizeReceivedData error: {ex.GetType().Name} - {ex.Message}"); + + return Array.Empty(); + } + } + + public async Task SendNicknameAsync(string nickname) + => await SendNicknameAsync(nickname, CancellationToken.None).ConfigureAwait(false); + + public async Task SendNicknameAsync(string nickname, CancellationToken cancellationToken) + { + if (string.IsNullOrWhiteSpace(nickname)) + { + return false; + } + + var result = await SendAsync($"[NICKNAME]{nickname}[/NICKNAME]", cancellationToken).ConfigureAwait(false); + if (result) + { + Nickname = nickname.Trim(); + OnNicknameSend?.Invoke(this, new ConnectionEventArgs + { + ClientId = nickname, + RemoteEndPoint = GetRemoteEndPoint(), + Nickname = nickname + }); + } + return result; + } + + public async Task SendAsync(string message) => await SendAsync(Encoding.UTF8.GetBytes(message)).ConfigureAwait(false); + + public async Task SendAsync(string message, CancellationToken cancellationToken) + => await SendAsync(Encoding.UTF8.GetBytes(message), cancellationToken).ConfigureAwait(false); + + public async Task SendAndWaitForResponseAsync(byte[] data, TimeSpan? timeout = null) + => await SendAndWaitForResponseAsync(data, timeout, CancellationToken.None).ConfigureAwait(false); + + public async Task SendAndWaitForResponseAsync(byte[] data, TimeSpan? timeout, CancellationToken cancellationToken) + { + if (data == null || data.Length == 0) + { + DebugConnection("SendAndWaitForResponseAsync: Cannot send null or empty data"); + return null; + } + + if (!IsConnected) + { + DebugConnection("SendAndWaitForResponseAsync: Not connected"); + return null; + } + + var effectiveTimeout = timeout ?? TimeSpan.FromSeconds(DEFAULT_WAITING_TIMEOUT_IN_SECONDS); + return await ResponseAwaiter.WaitForSingleAsync( + () => SendAsync(data, cancellationToken), + handler => OnDataReceived += handler, + handler => OnDataReceived -= handler, + effectiveTimeout, + cancellationToken: cancellationToken).ConfigureAwait(false); + } + + public async Task SendAndWaitForResponseAsync(string message, TimeSpan? timeout = null) + => await SendAndWaitForResponseAsync(Encoding.UTF8.GetBytes(message), timeout).ConfigureAwait(false); + + public async Task SendAndWaitForResponseAsync(string message, TimeSpan? timeout, CancellationToken cancellationToken) + => await SendAndWaitForResponseAsync(Encoding.UTF8.GetBytes(message), timeout, cancellationToken).ConfigureAwait(false); + + public async Task SendNicknameAndWaitForResponseAsync(string nickname, TimeSpan? timeout = null) + => await SendNicknameAndWaitForResponseAsync(nickname, timeout, CancellationToken.None).ConfigureAwait(false); + + public async Task SendNicknameAndWaitForResponseAsync(string nickname, TimeSpan? timeout, CancellationToken cancellationToken) + { + var effectiveTimeout = timeout ?? TimeSpan.FromSeconds(DEFAULT_WAITING_TIMEOUT_IN_SECONDS); + return await ResponseAwaiter.WaitForSingleAsync( + () => SendNicknameAsync(nickname, cancellationToken), + handler => OnDataReceived += handler, + handler => OnDataReceived -= handler, + effectiveTimeout, + cancellationToken: cancellationToken).ConfigureAwait(false); + } + + private async Task SendInternalAsync(byte[] data, CancellationToken token) + { + + if (data == null || data.Length == 0) + { + DebugConnection("SendInternalAsync: Null or empty data"); + return false; + } + + if (!IsConnected) + { + return false; + } + + if (_config.Protocol == ProtocolType.TCP) + { + if (_stream == null || !_stream.CanWrite) + { + DebugConnection($"SendInternalAsync: Stream is not available for writing for {_config.Host}:{_config.Port}, disconnecting"); + await DisconnectClientAsync(DisconnectReason.RemoteClosed).ConfigureAwait(false); + return false; + } + + try + { + using var cts = CancellationTokenSource.CreateLinkedTokenSource(token); + if (_config.WriteTimeoutSeconds > 0) + { + cts.CancelAfter(TimeSpan.FromSeconds(_config.WriteTimeoutSeconds)); + } + + await _streamWriteLock.WaitAsync(cts.Token).ConfigureAwait(false); + try + { + + if (_stream == null || !_stream.CanWrite) + { + DebugConnection($"SendInternalAsync: Stream became unavailable after lock acquired for {_config.Host}:{_config.Port}, disconnecting"); + await DisconnectClientAsync(DisconnectReason.RemoteClosed).ConfigureAwait(false); + return false; + } + + await _stream.WriteAsync(data, 0, data.Length, cts.Token).ConfigureAwait(false); + await _stream.FlushAsync(cts.Token).ConfigureAwait(false); + + Interlocked.Add(ref _bytesSent, data.Length); + Interlocked.Increment(ref _messagesSent); + MarkDataSent(); + return true; + } + finally + { + _streamWriteLock.Release(); + } + } + catch (OperationCanceledException ex) + { + if (token.IsCancellationRequested) + { + return false; + } + + DebugConnection($"SendInternalAsync: Write operation canceled for {_config.Host}:{_config.Port}, likely due to timeout or shutdown: {ex.Message}"); + RecordError(ex, "Write timeout in TCP send - stream may be unresponsive"); + await DisconnectClientAsync(DisconnectReason.Timeout, ex); + return false; + } + catch (SocketException socketEx) + { + DebugConnection($"SendInternalAsync: Socket error while sending TCP data to {_config.Host}:{_config.Port}: {socketEx.SocketErrorCode} - {socketEx.Message}"); + RecordError(socketEx, $"Socket error in TCP send: {socketEx.SocketErrorCode} - {socketEx.SocketErrorCode switch { SocketError.ConnectionReset => "Connection reset by remote host", SocketError.ConnectionAborted => "Connection aborted", SocketError.HostUnreachable => "Host unreachable", SocketError.NetworkUnreachable => "Network unreachable", SocketError.ConnectionRefused => "Connection refused", SocketError.NotConnected => "Socket not connected", SocketError.Shutdown => "Socket shutdown", SocketError.Disconnecting => "Socket disconnecting", _ => "Unknown socket error" }}"); + await DisconnectClientAsync(DisconnectReason.Error, socketEx); + return false; + } + catch (IOException ioEx) when (ioEx.InnerException is SocketException innerSocketEx) + { + DebugConnection($"SendInternalAsync: Socket IO error while sending TCP data to {_config.Host}:{_config.Port}: {innerSocketEx.SocketErrorCode} - {ioEx.Message}"); + RecordError(ioEx, $"Socket IO error in TCP send: {innerSocketEx.SocketErrorCode} - {innerSocketEx.SocketErrorCode switch { SocketError.ConnectionReset => "Connection reset by remote host", SocketError.ConnectionAborted => "Connection aborted", SocketError.NotConnected => "Socket not connected", _ => "Unknown socket error" }}"); + var reason = innerSocketEx.SocketErrorCode == SocketError.ConnectionReset || innerSocketEx.SocketErrorCode == SocketError.ConnectionAborted ? DisconnectReason.RemoteClosed : DisconnectReason.Error; + await DisconnectClientAsync(reason, ioEx); + return false; + } + catch (IOException ioEx) + { + + DebugConnection($"SendInternalAsync: IO error while sending TCP data to {_config.Host}:{_config.Port}: {ioEx.Message}"); + RecordError(ioEx, $"IO error in TCP send: {ioEx.Message}"); + await DisconnectClientAsync(DisconnectReason.Error, ioEx); + return false; + } + catch (ObjectDisposedException ex) + { + DebugConnection($"SendInternalAsync: ObjectDisposedException for {_config.Host}:{_config.Port}, stream was likely disposed during reconnection"); + RecordError(ex, "Stream disposed during TCP send - possible race condition during reconnection attempt"); + if (IsConnected) + { + await DisconnectClientAsync(DisconnectReason.Error, ex).ConfigureAwait(false); + } + return false; + } + catch (Exception ex) + { + DebugConnection($"SendInternalAsync: Exception occurred while sending data to {_config.Host}:{_config.Port}: {ex.GetType().Name} - {ex.Message}"); + RecordError(ex, $"Error in TCP send: {ex.GetType().Name} - {ex.Message}"); + await DisconnectClientAsync(DisconnectReason.Error, ex); + return false; + } + } + else + { + try + { + if (token.IsCancellationRequested) + { + return false; + } + + if (_udpClient != null) + { + await _udpClient.SendAsync(data, data.Length).ConfigureAwait(false); + Interlocked.Add(ref _bytesSent, data.Length); + Interlocked.Increment(ref _messagesSent); + MarkDataSent(); + return true; + } + return false; + } + catch (SocketException socketEx) + { + DebugConnection($"SendInternalAsync: Socket error sending UDP data to {_config.Host}:{_config.Port}: {socketEx.SocketErrorCode} - {socketEx.Message}"); + RecordError(socketEx, $"Socket error in UDP send: {socketEx.SocketErrorCode} - {socketEx.SocketErrorCode switch { SocketError.ConnectionReset => "Connection reset", SocketError.HostUnreachable => "Host unreachable", SocketError.NetworkUnreachable => "Network unreachable", _ => "Unknown socket error" }}"); + return false; + } + catch (Exception ex) + { + DebugConnection($"SendInternalAsync: Error sending UDP data to {_config.Host}:{_config.Port}: {ex.GetType().Name} - {ex.Message}"); + RecordError(ex, $"Error in UDP send: {ex.GetType().Name} - {ex.Message}"); + return false; + } + } + } + } +} diff --git a/EonaCat.Connections/Client/NetworkClient.Status.cs b/EonaCat.Connections/Client/NetworkClient.Status.cs new file mode 100644 index 0000000..17c1cd6 --- /dev/null +++ b/EonaCat.Connections/Client/NetworkClient.Status.cs @@ -0,0 +1,163 @@ +using EonaCat.Connections.Helpers; +using EonaCat.Connections.ConnectionDiagnostics; +using System.Globalization; +using System.Text; + +namespace EonaCat.Connections +{ + public partial class NetworkClient + { + public int IdleTimeInSeconds() + { + var idleTime = IdleTime(); + return (int)idleTime.TotalSeconds; + } + + public int IdleTimeInMinutes() + { + var idleTime = IdleTime(); + return (int)idleTime.TotalMinutes; + } + + public int IdleTimeInHours() + { + var idleTime = IdleTime(); + return (int)idleTime.TotalHours; + } + + public int IdleTimeInDays() + { + var idleTime = IdleTime(); + return (int)idleTime.TotalDays; + } + + public TimeSpan IdleTime() + { + return DateTime.UtcNow - LastActive; + } + + public string IdleTimeFormatted(bool includeDays = true, bool includeHours = true, bool includeMinutes = true, bool includeSeconds = true, bool includeMilliseconds = true) + { + return ConnectionTimeFormatter.Format( + IdleTime(), + includeDays, + includeHours, + includeMinutes, + includeSeconds, + includeMilliseconds); + } + + public int ConnectedTimeInSeconds() + { + var connectedTime = DateTime.UtcNow - ConnectionTime; + return (int)connectedTime.TotalSeconds; + } + + public int ConnectedTimeInMinutes() + { + var connectedTime = DateTime.UtcNow - ConnectionTime; + return (int)connectedTime.TotalMinutes; + } + + public int ConnectedTimeInHours() + { + var connectedTime = DateTime.UtcNow - ConnectionTime; + return (int)connectedTime.TotalHours; + } + + public int ConnectedTimeInDays() + { + var connectedTime = DateTime.UtcNow - ConnectionTime; + return (int)connectedTime.TotalDays; + } + + public TimeSpan ConnectedTime() + { + return DateTime.UtcNow - ConnectionTime; + } + + public string ConnectedTimeFormatted(bool includeDays = true, bool includeHours = true, bool includeMinutes = true, bool includeSeconds = true, bool includeMilliseconds = true) + { + return ConnectionTimeFormatter.Format( + ConnectedTime(), + includeDays, + includeHours, + includeMinutes, + includeSeconds, + includeMilliseconds); + } + + private string BuildHealthJson() + { + var E = HealthApiServer.JsonEscape; + return "{" + + "\"status\":\"ok\"," + + "\"type\":\"client\"," + + $"\"processName\":{E(HealthApiServer.GetProcessName())}," + + $"\"serverAddress\":{E(_config.Host + ":" + _config.Port)}," + + $"\"protocol\":{E(_config.Protocol.ToString())}," + + $"\"isConnected\":{(IsConnected ? "true" : "false")}," + + $"\"isSecure\":{(IsSecure ? "true" : "false")}," + + $"\"isEncrypted\":{(IsEncrypted ? "true" : "false")}," + + $"\"uptimeSeconds\":{Uptime.TotalSeconds.ToString("F1", CultureInfo.InvariantCulture)}," + + $"\"connectionTimeUtc\":{E(ConnectionTime.ToString("O"))}" + + "}"; + } + + private string BuildStatusJson() + { + var E = HealthApiServer.JsonEscape; + return "{" + + "\"status\":\"ok\"," + + "\"type\":\"client\"," + + $"\"serverAddress\":{E(_config.Host + ":" + _config.Port)}," + + $"\"protocol\":{E(_config.Protocol.ToString())}," + + $"\"isConnected\":{(IsConnected ? "true" : "false")}," + + $"\"isSecure\":{(IsSecure ? "true" : "false")}," + + $"\"isEncrypted\":{(IsEncrypted ? "true" : "false")}," + + $"\"nickname\":{E(Nickname ?? string.Empty)}," + + $"\"bytesSent\":{BytesSent}," + + $"\"bytesReceived\":{BytesReceived}," + + $"\"messagesSent\":{MessagesSent}," + + $"\"messagesReceived\":{MessagesReceived}," + + $"\"uptimeSeconds\":{Uptime.TotalSeconds.ToString("F1", CultureInfo.InvariantCulture)}," + + $"\"connectionTimeUtc\":{E(ConnectionTime.ToString("O"))}," + + $"\"lastActiveUtc\":{(LastActive == default ? "null" : E(LastActive.ToString("O")))}," + + $"\"idleTimeSeconds\":{IdleTime().TotalSeconds.ToString("F1", CultureInfo.InvariantCulture)}," + + $"\"lastDataSentUtc\":{(LastDataSent == default ? "null" : E(LastDataSent.ToString("O")))}," + + $"\"lastDataReceivedUtc\":{(LastDataReceived == default ? "null" : E(LastDataReceived.ToString("O")))}," + + $"\"disconnectionTimeUtc\":{(DisconnectionTime == default ? "null" : E(DisconnectionTime.ToString("O")))}," + + $"\"isAutoConnectStarted\":{(IsAutoConnectStarted ? "true" : "false")}," + + $"\"totalErrors\":{StatusPage.TotalErrors}," + + $"\"sslErrors\":{StatusPage.SslErrorCount}" + + "}"; + } + public string GetConnectionHealthSummary() + { + try + { + var sb = new StringBuilder(); + sb.AppendLine($"Connection Status: {(IsConnected ? "Connected" : "Disconnected")}"); + sb.AppendLine($"Endpoint: {_config?.Host}:{_config?.Port}"); + sb.AppendLine($"Protocol: {_config?.Protocol}"); + sb.AppendLine($"Connection Time: {(ConnectionTime != DateTime.MinValue ? ConnectionTime.ToString("O") : "N/A")}"); + sb.AppendLine($"Last Activity: {(LastActive != DateTime.MinValue ? LastActive.ToString("O") : "N/A")}"); + sb.AppendLine($"Last Pong: {(LastPongReceived != DateTime.MinValue ? LastPongReceived.ToString("O") : "N/A")}"); + sb.AppendLine($"Bytes Sent: {BytesSent}"); + sb.AppendLine($"Bytes Received: {BytesReceived}"); + sb.AppendLine($"Messages Sent: {MessagesSent}"); + sb.AppendLine($"Messages Received: {MessagesReceived}"); + sb.AppendLine($"Auto-connect Running: {IsAutoConnectStarted}"); + sb.AppendLine($"Nickname: {Nickname ?? "N/A"}"); + sb.AppendLine($"Encryption: {(IsEncrypted ? "Enabled (AES)" : "Disabled")}"); + sb.AppendLine($"SSL: {(_config?.UseSsl ?? false ? "Enabled" : "Disabled")}"); + + return sb.ToString(); + } + catch (Exception ex) + { + return $"Error getting health summary: {ex.GetType().Name} - {ex.Message}"; + } + } + } +} diff --git a/EonaCat.Connections/ConnectionDiagnostics/ConnectionLogger.cs b/EonaCat.Connections/ConnectionDiagnostics/ConnectionLogger.cs new file mode 100644 index 0000000..2f81acd --- /dev/null +++ b/EonaCat.Connections/ConnectionDiagnostics/ConnectionLogger.cs @@ -0,0 +1,282 @@ +using System.Text; + +namespace EonaCat.Connections.ConnectionDiagnostics +{ + + public class ConnectionLogger : IDisposable + { + private const long MAX_FILE_SIZE = 10 * 1024 * 1024; + private const int MAX_LOG_FILES = 10; + private const string LOG_DATE_FORMAT = "yyyy-MM-dd HH:mm:ss.fff"; + + private readonly string _logFilePath; + private readonly string _logDirectory; + private readonly string _baseFileName; + private readonly object _lockObject = new object(); + private bool _disposed = false; + + public ConnectionLogger(bool isServer, string customLogDirectory = null) + { + _logDirectory = string.IsNullOrEmpty(customLogDirectory) + ? Path.Combine(AppContext.BaseDirectory, "Logs") + : customLogDirectory; + + Directory.CreateDirectory(_logDirectory); + + _baseFileName = isServer ? "connection_server" : "connection_client"; + _logFilePath = Path.Combine(_logDirectory, $"{_baseFileName}.log"); + } + + public void LogDisconnection(string clientId, string nickname, string remoteEndPoint, string localEndPoint, string reason, string initiator, Exception exception = null, Dictionary additionalContext = null) + { + ThrowIfDisposed(); + var message = FormatDisconnectionLog(clientId, nickname, remoteEndPoint, localEndPoint, reason, initiator, exception, additionalContext); + WriteLog(message); + } + + public void LogEvent(string eventType, string clientId, string nickname, string remoteEndPoint, string localEndPoint, string message = null) + { + ThrowIfDisposed(); + var logMessage = FormatEventLog(eventType, clientId, nickname, remoteEndPoint, localEndPoint, message); + WriteLog(logMessage); + } + + public void LogError(string clientId, string remoteEndPoint, string localEndPoint, string errorType, Exception exception, Dictionary context = null) + { + ThrowIfDisposed(); + var logMessage = FormatErrorLog(clientId, remoteEndPoint, localEndPoint, errorType, exception, context); + WriteLog(logMessage); + } + + public void LogSocketError(string clientId, string remoteEndPoint, string localEndPoint, System.Net.Sockets.SocketError? socketError, string errorMessage, Exception exception = null) + { + ThrowIfDisposed(); + var logMessage = FormatSocketErrorLog(clientId, remoteEndPoint, localEndPoint, socketError, errorMessage, exception); + WriteLog(logMessage); + } + private string FormatDisconnectionLog(string clientId, string nickname, string remoteEndPoint, string localEndPoint, + string reason, string initiator, Exception exception, Dictionary additionalContext) + { + var stringBuilder = new StringBuilder(); + var utcTimestamp = DateTime.UtcNow.ToString(LOG_DATE_FORMAT); + var localTimestamp = DateTime.Now.ToString(LOG_DATE_FORMAT); + + stringBuilder.AppendLine("-------------------------------------------------------------------------------"); + stringBuilder.AppendLine($"[DISCONNECTION] Local: {localTimestamp} | UTC: {utcTimestamp}"); + stringBuilder.AppendLine("-------------------------------------------------------------------------------"); + stringBuilder.AppendLine($" Client ID: {clientId}"); + stringBuilder.AppendLine($" Nickname: {(string.IsNullOrEmpty(nickname) ? "[Not Set]" : nickname)}"); + stringBuilder.AppendLine($" Remote Endpoint: {remoteEndPoint}"); + stringBuilder.AppendLine($" Local Endpoint: {localEndPoint}"); + stringBuilder.AppendLine($" Disconnect Reason: {reason}"); + stringBuilder.AppendLine($" Initiated By: {initiator}"); + + if (exception != null) + { + stringBuilder.AppendLine($" Exception Type: {exception.GetType().FullName}"); + stringBuilder.AppendLine($" Exception Message: {exception.Message}"); + + if (!string.IsNullOrEmpty(exception.StackTrace)) + { + stringBuilder.AppendLine($" Stack Trace:"); + foreach (var line in exception.StackTrace.Split('\n')) + { + if (!string.IsNullOrWhiteSpace(line)) + { + stringBuilder.AppendLine($" {line}"); + } + } + } + + if (exception.InnerException != null) + { + stringBuilder.AppendLine($" Inner Exception: {exception.InnerException.GetType().FullName}: {exception.InnerException.Message}"); + } + } + + if (additionalContext != null && additionalContext.Count > 0) + { + stringBuilder.AppendLine($" Additional Context:"); + foreach (var kvp in additionalContext) + { + stringBuilder.AppendLine($" - {kvp.Key}: {kvp.Value}"); + } + } + + stringBuilder.AppendLine("-------------------------------------------------------------------------------"); + + return stringBuilder.ToString(); + } + + private string FormatEventLog(string eventType, string clientId, string nickname, + string remoteEndPoint, string localEndPoint, string message) + { + var utcTimestamp = DateTime.UtcNow.ToString(LOG_DATE_FORMAT); + var localTimestamp = DateTime.Now.ToString(LOG_DATE_FORMAT); + var sb = new StringBuilder(); + + sb.AppendLine($"[{eventType}] UTC: {utcTimestamp} | Local: {localTimestamp}"); + sb.AppendLine($" Client ID: {clientId}, Nickname: {(string.IsNullOrEmpty(nickname) ? "[Not Set]" : nickname)}, Remote: {remoteEndPoint}, Local: {localEndPoint}"); + + if (!string.IsNullOrEmpty(message)) + { + sb.AppendLine($" Details: {message}"); + } + + return sb.ToString(); + } + + private string FormatErrorLog(string clientId, string remoteEndPoint, string localEndPoint, string errorType, Exception exception, Dictionary context) + { + var utcTimestamp = DateTime.UtcNow.ToString(LOG_DATE_FORMAT); + var localTimestamp = DateTime.Now.ToString(LOG_DATE_FORMAT); + var stringBuilder = new StringBuilder(); + + stringBuilder.AppendLine("-------------------------------------------------------------------------------"); + stringBuilder.AppendLine($"[ERROR] Local: {localTimestamp} | UTC: {utcTimestamp}"); + stringBuilder.AppendLine($" Client ID: {clientId}"); + stringBuilder.AppendLine($" Remote Endpoint: {remoteEndPoint}"); + stringBuilder.AppendLine($" Local Endpoint: {localEndPoint}"); + stringBuilder.AppendLine($" Error Type: {errorType}"); + stringBuilder.AppendLine($" Exception: {exception?.GetType().Name}: {exception?.Message}"); + + if (context != null && context.Count > 0) + { + stringBuilder.AppendLine($" Context:"); + foreach (var kvp in context) + { + stringBuilder.AppendLine($" - {kvp.Key}: {kvp.Value}"); + } + } + + stringBuilder.AppendLine("-------------------------------------------------------------------------------"); + + return stringBuilder.ToString(); + } + + private string FormatSocketErrorLog(string clientId, string remoteEndPoint, string localEndPoint, System.Net.Sockets.SocketError? socketError, string errorMessage, Exception exception) + { + var utcTimestamp = DateTime.UtcNow.ToString(LOG_DATE_FORMAT); + var localTimestamp = DateTime.Now.ToString(LOG_DATE_FORMAT); + var stringBuilder = new StringBuilder(); + + stringBuilder.AppendLine("-------------------------------------------------------------------------------"); + stringBuilder.AppendLine($"[SOCKET_ERROR] Local: {localTimestamp} | UTC: {utcTimestamp}"); + stringBuilder.AppendLine($" Client ID: {clientId}"); + stringBuilder.AppendLine($" Remote Endpoint: {remoteEndPoint}"); + stringBuilder.AppendLine($" Local Endpoint: {localEndPoint}"); + + if (socketError.HasValue) + { + stringBuilder.AppendLine($" Socket Error: {socketError.Value} ({(int)socketError.Value})"); + } + + stringBuilder.AppendLine($" Message: {errorMessage}"); + + if (exception != null) + { + stringBuilder.AppendLine($" Exception: {exception.GetType().Name}: {exception.Message}"); + } + + stringBuilder.AppendLine("-------------------------------------------------------------------------------"); + + return stringBuilder.ToString(); + } + + private void WriteLog(string message) + { + lock (_lockObject) + { + try + { + + RotateIfNeeded(); + + File.AppendAllText(_logFilePath, message + Environment.NewLine); + } + catch (Exception ex) + { + + System.Diagnostics.Debug.WriteLine($"Failed to write to connection log: {ex.Message}"); + } + } + } + + private void RotateIfNeeded() + { + try + { + if (!File.Exists(_logFilePath)) + { + return; + } + + var fileInfo = new FileInfo(_logFilePath); + if (fileInfo.Length >= MAX_FILE_SIZE) + { + + var archiveFileName = $"{_baseFileName}_{DateTime.UtcNow:yyyyMMdd_HHmmss}.log"; + var archiveFilePath = Path.Combine(_logDirectory, archiveFileName); + + if (File.Exists(archiveFilePath)) + { + File.Delete(archiveFilePath); + } + File.Move(_logFilePath, archiveFilePath); + + CleanupOldLogs(); + } + } + catch (Exception ex) + { + System.Diagnostics.Debug.WriteLine($"Failed to rotate log file: {ex.Message}"); + } + } + + private void CleanupOldLogs() + { + try + { + if (!Directory.Exists(_logDirectory)) + { + return; + } + + var logFiles = Directory.GetFiles(_logDirectory, $"{_baseFileName}_*.log") + .OrderByDescending(f => File.GetCreationTimeUtc(f)) + .ToList(); + + while (logFiles.Count > MAX_LOG_FILES - 1) + { + try + { + File.Delete(logFiles[logFiles.Count - 1]); + logFiles.RemoveAt(logFiles.Count - 1); + } + catch (Exception ex) + { + System.Diagnostics.Debug.WriteLine($"Failed to delete old log file: {ex.Message}"); + break; + } + } + } + catch (Exception ex) + { + System.Diagnostics.Debug.WriteLine($"Failed to cleanup old logs: {ex.Message}"); + } + } + + private void ThrowIfDisposed() + { + if (_disposed) + { + throw new ObjectDisposedException(nameof(ConnectionLogger)); + } + } + + public void Dispose() + { + _disposed = true; + } + } +} diff --git a/EonaCat.Connections/ConnectionDiagnostics/ConnectionTimeFormatter.cs b/EonaCat.Connections/ConnectionDiagnostics/ConnectionTimeFormatter.cs new file mode 100644 index 0000000..8821f29 --- /dev/null +++ b/EonaCat.Connections/ConnectionDiagnostics/ConnectionTimeFormatter.cs @@ -0,0 +1,43 @@ +namespace EonaCat.Connections.ConnectionDiagnostics +{ + internal static class ConnectionTimeFormatter + { + public static string Format( + TimeSpan span, + bool includeDays, + bool includeHours, + bool includeMinutes, + bool includeSeconds, + bool includeMilliseconds) + { + var parts = new List(); + + if (includeDays) + { + parts.Add($"{(int)span.TotalDays:D2}d"); + } + + if (includeHours) + { + parts.Add($"{span.Hours:D2}h"); + } + + if (includeMinutes) + { + parts.Add($"{span.Minutes:D2}m"); + } + + if (includeSeconds) + { + parts.Add($"{span.Seconds:D2}s"); + } + + if (includeMilliseconds) + { + parts.Add($"{span.Milliseconds:D3}ms"); + } + + return string.Join(" ", parts); + } + } +} diff --git a/EonaCat.Connections/ConnectionDiagnostics/DisconnectionDiagnostics.cs b/EonaCat.Connections/ConnectionDiagnostics/DisconnectionDiagnostics.cs new file mode 100644 index 0000000..5c8ce75 --- /dev/null +++ b/EonaCat.Connections/ConnectionDiagnostics/DisconnectionDiagnostics.cs @@ -0,0 +1,276 @@ +using System.Net; +using System.Net.Sockets; + +namespace EonaCat.Connections.ConnectionDiagnostics +{ + + public class DisconnectionDiagnostics + { + + public static string DetermineInitiator(DisconnectReason reason, Exception exception) + { + if (reason == DisconnectReason.LocalClosed || + reason == DisconnectReason.ClientRequested || + reason == DisconnectReason.ServerShutdown || + reason == DisconnectReason.Reconnect || + reason == DisconnectReason.Forced) + { + return "Local"; + } + + if (reason == DisconnectReason.RemoteClosed) + { + return "Remote"; + } + + if (exception != null && exception is SocketException socketEx) + { + return DetermineInitiatorFromSocketError(socketEx.SocketErrorCode); + } + + return "Unknown"; + } + + public static string GetDetailedReasonDescription(DisconnectReason reason, Exception exception) + { + var description = reason switch + { + DisconnectReason.Unknown => "The disconnection reason is unknown", + DisconnectReason.RemoteClosed => "The remote peer closed the connection", + DisconnectReason.LocalClosed => "The local endpoint closed the connection", + DisconnectReason.Timeout => "Connection timeout - no data received within timeout period", + DisconnectReason.Error => "A general error occurred causing disconnection", + DisconnectReason.SSLError => "An SSL/TLS error occurred during secure communication", + DisconnectReason.ServerShutdown => "Server is shutting down", + DisconnectReason.Reconnect => "Disconnection for reconnection purposes", + DisconnectReason.ClientRequested => "The client requested disconnection", + DisconnectReason.Forced => "Connection was forcibly closed", + DisconnectReason.NoPongReceived => "No pong response received to ping - peer may be unresponsive", + DisconnectReason.ProtocolError => "A protocol error occurred in message parsing or handling", + DisconnectReason.BufferOverflow => "Receive buffer overflow - data loss occurred", + DisconnectReason.ConnectionReset => "Connection reset by peer", + DisconnectReason.ConnectionAborted => "Connection was aborted", + DisconnectReason.Refused => "Connection was refused by the peer", + DisconnectReason.NetUnreachable => "Network is unreachable", + DisconnectReason.HostUnreachable => "Host is unreachable", + DisconnectReason.InvalidAddress => "Invalid remote address", + DisconnectReason.AddressInUse => "Address is already in use", + DisconnectReason.AccessDenied => "Access denied - permission issue", + DisconnectReason.ResourceExhausted => "System resource exhaustion (memory, file handles, etc.)", + DisconnectReason.InvalidOperation => "Invalid operation on socket", + DisconnectReason.ShutdownInProgress => "Shutdown is in progress", + DisconnectReason.DataTransmissionError => "Error occurred during data transmission", + DisconnectReason.AesEncryptionError => "AES encryption/decryption error", + _ => $"Disconnection with reason: {reason}" + }; + + if (exception != null && exception is SocketException socketEx) + { + description += $" [SocketError: {socketEx.SocketErrorCode} ({(int)socketEx.SocketErrorCode})]"; + } + + return description; + } + + public static Dictionary AnalyzeSocketException(SocketException socketException) + { + var context = new Dictionary(); + + if (socketException == null) + { + return context; + } + + context["SocketErrorCode"] = $"{socketException.SocketErrorCode} ({(int)socketException.SocketErrorCode})"; + context["NativeErrorCode"] = socketException.NativeErrorCode.ToString(); + context["Message"] = socketException.Message ?? "[No message available]"; + + context["ErrorCategory"] = CategorizeSocketError(socketException.SocketErrorCode); + + var recommendation = GetSocketErrorRecommendation(socketException.SocketErrorCode); + if (!string.IsNullOrEmpty(recommendation)) + { + context["Recommendation"] = recommendation; + } + + return context; + } + + public static Dictionary GetEndpointDiagnostics(IPEndPoint endPoint) + { + var context = new Dictionary(); + + if (endPoint == null) + { + context["EndpointInfo"] = "No endpoint information available"; + return context; + } + + try + { + context["Address"] = endPoint.Address?.ToString() ?? "[Unknown]"; + context["Port"] = endPoint.Port.ToString(); + context["AddressFamily"] = endPoint.AddressFamily.ToString(); + context["IsLoopback"] = (endPoint.Address != null ? IPAddress.IsLoopback(endPoint.Address) : false).ToString(); + context["IsIPv4"] = (endPoint.AddressFamily == AddressFamily.InterNetwork).ToString(); + context["IsIPv6"] = (endPoint.AddressFamily == AddressFamily.InterNetworkV6).ToString(); + } + catch (Exception ex) + { + context["Error"] = $"Failed to extract endpoint diagnostics: {ex.Message}"; + } + + return context; + } + + private static string CategorizeSocketError(SocketError errorCode) + { + return errorCode switch + { + + SocketError.ConnectionReset or + SocketError.ConnectionAborted or + SocketError.ConnectionRefused or + SocketError.NotConnected or + SocketError.Shutdown or + SocketError.Disconnecting => "Connection/State Error", + + SocketError.TimedOut => "Timeout Error", + + SocketError.NetworkUnreachable or + SocketError.HostUnreachable or + SocketError.NetworkDown or + SocketError.HostDown => "Network Error", + + SocketError.AddressAlreadyInUse or + SocketError.AddressNotAvailable => "Address Error", + + SocketError.AccessDenied => "Permission Error", + + SocketError.NoBufferSpaceAvailable or + SocketError.TooManyOpenSockets => "Resource Error", + + SocketError.ProtocolNotSupported or + SocketError.ProtocolOption or + SocketError.ProtocolType or + SocketError.InvalidArgument => "Protocol/Argument Error", + + SocketError.OperationNotSupported or + SocketError.OperationAborted => "Operation Error", + + _ => "Other/Unknown Error" + }; + } + + private static string GetSocketErrorRecommendation(SocketError errorCode) + { + return errorCode switch + { + SocketError.ConnectionReset => "Connection was forcibly closed by peer. Check if peer crashed or network was interrupted.", + SocketError.ConnectionRefused => "Peer is not listening on this port. Verify peer is running and port is correct.", + SocketError.TimedOut => "No response from peer within timeout period. Check network connectivity and peer performance.", + SocketError.NetworkUnreachable => "Network path doesn't exist. Check routing and firewall rules.", + SocketError.HostUnreachable => "Cannot reach the host. Verify IP address is correct and host is online.", + SocketError.AddressAlreadyInUse => "Port is already in use. Wait for TIME_WAIT to expire or use different port.", + SocketError.AccessDenied => "Insufficient permissions. May need elevated privileges or firewall reconfiguration.", + SocketError.NoBufferSpaceAvailable => "System buffer exhausted. Consider reducing traffic or increasing system buffers.", + SocketError.TooManyOpenSockets => "Too many open connections. Close idle connections or increase system limits.", + SocketError.ProtocolNotSupported => "Protocol is not supported by system. Verify socket creation parameters.", + _ => null + }; + } + + private static string DetermineInitiatorFromSocketError(SocketError errorCode) + { + return errorCode switch + { + + SocketError.ConnectionReset or + SocketError.Shutdown or + SocketError.Disconnecting => "Remote", + + SocketError.TimedOut or + SocketError.NoBufferSpaceAvailable or + SocketError.TooManyOpenSockets or + SocketError.NetworkDown or + SocketError.NetworkUnreachable => "Local", + + SocketError.ConnectionRefused or + SocketError.HostUnreachable => "Remote", + + _ => "Unknown" + }; + } + + public static Dictionary CreateDisconnectionSummary( + string clientId, + string nickname, + IPEndPoint remoteEndPoint, + DisconnectReason reason, + Exception exception, + TimeSpan? connectionDuration = null) + { + var summary = new Dictionary + { + { "ClientId", string.IsNullOrEmpty(clientId) ? "[Unknown]" : clientId }, + { "Nickname", string.IsNullOrEmpty(nickname) ? "[Not Set]" : nickname }, + { "RemoteEndPoint", remoteEndPoint?.ToString() ?? "[Unknown]" }, + { "DisconnectReason", reason.ToString() }, + { "ReasonDescription", GetDetailedReasonDescription(reason, exception) }, + { "Initiator", DetermineInitiator(reason, exception) }, + { "Timestamp", DateTime.UtcNow.ToString("O") } + }; + + if (connectionDuration.HasValue) + { + summary["ConnectionDuration"] = FormatTimeSpan(connectionDuration.Value); + } + + if (exception != null) + { + summary["ExceptionType"] = exception.GetType().Name; + summary["ExceptionMessage"] = exception.Message ?? "[Exception message not available]"; + + if (exception is SocketException socketEx) + { + var socketContext = AnalyzeSocketException(socketEx); + foreach (var kvp in socketContext) + { + summary[$"Socket_{kvp.Key}"] = kvp.Value; + } + } + } + + if (remoteEndPoint != null) + { + var endpointContext = GetEndpointDiagnostics(remoteEndPoint); + foreach (var kvp in endpointContext) + { + summary[$"RemoteEndpoint_{kvp.Key}"] = kvp.Value; + } + } + + return summary; + } + + private static string FormatTimeSpan(TimeSpan duration) + { + if (duration.TotalHours >= 1) + { + return $"{duration.Hours}h {duration.Minutes}m {duration.Seconds}s"; + } + + if (duration.TotalMinutes >= 1) + { + return $"{duration.Minutes}m {duration.Seconds}s"; + } + + if (duration.TotalSeconds >= 1) + { + return $"{duration.TotalSeconds:F2}s"; + } + + return $"{duration.TotalMilliseconds:F0}ms"; + } + } +} diff --git a/EonaCat.Connections/ConnectionLogManager.cs b/EonaCat.Connections/ConnectionLogManager.cs new file mode 100644 index 0000000..5d4b132 --- /dev/null +++ b/EonaCat.Connections/ConnectionLogManager.cs @@ -0,0 +1,53 @@ +using EonaCat.Connections.ConnectionDiagnostics; + +namespace EonaCat.Connections +{ + + public static class ConnectionLogManager + { + private static ConnectionLogger _serverLogger; + private static ConnectionLogger _clientLogger; + private static readonly object _lockObject = new object(); + + public static ConnectionLogger GetServerLogger() + { + if (_serverLogger == null) + { + lock (_lockObject) + { + if (_serverLogger == null) + { + _serverLogger = new ConnectionLogger(isServer: true); + } + } + } + return _serverLogger; + } + + public static ConnectionLogger GetClientLogger() + { + if (_clientLogger == null) + { + lock (_lockObject) + { + if (_clientLogger == null) + { + _clientLogger = new ConnectionLogger(isServer: false); + } + } + } + return _clientLogger; + } + + public static void Dispose() + { + lock (_lockObject) + { + _serverLogger?.Dispose(); + _clientLogger?.Dispose(); + _serverLogger = null; + _clientLogger = null; + } + } + } +} diff --git a/EonaCat.Connections/Contracts/IConnectorClient.cs b/EonaCat.Connections/Contracts/IConnectorClient.cs new file mode 100644 index 0000000..ac8b76b --- /dev/null +++ b/EonaCat.Connections/Contracts/IConnectorClient.cs @@ -0,0 +1,54 @@ +using EonaCat.Connections.EventArguments; +using ConnectorErrorEventArgs = EonaCat.Connections.EventArguments.ErrorEventArgs; + +namespace EonaCat.Connections.Contracts +{ + public interface IConnectorClient : IDisposable, IAsyncDisposable + { + event EventHandler OnConnected; + event EventHandler OnNicknameSend; + event EventHandler OnDataReceived; + event EventHandler OnDisconnected; + event EventHandler OnSslError; + event EventHandler OnEncryptionError; + event EventHandler OnGeneralError; + event EventHandler OnSocketError; + event EventHandler OnPingResponse; + event EventHandler OnPongResponse; + + bool IsConnected { get; } + bool IsSecure { get; } + bool IsEncrypted { get; } + bool IsTcp { get; } + string IpAddress { get; } + int Port { get; } + string Nickname { get; } + DateTime ConnectionTime { get; } + TimeSpan Uptime { get; } + DateTime LastActive { get; } + long BytesSent { get; } + long BytesReceived { get; } + long MessagesSent { get; } + long MessagesReceived { get; } + + Task ConnectAsync(); + Task WaitForConnectedAsync(TimeSpan? timeout = null, CancellationToken cancellationToken = default); + Task DisconnectAsync(); + Task DisconnectDueTimeoutAsync(); + Task SendAsync(byte[] data); + Task SendAsync(byte[] data, CancellationToken cancellationToken); + Task SendAsync(string message); + Task SendAsync(string message, CancellationToken cancellationToken); + Task SendNicknameAsync(string nickname); + Task SendNicknameAsync(string nickname, CancellationToken cancellationToken); + Task SendAndWaitForResponseAsync(byte[] data, TimeSpan? timeout = null); + Task SendAndWaitForResponseAsync(byte[] data, TimeSpan? timeout, CancellationToken cancellationToken); + Task SendAndWaitForResponseAsync(string message, TimeSpan? timeout = null); + Task SendAndWaitForResponseAsync(string message, TimeSpan? timeout, CancellationToken cancellationToken); + Task SendNicknameAndWaitForResponseAsync(string nickname, TimeSpan? timeout = null); + Task SendNicknameAndWaitForResponseAsync(string nickname, TimeSpan? timeout, CancellationToken cancellationToken); + TimeSpan IdleTime(); + TimeSpan ConnectedTime(); + string GetConnectionHealthSummary(); + } +} diff --git a/EonaCat.Connections/Contracts/IConnectorServer.cs b/EonaCat.Connections/Contracts/IConnectorServer.cs new file mode 100644 index 0000000..36cb630 --- /dev/null +++ b/EonaCat.Connections/Contracts/IConnectorServer.cs @@ -0,0 +1,46 @@ +using EonaCat.Connections.EventArguments; +using EonaCat.Connections.Models; +using ConnectorErrorEventArgs = EonaCat.Connections.EventArguments.ErrorEventArgs; + +namespace EonaCat.Connections.Contracts +{ + public interface IConnectorServer : IDisposable + { + event EventHandler OnConnected; + event EventHandler OnConnectedWithNickname; + event EventHandler OnDataReceived; + event EventHandler OnDisconnected; + event EventHandler OnSslError; + event EventHandler OnEncryptionError; + event EventHandler OnGeneralError; + event EventHandler OnSocketError; + event EventHandler OnClientMissing; + event EventHandler OnClientPingResponse; + event EventHandler OnPongMissed; + + bool IsStarted { get; } + bool IsSecure { get; } + bool IsEncrypted { get; } + ProtocolType Protocol { get; } + string IpAddress { get; } + int Port { get; } + int ActiveConnections { get; } + int MaxConnections { get; } + Stats GetStats(); + Dictionary GetSecurityMetrics(); + Dictionary GetClients(); + List GetClient(string clientId); + + Task StartAsync(); + Task StopAsync(); + Task SendToClientAsync(string clientId, byte[] data); + Task SendToClientAsync(string clientId, string message); + Task SendFromClientToClientAsync(string fromClientId, string toClientId, byte[] data); + Task SendFromClientToClientAsync(string fromClientId, string toClientId, string message); + Task BroadcastAsync(byte[] data); + Task BroadcastAsync(string message); + Task DisconnectClientAsync(string clientId, DisconnectReason reason = DisconnectReason.Unknown, Exception? exception = null); + void SetSeparator(string separator); + void SetSeparator(byte[] separator); + } +} diff --git a/EonaCat.Connections/DisconnectReason.cs b/EonaCat.Connections/DisconnectReason.cs index c31b99b..66c1bde 100644 --- a/EonaCat.Connections/DisconnectReason.cs +++ b/EonaCat.Connections/DisconnectReason.cs @@ -1,10 +1,9 @@ namespace EonaCat.Connections { - // This file is part of the EonaCat project(s) which is released under the Apache License. - // See the LICENSE file or go to https://EonaCat.com/license for full license details. public enum DisconnectReason { + Unknown, RemoteClosed, LocalClosed, @@ -17,5 +16,20 @@ Forced, NoPongReceived, ProtocolError, + + BufferOverflow, + ConnectionReset, + ConnectionAborted, + Refused, + NetUnreachable, + HostUnreachable, + InvalidAddress, + AddressInUse, + AccessDenied, + ResourceExhausted, + InvalidOperation, + ShutdownInProgress, + DataTransmissionError, + AesEncryptionError, } -} \ No newline at end of file +} diff --git a/EonaCat.Connections/EonaCat.Connections.csproj b/EonaCat.Connections/EonaCat.Connections.csproj index 961b564..a073665 100644 --- a/EonaCat.Connections/EonaCat.Connections.csproj +++ b/EonaCat.Connections/EonaCat.Connections.csproj @@ -1,30 +1,44 @@  - netstandard2.0; net48; net8.0 + net481; net8.0 latest enable enable True EonaCat.Connections - EonaCat (Jeroen Saey) - EonaCat (Jeroen Saey) + EonaCat + Jeroen Saey readme.md EonaCat.Connections - 1.1.2 - EonaCat (Jeroen Saey) + 1.0.0 + Jeroen Saey LICENSE - EonaCat.png - https://git.saey.me/EonaCat/EonaCat.Connections - https://git.saey.me/EonaCat/EonaCat.Connections + EonaCat.Connections for TCP/UDP client/servers + icon.ico + icon.png - + + + + + + + - + + + + + + + + + True \ @@ -39,11 +53,19 @@ - - - - - + + + + + + + + + + + + + diff --git a/EonaCat.Connections/EonaCat.ico b/EonaCat.Connections/EonaCat.ico deleted file mode 100644 index 406f2659ac50172f9307c0af9038f473b50b6598..0000000000000000000000000000000000000000 GIT binary patch literal 0 HcmV?d00001 literal 254014 zcmeF42bdH^6Nbs*4mhHcC8}gl0TmP#vzRer!Yr6`&Z56LXArZ9f|vt{V$KOs6u2WJ zK};wZ=>L0rws&V|XLk1@2i)>BGdnvs)1khq>guZMN|h?>-!GLa>HjvBHZ7=HX#<^a zs=~EORlMt*R(h*yrS{z`*v~I-tyGRsxl(1c%1bKmseG>T zt;$rD&s5$~c|qktl}l9)QR%JHRHdp)=zGe22US$Cq6f-h4@BUpfv)#cIa6hf$`>k2 zRsK@>PsLn=0q2^i-*#l7!`Q*I^YEs_21o&;vo7=zD#Y160PTEKw;e7K?lTe7*A# zmEBZwRVr{?4(Oz!3gxc{0@$dd?+2<(Qb8{+E)I+P_rIwQ&#COHQd1?4H z5BTX`=Ur6Bt6&q(3QrEN+&^j3o95}K$C^9uywhBM+2!Ws;U}BJ4?EoKzu*35@4fc1 zW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G}_T5~R~p;|m2@pkLG z+H1e>e%tfo^J0e8s~?Z4#ISVeAP`_t`C3X^Z+YUu-!#6%_4?w8R3Ib7e;>eZgAeAv zBfrcSujvW$65wxA$fXG%L?P2=_<%_gcJ%-Ig8$o|!LMud_o~^|%ci(nDDX#8Oja~c IMBDrS02~H<8~^|S diff --git a/EonaCat.Connections/EventArguments/ClientMissingEventArgs.cs b/EonaCat.Connections/EventArguments/ClientMissingEventArgs.cs new file mode 100644 index 0000000..4579435 --- /dev/null +++ b/EonaCat.Connections/EventArguments/ClientMissingEventArgs.cs @@ -0,0 +1,9 @@ +namespace EonaCat.Connections.EventArguments +{ + public class ClientMissingEventArgs : EventArgs + { + public string ClientId { get; internal set; } + public DateTime Timestamp { get; internal set; } = DateTime.Now; + public byte[] Data { get; internal set; } + } +} diff --git a/EonaCat.Connections/EventArguments/ConnectionEventArgs.cs b/EonaCat.Connections/EventArguments/ConnectionEventArgs.cs index eef70a0..5df167a 100644 --- a/EonaCat.Connections/EventArguments/ConnectionEventArgs.cs +++ b/EonaCat.Connections/EventArguments/ConnectionEventArgs.cs @@ -1,9 +1,6 @@ using System.Net; using System.Net.Sockets; -// This file is part of the EonaCat project(s) which is released under the Apache License. -// See the LICENSE file or go to https://EonaCat.com/license for full license details. - namespace EonaCat.Connections.EventArguments { public class ConnectionEventArgs : EventArgs @@ -15,6 +12,14 @@ namespace EonaCat.Connections.EventArguments public Exception Exception { get; set; } public bool HasException => Exception != null; + public string Initiator { get; set; } + + public string ReasonDetails { get; set; } + + public TimeSpan? ConnectionDuration { get; set; } + + public Dictionary DiagnosticContext { get; set; } + public bool IsLocalDisconnect => Reason == DisconnectReason.LocalClosed || Reason == DisconnectReason.Timeout @@ -46,18 +51,31 @@ namespace EonaCat.Connections.EventArguments switch (socketException.SocketErrorCode) { case SocketError.ConnectionReset: + return DisconnectReason.ConnectionReset; + case SocketError.ConnectionAborted: + return DisconnectReason.ConnectionAborted; case SocketError.Shutdown: case SocketError.Disconnecting: return DisconnectReason.RemoteClosed; - case SocketError.TimedOut: return DisconnectReason.Timeout; - case SocketError.NetworkDown: case SocketError.NetworkReset: case SocketError.NetworkUnreachable: - return DisconnectReason.Error; - + return DisconnectReason.NetUnreachable; + case SocketError.HostUnreachable: + return DisconnectReason.HostUnreachable; + case SocketError.ConnectionRefused: + return DisconnectReason.Refused; + case SocketError.AddressAlreadyInUse: + return DisconnectReason.AddressInUse; + case SocketError.AccessDenied: + return DisconnectReason.AccessDenied; + case SocketError.NoBufferSpaceAvailable: + case SocketError.TooManyOpenSockets: + return DisconnectReason.ResourceExhausted; + case SocketError.InvalidArgument: + return DisconnectReason.InvalidOperation; default: return DisconnectReason.Error; } @@ -77,4 +95,4 @@ namespace EonaCat.Connections.EventArguments return DisconnectReason.Error; } } -} \ No newline at end of file +} diff --git a/EonaCat.Connections/EventArguments/DataReceivedEventArgs.cs b/EonaCat.Connections/EventArguments/DataReceivedEventArgs.cs index e04730e..5868e69 100644 --- a/EonaCat.Connections/EventArguments/DataReceivedEventArgs.cs +++ b/EonaCat.Connections/EventArguments/DataReceivedEventArgs.cs @@ -1,15 +1,12 @@ using System.Net; using System.Text; -// This file is part of the EonaCat project(s) which is released under the Apache License. -// See the LICENSE file or go to https://EonaCat.com/license for full license details. - namespace EonaCat.Connections { public class DataReceivedEventArgs : EventArgs { public string ClientId { get; set; } - public byte[] Data { get; set; } + public byte[] Data { get; set; } public string StringData => Data != null ? Encoding.UTF8.GetString(Data) : string.Empty; public bool IsBinary { get; internal set; } public DateTime Timestamp { get; set; } = DateTime.UtcNow; @@ -17,4 +14,4 @@ namespace EonaCat.Connections public string Nickname { get; set; } public bool HasNickname => !string.IsNullOrWhiteSpace(Nickname); } -} \ No newline at end of file +} diff --git a/EonaCat.Connections/EventArguments/ErrorEventArgs.cs b/EonaCat.Connections/EventArguments/ErrorEventArgs.cs index 79ef798..a57f81d 100644 --- a/EonaCat.Connections/EventArguments/ErrorEventArgs.cs +++ b/EonaCat.Connections/EventArguments/ErrorEventArgs.cs @@ -1,15 +1,12 @@ -namespace EonaCat.Connections.EventArguments +namespace EonaCat.Connections.EventArguments { - // This file is part of the EonaCat project(s) which is released under the Apache License. - // See the LICENSE file or go to https://EonaCat.com/license for full license details. - - public class ErrorEventArgs : EventArgs - { - public string ClientId { get; set; } - public string Nickname { get; set; } - public bool HasNickname => !string.IsNullOrWhiteSpace(Nickname); - public Exception Exception { get; set; } - public string Message { get; set; } - public DateTime Timestamp { get; set; } = DateTime.UtcNow; - } -} \ No newline at end of file + public class ErrorEventArgs : EventArgs + { + public string ClientId { get; set; } + public string Nickname { get; set; } + public bool HasNickname => !string.IsNullOrWhiteSpace(Nickname); + public Exception Exception { get; set; } + public string Message { get; set; } + public DateTime Timestamp { get; set; } = DateTime.UtcNow; + } +} diff --git a/EonaCat.Connections/EventArguments/IdleClientEventArgs.cs b/EonaCat.Connections/EventArguments/IdleClientEventArgs.cs deleted file mode 100644 index 17f3d00..0000000 --- a/EonaCat.Connections/EventArguments/IdleClientEventArgs.cs +++ /dev/null @@ -1,30 +0,0 @@ -using System.Net; - -namespace EonaCat.Connections.EventArguments -{ - // This file is part of the EonaCat project(s) which is released under the Apache License. - // See the LICENSE file or go to https://EonaCat.com/license for full license details. - - public class IdleClientEventArgs : EventArgs - { - public IdleClientEventArgs() { } - - public IdleClientEventArgs(double idleTimeoutSeconds, NetworkClient networkClient, string message) - { - IdleTimeoutSeconds = idleTimeoutSeconds; - NetworkClient = networkClient; - Message = message; - } - - public double IdleTimeoutSeconds { get; set; } - public NetworkClient? NetworkClient { get; set; } - public string? ClientId { get; set; } - public string? Nickname { get; set; } - public IPEndPoint? RemoteEndPoint { get; set; } - public double IdleTimeSeconds { get; set; } - public bool HasClient => NetworkClient != null; - public bool IsIdle => IdleTimeoutSeconds > 0 || IdleTimeSeconds > 0; - public bool HasMessage => !string.IsNullOrEmpty(Message); - public string? Message { get; set; } - } -} \ No newline at end of file diff --git a/EonaCat.Connections/EventArguments/IdleEventArgs.cs b/EonaCat.Connections/EventArguments/IdleEventArgs.cs deleted file mode 100644 index 0828ec8..0000000 --- a/EonaCat.Connections/EventArguments/IdleEventArgs.cs +++ /dev/null @@ -1,24 +0,0 @@ -using EonaCat.Connections.Models; - -namespace EonaCat.Connections.EventArguments -{ - // This file is part of the EonaCat project(s) which is released under the Apache License. - // See the LICENSE file or go to https://EonaCat.com/license for full license details. - - public class IdleEventArgs : EventArgs - { - public IdleEventArgs(double idleTimeoutSeconds, Connection connection, string message) - { - IdleTimeoutSeconds = idleTimeoutSeconds; - Connection = connection; - Message = message; - } - - public double IdleTimeoutSeconds { get; } - public Connection Connection { get; } - public bool HasConnection => Connection != null; - public bool IsIdle => IdleTimeoutSeconds > 0; - public bool HasMessage => !string.IsNullOrEmpty(Message); - public string Message { get; } - } -} \ No newline at end of file diff --git a/EonaCat.Connections/EventArguments/PingEventArgs.cs b/EonaCat.Connections/EventArguments/PingEventArgs.cs index 3bbe66e..9cb43b0 100644 --- a/EonaCat.Connections/EventArguments/PingEventArgs.cs +++ b/EonaCat.Connections/EventArguments/PingEventArgs.cs @@ -2,9 +2,6 @@ namespace EonaCat.Connections.EventArguments { - // This file is part of the EonaCat project(s) which is released under the Apache License. - // See the LICENSE file or go to https://EonaCat.com/license for full license details. - public class PingEventArgs : EventArgs { public string Id { get; set; } @@ -12,4 +9,4 @@ namespace EonaCat.Connections.EventArguments public string Nickname { get; set; } public IPEndPoint RemoteEndPoint { get; set; } } -} \ No newline at end of file +} diff --git a/EonaCat.Connections/Framing/MessageFrameDecoder.cs b/EonaCat.Connections/Framing/MessageFrameDecoder.cs new file mode 100644 index 0000000..374cb6e --- /dev/null +++ b/EonaCat.Connections/Framing/MessageFrameDecoder.cs @@ -0,0 +1,128 @@ +using System.Net; + +namespace EonaCat.Connections.Framing +{ + internal static class MessageFrameDecoder + { + public static bool TryReadLengthPrefixed(MemoryStream stream, int prefixSize, bool useBigEndian, double maxMessageBytes, out byte[]? message) + { + message = null; + var buffer = stream.GetBuffer(); + var bufferedLength = (int)stream.Length; + + if (bufferedLength < prefixSize) + { + return false; + } + + var messageLengthValue = ParseLengthPrefix(buffer, prefixSize, useBigEndian); + if (messageLengthValue <= 0 || messageLengthValue > maxMessageBytes) + { + throw new ProtocolViolationException($"Declared message length {messageLengthValue} is invalid or exceeds max allowed {maxMessageBytes} bytes."); + } + + var messageLength = (int)messageLengthValue; + if (bufferedLength - prefixSize < messageLength) + { + return false; + } + + message = new byte[messageLength]; + Buffer.BlockCopy(buffer, prefixSize, message, 0, messageLength); + RemoveConsumedBytes(stream, prefixSize + messageLength); + return true; + } + + public static bool TryReadDelimited(MemoryStream stream, byte[] delimiter, double maxMessageBytes, out byte[]? message) + { + message = null; + if (delimiter == null || delimiter.Length == 0) + { + throw new ProtocolViolationException("Delimiter framing requires a non-empty delimiter."); + } + + var buffer = stream.GetBuffer(); + var bufferedLength = (int)stream.Length; + var delimiterIndex = IndexOf(buffer, bufferedLength, delimiter); + if (delimiterIndex < 0) + { + if (bufferedLength > maxMessageBytes + delimiter.Length - 1) + { + throw new ProtocolViolationException($"Delimited message exceeds the maximum allowed {maxMessageBytes} bytes."); + } + + return false; + } + + if (delimiterIndex > maxMessageBytes) + { + throw new ProtocolViolationException($"Delimited message length {delimiterIndex} exceeds the maximum allowed {maxMessageBytes} bytes."); + } + + message = new byte[delimiterIndex]; + Buffer.BlockCopy(buffer, 0, message, 0, delimiterIndex); + RemoveConsumedBytes(stream, delimiterIndex + delimiter.Length); + return true; + } + + public static long ParseLengthPrefix(byte[] buffer, int length, bool useBigEndian) + { + if (buffer == null || buffer.Length == 0) + { + throw new ArgumentNullException(nameof(buffer)); + } + + if (length < 1 || length > 8 || length > buffer.Length) + { + throw new ArgumentOutOfRangeException(nameof(length), "Length must be between 1 and 8 bytes and fit in the buffer."); + } + + long value = 0; + for (var index = 0; index < length; index++) + { + value = useBigEndian + ? (value << 8) | buffer[index] + : value | (long)buffer[index] << (8 * index); + } + + return value; + } + + private static int IndexOf(byte[] buffer, int length, byte[] delimiter) + { + if (length < delimiter.Length) + { + return -1; + } + + for (var index = 0; index <= length - delimiter.Length; index++) + { + var matches = true; + for (var delimiterIndex = 0; delimiterIndex < delimiter.Length; delimiterIndex++) + { + if (buffer[index + delimiterIndex] != delimiter[delimiterIndex]) + { + matches = false; + break; + } + } + + if (matches) + { + return index; + } + } + + return -1; + } + + private static void RemoveConsumedBytes(MemoryStream stream, int consumedBytes) + { + var buffer = stream.GetBuffer(); + var remaining = (int)stream.Length - consumedBytes; + Buffer.BlockCopy(buffer, consumedBytes, buffer, 0, remaining); + stream.SetLength(remaining); + stream.Position = remaining; + } + } +} diff --git a/EonaCat.Connections/Framing/MessageFrameEncoder.cs b/EonaCat.Connections/Framing/MessageFrameEncoder.cs new file mode 100644 index 0000000..d168aea --- /dev/null +++ b/EonaCat.Connections/Framing/MessageFrameEncoder.cs @@ -0,0 +1,109 @@ +using EonaCat.Connections.Models; + +namespace EonaCat.Connections.Framing +{ + internal static class MessageFrameEncoder + { + public static byte[] Encode(byte[] payload, Configuration configuration) + { + var result = new byte[GetEncodedLength(payload, configuration)]; + Write(result, payload, configuration); + return result; + } + + public static int GetEncodedLength(byte[] payload, Configuration configuration) + { + if (payload == null) + { + throw new ArgumentNullException(nameof(payload)); + } + + if (configuration == null) + { + throw new ArgumentNullException(nameof(configuration)); + } + + return checked(payload.Length + GetFramingOverhead(configuration)); + } + + public static int Write(byte[] buffer, byte[] payload, Configuration configuration) + { + if (buffer == null) + { + throw new ArgumentNullException(nameof(buffer)); + } + + if (payload == null) + { + throw new ArgumentNullException(nameof(payload)); + } + + if (configuration == null) + { + throw new ArgumentNullException(nameof(configuration)); + } + + var requiredLength = GetEncodedLength(payload, configuration); + if (buffer.Length < requiredLength) + { + throw new InvalidOperationException("Buffer is too small for the framed message."); + } + + var offset = 0; + if (configuration.MessageFraming == FramingMode.LengthPrefixed) + { + WriteLengthPrefix(buffer, payload.Length, configuration.LengthPrefixedLength, configuration.UseBigEndian); + offset = configuration.LengthPrefixedLength; + } + + Buffer.BlockCopy(payload, 0, buffer, offset, payload.Length); + offset += payload.Length; + + if (configuration.MessageFraming == FramingMode.Delimiter && configuration.Delimiter?.Length > 0) + { + Buffer.BlockCopy(configuration.Delimiter, 0, buffer, offset, configuration.Delimiter.Length); + offset += configuration.Delimiter.Length; + } + + return offset; + } + + private static int GetFramingOverhead(Configuration configuration) + { + return configuration.MessageFraming switch + { + FramingMode.LengthPrefixed => ValidatePrefixSize(configuration.LengthPrefixedLength), + FramingMode.Delimiter => configuration.Delimiter?.Length ?? 0, + _ => 0 + }; + } + + private static int ValidatePrefixSize(int prefixSize) + { + if (prefixSize < 1 || prefixSize > sizeof(long)) + { + throw new ArgumentOutOfRangeException(nameof(prefixSize), "Length prefix must contain between 1 and 8 bytes."); + } + + return prefixSize; + } + + private static void WriteLengthPrefix(byte[] buffer, int payloadLength, int prefixSize, bool useBigEndian) + { + ValidatePrefixSize(prefixSize); + var maxLength = prefixSize == sizeof(long) ? long.MaxValue : (1L << (prefixSize * 8)) - 1; + if (payloadLength > maxLength) + { + throw new InvalidOperationException("Data length exceeds length prefix capacity."); + } + + long remainingLength = payloadLength; + for (var index = 0; index < prefixSize; index++) + { + var targetIndex = useBigEndian ? prefixSize - 1 - index : index; + buffer[targetIndex] = (byte)(remainingLength & 0xFF); + remainingLength >>= 8; + } + } + } +} diff --git a/EonaCat.Connections/Helpers/AesKeyExchange.cs b/EonaCat.Connections/Helpers/AesKeyExchange.cs index 6b08bc2..d0e79eb 100644 --- a/EonaCat.Connections/Helpers/AesKeyExchange.cs +++ b/EonaCat.Connections/Helpers/AesKeyExchange.cs @@ -3,29 +3,21 @@ using System.Text; namespace EonaCat.Connections.Helpers { - // This file is part of the EonaCat project(s) which is released under the Apache License. - // See the LICENSE file or go to https://EonaCat.com/license for full license details. - public static class AesKeyExchange { - // 256-bit salt + private const int _saltSize = 32; - // 128-bit IV private const int _ivSize = 16; - // 256-bit AES key private const int _aesKeySize = 32; - // 256-bit HMAC key (key confirmation) private const int _hmacKeySize = 32; - // PBKDF2 iterations private const int _iterations = 800_000; private static readonly byte[] KeyConfirmationLabel = Encoding.UTF8.GetBytes("KEYCONFIRMATION"); - // AES block size for PKCS7 padding public static int MaxEncryptionOverhead => 16; public static Task EncryptDataAsync(byte[] data, int length, Aes aes) @@ -62,14 +54,12 @@ namespace EonaCat.Connections.Helpers var salt = RandomBytes(_saltSize); var iv = RandomBytes(_ivSize); - // Derive AES key and HMAC key (for key confirmation) var keyMaterial = DeriveKey(password, salt, _aesKeySize + _hmacKeySize); var aesKey = new byte[_aesKeySize]; var hmacKey = new byte[_hmacKeySize]; Buffer.BlockCopy(keyMaterial, 0, aesKey, 0, _aesKeySize); Buffer.BlockCopy(keyMaterial, _aesKeySize, hmacKey, 0, _hmacKeySize); - // Compute key confirmation HMAC = HMAC(hmacKey, "KEYCONFIRM" || salt || iv) byte[] keyConfirm; using (var h = new HMACSHA256(hmacKey)) { @@ -79,13 +69,11 @@ namespace EonaCat.Connections.Helpers keyConfirm = h.Hash; } - // Send: salt, iv, keyConfirm (each length-prefixed 4-byte big-endian) await WriteWithLengthAsync(stream, salt).ConfigureAwait(false); await WriteWithLengthAsync(stream, iv).ConfigureAwait(false); await WriteWithLengthAsync(stream, keyConfirm).ConfigureAwait(false); await stream.FlushAsync().ConfigureAwait(false); - // Configure AES and return aes.KeySize = 256; aes.Mode = CipherMode.CBC; aes.Padding = PaddingMode.PKCS7; @@ -200,17 +188,10 @@ namespace EonaCat.Connections.Helpers private static byte[] DeriveKey(string password, byte[] salt, int size) { -#if NET472_OR_GREATER || NET8_0_OR_GREATER using (var pbkdf2 = new Rfc2898DeriveBytes(password, salt, _iterations, HashAlgorithmName.SHA256)) { return pbkdf2.GetBytes(size); } -#else - using (var pbkdf2 = new Rfc2898DeriveBytes(password, salt, _iterations)) - { - return pbkdf2.GetBytes(size); - } -#endif } private static byte[] RandomBytes(int total) @@ -244,4 +225,4 @@ namespace EonaCat.Connections.Helpers #endif } } -} \ No newline at end of file +} diff --git a/EonaCat.Connections/Helpers/CertificateHelper.cs b/EonaCat.Connections/Helpers/CertificateHelper.cs new file mode 100644 index 0000000..00e5392 --- /dev/null +++ b/EonaCat.Connections/Helpers/CertificateHelper.cs @@ -0,0 +1,270 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Net; +using System.Net.Security; +using System.Security.Cryptography; +using System.Security.Cryptography.X509Certificates; +using System.Text; +using System.Threading.Tasks; + +namespace EonaCat.Connections.Helpers +{ + public static class CertificateHelper + { + public static event EventHandler OnError; + + public static void CheckCertificate(HttpWebRequest request) + { + //TODO: As selfSigned certificates are not working and hang the client (for now return true) + ServicePointManager.ServerCertificateValidationCallback = new RemoteCertificateValidationCallback(ValidateServerCertificate); + } + + public static void InstallCertificate(X509Certificate2 certificate, StoreName storeName = StoreName.My, StoreLocation storeLocation = StoreLocation.LocalMachine) + { + using (X509Store store = new X509Store(storeName, storeLocation)) + { + store.Open(OpenFlags.ReadWrite); + store.Add(certificate); + store.Close(); + } + } + + public static void RemoveCertificate(X509Certificate2 certificate, StoreName storeName = StoreName.My, StoreLocation storeLocation = StoreLocation.LocalMachine) + { + using (X509Store store = new X509Store(storeName, storeLocation)) + { + store.Open(OpenFlags.ReadWrite); + store.Remove(certificate); + store.Close(); + } + } + + private static bool ValidateServerCertificate(object sender, X509Certificate certificate, X509Chain chain, SslPolicyErrors sslPolicyErrors) + { + return true; + //return sslPolicyErrors == SslPolicyErrors.None; + } + + public static X509Certificate2 LoadFromFile(string certificatePath, string certificatePassword = null) + { + if (!string.IsNullOrWhiteSpace(certificatePassword)) + { + return new X509Certificate2(certificatePath, certificatePassword); + } + else + { + return new X509Certificate2(certificatePath); + } + } + + public static X509Certificate2 GetCertificate(string certificatePath = null, string certificatePassword = null, string certificateThumbprint = null, string privateKeyPath = null) + { + X509Certificate2 certificate = null; + + try + { + if (!string.IsNullOrWhiteSpace(certificatePath)) + { + var extension = Path.GetExtension(certificatePath)?.ToLower(); + if (extension == ".pfx" || extension == ".p12") + { + // PFX/P12 file loading (supports encrypted private keys) + certificate = LoadFromFile(certificatePath, certificatePassword); + } + else if (extension == ".cer" || extension == ".crt") + { + // CER/CRT file loading (only the certificate, no private key) + certificate = LoadFromFile(certificatePath, certificatePassword); + } + else if (extension == ".pem") + { + // PEM file loading (supports both certificate and private key) + certificate = LoadPemCertificate(certificatePath, certificatePassword); + } + else + { + OnError?.Invoke(null, $"Unsupported certificate file format: {extension}"); + return null; + } + + if (certificate == null) + { + OnError?.Invoke(null, "Failed to load the certificate"); + return null; + } + + // If a private key is supplied separately, load and attach it + if (!string.IsNullOrWhiteSpace(privateKeyPath)) + { + var privateKey = LoadPrivateKeyFromPem(privateKeyPath); + if (privateKey != null) + { + certificate = certificate.CopyWithPrivateKey(privateKey); + } + } + } + else if (!string.IsNullOrWhiteSpace(certificateThumbprint)) + { + certificate = LoadFromKeyStore(valueToFind: certificateThumbprint); + certificate ??= LoadFromKeyStore(valueToFind: certificateThumbprint, storeLocation: StoreLocation.CurrentUser); + } + } + catch (Exception ex) + { + OnError?.Invoke(null, ex.Message); + } + return certificate; + } + + public static X509Certificate2 LoadPemCertificate(string certFilePath, string password) + { + try + { + var certBytes = File.ReadAllBytes(certFilePath); + X509Certificate2 cert = null; + string certText = Encoding.UTF8.GetString(certBytes); + + if (certText.Contains("BEGIN CERTIFICATE")) + { + // Certificate only + cert = new X509Certificate2(certBytes); + } + else if (certText.Contains("BEGIN PRIVATE KEY") || certText.Contains("BEGIN ENCRYPTED PRIVATE KEY")) + { + // Initialize certificate with private key + cert = new X509Certificate2(certBytes); + cert = cert.CopyWithPrivateKey(LoadPrivateKeyFromPem(certFilePath)); + } + + return cert; + } + catch (Exception ex) + { + OnError?.Invoke(null, $"Error loading PEM certificate: {ex.Message}"); + return null; + } + } + + public static string ExtractPrivateKeyFromPem(string pemFilePath) + { + try + { + string pemContents = File.ReadAllText(pemFilePath); + + // Strip out the header/footer of the private key section + string privateKeyPem = pemContents + .Replace("-----BEGIN PRIVATE KEY-----", "") + .Replace("-----END PRIVATE KEY-----", "") + .Replace("-----BEGIN ENCRYPTED PRIVATE KEY-----", "") + .Replace("-----END ENCRYPTED PRIVATE KEY-----", "") + .Trim(); + + return privateKeyPem; + } + catch (Exception ex) + { + OnError?.Invoke(null, $"Error extracting private key from PEM: {ex.Message}"); + return null; + } + } + + public static RSA LoadPrivateKeyFromPem(string privateKeyPath) + { + try + { + if (string.IsNullOrEmpty(privateKeyPath)) + { + OnError?.Invoke(null, "Please specify the private key file path"); + return null; + } + + // PEM might have private key, extract it + string keyText = ExtractPrivateKeyFromPem(privateKeyPath); + if (string.IsNullOrWhiteSpace(keyText)) + { + OnError?.Invoke(null, "Invalid or empty private key content."); + return null; + } + + // Load the private key + RSA privateKey = null; + +#if NET48_OR_GREATER + // This is a workaround for .NET Framework, as it does not support encrypted private keys + // You may need BouncyCastle here for .NET Framework to parse encrypted private keys. + // Below is commented as it's unnecessary for .NET 6.0 and greater + /* + using (var reader = new StringReader(keyText)) + { + var pemReader = new PemReader(reader); + var keyPair = pemReader.ReadObject() as AsymmetricCipherKeyPair; + privateKey = DotNetUtilities.ToRSA((RsaPrivateCrtKeyParameters)keyPair.Private); + } + */ +#endif + +#if NET6_0_OR_GREATER + // For .NET 6.0 and higher, you can directly load the private key with ImportFromPem + privateKey = RSA.Create(); + + try + { + privateKey.ImportFromPem(keyText.ToCharArray()); + } + catch (CryptographicException ex) + { + OnError?.Invoke(null, $"Error importing private key: {ex.Message}"); + return null; + } +#endif + + return privateKey; + } + catch (Exception ex) + { + OnError?.Invoke(null, $"Error loading private key: {ex.Message}"); + return null; + } + } + + + public static X509Certificate2 LoadFromKeyStore(StoreName storeName = StoreName.My, X509FindType findType = X509FindType.FindByThumbprint, string valueToFind = null, StoreLocation storeLocation = StoreLocation.LocalMachine, bool onlyGetValidCertificates = false) + { + // Open the certificate store + X509Store store = new X509Store(storeName, storeLocation); + store.Open(OpenFlags.ReadOnly); + + try + { + if (valueToFind == null) + { + OnError?.Invoke(null, "Please specify the value to search for"); + return null; + } + + // Find the certificate + X509Certificate2Collection certificates = store.Certificates.Find( + findType, + valueToFind, + onlyGetValidCertificates); + + if (certificates.Count > 0) + { + X509Certificate2 certificate = certificates[0]; + return certificate; + } + else + { + OnError?.Invoke(null, $"The certificate '{valueToFind}' was not found"); + return null; + } + } + finally + { + // Close the store + store.Close(); + } + } + } +} diff --git a/EonaCat.Connections/Helpers/HandlingHelpers.cs b/EonaCat.Connections/Helpers/HandlingHelpers.cs new file mode 100644 index 0000000..72a8258 --- /dev/null +++ b/EonaCat.Connections/Helpers/HandlingHelpers.cs @@ -0,0 +1,169 @@ +namespace EonaCat.Connections.Helpers +{ + public static class HandlingHelpers + { + + public static void SafeInvokeEventHandler(EventHandler handler, object sender, TEventArgs args, string eventName, Action logAction = null) where TEventArgs : EventArgs + { + if (handler == null) + { + return; + } + + try + { + handler.Invoke(sender, args); + } + catch (Exception ex) + { + string errorMsg = $"Exception in event handler for '{eventName}': {ex.GetType().Name} - {ex.Message}"; + logAction?.Invoke(errorMsg); + + System.Diagnostics.Debug.WriteLine(errorMsg); + System.Diagnostics.Debug.WriteLine(ex.StackTrace); + } + } + + public static void SafeInvokeEventHandler(EventHandler handler, object sender, EventArgs args, string eventName, Action logAction = null) + { + if (handler == null) + { + return; + } + + try + { + handler.Invoke(sender, args); + } + catch (Exception ex) + { + string errorMsg = $"Exception in event handler for '{eventName}': {ex.GetType().Name} - {ex.Message}"; + logAction?.Invoke(errorMsg); + System.Diagnostics.Debug.WriteLine(errorMsg); + System.Diagnostics.Debug.WriteLine(ex.StackTrace); + } + } + + public static Task SafeFireAndForgetTaskAsync(Func asyncAction, string taskName, Action logAction = null) + { + if (asyncAction == null) + { + throw new ArgumentNullException(nameof(asyncAction)); + } + + return Task.Run(async () => + { + try + { + await asyncAction(); + } + catch (OperationCanceledException) + { + + string msg = $"Fire-and-forget task '{taskName}' was cancelled"; + System.Diagnostics.Debug.WriteLine(msg); + } + catch (Exception ex) + { + string errorMsg = $"Unobserved exception in fire-and-forget task '{taskName}': {ex.GetType().Name} - {ex.Message}"; + logAction?.Invoke(errorMsg); + System.Diagnostics.Debug.WriteLine(errorMsg); + System.Diagnostics.Debug.WriteLine(ex.StackTrace); + } + }); + } + + public static Task SafeFireAndForgetTaskAsync(Action action, string taskName, Action logAction = null) + { + if (action == null) + { + throw new ArgumentNullException(nameof(action)); + } + + return Task.Run(() => + { + try + { + action(); + } + catch (OperationCanceledException) + { + string msg = $"Fire-and-forget task '{taskName}' was cancelled"; + System.Diagnostics.Debug.WriteLine(msg); + } + catch (Exception ex) + { + string errorMsg = $"Unobserved exception in fire-and-forget task '{taskName}': {ex.GetType().Name} - {ex.Message}"; + logAction?.Invoke(errorMsg); + System.Diagnostics.Debug.WriteLine(errorMsg); + System.Diagnostics.Debug.WriteLine(ex.StackTrace); + } + }); + } + + public static void SafeDispose(IDisposable disposable, string objectName = "object", Action logAction = null) + { + if (disposable == null) + { + return; + } + + try + { + disposable?.Dispose(); + } + catch (Exception ex) + { + string errorMsg = $"Exception while disposing '{objectName}': {ex.GetType().Name} - {ex.Message}"; + logAction?.Invoke(errorMsg); + System.Diagnostics.Debug.WriteLine(errorMsg); + } + } + + public static async Task SafeDisposeAsync(IAsyncDisposable asyncDisposable, string objectName = "object", Action logAction = null) + { + if (asyncDisposable == null) + { + return; + } + + try + { + await asyncDisposable.DisposeAsync(); + } + catch (Exception ex) + { + string errorMsg = $"Exception while disposing '{objectName}': {ex.GetType().Name} - {ex.Message}"; + logAction?.Invoke(errorMsg); + System.Diagnostics.Debug.WriteLine(errorMsg); + } + } + + public static void SafeClose(Action closeAction, string objectName = "stream", Action logAction = null) + { + if (closeAction == null) + { + return; + } + + try + { + closeAction(); + } + catch (System.Net.Sockets.SocketException ex) when (ex.SocketErrorCode == System.Net.Sockets.SocketError.ConnectionReset || ex.SocketErrorCode == System.Net.Sockets.SocketError.Shutdown) + { + + } + catch (ObjectDisposedException) + { + + } + catch (Exception ex) + { + string errorMsg = $"Exception while closing '{objectName}': {ex.GetType().Name} - {ex.Message}"; + logAction?.Invoke(errorMsg); + System.Diagnostics.Debug.WriteLine(errorMsg); + } + } + } +} diff --git a/EonaCat.Connections/Helpers/HealthApiServer.cs b/EonaCat.Connections/Helpers/HealthApiServer.cs index f8b5cfb..ca1e6f5 100644 --- a/EonaCat.Connections/Helpers/HealthApiServer.cs +++ b/EonaCat.Connections/Helpers/HealthApiServer.cs @@ -1,16 +1,11 @@ -using System.Net; +using System.Net; using System.Net.Sockets; using System.Text; +using System.Diagnostics; namespace EonaCat.Connections.Helpers { - // This file is part of the EonaCat project(s) which is released under the Apache License. - // See the LICENSE file or go to https://EonaCat.com/license for full license details. - ///

- /// A lightweight HTTP server that exposes health and status information via a REST API. - /// Listens on a configurable port (use 0 for a random available port). - /// public class HealthApiServer : IDisposable { private TcpListener _listener; @@ -19,45 +14,39 @@ namespace EonaCat.Connections.Helpers private volatile bool _running; private readonly Func _getHealthJson; private readonly Func _getStatusJson; - private int _maxRequestSize = 10 * 1024 * 1024; // 10 MB default - /// - /// Gets or sets the maximum HTTP request size in bytes. - /// Defaults to 10 MB. Set before calling Start(). - /// - public int MaxRequestSize - { - get => _maxRequestSize; - set => _maxRequestSize = Math.Max(1024, value); // Minimum 1 KB - } - - /// - /// Gets the actual port the server is listening on. - /// Returns 0 if the server is not started. - /// public int Port { get; private set; } - /// - /// Gets whether the server is currently running. - /// public bool IsRunning => _running; - /// - /// Creates a new HealthApiServer. - /// - /// Callback that returns the JSON for the /health endpoint. - /// Callback that returns the JSON for the /status endpoint. + public bool IsSharedPort { get; private set; } + + internal static string GetProcessName() + { + using (var process = Process.GetCurrentProcess()) + { + return process.ProcessName; + } + } + + internal void StartSharedPort(int port) + { + if (_running && !IsSharedPort) + { + throw new InvalidOperationException("The health API is already using a separate listener."); + } + + Port = port; + IsSharedPort = true; + _running = true; + } + public HealthApiServer(Func getHealthJson, Func getStatusJson) { _getHealthJson = getHealthJson ?? throw new ArgumentNullException(nameof(getHealthJson)); _getStatusJson = getStatusJson ?? throw new ArgumentNullException(nameof(getStatusJson)); } - /// - /// Starts the HTTP health API server. - /// - /// Port to listen on. Use 0 for a random available port. - /// IP address to bind to. Use IPAddress.Any for Docker/container environments. Defaults to IPAddress.Loopback. public void Start(int port = 0, IPAddress bindAddress = null) { if (_running) @@ -77,9 +66,6 @@ namespace EonaCat.Connections.Helpers _listenTask = Task.Run(async () => await AcceptLoopAsync(token).ConfigureAwait(false), token); } - /// - /// Stops the HTTP health API server. - /// public void Stop() { if (!_running) @@ -94,9 +80,9 @@ namespace EonaCat.Connections.Helpers { _listener?.Stop(); } - catch + catch (Exception) { - // Swallow + } try @@ -108,6 +94,7 @@ namespace EonaCat.Connections.Helpers } Port = 0; + IsSharedPort = false; } private async Task AcceptLoopAsync(CancellationToken token) @@ -118,7 +105,9 @@ namespace EonaCat.Connections.Helpers try { client = await _listener.AcceptTcpClientAsync().ConfigureAwait(false); - _ = Task.Run(() => HandleRequestAsync(client), token); + HandlingHelpers.SafeFireAndForgetTaskAsync( + () => HandleRequestAsync(client), + "HealthApiServer.HandleRequest"); } catch (ObjectDisposedException) { @@ -128,9 +117,9 @@ namespace EonaCat.Connections.Helpers { break; } - catch + catch (Exception) { - // Swallow individual connection errors to keep the loop alive + } } } @@ -145,62 +134,80 @@ namespace EonaCat.Connections.Helpers client.SendTimeout = 5000; using var stream = client.GetStream(); - var requestLine = await ReadRequestLineAsync(stream).ConfigureAwait(false); - - if (string.IsNullOrEmpty(requestLine)) - { - await WriteResponseAsync(stream, 400, "Bad Request", "text/plain", "Bad Request").ConfigureAwait(false); - return; - } - - var parts = requestLine.Split(' '); - if (parts.Length < 2) - { - await WriteResponseAsync(stream, 400, "Bad Request", "text/plain", "Bad Request").ConfigureAwait(false); - return; - } - - var method = parts[0].ToUpperInvariant(); - var path = parts[1].Split('?')[0].TrimEnd('/').ToLowerInvariant(); - - if (method != "GET") - { - await WriteResponseAsync(stream, 405, "Method Not Allowed", "text/plain", "Method Not Allowed").ConfigureAwait(false); - return; - } - - // Drain remaining headers - await DrainHeadersAsync(stream).ConfigureAwait(false); - - switch (path) - { - case "" or "/": - var indexJson = "{\"endpoints\":[\"/health\",\"/status\"]}"; - await WriteResponseAsync(stream, 200, "OK", "application/json", indexJson).ConfigureAwait(false); - break; - - case "/health": - var healthJson = SafeGetJson(_getHealthJson); - await WriteResponseAsync(stream, 200, "OK", "application/json", healthJson).ConfigureAwait(false); - break; - - case "/status": - var statusJson = SafeGetJson(_getStatusJson); - await WriteResponseAsync(stream, 200, "OK", "application/json", statusJson).ConfigureAwait(false); - break; - - default: - await WriteResponseAsync(stream, 404, "Not Found", "text/plain", "Not Found").ConfigureAwait(false); - break; - } + await HandleRequestAsync(stream).ConfigureAwait(false); } } - catch + catch (Exception) { - // Swallow individual request errors + } } + internal async Task HandleRequestAsync(Stream stream, bool allowAccess = true) + { + var requestLine = await ReadRequestLineAsync(stream).ConfigureAwait(false); + + if (string.IsNullOrEmpty(requestLine)) + { + await WriteResponseAsync(stream, 400, "Bad Request", "text/plain", "Bad Request").ConfigureAwait(false); + return; + } + + var parts = requestLine.Split(' '); + if (parts.Length < 2) + { + await WriteResponseAsync(stream, 400, "Bad Request", "text/plain", "Bad Request").ConfigureAwait(false); + return; + } + + var method = parts[0].ToUpperInvariant(); + var path = parts[1].Split('?')[0].TrimEnd('/').ToLowerInvariant(); + await DrainHeadersAsync(stream).ConfigureAwait(false); + + if (!allowAccess) + { + await WriteResponseAsync(stream, 403, "Forbidden", "text/plain", "Forbidden").ConfigureAwait(false); + return; + } + + if (method != "GET") + { + await WriteResponseAsync(stream, 405, "Method Not Allowed", "text/plain", "Method Not Allowed").ConfigureAwait(false); + return; + } + + switch (path) + { + case "" or "/": + var indexJson = "{\"endpoints\":[\"/health\",\"/status\",\"/dashboard\"]}"; + await WriteResponseAsync(stream, 200, "OK", "application/json", indexJson).ConfigureAwait(false); + break; + + case "/dashboard": + using (var resource = typeof(HealthApiServer).Assembly.GetManifestResourceStream("EonaCat.Connections.Helpers.TrafficDashboard.html") + ?? throw new InvalidOperationException("The traffic dashboard resource is missing.")) + using (var reader = new StreamReader(resource, Encoding.UTF8)) + { + await WriteResponseAsync(stream, 200, "OK", "text/html", reader.ReadToEnd()).ConfigureAwait(false); + } + break; + + case "/health": + var healthJson = SafeGetJson(_getHealthJson); + await WriteResponseAsync(stream, 200, "OK", "application/json", healthJson).ConfigureAwait(false); + break; + + case "/status": + var statusJson = SafeGetJson(_getStatusJson); + await WriteResponseAsync(stream, 200, "OK", "application/json", statusJson).ConfigureAwait(false); + break; + + default: + await WriteResponseAsync(stream, 404, "Not Found", "text/plain", "Not Found").ConfigureAwait(false); + break; + } + } + private static string SafeGetJson(Func getter) { try @@ -213,14 +220,13 @@ namespace EonaCat.Connections.Helpers } } - private async Task ReadRequestLineAsync(NetworkStream stream) + private static async Task ReadRequestLineAsync(Stream stream) { var sb = new StringBuilder(); var buffer = new byte[1]; var prev = (byte)0; - int maxLineSize = Math.Min(8192, _maxRequestSize); // Limit request line size - while (sb.Length < maxLineSize) + while (sb.Length < 8192) { int read = await stream.ReadAsync(buffer, 0, 1).ConfigureAwait(false); if (read == 0) @@ -234,12 +240,6 @@ namespace EonaCat.Connections.Helpers break; } - // Security: Reject null bytes and other control characters that shouldn't be in HTTP headers - if (b < 32 && b != (byte)'\r' && b != (byte)'\t') - { - throw new InvalidOperationException("Invalid character in HTTP request line"); - } - if (b != (byte)'\r') { sb.Append((char)b); @@ -248,24 +248,16 @@ namespace EonaCat.Connections.Helpers prev = b; } - // Security: Check if request line exceeds limit - if (sb.Length >= maxLineSize) - { - throw new InvalidOperationException("HTTP request line exceeds maximum size"); - } - return sb.ToString(); } - private async Task DrainHeadersAsync(NetworkStream stream) + private static async Task DrainHeadersAsync(Stream stream) { var sb = new StringBuilder(); var buffer = new byte[1]; int consecutiveNewlines = 0; - int totalBytesRead = 0; - int maxHeaderSize = Math.Min(65536, _maxRequestSize); // Limit header size to 64 KB - while (consecutiveNewlines < 2 && totalBytesRead < maxHeaderSize) + while (consecutiveNewlines < 2) { int read = await stream.ReadAsync(buffer, 0, 1).ConfigureAwait(false); if (read == 0) @@ -273,14 +265,6 @@ namespace EonaCat.Connections.Helpers break; } - totalBytesRead++; - - // Security: Reject null bytes in headers - if (buffer[0] == 0) - { - throw new InvalidOperationException("Null byte in HTTP headers"); - } - if (buffer[0] == (byte)'\n') { consecutiveNewlines++; @@ -290,43 +274,18 @@ namespace EonaCat.Connections.Helpers consecutiveNewlines = 0; } } - - // Security: Check if headers exceed limit - if (totalBytesRead >= maxHeaderSize) - { - throw new InvalidOperationException("HTTP headers exceed maximum size"); - } } - private async Task WriteResponseAsync(NetworkStream stream, int statusCode, string statusText, string contentType, string body) + private static async Task WriteResponseAsync(Stream stream, int statusCode, string statusText, string contentType, string body) { var bodyBytes = Encoding.UTF8.GetBytes(body); - - // Security: Enforce maximum response size - if (bodyBytes.Length > _maxRequestSize) - { - // Send error response instead - bodyBytes = Encoding.UTF8.GetBytes("{\"error\":\"Response too large\"}"); - } - - // Security: Validate content type to prevent injection - if (!string.IsNullOrEmpty(contentType) && - (contentType.Contains("\r") || contentType.Contains("\n") || contentType.Contains("\0"))) - { - contentType = "application/json"; - } - var header = $"HTTP/1.1 {statusCode} {statusText}\r\n" + $"Content-Type: {contentType}; charset=utf-8\r\n" + $"Content-Length: {bodyBytes.Length}\r\n" + "Access-Control-Allow-Origin: *\r\n" + "Connection: close\r\n" + "X-Content-Type-Options: nosniff\r\n" + - "X-Frame-Options: DENY\r\n" + - "X-XSS-Protection: 1; mode=block\r\n" + - "Strict-Transport-Security: max-age=31536000; includeSubDomains\r\n" + - "Cache-Control: no-store, no-cache, must-revalidate, private\r\n" + - "Pragma: no-cache\r\n" + + "Cache-Control: no-store\r\n" + "\r\n"; var headerBytes = Encoding.ASCII.GetBytes(header); @@ -335,9 +294,6 @@ namespace EonaCat.Connections.Helpers await stream.FlushAsync().ConfigureAwait(false); } - /// - /// Escapes a string value for safe embedding in JSON output. - /// public static string JsonEscape(string value) { if (value == null) diff --git a/EonaCat.Connections/Helpers/LoadTester.cs b/EonaCat.Connections/Helpers/LoadTester.cs new file mode 100644 index 0000000..4c7f025 --- /dev/null +++ b/EonaCat.Connections/Helpers/LoadTester.cs @@ -0,0 +1,261 @@ +using System.Collections.Concurrent; +using EonaCat.Connections.Models; + +namespace EonaCat.Connections.Helpers +{ + + public class LoadTester : IDisposable + { + public static event EventHandler OnLog; + private readonly Configuration _configuration; + private readonly int _targetConnections; + private readonly ConcurrentDictionary _connections; + private CancellationTokenSource _testCts; + private volatile bool _isRunning; + private DateTime _startTime; + + private long _successfulConnections; + private long _failedConnections; + private long _messagesSent; + private long _bytesSent; + private long _messagesReceived; + private long _bytesReceived; + private long _errors; + + public LoadTester(Configuration configuration, int targetConnections) + { + _configuration = configuration ?? throw new ArgumentNullException(nameof(configuration)); + _targetConnections = Math.Max(1, targetConnections); + _connections = new ConcurrentDictionary(); + } + + public async Task RunAsync(TimeSpan duration, int connectionRatePerSecond = 1000, int messageRate = 1) + { + if (_isRunning) + { + throw new InvalidOperationException("Test already running"); + } + + _isRunning = true; + _testCts = new CancellationTokenSource(duration); + _startTime = DateTime.UtcNow; + + var connectionTask = EstablishConnectionsAsync(connectionRatePerSecond, _testCts.Token); + var messageTask = SendMessagesAsync(messageRate, _testCts.Token); + var monitorTask = MonitorProgressAsync(_testCts.Token); + + try + { + await Task.WhenAll(connectionTask, messageTask, monitorTask).ConfigureAwait(false); + } + catch (OperationCanceledException) + { + + } + finally + { + _isRunning = false; + await CloseAllConnectionsAsync(); + } + } + + private async Task EstablishConnectionsAsync(int connectionsPerSecond, CancellationToken token) + { + var interval = TimeSpan.FromMilliseconds(1000.0 / Math.Max(1, connectionsPerSecond)); + var connectionId = 0; + + try + { + while (!token.IsCancellationRequested && _connections.Count < _targetConnections) + { + var id = $"conn_{connectionId++}"; + + try + { + var client = new NetworkClient(_configuration); + + var capturedId = id; + client.OnConnected += (sender, e) => + { + + }; + + client.OnGeneralError += (sender, e) => + { + Interlocked.Increment(ref _errors); + }; + + client.OnSocketError += (sender, e) => + { + Interlocked.Increment(ref _errors); + }; + + client.OnDisconnected += (sender, e) => + { + _connections.TryRemove(capturedId, out _); + }; + + await client.ConnectAsync().ConfigureAwait(false); + + if (_connections.TryAdd(id, client)) + { + Interlocked.Increment(ref _successfulConnections); + } + else + { + client.Dispose(); + } + } + catch + { + Interlocked.Increment(ref _failedConnections); + } + + await Task.Delay(interval, token).ConfigureAwait(false); + } + } + catch (OperationCanceledException) + { + + } + } + + private async Task SendMessagesAsync(int messagesPerSecond, CancellationToken token) + { + var interval = TimeSpan.FromMilliseconds(1000.0 / Math.Max(1, messagesPerSecond)); + var testMessage = "LOAD_TEST_MESSAGE"; + + try + { + while (!token.IsCancellationRequested) + { + foreach (var kvp in _connections) + { + if (token.IsCancellationRequested) + { + break; + } + + try + { + await kvp.Value.SendAsync(testMessage).ConfigureAwait(false); + Interlocked.Increment(ref _messagesSent); + Interlocked.Add(ref _bytesSent, System.Text.Encoding.UTF8.GetByteCount(testMessage)); + } + catch + { + Interlocked.Increment(ref _errors); + _connections.TryRemove(kvp.Key, out _); + } + } + + await Task.Delay(interval, token).ConfigureAwait(false); + } + } + catch (OperationCanceledException) + { + + } + } + + private async Task MonitorProgressAsync(CancellationToken token) + { + try + { + while (!token.IsCancellationRequested) + { + await Task.Delay(TimeSpan.FromSeconds(10), token).ConfigureAwait(false); + var elapsed = DateTime.UtcNow - _startTime; + await WriteToLogAsync($"[{elapsed:hh\\:mm\\:ss}] Connections: {_connections.Count}/{_targetConnections}, " + + $"Messages: {_messagesSent}, Bytes: {_bytesSent / (1024 * 1024)} MB, Errors: {_errors}"); + } + } + catch (OperationCanceledException) + { + + } + } + + private async Task WriteToLogAsync(string text) + { + OnLog?.Invoke(this, new LogMessage { Type = LogType.Debug, Message = text }); + } + + private async Task CloseAllConnectionsAsync() + { + var tasks = _connections.Values.Select(async client => + { + try + { + await client.DisconnectAsync().ConfigureAwait(false); + client?.Dispose(); + } + catch { } + }); + + await Task.WhenAll(tasks).ConfigureAwait(false); + _connections.Clear(); + } + + public LoadTestReport GetReport() + { + var elapsed = DateTime.UtcNow - _startTime; + + return new LoadTestReport + { + Duration = elapsed, + TargetConnections = _targetConnections, + ActualConnections = _connections.Count, + SuccessfulConnections = _successfulConnections, + FailedConnections = _failedConnections, + MessagesSent = _messagesSent, + BytesSent = _bytesSent, + MessagesReceived = _messagesReceived, + BytesReceived = _bytesReceived, + Errors = _errors, + MessagesPerSecond = elapsed.TotalSeconds > 0 ? _messagesSent / elapsed.TotalSeconds : 0, + MbpsSent = elapsed.TotalSeconds > 0 ? (_bytesSent * 8.0 / 1_000_000.0) / elapsed.TotalSeconds : 0, + ConnectionSuccessRate = (_successfulConnections + _failedConnections) > 0 + ? (100.0 * _successfulConnections) / (_successfulConnections + _failedConnections) + : 0, + }; + } + + public void Dispose() + { + _testCts?.Cancel(); + _testCts?.Dispose(); + } + } + + public class LoadTestReport + { + public TimeSpan Duration { get; set; } + public int TargetConnections { get; set; } + public int ActualConnections { get; set; } + public long SuccessfulConnections { get; set; } + public long FailedConnections { get; set; } + public long MessagesSent { get; set; } + public long BytesSent { get; set; } + public long MessagesReceived { get; set; } + public long BytesReceived { get; set; } + public long Errors { get; set; } + public double MessagesPerSecond { get; set; } + public double MbpsSent { get; set; } + public double ConnectionSuccessRate { get; set; } + + public override string ToString() + { + return $@" +=== Load Test Report === +Duration: {Duration} +Connections: {ActualConnections}/{TargetConnections} (Success: {SuccessfulConnections}, Failed: {FailedConnections}) +Success Rate: {ConnectionSuccessRate:F2}% +Message Rate: {MessagesPerSecond:F2} msg/sec +Throughput: {MbpsSent:F2} Mbps +Total Bytes Sent: {BytesSent / (1024 * 1024)} MB +Total Errors: {Errors} +"; + } + } +} diff --git a/EonaCat.Connections/Helpers/NetworkMonitor.cs b/EonaCat.Connections/Helpers/NetworkMonitor.cs index f5fc912..6905b20 100644 --- a/EonaCat.Connections/Helpers/NetworkMonitor.cs +++ b/EonaCat.Connections/Helpers/NetworkMonitor.cs @@ -1,13 +1,10 @@ -using System.Collections.Concurrent; +using System.Collections.Concurrent; using System.Diagnostics; using System.Net.NetworkInformation; using System.Text; namespace EonaCat.Connections.Helpers { - // This file is part of the EonaCat project(s) which is released under the Apache License. - // See the LICENSE file or go to https://EonaCat.com/license for full license details. - public class NetworkMonitor : IDisposable { private readonly string _targetHost; @@ -29,9 +26,6 @@ namespace EonaCat.Connections.Helpers public bool IsRunning => _isRunning; public string TargetHost => _targetHost; - /// - /// Gets whether automatic HTML report generation is currently running. - /// public bool IsAutoHtmlReportRunning => _autoReportRunning; public NetworkMonitor(string targetHost = "127.0.0.1", int pingIntervalMs = 5000, int maxHistory = 1000) @@ -177,7 +171,7 @@ namespace EonaCat.Connections.Helpers } catch { - // Network interface stats may not be available on all platforms + } return sample; @@ -266,7 +260,6 @@ namespace EonaCat.Connections.Helpers report.MinLatencyMs = minRtt; report.MaxLatencyMs = maxRtt; - // Calculate jitter (standard deviation of latency) double sumSquaredDiff = 0; foreach (var s in reachable) { @@ -277,7 +270,6 @@ namespace EonaCat.Connections.Helpers report.JitterMs = Math.Sqrt(sumSquaredDiff / reachable.Count); } - // Detect outage windows bool inOutage = false; DateTime outageStart = DateTime.MinValue; @@ -311,7 +303,6 @@ namespace EonaCat.Connections.Helpers }); } - // Bandwidth estimate between last two samples if (samples.Length >= 2) { var prev = samples[samples.Length - 2]; @@ -340,12 +331,6 @@ namespace EonaCat.Connections.Helpers _autoReportCts?.Dispose(); } - /// - /// Starts periodic automatic generation of the network health HTML report. - /// - /// Directory where the HTML file is written. - /// Interval in seconds between report generations. - /// The HTML file name. public void StartAutoHtmlReport(string outputDirectory, int intervalSeconds = 60, string fileName = "status-network.html") { if (_autoReportRunning) @@ -378,7 +363,7 @@ namespace EonaCat.Connections.Helpers } catch { - // Swallow to keep the loop alive + } try @@ -393,9 +378,6 @@ namespace EonaCat.Connections.Helpers }, token); } - /// - /// Stops the automatic HTML report generation. - /// public void StopAutoHtmlReport() { if (!_autoReportRunning) @@ -530,7 +512,6 @@ namespace EonaCat.Connections.Helpers sb.AppendLine("
"); sb.AppendLine($"

{HtmlEncode(title)}

"); - // Status banner if (TotalSamples > 0) { var bannerClass = IsStable ? "status-stable" : "status-unstable"; @@ -538,7 +519,6 @@ namespace EonaCat.Connections.Helpers sb.AppendLine($"
{bannerText}
"); } - // Summary cards var uptimeClass = UptimePercentage >= 99 ? "ok" : UptimePercentage >= 95 ? "warn" : "error"; var latencyClass = AverageLatencyMs < 50 ? "ok" : AverageLatencyMs < 150 ? "warn" : "error"; var jitterClass = JitterMs < 20 ? "ok" : JitterMs < 50 ? "warn" : "error"; @@ -552,13 +532,11 @@ namespace EonaCat.Connections.Helpers sb.AppendLine($"
0 ? "error" : "ok")}\">
Failed Pings
{FailedPings}
"); sb.AppendLine("
"); - // Uptime progress bar sb.AppendLine("

Uptime

"); var barColor = UptimePercentage >= 99 ? "#27ae60" : UptimePercentage >= 95 ? "#f39c12" : "#e74c3c"; var barWidth = Math.Max(0, Math.Min(100, UptimePercentage)); sb.AppendLine($"
{UptimePercentage:F2}%
"); - // Latency / Bandwidth sb.AppendLine("

Performance

"); sb.AppendLine("
"); sb.AppendLine($"
Min Latency
{MinLatencyMs} ms
"); @@ -567,7 +545,6 @@ namespace EonaCat.Connections.Helpers sb.AppendLine($"
Send Bandwidth
{FormatBytes(CurrentSendBytesPerSecond)}/s
"); sb.AppendLine("
"); - // Outage windows sb.AppendLine("

Outage History

"); if (OutageWindows.Count == 0) { diff --git a/EonaCat.Connections/Helpers/ProtocolProbeStream.cs b/EonaCat.Connections/Helpers/ProtocolProbeStream.cs new file mode 100644 index 0000000..c7c2b4d --- /dev/null +++ b/EonaCat.Connections/Helpers/ProtocolProbeStream.cs @@ -0,0 +1,97 @@ +using System.Text; + +namespace EonaCat.Connections.Helpers +{ + internal sealed class ProtocolProbeStream : Stream + { + private readonly Stream _inner; + private readonly MemoryStream _prefix = new MemoryStream(); + private readonly byte[] _probeBuffer = new byte[8192]; + private Task? _pendingRead; + + internal ProtocolProbeStream(Stream inner) + { + _inner = inner; + } + + internal async Task IsHttpAsync(CancellationToken token) + { + var prefixes = new[] { "GET /", "HEAD /", "POST /", "PUT /", "DELETE /", "OPTIONS /", "PATCH /" }; + try + { + while (_prefix.Length < 9) + { + _pendingRead = _inner.ReadAsync(_probeBuffer, 0, _probeBuffer.Length, token); + if (await Task.WhenAny(_pendingRead, Task.Delay(250, token)).ConfigureAwait(false) != _pendingRead) + { + token.ThrowIfCancellationRequested(); + _ = _pendingRead.ContinueWith(task => { _ = task.Exception; }, CancellationToken.None, + TaskContinuationOptions.OnlyOnFaulted | TaskContinuationOptions.ExecuteSynchronously, TaskScheduler.Default); + return false; + } + + var count = await _pendingRead.ConfigureAwait(false); + _pendingRead = null; + if (count == 0) return false; + _prefix.Write(_probeBuffer, 0, count); + var text = Encoding.ASCII.GetString(_prefix.GetBuffer(), 0, (int)Math.Min(_prefix.Length, 9)); + if (prefixes.Any(prefix => text.StartsWith(prefix, StringComparison.Ordinal))) return true; + if (!prefixes.Any(prefix => prefix.StartsWith(text, StringComparison.Ordinal))) return false; + } + return false; + } + finally + { + _prefix.Position = 0; + } + } + + public override async Task ReadAsync(byte[] buffer, int offset, int count, CancellationToken cancellationToken) + { + if (buffer == null) throw new ArgumentNullException(nameof(buffer)); + if (offset < 0 || count < 0 || offset > buffer.Length - count) throw new ArgumentOutOfRangeException(); + cancellationToken.ThrowIfCancellationRequested(); + if (count == 0) return 0; + if (_prefix.Position < _prefix.Length) return _prefix.Read(buffer, offset, count); + if (_pendingRead != null) + { + var pending = _pendingRead; + var received = await pending.ConfigureAwait(false); + _pendingRead = null; + if (received == 0) return 0; + var position = _prefix.Length; + _prefix.Position = position; + _prefix.Write(_probeBuffer, 0, received); + _prefix.Position = position; + return _prefix.Read(buffer, offset, count); + } + return await _inner.ReadAsync(buffer, offset, count, cancellationToken).ConfigureAwait(false); + } + + public override int Read(byte[] buffer, int offset, int count) => ReadAsync(buffer, offset, count, CancellationToken.None).GetAwaiter().GetResult(); + public override void Write(byte[] buffer, int offset, int count) => _inner.Write(buffer, offset, count); + public override Task WriteAsync(byte[] buffer, int offset, int count, CancellationToken cancellationToken) => _inner.WriteAsync(buffer, offset, count, cancellationToken); + public override void Flush() => _inner.Flush(); + public override Task FlushAsync(CancellationToken cancellationToken) => _inner.FlushAsync(cancellationToken); + public override bool CanRead => _inner.CanRead; + public override bool CanWrite => _inner.CanWrite; + public override bool CanSeek => false; + public override bool CanTimeout => _inner.CanTimeout; + public override int ReadTimeout { get => _inner.ReadTimeout; set => _inner.ReadTimeout = value; } + public override int WriteTimeout { get => _inner.WriteTimeout; set => _inner.WriteTimeout = value; } + public override long Length => throw new NotSupportedException(); + public override long Position { get => throw new NotSupportedException(); set => throw new NotSupportedException(); } + public override long Seek(long offset, SeekOrigin origin) => throw new NotSupportedException(); + public override void SetLength(long value) => throw new NotSupportedException(); + + protected override void Dispose(bool disposing) + { + if (disposing) + { + _inner.Dispose(); + _prefix.Dispose(); + } + base.Dispose(disposing); + } + } +} \ No newline at end of file diff --git a/EonaCat.Connections/Helpers/SecurityValidator.cs b/EonaCat.Connections/Helpers/SecurityValidator.cs deleted file mode 100644 index 5247570..0000000 --- a/EonaCat.Connections/Helpers/SecurityValidator.cs +++ /dev/null @@ -1,253 +0,0 @@ -using System; -using System.Collections.Concurrent; - -namespace EonaCat.Connections.Helpers -{ - // This file is part of the EonaCat project(s) which is released under the Apache License. - // See the LICENSE file or go to https://EonaCat.com/license for full license details. - - /// - /// Provides security validation utilities to protect against common network attacks - /// including buffer overflows, memory exhaustion (decompression bombs), malformed packets, - /// and injection attacks. - /// - public static class SecurityValidator - { - private static readonly ConcurrentDictionary _rateLimitCache = - new ConcurrentDictionary(); - - private class RateLimitEntry - { - public long RequestCount; - public DateTime WindowStart; - } - - /// - /// Validates a length prefix value against configuration limits. - /// Prevents buffer overflow and memory exhaustion attacks by: - /// - Rejecting negative or zero lengths - /// - Rejecting lengths exceeding configured maximum - /// - Rejecting obviously malformed values (e.g., impossibly large lengths) - /// - public static bool ValidateLengthPrefix(long messageLengthValue, int maxMessageSize) - { - // Reject negative, zero, or non-positive values - if (messageLengthValue <= 0) - { - return false; - } - - // Reject values exceeding maximum allowed message size - if (messageLengthValue > maxMessageSize) - { - return false; - } - - // Reject impossibly large values that could indicate malformed data - if (messageLengthValue > int.MaxValue) - { - return false; - } - - return true; - } - - /// - /// Validates message stream size to prevent memory exhaustion attacks. - /// Checks if accumulated message data exceeds configured thresholds. - /// - public static bool ValidateMessageStreamSize(long currentStreamLength, long maxStreamSize) - { - if (currentStreamLength <= 0 || maxStreamSize <= 0) - { - return true; // No limit configured - } - - return currentStreamLength < maxStreamSize; - } - - /// - /// Validates UDP packet size to prevent buffer overflow attacks. - /// - public static bool ValidateUdpPacketSize(int receivedBytes, int bufferSize) - { - // UDP packet should not exceed buffer size - if (receivedBytes <= 0 || receivedBytes > bufferSize) - { - return false; - } - - return true; - } - - /// - /// Implements basic rate limiting per source IP address. - /// Returns true if request is within rate limit, false if limit exceeded. - /// - public static bool CheckRateLimit(string sourceAddress, int maxRequestsPerSecond, int windowSizeSeconds = 1) - { - if (string.IsNullOrEmpty(sourceAddress) || maxRequestsPerSecond <= 0) - { - return true; // No rate limit configured - } - - var now = DateTime.UtcNow; - var entry = _rateLimitCache.AddOrUpdate(sourceAddress, - new RateLimitEntry { RequestCount = 1, WindowStart = now }, - (key, existing) => - { - // Check if we're still in the same window - var timeDiff = now - existing.WindowStart; - if (timeDiff.TotalSeconds < windowSizeSeconds) - { - existing.RequestCount++; - } - else - { - // Reset window - existing.RequestCount = 1; - existing.WindowStart = now; - } - return existing; - }); - - return entry.RequestCount <= maxRequestsPerSecond; - } - - /// - /// Validates HTTP header names and values to prevent header injection attacks. - /// - public static bool ValidateHttpHeader(string headerName, string headerValue) - { - if (string.IsNullOrEmpty(headerName) || string.IsNullOrEmpty(headerValue)) - { - return false; - } - - // Check for newline characters that could be used in HTTP header injection - if (headerName.Contains("\r") || headerName.Contains("\n") || - headerValue.Contains("\r") || headerValue.Contains("\n")) - { - return false; - } - - // Check for null bytes - if (headerName.Contains("\0") || headerValue.Contains("\0")) - { - return false; - } - - return true; - } - - /// - /// Validates that a message doesn't contain null bytes which could be used for injection attacks. - /// - public static bool ValidateMessageContent(byte[] data) - { - if (data == null || data.Length == 0) - { - return true; // Empty is generally OK - } - - // This is optional depending on your protocol - some protocols may legitimately use null bytes - // For now, we'll allow them but this can be made stricter if needed - return true; - } - - /// - /// Validates delimiter to prevent delimiter injection attacks. - /// - public static bool ValidateDelimiter(byte[] delimiter) - { - if (delimiter == null || delimiter.Length == 0) - { - return false; - } - - // Delimiter should be reasonably small - if (delimiter.Length > 256) - { - return false; - } - - return true; - } - - /// - /// Detects potential decompression bomb by checking if uncompressed size ratio is too high. - /// - public static bool ValidateCompressionRatio(long compressedSize, long decompressedSize, double maxRatio = 100.0) - { - if (compressedSize <= 0 || decompressedSize <= 0) - { - return true; // Can't validate - } - - double ratio = (double)decompressedSize / compressedSize; - return ratio <= maxRatio; - } - - /// - /// Cleans up old rate limit entries to prevent memory leaks. - /// Should be called periodically from cleanup/maintenance tasks. - /// - public static void CleanupRateLimitCache(int maxAgeSeconds = 300) - { - var now = DateTime.UtcNow; - var keysToRemove = new System.Collections.Generic.List(); - - foreach (var kvp in _rateLimitCache) - { - var age = now - kvp.Value.WindowStart; - if (age.TotalSeconds > maxAgeSeconds) - { - keysToRemove.Add(kvp.Key); - } - } - - foreach (var key in keysToRemove) - { - _rateLimitCache.TryRemove(key, out _); - } - } - - /// - /// Sanitizes error messages to prevent information leakage. - /// - public static string SanitizeErrorMessage(string message, bool isInternal = false) - { - if (string.IsNullOrEmpty(message)) - { - return "An error occurred"; - } - - if (isInternal) - { - // Internal logs can include full details - return message; - } - - // External error messages should be generic to avoid info leakage - // Only include safe error information back to clients - if (message.Contains("socket", StringComparison.OrdinalIgnoreCase) || - message.Contains("connection", StringComparison.OrdinalIgnoreCase)) - { - return "Connection error occurred"; - } - - if (message.Contains("timeout", StringComparison.OrdinalIgnoreCase)) - { - return "Operation timed out"; - } - - if (message.Contains("invalid", StringComparison.OrdinalIgnoreCase) || - message.Contains("malformed", StringComparison.OrdinalIgnoreCase)) - { - return "Invalid data received"; - } - - return "An error occurred"; - } - } -} diff --git a/EonaCat.Connections/Helpers/SslHandshakeDiagnostics.cs b/EonaCat.Connections/Helpers/SslHandshakeDiagnostics.cs index 7eec5d7..b5b6618 100644 --- a/EonaCat.Connections/Helpers/SslHandshakeDiagnostics.cs +++ b/EonaCat.Connections/Helpers/SslHandshakeDiagnostics.cs @@ -1,29 +1,17 @@ -using System; -using System.Diagnostics; +using System.Diagnostics; using System.Net.Security; namespace EonaCat.Connections.Helpers { - // This file is part of the EonaCat project(s) which is released under the Apache License. - // See the LICENSE file or go to https://EonaCat.com/license for full license details. - /// - /// Helper class for tracking and diagnosing SSL/TLS handshake performance and errors. - /// public class SslHandshakeDiagnostics { private readonly SslMetrics _metrics = new(); private readonly Stopwatch _totalStopwatch = new(); private Stopwatch? _stageStopwatch; - /// - /// Gets the current metrics object. - /// public SslMetrics Metrics => _metrics; - /// - /// Starts tracking a new SSL handshake attempt. - /// public void StartHandshake(string remoteEndPoint, bool mutualAuthRequired) { _totalStopwatch.Restart(); @@ -35,17 +23,11 @@ namespace EonaCat.Connections.Helpers _metrics.FailureReason = null; } - /// - /// Marks the start of a specific SSL stage (e.g., AuthenticateAsServer). - /// public void StartStage(string stageName) { _stageStopwatch = Stopwatch.StartNew(); } - /// - /// Marks the end of a specific SSL stage and records the duration. - /// public void EndStage(string stageName) { if (_stageStopwatch == null) @@ -82,9 +64,6 @@ namespace EonaCat.Connections.Helpers _stageStopwatch = null; } - /// - /// Records successful SSL handshake completion and captures protocol details. - /// public void RecordSuccess(SslStream sslStream) { _totalStopwatch.Stop(); @@ -103,16 +82,13 @@ namespace EonaCat.Connections.Helpers } catch { - // No cross-platform way to get these details, so ignore if not available. + } } _metrics.CumulativeDuration = _totalStopwatch.Elapsed; } - /// - /// Records SSL handshake failure with error details. - /// public void RecordFailure(Exception exception, bool isRecoverable) { _totalStopwatch.Stop(); @@ -123,11 +99,6 @@ namespace EonaCat.Connections.Helpers _metrics.CumulativeDuration = _totalStopwatch.Elapsed; } - /// - /// Analyzes the failure and determines if it's recoverable. - /// Non-recoverable failures: authentication failures, certificate errors, protocol mismatches - /// Recoverable failures: timeouts, network interruptions, EOF during handshake - /// public static bool IsRecoverableFailure(Exception exception) { if (exception == null) @@ -138,7 +109,6 @@ namespace EonaCat.Connections.Helpers var message = exception.Message?.ToLower() ?? ""; var typeName = exception.GetType().Name.ToLower(); - // Non-recoverable SSL authentication and certificate errors if (typeName.Contains("authenticationexception")) { return false; @@ -174,7 +144,6 @@ namespace EonaCat.Connections.Helpers return false; } - // Check for handshake_failure TLS alerts if (message.Contains("handshake_failure")) { return false; @@ -190,7 +159,6 @@ namespace EonaCat.Connections.Helpers return false; } - // Recoverable I/O and network errors if (message.Contains("0 bytes from the transport stream")) { return true; @@ -251,13 +219,9 @@ namespace EonaCat.Connections.Helpers return IsRecoverableFailure(exception.InnerException); } - // Default: assume recoverable for network-layer exceptions return typeName.Contains("exception"); } - /// - /// Returns a diagnostic summary of the handshake attempt. - /// public override string ToString() => _metrics.ToString(); } } diff --git a/EonaCat.Connections/Helpers/SslMetrics.cs b/EonaCat.Connections/Helpers/SslMetrics.cs index b68a214..4e84357 100644 --- a/EonaCat.Connections/Helpers/SslMetrics.cs +++ b/EonaCat.Connections/Helpers/SslMetrics.cs @@ -1,107 +1,47 @@ -using System; - -namespace EonaCat.Connections.Helpers +namespace EonaCat.Connections.Helpers { - // This file is part of the EonaCat project(s) which is released under the Apache License. - // See the LICENSE file or go to https://EonaCat.com/license for full license details. - /// - /// Tracks metrics and timing information for SSL/TLS handshake stages. - /// public class SslMetrics { - /// - /// Gets the timestamp when the SSL handshake attempt started. - /// + public DateTime StartTime { get; set; } - /// - /// Gets the timestamp when the SSL handshake completed (success or final failure). - /// public DateTime? EndTime { get; set; } - /// - /// Gets the total duration of the SSL handshake attempt. - /// public TimeSpan? TotalDuration => EndTime.HasValue ? EndTime.Value - StartTime : null; - /// - /// Gets the duration of the AuthenticateAsServer call (server-side). - /// public TimeSpan? ServerAuthenticationDuration { get; set; } - /// - /// Gets the duration of the AuthenticateAsClient call (client-side). - /// public TimeSpan? ClientAuthenticationDuration { get; set; } - /// - /// Gets the time spent retrying SSL handshakes after failures. - /// public TimeSpan? RetryDelayDuration { get; set; } - /// - /// Gets the total time spent in all SSL handshake attempts including retries. - /// public TimeSpan? CumulativeDuration { get; set; } - /// - /// Gets the number of SSL handshake attempts made. - /// public int AttemptCount { get; set; } - /// - /// Gets the SSL protocol version negotiated (e.g., "Tls13", "Tls12"). - /// public string? SslProtocolVersion { get; set; } - /// - /// Gets the cipher algorithm used (e.g., "Aes256", "ChaCha20"). - /// public string? CipherAlgorithm { get; set; } - /// - /// Gets the hash algorithm used (e.g., "Sha256"). - /// public string? HashAlgorithm { get; set; } - /// - /// Gets the key exchange algorithm used (e.g., "Ecdh"). - /// public string? KeyExchangeAlgorithm { get; set; } - /// - /// Gets whether the SSL handshake was successful. - /// public bool IsSuccessful { get; set; } - /// - /// Gets the exception message if the handshake failed. - /// public string? FailureReason { get; set; } - /// - /// Gets whether the failure is recoverable (can retry) or not. - /// public bool IsRecoverableFailure { get; set; } - /// - /// Gets the remote endpoint that was connected to/from. - /// public string? RemoteEndPoint { get; set; } - /// - /// Gets whether mutual authentication (client certificate) was required. - /// public bool MutualAuthenticationRequired { get; set; } - /// - /// Returns a formatted string summary of the SSL handshake metrics. - /// public override string ToString() { var result = $"SSL Metrics: Attempt {AttemptCount}, "; - result += IsSuccessful + result += IsSuccessful ? $"Success in {TotalDuration?.TotalMilliseconds:F2}ms, Protocol={SslProtocolVersion}, Cipher={CipherAlgorithm}" : $"Failed - {FailureReason} (Recoverable: {IsRecoverableFailure})"; diff --git a/EonaCat.Connections/Helpers/StringHelper.cs b/EonaCat.Connections/Helpers/StringHelper.cs index cf9b476..660d2f9 100644 --- a/EonaCat.Connections/Helpers/StringHelper.cs +++ b/EonaCat.Connections/Helpers/StringHelper.cs @@ -1,23 +1,85 @@ -namespace EonaCat.Connections.Helpers -{ - // This file is part of the EonaCat project(s) which is released under the Apache License. - // See the LICENSE file or go to https://EonaCat.com/license for full license details. +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; - internal static class StringHelper +namespace EonaCat.Connections.Helpers +{ + public class StringHelper { - public static string GetTextBetweenTags(this string value, - string startTag, - string endTag) + public static event EventHandler OnLog; + public static string GetTextBetweenTags(string message, string startTag, string endTag) { - if (value.Contains(startTag) && value.Contains(endTag)) + int startIndex = message.IndexOf(startTag); + if (startIndex == -1) { - int index = value.IndexOf(startTag) + startTag.Length; - return value.Substring(index, value.IndexOf(endTag) - index); + OnLog?.Invoke(null, $"Start tag not found in the message. => {message}"); + return string.Empty; } - else + + int endIndex = message.IndexOf(endTag, startIndex + startTag.Length); + if (endIndex == -1) { - return null; + OnLog?.Invoke(null, $"End tag not found in the message. => {message}"); + return string.Empty; } + + int length = endIndex - startIndex - startTag.Length; + if (length < 0) + { + OnLog?.Invoke(null, $"End tag appears before the start tag. => {message}"); + return string.Empty; + } + + return message.Substring(startIndex + startTag.Length, length); + } + + public static string? SanitizeUsername(string username, bool removeDomain = true) + { + if (string.IsNullOrWhiteSpace(username)) + { + return username; + } + + if (removeDomain && username.Contains("\\")) + { + var parts = username.Split('\\'); + if (parts.Length == 2) + { + return parts[1]; + } + } + + // Remove the dollar sign and anything after it (for service accounts) + if (username.Contains("$")) + { + var index = username.IndexOf("$"); + if (index > 0) + { + return username.Substring(0, index); + } + } + return username; + } + + public static string SanitizeComputerName(string machineName) + { + if (string.IsNullOrWhiteSpace(machineName)) + { + return machineName; + } + + // Remove the dollar sign and anything after it (for service accounts) + if (machineName.Contains("$")) + { + var index = machineName.IndexOf("$"); + if (index > 0) + { + return machineName.Substring(0, index); + } + } + return machineName; } } } diff --git a/EonaCat.Connections/Helpers/TcpSeparators.cs b/EonaCat.Connections/Helpers/TcpSeparators.cs index 493391f..1227455 100644 --- a/EonaCat.Connections/Helpers/TcpSeparators.cs +++ b/EonaCat.Connections/Helpers/TcpSeparators.cs @@ -2,9 +2,6 @@ namespace EonaCat.Connections.Helpers { - // This file is part of the EonaCat project(s) which is released under the Apache License. - // See the LICENSE file or go to https://EonaCat.com/license for full license details. - public static class TcpSeparators { public static byte[] NewLine => Encoding.UTF8.GetBytes("\n"); @@ -36,4 +33,4 @@ namespace EonaCat.Connections.Helpers public static byte[] OpenBracket => Encoding.UTF8.GetBytes("["); public static byte[] CloseBracket => Encoding.UTF8.GetBytes("]"); } -} \ No newline at end of file +} diff --git a/EonaCat.Connections/Helpers/TrafficDashboard.html b/EonaCat.Connections/Helpers/TrafficDashboard.html new file mode 100644 index 0000000..a3dda46 --- /dev/null +++ b/EonaCat.Connections/Helpers/TrafficDashboard.html @@ -0,0 +1,196 @@ + + + + + +EonaCat.Connections | Traffic + + + + +
+

EonaCat.Connections

Traffic Monitor

Connecting
+

Traffic Overview

+
+
Incoming
--
-- received
+
Outgoing
--
-- sent
Last sent (local): --
+
Messages / second
--
-- messages
+
Connections
--
-- uptime
+
+ +
+
+

Bandwidth

ReceivedSent
+

Message Rate

ReceivedSent
+
+ +
Waiting for traffic samples
+
+ + + \ No newline at end of file diff --git a/EonaCat.Connections/Infrastructure/SocketKeepAliveConfigurator.cs b/EonaCat.Connections/Infrastructure/SocketKeepAliveConfigurator.cs new file mode 100644 index 0000000..b08f364 --- /dev/null +++ b/EonaCat.Connections/Infrastructure/SocketKeepAliveConfigurator.cs @@ -0,0 +1,46 @@ +using System.Diagnostics; +using System.Net.Sockets; + +namespace EonaCat.Connections.Infrastructure +{ + internal static class SocketKeepAliveConfigurator + { + public static void Configure( + Socket socket, + int keepAliveTimeSeconds, + int keepAliveIntervalSeconds, + int keepAliveRetryCount = 10) + { + if (socket == null) + { + return; + } + + try + { + socket.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.KeepAlive, true); + +#if NET5_0_OR_GREATER + socket.SetSocketOption(SocketOptionLevel.Tcp, SocketOptionName.TcpKeepAliveTime, Math.Max(1, keepAliveTimeSeconds)); + socket.SetSocketOption(SocketOptionLevel.Tcp, SocketOptionName.TcpKeepAliveInterval, Math.Max(1, keepAliveIntervalSeconds)); + socket.SetSocketOption(SocketOptionLevel.Tcp, SocketOptionName.TcpKeepAliveRetryCount, Math.Max(1, keepAliveRetryCount)); +#else + uint onOff = 1; + uint keepAliveTime = (uint)Math.Max(1, keepAliveTimeSeconds) * 1000; + uint keepAliveInterval = (uint)Math.Max(1, keepAliveIntervalSeconds) * 1000; + + byte[] keepAliveSettings = new byte[12]; + Buffer.BlockCopy(BitConverter.GetBytes(onOff), 0, keepAliveSettings, 0, 4); + Buffer.BlockCopy(BitConverter.GetBytes(keepAliveTime), 0, keepAliveSettings, 4, 4); + Buffer.BlockCopy(BitConverter.GetBytes(keepAliveInterval), 0, keepAliveSettings, 8, 4); + + socket.IOControl(IOControlCode.KeepAliveValues, keepAliveSettings, null); +#endif + } + catch (Exception exception) + { + Debug.WriteLine($"Failed to configure TCP keep-alive: {exception.Message}"); + } + } + } +} diff --git a/EonaCat.Connections/Messaging/ResponseAwaiter.cs b/EonaCat.Connections/Messaging/ResponseAwaiter.cs new file mode 100644 index 0000000..56870de --- /dev/null +++ b/EonaCat.Connections/Messaging/ResponseAwaiter.cs @@ -0,0 +1,108 @@ +namespace EonaCat.Connections.Messaging +{ + internal static class ResponseAwaiter + { + public static async Task WaitForSingleAsync( + Func> sendAsync, + Action> subscribe, + Action> unsubscribe, + TimeSpan timeout, + Predicate? responseFilter = null, + CancellationToken cancellationToken = default) + { + if (cancellationToken.IsCancellationRequested) + { + return null; + } + + var completion = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously); + + void Handler(object? sender, DataReceivedEventArgs args) + { + if (responseFilter == null || responseFilter(args)) + { + completion.TrySetResult(args); + } + } + + subscribe(Handler); + try + { + if (!await sendAsync().ConfigureAwait(false)) + { + return null; + } + + using var timeoutSource = new CancellationTokenSource(timeout); + using var linkedSource = CancellationTokenSource.CreateLinkedTokenSource(timeoutSource.Token, cancellationToken); + using var registration = linkedSource.Token.Register(() => completion.TrySetCanceled()); + + try + { + return await completion.Task.ConfigureAwait(false); + } + catch (OperationCanceledException) + { + return null; + } + } + finally + { + unsubscribe(Handler); + } + } + + public static async Task> WaitForManyAsync( + Func> sendAsync, + Action> subscribe, + Action> unsubscribe, + TimeSpan timeout, + int expectedCount, + CancellationToken cancellationToken = default) + { + var responses = new List(expectedCount); + if (expectedCount <= 0 || cancellationToken.IsCancellationRequested) + { + return responses; + } + + var completion = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously); + + void Handler(object? sender, DataReceivedEventArgs args) + { + lock (responses) + { + if (responses.Count >= expectedCount) + { + return; + } + + responses.Add(args); + if (responses.Count >= expectedCount) + { + completion.TrySetResult(true); + } + } + } + + subscribe(Handler); + try + { + if (!await sendAsync().ConfigureAwait(false)) + { + return responses; + } + + using var timeoutSource = new CancellationTokenSource(timeout); + using var linkedSource = CancellationTokenSource.CreateLinkedTokenSource(timeoutSource.Token, cancellationToken); + using var registration = linkedSource.Token.Register(() => completion.TrySetResult(true)); + await completion.Task.ConfigureAwait(false); + return responses; + } + finally + { + unsubscribe(Handler); + } + } + } +} diff --git a/EonaCat.Connections/Models/Configuration.cs b/EonaCat.Connections/Models/Configuration.cs index 1ca68ac..baf9a6d 100644 --- a/EonaCat.Connections/Models/Configuration.cs +++ b/EonaCat.Connections/Models/Configuration.cs @@ -1,41 +1,25 @@ -using System.Diagnostics; +using EonaCat.Connections.Protocols; +using System.Diagnostics; using System.Net; using System.Net.Security; using System.Security.Cryptography.X509Certificates; namespace EonaCat.Connections.Models { - // This file is part of the EonaCat project(s) which is released under the Apache License. - // See the LICENSE file or go to https://EonaCat.com/license for full license details. - public class Configuration : IDisposable { - public event EventHandler OnLog; public List TrustedThumbprints = new List(); public bool EnableAutoReconnect { get; set; } = true; public int ReconnectDelayInSeconds { get; set; } = 5; - public int MaxReconnectAttempts { get; set; } = 0; // 0 means unlimited attempts - public int SSLMaxRetries { get; set; } = 0; // 0 means unlimited attempts - public int SSLTimeoutInSeconds { get; set; } = 35; + public int MaxReconnectAttempts { get; set; } = 0; + public int SSLMaxRetries { get; set; } = 0; + public int SSLTimeoutInSeconds { get; set; } = 60; public int SSLRetryDelayInSeconds { get; set; } = 5; - /// - /// Enables exponential backoff for SSL handshake retries. - /// When enabled, retry delays increase progressively: initial delay * (2 ^ attempt). - /// Caps out at SSLRetryDelayMaxSeconds to prevent excessive delays. - /// Default is false to provide instant retries after a fixed 5-second delay, allowing SSL handshakes up to 30 seconds to complete. - /// public bool UseExponentialBackoffForSslRetries { get; set; } = false; - /// - /// Maximum delay in seconds for SSL handshake retries when exponential backoff is enabled. (default: 60) - /// public int SSLRetryDelayMaxSeconds { get; set; } = 60; - /// - /// Enables diagnostic/tracing for SSL handshake process. - /// When enabled, detailed metrics and performance data are collected for each SSL connection attempt. - /// public bool EnableSslDiagnostics { get; set; } = false; public FramingMode MessageFraming { get; set; } = FramingMode.None; @@ -48,27 +32,56 @@ namespace EonaCat.Connections.Models public const string SSL_ERROR_SUFFIX = "[/SSL_ERROR]"; public ProtocolType Protocol { get; set; } = ProtocolType.TCP; + + public Func? ProtocolFactory { get; set; } + + public INetworkProtocol GetProtocol() + { + INetworkProtocol protocol; + + if (ProtocolFactory != null) + { + protocol = ProtocolFactory(); + } + else + { + protocol = EonaCat.Connections.Protocols.ProtocolFactory.CreateProtocol(Protocol); + } + + protocol.ConfigureBufferSize(BufferSize); + protocol.ConfigureNagle(EnableNagle); + protocol.ConfigureRst(EnableRST); + if (protocol is IBroadcastConfigurableProtocol broadcastProtocol) + { + broadcastProtocol.ConfigureBroadcast(EnableBroadcast); + } + protocol.ConfigureKeepAlive(EnableKeepAlive, KeepAliveTimeSeconds, KeepAliveIntervalSeconds, KeepAliveRetryCount); + protocol.ConfigureSsl(UseSsl, Host, CheckCertificateRevocation, AllowTlsRenegotiation); + + return protocol; + } public int Port { get; set; } = 8080; public string Host { get; set; } = "127.0.0.1"; public bool UseSsl => Certificate != null; public X509Certificate2 Certificate { get; set; } public X509Certificate2Collection AdditionalCertificates { get; set; } public bool UseAesEncryption { get; set; } = false; - public int BufferSize { get; set; } = (int)BufferSizeMaximum.ExtraLarge; - public int MaxConnections { get; set; } = 100000; - public TimeSpan ConnectionTimeout { get; set; } = TimeSpan.FromSeconds(30); + public int BufferSize { get; set; } = (int)BufferSizeMaximum.Huge; + public int MAX_MESSAGE_SIZE { get; set; } = (int)MessageSizeMaximum.Default; + + public int MaxConnections { get; set; } = 500000; + + public TimeSpan ConnectionTimeout { get; set; } = Timeout.InfiniteTimeSpan; public bool EnableKeepAlive { get; set; } = true; public int KeepAliveTimeSeconds { get; set; } = 60; public int KeepAliveIntervalSeconds { get; set; } = 10; - /// - /// Number of unacknowledged TCP keep-alive probes before the connection is considered dead. (default: 10) - /// public int KeepAliveRetryCount { get; set; } = 10; public bool EnableNagle { get; set; } = false; - // For testing purposes, allow self-signed certificates + public bool EnableBroadcast { get; set; } + public bool IsSelfSignedEnabled { get; set; } public string AesPassword { get; set; } @@ -82,132 +95,35 @@ namespace EonaCat.Connections.Models public bool UseBigEndian { get; set; } public int HeartbeatIntervalSeconds { get; set; } = 5; public bool EnablePingPongLogs { get; set; } - public int MAX_MESSAGE_SIZE { get; set; } = 100 * 1024 * 1024; // 100 MB - public bool DisconnectOnMissedPong { get; set; } - public double IdleTimeoutSeconds { get; set; } = 30; // 0 means no idle timeout + public bool DisconectOnMissedPong { get; set; } - /// - /// Determines whether to enable RST (Reset) flag on socket close. - /// public bool EnableRST { get; set; } - /// - /// Gets or sets the total bytes to read as a message prefix (if framing mode is LengthPrefixed) is enabled. - /// - /// The length prefix index determines where the length information is read or written in - /// the buffer. Changing this value may affect how data is parsed or serialized, depending on the protocol or - /// format in use. (default: 4) public int LengthPrefixedLength { get; set; } = 4; public bool EnableConnectionDebugLogs { get; set; } - /// - /// Enables automatic periodic generation of HTML status reports for errors and network health. - /// When enabled, reports are written to every seconds. - /// public bool EnableAutoHtmlReports { get; set; } - /// - /// The directory where auto-generated HTML reports are written. Defaults to "reports" under the current directory. - /// public string HtmlReportOutputDirectory { get; set; } = Path.Combine(Directory.GetCurrentDirectory(), "reports"); - /// - /// The interval in seconds between automatic HTML report generations. (default: 60) - /// public int HtmlReportIntervalSeconds { get; set; } = 60; - /// - /// Enables automatic periodic generation of an HTML status page showing connected clients and throughput. - /// When enabled, the page is written to every seconds. - /// Default is off. - /// public bool EnableServerStatusPage { get; set; } - /// - /// The interval in seconds between automatic server status page generations. (default: 5) - /// public int ServerStatusPageIntervalSeconds { get; set; } = 5; - /// - /// Enables a lightweight REST API that exposes health and status information via HTTP. - /// When enabled, the API listens on (use 0 for a random available port). - /// Default is off. - /// public bool EnableHealthApi { get; set; } - /// - /// The port for the health REST API. Use 0 (default) for a random available port. - /// The actual port can be retrieved from NetworkServer.HealthApi.Port or NetworkClient.HealthApi.Port after starting. - /// public int HealthApiPort { get; set; } = 0; - /// - /// The IP address the health API server binds to. - /// Use IPAddress.Any (0.0.0.0) for Docker/container environments where the API must be reachable from outside the container. - /// Defaults to IPAddress.Loopback (127.0.0.1) for security. - /// public IPAddress HealthApiBindAddress { get; set; } = IPAddress.Loopback; - /// - /// Write timeout in seconds for network operations. If a write operation takes longer than this duration, it will be aborted and an exception will be thrown. (default: 120 seconds) - /// - public double WriteTimeoutSeconds { get; set; } = 120; + public double WriteTimeoutSeconds { get; set; } = Timeout.Infinite; - /// - /// Read timeout in seconds for network operations. If a read operation takes longer than this duration, it will be aborted and an exception will be thrown. (default: 300 seconds) - /// - public double ReadTimeoutSeconds { get; set; } = 300; + public double ReadTimeoutSeconds { get; set; } = Timeout.Infinite; - // Security Settings (Protection against network attacks) - - /// - /// Maximum accumulated message stream size in bytes before considering it a potential memory exhaustion attack. - /// Prevents decompression bombs and message accumulation attacks. (default: 500 MB) - /// - public long MaxMessageStreamSize { get; set; } = 500 * 1024 * 1024; - - /// - /// Maximum number of messages allowed per client per second. 0 means unlimited. (default: 0) - /// Helps prevent flood/DoS attacks. - /// - public int MaxMessagesPerSecond { get; set; } = 0; - - /// - /// Enable strict validation of length-prefixed messages to detect malformed packets. (default: true) - /// - public bool EnableLengthPrefixValidation { get; set; } = true; - - /// - /// Enable rate limiting for UDP packets. 0 means unlimited. (default: 0) - /// - public int MaxUdpPacketsPerSecond { get; set; } = 0; - - /// - /// Maximum HTTP request/response size for health API in bytes. (default: 10 MB) - /// - public int MaxHealthApiRequestSize { get; set; } = 10 * 1024 * 1024; - - /// - /// Enable sanitization of error messages to prevent information leakage. (default: true) - /// When enabled, error details are hidden from clients. - /// - public bool EnableErrorMessageSanitization { get; set; } = true; - - /// - /// Enable automatic cleanup of rate limit cache. (default: true) - /// - public bool EnableRateLimitCacheCleanup { get; set; } = true; - - /// - /// Interval in seconds for cleaning up rate limit cache. (default: 300) - /// - public int RateLimitCacheCleanupIntervalSeconds { get; set; } = 300; - - /// - /// Enable validation of HTTP headers to prevent header injection attacks. (default: true) - /// - public bool EnableHttpHeaderValidation { get; set; } = true; + public SecurityOptions Security { get; set; } = new SecurityOptions(); internal RemoteCertificateValidationCallback GetRemoteCertificateValidationCallback() { @@ -217,7 +133,7 @@ namespace EonaCat.Connections.Models public void DisableInternalCertificateCheck() { CheckAgainstInternalTrustedCertificates = false; - OnLog?.Invoke(this, "Internal certificate check disabled."); + Debug.WriteLine("Internal certificate check disabled."); } private bool CertificateValidation(object sender, X509Certificate certificate, X509Chain chain, SslPolicyErrors sslPolicyErrors) @@ -242,29 +158,6 @@ namespace EonaCat.Connections.Models return result; } - try - { - if (chain != null && certificate is X509Certificate2 cert) - { - chain.ChainPolicy.RevocationMode = X509RevocationMode.NoCheck; - chain.ChainPolicy.VerificationFlags = - X509VerificationFlags.IgnoreCertificateAuthorityRevocationUnknown | - X509VerificationFlags.IgnoreEndRevocationUnknown | - X509VerificationFlags.AllowUnknownCertificateAuthority; - - chain.Build(cert); - - foreach (var status in chain.ChainStatus) - { - OnLog?.Invoke(this, $"ChainStatus: {status.Status} - {status.StatusInformation}"); - } - } - } - catch (Exception ex) - { - OnLog?.Invoke(this, $"Certificate validation succeeded in {stopwatch.ElapsedMilliseconds} ms"); - } - if (sslPolicyErrors == SslPolicyErrors.None) { reason = "Certificate validation succeeded"; @@ -272,52 +165,59 @@ namespace EonaCat.Connections.Models return result; } - if (CheckAgainstInternalTrustedCertificates && certificate is X509Certificate2 cert2) + if (certificate is X509Certificate2 cert2) { string thumbprint = cert2.Thumbprint?.Replace(" ", "").ToLowerInvariant(); - if (!string.IsNullOrEmpty(thumbprint) && TrustedThumbprints.Contains(thumbprint)) + if (CheckAgainstInternalTrustedCertificates && + !string.IsNullOrEmpty(thumbprint) && + TrustedThumbprints.Contains(thumbprint)) { reason = $"Trusted thumbprint matched: {thumbprint}"; result = true; return result; } - reason = $"Certificate thumbprint not trusted: {thumbprint}"; - result = false; - return result; - } - - if (sslPolicyErrors.HasFlag(SslPolicyErrors.RemoteCertificateChainErrors) && chain != null) - { - bool fatal = false; - - foreach (var status in chain.ChainStatus) + if (!CheckAgainstInternalTrustedCertificates && cert2.Subject.Contains("localhost", StringComparison.OrdinalIgnoreCase)) { - switch (status.Status) - { - case X509ChainStatusFlags.Revoked: - case X509ChainStatusFlags.NotSignatureValid: - fatal = true; - reason = $"Fatal chain error: {status.Status} - {status.StatusInformation}"; - break; - } - - if (fatal) - { - break; - } - } - - if (!fatal) - { - reason = "Certificate accepted (ignoring non-fatal chain warnings)"; + reason = $"Local development certificate accepted: {thumbprint}"; result = true; return result; } + } - result = false; - return result; + try + { + if (chain != null && certificate is X509Certificate2 cert) + { + chain.ChainPolicy.RevocationMode = X509RevocationMode.NoCheck; + chain.ChainPolicy.VerificationFlags = X509VerificationFlags.NoFlag; + chain.Build(cert); + + var fatalChainErrors = chain.ChainStatus + .Where(status => status.Status != X509ChainStatusFlags.NoError && + status.Status != X509ChainStatusFlags.UntrustedRoot && + status.Status != X509ChainStatusFlags.PartialChain) + .ToArray(); + + if (fatalChainErrors.Length == 0 && sslPolicyErrors == SslPolicyErrors.RemoteCertificateChainErrors) + { + reason = "Certificate chain warnings are not accepted without an explicit trusted thumbprint."; + return false; + } + + if (fatalChainErrors.Length > 0) + { + reason = $"Fatal chain error: {string.Join(", ", fatalChainErrors.Select(status => $"{status.Status} ({status.StatusInformation.Trim()})"))}"; + return false; + } + } + } + catch (Exception ex) + { + Debug.WriteLine($"Chain validation exception: {ex}"); + reason = $"Certificate validation exception: {ex}"; + return false; } reason = $"Certificate rejected: {sslPolicyErrors}"; @@ -334,24 +234,19 @@ namespace EonaCat.Connections.Models { stopwatch.Stop(); - OnLog?.Invoke(this, + Debug.WriteLine( $"Certificate validation result={result}. " + $"Reason={reason}. " + $"Duration={stopwatch.ElapsedMilliseconds} ms"); } } - /// - /// Detects whether the application is running inside a Docker container. - /// public static bool IsRunningInContainer => Environment.GetEnvironmentVariable("DOTNET_RUNNING_IN_CONTAINER") == "true" || File.Exists("/.dockerenv"); - /// - /// Configures the settings for use in a Docker/container environment. - /// Sets the host to 0.0.0.0 and the health API bind address to IPAddress.Any. - /// + public bool EnableDualStack { get; set; } + public Configuration UseContainerDefaults() { Host = "0.0.0.0"; @@ -359,11 +254,6 @@ namespace EonaCat.Connections.Models return this; } - /// - /// Calculates the SSL retry delay for a given attempt number, accounting for exponential backoff if enabled. - /// - /// The attempt number (1-based). - /// The delay in seconds. public int GetSslRetryDelaySeconds(int attemptNumber) { if (!UseExponentialBackoffForSslRetries || attemptNumber <= 1) @@ -371,14 +261,33 @@ namespace EonaCat.Connections.Models return SSLRetryDelayInSeconds; } - // Exponential backoff: baseDelay * 2^(attempt-1), capped at max var exponentialDelay = SSLRetryDelayInSeconds * Math.Pow(2, attemptNumber - 1); return (int)Math.Min(exponentialDelay, SSLRetryDelayMaxSeconds); } + public Configuration UseHighScaleProduction() + { + MaxConnections = 1000000; + EnableConnectionDebugLogs = false; + EnablePingPongLogs = false; + KeepAliveTimeSeconds = 30; + KeepAliveIntervalSeconds = 5; + return this; + } + + public Configuration UseDistributedProduction() + { + MaxConnections = 500000; + EnableConnectionDebugLogs = false; + EnableNagle = false; + EnableRST = true; + return this; + } + public void Dispose() { Certificate?.Dispose(); } } -} \ No newline at end of file + +} diff --git a/EonaCat.Connections/Models/Connection.cs b/EonaCat.Connections/Models/Connection.cs index 2bf5317..4a4c368 100644 --- a/EonaCat.Connections/Models/Connection.cs +++ b/EonaCat.Connections/Models/Connection.cs @@ -1,14 +1,13 @@ -using System.Net; +using EonaCat.Connections.ConnectionDiagnostics; +using System.Net; using System.Net.Sockets; using System.Security.Cryptography; using System.Text; using System.Threading.Channels; +using EonaCat.Connections.Security; namespace EonaCat.Connections.Models { - // This file is part of the EonaCat project(s) which is released under the Apache License. - // See the LICENSE file or go to https://EonaCat.com/license for full license details. - public class Connection : IDisposable, IAsyncDisposable { public string Id { get; set; } @@ -48,11 +47,9 @@ namespace EonaCat.Connections.Models return false; } - // Send a zero-byte packet to check if the connection is still alive try { socket.Send(Array.Empty(), 0, 0); - LastActive = DateTime.UtcNow; } catch { @@ -71,6 +68,8 @@ namespace EonaCat.Connections.Models public DateTime ConnectedAt { get; internal set; } private long _lastActiveTicks; + private long _lastDataSentTicks; + private long _lastDataReceivedTicks; public DateTime LastActive { @@ -79,15 +78,41 @@ namespace EonaCat.Connections.Models } public DateTime DisconnectionTime { get; internal set; } - public DateTime LastDataSent { get; internal set; } - public DateTime LastDataReceived { get; internal set; } + public DateTime LastDataSent + { + get => new DateTime(Interlocked.Read(ref _lastDataSentTicks)); + internal set => Interlocked.Exchange(ref _lastDataSentTicks, value.Ticks); + } + public DateTime LastDataReceived + { + get => new DateTime(Interlocked.Read(ref _lastDataReceivedTicks)); + internal set => Interlocked.Exchange(ref _lastDataReceivedTicks, value.Ticks); + } + + private long _securityViolationCount; + private long _rateLimitViolations; + + public long SecurityViolationCount + { + get => Interlocked.Read(ref _securityViolationCount); + set => Interlocked.Exchange(ref _securityViolationCount, value); + } + + public long RateLimitViolations + { + get => Interlocked.Read(ref _rateLimitViolations); + set => Interlocked.Exchange(ref _rateLimitViolations, value); + } + + public void IncrementRateLimitViolations() => Interlocked.Increment(ref _rateLimitViolations); + + public RateLimiter OutgoingRateLimiter { get; set; } public Channel SendQueue = Channel.CreateBounded(new BoundedChannelOptions(8192) { SingleReader = true, SingleWriter = false, - //FullMode = BoundedChannelFullMode.DropOldest }); public TimeSpan IdleTime() => DateTime.UtcNow - LastActive; @@ -117,34 +142,13 @@ namespace EonaCat.Connections.Models bool includeSeconds = true, bool includeMilliseconds = true) { - var parts = new List(); - - if (includeDays) - { - parts.Add($"{(int)span.TotalDays:D2}d"); - } - - if (includeHours) - { - parts.Add($"{span.Hours:D2}h"); - } - - if (includeMinutes) - { - parts.Add($"{span.Minutes:D2}m"); - } - - if (includeSeconds) - { - parts.Add($"{span.Seconds:D2}s"); - } - - if (includeMilliseconds) - { - parts.Add($"{span.Milliseconds:D3}ms"); - } - - return string.Join(" ", parts); + return ConnectionTimeFormatter.Format( + span, + includeDays, + includeHours, + includeMinutes, + includeSeconds, + includeMilliseconds); } public string IdleTimeFormatted(bool days = true, bool hours = true, bool minutes = true, bool seconds = true, bool ms = true) @@ -177,10 +181,6 @@ namespace EonaCat.Connections.Models public Task? SendLoopTask; public Task ReceiveDataTask { get; internal set; } - public bool IsIdleTimeoutTriggered { get; internal set; } - public DateTime LastIdleLogUtc { get; internal set; } - - public double ShowIdleReminderInSeconds { get; set; } = 20; public bool IsClosing { get; internal set; } private bool _disposed; @@ -201,8 +201,8 @@ namespace EonaCat.Connections.Models CancellationToken?.Cancel(); } catch - { - // Do nothing + { + } SendQueue.Writer.TryComplete(); @@ -237,7 +237,7 @@ namespace EonaCat.Connections.Models } catch { - // Do nothing + } SendQueue.Writer.TryComplete(); @@ -254,7 +254,7 @@ namespace EonaCat.Connections.Models } catch { - // Do nothing + } try @@ -263,7 +263,7 @@ namespace EonaCat.Connections.Models } catch { - // Do nothing + } try @@ -273,7 +273,7 @@ namespace EonaCat.Connections.Models } catch { - // Do nothing + } try @@ -282,7 +282,7 @@ namespace EonaCat.Connections.Models } catch { - // Do nothing + } try @@ -291,7 +291,7 @@ namespace EonaCat.Connections.Models } catch { - // Do nothing + } try @@ -300,7 +300,7 @@ namespace EonaCat.Connections.Models } catch { - // Do nothing + } Metadata.Clear(); @@ -328,7 +328,7 @@ namespace EonaCat.Connections.Models } catch { - // Do nothing + } try @@ -337,7 +337,7 @@ namespace EonaCat.Connections.Models } catch { - // Do nothing + } try @@ -346,20 +346,20 @@ namespace EonaCat.Connections.Models } catch { - // Do nothing + } } private static async Task SafeAwait(Task task) { - try + try { - await task.ConfigureAwait(false); + await task.ConfigureAwait(false); } catch { - // Do nothing + } } } -} \ No newline at end of file +} diff --git a/EonaCat.Connections/Models/FramingMode.cs b/EonaCat.Connections/Models/FramingMode.cs index 7bb4911..3749bc2 100644 --- a/EonaCat.Connections/Models/FramingMode.cs +++ b/EonaCat.Connections/Models/FramingMode.cs @@ -1,12 +1,9 @@ namespace EonaCat.Connections.Models { - // This file is part of the EonaCat project(s) which is released under the Apache License. - // See the LICENSE file or go to https://EonaCat.com/license for full license details. - public enum FramingMode { None, Delimiter, LengthPrefixed } -} \ No newline at end of file +} diff --git a/EonaCat.Connections/Models/ProcessedMessage.cs b/EonaCat.Connections/Models/ProcessedMessage.cs index dc26426..6d17dcf 100644 --- a/EonaCat.Connections/Models/ProcessedMessage.cs +++ b/EonaCat.Connections/Models/ProcessedMessage.cs @@ -1,8 +1,5 @@ namespace EonaCat.Connections.Models { - // This file is part of the EonaCat project(s) which is released under the Apache License. - // See the LICENSE file or go to https://EonaCat.com/license for full license details. - public class ProcessedMessage : IDisposable { public TData Data { get; set; } @@ -19,4 +16,4 @@ } } } -} \ No newline at end of file +} diff --git a/EonaCat.Connections/Models/ProcessedTextMessage.cs b/EonaCat.Connections/Models/ProcessedTextMessage.cs index 59111d1..21273a3 100644 --- a/EonaCat.Connections/Models/ProcessedTextMessage.cs +++ b/EonaCat.Connections/Models/ProcessedTextMessage.cs @@ -1,8 +1,5 @@ namespace EonaCat.Connections.Models { - // This file is part of the EonaCat project(s) which is released under the Apache License. - // See the LICENSE file or go to https://EonaCat.com/license for full license details. - public class ProcessedTextMessage : IDisposable { public string Text { get; set; } @@ -11,7 +8,7 @@ public void Dispose() { - // Nothing to dispose + } } -} \ No newline at end of file +} diff --git a/EonaCat.Connections/Models/ProtocolType.cs b/EonaCat.Connections/Models/ProtocolType.cs index bbf5aca..e60e1b3 100644 --- a/EonaCat.Connections/Models/ProtocolType.cs +++ b/EonaCat.Connections/Models/ProtocolType.cs @@ -1,11 +1,8 @@ -namespace EonaCat.Connections.Models +namespace EonaCat.Connections.Models { - // This file is part of the EonaCat project(s) which is released under the Apache License. - // See the LICENSE file or go to https://EonaCat.com/license for full license details. - - public enum ProtocolType - { - TCP, - UDP - } -} \ No newline at end of file + public enum ProtocolType + { + TCP, + UDP + } +} diff --git a/EonaCat.Connections/Models/SecurityOptions.cs b/EonaCat.Connections/Models/SecurityOptions.cs new file mode 100644 index 0000000..2a27e5a --- /dev/null +++ b/EonaCat.Connections/Models/SecurityOptions.cs @@ -0,0 +1,82 @@ +namespace EonaCat.Connections.Models +{ + + public class SecurityOptions + { + + public bool EnableGlobalRateLimiting { get; set; } = true; + + public int GlobalMessagesPerSecond { get; set; } = 50000; + + public bool EnablePerConnectionRateLimiting { get; set; } = true; + + public int ConnectionMessagesPerSecond { get; set; } = 10000; + + public bool EnablePayloadValidation { get; set; } = false; + + public bool EnableSuspiciousContentDetection { get; set; } = false; + + public long MaxPayloadSize { get; set; } = 50 * 1024 * 1024; + + public bool EnableDDoSDetection { get; set; } = false; + + public int MaxConnectionsPerSecondPerIp { get; set; } = 100; + + public int ConnectionSpamThreshold { get; set; } = 10; + + public int SpamDetectionWindowSeconds { get; set; } = 5; + + public bool EnableIPFiltering { get; set; } = false; + + public HashSet WhitelistedIPs { get; set; } = new(); + + public HashSet BlacklistedIPs { get; set; } = new(); + + public int AutoBlockIPAfterViolations { get; set; } = 0; + + public int IPBlockDurationSeconds { get; set; } = 300; + + public bool EnableSlowlorisDetection { get; set; } = false; + + public int SlowlorisMinBytesPerSecond { get; set; } = 1024; + + public int SlowlorisDetectionWindowSeconds { get; set; } = 30; + + public bool EnableHTTPAttackDetection { get; set; } = true; + + public int MaxHTTPHeaderSize { get; set; } = 8192; + + public int MaxHTTPHeaders { get; set; } = 100; + + public bool EnableSYNFloodDetection { get; set; } = false; + + public int MaxHalfOpenConnectionsPerIp { get; set; } = 100; + + public bool EnableRequestDeduplication { get; set; } = true; + + public int DeduplicationWindowSeconds { get; set; } = 60; + + public bool EnableSecurityLogging { get; set; } = true; + + public bool EnableSecurityMetrics { get; set; } = true; + + public bool ValidateMessageNotEmpty { get; set; } = false; + + public bool BlockNullBytePayloads { get; set; } = true; + + public int MessageTimeoutSeconds { get; set; } = 0; + + public bool IsAnyProtectionEnabled => + EnableGlobalRateLimiting || + EnablePerConnectionRateLimiting || + EnablePayloadValidation || + EnableSuspiciousContentDetection || + EnableDDoSDetection || + EnableIPFiltering || + EnableSlowlorisDetection || + EnableHTTPAttackDetection || + EnableSYNFloodDetection || + EnableRequestDeduplication || + BlockNullBytePayloads; + } +} diff --git a/EonaCat.Connections/Models/ServerStatusPage.cs b/EonaCat.Connections/Models/ServerStatusPage.cs index 1f03c86..81c7c05 100644 --- a/EonaCat.Connections/Models/ServerStatusPage.cs +++ b/EonaCat.Connections/Models/ServerStatusPage.cs @@ -1,11 +1,8 @@ -using System.Collections.Concurrent; +using System.Collections.Concurrent; using System.Text; namespace EonaCat.Connections.Models { - // This file is part of the EonaCat project(s) which is released under the Apache License. - // See the LICENSE file or go to https://EonaCat.com/license for full license details. - public class ServerStatusPage : IDisposable { private CancellationTokenSource _autoReportCts; @@ -28,17 +25,8 @@ namespace EonaCat.Connections.Models _errorPage = errorPage; } - /// - /// Gets whether automatic HTML status page generation is currently running. - /// public bool IsAutoReportRunning => _autoReportRunning; - /// - /// Starts periodic automatic generation of the HTML server status page. - /// - /// Directory where the HTML file is written. - /// Interval in seconds between page generations. - /// The HTML file name. public void StartAutoReport(string outputDirectory, int intervalSeconds = 5, string fileName = "status-server.html") { if (_autoReportRunning) @@ -70,7 +58,7 @@ namespace EonaCat.Connections.Models } catch { - // Swallow to keep the loop alive + } try @@ -85,9 +73,6 @@ namespace EonaCat.Connections.Models }, token); } - /// - /// Stops the automatic HTML status page generation. - /// public void StopAutoReport() { if (!_autoReportRunning) @@ -156,7 +141,6 @@ namespace EonaCat.Connections.Models sb.AppendLine("
"); sb.AppendLine($"

{HtmlEncode(title)}

"); - // Server summary cards sb.AppendLine("
"); sb.AppendLine($"
Listen Address
{HtmlEncode(_config.Host)}:{_config.Port}
"); sb.AppendLine($"
Protocol
{HtmlEncode(_config.Protocol.ToString())}
"); @@ -168,7 +152,6 @@ namespace EonaCat.Connections.Models sb.AppendLine($"
Uptime
{FormatTimeSpan(stats.Uptime)}
"); sb.AppendLine("
"); - // Throughput cards sb.AppendLine("
"); sb.AppendLine($"
Total Bytes Sent
{FormatBytes(stats.BytesSent)}
"); sb.AppendLine($"
Total Bytes Received
{FormatBytes(stats.BytesReceived)}
"); @@ -177,7 +160,6 @@ namespace EonaCat.Connections.Models sb.AppendLine($"
Msg/sec
{stats.MessagesPerSecond:F2}
"); sb.AppendLine("
"); - // Connected clients table sb.AppendLine("

Connected Clients

"); var clientList = clients.Values.ToArray(); @@ -231,51 +213,50 @@ namespace EonaCat.Connections.Models } sb.AppendLine(""); + sb.AppendLine(""); + } + + if (_errorPage != null) + { + var sslErrors = _errorPage.GetSslErrors(); + sb.AppendLine("

SSL Errors

"); + + if (sslErrors.Count == 0) + { + sb.AppendLine("
"); + sb.AppendLine("

✔ No SSL errors recorded.

"); + sb.AppendLine("
"); + } + else + { + sb.AppendLine("
"); + sb.AppendLine($"
Total SSL Errors
{sslErrors.Count}
"); + sb.AppendLine("
"); + sb.AppendLine(""); + sb.AppendLine(""); + sb.AppendLine(""); + sb.AppendLine(""); + sb.AppendLine(""); + sb.AppendLine(""); + sb.AppendLine(""); + sb.AppendLine(""); + sb.AppendLine(""); + + foreach (var sslError in sslErrors) + { + sb.AppendLine(""); + sb.AppendLine($""); + sb.AppendLine($""); + sb.AppendLine($""); + sb.AppendLine($""); + sb.AppendLine($""); + sb.AppendLine(""); + } + + sb.AppendLine(""); sb.AppendLine("
TimestampClient / ServerClient IDErrorException Type
{sslError.Timestamp:yyyy-MM-dd HH:mm:ss} UTC{HtmlEncode(sslError.Nickname ?? sslError.ClientId ?? "-")}{HtmlEncode(sslError.ClientId ?? "-")}{HtmlEncode(sslError.Message ?? "-")}{HtmlEncode(sslError.ExceptionType ?? "-")}
"); } - - // SSL Errors section - if (_errorPage != null) - { - var sslErrors = _errorPage.GetSslErrors(); - sb.AppendLine("

SSL Errors

"); - - if (sslErrors.Count == 0) - { - sb.AppendLine("
"); - sb.AppendLine("

✔ No SSL errors recorded.

"); - sb.AppendLine("
"); - } - else - { - sb.AppendLine("
"); - sb.AppendLine($"
Total SSL Errors
{sslErrors.Count}
"); - sb.AppendLine("
"); - sb.AppendLine(""); - sb.AppendLine(""); - sb.AppendLine(""); - sb.AppendLine(""); - sb.AppendLine(""); - sb.AppendLine(""); - sb.AppendLine(""); - sb.AppendLine(""); - sb.AppendLine(""); - - foreach (var sslError in sslErrors) - { - sb.AppendLine(""); - sb.AppendLine($""); - sb.AppendLine($""); - sb.AppendLine($""); - sb.AppendLine($""); - sb.AppendLine($""); - sb.AppendLine(""); - } - - sb.AppendLine(""); - sb.AppendLine("
TimestampClient / ServerClient IDErrorException Type
{sslError.Timestamp:yyyy-MM-dd HH:mm:ss} UTC{HtmlEncode(sslError.Nickname ?? sslError.ClientId ?? "-")}{HtmlEncode(sslError.ClientId ?? "-")}{HtmlEncode(sslError.Message ?? "-")}{HtmlEncode(sslError.ExceptionType ?? "-")}
"); - } - } + } sb.AppendLine($"
Generated at {now:yyyy-MM-dd HH:mm:ss} UTC — Auto-refresh every {_config.ServerStatusPageIntervalSeconds}s — EonaCat.Connections
"); sb.AppendLine("
"); diff --git a/EonaCat.Connections/Models/SocketErrorEntry.cs b/EonaCat.Connections/Models/SocketErrorEntry.cs index e2c09c6..3bcdb22 100644 --- a/EonaCat.Connections/Models/SocketErrorEntry.cs +++ b/EonaCat.Connections/Models/SocketErrorEntry.cs @@ -2,9 +2,6 @@ using System.Net.Sockets; namespace EonaCat.Connections.Models { - // This file is part of the EonaCat project(s) which is released under the Apache License. - // See the LICENSE file or go to https://EonaCat.com/license for full license details. - public class SocketErrorEntry { public DateTime Timestamp { get; set; } = DateTime.UtcNow; diff --git a/EonaCat.Connections/Models/SocketStatusPage.cs b/EonaCat.Connections/Models/SocketStatusPage.cs index 3e57236..7aae8e2 100644 --- a/EonaCat.Connections/Models/SocketStatusPage.cs +++ b/EonaCat.Connections/Models/SocketStatusPage.cs @@ -1,12 +1,9 @@ -using System.Collections.Concurrent; +using System.Collections.Concurrent; using System.Net.Sockets; using System.Text; namespace EonaCat.Connections.Models { - // This file is part of the EonaCat project(s) which is released under the Apache License. - // See the LICENSE file or go to https://EonaCat.com/license for full license details. - public class SocketStatusPage : IDisposable { private readonly ConcurrentQueue _errors = new ConcurrentQueue(); @@ -20,12 +17,6 @@ namespace EonaCat.Connections.Models _maxEntries = maxEntries; } - /// - /// Starts periodic automatic generation of the HTML status page. - /// - /// Directory where the HTML file is written. - /// Interval in seconds between report generations. - /// The HTML file name. public void StartAutoHtmlReport(string outputDirectory, int intervalSeconds = 60, string fileName = "status-errors.html") { if (_autoReportRunning) @@ -56,7 +47,7 @@ namespace EonaCat.Connections.Models } catch { - // Swallow to keep the loop alive + } try @@ -71,9 +62,6 @@ namespace EonaCat.Connections.Models }, token); } - /// - /// Stops the automatic HTML report generation. - /// public void StopAutoHtmlReport() { if (!_autoReportRunning) @@ -93,9 +81,6 @@ namespace EonaCat.Connections.Models } } - /// - /// Gets whether automatic HTML report generation is currently running. - /// public bool IsAutoHtmlReportRunning => _autoReportRunning; public void AddError(SocketErrorEntry entry) @@ -122,8 +107,13 @@ namespace EonaCat.Connections.Models { var all = _errors.ToArray(); int skip = Math.Max(0, all.Length - count); - var result = new SocketErrorEntry[Math.Min(count, all.Length)]; - Array.Copy(all, skip, result, 0, result.Length); + int take = Math.Min(count, all.Length); + if (skip == 0 && take == all.Length) + { + return all; + } + var result = new SocketErrorEntry[take]; + Array.Copy(all, skip, result, 0, take); return result; } diff --git a/EonaCat.Connections/Models/Stats.cs b/EonaCat.Connections/Models/Stats.cs index 1f79216..d08a341 100644 --- a/EonaCat.Connections/Models/Stats.cs +++ b/EonaCat.Connections/Models/Stats.cs @@ -1,10 +1,5 @@ -using System.Threading; - -namespace EonaCat.Connections +namespace EonaCat.Connections { - // This file is part of the EonaCat project(s) which is released under the Apache License. - // See the LICENSE file or go to https://EonaCat.com/license for full license details. - public class Stats : IDisposable { private int _activeConnections; @@ -78,7 +73,7 @@ namespace EonaCat.Connections public void Dispose() { - // Nothing to dispose + } } -} \ No newline at end of file +} diff --git a/EonaCat.Connections/NetworkClient.cs b/EonaCat.Connections/NetworkClient.cs index 8ce0a7c..69e22c2 100644 --- a/EonaCat.Connections/NetworkClient.cs +++ b/EonaCat.Connections/NetworkClient.cs @@ -1,25 +1,22 @@ -using EonaCat.Connections.EventArguments; +using EonaCat.Connections.Contracts; +using EonaCat.Connections.EventArguments; using EonaCat.Connections.Helpers; using EonaCat.Connections.Models; -using System.Buffers; using System.Net; -using System.Net.Security; using System.Net.Sockets; -using System.Security.Authentication; using System.Security.Cryptography; -using System.Security.Cryptography.X509Certificates; using System.Text; using ErrorEventArgs = EonaCat.Connections.EventArguments.ErrorEventArgs; using ProtocolType = EonaCat.Connections.Models.ProtocolType; namespace EonaCat.Connections { - // This file is part of the EonaCat project(s) which is released under the Apache License. - // See the LICENSE file or go to https://EonaCat.com/license for full license details. - - public class NetworkClient : IAsyncDisposable, IDisposable + public partial class NetworkClient : IConnectorClient { private const int DEFAULT_WAITING_TIMEOUT_IN_SECONDS = 30; + private const int SEND_RETRY_MAX_ATTEMPTS = 3; + private const int SEND_RETRY_INITIAL_DELAY_MS = 100; + private const int SEND_RETRY_MAX_DELAY_MS = 2000; private readonly Configuration _config; private Task _autoReconnectTask; private TcpClient _tcpClient; @@ -34,168 +31,97 @@ namespace EonaCat.Connections private readonly Decoder _utf8Decoder = Encoding.UTF8.GetDecoder(); private char[] _charBuffer = new char[8192]; + private IPEndPoint _resolvedEndPoint; + private static readonly byte[] PingBytes = Encoding.UTF8.GetBytes(Configuration.PING_VALUE); private static readonly byte[] PongBytes = Encoding.UTF8.GetBytes(Configuration.PONG_VALUE); - public event EventHandler OnLog; + private bool _isConnected; public bool IsConnected { - get; - set; + get => _isConnected && ValidateConnectionState(); + set => _isConnected = value; + } + + private bool ValidateConnectionState() + { + if (!_isConnected) + { + return false; + } + + if (_config.Protocol == ProtocolType.TCP) + { + if (_tcpClient == null || _stream == null) + { + return false; + } + + try + { + if (!_tcpClient.Connected) + { + return false; + } + + if (_tcpClient.Client != null && _tcpClient.Client.Connected) + { + try + { + _tcpClient.Client.Send(Array.Empty(), 0, 0, SocketFlags.None); + return true; + } + catch + { + return false; + } + } + return false; + } + catch + { + return false; + } + } + else + { + return _udpClient != null && _udpClient.Client != null; + } } private Task _pingTask; private Task _pongTask; - private Task _idleMonitorTask; - public bool IsSecure => _config != null && (_config.UseSsl || _config.UseAesEncryption); public bool IsEncrypted => _config != null && _config.UseAesEncryption; public bool IsTcp => _config != null && _config.Protocol == ProtocolType.TCP; private readonly SemaphoreSlim _connectLock = new(1, 1); - private readonly SemaphoreSlim _streamReadLock = new(1, 1); private readonly SemaphoreSlim _streamWriteLock = new(1, 1); private readonly SemaphoreSlim _connectionAttemptLock = new(1, 1); + private readonly SemaphoreSlim _disconnectLock = new(1, 1); private long _bytesSent; private long _bytesReceived; private long _messagesSent; private long _messagesReceived; + private long _lastActiveTicks; public DateTime ConnectionTime { get; private set; } public TimeSpan Uptime => DateTime.UtcNow - ConnectionTime; - public DateTime LastActive { get; internal set; } + public DateTime LastActive + { + get => new DateTime(Interlocked.Read(ref _lastActiveTicks)); + internal set => Interlocked.Exchange(ref _lastActiveTicks, value.Ticks); + } public long BytesSent => Interlocked.Read(ref _bytesSent); public long BytesReceived => Interlocked.Read(ref _bytesReceived); public long MessagesSent => Interlocked.Read(ref _messagesSent); public long MessagesReceived => Interlocked.Read(ref _messagesReceived); - public int IdleTimeInSeconds() - { - var idleTime = IdleTime(); - return (int)idleTime.TotalSeconds; - } - - public int IdleTimeInMinutes() - { - var idleTime = IdleTime(); - return (int)idleTime.TotalMinutes; - } - - public int IdleTimeInHours() - { - var idleTime = IdleTime(); - return (int)idleTime.TotalHours; - } - - public int IdleTimeInDays() - { - var idleTime = IdleTime(); - return (int)idleTime.TotalDays; - } - - public TimeSpan IdleTime() - { - return DateTime.UtcNow - LastActive; - } - - public string IdleTimeFormatted(bool includeDays = true, bool includeHours = true, bool includeMinutes = true, bool includeSeconds = true, bool includeMilliseconds = true) - { - var idleTime = IdleTime(); - var parts = new List(); - - if (includeDays) - { - parts.Add($"{(int)idleTime.TotalDays:D2}d"); - } - - if (includeHours) - { - parts.Add($"{idleTime.Hours:D2}h"); - } - - if (includeMinutes) - { - parts.Add($"{idleTime.Minutes:D2}m"); - } - - if (includeSeconds) - { - parts.Add($"{idleTime.Seconds:D2}s"); - } - - if (includeMilliseconds) - { - parts.Add($"{idleTime.Milliseconds:D3}ms"); - } - return string.Join(" ", parts); - } - - public int ConnectedTimeInSeconds() - { - var connectedTime = DateTime.UtcNow - ConnectionTime; - return (int)connectedTime.TotalSeconds; - } - - public int ConnectedTimeInMinutes() - { - var connectedTime = DateTime.UtcNow - ConnectionTime; - return (int)connectedTime.TotalMinutes; - } - - public int ConnectedTimeInHours() - { - var connectedTime = DateTime.UtcNow - ConnectionTime; - return (int)connectedTime.TotalHours; - } - - public int ConnectedTimeInDays() - { - var connectedTime = DateTime.UtcNow - ConnectionTime; - return (int)connectedTime.TotalDays; - } - - public TimeSpan ConnectedTime() - { - return DateTime.UtcNow - ConnectionTime; - } - - public string ConnectedTimeFormatted(bool includeDays = true, bool includeHours = true, bool includeMinutes = true, bool includeSeconds = true, bool includeMilliseconds = true) - { - var connectedTime = ConnectedTime(); - var parts = new List(); - - if (includeDays) - { - parts.Add($"{(int)connectedTime.TotalDays:D2}d"); - } - - if (includeHours) - { - parts.Add($"{connectedTime.Hours:D2}h"); - } - - if (includeMinutes) - { - parts.Add($"{connectedTime.Minutes:D2}m"); - } - - if (includeSeconds) - { - parts.Add($"{connectedTime.Seconds:D2}s"); - } - - if (includeMilliseconds) - { - parts.Add($"{connectedTime.Milliseconds:D3}ms"); - } - return string.Join(" ", parts); - } - private bool _disposed; private bool _stopAutoReconnecting; - private DisconnectReason _reason; + private DisconnectReason _reason = DisconnectReason.Unknown; private bool _wasConnected; public event EventHandler OnConnected; @@ -228,2359 +154,6 @@ namespace EonaCat.Connections HealthApi = new HealthApiServer(BuildHealthJson, BuildStatusJson); } - private string BuildHealthJson() - { - var E = HealthApiServer.JsonEscape; - return "{" + - "\"status\":\"ok\"," + - "\"type\":\"client\"," + - $"\"serverAddress\":{E(_config.Host + ":" + _config.Port)}," + - $"\"protocol\":{E(_config.Protocol.ToString())}," + - $"\"isConnected\":{(IsConnected ? "true" : "false")}," + - $"\"isSecure\":{(IsSecure ? "true" : "false")}," + - $"\"isEncrypted\":{(IsEncrypted ? "true" : "false")}," + - $"\"uptimeSeconds\":{Uptime.TotalSeconds:F1}," + - $"\"connectionTimeUtc\":{E(ConnectionTime.ToString("O"))}" + - "}"; - } - private string BuildStatusJson() - { - var E = HealthApiServer.JsonEscape; - return "{" + - "\"status\":\"ok\"," + - "\"type\":\"client\"," + - $"\"serverAddress\":{E(_config.Host + ":" + _config.Port)}," + - $"\"protocol\":{E(_config.Protocol.ToString())}," + - $"\"isConnected\":{(IsConnected ? "true" : "false")}," + - $"\"isSecure\":{(IsSecure ? "true" : "false")}," + - $"\"isEncrypted\":{(IsEncrypted ? "true" : "false")}," + - $"\"nickname\":{E(Nickname)}," + - $"\"bytesSent\":{BytesSent}," + - $"\"bytesReceived\":{BytesReceived}," + - $"\"messagesSent\":{MessagesSent}," + - $"\"messagesReceived\":{MessagesReceived}," + - $"\"uptimeSeconds\":{Uptime.TotalSeconds:F1}," + - $"\"connectionTimeUtc\":{E(ConnectionTime.ToString("O"))}," + - $"\"lastActiveUtc\":{(LastActive == default ? "null" : E(LastActive.ToString("O")))}," + - $"\"idleTimeSeconds\":{IdleTime().TotalSeconds:F1}," + - $"\"lastDataSentUtc\":{(LastDataSent == default ? "null" : E(LastDataSent.ToString("O")))}," + - $"\"lastDataReceivedUtc\":{(LastDataReceived == default ? "null" : E(LastDataReceived.ToString("O")))}," + - $"\"disconnectionTimeUtc\":{(DisconnectionTime == default ? "null" : E(DisconnectionTime.ToString("O")))}," + - $"\"isAutoConnectStarted\":{(IsAutoConnectStarted ? "true" : "false")}," + - $"\"totalErrors\":{StatusPage.TotalErrors}," + - $"\"sslErrors\":{StatusPage.SslErrorCount}" + - "}"; - } - - public async Task ConnectAsync() - { - DebugConnection($"Attempting to connect to {_config.Host}:{_config.Port} using protocol {_config.Protocol} with SSL: {_config.UseSsl} and AES: {_config.UseAesEncryption}"); - await _connectLock.WaitAsync().ConfigureAwait(false); - DebugConnection($"Acquired connection lock for {_config.Host}:{_config.Port}"); - - try - { - if (_clientCts == null || _clientCts.IsCancellationRequested) - { - _clientCts?.Dispose(); - _clientCts = new CancellationTokenSource(); - } - - // Prevent duplicate connections if already connected - if (IsConnected) - { - if (_config.Protocol == ProtocolType.TCP) - { - if (_stream == null || !_stream.CanRead || !_stream.CanWrite) - { - await DisconnectClientAsync(DisconnectReason.RemoteClosed).ConfigureAwait(false); - } - else - { - return true; - } - } - else - { - if (_udpClient == null) - { - IsConnected = false; - } - else - { - return true; - } - } - } - - DebugConnection($"Starting connection process for {_config.Host}:{_config.Port}"); - DebugConnection($"Cleaned up existing connection for {_config.Host}:{_config.Port}"); - _connectionCts?.Cancel(); - _connectionCts?.Dispose(); - - _connectionCts = new CancellationTokenSource(); - - DebugConnection($"Connecting to {_config.Host}:{_config.Port} using protocol {_config.Protocol}"); - bool isConnected = false; - - if (_config.Protocol == ProtocolType.TCP) - { - var result = await ConnectTcpAsync().ConfigureAwait(false); - isConnected = result; - if (!result) - { - throw new Exception("Failed to connect via TCP"); - } - } - else - { - var result = await ConnectUdpAsync().ConfigureAwait(false); - isConnected = result; - if (!result) - { - throw new Exception("Failed to connect via UDP"); - } - } - - if (isConnected) - { - DebugConnection($"Successfully connected to {_config.Host}:{_config.Port}"); - - // If we already had a nickname, resend it - if (!string.IsNullOrEmpty(Nickname)) - { - await SendNicknameAsync(Nickname).ConfigureAwait(false); - } - - DebugConnection($"Starting background tasks for {_config.Host}:{_config.Port}"); - if (_config.EnableAutoReconnect && - (_autoReconnectTask == null || _autoReconnectTask.IsCompleted || _autoReconnectTask.IsCanceled || _autoReconnectTask.IsFaulted)) - { - if (_autoReconnectSource == null || _autoReconnectSource.IsCancellationRequested) - { - _autoReconnectSource?.Dispose(); - _autoReconnectSource = new CancellationTokenSource(); - } - - _autoReconnectTask = Task.Run(() => AutoReconnectAsync(_autoReconnectSource.Token), _autoReconnectSource.Token); - } - - _wasConnected = true; - } - - OnConnected?.Invoke(this, new ConnectionEventArgs - { - ClientId = Nickname ?? "self", - RemoteEndPoint = new IPEndPoint(IPAddress.Parse(_config.Host), _config.Port) - }); - - if (_config.EnableAutoHtmlReports) - { - StatusPage.StartAutoHtmlReport( - _config.HtmlReportOutputDirectory, - _config.HtmlReportIntervalSeconds, - "status-client-errors.html"); - } - - if (_config.EnableHealthApi && !HealthApi.IsRunning) - { - HealthApi.Start(_config.HealthApiPort, _config.HealthApiBindAddress); - } - - return true; - } - catch (Exception exception) - { - RecordError(exception, "Connection error"); - OnGeneralError?.Invoke(this, new ErrorEventArgs - { - Exception = exception, - Message = "Connection error" - }); - return false; - } - finally - { - try - { - _connectLock?.Release(); - } - catch - { - // Do nothing - } - } - } - - private async Task CleanupExistingConnectionAsync() - { - try - { - _stream?.Close(); - _stream?.Dispose(); - _stream = null; - - if (_tcpClient != null) - { - try - { - _tcpClient?.Client?.Shutdown(SocketShutdown.Both); - } - catch - { - // Do nothing - } - - _tcpClient?.Close(); - _tcpClient?.Dispose(); - _tcpClient = null; - } - - if (_receiveTask != null) - { - await Task.WhenAny(_receiveTask, Task.Delay(3000)); - } - } - catch (Exception ex) - { - DebugConnection($"Error cleaning up existing connection for {_config.Host}:{_config.Port}: {ex.Message}"); - OnLog?.Invoke(this, $"Error cleaning up existing connection: {ex.Message}"); - } - } - - private async Task ConnectTcpAsync() - { - await _connectionAttemptLock.WaitAsync(); - - try - { - if (IsConnected) - { - return true; - } - - int attempt = 0; - - while (_config.SSLMaxRetries == 0 || attempt < _config.SSLMaxRetries) - { - if (_clientCts != null && _clientCts.IsCancellationRequested) - { - break; - } - - attempt++; - - TcpClient tcpClient = null; - SslHandshakeDiagnostics sslDiagnostics = null; - - try - { - tcpClient = new TcpClient - { - NoDelay = !_config.EnableNagle, - ReceiveBufferSize = _config.BufferSize, - SendBufferSize = _config.BufferSize, - LingerState = new LingerOption(_config.EnableRST, 0) - }; - - if (EnableKeepAlive) - { - DebugConnection($"Enabling TCP keep-alive for {_config.Host}:{_config.Port} with KeepAliveTimeSeconds: {_config.KeepAliveTimeSeconds}, KeepAliveIntervalSeconds: {_config.KeepAliveIntervalSeconds}, KeepAliveRetryCount: {_config.KeepAliveRetryCount}"); - ConfigureKeepAlive(tcpClient.Client, _config.KeepAliveTimeSeconds, _config.KeepAliveIntervalSeconds, _config.KeepAliveRetryCount); - } - - await CleanupExistingConnectionAsync().ConfigureAwait(false); - using var connectCts = CancellationTokenSource.CreateLinkedTokenSource(_clientCts.Token); - connectCts.CancelAfter(_config.ConnectionTimeout > TimeSpan.Zero ? _config.ConnectionTimeout : TimeSpan.FromSeconds(10)); -#if NET8_0_OR_GREATER - await tcpClient.ConnectAsync(_config.Host, _config.Port, connectCts.Token).ConfigureAwait(false); -#else - var connectTask = tcpClient.ConnectAsync(_config.Host, _config.Port); - var timeoutTask = Task.Delay(Timeout.Infinite, connectCts.Token); - if (await Task.WhenAny(connectTask, timeoutTask).ConfigureAwait(false) != connectTask) - { - throw new OperationCanceledException("TCP connect timed out."); - } - await connectTask.ConfigureAwait(false); -#endif - _tcpClient = tcpClient; - tcpClient = null; - - LastPongReceived = DateTime.UtcNow; - DebugConnection($"TCP connection established to {_config.Host}:{_config.Port} on attempt {attempt} using client {_tcpClient.Client.LocalEndPoint}"); - NetworkStream networkStream = _tcpClient.GetStream(); - DebugConnection($"Obtained network stream for {_config.Host}:{_config.Port} on attempt {attempt}, SSL Enabled: {_config.UseSsl}"); - - if (!_config.UseSsl) - { - _stream = networkStream; - break; - } - - // SSL setup - var sslStream = new SslStream(networkStream, leaveInnerStreamOpen: true, _config.GetRemoteCertificateValidationCallback()); - sslDiagnostics = _config.EnableSslDiagnostics ? new SslHandshakeDiagnostics() : null; - var remoteEndPoint = _tcpClient?.Client.RemoteEndPoint?.ToString() ?? "unknown"; - sslDiagnostics?.StartHandshake(remoteEndPoint, _config.Certificate != null); - -#if NET8_0_OR_GREATER - var clientOptions = new SslClientAuthenticationOptions - { - TargetHost = _config.Host, - ClientCertificates = _config.Certificate != null ? new X509CertificateCollection { _config.Certificate } : null, - EnabledSslProtocols = SslProtocols.Tls12 | SslProtocols.Tls13, - CertificateRevocationCheckMode = _config.CheckCertificateRevocation ? X509RevocationMode.Online : X509RevocationMode.NoCheck, - AllowRenegotiation = _config.AllowTlsRenegotiation - }; - DebugConnection($"Authenticating SSL connection to {_config.Host}:{_config.Port} with SNI: {_config.Host}, Client Certificate: {(_config.Certificate != null ? "Yes" : "No")}, Enabled Protocols: {clientOptions.EnabledSslProtocols}, Check Certificate Revocation: {_config.CheckCertificateRevocation}"); - sslDiagnostics?.StartStage("ClientAuth"); - await sslStream.AuthenticateAsClientAsync(clientOptions).ConfigureAwait(false); - sslDiagnostics?.EndStage("ClientAuth"); -#else - sslDiagnostics?.StartStage("ClientAuth"); - if (_config.Certificate != null) - { - await sslStream.AuthenticateAsClientAsync(_config.Host, new X509CertificateCollection { _config.Certificate }, SslProtocols.Tls12, _config.CheckCertificateRevocation).ConfigureAwait(false); - } - else - { - await sslStream.AuthenticateAsClientAsync(_config.Host, null, SslProtocols.Tls12, _config.CheckCertificateRevocation).ConfigureAwait(false); - } - sslDiagnostics?.EndStage("ClientAuth"); -#endif - - DebugConnection($"SSL authentication successful for {_config.Host}:{_config.Port} using SNI: {_config.Host}, Client Certificate: {(_config.Certificate != null ? "Yes" : "No")}, Enabled Protocols: {(sslStream.SslProtocol)}, Cipher Algorithm: {sslStream.CipherAlgorithm}, Hash Algorithm: {sslStream.HashAlgorithm}, Key Exchange Algorithm: {sslStream.KeyExchangeAlgorithm}"); - sslDiagnostics?.RecordSuccess(sslStream); - if (sslDiagnostics != null) - { - DebugConnection($"[SSL Metrics] {sslDiagnostics}"); - } - _stream = sslStream; - break; - } - catch (SocketException socketEx) - { - var errorMsg = $"Socket error on TCP connect attempt {attempt}: {socketEx.SocketErrorCode} - {socketEx.SocketErrorCode switch { SocketError.ConnectionRefused => "Connection refused - server not listening or firewall blocked", SocketError.HostUnreachable => "Host unreachable - network unreachable or no route to host", SocketError.NetworkUnreachable => "Network unreachable", SocketError.TimedOut => "Connection attempt timed out", _ => "Unknown socket error" }}"; - RecordError(socketEx, errorMsg); - DebugConnection($"[Attempt {attempt}] Socket error: {socketEx.SocketErrorCode} - {socketEx.Message}"); - OnLog?.Invoke(this, $"[Attempt {attempt}] TCP connection failed (SocketError={socketEx.SocketErrorCode}): {socketEx.Message}, cannot connect to {_config.Host}:{_config.Port}"); - if (_config.SSLMaxRetries != 0 && attempt >= _config.SSLMaxRetries) - { - throw; - } - } - catch (IOException ioEx) when (ioEx.InnerException is SocketException innerSocketEx) - { - var errorMsg = $"Socket IO error on TCP connect attempt {attempt}: {innerSocketEx.SocketErrorCode} - {innerSocketEx.SocketErrorCode switch { SocketError.ConnectionRefused => "Connection refused", SocketError.HostUnreachable => "Host unreachable", _ => "Unknown socket error" }}"; - RecordError(ioEx, errorMsg); - DebugConnection($"[Attempt {attempt}] Socket IO error: {innerSocketEx.SocketErrorCode} - {ioEx.Message}"); - OnLog?.Invoke(this, $"[Attempt {attempt}] TCP connection failed (SocketError={innerSocketEx.SocketErrorCode}): {ioEx.Message}, cannot connect to {_config.Host}:{_config.Port}"); - if (_config.SSLMaxRetries != 0 && attempt >= _config.SSLMaxRetries) - { - throw; - } - } - catch (Exception ex) - { - var isRecoverable = _config.UseSsl ? Helpers.SslHandshakeDiagnostics.IsRecoverableFailure(ex) : false; - sslDiagnostics?.RecordFailure(ex, isRecoverable); - - RecordError(ex, $"Connection error on attempt {attempt}: {ex.GetType().Name} - {ex.Message}", isSslError: _config.UseSsl); - if (_config.UseSsl) - { - // Try to read SSL error notification from server - string serverSslError = null; - try - { - var rawStream = _tcpClient?.GetStream(); - if (rawStream != null && rawStream.DataAvailable) - { - var buf = new byte[1024]; - var n = await rawStream.ReadAsync(buf, 0, buf.Length).ConfigureAwait(false); - if (n > 0) - { - var msg = Encoding.UTF8.GetString(buf, 0, n); - if (msg.Contains(Configuration.SSL_ERROR_PREFIX)) - { - var startIdx = msg.IndexOf(Configuration.SSL_ERROR_PREFIX, StringComparison.Ordinal) + Configuration.SSL_ERROR_PREFIX.Length; - var endIdx = msg.IndexOf(Configuration.SSL_ERROR_SUFFIX, StringComparison.Ordinal); - if (endIdx > startIdx) - { - serverSslError = msg.Substring(startIdx, endIdx - startIdx); - } - } - } - } - } - catch (Exception readEx) - { - DebugConnection($"Unable to read SSL error notification from server: {readEx.GetType().Name}"); - } - - // Try to send SSL error notification to server - try - { - var rawStream = _tcpClient?.GetStream(); - if (rawStream != null) - { - var notification = Encoding.UTF8.GetBytes($"{Configuration.SSL_ERROR_PREFIX}Client SSL error: {ex.GetType().Name} - {ex.Message}{Configuration.SSL_ERROR_SUFFIX}"); - await rawStream.WriteAsync(notification, 0, notification.Length).ConfigureAwait(false); - await rawStream.FlushAsync().ConfigureAwait(false); - } - } - catch (Exception sendEx) - { - DebugConnection($"Unable to send SSL error notification to server: {sendEx.GetType().Name}"); - } - - OnSslError?.Invoke(this, new ErrorEventArgs - { - Exception = ex, - Message = serverSslError != null - ? $"SSL connection error on attempt {attempt}. Server reported: {serverSslError}" - : $"SSL connection error on attempt {attempt}: {ex.GetType().Name} - {ex.Message}" - }); - } - else - { - OnGeneralError?.Invoke(this, new ErrorEventArgs - { - Exception = ex, - Message = $"TCP connection error on attempt {attempt}: {ex.GetType().Name} - {ex.Message}" - }); - } - OnLog?.Invoke(this, $"[Attempt {attempt}] TCP/SSL connection failed: {ex.GetType().Name} - {ex.Message}, cannot connect to {_config.Host}:{_config.Port}"); - if (_config.SSLMaxRetries != 0 && attempt >= _config.SSLMaxRetries) - { - throw; - } - } - finally - { - try { tcpClient?.Close(); tcpClient?.Dispose(); } catch { } - tcpClient = null; - } - await Task.Delay(_config.SSLRetryDelayInSeconds * 1000).ConfigureAwait(false); - } - - if (_config.UseAesEncryption) - { - _aesEncryption?.Dispose(); - _aesEncryption = await AesKeyExchange.ReceiveAesKeyAsync(_stream, _config.AesPassword).ConfigureAwait(false); - } - - IsConnected = true; - - // Start receive loop - _receiveTask = Task.Run(async () => await ReceiveDataAsync(_connectionCts.Token)); - - if (_config.EnableHeartbeat) - { - _pingTask = Task.Run(() => StartPingLoopAsync(_connectionCts.Token)); - _pongTask = Task.Run(() => StartPongLoop(_connectionCts.Token)); - } - - if (_config.IdleTimeoutSeconds > 0) - { - _idleMonitorTask = Task.Run(() => MonitorIdleTimeoutAsync(_connectionCts.Token)); - } - - return true; - } - finally - { - _connectionAttemptLock.Release(); - } - } - - private void UpdateLastActive() - { - LastActive = DateTime.UtcNow; - LastDataReceived = DateTime.UtcNow; - IsIdleTimeoutTriggered = false; - _lastIdleLogUtc = DateTime.MinValue; - } - - private async Task CancelAndWaitAsync() - { - _connectionCts?.Cancel(); - _connectionCts?.Dispose(); - _connectionCts = null; - - await Task.WhenAll( - SafeTaskCompletion(_pingTask), - SafeTaskCompletion(_pongTask), - SafeTaskCompletion(_receiveTask), - SafeTaskCompletion(_idleMonitorTask) - ); - } - - public async ValueTask DisposeAsync() - { - if (_disposed) - { - return; - } - - _disposed = true; - - try - { - _clientCts?.Cancel(); - - await SafeTaskCompletion(_autoReconnectTask); - try - { - _autoReconnectTask?.Dispose(); - } - catch - { - // Do nothing - } - - _autoReconnectTask = null; - - await DisconnectClientAsync(); - await CleanupAsync(); - - _clientCts?.Dispose(); - _clientCts = null; - - _autoReconnectSource?.Cancel(); - _autoReconnectSource?.Dispose(); - _autoReconnectSource = null; - - await SafeTaskCompletion(_pingTask); - await SafeTaskCompletion(_pongTask); - await SafeTaskCompletion(_idleMonitorTask); - - _pingTask?.Dispose(); - _pongTask?.Dispose(); - _idleMonitorTask?.Dispose(); - - _pingTask = null; - _pongTask = null; - _idleMonitorTask = null; - - _connectLock?.Dispose(); - _connectionAttemptLock?.Dispose(); - _streamReadLock?.Dispose(); - _streamWriteLock?.Dispose(); - - HealthApi.Dispose(); - - OnConnected = null; - OnDisconnected = null; - OnDataReceived = null; - OnGeneralError = null; - OnPingResponse = null; - OnPongResponse = null; - OnSslError = null; - OnEncryptionError = null; - OnNicknameSend = null; - OnSocketError = null; - } - finally - { - GC.SuppressFinalize(this); - } - } - - private async Task CleanupAsync() - { - IsConnected = false; - await CancelAndWaitAsync(); - - if (_pingTask != null) - { - await Task.WhenAny(_pingTask, Task.Delay(3000)); - } - - if (_pongTask != null) - { - await Task.WhenAny(_pongTask, Task.Delay(3000)); - } - - if (_idleMonitorTask != null) - { - await Task.WhenAny(_idleMonitorTask, Task.Delay(3000)); - } - - _pingTask?.Dispose(); - _pongTask?.Dispose(); - _idleMonitorTask?.Dispose(); - _receiveTask?.Dispose(); - - _pingTask = null; - _pongTask = null; - _idleMonitorTask = null; - _receiveTask = null; - - _tcpClient?.Close(); - _tcpClient?.Dispose(); - _tcpClient = null; - - _udpClient?.Close(); - _udpClient?.Dispose(); - _udpClient = null; - - _stream?.Close(); - _stream?.Dispose(); - _stream = null; - - _utf8Decoder.Reset(); - _aesEncryption?.Dispose(); - _aesEncryption = null; - - _stopAutoReconnecting = false; - } - - public string IpAddress => _config != null ? _config.Host : string.Empty; - public int Port => _config != null ? _config.Port : 0; - public string Nickname { get; private set; } - public bool DEBUG_DATA_SEND { get; set; } - public bool DEBUG_DATA_RECEIVED { get; set; } - public DateTime LastPongReceived { get; private set; } - public DateTime LastPingSent { get; private set; } - public bool DisconnectOnMissedPong { get; set; } - public DateTime LastDataSent { get; private set; } - public DateTime LastDataReceived { get; private set; } - public DateTime DisconnectionTime { get; private set; } - public bool IsAutoConnectStarted { get; private set; } - public bool IsIdleTimeoutTriggered { get; private set; } - - private DateTime _lastIdleLogUtc; - private CancellationTokenSource _autoReconnectSource; - - public bool EnableKeepAlive { get; set; } = true; - - /// - /// Determines after how many seconds of idleness a reminder log is shown. - /// - public double ShowIdleReminderInSeconds { get; set; } = 20; - - /// - /// Occurs when a client has been idle for longer than the configured timeout period. - /// - /// Subscribers can use this event to perform actions such as disconnecting or notifying - /// idle clients. The event is raised with an instance containing details - /// about the idle client. - public event EventHandler OnIdleTimeout; - - private async Task ConnectUdpAsync() - { - try - { - DebugConnection($"Attempting UDP connection to {_config.Host}:{_config.Port}"); - - _udpClient = new UdpClient(); - _udpClient.Client.ReceiveBufferSize = _config.BufferSize; - _udpClient.Client.SendBufferSize = _config.BufferSize; - - try - { - _udpClient.Connect(_config.Host, _config.Port); - } - catch (SocketException socketEx) - { - var errorMsg = $"UDP connection failed: {socketEx.SocketErrorCode} - {socketEx.SocketErrorCode switch { SocketError.ConnectionRefused => "Connection refused - server not listening", SocketError.HostUnreachable => "Host unreachable", SocketError.NetworkUnreachable => "Network unreachable", _ => "Unknown socket error" }}"; - DebugConnection($"UDP connection socket error: {socketEx.SocketErrorCode} - {socketEx.Message}"); - RecordError(socketEx, errorMsg); - OnGeneralError?.Invoke(this, new ErrorEventArgs { Exception = socketEx, Message = errorMsg }); - - try { _udpClient?.Close(); _udpClient?.Dispose(); } catch { } - _udpClient = null; - return false; - } - catch (Exception ex) - { - var errorMsg = $"UDP connection error: {ex.GetType().Name} - {ex.Message}"; - DebugConnection($"UDP connection failed: {ex.GetType().Name} - {ex.Message}"); - RecordError(ex, errorMsg); - OnGeneralError?.Invoke(this, new ErrorEventArgs { Exception = ex, Message = errorMsg }); - - try { _udpClient?.Close(); _udpClient?.Dispose(); } catch { } - _udpClient = null; - return false; - } - - ConnectionTime = DateTime.UtcNow; - LastPongReceived = DateTime.UtcNow; - UpdateLastActive(); - - DebugConnection($"UDP connection established to {_config.Host}:{_config.Port}"); - - _ = Task.Run(() => ReceiveUdpDataAsync(), _connectionCts.Token); - - if (_config.EnableHeartbeat) - { - _pingTask = Task.Run(() => StartPingLoopAsync(_connectionCts.Token)); - _pongTask = Task.Run(() => StartPongLoop(_connectionCts.Token)); - } - - if (_config.IdleTimeoutSeconds > 0) - { - _idleMonitorTask = Task.Run(() => MonitorIdleTimeoutAsync(_connectionCts.Token)); - } - - IsConnected = true; - OnConnected?.Invoke(this, new ConnectionEventArgs { ClientId = "self", RemoteEndPoint = new IPEndPoint(IPAddress.Parse(_config.Host), _config.Port) }); - return true; - } - catch (Exception exception) - { - DebugConnection($"Unexpected error during UDP connection: {exception.GetType().Name} - {exception.Message}"); - RecordError(exception, $"UDP connection error: {exception.GetType().Name} - {exception.Message}"); - OnGeneralError?.Invoke(this, new ErrorEventArgs { Exception = exception, Message = $"UDP connection error: {exception.GetType().Name}" }); - - try { _udpClient?.Close(); _udpClient?.Dispose(); } catch { } - _udpClient = null; - return false; - } - } - - private async Task StartPingLoopAsync(CancellationToken token) - { - var interval = TimeSpan.FromSeconds(_config.HeartbeatIntervalSeconds); - var next = DateTime.UtcNow + interval; - - try - { - while (!token.IsCancellationRequested && IsConnected) - { - try - { - if (_stream == null || !_stream.CanWrite) - { - DebugConnection("Ping loop stopping - stream not available for writing"); - break; - } - - var result = await SendInternalAsync(PingBytes, token).ConfigureAwait(false); - - if (result) - { - LastPingSent = DateTime.UtcNow; - if (_config.EnablePingPongLogs) - { - OnLog?.Invoke(this, $"[PING] Sent at {DateTime.UtcNow:O}"); - } - } - else - { - DebugConnection("Ping loop failed to send ping - will retry on next interval"); - } - - var delay = next - DateTime.UtcNow; - if (delay > TimeSpan.Zero) - { - await Task.Delay(delay, token).ConfigureAwait(false); - } - - next += interval; - } - catch (OperationCanceledException) - { - DebugConnection($"Ping loop: Operation canceled for {_config.Host}:{_config.Port}"); - break; - } - catch (Exception exception) - { - DebugConnection($"Ping loop: Error sending ping to {_config.Host}:{_config.Port}: {exception.GetType().Name} - {exception.Message}"); - RecordError(exception, $"Ping loop error: {exception.GetType().Name} - {exception.Message}"); - OnLog?.Invoke(this, $"[PING] Error sending ping: {exception.GetType().Name} - {exception.Message}"); - break; - } - } - } - catch (Exception ex) - { - DebugConnection($"Ping loop: Unexpected error: {ex.GetType().Name} - {ex.Message}"); - RecordError(ex, $"Ping loop unexpected error: {ex.GetType().Name}"); - } - finally - { - DebugConnection("Ping loop stopped."); - } - } - - private async Task StartPongLoop(CancellationToken token) - { - var interval = TimeSpan.FromSeconds(1); - var next = DateTime.UtcNow + interval; - - try - { - while (!token.IsCancellationRequested) - { - try - { - if (!IsConnected) - { - DebugConnection("Pong loop stopping - client disconnected"); - break; - } - - var elapsed = (DateTime.UtcNow - LastPongReceived).TotalSeconds; - - if (LastPongReceived != DateTime.MinValue && - elapsed > _config.HeartbeatIntervalSeconds * 5) - { - if (DisconnectOnMissedPong) - { - var msg = $"No PONG received for {elapsed:F1}s (threshold: {_config.HeartbeatIntervalSeconds * 5}s) - disconnecting due to unresponsive server"; - DebugConnection($"Pong monitor: {msg}"); - RecordError(null, msg); - await DisconnectClientAsync(DisconnectReason.NoPongReceived); - break; - } - } - - var delay = next - DateTime.UtcNow; - if (delay > TimeSpan.Zero) - { - await Task.Delay(delay, token); - } - - next += interval; - } - catch (OperationCanceledException) - { - DebugConnection($"Pong loop: Operation canceled for {_config.Host}:{_config.Port}"); - break; - } - catch (Exception ex) - { - DebugConnection($"Pong loop: Error monitoring pong for {_config.Host}:{_config.Port}: {ex.GetType().Name} - {ex.Message}"); - RecordError(ex, $"Pong loop error: {ex.GetType().Name} - {ex.Message}"); - await DisconnectClientAsync(DisconnectReason.Error, ex); - break; - } - } - } - catch (Exception ex) - { - DebugConnection($"Pong loop: Unexpected error: {ex.GetType().Name} - {ex.Message}"); - RecordError(ex, $"Pong loop unexpected error: {ex.GetType().Name}"); - } - finally - { - DebugConnection("Pong loop stopped."); - } - } - - private async Task MonitorIdleTimeoutAsync(CancellationToken token) - { - var checkInterval = TimeSpan.FromSeconds(1); - - while (!token.IsCancellationRequested && IsConnected) - { - try - { - var idleTime = IdleTime(); - var idleSeconds = idleTime.TotalSeconds; - - // Check if idle timeout threshold is exceeded - if (_config.IdleTimeoutSeconds > 0 && idleSeconds >= _config.IdleTimeoutSeconds) - { - if (!IsIdleTimeoutTriggered) - { - IsIdleTimeoutTriggered = true; - - DebugConnection($"Idle timeout triggered: {idleSeconds:F1}s >= {_config.IdleTimeoutSeconds}s"); - - OnIdleTimeout?.Invoke(this, new IdleClientEventArgs( - _config.IdleTimeoutSeconds, - this, - $"Client idle for {IdleTimeFormatted(includeMilliseconds: false)}" - )); - } - } - - // Show idle reminder log if configured - if (ShowIdleReminderInSeconds > 0 && idleSeconds >= ShowIdleReminderInSeconds) - { - var now = DateTime.UtcNow; - if ((now - _lastIdleLogUtc).TotalSeconds >= ShowIdleReminderInSeconds) - { - _lastIdleLogUtc = now; - DebugConnection($"Client idle for {IdleTimeFormatted(includeMilliseconds: false)}"); - } - } - - await Task.Delay(checkInterval, token).ConfigureAwait(false); - } - catch (OperationCanceledException) - { - DebugConnection($"MonitorIdleTimeoutAsync: Operation canceled for {_config.Host}:{_config.Port}"); - break; - } - catch (Exception ex) - { - DebugConnection($"MonitorIdleTimeoutAsync: Error monitoring idle timeout for {_config.Host}:{_config.Port}: {ex.Message}"); - OnLog?.Invoke(this, $"[IDLE] Error monitoring idle timeout: {ex.Message}"); - break; - } - } - } - - private async Task ReceiveDataAsync(CancellationToken token) - { - DebugConnection($"ReceiveDataAsync started for {_config.Host}:{_config.Port} with framing mode {_config.MessageFraming}"); - - try - { - switch (_config.MessageFraming) - { - case FramingMode.LengthPrefixed: - await ReceiveLengthPrefixedAsync(token); - break; - - case FramingMode.Delimiter: - await ReceiveDelimiterAsync(token); - break; - - case FramingMode.None: - await ReceiveNoneAsync(token); - break; - } - } - catch (OperationCanceledException ex) - { - DebugConnection("Receive loop cancelled by cancellation token."); - RecordError(ex, "Receive loop cancellation requested"); - } - catch (SocketException socketEx) - { - var errorMsg = $"Socket error in receive loop: {socketEx.SocketErrorCode} - {socketEx.SocketErrorCode switch { SocketError.ConnectionReset => "Connection reset by remote", SocketError.ConnectionAborted => "Connection aborted", SocketError.TimedOut => "Receive timeout", _ => "Unknown socket error" }}"; - RecordError(socketEx, errorMsg); - DebugConnection($"Receive loop socket error: {socketEx.SocketErrorCode} - {socketEx.Message}"); - var reason = socketEx.SocketErrorCode == SocketError.ConnectionReset || socketEx.SocketErrorCode == SocketError.ConnectionAborted - ? DisconnectReason.RemoteClosed - : DisconnectReason.Error; - await DisconnectClientAsync(reason, socketEx); - } - catch (IOException ioEx) when (ioEx.InnerException is SocketException innerSocketEx) - { - var errorMsg = $"Socket IO error in receive loop: {innerSocketEx.SocketErrorCode} - {innerSocketEx.SocketErrorCode switch { SocketError.ConnectionReset => "Connection reset", SocketError.ConnectionAborted => "Connection aborted", _ => "Unknown socket error" }}"; - RecordError(ioEx, errorMsg); - DebugConnection($"Receive loop socket IO error: {innerSocketEx.SocketErrorCode} - {ioEx.Message}"); - var reason = innerSocketEx.SocketErrorCode == SocketError.ConnectionReset - || innerSocketEx.SocketErrorCode == SocketError.ConnectionAborted - ? DisconnectReason.RemoteClosed - : DisconnectReason.Error; - await DisconnectClientAsync(reason, ioEx); - } - catch (IOException ioEx) - { - DebugConnection($"IO error in receive loop: {ioEx.GetType().Name} - {ioEx.Message}"); - RecordError(ioEx, $"IO error in receive loop: {ioEx.GetType().Name}"); - await DisconnectClientAsync(DisconnectReason.Error, ioEx); - } - catch (Exception ex) - { - DebugConnection($"Unexpected error in receive loop: {ex.GetType().Name} - {ex.Message}"); - RecordError(ex, $"Receive loop error: {ex.GetType().Name} - {ex.Message}"); - await DisconnectClientAsync(DisconnectReason.Error, ex); - } - finally - { - DebugConnection("Receive loop exited."); - } - } - - private async Task ReceiveLengthPrefixedAsync(CancellationToken token) - { - int prefixSize = _config.LengthPrefixedLength; - - if (prefixSize < 1 || prefixSize > 8) - { - throw new InvalidOperationException("LengthPrefixedLength must be between 1 and 8."); - } - - byte[] lengthBuffer = ArrayPool.Shared.Rent(prefixSize); - - try - { - while (!token.IsCancellationRequested && IsConnected && _stream?.CanRead == true) - { - await ReadExactAsync(_stream, lengthBuffer, 0, prefixSize).ConfigureAwait(false); - - long length = ParseLengthPrefix(lengthBuffer, prefixSize, _config.UseBigEndian); - - // Security: Validate length prefix using SecurityValidator - if (!Helpers.SecurityValidator.ValidateLengthPrefix(length, _config.MAX_MESSAGE_SIZE)) - { - throw new InvalidOperationException($"Invalid message length {length}. Expected value between 1 and {_config.MAX_MESSAGE_SIZE}."); - } - - byte[] buffer = ArrayPool.Shared.Rent((int)length); - - try - { - await ReadExactAsync(_stream, buffer, 0, (int)length).ConfigureAwait(false); - - if (_config.UseAesEncryption && _aesEncryption != null) - { - var decrypted = await AesKeyExchange.DecryptDataAsync(buffer.AsSpan(0, (int)length).ToArray(), (int)length, _aesEncryption).ConfigureAwait(false); - await ProcessReceivedDataAsync(decrypted).ConfigureAwait(false); - } - else - { - await ProcessReceivedDataAsync(buffer.AsMemory(0, (int)length)).ConfigureAwait(false); - } - - UpdateLastActive(); - } - finally - { - ArrayPool.Shared.Return(buffer); - } - } - } - catch (OperationCanceledException ex) - { - DebugConnection($"Length-prefixed read timeout: {ex.Message}"); - RecordError(ex, "Read timeout during length-prefixed receive - stream may have hung"); - await DisconnectClientAsync(DisconnectReason.Timeout, ex); - } - catch (InvalidOperationException invOpEx) when (invOpEx.Message.Contains("Invalid message length")) - { - // Malformed message length - security issue - DebugConnection($"Malformed message length detected: {invOpEx.Message}"); - RecordError(invOpEx, $"Malformed message length: {invOpEx.Message}"); - await DisconnectClientAsync(DisconnectReason.Error, invOpEx); - } - catch (SocketException socketEx) - { - DebugConnection($"Socket error in length-prefixed receive: {socketEx.SocketErrorCode} - {socketEx.Message}"); - RecordError(socketEx, $"Socket error in length-prefixed receive: {socketEx.SocketErrorCode} - {socketEx.SocketErrorCode switch { SocketError.ConnectionReset => "Connection reset by remote", SocketError.ConnectionAborted => "Connection aborted", _ => "Unknown socket error" }}"); - - var reason = socketEx.SocketErrorCode == SocketError.ConnectionReset || socketEx.SocketErrorCode == SocketError.ConnectionAborted - ? DisconnectReason.RemoteClosed - : DisconnectReason.Error; - await DisconnectClientAsync(reason, socketEx); - } - catch (IOException ex) when (ex.InnerException is SocketException innerSocketEx) - { - DebugConnection($"Socket IO error in length-prefixed receive: {innerSocketEx.SocketErrorCode} - {ex.Message}"); - RecordError(ex, $"Socket IO error in length-prefixed receive: {innerSocketEx.SocketErrorCode} - {innerSocketEx.SocketErrorCode switch { SocketError.ConnectionReset => "Connection reset", SocketError.ConnectionAborted => "Connection aborted", _ => "Unknown socket error" }}"); - var reason = innerSocketEx.SocketErrorCode == SocketError.ConnectionReset - || innerSocketEx.SocketErrorCode == SocketError.ConnectionAborted - ? DisconnectReason.RemoteClosed - : DisconnectReason.Error; - await DisconnectClientAsync(reason, ex); - } - catch (IOException ex) - { - DebugConnection($"Connection closed during length-prefixed receive: {ex.GetType().Name} - {ex.Message}"); - RecordError(ex, "Connection closed during length-prefixed receive"); - await DisconnectClientAsync(DisconnectReason.RemoteClosed, ex); - } - catch (Exception ex) - { - DebugConnection($"Unexpected error in length-prefixed receive: {ex.GetType().Name} - {ex.Message}"); - RecordError(ex, $"Unexpected error in length-prefixed receive: {ex.GetType().Name} - {ex.Message}"); - await DisconnectClientAsync(DisconnectReason.Error, ex); - } - finally - { - ArrayPool.Shared.Return(lengthBuffer); - } - } - - private static long ParseLengthPrefix(byte[] buffer, int length, bool useBigEndian) - { - long value = 0; - - if (useBigEndian) - { - for (int i = 0; i < length; i++) - { - value = (value << 8) | buffer[i]; - } - } - else - { - for (int i = 0; i < length; i++) - { - value |= (long)buffer[i] << (8 * i); - } - } - - return value; - } - - private async Task ReceiveNoneAsync(CancellationToken token) - { - byte[] buffer = ArrayPool.Shared.Rent(_config.BufferSize); - - try - { - while (!token.IsCancellationRequested && IsConnected && _stream?.CanRead == true) - { - using var cts = CancellationTokenSource.CreateLinkedTokenSource(token); - cts.CancelAfter(TimeSpan.FromSeconds(_config.ReadTimeoutSeconds)); - - int read = await _stream.ReadAsync(buffer, 0, buffer.Length, cts.Token); - - if (read == 0) - { - DebugConnection("Remote closed connection."); - await DisconnectClientAsync(DisconnectReason.RemoteClosed); - return; - } - - ReadOnlyMemory payload = buffer.AsMemory(0, read); - - if (_config.UseAesEncryption && _aesEncryption != null) - { - try - { - var decrypted = await AesKeyExchange.DecryptDataAsync(payload.ToArray(), read, _aesEncryption); - await ProcessReceivedDataAsync(decrypted); - } - catch (Exception ex) - { - DebugConnection($"Decrypt error: {ex.Message}"); - OnEncryptionError?.Invoke(this, new ErrorEventArgs - { - Exception = ex, - Message = "Error decrypting data" - }); - } - } - else - { - await ProcessReceivedDataAsync(payload); - } - - UpdateLastActive(); - } - } - catch (OperationCanceledException ex) - { - DebugConnection($"Read timeout during raw receive: {ex.Message}"); - RecordError(ex, "Read timeout in raw receive - stream may be unresponsive"); - await DisconnectClientAsync(DisconnectReason.Timeout, ex); - } - catch (SocketException socketEx) - { - DebugConnection($"Socket error in raw receive: {socketEx.SocketErrorCode} - {socketEx.Message}"); - var errorMsg = $"Socket error in raw receive: {socketEx.SocketErrorCode} - {socketEx.SocketErrorCode switch { SocketError.ConnectionReset => "Connection reset", SocketError.ConnectionAborted => "Connection aborted", _ => "Unknown socket error" }}"; - RecordError(socketEx, errorMsg); - var reason = socketEx.SocketErrorCode == SocketError.ConnectionReset || socketEx.SocketErrorCode == SocketError.ConnectionAborted - ? DisconnectReason.RemoteClosed - : DisconnectReason.Error; - await DisconnectClientAsync(reason, socketEx); - } - catch (IOException ex) when (ex.InnerException is SocketException innerSocketEx) - { - DebugConnection($"Socket IO error in raw receive: {innerSocketEx.SocketErrorCode} - {ex.Message}"); - var errorMsg = $"Socket IO error in raw receive: {innerSocketEx.SocketErrorCode} - {innerSocketEx.SocketErrorCode switch { SocketError.ConnectionReset => "Connection reset", SocketError.ConnectionAborted => "Connection aborted", _ => "Unknown socket error" }}"; - RecordError(ex, errorMsg); - var reason = innerSocketEx.SocketErrorCode == SocketError.ConnectionReset - || innerSocketEx.SocketErrorCode == SocketError.ConnectionAborted - ? DisconnectReason.RemoteClosed - : DisconnectReason.Error; - await DisconnectClientAsync(reason, ex); - } - catch (IOException ex) - { - DebugConnection($"Connection closed during raw receive: {ex.GetType().Name} - {ex.Message}"); - RecordError(ex, "Connection closed during raw receive"); - await DisconnectClientAsync(DisconnectReason.RemoteClosed, ex); - } - catch (Exception ex) - { - DebugConnection($"Unexpected error in raw receive: {ex.GetType().Name} - {ex.Message}"); - RecordError(ex, $"Error in raw receive: {ex.GetType().Name} - {ex.Message}"); - await DisconnectClientAsync(DisconnectReason.Error, ex); - } - finally - { - ArrayPool.Shared.Return(buffer); - } - } - - private async Task ReceiveDelimiterAsync(CancellationToken token) - { - byte[] buffer = ArrayPool.Shared.Rent(_config.BufferSize); - var memory = new MemoryStream(); - - try - { - while (!token.IsCancellationRequested && IsConnected && _stream?.CanRead == true) - { - using var cts = CancellationTokenSource.CreateLinkedTokenSource(token); - cts.CancelAfter(TimeSpan.FromSeconds(_config.ReadTimeoutSeconds)); - - int read = await _stream.ReadAsync(buffer, 0, buffer.Length, cts.Token); - - if (read == 0) - { - DebugConnection("Remote closed connection."); - await DisconnectClientAsync(DisconnectReason.RemoteClosed); - return; - } - - memory.Write(buffer, 0, read); - - // Security: Check both individual message size and accumulated stream size - if (memory.Length > _config.MAX_MESSAGE_SIZE) - { - throw new InvalidOperationException($"Message too large: {memory.Length} > {_config.MAX_MESSAGE_SIZE}"); - } - - // Additional security: Enforce max accumulated message stream size - if (_config.MaxMessageStreamSize > 0 && memory.Length > _config.MaxMessageStreamSize) - { - throw new InvalidOperationException($"Message buffer exceeded maximum size of {_config.MaxMessageStreamSize} bytes."); - } - - while (TryExtractMessage(memory, _config.Delimiter, out var message)) - { - if (_config.UseAesEncryption && _aesEncryption != null) - { - message = await AesKeyExchange.DecryptDataAsync(message, message.Length, _aesEncryption); - } - - await ProcessReceivedDataAsync(message); - UpdateLastActive(); - } - } - } - catch (OperationCanceledException ex) - { - DebugConnection($"Read timeout during delimiter receive: {ex.Message}"); - RecordError(ex, "Read timeout in delimiter receive - stream may be unresponsive"); - await DisconnectClientAsync(DisconnectReason.Timeout, ex); - } - catch (InvalidOperationException invOpEx) when (invOpEx.Message.Contains("Message")) - { - // Message size violation - security issue - DebugConnection($"Message size limit violation: {invOpEx.Message}"); - RecordError(invOpEx, $"Message size limit violated: {invOpEx.Message}"); - await DisconnectClientAsync(DisconnectReason.Error, invOpEx); - } - catch (SocketException socketEx) - { - DebugConnection($"Socket error in delimiter receive: {socketEx.SocketErrorCode} - {socketEx.Message}"); - var errorMsg = $"Socket error in delimiter receive: {socketEx.SocketErrorCode} - {socketEx.SocketErrorCode switch { SocketError.ConnectionReset => "Connection reset", SocketError.ConnectionAborted => "Connection aborted", _ => "Unknown socket error" }}"; - RecordError(socketEx, errorMsg); - var reason = socketEx.SocketErrorCode == SocketError.ConnectionReset || socketEx.SocketErrorCode == SocketError.ConnectionAborted - ? DisconnectReason.RemoteClosed - : DisconnectReason.Error; - await DisconnectClientAsync(reason, socketEx); - } - catch (IOException ex) when (ex.InnerException is SocketException innerSocketEx) - { - DebugConnection($"Socket IO error in delimiter receive: {innerSocketEx.SocketErrorCode} - {ex.Message}"); - var errorMsg = $"Socket IO error in delimiter receive: {innerSocketEx.SocketErrorCode} - {innerSocketEx.SocketErrorCode switch { SocketError.ConnectionReset => "Connection reset", SocketError.ConnectionAborted => "Connection aborted", _ => "Unknown socket error" }}"; - RecordError(ex, errorMsg); - var reason = innerSocketEx.SocketErrorCode == SocketError.ConnectionReset - || innerSocketEx.SocketErrorCode == SocketError.ConnectionAborted - ? DisconnectReason.RemoteClosed - : DisconnectReason.Error; - await DisconnectClientAsync(reason, ex); - } - catch (IOException ex) - { - DebugConnection($"Connection closed during delimiter receive: {ex.GetType().Name} - {ex.Message}"); - RecordError(ex, "Connection closed during delimiter receive"); - await DisconnectClientAsync(DisconnectReason.RemoteClosed, ex); - } - catch (Exception ex) - { - DebugConnection($"Unexpected error in delimiter receive: {ex.GetType().Name} - {ex.Message}"); - RecordError(ex, $"Error in delimiter receive: {ex.GetType().Name} - {ex.Message}"); - await DisconnectClientAsync(DisconnectReason.Error, ex); - } - finally - { - ArrayPool.Shared.Return(buffer); - memory.Dispose(); - } - } - - private static bool TryExtractMessage(MemoryStream stream, byte[] delimiter, out byte[] message) - { - var buffer = stream.GetBuffer(); - int length = (int)stream.Length; - - int index = IndexOfDelimiter(buffer, length, delimiter); - - if (index < 0) - { - message = null; - return false; - } - - message = new byte[index]; - Buffer.BlockCopy(buffer, 0, message, 0, index); - - int remaining = length - index - delimiter.Length; - - Buffer.BlockCopy(buffer, index + delimiter.Length, buffer, 0, remaining); - stream.SetLength(remaining); - stream.Position = remaining; - - return true; - } - - private static int IndexOfDelimiter(byte[] buffer, int length, byte[] delimiter) - { - if (delimiter == null || delimiter.Length == 0 || length < delimiter.Length) - { - return -1; - } - - for (int i = 0; i <= length - delimiter.Length; i++) - { - bool match = true; - - for (int j = 0; j < delimiter.Length; j++) - { - if (buffer[i + j] != delimiter[j]) - { - match = false; - break; - } - } - - if (match) - { - return i; - } - } - - return -1; - } - - public async Task SendAsync(byte[] data) - { - try - { - byte[] payload = data; - - if (_config.UseAesEncryption && _aesEncryption != null) - { - payload = await AesKeyExchange.EncryptDataAsync(data, data.Length, _aesEncryption); - } - - byte[] framed = Frame(payload); - - return await SendInternalAsync(framed, _connectionCts?.Token ?? CancellationToken.None).ConfigureAwait(false); - } - catch (Exception ex) - { - await DisconnectClientAsync(DisconnectReason.Error, ex); - return false; - } - } - - private byte[] Frame(byte[] payload) - { - switch (_config.MessageFraming) - { - case FramingMode.LengthPrefixed: - return CreateLengthPrefixed(payload); - - case FramingMode.Delimiter: - return Combine(payload, _config.Delimiter); - - case FramingMode.None: - default: - return payload; - } - } - - private static byte[] Combine(byte[] payload, byte[] delimiter) - { - if (delimiter == null || delimiter.Length == 0) - { - return payload; - } - - var result = new byte[payload.Length + delimiter.Length]; - - Buffer.BlockCopy(payload, 0, result, 0, payload.Length); - Buffer.BlockCopy(delimiter, 0, result, payload.Length, delimiter.Length); - - return result; - } - - private byte[] CreateLengthPrefixed(byte[] payload) - { - int prefixSize = _config.LengthPrefixedLength; - - if (prefixSize < 1 || prefixSize > 8) - { - throw new InvalidOperationException("LengthPrefixedLength must be between 1 and 8 bytes."); - } - - long length = payload.Length; - - // Validate that the payload fits into the configured prefix size - long maxValue = (1L << (prefixSize * 8)) - 1; - if (length > maxValue) - { - throw new InvalidOperationException( - $"Payload too large for {prefixSize}-byte length prefix."); - } - - byte[] result = new byte[prefixSize + payload.Length]; - - if (_config.UseBigEndian) - { - for (int i = 0; i < prefixSize; i++) - { - result[prefixSize - 1 - i] = (byte)(length & 0xFF); - length >>= 8; - } - } - else - { - for (int i = 0; i < prefixSize; i++) - { - result[i] = (byte)(length & 0xFF); - length >>= 8; - } - } - - Buffer.BlockCopy(payload, 0, result, prefixSize, payload.Length); - - return result; - } - - private static async Task ReadExactAsync(Stream stream, byte[] buffer, int offset, int count) - { - int totalRead = 0; - - while (totalRead < count) - { - int read = await stream.ReadAsync(buffer, offset + totalRead, count - totalRead).ConfigureAwait(false); - - if (read == 0) - { - throw new IOException("Remote socket closed while reading."); - } - - totalRead += read; - } - } - - private async Task ProcessReceivedDataAsync(ReadOnlyMemory data) - { - if (data.IsEmpty) - { - return; - } - - var now = DateTime.UtcNow; - LastDataReceived = now; - Interlocked.Add(ref _bytesReceived, data.Length); - Interlocked.Increment(ref _messagesReceived); - UpdateLastActive(); - - bool needsText = _config.EnableHeartbeat || OnDataReceived != null; - - string stringData = null; - bool isText = false; - - if (needsText) - { - try - { -#if NET8_0_OR_GREATER - var span = data.Span; - int charCount = Encoding.UTF8.GetCharCount(span); - - if (_charBuffer.Length < charCount) - { - _charBuffer = new char[charCount]; - } - - int written = Encoding.UTF8.GetChars(span, _charBuffer); -#else - byte[] bytes = data.ToArray(); - int charCount = _utf8Decoder.GetCharCount(bytes, 0, bytes.Length); - - if (_charBuffer.Length < charCount) - { - _charBuffer = new char[charCount]; - } - - int written = _utf8Decoder.GetChars(bytes, 0, bytes.Length, _charBuffer, 0); -#endif - if (written > 0) - { - stringData = new string(_charBuffer, 0, written); - isText = true; - } - } - catch - { - isText = false; - } - } - - // Heartbeat - if (_config.EnableHeartbeat && isText) - { - ProcessPingPong(ref stringData); - - if (string.IsNullOrEmpty(stringData)) - { - return; - } - } - - // SSL error notification from server - if (isText && !string.IsNullOrEmpty(stringData) && stringData.Contains(Configuration.SSL_ERROR_PREFIX, StringComparison.OrdinalIgnoreCase)) - { - string sslError = null; - var startIdx = stringData.IndexOf(Configuration.SSL_ERROR_PREFIX, StringComparison.Ordinal) + Configuration.SSL_ERROR_PREFIX.Length; - var endIdx = stringData.IndexOf(Configuration.SSL_ERROR_SUFFIX, StringComparison.Ordinal); - if (endIdx > startIdx) - { - sslError = stringData.Substring(startIdx, endIdx - startIdx); - } - RecordError(null, $"Server reported SSL error: {sslError ?? stringData}", isSslError: true); - OnSslError?.Invoke(this, new ErrorEventArgs - { - Message = $"Server reported SSL error: {sslError ?? stringData}" - }); - await DisconnectClientAsync(DisconnectReason.SSLError).ConfigureAwait(false); - return; - } - - if (DEBUG_DATA_RECEIVED) - { - OnLog?.Invoke(this, $"[DEBUG DATA] Received {data.Length} bytes"); - } - - OnDataReceived?.Invoke(this, new DataReceivedEventArgs - { - ClientId = "server", - Data = data.ToArray(), - IsBinary = !isText, - Timestamp = DateTime.UtcNow, - RemoteEndPoint = new IPEndPoint(IPAddress.Parse(_config.Host), _config.Port), - Nickname = Nickname, - }); - } - - private void ProcessPingPong(ref string message) - { - if (!_config.EnableHeartbeat || string.IsNullOrEmpty(message)) - { - return; - } - - if (message.Contains(Configuration.PING_VALUE)) - { - LastPingSent = DateTime.UtcNow; - if (_config.EnablePingPongLogs) - { - OnLog?.Invoke(this, "Received PING from server. Sending PONG response."); - } - - OnPingResponse?.Invoke(this, new PingEventArgs - { - Id = "server", - Nickname = Nickname, - ReceivedTime = DateTime.UtcNow, - RemoteEndPoint = new IPEndPoint(IPAddress.Parse(_config.Host), _config.Port) - }); - _ = SendAsync(Configuration.PONG_VALUE).ConfigureAwait(false); - message = message.Replace(Configuration.PING_VALUE, string.Empty); - } - - if (message.Contains(Configuration.PONG_VALUE)) - { - LastPongReceived = DateTime.UtcNow; - if (_config.EnablePingPongLogs) - { - OnLog?.Invoke(this, "Received PONG from server for PING"); - } - OnPongResponse?.Invoke(this, new PingEventArgs - { - Id = "server", - Nickname = Nickname, - ReceivedTime = DateTime.UtcNow, - RemoteEndPoint = new IPEndPoint(IPAddress.Parse(_config.Host), _config.Port) - }); - message = message.Replace(Configuration.PONG_VALUE, string.Empty); - } - } - - private async Task ReceiveUdpDataAsync() - { - DebugConnection($"UDP receive loop started for {_config.Host}:{_config.Port}"); - - while (_connectionCts != null && !_connectionCts.Token.IsCancellationRequested && IsConnected) - { - try - { - var result = await _udpClient.ReceiveAsync().ConfigureAwait(false); - var buffer = result.Buffer; - - if (_config.EnableHeartbeat) - { - try - { - buffer = HandleHeartbeat(buffer, out bool foundHeartbeat); - if (foundHeartbeat) - { - LastPongReceived = DateTime.UtcNow; - if (_config.EnablePingPongLogs) - { - OnLog?.Invoke(this, "Received PONG from server for PING (UDP)"); - } - } - if (buffer == null || buffer.Length == 0) - { - continue; - } - } - catch (Exception exception) - { - DebugConnection($"Heartbeat handling error in UDP: {exception.GetType().Name} - {exception.Message}"); - RecordError(exception, $"Heartbeat handling failed (UDP): {exception.GetType().Name} - {exception.Message}"); - OnGeneralError?.Invoke(this, new ErrorEventArgs { Exception = exception, Message = "Heartbeat handling failed (UDP)" }); - } - } - - UpdateLastActive(); - await ProcessReceivedDataAsync(buffer).ConfigureAwait(false); - } - catch (SocketException socketEx) - { - var errorMsg = $"Socket error in UDP receive: {socketEx.SocketErrorCode} - {socketEx.SocketErrorCode switch { SocketError.ConnectionReset => "Connection reset", SocketError.HostUnreachable => "Host unreachable", _ => "Unknown socket error" }}"; - DebugConnection($"UDP receive socket error: {socketEx.SocketErrorCode} - {socketEx.Message}"); - RecordError(socketEx, errorMsg); - OnGeneralError?.Invoke(this, new ErrorEventArgs { Exception = socketEx, Message = errorMsg }); - ConnectionTime = DateTime.MinValue; - break; - } - catch (ObjectDisposedException ex) - { - DebugConnection("UDP receive loop: UDP client disposed, stopping receive loop."); - RecordError(ex, "UDP client disposed - connection closing"); - break; - } - catch (OperationCanceledException) - { - DebugConnection("UDP receive loop: Operation canceled."); - break; - } - catch (Exception exception) - { - DebugConnection($"UDP receive error: {exception.GetType().Name} - {exception.Message}"); - RecordError(exception, $"Error receiving UDP data: {exception.GetType().Name} - {exception.Message}"); - OnGeneralError?.Invoke(this, new ErrorEventArgs { Exception = exception, Message = $"UDP receive error: {exception.GetType().Name}" }); - ConnectionTime = DateTime.MinValue; - break; - } - } - - DebugConnection("UDP receive loop stopped."); - } - - public async Task SendNicknameAsync(string nickname) - { - if (string.IsNullOrWhiteSpace(nickname)) - { - return false; - } - - var result = await SendAsync($"[NICKNAME]{nickname}[/NICKNAME]").ConfigureAwait(false); - if (result) - { - Nickname = nickname.Trim(); - OnNicknameSend?.Invoke(this, new ConnectionEventArgs - { - ClientId = nickname, - RemoteEndPoint = new IPEndPoint(IPAddress.Parse(_config.Host), _config.Port), - Nickname = nickname - }); - } - return result; - } - - public async Task SendAsync(string message) => await SendAsync(Encoding.UTF8.GetBytes(message)).ConfigureAwait(false); - - public async Task SendAndWaitForResponseAsync(byte[] data, TimeSpan? timeout = null) - { - var tcs = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously); - var effectiveTimeout = timeout ?? TimeSpan.FromSeconds(DEFAULT_WAITING_TIMEOUT_IN_SECONDS); - - void Handler(object sender, DataReceivedEventArgs e) - { - tcs.TrySetResult(e); - } - - OnDataReceived += Handler; - try - { - var sent = await SendAsync(data).ConfigureAwait(false); - if (!sent) - { - return null; - } - - using var cts = new CancellationTokenSource(effectiveTimeout); - using var registration = cts.Token.Register(() => tcs.TrySetCanceled()); - - try - { - return await tcs.Task.ConfigureAwait(false); - } - catch (OperationCanceledException) - { - return null; - } - } - finally - { - OnDataReceived -= Handler; - } - } - - public async Task SendAndWaitForResponseAsync(string message, TimeSpan? timeout = null) - => await SendAndWaitForResponseAsync(Encoding.UTF8.GetBytes(message), timeout).ConfigureAwait(false); - - public async Task SendNicknameAndWaitForResponseAsync(string nickname, TimeSpan? timeout = null) - { - var tcs = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously); - var effectiveTimeout = timeout ?? TimeSpan.FromSeconds(DEFAULT_WAITING_TIMEOUT_IN_SECONDS); - - void Handler(object sender, DataReceivedEventArgs e) - { - tcs.TrySetResult(e); - } - - OnDataReceived += Handler; - try - { - var sent = await SendNicknameAsync(nickname).ConfigureAwait(false); - if (!sent) - { - return null; - } - - using var cts = new CancellationTokenSource(effectiveTimeout); - using var registration = cts.Token.Register(() => tcs.TrySetCanceled()); - - try - { - return await tcs.Task.ConfigureAwait(false); - } - catch (OperationCanceledException) - { - return null; - } - } - finally - { - OnDataReceived -= Handler; - } - } - - private async Task SendInternalAsync(byte[] data, CancellationToken token) - { - if (!IsConnected) - { - return false; - } - - if (_config.Protocol == ProtocolType.TCP) - { - if (_stream == null || !_stream.CanWrite) - { - DebugConnection($"SendInternalAsync: Stream is not available for writing for {_config.Host}:{_config.Port}, disconnecting"); - await DisconnectClientAsync(DisconnectReason.RemoteClosed).ConfigureAwait(false); - return false; - } - - try - { - using var cts = CancellationTokenSource.CreateLinkedTokenSource(token); - cts.CancelAfter(TimeSpan.FromSeconds(_config.WriteTimeoutSeconds)); - - await _streamWriteLock.WaitAsync(cts.Token).ConfigureAwait(false); - try - { - await _stream.WriteAsync(data, 0, data.Length, cts.Token).ConfigureAwait(false); - await _stream.FlushAsync(cts.Token).ConfigureAwait(false); - - LastDataSent = DateTime.UtcNow; - Interlocked.Add(ref _bytesSent, data.Length); - Interlocked.Increment(ref _messagesSent); - UpdateLastActive(); - return true; - } - finally - { - _streamWriteLock.Release(); - } - } - catch (OperationCanceledException ex) - { - DebugConnection($"SendInternalAsync: Write operation canceled for {_config.Host}:{_config.Port}, likely due to timeout or shutdown: {ex.Message}"); - RecordError(ex, "Write timeout in TCP send - stream may be unresponsive"); - await DisconnectClientAsync(DisconnectReason.Timeout, ex); - return false; - } - catch (SocketException socketEx) - { - DebugConnection($"SendInternalAsync: Socket error while sending TCP data to {_config.Host}:{_config.Port}: {socketEx.SocketErrorCode} - {socketEx.Message}"); - RecordError(socketEx, $"Socket error in TCP send: {socketEx.SocketErrorCode} - {socketEx.SocketErrorCode switch { SocketError.ConnectionReset => "Connection reset by remote host", SocketError.ConnectionAborted => "Connection aborted", SocketError.HostUnreachable => "Host unreachable", SocketError.NetworkUnreachable => "Network unreachable", SocketError.ConnectionRefused => "Connection refused", _ => "Unknown socket error" }}"); - await DisconnectClientAsync(DisconnectReason.Error, socketEx); - return false; - } - catch (IOException ioEx) when (ioEx.InnerException is SocketException innerSocketEx) - { - DebugConnection($"SendInternalAsync: Socket IO error while sending TCP data to {_config.Host}:{_config.Port}: {innerSocketEx.SocketErrorCode} - {ioEx.Message}"); - RecordError(ioEx, $"Socket IO error in TCP send: {innerSocketEx.SocketErrorCode} - {innerSocketEx.SocketErrorCode switch { SocketError.ConnectionReset => "Connection reset by remote host", SocketError.ConnectionAborted => "Connection aborted", _ => "Unknown socket error" }}"); - var reason = innerSocketEx.SocketErrorCode == SocketError.ConnectionReset || innerSocketEx.SocketErrorCode == SocketError.ConnectionAborted ? DisconnectReason.RemoteClosed : DisconnectReason.Error; - await DisconnectClientAsync(reason, ioEx); - return false; - } - catch (ObjectDisposedException ex) - { - DebugConnection($"SendInternalAsync: ObjectDisposedException for {_config.Host}:{_config.Port}, stream was likely disposed during reconnection"); - RecordError(ex, "Stream disposed during TCP send - possible race condition during reconnection attempt"); - if (IsConnected) - { - await DisconnectClientAsync(DisconnectReason.Error, ex).ConfigureAwait(false); - } - return false; - } - catch (Exception ex) - { - DebugConnection($"SendInternalAsync: Exception occurred while sending data to {_config.Host}:{_config.Port}: {ex.GetType().Name} - {ex.Message}"); - RecordError(ex, $"Error in TCP send: {ex.GetType().Name} - {ex.Message}"); - await DisconnectClientAsync(DisconnectReason.Error, ex); - return false; - } - } - else - { - try - { - if (_udpClient != null) - { - await _udpClient.SendAsync(data, data.Length).ConfigureAwait(false); - LastDataSent = DateTime.UtcNow; - Interlocked.Add(ref _bytesSent, data.Length); - Interlocked.Increment(ref _messagesSent); - return true; - } - return false; - } - catch (SocketException socketEx) - { - DebugConnection($"SendInternalAsync: Socket error sending UDP data to {_config.Host}:{_config.Port}: {socketEx.SocketErrorCode} - {socketEx.Message}"); - RecordError(socketEx, $"Socket error in UDP send: {socketEx.SocketErrorCode} - {socketEx.SocketErrorCode switch { SocketError.ConnectionReset => "Connection reset", SocketError.HostUnreachable => "Host unreachable", SocketError.NetworkUnreachable => "Network unreachable", _ => "Unknown socket error" }}"); - return false; - } - catch (Exception ex) - { - DebugConnection($"SendInternalAsync: Error sending UDP data to {_config.Host}:{_config.Port}: {ex.GetType().Name} - {ex.Message}"); - RecordError(ex, $"Error in UDP send: {ex.GetType().Name} - {ex.Message}"); - return false; - } - } - } - - private async Task AutoReconnectAsync(CancellationToken token) - { - IsAutoConnectStarted = true; - int consecutiveFailures = 0; - const int MAX_CONSECUTIVE_FAILURES = 10; - const int MAX_BACKOFF_SECONDS = 300; // 5 minutes max backoff - - try - { - while (!token.IsCancellationRequested) - { - if (!_config.EnableAutoReconnect || - _reason == DisconnectReason.LocalClosed || - !_wasConnected) - { - DebugConnection("Auto-reconnect disabled or not previously connected; stopping auto-reconnect task."); - break; - } - - // Check if the disconnect reason prevents reconnect - if (_reason == DisconnectReason.ClientRequested) - { - // Don't attempt to reconnect if the client explicitly requested disconnection - DebugConnection("Client explicitly requested disconnection; stopping auto-reconnect task."); - _autoReconnectSource?.Cancel(); - break; - } - - if (IsConnected) - { - DebugConnection("Client is already connected; resetting backoff counter."); - consecutiveFailures = 0; - await Task.Delay(1_000, token).ConfigureAwait(false); - continue; - } - - // Try to reconnect with exponential backoff - bool reconnected = await TryReconnectWithRetriesAsync(token).ConfigureAwait(false); - - if (reconnected) - { - consecutiveFailures = 0; - DebugConnection("Reconnection successful; resetting backoff counter."); - } - else - { - consecutiveFailures++; - - if (consecutiveFailures >= MAX_CONSECUTIVE_FAILURES) - { - var criticalMsg = $"Too many consecutive reconnection failures ({consecutiveFailures}); stopping auto-reconnect task to prevent resource exhaustion."; - DebugConnection(criticalMsg); - RecordError(null, criticalMsg); - break; - } - - // Calculate exponential backoff: min 1s, max 5 minutes, doubles each attempt - int backoffSeconds = Math.Min( - (int)Math.Pow(2, Math.Min(consecutiveFailures - 1, 8)), - MAX_BACKOFF_SECONDS - ); - - DebugConnection($"Reconnection failed (attempt {consecutiveFailures}); waiting {backoffSeconds}s before next attempt..."); - - try - { - await Task.Delay(TimeSpan.FromSeconds(backoffSeconds), token).ConfigureAwait(false); - } - catch (OperationCanceledException) - { - break; - } - } - } - } - catch (OperationCanceledException) - { - DebugConnection("Auto-reconnect task canceled."); - } - catch (Exception ex) - { - DebugConnection($"Auto-reconnect task encountered unexpected error: {ex.GetType().Name} - {ex.Message}"); - RecordError(ex, $"Auto-reconnect task failed: {ex.GetType().Name} - {ex.Message}"); - } - finally - { - IsAutoConnectStarted = false; - DebugConnection("Auto-reconnect task stopped."); - } - } - - private async Task TryReconnectWithRetriesAsync(CancellationToken token) - { - int attempt = 0; - var maxAttempts = _config.MaxReconnectAttempts; - - while (!token.IsCancellationRequested && (maxAttempts == 0 || attempt < maxAttempts)) - { - if (IsConnected) - { - return true; - } - - attempt++; - - try - { - DebugConnection($"Attempting to reconnect... Attempt {attempt}/{(maxAttempts == 0 ? "unlimited" : maxAttempts.ToString())}"); - var connected = await ConnectAsync().ConfigureAwait(false); - - if (connected && IsConnected) - { - _reason = DisconnectReason.Unknown; - - var successMsg = $"Reconnected successfully after {attempt} attempt(s)"; - DebugConnection(successMsg); - - OnGeneralError?.Invoke( - this, - new ErrorEventArgs - { - Message = successMsg - }); - - return true; - } - } - catch (OperationCanceledException) - { - DebugConnection($"Reconnection attempt {attempt} canceled."); - throw; - } - catch (Exception ex) - { - var errorMsg = $"Reconnection attempt {attempt} failed: {ex.GetType().Name} - {ex.Message}"; - DebugConnection(errorMsg); - RecordError(ex, errorMsg); - - OnGeneralError?.Invoke( - this, - new ErrorEventArgs - { - Exception = ex, - Message = errorMsg - }); - } - - // Don't delay after the last failed attempt - if (maxAttempts > 0 && attempt >= maxAttempts) - { - DebugConnection($"Maximum reconnection attempts ({maxAttempts}) reached."); - break; - } - - // Brief delay between retry attempts (exponential backoff is handled at higher level) - Int32 retryDelayMs = Math.Min(500 * attempt, 2000); // Max 2s between individual retries - try - { - await Task.Delay(retryDelayMs, token).ConfigureAwait(false); - } - catch (OperationCanceledException) - { - break; - } - } - - return false; - } - - private void DebugConnection(string debugText) - { - if (!_config.EnableConnectionDebugLogs) - { - return; - } - OnLog?.Invoke(this, $"[NetworkClient] {debugText}"); - } - - private void RecordError(Exception exception, string message, string clientId = null, string nickname = null, bool isSslError = false) - { - var socketEx = exception as SocketException - ?? (exception as IOException)?.InnerException as SocketException; - - var entry = new SocketErrorEntry - { - Timestamp = DateTime.UtcNow, - Source = "Client", - ClientId = clientId ?? Nickname ?? "self", - Nickname = nickname ?? Nickname, - SocketErrorCode = socketEx?.SocketErrorCode, - ErrorCode = socketEx != null ? socketEx.SocketErrorCode.ToString() : exception?.GetType().Name, - Message = message, - ExceptionType = exception?.GetType().FullName, - StackTrace = exception?.StackTrace, - Exception = exception, - IsSslError = isSslError - }; - - StatusPage.AddError(entry); - - if (socketEx != null) - { - OnSocketError?.Invoke(this, new ErrorEventArgs - { - ClientId = entry.ClientId, - Nickname = entry.Nickname, - Exception = exception, - Message = $"SocketError {socketEx.SocketErrorCode}: {message}" - }); - } - } - - public async Task DisconnectAsync() => await DisconnectClientAsync(DisconnectReason.ClientRequested).ConfigureAwait(false); - - public async Task DisconnectDueTimeoutAsync() => await DisconnectClientAsync(DisconnectReason.Timeout).ConfigureAwait(false); - - private async Task DisconnectClientAsync( - DisconnectReason reason = DisconnectReason.LocalClosed, - Exception exception = null) - { - DisconnectionTime = DateTime.UtcNow; - IsConnected = false; - _reason = reason; - - if (reason == DisconnectReason.ClientRequested || reason == DisconnectReason.LocalClosed) - { - _autoReconnectSource?.Cancel(); - } - - // Close the actual connection resources - try - { - _connectionCts?.Cancel(); - } - catch - { - // Do nothing - } - - try - { - _connectionCts?.Dispose(); - } - catch - { - // Do nothing - } - _connectionCts = null; - - try - { - _stream?.Close(); - _stream?.Dispose(); - _stream = null; - } - catch - { - // Do nothing - } - - try - { - if (_tcpClient != null) - { - try - { - _tcpClient.Client?.Shutdown(System.Net.Sockets.SocketShutdown.Both); - } - catch - { - // Do nothing - } - - _tcpClient.Close(); - _tcpClient.Dispose(); - _tcpClient = null; - } - } - catch - { - // Do nothing - } - - try - { - _udpClient?.Close(); - _udpClient?.Dispose(); - _udpClient = null; - } - catch - { - // Do nothing - } - - OnDisconnected?.Invoke(this, new ConnectionEventArgs - { - ClientId = "self", - RemoteEndPoint = new IPEndPoint(IPAddress.Parse(_config.Host), _config.Port), - Reason = ConnectionEventArgs.Determine(reason, exception), - Exception = exception - }); - - StatusPage.StopAutoHtmlReport(); - HealthApi.Stop(); - } - - private async Task SafeTaskCompletion(Task task) - { - if (task == null) - { - return; - } - - try - { - await task.ConfigureAwait(false); - } - catch - { - // Do nothing - } - } - - private byte[] HandleHeartbeat(byte[] data, out bool hasHeartbeat) - { - hasHeartbeat = false; - if (!_config.EnableHeartbeat || data == null || data.Length == 0) - { - return data; - } - - string text = null; - - try - { - text = Encoding.UTF8.GetString(data); - } - catch - { - // Not a valid UTF-8 string - } - - if (string.IsNullOrEmpty(text)) - { - return data; - } - - if (text.Contains("[DISCONNECT]", StringComparison.OrdinalIgnoreCase)) - { - DisconnectClientAsync(DisconnectReason.RemoteClosed).ConfigureAwait(false); - hasHeartbeat = true; - } - if (text.Contains(Configuration.SSL_ERROR_PREFIX, StringComparison.OrdinalIgnoreCase)) - { - string sslError = null; - var startIdx = text.IndexOf(Configuration.SSL_ERROR_PREFIX, StringComparison.Ordinal) + Configuration.SSL_ERROR_PREFIX.Length; - var endIdx = text.IndexOf(Configuration.SSL_ERROR_SUFFIX, StringComparison.Ordinal); - if (endIdx > startIdx) - { - sslError = text.Substring(startIdx, endIdx - startIdx); - } - RecordError(null, $"Server reported SSL error: {sslError ?? text}", isSslError: true); - OnSslError?.Invoke(this, new ErrorEventArgs - { - Message = $"Server reported SSL error: {sslError ?? text}" - }); - DisconnectClientAsync(DisconnectReason.SSLError).ConfigureAwait(false); - hasHeartbeat = true; - } - if (text.Contains(Configuration.PING_VALUE)) - { - hasHeartbeat = true; - SendAsync(Configuration.PONG_VALUE).ConfigureAwait(false); - if (_config.EnablePingPongLogs) - { - OnLog?.Invoke(this, "PING received. Sent PONG response."); - } - } - if (text.Contains(Configuration.PONG_VALUE)) - { - hasHeartbeat = true; - var now = DateTime.UtcNow; - OnPingResponse?.Invoke(this, new PingEventArgs - { - Id = "server", - Nickname = Nickname, - ReceivedTime = now, - RemoteEndPoint = new IPEndPoint(IPAddress.Parse(_config.Host), _config.Port) - }); - if (_config.EnablePingPongLogs) - { - OnLog?.Invoke(this, "PONG received."); - } - } - if (hasHeartbeat && !string.IsNullOrEmpty(text)) - { - text = text.Replace(Configuration.PING_VALUE, string.Empty).Replace(Configuration.PONG_VALUE, string.Empty).Replace("[DISCONNECT]", string.Empty); - data = Encoding.UTF8.GetBytes(text); - } - return data; - } - - public void Dispose() - { - Dispose(true); - GC.SuppressFinalize(this); - } - - protected virtual void Dispose(bool disposing) - { - if (!disposing) - { - return; - } - - try - { - _clientCts?.Cancel(); - _autoReconnectSource?.Cancel(); - _connectionCts?.Cancel(); - } - catch - { - // Do nothing - } - - try { _stream?.Close(); _stream?.Dispose(); _stream = null; } catch { } - try - { - if (_tcpClient != null) - { - try { _tcpClient.Client?.Shutdown(SocketShutdown.Both); } catch { } - _tcpClient.Close(); - _tcpClient.Dispose(); - _tcpClient = null; - } - } - catch { } - try { _udpClient?.Close(); _udpClient?.Dispose(); _udpClient = null; } catch { } - try { _aesEncryption?.Dispose(); _aesEncryption = null; } catch { } - - try { _clientCts?.Dispose(); _clientCts = null; } catch { } - try { _autoReconnectSource?.Dispose(); _autoReconnectSource = null; } catch { } - try { _connectionCts?.Dispose(); _connectionCts = null; } catch { } - - try { _connectLock?.Dispose(); } catch { } - try { _connectionAttemptLock?.Dispose(); } catch { } - try { _streamReadLock?.Dispose(); } catch { } - try { _streamWriteLock?.Dispose(); } catch { } - - HealthApi.Dispose(); - } - - private void ConfigureKeepAlive(Socket socket, int keepAliveTimeSeconds, int keepAliveIntervalSeconds, int keepAliveRetryCount = 10) - { - if (socket == null) - { - return; - } - - try - { - socket.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.KeepAlive, true); - -#if NET5_0_OR_GREATER - socket.SetSocketOption(SocketOptionLevel.Tcp, SocketOptionName.TcpKeepAliveTime, Math.Max(1, keepAliveTimeSeconds)); - socket.SetSocketOption(SocketOptionLevel.Tcp, SocketOptionName.TcpKeepAliveInterval, Math.Max(1, keepAliveIntervalSeconds)); - socket.SetSocketOption(SocketOptionLevel.Tcp, SocketOptionName.TcpKeepAliveRetryCount, Math.Max(1, keepAliveRetryCount)); -#else - uint onOff = 1; - uint keepAliveTime = (uint)Math.Max(1, keepAliveTimeSeconds) * 1000; - uint keepAliveInterval = (uint)Math.Max(1, keepAliveIntervalSeconds) * 1000; - - byte[] keepAliveSettings = new byte[12]; - Buffer.BlockCopy(BitConverter.GetBytes(onOff), 0, keepAliveSettings, 0, 4); - Buffer.BlockCopy(BitConverter.GetBytes(keepAliveTime), 0, keepAliveSettings, 4, 4); - Buffer.BlockCopy(BitConverter.GetBytes(keepAliveInterval), 0, keepAliveSettings, 8, 4); - - socket.IOControl(IOControlCode.KeepAliveValues, keepAliveSettings, null); -#endif - } - catch (Exception ex) - { - OnLog?.Invoke(this, $"Failed to configure TCP keep-alive: {ex.Message}"); - } - } } -} \ No newline at end of file +} diff --git a/EonaCat.Connections/NetworkServer.cs b/EonaCat.Connections/NetworkServer.cs index 0072fcc..1a4ecfa 100644 --- a/EonaCat.Connections/NetworkServer.cs +++ b/EonaCat.Connections/NetworkServer.cs @@ -1,46 +1,51 @@ -using EonaCat.Connections.EventArguments; +using EonaCat.Connections.Contracts; +using EonaCat.Connections.EventArguments; using EonaCat.Connections.Helpers; using EonaCat.Connections.Models; +using EonaCat.Connections.Security; using System.Buffers; using System.Collections.Concurrent; using System.Net; -using System.Net.Security; using System.Net.Sockets; -using System.Security.Authentication; -using System.Security.Cryptography; -using System.Security.Cryptography.X509Certificates; -using System.Text; -using System.Text.RegularExpressions; using ErrorEventArgs = EonaCat.Connections.EventArguments.ErrorEventArgs; using ProtocolType = EonaCat.Connections.Models.ProtocolType; namespace EonaCat.Connections { - // This file is part of the EonaCat project(s) which is released under the Apache License. - // See the LICENSE file or go to https://EonaCat.com/license for full license details. - - public partial class NetworkServer : IDisposable + public partial class NetworkServer : IConnectorServer { + public static event EventHandler OnLog; private const int MAX_BUFFER_MEMORY_IN_KILOBYTES = 1024 * 200; private const int DEFAULT_WAITING_TIMEOUT_IN_SECONDS = 30; + private const int DNS_RESOLVE_MAX_ATTEMPTS = 3; + private readonly Configuration _config; private readonly Stats _stats; private readonly ConcurrentDictionary _clients; - private TcpListener? _tcpListener; - private UdpClient? _udpListener; + + private readonly ConcurrentDictionary> _nicknameToClientIds = new(StringComparer.OrdinalIgnoreCase); + + private readonly List _tcpListeners = new(); + private readonly List _udpListeners = new(); + + private readonly ConcurrentDictionary _udpClientOrigin = new(); private CancellationTokenSource? _serverCancellation; private Task? _tcpTask; private Task? _udpTask; - private Task? _acceptTcpClientsTask; + private readonly List _acceptTcpClientsTasks = new(); private Task? _pingTask; private Task? _pongTask; private Task? _cleanupTask; - public event EventHandler OnLog; - - private readonly SemaphoreSlim _udpLock = new(1, 1); + private Security.RateLimiter? _globalRateLimiter; + private PerConnectionRateLimiter? _perConnectionRateLimiter; + private DDoSDetector? _ddosDetector; + private SlowlorisDetector? _slowlorisDetector; + private PayloadValidator? _payloadValidator; + private RequestDeduplicator? _deduplicator; + private IPBlocklist? _ipBlocklist; public event EventHandler OnConnected; @@ -57,6 +62,7 @@ namespace EonaCat.Connections public event EventHandler OnGeneralError; public event EventHandler OnSocketError; + public event EventHandler OnClientMissing; public SocketStatusPage StatusPage { get; } = new SocketStatusPage(); @@ -93,6 +99,13 @@ namespace EonaCat.Connections public HealthApiServer HealthApi { get; } + private sealed class UdpListenerEntry + { + public UdpClient? Client; + public IPEndPoint LocalEndPoint = null!; + public readonly SemaphoreSlim Lock = new(1, 1); + } + public NetworkServer(Configuration config) { _config = config; @@ -100,2395 +113,13 @@ namespace EonaCat.Connections _clients = new ConcurrentDictionary(); ServerStatus = new ServerStatusPage(() => _clients, () => GetStats(), _config, StatusPage); HealthApi = new HealthApiServer(BuildHealthJson, BuildStatusJson); - } - public Stats GetStats() - { - _stats.ActiveConnections = GetActiveConnectionCount(); - return _stats; - } - - private int GetActiveConnectionCount() - { - if (_clients.IsEmpty) + if (_config?.Security?.IsAnyProtectionEnabled == true) { - return 0; - } - - int activeCount = 0; - - foreach (var client in _clients.Values) - { - if (client == null || client.IsClosing) - { - continue; - } - - if (_config.Protocol == ProtocolType.UDP) - { - activeCount++; - continue; - } - - if (IsTcpClientAlive(client)) - { - activeCount++; - } - } - - return activeCount; - } - - private static bool IsTcpClientAlive(Connection client) - { - var socket = client?.TcpClient?.Client; - if (socket == null) - { - return false; - } - - try - { - if (!socket.Connected) - { - return false; - } - - return !(socket.Poll(0, SelectMode.SelectRead) && socket.Available == 0); - } - catch - { - return false; + InitializeSecurityComponents(); } } - public string IpAddress => _config != null ? _config.Host : string.Empty; - public int Port => _config != null ? _config.Port : 0; - public bool DEBUG_DATA_SEND { get; set; } - public bool DEBUG_DATA_RECEIVED { get; set; } - - /// - /// Occurs when a client has been idle for longer than the configured timeout period. - /// - /// Subscribers can use this event to perform actions such as disconnecting or notifying - /// idle clients. The event is raised with an instance containing details - /// about the idle client. - public event EventHandler OnIdleTimeout; - - private string BuildHealthJson() - { - var E = HealthApiServer.JsonEscape; - var stats = GetStats(); - return "{" + - "\"status\":\"ok\"," + - "\"type\":\"server\"," + - $"\"listenAddress\":{E(_config.Host + ":" + _config.Port)}," + - $"\"protocol\":{E(_config.Protocol.ToString())}," + - $"\"isStarted\":{(IsStarted ? "true" : "false")}," + - $"\"isSecure\":{(IsSecure ? "true" : "false")}," + - $"\"isEncrypted\":{(IsEncrypted ? "true" : "false")}," + - $"\"activeConnections\":{stats.ActiveConnections}," + - $"\"maxConnections\":{_config.MaxConnections}," + - $"\"uptimeSeconds\":{stats.Uptime.TotalSeconds:F1}," + - $"\"startTimeUtc\":{E(stats.StartTime.ToString("O"))}" + - "}"; - } - - private string BuildStatusJson() - { - var E = HealthApiServer.JsonEscape; - var stats = GetStats(); - var sb = new StringBuilder(); - sb.Append("{"); - sb.Append("\"status\":\"ok\","); - sb.Append("\"type\":\"server\","); - sb.Append($"\"listenAddress\":{E(_config.Host + ":" + _config.Port)},"); - sb.Append($"\"protocol\":{E(_config.Protocol.ToString())},"); - sb.Append($"\"isStarted\":{(IsStarted ? "true" : "false")},"); - sb.Append($"\"isSecure\":{(IsSecure ? "true" : "false")},"); - sb.Append($"\"isEncrypted\":{(IsEncrypted ? "true" : "false")},"); - sb.Append($"\"activeConnections\":{stats.ActiveConnections},"); - sb.Append($"\"maxConnections\":{_config.MaxConnections},"); - sb.Append($"\"totalConnections\":{stats.TotalConnections},"); - sb.Append($"\"droppedConnections\":{stats.DroppedConnections},"); - sb.Append($"\"droppedPackets\":{stats.DroppedPackets},"); - sb.Append($"\"bytesSent\":{stats.BytesSent},"); - sb.Append($"\"bytesReceived\":{stats.BytesReceived},"); - sb.Append($"\"messagesSent\":{stats.MessagesSent},"); - sb.Append($"\"messagesReceived\":{stats.MessagesReceived},"); - sb.Append($"\"messagesPerSecond\":{stats.MessagesPerSecond:F2},"); - sb.Append($"\"uptimeSeconds\":{stats.Uptime.TotalSeconds:F1},"); - sb.Append($"\"startTimeUtc\":{E(stats.StartTime.ToString("O"))},"); - - // Clients array - sb.Append("\"clients\":["); - var clientList = _clients.Values.ToArray(); - for (int i = 0; i < clientList.Length; i++) - { - var c = clientList[i]; - if (i > 0) - { - sb.Append(","); - } - - sb.Append("{"); - sb.Append($"\"id\":{E(c.Id)},"); - sb.Append($"\"nickname\":{E(c.Nickname)},"); - sb.Append($"\"remoteEndPoint\":{E(c.RemoteEndPoint?.ToString())},"); - sb.Append($"\"connectedAtUtc\":{E(c.ConnectedAt.ToString("O"))},"); - sb.Append($"\"connectedTimeSeconds\":{c.ConnectedTime().TotalSeconds:F1},"); - sb.Append($"\"idleTimeSeconds\":{c.IdleTime().TotalSeconds:F1},"); - sb.Append($"\"bytesSent\":{c.BytesSent},"); - sb.Append($"\"bytesReceived\":{c.BytesReceived},"); - sb.Append($"\"lastDataSentUtc\":{(c.LastDataSent == default ? "null" : E(c.LastDataSent.ToString("O")))},"); - sb.Append($"\"lastDataReceivedUtc\":{(c.LastDataReceived == default ? "null" : E(c.LastDataReceived.ToString("O")))},"); - sb.Append($"\"isSecure\":{(c.IsSecure ? "true" : "false")},"); - sb.Append($"\"isEncrypted\":{(c.IsEncrypted ? "true" : "false")}"); - sb.Append("}"); - } - sb.Append("]"); - - // SSL error summary - sb.Append(",\"sslErrors\":{"); - sb.Append($"\"total\":{StatusPage.SslErrorCount},"); - var sslErrors = StatusPage.GetSslErrors(); - sb.Append("\"entries\":["); - for (int i = 0; i < sslErrors.Count; i++) - { - var se = sslErrors[i]; - if (i > 0) - { - sb.Append(","); - } - - sb.Append("{"); - sb.Append($"\"timestamp\":{E(se.Timestamp.ToString("O"))},"); - sb.Append($"\"clientId\":{E(se.ClientId)},"); - sb.Append($"\"nickname\":{E(se.Nickname)},"); - sb.Append($"\"message\":{E(se.Message)},"); - sb.Append($"\"exceptionType\":{E(se.ExceptionType)}"); - sb.Append("}"); - } - sb.Append("]}"); - - sb.Append("}"); - return sb.ToString(); - } - - public Task StartAsync() - { - if (_isStarting) - { - return Task.CompletedTask; - } - - _isStarting = true; - _serverCancellation?.Dispose(); - _serverCancellation = new CancellationTokenSource(); - - if (_config.Protocol == ProtocolType.TCP) - { - _tcpTask = Task.Run(() => StartTcpServerAsync(), _serverCancellation.Token); - _cleanupTask = Task.Run(() => CleanupTcpClientsAsync(_serverCancellation.Token), _serverCancellation.Token); - } - else - { - _udpTask = Task.Run(() => StartUdpServerAsync(_serverCancellation.Token), _serverCancellation.Token); - } - - if (_config.EnableHeartbeat) - { - _pingTask = Task.Run(() => StartPingLoopAsync(_serverCancellation.Token), _serverCancellation.Token); - _pongTask = Task.Run(() => StartPongLoopAsync(_serverCancellation.Token), _serverCancellation.Token); - } - - // Start rate limit cache cleanup if enabled - if (_config.EnableRateLimitCacheCleanup) - { - _ = Task.Run(() => CleanupRateLimitCacheAsync(_serverCancellation.Token), _serverCancellation.Token); - } - - if (_config.EnableAutoHtmlReports) - { - StatusPage.StartAutoHtmlReport( - _config.HtmlReportOutputDirectory, - _config.HtmlReportIntervalSeconds, - "status-server-errors.html"); - } - - if (_config.EnableServerStatusPage) - { - ServerStatus.StartAutoReport( - _config.HtmlReportOutputDirectory, - _config.ServerStatusPageIntervalSeconds, - "status-server.html"); - } - - if (_config.EnableHealthApi) - { - HealthApi.Start(_config.HealthApiPort, _config.HealthApiBindAddress); - } - - _isStarting = false; - return Task.CompletedTask; - } - - private async Task StartPongLoopAsync(CancellationToken token) - { - while (!token.IsCancellationRequested) - { - try - { - var now = DateTime.UtcNow; - var timeout = _config.HeartbeatIntervalSeconds * 2; - - var pingTimes = _lastPingTimes.ToList(); - var toRemove = new List(); - - foreach (var pings in pingTimes) - { - var clientId = pings.Key; - var lastPong = pings.Value; - - if (!_clients.TryGetValue(clientId, out var client)) - { - toRemove.Add(clientId); - continue; - } - - if (!client.IsConnected) - { - await DisconnectClientAsync(clientId, DisconnectReason.RemoteClosed); - continue; - } - - var elapsed = (now - lastPong).TotalSeconds; - - if (elapsed > timeout) - { - if (_config.EnablePingPongLogs) - { - OnLog?.Invoke(this, $"Client '{client.Nickname}' no PONG for {elapsed:F1}s, disconnect."); - } - - OnPongMissed?.Invoke(this, new PingEventArgs - { - Id = client.Id, - Nickname = client.Nickname, - ReceivedTime = now, - RemoteEndPoint = client.RemoteEndPoint - }); - - if (_config.DisconnectOnMissedPong) - { - DebugConnection($"Disconnecting client {client.Nickname} ({client.Id}) due to missed PONG response."); - _ = DisconnectClientAsync(clientId, DisconnectReason.NoPongReceived); - } - } - - if (elapsed > _config.HeartbeatIntervalSeconds * 4) - { - toRemove.Add(clientId); - } - } - - foreach (var remove in toRemove) - { - _lastPingTimes.TryRemove(remove, out _); - } - - await Task.Delay(TimeSpan.FromSeconds(1), token); - } - catch (TaskCanceledException) - { - DebugConnection("Pong loop canceled."); - break; - } - catch (Exception exception) - { - DebugConnection($"StartPongLoopAsync: Error checking pong responses for {_config.Host}:{_config.Port}: {exception.Message}"); - OnGeneralError?.Invoke(this, new ErrorEventArgs - { - Exception = exception, - Message = "Pong loop error" - }); - } - } - } - - private async Task StartPingLoopAsync(CancellationToken token) - { - while (!token.IsCancellationRequested) - { - try - { - var clients = _clients.Values.ToList(); - var pingTasks = new List(clients.Count); - - foreach (var client in clients) - { - if (!client.IsConnected || client.IsClosing) - { - continue; - } - - pingTasks.Add(SendToClientAsync(client.Id, Configuration.PING_VALUE)); - } - - if (pingTasks.Count > 0) - { - await Task.WhenAll(pingTasks).ConfigureAwait(false); - } - - await Task.Delay(TimeSpan.FromSeconds(_config.HeartbeatIntervalSeconds), token).ConfigureAwait(false); - } - catch (TaskCanceledException) - { - DebugConnection("Ping loop canceled."); - break; - } - catch (Exception exception) - { - DebugConnection($"StartPingLoopAsync: Error sending ping to {_config.Host}:{_config.Port}: {exception.Message}"); - RecordError(exception, $"Ping loop error: {exception.Message}"); - OnGeneralError?.Invoke(this, new ErrorEventArgs - { - Exception = exception, - Message = "Ping loop error" - }); - } - } - } - - private void DebugConnection(string debugText) - { - if (!_config.EnableConnectionDebugLogs) - { - return; - } - OnLog?.Invoke(this, $"[NetworkServer] {debugText}"); - } - - private void RecordError(Exception exception, string message, string clientId = null, string nickname = null, bool isSslError = false) - { - var socketEx = exception as SocketException - ?? (exception as IOException)?.InnerException as SocketException; - - var entry = new SocketErrorEntry - { - Timestamp = DateTime.UtcNow, - Source = "Server", - ClientId = clientId, - Nickname = nickname, - SocketErrorCode = socketEx?.SocketErrorCode, - ErrorCode = socketEx != null ? socketEx.SocketErrorCode.ToString() : exception?.GetType().Name, - Message = message, - ExceptionType = exception?.GetType().FullName, - StackTrace = exception?.StackTrace, - Exception = exception, - IsSslError = isSslError - }; - - StatusPage.AddError(entry); - - if (socketEx != null) - { - OnSocketError?.Invoke(this, new ErrorEventArgs - { - ClientId = clientId, - Nickname = nickname, - Exception = exception, - Message = $"SocketError {socketEx.SocketErrorCode}: {message}" - }); - } - } - - public Task StartTcpServerAsync() - { - if (Interlocked.CompareExchange(ref _tcpRunning, 1, 0) == 1) - { - return Task.CompletedTask; - } - - _acceptTcpClientsTask = AcceptClientsAsync(_serverCancellation.Token); - return Task.CompletedTask; - } - - private async Task AcceptClientsAsync(CancellationToken token) - { - if (_tcpListener == null || !_tcpListener.Server.IsBound) - { - _tcpListener = new TcpListener(IPAddress.Parse(_config.Host), _config.Port); - _tcpListener.Server.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ReuseAddress, true); - _tcpListener.Start(); - - Console.WriteLine($"EonaCat.Connections TCP Server started on {_config.Host}:{_config.Port}"); - } - - while (!token.IsCancellationRequested) - { - try - { - if (token.IsCancellationRequested) - { - DebugConnection("Cancellation requested, stopping accept loop."); - break; - } - - if (_tcpListener == null) - { - DebugConnection("TCP listener is null, stopping accept loop."); - break; - } - - TcpClient tcpClient = await _tcpListener.AcceptTcpClientAsync().ConfigureAwait(false); - - if (_config.MaxConnections > 0 && GetActiveConnectionCount() >= _config.MaxConnections) - { - tcpClient.Close(); - tcpClient.Dispose(); - _stats.IncrementDroppedConnections(); - OnLog?.Invoke(this, $"Incoming TCP client ignored: max connections ({_config.MaxConnections}) reached."); - continue; - } - - _ = Task.Run(() => HandleTcpClientAsync(tcpClient), token); - } - catch (ObjectDisposedException) - { - DebugConnection("TCP listener disposed, stopping accept loop."); - break; - } - catch (SocketException ex) when (ex.SocketErrorCode == SocketError.Interrupted || ex.SocketErrorCode == SocketError.OperationAborted) - { - DebugConnection($"TCP listener interrupted, stopping accept loop: {ex.Message}"); - RecordError(ex, $"TCP listener interrupted: {ex.SocketErrorCode}"); - break; - } - catch (SocketException ex) - { - DebugConnection($"Socket error in accept loop: {ex.Message}"); - RecordError(ex, $"Socket error in accept loop: {ex.SocketErrorCode}"); - OnLog?.Invoke(this, $"Socket error in accept loop: {ex.Message}"); - await Task.Delay(100, token).ConfigureAwait(false); - } - catch (OperationCanceledException) - { - DebugConnection("Accept loop canceled."); - break; - } - catch (Exception ex) - { - DebugConnection($"Unexpected error in accept loop: {ex.Message}"); - RecordError(ex, $"Unexpected error in accept loop: {ex.Message}"); - OnLog?.Invoke(this, $"Unexpected error in accept loop: {ex.Message}"); - await Task.Delay(100, token).ConfigureAwait(false); - } - } - } - - public async Task StopTcpServerAsync() - { - await StopAsync().ConfigureAwait(false); - } - - public Dictionary GetClients() - { - return _clients.ToDictionary(kvp => kvp.Key, kvp => kvp.Value); - } - - public async Task StartUdpServerAsync(CancellationToken token) - { - if (Interlocked.CompareExchange(ref _udpRunning, 1, 0) == 1) - { - Console.WriteLine("EonaCat.Connections UDP Server is already running."); - return; - } - - try - { - await _udpLock.WaitAsync(token).ConfigureAwait(false); - try - { - _udpListener = new UdpClient(_config.Port); - } - finally - { - _udpLock.Release(); - } - - Console.WriteLine($"EonaCat.Connections UDP Server started on {_config.Host}:{_config.Port}"); - - _ = Task.Run(async () => await CleanupUdpClientsAsync(token), token).ConfigureAwait(false); - - while (!token.IsCancellationRequested) - { - try - { - UdpReceiveResult result; - - await _udpLock.WaitAsync(token).ConfigureAwait(false); - try - { - if (_udpListener == null) - { - break; - } - - result = await _udpListener!.ReceiveAsync().ConfigureAwait(false); - } - finally - { - _udpLock.Release(); - } - - _ = Task.Run(() => HandleUdpDataAsync(result), token); - } - catch (ObjectDisposedException) - { - DebugConnection("UDP listener disposed, stopping receive loop."); - break; - } - catch (SocketException exception) when (exception.SocketErrorCode == SocketError.Interrupted) - { - DebugConnection("UDP listener interrupted, stopping receive loop."); - RecordError(exception, $"UDP listener interrupted: {exception.SocketErrorCode}"); - break; - } - catch (SocketException exception) - { - DebugConnection($"Socket error receiving UDP data: {exception.SocketErrorCode} - {exception.Message}"); - RecordError(exception, $"Socket error receiving UDP data: {exception.SocketErrorCode}"); - OnGeneralError?.Invoke(this, new ErrorEventArgs - { - Exception = exception, - Message = $"UDP receive socket error: {exception.SocketErrorCode}" - }); - } - catch (Exception exception) - { - DebugConnection($"Error receiving UDP data: {exception.Message}"); - RecordError(exception, $"Error receiving UDP data: {exception.Message}"); - OnGeneralError?.Invoke(this, new ErrorEventArgs - { - Exception = exception, - Message = "Error receiving UDP data" - }); - } - } - } - finally - { - DebugConnection("UDP server stopping, closing listener and disconnecting clients."); - await StopUdpServerAsync(); - } - } - - private async Task StopUdpServerAsync() - { - await _udpLock.WaitAsync().ConfigureAwait(false); - try - { - _udpListener?.Close(); - _udpListener?.Dispose(); - _udpListener = null; - } - finally - { - _udpLock.Release(); - } - Interlocked.Exchange(ref _udpRunning, 0); - } - - private void ConfigureKeepAlive(Socket socket, int keepAliveTimeSeconds, int keepAliveIntervalSeconds, int keepAliveRetryCount = 10) - { - if (socket == null) - { - return; - } - - try - { - socket.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.KeepAlive, true); - -#if NET5_0_OR_GREATER - socket.SetSocketOption(SocketOptionLevel.Tcp, SocketOptionName.TcpKeepAliveTime, Math.Max(1, keepAliveTimeSeconds)); - socket.SetSocketOption(SocketOptionLevel.Tcp, SocketOptionName.TcpKeepAliveInterval, Math.Max(1, keepAliveIntervalSeconds)); - socket.SetSocketOption(SocketOptionLevel.Tcp, SocketOptionName.TcpKeepAliveRetryCount, Math.Max(1, keepAliveRetryCount)); -#else - uint onOff = 1; - uint keepAliveTime = (uint)Math.Max(1, keepAliveTimeSeconds) * 1000; - uint keepAliveInterval = (uint)Math.Max(1, keepAliveIntervalSeconds) * 1000; - - byte[] keepAliveSettings = new byte[12]; - Buffer.BlockCopy(BitConverter.GetBytes(onOff), 0, keepAliveSettings, 0, 4); - Buffer.BlockCopy(BitConverter.GetBytes(keepAliveTime), 0, keepAliveSettings, 4, 4); - Buffer.BlockCopy(BitConverter.GetBytes(keepAliveInterval), 0, keepAliveSettings, 8, 4); - - socket.IOControl(IOControlCode.KeepAliveValues, keepAliveSettings, null); -#endif - } - catch (Exception ex) - { - OnLog?.Invoke(this, $"Failed to configure TCP keep-alive: {ex.Message}"); - } - } - - private void ConfigureSocketOptions(Socket socket) - { - if (socket == null) - { - return; - } - - try - { - // Set socket-level timeouts as a fallback - socket.ReceiveTimeout = (int)(_config.ReadTimeoutSeconds * 1000); - socket.SendTimeout = (int)(_config.WriteTimeoutSeconds * 1000); - - // Configure linger to prevent hanging connections - socket.LingerState = new LingerOption(_config.EnableRST, 0); - - // Disable delay for connection close - socket.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.DontLinger, !_config.EnableRST); - - // Set buffer sizes to match configuration - socket.ReceiveBufferSize = _config.BufferSize; - socket.SendBufferSize = _config.BufferSize; - - DebugConnection($"Socket options configured: ReceiveTimeout={_config.ReadTimeoutSeconds}s, SendTimeout={_config.WriteTimeoutSeconds}s, Linger={_config.EnableRST}"); - } - catch (Exception ex) - { - DebugConnection($"Error configuring socket options: {ex.Message}"); - } - } - - private async Task HandleTcpClientAsync(TcpClient tcpClient) - { - var clientId = Guid.NewGuid().ToString(); - var remoteEndPoint = tcpClient.Client.RemoteEndPoint as IPEndPoint ?? new IPEndPoint(IPAddress.None, 0); - var client = new Connection - { - Id = clientId, - TcpClient = tcpClient, - RemoteEndPoint = remoteEndPoint, - ConnectedAt = DateTime.UtcNow, - LastActive = DateTime.UtcNow, - CancellationToken = new CancellationTokenSource() - }; - - UpdateLastActive(client); - - try - { - tcpClient.NoDelay = !_config.EnableNagle; - - // Configure socket-level timeouts and options - ConfigureSocketOptions(tcpClient.Client); - - if (_config.EnableKeepAlive) - { - ConfigureKeepAlive(tcpClient.Client, _config.KeepAliveTimeSeconds, _config.KeepAliveIntervalSeconds, _config.KeepAliveRetryCount); - } - - Stream stream = tcpClient.GetStream(); - - // Set NetworkStream timeouts - if (stream is NetworkStream networkStream) - { - networkStream.ReadTimeout = (int)(_config.ReadTimeoutSeconds * 1000); - networkStream.WriteTimeout = (int)(_config.WriteTimeoutSeconds * 1000); - DebugConnection($"Set stream timeouts: Read={_config.ReadTimeoutSeconds}s, Write={_config.WriteTimeoutSeconds}s for {remoteEndPoint}"); - } - - if (_config.UseSsl) - { - bool sslAuthenticated = false; - var sslDiagnostics = _config.EnableSslDiagnostics ? new Helpers.SslHandshakeDiagnostics() : null; - - for (int attempt = 1; attempt <= _config.SSLMaxRetries || _config.SSLMaxRetries == 0; attempt++) - { - SslStream? sslStream = null; - - try - { - sslDiagnostics?.StartHandshake(remoteEndPoint.ToString(), _config.MutuallyAuthenticate); - - sslStream = new SslStream(stream, leaveInnerStreamOpen: true, _config.GetRemoteCertificateValidationCallback()); - -#if NET8_0_OR_GREATER - var serverOptions = new SslServerAuthenticationOptions - { - ServerCertificate = _config.Certificate, - ClientCertificateRequired = _config.MutuallyAuthenticate, - EnabledSslProtocols = SslProtocols.Tls12 | SslProtocols.Tls13, - CertificateRevocationCheckMode = _config.CheckCertificateRevocation ? X509RevocationMode.Online : X509RevocationMode.NoCheck, - AllowRenegotiation = _config.AllowTlsRenegotiation - }; - DebugConnection($"Starting SSL authentication for {remoteEndPoint}, attempt {attempt}."); - - sslDiagnostics?.StartStage("ServerAuth"); - await sslStream.AuthenticateAsServerAsync(serverOptions, CancellationToken.None).ConfigureAwait(false); - sslDiagnostics?.EndStage("ServerAuth"); - - DebugConnection($"SSL authentication successful for {remoteEndPoint} on attempt {attempt}."); -#else - sslDiagnostics?.StartStage("ServerAuth"); - await sslStream.AuthenticateAsServerAsync(_config.Certificate, _config.MutuallyAuthenticate, SslProtocols.Tls12, _config.CheckCertificateRevocation).ConfigureAwait(false); - sslDiagnostics?.EndStage("ServerAuth"); -#endif - - stream = sslStream; - client.IsSecure = true; - sslAuthenticated = true; - - sslDiagnostics?.RecordSuccess(sslStream); - if (sslDiagnostics != null) - { - DebugConnection($"[SSL Metrics] {sslDiagnostics}"); - } - break; - } - catch (IOException ioException) when (ioException.Message.Contains("0 bytes from the transport stream") || ioException.Message.Contains("Unexpected EOF")) - { - var isRecoverable = Helpers.SslHandshakeDiagnostics.IsRecoverableFailure(ioException); - sslDiagnostics?.RecordFailure(ioException, isRecoverable); - - RecordError(ioException, "SSL handshake failed due to EOF", clientId, client.Nickname, isSslError: true); - OnSslError?.Invoke(this, new ErrorEventArgs - { - ClientId = clientId, - Nickname = client.Nickname, - Exception = ioException, - Message = "SSL handshake failed due to EOF" - }); - DebugConnection($"SSL handshake EOF from {remoteEndPoint} on attempt {attempt}: {ioException.Message}"); - OnLog?.Invoke(this, $"SSL handshake EOF from {remoteEndPoint}. Attempt {attempt}"); - } - catch (AuthenticationException authException) - { - var isRecoverable = Helpers.SslHandshakeDiagnostics.IsRecoverableFailure(authException); - sslDiagnostics?.RecordFailure(authException, isRecoverable); - - RecordError(authException, "SSL authentication failed", clientId, client.Nickname, isSslError: true); - OnSslError?.Invoke(this, new ErrorEventArgs - { - ClientId = clientId, - Nickname = client.Nickname, - Exception = authException, - Message = "SSL authentication failed" - }); - DebugConnection($"SSL authentication failed for {remoteEndPoint} on attempt {attempt}: {authException.Message}"); - OnLog?.Invoke(this, $"SSL Authentication failed for {remoteEndPoint}: {authException.Message}"); - - if (!isRecoverable) - { - try - { - var notification = Encoding.UTF8.GetBytes($"{Configuration.SSL_ERROR_PREFIX}SSL authentication failed: {authException.Message}{Configuration.SSL_ERROR_SUFFIX}"); - var rawStream = tcpClient.GetStream(); - await rawStream.WriteAsync(notification, 0, notification.Length).ConfigureAwait(false); - await rawStream.FlushAsync().ConfigureAwait(false); - } - catch - { - // Cannot notify client, likely already disconnected - } - tcpClient?.Client?.Disconnect(false); - break; - } - } - catch (Exception ex) - { - var isRecoverable = Helpers.SslHandshakeDiagnostics.IsRecoverableFailure(ex); - sslDiagnostics?.RecordFailure(ex, isRecoverable); - - RecordError(ex, $"SSL error: {ex.GetType().Name}", clientId, client.Nickname, isSslError: true); - DebugConnection($"SSL error for {remoteEndPoint} on attempt {attempt}: {ex.Message}"); - - if (!isRecoverable) - { - break; - } - } - finally - { -#if NET8_0_OR_GREATER - if (!sslAuthenticated) - { - DebugConnection($"Disposing SSL stream for {remoteEndPoint} after failed authentication attempt {attempt}."); - - try - { - await (sslStream?.DisposeAsync() ?? ValueTask.CompletedTask); - } - catch - { - // Do nothing - } - } -#else - if (!sslAuthenticated) - { - DebugConnection($"Disposing SSL stream for {remoteEndPoint} after failed authentication attempt {attempt}."); - sslStream?.Dispose(); - } -#endif - } - - if (!sslAuthenticated && (attempt < _config.SSLMaxRetries || _config.SSLMaxRetries == 0)) - { - int delaySeconds = _config.GetSslRetryDelaySeconds(attempt); - DebugConnection($"SSL retry in {delaySeconds}s (attempt {attempt})"); - sslDiagnostics?.StartStage("RetryDelay"); - await Task.Delay(delaySeconds * 1000).ConfigureAwait(false); - sslDiagnostics?.EndStage("RetryDelay"); - } - } - - if (!sslAuthenticated) - { - DebugConnection($"SSL authentication failed for {remoteEndPoint} after {_config.SSLMaxRetries} attempts, disconnecting client."); - if (sslDiagnostics != null) - { - DebugConnection($"[SSL Final Metrics] {sslDiagnostics}"); - } - try - { - var notification = Encoding.UTF8.GetBytes($"{Configuration.SSL_ERROR_PREFIX}SSL authentication failed after {_config.SSLMaxRetries} attempts{Configuration.SSL_ERROR_SUFFIX}"); - var rawStream = tcpClient.GetStream(); - await rawStream.WriteAsync(notification, 0, notification.Length).ConfigureAwait(false); - await rawStream.FlushAsync().ConfigureAwait(false); - } - catch - { - // Cannot notify client, likely already disconnected - } - await DisconnectClientAsync(clientId, DisconnectReason.SSLError).ConfigureAwait(false); - return; - } - } - - if (_config.EnableKeepAlive) - { - DebugConnection($"Enabling TCP keep-alive for client {client.Nickname} ({client.Id}) with keep-alive time {_config.KeepAliveTimeSeconds}s and interval {_config.KeepAliveIntervalSeconds}s."); - tcpClient.Client.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.KeepAlive, true); - } - - if (_config.UseAesEncryption) - { - try - { - client.AesEncryption = Aes.Create(); - client.AesEncryption.GenerateKey(); - client.AesEncryption.GenerateIV(); - client.IsEncrypted = true; - await AesKeyExchange.SendAesKeyAsync(stream, client.AesEncryption, _config.AesPassword); - } - catch (Exception exception) - { - OnEncryptionError?.Invoke(this, new ErrorEventArgs - { - ClientId = clientId, - Nickname = client.Nickname, - Exception = exception, - Message = "AES setup failed" - }); - client.Stream = stream; - try { await client.DisposeAsync(); } catch { } - return; - } - } - - client.Stream = stream; - UpdateLastActive(client); - client.LastDataReceived = DateTime.UtcNow; - client.LastDataSent = DateTime.UtcNow; - - _clients[clientId] = client; - client.ReceiveDataTask = Task.Run(() => HandleClientCommunicationAsync(client), client.CancellationToken.Token); - _stats.IncrementTotalConnections(); - - DebugConnection($"Client connected: {client.Nickname} ({client.Id}) from {remoteEndPoint}. Total connections: {ActiveConnections}"); - - OnConnected?.Invoke(this, new ConnectionEventArgs - { - ClientId = clientId, - RemoteEndPoint = remoteEndPoint, - Nickname = client.Nickname - }); - } - catch (SocketException socketEx) - { - DebugConnection($"Socket error handling TCP client {remoteEndPoint}: {socketEx.SocketErrorCode} - {socketEx.Message}"); - RecordError(socketEx, $"Socket error handling TCP client: {socketEx.SocketErrorCode}", clientId, client.Nickname); - if (!_clients.ContainsKey(clientId)) - { - try { await client.DisposeAsync(); } catch { } - } - else - { - await DisconnectClientAsync(clientId, DisconnectReason.Error, socketEx).ConfigureAwait(false); - } - } - catch (Exception exception) - { - DebugConnection($"Error handling TCP client {remoteEndPoint}: {exception.Message}"); - RecordError(exception, $"Error handling TCP client: {exception.Message}", clientId, client.Nickname); - if (!_clients.ContainsKey(clientId)) - { - try { await client.DisposeAsync(); } catch { } - } - else - { - await DisconnectClientAsync(clientId, DisconnectReason.Error, exception).ConfigureAwait(false); - } - } - } - - private static void UpdateLastActive(Connection client) - { - if (client == null) - { - return; - } - - var now = DateTime.UtcNow; - client.LastActive = now; - client.IsIdleTimeoutTriggered = false; - client.LastIdleLogUtc = DateTime.MinValue; - } - - private async Task CleanupTcpClientsAsync(CancellationToken token) - { - while (!token.IsCancellationRequested) - { - try - { - foreach (var kvp in _clients) - { - var client = kvp.Value; - - if (client.IsClosing) - { - continue; - } - - if (!client.IsConnected) - { - DebugConnection($"TCP client {client.Nickname} ({kvp.Key}) detected as disconnected during cleanup, removing."); - await DisconnectClientAsync(kvp.Key, DisconnectReason.RemoteClosed); - continue; - } - - if (_config.IdleTimeoutSeconds > 0 && (DateTime.UtcNow - client.LastActive).TotalSeconds > _config.IdleTimeoutSeconds) - { - DebugConnection($"TCP client {client.Nickname} ({kvp.Key}) idle for more than {_config.IdleTimeoutSeconds} seconds"); - - if (!client.IsIdleTimeoutTriggered) - { - client.IsIdleTimeoutTriggered = true; - OnIdleTimeout?.Invoke(this, new IdleEventArgs(_config.IdleTimeoutSeconds, client, "The client has been idle for too long.")); - } - - await DisconnectClientAsync(kvp.Key, DisconnectReason.Timeout).ConfigureAwait(false); - } - } - } - catch (TaskCanceledException) - { - DebugConnection("CleanupTcpClientsAsync canceled."); - break; - } - catch (Exception exception) - { - DebugConnection($"CleanupTcpClientsAsync error: {exception.Message}"); - OnGeneralError?.Invoke(this, new ErrorEventArgs - { - Exception = exception, - Message = "TCP client cleanup error" - }); - } - - await Task.Delay(TimeSpan.FromSeconds(30), token); - } - } - - private async Task CleanupRateLimitCacheAsync(CancellationToken token) - { - while (!token.IsCancellationRequested) - { - try - { - // Periodically clean up old rate limit entries to prevent memory leaks - Helpers.SecurityValidator.CleanupRateLimitCache(_config.RateLimitCacheCleanupIntervalSeconds); - } - catch (Exception exception) - { - DebugConnection($"Rate limit cache cleanup error: {exception.Message}"); - } - - try - { - await Task.Delay(TimeSpan.FromSeconds(_config.RateLimitCacheCleanupIntervalSeconds), token); - } - catch (OperationCanceledException) - { - break; - } - } - } - - private async Task CleanupUdpClientsAsync(CancellationToken token) - { - while (!token.IsCancellationRequested) - { - foreach (var kvp in _clients) - { - if (_config.IdleTimeoutSeconds > 0 && (DateTime.UtcNow - kvp.Value.LastActive).TotalSeconds > _config.IdleTimeoutSeconds) - { - DebugConnection($"UDP client {kvp.Value.Nickname} ({kvp.Key}) idle for more than {_config.IdleTimeoutSeconds} seconds, disconnecting."); - await DisconnectClientAsync(kvp.Key, DisconnectReason.Timeout); - } - } - await Task.Delay(TimeSpan.FromMilliseconds(500), token); - } - } - - private async Task HandleUdpDataAsync(UdpReceiveResult result) - { - var clientKey = result.RemoteEndPoint.ToString(); - - // Security: Validate UDP packet size - if (result.Buffer.Length <= 0 || result.Buffer.Length > _config.BufferSize) - { - RecordError(null, $"UDP packet size validation failed: {result.Buffer.Length} not in range [1, {_config.BufferSize}]", clientKey, null); - return; - } - - // Security: Rate limiting for UDP packets - if (_config.MaxUdpPacketsPerSecond > 0 && - !Helpers.SecurityValidator.CheckRateLimit(clientKey, _config.MaxUdpPacketsPerSecond)) - { - DebugConnection($"UDP rate limit exceeded for {clientKey}, packet dropped."); - _stats.IncrementDroppedPackets(); - return; - } - - if (!_clients.TryGetValue(clientKey, out var client)) - { - client = new Connection - { - Id = clientKey, - RemoteEndPoint = result.RemoteEndPoint, - ConnectedAt = DateTime.UtcNow - }; - _clients[clientKey] = client; - - _stats.IncrementTotalConnections(); - OnConnected?.Invoke(this, new ConnectionEventArgs { ClientId = clientKey, RemoteEndPoint = result.RemoteEndPoint }); - } - await ProcessReceivedDataAsync(client, result.Buffer); - } - - public void SetSeparator(string separator) => _config.Delimiter = Encoding.UTF8.GetBytes(separator); - - public void SetSeparator(byte[] separator) => _config.Delimiter = separator; - - private async Task HandleClientCommunicationAsync(Connection client) - { - if (client.Stream == null) - { - DebugConnection("Client stream is null at start of communication loop."); - throw new InvalidOperationException("Client stream is null."); - } - - var stream = client.Stream; - var token = client.CancellationToken.Token; - - byte[] readBuffer = ArrayPool.Shared.Rent(_config.BufferSize); - - using var messageStream = new MemoryStream(1024 * 64); - - try - { - while (!token.IsCancellationRequested && client.IsConnected && stream != null) - { - int bytesRead = 0; - - try - { - bytesRead = await stream.ReadAsync(readBuffer, 0, _config.BufferSize, token); - } - catch (IOException ioEx) when (ioEx.InnerException is SocketException socketEx) - { - RecordError(ioEx, $"Socket IO error during read: {socketEx.SocketErrorCode}", client.Id, client.Nickname); - - // Handle socket timeouts and connection resets - if (socketEx.SocketErrorCode == SocketError.TimedOut) - { - DebugConnection($"Read timeout for client {client.Nickname} ({client.Id}), disconnecting."); - await DisconnectClientAsync(client.Id, DisconnectReason.Timeout); - return; - } - else if (socketEx.SocketErrorCode == SocketError.ConnectionReset || - socketEx.SocketErrorCode == SocketError.ConnectionAborted) - { - DebugConnection($"Connection reset/aborted for client {client.Nickname} ({client.Id})."); - await DisconnectClientAsync(client.Id, DisconnectReason.RemoteClosed); - return; - } - throw; - } - catch (SocketException socketEx) - { - RecordError(socketEx, $"Socket error during read: {socketEx.SocketErrorCode}", client.Id, client.Nickname); - DebugConnection($"Socket error during read for client {client.Nickname} ({client.Id}): {socketEx.SocketErrorCode}"); - - if (socketEx.SocketErrorCode == SocketError.TimedOut) - { - await DisconnectClientAsync(client.Id, DisconnectReason.Timeout, socketEx); - return; - } - else if (socketEx.SocketErrorCode == SocketError.ConnectionReset || - socketEx.SocketErrorCode == SocketError.ConnectionAborted) - { - await DisconnectClientAsync(client.Id, DisconnectReason.RemoteClosed, socketEx); - return; - } - throw; - } - - if (bytesRead == 0) - { - DebugConnection($"Client {client.Nickname} disconnected (0 bytes read)."); - await DisconnectClientAsync(client.Id, DisconnectReason.RemoteClosed); - return; - } - - // Security check: Validate message stream doesn't exceed maximum safe size - long newStreamLength = messageStream.Length + bytesRead; - if (_config.MaxMessageStreamSize > 0 && - newStreamLength > _config.MaxMessageStreamSize) - { - DebugConnection($"Message buffer exceeded maximum size ({_config.MaxMessageStreamSize} bytes) for client {client.Nickname} ({client.Id}), disconnecting."); - RecordError(null, $"Message buffer size exceeded for client: {newStreamLength} > {_config.MaxMessageStreamSize}", client.Id, client.Nickname); - await DisconnectClientAsync(client.Id, DisconnectReason.Error); - return; - } - - UpdateLastActive(client); - await messageStream.WriteAsync(readBuffer, 0, bytesRead, token); - - if (_config.MessageFraming == FramingMode.LengthPrefixed) - { - while (TryExtractLengthPrefixedMessage(messageStream, out byte[]? message)) - { - if (client.IsEncrypted && client.AesEncryption != null) - { - message = await AesKeyExchange.DecryptDataAsync(message, message.Length, client.AesEncryption); - } - - await ProcessReceivedDataAsync(client, message); - } - } - else if (_config.MessageFraming == FramingMode.Delimiter) - { - while (TryExtractDelimitedMessage(messageStream, out byte[]? message)) - { - if (client.IsEncrypted && client.AesEncryption != null) - { - message = await AesKeyExchange.DecryptDataAsync(message, message.Length, client.AesEncryption); - } - - await ProcessReceivedDataAsync(client, message); - } - } - else if (_config.MessageFraming == FramingMode.None) - { - var data = messageStream.ToArray(); - messageStream.SetLength(0); - - if (client.IsEncrypted && client.AesEncryption != null) - { - data = await AesKeyExchange.DecryptDataAsync(data, data.Length, client.AesEncryption); - } - - await ProcessReceivedDataAsync(client, data); - } - } - } - catch (OperationCanceledException) - { - DebugConnection($"Communication loop canceled for client {client.Nickname} ({client.Id})."); - // normal shutdown - } - catch (SocketException socketEx) - { - DebugConnection($"Socket error in communication loop for client {client.Nickname} ({client.Id}): {socketEx.SocketErrorCode} - {socketEx.Message}, Disconnecting"); - RecordError(socketEx, $"Socket error in communication loop: {socketEx.SocketErrorCode}", client.Id, client.Nickname); - var reason = socketEx.SocketErrorCode == SocketError.ConnectionReset - || socketEx.SocketErrorCode == SocketError.ConnectionAborted - ? DisconnectReason.RemoteClosed - : DisconnectReason.Error; - await DisconnectClientAsync(client.Id, reason, socketEx); - } - catch (ObjectDisposedException) - { - // Stream was disposed during disconnect - if (client.IsConnected) - { - DebugConnection($"Stream disposed for client {client.Nickname} ({client.Id}) during communication loop, disconnecting client."); - await DisconnectClientAsync(client.Id, DisconnectReason.Error); - } - } - catch (IOException ioEx) when (ioEx.InnerException is SocketException innerSocketEx) - { - DebugConnection($"Socket IO error in communication loop for client {client.Nickname} ({client.Id}): {innerSocketEx.SocketErrorCode} - {ioEx.Message}, Disconnecting"); - RecordError(ioEx, $"Socket IO error in communication loop: {innerSocketEx.SocketErrorCode}", client.Id, client.Nickname); - var reason = innerSocketEx.SocketErrorCode == SocketError.ConnectionReset - || innerSocketEx.SocketErrorCode == SocketError.ConnectionAborted - ? DisconnectReason.RemoteClosed - : DisconnectReason.Error; - await DisconnectClientAsync(client.Id, reason, ioEx); - } - catch (IOException ioEx) - { - DebugConnection($"IO error in communication loop for client {client.Nickname} ({client.Id}): {ioEx.Message}, Disconnecting"); - RecordError(ioEx, $"IO error in communication loop: {ioEx.Message}", client.Id, client.Nickname); - await DisconnectClientAsync(client.Id, DisconnectReason.Error, ioEx); - } - catch (InvalidOperationException invOpEx) when (invOpEx.Message.Contains("Invalid message length")) - { - // Malformed message length - security issue - DebugConnection($"Malformed message length detected for client {client.Nickname} ({client.Id}): {invOpEx.Message}, disconnecting."); - RecordError(invOpEx, $"Malformed message length: {invOpEx.Message}", client.Id, client.Nickname); - await DisconnectClientAsync(client.Id, DisconnectReason.Error); - } - catch (Exception ex) - { - DebugConnection($"Error in communication loop for client {client.Nickname} ({client.Id}): {ex.Message}, Disconnecting"); - RecordError(ex, $"Error in communication loop: {ex.Message}", client.Id, client.Nickname); - await DisconnectClientAsync(client.Id, DisconnectReason.Error, ex); - } - finally - { - ArrayPool.Shared.Return(readBuffer); - } - } - - private bool TryExtractLengthPrefixedMessage(MemoryStream stream, out byte[]? message) - { - message = null; - - var buffer = stream.GetBuffer(); - int length = (int)stream.Length; - - int prefixSize = _config.LengthPrefixedLength; - - if (length < prefixSize) - { - return false; - } - - long messageLengthValue = ParseLengthPrefix(buffer, prefixSize, _config.UseBigEndian); - - // Validate length prefix using SecurityValidator - if (!Helpers.SecurityValidator.ValidateLengthPrefix(messageLengthValue, _config.MAX_MESSAGE_SIZE)) - { - throw new InvalidOperationException($"Invalid message length: {messageLengthValue}. Expected value between 1 and {_config.MAX_MESSAGE_SIZE}."); - } - - int messageLength = (int)messageLengthValue; - - if (length < prefixSize + messageLength) - { - return false; - } - - // Check if message stream would exceed maximum safe size (prevents memory exhaustion attacks) - if (_config.MaxMessageStreamSize > 0 && - length - prefixSize - messageLength > _config.MaxMessageStreamSize) - { - throw new InvalidOperationException($"Message buffer exceeded maximum size of {_config.MaxMessageStreamSize} bytes."); - } - - message = new byte[messageLength]; - Buffer.BlockCopy(buffer, prefixSize, message, 0, messageLength); - - // Slide remaining bytes - int remaining = length - (prefixSize + messageLength); - Buffer.BlockCopy( - buffer, - prefixSize + messageLength, - buffer, - 0, - remaining); - - stream.SetLength(remaining); - - return true; - } - - private static long ParseLengthPrefix(byte[] buffer, int length, bool useBigEndian) - { - long value = 0; - - if (useBigEndian) - { - for (int i = 0; i < length; i++) - { - value = (value << 8) | buffer[i]; - } - } - else - { - for (int i = 0; i < length; i++) - { - value |= (long)buffer[i] << (8 * i); - } - } - - return value; - } - - private bool TryExtractDelimitedMessage(MemoryStream stream, out byte[]? message) - { - message = null; - var delimiter = _config.Delimiter; - - if (delimiter == null || delimiter.Length == 0) - { - return false; - } - - var buffer = stream.GetBuffer(); - int length = (int)stream.Length; - - if (length < delimiter.Length) - { - return false; - } - - int index = IndexOfDelimiter(buffer, length, delimiter); - - if (index < 0) - { - return false; - } - - message = new byte[index]; - Buffer.BlockCopy(buffer, 0, message, 0, index); - - int remaining = length - index - delimiter.Length; - Buffer.BlockCopy(buffer, index + delimiter.Length, buffer, 0, remaining); - stream.SetLength(remaining); - - return true; - } - - private static int IndexOfDelimiter(byte[] buffer, int length, byte[] delimiter) - { - for (int i = 0; i <= length - delimiter.Length; i++) - { - bool match = true; - for (int j = 0; j < delimiter.Length; j++) - { - if (buffer[i + j] != delimiter[j]) - { - match = false; - break; - } - } - if (match) - { - return i; - } - } - return -1; - } - - private void ProcessPingPong(Connection client, ref string message) - { - if (!_config.EnableHeartbeat || string.IsNullOrEmpty(message)) - { - return; - } - - if (message.Contains(Configuration.PING_VALUE)) - { - if (_config.EnablePingPongLogs) - { - OnLog?.Invoke(this, $"[PING] Client {client.Id} PING received at {DateTime.UtcNow:O}, sending pong"); - } - - _ = SendToClientAsync(client.Id, Configuration.PONG_VALUE).ConfigureAwait(false); - message = message.Replace(Configuration.PING_VALUE, string.Empty); - } - - if (message.Contains(Configuration.PONG_VALUE)) - { - if (_config.EnablePingPongLogs) - { - OnLog?.Invoke(this, $"[PING] Client {client.Id} PONG received for PING sent"); - } - - OnClientPingResponse?.Invoke(this, new PingEventArgs - { - Id = client.Id, - Nickname = client.Nickname, - ReceivedTime = DateTime.UtcNow, - RemoteEndPoint = client.RemoteEndPoint - }); - message = message.Replace(Configuration.PONG_VALUE, string.Empty); - } - } - - private async Task ProcessReceivedDataAsync(Connection client, byte[] data) - { - if (client == null || data == null || data.Length == 0) - { - return; - } - - try - { - var now = DateTime.UtcNow; - LastDataReceived = now; - client.LastDataReceived = now; - UpdateLastActive(client); - client.AddBytesReceived(data.Length); - _lastPingTimes[client.Id] = now; - - _stats.AddBytesReceived(data.Length); - _stats.IncrementMessagesReceived(); - - string stringData = null; - bool isBinary = false; - - try - { - int requiredChars = client.Utf8Decoder.GetCharCount(data, 0, data.Length); - if (client.CharBuffer == null || client.CharBuffer.Length < requiredChars) - { - client.CharBuffer = new char[requiredChars]; - } - - int charCount = client.Utf8Decoder.GetChars( - data, - 0, - data.Length, - client.CharBuffer, - 0, - false); - - if (charCount > 0) - { - stringData = new string(client.CharBuffer, 0, charCount); - } - } - catch - { - // If decoding fails, treat as binary - isBinary = true; - stringData = null; - } - - if (!string.IsNullOrEmpty(stringData)) - { - ProcessPingPong(client, ref stringData); - - if (string.IsNullOrEmpty(stringData)) - { - return; - } - } - - if (DEBUG_DATA_RECEIVED) - { - var debug = isBinary - ? $"[DEBUG DATA] Received from {client.Id} ({client.Nickname ?? "NoNickname"}): [binary {data.Length} bytes]" - : $"[DEBUG DATA] Received from {client.Id} ({client.Nickname ?? "NoNickname"}): {stringData}"; - - OnLog?.Invoke(this, debug); - } - - if (!string.IsNullOrEmpty(stringData)) - { - if (stringData.Contains(Configuration.SSL_ERROR_PREFIX, StringComparison.OrdinalIgnoreCase)) - { - string sslError = StringHelper.GetTextBetweenTags(stringData, Configuration.SSL_ERROR_PREFIX, Configuration.SSL_ERROR_SUFFIX); - RecordError(null, $"Client reported SSL error: {sslError}", client.Id, client.Nickname, isSslError: true); - OnSslError?.Invoke(this, new ErrorEventArgs - { - ClientId = client.Id, - Nickname = client.Nickname, - Message = $"Client reported SSL error: {sslError}" - }); - DebugConnection($"[SSL_ERROR] detected from client {client.Id}: {sslError}"); - await DisconnectClientAsync(client.Id, DisconnectReason.SSLError).ConfigureAwait(false); - return; - } - else if (stringData.Contains("[NICKNAME]", StringComparison.OrdinalIgnoreCase)) - { - string nickname = StringHelper.GetTextBetweenTags(stringData, "[NICKNAME]", "[/NICKNAME]"); - HandleNickname(client, nickname); - - stringData = Regex.Replace( - stringData, - "\\[NICKNAME\\].*?\\[/NICKNAME\\]", - string.Empty, - RegexOptions.IgnoreCase | RegexOptions.Singleline); - - if (string.IsNullOrEmpty(stringData)) - { - return; - } - } - else if (stringData.Contains("[DISCONNECT]", StringComparison.OrdinalIgnoreCase)) - { - DebugConnection($"[DISCONNECT] detected, disconnecting client {client.Id}"); - await DisconnectClientAsync(client.Id, DisconnectReason.ClientRequested).ConfigureAwait(false); - return; - } - } - - var eventArgs = new DataReceivedEventArgs - { - ClientId = client.Id, - Nickname = client.Nickname, - RemoteEndPoint = client.RemoteEndPoint, - Data = data, - IsBinary = isBinary, - Timestamp = now - }; - - try - { - OnDataReceived?.Invoke(this, eventArgs); - } - catch (Exception ex) - { - OnGeneralError?.Invoke(this, new ErrorEventArgs - { - ClientId = client.Id, - Nickname = client.Nickname, - Exception = ex, - Message = "Error in OnDataReceived event handler" - }); - } - } - catch (Exception ex) - { - _stats.IncrementDroppedPackets(); - - var handler = client.IsEncrypted ? OnEncryptionError : OnGeneralError; - - handler?.Invoke(this, new ErrorEventArgs - { - ClientId = client.Id, - Nickname = client.Nickname, - Exception = ex, - Message = "Error processing data" - }); - } - } - - private void HandleNickname(Connection client, string nickname) - { - if (!string.IsNullOrWhiteSpace(nickname)) - { - // Only update and fire once per client, and only when nickname actually changes - var previousNickname = client.Nickname; - if (!string.Equals(previousNickname, nickname, StringComparison.Ordinal)) - { - client.Nickname = nickname; - _clients[client.Id] = client; - - OnConnectedWithNickname?.Invoke(this, new ConnectionEventArgs - { - ClientId = client.Id, - RemoteEndPoint = client.RemoteEndPoint, - Nickname = nickname - }); - } - } - } - - public List GetClient(string clientId) - { - var result = new HashSet(); - if (Guid.TryParse(clientId, out _)) - { - if (_clients.TryGetValue(clientId, out var client)) - { - result.Add(client); - } - } - - string[] parts = clientId.Split(':'); - if (parts.Length == 2 && IPAddress.TryParse(parts[0], out IPAddress ip) && int.TryParse(parts[1], out int port)) - { - var endPoint = new IPEndPoint(ip, port); - string clientKey = endPoint.ToString(); - if (_clients.TryGetValue(clientKey, out var client)) - { - result.Add(client); - } - } - - foreach (var kvp in _clients) - { - if (kvp.Value.Nickname != null && kvp.Value.Nickname.Equals(clientId, StringComparison.OrdinalIgnoreCase)) - { - result.Add(kvp.Value); - } - } - return result.ToList(); - } - - public async Task SendToClientAsync(String clientId, byte[] data) - { - var clientList = GetClient(clientId); - - if (clientList == null || clientList.Count == 0) - { - return false; - } - - bool any = false; - - foreach (var client in clientList) - { - if (await SendDataAsync(client, data).ConfigureAwait(false)) - { - any = true; - } - } - return any; - } - - public async Task SendToClientAsync(String clientId, String message) => await SendToClientAsync(clientId, Encoding.UTF8.GetBytes(message)); - - public async Task SendFromClientToClientAsync(String fromClientId, String toClientId, byte[] data) - { - var toClient = GetClient(toClientId); - - if (toClient == null || toClient.Count == 0) - { - return false; - } - - bool any = false; - foreach (var client in toClient) - { - if (await SendDataAsync(client, data).ConfigureAwait(false)) - { - any = true; - } - } - return any; - } - - public async Task SendFromClientToClientAsync(String fromClientId, String toClientId, String message) => await SendFromClientToClientAsync(fromClientId, toClientId, Encoding.UTF8.GetBytes(message)); - - public async Task BroadcastAsync(byte[] data) - { - if (data == null || data.Length == 0) - { - return false; - } - - var clients = _clients.Values.ToArray(); - if (clients.Length == 0) - { - return false; - } - - var tasks = new Task[clients.Length]; - for (int i = 0; i < clients.Length; i++) - { - tasks[i] = SendDataAsync(clients[i], data); - } - - var results = await Task.WhenAll(tasks).ConfigureAwait(false); - return Array.Exists(results, r => r); - } - - public async Task BroadcastAsync(String message) => await BroadcastAsync(Encoding.UTF8.GetBytes(message)); - - public async Task SendToClientAndWaitForResponseAsync(string clientId, byte[] data, TimeSpan? timeout = null) - { - var tcs = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously); - var effectiveTimeout = timeout ?? TimeSpan.FromSeconds(DEFAULT_WAITING_TIMEOUT_IN_SECONDS); - var clientList = GetClient(clientId); - var clientIds = new HashSet(clientList.Select(c => c.Id)); - - void Handler(object sender, DataReceivedEventArgs e) - { - if (clientIds.Contains(e.ClientId)) - { - tcs.TrySetResult(e); - } - } - - OnDataReceived += Handler; - try - { - var sent = await SendToClientAsync(clientId, data).ConfigureAwait(false); - if (!sent) - { - return null; - } - - using var cts = new CancellationTokenSource(effectiveTimeout); - using var registration = cts.Token.Register(() => tcs.TrySetCanceled()); - - try - { - return await tcs.Task.ConfigureAwait(false); - } - catch (OperationCanceledException) - { - return null; - } - } - finally - { - OnDataReceived -= Handler; - } - } - - public async Task SendToClientAndWaitForResponseAsync(string clientId, string message, TimeSpan? timeout = null) - => await SendToClientAndWaitForResponseAsync(clientId, Encoding.UTF8.GetBytes(message), timeout).ConfigureAwait(false); - - public async Task SendFromClientToClientAndWaitForResponseAsync(string fromClientId, string toClientId, byte[] data, TimeSpan? timeout = null) - { - var tcs = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously); - var effectiveTimeout = timeout ?? TimeSpan.FromSeconds(DEFAULT_WAITING_TIMEOUT_IN_SECONDS); - var clientList = GetClient(toClientId); - var clientIds = new HashSet(clientList.Select(c => c.Id)); - - void Handler(object sender, DataReceivedEventArgs e) - { - if (clientIds.Contains(e.ClientId)) - { - tcs.TrySetResult(e); - } - } - - OnDataReceived += Handler; - try - { - var sent = await SendFromClientToClientAsync(fromClientId, toClientId, data).ConfigureAwait(false); - if (!sent) - { - return null; - } - - using var cts = new CancellationTokenSource(effectiveTimeout); - using var registration = cts.Token.Register(() => tcs.TrySetCanceled()); - - try - { - return await tcs.Task.ConfigureAwait(false); - } - catch (OperationCanceledException) - { - return null; - } - } - finally - { - OnDataReceived -= Handler; - } - } - - public async Task SendFromClientToClientAndWaitForResponseAsync(string fromClientId, string toClientId, string message, TimeSpan? timeout = null) - => await SendFromClientToClientAndWaitForResponseAsync(fromClientId, toClientId, Encoding.UTF8.GetBytes(message), timeout).ConfigureAwait(false); - - public async Task> BroadcastAndWaitForResponsesAsync(byte[] data, TimeSpan? timeout = null) - { - var effectiveTimeout = timeout ?? TimeSpan.FromSeconds(DEFAULT_WAITING_TIMEOUT_IN_SECONDS); - var responses = new List(); - var expectedCount = _clients.Count; - - if (expectedCount == 0) - { - return responses; - } - - var tcs = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously); - - void Handler(object sender, DataReceivedEventArgs e) - { - lock (responses) - { - responses.Add(e); - if (responses.Count >= expectedCount) - { - tcs.TrySetResult(true); - } - } - } - - OnDataReceived += Handler; - try - { - var sent = await BroadcastAsync(data).ConfigureAwait(false); - if (!sent) - { - return responses; - } - - using var cts = new CancellationTokenSource(effectiveTimeout); - using var registration = cts.Token.Register(() => tcs.TrySetResult(true)); - - await tcs.Task.ConfigureAwait(false); - return responses; - } - finally - { - OnDataReceived -= Handler; - } - } - - public async Task> BroadcastAndWaitForResponsesAsync(string message, TimeSpan? timeout = null) - => await BroadcastAndWaitForResponsesAsync(Encoding.UTF8.GetBytes(message), timeout).ConfigureAwait(false); - - private async Task SendDataAsync(Connection client, byte[] data) - { - if (client == null || - !client.IsConnected || - data == null || - data.Length == 0) - { - return false; - } - - if (_config.Protocol == ProtocolType.TCP && - (client.Stream == null || !client.Stream.CanWrite)) - { - return false; - } - - byte[] rentedBuffer = null; - int bytesToSend = 0; - - try - { - // Encrypt BEFORE framing so the frame header describes the encrypted payload length - byte[] payloadToFrame = data; - if (client.IsEncrypted && client.AesEncryption != null) - { - payloadToFrame = await AesKeyExchange.EncryptDataAsync(data, data.Length, client.AesEncryption).ConfigureAwait(false); - } - - int framingOverhead = _config.MessageFraming switch - { - FramingMode.LengthPrefixed => _config.LengthPrefixedLength, - FramingMode.Delimiter => _config.Delimiter?.Length ?? 0, - _ => 0 - }; - - int requiredSize = payloadToFrame.Length + framingOverhead; - - if (requiredSize > MAX_BUFFER_MEMORY_IN_KILOBYTES * 1024) - { - throw new InvalidOperationException("Message exceeds maximum allowed buffer size."); - } - - rentedBuffer = ArrayPool.Shared.Rent(requiredSize); - - bytesToSend = BuildMessage(rentedBuffer, payloadToFrame, _config); - - if (_config.Protocol == ProtocolType.TCP) - { - using var cts = CancellationTokenSource.CreateLinkedTokenSource(client.CancellationToken?.Token ?? CancellationToken.None); - cts.CancelAfter(TimeSpan.FromSeconds(_config.WriteTimeoutSeconds)); - - await client.WriteLock.WaitAsync(cts.Token).ConfigureAwait(false); - try - { - if (client.Stream == null || !client.Stream.CanWrite) - { - return false; - } - - await client.Stream.WriteAsync(rentedBuffer, 0, bytesToSend, cts.Token).ConfigureAwait(false); - await client.Stream.FlushAsync(cts.Token).ConfigureAwait(false); - } - finally - { - client.WriteLock.Release(); - } - } - else - { - await _udpLock.WaitAsync().ConfigureAwait(false); - try - { - if (_udpListener == null) - { - return false; - } - - await _udpListener.SendAsync(rentedBuffer, bytesToSend, client.RemoteEndPoint).ConfigureAwait(false); - } - finally - { - _udpLock.Release(); - } - } - - client.LastDataSent = DateTime.UtcNow; - client.AddBytesSent(bytesToSend); - - _stats.AddBytesSent(bytesToSend); - _stats.IncrementMessagesSent(); - - return true; - } - catch (OperationCanceledException ex) - { - DebugConnection($"Write timeout for client {client.Nickname} ({client.Id}): {ex.Message} => disconnecting client"); - RecordError(ex, "Write timeout in send", client.Id, client.Nickname); - await SafeDisconnectAsync(client, DisconnectReason.Timeout).ConfigureAwait(false); - return false; - } - catch (SocketException socketEx) - { - DebugConnection($"Socket error sending data to client {client.Nickname} ({client.Id}): {socketEx.SocketErrorCode} - {socketEx.Message}"); - RecordError(socketEx, $"Socket error in send: {socketEx.SocketErrorCode}", client.Id, client.Nickname); - await SafeDisconnectAsync(client, DisconnectReason.Error).ConfigureAwait(false); - return false; - } - catch (IOException ioEx) when (ioEx.InnerException is SocketException innerSocketEx) - { - DebugConnection($"Socket IO error sending data to client {client.Nickname} ({client.Id}): {innerSocketEx.SocketErrorCode} - {ioEx.Message}"); - RecordError(ioEx, $"Socket IO error in send: {innerSocketEx.SocketErrorCode}", client.Id, client.Nickname); - await SafeDisconnectAsync(client, DisconnectReason.Error).ConfigureAwait(false); - return false; - } - catch (Exception exception) - { - RecordError(exception, $"Error sending data: {exception.Message}", client.Id, client.Nickname); - var handler = client.IsEncrypted ? OnEncryptionError : OnGeneralError; - handler?.Invoke(this, new ErrorEventArgs - { - ClientId = client.Id, - Nickname = client.Nickname, - Exception = exception, - Message = "Error sending data" - }); - - await SafeDisconnectAsync(client, DisconnectReason.Error).ConfigureAwait(false); - return false; - } - finally - { - if (rentedBuffer != null) - { - ArrayPool.Shared.Return(rentedBuffer, clearArray: true); - } - } - } - - private static int BuildMessage(byte[] buffer, byte[] data, Configuration config) - { - int offset = 0; - - switch (config.MessageFraming) - { - case FramingMode.LengthPrefixed: - { - int prefixSize = config.LengthPrefixedLength; - - if (prefixSize < 1 || prefixSize > sizeof(long)) - { - throw new ArgumentOutOfRangeException(nameof(config.LengthPrefixedLength)); - } - - long length = data.Length; - - // Make sure length fits in the chosen prefix size - long maxLength = (1L << (prefixSize * 8)) - 1; - if (length > maxLength) - { - throw new InvalidOperationException("Data length exceeds length prefix capacity."); - } - - if (buffer.Length < offset + prefixSize + data.Length) - { - throw new InvalidOperationException("Buffer too small for length-prefixed message."); - } - - if (config.UseBigEndian) - { - for (int i = prefixSize - 1; i >= 0; i--) - { - buffer[offset + i] = (byte)(length & 0xFF); - length >>= 8; - } - } - else - { - for (int i = 0; i < prefixSize; i++) - { - buffer[offset + i] = (byte)(length & 0xFF); - length >>= 8; - } - } - - offset += prefixSize; - - Array.Copy(data, 0, buffer, offset, data.Length); - offset += data.Length; - break; - } - - case FramingMode.Delimiter: - { - int delimiterLength = config.Delimiter?.Length ?? 0; - - if (buffer.Length < data.Length + delimiterLength) - { - throw new InvalidOperationException("Buffer too small for delimited message."); - } - - Array.Copy(data, 0, buffer, offset, data.Length); - offset += data.Length; - - if (delimiterLength > 0) - { - Array.Copy(config.Delimiter, 0, buffer, offset, delimiterLength); - offset += delimiterLength; - } - - break; - } - - case FramingMode.None: - default: - { - if (buffer.Length < data.Length) - { - throw new InvalidOperationException("Buffer too small for message."); - } - - Array.Copy(data, 0, buffer, offset, data.Length); - offset += data.Length; - break; - } - } - - return offset; - } - - public async Task DisconnectClientAsync(string clientId, DisconnectReason reason = DisconnectReason.Unknown, Exception? exception = null) - { - if (!_clients.TryGetValue(clientId, out var client)) - { - return; - } - - // Always remove from clients dict on first call, even if already marked for disconnection - bool isFirstDisconnect = client.MarkDisconnected(); - _clients.TryRemove(clientId, out _); - _lastPingTimes.TryRemove(clientId, out _); - - if (!isFirstDisconnect) - { - // Already disconnected, skip cleanup - return; - } - - if (reason == DisconnectReason.Error - || reason == DisconnectReason.Timeout - || reason == DisconnectReason.SSLError - || reason == DisconnectReason.NoPongReceived - || reason == DisconnectReason.ProtocolError) - { - _stats.IncrementDroppedConnections(); - } - - client.IsClosing = true; - - try - { - client.DisconnectionTime = DateTime.UtcNow; - -#if NET8_0_OR_GREATER - try - { - await (client.CancellationToken?.CancelAsync() ?? Task.CompletedTask); - } - catch - { - // Do nothing - } -#else - try - { - client.CancellationToken?.Cancel(); - } - catch - { - // Do nothing - } -#endif - - try - { - if (client.Stream != null) - { - try - { - await client.Stream.FlushAsync().ConfigureAwait(false); -#if NET8_0_OR_GREATER - try - { - await client.Stream.DisposeAsync(); - } - catch - { - // Do nothing - } -#else - client.Stream.Close(); - client.Stream.Dispose(); -#endif - } - catch - { - // Do nothing - } - } - - OnDisconnected?.Invoke(this, new ConnectionEventArgs - { - ClientId = clientId, - Nickname = client.Nickname, - RemoteEndPoint = client.RemoteEndPoint, - Reason = reason, - Exception = exception - }); - DebugConnection($"Client disconnected: {client.Nickname} ({client.Id}) from {client.RemoteEndPoint}. Reason: {reason}. Total connections: {ActiveConnections}"); - ForceCloseTcpClient(client.TcpClient); - client.UdpClient?.Close(); - client.UdpClient?.Dispose(); - client.AesEncryption?.Clear(); - client.AesEncryption?.Dispose(); - client.Utf8Decoder.Reset(); - - // Dispose WriteLock - client.WriteLock?.Dispose(); - - // Dispose CancellationTokenSource - client.CancellationToken?.Dispose(); - } - catch - { - // Do nothing - } - } - catch (Exception ex) - { - OnGeneralError?.Invoke(this, new ErrorEventArgs - { - ClientId = clientId, - Nickname = client.Nickname, - Exception = ex, - Message = "Error while disconnecting client" - }); - } - } - - private static void ForceCloseTcpClient(TcpClient? tcpClient) - { - if (tcpClient == null) - { - return; - } - - try - { - tcpClient.Client?.Shutdown(SocketShutdown.Both); - } - catch - { - // Do nothing - } - - try - { - tcpClient.Close(); - } - catch - { - // Do nothing - } - - try - { - tcpClient.Dispose(); - } - catch - { - // Do nothing - } - } - - private async Task SafeDisconnectAsync(Connection client, DisconnectReason reason) - { - if (client != null) - { - try - { - await DisconnectClientAsync(client.Id, reason).ConfigureAwait(false); - } - catch - { - } - } - } - - public void Stop() - { - _ = StopAsync(); - } - - public async Task StopAsync() - { - if (_isStarting) - { - return; - } - - if (Interlocked.CompareExchange(ref _tcpRunning, 0, 1) == 0 && - Interlocked.CompareExchange(ref _udpRunning, 0, 1) == 0) - { - return; - } - -#if NET8_0_OR_GREATER - try - { - await (_serverCancellation?.CancelAsync() ?? Task.CompletedTask); } - catch - { - // Do nothing - } -#else - _serverCancellation?.Cancel(); -#endif - - _tcpListener?.Stop(); - - var clientIds = _clients.Keys.ToList(); - - var disconnectTasks = clientIds - .Select(id => DisconnectClientAsync(id, DisconnectReason.ServerShutdown)) - .ToList(); - - try - { - await Task.WhenAll(disconnectTasks).ConfigureAwait(false); - } - catch - { - // Do nothing - } - - if (_config.Protocol == ProtocolType.TCP) - { - try - { - await StopTcpServerAsync().ConfigureAwait(false); - } - catch - { - // Do nothing - } - } - else if (_config.Protocol == ProtocolType.UDP) - { - try - { - await StopUdpServerAsync().ConfigureAwait(false); - } - catch - { - // Do nothing - } - } - - await AwaitAndDisposeAsync(_tcpTask); - await AwaitAndDisposeAsync(_acceptTcpClientsTask); - await AwaitAndDisposeAsync(_udpTask); - await AwaitAndDisposeAsync(_pingTask); - await AwaitAndDisposeAsync(_pongTask); - await AwaitAndDisposeAsync(_cleanupTask); - - DisposeAndNull(ref _serverCancellation); - _udpLock?.Dispose(); - - StatusPage.StopAutoHtmlReport(); - ServerStatus.StopAutoReport(); - HealthApi.Stop(); - - _tcpListener = null; - _clients.Clear(); - _lastPingTimes.Clear(); - } - - private static async Task AwaitAndDisposeAsync(Task? task) - { - if (task == null) - { - return; - } - - try - { - await task.ConfigureAwait(false); - } - catch - { - // Do nothing - } - - task.Dispose(); - } - - private static void DisposeAndNull(ref T disposable) - where T : class, IDisposable - { - disposable?.Dispose(); - disposable = null; - } - - public void Dispose() - { - _ = StopAsync(); - - ServerStatus.Dispose(); - HealthApi.Dispose(); - - OnConnected = null; - OnDisconnected = null; - OnDataReceived = null; - OnConnectedWithNickname = null; - OnSslError = null; - OnEncryptionError = null; - OnGeneralError = null; - OnClientPingResponse = null; - OnPongMissed = null; - OnSocketError = null; - } - } -} \ No newline at end of file +} diff --git a/EonaCat.Connections/Processors/JsonDataProcessor.cs b/EonaCat.Connections/Processors/JsonDataProcessor.cs index 531afec..fb373c7 100644 --- a/EonaCat.Connections/Processors/JsonDataProcessor.cs +++ b/EonaCat.Connections/Processors/JsonDataProcessor.cs @@ -7,9 +7,6 @@ using System.Timers; public sealed class JsonDataProcessor : IDisposable { - // This file is part of the EonaCat project(s) which is released under the Apache License. - // See the LICENSE file or go to https://EonaCat.com/license for full license details. - private sealed class ClientContext { public JsonChunkParser Parser { get; private set; } @@ -284,7 +281,7 @@ public sealed class JsonDataProcessor : IDisposable } catch { - // prevent user event handlers from breaking the processor + } } @@ -310,4 +307,4 @@ public sealed class JsonDataProcessor : IDisposable OnError = null; OnClientRemovedDueToIdle = null; } -} \ No newline at end of file +} diff --git a/EonaCat.Connections/Protocols/INetworkProtocol.cs b/EonaCat.Connections/Protocols/INetworkProtocol.cs new file mode 100644 index 0000000..d8d33c0 --- /dev/null +++ b/EonaCat.Connections/Protocols/INetworkProtocol.cs @@ -0,0 +1,50 @@ +using System.Net.Sockets; + +namespace EonaCat.Connections.Protocols +{ + + public interface INetworkProtocol : IDisposable + { + + string ProtocolName { get; } + + Task ConnectAsync(string host, int port, CancellationToken cancellationToken); + + Task SendAsync(byte[] data, CancellationToken cancellationToken); + + Task ReceiveAsync(CancellationToken cancellationToken); + + Task DisconnectAsync(CancellationToken cancellationToken); + + bool IsConnected { get; } + + bool CanRead { get; } + + bool CanWrite { get; } + + void ConfigureKeepAlive(bool keepAliveEnabled, int timeInSeconds, int intervalInSeconds, int retryCount); + + void ConfigureSsl(bool useSsl, string? serverName, bool checkCertificateRevocation, bool allowRenegotiation); + + string? GetRemoteEndPoint(); + + string? GetLocalEndPoint(); + + Task CleanupAsync(CancellationToken cancellationToken); + + void ConfigureBufferSize(int bufferSize); + + void ConfigureNagle(bool enableNagle); + + void ConfigureRst(bool enableRst); + + Socket? GetUnderlyingSocket(); + + Stream? GetUnderlyingStream(); + } + + public interface IBroadcastConfigurableProtocol + { + void ConfigureBroadcast(bool enableBroadcast); + } +} diff --git a/EonaCat.Connections/Protocols/ProtocolFactory.cs b/EonaCat.Connections/Protocols/ProtocolFactory.cs new file mode 100644 index 0000000..b548fcf --- /dev/null +++ b/EonaCat.Connections/Protocols/ProtocolFactory.cs @@ -0,0 +1,83 @@ +using EonaCat.Connections.Models; +using System.Collections.Concurrent; + +namespace EonaCat.Connections.Protocols +{ + + public static class ProtocolFactory + { + private static readonly ConcurrentDictionary> _protocols = + new(StringComparer.OrdinalIgnoreCase); + + static ProtocolFactory() + { + + RegisterProtocol("TCP", () => new TcpProtocol()); + RegisterProtocol("UDP", () => new UdpProtocol()); + } + + public static void RegisterProtocol(string name, Func factory) + { + if (string.IsNullOrWhiteSpace(name)) + { + throw new ArgumentException("Protocol name cannot be null or empty", nameof(name)); + } + + if (factory == null) + { + throw new ArgumentNullException(nameof(factory)); + } + + _protocols.AddOrUpdate(name, factory, (_, __) => factory); + } + + public static INetworkProtocol CreateProtocol(string protocolName) + { + if (string.IsNullOrWhiteSpace(protocolName)) + { + throw new ArgumentException("Protocol name cannot be null or empty", nameof(protocolName)); + } + + if (!_protocols.TryGetValue(protocolName, out var factory)) + { + throw new ArgumentException( + $"Protocol '{protocolName}' is not registered. Registered protocols: {string.Join(", ", _protocols.Keys)}", + nameof(protocolName)); + } + + return factory(); + } + + public static INetworkProtocol CreateProtocol(ProtocolType protocolType) + { + return protocolType switch + { + ProtocolType.TCP => CreateProtocol("TCP"), + ProtocolType.UDP => CreateProtocol("UDP"), + _ => throw new ArgumentException($"Unknown protocol type: {protocolType}", nameof(protocolType)) + }; + } + + public static bool IsProtocolRegistered(string protocolName) + { + return !string.IsNullOrWhiteSpace(protocolName) && _protocols.ContainsKey(protocolName); + } + + public static IEnumerable GetRegisteredProtocols() + { + return _protocols.Keys.AsEnumerable(); + } + + public static bool UnregisterProtocol(string protocolName) + { + + if (protocolName?.Equals("TCP", StringComparison.OrdinalIgnoreCase) == true || + protocolName?.Equals("UDP", StringComparison.OrdinalIgnoreCase) == true) + { + return false; + } + + return _protocols.TryRemove(protocolName, out _); + } + } +} diff --git a/EonaCat.Connections/Protocols/TcpProtocol.cs b/EonaCat.Connections/Protocols/TcpProtocol.cs new file mode 100644 index 0000000..0c9cf6e --- /dev/null +++ b/EonaCat.Connections/Protocols/TcpProtocol.cs @@ -0,0 +1,422 @@ +using System.Net.Security; +using System.Net.Sockets; +using System.Runtime.InteropServices; +using System.Security.Authentication; +using System.Security.Cryptography.X509Certificates; + +namespace EonaCat.Connections.Protocols +{ + + public class TcpProtocol : INetworkProtocol + { + private TcpClient? _tcpClient; + private Stream? _stream; + private bool _disposed; + + private bool _keepAliveEnabled; + private int _keepAliveTimeSeconds; + private int _keepAliveIntervalSeconds; + private int _keepAliveRetryCount; + private bool _useSsl; + private string? _sslServerName; + private bool _checkCertificateRevocation; + private bool _allowTlsRenegotiation; + private int _bufferSize = (int)BufferSizeMaximum.ExtraLarge; + private bool _enableNagle; + private bool _enableRst; + + private RemoteCertificateValidationCallback? _certificateValidationCallback; + private X509Certificate2? _clientCertificate; + private X509CertificateCollection? _additionalCertificates; + + public string ProtocolName => "TCP"; + + public bool IsConnected => _tcpClient?.Connected == true && _stream != null && _stream.CanRead && _stream.CanWrite; + + public bool CanRead => _stream?.CanRead == true; + + public bool CanWrite => _stream?.CanWrite == true; + + public TimeSpan ConnectionTimeout { get; set; } + + public TcpProtocol(int connectionTimeout = Timeout.Infinite) + { + ConnectionTimeout = TimeSpan.FromMilliseconds(connectionTimeout); + } + + public async Task ConnectAsync(string host, int port, CancellationToken cancellationToken) + { + if (IsConnected) + { + return true; + } + + await CleanupAsync(cancellationToken); + + try + { + _tcpClient = new TcpClient + { + NoDelay = !_enableNagle, + ReceiveBufferSize = _bufferSize, + SendBufferSize = _bufferSize, + LingerState = new LingerOption(_enableRst, 0) + }; + + if (_keepAliveEnabled) + { + ConfigureSocketKeepAlive(_tcpClient.Client); + } + + var connectCts = CancellationTokenSource.CreateLinkedTokenSource(cancellationToken); + if (ConnectionTimeout.TotalMilliseconds > 0) + { + connectCts.CancelAfter(ConnectionTimeout); + } + +#if NET8_0_OR_GREATER + await _tcpClient.ConnectAsync(host, port, connectCts.Token); +#else + var connectTask = _tcpClient.ConnectAsync(host, port); + var timeoutTask = Task.Delay(Timeout.Infinite, connectCts.Token); + if (await Task.WhenAny(connectTask, timeoutTask) != connectTask) + { + throw new OperationCanceledException("TCP connect timed out."); + } + await connectTask; +#endif + + var networkStream = _tcpClient.GetStream(); + + if (_useSsl) + { + _stream = await CreateSslStreamAsync(networkStream, host, cancellationToken); + } + else + { + _stream = networkStream; + } + + return true; + } + catch (OperationCanceledException) when (cancellationToken.IsCancellationRequested) + { + await CleanupAsync(default); + throw; + } + catch (Exception) + { + await CleanupAsync(default); + throw; + } + } + + public async Task SendAsync(byte[] data, CancellationToken cancellationToken) + { + if (data == null || data.Length == 0) + { + return false; + } + + if (!IsConnected || _stream == null || !_stream.CanWrite) + { + return false; + } + + try + { + await _stream.WriteAsync(data, 0, data.Length, cancellationToken); + await _stream.FlushAsync(cancellationToken); + return true; + } + catch (OperationCanceledException) + { + throw; + } + catch (ObjectDisposedException) + { + return false; + } + catch (Exception) + { + return false; + } + } + + public async Task ReceiveAsync(CancellationToken cancellationToken) + { + if (!IsConnected || _stream == null || !_stream.CanRead) + { + return null; + } + + try + { + var buffer = new byte[_bufferSize]; + int bytesRead = await _stream.ReadAsync(buffer, 0, buffer.Length, cancellationToken); + + if (bytesRead == 0) + { + return null; + } + + if (bytesRead < buffer.Length) + { + Array.Resize(ref buffer, bytesRead); + } + + return buffer; + } + catch (OperationCanceledException) + { + throw; + } + catch (ObjectDisposedException) + { + return null; + } + catch (IOException) + { + return null; + } + catch (Exception) + { + return null; + } + } + + public async Task DisconnectAsync(CancellationToken cancellationToken) + { + await CleanupAsync(cancellationToken); + } + + public async Task CleanupAsync(CancellationToken cancellationToken) + { + try + { + if (_stream != null) + { + try + { + await _stream.FlushAsync(cancellationToken); + } + catch { } + + try + { + _stream.Dispose(); + } + catch { } + + _stream = null; + } + + if (_tcpClient != null) + { + try + { + _tcpClient.Close(); + _tcpClient.Dispose(); + } + catch { } + + _tcpClient = null; + } + } + catch { } + } + + public void ConfigureKeepAlive(bool keepAliveEnabled, int timeInSeconds, int intervalInSeconds, int retryCount) + { + _keepAliveEnabled = keepAliveEnabled; + _keepAliveTimeSeconds = timeInSeconds; + _keepAliveIntervalSeconds = intervalInSeconds; + _keepAliveRetryCount = retryCount; + + if (_tcpClient?.Connected == true) + { + ConfigureSocketKeepAlive(_tcpClient.Client); + } + } + + public void ConfigureSsl(bool useSsl, string? serverName, bool checkCertificateRevocation, bool allowRenegotiation) + { + _useSsl = useSsl; + _sslServerName = serverName; + _checkCertificateRevocation = checkCertificateRevocation; + _allowTlsRenegotiation = allowRenegotiation; + } + + public void ConfigureBufferSize(int bufferSize) + { + if (bufferSize > 0) + { + _bufferSize = bufferSize; + } + } + + public void ConfigureNagle(bool enableNagle) + { + _enableNagle = enableNagle; + if (_tcpClient?.Connected == true) + { + _tcpClient.NoDelay = !enableNagle; + } + } + + public void ConfigureRst(bool enableRst) + { + _enableRst = enableRst; + if (_tcpClient?.Connected == true) + { + _tcpClient.LingerState = new LingerOption(enableRst, 0); + } + } + + public string? GetRemoteEndPoint() + { + return _tcpClient?.Client.RemoteEndPoint?.ToString(); + } + + public string? GetLocalEndPoint() + { + return _tcpClient?.Client.LocalEndPoint?.ToString(); + } + + public Socket? GetUnderlyingSocket() + { + return _tcpClient?.Client; + } + + public Stream? GetUnderlyingStream() + { + return _stream; + } + + public void SetCertificateValidationCallback(RemoteCertificateValidationCallback callback) + { + _certificateValidationCallback = callback; + } + + public void SetClientCertificate(X509Certificate2? certificate) + { + _clientCertificate = certificate; + } + + public void SetAdditionalCertificates(X509CertificateCollection? certificates) + { + _additionalCertificates = certificates; + } + + public void Dispose() + { + if (_disposed) + { + return; + } + + _disposed = true; + try + { + _stream?.Dispose(); + _tcpClient?.Dispose(); + } + catch { } + finally + { + _stream = null; + _tcpClient = null; + } + } + + private void ConfigureSocketKeepAlive(Socket socket) + { + try + { + socket.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.KeepAlive, true); + + if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows)) + { + int keepAliveMs = _keepAliveTimeSeconds * 1000; + int retryIntervalMs = _keepAliveIntervalSeconds * 1000; + + uint[] inOptionValues = new uint[3] + { + 1, + (uint)keepAliveMs, + (uint)retryIntervalMs + }; + + socket.IOControl(IOControlCode.KeepAliveValues, + ConvertUIntArrayToByteArray(inOptionValues), null); + } + } + catch { } + } + + private byte[] ConvertUIntArrayToByteArray(uint[] uintArray) + { + byte[] byteArray = new byte[uintArray.Length * sizeof(uint)]; + Buffer.BlockCopy(uintArray, 0, byteArray, 0, byteArray.Length); + return byteArray; + } + + private async Task CreateSslStreamAsync(NetworkStream networkStream, string host, CancellationToken cancellationToken) + { + var sslStream = new SslStream(networkStream, leaveInnerStreamOpen: true, _certificateValidationCallback); + +#if NET8_0_OR_GREATER + var clientOptions = new SslClientAuthenticationOptions + { + TargetHost = _sslServerName ?? host, + ClientCertificates = _clientCertificate != null ? new X509CertificateCollection { _clientCertificate } : null, + EnabledSslProtocols = SslProtocols.Tls12 | SslProtocols.Tls13, + CertificateRevocationCheckMode = _checkCertificateRevocation ? X509RevocationMode.Online : X509RevocationMode.NoCheck, + AllowRenegotiation = _allowTlsRenegotiation + }; + + if (_additionalCertificates != null) + { + clientOptions.ClientCertificates = _additionalCertificates; + if (_clientCertificate != null && !_additionalCertificates.Contains(_clientCertificate)) + { + if (clientOptions.ClientCertificates == null) + { + clientOptions.ClientCertificates = new X509CertificateCollection(); + } + + clientOptions.ClientCertificates.Add(_clientCertificate); + } + } + + await sslStream.AuthenticateAsClientAsync(clientOptions, cancellationToken); +#else + X509CertificateCollection? certificates = null; + if (_clientCertificate != null) + { + certificates = new X509CertificateCollection { _clientCertificate }; + if (_additionalCertificates != null) + { + certificates.AddRange(_additionalCertificates); + } + } + else if (_additionalCertificates != null) + { + certificates = _additionalCertificates; + } + + var targetHost = _sslServerName ?? host; + if (certificates != null) + { + await sslStream.AuthenticateAsClientAsync(targetHost, certificates, SslProtocols.Tls12 | SslProtocols.Tls13, _checkCertificateRevocation); + } + else + { + await sslStream.AuthenticateAsClientAsync(targetHost, null, SslProtocols.Tls12 | SslProtocols.Tls13, _checkCertificateRevocation); + } +#endif + + return sslStream; + } + } +} diff --git a/EonaCat.Connections/Protocols/UdpProtocol.cs b/EonaCat.Connections/Protocols/UdpProtocol.cs new file mode 100644 index 0000000..0795f25 --- /dev/null +++ b/EonaCat.Connections/Protocols/UdpProtocol.cs @@ -0,0 +1,243 @@ +using System.Net; +using System.Net.Sockets; + +namespace EonaCat.Connections.Protocols +{ + + public class UdpProtocol : INetworkProtocol, IBroadcastConfigurableProtocol + { + private UdpClient? _udpClient; + private IPEndPoint? _remoteEndPoint; + private bool _disposed; + private bool _enableBroadcast; + + private int _bufferSize = (int)BufferSizeMaximum.ExtraLarge; + + public string ProtocolName => "UDP"; + + public bool IsConnected => _udpClient != null; + + public bool CanRead => _udpClient != null; + + public bool CanWrite => _udpClient != null; + + public UdpProtocol() + { + + } + + public async Task ConnectAsync(string host, int port, CancellationToken cancellationToken) + { + if (IsConnected) + { + return true; + } + + await CleanupAsync(cancellationToken); + + try + { + _udpClient = new UdpClient + { + EnableBroadcast = _enableBroadcast, + Client = { ReceiveBufferSize = _bufferSize, SendBufferSize = _bufferSize } + }; + + _udpClient.Connect(host, port); + _remoteEndPoint = _udpClient.Client.RemoteEndPoint as IPEndPoint; + + return true; + } + catch (OperationCanceledException) when (cancellationToken.IsCancellationRequested) + { + await CleanupAsync(default); + throw; + } + catch (Exception) + { + await CleanupAsync(default); + throw; + } + } + + public async Task SendAsync(byte[] data, CancellationToken cancellationToken) + { + if (data == null || data.Length == 0) + { + return false; + } + + if (!IsConnected || _udpClient == null || _remoteEndPoint == null) + { + return false; + } + + try + { +#if NET8_0_OR_GREATER + await _udpClient.SendAsync(data, _remoteEndPoint, cancellationToken); +#else + await _udpClient.SendAsync(data, data.Length, _remoteEndPoint); +#endif + return true; + } + catch (OperationCanceledException) + { + throw; + } + catch (ObjectDisposedException) + { + return false; + } + catch (Exception) + { + return false; + } + } + + public async Task ReceiveAsync(CancellationToken cancellationToken) + { + if (!IsConnected || _udpClient == null) + { + return null; + } + + try + { +#if NET8_0_OR_GREATER + var result = await _udpClient.ReceiveAsync(cancellationToken); + return result.Buffer; +#else + var result = await _udpClient.ReceiveAsync(); + return result.Buffer; +#endif + } + catch (OperationCanceledException) + { + throw; + } + catch (ObjectDisposedException) + { + return null; + } + catch (SocketException) + { + return null; + } + catch (Exception) + { + return null; + } + } + + public async Task DisconnectAsync(CancellationToken cancellationToken) + { + await CleanupAsync(cancellationToken); + } + + public async Task CleanupAsync(CancellationToken cancellationToken) + { + try + { + if (_udpClient != null) + { + try + { + _udpClient.Close(); + _udpClient.Dispose(); + } + catch { } + + _udpClient = null; + } + + _remoteEndPoint = null; + } + catch { } + + await Task.CompletedTask; + } + + public void ConfigureKeepAlive(bool keepAliveEnabled, int timeInSeconds, int intervalInSeconds, int retryCount) + { + + } + + public void ConfigureSsl(bool useSsl, string? serverName, bool checkCertificateRevocation, bool allowRenegotiation) + { + + } + + public void ConfigureBufferSize(int bufferSize) + { + if (bufferSize > 0) + { + _bufferSize = bufferSize; + if (_udpClient?.Client != null) + { + _udpClient.Client.ReceiveBufferSize = bufferSize; + _udpClient.Client.SendBufferSize = bufferSize; + } + } + } + + public void ConfigureNagle(bool enableNagle) + { + + } + + public void ConfigureRst(bool enableRst) + { + + } + + public void ConfigureBroadcast(bool enableBroadcast) + { + _enableBroadcast = enableBroadcast; + if (_udpClient != null) + { + _udpClient.EnableBroadcast = enableBroadcast; + } + } + + public string? GetRemoteEndPoint() + { + return _remoteEndPoint?.ToString(); + } + + public string? GetLocalEndPoint() + { + return _udpClient?.Client.LocalEndPoint?.ToString(); + } + + public Socket? GetUnderlyingSocket() + { + return _udpClient?.Client; + } + + public Stream? GetUnderlyingStream() + { + + return null; + } + + public void Dispose() + { + if (_disposed) + { + return; + } + + _disposed = true; + try + { + _udpClient?.Dispose(); + } + catch { } + finally + { + _udpClient = null; + } + } + } +} diff --git a/EonaCat.Connections/Security/DDoSDetector.cs b/EonaCat.Connections/Security/DDoSDetector.cs new file mode 100644 index 0000000..6880ff5 --- /dev/null +++ b/EonaCat.Connections/Security/DDoSDetector.cs @@ -0,0 +1,264 @@ +namespace EonaCat.Connections.Security +{ + + public class DDoSDetector + { + private class IPConnectionTracking + { + public Queue RecentConnections { get; } = new(); + public int ViolationCount { get; set; } + public DateTime LastViolation { get; set; } + } + + private readonly Dictionary _ipTracking = new(); + private readonly object _lockObj = new object(); + private readonly int _maxConnectionsPerSecond; + private readonly int _spamThreshold; + private readonly int _windowSeconds; + + public long TotalAttacksDetected { get; private set; } + public long ConnectionsBlocked { get; private set; } + + public DDoSDetector(int maxConnectionsPerSecond, int spamThreshold, int windowSeconds) + { + _maxConnectionsPerSecond = maxConnectionsPerSecond; + _spamThreshold = spamThreshold; + _windowSeconds = windowSeconds; + } + + public bool IsConnectionSuspicious(string ipAddress) + { + if (string.IsNullOrEmpty(ipAddress)) + { + return false; + } + + lock (_lockObj) + { + var now = DateTime.UtcNow; + + if (!_ipTracking.TryGetValue(ipAddress, out var tracking)) + { + tracking = new IPConnectionTracking(); + _ipTracking[ipAddress] = tracking; + } + + while (tracking.RecentConnections.Count > 0 && + (now - tracking.RecentConnections.Peek()).TotalSeconds > _windowSeconds) + { + tracking.RecentConnections.Dequeue(); + } + + if (tracking.RecentConnections.Count >= _spamThreshold) + { + tracking.ViolationCount++; + tracking.LastViolation = now; + TotalAttacksDetected++; + ConnectionsBlocked++; + return true; + } + + var connectionsInLastSecond = tracking.RecentConnections + .Count(c => (now - c).TotalSeconds <= 1); + + if (connectionsInLastSecond >= _maxConnectionsPerSecond) + { + tracking.ViolationCount++; + tracking.LastViolation = now; + TotalAttacksDetected++; + ConnectionsBlocked++; + return true; + } + + tracking.RecentConnections.Enqueue(now); + return false; + } + } + + public void RecordConnectionAttempt(string ipAddress) + { + if (string.IsNullOrEmpty(ipAddress)) + { + return; + } + + lock (_lockObj) + { + var now = DateTime.UtcNow; + + if (!_ipTracking.TryGetValue(ipAddress, out var tracking)) + { + tracking = new IPConnectionTracking(); + _ipTracking[ipAddress] = tracking; + } + + while (tracking.RecentConnections.Count > 0 && + (now - tracking.RecentConnections.Peek()).TotalSeconds > _windowSeconds) + { + tracking.RecentConnections.Dequeue(); + } + + tracking.RecentConnections.Enqueue(now); + } + } + + public int GetViolationCount(string ipAddress) + { + lock (_lockObj) + { + if (_ipTracking.TryGetValue(ipAddress, out var tracking)) + { + return tracking.ViolationCount; + } + return 0; + } + } + + public void ResetViolationCount(string ipAddress) + { + lock (_lockObj) + { + if (_ipTracking.TryGetValue(ipAddress, out var tracking)) + { + tracking.ViolationCount = 0; + } + } + } + + public int TrackedIPCount + { + get + { + lock (_lockObj) + { + return _ipTracking.Count; + } + } + } + + public Dictionary GetTrackingSnapshot() + { + lock (_lockObj) + { + return _ipTracking + .Where(x => x.Value.ViolationCount > 0) + .ToDictionary(x => x.Key, x => x.Value.ViolationCount); + } + } + + public void CleanupOldData(int maxAgeSeconds = 3600) + { + lock (_lockObj) + { + var cutoff = DateTime.UtcNow.AddSeconds(-maxAgeSeconds); + var keysToRemove = _ipTracking + .Where(x => x.Value.LastViolation < cutoff && x.Value.RecentConnections.Count == 0) + .Select(x => x.Key) + .ToList(); + + foreach (var key in keysToRemove) + { + _ipTracking.Remove(key); + } + } + } + + public void Reset() + { + lock (_lockObj) + { + _ipTracking.Clear(); + TotalAttacksDetected = 0; + ConnectionsBlocked = 0; + } + } + } + + public class SlowlorisDetector + { + private class ConnectionMetrics + { + public long BytesReceived { get; set; } + public DateTime FirstByteTime { get; set; } + public long ViolationCount { get; set; } + } + + private readonly Dictionary _metrics = new(); + private readonly object _lockObj = new object(); + private readonly int _minBytesPerSecond; + private readonly int _windowSeconds; + + public long TotalSlowlorisDetected { get; private set; } + + public SlowlorisDetector(int minBytesPerSecond, int windowSeconds) + { + _minBytesPerSecond = minBytesPerSecond; + _windowSeconds = windowSeconds; + } + + public bool RecordDataReceived(string connectionId, int bytesReceived) + { + if (string.IsNullOrEmpty(connectionId) || bytesReceived <= 0) + { + return false; + } + + lock (_lockObj) + { + var now = DateTime.UtcNow; + + if (!_metrics.TryGetValue(connectionId, out var metric)) + { + metric = new ConnectionMetrics { FirstByteTime = now }; + _metrics[connectionId] = metric; + } + + metric.BytesReceived += bytesReceived; + + var elapsed = (now - metric.FirstByteTime).TotalSeconds; + + if (elapsed >= _windowSeconds && metric.BytesReceived > 0) + { + var bytesPerSecond = metric.BytesReceived / elapsed; + + if (bytesPerSecond < _minBytesPerSecond) + { + metric.ViolationCount++; + TotalSlowlorisDetected++; + return true; + } + } + + return false; + } + } + + public void RemoveConnection(string connectionId) + { + lock (_lockObj) + { + _metrics.Remove(connectionId); + } + } + + public int TrackedConnectionCount + { + get + { + lock (_lockObj) + { + return _metrics.Count; + } + } + } + + public void Reset() + { + lock (_lockObj) + { + _metrics.Clear(); + TotalSlowlorisDetected = 0; + } + } + } +} diff --git a/EonaCat.Connections/Security/IPBlocklist.cs b/EonaCat.Connections/Security/IPBlocklist.cs new file mode 100644 index 0000000..12fff5c --- /dev/null +++ b/EonaCat.Connections/Security/IPBlocklist.cs @@ -0,0 +1,260 @@ +namespace EonaCat.Connections.Security +{ + + public class IPBlocklist + { + private class BlockedIPEntry + { + public DateTime BlockedAt { get; set; } + public int ViolationCount { get; set; } + public string? Reason { get; set; } + } + + private readonly object _lockObj = new object(); + private readonly HashSet _whitelist = new(); + private readonly HashSet _blacklist = new(); + private readonly Dictionary _blockedIPs = new(); + private readonly int _blockDurationSeconds; + + public long TotalBlocked { get; private set; } + public long TotalAllowed { get; private set; } + + public IPBlocklist(int blockDurationSeconds = 300) + { + _blockDurationSeconds = blockDurationSeconds; + } + + public bool IsIPAllowed(string ipAddress) + { + if (string.IsNullOrEmpty(ipAddress)) + { + return true; + } + + lock (_lockObj) + { + var now = DateTime.UtcNow; + + if (_blockedIPs.TryGetValue(ipAddress, out var blocked)) + { + if ((now - blocked.BlockedAt).TotalSeconds < _blockDurationSeconds) + { + TotalBlocked++; + return false; + } + else + { + _blockedIPs.Remove(ipAddress); + } + } + + if (_blacklist.Contains(ipAddress)) + { + TotalBlocked++; + return false; + } + + if (_whitelist.Count > 0 && !_whitelist.Contains(ipAddress)) + { + TotalBlocked++; + return false; + } + + TotalAllowed++; + return true; + } + } + + public void BlockIP(string ipAddress, string? reason = null) + { + if (string.IsNullOrEmpty(ipAddress)) + { + return; + } + + lock (_lockObj) + { + if (!_blockedIPs.ContainsKey(ipAddress)) + { + _blockedIPs[ipAddress] = new BlockedIPEntry + { + BlockedAt = DateTime.UtcNow, + ViolationCount = 1, + Reason = reason + }; + } + else + { + _blockedIPs[ipAddress].ViolationCount++; + _blockedIPs[ipAddress].BlockedAt = DateTime.UtcNow; + } + } + } + + public void UnblockIP(string ipAddress) + { + if (string.IsNullOrEmpty(ipAddress)) + { + return; + } + + lock (_lockObj) + { + _blockedIPs.Remove(ipAddress); + } + } + + public void AddToBlacklist(string ipAddress) + { + if (string.IsNullOrEmpty(ipAddress)) + { + return; + } + + lock (_lockObj) + { + _blacklist.Add(ipAddress); + } + } + + public void RemoveFromBlacklist(string ipAddress) + { + if (string.IsNullOrEmpty(ipAddress)) + { + return; + } + + lock (_lockObj) + { + _blacklist.Remove(ipAddress); + } + } + + public void AddToWhitelist(string ipAddress) + { + if (string.IsNullOrEmpty(ipAddress)) + { + return; + } + + lock (_lockObj) + { + _whitelist.Add(ipAddress); + } + } + + public void RemoveFromWhitelist(string ipAddress) + { + if (string.IsNullOrEmpty(ipAddress)) + { + return; + } + + lock (_lockObj) + { + _whitelist.Remove(ipAddress); + } + } + + public bool IsWhitelistActive + { + get + { + lock (_lockObj) + { + return _whitelist.Count > 0; + } + } + } + + public int BlockedIPCount + { + get + { + lock (_lockObj) + { + return _blockedIPs.Count; + } + } + } + + public int BlacklistedIPCount + { + get + { + lock (_lockObj) + { + return _blacklist.Count; + } + } + } + + public int WhitelistedIPCount + { + get + { + lock (_lockObj) + { + return _whitelist.Count; + } + } + } + + public Dictionary GetBlockedIPs() + { + lock (_lockObj) + { + return _blockedIPs + .ToDictionary(x => x.Key, + x => (x.Value.ViolationCount, x.Value.Reason)); + } + } + + public HashSet GetBlacklist() + { + lock (_lockObj) + { + return new HashSet(_blacklist); + } + } + + public HashSet GetWhitelist() + { + lock (_lockObj) + { + return new HashSet(_whitelist); + } + } + + public int CleanupExpiredBlocks() + { + lock (_lockObj) + { + var now = DateTime.UtcNow; + var keysToRemove = _blockedIPs + .Where(x => (now - x.Value.BlockedAt).TotalSeconds >= _blockDurationSeconds) + .Select(x => x.Key) + .ToList(); + + foreach (var key in keysToRemove) + { + _blockedIPs.Remove(key); + } + + return keysToRemove.Count; + } + } + + public void Clear() + { + lock (_lockObj) + { + _whitelist.Clear(); + _blacklist.Clear(); + _blockedIPs.Clear(); + TotalBlocked = 0; + TotalAllowed = 0; + } + } + } +} diff --git a/EonaCat.Connections/Security/PayloadValidator.cs b/EonaCat.Connections/Security/PayloadValidator.cs new file mode 100644 index 0000000..8185f46 --- /dev/null +++ b/EonaCat.Connections/Security/PayloadValidator.cs @@ -0,0 +1,359 @@ +using System.Security.Cryptography; +using System.Text; +using EonaCat.Connections.Models; + +namespace EonaCat.Connections.Security +{ + + public class PayloadValidator + { + public long TotalValidated { get; private set; } + public long TotalRejected { get; private set; } + public long TotalNullByteDetected { get; private set; } + public long TotalSizeViolations { get; private set; } + public long TotalEmptyPayloads { get; private set; } + public long TotalSuspiciousContentDetected { get; private set; } + + public bool IsValidSize(long payloadSize, long maxSize) + { + if (maxSize <= 0) + { + return true; + } + + if (payloadSize > maxSize) + { + TotalSizeViolations++; + TotalRejected++; + return false; + } + + TotalValidated++; + return true; + } + + public bool IsNotEmpty(byte[]? payload) + { + if (payload == null || payload.Length == 0) + { + TotalEmptyPayloads++; + TotalRejected++; + return false; + } + + TotalValidated++; + return true; + } + + public bool ContainsNullBytes(byte[]? payload) + { + if (payload == null || payload.Length == 0) + { + return false; + } + + for (int i = 0; i < payload.Length; i++) + { + if (payload[i] == 0) + { + TotalNullByteDetected++; + TotalRejected++; + return true; + } + } + + return false; + } + + public bool TryValidatePayload(byte[]? payload, SecurityOptions? securityOptions, out string? rejectionReason) + { + rejectionReason = null; + + if (securityOptions == null) + { + return true; + } + + if (securityOptions.ValidateMessageNotEmpty && !IsNotEmpty(payload)) + { + rejectionReason = "payload is empty"; + return false; + } + + if (securityOptions.EnablePayloadValidation && !IsValidSize(payload?.Length ?? 0, securityOptions.MaxPayloadSize)) + { + rejectionReason = $"payload exceeds the configured maximum size of {securityOptions.MaxPayloadSize} bytes"; + return false; + } + + if (securityOptions.BlockNullBytePayloads && ContainsNullBytes(payload)) + { + rejectionReason = "payload contains null bytes"; + return false; + } + + if (securityOptions.EnableSuspiciousContentDetection && payload is { Length: > 0 }) + { + try + { + var text = new UTF8Encoding(false, true).GetString(payload); + if (ContainsSuspiciousSqlPatterns(text)) + { + rejectionReason = "payload contains a suspicious SQL pattern"; + } + else if (ContainsSuspiciousXssPatterns(text)) + { + rejectionReason = "payload contains a suspicious script pattern"; + } + else if (ContainsPathTraversal(text)) + { + rejectionReason = "payload contains a path traversal pattern"; + } + + if (rejectionReason != null) + { + TotalSuspiciousContentDetected++; + return false; + } + } + catch (DecoderFallbackException) + { + // This detector is for text protocols; preserve arbitrary binary payloads. + } + } + + return true; + } + + public bool IsValidHttpRequest(byte[]? payload) + { + if (payload == null || payload.Length == 0) + { + return false; + } + + try + { + + var text = Encoding.UTF8.GetString(payload, 0, Math.Min(payload.Length, 100)); + + return text.StartsWith("GET ") || + text.StartsWith("POST ") || + text.StartsWith("PUT ") || + text.StartsWith("DELETE ") || + text.StartsWith("PATCH ") || + text.StartsWith("HEAD ") || + text.StartsWith("OPTIONS ") || + text.StartsWith("TRACE "); + } + catch + { + return false; + } + } + + public string ComputePayloadHash(byte[]? payload) + { + if (payload == null || payload.Length == 0) + { + return string.Empty; + } + + using (var sha = SHA256.Create()) + { + var hash = sha.ComputeHash(payload); + return Convert.ToBase64String(hash); + } + } + + public bool ContainsSuspiciousSqlPatterns(string? payload) + { + if (string.IsNullOrEmpty(payload)) + { + return false; + } + + var suspicious = new[] { + "'; DROP", + "' OR '", + "1=1", + "UNION SELECT", + "exec(", + "execute(", + "--", + "/*", + "*/", + "xp_", + "sp_" + }; + + var upperPayload = payload.ToUpperInvariant(); + + foreach (var pattern in suspicious) + { + if (upperPayload.Contains(pattern)) + { + TotalRejected++; + return true; + } + } + + return false; + } + + public bool ContainsSuspiciousXssPatterns(string? payload) + { + if (string.IsNullOrEmpty(payload)) + { + return false; + } + + var suspicious = new[] { + " _requestHashes = new(); + private readonly object _lockObj = new object(); + private readonly int _windowSeconds; + public long TotalDuplicatesDetected { get; private set; } + + public RequestDeduplicator(int windowSeconds) + { + _windowSeconds = windowSeconds; + } + + public bool IsDuplicate(string hash) + { + if (string.IsNullOrEmpty(hash)) + { + return false; + } + + lock (_lockObj) + { + var now = DateTime.UtcNow; + + var keysToRemove = new List(); + foreach (var kvp in _requestHashes) + { + if ((now - kvp.Value.Timestamp).TotalSeconds > _windowSeconds) + { + keysToRemove.Add(kvp.Key); + } + } + + foreach (var key in keysToRemove) + { + _requestHashes.Remove(key); + } + + if (_requestHashes.TryGetValue(hash, out var entry)) + { + entry.Count++; + TotalDuplicatesDetected++; + return true; + } + else + { + _requestHashes[hash] = new HashEntry + { + Timestamp = now, + Count = 1 + }; + return false; + } + } + } + + public int TrackedHashCount + { + get + { + lock (_lockObj) + { + return _requestHashes.Count; + } + } + } + + public void Clear() + { + lock (_lockObj) + { + _requestHashes.Clear(); + TotalDuplicatesDetected = 0; + } + } + } +} diff --git a/EonaCat.Connections/Security/RateLimiter.cs b/EonaCat.Connections/Security/RateLimiter.cs new file mode 100644 index 0000000..5450fab --- /dev/null +++ b/EonaCat.Connections/Security/RateLimiter.cs @@ -0,0 +1,216 @@ +using System.Collections.Concurrent; +using EonaCat.Connections.Helpers; + +namespace EonaCat.Connections.Security +{ + + public class RateLimiter + { + private long _tokensAsLong; + private long _lastRefillTicks; + private readonly long _tokensPerSecondAsLong; + private long _totalAllowed; + private long _totalRejected; + private readonly long _maxTokens; + + public RateLimiter(long tokensPerSecond) + { + _tokensPerSecondAsLong = tokensPerSecond * 1000; + _maxTokens = _tokensPerSecondAsLong * 2; + _tokensAsLong = _tokensPerSecondAsLong; + _lastRefillTicks = DateTime.UtcNow.Ticks; + } + + public bool TryConsumeTokens(long tokenCost = 1000) + { + if (tokenCost <= 0) + { + throw new ArgumentException("Token cost must be positive"); + } + + tokenCost = Math.Min(tokenCost, _tokensPerSecondAsLong); + + while (true) + { + + var now = DateTime.UtcNow.Ticks; + var lastRefill = Interlocked.Read(ref _lastRefillTicks); + var elapsedTicks = now - lastRefill; + var elapsedSeconds = elapsedTicks / (double)TimeSpan.TicksPerSecond; + + var tokensToAdd = (long)(elapsedSeconds * _tokensPerSecondAsLong); + + var currentTokens = Interlocked.Read(ref _tokensAsLong); + var newRefillTicks = now; + + var tokensAfterRefill = Math.Min(currentTokens + tokensToAdd, _maxTokens); + + if (tokensAfterRefill >= tokenCost) + { + + var newTokens = tokensAfterRefill - tokenCost; + + if (Interlocked.CompareExchange(ref _tokensAsLong, newTokens, currentTokens) == currentTokens) + { + Interlocked.Exchange(ref _lastRefillTicks, newRefillTicks); + Interlocked.Increment(ref _totalAllowed); + return true; + } + + } + else + { + + Interlocked.CompareExchange(ref _lastRefillTicks, newRefillTicks, lastRefill); + Interlocked.Increment(ref _totalRejected); + return false; + } + } + } + + public double GetTokenCount() + { + var tokens = Interlocked.Read(ref _tokensAsLong); + return tokens / 1000.0; + } + + public (long Allowed, long Rejected) GetStats() + { + return (Interlocked.Read(ref _totalAllowed), Interlocked.Read(ref _totalRejected)); + } + + public void Reset() + { + Interlocked.Exchange(ref _tokensAsLong, _tokensPerSecondAsLong); + Interlocked.Exchange(ref _lastRefillTicks, DateTime.UtcNow.Ticks); + Interlocked.Exchange(ref _totalAllowed, 0); + Interlocked.Exchange(ref _totalRejected, 0); + } + } + + public class PerConnectionRateLimiter + { + private readonly ConcurrentDictionary _limiters; + private readonly long _tokensPerSecond; + private readonly int _cleanupIntervalSeconds; + private DateTime _lastCleanup = DateTime.UtcNow; + private volatile bool _cleanupInProgress; + + public int LimiterCount => _limiters.Count; + + public PerConnectionRateLimiter(long tokensPerSecond = 1000, int cleanupIntervalSeconds = 300) + { + _tokensPerSecond = tokensPerSecond; + _cleanupIntervalSeconds = cleanupIntervalSeconds; + _limiters = new ConcurrentDictionary( + Environment.ProcessorCount * 2, + 128); + } + + public bool TryConsumeToken(string connectionId, long tokenCost = 1000) + { + if (string.IsNullOrEmpty(connectionId)) + { + return false; + } + + var entry = _limiters.GetOrAdd(connectionId, + _ => (new RateLimiter(_tokensPerSecond), DateTime.UtcNow)); + + var allowed = entry.Limiter.TryConsumeTokens(tokenCost); + + if ((DateTime.UtcNow - _lastCleanup).TotalSeconds > _cleanupIntervalSeconds && + !_cleanupInProgress) + { + _cleanupInProgress = true; + HandlingHelpers.SafeFireAndForgetTaskAsync(CleanupAsync, "RateLimiter.CleanupAsync"); + } + + return allowed; + } + + private async Task CleanupAsync() + { + try + { + var now = DateTime.UtcNow; + var timeout = TimeSpan.FromMinutes(10); + + foreach (var kvp in _limiters) + { + if (now - kvp.Value.CreatedAt > timeout) + { + _limiters.TryRemove(kvp.Key, out _); + } + } + } + finally + { + _lastCleanup = DateTime.UtcNow; + _cleanupInProgress = false; + } + } + + public bool RemoveLimiter(string connectionId) + { + return _limiters.TryRemove(connectionId, out _); + } + + public void Clear() + { + _limiters.Clear(); + } + + public (long Allowed, long Rejected, double CurrentTokens) GetStats(string connectionId) + { + if (_limiters.TryGetValue(connectionId, out var entry)) + { + var (allowed, rejected) = entry.Limiter.GetStats(); + var tokens = entry.Limiter.GetTokenCount(); + return (allowed, rejected, tokens); + } + return (0, 0, 0); + } + } + + public class GlobalRateLimiter + { + private readonly RateLimiter _rateLimiter; + private volatile bool _disposed; + + public GlobalRateLimiter(long tokensPerSecond) + { + _rateLimiter = new RateLimiter(tokensPerSecond); + } + + public bool TryConsumeToken(long tokenCost = 1000) + { + if (_disposed) + { + throw new ObjectDisposedException(nameof(GlobalRateLimiter)); + } + + return _rateLimiter.TryConsumeTokens(tokenCost); + } + + public double GetTokenCount() + { + return _rateLimiter.GetTokenCount(); + } + + public (long Allowed, long Rejected) GetStats() + { + return _rateLimiter.GetStats(); + } + + public void Reset() + { + _rateLimiter.Reset(); + } + + public void Dispose() + { + _disposed = true; + } + } +} diff --git a/EonaCat.Connections/Server/NetworkServer.ClientRegistry.cs b/EonaCat.Connections/Server/NetworkServer.ClientRegistry.cs new file mode 100644 index 0000000..cd4faa6 --- /dev/null +++ b/EonaCat.Connections/Server/NetworkServer.ClientRegistry.cs @@ -0,0 +1,217 @@ +using EonaCat.Connections.EventArguments; +using EonaCat.Connections.Helpers; +using EonaCat.Connections.Models; +using System.Net; +using System.Net.Sockets; + +namespace EonaCat.Connections +{ + public partial class NetworkServer + { + private void HandleNickname(Connection client, string nickname) + { + if (!string.IsNullOrWhiteSpace(nickname)) + { + + var previousNickname = client.Nickname; + if (!string.Equals(previousNickname, nickname, StringComparison.Ordinal)) + { + if (!string.IsNullOrEmpty(previousNickname)) + { + + if (_nicknameToClientIds.TryGetValue(previousNickname, out var previousSet)) + { + previousSet.Remove(client.Id); + + if (previousSet.Count == 0) + { + _nicknameToClientIds.TryRemove(previousNickname, out _); + } + } + } + + client.Nickname = nickname; + _clients[client.Id] = client; + + _nicknameToClientIds.AddOrUpdate(nickname, + new HashSet { client.Id }, + (key, existingSet) => + { + existingSet.Add(client.Id); + return existingSet; + }); + + HandlingHelpers.SafeInvokeEventHandler( + OnConnectedWithNickname, + this, + new ConnectionEventArgs + { + ClientId = client.Id, + RemoteEndPoint = client.RemoteEndPoint, + Nickname = nickname + }, + nameof(OnConnectedWithNickname), + msg => RecordError(null, msg)); + } + } + } + + public List GetClient(string clientId) + { + var result = new Dictionary(StringComparer.OrdinalIgnoreCase); + Action addClient = delegate (string key) + { + if (_clients.TryGetValue(key, out Connection client)) + { + if (!result.ContainsKey(client.Id)) + { + result.Add(client.Id, client); + } + } + }; + + addClient(clientId); + + if (TryParseEndpoint(clientId, out string host, out int port)) + { + if (string.Equals(host, "localhost", StringComparison.OrdinalIgnoreCase)) + { + + addClient(new IPEndPoint(IPAddress.Loopback, port).ToString()); + addClient(new IPEndPoint(IPAddress.IPv6Loopback, port).ToString()); + } + else + { + if (IPAddress.TryParse(host, out IPAddress ip)) + { + addClient(new IPEndPoint(ip, port).ToString()); + } + else + { + try + { + foreach (IPAddress address in Dns.GetHostAddresses(host)) + { + addClient(new IPEndPoint(address, port).ToString()); + } + } + catch (SocketException) + { + + } + } + } + } + + if (_nicknameToClientIds.TryGetValue(clientId, out var nicknameClientIds)) + { + foreach (var nicknameClientId in nicknameClientIds) + { + addClient(nicknameClientId); + } + } + + foreach (KeyValuePair pair in _clients) + { + Connection currentClient = pair.Value; + + if (string.Equals(currentClient.Nickname, clientId, StringComparison.OrdinalIgnoreCase)) + { + if (!result.ContainsKey(currentClient.Id)) + { + result.Add(currentClient.Id, currentClient); + } + } + } + + var connectedClients = new List(); + foreach (KeyValuePair pair in result) + { + Connection client = pair.Value; + + if (IsConnected(client)) + { + connectedClients.Add(client); + } + else + { + RemoveClient(pair.Key, client); + } + } + return connectedClients; + } + + private static bool TryParseEndpoint(string value, out string host, out int port) + { + host = string.Empty; + port = 0; + + if (string.IsNullOrWhiteSpace(value)) + { + return false; + } + + value = value.Trim(); + + if (value.StartsWith("[")) + { + int closingBracket = value.IndexOf(']'); + if (closingBracket <= 0 || closingBracket + 1 >= value.Length || value[closingBracket + 1] != ':') + { + return false; + } + + host = value.Substring(1, closingBracket - 1); + string portString = value.Substring(closingBracket + 2); + + return int.TryParse(portString, out port) && port >= 0 && port <= 65535; + } + + int separator = value.LastIndexOf(':'); + + if (separator <= 0 || separator == value.Length - 1) + { + return false; + } + + host = value.Substring(0, separator); + string portValue = value.Substring(separator + 1); + return int.TryParse(portValue, out port) && port >= 0 && port <= 65535; + } + + private void RemoveClient(string key, Connection client) + { + if (client != null) + { + _clients.TryRemove(key, out _); + if (!string.IsNullOrEmpty(client.Nickname)) + { + + if (_nicknameToClientIds.TryGetValue(client.Nickname, out var nicknameSet)) + { + nicknameSet.Remove(client.Id); + + if (nicknameSet.Count == 0) + { + _nicknameToClientIds.TryRemove(client.Nickname, out _); + } + } + } + _udpClientOrigin.TryRemove(key, out _); + } + } + + private bool IsConnected(Connection client) + { + if (client == null) + { + return false; + } + if (_clients.TryGetValue(client.Id, out var existingClient)) + { + return existingClient.IsConnected; + } + return false; + } + } +} diff --git a/EonaCat.Connections/Server/NetworkServer.Diagnostics.cs b/EonaCat.Connections/Server/NetworkServer.Diagnostics.cs new file mode 100644 index 0000000..b90124c --- /dev/null +++ b/EonaCat.Connections/Server/NetworkServer.Diagnostics.cs @@ -0,0 +1,55 @@ +using EonaCat.Connections.Models; +using System.Diagnostics; +using System.Net.Sockets; +using ErrorEventArgs = EonaCat.Connections.EventArguments.ErrorEventArgs; + +namespace EonaCat.Connections +{ + public partial class NetworkServer + { + private void DebugConnection(string debugText) + { + if (!_config.EnableConnectionDebugLogs) + { + return; + } + OnLog?.Invoke(this, new LogMessage { Type = LogType.Debug, Message = $"[NetworkServer] {debugText}" }); + } + + private void RecordError(Exception exception, string message, string clientId = null, string nickname = null, bool isSslError = false) + { + var socketEx = exception as SocketException + ?? (exception as IOException)?.InnerException as SocketException; + + var entry = new SocketErrorEntry + { + Timestamp = DateTime.UtcNow, + Source = "Server", + ClientId = clientId, + Nickname = nickname, + SocketErrorCode = socketEx?.SocketErrorCode, + ErrorCode = socketEx != null ? socketEx.SocketErrorCode.ToString() : exception?.GetType().Name, + Message = message, + ExceptionType = exception?.GetType().FullName, + StackTrace = exception?.StackTrace, + Exception = exception, + IsSslError = isSslError + }; + + StatusPage.AddError(entry); + + if (socketEx != null) + { + OnSocketError?.Invoke(this, new ErrorEventArgs + { + ClientId = clientId, + Nickname = nickname, + Exception = exception, + Message = $"SocketError {socketEx.SocketErrorCode}: {message}" + }); + } + } + + + } +} diff --git a/EonaCat.Connections/Server/NetworkServer.Heartbeat.cs b/EonaCat.Connections/Server/NetworkServer.Heartbeat.cs new file mode 100644 index 0000000..13ebed7 --- /dev/null +++ b/EonaCat.Connections/Server/NetworkServer.Heartbeat.cs @@ -0,0 +1,141 @@ +using EonaCat.Connections.EventArguments; +using EonaCat.Connections.Helpers; +using EonaCat.Connections.Models; +using ErrorEventArgs = EonaCat.Connections.EventArguments.ErrorEventArgs; + +namespace EonaCat.Connections +{ + public partial class NetworkServer + { + private async Task StartPongLoopAsync(CancellationToken token) + { + while (!token.IsCancellationRequested) + { + try + { + var now = DateTime.UtcNow; + var timeout = _config.HeartbeatIntervalSeconds * 2; + + var pingTimes = _lastPingTimes.ToList(); + var toRemove = new List(); + + foreach (var pings in pingTimes) + { + var clientId = pings.Key; + var lastPong = pings.Value; + + if (!_clients.TryGetValue(clientId, out var client)) + { + toRemove.Add(clientId); + continue; + } + + if (!client.IsConnected) + { + await DisconnectClientAsync(clientId, DisconnectReason.RemoteClosed); + continue; + } + + var elapsed = (now - lastPong).TotalSeconds; + + if (elapsed > timeout) + { + if (_config.EnablePingPongLogs) + { + OnLog?.Invoke(this, new LogMessage { Type = LogType.Debug, Message = $"Client '{client.Nickname}' no PONG for {elapsed:F1}s, disconnect." }); + } + + OnPongMissed?.Invoke(this, new PingEventArgs + { + Id = client.Id, + Nickname = client.Nickname, + ReceivedTime = now, + RemoteEndPoint = client.RemoteEndPoint + }); + + if (_config.DisconectOnMissedPong) + { + DebugConnection($"Disconnecting client {client.Nickname} ({client.Id}) due to missed PONG response."); + _ = DisconnectClientAsync(clientId, DisconnectReason.NoPongReceived); + } + } + + if (elapsed > _config.HeartbeatIntervalSeconds * 4) + { + toRemove.Add(clientId); + } + } + + foreach (var remove in toRemove) + { + _lastPingTimes.TryRemove(remove, out _); + } + + await Task.Delay(TimeSpan.FromSeconds(1), token); + } + catch (TaskCanceledException) + { + DebugConnection("Pong loop canceled."); + break; + } + catch (Exception exception) + { + DebugConnection($"StartPongLoopAsync: Error checking pong responses for {_config.Host}:{_config.Port}: {exception.Message}"); + HandlingHelpers.SafeInvokeEventHandler( + OnGeneralError, + this, + new ErrorEventArgs + { + Exception = exception, + Message = "Pong loop error" + }, + nameof(OnGeneralError)); + } + } + } + + private async Task StartPingLoopAsync(CancellationToken token) + { + while (!token.IsCancellationRequested) + { + try + { + var clients = _clients.Values.ToList(); + var pingTasks = new List(clients.Count); + + foreach (var client in clients) + { + if (!client.IsConnected || client.IsClosing) + { + continue; + } + + pingTasks.Add(SendToClientAsync(client.Id, Configuration.PING_VALUE)); + } + + if (pingTasks.Count > 0) + { + await Task.WhenAll(pingTasks).ConfigureAwait(false); + } + + await Task.Delay(TimeSpan.FromSeconds(_config.HeartbeatIntervalSeconds), token).ConfigureAwait(false); + } + catch (TaskCanceledException) + { + DebugConnection("Ping loop canceled."); + break; + } + catch (Exception exception) + { + DebugConnection($"StartPingLoopAsync: Error sending ping to {_config.Host}:{_config.Port}: {exception.Message}"); + RecordError(exception, $"Ping loop error: {exception.Message}"); + OnGeneralError?.Invoke(this, new ErrorEventArgs + { + Exception = exception, + Message = "Ping loop error" + }); + } + } + } + } +} diff --git a/EonaCat.Connections/Server/NetworkServer.Lifecycle.cs b/EonaCat.Connections/Server/NetworkServer.Lifecycle.cs new file mode 100644 index 0000000..0bb7457 --- /dev/null +++ b/EonaCat.Connections/Server/NetworkServer.Lifecycle.cs @@ -0,0 +1,525 @@ +using EonaCat.Connections.EventArguments; +using EonaCat.Connections.Helpers; +using EonaCat.Connections.Models; +using EonaCat.Connections.ConnectionDiagnostics; +using System.Net.Sockets; +using ErrorEventArgs = EonaCat.Connections.EventArguments.ErrorEventArgs; +using ProtocolType = EonaCat.Connections.Models.ProtocolType; + +namespace EonaCat.Connections +{ + public partial class NetworkServer + { + public async Task WaitForClientAsync( + string clientId, + TimeSpan? timeout = null, + CancellationToken cancellationToken = default) + { + if (string.IsNullOrWhiteSpace(clientId) || cancellationToken.IsCancellationRequested) + { + return null; + } + + if (_clients.TryGetValue(clientId, out var existingClient)) + { + return existingClient; + } + + var completion = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously); + EventHandler handler = (_, args) => + { + if (string.Equals(args.ClientId, clientId, StringComparison.Ordinal) && + _clients.TryGetValue(clientId, out var connectedClient)) + { + completion.TrySetResult(connectedClient); + } + }; + OnConnected += handler; + + try + { + if (_clients.TryGetValue(clientId, out existingClient)) + { + completion.TrySetResult(existingClient); + } + + using var timeoutSource = timeout.HasValue + ? new CancellationTokenSource(timeout.Value) + : new CancellationTokenSource(); + using var linkedSource = CancellationTokenSource.CreateLinkedTokenSource(timeoutSource.Token, cancellationToken); + using var registration = linkedSource.Token.Register(() => completion.TrySetResult(null)); + return await completion.Task.ConfigureAwait(false); + } + finally + { + OnConnected -= handler; + } + } + + public Task StartAsync() + { + if (_isStarting) + { + return Task.CompletedTask; + } + + _isStarting = true; + try + { + _serverCancellation?.Dispose(); + _serverCancellation = new CancellationTokenSource(); + + if (_config.Protocol == ProtocolType.TCP) + { + _tcpTask = Task.Run(() => StartTcpServerAsync(), _serverCancellation.Token); + _cleanupTask = Task.Run(() => CleanupTcpClientsAsync(_serverCancellation.Token), _serverCancellation.Token); + } + else + { + _udpTask = Task.Run(() => StartUdpServerAsync(_serverCancellation.Token), _serverCancellation.Token); + } + + if (_config.EnableHeartbeat) + { + _pingTask = Task.Run(() => StartPingLoopAsync(_serverCancellation.Token), _serverCancellation.Token); + _pongTask = Task.Run(() => StartPongLoopAsync(_serverCancellation.Token), _serverCancellation.Token); + } + + if (_config.EnableAutoHtmlReports) + { + StatusPage.StartAutoHtmlReport( + _config.HtmlReportOutputDirectory, + _config.HtmlReportIntervalSeconds, + "status-server-errors.html"); + } + + if (_config.EnableServerStatusPage) + { + ServerStatus.StartAutoReport( + _config.HtmlReportOutputDirectory, + _config.ServerStatusPageIntervalSeconds, + "status-server.html"); + } + + } + finally + { + _isStarting = false; + } + + return Task.CompletedTask; + } + public async Task DisconnectClientAsync(string clientId, DisconnectReason reason = DisconnectReason.Unknown, Exception? exception = null) + { + if (!_clients.TryGetValue(clientId, out var client)) + { + return; + } + + bool isFirstDisconnect = client.MarkDisconnected(); + _clients.TryRemove(clientId, out _); + _lastPingTimes.TryRemove(clientId, out _); + _udpClientOrigin.TryRemove(clientId, out _); + + if (!string.IsNullOrEmpty(client.Nickname)) + { + + if (_nicknameToClientIds.TryGetValue(client.Nickname, out var nicknameSet)) + { + nicknameSet.Remove(client.Id); + + if (nicknameSet.Count == 0) + { + _nicknameToClientIds.TryRemove(client.Nickname, out _); + } + } + } + + if (!isFirstDisconnect) + { + + return; + } + + if (reason == DisconnectReason.Error + || reason == DisconnectReason.Timeout + || reason == DisconnectReason.SSLError + || reason == DisconnectReason.NoPongReceived + || reason == DisconnectReason.ProtocolError) + { + _stats.IncrementDroppedConnections(); + } + + client.IsClosing = true; + + try + { + client.DisconnectionTime = DateTime.UtcNow; + +#if NET8_0_OR_GREATER + try + { + await (client.CancellationToken?.CancelAsync() ?? Task.CompletedTask); + } + catch + { + + } +#else + try + { + client.CancellationToken?.Cancel(); + } + catch + { + + } +#endif + + try + { + if (client.Stream != null) + { + try + { + await client.Stream.FlushAsync().ConfigureAwait(false); +#if NET8_0_OR_GREATER + try + { + await client.Stream.DisposeAsync(); + } + catch + { + + } +#else + client.Stream.Close(); + client.Stream.Dispose(); +#endif + } + catch + { + + } + } + + var initiator = DisconnectionDiagnostics.DetermineInitiator(reason, exception); + var reasonDetails = DisconnectionDiagnostics.GetDetailedReasonDescription(reason, exception); + var connectionDuration = client.ConnectedAt != default(DateTime) + ? new TimeSpan?(DateTime.UtcNow - client.ConnectedAt) + : null; + + var diagnosticContext = new Dictionary(); + 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["TotalConnections"] = ActiveConnections.ToString(); + diagnosticContext["IsLocalInitiated"] = initiator == "Local" ? "true" : "false"; + + var connectionEventArgs = new ConnectionEventArgs + { + ClientId = clientId, + Nickname = client.Nickname, + RemoteEndPoint = client.RemoteEndPoint, + Reason = reason, + Exception = exception, + Initiator = initiator, + ReasonDetails = reasonDetails, + ConnectionDuration = connectionDuration, + DiagnosticContext = diagnosticContext + }; + + try + { + var serverLogger = ConnectionLogManager.GetServerLogger(); + var localEndPoint = client.TcpClient?.Client?.LocalEndPoint?.ToString() ?? + client.UdpClient?.Client?.LocalEndPoint?.ToString() ?? + "[Unknown]"; + serverLogger.LogDisconnection( + clientId, + client.Nickname, + client.RemoteEndPoint?.ToString() ?? "[Unknown]", + localEndPoint, + reason.ToString(), + initiator, + exception, + diagnosticContext + ); + } + catch (Exception logEx) + { + + System.Diagnostics.Debug.WriteLine($"Failed to log disconnection: {logEx.Message}"); + } + + HandlingHelpers.SafeInvokeEventHandler( + OnDisconnected, + this, + connectionEventArgs, + nameof(OnDisconnected), + msg => RecordError(null, msg)); + DebugConnection($"Client disconnected: {client.Nickname} ({client.Id}) from {client.RemoteEndPoint}. Reason: {reason}. Initiator: {initiator}. Total connections: {ActiveConnections}"); + ForceCloseTcpClient(client.TcpClient); + client.UdpClient?.Close(); + client.UdpClient?.Dispose(); + client.AesEncryption?.Clear(); + client.AesEncryption?.Dispose(); + client.Utf8Decoder.Reset(); + + client.WriteLock?.Dispose(); + + client.CancellationToken?.Dispose(); + } + catch (Exception ex) + { + OnGeneralError?.Invoke(this, new ErrorEventArgs + { + ClientId = clientId, + Nickname = client.Nickname, + Exception = ex, + Message = "Error while disconnecting client" + }); + } + } + catch (Exception ex) + { + OnGeneralError?.Invoke(this, new ErrorEventArgs + { + ClientId = clientId, + Nickname = client.Nickname, + Exception = ex, + Message = "Error while disconnecting client" + }); + } + } + + private static void ForceCloseTcpClient(TcpClient? tcpClient) + { + if (tcpClient == null) + { + return; + } + + try + { + tcpClient.Client?.Shutdown(SocketShutdown.Both); + } + catch + { + + } + + try + { + tcpClient.Close(); + } + catch + { + + } + + try + { + tcpClient.Dispose(); + } + catch + { + + } + } + + private async Task SafeDisconnectAsync(Connection client, DisconnectReason reason) + { + if (client != null) + { + try + { + await DisconnectClientAsync(client.Id, reason).ConfigureAwait(false); + } + catch + { + } + } + } + + public void Stop() + { + _ = StopAsync(); + } + + public async Task StopAsync() + { + if (_isStarting) + { + return; + } + + var wasTcpRunning = Interlocked.Exchange(ref _tcpRunning, 0) == 1; + var wasUdpRunning = Interlocked.Exchange(ref _udpRunning, 0) == 1; + + if (!wasTcpRunning && !wasUdpRunning) + { + return; + } + +#if NET8_0_OR_GREATER + try + { + await (_serverCancellation?.CancelAsync() ?? Task.CompletedTask); + } + catch + { + + } +#else + _serverCancellation?.Cancel(); +#endif + + List tcpListenersSnapshot; + lock (_tcpListeners) + { + tcpListenersSnapshot = _tcpListeners.ToList(); + _tcpListeners.Clear(); + } + + foreach (var listener in tcpListenersSnapshot) + { + try { listener.Stop(); } catch { } + } + + var clientIds = _clients.Keys.ToList(); + + var disconnectTasks = clientIds + .Select(id => DisconnectClientAsync(id, DisconnectReason.ServerShutdown)) + .ToList(); + + try + { + await Task.WhenAll(disconnectTasks).ConfigureAwait(false); + } + catch + { + + } + + if (wasTcpRunning) + { + try + { + await StopTcpServerAsync().ConfigureAwait(false); + } + catch + { + + } + } + + if (wasUdpRunning) + { + try + { + await StopUdpServerAsync().ConfigureAwait(false); + } + catch + { + + } + } + + await AwaitAndDisposeAsync(_tcpTask); + + List acceptTasksSnapshot; + lock (_acceptTcpClientsTasks) + { + acceptTasksSnapshot = _acceptTcpClientsTasks.ToList(); + _acceptTcpClientsTasks.Clear(); + } + foreach (var acceptTask in acceptTasksSnapshot) + { + await AwaitAndDisposeAsync(acceptTask); + } + + await AwaitAndDisposeAsync(_udpTask); + await AwaitAndDisposeAsync(_pingTask); + await AwaitAndDisposeAsync(_pongTask); + await AwaitAndDisposeAsync(_cleanupTask); + + DisposeAndNull(ref _serverCancellation); + + StatusPage.StopAutoHtmlReport(); + ServerStatus.StopAutoReport(); + HealthApi.Stop(); + + _clients.Clear(); + _nicknameToClientIds.Clear(); + _lastPingTimes.Clear(); + _udpClientOrigin.Clear(); + } + + private static async Task AwaitAndDisposeAsync(Task? task) + { + if (task == null) + { + return; + } + + try + { + await task.ConfigureAwait(false); + } + catch + { + + } + + task.Dispose(); + } + + private static void DisposeAndNull(ref T disposable) + where T : class, IDisposable + { + disposable?.Dispose(); + disposable = null; + } + + public void Dispose() + { + _ = StopAsync(); + + try + { + ServerStatus?.Dispose(); + } + catch + { + + } + + try + { + HealthApi?.Dispose(); + } + catch + { + + } + + OnConnected = null; + OnDisconnected = null; + OnDataReceived = null; + OnConnectedWithNickname = null; + OnSslError = null; + OnEncryptionError = null; + OnGeneralError = null; + OnClientPingResponse = null; + OnPongMissed = null; + OnSocketError = null; + } + } +} diff --git a/EonaCat.Connections/Server/NetworkServer.Listeners.cs b/EonaCat.Connections/Server/NetworkServer.Listeners.cs new file mode 100644 index 0000000..bdaf5db --- /dev/null +++ b/EonaCat.Connections/Server/NetworkServer.Listeners.cs @@ -0,0 +1,903 @@ +using System.Diagnostics; +using EonaCat.Connections.EventArguments; +using EonaCat.Connections.Helpers; +using EonaCat.Connections.Infrastructure; +using EonaCat.Connections.Models; +using System.Buffers; +using System.Net; +using System.Net.Security; +using System.Net.Sockets; +using System.Security.Authentication; +using System.Security.Cryptography; +using System.Security.Cryptography.X509Certificates; +using System.Text; +using ErrorEventArgs = EonaCat.Connections.EventArguments.ErrorEventArgs; + +namespace EonaCat.Connections +{ + public partial class NetworkServer + { + private async Task> ResolveHostAddressesAsync(string host, CancellationToken token) + { + Exception? lastError = null; + + for (int attempt = 1; attempt <= DNS_RESOLVE_MAX_ATTEMPTS; attempt++) + { + try + { + var resolved = await Dns.GetHostAddressesAsync(host).ConfigureAwait(false); + + if (resolved == null || resolved.Length == 0) + { + throw new InvalidOperationException($"DNS returned no addresses for host '{host}'."); + } + + if (!_config.EnableDualStack) + { + var v4 = resolved.FirstOrDefault(a => a.AddressFamily == AddressFamily.InterNetwork); + return new List { v4 ?? resolved[0] }; + } + + return resolved + .GroupBy(a => a.AddressFamily) + .Select(g => g.First()) + .ToList(); + } + catch (Exception ex) when (ex is not OperationCanceledException) + { + lastError = ex; + DebugConnection($"DNS resolution attempt {attempt}/{DNS_RESOLVE_MAX_ATTEMPTS} for '{host}' failed: {ex.Message}"); + + if (attempt < DNS_RESOLVE_MAX_ATTEMPTS) + { + await Task.Delay(TimeSpan.FromSeconds(attempt), token).ConfigureAwait(false); + } + } + } + + throw new InvalidOperationException($"Could not resolve host '{host}' after {DNS_RESOLVE_MAX_ATTEMPTS} attempts.", lastError); + } + + private static bool IsWildcardHost(string? host) + { + return string.IsNullOrWhiteSpace(host) + || host == "*" + || host == "0.0.0.0" + || host == "::"; + } + + private async Task> CreateTcpListenersAsync(CancellationToken token) + { + var host = _config.Host; + var listeners = new List(); + + if (IsWildcardHost(host)) + { + if (_config.EnableDualStack) + { + var listener = new TcpListener(IPAddress.IPv6Any, _config.Port); + listener.Server.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ReuseAddress, true); + try + { + + listener.Server.DualMode = true; + } + catch (Exception ex) + { + DebugConnection($"DualMode not supported on this platform for TCP wildcard listener, falling back to IPv6-only: {ex.Message}"); + } + listeners.Add(listener); + } + else + { + var listener = new TcpListener(IPAddress.Any, _config.Port); + listener.Server.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ReuseAddress, true); + listeners.Add(listener); + } + + return listeners; + } + + if (IPAddress.TryParse(host, out var literal)) + { + var listener = new TcpListener(literal, _config.Port); + listener.Server.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ReuseAddress, true); + listeners.Add(listener); + return listeners; + } + + var addresses = await ResolveHostAddressesAsync(host, token).ConfigureAwait(false); + + foreach (var address in addresses) + { + var listener = new TcpListener(address, _config.Port); + listener.Server.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ReuseAddress, true); + listeners.Add(listener); + } + + return listeners; + } + + private async Task> CreateUdpListenersAsync(CancellationToken token) + { + var host = _config.Host; + var entries = new List(); + + if (IsWildcardHost(host)) + { + if (_config.EnableDualStack) + { + var client = new UdpClient(AddressFamily.InterNetworkV6); + try + { + client.Client.DualMode = true; + } + catch (Exception ex) + { + DebugConnection($"DualMode not supported on this platform for UDP wildcard listener, falling back to IPv6-only: {ex.Message}"); + } + client.Client.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ReuseAddress, true); + client.Client.Bind(new IPEndPoint(IPAddress.IPv6Any, _config.Port)); + entries.Add(new UdpListenerEntry { Client = client, LocalEndPoint = (IPEndPoint)client.Client.LocalEndPoint! }); + } + else + { + var client = new UdpClient(new IPEndPoint(IPAddress.Any, _config.Port)); + entries.Add(new UdpListenerEntry { Client = client, LocalEndPoint = (IPEndPoint)client.Client.LocalEndPoint! }); + } + + return entries; + } + + if (IPAddress.TryParse(host, out var literal)) + { + var client = new UdpClient(new IPEndPoint(literal, _config.Port)); + entries.Add(new UdpListenerEntry { Client = client, LocalEndPoint = (IPEndPoint)client.Client.LocalEndPoint! }); + return entries; + } + + var addresses = await ResolveHostAddressesAsync(host, token).ConfigureAwait(false); + + foreach (var address in addresses) + { + var client = new UdpClient(new IPEndPoint(address, _config.Port)); + entries.Add(new UdpListenerEntry { Client = client, LocalEndPoint = (IPEndPoint)client.Client.LocalEndPoint! }); + } + + return entries; + } + + private static string FormatTcpListenerAddress(TcpListener listener) + { + return (listener.LocalEndpoint as IPEndPoint)?.ToString() ?? "unknown"; + } + + public Task StartTcpServerAsync() + { + if (Interlocked.CompareExchange(ref _tcpRunning, 1, 0) == 1) + { + return Task.CompletedTask; + } + + lock (_acceptTcpClientsTasks) + { + _acceptTcpClientsTasks.Clear(); + _acceptTcpClientsTasks.Add(Task.Run(() => BindAndAcceptTcpAsync(_serverCancellation.Token), _serverCancellation.Token)); + } + + return Task.CompletedTask; + } + + private async Task BindAndAcceptTcpAsync(CancellationToken token) + { + List listeners; + + try + { + listeners = await CreateTcpListenersAsync(token).ConfigureAwait(false); + + foreach (var listener in listeners) + { + listener.Start(); + Console.WriteLine($"EonaCat TCP Server started on {FormatTcpListenerAddress(listener)}"); + } + + if (_config.EnableHealthApi) + { + HealthApi.StartSharedPort(((IPEndPoint)listeners[0].LocalEndpoint).Port); + } + } + catch (Exception ex) + { + DebugConnection($"Failed to start TCP listener(s) on {_config.Host}:{_config.Port}: {ex.Message}"); + RecordError(ex, $"Failed to start TCP listener(s) on {_config.Host}:{_config.Port}"); + OnGeneralError?.Invoke(this, new ErrorEventArgs + { + Exception = ex, + Message = "TCP listener failed to start" + }); + Interlocked.Exchange(ref _tcpRunning, 0); + return; + } + + lock (_tcpListeners) + { + _tcpListeners.AddRange(listeners); + } + + var acceptTasks = listeners.Select(l => AcceptClientsAsync(l, token)).ToArray(); + + try + { + await Task.WhenAll(acceptTasks).ConfigureAwait(false); + } + catch + { + + } + } + + private async Task AcceptClientsAsync(TcpListener listener, CancellationToken token) + { + while (!token.IsCancellationRequested) + { + try + { + if (token.IsCancellationRequested) + { + DebugConnection("Cancellation requested, stopping accept loop."); + break; + } + + TcpClient tcpClient = await listener.AcceptTcpClientAsync().ConfigureAwait(false); + + var clientIp = (tcpClient.Client.RemoteEndPoint as IPEndPoint)?.Address.ToString() ?? "unknown"; + + if (_ipBlocklist != null && !_ipBlocklist.IsIPAllowed(clientIp)) + { + tcpClient.Close(); + tcpClient.Dispose(); + _stats.IncrementDroppedConnections(); + if (_config.Security?.EnableSecurityLogging == true) + { + OnLog?.Invoke(this, new LogMessage { Type = LogType.Debug, Message = $"TCP connection blocked by IP filter: {clientIp}" }); + } + continue; + } + + if (_ddosDetector != null && _ddosDetector.IsConnectionSuspicious(clientIp)) + { + tcpClient.Close(); + tcpClient.Dispose(); + _stats.IncrementDroppedConnections(); + if (_config.Security?.EnableSecurityLogging == true) + { + OnLog?.Invoke(this, new LogMessage { Type = LogType.Debug, Message = $"TCP connection blocked by DDoS detection: {clientIp}" }); + } + continue; + } + + _ = HandlingHelpers.SafeFireAndForgetTaskAsync(() => HandleTcpClientAsync(tcpClient), "HandleTcpClient", message => RecordError(null, message)); + } + catch (ObjectDisposedException) + { + DebugConnection("TCP listener disposed, stopping accept loop."); + break; + } + catch (SocketException ex) when (ex.SocketErrorCode == SocketError.Interrupted || ex.SocketErrorCode == SocketError.OperationAborted) + { + DebugConnection($"TCP listener interrupted, stopping accept loop: {ex.Message}"); + RecordError(ex, $"TCP listener interrupted: {ex.SocketErrorCode}"); + break; + } + catch (SocketException ex) + { + DebugConnection($"Socket error in accept loop: {ex.Message}"); + RecordError(ex, $"Socket error in accept loop: {ex.SocketErrorCode}"); + OnLog?.Invoke(this, new LogMessage { Type = LogType.Error, Message = $"Socket error in accept loop: {ex.Message}" }); + await Task.Delay(100, token).ConfigureAwait(false); + } + catch (OperationCanceledException) + { + DebugConnection("Accept loop canceled."); + break; + } + catch (Exception ex) + { + DebugConnection($"Unexpected error in accept loop: {ex.Message}"); + RecordError(ex, $"Unexpected error in accept loop: {ex.Message}"); + OnLog?.Invoke(this, new LogMessage { Type = LogType.Error, Message = $"Unexpected error in accept loop: {ex.Message}" }); + await Task.Delay(100, token).ConfigureAwait(false); + } + } + } + + public async Task StopTcpServerAsync() + { + await StopAsync().ConfigureAwait(false); + } + + public Dictionary GetClients() + { + return _clients.ToDictionary(kvp => kvp.Key, kvp => kvp.Value); + } + + public async Task StartUdpServerAsync(CancellationToken token) + { + if (Interlocked.CompareExchange(ref _udpRunning, 1, 0) == 1) + { + Console.WriteLine("EonaCat UDP Server is already running."); + return; + } + + List entries; + + try + { + entries = await CreateUdpListenersAsync(token).ConfigureAwait(false); + + if (_config.EnableHealthApi) + { + HealthApi.Start(entries[0].LocalEndPoint.Port, _config.HealthApiBindAddress); + } + } + catch (Exception ex) + { + DebugConnection($"Failed to start UDP listener(s) on {_config.Host}:{_config.Port}: {ex.Message}"); + RecordError(ex, $"Failed to start UDP listener(s) on {_config.Host}:{_config.Port}"); + OnGeneralError?.Invoke(this, new ErrorEventArgs + { + Exception = ex, + Message = "UDP listener failed to start" + }); + Interlocked.Exchange(ref _udpRunning, 0); + return; + } + + lock (_udpListeners) + { + _udpListeners.AddRange(entries); + } + + foreach (var entry in entries) + { + Console.WriteLine($"EonaCat UDP Server started on {entry.LocalEndPoint}"); + } + + try + { + var receiveTasks = entries.Select(e => ReceiveUdpLoopAsync(e, token)).ToArray(); + await Task.WhenAll(receiveTasks).ConfigureAwait(false); + } + finally + { + DebugConnection("UDP server stopping, closing listener(s) and disconnecting clients."); + await StopUdpServerAsync(); + } + } + + private async Task ReceiveUdpLoopAsync(UdpListenerEntry entry, CancellationToken token) + { + while (!token.IsCancellationRequested) + { + try + { + UdpReceiveResult result; + + UdpClient udpReceiveClient; + await entry.Lock.WaitAsync(token).ConfigureAwait(false); + try + { + if (entry.Client == null) + { + break; + } + + udpReceiveClient = entry.Client; + } + finally + { + entry.Lock.Release(); + } + + result = await udpReceiveClient.ReceiveAsync().ConfigureAwait(false); + + _ = HandlingHelpers.SafeFireAndForgetTaskAsync( + () => HandleUdpDataAsync(result, entry), + "HandleUdpData", + msg => RecordError(null, msg)); + } + catch (ObjectDisposedException) + { + DebugConnection("UDP listener disposed, stopping receive loop."); + break; + } + catch (SocketException exception) when (exception.SocketErrorCode == SocketError.Interrupted) + { + DebugConnection("UDP listener interrupted, stopping receive loop."); + RecordError(exception, $"UDP listener interrupted: {exception.SocketErrorCode}"); + break; + } + catch (SocketException exception) + { + DebugConnection($"Socket error receiving UDP data: {exception.SocketErrorCode} - {exception.Message}"); + RecordError(exception, $"Socket error receiving UDP data: {exception.SocketErrorCode}"); + OnGeneralError?.Invoke(this, new ErrorEventArgs + { + Exception = exception, + Message = $"UDP receive socket error: {exception.SocketErrorCode}" + }); + } + catch (OperationCanceledException) + { + DebugConnection("UDP receive loop canceled."); + break; + } + catch (Exception exception) + { + DebugConnection($"Error receiving UDP data: {exception.Message}"); + RecordError(exception, $"Error receiving UDP data: {exception.Message}"); + OnGeneralError?.Invoke(this, new ErrorEventArgs + { + Exception = exception, + Message = "Error receiving UDP data" + }); + } + } + } + + private async Task StopUdpServerAsync() + { + List entries; + + lock (_udpListeners) + { + entries = _udpListeners.ToList(); + _udpListeners.Clear(); + } + + foreach (var entry in entries) + { + await entry.Lock.WaitAsync().ConfigureAwait(false); + try + { + entry.Client?.Close(); + entry.Client?.Dispose(); + entry.Client = null; + } + finally + { + entry.Lock.Release(); + } + } + + _udpClientOrigin.Clear(); + Interlocked.Exchange(ref _udpRunning, 0); + } + + private void ConfigureSocketOptions(Socket socket) + { + if (socket == null) + { + return; + } + + try + { + + if (_config.ReadTimeoutSeconds > 0) + { + socket.ReceiveTimeout = (int)(_config.ReadTimeoutSeconds * 1000); + } + + if (_config.WriteTimeoutSeconds > 0) + { + socket.SendTimeout = (int)(_config.WriteTimeoutSeconds * 1000); + } + + socket.LingerState = new LingerOption(_config.EnableRST, 0); + + socket.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.DontLinger, !_config.EnableRST); + + socket.ReceiveBufferSize = _config.BufferSize; + socket.SendBufferSize = _config.BufferSize; + + DebugConnection($"Socket options configured: ReceiveTimeout={_config.ReadTimeoutSeconds}s, SendTimeout={_config.WriteTimeoutSeconds}s, Linger={_config.EnableRST}"); + } + catch (Exception ex) + { + DebugConnection($"Error configuring socket options: {ex.Message}"); + } + } + + private async Task HandleHealthRequestAsync(TcpClient tcpClient, Connection client, Stream stream) + { + using var timeout = CancellationTokenSource.CreateLinkedTokenSource(_serverCancellation.Token); + timeout.CancelAfter(TimeSpan.FromSeconds(5)); + using var registration = timeout.Token.Register(tcpClient.Close); + var bindAddress = _config.HealthApiBindAddress ?? IPAddress.Loopback; + var localAddress = ((IPEndPoint)tcpClient.Client.LocalEndPoint).Address; + var allowAccess = bindAddress.Equals(IPAddress.Any) || bindAddress.Equals(IPAddress.IPv6Any) + || bindAddress.MapToIPv6().Equals(localAddress.MapToIPv6()); + try + { + await HealthApi.HandleRequestAsync(stream, allowAccess).ConfigureAwait(false); + } + catch (Exception) + { + } + finally + { + await client.DisposeAsync().ConfigureAwait(false); + } + } + + private async Task HandleTcpClientAsync(TcpClient tcpClient) + { + var clientId = Guid.NewGuid().ToString(); + var remoteEndPoint = tcpClient.Client.RemoteEndPoint as IPEndPoint ?? new IPEndPoint(IPAddress.None, 0); + var client = new Connection + { + Id = clientId, + TcpClient = tcpClient, + RemoteEndPoint = remoteEndPoint, + ConnectedAt = DateTime.UtcNow, + LastActive = DateTime.UtcNow, + CancellationToken = new CancellationTokenSource(), + + OutgoingRateLimiter = _config.Security.EnablePerConnectionRateLimiting ? new Security.RateLimiter(100) : null + }; + + UpdateLastActive(client); + + try + { + tcpClient.NoDelay = !_config.EnableNagle; + + ConfigureSocketOptions(tcpClient.Client); + + if (_config.EnableKeepAlive) + { + SocketKeepAliveConfigurator.Configure(tcpClient.Client, _config.KeepAliveTimeSeconds, _config.KeepAliveIntervalSeconds, _config.KeepAliveRetryCount); + } + + Stream stream = tcpClient.GetStream(); + var clientCertificateValidated = false; + + if (stream is NetworkStream networkStream) + { + if (_config.ReadTimeoutSeconds > 0) + { + networkStream.ReadTimeout = (int)(_config.ReadTimeoutSeconds * 1000); + } + + if (_config.WriteTimeoutSeconds > 0) + { + networkStream.WriteTimeout = (int)(_config.WriteTimeoutSeconds * 1000); + } + DebugConnection($"Set stream timeouts: Read={_config.ReadTimeoutSeconds}s, Write={_config.WriteTimeoutSeconds}s for {remoteEndPoint}"); + } + + if (_config.UseSsl) + { + if (_config.EnableHealthApi) + { + var probe = new ProtocolProbeStream(stream); + stream = probe; + client.Stream = stream; + if (await probe.IsHttpAsync(_serverCancellation.Token).ConfigureAwait(false)) + { + await HandleHealthRequestAsync(tcpClient, client, stream).ConfigureAwait(false); + return; + } + } + + if (_config.Certificate == null) + { + var certEx = new InvalidOperationException("SSL is enabled but no server certificate is configured."); + RecordError(certEx, "SSL is enabled but no server certificate is configured.", clientId, client.Nickname, isSslError: true); + OnSslError?.Invoke(this, new ErrorEventArgs + { + ClientId = clientId, + Nickname = client.Nickname, + Exception = certEx, + Message = "SSL is enabled but no server certificate is configured." + }); + try { await client.DisposeAsync(); } catch { } + return; + } + + bool sslAuthenticated = false; + var sslDiagnostics = _config.EnableSslDiagnostics ? new Helpers.SslHandshakeDiagnostics() : null; + + for (int attempt = 1; attempt <= _config.SSLMaxRetries || _config.SSLMaxRetries == 0; attempt++) + { + SslStream? sslStream = null; + + try + { + sslDiagnostics?.StartHandshake(remoteEndPoint.ToString(), _config.MutuallyAuthenticate); + + var validateCertificate = _config.GetRemoteCertificateValidationCallback(); + sslStream = new SslStream(stream, leaveInnerStreamOpen: true, + (sender, certificate, chain, errors) => + { + clientCertificateValidated = certificate != null + && validateCertificate(sender, certificate, chain, errors); + return certificate == null + ? _config.EnableHealthApi || !_config.MutuallyAuthenticate + : clientCertificateValidated; + }); + +#if NET8_0_OR_GREATER + var serverOptions = new SslServerAuthenticationOptions + { + ServerCertificate = _config.Certificate, + ClientCertificateRequired = _config.MutuallyAuthenticate, + EnabledSslProtocols = SslProtocols.Tls12 | SslProtocols.Tls13, + CertificateRevocationCheckMode = _config.CheckCertificateRevocation ? X509RevocationMode.Online : X509RevocationMode.NoCheck, + AllowRenegotiation = _config.AllowTlsRenegotiation + }; + DebugConnection($"Starting SSL authentication for {remoteEndPoint}, attempt {attempt}."); + + sslDiagnostics?.StartStage("ServerAuth"); + await sslStream.AuthenticateAsServerAsync(serverOptions, CancellationToken.None).ConfigureAwait(false); + sslDiagnostics?.EndStage("ServerAuth"); + + DebugConnection($"SSL authentication successful for {remoteEndPoint} on attempt {attempt}."); +#else + sslDiagnostics?.StartStage("ServerAuth"); + await sslStream.AuthenticateAsServerAsync(_config.Certificate, _config.MutuallyAuthenticate, SslProtocols.Tls12 | SslProtocols.Tls13, _config.CheckCertificateRevocation).ConfigureAwait(false); + sslDiagnostics?.EndStage("ServerAuth"); +#endif + + stream = sslStream; + client.IsSecure = true; + sslAuthenticated = true; + + sslDiagnostics?.RecordSuccess(sslStream); + if (sslDiagnostics != null) + { + DebugConnection($"[SSL Metrics] {sslDiagnostics}"); + } + break; + } + catch (IOException ioException) when (ioException.Message.Contains("0 bytes from the transport stream") || ioException.Message.Contains("Unexpected EOF")) + { + var isRecoverable = Helpers.SslHandshakeDiagnostics.IsRecoverableFailure(ioException); + sslDiagnostics?.RecordFailure(ioException, isRecoverable); + + RecordError(ioException, "SSL handshake failed due to EOF", clientId, client.Nickname, isSslError: true); + OnSslError?.Invoke(this, new ErrorEventArgs + { + ClientId = clientId, + Nickname = client.Nickname, + Exception = ioException, + Message = "SSL handshake failed due to EOF" + }); + DebugConnection($"SSL handshake EOF from {remoteEndPoint} on attempt {attempt}: {ioException.Message}"); + OnLog?.Invoke(this, new LogMessage { Type = LogType.Warning, Message = $"SSL handshake EOF from {remoteEndPoint}. Attempt {attempt}" }); + } + catch (AuthenticationException authException) + { + var isRecoverable = Helpers.SslHandshakeDiagnostics.IsRecoverableFailure(authException); + sslDiagnostics?.RecordFailure(authException, isRecoverable); + + RecordError(authException, "SSL authentication failed", clientId, client.Nickname, isSslError: true); + OnSslError?.Invoke(this, new ErrorEventArgs + { + ClientId = clientId, + Nickname = client.Nickname, + Exception = authException, + Message = "SSL authentication failed" + }); + DebugConnection($"SSL authentication failed for {remoteEndPoint} on attempt {attempt}: {authException.Message}"); + OnLog?.Invoke(this, new LogMessage { Type = LogType.Error, Message = $"SSL Authentication failed for {remoteEndPoint}: {authException.Message}" }); + + if (!isRecoverable) + { + try + { + var notification = Encoding.UTF8.GetBytes($"{Configuration.SSL_ERROR_PREFIX}SSL authentication failed: {authException.Message}{Configuration.SSL_ERROR_SUFFIX}"); + var rawStream = tcpClient.GetStream(); + await rawStream.WriteAsync(notification, 0, notification.Length).ConfigureAwait(false); + await rawStream.FlushAsync().ConfigureAwait(false); + } + catch + { + + } + tcpClient?.Client?.Disconnect(false); + break; + } + } + catch (Exception ex) + { + var isRecoverable = Helpers.SslHandshakeDiagnostics.IsRecoverableFailure(ex); + sslDiagnostics?.RecordFailure(ex, isRecoverable); + + RecordError(ex, $"SSL error: {ex.GetType().Name}", clientId, client.Nickname, isSslError: true); + DebugConnection($"SSL error for {remoteEndPoint} on attempt {attempt}: {ex.Message}"); + + if (!isRecoverable) + { + break; + } + } + finally + { +#if NET8_0_OR_GREATER + if (!sslAuthenticated) + { + DebugConnection($"Disposing SSL stream for {remoteEndPoint} after failed authentication attempt {attempt}."); + + try + { + await (sslStream?.DisposeAsync() ?? ValueTask.CompletedTask); + } + catch + { + + } + } +#else + if (!sslAuthenticated) + { + DebugConnection($"Disposing SSL stream for {remoteEndPoint} after failed authentication attempt {attempt}."); + sslStream?.Dispose(); + } +#endif + } + + if (!sslAuthenticated && (attempt < _config.SSLMaxRetries || _config.SSLMaxRetries == 0)) + { + int delaySeconds = _config.GetSslRetryDelaySeconds(attempt); + DebugConnection($"SSL retry in {delaySeconds}s (attempt {attempt})"); + sslDiagnostics?.StartStage("RetryDelay"); + await Task.Delay(delaySeconds * 1000).ConfigureAwait(false); + sslDiagnostics?.EndStage("RetryDelay"); + } + } + + if (!sslAuthenticated) + { + DebugConnection($"SSL authentication failed for {remoteEndPoint} after {_config.SSLMaxRetries} attempts, disconnecting client."); + if (sslDiagnostics != null) + { + DebugConnection($"[SSL Final Metrics] {sslDiagnostics}"); + } + try + { + var notification = Encoding.UTF8.GetBytes($"{Configuration.SSL_ERROR_PREFIX}SSL authentication failed after {_config.SSLMaxRetries} attempts{Configuration.SSL_ERROR_SUFFIX}"); + var rawStream = tcpClient.GetStream(); + await rawStream.WriteAsync(notification, 0, notification.Length).ConfigureAwait(false); + await rawStream.FlushAsync().ConfigureAwait(false); + } + catch + { + + } + await DisconnectClientAsync(clientId, DisconnectReason.SSLError).ConfigureAwait(false); + return; + } + } + + if (_config.EnableKeepAlive) + { + DebugConnection($"Enabling TCP keep-alive for client {client.Nickname} ({client.Id}) with keep-alive time {_config.KeepAliveTimeSeconds}s and interval {_config.KeepAliveIntervalSeconds}s."); + tcpClient.Client.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.KeepAlive, true); + } + + if (_config.EnableHealthApi) + { + var probe = new ProtocolProbeStream(stream); + stream = probe; + client.Stream = stream; + if (await probe.IsHttpAsync(_serverCancellation.Token).ConfigureAwait(false)) + { + await HandleHealthRequestAsync(tcpClient, client, stream).ConfigureAwait(false); + return; + } + } + + if (_config.UseSsl && _config.MutuallyAuthenticate && !clientCertificateValidated) + { + var exception = new AuthenticationException("A valid client certificate is required for connector connections."); + RecordError(exception, exception.Message, clientId, client.Nickname, isSslError: true); + client.Stream = stream; + await client.DisposeAsync().ConfigureAwait(false); + OnSslError?.Invoke(this, new ErrorEventArgs + { + ClientId = clientId, + Nickname = client.Nickname, + Exception = exception, + Message = exception.Message + }); + return; + } + + if (_config.MaxConnections > 0 && GetActiveConnectionCount() >= _config.MaxConnections) + { + _stats.IncrementDroppedConnections(); + client.Stream = stream; + await client.DisposeAsync().ConfigureAwait(false); + return; + } + + if (_config.UseAesEncryption) + { + try + { + client.AesEncryption = Aes.Create(); + client.AesEncryption.GenerateKey(); + client.AesEncryption.GenerateIV(); + client.IsEncrypted = true; + await AesKeyExchange.SendAesKeyAsync(stream, client.AesEncryption, _config.AesPassword); + } + catch (Exception exception) + { + OnEncryptionError?.Invoke(this, new ErrorEventArgs + { + ClientId = clientId, + Nickname = client.Nickname, + Exception = exception, + Message = "AES setup failed" + }); + client.Stream = stream; + try { await client.DisposeAsync(); } catch { } + return; + } + } + + client.Stream = stream; + UpdateLastActive(client); + client.LastDataReceived = DateTime.UtcNow; + client.LastDataSent = DateTime.UtcNow; + + _clients[clientId] = client; + client.ReceiveDataTask = Task.Run(() => HandleClientCommunicationAsync(client), client.CancellationToken.Token); + _stats.IncrementTotalConnections(); + + DebugConnection($"Client connected: {client.Nickname} ({client.Id}) from {remoteEndPoint}. Total connections: {ActiveConnections}"); + + HandlingHelpers.SafeInvokeEventHandler( + OnConnected, + this, + new ConnectionEventArgs + { + ClientId = clientId, + RemoteEndPoint = remoteEndPoint, + Nickname = client.Nickname + }, + nameof(OnConnected), + msg => RecordError(null, msg)); + } + catch (SocketException socketEx) + { + DebugConnection($"Socket error handling TCP client {remoteEndPoint}: {socketEx.SocketErrorCode} - {socketEx.Message}"); + RecordError(socketEx, $"Socket error handling TCP client: {socketEx.SocketErrorCode}", clientId, client.Nickname); + if (!_clients.ContainsKey(clientId)) + { + try { await client.DisposeAsync(); } catch { } + } + else + { + await DisconnectClientAsync(clientId, DisconnectReason.Error, socketEx).ConfigureAwait(false); + } + } + catch (Exception exception) + { + DebugConnection($"Error handling TCP client {remoteEndPoint}: {exception.Message}"); + RecordError(exception, $"Error handling TCP client: {exception.Message}", clientId, client.Nickname); + if (!_clients.ContainsKey(clientId)) + { + try { await client.DisposeAsync(); } catch { } + } + else + { + await DisconnectClientAsync(clientId, DisconnectReason.Error, exception).ConfigureAwait(false); + } + } + } + } +} diff --git a/EonaCat.Connections/Server/NetworkServer.Receiving.cs b/EonaCat.Connections/Server/NetworkServer.Receiving.cs new file mode 100644 index 0000000..9621fc4 --- /dev/null +++ b/EonaCat.Connections/Server/NetworkServer.Receiving.cs @@ -0,0 +1,601 @@ +using EonaCat.Connections.EventArguments; +using EonaCat.Connections.Framing; +using EonaCat.Connections.Helpers; +using EonaCat.Connections.Models; +using System.Buffers; +using System.Net; +using System.Net.Sockets; +using System.Text; +using System.Text.RegularExpressions; +using ErrorEventArgs = EonaCat.Connections.EventArguments.ErrorEventArgs; + +namespace EonaCat.Connections +{ + public partial class NetworkServer + { + private static void UpdateLastActive(Connection client) + { + if (client == null) + { + return; + } + + var now = DateTime.UtcNow; + client.LastActive = now; + } + + private static void MarkDataReceived(Connection client) + { + if (client == null) + { + return; + } + + var now = DateTime.UtcNow; + client.LastActive = now; + client.LastDataReceived = now; + } + + private async Task CleanupTcpClientsAsync(CancellationToken token) + { + while (!token.IsCancellationRequested) + { + try + { + foreach (var kvp in _clients) + { + var client = kvp.Value; + + if (client.IsClosing) + { + continue; + } + + if (!client.IsConnected) + { + DebugConnection($"TCP client {client.Nickname} ({kvp.Key}) detected as disconnected during cleanup, removing."); + await DisconnectClientAsync(kvp.Key, DisconnectReason.RemoteClosed); + continue; + } + } + } + catch (TaskCanceledException) + { + DebugConnection("CleanupTcpClientsAsync canceled."); + break; + } + catch (Exception exception) + { + DebugConnection($"CleanupTcpClientsAsync error: {exception.Message}"); + OnGeneralError?.Invoke(this, new ErrorEventArgs + { + Exception = exception, + Message = "TCP client cleanup error" + }); + } + + await Task.Delay(TimeSpan.FromSeconds(30), token); + } + } + + private async Task HandleUdpDataAsync(UdpReceiveResult result, UdpListenerEntry origin) + { + var clientIp = result.RemoteEndPoint.Address.ToString(); + + if (_ipBlocklist != null && !_ipBlocklist.IsIPAllowed(clientIp)) + { + _stats.IncrementDroppedPackets(); + if (_config.Security?.EnableSecurityLogging == true) + { + OnLog?.Invoke(this, new LogMessage { Type = LogType.Debug, Message = $"UDP datagram blocked by IP filter: {clientIp}" }); + } + return; + } + + if (_ddosDetector != null && _ddosDetector.IsConnectionSuspicious(clientIp)) + { + _stats.IncrementDroppedPackets(); + if (_config.Security?.EnableSecurityLogging == true) + { + OnLog?.Invoke(this, new LogMessage { Type = LogType.Debug, Message = $"UDP datagram blocked by DDoS detection: {clientIp}" }); + } + return; + } + + var clientKey = result.RemoteEndPoint.ToString(); + + if (!_clients.TryGetValue(clientKey, out var client)) + { + if (_config.MaxConnections > 0 && GetActiveConnectionCount() >= _config.MaxConnections) + { + _stats.IncrementDroppedConnections(); + if (_config.Security?.EnableSecurityLogging == true) + { + OnLog?.Invoke(this, new LogMessage { Type = LogType.Debug, Message = $"Incoming UDP client ignored: max connections ({_config.MaxConnections}) reached." }); + } + return; + } + + client = new Connection + { + Id = clientKey, + RemoteEndPoint = result.RemoteEndPoint, + ConnectedAt = DateTime.UtcNow, + LastActive = DateTime.UtcNow, + + OutgoingRateLimiter = _config.Security.EnablePerConnectionRateLimiting ? new Security.RateLimiter(100) : null + }; + _clients[clientKey] = client; + _udpClientOrigin[clientKey] = origin; + + _stats.IncrementTotalConnections(); + HandlingHelpers.SafeInvokeEventHandler( + OnConnected, + this, + new ConnectionEventArgs { ClientId = clientKey, RemoteEndPoint = result.RemoteEndPoint }, + nameof(OnConnected), + msg => RecordError(null, msg)); + } + await ProcessReceivedDataAsync(client, result.Buffer); + } + + public void SetSeparator(string separator) => _config.Delimiter = Encoding.UTF8.GetBytes(separator); + + public void SetSeparator(byte[] separator) => _config.Delimiter = separator; + + private async Task HandleClientCommunicationAsync(Connection client) + { + if (client.Stream == null) + { + DebugConnection("Client stream is null at start of communication loop."); + throw new InvalidOperationException("Client stream is null."); + } + + var stream = client.Stream; + var token = client.CancellationToken.Token; + var maxMessageBytes = GetEffectiveMaxMessageBytes(); + + byte[] readBuffer = ArrayPool.Shared.Rent(_config.BufferSize); + + using var messageStream = new MemoryStream(1024 * 64); + + try + { + while (!token.IsCancellationRequested && client.IsConnected && stream != null) + { + int bytesRead = 0; + + try + { + bytesRead = await stream.ReadAsync(readBuffer, 0, _config.BufferSize, token); + } + catch (IOException ioEx) when (ioEx.InnerException is SocketException socketEx) + { + RecordError(ioEx, $"Socket IO error during read: {socketEx.SocketErrorCode}", client.Id, client.Nickname); + + if (socketEx.SocketErrorCode == SocketError.TimedOut) + { + DebugConnection($"Read timeout for client {client.Nickname} ({client.Id}), disconnecting."); + await DisconnectClientAsync(client.Id, DisconnectReason.Timeout); + return; + } + else if (socketEx.SocketErrorCode == SocketError.ConnectionReset || + socketEx.SocketErrorCode == SocketError.ConnectionAborted) + { + DebugConnection($"Connection reset/aborted for client {client.Nickname} ({client.Id})."); + await DisconnectClientAsync(client.Id, DisconnectReason.RemoteClosed); + return; + } + throw; + } + catch (SocketException socketEx) + { + RecordError(socketEx, $"Socket error during read: {socketEx.SocketErrorCode}", client.Id, client.Nickname); + DebugConnection($"Socket error during read for client {client.Nickname} ({client.Id}): {socketEx.SocketErrorCode}"); + + if (socketEx.SocketErrorCode == SocketError.TimedOut) + { + await DisconnectClientAsync(client.Id, DisconnectReason.Timeout, socketEx); + return; + } + else if (socketEx.SocketErrorCode == SocketError.ConnectionReset || + socketEx.SocketErrorCode == SocketError.ConnectionAborted) + { + await DisconnectClientAsync(client.Id, DisconnectReason.RemoteClosed, socketEx); + return; + } + throw; + } + + if (bytesRead == 0) + { + DebugConnection($"Client {client.Nickname} disconnected (0 bytes read)."); + await DisconnectClientAsync(client.Id, DisconnectReason.RemoteClosed); + return; + } + + MarkDataReceived(client); + await messageStream.WriteAsync(readBuffer, 0, bytesRead, token); + + if (_config.MessageFraming == FramingMode.LengthPrefixed) + { + while (TryExtractLengthPrefixedMessage(messageStream, maxMessageBytes, out byte[]? message)) + { + if (client.IsEncrypted && client.AesEncryption != null) + { + message = await AesKeyExchange.DecryptDataAsync(message, message.Length, client.AesEncryption); + } + + await ProcessReceivedDataAsync(client, message); + } + } + else if (_config.MessageFraming == FramingMode.Delimiter) + { + while (TryExtractDelimitedMessage(messageStream, maxMessageBytes, out byte[]? message)) + { + if (client.IsEncrypted && client.AesEncryption != null) + { + message = await AesKeyExchange.DecryptDataAsync(message, message.Length, client.AesEncryption); + } + + await ProcessReceivedDataAsync(client, message); + } + } + else if (_config.MessageFraming == FramingMode.None) + { + + if (messageStream.Length > maxMessageBytes) + { + DebugConnection($"Client {client.Nickname} ({client.Id}) exceeded max message size ({maxMessageBytes} bytes) in None-framing mode, disconnecting."); + RecordError(null, $"Client exceeded max message size ({maxMessageBytes} bytes) in None-framing mode.", client.Id, client.Nickname); + await DisconnectClientAsync(client.Id, DisconnectReason.ProtocolError).ConfigureAwait(false); + return; + } + + var data = messageStream.ToArray(); + messageStream.SetLength(0); + + if (client.IsEncrypted && client.AesEncryption != null) + { + data = await AesKeyExchange.DecryptDataAsync(data, data.Length, client.AesEncryption); + } + + await ProcessReceivedDataAsync(client, data); + } + } + } + catch (OperationCanceledException) + { + DebugConnection($"Communication loop canceled for client {client.Nickname} ({client.Id})."); + + } + catch (ProtocolViolationException protoEx) + { + DebugConnection($"Protocol violation from client {client.Nickname} ({client.Id}): {protoEx.Message}, Disconnecting"); + RecordError(protoEx, $"Protocol violation: {protoEx.Message}", client.Id, client.Nickname); + await DisconnectClientAsync(client.Id, DisconnectReason.ProtocolError, protoEx); + } + catch (SocketException socketEx) + { + DebugConnection($"Socket error in communication loop for client {client.Nickname} ({client.Id}): {socketEx.SocketErrorCode} - {socketEx.Message}, Disconnecting"); + RecordError(socketEx, $"Socket error in communication loop: {socketEx.SocketErrorCode}", client.Id, client.Nickname); + var reason = socketEx.SocketErrorCode == SocketError.ConnectionReset + || socketEx.SocketErrorCode == SocketError.ConnectionAborted + ? DisconnectReason.RemoteClosed + : DisconnectReason.Error; + await DisconnectClientAsync(client.Id, reason, socketEx); + } + catch (ObjectDisposedException) + { + + if (client.IsConnected) + { + DebugConnection($"Stream disposed for client {client.Nickname} ({client.Id}) during communication loop, disconnecting client."); + await DisconnectClientAsync(client.Id, DisconnectReason.Error); + } + } + catch (IOException ioEx) when (ioEx.InnerException is SocketException innerSocketEx) + { + DebugConnection($"Socket IO error in communication loop for client {client.Nickname} ({client.Id}): {innerSocketEx.SocketErrorCode} - {ioEx.Message}, Disconnecting"); + RecordError(ioEx, $"Socket IO error in communication loop: {innerSocketEx.SocketErrorCode}", client.Id, client.Nickname); + var reason = innerSocketEx.SocketErrorCode == SocketError.ConnectionReset + || innerSocketEx.SocketErrorCode == SocketError.ConnectionAborted + ? DisconnectReason.RemoteClosed + : DisconnectReason.Error; + await DisconnectClientAsync(client.Id, reason, ioEx); + } + catch (IOException ioEx) + { + DebugConnection($"IO error in communication loop for client {client.Nickname} ({client.Id}): {ioEx.Message}, Disconnecting"); + RecordError(ioEx, $"IO error in communication loop: {ioEx.Message}", client.Id, client.Nickname); + await DisconnectClientAsync(client.Id, DisconnectReason.Error, ioEx); + } + catch (Exception ex) + { + DebugConnection($"Error in communication loop for client {client.Nickname} ({client.Id}): {ex.Message}, Disconnecting"); + RecordError(ex, $"Error in communication loop: {ex.Message}", client.Id, client.Nickname); + await DisconnectClientAsync(client.Id, DisconnectReason.Error, ex); + } + finally + { + ArrayPool.Shared.Return(readBuffer); + } + } + + private bool TryExtractLengthPrefixedMessage(MemoryStream stream, double maxMessageBytes, out byte[]? message) + { + return MessageFrameDecoder.TryReadLengthPrefixed( + stream, + _config.LengthPrefixedLength, + _config.UseBigEndian, + maxMessageBytes, + out message); + } + + private bool TryExtractDelimitedMessage(MemoryStream stream, double maxMessageBytes, out byte[]? message) + { + return MessageFrameDecoder.TryReadDelimited(stream, _config.Delimiter, maxMessageBytes, out message); + } + + private void ProcessPingPong(Connection client, ref string message) + { + if (!_config.EnableHeartbeat || string.IsNullOrEmpty(message)) + { + return; + } + + if (message.Contains(Configuration.PING_VALUE)) + { + if (_config.EnablePingPongLogs) + { + OnLog?.Invoke(this, new LogMessage { Type = LogType.Debug, Message = $"[PING] Client {client.Id} PING received at {DateTime.UtcNow:O}, sending pong" }); + } + + _ = SendToClientAsync(client.Id, Configuration.PONG_VALUE).ConfigureAwait(false); + message = message.Replace(Configuration.PING_VALUE, string.Empty); + } + + if (message.Contains(Configuration.PONG_VALUE)) + { + if (_config.EnablePingPongLogs) + { + OnLog?.Invoke(this, new LogMessage { Type = LogType.Debug, Message = $"[PING] Client {client.Id} PONG received for PING sent" }); + } + + OnClientPingResponse?.Invoke(this, new PingEventArgs + { + Id = client.Id, + Nickname = client.Nickname, + ReceivedTime = DateTime.UtcNow, + RemoteEndPoint = client.RemoteEndPoint + }); + message = message.Replace(Configuration.PONG_VALUE, string.Empty); + } + } + + private async Task ProcessReceivedDataAsync(Connection client, byte[] data) + { + if (client == null || data == null || data.Length == 0) + { + return; + } + + // Bytes physically arrived, so activity is recorded before any gate that can drop the message. + var receivedAt = DateTime.UtcNow; + LastDataReceived = receivedAt; + MarkDataReceived(client); + client.AddBytesReceived(data.Length); + _lastPingTimes[client.Id] = receivedAt; + + _stats.AddBytesReceived(data.Length); + _stats.IncrementMessagesReceived(); + + try + { + + if (_payloadValidator != null && _config.Security != null) + { + if (!_payloadValidator.TryValidatePayload(data, _config.Security, out var validationFailure)) + { + if (_config.Security.EnableSecurityLogging) + { + OnLog?.Invoke(this, new LogMessage { Type = LogType.Warning, Message = $"Payload validation failed for {client.Id} ({client.Nickname}): {validationFailure}" }); + } + + client.SecurityViolationCount++; + + if (_config.Security.AutoBlockIPAfterViolations > 0 && + client.SecurityViolationCount >= _config.Security.AutoBlockIPAfterViolations) + { + var clientIp = (client.RemoteEndPoint?.Address.ToString()) ?? "unknown"; + _ipBlocklist?.BlockIP(clientIp, validationFailure ?? "Payload validation failure"); + } + + return; + } + } + + if (_slowlorisDetector != null && _slowlorisDetector.RecordDataReceived(client.Id, data.Length)) + { + if (_config.Security?.EnableSecurityLogging == true) + { + OnLog?.Invoke(this, new LogMessage { Type = LogType.Warning, Message = $"Slowloris attack detected from {client.Id} ({client.Nickname})" }); + } + + client.SecurityViolationCount++; + return; + } + + if (_globalRateLimiter != null && !_globalRateLimiter.TryConsumeTokens()) + { + if (_config.Security?.EnableSecurityLogging == true) + { + OnLog?.Invoke(this, new LogMessage { Type = LogType.Warning, Message = $"Global rate limit exceeded for message from {client.Id} ({client.Nickname})" }); + } + + client.RateLimitViolations++; + return; + } + + if (_perConnectionRateLimiter != null && !_perConnectionRateLimiter.TryConsumeToken(client.Id)) + { + if (_config.Security?.EnableSecurityLogging == true) + { + OnLog?.Invoke(this, new LogMessage { Type = LogType.Warning, Message = $"Per-connection rate limit exceeded for {client.Id} ({client.Nickname})" }); + } + + client.RateLimitViolations++; + + if (_config.Security?.AutoBlockIPAfterViolations > 0) + { + if (client.RateLimitViolations >= _config.Security.AutoBlockIPAfterViolations) + { + var clientIp = (client.RemoteEndPoint?.Address.ToString()) ?? "unknown"; + _ipBlocklist?.BlockIP(clientIp, "Rate limit violations"); + } + } + return; + } + + string stringData = null; + bool isBinary = false; + + try + { + int requiredChars = client.Utf8Decoder.GetCharCount(data, 0, data.Length); + if (client.CharBuffer == null || client.CharBuffer.Length < requiredChars) + { + client.CharBuffer = new char[requiredChars]; + } + + int charCount = client.Utf8Decoder.GetChars( + data, + 0, + data.Length, + client.CharBuffer, + 0, + false); + + if (charCount > 0) + { + stringData = new string(client.CharBuffer, 0, charCount); + } + } + catch + { + + isBinary = true; + stringData = null; + } + + if (!string.IsNullOrEmpty(stringData)) + { + ProcessPingPong(client, ref stringData); + + if (string.IsNullOrEmpty(stringData)) + { + return; + } + } + + if (DEBUG_DATA_RECEIVED) + { + var debug = isBinary + ? $"[DEBUG DATA] Received from {client.Id} ({client.Nickname ?? "NoNickname"}): [binary {data.Length} bytes]" + : $"[DEBUG DATA] Received from {client.Id} ({client.Nickname ?? "NoNickname"}): {stringData}"; + + OnLog?.Invoke(this, new LogMessage { Type = LogType.Debug, Message = debug }); + } + + if (!string.IsNullOrEmpty(stringData)) + { + if (stringData.Contains(Configuration.SSL_ERROR_PREFIX, StringComparison.OrdinalIgnoreCase)) + { + string sslError = StringHelper.GetTextBetweenTags(stringData, Configuration.SSL_ERROR_PREFIX, Configuration.SSL_ERROR_SUFFIX); + RecordError(null, $"Client reported SSL error: {sslError}", client.Id, client.Nickname, isSslError: true); + OnSslError?.Invoke(this, new ErrorEventArgs + { + ClientId = client.Id, + Nickname = client.Nickname, + Message = $"Client reported SSL error: {sslError}" + }); + DebugConnection($"[SSL_ERROR] detected from client {client.Id}: {sslError}"); + await DisconnectClientAsync(client.Id, DisconnectReason.SSLError).ConfigureAwait(false); + return; + } + else if (stringData.Contains("[NICKNAME]", StringComparison.OrdinalIgnoreCase)) + { + string nickname = StringHelper.GetTextBetweenTags(stringData, "[NICKNAME]", "[/NICKNAME]"); + HandleNickname(client, nickname); + + stringData = Regex.Replace( + stringData, + "\\[NICKNAME\\].*?\\[/NICKNAME\\]", + string.Empty, + RegexOptions.IgnoreCase | RegexOptions.Singleline); + + if (string.IsNullOrEmpty(stringData)) + { + return; + } + } + else if (stringData.Contains("[DISCONNECT]", StringComparison.OrdinalIgnoreCase)) + { + DebugConnection($"[DISCONNECT] detected, disconnecting client {client.Id}"); + await DisconnectClientAsync(client.Id, DisconnectReason.ClientRequested).ConfigureAwait(false); + return; + } + } + + var eventArgs = new DataReceivedEventArgs + { + ClientId = client.Id, + Nickname = client.Nickname, + RemoteEndPoint = client.RemoteEndPoint, + Data = data, + IsBinary = isBinary, + Timestamp = receivedAt + }; + + try + { + HandlingHelpers.SafeInvokeEventHandler( + OnDataReceived, + this, + eventArgs, + nameof(OnDataReceived), + msg => RecordError(null, msg)); + } + catch (Exception ex) + { + HandlingHelpers.SafeInvokeEventHandler( + OnGeneralError, + this, + new ErrorEventArgs + { + ClientId = client.Id, + Nickname = client.Nickname, + Exception = ex, + Message = "Error in OnDataReceived event handler" + }, + nameof(OnGeneralError), + msg => RecordError(null, msg)); + } + } + catch (Exception ex) + { + _stats.IncrementDroppedPackets(); + + var handler = client.IsEncrypted ? OnEncryptionError : OnGeneralError; + + handler?.Invoke(this, new ErrorEventArgs + { + ClientId = client.Id, + Nickname = client.Nickname, + Exception = ex, + Message = "Error processing data" + }); + } + } + } +} diff --git a/EonaCat.Connections/Server/NetworkServer.Sending.cs b/EonaCat.Connections/Server/NetworkServer.Sending.cs new file mode 100644 index 0000000..9d7d975 --- /dev/null +++ b/EonaCat.Connections/Server/NetworkServer.Sending.cs @@ -0,0 +1,392 @@ +using EonaCat.Connections.EventArguments; +using EonaCat.Connections.Framing; +using EonaCat.Connections.Helpers; +using EonaCat.Connections.Messaging; +using EonaCat.Connections.Models; +using System.Buffers; +using System.Net.Sockets; +using System.Text; +using ErrorEventArgs = EonaCat.Connections.EventArguments.ErrorEventArgs; +using ProtocolType = EonaCat.Connections.Models.ProtocolType; + +namespace EonaCat.Connections +{ + public partial class NetworkServer + { + public async Task SendToClientAsync(String clientId, byte[] data) + => await SendToClientAsync(clientId, data, CancellationToken.None).ConfigureAwait(false); + + public async Task SendToClientAsync(String clientId, byte[] data, CancellationToken cancellationToken) + { + var clientList = GetClient(clientId); + + if (clientList == null || clientList.Count == 0) + { + ClientMissing(clientId, data); + return false; + } + + bool any = false; + + foreach (var client in clientList) + { + if (await SendDataAsync(client, data, cancellationToken).ConfigureAwait(false)) + { + any = true; + } + } + return any; + } + + private void ClientMissing(string clientId, byte[] data) + { + DebugConnection($"Client missing: {clientId}, unable to send data of length {data?.Length ?? 0} bytes."); + OnClientMissing?.Invoke(this, new ClientMissingEventArgs + { + ClientId = clientId, + Timestamp = DateTime.UtcNow, + Data = data, + }); + } + + public async Task SendToClientAsync(String clientId, String message) => await SendToClientAsync(clientId, Encoding.UTF8.GetBytes(message)); + + public async Task SendToClientAsync(String clientId, String message, CancellationToken cancellationToken) + => await SendToClientAsync(clientId, Encoding.UTF8.GetBytes(message), cancellationToken).ConfigureAwait(false); + + public async Task SendFromClientToClientAsync(String fromClientId, String toClientId, byte[] data) + => await SendFromClientToClientAsync(fromClientId, toClientId, data, CancellationToken.None).ConfigureAwait(false); + + public async Task SendFromClientToClientAsync(String fromClientId, String toClientId, byte[] data, CancellationToken cancellationToken) + { + var toClient = GetClient(toClientId); + + if (toClient == null || toClient.Count == 0) + { + ClientMissing(toClientId, fromClientId, data); + return false; + } + + bool any = false; + foreach (var client in toClient) + { + if (await SendDataAsync(client, data, cancellationToken).ConfigureAwait(false)) + { + any = true; + } + } + return any; + } + + private void ClientMissing(string toClientId, string fromClientId, byte[] data) + { + DebugConnection($"Client missing: {toClientId}, unable to send data of length {data?.Length ?? 0} bytes from {fromClientId}."); + OnClientMissing?.Invoke(this, new ClientMissingEventArgs + { + ClientId = toClientId, + Timestamp = DateTime.UtcNow, + Data = data, + }); + } + + public async Task SendFromClientToClientAsync(String fromClientId, String toClientId, String message) => await SendFromClientToClientAsync(fromClientId, toClientId, Encoding.UTF8.GetBytes(message)); + + public async Task SendFromClientToClientAsync(String fromClientId, String toClientId, String message, CancellationToken cancellationToken) + => await SendFromClientToClientAsync(fromClientId, toClientId, Encoding.UTF8.GetBytes(message), cancellationToken).ConfigureAwait(false); + + public async Task BroadcastAsync(byte[] data) + => await BroadcastAsync(data, CancellationToken.None).ConfigureAwait(false); + + public async Task BroadcastAsync(byte[] data, CancellationToken cancellationToken) + { + if (data == null || data.Length == 0) + { + return false; + } + + var clients = _clients.Values.ToArray(); + if (clients.Length == 0) + { + return false; + } + + var tasks = new Task[clients.Length]; + for (int i = 0; i < clients.Length; i++) + { + tasks[i] = SendDataAsync(clients[i], data, cancellationToken); + } + + var results = await Task.WhenAll(tasks).ConfigureAwait(false); + return Array.Exists(results, r => r); + } + + public async Task BroadcastAsync(String message) => await BroadcastAsync(Encoding.UTF8.GetBytes(message)); + + public async Task BroadcastAsync(String message, CancellationToken cancellationToken) + => await BroadcastAsync(Encoding.UTF8.GetBytes(message), cancellationToken).ConfigureAwait(false); + + public async Task SendToClientAndWaitForResponseAsync(string clientId, byte[] data, TimeSpan? timeout = null) + => await SendToClientAndWaitForResponseAsync(clientId, data, timeout, CancellationToken.None).ConfigureAwait(false); + + public async Task SendToClientAndWaitForResponseAsync(string clientId, byte[] data, TimeSpan? timeout, CancellationToken cancellationToken) + { + var effectiveTimeout = timeout ?? TimeSpan.FromSeconds(DEFAULT_WAITING_TIMEOUT_IN_SECONDS); + var clientList = GetClient(clientId); + var clientIds = new HashSet(clientList.Select(c => c.Id)); + return await ResponseAwaiter.WaitForSingleAsync( + () => SendToClientAsync(clientId, data, cancellationToken), + handler => OnDataReceived += handler, + handler => OnDataReceived -= handler, + effectiveTimeout, + response => clientIds.Contains(response.ClientId), + cancellationToken).ConfigureAwait(false); + } + + public async Task SendToClientAndWaitForResponseAsync(string clientId, string message, TimeSpan? timeout = null) + => await SendToClientAndWaitForResponseAsync(clientId, Encoding.UTF8.GetBytes(message), timeout).ConfigureAwait(false); + + public async Task SendToClientAndWaitForResponseAsync(string clientId, string message, TimeSpan? timeout, CancellationToken cancellationToken) + => await SendToClientAndWaitForResponseAsync(clientId, Encoding.UTF8.GetBytes(message), timeout, cancellationToken).ConfigureAwait(false); + + public async Task SendFromClientToClientAndWaitForResponseAsync(string fromClientId, string toClientId, byte[] data, TimeSpan? timeout = null) + => await SendFromClientToClientAndWaitForResponseAsync(fromClientId, toClientId, data, timeout, CancellationToken.None).ConfigureAwait(false); + + public async Task SendFromClientToClientAndWaitForResponseAsync(string fromClientId, string toClientId, byte[] data, TimeSpan? timeout, CancellationToken cancellationToken) + { + var effectiveTimeout = timeout ?? TimeSpan.FromSeconds(DEFAULT_WAITING_TIMEOUT_IN_SECONDS); + var clientList = GetClient(toClientId); + var clientIds = new HashSet(clientList.Select(c => c.Id)); + return await ResponseAwaiter.WaitForSingleAsync( + () => SendFromClientToClientAsync(fromClientId, toClientId, data, cancellationToken), + handler => OnDataReceived += handler, + handler => OnDataReceived -= handler, + effectiveTimeout, + response => clientIds.Contains(response.ClientId), + cancellationToken).ConfigureAwait(false); + } + + public async Task SendFromClientToClientAndWaitForResponseAsync(string fromClientId, string toClientId, string message, TimeSpan? timeout = null) + => await SendFromClientToClientAndWaitForResponseAsync(fromClientId, toClientId, Encoding.UTF8.GetBytes(message), timeout).ConfigureAwait(false); + + public async Task SendFromClientToClientAndWaitForResponseAsync(string fromClientId, string toClientId, string message, TimeSpan? timeout, CancellationToken cancellationToken) + => await SendFromClientToClientAndWaitForResponseAsync(fromClientId, toClientId, Encoding.UTF8.GetBytes(message), timeout, cancellationToken).ConfigureAwait(false); + + public async Task> BroadcastAndWaitForResponsesAsync(byte[] data, TimeSpan? timeout = null) + => await BroadcastAndWaitForResponsesAsync(data, timeout, CancellationToken.None).ConfigureAwait(false); + + public async Task> BroadcastAndWaitForResponsesAsync(byte[] data, TimeSpan? timeout, CancellationToken cancellationToken) + { + var effectiveTimeout = timeout ?? TimeSpan.FromSeconds(DEFAULT_WAITING_TIMEOUT_IN_SECONDS); + var expectedCount = _clients.Count; + return await ResponseAwaiter.WaitForManyAsync( + () => BroadcastAsync(data, cancellationToken), + handler => OnDataReceived += handler, + handler => OnDataReceived -= handler, + effectiveTimeout, + expectedCount, + cancellationToken).ConfigureAwait(false); + } + + public async Task> BroadcastAndWaitForResponsesAsync(string message, TimeSpan? timeout = null) + => await BroadcastAndWaitForResponsesAsync(Encoding.UTF8.GetBytes(message), timeout).ConfigureAwait(false); + + public async Task> BroadcastAndWaitForResponsesAsync(string message, TimeSpan? timeout, CancellationToken cancellationToken) + => await BroadcastAndWaitForResponsesAsync(Encoding.UTF8.GetBytes(message), timeout, cancellationToken).ConfigureAwait(false); + + private async Task SendDataAsync(Connection client, byte[] data, CancellationToken cancellationToken = default) + { + if (client == null || + !client.IsConnected || + data == null || + data.Length == 0) + { + return false; + } + + if (client.OutgoingRateLimiter != null && !client.OutgoingRateLimiter.TryConsumeTokens(1000)) + { + + client.IncrementRateLimitViolations(); + return false; + } + + if (_config.Protocol == ProtocolType.TCP && + (client.Stream == null || !client.Stream.CanWrite)) + { + return false; + } + + byte[] rentedBuffer = null; + int bytesToSend = 0; + + try + { + + byte[] payloadToFrame = data; + if (client.IsEncrypted && client.AesEncryption != null) + { + payloadToFrame = await AesKeyExchange.EncryptDataAsync(data, data.Length, client.AesEncryption).ConfigureAwait(false); + } + + if (payloadToFrame.Length > _config.MAX_MESSAGE_SIZE) + { + throw new InvalidOperationException($"Payload size {payloadToFrame.Length} exceeds maximum message size {_config.MAX_MESSAGE_SIZE}"); + } + + int requiredSize = MessageFrameEncoder.GetEncodedLength(payloadToFrame, _config); + + if (requiredSize > MAX_BUFFER_MEMORY_IN_KILOBYTES * 1024) + { + throw new InvalidOperationException("Message exceeds maximum allowed buffer size."); + } + + rentedBuffer = ArrayPool.Shared.Rent(requiredSize); + + bytesToSend = MessageFrameEncoder.Write(rentedBuffer, payloadToFrame, _config); + + if (_config.Protocol == ProtocolType.TCP) + { + using var cts = CancellationTokenSource.CreateLinkedTokenSource(client.CancellationToken?.Token ?? CancellationToken.None, cancellationToken); + if (_config.WriteTimeoutSeconds > 0) + { + cts.CancelAfter(TimeSpan.FromSeconds(_config.WriteTimeoutSeconds)); + } + + try + { + await client.WriteLock.WaitAsync(cts.Token).ConfigureAwait(false); + } + catch (ObjectDisposedException) + { + + return false; + } + + try + { + if (client.Stream == null || !client.Stream.CanWrite) + { + return false; + } + + await client.Stream.WriteAsync(rentedBuffer, 0, bytesToSend, cts.Token).ConfigureAwait(false); + await client.Stream.FlushAsync(cts.Token).ConfigureAwait(false); + } + finally + { + try + { + client.WriteLock.Release(); + } + catch (ObjectDisposedException) + { + + } + } + } + else + { + if (cancellationToken.IsCancellationRequested) + { + return false; + } + + UdpListenerEntry sendEntry = null; + + if (!_udpClientOrigin.TryGetValue(client.Id, out sendEntry) || sendEntry?.Client == null) + { + lock (_udpListeners) + { + sendEntry = _udpListeners.FirstOrDefault(e => e.Client != null + && e.LocalEndPoint.AddressFamily == client.RemoteEndPoint.AddressFamily) + ?? _udpListeners.FirstOrDefault(e => e.Client != null); + } + } + + if (sendEntry?.Client == null) + { + return false; + } + + UdpClient udpSendClient; + await sendEntry.Lock.WaitAsync().ConfigureAwait(false); + try + { + if (sendEntry.Client == null) + { + return false; + } + + udpSendClient = sendEntry.Client; + } + finally + { + sendEntry.Lock.Release(); + } + + await udpSendClient.SendAsync(rentedBuffer, bytesToSend, client.RemoteEndPoint).ConfigureAwait(false); + } + + var sentAt = DateTime.UtcNow; + client.LastDataSent = sentAt; + client.LastActive = sentAt; + LastDataSent = sentAt; + client.AddBytesSent(bytesToSend); + + _stats.AddBytesSent(bytesToSend); + _stats.IncrementMessagesSent(); + + return true; + } + catch (OperationCanceledException ex) + { + if (cancellationToken.IsCancellationRequested) + { + return false; + } + + DebugConnection($"Write timeout for client {client.Nickname} ({client.Id}): {ex.Message} => disconnecting client"); + RecordError(ex, "Write timeout in send", client.Id, client.Nickname); + await SafeDisconnectAsync(client, DisconnectReason.Timeout).ConfigureAwait(false); + return false; + } + catch (SocketException socketEx) + { + DebugConnection($"Socket error sending data to client {client.Nickname} ({client.Id}): {socketEx.SocketErrorCode} - {socketEx.Message}"); + RecordError(socketEx, $"Socket error in send: {socketEx.SocketErrorCode}", client.Id, client.Nickname); + await SafeDisconnectAsync(client, DisconnectReason.Error).ConfigureAwait(false); + return false; + } + catch (IOException ioEx) when (ioEx.InnerException is SocketException innerSocketEx) + { + DebugConnection($"Socket IO error sending data to client {client.Nickname} ({client.Id}): {innerSocketEx.SocketErrorCode} - {ioEx.Message}"); + RecordError(ioEx, $"Socket IO error in send: {innerSocketEx.SocketErrorCode}", client.Id, client.Nickname); + await SafeDisconnectAsync(client, DisconnectReason.Error).ConfigureAwait(false); + return false; + } + catch (Exception exception) + { + RecordError(exception, $"Error sending data: {exception.Message}", client.Id, client.Nickname); + var handler = client.IsEncrypted ? OnEncryptionError : OnGeneralError; + handler?.Invoke(this, new ErrorEventArgs + { + ClientId = client.Id, + Nickname = client.Nickname, + Exception = exception, + Message = "Error sending data" + }); + + await SafeDisconnectAsync(client, DisconnectReason.Error).ConfigureAwait(false); + return false; + } + finally + { + if (rentedBuffer != null) + { + ArrayPool.Shared.Return(rentedBuffer); + } + } + } + + } +} diff --git a/EonaCat.Connections/Server/NetworkServer.Status.cs b/EonaCat.Connections/Server/NetworkServer.Status.cs new file mode 100644 index 0000000..5d319b5 --- /dev/null +++ b/EonaCat.Connections/Server/NetworkServer.Status.cs @@ -0,0 +1,328 @@ +using EonaCat.Connections.Helpers; +using EonaCat.Connections.Models; +using EonaCat.Connections.Security; +using System.Buffers; +using System.Globalization; +using System.Net.Sockets; +using System.Text; +using ProtocolType = EonaCat.Connections.Models.ProtocolType; + +namespace EonaCat.Connections +{ + public partial class NetworkServer + { + private void InitializeSecurityComponents() + { + if (_config?.Security == null) + { + return; + } + + var security = _config.Security; + + if (security.EnableGlobalRateLimiting) + { + _globalRateLimiter = new Security.RateLimiter(security.GlobalMessagesPerSecond); + } + + if (security.EnablePerConnectionRateLimiting) + { + _perConnectionRateLimiter = new PerConnectionRateLimiter(security.ConnectionMessagesPerSecond); + } + + if (security.EnableDDoSDetection) + { + _ddosDetector = new DDoSDetector( + security.MaxConnectionsPerSecondPerIp, + security.ConnectionSpamThreshold, + security.SpamDetectionWindowSeconds); + } + + if (security.EnableSlowlorisDetection) + { + _slowlorisDetector = new SlowlorisDetector( + security.SlowlorisMinBytesPerSecond, + security.SlowlorisDetectionWindowSeconds); + } + + if (security.EnablePayloadValidation || security.EnableSuspiciousContentDetection || security.BlockNullBytePayloads || security.ValidateMessageNotEmpty) + { + _payloadValidator = new PayloadValidator(); + } + + if (security.EnableRequestDeduplication) + { + _deduplicator = new RequestDeduplicator(security.DeduplicationWindowSeconds); + } + + if (security.EnableIPFiltering) + { + _ipBlocklist = new IPBlocklist(security.IPBlockDurationSeconds); + + foreach (var ip in security.WhitelistedIPs) + { + _ipBlocklist?.AddToWhitelist(ip); + } + + foreach (var ip in security.BlacklistedIPs) + { + _ipBlocklist?.AddToBlacklist(ip); + } + } + } + + private double GetEffectiveMaxMessageBytes() + { + var maxMessageSize = _config?.MAX_MESSAGE_SIZE ?? (int)MessageSizeMaximum.Default; + var configuredPayloadSize = _config?.Security?.MaxPayloadSize ?? 0; + + if (configuredPayloadSize > 0 && configuredPayloadSize < maxMessageSize) + { + return configuredPayloadSize; + } + + return maxMessageSize; + } + + public Stats GetStats() + { + _stats.ActiveConnections = GetActiveConnectionCount(); + return _stats; + } + + public Dictionary GetSecurityMetrics() + { + var metrics = new Dictionary(); + + if (!(_config?.Security?.IsAnyProtectionEnabled ?? false)) + { + metrics["ProtectionsEnabled"] = false; + return metrics; + } + + metrics["ProtectionsEnabled"] = true; + + if (_globalRateLimiter != null) + { + metrics["GlobalRateLimitEnabled"] = true; + metrics["GlobalTokenCount"] = _globalRateLimiter.GetTokenCount(); + } + + if (_perConnectionRateLimiter != null) + { + metrics["PerConnectionRateLimitEnabled"] = true; + metrics["PerConnectionLimiters"] = _perConnectionRateLimiter.LimiterCount; + } + + if (_ddosDetector != null) + { + metrics["DDoSDetectionEnabled"] = true; + metrics["TotalDDoSAttacksDetected"] = _ddosDetector.TotalAttacksDetected; + metrics["TotalConnectionsBlocked"] = _ddosDetector.ConnectionsBlocked; + metrics["TrackedIPs"] = _ddosDetector.TrackedIPCount; + } + + if (_slowlorisDetector != null) + { + metrics["SlowlorisDetectionEnabled"] = true; + metrics["TotalSlowlorisDetected"] = _slowlorisDetector.TotalSlowlorisDetected; + metrics["TrackedConnections"] = _slowlorisDetector.TrackedConnectionCount; + } + + if (_payloadValidator != null) + { + metrics["PayloadValidationEnabled"] = true; + metrics["TotalPayloadsValidated"] = _payloadValidator.TotalValidated; + metrics["TotalPayloadsRejected"] = _payloadValidator.TotalRejected; + metrics["TotalNullByteDetected"] = _payloadValidator.TotalNullByteDetected; + metrics["TotalSizeViolations"] = _payloadValidator.TotalSizeViolations; + metrics["TotalSuspiciousContentDetected"] = _payloadValidator.TotalSuspiciousContentDetected; + } + + if (_deduplicator != null) + { + metrics["RequestDeduplicationEnabled"] = true; + metrics["TotalDuplicatesDetected"] = _deduplicator.TotalDuplicatesDetected; + metrics["TrackedHashes"] = _deduplicator.TrackedHashCount; + } + + if (_ipBlocklist != null) + { + metrics["IPFilteringEnabled"] = true; + metrics["IPsAllowed"] = _ipBlocklist.TotalAllowed; + metrics["IPsBlocked"] = _ipBlocklist.TotalBlocked; + metrics["TempBlockedIPs"] = _ipBlocklist.BlockedIPCount; + metrics["BlacklistedIPs"] = _ipBlocklist.BlacklistedIPCount; + metrics["WhitelistedIPs"] = _ipBlocklist.WhitelistedIPCount; + } + + var totalSecurityViolations = _clients.Values.Sum(c => c.SecurityViolationCount); + var totalRateLimitViolations = _clients.Values.Sum(c => c.RateLimitViolations); + metrics["TotalClientSecurityViolations"] = totalSecurityViolations; + metrics["TotalClientRateLimitViolations"] = totalRateLimitViolations; + + return metrics; + } + + private int GetActiveConnectionCount() + { + if (_clients.IsEmpty) + { + return 0; + } + + int activeCount = 0; + + foreach (var client in _clients.Values) + { + if (client == null || client.IsClosing) + { + continue; + } + + if (_config.Protocol == ProtocolType.UDP) + { + activeCount++; + continue; + } + + if (IsTcpClientAlive(client)) + { + activeCount++; + } + } + + return activeCount; + } + + private static bool IsTcpClientAlive(Connection client) + { + var socket = client?.TcpClient?.Client; + if (socket == null) + { + return false; + } + + try + { + if (!socket.Connected) + { + return false; + } + + return !(socket.Poll(0, SelectMode.SelectRead) && socket.Available == 0); + } + catch (Exception) + { + + return false; + } + } + + public string IpAddress => _config != null ? _config.Host : string.Empty; + public int Port => _config != null ? _config.Port : 0; + + public bool DEBUG_DATA_SEND { get; set; } + public bool DEBUG_DATA_RECEIVED { get; set; } + + private string BuildHealthJson() + { + var E = HealthApiServer.JsonEscape; + var stats = GetStats(); + return "{" + + "\"status\":\"ok\"," + + "\"type\":\"server\"," + + $"\"listenAddress\":{E(_config.Host + ":" + _config.Port)}," + + $"\"protocol\":{E(_config.Protocol.ToString())}," + + $"\"isStarted\":{(IsStarted ? "true" : "false")}," + + $"\"isSecure\":{(IsSecure ? "true" : "false")}," + + $"\"isEncrypted\":{(IsEncrypted ? "true" : "false")}," + + $"\"activeConnections\":{stats.ActiveConnections}," + + $"\"maxConnections\":{_config.MaxConnections}," + + $"\"uptimeSeconds\":{stats.Uptime.TotalSeconds.ToString("F1", CultureInfo.InvariantCulture)}," + + $"\"startTimeUtc\":{E(stats.StartTime.ToString("O"))}" + + "}"; + } + + private string BuildStatusJson() + { + var E = HealthApiServer.JsonEscape; + var stats = GetStats(); + var sb = new StringBuilder(); + sb.Append("{"); + sb.Append("\"status\":\"ok\","); + sb.Append("\"type\":\"server\","); + sb.Append($"\"processName\":{E(HealthApiServer.GetProcessName())},"); + sb.Append($"\"listenAddress\":{E(_config.Host + ":" + _config.Port)},"); + sb.Append($"\"protocol\":{E(_config.Protocol.ToString())},"); + sb.Append($"\"isStarted\":{(IsStarted ? "true" : "false")},"); + sb.Append($"\"isSecure\":{(IsSecure ? "true" : "false")},"); + sb.Append($"\"isEncrypted\":{(IsEncrypted ? "true" : "false")},"); + sb.Append($"\"activeConnections\":{stats.ActiveConnections},"); + sb.Append($"\"maxConnections\":{_config.MaxConnections},"); + sb.Append($"\"totalConnections\":{stats.TotalConnections},"); + sb.Append($"\"droppedConnections\":{stats.DroppedConnections},"); + sb.Append($"\"droppedPackets\":{stats.DroppedPackets},"); + sb.Append($"\"bytesSent\":{stats.BytesSent},"); + sb.Append($"\"bytesReceived\":{stats.BytesReceived},"); + sb.Append($"\"messagesSent\":{stats.MessagesSent},"); + sb.Append($"\"messagesReceived\":{stats.MessagesReceived},"); + sb.Append($"\"messagesPerSecond\":{stats.MessagesPerSecond.ToString("F2", CultureInfo.InvariantCulture)},"); + sb.Append($"\"lastDataSentUtc\":{(LastDataSent == default ? "null" : E(LastDataSent.ToString("O")))},"); + sb.Append($"\"uptimeSeconds\":{stats.Uptime.TotalSeconds.ToString("F1", CultureInfo.InvariantCulture)},"); + sb.Append($"\"startTimeUtc\":{E(stats.StartTime.ToString("O"))},"); + + sb.Append("\"clients\":["); + var clientList = _clients.Values.ToArray(); + for (int i = 0; i < clientList.Length; i++) + { + var c = clientList[i]; + if (i > 0) + { + sb.Append(","); + } + + sb.Append("{"); + sb.Append($"\"id\":{E(c.Id)},"); + sb.Append($"\"nickname\":{E(c.Nickname)},"); + sb.Append($"\"remoteEndPoint\":{E(c.RemoteEndPoint?.ToString())},"); + sb.Append($"\"connectedAtUtc\":{E(c.ConnectedAt.ToString("O"))},"); + sb.Append($"\"connectedTimeSeconds\":{c.ConnectedTime().TotalSeconds.ToString("F1", CultureInfo.InvariantCulture)},"); + sb.Append($"\"idleTimeSeconds\":{c.IdleTime().TotalSeconds.ToString("F1", CultureInfo.InvariantCulture)},"); + sb.Append($"\"bytesSent\":{c.BytesSent},"); + sb.Append($"\"bytesReceived\":{c.BytesReceived},"); + sb.Append($"\"lastDataSentUtc\":{(c.LastDataSent == default ? "null" : E(c.LastDataSent.ToString("O")))},"); + sb.Append($"\"lastDataReceivedUtc\":{(c.LastDataReceived == default ? "null" : E(c.LastDataReceived.ToString("O")))},"); + sb.Append($"\"isSecure\":{(c.IsSecure ? "true" : "false")},"); + sb.Append($"\"isEncrypted\":{(c.IsEncrypted ? "true" : "false")}"); + sb.Append("}"); + } + sb.Append("]"); + + sb.Append(",\"sslErrors\":{"); + sb.Append($"\"total\":{StatusPage.SslErrorCount},"); + var sslErrors = StatusPage.GetSslErrors(); + sb.Append("\"entries\":["); + for (int i = 0; i < sslErrors.Count; i++) + { + var se = sslErrors[i]; + if (i > 0) + { + sb.Append(","); + } + + sb.Append("{"); + sb.Append($"\"timestamp\":{E(se.Timestamp.ToString("O"))},"); + sb.Append($"\"clientId\":{E(se.ClientId)},"); + sb.Append($"\"nickname\":{E(se.Nickname)},"); + sb.Append($"\"message\":{E(se.Message)},"); + sb.Append($"\"exceptionType\":{E(se.ExceptionType)}"); + sb.Append("}"); + } + sb.Append("]}"); + + sb.Append("}"); + return sb.ToString(); + } + } +} diff --git a/EonaCat.Connections/Testing/StressTest.cs b/EonaCat.Connections/Testing/StressTest.cs new file mode 100644 index 0000000..f083f72 --- /dev/null +++ b/EonaCat.Connections/Testing/StressTest.cs @@ -0,0 +1,448 @@ +using EonaCat.Connections.Models; +using System.Collections.Concurrent; +using System.Diagnostics; +using System.Text; + +namespace EonaCat.Connections.Client.Tests +{ + + public class StressTest + { + public event EventHandler OnLog; + private readonly string _host; + private readonly int _port; + private readonly int _numberOfClients; + private readonly int _messagesPerClient; + private readonly string _messageTemplate; + + private ConcurrentDictionary _messagesSentByClient; + private ConcurrentDictionary _messagesReceivedByClient; + private ConcurrentDictionary> _receivedMessageIds; + private ConcurrentDictionary _clientErrors; + private List _clients; + private readonly Configuration _configuration; + + public StressTestResult Result { get; private set; } + + public StressTest(Configuration configuration, int numberOfClients = 10, + int messagesPerClient = 100, string messageTemplate = null) + { + _configuration = configuration ?? throw new ArgumentNullException(nameof(configuration)); + _numberOfClients = numberOfClients; + _messagesPerClient = messagesPerClient; + _messageTemplate = messageTemplate ?? "STRESS_TEST_MESSAGE_{0}_{1}"; + + _messagesSentByClient = new ConcurrentDictionary(); + _messagesReceivedByClient = new ConcurrentDictionary(); + _receivedMessageIds = new ConcurrentDictionary>(); + _clientErrors = new ConcurrentDictionary(); + _clients = new List(); + } + + public async Task RunAsync() + { + OnLog?.Invoke(this, new LogMessage { Type = LogType.Debug, Message = $"STARTING STRESS TEST" }); + OnLog?.Invoke(this, new LogMessage { Type = LogType.Debug, Message = $"Clients: {_numberOfClients}, Messages per client: {_messagesPerClient}" }); + OnLog?.Invoke(this, new LogMessage { Type = LogType.Debug, Message = $"Total messages to send: {_numberOfClients * _messagesPerClient}" }); + + var stopwatch = Stopwatch.StartNew(); + + try + { + + await CreateAndConnectClientsAsync(); + + await SendMessagesAsync(); + + await WaitForProcessingAsync(); + + stopwatch.Stop(); + + Result = GenerateReport(stopwatch.Elapsed); + + await PrintSummaryAsync(); + } + catch (Exception ex) + { + OnLog?.Invoke(this, new LogMessage { Type = LogType.Error, Message = $"ERROR: Stress test failed with exception: {ex.Message}" }); + OnLog?.Invoke(this, new LogMessage { Type = LogType.Error, Message = ex.StackTrace }); + } + finally + { + + await CleanupAsync(); + } + } + + private async Task CreateAndConnectClientsAsync() + { + if (_configuration == null) + { + throw new InvalidOperationException("Configuration must be provided before creating clients."); + } + + OnLog?.Invoke(this, new LogMessage { Type = LogType.Debug, Message = $"Creating {_numberOfClients} clients..." }); + + var connectionTasks = new List(); + + for (int i = 0; i < _numberOfClients; i++) + { + var clientId = $"StressClient_{i:D4}"; + var client = new NetworkClient(_configuration); + + _messagesSentByClient.TryAdd(clientId, 0); + _messagesReceivedByClient.TryAdd(clientId, 0); + _receivedMessageIds.TryAdd(clientId, new List()); + + var capturedClientId = clientId; + client.OnConnected += (sender, e) => + { + OnLog?.Invoke(this, new LogMessage { Type = LogType.Debug, Message = $"[{capturedClientId}] Connected" }); + }; + + client.OnDataReceived += (sender, e) => + { + HandleMessageReceived(capturedClientId, e.StringData); + }; + + client.OnGeneralError += (sender, e) => + { + _clientErrors.TryAdd(capturedClientId, new Exception(e.Exception?.Message ?? "Unknown error")); + OnLog?.Invoke(this, new LogMessage { Type = LogType.Error, Message = $"[{capturedClientId}] Error: {e.Exception?.Message}" }); + }; + + client.OnSocketError += (sender, e) => + { + _clientErrors.TryAdd(capturedClientId, new Exception(e.Exception?.Message ?? "Socket error")); + OnLog?.Invoke(this, new LogMessage { Type = LogType.Error, Message = $"[{capturedClientId}] Socket Error: {e.Exception?.Message}" }); + }; + + client.OnDisconnected += (sender, e) => + { + OnLog?.Invoke(this, new LogMessage { Type = LogType.Debug, Message = $"[{capturedClientId}] Disconnected" }); + }; + + _clients.Add(client); + + var connectTask = client.ConnectAsync().ContinueWith(t => + { + if (t.IsFaulted) + { + _clientErrors.TryAdd(capturedClientId, t.Exception); + OnLog?.Invoke(this, new LogMessage { Type = LogType.Error, Message = $"[{capturedClientId}] Failed to connect: {t.Exception?.Message}" }); + } + }); + + connectionTasks.Add(connectTask); + } + + await Task.WhenAll(connectionTasks); + OnLog?.Invoke(this, new LogMessage { Type = LogType.Debug, Message = $"All {_numberOfClients} clients connected.\n" }); + } + + private async Task SendMessagesAsync() + { + OnLog?.Invoke(this, new LogMessage { Type = LogType.Debug, Message = $"Sending {_messagesPerClient} messages from each of {_numberOfClients} clients..." }); + + var sendTasks = new List(); + + for (int clientIdx = 0; clientIdx < _clients.Count; clientIdx++) + { + var client = _clients[clientIdx]; + var clientId = $"StressClient_{clientIdx:D4}"; + + for (int msgIdx = 0; msgIdx < _messagesPerClient; msgIdx++) + { + var messageId = string.Format(_messageTemplate, clientIdx, msgIdx); + var message = $"{messageId}|{DateTime.UtcNow:O}"; + + var sendTask = SendMessageWithRetryAsync(client, clientId, message); + sendTasks.Add(sendTask); + + await Task.Delay(1); + } + } + + await Task.WhenAll(sendTasks); + OnLog?.Invoke(this, new LogMessage { Type = LogType.Debug, Message = $"All messages sent.\n" }); + } + + private async Task SendMessageWithRetryAsync(NetworkClient client, string clientId, string message, int maxRetries = 3) + { + for (int attempt = 0; attempt < maxRetries; attempt++) + { + try + { + await client.SendAsync(message); + _messagesSentByClient[clientId]++; + return; + } + catch (Exception ex) + { + if (attempt == maxRetries - 1) + { + OnLog?.Invoke(this, new LogMessage { Type = LogType.Error, Message = $"[{clientId}] Failed to send message after {maxRetries} attempts: {ex.Message}" }); + return; + } + await Task.Delay(100 * (attempt + 1)); + } + } + } + + private async void HandleMessageReceived(string clientId, string data) + { + try + { + + var parts = data.Split('|'); + if (parts.Length >= 1) + { + var messageId = parts[0]; + _messagesReceivedByClient[clientId]++; + _receivedMessageIds[clientId].Add(messageId); + } + } + catch (Exception ex) + { + OnLog?.Invoke(this, new LogMessage { Type = LogType.Error, Message = $"[{clientId}] Error processing received message: {ex.Message}" }); + } + } + + private async Task WaitForProcessingAsync() + { + OnLog?.Invoke(this, new LogMessage { Type = LogType.Debug, Message = "Waiting for messages to be processed..." }); + + var maxWaitTime = TimeSpan.FromSeconds(60); + var stopwatch = Stopwatch.StartNew(); + + while (stopwatch.Elapsed < maxWaitTime) + { + var totalSent = _messagesSentByClient.Values.Sum(); + var totalReceived = _messagesReceivedByClient.Values.Sum(); + + OnLog?.Invoke(this, new LogMessage { Type = LogType.Debug, Message = $"Progress: {totalReceived}/{totalSent} messages received ({(totalSent > 0 ? (totalReceived * 100 / totalSent) : 0)}%)" }); + + if (totalReceived >= totalSent && totalSent > 0) + { + OnLog?.Invoke(this, new LogMessage { Type = LogType.Debug, Message = "All messages received!\n" }); + return; + } + + await Task.Delay(1000); + } + + OnLog?.Invoke(this, new LogMessage { Type = LogType.Debug, Message = $"Timeout: Not all messages processed within {maxWaitTime.TotalSeconds} seconds\n" }); + } + + private StressTestResult GenerateReport(TimeSpan elapsed) + { + var result = new StressTestResult + { + TestDuration = elapsed, + TotalClientsCreated = _numberOfClients, + TotalClientsConnected = _clients.Count(c => c.IsConnected), + }; + + result.TotalMessagesSent = _messagesSentByClient.Values.Sum(); + result.TotalMessagesReceived = _messagesReceivedByClient.Values.Sum(); + result.DroppedMessages = result.TotalMessagesSent - result.TotalMessagesReceived; + result.DeliverySuccessRate = result.TotalMessagesSent > 0 + ? (result.TotalMessagesReceived * 100.0 / result.TotalMessagesSent) + : 0; + + result.PerClientStats = new Dictionary(); + for (int i = 0; i < _numberOfClients; i++) + { + var clientId = $"StressClient_{i:D4}"; + var sent = _messagesSentByClient.TryGetValue(clientId, out var s) ? s : 0; + var received = _messagesReceivedByClient.TryGetValue(clientId, out var r) ? r : 0; + + result.PerClientStats[clientId] = new ClientStats + { + MessagesSent = sent, + MessagesReceived = received, + DroppedMessages = sent - received, + SuccessRate = sent > 0 ? (received * 100.0 / sent) : 0 + }; + } + + result.ErrorCount = _clientErrors.Count; + result.Errors = _clientErrors.ToDictionary(kvp => kvp.Key, kvp => kvp.Value.Message); + + return result; + } + + private async Task PrintSummaryAsync() + { + if (Result == null) + { + OnLog?.Invoke(this, new LogMessage { Type = LogType.Debug, Message = "No test results available." }); + return; + } + + OnLog?.Invoke(this, new LogMessage { Type = LogType.Debug, Message = "STRESS TEST RESULTS" }); + + OnLog?.Invoke(this, new LogMessage { Type = LogType.Debug, Message = $"\nTest Duration: {Result.TestDuration.TotalSeconds:F2} seconds" }); + OnLog?.Invoke(this, new LogMessage { Type = LogType.Debug, Message = $"\nConnectivity:" }); + OnLog?.Invoke(this, new LogMessage { Type = LogType.Debug, Message = $" Clients Created: {Result.TotalClientsCreated}" }); + OnLog?.Invoke(this, new LogMessage { Type = LogType.Debug, Message = $" Clients Connected: {Result.TotalClientsConnected}" }); + + OnLog?.Invoke(this, new LogMessage { Type = LogType.Debug, Message = $"\nMessage Statistics:" }); + OnLog?.Invoke(this, new LogMessage { Type = LogType.Debug, Message = $" Total Messages Sent: {Result.TotalMessagesSent:N0}" }); + OnLog?.Invoke(this, new LogMessage { Type = LogType.Debug, Message = $" Total Messages Received: {Result.TotalMessagesReceived:N0}" }); + OnLog?.Invoke(this, new LogMessage { Type = LogType.Debug, Message = $" Dropped Messages: {Result.DroppedMessages:N0}" }); + OnLog?.Invoke(this, new LogMessage { Type = LogType.Debug, Message = $" Delivery Success Rate: {Result.DeliverySuccessRate:F2}%" }); + + if (Result.ErrorCount > 0) + { + OnLog?.Invoke(this, new LogMessage { Type = LogType.Debug, Message = $"\nErrors Encountered: {Result.ErrorCount}" }); + foreach (var error in Result.Errors.Take(10)) + { + OnLog?.Invoke(this, new LogMessage { Type = LogType.Debug, Message = $" [{error.Key}] {error.Value}" }); + } + if (Result.Errors.Count > 10) + { + OnLog?.Invoke(this, new LogMessage { Type = LogType.Debug, Message = $" ... and {Result.Errors.Count - 10} more errors" }); + } + } + + var messagesPerSecond = Result.TotalMessagesSent / Result.TestDuration.TotalSeconds; + var bytesPerSecond = (Result.TotalMessagesSent * 50) / Result.TestDuration.TotalSeconds; + + OnLog?.Invoke(this, new LogMessage { Type = LogType.Debug, Message = $"\nPerformance Metrics:" }); + OnLog?.Invoke(this, new LogMessage { Type = LogType.Debug, Message = $" Messages/Second: {messagesPerSecond:F2}" }); + OnLog?.Invoke(this, new LogMessage { Type = LogType.Debug, Message = $" Throughput: {(bytesPerSecond / 1024 / 1024):F2} MB/s (estimated)" }); + + OnLog?.Invoke(this, new LogMessage { Type = LogType.Debug, Message = $"\nPer-Client Breakdown (showing clients with issues):" }); + var problemClients = Result.PerClientStats + .Where(kvp => kvp.Value.DroppedMessages > 0) + .OrderByDescending(kvp => kvp.Value.DroppedMessages) + .Take(20); + + if (problemClients.Any()) + { + foreach (var client in problemClients) + { + OnLog?.Invoke(this, new LogMessage { Type = LogType.Debug, Message = $" [{client.Key}]" }); + OnLog?.Invoke(this, new LogMessage { Type = LogType.Debug, Message = $" Sent: {client.Value.MessagesSent:N0}" }); + OnLog?.Invoke(this, new LogMessage { Type = LogType.Debug, Message = $" Received: {client.Value.MessagesReceived:N0}" }); + OnLog?.Invoke(this, new LogMessage { Type = LogType.Debug, Message = $" Dropped: {client.Value.DroppedMessages:N0}" }); + OnLog?.Invoke(this, new LogMessage { Type = LogType.Debug, Message = $" Success: {client.Value.SuccessRate:F2}%" }); + } + } + else + { + OnLog?.Invoke(this, new LogMessage { Type = LogType.Debug, Message = " All clients: 100% success rate" }); + } + + if (Result.DeliverySuccessRate >= 99.9) + { + OnLog?.Invoke(this, new LogMessage { Type = LogType.Debug, Message = "✓ PASSED: Excellent message delivery rate" }); + } + else if (Result.DeliverySuccessRate >= 95) + { + OnLog?.Invoke(this, new LogMessage { Type = LogType.Debug, Message = "⚠ WARNING: Good delivery rate, but some messages were lost" }); + } + else + { + OnLog?.Invoke(this, new LogMessage { Type = LogType.Debug, Message = "✗ FAILED: Significant message loss detected" }); + } + } + + private async Task CleanupAsync() + { + OnLog?.Invoke(this, new LogMessage { Type = LogType.Debug, Message = "Cleaning up clients..." }); + + var disconnectTasks = _clients.Select(async client => + { + try + { + await client.DisconnectAsync(); + await client.DisposeAsync(); + } + catch (Exception ex) + { + OnLog?.Invoke(this, new LogMessage { Type = LogType.Error, Message = $"Error during cleanup: {ex.Message}" }); + } + }); + + await Task.WhenAll(disconnectTasks); + _clients.Clear(); + + OnLog?.Invoke(this, new LogMessage { Type = LogType.Debug, Message = "Cleanup complete.\n" }); + } + + public string ExportToCsv() + { + if (Result == null) + { + return "No results to export"; + } + + var csv = new StringBuilder(); + csv.AppendLine("Client ID,Messages Sent,Messages Received,Dropped,Success Rate (%)"); + + foreach (var stat in Result.PerClientStats) + { + csv.AppendLine($"{stat.Key},{stat.Value.MessagesSent},{stat.Value.MessagesReceived}," + + $"{stat.Value.DroppedMessages},{stat.Value.SuccessRate:F2}"); + } + + csv.AppendLine(); + csv.AppendLine($"Summary"); + csv.AppendLine($"Total Sent,{Result.TotalMessagesSent}"); + csv.AppendLine($"Total Received,{Result.TotalMessagesReceived}"); + csv.AppendLine($"Total Dropped,{Result.DroppedMessages}"); + csv.AppendLine($"Success Rate %,{Result.DeliverySuccessRate:F2}"); + csv.AppendLine($"Duration (seconds),{Result.TestDuration.TotalSeconds:F2}"); + + return csv.ToString(); + } + } + + public class StressTestResult + { + public TimeSpan TestDuration { get; set; } + public int TotalClientsCreated { get; set; } + public int TotalClientsConnected { get; set; } + public int TotalMessagesSent { get; set; } + public int TotalMessagesReceived { get; set; } + public int DroppedMessages { get; set; } + public double DeliverySuccessRate { get; set; } + public int ErrorCount { get; set; } + public Dictionary Errors { get; set; } = new(); + public Dictionary PerClientStats { get; set; } = new(); + } + + public class ClientStats + { + public int MessagesSent { get; set; } + public int MessagesReceived { get; set; } + public int DroppedMessages { get; set; } + public double SuccessRate { get; set; } + } + + public static class StressTestRunner + { + public static async Task RunQuickTestAsync(Configuration configuration, int numberOfClients = 10, int messagesPerClient = 100) + { + var test = new StressTest(configuration, numberOfClients, messagesPerClient); + await test.RunAsync(); + return test.Result; + } + + public static async Task RunIntensiveTestAsync(Configuration configuration, int numberOfClients = 50, int messagesPerClient = 1000) + { + var test = new StressTest(configuration, numberOfClients, messagesPerClient); + await test.RunAsync(); + return test.Result; + } + + public static async Task RunExtremeTestAsync(Configuration configuration, int numberOfClients = 100, int messagesPerClient = 5000) + { + var test = new StressTest(configuration, numberOfClients, messagesPerClient); + await test.RunAsync(); + return test.Result; + } + } +} diff --git a/EonaCat.Connections/icon.ico b/EonaCat.Connections/icon.ico index 406f2659ac50172f9307c0af9038f473b50b6598..9e7d412bada149610a55f28547f89aeb5583ea33 100644 GIT binary patch literal 7406 zcmeHLSxj7282)BsHkcV0E;9_=%P>G0D9f}RmJV$hC{$T0P(Ueap_F2cwRLF|qqT9V znpQ(y8jDt|O{Hm4YpQ80CN2-gsBwRAi4Q($;)D8N;u53AbIzT)y_~tgG~of$dy+f% z|Nrkh=gj%<+{yp_fB_~%A|Q7gPP>450Ks6ww*lXgn8zdgJ1oG%J|IjuWC}*fMdz_$ zmv8LTAlrpUX5fACQ&ipe1S%e!g5|YeF%dN&_xMK`UN51qCyMI*ldzxt5qRTYc&5Kb z=jN+0vL+h?T{YO&V8v+6g`5*#AmiLG=pJlA-gEC`yv~fG$6rOwzC&=F`5wmC|AKJ* zLzpi7f#}|QvG(ShU_JLU20JQI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Go-6pS z0C_PGav44OF~KPUVwMZ^+)X?Ba&P&2`i*aSZ^0#k#|6I=Fi-wZK@)!EzCQ?P*DnPR z3oaKNE?6oU;@Q4*)X+1HFd+IW@K5XacpbMB{Dt5P0{HC}0r_m1zo8E{p>6md-_@%E z==watE&|qF6u#T2vOT(~{O#cPWSws>I8tzd;Ol}%1V0qKAYiWXoB)}PzVbBzbC44R zD+J7E#|a8;3xD^h2}7?L!axB7A&o`OC+gZ#!Cr!s1=yKx7QmDIp$9|TKjVk~9unLr z_=Mn40e)!Ydz7vV73tzf7XI;E_*)+7@aG>XUlCp@mj5&5lhfsEC?B3KUq$)rlI8zJ z@vvblgBuFpchxIauu%R7dwxOc`Sn&FHlXl)t9*3o`8D=@*ucW`tE@b1V4>WKOP2~C zvpWix@*geq6c7}?tc9Keg2Hmwdwd~4Kv=%UzFz3Tu-q3HueIyfu3lKd;NDj6@RkMb zhl29;`TO$<2IXt=^1KIv@>O|x-UC5-UR=27s}fW{Xh42zQ2hYId3hVVe5c*OM0vY` zdHMRVer*!W%h!bEZ3N`ytHSa&0-BeHkLOQ?XW<!e%iF|hZ&}fLLC?wy z-II4f`~98D3*DEqNc;Kzmah-7H*A>i;P(4Bba}CQ?P~dxQunqy*q4{Ox6L8GyoA0s zf_-_Z`E3OG@-^l9wK%|+uPT?fIG|NtslIMzG zwDR?_`nxfSK zwdD(j4IAk48uFC_IBZyd%h#uSSCiyn!}?pkro;Pd%ZCpewxP>c)zx41t1W-sz?aum zZn|#kSNhU~ z#V0S0tE54>)RM}d*=t)jt*R6k-KuM<<<6Yxzp=hr-gY^0Pa9SFeGB}v96f>p`LH4^ z_Xtw?n$|1A;x+nWADno?+9yMfX_T1_cb zKl4hz^rKc&R<=LwPFh->^fNmvRo^#YrPn`8)$ OnConnected; -public event EventHandler OnConnectedWithNickname; -public event EventHandler OnDisconnected; +using EonaCat.Connections; +using EonaCat.Connections.Models; -// Data events -public event EventHandler OnDataReceived; - -// Error events -public event EventHandler OnSslError; -public event EventHandler OnEncryptionError; -public event EventHandler OnGeneralError; -public event EventHandler OnSocketError; - -// Heartbeat events -public event EventHandler OnClientPingResponse; -public event EventHandler OnPongMissed; - -// Idle/Timeout events -public event EventHandler OnIdleTimeout; - -// Logging -public event EventHandler OnLog; -``` - -### Properties - -```csharp -// Server Status -public bool IsStarted { get; } -public int Port { get; } -public int ActiveConnections { get; } -public int MaxConnections { get; } -public ProtocolType Protocol { get; } - -// Security Status -public bool IsSecure { get; } // TLS or AES enabled -public bool IsEncrypted { get; } // AES enabled - -// Statistics -public long DroppedPackets { get; } -public long DroppedConnections { get; } -public long TotalConnections { get; } -public long BytesSent { get; } -public long BytesReceived { get; } -public long MessagesSent { get; } -public long MessagesReceived { get; } -public double MessagesPerSecond { get; } -public TimeSpan Uptime { get; } -public DateTime StartTime { get; } -public DateTime LastDataSent { get; } -public DateTime LastDataReceived { get; } - -// Status Pages -public ServerStatusPage ServerStatus { get; } -public SocketStatusPage StatusPage { get; } -public HealthApiServer HealthApi { get; } - -// Debug -public bool DEBUG_DATA_SEND { get; set; } -public bool DEBUG_DATA_RECEIVED { get; set; } -``` - -### Core Methods - -```csharp -// Lifecycle -public Task StartAsync(); -public void Stop(); -public async Task StopAsync(); -public Task StartTcpServerAsync(); -public async Task StartUdpServerAsync(CancellationToken token); -public async Task StopTcpServerAsync(); - -// Client Management -public Dictionary GetClients(); -public List GetClient(string clientId); -public async Task DisconnectClientAsync(string clientId, DisconnectReason reason, Exception? exception); - -// Messaging - Send to Specific Client -public async Task SendToClientAsync(string clientId, byte[] data); -public async Task SendToClientAsync(string clientId, string message); - -// Messaging - Client-to-Client -public async Task SendFromClientToClientAsync(string fromClientId, string toClientId, byte[] data); -public async Task SendFromClientToClientAsync(string fromClientId, string toClientId, string message); - -// Broadcast Messaging -public async Task BroadcastAsync(byte[] data); -public async Task BroadcastAsync(string message); - -// Request-Response Patterns -public async Task SendToClientAndWaitForResponseAsync( - string clientId, byte[] data, TimeSpan? timeout = null); -public async Task SendToClientAndWaitForResponseAsync( - string clientId, string message, TimeSpan? timeout = null); - -public async Task SendFromClientToClientAndWaitForResponseAsync( - string fromClientId, string toClientId, byte[] data, TimeSpan? timeout = null); -public async Task SendFromClientToClientAndWaitForResponseAsync( - string fromClientId, string toClientId, string message, TimeSpan? timeout = null); - -public async Task> BroadcastAndWaitForResponsesAsync( - byte[] data, TimeSpan? timeout = null); -public async Task> BroadcastAndWaitForResponsesAsync( - string message, TimeSpan? timeout = null); - -// Configuration -public void SetSeparator(string separator); -public void SetSeparator(byte[] separator); - -// Statistics -public Stats GetStats(); - -// Cleanup -public void Dispose(); -``` - - - -## NetworkClient API - -### Events - -```csharp -// Connection events -public event EventHandler OnConnected; -public event EventHandler OnNicknameSend; -public event EventHandler OnDisconnected; - -// Data events -public event EventHandler OnDataReceived; - -// Error events -public event EventHandler OnSslError; -public event EventHandler OnEncryptionError; -public event EventHandler OnGeneralError; -public event EventHandler OnSocketError; - -// Heartbeat events -public event EventHandler OnPingResponse; -public event EventHandler OnPongResponse; - -// Idle/Timeout events -public event EventHandler OnIdleTimeout; - -// Logging -public event EventHandler OnLog; -``` - -### Properties - -```csharp -// Connection Status -public bool IsConnected { get; set; } -public int Port { get; } - -// Connection Time Metrics -public DateTime ConnectionTime { get; } -public TimeSpan Uptime { get; } -public DateTime LastActive { get; } -public int IdleTimeInSeconds(); -public int IdleTimeInMinutes(); -public int IdleTimeInHours(); -public int IdleTimeInDays(); -public int ConnectedTimeInSeconds(); -public int ConnectedTimeInMinutes(); -public int ConnectedTimeInHours(); -public int ConnectedTimeInDays(); - -// Security Status -public bool IsSecure { get; } // TLS or AES enabled -public bool IsEncrypted { get; } // AES enabled -public bool IsTcp { get; } - -// Statistics -public long BytesSent { get; } -public long BytesReceived { get; } -public long MessagesSent { get; } -public long MessagesReceived { get; } - -// Heartbeat -public bool DisconnectOnMissedPong { get; set; } -public bool EnableKeepAlive { get; set; } - -// Auto-Reconnect -public bool IsAutoConnectStarted { get; } -public bool IsIdleTimeoutTriggered { get; } - -// Debug -public bool DEBUG_DATA_SEND { get; set; } -public bool DEBUG_DATA_RECEIVED { get; set; } -``` - -### Core Methods - -```csharp -// Connection Lifecycle -public async Task ConnectAsync(); -public async Task DisconnectAsync(); -public async Task DisconnectDueTimeoutAsync(); - -// Messaging -public async Task SendAsync(byte[] data); -public async Task SendAsync(string message); - -// Nickname -public async Task SendNicknameAsync(string nickname); - -// Request-Response -public async Task SendAndWaitForResponseAsync( - byte[] data, TimeSpan? timeout = null); -public async Task SendAndWaitForResponseAsync( - string message, TimeSpan? timeout = null); -public async Task SendNicknameAndWaitForResponseAsync( - string nickname, TimeSpan? timeout = null); - -// Cleanup -public void Dispose(); -``` - - - -## Message Framing Modes - -Three message framing modes are supported: - -### 1. None (Default) -Raw bytes sent as-is, no frame boundaries marked: -```csharp -config.MessageFraming = FramingMode.None; -``` - -### 2. Delimiter -Messages separated by a delimiter byte sequence (default: %): -```csharp -config.MessageFraming = FramingMode.Delimiter; -config.Delimiter = Encoding.UTF8.GetBytes("%"); -``` - -### 3. Length-Prefixed -Messages prefixed with their length as bytes: -```csharp -config.MessageFraming = FramingMode.LengthPrefixed; -config.LengthPrefixedLength = 4; // 4-byte prefix -``` - - - -## SSL/TLS Certificate Setup - -### Generate self-signed certificate for TLS (TCP): -Run the following in PowerShell as Administrator: - -```powershell -$cert = New-SelfSignedCertificate ` - -DnsName "localhost" ` - -CertStoreLocation "Cert:\LocalMachine\My" ` - -KeyExportPolicy Exportable ` - -NotAfter (Get-Date).AddYears(5) ` - -FriendlyName "EonaCat Connections Test Certificate" - -$password = ConvertTo-SecureString -String "p@ss" -Force -AsPlainText - -Export-PfxCertificate ` - -Cert "Cert:\LocalMachine\My\$($cert.Thumbprint)" ` - -FilePath "C:\temp\server.pfx" ` - -Password $password -``` - -This creates a self-signed certificate with password `p@ss` in `C:\temp\server.pfx`. - - - -## Advanced Features - -### Auto-Reconnection -The client automatically reconnects on disconnect: -```csharp -config.EnableAutoReconnect = true; // Enable auto-reconnect -config.ReconnectDelayInSeconds = 5; // Delay before retry -config.MaxReconnectAttempts = 0; // 0 = unlimited attempts -``` - -### Heartbeat (Ping-Pong) -Keep connections alive and detect dead connections: -```csharp -config.EnableHeartbeat = true; -config.HeartbeatIntervalSeconds = 5; -config.DisconnectOnMissedPong = true; // Disconnect if pong not received -``` - -### Idle Detection -Automatically disconnect idle connections: -```csharp -config.IdleTimeoutSeconds = 30; // 0 = disabled -``` - -### Request-Response Patterns -Send a message and wait for a response with timeout: -```csharp -// Server sends message and waits for client response -var response = await server.SendToClientAndWaitForResponseAsync( - clientId, "question", TimeSpan.FromSeconds(5)); - -if (response != null) +var configuration = new Configuration { - Console.WriteLine($"Got response: {response.StringData}"); + Protocol = ProtocolType.TCP, + Host = "127.0.0.1", + Port = 5050 +}; + +using var server = new NetworkServer(configuration); + +server.OnConnected += (_, connection) => + Console.WriteLine($"Connected: {connection.ClientId} from {connection.RemoteEndPoint}"); + +server.OnDataReceived += async (_, message) => +{ + Console.WriteLine($"Received from {message.ClientId}: {message.StringData}"); + await server.SendToClientAsync(message.ClientId, $"Echo: {message.StringData}"); +}; + +server.OnDisconnected += (_, connection) => + Console.WriteLine($"Disconnected: {connection.ClientId} ({connection.Reason})"); + +await server.StartAsync(); +Console.WriteLine("Listening. Press Ctrl+C to stop."); + +using var stop = new CancellationTokenSource(); +Console.CancelKeyPress += (_, eventArgs) => +{ + eventArgs.Cancel = true; + stop.Cancel(); +}; + +try +{ + await Task.Delay(Timeout.Infinite, stop.Token); +} +catch (OperationCanceledException) +{ + // Ctrl+C requested shutdown. +} +finally +{ + await server.StopAsync(); +} +``` + +`StartAsync()` starts the listener and returns; it does not block until the server stops. Use `StopAsync()` for an awaited shutdown. + +### Client + +```csharp +using EonaCat.Connections; +using EonaCat.Connections.Models; + +var configuration = new Configuration +{ + Protocol = ProtocolType.TCP, + Host = "127.0.0.1", + Port = 5050, + EnableAutoReconnect = true +}; + +using var client = new NetworkClient(configuration); + +client.OnConnected += (_, connection) => + Console.WriteLine($"Connected to {connection.RemoteEndPoint}"); + +client.OnDataReceived += (_, message) => + Console.WriteLine($"Server replied: {message.StringData}"); + +client.OnDisconnected += (_, connection) => + Console.WriteLine($"Disconnected: {connection.Reason}"); + +if (await client.ConnectAsync()) +{ + await client.SendAsync("Hello from the client"); } -// Client sends message and waits for server response +await client.DisconnectAsync(); +``` + +`ConnectAsync()` returns whether the connection succeeded. `WaitForConnectedAsync(timeout, cancellationToken)` can be used to await the next successful connection event. Dispose clients when finished. + +## Sending and Receiving + +### Text and binary data + +String overloads encode and decode UTF-8. Use byte-array overloads for binary protocols or when the application owns serialization: + +```csharp +byte[] payload = [0x01, 0x02, 0x03]; +await client.SendAsync(payload, cancellationToken); + +await server.SendToClientAsync(clientId, payload, cancellationToken); +await server.BroadcastAsync("Service maintenance in five minutes"); +``` + +`DataReceivedEventArgs` provides `Data` (raw bytes), `StringData` (UTF-8 text), `IsBinary`, `ClientId`, `Nickname`, `RemoteEndPoint`, and `Timestamp`. + +### Request and response + +The convenience methods send data and wait for the next matching received message. The default timeout is 30 seconds; pass a timeout and cancellation token to override it. + +```csharp var response = await client.SendAndWaitForResponseAsync( - "answer", TimeSpan.FromSeconds(5)); -``` + "status", + timeout: TimeSpan.FromSeconds(5), + cancellationToken); -### Health API -Enable a lightweight REST API for server monitoring: -```csharp -config.EnableHealthApi = true; -config.HealthApiPort = 0; // Random port -config.HealthApiBindAddress = IPAddress.Any; // For Docker/containers - -// After server starts, access the API: -// http://localhost:{HealthApi.Port}/health -// http://localhost:{HealthApi.Port}/stats -``` - -### Status Pages -Auto-generate HTML status reports: -```csharp -config.EnableServerStatusPage = true; -config.ServerStatusPageIntervalSeconds = 5; - -config.EnableAutoHtmlReports = true; -config.HtmlReportOutputDirectory = "./reports"; -config.HtmlReportIntervalSeconds = 60; -``` - -### SSL Diagnostics -Enable detailed SSL handshake diagnostics: -```csharp -config.EnableSslDiagnostics = true; -// Access via: server.StatusPage.SslMetrics -``` - -### Network Monitoring -Monitor network health and detect outages: -```csharp -var monitor = new NetworkMonitor(); -monitor.OnNetworkOutageDetected += (s, e) => +if (response is not null) { - Console.WriteLine($"Network outage detected: {e.Duration}"); + Console.WriteLine(response.StringData); +} +``` + +On the server, use `SendToClientAndWaitForResponseAsync`, `SendFromClientToClientAndWaitForResponseAsync`, or `BroadcastAndWaitForResponsesAsync`. These helpers do not define application-level request IDs. If concurrent requests can overlap, include a correlation ID in your protocol and match responses in your application. + +### Nicknames and client addressing + +Clients can send or update a nickname with `SendNicknameAsync("worker-1")`. The server raises `OnConnectedWithNickname` when it receives a nickname. Server send methods can address a client by its client ID, endpoint, or nickname. `GetClient(clientId)` returns the connected client matches; `GetClients()` returns the client registry. + +```csharp +await client.SendNicknameAsync("worker-1"); +await server.SendToClientAsync("worker-1", "You are registered"); +``` + +The server can also forward data to another client with `SendFromClientToClientAsync(fromClientId, toClientId, data)`. The server sends to the destination; the `fromClientId` identifies the source for missing-client diagnostics. + +### Connection management + +`ConnectAsync()` returns `true` when the initial connection succeeds. `WaitForConnectedAsync(timeout, cancellationToken)` waits for a successful client connection event and returns `false` if the wait ends without a connection. `IsConnected`, `ConnectionTime`, `Uptime`, `LastActive`, `LastDataSent`, `LastDataReceived`, `BytesSent`, `BytesReceived`, `MessagesSent`, and `MessagesReceived` expose client state and counters. Idle and connected durations are also available as `TimeSpan`, integer units, or formatted strings. + +When enabled, client auto-reconnect starts after a client has connected once and a later connection is lost. A client-requested disconnect stops reconnecting. `MaxReconnectAttempts = 0` removes the configured attempt limit for a reconnect sequence; repeated sequences are still bounded by the client's consecutive-failure protection. SSL/TLS connection retries are controlled separately by `SSLMaxRetries`, `SSLRetryDelayInSeconds`, and the retry-delay settings. A zero SSL retry count means the retry loop has no configured maximum, so use cancellation or a finite limit when indefinite retries are not appropriate. + +On the server, `WaitForClientAsync(clientId, timeout, cancellationToken)` waits for a client with that exact ID. `DisconnectClientAsync` removes a client and records the supplied `DisconnectReason`. `GetClient(clientId)` can resolve a client ID, nickname, or remote endpoint; endpoint hostnames are resolved to addresses, and a nickname shared by multiple clients can return more than one result. `GetClients()` returns the registry. Send methods return `false` when there is no matching connected client or when no send succeeds; a missing target also raises `OnClientMissing`. + +Server unicast, broadcast, and client-to-client forwarding have byte and UTF-8 string overloads. Send and response helpers accept timeouts and cancellation tokens. `BroadcastAndWaitForResponsesAsync` collects responses until the timeout or expected response count; these helpers do not correlate overlapping application requests, so include your own request ID when concurrent calls are possible. With UDP, a client registry entry is keyed by its endpoint and exists after the first datagram; UDP still does not provide a reliable session or delivery guarantee. + +## Message Framing + +TCP is a byte stream; a single send is not guaranteed to arrive as one receive operation. `MessageFraming.None` (the default) forwards received data without reconstructing application message boundaries. Choose framing when each received event must represent one complete message, and configure both ends consistently. + +```csharp +var configuration = new Configuration +{ + Protocol = ProtocolType.TCP, + Host = "127.0.0.1", + Port = 5050, + MessageFraming = FramingMode.LengthPrefixed, + LengthPrefixedLength = 4, + UseBigEndian = true, + MAX_MESSAGE_SIZE = 1024 * 1024 }; ``` +Available modes: +- `FramingMode.None`: no message-boundary reconstruction. +- `FramingMode.LengthPrefixed`: a length header followed by the payload. Prefix sizes from 1 to 8 bytes are supported. The default is 4 bytes; `UseBigEndian` controls byte order and defaults to `false` (little-endian). +- `FramingMode.Delimiter`: payloads end at a delimiter. The default delimiter is `%`. Servers also expose `SetSeparator(string)` and `SetSeparator(byte[])`; configure the same delimiter on both peers. -## Server Example +`MAX_MESSAGE_SIZE` limits message payload size. It is not a substitute for application-level validation. + +## Protocols and Encryption + +### TCP and UDP + +Set `Configuration.Protocol` to `ProtocolType.TCP` or `ProtocolType.UDP`. TCP supports stream-oriented communication and the library's TLS option. UDP is datagram-oriented and does not provide TCP's delivery or ordering guarantees. For UDP broadcast, set `EnableBroadcast = true` where applicable. + +### TLS + +TLS is enabled by configuring an `X509Certificate2` on `Configuration`; certificate validation and client-certificate behavior are controlled by the certificate and TLS settings. Configure valid certificates and trust on the communicating peers. Do not enable `IsSelfSignedEnabled` in production: it accepts certificates without normal certificate validation. `TrustedThumbprints`, `CheckCertificateRevocation`, `MutuallyAuthenticate`, `AdditionalCertificates`, and `AllowTlsRenegotiation` provide additional certificate and handshake controls. + +### AES encryption + +Set `UseAesEncryption = true` and provide an `AesPassword` on both peers to enable the library's AES key exchange and payload encryption. Keep the password secret and deliver it through a secure configuration mechanism; do not commit it to source control. TLS is generally preferable for protecting data in transit and authenticating the remote endpoint. + +### Custom protocol abstractions + +`NetworkClient` and `NetworkServer` currently select only `ProtocolType.TCP` or `ProtocolType.UDP`; they do not call `Configuration.GetProtocol()` or use `ProtocolFactory` to replace their transport. The protocol interface and registry are available for applications that create and manage protocol instances directly. `Configuration.GetProtocol()` creates an instance from `ProtocolFactory` or the built-in registry and applies the configured buffer, Nagle, reset, broadcast, keep-alive, and SSL options. + +To register and create a protocol instance: ```csharp -using EonaCat.Connections; using EonaCat.Connections.Models; -using System.Security.Cryptography.X509Certificates; +using EonaCat.Connections.Protocols; -namespace EonaCat.Connections.Server.Example +ProtocolFactory.RegisterProtocol("CUSTOM", () => new MyNetworkProtocol()); + +var configuration = new Configuration { - public class Program - { - private static NetworkServer _server; + Host = "example.net", + Port = 7000, + ProtocolFactory = () => ProtocolFactory.CreateProtocol("CUSTOM") +}; - public static void Main(string[] args) - { - CreateServerAsync().GetAwaiter().GetResult(); - - while (true) - { - Console.Write("Enter message to broadcast (or 'exit' to quit): "); - var message = Console.ReadLine(); - - if (!string.IsNullOrEmpty(message) && message.Equals("exit", StringComparison.OrdinalIgnoreCase)) - { - _server.StopAsync().GetAwaiter().GetResult(); - _server.Dispose(); - Console.WriteLine("Server stopped."); - break; - } - - if (!string.IsNullOrEmpty(message)) - { - _server.BroadcastAsync(message).GetAwaiter().GetResult(); - } - } - } - - private static async Task CreateServerAsync() - { - var config = new Configuration - { - Protocol = ProtocolType.TCP, - Port = 1111, - Certificate = new X509Certificate2("server.pfx", "p@ss"), // Enables TLS - UseAesEncryption = true, - AesPassword = "EonaCat.Connections.Password", - MaxConnections = 100000, - EnableHeartbeat = true, - HeartbeatIntervalSeconds = 5, - IdleTimeoutSeconds = 30, - EnableHealthApi = true, - HealthApiPort = 8888, - }; - - _server = new NetworkServer(config); - - // Connection events - _server.OnConnected += (sender, e) => - Console.WriteLine($"[CONNECTED] Client {e.ClientId} from {e.RemoteEndPoint}"); - - _server.OnConnectedWithNickname += (sender, e) => - Console.WriteLine($"[NICKNAME] Client {e.ClientId} identified as: {e.Nickname}"); - - // Data reception - _server.OnDataReceived += async (sender, e) => - { - var clientName = e.HasNickname ? e.Nickname : e.ClientId; - Console.WriteLine($"[DATA] From {clientName}: {(e.IsBinary ? $"{e.Data.Length} bytes" : e.StringData)}"); - - // Echo response - if (e.IsBinary) - { - await _server.SendToClientAsync(e.ClientId, e.Data); - } - else - { - await _server.SendToClientAsync(e.ClientId, $"Echo: {e.StringData}"); - } - }; - - // Disconnection - _server.OnDisconnected += (sender, e) => - { - var clientName = e.HasNickname ? e.Nickname : e.ClientId; - Console.WriteLine($"[DISCONNECTED] {clientName} ({e.DisconnectReason})"); - }; - - // Error handling - _server.OnGeneralError += (sender, e) => - Console.WriteLine($"[ERROR] {e.Message}"); - - _server.OnSslError += (sender, e) => - Console.WriteLine($"[SSL ERROR] {e.Message}"); - - // Idle connections - _server.OnIdleTimeout += (sender, e) => - Console.WriteLine($"[IDLE] Client disconnected due to timeout: {e.ClientId}"); - - // Heartbeat - _server.OnPongMissed += (sender, e) => - Console.WriteLine($"[HEARTBEAT] Pong missed from {e.ClientId}"); - - Console.WriteLine("Server starting..."); - await _server.StartAsync(); - Console.WriteLine($"Server listening on port {_server.Port}"); - Console.WriteLine($"Health API available on: http://localhost:8888/health"); - } - } +using var protocol = configuration.GetProtocol(); +byte[] payload = [0x01, 0x02, 0x03]; +using var cancellation = new CancellationTokenSource(); +var cancellationToken = cancellation.Token; +if (await protocol.ConnectAsync(configuration.Host, configuration.Port, cancellationToken)) +{ + await protocol.SendAsync(payload, cancellationToken); } ``` +`INetworkProtocol` defines connection, send/receive, cleanup, configuration, and endpoint/socket access members. `ProtocolFactory` can register, create, query, list, and unregister custom registrations; built-in TCP and UDP registrations cannot be removed. Return a fresh disposable instance for each independent connection. Implement the configuration hooks your protocol supports; `IBroadcastConfigurableProtocol` adds the optional broadcast hook. This low-level API does not automatically add core message framing, lifecycle events, client registry, reconnect, or server send helpers to the custom transport. See [Custom Crap/CUSTOMPROTOCOLS.md](Custom%20Crap/CUSTOMPROTOCOLS.md) for the interface implementation example. +## Server Protections -## Client Example +Server controls are configured through `Configuration.Security` (`SecurityOptions`). Implemented protections include: + +- Global and per-connection message rate limits. +- Payload size, empty-message, null-byte, and suspicious-content checks. +- DDoS and Slowloris detection. +- IP allow/deny lists, temporary blocking, and automatic blocking after violations. +- Security logging and counters for enabled protections. + +Example: + +```csharp +var configuration = new Configuration +{ + Host = "0.0.0.0", + Port = 5050, + Security = new SecurityOptions + { + EnableGlobalRateLimiting = true, + GlobalMessagesPerSecond = 20_000, + EnablePerConnectionRateLimiting = true, + ConnectionMessagesPerSecond = 2_000, + EnablePayloadValidation = true, + MaxPayloadSize = 1024 * 1024, + EnableIPFiltering = true, + WhitelistedIPs = new HashSet { "127.0.0.1" } + } +}; +``` + +`SecurityOptions` enables global and per-connection rate limiting, security logging, and null-byte blocking by default. Payload validation, suspicious-content detection, DDoS detection, Slowloris detection, and IP filtering default to disabled. The controls apply to server-side incoming connections and messages; they do not provide user authentication or authorization. Tune limits for the expected traffic and payload profile. These controls complement, but do not replace, operating-system firewalls, network-layer protections, or application authorization. + +| Security setting | Default | Effect when implemented | +| --- | ---: | --- | +| `EnableGlobalRateLimiting`, `GlobalMessagesPerSecond` | `true`, `50000` | Caps the aggregate incoming message rate. | +| `EnablePerConnectionRateLimiting`, `ConnectionMessagesPerSecond` | `true`, `10000` | Caps messages per client connection. | +| `EnablePayloadValidation`, `MaxPayloadSize` | `false`, 50 MiB | Rejects payloads above this configured size when validation is enabled. The core `MAX_MESSAGE_SIZE` remains a separate limit. | +| `ValidateMessageNotEmpty` | `false` | Rejects empty payloads independently of the size-validation toggle. | +| `BlockNullBytePayloads` | `true` | Rejects payloads containing a zero byte. Disable it for binary protocols that legitimately use zero bytes. | +| `EnableSuspiciousContentDetection` | `false` | Checks valid UTF-8 text for SQL-like, script, and path-traversal patterns. Invalid UTF-8 binary payloads are not scanned. Pattern matching is heuristic, not application-level validation. | +| `EnableDDoSDetection`, `MaxConnectionsPerSecondPerIp`, `ConnectionSpamThreshold`, `SpamDetectionWindowSeconds` | `false`, `100`, `10`, `5` | Tracks connection attempts by IP and can reject traffic classified as suspicious. | +| `EnableSlowlorisDetection`, `SlowlorisMinBytesPerSecond`, `SlowlorisDetectionWindowSeconds` | `false`, `1024`, `30` | Detects clients whose received-byte rate falls below the configured threshold. | +| `EnableIPFiltering`, `WhitelistedIPs`, `BlacklistedIPs` | `false`, empty, empty | Enables IP allow/deny lists. Explicitly configure the lists before enabling filtering. | +| `AutoBlockIPAfterViolations`, `IPBlockDurationSeconds` | `0`, `300` | A positive violation threshold temporarily blocks an IP when IP filtering is enabled; zero disables automatic blocking. | +| `EnableSecurityLogging` | `true` | Emits logs when security checks reject or limit traffic. | + +The following properties are present in `SecurityOptions` but are not currently enforced by the core network paths: `EnableHTTPAttackDetection`, `MaxHTTPHeaderSize`, `MaxHTTPHeaders`, `EnableSYNFloodDetection`, `MaxHalfOpenConnectionsPerIp`, `EnableRequestDeduplication`, `DeduplicationWindowSeconds`, `EnableSecurityMetrics`, and `MessageTimeoutSeconds`. Setting them does not activate the named behavior. `GetSecurityMetrics()` reports counters for implemented protections regardless of `EnableSecurityMetrics`. + +The lower-level `RateLimiter`, `PerConnectionRateLimiter`, `DDoSDetector`, `SlowlorisDetector`, `IPBlocklist`, and `PayloadValidator` classes can also be used directly. `RequestDeduplicator` hashes payloads and tracks repeated hashes in a time window, but it is not currently connected to `NetworkServer` message processing. + +## Configuration Reference + +`Configuration` is shared by the client or server created from it. The defaults below are from the core package; separate transports use only the settings relevant to their transport. + +| Setting | Purpose | +| --- | --- | +| `Protocol`, `Host`, `Port` | Select TCP/UDP and the endpoint. The default protocol is TCP; the default endpoint is `127.0.0.1:8080`. | +| `ProtocolFactory` | Optional custom `INetworkProtocol` factory used by `Configuration.GetProtocol()`. It does not replace the transports in `NetworkClient` or `NetworkServer`. | +| `MaxConnections` | Maximum server connection limit. | +| `BufferSize`, `MAX_MESSAGE_SIZE` | I/O buffer and maximum accepted message size. The defaults are `BufferSizeMaximum.Huge` and `MessageSizeMaximum.Default`. | +| `MessageFraming`, `Delimiter`, `LengthPrefixedLength`, `UseBigEndian` | TCP message framing and length-prefix format. `Delimiter` defaults to `%`; the default prefix length is 4 bytes and default byte order is little-endian. | +| `EnableAutoReconnect`, `MaxReconnectAttempts` | Client reconnect policy. Auto-reconnect defaults on; a maximum of zero means no configured per-sequence attempt limit. Repeated retry sequences stop after the internal consecutive-failure cutoff. | +| `ReconnectDelayInSeconds` | Public setting currently not read by the core reconnect loop; retries use its implemented backoff instead. | +| `SSLMaxRetries`, `SSLRetryDelayInSeconds`, `UseExponentialBackoffForSslRetries`, `SSLRetryDelayMaxSeconds` | Connect/TLS retry policy. Zero retry count means no configured maximum. The exponential delay helper is used by the server handshake path; the TCP client currently uses the fixed delay. | +| `SSLTimeoutInSeconds` | Public setting currently not read by the core connection paths. Use `ConnectionTimeout` and cancellation for actual connection timeout behavior. | +| `EnableKeepAlive`, `KeepAliveTimeSeconds`, `KeepAliveIntervalSeconds`, `KeepAliveRetryCount` | TCP keep-alive behavior. | +| `EnableHeartbeat`, `HeartbeatIntervalSeconds`, `DisconectOnMissedPong` | Application-level ping/pong heartbeat behavior. | +| `ConnectionTimeout`, `ReadTimeoutSeconds`, `WriteTimeoutSeconds` | Connection and I/O timeouts. | +| `Certificate`, `AdditionalCertificates`, `TrustedThumbprints`, `CheckCertificateRevocation`, `MutuallyAuthenticate`, `AllowTlsRenegotiation`, `IsSelfSignedEnabled` | TLS certificate and trust controls. `UseSsl` is derived from whether `Certificate` is set; `AdditionalCertificates` supplies chain certificates and `TrustedThumbprints` provides explicit thumbprint trust. Revocation checks and renegotiation are off by default. `MutuallyAuthenticate` enables client-certificate authentication. `IsSelfSignedEnabled` bypasses normal validation and is unsafe in production. | +| `UseAesEncryption`, `AesPassword` | Optional AES payload encryption. | +| `EnableNagle`, `EnableRST`, `EnableDualStack`, `EnableBroadcast` | `EnableNagle` controls TCP Nagle buffering; `EnableRST` configures reset-on-close; `EnableDualStack` enables IPv4/IPv6 server listeners where supported; `EnableBroadcast` enables UDP broadcast. All default to `false`. | +| `EnableConnectionDebugLogs`, `EnablePingPongLogs`, `EnableSslDiagnostics` | Diagnostic logging options. | +| `EnableHealthApi`, `HealthApiPort`, `HealthApiBindAddress` | Optional health/status listener. Port `0` asks the OS for an available port; the default bind address is loopback. | +| `EnableAutoHtmlReports`, `HtmlReportOutputDirectory`, `HtmlReportIntervalSeconds` | Periodic socket diagnostic HTML reports. | +| `EnableServerStatusPage`, `ServerStatusPageIntervalSeconds` | Periodic server status report. | +| `IsRunningInContainer`, `DisableInternalCertificateCheck()` | Runtime/container detection and an option to disable the library's built-in trusted-thumbprint check. This does not make an untrusted certificate safe to accept. | + +Convenience methods `UseContainerDefaults()`, `UseHighScaleProduction()`, and `UseDistributedProduction()` adjust selected defaults. Review their values against your deployment rather than treating them as universal tuning profiles. + +`UseContainerDefaults()` binds the primary endpoint and health listener to all interfaces. `UseHighScaleProduction()` raises the connection limit, disables verbose connection/ping logging, and adjusts TCP keep-alive intervals. `UseDistributedProduction()` changes the connection limit and socket options. These methods do not configure certificates, secrets, firewall rules, or application authorization. + +## Events and Monitoring + +### Client events + +`NetworkClient` exposes `OnConnected`, `OnDisconnected`, `OnDataReceived`, `OnNicknameSend`, `OnSslError`, `OnEncryptionError`, `OnGeneralError`, `OnSocketError`, `OnPingResponse`, and `OnPongResponse`. + +### Server events + +`NetworkServer` exposes `OnConnected`, `OnConnectedWithNickname`, `OnDisconnected`, `OnDataReceived`, `OnClientMissing`, `OnSslError`, `OnEncryptionError`, `OnGeneralError`, `OnSocketError`, `OnClientPingResponse`, and `OnPongMissed`. + +`OnConnected` and `OnDisconnected` report lifecycle changes; nickname events report a nickname being sent or registered; `OnDataReceived` reports each payload delivered by the configured framing mode. Errors are separated by TLS, AES, socket, and general failures. Server `OnClientMissing` reports failed addressing, and ping/pong events report heartbeat responses or missed responses. Event handlers should return quickly; queue longer work elsewhere so receive processing is not delayed. + +Both types expose byte/message counters, connection state, and a `StatusPage` for socket diagnostics. The server additionally provides `ActiveConnections`, `TotalConnections`, `DroppedConnections`, `DroppedPackets`, `MessagesPerSecond`, `Uptime`, `GetStats()`, and `GetSecurityMetrics()`. `HealthApi` is available on both types; configure `EnableHealthApi` and its bind address to enable the optional API. Server status reporting is controlled by `EnableServerStatusPage`. + +`Stats.MessagesPerSecond` is the cumulative number of received messages divided by uptime, not a short-window throughput gauge. `ConnectionEventArgs` carries client ID, nickname, endpoint, timestamp, disconnect reason, exception, initiator, reason details, and diagnostic context. `DataReceivedEventArgs` carries raw bytes and metadata; `StringData` decodes those bytes as UTF-8 even when `IsBinary` is true. `ErrorEventArgs` carries the exception and message. Ping event args identify the peer and response time. + +Disconnect reasons distinguish local/remote closure, timeout, TLS or encryption failure, missed pong, protocol error, buffer overflow, common socket failures such as reset/refused/unreachable, and server shutdown. `ConnectionEventArgs.Determine` maps common socket and transport exceptions to a reason. Inspect `Exception` and diagnostic context as well as the enum when handling disconnects. + +The static `NetworkClient.OnLog` and `NetworkServer.OnLog` events publish library log messages. `DEBUG_DATA_SEND` and `DEBUG_DATA_RECEIVED` enable payload-level debug output on instances; avoid verbose payload logging for sensitive data or high-volume production traffic. + +### Health and diagnostic reports + +When `EnableHealthApi` is enabled, the client or server starts a small HTTP listener. It accepts `GET` requests at `/health` and `/status` for JSON health/state, `/dashboard` for the built-in traffic dashboard, and `/` for the endpoint index. The default bind address is loopback; the listener does not provide authentication or HTTPS, so do not bind it to an untrusted network. When `HealthApiPort` is `0`, read the selected port from `HealthApi.Port` after startup. + +`StatusPage` is a bounded in-memory history of socket, general, and TLS errors. It exposes recent/all errors and filters by time, source, socket code, socket exception, or TLS error; it can also generate a periodic HTML report. `ServerStatus` generates a separate HTML snapshot of server connection counts, traffic counters, connected clients, and recent TLS errors. Both reports write files to `HtmlReportOutputDirectory`; configure permissions and storage retention for the host. + +## Utility Types + +### JSON stream processing + +`JsonDataProcessor` accepts arbitrary byte or string chunks and keeps an incremental JSON parser per client name. It emits `OnProcessMessage` for complete JSON values deserialized to `TData`, and `OnProcessTextMessage` for non-JSON text between JSON values. `OnError` reports invalid input or parse failures. `RemoveClient` discards one parser context; idle contexts are periodically removed unless `KeepIdleClients` is true. `MaxAllowedBufferSize` limits parser buffering and `IdleTimeout` controls cleanup. Dispose the processor to stop its cleanup timer and release parser state. + +### Network monitoring + +`NetworkMonitor` periodically pings a target host, stores a bounded history of samples, and raises sample, outage-detected, and outage-recovered events. `GetHealthReport()` summarizes reachability, uptime percentage, average/min/max latency, jitter, outage windows, and current system network-interface byte rates. Those byte-rate values describe active host interfaces, not traffic for a particular `NetworkClient`. `StartAutoHtmlReport()` periodically writes the health report as HTML. ICMP may be blocked or deprioritized even when the application's TCP/UDP endpoint is reachable. + +### Load and stress testing + +`LoadTester` repeatedly creates core `NetworkClient` instances up to a target connection count, sends a fixed test message at the configured rate, logs progress, and closes its clients when the duration ends. `RunAsync(duration, connectionRatePerSecond, messageRate)` runs the workload; `GetReport()` returns connection, send-volume, error, and throughput fields. Use it against an explicitly authorized test server; the configured connection and send rates can consume substantial local and remote resources. + +`StressTest` creates a fixed number of clients, sends a configured number of messages per client, records replies and per-client errors, and exposes a `StressTestResult` with summary and CSV export. `StressTestRunner.RunQuickTestAsync` provides a smaller convenience run. These tools exercise the core `NetworkClient`; they are not protocol-independent load generators. + +### Certificates and protocols + +`CertificateHelper` loads certificates from supported files or the local certificate store and provides install/remove helpers. **Do not use `CertificateHelper.CheckCertificate` for trust validation:** its current callback accepts all server certificates. Use the normal `Configuration` certificate validation path and an explicit trust configuration instead. + +`ProtocolFactory` can register named protocol factories, create by name or `ProtocolType`, query whether a name is registered, list registrations, and unregister custom registrations. The built-in TCP and UDP registrations cannot be removed. `INetworkProtocol` defines the transport lifecycle, send/receive, socket/stream access, and configuration hooks; custom implementations should return a fresh disposable instance and honor the hooks they support. `IBroadcastConfigurableProtocol` adds the optional UDP broadcast configuration hook. + +`TcpSeparators` provides common delimiter byte sequences. `Connection` represents a server-side peer and exposes its ID, endpoint, nickname, times, byte counters, security flags, metadata dictionary, and connection state. `Stats` holds aggregate counts. `DisconnectionDiagnostics`, `ConnectionLogger`, and `ConnectionLogManager` provide disconnect-cause analysis and connection/error logging; `SslHandshakeDiagnostics` and `SslMetrics` expose TLS handshake stages and negotiated details. + +`AesKeyExchange` contains the low-level AES key-exchange and payload encrypt/decrypt helpers used by the built-in encryption flow. `StringHelper.GetTextBetweenTags` extracts text between markers and `SanitizeUsername` normalizes a username. `ConnectionTimeFormatter` formats elapsed durations, while `HandlingHelpers` provides guarded event invocation, fire-and-forget task handling, and safe disposal helpers. + +## Related Packages + +`EonaCat.Connections` provides TCP and UDP. The transports and integrations below are separate NuGet packages with their own entry-point types; installing one does not replace `NetworkClient` or `NetworkServer` automatically. + +| Package | Client and server types | Framework | +| --- | --- | --- | +| `EonaCat.Connections` | `NetworkClient`, `NetworkServer` (TCP/UDP) | .NET Framework 4.8.1 and .NET 8 | +| `EonaCat.Connections.gRPC` | `GrpcNetworkClient`, `GrpcNetworkServer` | .NET 8 | +| `EonaCat.Connections.Quic` | `QuicNetworkClient`, `QuicNetworkServer` | .NET 8; preview-feature opt-in | +| `EonaCat.Connections.REST` | `RestNetworkClient`, `RestNetworkServer` | .NET 8 | +| `EonaCat.Connections.OpcUa` | `OpcUaNetworkClient`, `OpcUaNetworkServer` | .NET 8 | + +Install only the packages needed by the application: + +```bash +dotnet add package EonaCat.Connections.gRPC +dotnet add package EonaCat.Connections.Quic +dotnet add package EonaCat.Connections.REST +dotnet add package EonaCat.Connections.OpcUa +``` + +### gRPC + +The gRPC integration provides a bidirectional streaming RPC. It supports text and byte payloads, nicknames, client events, per-client sends, broadcasts, optional heartbeat, automatic reconnect, statistics, and the optional health API. The server exposes an HTTP/2 endpoint and enforces `MAX_MESSAGE_SIZE` for received and sent gRPC messages. TLS 1.2/1.3 is enabled when a certificate is configured on the shared `Configuration`. + +The `ConnectorService.Connect` RPC reads and writes `ConnectorMessage` values. `DATA` carries the application bytes in `Data`; `NICKNAME` carries a nickname in `Text`; `PING` and `PONG` are heartbeat controls; and `DISCONNECT` closes the stream. Heartbeat controls are exchanged when `EnableHeartbeat` is enabled. Applications normally use `GrpcNetworkClient` and `GrpcNetworkServer` rather than constructing these protobuf messages directly. ```csharp -using EonaCat.Connections; using EonaCat.Connections.Models; -using System.Security.Cryptography.X509Certificates; +using EonaCat.Connections.gRPC; -namespace EonaCat.Connections.Client.Example +var serverConfig = new Configuration { Host = "0.0.0.0", Port = 5051 }; +using var server = new GrpcNetworkServer(serverConfig); +server.OnDataReceived += async (_, message) => + await server.SendToClientAsync(message.ClientId, message.Data); +await server.StartAsync(); + +var clientConfig = new Configuration { Host = "127.0.0.1", Port = 5051 }; +using var client = new GrpcNetworkClient(clientConfig); +client.OnDataReceived += (_, message) => Console.WriteLine(message.StringData); + +if (await client.ConnectAsync()) { - public class Program - { - private static NetworkClient _client; - - public static async Task Main(string[] args) - { - await CreateClientAsync(); - - while (true) - { - if (!_client.IsConnected) - { - Console.WriteLine("Waiting for connection..."); - await Task.Delay(1000); - continue; - } - - Console.Write("Enter message to send (or 'exit' to quit): "); - var message = Console.ReadLine(); - - if (!string.IsNullOrEmpty(message) && message.Equals("exit", StringComparison.OrdinalIgnoreCase)) - { - await _client.DisconnectAsync(); - _client.Dispose(); - break; - } - - if (!string.IsNullOrEmpty(message)) - { - await _client.SendAsync(message); - - // Optional: wait for response - var response = await _client.SendAndWaitForResponseAsync( - message, TimeSpan.FromSeconds(5)); - - if (response != null) - { - Console.WriteLine($"Server response: {response.StringData}"); - } - } - } - } - - private static async Task CreateClientAsync() - { - var config = new Configuration - { - Protocol = ProtocolType.TCP, - Host = "127.0.0.1", - Port = 1111, - Certificate = new X509Certificate2("client.pfx", "p@ss"), // For TLS (optional) - UseAesEncryption = true, - AesPassword = "EonaCat.Connections.Password", - EnableAutoReconnect = true, - ReconnectDelayInSeconds = 5, - MaxReconnectAttempts = 0, // Unlimited retries - EnableHeartbeat = true, - HeartbeatIntervalSeconds = 5, - IdleTimeoutSeconds = 30, - }; - - _client = new NetworkClient(config); - - // Error handling - _client.OnGeneralError += (sender, e) => - Console.WriteLine($"[ERROR] {e.Message}"); - - _client.OnSslError += (sender, e) => - Console.WriteLine($"[SSL ERROR] {e.Message}"); - - // Connection events - _client.OnConnected += async (sender, e) => - { - Console.WriteLine($"[CONNECTED] Connected to server at {e.RemoteEndPoint}"); - - // Set client nickname - await _client.SendNicknameAsync("TestUser"); - - // Send initial message - await _client.SendAsync("Hello from client!"); - }; - - // Data reception - _client.OnDataReceived += (sender, e) => - Console.WriteLine($"[SERVER] {(e.IsBinary ? $"{e.Data.Length} bytes" : e.StringData)}"); - - // Disconnection - _client.OnDisconnected += (sender, e) => - Console.WriteLine($"[DISCONNECTED] Disconnected from server ({e.DisconnectReason})"); - - // Idle/Timeout - _client.OnIdleTimeout += (sender, e) => - Console.WriteLine($"[IDLE] Connection idle for {e.IdleTime} seconds"); - - // Heartbeat - _client.OnPingResponse += (sender, e) => - Console.WriteLine($"[PING] Response time: {e.ResponseTime}ms"); - - Console.WriteLine("Client connecting..."); - await _client.ConnectAsync(); - } - } + await client.SendAsync("Hello over gRPC"); } ``` +Configure the same TLS certificate/trust expectations on both sides when securing the endpoint. As with the core client, configure certificate validation deliberately; `IsSelfSignedEnabled` disables normal certificate validation and is unsuitable for production. +### QUIC -## Advanced Usage Examples +QUIC uses a TLS-protected connection with a bidirectional stream. The client and server provide connect, send, disconnect, lifecycle/data/error events, connection limits on the server, counters, and server broadcasts. The server requires `Configuration.Certificate`; configure the client to trust that certificate. QUIC support depends on the operating system and runtime, and the implementation is annotated as using preview features. The current client expects `Configuration.Host` to be an IP address because it parses the value directly. -### Request-Response Pattern +The QUIC stream is byte-oriented: a receive event reflects a stream read, not an application message boundary. Add application framing when the protocol needs discrete messages. Client and server must use the same `PROTOCOL_CONNECTION_NAME` for ALPN negotiation; inbound stream limits and default stream/connection close error codes are also configurable on the QUIC types. ```csharp -// Server: Wait for client to send data, then respond -_server.OnDataReceived += async (sender, e) => +using EonaCat.Connections.Models; +using EonaCat.Connections.Quic; + +var serverConfig = new Configuration { - if (e.StringData == "QUERY") - { - await _server.SendToClientAsync(e.ClientId, "RESPONSE_DATA"); - } + Host = "0.0.0.0", + Port = 5052, + Certificate = serverCertificate }; +using var server = new QuicNetworkServer(serverConfig); +server.OnDataReceived += async (_, message) => + await server.SendToClientAsync(message.ClientId, message.Data); +await server.StartAsync(); -// Client: Send request and wait for response -var response = await _client.SendAndWaitForResponseAsync( - "QUERY", TimeSpan.FromSeconds(10)); -Console.WriteLine($"Got: {response.StringData}"); - -// Server: Broadcast and wait for all responses -var responses = await _server.BroadcastAndWaitForResponsesAsync( - "QUESTION", TimeSpan.FromSeconds(15)); -Console.WriteLine($"Received {responses.Count} responses"); -``` - -### Client-to-Client Communication - -```csharp -// Client A sends to Client B through server -await _server.SendFromClientToClientAsync( - "clientA_id", "clientB_id", "Direct message"); - -// Or with response -var response = await _server.SendFromClientToClientAndWaitForResponseAsync( - "clientA_id", "clientB_id", "Question for B"); -``` - -### Message Framing - -```csharp -// Delimiter-based framing -config.MessageFraming = FramingMode.Delimiter; -config.Delimiter = Encoding.UTF8.GetBytes("\n"); - -// Length-prefixed framing -config.MessageFraming = FramingMode.LengthPrefixed; -config.LengthPrefixedLength = 4; // 4-byte length prefix - -// Custom separator -server.SetSeparator("||"); -``` - -### Accessing Statistics - -```csharp -// Server statistics -Console.WriteLine($"Active connections: {_server.ActiveConnections}"); -Console.WriteLine($"Total connected: {_server.TotalConnections}"); -Console.WriteLine($"Messages/sec: {_server.MessagesPerSecond}"); -Console.WriteLine($"Data sent: {_server.BytesSent} bytes"); -Console.WriteLine($"Data received: {_server.BytesReceived} bytes"); -Console.WriteLine($"Uptime: {_server.Uptime}"); - -var stats = _server.GetStats(); -Console.WriteLine($"Dropped packets: {stats.DroppedPackets}"); -Console.WriteLine($"Dropped connections: {stats.DroppedConnections}"); - -// Client statistics -Console.WriteLine($"Connection time: {_client.ConnectedTimeInHours()} hours"); -Console.WriteLine($"Idle time: {_client.IdleTimeInSeconds()} seconds"); -Console.WriteLine($"Bytes sent: {_client.BytesSent}"); -Console.WriteLine($"Messages sent: {_client.MessagesSent}"); -``` - -### SSL/TLS with Certificate Validation - -```csharp -// Server with certificate -var config = new Configuration +var clientConfig = new Configuration { Host = "127.0.0.1", Port = 5052 }; +await using var client = new QuicNetworkClient(clientConfig); +if (await client.ConnectAsync()) { - Certificate = new X509Certificate2("server.pfx", "password"), - MutuallyAuthenticate = true, - CheckCertificateRevocation = true, -}; - -// Client with certificate validation -var clientConfig = new Configuration -{ - Host = "server.example.com", - Port = 443, - Certificate = new X509Certificate2("client.pfx", "password"), - MutuallyAuthenticate = true, - TrustedThumbprints = new List { "CERT_THUMBPRINT" }, - CheckCertificateRevocation = true, -}; -``` - -### Encryption and Security - -```csharp -// AES Encryption -config.UseAesEncryption = true; -config.AesPassword = "SecurePassword123"; - -// Both TLS and AES together -config.Certificate = new X509Certificate2("server.pfx", "pass"); -config.UseAesEncryption = true; -config.AesPassword = "AdditionalPassword"; - -// Disable Nagle for low-latency -config.EnableNagle = false; -``` - -## Event Arguments Reference - -### ConnectionEventArgs -- `string ClientId` - Unique client identifier -- `EndPoint RemoteEndPoint` - Client's remote address/port -- `string Nickname` - Client's nickname (if set) -- `bool HasNickname` - Whether client has a nickname - -### DataReceivedEventArgs -- `string ClientId` - Sender client ID -- `byte[] Data` - Raw binary data -- `string StringData` - Data decoded as UTF-8 string -- `bool IsBinary` - True if binary data, false if text -- `bool HasNickname` - Whether sender has a nickname -- `string Nickname` - Sender's nickname (if set) - -### ErrorEventArgs -- `string Message` - Error description -- `string ClientId` - Associated client (if applicable) -- `Exception Exception` - Inner exception details - -### PingEventArgs -- `string ClientId` - Client that responded to ping -- `long ResponseTime` - Response time in milliseconds - -### IdleEventArgs / IdleClientEventArgs -- `string ClientId` - Idle client ID -- `double IdleTime` - Idle duration in seconds -- `DisconnectReason Reason` - Reason for disconnection - -## Disconnect Reasons - -The `DisconnectReason` enum provides detailed disconnect information: - -```csharp -public enum DisconnectReason -{ - Unknown, // Unknown reason - RemoteClosed, // Remote peer closed connection - LocalClosed, // Local side closed connection - Timeout, // Connection timeout - Error, // General error - SSLError, // SSL/TLS handshake error - ServerShutdown, // Server shutting down - Reconnect, // Reconnecting (client) - ClientRequested, // Client requested disconnect - Forced, // Forcefully disconnected - NoPongReceived, // Heartbeat pong not received - ProtocolError, // Protocol violation + await client.SendAsync("Hello over QUIC"); } ``` -## Key Security Enhancements +QUIC is a separate API, not a `ProtocolType` option for `NetworkClient` or `NetworkServer`. Confirm `QuicConnection.IsSupported` on the deployment platform and enable preview features in applications that consume the package. -### 1. New Security Validation Layer (SecurityValidator.cs) +### REST and webhooks -**Location:** `EonaCat.Connections/Helpers/SecurityValidator.cs` +The REST package hosts an HTTP API and represents each connected client with a generated client ID. `RestNetworkClient.ConnectAsync()` registers the client; it sends data using HTTP POST and receives queued server messages by polling. The server supports these routes: -**Features:** -- **Length Prefix Validation** - Prevents buffer overflow and memory exhaustion by validating message lengths against configured maximum -- **Message Stream Size Validation** - Detects decompression bombs and message accumulation attacks -- **UDP Packet Validation** - Ensures UDP packets don't exceed buffer boundaries -- **Rate Limiting** - Implements token-bucket style rate limiting per source address to prevent DoS attacks -- **HTTP Header Validation** - Detects header injection attacks by checking for newline and null byte characters -- **Delimiter Validation** - Prevents delimiter injection attacks -- **Compression Ratio Validation** - Detects decompression bomb attacks -- **Error Message Sanitization** - Prevents information leakage in error responses -- **Rate Limit Cache Cleanup** - Prevents memory leaks from rate limit tracking +| Method and route | Purpose | +| --- | --- | +| `POST /api/connect` | Creates a client record and returns its generated `clientId`; returns `429` when the connection limit is reached. | +| `POST /api/disconnect` | Disconnects the client named by `clientId`. | +| `POST /api/send` | Sends a client's payload to the server-side `OnDataReceived` event. Clients send payloads as Base64 in the `data` field. | +| `GET /api/poll/{clientId}` | Drains that client's pending server messages and returns them as Base64 strings in `messages`. | +| `POST /api/broadcast` | Broadcasts `data` to all clients except the optional sender `clientId`. | +| `POST /api/nickname` | Sets the supplied `nickname` on the identified client. | +| `GET /api/ping/{clientId}` | Updates activity/pong time and returns a pong response. | +| `POST /api/webhooks/register` | Sets the client's callback URL used for server-to-client message delivery. | +| `POST /api/webhooks/unregister` | Clears the client's callback URL so queued polling is used again. | +| `POST /api/aes/init/{clientId}` | Initializes a client's AES state from supplied salt/IV when AES is enabled on the server. | -### 2. Configuration Security Settings +REST client/server also expose lifecycle and data events, counters, connection limits, optional TLS, and optional AES payload encryption. The routes do not implement authentication or authorization; put the server behind an authenticated gateway or restrict network access before exposing it beyond a trusted network. ```csharp -public long MaxMessageStreamSize { get; set; } = 500 * 1024 * 1024; // 500 MB -public int MaxMessagesPerSecond { get; set; } = 0; // 0 = unlimited -public bool EnableLengthPrefixValidation { get; set; } = true; -public int MaxUdpPacketsPerSecond { get; set; } = 0; // 0 = unlimited -public int MaxHealthApiRequestSize { get; set; } = 10 * 1024 * 1024; // 10 MB -public bool EnableErrorMessageSanitization { get; set; } = true; -public bool EnableRateLimitCacheCleanup { get; set; } = true; -public int RateLimitCacheCleanupIntervalSeconds { get; set; } = 300; -public bool EnableHttpHeaderValidation { get; set; } = true; -``` +using EonaCat.Connections.Models; +using EonaCat.Connections.REST; -**Benefits:** -- Configurable security thresholds for different deployment scenarios -- Ability to fine-tune security vs. performance trade-offs -- Granular control over which protections are enabled +var serverConfig = new Configuration { Host = "0.0.0.0", Port = 5053 }; +using var server = new RestNetworkServer(serverConfig); +server.OnDataReceived += async (_, message) => + await server.SendToClientAsync(message.ClientId, $"Echo: {message.StringData}"); +await server.StartAsync(); -### 3. NetworkServer Hardening - -1. **Message Extraction Validation** - - Updated `TryExtractLengthPrefixedMessage()` to use SecurityValidator for length prefix validation - - Added checks to prevent message stream from exceeding configured maximum size - - Enhanced error messages to indicate validation failures - -2. **Message Stream Protection** - - `HandleClientCommunicationAsync()` now validates message stream size before writing received data - - Prevents accumulation of large amounts of buffered data that could exhaust memory - - Disconnects clients that exceed limits with proper error logging - -3. **UDP Rate Limiting** - - `HandleUdpDataAsync()` implements packet size validation - - UDP packet rate limiting prevents flood attacks - - Per-source tracking of packet rates - -4. **Background Cleanup Task** - - Added `CleanupRateLimitCacheAsync()` to periodically clean up rate limit entries - - Prevents memory leaks from unbounded cache growth - - Configurable cleanup interval - -5. **Startup Integration** - - Rate limit cache cleanup task integrated into server startup - - Runs as background task with configurable interval - -### 4. NetworkClient Hardening - -1. **Length-Prefixed Message Validation** - - Updated `ReceiveLengthPrefixedMessagesAsync()` to validate length prefixes using SecurityValidator - - Added dedicated exception handling for malformed length messages - - Improved error messages for validation failures - -2. **Delimiter-Based Message Protection** - - Enhanced `ReceiveDelimiterAsync()` with max message stream size enforcement - - Added checks for accumulated message buffer size - - Prevents memory exhaustion from large buffered data - -### 5. HealthApiServer REST API Hardening - -1. **Request Size Limits** - - New `MaxRequestSize` property to enforce maximum HTTP request/response size - - Defaults to 10 MB, configurable before server starts - - Request line limited to 8192 bytes - - Total headers limited to 65536 bytes - -2. **HTTP Header Security** - - Enhanced `ReadRequestLineAsync()` to validate for invalid control characters - - Rejects null bytes (0x00) in request lines - - `DrainHeadersAsync()` validates header size and detects null bytes - - Prevents header-based injection attacks - -3. **Response Security Hardening** - - `WriteResponseAsync()` validates response body size against limit - - Content-Type validation prevents injection of control characters - - Additional security headers added: - - `X-Frame-Options: DENY` - Clickjacking protection - - `X-XSS-Protection: 1; mode=block` - XSS protection - - `Strict-Transport-Security` - Forces HTTPS - - `Pragma: no-cache` - Additional cache control - - Improved error handling for oversized responses - -## Attack Vectors Mitigated - -### 1. Buffer Overflow Attacks -- **Mitigation:** Length prefix validation, buffer size checks, message size limits -- **Implementation:** SecurityValidator validates all length values before buffer allocation - -### 2. Memory Exhaustion / Decompression Bombs -- **Mitigation:** MaxMessageStreamSize configuration, per-message size limits -- **Implementation:** Accumulated stream size checked before each write operation - -### 3. Slow Loris / Slowhttptest Attacks -- **Mitigation:** Request timeouts, header size limits -- **Implementation:** Network timeouts and maximum header sizes enforced - -### 4. UDP Flood / Amplification Attacks -- **Mitigation:** UDP rate limiting, packet size validation -- **Implementation:** Per-source rate limiting with configurable thresholds - -### 5. HTTP Header Injection -- **Mitigation:** HTTP header validation, null byte detection -- **Implementation:** SecurityValidator checks for newlines and null bytes in headers - -### 6. Malformed Packet Attacks -- **Mitigation:** Strict validation of message framing and length prefixes -- **Implementation:** Enhanced error handling with specific exceptions for malformed data - -### 7. Information Leakage -- **Mitigation:** Error message sanitization -- **Implementation:** Sensitive error details hidden from clients, detailed logs for server admins - -### 8. Rate Limiting / DoS -- **Mitigation:** Per-client/source rate limiting capability -- **Implementation:** SecurityValidator.CheckRateLimit with configurable thresholds - -## Configuration Best Practices - -### Production Deployment -```csharp -var config = new Configuration +var clientConfig = new Configuration { Host = "127.0.0.1", Port = 5053 }; +using var client = new RestNetworkClient(clientConfig); +client.OnDataReceived += (_, message) => Console.WriteLine(message.StringData); +if (await client.ConnectAsync()) { - // Message constraints - MAX_MESSAGE_SIZE = 100 * 1024 * 1024, // 100 MB - MaxMessageStreamSize = 500 * 1024 * 1024, // 500 MB - - // Rate limiting - MaxMessagesPerSecond = 1000, // Per client - MaxUdpPacketsPerSecond = 5000, // Per source - MaxHealthApiRequestSize = 10 * 1024 * 1024, // 10 MB - - // Security features - EnableLengthPrefixValidation = true, - EnableErrorMessageSanitization = true, - EnableRateLimitCacheCleanup = true, - EnableHttpHeaderValidation = true -}; + await client.SendAsync("Hello over REST"); +} ``` -### High-Security Deployment +For callback delivery, `RestNetworkServer.Webhooks` registers event names and destination URLs, for example `connected`, `data_received`, and `broadcast`. A REST client can also start a local webhook listener with `StartWebhookListenerAsync(port)` and register it with `RegisterWebhookAsync`; the built-in listener binds to loopback, so it is intended for local callback delivery unless the application provides another reachable endpoint. Webhook delivery is outbound HTTP POST, sequential, best-effort, and has no retry; outbound failures are swallowed. Protect and monitor the callback targets like any other outbound integration. + +REST provides HTTP request/response semantics rather than TCP-style stream delivery: clients poll for messages when webhooks are not used, so account for polling latency and HTTP overhead when choosing it. + +### OPC UA + +The OPC UA package is a separate industrial interoperability API, not a byte-message transport. `OpcUaNetworkServer` publishes a configured address space under an `EonaCat` folder; register variables and callable methods before starting it. Variables have scalar data types, initial values, access levels, and optional descriptions. `TrySetValue` updates a registered variable and raises `ValueChanged`; client writes to a writable variable also raise that event. Methods declare typed input/output arguments and invoke the supplied handler when called. + +`OpcUaNetworkClient` connects to an endpoint, browses hierarchical references from `ObjectsFolder`, reads and writes variable values, calls methods, and subscribes to monitored value changes. Subscriptions default to 1000 ms publishing/sampling intervals, queue up to 10 values per item, and discard the oldest queued value when full. The client can reconnect after a session keep-alive failure, and both client and server expose lifecycle/error events. + ```csharp -var config = new Configuration +using EonaCat.Connections.OpcUa.Configuration; +using EonaCat.Connections.OpcUa.Models; +using EonaCat.Connections.OpcUa.Server; +using Opc.Ua; + +var server = new OpcUaNetworkServer(new OpcUaServerOptions { - MAX_MESSAGE_SIZE = 10 * 1024 * 1024, // 10 MB - MaxMessageStreamSize = 50 * 1024 * 1024, // 50 MB - MaxMessagesPerSecond = 100, // Strict rate limit - MaxUdpPacketsPerSecond = 500, // Strict UDP limit - MaxHealthApiRequestSize = 1 * 1024 * 1024, // 1 MB - // All security features enabled by default -}; + BaseAddress = "opc.tcp://localhost:4840/EonaCat/Connector", + NamespaceUri = "urn:example:machine" +}); +server.AddVariable(new OpcUaNodeDefinition( + Identifier: "Temperature", + DisplayName: "Temperature", + DataType: DataTypeIds.Double, + InitialValue: 20.0)); +server.AddMethod(new OpcUaMethodDefinition( + Identifier: "Add", + DisplayName: "Add", + InputArguments: + [ + new OpcUaMethodArgument("left", DataTypeIds.Double), + new OpcUaMethodArgument("right", DataTypeIds.Double) + ], + OutputArguments: [new OpcUaMethodArgument("sum", DataTypeIds.Double)], + Handler: arguments => new object?[] { (double)arguments[0]! + (double)arguments[1]! })); +await server.StartAsync(); + +// Update a published variable by its registered identifier. +server.TrySetValue("Temperature", 21.5); ``` -## Performance Considerations +```csharp +using EonaCat.Connections.OpcUa.Client; +using EonaCat.Connections.OpcUa.Configuration; -### Optimization Tips -1. **Disable Nagle's Algorithm**: Set `EnableNagle = false` for lower latency -2. **Buffer Size**: Use appropriate `BufferSize` (default is ExtraLarge ~65KB) -3. **Keep-Alive**: Enable `EnableKeepAlive` to detect dead connections early -4. **Message Framing**: Use `LengthPrefixed` for better parsing performance -5. **Connection Pool**: Design clients to maintain persistent connections -6. **Batching**: Group small messages when possible -7. **Thread Affinity**: Run on dedicated cores for high throughput +await using var client = new OpcUaNetworkClient(new OpcUaClientOptions +{ + EndpointUrl = "opc.tcp://localhost:4840/EonaCat/Connector" +}); -### Monitoring -- Use `HealthApi` for external monitoring -- Enable `EnableServerStatusPage` for HTML reports -- Monitor `MessagesPerSecond` for throughput -- Track `IdleTimeout` events for connection health -- Use `NetworkMonitor` for advanced diagnostics +if (await client.ConnectAsync()) +{ + const string namespaceUri = "urn:example:machine"; + var temperatureNode = client.GetNodeId(namespaceUri, "Temperature"); + Console.WriteLine((await client.ReadAsync(temperatureNode)).Value); + await client.WriteAsync(temperatureNode, 22.0); -## Thread Safety + var sum = await client.CallAsync( + client.GetNodeId(namespaceUri, "EonaCat"), + client.GetNodeId(namespaceUri, "Add"), + new object?[] { 2.0, 3.0 }); + Console.WriteLine(sum[0]); -- `NetworkServer` and `NetworkClient` are thread-safe for all public methods -- Events are called on socket completion threads -- Use `ConfigureAwait(false)` in async handlers -- Access shared state with appropriate synchronization + await using var subscription = await client.SubscribeAsync( + new[] { temperatureNode }, + (_, change) => Console.WriteLine($"Temperature: {change.Value}")); +} +``` -## Supported Platforms +The corresponding client uses `OpcUaClientOptions.EndpointUrl` and `ConnectAsync()`. Resolve a node using `GetNodeId(namespaceUri, identifier)` or browse from `ObjectsFolder`, then use `ReadAsync`, `WriteAsync`, `CallAsync`, or `SubscribeAsync`. `CallAsync` takes both the containing object node ID and method node ID plus ordered input values. Dispose the returned subscription when it is no longer needed. Server security defaults enable a secure endpoint and also allow an unsecured endpoint; client security defaults on, untrusted certificates are not automatically accepted, and revocation checking is on. Server options control endpoint/namespace, certificate policy, session count, and subscription count. Client options control endpoint security, optional username/password identity, certificate checks, operation/session timeouts, and reconnect behavior. Disable unsecured endpoints unless required and configure trust before exposing an OPC UA endpoint. -- ** .NET Standard 2.0** - Full support -- **.NET Framework 4.8+** - Full support -- **.NET 8.0** - Full support -- **Platforms**: Windows, Linux, macOS (with .NET Core) +All transports and integrations should be stopped and disposed explicitly. For TCP, UDP, gRPC, and REST servers, `StartAsync()` starts listening and returns; await `StopAsync()` during graceful shutdown. QUIC and OPC UA have their own client/server lifecycle methods as described above. + +## Resource Cleanup + +Dispose clients and servers when finished. On servers, use `await StopAsync()` when shutdown should complete before the application exits; `Stop()` is a fire-and-forget convenience method. `Configuration` implements `IDisposable` and disposes its configured certificate, so avoid sharing a certificate-owning configuration across components with unrelated lifetimes. + +## License + +See the [LICENSE](LICENSE) file. diff --git a/docker/Dockerfile b/docker/Dockerfile new file mode 100644 index 0000000..030f3a2 --- /dev/null +++ b/docker/Dockerfile @@ -0,0 +1,25 @@ +# syntax=docker/dockerfile:1.4 + +FROM mcr.microsoft.com/dotnet/sdk:8.0 AS build +WORKDIR /src + +# Copy the projects +COPY EonaCat.Connections/EonaCat.Connections.csproj EonaCat.Connections/ +COPY EonaCat.Connections.Server/EonaCat.Connections.Server.csproj EonaCat.Connections.Server/ +RUN dotnet restore EonaCat.Connections.Server/EonaCat.Connections.Server.csproj + +# Copy remaining sources +COPY . . +RUN dotnet publish EonaCat.Connections.Server/EonaCat.Connections.Server.csproj -c Release -o /app/publish --no-restore + +# Runtime image +FROM mcr.microsoft.com/dotnet/runtime:8.0 AS final +WORKDIR /app +COPY --from=build /app/publish . + +EXPOSE 8080 + +# Set environment variable to signal Docker environment +ENV DOTNET_RUNNING_IN_CONTAINER=true + +ENTRYPOINT ["dotnet", "EonaCat.Connections.Server.dll"]