using System.Security.Cryptography; using System.Text.Json; namespace XFEWarframe.Client; public static class SafePath { public static string Within(string root, string relative) { root = Path.GetFullPath(root).TrimEnd(Path.DirectorySeparatorChar) + Path.DirectorySeparatorChar; if (Path.IsPathRooted(relative) || relative.Contains(':')) throw new InvalidDataException("不允许绝对路径或文件流。"); var path = Path.GetFullPath(Path.Combine(root, relative)); if (!path.StartsWith(root, StringComparison.OrdinalIgnoreCase)) throw new InvalidDataException("路径超出游戏目录。"); CheckNoLinks(path); return path; } public static void CheckNoLinks(string path) { for (string? current = Path.GetFullPath(path); current is not null; current = Path.GetDirectoryName(current)) if ((File.Exists(current) || Directory.Exists(current)) && (File.GetAttributes(current) & FileAttributes.ReparsePoint) != 0) throw new IOException("为防止写入其他目录,请使用真实副本,不要使用符号链接或目录联接:" + current); } } /// Durable undo journal. Only caller-supplied files change; game data is never recursively removed. public static class FileTransaction { private const string JournalName = "XFEWarframe/transaction.json"; public static void Apply(string root, IReadOnlyDictionary files, CancellationToken cancel = default, Action? afterWrite = null) { Recover(root); var journalPath = SafePath.Within(root, JournalName); var journal = new TransactionJournal(); var id = Guid.NewGuid().ToString("N"); foreach (var (relative, bytes) in files) { cancel.ThrowIfCancellationRequested(); var path = SafePath.Within(root, relative); string? backup = null, before = null; if (File.Exists(path)) { backup = $"XFEWarframe/backups/transactions/{id}/{journal.Changes.Count}.bak"; var original = File.ReadAllBytes(path); before = Convert.ToHexString(SHA256.HashData(original)); AtomicWrite(SafePath.Within(root, backup), original); } journal.Changes.Add(new(relative, backup, before, bytes is null ? null : Convert.ToHexString(SHA256.HashData(bytes)))); } AtomicWrite(journalPath, JsonSerializer.SerializeToUtf8Bytes(journal, ClientJson.Default.TransactionJournal)); try { var index = 0; foreach (var (relative, bytes) in files) { cancel.ThrowIfCancellationRequested(); var path = SafePath.Within(root, relative); if (bytes is null) File.Delete(path); else AtomicWrite(path, bytes); afterWrite?.Invoke(++index); } File.Delete(journalPath); } catch { Recover(root); throw; } } public static void Recover(string root) { var journalPath = SafePath.Within(root, JournalName); if (!File.Exists(journalPath)) return; var journal = JsonSerializer.Deserialize(File.ReadAllText(journalPath), ClientJson.Default.TransactionJournal) ?? throw new InvalidDataException("恢复日志损坏。"); if (journal.SchemaVersion != 1) throw new InvalidDataException("恢复日志版本不支持。"); // Preflight every entry before restoring anything. foreach (var change in journal.Changes) { var path = SafePath.Within(root, change.Path); var current = File.Exists(path) ? Compatibility.Hash(path) : null; if (current != change.BeforeHash && current != change.AfterHash) throw new IOException("中断后文件被其他程序修改,请保留备份后处理:" + change.Path); if (change.Backup is not null && Compatibility.Hash(SafePath.Within(root, change.Backup)) != change.BeforeHash) throw new InvalidDataException("恢复备份校验失败:" + change.Path); } foreach (var change in journal.Changes.AsEnumerable().Reverse()) { var path = SafePath.Within(root, change.Path); if (change.Backup is null) File.Delete(path); else AtomicWrite(path, File.ReadAllBytes(SafePath.Within(root, change.Backup))); } File.Delete(journalPath); } public static void AtomicWrite(string path, byte[] bytes) { SafePath.CheckNoLinks(path); Directory.CreateDirectory(Path.GetDirectoryName(path)!); var temporary = path + "." + Guid.NewGuid().ToString("N") + ".tmp"; try { using (var file = new FileStream(temporary, FileMode.CreateNew, FileAccess.Write, FileShare.None, 4096, FileOptions.WriteThrough)) { file.Write(bytes); file.Flush(true); } File.Move(temporary, path, true); } finally { if (File.Exists(temporary)) File.Delete(temporary); } } }