| 1 | using System.Diagnostics; |
| 2 | using System.Globalization; |
| 3 | using System.Reflection; |
| 4 | using System.Security.Cryptography; |
| 5 | using System.Text.Json; |
| 6 | |
| 7 | namespace Cage.Windows; |
| 8 | |
| 9 | internal sealed class AppUpdater : IDisposable |
| 10 | { |
| 11 | public static string Version => typeof(AppUpdater).Assembly.GetCustomAttribute<AssemblyInformationalVersionAttribute>()?.InformationalVersion ?? "development"; |
| 12 | public static string Root => Path.Combine(Backend.Root, "updates"); |
| 13 | private readonly Action<Dictionary<string, object?>> changed; |
| 14 | private readonly Action quit, reconnect; |
| 15 | private readonly Dictionary<string, object?> state = new() { ["phase"] = "idle", ["currentVersion"] = Version, ["message"] = "" }; |
| 16 | private CancellationTokenSource? cancellation; |
| 17 | private InstallPlan? prepared; |
| 18 | private bool committed; |
| 19 | |
| 20 | public AppUpdater(Action<Dictionary<string, object?>> changed, Action quit, Action reconnect) |
| 21 | { |
| 22 | this.changed = changed; this.quit = quit; this.reconnect = reconnect; |
| 23 | try |
| 24 | { |
| 25 | var result = Path.Combine(Root, "last-result.json"); |
| 26 | if (File.Exists(result) && new FileInfo(result).Length <= 16384) |
| 27 | { |
| 28 | var value = JsonDocument.Parse(File.ReadAllText(result)).RootElement; |
| 29 | state["message"] = value.Text("message"); |
| 30 | if (value.TryGetProperty("success", out var success) && !success.GetBoolean()) { state["phase"] = "failed"; state["retryable"] = true; } |
| 31 | } |
| 32 | } |
| 33 | catch (Exception e) when (e is IOException or JsonException or UnauthorizedAccessException) { } |
| 34 | } |
| 35 | |
| 36 | public Dictionary<string, object?> Handle(string operation) |
| 37 | { |
| 38 | if (Backend.ClientOnly) |
| 39 | { |
| 40 | if (state["phase"] as string != "manual" || operation != "status") |
| 41 | Change("manual", "轻量客户端使用独立安装包更新;连接配置会保留,云端任务不受影响。"); |
| 42 | return new(state); |
| 43 | } |
| 44 | if (operation is "check" or "install" && |
| 45 | DateTimeOffset.TryParse(state.GetValueOrDefault("retryAt") as string, CultureInfo.InvariantCulture, DateTimeStyles.AssumeUniversal, out var retryAt) && retryAt > DateTimeOffset.UtcNow) |
| 46 | return new(state); |
| 47 | switch (operation) |
| 48 | { |
| 49 | case "status": break; |
| 50 | case "check": if (cancellation == null && prepared == null) _ = Run(true); break; |
| 51 | case "install": if (cancellation == null) _ = prepared != null ? Install() : Run(false); break; |
| 52 | case "cancel": if (!committed && state["phase"] as string != "installing") cancellation?.Cancel(); break; |
| 53 | default: throw new InvalidDataException("更新操作无效"); |
| 54 | } |
| 55 | return new(state); |
| 56 | } |
| 57 | |
| 58 | private void Change(string phase, string message, bool retryable = false, string retryAt = "") |
| 59 | { |
| 60 | state["phase"] = phase; state["message"] = message; state["retryable"] = retryable; state["retryAt"] = retryAt; changed(new(state)); |
| 61 | } |
| 62 | |
| 63 | public void MarkReady() |
| 64 | { |
| 65 | if (!Guid.TryParse(Environment.GetEnvironmentVariable("CAGE_UPDATE_CONFIRMATION"), out var token)) return; |
| 66 | Directory.CreateDirectory(Root); UpdatePolicy.PlainPath(Root); |
| 67 | File.WriteAllText(Path.Combine(Root, "launch-" + token + ".json"), JsonSerializer.Serialize(new { version = Version })); |
| 68 | Change("current", "Cage 已更新至 " + Version); |
| 69 | Environment.SetEnvironmentVariable("CAGE_UPDATE_CONFIRMATION", null); |
| 70 | } |
| 71 | |
| 72 | private async Task Run(bool checkOnly) |
| 73 | { |
| 74 | cancellation = new CancellationTokenSource(TimeSpan.FromMinutes(25)); |
| 75 | var token = cancellation.Token; |
| 76 | Change("checking", "正在通过所选代理检查更新"); |
| 77 | string? archive = null; |
| 78 | string retryAt = ""; |
| 79 | using var process = new Process { StartInfo = Backend.StartInfo(Backend.Executable, "app-update", checkOnly ? "check" : "download") }; |
| 80 | var started = false; |
| 81 | try |
| 82 | { |
| 83 | if (!process.Start()) throw new IOException("无法启动更新检查"); |
| 84 | started = true; |
| 85 | using var abort = token.Register(() => { try { if (!process.HasExited) process.Kill(); } catch (InvalidOperationException) { } }); |
| 86 | var errors = Backend.Drain(process.StandardError, token); |
| 87 | JsonElement last = default; |
| 88 | while (await process.StandardOutput.ReadLineAsync(token) is { } line) |
| 89 | { |
| 90 | if (line.Length > 65536) throw new IOException("更新响应超过允许大小"); |
| 91 | last = JsonDocument.Parse(line).RootElement.Clone(); |
| 92 | retryAt = last.Text("retryAt"); |
| 93 | foreach (var property in last.EnumerateObject()) |
| 94 | if (property.Name is not ("archivePath" or "sha256")) state[property.Name] = property.Value.ValueKind switch { |
| 95 | JsonValueKind.String => property.Value.GetString(), |
| 96 | JsonValueKind.True => true, JsonValueKind.False => false, |
| 97 | JsonValueKind.Number => property.Value.GetInt64(), |
| 98 | _ => property.Value.Clone(), |
| 99 | }; |
| 100 | changed(new(state)); |
| 101 | } |
| 102 | await process.WaitForExitAsync(token); await errors; |
| 103 | if (process.ExitCode != 0) throw new IOException(last.ValueKind == JsonValueKind.Object && last.Text("message") is { Length: > 0 } error ? error : "更新请求未完成"); |
| 104 | if (checkOnly || last.Text("phase") != "downloaded") return; |
| 105 | archive = UpdatePolicy.DownloadPath(last.Text("archivePath"), Root); |
| 106 | var version = last.Text("latestVersion"); var digest = last.Text("sha256"); |
| 107 | if (!UpdatePolicy.IsNewer(version, Version)) throw new IOException("安装包版本无效或不高于当前版本"); |
| 108 | Change("verifying", "正在验证 Windows 签名和安装包内容"); |
| 109 | var publisher = await Task.Run(() => Authenticode.Publisher(Environment.ProcessPath!), token); |
| 110 | await Task.Run(() => UpdateInstaller.VerifyArchive(archive, digest, version, publisher), token); |
| 111 | token.ThrowIfCancellationRequested(); |
| 112 | prepared = new InstallPlan(archive, digest, version, publisher, |
| 113 | AppContext.BaseDirectory.TrimEnd(Path.DirectorySeparatorChar), Environment.ProcessId, |
| 114 | Process.GetCurrentProcess().StartTime.ToUniversalTime().Ticks, Guid.NewGuid().ToString()); |
| 115 | archive = null; |
| 116 | Change("ready", "更新已下载并验证,可安装重启", true); |
| 117 | } |
| 118 | catch (OperationCanceledException) { Change("failed", "更新已暂停,可稍后重试", true); } |
| 119 | catch (Exception error) { Change("failed", error.Message, true, retryAt); } |
| 120 | finally |
| 121 | { |
| 122 | if (started && !process.HasExited) process.Kill(); |
| 123 | if (archive != null) { try { Directory.Delete(Path.GetDirectoryName(archive)!, true); } catch (IOException) { } } |
| 124 | cancellation.Dispose(); cancellation = null; |
| 125 | } |
| 126 | if (prepared != null) await Install(); |
| 127 | } |
| 128 | |
| 129 | private async Task Install() |
| 130 | { |
| 131 | if (prepared == null) return; |
| 132 | cancellation = new CancellationTokenSource(TimeSpan.FromMinutes(5)); |
| 133 | var token = cancellation.Token; |
| 134 | Process? helper = null; |
| 135 | var helperPath = Path.Combine(Root, "helper-" + Guid.NewGuid() + ".exe"); |
| 136 | Change("installing", "正在准备安装更新"); |
| 137 | try |
| 138 | { |
| 139 | |
| 140 | UpdatePolicy.PlainPath(prepared.Target); |
| 141 | Directory.CreateDirectory(Root); UpdatePolicy.PlainPath(Root); |
| 142 | File.Copy(Environment.ProcessPath!, helperPath); |
| 143 | await Task.Run(() => Authenticode.SamePublisher(helperPath, prepared.Publisher), token); |
| 144 | var start = Backend.StartInfo(helperPath, "--install-update"); start.RedirectStandardInput = true; |
| 145 | helper = new Process { StartInfo = start }; |
| 146 | if (!helper.Start()) throw new IOException("无法启动安全安装程序"); |
| 147 | await helper.StandardInput.WriteLineAsync(JsonSerializer.Serialize(prepared)); |
| 148 | await helper.StandardInput.FlushAsync(token); |
| 149 | var ready = await helper.StandardOutput.ReadLineAsync(token); |
| 150 | if (ready != "READY") throw new IOException("安装程序准备失败,原应用已保留"); |
| 151 | var (exit, data) = await Backend.Json(["prepare-update", "--json"], token); |
| 152 | if (data.Text("status") == "stop_required") |
| 153 | { |
| 154 | (exit, data) = await Backend.Json(["prepare-update", "--json", "--stop"], token); |
| 155 | } |
| 156 | if (exit != 0 || data.Text("status") != "prepared") throw new IOException(data.Text("message") is { Length: > 0 } detail ? detail : "环境未能安全停止"); |
| 157 | if (helper.HasExited) throw new IOException("安装程序已退出,原应用已保留"); |
| 158 | await helper.StandardInput.WriteLineAsync("COMMIT"); await helper.StandardInput.FlushAsync(token); |
| 159 | helper.StandardInput.Close(); committed = true; |
| 160 | Change("installing", "正在安装并重启 Cage"); quit(); |
| 161 | } |
| 162 | catch (Exception error) { Change("failed", error is OperationCanceledException ? "安装准备超时,原应用已保留" : error.Message, true); reconnect(); } |
| 163 | finally |
| 164 | { |
| 165 | if (!committed && helper != null) |
| 166 | { |
| 167 | helper.StandardInput.Close(); |
| 168 | try { await helper.WaitForExitAsync().WaitAsync(TimeSpan.FromSeconds(5)); } |
| 169 | catch (TimeoutException) { if (!helper.HasExited) helper.Kill(); } |
| 170 | } |
| 171 | helper?.Dispose(); |
| 172 | if (!committed) { try { File.Delete(helperPath); } catch (IOException) { } } |
| 173 | cancellation?.Dispose(); cancellation = null; |
| 174 | } |
| 175 | } |
| 176 | |
| 177 | public void Dispose() { if (!committed) cancellation?.Cancel(); } |
| 178 | } |
| 179 | |
| 180 | internal sealed record InstallPlan(string Archive, string Digest, string Version, string Publisher, |
| 181 | string Target, int ParentPid, long ParentStartTicks, string Confirmation); |