diff --git a/EonaCat.Connections/Helpers/HealthApiServer.cs b/EonaCat.Connections/Helpers/HealthApiServer.cs index 55e6216..5b9b239 100644 --- a/EonaCat.Connections/Helpers/HealthApiServer.cs +++ b/EonaCat.Connections/Helpers/HealthApiServer.cs @@ -134,9 +134,13 @@ namespace EonaCat.Connections.Helpers client.SendTimeout = 5000; using var stream = client.GetStream(); - using var idleTimeout = new CancellationTokenSource(); - using var registration = idleTimeout.Token.Register(client.Close); - await HandleConnectionAsync(stream, idleTimeout).ConfigureAwait(false); + using var idle = CancellationTokenSource.CreateLinkedTokenSource(_cts?.Token ?? CancellationToken.None); + using var registration = idle.Token.Register(client.Close); + do + { + idle.CancelAfter(KeepAliveTimeout); + } + while (await HandleRequestAsync(stream).ConfigureAwait(false)); } } catch (Exception) @@ -146,30 +150,20 @@ namespace EonaCat.Connections.Helpers } internal static readonly TimeSpan KeepAliveTimeout = TimeSpan.FromSeconds(30); - private const int MaxRequestsPerConnection = 10000; - internal async Task HandleConnectionAsync(Stream stream, CancellationTokenSource idleTimeout, bool allowAccess = true) - { - for (int i = 0; i < MaxRequestsPerConnection; i++) - { - idleTimeout.CancelAfter(KeepAliveTimeout); - if (!await HandleRequestAsync(stream, allowAccess, i == 0, i < MaxRequestsPerConnection - 1).ConfigureAwait(false)) - { - break; - } - } - } - - private async Task HandleRequestAsync(Stream stream, bool allowAccess, bool isFirstRequest, bool allowKeepAlive) + /// True when the connection should be kept open for another request. + internal async Task HandleRequestAsync(Stream stream, bool allowAccess = true) { var requestLine = await ReadRequestLineAsync(stream).ConfigureAwait(false); - if (string.IsNullOrEmpty(requestLine)) + if (requestLine == null) { - if (isFirstRequest) - { - await WriteResponseAsync(stream, 400, "Bad Request", "text/plain", "Bad Request", false).ConfigureAwait(false); - } + return false; + } + + if (requestLine.Length == 0) + { + await WriteResponseAsync(stream, 400, "Bad Request", "text/plain", "Bad Request", false).ConfigureAwait(false); return false; } @@ -182,11 +176,12 @@ namespace EonaCat.Connections.Helpers var method = parts[0].ToUpperInvariant(); var path = parts[1].Split('?')[0].TrimEnd('/').ToLowerInvariant(); - var isHttp11 = parts.Length > 2 && parts[2].Trim().Equals("HTTP/1.1", StringComparison.OrdinalIgnoreCase); + var isHttp11 = parts.Length >= 3 && parts[2].Equals("HTTP/1.1", StringComparison.OrdinalIgnoreCase); var connectionHeader = await DrainHeadersAsync(stream).ConfigureAwait(false); - var keepAlive = allowKeepAlive && (connectionHeader == null + var keepAlive = connectionHeader == null ? isHttp11 - : connectionHeader.IndexOf("keep-alive", StringComparison.OrdinalIgnoreCase) >= 0); + : connectionHeader.IndexOf("keep-alive", StringComparison.OrdinalIgnoreCase) >= 0 + || (isHttp11 && connectionHeader.IndexOf("close", StringComparison.OrdinalIgnoreCase) < 0); if (!allowAccess) { @@ -208,7 +203,7 @@ namespace EonaCat.Connections.Helpers break; case "/dashboard": - using (var resource = typeof(HealthApiServer).Assembly.GetManifestResourceStream("EonaCat.Connections.Helpers.TrafficDashboard.html") + using (var resource = typeof(HealthApiServer).Assembly.GetManifestResourceStream("Heijmans.Connector.Helpers.TrafficDashboard.html") ?? throw new InvalidOperationException("The traffic dashboard resource is missing.")) using (var reader = new StreamReader(resource, Encoding.UTF8)) { @@ -226,10 +221,6 @@ namespace EonaCat.Connections.Helpers await WriteResponseAsync(stream, 200, "OK", "application/json", statusJson, keepAlive).ConfigureAwait(false); break; - case "/favicon.ico": - await WriteResponseAsync(stream, 204, "No Content", "text/plain", string.Empty, keepAlive, "Cache-Control: max-age=86400").ConfigureAwait(false); - break; - default: await WriteResponseAsync(stream, 404, "Not Found", "text/plain", "Not Found", keepAlive).ConfigureAwait(false); break; @@ -261,7 +252,7 @@ namespace EonaCat.Connections.Helpers int read = await stream.ReadAsync(buffer, 0, 1).ConfigureAwait(false); if (read == 0) { - break; + return sb.Length == 0 ? null : sb.ToString(); } var b = buffer[0]; @@ -281,12 +272,13 @@ namespace EonaCat.Connections.Helpers return sb.ToString(); } + /// The value of the Connection header, or null when absent. private static async Task DrainHeadersAsync(Stream stream) { - string connectionHeader = null; - int totalLength = 0; + string connection = null; + int totalRead = 0; - while (totalLength < 65536) + while (totalRead < 65536) { var line = await ReadRequestLineAsync(stream).ConfigureAwait(false); if (string.IsNullOrEmpty(line)) @@ -294,29 +286,30 @@ namespace EonaCat.Connections.Helpers break; } - totalLength += line.Length; + totalRead += line.Length; var colon = line.IndexOf(':'); if (colon > 0 && line.Substring(0, colon).Trim().Equals("Connection", StringComparison.OrdinalIgnoreCase)) { - connectionHeader = line.Substring(colon + 1).Trim(); + connection = line.Substring(colon + 1).Trim(); } } - return connectionHeader; + return connection; } - private static async Task WriteResponseAsync(Stream stream, int statusCode, string statusText, string contentType, string body, bool keepAlive, string cacheControl = "Cache-Control: no-store") + private static async Task WriteResponseAsync(Stream stream, int statusCode, string statusText, string contentType, string body, bool keepAlive) { var bodyBytes = Encoding.UTF8.GetBytes(body); + var connectionHeader = keepAlive + ? $"Connection: keep-alive\r\nKeep-Alive: timeout={(int)KeepAliveTimeout.TotalSeconds}\r\n" + : "Connection: close\r\n"; 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" + - (keepAlive - ? $"Connection: keep-alive\r\nKeep-Alive: timeout={(int)KeepAliveTimeout.TotalSeconds}\r\n" - : "Connection: close\r\n") + + connectionHeader + "X-Content-Type-Options: nosniff\r\n" + - cacheControl + "\r\n" + + "Cache-Control: no-store\r\n" + "\r\n"; var headerBytes = Encoding.ASCII.GetBytes(header); diff --git a/EonaCat.Connections/Helpers/ProtocolProbeStream.cs b/EonaCat.Connections/Helpers/ProtocolProbeStream.cs index c7c2b4d..81538e1 100644 --- a/EonaCat.Connections/Helpers/ProtocolProbeStream.cs +++ b/EonaCat.Connections/Helpers/ProtocolProbeStream.cs @@ -14,7 +14,7 @@ namespace EonaCat.Connections.Helpers _inner = inner; } - internal async Task IsHttpAsync(CancellationToken token) + internal async Task IsHttpAsync(CancellationToken token, int timeoutMilliseconds = 250) { var prefixes = new[] { "GET /", "HEAD /", "POST /", "PUT /", "DELETE /", "OPTIONS /", "PATCH /" }; try @@ -22,7 +22,7 @@ namespace EonaCat.Connections.Helpers while (_prefix.Length < 9) { _pendingRead = _inner.ReadAsync(_probeBuffer, 0, _probeBuffer.Length, token); - if (await Task.WhenAny(_pendingRead, Task.Delay(250, token)).ConfigureAwait(false) != _pendingRead) + if (await Task.WhenAny(_pendingRead, Task.Delay(timeoutMilliseconds, token)).ConfigureAwait(false) != _pendingRead) { token.ThrowIfCancellationRequested(); _ = _pendingRead.ContinueWith(task => { _ = task.Exception; }, CancellationToken.None, @@ -32,11 +32,22 @@ namespace EonaCat.Connections.Helpers var count = await _pendingRead.ConfigureAwait(false); _pendingRead = null; - if (count == 0) return false; + 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; + if (prefixes.Any(prefix => text.StartsWith(prefix, StringComparison.Ordinal))) + { + return true; + } + + if (!prefixes.Any(prefix => prefix.StartsWith(text, StringComparison.Ordinal))) + { + return false; + } } return false; } @@ -46,19 +57,67 @@ namespace EonaCat.Connections.Helpers } } + internal bool OffersHttpAlpn() + { + var alpn = new byte[] { 0x08, (byte)'h', (byte)'t', (byte)'t', (byte)'p', (byte)'/', (byte)'1', (byte)'.', (byte)'1' }; + var buffer = _prefix.GetBuffer(); + var length = (int)_prefix.Length; + + if (length < 6 || buffer[0] != 0x16 || buffer[5] != 0x01) + { + return false; + } + + for (int i = 0; i <= length - alpn.Length; i++) + { + int j = 0; + while (j < alpn.Length && buffer[i + j] == alpn[j]) + { + j++; + } + + if (j == alpn.Length) + { + return true; + } + } + + return false; + } + 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(); + 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 (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; + if (received == 0) + { + return 0; + } + var position = _prefix.Length; _prefix.Position = position; _prefix.Write(_probeBuffer, 0, received); diff --git a/EonaCat.Connections/Server/NetworkServer.Listeners.cs b/EonaCat.Connections/Server/NetworkServer.Listeners.cs index 4d885ec..a75fd78 100644 --- a/EonaCat.Connections/Server/NetworkServer.Listeners.cs +++ b/EonaCat.Connections/Server/NetworkServer.Listeners.cs @@ -199,7 +199,7 @@ namespace EonaCat.Connections foreach (var listener in listeners) { listener.Start(); - Console.WriteLine($"EonaCat TCP Server started on {FormatTcpListenerAddress(listener)}"); + Console.WriteLine($"Heijmans TCP Server started on {FormatTcpListenerAddress(listener)}"); } if (_config.EnableHealthApi) @@ -260,7 +260,11 @@ namespace EonaCat.Connections _stats.IncrementDroppedConnections(); if (_config.Security?.EnableSecurityLogging == true) { - OnLog?.Invoke(this, new LogMessage { Type = LogType.Debug, Message = $"TCP connection blocked by IP filter: {clientIp}" }); + OnLog?.Invoke(this, new LogMessage + { + Type = LogType.Trace, + Message = $"TCP connection blocked by IP filter: {clientIp}" + }); } continue; } @@ -272,7 +276,11 @@ namespace EonaCat.Connections _stats.IncrementDroppedConnections(); if (_config.Security?.EnableSecurityLogging == true) { - OnLog?.Invoke(this, new LogMessage { Type = LogType.Debug, Message = $"TCP connection blocked by DDoS detection: {clientIp}" }); + OnLog?.Invoke(this, new LogMessage + { + Type = LogType.Warning, + Message = $"TCP connection blocked by DDoS detection: {clientIp}" + }); } continue; } @@ -294,7 +302,11 @@ namespace EonaCat.Connections { 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}" }); + OnLog?.Invoke(this, new LogMessage + { + Type = LogType.Error, + Message = $"Socket error in accept loop: {ex.SocketErrorCode}" + }); await Task.Delay(100, token).ConfigureAwait(false); } catch (OperationCanceledException) @@ -306,7 +318,11 @@ namespace EonaCat.Connections { 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}" }); + OnLog?.Invoke(this, new LogMessage + { + Type = LogType.Error, + Message = $"Unexpected error in accept loop: {ex.Message}" + }); await Task.Delay(100, token).ConfigureAwait(false); } } @@ -326,7 +342,7 @@ namespace EonaCat.Connections { if (Interlocked.CompareExchange(ref _udpRunning, 1, 0) == 1) { - Console.WriteLine("EonaCat UDP Server is already running."); + Console.WriteLine("Heijmans UDP Server is already running."); return; } @@ -361,7 +377,7 @@ namespace EonaCat.Connections foreach (var entry in entries) { - Console.WriteLine($"EonaCat UDP Server started on {entry.LocalEndPoint}"); + Console.WriteLine($"Heijmans UDP Server started on {entry.LocalEndPoint}"); } try @@ -520,7 +536,11 @@ namespace EonaCat.Connections || bindAddress.MapToIPv6().Equals(localAddress.MapToIPv6()); try { - await HealthApi.HandleConnectionAsync(stream, timeout, allowAccess).ConfigureAwait(false); + do + { + timeout.CancelAfter(HealthApiServer.KeepAliveTimeout); + } + while (await HealthApi.HandleRequestAsync(stream, allowAccess).ConfigureAwait(false)); } catch (Exception) { @@ -579,18 +599,24 @@ namespace EonaCat.Connections if (_config.UseSsl) { + var isHttpClient = false; + if (_config.EnableHealthApi) { var probe = new ProtocolProbeStream(stream); stream = probe; client.Stream = stream; - if (await probe.IsHttpAsync(_serverCancellation.Token).ConfigureAwait(false)) + if (await probe.IsHttpAsync(_serverCancellation.Token, (int)HealthApiServer.KeepAliveTimeout.TotalMilliseconds).ConfigureAwait(false)) { await HandleHealthRequestAsync(tcpClient, client, stream).ConfigureAwait(false); return; } + + isHttpClient = probe.OffersHttpAlpn(); } + var sslMaxRetries = isHttpClient ? 1 : _config.SSLMaxRetries; + if (_config.Certificate == null) { var certEx = new InvalidOperationException("SSL is enabled but no server certificate is configured."); @@ -609,7 +635,7 @@ namespace EonaCat.Connections bool sslAuthenticated = false; var sslDiagnostics = _config.EnableSslDiagnostics ? new Helpers.SslHandshakeDiagnostics() : null; - for (int attempt = 1; attempt <= _config.SSLMaxRetries || _config.SSLMaxRetries == 0; attempt++) + for (int attempt = 1; attempt <= sslMaxRetries || sslMaxRetries == 0; attempt++) { SslStream? sslStream = null; @@ -675,7 +701,11 @@ namespace EonaCat.Connections 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}" }); + OnLog?.Invoke(this, new LogMessage + { + Type = LogType.Warning, + Message = $"SSL handshake EOF from {remoteEndPoint} on attempt {attempt}: {ioException.Message}" + }); } catch (AuthenticationException authException) { @@ -691,7 +721,11 @@ namespace EonaCat.Connections 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}" }); + OnLog?.Invoke(this, new LogMessage + { + Type = LogType.Warning, + Message = $"SSL authentication failed for {remoteEndPoint} on attempt {attempt}: {authException.Message}" + }); if (!isRecoverable) { @@ -748,7 +782,7 @@ namespace EonaCat.Connections #endif } - if (!sslAuthenticated && (attempt < _config.SSLMaxRetries || _config.SSLMaxRetries == 0)) + if (!sslAuthenticated && (attempt < sslMaxRetries || sslMaxRetries == 0)) { int delaySeconds = _config.GetSslRetryDelaySeconds(attempt); DebugConnection($"SSL retry in {delaySeconds}s (attempt {attempt})"); @@ -760,7 +794,12 @@ namespace EonaCat.Connections if (!sslAuthenticated) { - DebugConnection($"SSL authentication failed for {remoteEndPoint} after {_config.SSLMaxRetries} attempts, disconnecting client."); + DebugConnection($"SSL authentication failed for {remoteEndPoint} after {sslMaxRetries} attempts, disconnecting client."); + if (isHttpClient) + { + try { await client.DisposeAsync().ConfigureAwait(false); } catch { } + return; + } if (sslDiagnostics != null) { DebugConnection($"[SSL Final Metrics] {sslDiagnostics}");