This commit is contained in:
EonaCat authored and Jeroen Saey committed 2026-11-04 12:58:16 +01:00
1 parent 7ae2023c91
commit 5b1b773bfd
3 files changed
+155 -64

No files matched your search

+33 -40
View File
@@ -134,9 +134,13 @@ namespace EonaCat.Connections.Helpers
client.SendTimeout = 5000; client.SendTimeout = 5000;
using var stream = client.GetStream(); using var stream = client.GetStream();
using var idleTimeout = new CancellationTokenSource(); using var idle = CancellationTokenSource.CreateLinkedTokenSource(_cts?.Token ?? CancellationToken.None);
using var registration = idleTimeout.Token.Register(client.Close); using var registration = idle.Token.Register(client.Close);
await HandleConnectionAsync(stream, idleTimeout).ConfigureAwait(false); do
{
idle.CancelAfter(KeepAliveTimeout);
}
while (await HandleRequestAsync(stream).ConfigureAwait(false));
} }
} }
catch (Exception) catch (Exception)
@@ -146,30 +150,20 @@ namespace EonaCat.Connections.Helpers
} }
internal static readonly TimeSpan KeepAliveTimeout = TimeSpan.FromSeconds(30); internal static readonly TimeSpan KeepAliveTimeout = TimeSpan.FromSeconds(30);
private const int MaxRequestsPerConnection = 10000;
internal async Task HandleConnectionAsync(Stream stream, CancellationTokenSource idleTimeout, bool allowAccess = true) /// <returns>True when the connection should be kept open for another request.</returns>
{ internal async Task<bool> HandleRequestAsync(Stream stream, 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<bool> HandleRequestAsync(Stream stream, bool allowAccess, bool isFirstRequest, bool allowKeepAlive)
{ {
var requestLine = await ReadRequestLineAsync(stream).ConfigureAwait(false); var requestLine = await ReadRequestLineAsync(stream).ConfigureAwait(false);
if (string.IsNullOrEmpty(requestLine)) if (requestLine == null)
{ {
if (isFirstRequest) return false;
}
if (requestLine.Length == 0)
{ {
await WriteResponseAsync(stream, 400, "Bad Request", "text/plain", "Bad Request", false).ConfigureAwait(false); await WriteResponseAsync(stream, 400, "Bad Request", "text/plain", "Bad Request", false).ConfigureAwait(false);
}
return false; return false;
} }
@@ -182,11 +176,12 @@ namespace EonaCat.Connections.Helpers
var method = parts[0].ToUpperInvariant(); var method = parts[0].ToUpperInvariant();
var path = parts[1].Split('?')[0].TrimEnd('/').ToLowerInvariant(); 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 connectionHeader = await DrainHeadersAsync(stream).ConfigureAwait(false);
var keepAlive = allowKeepAlive && (connectionHeader == null var keepAlive = connectionHeader == null
? isHttp11 ? isHttp11
: connectionHeader.IndexOf("keep-alive", StringComparison.OrdinalIgnoreCase) >= 0); : connectionHeader.IndexOf("keep-alive", StringComparison.OrdinalIgnoreCase) >= 0
|| (isHttp11 && connectionHeader.IndexOf("close", StringComparison.OrdinalIgnoreCase) < 0);
if (!allowAccess) if (!allowAccess)
{ {
@@ -208,7 +203,7 @@ namespace EonaCat.Connections.Helpers
break; break;
case "/dashboard": 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.")) ?? throw new InvalidOperationException("The traffic dashboard resource is missing."))
using (var reader = new StreamReader(resource, Encoding.UTF8)) 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); await WriteResponseAsync(stream, 200, "OK", "application/json", statusJson, keepAlive).ConfigureAwait(false);
break; break;
case "/favicon.ico":
await WriteResponseAsync(stream, 204, "No Content", "text/plain", string.Empty, keepAlive, "Cache-Control: max-age=86400").ConfigureAwait(false);
break;
default: default:
await WriteResponseAsync(stream, 404, "Not Found", "text/plain", "Not Found", keepAlive).ConfigureAwait(false); await WriteResponseAsync(stream, 404, "Not Found", "text/plain", "Not Found", keepAlive).ConfigureAwait(false);
break; break;
@@ -261,7 +252,7 @@ namespace EonaCat.Connections.Helpers
int read = await stream.ReadAsync(buffer, 0, 1).ConfigureAwait(false); int read = await stream.ReadAsync(buffer, 0, 1).ConfigureAwait(false);
if (read == 0) if (read == 0)
{ {
break; return sb.Length == 0 ? null : sb.ToString();
} }
var b = buffer[0]; var b = buffer[0];
@@ -281,12 +272,13 @@ namespace EonaCat.Connections.Helpers
return sb.ToString(); return sb.ToString();
} }
/// <returns>The value of the Connection header, or null when absent.</returns>
private static async Task<string> DrainHeadersAsync(Stream stream) private static async Task<string> DrainHeadersAsync(Stream stream)
{ {
string connectionHeader = null; string connection = null;
int totalLength = 0; int totalRead = 0;
while (totalLength < 65536) while (totalRead < 65536)
{ {
var line = await ReadRequestLineAsync(stream).ConfigureAwait(false); var line = await ReadRequestLineAsync(stream).ConfigureAwait(false);
if (string.IsNullOrEmpty(line)) if (string.IsNullOrEmpty(line))
@@ -294,29 +286,30 @@ namespace EonaCat.Connections.Helpers
break; break;
} }
totalLength += line.Length; totalRead += line.Length;
var colon = line.IndexOf(':'); var colon = line.IndexOf(':');
if (colon > 0 && line.Substring(0, colon).Trim().Equals("Connection", StringComparison.OrdinalIgnoreCase)) 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 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" + var header = $"HTTP/1.1 {statusCode} {statusText}\r\n" +
$"Content-Type: {contentType}; charset=utf-8\r\n" + $"Content-Type: {contentType}; charset=utf-8\r\n" +
$"Content-Length: {bodyBytes.Length}\r\n" + $"Content-Length: {bodyBytes.Length}\r\n" +
"Access-Control-Allow-Origin: *\r\n" + "Access-Control-Allow-Origin: *\r\n" +
(keepAlive connectionHeader +
? $"Connection: keep-alive\r\nKeep-Alive: timeout={(int)KeepAliveTimeout.TotalSeconds}\r\n"
: "Connection: close\r\n") +
"X-Content-Type-Options: nosniff\r\n" + "X-Content-Type-Options: nosniff\r\n" +
cacheControl + "\r\n" + "Cache-Control: no-store\r\n" +
"\r\n"; "\r\n";
var headerBytes = Encoding.ASCII.GetBytes(header); var headerBytes = Encoding.ASCII.GetBytes(header);
@@ -14,7 +14,7 @@ namespace EonaCat.Connections.Helpers
_inner = inner; _inner = inner;
} }
internal async Task<bool> IsHttpAsync(CancellationToken token) internal async Task<bool> IsHttpAsync(CancellationToken token, int timeoutMilliseconds = 250)
{ {
var prefixes = new[] { "GET /", "HEAD /", "POST /", "PUT /", "DELETE /", "OPTIONS /", "PATCH /" }; var prefixes = new[] { "GET /", "HEAD /", "POST /", "PUT /", "DELETE /", "OPTIONS /", "PATCH /" };
try try
@@ -22,7 +22,7 @@ namespace EonaCat.Connections.Helpers
while (_prefix.Length < 9) while (_prefix.Length < 9)
{ {
_pendingRead = _inner.ReadAsync(_probeBuffer, 0, _probeBuffer.Length, token); _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(); token.ThrowIfCancellationRequested();
_ = _pendingRead.ContinueWith(task => { _ = task.Exception; }, CancellationToken.None, _ = _pendingRead.ContinueWith(task => { _ = task.Exception; }, CancellationToken.None,
@@ -32,11 +32,22 @@ namespace EonaCat.Connections.Helpers
var count = await _pendingRead.ConfigureAwait(false); var count = await _pendingRead.ConfigureAwait(false);
_pendingRead = null; _pendingRead = null;
if (count == 0) return false; if (count == 0)
{
return false;
}
_prefix.Write(_probeBuffer, 0, count); _prefix.Write(_probeBuffer, 0, count);
var text = Encoding.ASCII.GetString(_prefix.GetBuffer(), 0, (int)Math.Min(_prefix.Length, 9)); 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 => text.StartsWith(prefix, StringComparison.Ordinal)))
if (!prefixes.Any(prefix => prefix.StartsWith(text, StringComparison.Ordinal))) return false; {
return true;
}
if (!prefixes.Any(prefix => prefix.StartsWith(text, StringComparison.Ordinal)))
{
return false;
}
} }
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<int> ReadAsync(byte[] buffer, int offset, int count, CancellationToken cancellationToken) public override async Task<int> ReadAsync(byte[] buffer, int offset, int count, CancellationToken cancellationToken)
{ {
if (buffer == null) throw new ArgumentNullException(nameof(buffer)); if (buffer == null)
if (offset < 0 || count < 0 || offset > buffer.Length - count) throw new ArgumentOutOfRangeException(); {
throw new ArgumentNullException(nameof(buffer));
}
if (offset < 0 || count < 0 || offset > buffer.Length - count)
{
throw new ArgumentOutOfRangeException();
}
cancellationToken.ThrowIfCancellationRequested(); cancellationToken.ThrowIfCancellationRequested();
if (count == 0) return 0; if (count == 0)
if (_prefix.Position < _prefix.Length) return _prefix.Read(buffer, offset, count); {
return 0;
}
if (_prefix.Position < _prefix.Length)
{
return _prefix.Read(buffer, offset, count);
}
if (_pendingRead != null) if (_pendingRead != null)
{ {
var pending = _pendingRead; var pending = _pendingRead;
var received = await pending.ConfigureAwait(false); var received = await pending.ConfigureAwait(false);
_pendingRead = null; _pendingRead = null;
if (received == 0) return 0; if (received == 0)
{
return 0;
}
var position = _prefix.Length; var position = _prefix.Length;
_prefix.Position = position; _prefix.Position = position;
_prefix.Write(_probeBuffer, 0, received); _prefix.Write(_probeBuffer, 0, received);
@@ -199,7 +199,7 @@ namespace EonaCat.Connections
foreach (var listener in listeners) foreach (var listener in listeners)
{ {
listener.Start(); listener.Start();
Console.WriteLine($"EonaCat TCP Server started on {FormatTcpListenerAddress(listener)}"); Console.WriteLine($"Heijmans TCP Server started on {FormatTcpListenerAddress(listener)}");
} }
if (_config.EnableHealthApi) if (_config.EnableHealthApi)
@@ -260,7 +260,11 @@ namespace EonaCat.Connections
_stats.IncrementDroppedConnections(); _stats.IncrementDroppedConnections();
if (_config.Security?.EnableSecurityLogging == true) 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; continue;
} }
@@ -272,7 +276,11 @@ namespace EonaCat.Connections
_stats.IncrementDroppedConnections(); _stats.IncrementDroppedConnections();
if (_config.Security?.EnableSecurityLogging == true) 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; continue;
} }
@@ -294,7 +302,11 @@ namespace EonaCat.Connections
{ {
DebugConnection($"Socket error in accept loop: {ex.Message}"); DebugConnection($"Socket error in accept loop: {ex.Message}");
RecordError(ex, $"Socket error in accept loop: {ex.SocketErrorCode}"); 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); await Task.Delay(100, token).ConfigureAwait(false);
} }
catch (OperationCanceledException) catch (OperationCanceledException)
@@ -306,7 +318,11 @@ namespace EonaCat.Connections
{ {
DebugConnection($"Unexpected error in accept loop: {ex.Message}"); DebugConnection($"Unexpected error in accept loop: {ex.Message}");
RecordError(ex, $"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); await Task.Delay(100, token).ConfigureAwait(false);
} }
} }
@@ -326,7 +342,7 @@ namespace EonaCat.Connections
{ {
if (Interlocked.CompareExchange(ref _udpRunning, 1, 0) == 1) 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; return;
} }
@@ -361,7 +377,7 @@ namespace EonaCat.Connections
foreach (var entry in entries) foreach (var entry in entries)
{ {
Console.WriteLine($"EonaCat UDP Server started on {entry.LocalEndPoint}"); Console.WriteLine($"Heijmans UDP Server started on {entry.LocalEndPoint}");
} }
try try
@@ -520,7 +536,11 @@ namespace EonaCat.Connections
|| bindAddress.MapToIPv6().Equals(localAddress.MapToIPv6()); || bindAddress.MapToIPv6().Equals(localAddress.MapToIPv6());
try try
{ {
await HealthApi.HandleConnectionAsync(stream, timeout, allowAccess).ConfigureAwait(false); do
{
timeout.CancelAfter(HealthApiServer.KeepAliveTimeout);
}
while (await HealthApi.HandleRequestAsync(stream, allowAccess).ConfigureAwait(false));
} }
catch (Exception) catch (Exception)
{ {
@@ -579,18 +599,24 @@ namespace EonaCat.Connections
if (_config.UseSsl) if (_config.UseSsl)
{ {
var isHttpClient = false;
if (_config.EnableHealthApi) if (_config.EnableHealthApi)
{ {
var probe = new ProtocolProbeStream(stream); var probe = new ProtocolProbeStream(stream);
stream = probe; stream = probe;
client.Stream = stream; 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); await HandleHealthRequestAsync(tcpClient, client, stream).ConfigureAwait(false);
return; return;
} }
isHttpClient = probe.OffersHttpAlpn();
} }
var sslMaxRetries = isHttpClient ? 1 : _config.SSLMaxRetries;
if (_config.Certificate == null) if (_config.Certificate == null)
{ {
var certEx = new InvalidOperationException("SSL is enabled but no server certificate is configured."); var certEx = new InvalidOperationException("SSL is enabled but no server certificate is configured.");
@@ -609,7 +635,7 @@ namespace EonaCat.Connections
bool sslAuthenticated = false; bool sslAuthenticated = false;
var sslDiagnostics = _config.EnableSslDiagnostics ? new Helpers.SslHandshakeDiagnostics() : null; 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; SslStream? sslStream = null;
@@ -675,7 +701,11 @@ namespace EonaCat.Connections
Message = "SSL handshake failed due to EOF" Message = "SSL handshake failed due to EOF"
}); });
DebugConnection($"SSL handshake EOF from {remoteEndPoint} on attempt {attempt}: {ioException.Message}"); 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) catch (AuthenticationException authException)
{ {
@@ -691,7 +721,11 @@ namespace EonaCat.Connections
Message = "SSL authentication failed" Message = "SSL authentication failed"
}); });
DebugConnection($"SSL authentication failed for {remoteEndPoint} on attempt {attempt}: {authException.Message}"); 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) if (!isRecoverable)
{ {
@@ -748,7 +782,7 @@ namespace EonaCat.Connections
#endif #endif
} }
if (!sslAuthenticated && (attempt < _config.SSLMaxRetries || _config.SSLMaxRetries == 0)) if (!sslAuthenticated && (attempt < sslMaxRetries || sslMaxRetries == 0))
{ {
int delaySeconds = _config.GetSslRetryDelaySeconds(attempt); int delaySeconds = _config.GetSslRetryDelaySeconds(attempt);
DebugConnection($"SSL retry in {delaySeconds}s (attempt {attempt})"); DebugConnection($"SSL retry in {delaySeconds}s (attempt {attempt})");
@@ -760,7 +794,12 @@ namespace EonaCat.Connections
if (!sslAuthenticated) 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) if (sslDiagnostics != null)
{ {
DebugConnection($"[SSL Final Metrics] {sslDiagnostics}"); DebugConnection($"[SSL Final Metrics] {sslDiagnostics}");