using System.Text.Json; namespace UCVL.VPNPlus; // Explicit uninstall only. Program files are backed up, never a recursive tree // deletion. Both installation-directory extras and separate AppData are kept. internal static class InstallationRemoval { internal record RemovalJournal(string InstallId, string BackupId, string State, List Files); private const string JournalName = "uninstall-journal.json"; private static readonly HashSet KnownFiles = new(StringComparer.Ordinal) { "VPNPlus.exe", "README.md", "THIRD_PARTY_NOTICES.md", "assets/company-logo-original.png", "assets/zonghengjia-app-logo-v1.png", "assets/zonghengjia-app-v1.ico", "xray/xray.exe", "xray/wintun.dll", "xray/geoip.dat", "xray/geosite.dat", "licenses/NSIS-COPYING.txt", "licenses/Wintun-License.txt", "licenses/Xray-MPL-2.0.txt", }; private static string Metadata(string target) => Path.Combine(target, ".ucvl-installer"); private static T Read(string path) { InstallationTransaction.NoLinks(path); if (new FileInfo(path).Length > 2 * 1024 * 1024) throw new IOException("安装所有权记录过大。"); return JsonSerializer.Deserialize(File.ReadAllText(path)) ?? throw new IOException("安装所有权记录无效。"); } private static void Save(string metadata, RemovalJournal journal) { var temporary = Path.Combine(metadata, "uninstall-" + Guid.NewGuid().ToString("N") + ".tmp"); try { File.WriteAllText(temporary, JsonSerializer.Serialize(journal)); InstallationTransaction.Replace(temporary, Path.Combine(metadata, JournalName)); } finally { if (File.Exists(temporary)) File.Delete(temporary); } } private static void ValidateFiles(List files) { if (files.Count is 0 or > 13 || files.Select(f => f.Path).Distinct(StringComparer.OrdinalIgnoreCase).Count() != files.Count || !files.Any(f => f.Path == "VPNPlus.exe") || !files.Any(f => f.Path == "xray/xray.exe") || !files.Any(f => f.Path == "xray/wintun.dll") || files.Any(f => !KnownFiles.Contains(f.Path) || f.Sha256 is null || f.Sha256.Length != 64 || f.Sha256.Any(c => !Uri.IsHexDigit(c)))) throw new IOException("卸载记录包含未知文件或无效校验值,未删除文件。"); } private static InstallationTransaction.Journal Ownership(string target, string? helperDigest = null) { target = InstallationTransaction.Root(target); var metadata = Metadata(target); var installed = Read(Path.Combine(metadata, "journal.json")); if (installed.State != "committed" || !Guid.TryParseExact(installed.BackupId,"N",out _)) throw new IOException("安装事务尚未完成,先修复安装,不执行卸载。"); var files=installed.Files.Select(f => new InstallationTransaction.PayloadFile(f.Path,f.Sha256)).ToList(); ValidateFiles(files); foreach (var file in files) _ = InstallationTransaction.Resolve(target,file.Path); if (helperDigest is not null && !string.Equals(files.Single(f => f.Path == "VPNPlus.exe").Sha256,helperDigest,StringComparison.OrdinalIgnoreCase)) throw new IOException("卸载器版本与当前安装不一致,请使用当前版本卸载器。"); return installed; } private static RemovalJournal? Existing(string target, string installId) { var path=Path.Combine(Metadata(target),JournalName); if (!File.Exists(path)) return null; var journal=Read(path); if (!Guid.TryParseExact(journal.InstallId,"N",out _) || !Guid.TryParseExact(journal.BackupId,"N",out _) || journal.State is not ("pending" or "removed" or "rolled-back")) throw new IOException("卸载恢复记录无效。"); ValidateFiles(journal.Files); if (journal.InstallId != installId) { if (journal.State == "pending") throw new IOException("另一个安装的卸载恢复未完成。"); return null; // A completed old removal does not apply to a later reinstall. } var expected=Ownership(target).Files.ToDictionary(f=>f.Path,f=>f.Sha256,StringComparer.Ordinal); if (journal.Files.Count != expected.Count || journal.Files.Any(f=>!expected.TryGetValue(f.Path,out var digest) || !string.Equals(digest,f.Sha256,StringComparison.OrdinalIgnoreCase))) throw new IOException("卸载恢复记录与安装所有权不一致,未修改文件。"); return journal; } internal static void Check(string target, string? helperDigest = null) { target=InstallationTransaction.Root(target); var installed=Ownership(target,helperDigest); var journal=Existing(target,installed.BackupId); if (journal?.State == "removed") { if (installed.Files.Any(f=>File.Exists(InstallationTransaction.Resolve(target,f.Path)))) throw new IOException("已卸载目录又出现程序文件,请先重新安装以更新所有权记录。"); return; } foreach (var file in installed.Files) if (!(journal?.State == "pending" && !File.Exists(InstallationTransaction.Resolve(target,file.Path))) && !InstallationTransaction.Matches(InstallationTransaction.Resolve(target,file.Path),file.Sha256)) throw new IOException("程序文件缺失或被修改,保留目录,请先修复安装:"+file.Path); } internal static void RecoverIfPending(string target) { var metadata=Metadata(InstallationTransaction.Root(target)); if (!File.Exists(Path.Combine(metadata,JournalName))) return; // An old completed removal must not prevent the installer's own pending // transaction from recovering after a later interrupted reinstall. var stored=Read(Path.Combine(metadata,JournalName)); if (stored.State is "removed" or "rolled-back") return; var installed=Ownership(target); var journal=Existing(target,installed.BackupId); if (journal?.State != "pending") return; var backup=Path.Combine(metadata,"uninstall-"+journal.BackupId); foreach (var file in journal.Files) { var destination=InstallationTransaction.Resolve(target,file.Path); if (File.Exists(destination) && !InstallationTransaction.Matches(destination,file.Sha256)) throw new IOException("卸载期间文件被其它程序修改,备份保留:"+file.Path); if (!InstallationTransaction.Matches(InstallationTransaction.Resolve(backup,file.Path),file.Sha256)) throw new IOException("卸载恢复备份校验失败:"+file.Path); } foreach (var file in journal.Files) if (!File.Exists(InstallationTransaction.Resolve(target,file.Path))) InstallationTransaction.Replace(InstallationTransaction.Resolve(backup,file.Path),InstallationTransaction.Resolve(target,file.Path)); Save(metadata,journal with {State="rolled-back"}); } internal static void Remove(string target, string? helperDigest = null, Action? afterDelete = null, bool recoverOnFailure = true) { target=InstallationTransaction.Root(target); var installed=Ownership(target,helperDigest); var metadata=Metadata(target); using var transactionLock=new FileStream(Path.Combine(metadata,"install.lock"),FileMode.OpenOrCreate,FileAccess.ReadWrite,FileShare.None); RecoverIfPending(target); if (Existing(target,installed.BackupId)?.State == "removed") return; Check(target,helperDigest); // Validate all owned files before modifying any. var files=installed.Files.Select(f=>new InstallationTransaction.PayloadFile(f.Path,f.Sha256)) .OrderBy(f=>f.Path=="VPNPlus.exe"?1:0).ThenBy(f=>f.Path,StringComparer.Ordinal).ToList(); var id=Guid.NewGuid().ToString("N"); var backup=Path.Combine(metadata,"uninstall-"+id); foreach(var file in files) { var copy=InstallationTransaction.Resolve(backup,file.Path); Directory.CreateDirectory(Path.GetDirectoryName(copy)!); File.Copy(InstallationTransaction.Resolve(target,file.Path),copy); if(!InstallationTransaction.Matches(copy,file.Sha256)) throw new IOException("卸载备份校验失败。"); } var journal=new RemovalJournal(installed.BackupId,id,"pending",files); Save(metadata,journal); try { for(var i=0;i