// SPDX-License-Identifier: MPL-2.0 using System.Collections.Concurrent; using System.Diagnostics; using System.Net; using System.Net.Http.Headers; using System.Net.NetworkInformation; using System.Net.Sockets; using System.Text; using System.Text.Json; using log4net; using OpenMetaverse; using OpenSim.Region.Framework.Interfaces; using OpenSim.Region.Framework.Scenes; namespace OpenGenesisLINK.Addons.OSWebInterface; /// Privileged operations, scoped to scenes hosted by this ONE simulator. internal sealed class AdminOperations : IDisposable { public const long MaxUploadBytes = 2L * 1024 * 1024 * 1024; internal sealed class OperationException(int code, string message) : Exception(message) { public int Status { get; } = code; } private sealed class Job { public string Id = ""; public string Region = ""; public string Kind = ""; public string State = "queued"; public string Message = ""; public DateTimeOffset Created = DateTimeOffset.UtcNow; public long Bytes; public long Total; public string File = ""; public DateTimeOffset? Finished; public bool FileObserved; public List<(DateTimeOffset Time, string Text)> Events = new(); } private readonly ConcurrentDictionary _scenes; private readonly ConcurrentDictionary _jobs = new(); private readonly ConcurrentDictionary _busy = new(); private readonly string _archiveDir; private readonly string _storage; private readonly int _retention; private readonly List<(string Name, Uri Uri)> _services; private readonly UpdateStager _updateStager; private static readonly ILog Log = LogManager.GetLogger(typeof(AdminOperations)); public AdminOperations(ConcurrentDictionary scenes, string storage, int retention, List<(string Name, Uri Uri)> services) { _scenes = scenes; _storage = storage; _retention = retention; _services = services; _updateStager = new UpdateStager(storage, retention); _archiveDir = Path.Combine(storage, "archives"); Directory.CreateDirectory(_archiveDir); } private Scene Region(string id) { if (!UUID.TryParse(id, out UUID uid) || !_scenes.TryGetValue(uid, out Scene? s)) throw new OperationException(404, "Region nicht gefunden"); return s; } private (Scene Scene, IRegionArchiverModule Archiver) GetArchiver(string id) { Scene scene = Region(id); var archive = scene.RequestModuleInterface(); if (archive is null) throw new OperationException(503, "OAR-Modul in dieser Region nicht verfügbar"); return (scene, archive); } private Job Begin(string id, string kind) { Scene scene = Region(id); string jobId = Guid.NewGuid().ToString("N"); var job = new Job { Id = jobId, Region = scene.RegionInfo.RegionName, Kind = kind }; if (!_busy.TryAdd(scene.RegionInfo.RegionID, jobId)) throw new OperationException(409, "Diese Region führt bereits einen Archivauftrag aus"); _jobs[jobId] = job; Record(job, "Archivauftrag angelegt"); return job; } private static void Record(Job job, string message) { lock (job) { job.Events.Add((DateTimeOffset.UtcNow, message)); if (job.Events.Count > 12) job.Events.RemoveAt(0); } } private void Complete(UUID regionId, Job job, string? error) { lock (job) { if (job.State is "completed" or "failed") return; if (string.IsNullOrWhiteSpace(error) && job.Kind == "export") { try { if (!File.Exists(job.File)) error = "OAR-Datei wurde nicht erstellt."; else { job.Bytes = new FileInfo(job.File).Length; if (job.Bytes == 0) error = "OAR-Datei ist leer."; } } catch (IOException e) { error = "OAR-Datei konnte nicht geprüft werden: " + e.Message; } } job.Message = error ?? ""; job.State = string.IsNullOrWhiteSpace(error) ? "completed" : "failed"; job.Finished = DateTimeOffset.UtcNow; job.Events.Add((job.Finished.Value, job.State == "completed" ? (job.Kind == "export" ? "OAR-Datei vollständig erstellt" : "Import abgeschlossen") : "Archivauftrag fehlgeschlagen: " + job.Message)); } _busy.TryRemove(new KeyValuePair(regionId, job.Id)); } // Status is derived from the actual archive file and the archiver // completion event. A percent value cannot be determined by this API. private object Snapshot(Job job) { lock (job) { if (job.Kind == "export" && job.State == "saving") { try { if (File.Exists(job.File)) { long bytes = new FileInfo(job.File).Length; if (bytes > job.Bytes) job.Bytes = bytes; if (bytes > 0 && !job.FileObserved) { job.FileObserved = true; job.Events.Add((DateTimeOffset.UtcNow, "OAR-Datei wird geschrieben")); } } } catch (IOException) { /* Transient write; next poll retries. */ } } string stage = job.State switch { "queued" => "Auftrag angenommen", "saving" => job.Bytes > 0 ? "Archivdaten werden geschrieben" : "Region wird für das OAR gesichert", "uploading" => "OAR-Datei wird hochgeladen", "importing" => "OAR-Datei wird importiert", "completed" => "OAR-Auftrag abgeschlossen", "failed" => "OAR-Auftrag fehlgeschlagen", _ => "Archivauftrag wird bearbeitet" }; var now = DateTimeOffset.UtcNow; return new { id=job.Id,region=job.Region,kind=job.Kind,state=job.State, stage,message=job.Message,created=job.Created, finishedAtUtc=job.Finished, elapsedSeconds=Math.Max(0,(long)((job.Finished??now)-job.Created).TotalSeconds), bytes=job.Bytes,bytesWritten=job.Bytes,total=job.Total, percent=job.Kind=="import" && job.Total>0 ? (int?)Math.Min(100,100*job.Bytes/job.Total) : null, download=job.Kind=="export" && job.State=="completed", events=job.Events.Select(e=>new{timeUtc=e.Time,message=e.Text}).ToArray() }; } } public object? OarStatus(string id) { if (!Guid.TryParseExact(id, "N", out _) || !_jobs.TryGetValue(id, out Job? job) || job.Kind != "export") return null; return Snapshot(job); } public object[] RegionSummary() { return _scenes.Values.OrderBy(s => s.RegionInfo.RegionName).Select(s => { var r = s.RegionInfo; return (object)new { id = r.RegionID.ToString(), name = r.RegionName, location = $"{r.RegionLocX}, {r.RegionLocY}", size = $"{r.RegionSizeX} × {r.RegionSizeY}", udpPort = r.InternalEndPoint?.Port, httpPort = r.HttpPort, serverUri = r.ServerURI, ready = s.Ready, agents = s.GetRootAgentCount(), scriptsEnabled = s.ScriptsEnabled, physicsEnabled = s.PhysicsEnabled }; }).ToArray(); } public object[] PortSummary() { IPEndPoint[] udp; IPEndPoint[] tcp; try { udp = IPGlobalProperties.GetIPGlobalProperties().GetActiveUdpListeners(); tcp = IPGlobalProperties.GetIPGlobalProperties().GetActiveTcpListeners(); } catch { udp = []; tcp = []; } var rows = new List(); foreach (Scene s in _scenes.Values.OrderBy(v => v.RegionInfo.RegionName)) { var r = s.RegionInfo; int udpPort = r.InternalEndPoint?.Port ?? 0; rows.Add(new { name = r.RegionName, protocol = "UDP", port = udpPort, local = udpPort > 0 && udp.Any(x => x.Port == udpPort), publicStatus = "UDP: kein externer Protokoll-Handshake geprüft", hint = "Ein TCP-Verbindungstest bestätigt keine UDP-Erreichbarkeit." }); int httpPort = (int)r.HttpPort; rows.Add(new { name = r.RegionName, protocol = "TCP", port = httpPort, local = httpPort > 0 && tcp.Any(x => x.Port == httpPort), publicStatus = "Externe TCP-Prüfung wird geladen", hint = "Messung erfolgt von einem unabhängigen Standort." }); } return rows.ToArray(); } public async Task ServiceSummaryAsync(CancellationToken stop) { var checks = _services.Select(async item => { bool reachable = false; using var timeout = CancellationTokenSource.CreateLinkedTokenSource(stop); timeout.CancelAfter(TimeSpan.FromSeconds(2)); try { using var client = new TcpClient(); await client.ConnectAsync(item.Uri.Host, item.Uri.Port, timeout.Token); reachable = client.Connected; } catch (Exception) { } return (object)new { name = item.Name, host = item.Uri.Host, port = item.Uri.Port, protocol = item.Uri.Scheme.ToUpperInvariant() + "/TCP", reachable, detail = reachable ? "TCP-Verbindung erfolgreich – Dienstfunktion nicht geprüft" : "TCP nicht erreichbar: Dienst, DNS, Routing oder Firewall prüfen" }; }); return await Task.WhenAll(checks); } public bool Restart(string id) { Scene s; try { s = Region(id); } catch (OperationException) { return false; } _ = Task.Run(async () => { await Task.Delay(500); try { s.RestartNow(); } catch (Exception e) { Log.Error("[OS WEBINTERFACE] Region restart failed", e); } }); Log.Warn("[OS WEBINTERFACE] Region restart requested: " + s.RegionInfo.RegionName); return true; } public string LogTail() { string path = Path.Combine(AppContext.BaseDirectory, "OpenSim.log"); if (!File.Exists(path)) { string logs = Path.Combine(AppContext.BaseDirectory, "logs"); if (Directory.Exists(logs)) path = Directory.GetFiles(logs, "*.log") .OrderByDescending(File.GetLastWriteTimeUtc).FirstOrDefault() ?? ""; } if (string.IsNullOrEmpty(path) || !File.Exists(path)) return "Keine OpenSim.log gefunden."; try { using var f = File.Open(path, FileMode.Open, FileAccess.Read, FileShare.ReadWrite | FileShare.Delete); long size = Math.Min(f.Length, 100 * 1024); f.Seek(-size, SeekOrigin.End); using var reader = new StreamReader(f, Encoding.UTF8, true, 1024); string text = reader.ReadToEnd(); return text.Length > 90_000 ? text[^90_000..] : text; } catch (IOException) { return "Logdatei vorübergehend nicht lesbar."; } } public object[] Jobs() => _jobs.Values.OrderByDescending(x => x.Created).Take(30) .Select(Snapshot).ToArray(); public object Export(string regionId) { var (scene, archive) = GetArchiver(regionId); Job job = Begin(regionId, "export"); job.File = Path.Combine(_archiveDir, job.Id + ".oar"); Guid requestId = Guid.ParseExact(job.Id, "N"); EventManager.OarFileSaved? complete = null; complete = (id, message) => { if (id != requestId) return; scene.EventManager.OnOarFileSaved -= complete; Complete(scene.RegionInfo.RegionID, job, message); }; scene.EventManager.OnOarFileSaved += complete; // Return the identifier immediately: writing the archive can take // minutes, and the UI must be able to poll while it is running. _ = Task.Run(() => { try { lock (job) job.State = "saving"; Record(job, "Archivierung für " + job.Region + " gestartet"); archive.ArchiveRegion(job.File, requestId, new Dictionary()); } catch (Exception e) { scene.EventManager.OnOarFileSaved -= complete; Log.Error("[OS WEBINTERFACE] OAR export failed for " + job.Region, e); Complete(scene.RegionInfo.RegionID, job, e.Message); } }); return new { id = job.Id, state = "queued" }; } public async Task ImportAsync(string regionId, Stream source, long contentLength, CancellationToken stop) { var (scene, archive) = GetArchiver(regionId); Job job = Begin(regionId, "import"); job.File = Path.Combine(_archiveDir, job.Id + ".upload"); job.Total = contentLength; try { job.State = "uploading"; using (var dst = new FileStream(job.File, FileMode.CreateNew, FileAccess.Write, FileShare.None, 64 * 1024, true)) { byte[] buffer = new byte[64 * 1024]; int read; while ((read = await source.ReadAsync(buffer, stop)) != 0) { job.Bytes += read; if (job.Bytes > contentLength || job.Bytes > MaxUploadBytes) throw new OperationException(413, "OAR Upload zu groß"); await dst.WriteAsync(buffer.AsMemory(0, read), stop); } } if (job.Bytes != contentLength) throw new OperationException(400, "Unvollständiger OAR-Upload"); EventManager.OarFileLoaded? complete = null; complete = (requestId, loadedScenes, message) => { if (requestId != Guid.ParseExact(job.Id, "N")) return; scene.EventManager.OnOarFileLoaded -= complete; Complete(scene.RegionInfo.RegionID, job, message); try { File.Delete(job.File); } catch { } }; scene.EventManager.OnOarFileLoaded += complete; try { job.State = "importing"; archive.DearchiveRegion(job.File, Guid.ParseExact(job.Id, "N"), new Dictionary()); } catch { scene.EventManager.OnOarFileLoaded -= complete; throw; } } catch (Exception e) { Complete(scene.RegionInfo.RegionID, job, e.Message); try { File.Delete(job.File); } catch { } if (e is OperationException) throw; throw new OperationException(500, "OAR-Import fehlgeschlagen: " + e.Message); } Log.Warn("[OS WEBINTERFACE] OAR import initiated for " + scene.RegionInfo.RegionName); return new { id = job.Id, state = job.State }; } public string? ExportFile(string id) { if (!Guid.TryParseExact(id, "N", out _) || !_jobs.TryGetValue(id, out Job? j) || j.Kind != "export" || j.State != "completed") return null; string expected = Path.Combine(_archiveDir, id + ".oar"); lock (j) return j.File == expected && File.Exists(expected) ? expected : null; } public Task CheckUpdatesAsync(CancellationToken stop) => _updateStager.CheckAsync(stop); public Task StageUpdateAsync(string sha, CancellationToken stop) => _updateStager.StageAsync(sha, stop); public void Dispose() { } }