Updated
This commit is contained in:
1 parent
37ca318245
commit
7ae2023c91
2 files changed
+65
-35
No files matched your search
@@ -134,7 +134,9 @@ namespace EonaCat.Connections.Helpers
|
|||||||
client.SendTimeout = 5000;
|
client.SendTimeout = 5000;
|
||||||
|
|
||||||
using var stream = client.GetStream();
|
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)
|
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);
|
var requestLine = await ReadRequestLineAsync(stream).ConfigureAwait(false);
|
||||||
|
|
||||||
if (string.IsNullOrEmpty(requestLine))
|
if (string.IsNullOrEmpty(requestLine))
|
||||||
{
|
{
|
||||||
await WriteResponseAsync(stream, 400, "Bad Request", "text/plain", "Bad Request").ConfigureAwait(false);
|
if (isFirstRequest)
|
||||||
return;
|
{
|
||||||
|
await WriteResponseAsync(stream, 400, "Bad Request", "text/plain", "Bad Request", false).ConfigureAwait(false);
|
||||||
|
}
|
||||||
|
return false;
|
||||||
}
|
}
|
||||||
|
|
||||||
var parts = requestLine.Split(' ');
|
var parts = requestLine.Split(' ');
|
||||||
if (parts.Length < 2)
|
if (parts.Length < 2)
|
||||||
{
|
{
|
||||||
await WriteResponseAsync(stream, 400, "Bad Request", "text/plain", "Bad Request").ConfigureAwait(false);
|
await WriteResponseAsync(stream, 400, "Bad Request", "text/plain", "Bad Request", false).ConfigureAwait(false);
|
||||||
return;
|
return false;
|
||||||
}
|
}
|
||||||
|
|
||||||
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();
|
||||||
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)
|
if (!allowAccess)
|
||||||
{
|
{
|
||||||
await WriteResponseAsync(stream, 403, "Forbidden", "text/plain", "Forbidden").ConfigureAwait(false);
|
await WriteResponseAsync(stream, 403, "Forbidden", "text/plain", "Forbidden", false).ConfigureAwait(false);
|
||||||
return;
|
return false;
|
||||||
}
|
}
|
||||||
|
|
||||||
if (method != "GET")
|
if (method != "GET")
|
||||||
{
|
{
|
||||||
await WriteResponseAsync(stream, 405, "Method Not Allowed", "text/plain", "Method Not Allowed").ConfigureAwait(false);
|
await WriteResponseAsync(stream, 405, "Method Not Allowed", "text/plain", "Method Not Allowed", false).ConfigureAwait(false);
|
||||||
return;
|
return false;
|
||||||
}
|
}
|
||||||
|
|
||||||
switch (path)
|
switch (path)
|
||||||
{
|
{
|
||||||
case "" or "/":
|
case "" or "/":
|
||||||
var indexJson = "{\"endpoints\":[\"/health\",\"/status\",\"/dashboard\"]}";
|
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;
|
break;
|
||||||
|
|
||||||
case "/dashboard":
|
case "/dashboard":
|
||||||
@@ -188,25 +212,31 @@ namespace EonaCat.Connections.Helpers
|
|||||||
?? 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))
|
||||||
{
|
{
|
||||||
await WriteResponseAsync(stream, 200, "OK", "text/html", reader.ReadToEnd()).ConfigureAwait(false);
|
await WriteResponseAsync(stream, 200, "OK", "text/html", reader.ReadToEnd(), keepAlive).ConfigureAwait(false);
|
||||||
}
|
}
|
||||||
break;
|
break;
|
||||||
|
|
||||||
case "/health":
|
case "/health":
|
||||||
var healthJson = SafeGetJson(_getHealthJson);
|
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;
|
break;
|
||||||
|
|
||||||
case "/status":
|
case "/status":
|
||||||
var statusJson = SafeGetJson(_getStatusJson);
|
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;
|
break;
|
||||||
|
|
||||||
default:
|
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;
|
break;
|
||||||
}
|
}
|
||||||
}
|
|
||||||
|
return keepAlive;
|
||||||
|
}
|
||||||
|
|
||||||
private static string SafeGetJson(Func<string> getter)
|
private static string SafeGetJson(Func<string> getter)
|
||||||
{
|
{
|
||||||
@@ -251,41 +281,42 @@ namespace EonaCat.Connections.Helpers
|
|||||||
return sb.ToString();
|
return sb.ToString();
|
||||||
}
|
}
|
||||||
|
|
||||||
private static async Task DrainHeadersAsync(Stream stream)
|
private static async Task<string> DrainHeadersAsync(Stream stream)
|
||||||
{
|
{
|
||||||
var sb = new StringBuilder();
|
string connectionHeader = null;
|
||||||
var buffer = new byte[1];
|
int totalLength = 0;
|
||||||
int consecutiveNewlines = 0;
|
|
||||||
|
|
||||||
while (consecutiveNewlines < 2)
|
while (totalLength < 65536)
|
||||||
{
|
{
|
||||||
int read = await stream.ReadAsync(buffer, 0, 1).ConfigureAwait(false);
|
var line = await ReadRequestLineAsync(stream).ConfigureAwait(false);
|
||||||
if (read == 0)
|
if (string.IsNullOrEmpty(line))
|
||||||
{
|
{
|
||||||
break;
|
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++;
|
connectionHeader = line.Substring(colon + 1).Trim();
|
||||||
}
|
|
||||||
else if (buffer[0] != (byte)'\r')
|
|
||||||
{
|
|
||||||
consecutiveNewlines = 0;
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
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 bodyBytes = Encoding.UTF8.GetBytes(body);
|
||||||
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" +
|
||||||
"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" +
|
"X-Content-Type-Options: nosniff\r\n" +
|
||||||
"Cache-Control: no-store\r\n" +
|
cacheControl + "\r\n" +
|
||||||
"\r\n";
|
"\r\n";
|
||||||
|
|
||||||
var headerBytes = Encoding.ASCII.GetBytes(header);
|
var headerBytes = Encoding.ASCII.GetBytes(header);
|
||||||
|
|||||||
@@ -513,7 +513,6 @@ namespace EonaCat.Connections
|
|||||||
private async Task HandleHealthRequestAsync(TcpClient tcpClient, Connection client, Stream stream)
|
private async Task HandleHealthRequestAsync(TcpClient tcpClient, Connection client, Stream stream)
|
||||||
{
|
{
|
||||||
using var timeout = CancellationTokenSource.CreateLinkedTokenSource(_serverCancellation.Token);
|
using var timeout = CancellationTokenSource.CreateLinkedTokenSource(_serverCancellation.Token);
|
||||||
timeout.CancelAfter(TimeSpan.FromSeconds(5));
|
|
||||||
using var registration = timeout.Token.Register(tcpClient.Close);
|
using var registration = timeout.Token.Register(tcpClient.Close);
|
||||||
var bindAddress = _config.HealthApiBindAddress ?? IPAddress.Loopback;
|
var bindAddress = _config.HealthApiBindAddress ?? IPAddress.Loopback;
|
||||||
var localAddress = ((IPEndPoint)tcpClient.Client.LocalEndPoint).Address;
|
var localAddress = ((IPEndPoint)tcpClient.Client.LocalEndPoint).Address;
|
||||||
@@ -521,7 +520,7 @@ namespace EonaCat.Connections
|
|||||||
|| bindAddress.MapToIPv6().Equals(localAddress.MapToIPv6());
|
|| bindAddress.MapToIPv6().Equals(localAddress.MapToIPv6());
|
||||||
try
|
try
|
||||||
{
|
{
|
||||||
await HealthApi.HandleRequestAsync(stream, allowAccess).ConfigureAwait(false);
|
await HealthApi.HandleConnectionAsync(stream, timeout, allowAccess).ConfigureAwait(false);
|
||||||
}
|
}
|
||||||
catch (Exception)
|
catch (Exception)
|
||||||
{
|
{
|
||||||
|
|||||||
Reference in new issue
Block a user