using System.Security.Cryptography; using System.Security.AccessControl; using System.Runtime.InteropServices; using System.Text.Json; namespace UCVL.VPNPlus; // Runs from the fully extracted installer payload, never from the live directory. // Only manifest-listed program files are changed; AppPaths.DataDirectory is not used. internal static class InstallationTransaction { internal record PayloadFile(string Path, string Sha256); internal record SavedFile(string Path, string Sha256, string? PreviousSha256); internal record Journal(string BackupId, string State, List Files, InstallationIntegration.Snapshot? Integration = null); private const string Metadata = ".ucvl-installer"; private const string Manifest = "install-manifest.json"; internal static void ValidateClientLaunch(string directory) { var metadata = System.IO.Path.Combine(Root(directory), Metadata); foreach (var filename in new[] { "journal.json", "uninstall-journal.json" }) { var path = System.IO.Path.Combine(metadata, filename); NoLinks(path); if (!File.Exists(path)) continue; if (new FileInfo(path).Length > 2 * 1024 * 1024) throw new IOException("安装恢复记录异常。"); using var document = JsonDocument.Parse(File.ReadAllText(path)); var state = document.RootElement.GetProperty("State").GetString(); var complete = filename == "journal.json" ? state is "committed" or "rolled-back" : state is "removed" or "rolled-back"; if (!complete) throw new IOException("上次安装或卸载尚未完成。请重新运行最新安装包恢复;不要卸载或删除程序目录。账号和配置仍保留。"); } } // The NSIS pipeline acceptance driver can only install inside one fresh // temporary fixture. It never stops or takes the live client's mutex. internal static string IsolatedTarget(string target) { var full = Root(target); var job = System.IO.Path.GetDirectoryName(full)!; var parent = System.IO.Path.GetDirectoryName(job); const string prefix = "ucvl-nsis-acceptance-"; var name = System.IO.Path.GetFileName(job); if (!string.Equals(System.IO.Path.GetFileName(full), "installed", StringComparison.Ordinal) || !string.Equals(parent, Root(System.IO.Path.GetTempPath()), StringComparison.OrdinalIgnoreCase) || !name.StartsWith(prefix, StringComparison.Ordinal) || !Guid.TryParseExact(name[prefix.Length..], "N", out _) || !Directory.Exists(job)) throw new IOException("隔离安装验收只允许已有临时任务的 installed 子目录。"); return full; } internal static int RunIsolated(string target, bool integrated = false, int? interruptAfter = null) { try { if (interruptAfter is < 0 or > 12) throw new IOException("无效隔离故障注入位置。"); Apply(AppContext.BaseDirectory, IsolatedTarget(target), integrated: integrated, isolated: true, afterIntegrationWrite: interruptAfter is null ? null : i => { if (i == interruptAfter) Environment.Exit(42); }); return 0; } catch (Exception error) { File.WriteAllText(System.IO.Path.Combine(AppContext.BaseDirectory, "install-error.txt"), error.ToString()); return 20; } } internal static int RecoverIsolated(string target) { try { target = IsolatedTarget(target); using var guard = new FileStream(System.IO.Path.Combine(target, Metadata, "install.lock"), FileMode.OpenOrCreate, FileAccess.ReadWrite, FileShare.None); Recover(target, isolated: true); ValidateClientLaunch(target); return 0; } catch { return 22; } } internal static int Run(string target, bool verifyOnly, bool integrated = false) { try { if (verifyOnly) { ValidatePayload(AppContext.BaseDirectory); return 0; } // Matches all supported old clients, so a running client blocks replacement. using var client = new Mutex(false, "Local\\UCVL.VPNPlus.Client"); bool acquired; try { acquired = client.WaitOne(0); } catch (AbandonedMutexException) { acquired = true; } if (!acquired) throw new IOException("原程序仍在运行,未修改安装目录。"); try { Apply(AppContext.BaseDirectory, target, integrated: integrated); } finally { client.ReleaseMutex(); } return 0; } catch (Exception exception) { // No session tokens, passwords, or network changes in this helper. File.WriteAllText(System.IO.Path.Combine(AppContext.BaseDirectory, "install-error.txt"), exception.ToString()); // Do not relaunch a potentially mixed installation if rollback itself failed. var pending = System.IO.Path.Combine(target, Metadata, "journal.json"); try { if (!verifyOnly && File.Exists(pending) && JsonSerializer.Deserialize(File.ReadAllText(pending))?.State == "pending") return 22; } catch { return 22; } return 20; } } internal static string Root(string directory) { var root = System.IO.Path.TrimEndingDirectorySeparator(System.IO.Path.GetFullPath(directory)); if (string.Equals(root, System.IO.Path.GetPathRoot(root), StringComparison.OrdinalIgnoreCase)) throw new IOException("不能使用磁盘根目录作为安装目录。"); NoLinks(root); return root; } internal static void NoLinks(string path) { for (var current = path; !string.IsNullOrEmpty(current); current = System.IO.Path.GetDirectoryName(current)) if ((File.Exists(current) || Directory.Exists(current)) && (File.GetAttributes(current) & FileAttributes.ReparsePoint) != 0) throw new IOException("安装路径中不能包含链接或目录联接。"); } internal static string Resolve(string root, string relative) { if (string.IsNullOrWhiteSpace(relative) || relative.Contains(':') || relative.Contains('\\') || System.IO.Path.IsPathRooted(relative) || relative.Split('/').Any(p => p is "" or "." or ".." || p.EndsWith(' ') || p.EndsWith('.'))) throw new IOException("安装清单路径无效。"); var allowed = relative is "VPNPlus.exe" or "README.md" or "THIRD_PARTY_NOTICES.md" || relative.StartsWith("assets/", StringComparison.Ordinal) || relative.StartsWith("xray/", StringComparison.Ordinal) || relative.StartsWith("licenses/", StringComparison.Ordinal); if (!allowed) throw new IOException("安装清单包含非程序文件。"); var full = System.IO.Path.GetFullPath(System.IO.Path.Combine(root, relative)); if (!full.StartsWith(root + System.IO.Path.DirectorySeparatorChar, StringComparison.OrdinalIgnoreCase)) throw new IOException("安装路径越界。"); NoLinks(full); return full; } internal static string Digest(string path) { using var file = File.OpenRead(path); return Convert.ToHexString(SHA256.HashData(file)); } internal static bool Matches(string path, string? digest) => digest is null ? !File.Exists(path) : File.Exists(path) && string.Equals(Digest(path), digest, StringComparison.OrdinalIgnoreCase); private static List ValidatePayload(string source) { source = Root(source); var files = JsonSerializer.Deserialize>(File.ReadAllText(System.IO.Path.Combine(source, Manifest))) ?? throw new IOException("安装包缺少文件清单。"); if (files.Count == 0 || files.Count > 10000 || 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")) throw new IOException("安装清单不完整或存在重复文件。"); foreach (var file in files) if (file.Sha256 is null || file.Sha256.Length != 64 || !Matches(Resolve(source, file.Path), file.Sha256)) throw new IOException("安装包文件校验失败:" + file.Path); // Dependencies first. The public executable path is always present during an upgrade. return files.OrderBy(f => f.Path == "VPNPlus.exe" ? 1 : 0).ThenBy(f => f.Path, StringComparer.Ordinal).ToList(); } internal static void Replace(string source, string target) { NoLinks(target); Directory.CreateDirectory(System.IO.Path.GetDirectoryName(target)!); var temporary = target + ".update-" + Guid.NewGuid().ToString("N") + ".tmp"; try { File.Copy(source, temporary); // Preserve the installed file's owner/group/DACL before the rename. // This is a program-file transaction, not a merge of old file data. if (File.Exists(target)) { const AccessControlSections sections = AccessControlSections.Access | AccessControlSections.Owner | AccessControlSections.Group; var security = new FileSecurity(); security.SetSecurityDescriptorBinaryForm(new FileInfo(target).GetAccessControl(sections).GetSecurityDescriptorBinaryForm(), sections); new FileInfo(temporary).SetAccessControl(security); } using (var flush = new FileStream(temporary, FileMode.Open, FileAccess.Write, FileShare.None)) flush.Flush(true); // ReplaceFile can briefly remove the public name (and documents // partial-failure states). Rename a flushed sibling instead, never // deleting or moving the installed file out of the way first. // https://learn.microsoft.com/windows/win32/api/winbase/nf-winbase-movefileexw for (var attempt = 0; ; attempt++) { // No COPY_ALLOWED, DELAY_UNTIL_REBOOT or cross-volume fallback. if (MoveFileExW(temporary, target, 0x1 | 0x8)) break; var error = Marshal.GetLastWin32Error(); if (attempt >= 24 || error is not (5 or 32 or 33) || !File.Exists(temporary) || !File.Exists(target)) throw new IOException("程序文件重命名失败,保留原安装并执行事务恢复。", new System.ComponentModel.Win32Exception(error)); Thread.Sleep(20); // Bounded antivirus/share contention; never retry by deleting the target. } } finally { if (File.Exists(temporary)) File.Delete(temporary); } } [DllImport("kernel32.dll", CharSet = CharSet.Unicode, SetLastError = true)] [return: MarshalAs(UnmanagedType.Bool)] private static extern bool MoveFileExW(string existing, string destination, uint flags); private static void Save(string metadata, Journal journal) { var temporary = System.IO.Path.Combine(metadata, "journal-" + Guid.NewGuid().ToString("N") + ".tmp"); try { File.WriteAllText(temporary, JsonSerializer.Serialize(journal)); Replace(temporary, System.IO.Path.Combine(metadata, "journal.json")); } finally { if (File.Exists(temporary)) File.Delete(temporary); } } internal static void Recover(string target, bool isolated = false) { target = Root(target); var metadata = System.IO.Path.Combine(target, Metadata); NoLinks(metadata); var path = System.IO.Path.Combine(metadata, "journal.json"); if (!File.Exists(path)) return; var journal = JsonSerializer.Deserialize(File.ReadAllText(path)) ?? throw new IOException("恢复记录无效。"); if (journal.State is "committed" or "rolled-back") return; if (journal.State != "pending" || !Guid.TryParseExact(journal.BackupId, "N", out _)) throw new IOException("恢复记录状态无效。"); if (journal.Integration is not null && journal.Integration.Isolated != isolated) throw new IOException("安装恢复记录的生产/隔离作用域不匹配,未修改文件或登记。"); var backup = System.IO.Path.Combine(metadata, journal.BackupId); // Validate every backup and destination before changing any of them. foreach (var file in journal.Files) { var destination = Resolve(target, file.Path); if (!Matches(destination, file.PreviousSha256) && !Matches(destination, file.Sha256)) throw new IOException("检测到安装文件被其它程序改变,备份已保留:" + file.Path); if (file.PreviousSha256 is not null && !Matches(Resolve(backup, file.Path), file.PreviousSha256)) throw new IOException("恢复备份校验失败:" + file.Path); } if (journal.Integration is not null) InstallationIntegration.Recover(target, backup, journal.Integration); foreach (var file in journal.Files.AsEnumerable().Reverse()) { var destination = Resolve(target, file.Path); if (Matches(destination, file.PreviousSha256)) continue; if (file.PreviousSha256 is null) File.Delete(destination); // Exact manifest file, never a directory. else Replace(Resolve(backup, file.Path), destination); } Save(metadata, journal with { State = "rolled-back" }); } internal static void Apply(string source, string target, Action? afterWrite = null, bool recoverOnFailure = true, bool integrated = false, bool isolated = false, Action? afterIntegrationWrite = null) { source = Root(source); target = Root(target); if (string.Equals(source, target, StringComparison.OrdinalIgnoreCase) || source.StartsWith(target + "\\", StringComparison.OrdinalIgnoreCase) || target.StartsWith(source + "\\", StringComparison.OrdinalIgnoreCase)) throw new IOException("临时安装包与正式目录必须分开。"); var files = ValidatePayload(source); // Fail before touching the installed files. Directory.CreateDirectory(target); var metadata = System.IO.Path.Combine(target, Metadata); NoLinks(metadata); Directory.CreateDirectory(metadata); // Excludes installers in other Windows sessions too. using var transactionLock = new FileStream(System.IO.Path.Combine(metadata, "install.lock"), FileMode.OpenOrCreate, FileAccess.ReadWrite, FileShare.None); InstallationRemoval.RecoverIfPending(target); Recover(target, isolated); var id = Guid.NewGuid().ToString("N"); var backup = System.IO.Path.Combine(metadata, id); var saved = new List(); foreach (var file in files) { var destination = Resolve(target, file.Path); var digest = File.Exists(destination) ? Digest(destination) : null; if (digest is not null) { var copy = Resolve(backup, file.Path); Directory.CreateDirectory(System.IO.Path.GetDirectoryName(copy)!); File.Copy(destination, copy); if (!Matches(copy, digest)) throw new IOException("旧版本备份校验失败。"); } saved.Add(new SavedFile(file.Path, file.Sha256, digest)); } var stage = System.IO.Path.Combine(System.IO.Path.GetDirectoryName(source)!, "integration"); var integration = integrated ? InstallationIntegration.Prepare(stage, target, backup, isolated, Application.ProductVersion) : null; var journal = new Journal(id, "pending", saved, integration); Save(metadata, journal); try { for (var i = 0; i < files.Count; i++) { var file = files[i]; var destination = Resolve(target, file.Path); if (!Matches(destination, saved[i].PreviousSha256)) throw new IOException("安装文件在备份后发生改变。"); Replace(Resolve(source, file.Path), destination); if (!Matches(destination, file.Sha256)) throw new IOException("安装后校验失败:" + file.Path); afterWrite?.Invoke(i); // Isolated fault injection only; never provided by the installer. } if (integration is not null) InstallationIntegration.Apply(stage, target, integration, afterIntegrationWrite); Save(metadata, journal with { State = "committed" }); } catch { if (recoverOnFailure) Recover(target, isolated); throw; } } }