Generation 1.1 .NET 10 ARM64 Server Runtime / ROBUST and Simulator .NET 10 ARM64 build + boot (push) Waiting to run
OpenGenesisLINK main - .NET 10 Build Gate / .NET 10 Windows x64 build (push) Waiting to run
NexVerse CI / Build NexVerse (push) Failing after 1m0s
NexVerse CI / NV dollar live database matrix (push) Failing after 16s
Generation 1 Stable and Updates source policy / release-policy (push) Successful in 17s
OpenGenesisLINK main - .NET 10 Build Gate / .NET 10 generated-project and server build (push) Successful in 1m36s
OpenGenesisLINK Generation 1 - Abgeschlossene Branches bereinigen / Abgeschlossene und nicht mehr benoetigte Branches entfernen (push) Successful in 27s
330 lines
17 KiB
C#
330 lines
17 KiB
C#
// SPDX-License-Identifier: MPL-2.0
|
|
using System.Globalization;
|
|
using System.Net;
|
|
using System.Net.Http.Headers;
|
|
using System.Reflection;
|
|
using System.Reflection.Metadata;
|
|
using System.Reflection.PortableExecutable;
|
|
using System.Text;
|
|
using System.Text.RegularExpressions;
|
|
using System.Xml;
|
|
using System.Xml.Linq;
|
|
|
|
namespace OpenGenesisLINK.Addons.OSWebInterface;
|
|
|
|
/// <summary>Fixed, server-side HTTPS backup destination. Never exposes NAS credentials to the browser.</summary>
|
|
internal sealed class WebDavBackupStore : IDisposable
|
|
{
|
|
internal const string CredentialPath = "/etc/opengenesislink/private/Ogl.WebDav.Private.dll";
|
|
private static readonly Uri Destination = new("https://s3.stadt-nexverse.de:5006/ogl-backup/");
|
|
private static readonly Regex OarName = new(@"^[a-zA-Z0-9_-]{1,60}--[0-9a-f]{32}--[0-9]{8}T[0-9]{6}Z--[0-9a-f]{32}\.oar\z", RegexOptions.CultureInvariant);
|
|
private static readonly Regex IarName = new(@"^avatar-[0-9a-f]{32}\.iar\z", RegexOptions.CultureInvariant);
|
|
private static readonly XNamespace Dav = "DAV:";
|
|
private static readonly SemaphoreSlim Transfers = new(2, 2);
|
|
private readonly HttpClient _client;
|
|
private readonly Uri _root;
|
|
private readonly Func<AuthenticationHeaderValue> _authentication;
|
|
internal sealed record Entry(string Kind, string Name, long Bytes, DateTimeOffset? Modified);
|
|
internal sealed class BackupException(int status, string message) : Exception(message)
|
|
{
|
|
public int Status { get; } = status;
|
|
}
|
|
|
|
public WebDavBackupStore() : this(new HttpClient(new SocketsHttpHandler
|
|
{
|
|
AllowAutoRedirect = false,
|
|
UseCookies = false,
|
|
ConnectTimeout = TimeSpan.FromSeconds(10),
|
|
PooledConnectionLifetime = TimeSpan.FromMinutes(5)
|
|
}) { Timeout = Timeout.InfiniteTimeSpan }, Destination, ReadCredentials) { }
|
|
|
|
// Injectable only for isolated protocol regression tests.
|
|
internal WebDavBackupStore(HttpClient client, Uri root, Func<AuthenticationHeaderValue> authentication)
|
|
{
|
|
if (root.Scheme != Uri.UriSchemeHttps || root.UserInfo.Length != 0 ||
|
|
root.Query.Length != 0 || root.Fragment.Length != 0 || !root.AbsolutePath.EndsWith('/'))
|
|
throw new ArgumentException("HTTPS backup root required");
|
|
_client = client;
|
|
_root = root;
|
|
_authentication = authentication;
|
|
}
|
|
|
|
private static AuthenticationHeaderValue ReadCredentials()
|
|
{
|
|
try
|
|
{
|
|
var info = new FileInfo(CredentialPath);
|
|
var directory = info.Directory!;
|
|
if (!OperatingSystem.IsLinux() || !info.Exists || info.LinkTarget != null ||
|
|
directory.LinkTarget != null || info.Length is < 512 or > 1024 * 1024 ||
|
|
!IsPrivate(File.GetUnixFileMode(CredentialPath)) ||
|
|
!IsPrivate(File.GetUnixFileMode(directory.FullName)))
|
|
throw new IOException("Private WebDAV DLL unavailable");
|
|
using var input = new FileStream(CredentialPath, FileMode.Open, FileAccess.Read,
|
|
FileShare.Read | FileShare.Delete);
|
|
return ReadPrivateAssembly(input);
|
|
}
|
|
catch (Exception e) when (e is IOException or UnauthorizedAccessException or
|
|
BadImageFormatException or InvalidOperationException or ArgumentException)
|
|
{
|
|
// Do not log exception details or any metadata values.
|
|
throw new BackupException(503, "Private WebDAV-DLL fehlt, ist ungültig oder nicht geschützt.");
|
|
}
|
|
}
|
|
|
|
private static bool IsPrivate(UnixFileMode mode) =>
|
|
(mode & (UnixFileMode.GroupRead | UnixFileMode.GroupWrite | UnixFileMode.GroupExecute |
|
|
UnixFileMode.OtherRead | UnixFileMode.OtherWrite | UnixFileMode.OtherExecute)) == 0;
|
|
|
|
// Read literal string constants from managed DLL metadata. The private
|
|
// assembly is never loaded/executed; replacing it is effective on the next
|
|
// request without leaking credentials into a public assembly or INI.
|
|
internal static AuthenticationHeaderValue ReadPrivateAssembly(Stream input)
|
|
{
|
|
using var pe = new PEReader(input, PEStreamOptions.LeaveOpen);
|
|
if (!pe.HasMetadata) throw new BadImageFormatException();
|
|
var md = pe.GetMetadataReader();
|
|
if (!md.IsAssembly ||
|
|
md.GetString(md.GetAssemblyDefinition().Name) != "Ogl.WebDav.Private")
|
|
throw new BadImageFormatException();
|
|
string? user = null, password = null;
|
|
bool found = false;
|
|
foreach (var handle in md.TypeDefinitions)
|
|
{
|
|
var type = md.GetTypeDefinition(handle);
|
|
if (md.GetString(type.Namespace) != "Ogl.Private" ||
|
|
md.GetString(type.Name) != "WebDavCredentials") continue;
|
|
if (found) throw new BadImageFormatException();
|
|
found = true;
|
|
foreach (var fieldHandle in type.GetFields())
|
|
{
|
|
var field = md.GetFieldDefinition(fieldHandle);
|
|
string name = md.GetString(field.Name);
|
|
if (name != "Username" && name != "Password") continue;
|
|
if ((field.Attributes & (FieldAttributes.Literal | FieldAttributes.Static)) !=
|
|
(FieldAttributes.Literal | FieldAttributes.Static) || field.GetDefaultValue().IsNil)
|
|
throw new BadImageFormatException();
|
|
var constant = md.GetConstant(field.GetDefaultValue());
|
|
if (constant.TypeCode != ConstantTypeCode.String)
|
|
throw new BadImageFormatException();
|
|
var blob = md.GetBlobReader(constant.Value);
|
|
if (blob.Length > 8192 || blob.Length % 2 != 0)
|
|
throw new BadImageFormatException();
|
|
string value = blob.ReadUTF16(blob.Length);
|
|
if (name == "Username")
|
|
{
|
|
if (user != null) throw new BadImageFormatException();
|
|
user = value;
|
|
}
|
|
else
|
|
{
|
|
if (password != null) throw new BadImageFormatException();
|
|
password = value;
|
|
}
|
|
}
|
|
}
|
|
if (string.IsNullOrWhiteSpace(user) || user.Contains(':') ||
|
|
string.IsNullOrEmpty(password) || user.Any(char.IsControl) ||
|
|
password.Any(char.IsControl))
|
|
throw new BadImageFormatException();
|
|
return new AuthenticationHeaderValue("Basic",
|
|
Convert.ToBase64String(Encoding.UTF8.GetBytes(user + ":" + password)));
|
|
}
|
|
|
|
internal void EnsureConfigured() => _ = _authentication();
|
|
private static string Folder(string kind) => kind switch
|
|
{
|
|
"oar" => "OAR/",
|
|
"iar" => "IAR/",
|
|
_ => throw new BackupException(400, "Ungültiger Archivtyp.")
|
|
};
|
|
internal static bool ValidName(string kind, string name) =>
|
|
kind == "oar" ? OarName.IsMatch(name) : kind == "iar" && IarName.IsMatch(name);
|
|
internal static string RegionName(string region, Guid regionId, Guid jobId, DateTimeOffset time)
|
|
{
|
|
string safe = Regex.Replace(region, @"[^a-zA-Z0-9_-]+", "_").Trim('_');
|
|
if (safe.Length == 0) safe = "region";
|
|
if (safe.Length > 60) safe = safe[..60];
|
|
return $"{safe}--{regionId:N}--{time.UtcDateTime.ToString("yyyyMMdd'T'HHmmss'Z'", CultureInfo.InvariantCulture)}--{jobId:N}.oar";
|
|
}
|
|
internal static string AvatarName(Guid avatarId) => $"avatar-{avatarId:N}.iar";
|
|
private Uri DirectoryUri(string kind) => new(_root, Folder(kind));
|
|
private Uri FileUri(string kind, string name)
|
|
{
|
|
if (!ValidName(kind, name)) throw new BackupException(400, "Ungültiger Archivname.");
|
|
return new Uri(DirectoryUri(kind), name);
|
|
}
|
|
|
|
private async Task<HttpResponseMessage> SendAsync(HttpMethod method, Uri uri,
|
|
CancellationToken stop, HttpContent? content = null, Action<HttpRequestMessage>? configure = null)
|
|
{
|
|
using var request = new HttpRequestMessage(method, uri);
|
|
request.Headers.Authorization = _authentication();
|
|
request.Content = content;
|
|
configure?.Invoke(request);
|
|
try { return await _client.SendAsync(request, HttpCompletionOption.ResponseHeadersRead, stop); }
|
|
catch (HttpRequestException)
|
|
{ throw new BackupException(502, "WebDAV-Verbindung fehlgeschlagen (Netzwerk oder TLS)."); }
|
|
}
|
|
|
|
private static void Require(HttpResponseMessage response, params HttpStatusCode[] accepted)
|
|
{
|
|
if (!accepted.Contains(response.StatusCode))
|
|
throw new BackupException(response.StatusCode == HttpStatusCode.NotFound ? 404 : 502,
|
|
$"WebDAV-Auftrag abgelehnt (HTTP {(int)response.StatusCode}).");
|
|
}
|
|
|
|
private static CancellationTokenSource Deadline(CancellationToken stop, TimeSpan duration)
|
|
{
|
|
var cts = CancellationTokenSource.CreateLinkedTokenSource(stop);
|
|
cts.CancelAfter(duration);
|
|
return cts;
|
|
}
|
|
|
|
private async Task EnsureFolderAsync(string kind, CancellationToken stop)
|
|
{
|
|
using var response = await SendAsync(new HttpMethod("MKCOL"), DirectoryUri(kind), stop);
|
|
Require(response, HttpStatusCode.Created, HttpStatusCode.MethodNotAllowed);
|
|
}
|
|
|
|
private async Task<long> SizeAsync(Uri uri, CancellationToken stop)
|
|
{
|
|
using var response = await SendAsync(HttpMethod.Head, uri, stop);
|
|
Require(response, HttpStatusCode.OK);
|
|
return response.Content.Headers.ContentLength ?? -1;
|
|
}
|
|
|
|
// Upload to a unique temporary object first. Only a complete, size-checked
|
|
// object is moved into the final name. Existing IARs are never deleted first.
|
|
internal async Task SaveAsync(string kind, string name, string localFile, CancellationToken stop = default)
|
|
{
|
|
Uri final = FileUri(kind, name);
|
|
EnsureConfigured();
|
|
using var deadline = Deadline(stop, TimeSpan.FromHours(4));
|
|
CancellationToken ct = deadline.Token;
|
|
await Transfers.WaitAsync(ct);
|
|
Uri temp = new(DirectoryUri(kind), "upload-" + Guid.NewGuid().ToString("N") + ".part");
|
|
bool staged = false;
|
|
try
|
|
{
|
|
await EnsureFolderAsync(kind, ct);
|
|
using (var file = new FileStream(localFile, FileMode.Open, FileAccess.Read, FileShare.Read, 128 * 1024, true))
|
|
{
|
|
if (file.Length <= 0) throw new BackupException(500, "Archiv ist leer.");
|
|
long size = file.Length;
|
|
using var content = new StreamContent(file);
|
|
content.Headers.ContentType = new MediaTypeHeaderValue("application/octet-stream");
|
|
content.Headers.ContentLength = size;
|
|
// The randomly generated staging URI belongs to this job alone.
|
|
staged = true;
|
|
using (var put = await SendAsync(HttpMethod.Put, temp, ct, content,
|
|
request => request.Headers.TryAddWithoutValidation("If-None-Match", "*")))
|
|
Require(put, HttpStatusCode.Created, HttpStatusCode.NoContent, HttpStatusCode.OK);
|
|
if (await SizeAsync(temp, ct) != size)
|
|
throw new BackupException(502, "WebDAV-Dateigröße stimmt nach Upload nicht überein.");
|
|
using (var move = await SendAsync(new HttpMethod("MOVE"), temp, ct, configure: request =>
|
|
{
|
|
request.Headers.TryAddWithoutValidation("Destination", final.AbsoluteUri);
|
|
request.Headers.TryAddWithoutValidation("Overwrite", kind == "iar" ? "T" : "F");
|
|
}))
|
|
Require(move, HttpStatusCode.Created, HttpStatusCode.NoContent);
|
|
staged = false;
|
|
if (await SizeAsync(final, ct) != size)
|
|
throw new BackupException(502, "WebDAV-Ziel konnte nach Veröffentlichung nicht bestätigt werden.");
|
|
}
|
|
}
|
|
finally
|
|
{
|
|
if (staged)
|
|
{
|
|
try
|
|
{
|
|
using var cleanup = new CancellationTokenSource(TimeSpan.FromSeconds(10));
|
|
using var ignored = await SendAsync(HttpMethod.Delete, temp, cleanup.Token);
|
|
}
|
|
catch { /* Orphan .part remains invisible to listing and download. */ }
|
|
}
|
|
Transfers.Release();
|
|
}
|
|
}
|
|
|
|
internal async Task<Entry[]> ListAsync(CancellationToken stop)
|
|
{
|
|
using var deadline = Deadline(stop, TimeSpan.FromSeconds(45));
|
|
using (var probe = await SendAsync(new HttpMethod("PROPFIND"), _root, deadline.Token,
|
|
configure: request => request.Headers.TryAddWithoutValidation("Depth", "0")))
|
|
Require(probe, (HttpStatusCode)207);
|
|
var entries = new List<Entry>();
|
|
foreach (string kind in new[] { "oar", "iar" })
|
|
{
|
|
Uri directory = DirectoryUri(kind);
|
|
using var body = new StringContent(
|
|
"<?xml version=\"1.0\"?><d:propfind xmlns:d=\"DAV:\"><d:prop><d:getcontentlength/><d:getlastmodified/><d:resourcetype/></d:prop></d:propfind>",
|
|
Encoding.UTF8, "application/xml");
|
|
using var response = await SendAsync(new HttpMethod("PROPFIND"), directory, deadline.Token, body,
|
|
request => request.Headers.TryAddWithoutValidation("Depth", "1"));
|
|
if (response.StatusCode == HttpStatusCode.NotFound) continue;
|
|
Require(response, (HttpStatusCode)207);
|
|
using var stream = await response.Content.ReadAsStreamAsync(deadline.Token);
|
|
using var reader = XmlReader.Create(stream, new XmlReaderSettings
|
|
{
|
|
Async = true, DtdProcessing = DtdProcessing.Prohibit, XmlResolver = null,
|
|
MaxCharactersInDocument = 8 * 1024 * 1024
|
|
});
|
|
var xml = await XDocument.LoadAsync(reader, LoadOptions.None, deadline.Token);
|
|
foreach (var item in xml.Descendants(Dav + "response"))
|
|
{
|
|
string? href = item.Element(Dav + "href")?.Value;
|
|
if (href == null || !Uri.TryCreate(directory, href, out var itemUri) ||
|
|
itemUri.GetLeftPart(UriPartial.Authority) != directory.GetLeftPart(UriPartial.Authority) ||
|
|
!itemUri.AbsolutePath.StartsWith(directory.AbsolutePath, StringComparison.Ordinal)) continue;
|
|
string name = Uri.UnescapeDataString(itemUri.AbsolutePath[directory.AbsolutePath.Length..]);
|
|
if (!ValidName(kind, name)) continue;
|
|
var props = item.Elements(Dav + "propstat").FirstOrDefault(v =>
|
|
v.Element(Dav + "status")?.Value.Contains(" 200 ", StringComparison.Ordinal) == true)?.Element(Dav + "prop");
|
|
if (props == null || props.Element(Dav + "resourcetype")?.Element(Dav + "collection") != null ||
|
|
!long.TryParse(props.Element(Dav + "getcontentlength")?.Value, out long size) || size <= 0) continue;
|
|
DateTimeOffset? modified = DateTimeOffset.TryParse(props.Element(Dav + "getlastmodified")?.Value,
|
|
CultureInfo.InvariantCulture, DateTimeStyles.AssumeUniversal, out var time) ? time : null;
|
|
entries.Add(new Entry(kind, name, size, modified));
|
|
}
|
|
}
|
|
return entries.DistinctBy(x => (x.Kind, x.Name)).OrderByDescending(x => x.Modified).ToArray();
|
|
}
|
|
|
|
internal async Task DownloadAsync(string kind, string name, HttpListenerRequest request,
|
|
HttpListenerResponse response, CancellationToken stop)
|
|
{
|
|
Uri uri = FileUri(kind, name);
|
|
using var deadline = Deadline(stop, TimeSpan.FromHours(4));
|
|
RangeHeaderValue? range = null;
|
|
if (request.Headers["Range"] is string value &&
|
|
(!RangeHeaderValue.TryParse(value, out range) || range.Ranges.Count != 1 || range.Unit != "bytes"))
|
|
throw new BackupException(416, "Ungültiger Downloadbereich.");
|
|
using var upstream = await SendAsync(HttpMethod.Get, uri, deadline.Token,
|
|
configure: r => r.Headers.Range = range);
|
|
Require(upstream, HttpStatusCode.OK, HttpStatusCode.PartialContent, HttpStatusCode.RequestedRangeNotSatisfiable);
|
|
response.StatusCode = (int)upstream.StatusCode;
|
|
response.ContentType = "application/octet-stream";
|
|
response.Headers["Cache-Control"] = "no-store";
|
|
response.Headers["Content-Disposition"] = $"attachment; filename=\"{name}\"";
|
|
response.Headers["Accept-Ranges"] = "bytes";
|
|
if (upstream.Content.Headers.ContentRange is { } contentRange)
|
|
response.Headers["Content-Range"] = contentRange.ToString();
|
|
if (upstream.Content.Headers.ContentLength is long length) response.ContentLength64 = length;
|
|
else response.SendChunked = true;
|
|
try
|
|
{
|
|
using var stream = await upstream.Content.ReadAsStreamAsync(deadline.Token);
|
|
await stream.CopyToAsync(response.OutputStream, 128 * 1024, deadline.Token);
|
|
}
|
|
catch (Exception e) when (e is IOException or HttpRequestException or HttpListenerException or OperationCanceledException)
|
|
{
|
|
// Do not append a JSON error to a partially streamed archive.
|
|
response.Abort();
|
|
}
|
|
}
|
|
|
|
public void Dispose() => _client.Dispose();
|
|
}
|