183 lines
9.2 KiB
C#
183 lines
9.2 KiB
C#
// SPDX-License-Identifier: MPL-2.0
|
|
using System.IO.Compression;
|
|
using System.Net;
|
|
using System.Net.Http.Headers;
|
|
using System.Text.Json;
|
|
|
|
namespace OpenGenesisLINK.Addons.OSWebInterface;
|
|
|
|
/// <summary>
|
|
/// Safe download-only update stage: verifies advertised SHA, saves the GitHub
|
|
/// source snapshot, and backs up configuration BEFORE any future installation.
|
|
/// Does not execute downloaded source or replace running simulator assemblies.
|
|
/// </summary>
|
|
internal sealed class UpdateStager
|
|
{
|
|
private static readonly HttpClient GitHub = CreateClient();
|
|
private readonly string _data;
|
|
private readonly int _retention;
|
|
private readonly SemaphoreSlim _lock = new(1, 1);
|
|
public const long MaxSnapshot = 256L * 1024 * 1024;
|
|
|
|
private static HttpClient CreateClient()
|
|
{
|
|
var client = new HttpClient(new HttpClientHandler { AllowAutoRedirect = false })
|
|
{
|
|
Timeout = TimeSpan.FromMinutes(5)
|
|
};
|
|
client.DefaultRequestHeaders.UserAgent.Add(new ProductInfoHeaderValue("OpenGenesisLINK-UpdateStage", "0.1"));
|
|
client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/vnd.github+json"));
|
|
return client;
|
|
}
|
|
public UpdateStager(string data, int retention)
|
|
{
|
|
_data = data;
|
|
_retention = retention;
|
|
}
|
|
|
|
private static void PrivateDirectory(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);
|
|
}
|
|
private static bool Sha(string sha) =>
|
|
sha.Length == 40 && sha.All(Uri.IsHexDigit);
|
|
|
|
private static async Task<HttpResponseMessage> RequestSnapshot(string sha, CancellationToken stop)
|
|
{
|
|
var first = await GitHub.GetAsync(
|
|
"https://api.github.com/repos/opengenesislink/opengenesislinkserver/tarball/" + sha,
|
|
HttpCompletionOption.ResponseHeadersRead, stop);
|
|
if (first.StatusCode is HttpStatusCode.MovedPermanently or HttpStatusCode.Redirect or
|
|
HttpStatusCode.RedirectMethod or HttpStatusCode.TemporaryRedirect or HttpStatusCode.PermanentRedirect)
|
|
{
|
|
Uri? target = first.Headers.Location;
|
|
first.Dispose();
|
|
if (target is null || target.Scheme != Uri.UriSchemeHttps ||
|
|
!string.Equals(target.Host, "codeload.github.com", StringComparison.OrdinalIgnoreCase) ||
|
|
!target.AbsolutePath.StartsWith("/opengenesislink/opengenesislinkserver/", StringComparison.Ordinal))
|
|
throw new IOException("GitHub-Snapshot verweist auf eine unerwartete Adresse.");
|
|
return await GitHub.GetAsync(target, HttpCompletionOption.ResponseHeadersRead, stop);
|
|
}
|
|
return first;
|
|
}
|
|
|
|
public async Task<object> StageAsync(string sha, CancellationToken stop)
|
|
{
|
|
if (!Sha(sha)) throw new AdminOperations.OperationException(400, "Ungültiger Commit SHA");
|
|
if (OperatingSystem.IsWindows()) throw new AdminOperations.OperationException(501, "Windows-Update-Backup benötigt zuerst geprüfte NTFS-ACL-Berechtigungen; Update-Staging deaktiviert.");
|
|
if (!_lock.Wait(0)) throw new AdminOperations.OperationException(409, "Ein Update-Download läuft bereits");
|
|
try
|
|
{
|
|
using var latestResponse = await GitHub.GetAsync(
|
|
"https://api.github.com/repos/opengenesislink/opengenesislinkserver/commits/main", stop);
|
|
latestResponse.EnsureSuccessStatusCode();
|
|
using var latestDocument = JsonDocument.Parse(await latestResponse.Content.ReadAsStringAsync(stop));
|
|
string latest = latestDocument.RootElement.GetProperty("sha").GetString() ?? "";
|
|
if (!string.Equals(latest, sha, StringComparison.OrdinalIgnoreCase))
|
|
throw new AdminOperations.OperationException(409, "Commit ist nicht mehr die aktuelle main-Version. Bitte neu prüfen.");
|
|
|
|
string stage = Path.Combine(_data, "updates");
|
|
string backups = Path.Combine(_data, "configuration-backups");
|
|
PrivateDirectory(stage);
|
|
PrivateDirectory(backups);
|
|
string filename = Path.Combine(stage, sha.ToLowerInvariant() + ".tar.gz");
|
|
if (File.Exists(filename))
|
|
return new { state = "staged", sha, path = "updates/" + Path.GetFileName(filename), note = "Quellcode bereits heruntergeladen. Keine Binärdateien verändert." };
|
|
|
|
string tmp = filename + ".partial";
|
|
try
|
|
{
|
|
using var response = await RequestSnapshot(sha, stop);
|
|
response.EnsureSuccessStatusCode();
|
|
if (response.Content.Headers.ContentLength > MaxSnapshot)
|
|
throw new IOException("Quellcode-Snapshot überschreitet das Downloadlimit.");
|
|
await using (var input = await response.Content.ReadAsStreamAsync(stop))
|
|
await using (var output = new FileStream(tmp, FileMode.CreateNew, FileAccess.Write,
|
|
FileShare.None, 128 * 1024, true))
|
|
{
|
|
byte[] buffer = new byte[128 * 1024];
|
|
long copied = 0;
|
|
int count;
|
|
while ((count = await input.ReadAsync(buffer, stop)) > 0)
|
|
{
|
|
copied += count;
|
|
if (copied > MaxSnapshot) throw new IOException("Quellcode-Snapshot zu groß");
|
|
await output.WriteAsync(buffer.AsMemory(0, count), stop);
|
|
}
|
|
}
|
|
PrivateFile(tmp);
|
|
// Config and secret backup is local only, restricted to the service account.
|
|
string stamp = DateTimeOffset.UtcNow.ToString("yyyyMMddTHHmmssfffZ");
|
|
string backup = Path.Combine(backups, stamp + "-" + sha[..12] + ".zip");
|
|
BackupConfigs(backup);
|
|
File.Move(tmp, filename);
|
|
PrivateFile(filename);
|
|
Prune(backups);
|
|
return new
|
|
{
|
|
state = "staged", sha, path = "updates/" + Path.GetFileName(filename),
|
|
backup = "configuration-backups/" + Path.GetFileName(backup),
|
|
note = "Quellcode heruntergeladen und Konfiguration gesichert. Noch KEIN Build, KEINE Installation und KEIN Neustart erfolgt."
|
|
};
|
|
}
|
|
finally { try { if (File.Exists(tmp)) File.Delete(tmp); } catch { } }
|
|
}
|
|
catch (AdminOperations.OperationException) { throw; }
|
|
catch (Exception e) { throw new AdminOperations.OperationException(502, "Update konnte nicht vorbereitet werden: " + e.Message); }
|
|
finally { _lock.Release(); }
|
|
}
|
|
|
|
private static void BackupConfigs(string backup)
|
|
{
|
|
string root = AppContext.BaseDirectory.TrimEnd(Path.DirectorySeparatorChar);
|
|
// Never allow a backup root provided by the browser.
|
|
string[] direct = ["OpenSim.ini", "OpenSimDefaults.ini", "nexverse.local.env"];
|
|
string[] dirs = ["Regions", "config-include"];
|
|
using var zip = new ZipArchive(File.Open(backup, FileMode.CreateNew), ZipArchiveMode.Create);
|
|
PrivateFile(backup);
|
|
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 (relative.EndsWith(".ini", StringComparison.OrdinalIgnoreCase) ||
|
|
relative.EndsWith(".xml", StringComparison.OrdinalIgnoreCase) ||
|
|
relative.EndsWith(".pem", StringComparison.OrdinalIgnoreCase) ||
|
|
relative.EndsWith(".env", StringComparison.OrdinalIgnoreCase) ||
|
|
relative.EndsWith(".p12", StringComparison.OrdinalIgnoreCase) ||
|
|
relative.EndsWith(".pfx", StringComparison.OrdinalIgnoreCase) ||
|
|
relative.EndsWith(".key", StringComparison.OrdinalIgnoreCase) ||
|
|
relative.EndsWith(".crt", StringComparison.OrdinalIgnoreCase) ||
|
|
relative.EndsWith(".json", 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);
|
|
}
|
|
}
|
|
}
|