This commit is contained in:
EonaCat authored and Jeroen Saey committed 2026-11-04 11:09:42 +01:00
1 parent 37ca318245
commit 7ae2023c91
2 files changed
+65 -35

No files matched your search

+64 -33
View File
@@ -134,7 +134,9 @@ namespace EonaCat.Connections.Helpers
client.SendTimeout = 5000;
using var stream = client.GetStream();
await HandleRequestAsync(stream).ConfigureAwait(false);
using var idleTimeout = new CancellationTokenSource();
using var registration = idleTimeout.Token.Register(client.Close);
await HandleConnectionAsync(stream, idleTimeout).ConfigureAwait(false);
}
}
catch (Exception)
@@ -143,44 +145,66 @@ namespace EonaCat.Connections.Helpers
}
}
internal async Task HandleRequestAsync(Stream stream, bool allowAccess = true)
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<bool> HandleRequestAsync(Stream stream, bool allowAccess, bool isFirstRequest, bool allowKeepAlive)
{
var requestLine = await ReadRequestLineAsync(stream).ConfigureAwait(false);
if (string.IsNullOrEmpty(requestLine))
{
await WriteResponseAsync(stream, 400, "Bad Request", "text/plain", "Bad Request").ConfigureAwait(false);
return;
if (isFirstRequest)
{
await WriteResponseAsync(stream, 400, "Bad Request", "text/plain", "Bad Request", false).ConfigureAwait(false);
}
return false;
}
var parts = requestLine.Split(' ');
if (parts.Length < 2)
{
await WriteResponseAsync(stream, 400, "Bad Request", "text/plain", "Bad Request").ConfigureAwait(false);
return;
await WriteResponseAsync(stream, 400, "Bad Request", "text/plain", "Bad Request", false).ConfigureAwait(false);
return false;
}
var method = parts[0].ToUpperInvariant();
var path = parts[1].Split('?')[0].TrimEnd('/').ToLowerInvariant();
await DrainHeadersAsync(stream).ConfigureAwait(false);
var isHttp11 = parts.Length > 2 && parts[2].Trim().Equals("HTTP/1.1", StringComparison.OrdinalIgnoreCase);
var connectionHeader = await DrainHeadersAsync(stream).ConfigureAwait(false);
var keepAlive = allowKeepAlive && (connectionHeader == null
? isHttp11
: connectionHeader.IndexOf("keep-alive", StringComparison.OrdinalIgnoreCase) >= 0);
if (!allowAccess)
{
await WriteResponseAsync(stream, 403, "Forbidden", "text/plain", "Forbidden").ConfigureAwait(false);
return;
await WriteResponseAsync(stream, 403, "Forbidden", "text/plain", "Forbidden", false).ConfigureAwait(false);
return false;
}
if (method != "GET")
{
await WriteResponseAsync(stream, 405, "Method Not Allowed", "text/plain", "Method Not Allowed").ConfigureAwait(false);
return;
await WriteResponseAsync(stream, 405, "Method Not Allowed", "text/plain", "Method Not Allowed", false).ConfigureAwait(false);
return false;
}
switch (path)
{
case "" or "/":
var indexJson = "{\"endpoints\":[\"/health\",\"/status\",\"/dashboard\"]}";
await WriteResponseAsync(stream, 200, "OK", "application/json", indexJson).ConfigureAwait(false);
await WriteResponseAsync(stream, 200, "OK", "application/json", indexJson, keepAlive).ConfigureAwait(false);
break;
case "/dashboard":
@@ -188,25 +212,31 @@ namespace EonaCat.Connections.Helpers
?? 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);
await WriteResponseAsync(stream, 200, "OK", "text/html", reader.ReadToEnd(), keepAlive).ConfigureAwait(false);
}
break;
case "/health":
var healthJson = SafeGetJson(_getHealthJson);
await WriteResponseAsync(stream, 200, "OK", "application/json", healthJson).ConfigureAwait(false);
await WriteResponseAsync(stream, 200, "OK", "application/json", healthJson, keepAlive).ConfigureAwait(false);
break;
case "/status":
var statusJson = SafeGetJson(_getStatusJson);
await WriteResponseAsync(stream, 200, "OK", "application/json", statusJson).ConfigureAwait(false);
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").ConfigureAwait(false);
await WriteResponseAsync(stream, 404, "Not Found", "text/plain", "Not Found", keepAlive).ConfigureAwait(false);
break;
}
}
return keepAlive;
}
private static string SafeGetJson(Func<string> getter)
{
@@ -251,41 +281,42 @@ namespace EonaCat.Connections.Helpers
return sb.ToString();
}
private static async Task DrainHeadersAsync(Stream stream)
private static async Task<string> DrainHeadersAsync(Stream stream)
{
var sb = new StringBuilder();
var buffer = new byte[1];
int consecutiveNewlines = 0;
string connectionHeader = null;
int totalLength = 0;
while (consecutiveNewlines < 2)
while (totalLength < 65536)
{
int read = await stream.ReadAsync(buffer, 0, 1).ConfigureAwait(false);
if (read == 0)
var line = await ReadRequestLineAsync(stream).ConfigureAwait(false);
if (string.IsNullOrEmpty(line))
{
break;
}
if (buffer[0] == (byte)'\n')
totalLength += line.Length;
var colon = line.IndexOf(':');
if (colon > 0 && line.Substring(0, colon).Trim().Equals("Connection", StringComparison.OrdinalIgnoreCase))
{
consecutiveNewlines++;
}
else if (buffer[0] != (byte)'\r')
{
consecutiveNewlines = 0;
connectionHeader = line.Substring(colon + 1).Trim();
}
}
return connectionHeader;
}
private static async Task WriteResponseAsync(Stream stream, int statusCode, string statusText, string contentType, string body)
private static async Task WriteResponseAsync(Stream stream, int statusCode, string statusText, string contentType, string body, bool keepAlive, string cacheControl = "Cache-Control: no-store")
{
var bodyBytes = Encoding.UTF8.GetBytes(body);
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" +
(keepAlive
? $"Connection: keep-alive\r\nKeep-Alive: timeout={(int)KeepAliveTimeout.TotalSeconds}\r\n"
: "Connection: close\r\n") +
"X-Content-Type-Options: nosniff\r\n" +
"Cache-Control: no-store\r\n" +
cacheControl + "\r\n" +
"\r\n";
var headerBytes = Encoding.ASCII.GetBytes(header);
@@ -513,7 +513,6 @@ namespace EonaCat.Connections
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;
@@ -521,7 +520,7 @@ namespace EonaCat.Connections
|| bindAddress.MapToIPv6().Equals(localAddress.MapToIPv6());
try
{
await HealthApi.HandleRequestAsync(stream, allowAccess).ConfigureAwait(false);
await HealthApi.HandleConnectionAsync(stream, timeout, allowAccess).ConfigureAwait(false);
}
catch (Exception)
{