// 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;
///
/// Closed-code OGL update client. Fetches only reviewed binary releases from
/// the central OGL Update Center. Does not access git or execute installer code.
///
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 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