using System.ComponentModel; using System.Diagnostics; using System.Net.Sockets; using System.Text.Json; using Gateway.Api.Options; using Microsoft.Extensions.Options; namespace Gateway.Api.Services; public sealed record SystemUpdateRequest(string Password); public sealed record SystemUpdateStatus(string Phase, string Message, string? Commit = null, string? Target = null, DateTimeOffset? UpdatedAt = null, string? RunId = null, string? RunningCommit = null); public sealed record SystemUpdateAvailability(string State, string Branch, string? RemoteCommit = null); public sealed class SystemUpdateService(IOptions options) : IDisposable { private static readonly JsonSerializerOptions StatusJson = new(JsonSerializerDefaults.Web); private readonly SemaphoreSlim _availabilityLock = new(1, 1); private SystemUpdateAvailability? _availability; private DateTimeOffset _checkedAt; public bool Enabled => OperatingSystem.IsLinux() && !string.IsNullOrWhiteSpace(options.Value.UpdateSocketPath) && !string.IsNullOrWhiteSpace(options.Value.UpdateStatusPath); public string? RunningCommit => IsCommit(options.Value.RunningCommit) ? options.Value.RunningCommit!.ToLowerInvariant() : null; public SystemUpdateStatus GetStatus() { if (!Enabled) return new("disabled", "Der lokale Systemupdate-Dienst ist für dieses Gateway nicht eingerichtet."); try { var status = JsonSerializer.Deserialize(File.ReadAllText(options.Value.UpdateStatusPath!), StatusJson); if (status is not null) return status; } catch (FileNotFoundException) { return new("ready", "Bereit für ein Update aus Git."); } catch (DirectoryNotFoundException) { return new("ready", "Bereit für ein Update aus Git."); } catch (IOException) { } catch (UnauthorizedAccessException) { } catch (JsonException) { } return new("unavailable", "Der Update-Status konnte nicht gelesen werden."); } public async Task CheckAvailabilityAsync(bool refresh, CancellationToken cancellationToken) { var branch = options.Value.UpdateBranch; if (!Enabled || string.IsNullOrWhiteSpace(options.Value.UpdateAvailabilityCommand)) return new("disabled", branch); if (RunningCommit is not { } running) return new("unknown", branch); await _availabilityLock.WaitAsync(cancellationToken); try { if (!refresh && _availability is not null && DateTimeOffset.UtcNow - _checkedAt < TimeSpan.FromSeconds(15)) return _availability; _availability = await ProbeAsync(running, branch, cancellationToken); _checkedAt = DateTimeOffset.UtcNow; return _availability; } finally { _availabilityLock.Release(); } } private async Task ProbeAsync(string running, string branch, CancellationToken cancellationToken) { using var timeout = CancellationTokenSource.CreateLinkedTokenSource(cancellationToken); timeout.CancelAfter(TimeSpan.FromSeconds(32)); var start = new ProcessStartInfo(options.Value.UpdateAvailabilityCommand!) { UseShellExecute = false, RedirectStandardOutput = true }; start.ArgumentList.Add(running); try { using var process = Process.Start(start); if (process is null) return new("unavailable", branch); try { var output = await process.StandardOutput.ReadToEndAsync(timeout.Token); await process.WaitForExitAsync(timeout.Token); var parts = output.Trim().Split(' '); if (process.ExitCode == 0 && parts is ["current" or "available" or "incompatible", var tip] && IsCommit(tip)) return new(parts[0], branch, tip); } catch (OperationCanceledException) { try { if (!process.HasExited) process.Kill(entireProcessTree: true); } catch (InvalidOperationException) { } catch (Win32Exception) { } cancellationToken.ThrowIfCancellationRequested(); } } catch (Win32Exception) { } catch (IOException) { } return new("unavailable", branch); } private static bool IsCommit(string? value) => value is { Length: 40 } && value.All(Uri.IsHexDigit); public void Dispose() => _availabilityLock.Dispose(); public async Task StartAsync(CancellationToken cancellationToken) { if (!Enabled) return false; using var timeout = CancellationTokenSource.CreateLinkedTokenSource(cancellationToken); timeout.CancelAfter(TimeSpan.FromSeconds(5)); using var socket = new Socket(AddressFamily.Unix, SocketType.Stream, ProtocolType.Unspecified); try { await socket.ConnectAsync(new UnixDomainSocketEndPoint(options.Value.UpdateSocketPath!), timeout.Token); using var stream = new NetworkStream(socket); using var response = new StreamReader(stream); return string.Equals(await response.ReadLineAsync(timeout.Token), "accepted", StringComparison.Ordinal); } catch (OperationCanceledException) when (!cancellationToken.IsCancellationRequested) { return false; } catch (SocketException) { return false; } catch (IOException) { return false; } } }