OpenGenesisLINK main - .NET 10 Build Gate / .NET 10 Windows x64 build (push) Waiting to run
Generation 1.1 .NET 10 ARM64 Server Runtime / ROBUST and Simulator .NET 10 ARM64 build + boot (push) Canceled after 0s
NexVerse CI / NV dollar live database matrix (push) Failing after 15s
OpenGenesisLINK main - .NET 10 Build Gate / .NET 10 generated-project and server build (push) Successful in 1m33s
OpenGenesisLINK Generation 1 - Abgeschlossene Branches bereinigen / Abgeschlossene und nicht mehr benoetigte Branches entfernen (push) Successful in 30s
Generation 1 Stable and Updates source policy / release-policy (push) Successful in 17s
NexVerse CI / Build NexVerse (push) Failing after 57s
742 lines
37 KiB
C#
742 lines
37 KiB
C#
// SPDX-License-Identifier: MPL-2.0
|
||
using System.Collections.Concurrent;
|
||
using System.Net;
|
||
using System.Security.Cryptography;
|
||
using System.Text;
|
||
using System.Text.Json;
|
||
using log4net;
|
||
using OpenMetaverse;
|
||
using OpenSim.Framework;
|
||
using OpenSim.Region.Framework.Scenes;
|
||
using OpenSim.Services.Interfaces;
|
||
|
||
namespace OpenGenesisLINK.Addons.OSWebInterface;
|
||
|
||
internal sealed class AdminHttpServer : IDisposable
|
||
{
|
||
private sealed record Session(UUID Principal, string Name, string Csrf, DateTimeOffset Expires);
|
||
private sealed class Attempt { public int Count; public DateTimeOffset Reset = DateTimeOffset.UtcNow.AddMinutes(5); }
|
||
private sealed record LoginRequest(string Username, string Password);
|
||
private sealed record RegionRequest(string RegionId);
|
||
private sealed record IarRequest(string RegionId, string Avatar);
|
||
private sealed record UpdateRequest(string Sha);
|
||
private sealed record ImportRequest(string RegionId);
|
||
|
||
private static readonly ILog Log = LogManager.GetLogger(typeof(AdminHttpServer));
|
||
private static readonly JsonSerializerOptions JsonOptions = new(JsonSerializerDefaults.Web);
|
||
private static object DllCompatibilityStatus()
|
||
{
|
||
// Only readable from an authenticated OGL.WebInterface admin session.
|
||
// Reports are written by the offline startup gate with private file mode.
|
||
string basePath = Path.Combine(AppContext.BaseDirectory, "ops-data");
|
||
var reports = new List<object>();
|
||
foreach (string mode in new[] { "simulator", "robust" })
|
||
{
|
||
string file = Path.Combine(basePath, "compatibility-" + mode + ".json");
|
||
if (!File.Exists(file)) continue;
|
||
try
|
||
{
|
||
var info = new FileInfo(file);
|
||
if (info.Length is < 10 or > 131072) continue;
|
||
using JsonDocument doc = JsonDocument.Parse(File.ReadAllText(file));
|
||
JsonElement r = doc.RootElement;
|
||
var errors = r.GetProperty("errors").EnumerateArray()
|
||
.Take(25).Select(x => x.GetString() ?? "").ToArray();
|
||
var warnings = r.GetProperty("warnings").EnumerateArray()
|
||
.Take(25).Select(x => x.GetString() ?? "").ToArray();
|
||
reports.Add(new
|
||
{
|
||
instance=mode,
|
||
status=r.GetProperty("status").GetString() ?? "unknown",
|
||
checkedAtUtc=r.GetProperty("checkedAtUtc").GetString(),
|
||
frameworkVersion=r.GetProperty("frameworkVersion").GetString(),
|
||
errors, warnings,
|
||
checkCount=r.GetProperty("checks").GetArrayLength()
|
||
});
|
||
}
|
||
catch (Exception e) when (e is IOException or UnauthorizedAccessException or JsonException
|
||
or KeyNotFoundException or InvalidOperationException)
|
||
{
|
||
reports.Add(new { instance=mode,status="unknown", checkedAtUtc=(string?)null,
|
||
frameworkVersion=(string?)null,errors=new[] { "Prüfbericht nicht lesbar." },
|
||
warnings=Array.Empty<string>(),checkCount=0 });
|
||
}
|
||
}
|
||
return new
|
||
{
|
||
reports,
|
||
currentState=reports.Count>0?"Verfügbare DLL-Dateien wurden geprüft.":
|
||
"Noch keine DLL-Startprüfung vorhanden.",
|
||
note="Der Offline-Prüfer kontrolliert die lokalen DLL-Dateien. " +
|
||
"Geänderte Dateien werden erst nach einem Neustart in den Prozess geladen. " +
|
||
"Ein grüner Prüfbericht allein ersetzt keinen echten Login- oder Regionstest."
|
||
};
|
||
}
|
||
|
||
private static readonly HttpClient NetworkClient = new(
|
||
new HttpClientHandler { AllowAutoRedirect = false })
|
||
{ Timeout = TimeSpan.FromSeconds(5) };
|
||
|
||
// Read-only admin endpoint. Only the OGL service sees the node credential;
|
||
// the browser receives the external observer's port statuses, never tokens.
|
||
private static async Task<object> ExternalNetworkStatusAsync()
|
||
{
|
||
string endpoint = Environment.GetEnvironmentVariable("OGL_UPDATE_CENTRAL_URL") ?? "";
|
||
string token = Environment.GetEnvironmentVariable("OGL_UPDATE_NODE_TOKEN") ?? "";
|
||
string nodeId = Environment.GetEnvironmentVariable("OGL_UPDATE_NODE_ID") ?? "";
|
||
if (endpoint.Length == 0 || token.Length < 32 || nodeId.Length == 0)
|
||
return new { configured = false, reachable = false, fresh = false,
|
||
checkedAtUtc = (string?)null, ageSeconds = (int?)null,
|
||
nodeId, checks = Array.Empty<object>(),
|
||
message = "Externer Prüfstandort noch nicht für diesen Simulator konfiguriert." };
|
||
if (!Uri.TryCreate(endpoint, UriKind.Absolute, out Uri? uri) ||
|
||
uri.Scheme != Uri.UriSchemeHttps || uri.UserInfo.Length != 0 ||
|
||
uri.AbsolutePath != "/" || uri.Query.Length != 0 || uri.Fragment.Length != 0)
|
||
return new { configured = false, reachable = false, fresh = false,
|
||
checkedAtUtc = (string?)null, ageSeconds = (int?)null,
|
||
nodeId, checks = Array.Empty<object>(),
|
||
message = "Adresse des Prüfstandorts ist nicht gültig." };
|
||
try
|
||
{
|
||
using var req = new HttpRequestMessage(HttpMethod.Get,
|
||
new Uri(uri,"/v1/network"));
|
||
req.Headers.Authorization = new System.Net.Http.Headers.AuthenticationHeaderValue(
|
||
"Bearer", token);
|
||
using var response = await NetworkClient.SendAsync(req);
|
||
if (!response.IsSuccessStatusCode)
|
||
throw new HttpRequestException("HTTP " + (int)response.StatusCode);
|
||
using var doc = JsonDocument.Parse(await response.Content.ReadAsStreamAsync());
|
||
JsonElement result = doc.RootElement;
|
||
bool fresh = result.GetProperty("fresh").GetBoolean();
|
||
JsonElement sample = result.GetProperty("checks").Clone();
|
||
return new {
|
||
configured = true, reachable = true, fresh,
|
||
checkedAtUtc = result.GetProperty("checkedAtUtc").ValueKind == JsonValueKind.String
|
||
? result.GetProperty("checkedAtUtc").GetString() : null,
|
||
ageSeconds = result.GetProperty("ageSeconds").ValueKind == JsonValueKind.Number
|
||
? (int?)result.GetProperty("ageSeconds").GetInt32() : null,
|
||
nodeId, checks = sample,
|
||
message = fresh ? "Externe TCP-Messung erfolgreich aktualisiert."
|
||
: "Externe Messung ist veraltet oder der Prüfstandort ist offline."
|
||
};
|
||
}
|
||
catch (Exception error)
|
||
{
|
||
Log.Warn("[OS WEBINTERFACE] External network monitor unavailable: " +
|
||
error.GetType().Name);
|
||
return new { configured = true, reachable = false, fresh = false,
|
||
checkedAtUtc = (string?)null, ageSeconds = (int?)null,
|
||
nodeId, checks = Array.Empty<object>(),
|
||
message = "Externer Prüfstandort ist momentan nicht erreichbar." };
|
||
}
|
||
}
|
||
|
||
private static readonly HttpClient TranslatorClient = new(
|
||
new HttpClientHandler { AllowAutoRedirect = false })
|
||
{ Timeout = TimeSpan.FromSeconds(5) };
|
||
|
||
// Admin-only: central translation health without disclosing per-node tokens.
|
||
private static async Task<object> TranslatorStatusAsync()
|
||
{
|
||
string node = Environment.GetEnvironmentVariable("OGL_TRANSLATOR_NODE_ID") ?? "";
|
||
string url = Environment.GetEnvironmentVariable("OGL_TRANSLATOR_CENTRAL_URL") ?? "";
|
||
string token = Environment.GetEnvironmentVariable("OGL_TRANSLATOR_NODE_TOKEN") ?? "";
|
||
DateTimeOffset checkedAtUtc = DateTimeOffset.UtcNow;
|
||
if (node.Length == 0 || url.Length == 0 || token.Length < 32)
|
||
return new { configured = false, connected = false, available = false,
|
||
nodeId = node.Length > 0 ? node : "–", endpoint = "",
|
||
chat = false, directIm = false, groupIm = false,
|
||
providerKeyOnNode = false, checkedAtUtc,
|
||
message = "Auf diesem Simulator ist der Global Translater nicht aktiviert." };
|
||
if (!Uri.TryCreate(url, UriKind.Absolute, out Uri? parsed) ||
|
||
parsed.Scheme != Uri.UriSchemeHttps || parsed.UserInfo.Length > 0 ||
|
||
parsed.AbsolutePath != "/" || parsed.Query.Length > 0 || parsed.Fragment.Length > 0)
|
||
return new { configured = true, connected = false, available = false,
|
||
nodeId = node, endpoint = "", chat = false, directIm = false,
|
||
groupIm = false, providerKeyOnNode = false, checkedAtUtc,
|
||
message = "Zentrale HTTPS-Adresse ungültig." };
|
||
string endpoint = parsed.GetLeftPart(UriPartial.Authority);
|
||
try
|
||
{
|
||
using var req = new HttpRequestMessage(HttpMethod.Get,
|
||
new Uri(parsed, "/v1/status"));
|
||
req.Headers.Authorization = new System.Net.Http.Headers.AuthenticationHeaderValue(
|
||
"Bearer", token);
|
||
using var res = await TranslatorClient.SendAsync(req);
|
||
if (!res.IsSuccessStatusCode)
|
||
return new { configured = true, connected = false, available = false,
|
||
nodeId = node, endpoint, chat = false, directIm = false,
|
||
groupIm = false, providerKeyOnNode = false, checkedAtUtc,
|
||
message = "Node-Anmeldung beim zentralen Dienst fehlgeschlagen (HTTP " +
|
||
(int)res.StatusCode + ")." };
|
||
using JsonDocument doc = JsonDocument.Parse(
|
||
await res.Content.ReadAsStreamAsync());
|
||
JsonElement status = doc.RootElement;
|
||
bool online = status.TryGetProperty("available", out JsonElement a) && a.GetBoolean();
|
||
bool chat = status.TryGetProperty("chat", out JsonElement ch) && ch.GetBoolean();
|
||
bool directIm = status.TryGetProperty("directIm", out JsonElement im) && im.GetBoolean();
|
||
bool groupIm = status.TryGetProperty("groupIm", out JsonElement gr) && gr.GetBoolean();
|
||
return new { configured = true, connected = true, available = online,
|
||
nodeId = node, endpoint, chat, directIm, groupIm,
|
||
providerKeyOnNode = false, checkedAtUtc,
|
||
message = online ? "OGL Translater: einsatzbereit."
|
||
: "Zentraler Dienst antwortet, Übersetzung derzeit nicht verfügbar." };
|
||
}
|
||
catch (Exception e)
|
||
{
|
||
Log.Warn("[OS WEBINTERFACE] Central translation status unavailable: " +
|
||
e.GetType().Name);
|
||
return new { configured = true, connected = false, available = false,
|
||
nodeId = node, endpoint, chat = false, directIm = false,
|
||
groupIm = false, providerKeyOnNode = false, checkedAtUtc,
|
||
message = "Zentraler Übersetzungsdienst nicht erreichbar." };
|
||
}
|
||
}
|
||
|
||
private readonly ConcurrentDictionary<UUID, Scene> _scenes;
|
||
private readonly ConcurrentDictionary<string, Session> _sessions = new();
|
||
private readonly ConcurrentDictionary<string, Attempt> _attempts = new();
|
||
private readonly HttpListener _listener = new();
|
||
private readonly CancellationTokenSource _stop = new();
|
||
private readonly AdminOperations _operations;
|
||
private readonly LiveUpdateBridge _liveUpdate;
|
||
private readonly Uri? _publicOrigin;
|
||
private readonly string _loopbackHost;
|
||
// Cookies are shared by hostname, NOT by port; give each service its own name.
|
||
private readonly string _cookieName;
|
||
private Task? _acceptTask;
|
||
private readonly DateTimeOffset _started = DateTimeOffset.UtcNow;
|
||
|
||
public AdminHttpServer(ConcurrentDictionary<UUID, Scene> scenes, string storage, int port, int retention, List<(string Name, Uri Uri)> services, LiveUpdateBridge liveUpdate, string publicOrigin)
|
||
{
|
||
_loopbackHost = $"127.0.0.1:{port}";
|
||
_cookieName = $"ogl_admin_{port}";
|
||
if (!string.IsNullOrWhiteSpace(publicOrigin))
|
||
{
|
||
if (!Uri.TryCreate(publicOrigin, UriKind.Absolute, out Uri? parsed) ||
|
||
parsed.Scheme != Uri.UriSchemeHttps || parsed.AbsolutePath != "/" ||
|
||
parsed.Query.Length != 0 || parsed.Fragment.Length != 0 ||
|
||
parsed.UserInfo.Length != 0)
|
||
throw new ArgumentException("PublicOrigin muss eine HTTPS-Origin ohne Pfad sein.");
|
||
_publicOrigin = parsed;
|
||
}
|
||
_scenes = scenes;
|
||
_operations = new AdminOperations(scenes, storage, retention, services);
|
||
_liveUpdate = liveUpdate;
|
||
// Binding to any public interface is deliberately unsupported.
|
||
_listener.Prefixes.Add($"http://127.0.0.1:{port}/");
|
||
}
|
||
|
||
public void Start()
|
||
{
|
||
_listener.Start();
|
||
_acceptTask = Task.Run(AcceptLoopAsync);
|
||
}
|
||
|
||
private async Task AcceptLoopAsync()
|
||
{
|
||
while (!_stop.IsCancellationRequested)
|
||
{
|
||
HttpListenerContext context;
|
||
try { context = await _listener.GetContextAsync(); }
|
||
catch (Exception e) when (e is HttpListenerException or ObjectDisposedException) { break; }
|
||
_ = Task.Run(() => DispatchAsync(context));
|
||
}
|
||
}
|
||
|
||
private static string Token() => Convert.ToHexString(RandomNumberGenerator.GetBytes(32)).ToLowerInvariant();
|
||
|
||
private static async Task<T?> ReadJsonAsync<T>(HttpListenerRequest req) where T : class
|
||
{
|
||
if (req.ContentLength64 > 16384 || req.ContentType is null ||
|
||
!req.ContentType.StartsWith("application/json", StringComparison.OrdinalIgnoreCase))
|
||
return null;
|
||
using var buffer = new MemoryStream();
|
||
byte[] block = new byte[4096];
|
||
int count;
|
||
while ((count = await req.InputStream.ReadAsync(block)) > 0)
|
||
{
|
||
if (buffer.Length + count > 16384) return null;
|
||
buffer.Write(block, 0, count);
|
||
}
|
||
try { return JsonSerializer.Deserialize<T>(buffer.ToArray(), JsonOptions); }
|
||
catch (JsonException) { return null; }
|
||
}
|
||
|
||
private static async Task SendAsync(HttpListenerResponse response, int code, object data)
|
||
{
|
||
response.StatusCode = code;
|
||
response.ContentType = "application/json; charset=utf-8";
|
||
byte[] payload = JsonSerializer.SerializeToUtf8Bytes(data, JsonOptions);
|
||
response.ContentLength64 = payload.Length;
|
||
await response.OutputStream.WriteAsync(payload);
|
||
}
|
||
|
||
private static void SecurityHeaders(HttpListenerResponse r)
|
||
{
|
||
r.Headers["X-Content-Type-Options"] = "nosniff";
|
||
r.Headers["Referrer-Policy"] = "no-referrer";
|
||
r.Headers["X-Frame-Options"] = "DENY";
|
||
r.Headers["Cache-Control"] = "no-store, private";
|
||
r.Headers["Content-Security-Policy"] =
|
||
"default-src 'none'; script-src 'self'; style-src 'self'; connect-src 'self'; img-src 'self' data:; base-uri 'none'; form-action 'self'; frame-ancestors 'none'";
|
||
}
|
||
|
||
private bool IsTrustedProxyRequest(HttpListenerRequest request) =>
|
||
_publicOrigin is not null &&
|
||
IPAddress.IsLoopback(request.RemoteEndPoint?.Address ?? IPAddress.None) &&
|
||
string.Equals(request.Headers["Host"], _loopbackHost, StringComparison.OrdinalIgnoreCase) &&
|
||
string.Equals(request.Headers["X-Forwarded-Proto"], "https", StringComparison.OrdinalIgnoreCase) &&
|
||
string.Equals(request.Headers["X-Forwarded-Host"], _publicOrigin.Authority, StringComparison.OrdinalIgnoreCase);
|
||
|
||
private bool SameOrigin(HttpListenerRequest request)
|
||
{
|
||
// Reverse proxy must send Host: 127.0.0.1:PORT to satisfy the listener
|
||
// and replace X-Forwarded-Host/Proto with a configured HTTPS origin.
|
||
string origin = request.Headers["Origin"] ?? "";
|
||
if (!string.IsNullOrEmpty(origin))
|
||
{
|
||
if (!Uri.TryCreate(origin, UriKind.Absolute, out Uri? parsed)) return false;
|
||
bool local = parsed.Scheme == Uri.UriSchemeHttp &&
|
||
string.Equals(parsed.Authority, _loopbackHost, StringComparison.OrdinalIgnoreCase);
|
||
bool proxy = IsTrustedProxyRequest(request) &&
|
||
string.Equals(parsed.GetLeftPart(UriPartial.Authority),
|
||
_publicOrigin!.GetLeftPart(UriPartial.Authority), StringComparison.OrdinalIgnoreCase);
|
||
return local || proxy;
|
||
}
|
||
string fetchSite = request.Headers["Sec-Fetch-Site"] ?? "";
|
||
return fetchSite is "" or "same-origin" or "none";
|
||
}
|
||
|
||
private bool TrySession(HttpListenerRequest request, out Session? session)
|
||
{
|
||
session = null;
|
||
string? id = request.Cookies[_cookieName]?.Value;
|
||
if (id is null || !_sessions.TryGetValue(id, out Session? s)) return false;
|
||
if (s.Expires <= DateTimeOffset.UtcNow)
|
||
{
|
||
_sessions.TryRemove(id, out _);
|
||
return false;
|
||
}
|
||
// UserLevel can be revoked while a session is active. Revalidate on each action.
|
||
Scene? scene = _scenes.Values.FirstOrDefault(v => v.UserAccountService is not null);
|
||
if (scene is null) return false;
|
||
try
|
||
{
|
||
UserAccount? account = scene.UserAccountService?.GetUserAccount(UUID.Zero, s.Principal);
|
||
if (account is null || account.UserLevel < 200 || !account.LoginAllowed) return false;
|
||
}
|
||
catch (Exception e) { Log.Warn("[OS WEBINTERFACE] Account revalidation failed", e); return false; }
|
||
session = s;
|
||
return true;
|
||
}
|
||
|
||
private async Task LoginAsync(HttpListenerContext ctx)
|
||
{
|
||
var request = await ReadJsonAsync<LoginRequest>(ctx.Request);
|
||
if (request is null || string.IsNullOrWhiteSpace(request.Username) ||
|
||
string.IsNullOrEmpty(request.Password) || request.Username.Length > 120 ||
|
||
request.Password.Length > 1024)
|
||
{
|
||
await SendAsync(ctx.Response, 400, new { error = "Ungültige Anmeldung" });
|
||
return;
|
||
}
|
||
string key = request.Username.Trim().ToLowerInvariant();
|
||
Attempt attempt = _attempts.GetOrAdd(key, _ => new Attempt());
|
||
lock (attempt)
|
||
{
|
||
if (attempt.Reset <= DateTimeOffset.UtcNow) { attempt.Count = 0; attempt.Reset = DateTimeOffset.UtcNow.AddMinutes(5); }
|
||
if (++attempt.Count > 8)
|
||
{
|
||
ctx.Response.StatusCode = 429;
|
||
return;
|
||
}
|
||
}
|
||
string[] split = request.Username.Replace('.', ' ').Split(' ', 2, StringSplitOptions.RemoveEmptyEntries | StringSplitOptions.TrimEntries);
|
||
if (split.Length != 2)
|
||
{
|
||
await SendAsync(ctx.Response, 401, new { error = "Anmeldung fehlgeschlagen" });
|
||
return;
|
||
}
|
||
|
||
Scene? scene = _scenes.Values.FirstOrDefault(s => s.UserAccountService is not null && s.AuthenticationService is not null);
|
||
if (scene is null)
|
||
{
|
||
await SendAsync(ctx.Response, 503, new { error = "Authentifizierungsdienste nicht verfügbar" });
|
||
return;
|
||
}
|
||
try
|
||
{
|
||
UserAccount? account = scene.UserAccountService.GetUserAccount(UUID.Zero, split[0], split[1]);
|
||
if (account is null || !account.LoginAllowed)
|
||
{
|
||
await SendAsync(ctx.Response, 401, new { error = "Anmeldung fehlgeschlagen" });
|
||
return;
|
||
}
|
||
// Same password transformation as the simulator login service.
|
||
string hashed = Util.Md5Hash(request.Password);
|
||
string token = scene.AuthenticationService.Authenticate(account.PrincipalID, hashed, 30);
|
||
if (string.IsNullOrWhiteSpace(token) || !UUID.TryParse(token, out UUID secureSession) || secureSession == UUID.Zero)
|
||
{
|
||
await SendAsync(ctx.Response, 401, new { error = "Anmeldung fehlgeschlagen" });
|
||
return;
|
||
}
|
||
try { scene.AuthenticationService.Release(account.PrincipalID, token); }
|
||
catch (Exception e) { Log.Warn("[OS WEBINTERFACE] Token cleanup failed", e); }
|
||
if (account.UserLevel < 200)
|
||
{
|
||
await SendAsync(ctx.Response, 403, new { error = "Access Denied – Keine Berechtigung." });
|
||
return;
|
||
}
|
||
lock (attempt) attempt.Count = 0;
|
||
string sid = Token();
|
||
var session = new Session(account.PrincipalID, account.Name, Token(), DateTimeOffset.UtcNow.AddHours(1));
|
||
_sessions[sid] = session;
|
||
bool secure = ctx.Request.IsSecureConnection || IsTrustedProxyRequest(ctx.Request);
|
||
ctx.Response.AppendHeader("Set-Cookie", _cookieName + "=" + sid +
|
||
"; Path=/; HttpOnly; SameSite=Strict; Max-Age=3600" + (secure ? "; Secure" : ""));
|
||
await SendAsync(ctx.Response, 200, new { name = session.Name, csrf = session.Csrf, expires = session.Expires });
|
||
Log.Info("[OS WEBINTERFACE] Administrative session established");
|
||
}
|
||
catch (Exception e)
|
||
{
|
||
Log.Error("[OS WEBINTERFACE] Authentication service error", e);
|
||
await SendAsync(ctx.Response, 503, new { error = "Authentifizierungsdienst nicht verfügbar" });
|
||
}
|
||
}
|
||
|
||
private static async Task ServeResourceAsync(HttpListenerResponse response, string resource, string contentType)
|
||
{
|
||
using Stream? stream = typeof(AdminHttpServer).Assembly.GetManifestResourceStream(
|
||
"os_webinterface.www." + resource);
|
||
if (stream is null) { response.StatusCode = 404; return; }
|
||
response.ContentType = contentType;
|
||
response.ContentLength64 = stream.Length;
|
||
await stream.CopyToAsync(response.OutputStream);
|
||
}
|
||
|
||
private bool ValidateMutation(HttpListenerRequest request, Session session) =>
|
||
SameOrigin(request) && string.Equals(request.Headers["X-OGL-CSRF"], session.Csrf, StringComparison.Ordinal);
|
||
|
||
private async Task DispatchAsync(HttpListenerContext ctx)
|
||
{
|
||
try
|
||
{
|
||
SecurityHeaders(ctx.Response);
|
||
HttpListenerRequest request = ctx.Request;
|
||
string route = request.Url?.AbsolutePath ?? "/";
|
||
string method = request.HttpMethod;
|
||
if (method == "GET" && route is "/" or "/index.html")
|
||
{
|
||
await ServeResourceAsync(ctx.Response, "index.html", "text/html; charset=utf-8");
|
||
return;
|
||
}
|
||
if (method == "GET" && route == "/style.css")
|
||
{
|
||
await ServeResourceAsync(ctx.Response, "style.css", "text/css; charset=utf-8");
|
||
return;
|
||
}
|
||
if (method == "GET" && route == "/ogl-simulator-logo.webp")
|
||
{
|
||
await ServeResourceAsync(ctx.Response, "ogl-simulator-logo.webp", "image/webp");
|
||
return;
|
||
}
|
||
if (method == "GET" && route == "/ogl-simulator-favicon.png")
|
||
{
|
||
await ServeResourceAsync(ctx.Response, "ogl-simulator-favicon.png", "image/png");
|
||
return;
|
||
}
|
||
if (method == "GET" && route == "/ogl-simulator-apple-icon.png")
|
||
{
|
||
await ServeResourceAsync(ctx.Response, "ogl-simulator-apple-icon.png", "image/png");
|
||
return;
|
||
}
|
||
if (method == "GET" && route == "/oar-live.css")
|
||
{
|
||
await ServeResourceAsync(ctx.Response, "oar-live.css", "text/css; charset=utf-8");
|
||
return;
|
||
}
|
||
if (method == "GET" && route == "/oar-live.js")
|
||
{
|
||
await ServeResourceAsync(ctx.Response, "oar-live.js", "text/javascript; charset=utf-8");
|
||
return;
|
||
}
|
||
if (method == "GET" && route == "/app.js")
|
||
{
|
||
await ServeResourceAsync(ctx.Response, "app.js", "text/javascript; charset=utf-8");
|
||
return;
|
||
}
|
||
if (method == "POST" && route == "/api/login")
|
||
{
|
||
if (!SameOrigin(request)) { await SendAsync(ctx.Response, 403, new { error = "Origin nicht erlaubt" }); return; }
|
||
await LoginAsync(ctx); return;
|
||
}
|
||
if (!route.StartsWith("/api/", StringComparison.Ordinal))
|
||
{
|
||
await SendAsync(ctx.Response, 404, new { error = "Nicht gefunden" }); return;
|
||
}
|
||
if (!TrySession(request, out Session? session) || session is null)
|
||
{
|
||
await SendAsync(ctx.Response, 401, new { error = "Nicht angemeldet" }); return;
|
||
}
|
||
if (method != "GET" && !ValidateMutation(request, session))
|
||
{
|
||
await SendAsync(ctx.Response, 403, new { error = "CSRF/Origin-Prüfung fehlgeschlagen" }); return;
|
||
}
|
||
if (method == "POST" && route == "/api/logout")
|
||
{
|
||
string? sid = request.Cookies[_cookieName]?.Value;
|
||
if (sid is not null) _sessions.TryRemove(sid, out _);
|
||
ctx.Response.AppendHeader("Set-Cookie", _cookieName + "=; Path=/; HttpOnly; SameSite=Strict; Secure; Max-Age=0");
|
||
await SendAsync(ctx.Response, 200, new { ok = true }); return;
|
||
}
|
||
if (method == "GET" && route == "/api/me")
|
||
{
|
||
await SendAsync(ctx.Response, 200, new { name = session.Name, csrf = session.Csrf }); return;
|
||
}
|
||
if (method == "GET" && route == "/api/translator/status")
|
||
{
|
||
await SendAsync(ctx.Response, 200, await TranslatorStatusAsync());
|
||
return;
|
||
}
|
||
if (method == "GET" && route == "/api/network/external")
|
||
{
|
||
await SendAsync(ctx.Response, 200, await ExternalNetworkStatusAsync());
|
||
return;
|
||
}
|
||
if (method == "GET" && route == "/api/health-center/summary")
|
||
{
|
||
await SendAsync(ctx.Response, 200,
|
||
await OglHealthDiagnostics.SummaryAsync(_operations, _stop.Token));
|
||
return;
|
||
}
|
||
if (method == "GET" && route == "/api/health-center/login-diagnostics")
|
||
{
|
||
await SendAsync(ctx.Response, 200,
|
||
OglHealthDiagnostics.LoginDiagnostics());
|
||
return;
|
||
}
|
||
if (method == "GET" && route == "/api/system/compatibility")
|
||
{
|
||
await SendAsync(ctx.Response, 200, DllCompatibilityStatus());
|
||
return;
|
||
}
|
||
if (method == "GET" && route == "/api/overview")
|
||
{
|
||
await SendAsync(ctx.Response, 200, new
|
||
{
|
||
started = _started,
|
||
uptimeSeconds = (long)(DateTimeOffset.UtcNow - _started).TotalSeconds,
|
||
memoryBytes = Environment.WorkingSet,
|
||
gcBytes = GC.GetTotalMemory(false),
|
||
regions = _operations.RegionSummary(),
|
||
endpoints = _operations.PortSummary(),
|
||
services = await _operations.ServiceSummaryAsync(_stop.Token)
|
||
});
|
||
return;
|
||
}
|
||
if (method == "GET" && route == "/api/logs")
|
||
{
|
||
await SendAsync(ctx.Response, 200, new { content = _operations.LogTail() }); return;
|
||
}
|
||
if (method == "GET" && route == "/api/jobs")
|
||
{
|
||
await SendAsync(ctx.Response, 200, new { jobs = _operations.Jobs() }); return;
|
||
}
|
||
if (method == "POST" && route == "/api/regions/restart")
|
||
{
|
||
var payload = await ReadJsonAsync<RegionRequest>(request);
|
||
if (payload is null || !_operations.Restart(payload.RegionId))
|
||
await SendAsync(ctx.Response, 404, new { error = "Region nicht gefunden" });
|
||
else await SendAsync(ctx.Response, 202, new { message = "Region-Neustart angefordert" });
|
||
return;
|
||
}
|
||
// All backup operations are behind the existing revalidated admin
|
||
// session; mutations additionally require same-origin CSRF checks.
|
||
if (method == "GET" && route == "/api/backups")
|
||
{
|
||
await SendAsync(ctx.Response, 200, await _operations.ListBackupsAsync(_stop.Token));
|
||
return;
|
||
}
|
||
if (method == "GET" && route == "/api/backups/download")
|
||
{
|
||
await _operations.DownloadBackupAsync(request.QueryString["kind"] ?? "",
|
||
request.QueryString["name"] ?? "", request, ctx.Response, _stop.Token);
|
||
return;
|
||
}
|
||
if (method == "POST" && route == "/api/iar/export")
|
||
{
|
||
var payload = await ReadJsonAsync<IarRequest>(request);
|
||
if (payload is null) { await SendAsync(ctx.Response, 400, new { error = "Avatar oder Region fehlt" }); return; }
|
||
await SendAsync(ctx.Response, 202, _operations.ExportInventory(payload.RegionId, payload.Avatar));
|
||
return;
|
||
}
|
||
if (method == "GET" && route == "/api/oar/status")
|
||
{
|
||
object? status = _operations.OarStatus(request.QueryString["id"] ?? "");
|
||
if (status is null)
|
||
await SendAsync(ctx.Response, 404, new { error = "OAR-Auftrag nicht gefunden" });
|
||
else
|
||
await SendAsync(ctx.Response, 200, status);
|
||
return;
|
||
}
|
||
if (method == "POST" && route == "/api/oar/export")
|
||
{
|
||
var payload = await ReadJsonAsync<RegionRequest>(request);
|
||
if (payload is null) { await SendAsync(ctx.Response, 400, new { error = "Region fehlt" }); return; }
|
||
await SendAsync(ctx.Response, 202, _operations.Export(payload.RegionId)); return;
|
||
}
|
||
if (method == "POST" && route == "/api/oar/import")
|
||
{
|
||
string regionId = request.QueryString["region"] ?? "";
|
||
if (request.ContentLength64 <= 0 || request.ContentLength64 > AdminOperations.MaxUploadBytes ||
|
||
request.ContentType != "application/octet-stream")
|
||
{
|
||
await SendAsync(ctx.Response, 413, new { error = "Nur OAR-Dateien bis 2 GiB erlaubt" }); return;
|
||
}
|
||
var job = await _operations.ImportAsync(regionId, request.InputStream, request.ContentLength64, _stop.Token);
|
||
await SendAsync(ctx.Response, 202, job); return;
|
||
}
|
||
if (method == "GET" && route == "/api/oar/download")
|
||
{
|
||
string id = request.QueryString["id"] ?? "";
|
||
string? remote = _operations.RemoteOarName(id);
|
||
if (!string.IsNullOrEmpty(remote))
|
||
{
|
||
await _operations.DownloadBackupAsync("oar", remote, request, ctx.Response, _stop.Token);
|
||
return;
|
||
}
|
||
string? file = _operations.ExportFile(id);
|
||
if (file is null) { await SendAsync(ctx.Response, 404, new { error = "Archiv nicht verfügbar" }); return; }
|
||
using var input = File.Open(file, FileMode.Open, FileAccess.Read, FileShare.Read);
|
||
long size = input.Length;
|
||
if (size == 0)
|
||
{
|
||
await SendAsync(ctx.Response, 503, new { error = "Archiv ist leer" });
|
||
return;
|
||
}
|
||
long first = 0, last = size - 1;
|
||
string? range = request.Headers["Range"];
|
||
if (!string.IsNullOrWhiteSpace(range))
|
||
{
|
||
// Single-range HTTP downloads allow large archives to resume
|
||
// after a browser/proxy connection drops.
|
||
if (!range.StartsWith("bytes=", StringComparison.OrdinalIgnoreCase)
|
||
|| range.Contains(',', StringComparison.Ordinal))
|
||
{
|
||
ctx.Response.Headers["Content-Range"] = $"bytes */{size}";
|
||
await SendAsync(ctx.Response, 416, new { error = "Ungültiger Downloadbereich" });
|
||
return;
|
||
}
|
||
string[] parts = range["bytes=".Length..].Split('-', 2);
|
||
bool valid = parts.Length == 2;
|
||
if (valid && parts[0].Length > 0)
|
||
{
|
||
valid = long.TryParse(parts[0], out first) && first >= 0 && first < size;
|
||
if (valid && parts[1].Length > 0)
|
||
valid = long.TryParse(parts[1], out last) && last >= first;
|
||
else if (valid) last = size - 1;
|
||
if (last >= size) last = size - 1;
|
||
}
|
||
else if (valid && parts[1].Length > 0)
|
||
{
|
||
valid = long.TryParse(parts[1], out long suffix) && suffix > 0;
|
||
if (valid) first = Math.Max(0, size - suffix);
|
||
}
|
||
else valid = false;
|
||
if (!valid)
|
||
{
|
||
ctx.Response.Headers["Content-Range"] = $"bytes */{size}";
|
||
await SendAsync(ctx.Response, 416, new { error = "Ungültiger Downloadbereich" });
|
||
return;
|
||
}
|
||
}
|
||
ctx.Response.ContentType = "application/octet-stream";
|
||
ctx.Response.Headers["Content-Disposition"] = "attachment; filename=\"region-" + id + ".oar\"";
|
||
ctx.Response.Headers["Accept-Ranges"] = "bytes";
|
||
if (range is not null)
|
||
{
|
||
ctx.Response.StatusCode = 206;
|
||
ctx.Response.Headers["Content-Range"] = $"bytes {first}-{last}/{size}";
|
||
}
|
||
ctx.Response.ContentLength64 = last - first + 1;
|
||
input.Position = first;
|
||
try
|
||
{
|
||
byte[] buffer = new byte[64 * 1024];
|
||
long remaining = last - first + 1;
|
||
while (remaining > 0)
|
||
{
|
||
int count = await input.ReadAsync(buffer.AsMemory(0, (int)Math.Min(remaining, buffer.Length)));
|
||
if (count == 0) throw new IOException("OAR-Datei endete vorzeitig");
|
||
await ctx.Response.OutputStream.WriteAsync(buffer.AsMemory(0, count));
|
||
remaining -= count;
|
||
}
|
||
}
|
||
catch (HttpListenerException)
|
||
{
|
||
// Browser cancelled/resumed the download. The saved OAR on
|
||
// disk is unaffected; do not generate another error response.
|
||
Log.Info("[OS WEBINTERFACE] OAR download connection closed by client: " + id);
|
||
}
|
||
catch (IOException e)
|
||
{
|
||
Log.Warn("[OS WEBINTERFACE] OAR download interrupted: " + id, e);
|
||
}
|
||
return;
|
||
}
|
||
if (method == "GET" && route == "/api/updates/check")
|
||
{
|
||
await SendAsync(ctx.Response, 200, await _operations.CheckUpdatesAsync(_stop.Token)); return;
|
||
}
|
||
if (method == "GET" && route == "/api/updates/live-status")
|
||
{
|
||
await SendAsync(ctx.Response, 200,
|
||
new { enabled = false, reachable = false,
|
||
message = "Historischer Git-Quellcode-Updater im Closed-Code-Modell deaktiviert." });
|
||
return;
|
||
}
|
||
if (method == "POST" && route == "/api/updates/live-start")
|
||
{
|
||
await SendAsync(ctx.Response, 410, new {
|
||
error = "Der historische Git-Updater ist deaktiviert. Es werden nur geprüfte OGL-Binärpakete bereitgestellt."
|
||
});
|
||
return;
|
||
}
|
||
if (method == "POST" && route == "/api/updates/stage")
|
||
{
|
||
var payload = await ReadJsonAsync<UpdateRequest>(request);
|
||
if (payload is null) { await SendAsync(ctx.Response, 400, new { error = "Commit fehlt" }); return; }
|
||
await SendAsync(ctx.Response, 200, await _operations.StageUpdateAsync(payload.Sha, _stop.Token)); return;
|
||
}
|
||
await SendAsync(ctx.Response, 404, new { error = "Route nicht gefunden" });
|
||
}
|
||
catch (WebDavBackupStore.BackupException e)
|
||
{
|
||
if (ctx.Response.OutputStream.CanWrite)
|
||
await SendAsync(ctx.Response, e.Status, new { error = e.Message });
|
||
}
|
||
catch (AdminOperations.OperationException e)
|
||
{
|
||
if (ctx.Response.OutputStream.CanWrite)
|
||
await SendAsync(ctx.Response, e.Status, new { error = e.Message });
|
||
}
|
||
catch (Exception e)
|
||
{
|
||
Log.Error("[OS WEBINTERFACE] Request failed", e);
|
||
try { if (ctx.Response.OutputStream.CanWrite) await SendAsync(ctx.Response, 500, new { error = "Interner Fehler" }); } catch { }
|
||
}
|
||
finally { try { ctx.Response.Close(); } catch { } }
|
||
}
|
||
|
||
public void Dispose()
|
||
{
|
||
_stop.Cancel();
|
||
try { _listener.Stop(); _listener.Close(); } catch { }
|
||
_operations.Dispose();
|
||
_liveUpdate.Dispose();
|
||
_sessions.Clear();
|
||
_stop.Dispose();
|
||
}
|
||
}
|