Files
opengenesislinkserver/addons/OSWebInterface/UpdateStager.cs
T
OpenGenesis (EULA) a9880cf2e4 feat(gen1): OGL Health Center, anonymisierte Login-Diagnose und DLL-Startschutz
Integrates administrator-only health endpoints, privacy-preserving ROBUST login diagnostics, validated DLL preflight sources, WebInterface runtime UI and required assets. Verified with .NET 10 builds, synthetic log tests and responsive browser tests. Live rollout on NexTopia; main simulator awaits its next controlled restart.
2026-11-21 23:19:34 +01:00

293 lines
14 KiB
C#

// SPDX-License-Identifier: LicenseRef-OpenGenesisLINK-EULA
using System.IO.Compression;
using System.Net;
using System.Net.Http.Headers;
using System.Runtime.InteropServices;
using System.Security.Cryptography;
using System.Text.Json;
namespace OpenGenesisLINK.Addons.OSWebInterface;
/// <summary>
/// Closed-code OGL update client. Fetches only reviewed binary releases from
/// the central OGL Update Center. Does not access git or execute installer code.
/// </summary>
internal sealed class UpdateStager
{
private readonly string _data;
private readonly int _retention;
private readonly SemaphoreSlim _lock = new(1, 1);
private readonly HttpClient _client = new(
new HttpClientHandler { AllowAutoRedirect = false })
{ Timeout = TimeSpan.FromMinutes(5) };
private const long MaxArchive = 768L * 1024 * 1024;
private sealed record Release(string Id, string Version, string TargetOs,
string TargetArch, string Sha256, long Size, string Notes, string PublishedAtUtc);
private sealed record Snapshot(bool Configured, bool Connected, bool Available,
string Node, string Message, Release? Release);
public UpdateStager(string data, int retention)
{
_data = data;
_retention = retention;
}
private static (Uri? Base, string Node, string Token) Settings()
{
string url = Environment.GetEnvironmentVariable("OGL_UPDATE_CENTRAL_URL")?.Trim() ?? "";
string node = Environment.GetEnvironmentVariable("OGL_UPDATE_NODE_ID")?.Trim() ?? "";
string token = Environment.GetEnvironmentVariable("OGL_UPDATE_NODE_TOKEN") ?? "";
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 ||
token.Length < 32 || node.Length < 3 || node.Length > 64)
return (null, node, "");
return (parsed, node, token);
}
private static string OsName =>
OperatingSystem.IsLinux() ? "linux" :
OperatingSystem.IsWindows() ? "windows" :
OperatingSystem.IsMacOS() ? "macos" : "unsupported";
private static string ArchName => RuntimeInformation.OSArchitecture switch
{
Architecture.X64 => "x64", Architecture.Arm64 => "arm64",
Architecture.X86 => "x86", _ => "unsupported"
};
private async Task<Snapshot> GetAsync(CancellationToken stop)
{
var (baseUri, node, token) = Settings();
if (baseUri is null)
return new(false, false, false, node,
"Dieser Simulator ist noch nicht beim OGL Update Center registriert.", null);
try
{
using var req = new HttpRequestMessage(HttpMethod.Get,
new Uri(baseUri, "/v1/releases/latest?os=" + OsName + "&arch=" + ArchName));
req.Headers.Authorization = new AuthenticationHeaderValue("Bearer", token);
using var linked = CancellationTokenSource.CreateLinkedTokenSource(stop);
linked.CancelAfter(TimeSpan.FromSeconds(8));
using HttpResponseMessage res = await _client.SendAsync(req, linked.Token);
if (!res.IsSuccessStatusCode)
return new(true, false, false, node,
"OGL Update Center: Node-Anmeldung oder Verbindung fehlgeschlagen (HTTP " +
(int)res.StatusCode + ").", null);
using var document = JsonDocument.Parse(await res.Content.ReadAsStreamAsync(linked.Token));
JsonElement root = document.RootElement;
bool available = root.GetProperty("available").GetBoolean();
if (!available)
return new(true, true, false, node,
root.TryGetProperty("message", out var msg)
? (msg.GetString() ?? "Keine neue Version freigegeben.")
: "Keine neue Version freigegeben.", null);
JsonElement item = root.GetProperty("release");
var release = new Release(
item.GetProperty("id").GetString() ?? "",
item.GetProperty("version").GetString() ?? "",
item.GetProperty("targetOs").GetString() ?? "",
item.GetProperty("targetArch").GetString() ?? "",
item.GetProperty("sha256").GetString() ?? "",
item.GetProperty("size").GetInt64(),
item.TryGetProperty("notes", out var notes) ? notes.GetString() ?? "" : "",
item.TryGetProperty("publishedAtUtc", out var published)
? published.GetString() ?? "" : "");
bool compatible = release.TargetOs == OsName && release.TargetArch == ArchName;
return new(true, true, compatible, node,
compatible ? "Ein geprüftes Update steht zum Herunterladen bereit." :
"Ein neues Release ist vorhanden, jedoch nicht für diese Plattform/Architektur.",
release);
}
catch (Exception ex) when (ex is not OperationCanceledException || !stop.IsCancellationRequested)
{
return new(true, false, false, node,
"OGL Update Center derzeit nicht erreichbar (" + ex.GetType().Name + ").", null);
}
}
public async Task<object> CheckAsync(CancellationToken stop)
{
Snapshot snap = await GetAsync(stop);
string local = OpenSim.VersionInfo.VersionNumber;
return new
{
configured = snap.Configured,
connected = snap.Connected,
nodeId = snap.Node,
currentVersion = local,
available = snap.Available &&
snap.Release is not null &&
!string.Equals(snap.Release.Version, local, StringComparison.OrdinalIgnoreCase),
release = snap.Release is null ? null : new
{
id = snap.Release.Id, version = snap.Release.Version,
targetOs = snap.Release.TargetOs, targetArch = snap.Release.TargetArch,
sha256 = snap.Release.Sha256, size = snap.Release.Size,
notes = snap.Release.Notes, publishedAtUtc = snap.Release.PublishedAtUtc
},
message = snap.Release?.Version == local ?
"Diese OGL-Version ist bereits installiert." : snap.Message,
checkedAtUtc = DateTimeOffset.UtcNow
};
}
private static bool ReleaseId(string id) =>
id.Length is >= 3 and <= 71 && char.IsLetterOrDigit(id[0]) &&
id.All(c => char.IsLetterOrDigit(c) || c is '-' or '_' or '.');
private static void PrivateDir(string dir)
{
Directory.CreateDirectory(dir);
if (!OperatingSystem.IsWindows())
File.SetUnixFileMode(dir,
UnixFileMode.UserRead | UnixFileMode.UserWrite | UnixFileMode.UserExecute);
}
private static void PrivateFile(string file)
{
if (!OperatingSystem.IsWindows())
File.SetUnixFileMode(file, UnixFileMode.UserRead | UnixFileMode.UserWrite);
}
public async Task<object> StageAsync(string id, CancellationToken stop)
{
if (!ReleaseId(id))
throw new AdminOperations.OperationException(400, "Ungültige OGL-Releasekennung.");
if (OperatingSystem.IsWindows())
throw new AdminOperations.OperationException(501,
"Windows-Staging erfordert zuerst geprüfte NTFS-ACLs.");
if (!_lock.Wait(0))
throw new AdminOperations.OperationException(409, "Ein Update-Download läuft bereits.");
try
{
Snapshot snap = await GetAsync(stop);
if (!snap.Connected || !snap.Available || snap.Release is null)
throw new AdminOperations.OperationException(503, snap.Message);
Release release = snap.Release;
if (release.Id != id ||
release.Version == OpenSim.VersionInfo.VersionNumber ||
release.Size is < 1 or > MaxArchive ||
release.Sha256.Length != 64 || !release.Sha256.All(Uri.IsHexDigit))
throw new AdminOperations.OperationException(409,
"Dieses Release ist nicht für den Simulator freigegeben.");
var (baseUri, _, token) = Settings();
if (baseUri is null)
throw new AdminOperations.OperationException(503,"Node-Verbindung fehlt.");
string staging = Path.Combine(_data, "updates");
string backups = Path.Combine(_data, "configuration-backups");
PrivateDir(staging); PrivateDir(backups);
string filename = Path.Combine(staging, release.Id + ".zip");
if (File.Exists(filename))
{
await using var existing = File.OpenRead(filename);
string localSha = Convert.ToHexString(await SHA256.HashDataAsync(existing, stop));
if (localSha.Equals(release.Sha256,StringComparison.OrdinalIgnoreCase))
return new { state = "staged", release = release.Id, path = "updates/" +
Path.GetFileName(filename), note = "Bereits geprüft heruntergeladen; keine Installation ausgeführt." };
File.Delete(filename);
}
string temp = filename + ".partial";
if (File.Exists(temp)) File.Delete(temp);
try
{
using var request = new HttpRequestMessage(HttpMethod.Get,
new Uri(baseUri, "/v1/releases/" + release.Id + "/download"));
request.Headers.Authorization = new AuthenticationHeaderValue("Bearer", token);
using HttpResponseMessage res = await _client.SendAsync(request,
HttpCompletionOption.ResponseHeadersRead, stop);
if (!res.IsSuccessStatusCode)
throw new IOException("Das Updatepaket wurde nicht freigegeben (HTTP " +
(int)res.StatusCode + ").");
if (res.Content.Headers.ContentLength != release.Size)
throw new IOException("Paketgröße entspricht nicht der geprüften Freigabe.");
await using (Stream input = await res.Content.ReadAsStreamAsync(stop))
await using (var output = new FileStream(temp, FileMode.CreateNew,
FileAccess.Write, FileShare.None, 128*1024, true))
{
long copied = 0;
byte[] buf = new byte[128*1024];
int count;
while ((count = await input.ReadAsync(buf, stop)) > 0)
{
copied += count;
if (copied > release.Size || copied > MaxArchive)
throw new IOException("Ungültige Paketgröße.");
await output.WriteAsync(buf.AsMemory(0,count),stop);
}
if (copied != release.Size)
throw new IOException("Unvollständiger Download.");
}
PrivateFile(temp);
await using (var verify = File.OpenRead(temp))
{
string hash = Convert.ToHexString(await SHA256.HashDataAsync(verify,stop));
if (!hash.Equals(release.Sha256,StringComparison.OrdinalIgnoreCase))
throw new IOException("SHA-256-Prüfung fehlgeschlagen.");
}
string stamp = DateTimeOffset.UtcNow.ToString("yyyyMMddTHHmmssfffZ");
string backup = Path.Combine(backups, stamp+"-"+release.Id+".zip");
BackupConfigs(backup);
File.Move(temp, filename);
PrivateFile(filename);
Prune(backups);
return new
{
state = "staged", release = release.Id,
path = "updates/" + Path.GetFileName(filename),
backup = "configuration-backups/" + Path.GetFileName(backup),
note = "Geprüftes OGL-Binärupdate heruntergeladen; lokale Konfiguration gesichert. " +
"Keine Installation oder Simulatorunterbrechung ausgeführt."
};
}
finally { try { if (File.Exists(temp)) File.Delete(temp); } catch { } }
}
catch (AdminOperations.OperationException) { throw; }
catch (Exception error)
{
throw new AdminOperations.OperationException(502,
"OGL Update Center: Paket konnte nicht vorbereitet werden (" +
error.GetType().Name + ").");
}
finally { _lock.Release(); }
}
private static void BackupConfigs(string target)
{
string root = AppContext.BaseDirectory.TrimEnd(Path.DirectorySeparatorChar);
string[] direct = ["OpenSim.ini", "OpenSimDefaults.ini", "nexverse.local.env"];
string[] dirs = ["Regions", "config-include"];
using var zip = new ZipArchive(File.Open(target, FileMode.CreateNew), ZipArchiveMode.Create);
PrivateFile(target);
foreach (string f in direct)
{
string path = Path.Combine(root, f);
if (File.Exists(path) && (File.GetAttributes(path) & FileAttributes.ReparsePoint) == 0)
zip.CreateEntryFromFile(path, f, CompressionLevel.Optimal);
}
foreach (string d in dirs)
{
string folder = Path.Combine(root, d);
if (!Directory.Exists(folder)) continue;
foreach (string f in Directory.EnumerateFiles(folder, "*", SearchOption.AllDirectories))
{
if ((File.GetAttributes(f) & FileAttributes.ReparsePoint) != 0) continue;
string relative = Path.GetRelativePath(root, f);
if (new[]{".ini",".xml",".pem",".env",".p12",".pfx",".key",".crt",".json"}
.Any(ext => relative.EndsWith(ext,StringComparison.OrdinalIgnoreCase)))
zip.CreateEntryFromFile(f, relative.Replace('\\','/'), CompressionLevel.Optimal);
}
}
}
private void Prune(string backupDir)
{
foreach (string old in Directory.EnumerateFiles(backupDir, "*.zip")
.OrderByDescending(File.GetCreationTimeUtc).Skip(_retention))
{
if (Path.GetFileName(old).Length > 30) File.Delete(old);
}
}
}