| 1 | using System.Diagnostics; |
| 2 | using System.Security.Cryptography; |
| 3 | using System.Text.Json; |
| 4 | |
| 5 | namespace Cage.Windows; |
| 6 | |
| 7 | internal static class UpdateInstaller |
| 8 | { |
| 9 | [System.Runtime.InteropServices.DllImport("user32.dll", CharSet = System.Runtime.InteropServices.CharSet.Unicode)] |
| 10 | private static extern int MessageBoxW(IntPtr owner, string text, string title, uint flags); |
| 11 | public static void VerifyArchive(string path, string hash, string version, string publisher) |
| 12 | { |
| 13 | UpdatePolicy.DownloadPath(path, AppUpdater.Root); UpdatePolicy.PlainPath(path); |
| 14 | if (new FileInfo(path).Length is <= 0 or > (512L << 20)) throw new IOException("安装包大小无效"); |
| 15 | using var stream = new FileStream(path, FileMode.Open, FileAccess.Read, FileShare.Read); |
| 16 | var actual = Convert.ToHexString(SHA256.HashData(stream)); |
| 17 | if (hash.Length != 64 || !string.Equals(actual, hash, StringComparison.OrdinalIgnoreCase)) |
| 18 | throw new IOException("安装包下载后发生变化,请重新下载"); |
| 19 | Authenticode.SamePublisher(path, publisher); |
| 20 | var metadata = FileVersionInfo.GetVersionInfo(path); |
| 21 | if (metadata.ProductName != "Cage" || metadata.ProductVersion != version) |
| 22 | throw new IOException("安装包产品身份或版本不匹配"); |
| 23 | } |
| 24 | |
| 25 | public static async Task<int> Run() |
| 26 | { |
| 27 | InstallPlan? plan = null; |
| 28 | string? backup = null; |
| 29 | var replaced = false; |
| 30 | var committed = false; |
| 31 | var succeeded = false; |
| 32 | Process? launched = null; |
| 33 | try |
| 34 | { |
| 35 | using var inputTimeout = new CancellationTokenSource(TimeSpan.FromMinutes(5)); |
| 36 | var line = await Console.In.ReadLineAsync(inputTimeout.Token); |
| 37 | if (line == null || line.Length > 16384) return 1; |
| 38 | plan = JsonSerializer.Deserialize<InstallPlan>(line) ?? throw new IOException("安装计划无效"); |
| 39 | if (!Guid.TryParse(plan.Confirmation, out _) || !Path.IsPathFullyQualified(plan.Target) || plan.Target.Contains('"') || |
| 40 | plan.Target.TrimEnd(Path.DirectorySeparatorChar) != plan.Target || |
| 41 | string.Equals(Path.GetPathRoot(plan.Target), plan.Target, StringComparison.OrdinalIgnoreCase)) |
| 42 | throw new IOException("安装目标无效"); |
| 43 | UpdatePolicy.PlainPath(plan.Target); UpdatePolicy.PlainPath(AppUpdater.Root); |
| 44 | if (File.ReadAllText(Path.Combine(plan.Target, "Cage.install-id")).Trim() != "io.github.lee-xeo.claude-cage") |
| 45 | throw new IOException("请先使用 Cage 安装程序安装应用,再自动更新"); |
| 46 | var original = Path.Combine(plan.Target, "Cage.exe"); |
| 47 | var ownPublisher = Authenticode.Publisher(Environment.ProcessPath!); |
| 48 | if (plan.Publisher != ownPublisher) throw new IOException("安装计划发布者不匹配"); |
| 49 | Authenticode.SamePublisher(original, ownPublisher); |
| 50 | if (!UpdatePolicy.IsNewer(plan.Version, FileVersionInfo.GetVersionInfo(original).ProductVersion ?? "")) |
| 51 | throw new IOException("更新版本必须高于当前安装版本"); |
| 52 | VerifyArchive(plan.Archive, plan.Digest, plan.Version, ownPublisher); |
| 53 | |
| 54 | |
| 55 | await using var archiveLock = new FileStream(plan.Archive, FileMode.Open, FileAccess.Read, FileShare.Read); |
| 56 | VerifyArchive(plan.Archive, plan.Digest, plan.Version, ownPublisher); |
| 57 | using var parent = Process.GetProcessById(plan.ParentPid); |
| 58 | if (parent.StartTime.ToUniversalTime().Ticks != plan.ParentStartTicks || |
| 59 | !string.Equals(parent.MainModule?.FileName, original, StringComparison.OrdinalIgnoreCase)) |
| 60 | throw new IOException("更新请求进程身份不匹配"); |
| 61 | backup = Path.Combine(AppUpdater.Root, "previous-" + plan.Confirmation); |
| 62 | if (Directory.Exists(backup)) throw new IOException("更新备份目录已存在"); |
| 63 | |
| 64 | CopyTree(plan.Target, backup); |
| 65 | Authenticode.SamePublisher(UpdateRecovery.BackendPath(backup), ownPublisher); |
| 66 | Console.WriteLine("READY"); await Console.Out.FlushAsync(); |
| 67 | if (await Console.In.ReadLineAsync(inputTimeout.Token) != "COMMIT") return 1; |
| 68 | committed = true; |
| 69 | await parent.WaitForExitAsync().WaitAsync(TimeSpan.FromSeconds(45)); |
| 70 | VerifyArchive(plan.Archive, plan.Digest, plan.Version, ownPublisher); |
| 71 | |
| 72 | |
| 73 | using (var installer = Process.Start(new ProcessStartInfo(plan.Archive) { |
| 74 | UseShellExecute = false, CreateNoWindow = true, |
| 75 | Arguments = "/S /UPDATE /D=" + plan.Target, |
| 76 | WorkingDirectory = Path.GetDirectoryName(plan.Archive), |
| 77 | }) ?? throw new IOException("无法启动 Windows 安装器")) |
| 78 | { |
| 79 | replaced = true; |
| 80 | try { await installer.WaitForExitAsync().WaitAsync(TimeSpan.FromMinutes(10)); } |
| 81 | catch (TimeoutException) { if (!installer.HasExited) installer.Kill(true); await installer.WaitForExitAsync(); throw; } |
| 82 | if (installer.ExitCode != 0) throw new IOException("Windows 安装程序未完成安装"); |
| 83 | } |
| 84 | EnsureInstallationComplete(plan.Target); |
| 85 | Authenticode.SamePublisher(original, ownPublisher); |
| 86 | if (FileVersionInfo.GetVersionInfo(original).ProductVersion != plan.Version) |
| 87 | throw new IOException("安装后版本不匹配"); |
| 88 | var marker = Path.Combine(AppUpdater.Root, "launch-" + plan.Confirmation + ".json"); |
| 89 | if (File.Exists(marker)) File.Delete(marker); |
| 90 | var launch = new ProcessStartInfo(original) { UseShellExecute = false, WorkingDirectory = plan.Target }; |
| 91 | launch.Environment["CAGE_UPDATE_CONFIRMATION"] = plan.Confirmation; |
| 92 | launched = Process.Start(launch) ?? throw new IOException("新版 Cage 无法启动"); |
| 93 | var deadline = DateTime.UtcNow.AddSeconds(120); |
| 94 | var ready = false; |
| 95 | while (DateTime.UtcNow < deadline && !launched.HasExited) |
| 96 | { |
| 97 | if (File.Exists(marker) && new FileInfo(marker).Length < 16384) |
| 98 | { |
| 99 | try |
| 100 | { |
| 101 | var confirmation = JsonDocument.Parse(await File.ReadAllTextAsync(marker)).RootElement; |
| 102 | ready = confirmation.Text("version") == plan.Version; |
| 103 | } |
| 104 | catch (IOException) { } |
| 105 | catch (JsonException) { } |
| 106 | if (ready) break; |
| 107 | } |
| 108 | await Task.Delay(500); |
| 109 | } |
| 110 | if (!ready) throw new IOException("新版工作台未能完成启动确认"); |
| 111 | succeeded = true; |
| 112 | Result(true, "Cage 已更新至 " + plan.Version); |
| 113 | |
| 114 | |
| 115 | return 0; |
| 116 | } |
| 117 | catch (Exception error) |
| 118 | { |
| 119 | if (succeeded) return 0; |
| 120 | var detail = error.Message; |
| 121 | var recoveryIncomplete = false; |
| 122 | if (replaced && plan != null && backup != null) |
| 123 | { |
| 124 | try |
| 125 | { |
| 126 | |
| 127 | |
| 128 | using var installationLock = new Mutex(false, "Global\\Cage.Installation", out var ownsInstallation); |
| 129 | if (!ownsInstallation) throw new IOException("另一个安装或卸载正在进行,已保留更新备份,请等待完成后恢复。"); |
| 130 | EnsureInstallationComplete(plan.Target); |
| 131 | |
| 132 | |
| 133 | Authenticode.SamePublisher(UpdateRecovery.BackendPath(backup), plan.Publisher); |
| 134 | await UpdateRecovery.PrepareRollback(backup); |
| 135 | if (launched is { HasExited: false }) { launched.Kill(); await launched.WaitForExitAsync(); } |
| 136 | var restored = plan.Target + ".restore-" + plan.Confirmation; |
| 137 | var failed = plan.Target + ".failed-" + plan.Confirmation; |
| 138 | CopyTree(backup, restored); |
| 139 | var receipt = plan.Target + ".cage-installation.json"; |
| 140 | await PreserveFiles("prepare", plan.Target, restored, receipt, failed); |
| 141 | Directory.Move(plan.Target, failed); |
| 142 | try |
| 143 | { |
| 144 | await PreserveFiles("move", failed, restored, receipt); |
| 145 | Directory.Move(restored, plan.Target); |
| 146 | } |
| 147 | catch |
| 148 | { |
| 149 | await PreserveFiles("restore", restored, failed, receipt); |
| 150 | Directory.Move(failed, plan.Target); |
| 151 | await PreserveFiles("complete", "", plan.Target, receipt); |
| 152 | throw; |
| 153 | } |
| 154 | await PreserveFiles("cleanup", failed, plan.Target, receipt); |
| 155 | EnsureInstallationComplete(plan.Target); |
| 156 | UpdateRecovery.CleanupDirectory(backup); backup = null; |
| 157 | Result(false, "更新未完成,已恢复原应用:" + detail); |
| 158 | Process.Start(new ProcessStartInfo(Path.Combine(plan.Target, "Cage.exe")) { UseShellExecute = false, WorkingDirectory = plan.Target }); |
| 159 | return 1; |
| 160 | } |
| 161 | catch (Exception recovery) |
| 162 | { |
| 163 | recoveryIncomplete = true; |
| 164 | detail += "。自动恢复未完成。" + recovery.Message; |
| 165 | if (File.Exists(plan.Target + ".cage-installation.json")) |
| 166 | detail += "。恢复目录记录在 " + plan.Target + ".cage-installation.json"; |
| 167 | if (backup != null) detail += "。程序备份保留在 " + backup; |
| 168 | } |
| 169 | } |
| 170 | Result(false, "更新未完成:" + detail); |
| 171 | if (recoveryIncomplete && OperatingSystem.IsWindows()) MessageBoxW(IntPtr.Zero, detail, "Cage 更新需要恢复", 0x00010010); |
| 172 | if (committed && !replaced && plan != null) |
| 173 | { |
| 174 | try |
| 175 | { |
| 176 | var original = Path.Combine(plan.Target, "Cage.exe"); |
| 177 | Authenticode.SamePublisher(original, plan.Publisher); |
| 178 | Process.Start(new ProcessStartInfo(original) { UseShellExecute = false, WorkingDirectory = plan.Target }); |
| 179 | } |
| 180 | catch (Exception restart) when (restart is IOException or System.ComponentModel.Win32Exception) { } |
| 181 | } |
| 182 | return 1; |
| 183 | } |
| 184 | finally |
| 185 | { |
| 186 | launched?.Dispose(); |
| 187 | if (succeeded && plan != null && backup != null) |
| 188 | UpdateRecovery.CleanupAfterSuccess(backup, Path.GetDirectoryName(plan.Archive)!, Path.Combine(AppUpdater.Root, "launch-" + plan.Confirmation + ".json")); |
| 189 | else if (!replaced) UpdateRecovery.CleanupDirectory(backup); |
| 190 | } |
| 191 | } |
| 192 | |
| 193 | private static void Result(bool success, string message) |
| 194 | { |
| 195 | try |
| 196 | { |
| 197 | Directory.CreateDirectory(AppUpdater.Root); UpdatePolicy.PlainPath(AppUpdater.Root); |
| 198 | File.WriteAllText(Path.Combine(AppUpdater.Root, "last-result.json"), JsonSerializer.Serialize(new { success, message })); |
| 199 | } |
| 200 | catch (IOException) { } |
| 201 | catch (UnauthorizedAccessException) { } |
| 202 | } |
| 203 | |
| 204 | private static void EnsureInstallationComplete(string target) |
| 205 | { |
| 206 | var receipt = target + ".cage-installation.json"; |
| 207 | if (!File.Exists(receipt) && Directory.Exists(target)) return; |
| 208 | var message = "安装目录或个人文件仍需恢复,已停止自动启动。请保留并检查 " + receipt; |
| 209 | if (File.Exists(receipt) && new FileInfo(receipt).Length <= 16 * 1024 * 1024) |
| 210 | { |
| 211 | try |
| 212 | { |
| 213 | using var document = JsonDocument.Parse(File.ReadAllText(receipt)); |
| 214 | foreach (var name in new[] { "stagePath", "backupPath" }) |
| 215 | if (document.RootElement.Text(name) is { Length: > 0 } path) message += "。保留目录 " + path; |
| 216 | } |
| 217 | catch (Exception error) when (error is IOException or JsonException or InvalidOperationException) { } |
| 218 | } |
| 219 | throw new IOException(message); |
| 220 | } |
| 221 | |
| 222 | private static async Task PreserveFiles(string operation, string source, string target, string receipt, string? backupPath = null) |
| 223 | { |
| 224 | var directory = receipt + ".helper-" + Guid.NewGuid().ToString("N"); |
| 225 | Directory.CreateDirectory(directory); |
| 226 | var script = Path.Combine(directory, "installation-files.ps1"); |
| 227 | try |
| 228 | { |
| 229 | await using (var resource = typeof(UpdateInstaller).Assembly.GetManifestResourceStream("Cage.InstallationFiles.ps1") |
| 230 | ?? throw new IOException("缺少安装文件保留组件")) |
| 231 | await using (var output = File.Create(script)) { await resource.CopyToAsync(output); } |
| 232 | await using (var resource = typeof(UpdateInstaller).Assembly.GetManifestResourceStream("Cage.VerifiedFileDeletion.cs") |
| 233 | ?? throw new IOException("缺少安装文件校验组件")) |
| 234 | await using (var output = File.Create(Path.Combine(directory, "verified-file-deletion.cs"))) { await resource.CopyToAsync(output); } |
| 235 | using var deadline = new CancellationTokenSource(TimeSpan.FromMinutes(10)); |
| 236 | var executable = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.System), "WindowsPowerShell", "v1.0", "powershell.exe"); |
| 237 | var arguments = new List<string> { "-NoProfile", "-ExecutionPolicy", "Bypass", "-File", script, |
| 238 | "-Operation", operation, "-Source", source, "-Target", target, "-Receipt", receipt, "-LegacyTarget" }; |
| 239 | if (backupPath != null) { arguments.Add("-Backup"); arguments.Add(backupPath); } |
| 240 | using var process = new Process { StartInfo = Backend.StartInfo(executable, arguments.ToArray()) }; |
| 241 | if (!process.Start()) throw new IOException("无法启动安装文件保留组件"); |
| 242 | using var abort = deadline.Token.Register(() => { try { if (!process.HasExited) process.Kill(); } catch (InvalidOperationException) { } }); |
| 243 | var outputText = Backend.ReadLimited(process.StandardOutput, 65536, deadline.Token); |
| 244 | var errorText = Backend.ReadLimited(process.StandardError, 65536, deadline.Token); |
| 245 | await process.WaitForExitAsync(deadline.Token); |
| 246 | await outputText; |
| 247 | var error = await errorText; |
| 248 | if (process.ExitCode != 0) throw new IOException("安装文件保留未完成:" + error.Trim()); |
| 249 | } |
| 250 | finally |
| 251 | { |
| 252 | UpdateRecovery.CleanupDirectory(directory); |
| 253 | } |
| 254 | } |
| 255 | |
| 256 | private static void CopyTree(string source, string target) |
| 257 | { |
| 258 | source = Path.GetFullPath(source).TrimEnd(Path.DirectorySeparatorChar); |
| 259 | target = Path.GetFullPath(target).TrimEnd(Path.DirectorySeparatorChar); |
| 260 | var comparison = OperatingSystem.IsWindows() ? StringComparison.OrdinalIgnoreCase : StringComparison.Ordinal; |
| 261 | if (string.Equals(source, target, comparison) || target.StartsWith(source + Path.DirectorySeparatorChar, comparison)) |
| 262 | throw new InvalidDataException("更新备份目录位于程序目录内,无法安全备份。请使用完整安装包手动更新。"); |
| 263 | UpdatePolicy.PlainPath(source); UpdatePolicy.PlainPath(target); Directory.CreateDirectory(target); |
| 264 | HashSet<string>? owned = null; |
| 265 | var manifest = Path.Combine(source, "Cage.install-files.json"); |
| 266 | if (File.Exists(manifest) && (File.GetAttributes(manifest) & FileAttributes.ReparsePoint) == 0) |
| 267 | { |
| 268 | try |
| 269 | { |
| 270 | using var document = JsonDocument.Parse(File.ReadAllText(manifest)); |
| 271 | if (document.RootElement.GetProperty("version").GetInt32() == 1) |
| 272 | { |
| 273 | var paths = new HashSet<string>(StringComparer.OrdinalIgnoreCase); |
| 274 | foreach (var entry in document.RootElement.GetProperty("files").EnumerateArray()) |
| 275 | { |
| 276 | var path = entry.GetProperty("path").GetString(); |
| 277 | var digest = entry.GetProperty("sha256").GetString(); |
| 278 | if (string.IsNullOrEmpty(path) || path.StartsWith('/') || path.Contains('\\') || path.Contains(':') || |
| 279 | path.Split('/').Any(part => part is "." or "..") || digest?.Length != 64 || !digest.All(char.IsAsciiHexDigit)) |
| 280 | throw new JsonException("Invalid installation file record"); |
| 281 | paths.Add(path); |
| 282 | } |
| 283 | if (paths.Count > 0) { paths.Add("Cage.install-files.json"); owned = paths; } |
| 284 | } |
| 285 | } |
| 286 | catch (Exception error) when (error is IOException or JsonException or InvalidOperationException or KeyNotFoundException or FormatException) { } |
| 287 | } |
| 288 | long size = 0; var count = 0; |
| 289 | var pending = new Queue<string>(); pending.Enqueue(source); |
| 290 | while (pending.TryDequeue(out var directory)) |
| 291 | foreach (var entry in Directory.EnumerateFileSystemEntries(directory)) |
| 292 | { |
| 293 | var attributes = File.GetAttributes(entry); |
| 294 | if (++count > 100000) throw new IOException("安装目录文件过多,无法安全备份"); |
| 295 | |
| 296 | |
| 297 | if ((attributes & FileAttributes.ReparsePoint) != 0) continue; |
| 298 | var relative = Path.GetRelativePath(source, entry); |
| 299 | var key = relative.Replace(Path.DirectorySeparatorChar, '/'); |
| 300 | if (owned != null && !owned.Contains(key) && !owned.Any(path => path.StartsWith(key + "/", StringComparison.OrdinalIgnoreCase))) continue; |
| 301 | var destination = Path.Combine(target, relative); |
| 302 | if ((attributes & FileAttributes.Directory) != 0) { Directory.CreateDirectory(destination); pending.Enqueue(entry); } |
| 303 | else |
| 304 | { |
| 305 | size += new FileInfo(entry).Length; |
| 306 | if (size > (4L << 30)) throw new IOException("安装目录超过允许的备份大小"); |
| 307 | File.Copy(entry, destination, false); |
| 308 | } |
| 309 | } |
| 310 | } |
| 311 | } |