using System.Security.Cryptography; using System.Text; namespace XFEEDToolBox.NativeSupport; /// Materializes this build's embedded native support without changing the game installation. public static class NativeSupportPackage { private const string ResourcePrefix = "XFEEDToolBox.NativeSupport."; internal static readonly string[] ResourcePaths = [ "package.json", "dinput8.dll", "interaction.json", "XFEEDInteraction.dll", "DockingControl/interaction.json", "DockingControl/XFEEDInteraction.dll", "CruiseControl/interaction.json", "CruiseControl/XFEEDInteraction.dll" ]; private sealed record Payload(string Path, byte[] Bytes, byte[] Hash); private static readonly Lazy Embedded = new(ReadEmbedded); public static string Directory => GetDirectory(); public static string GetDirectory() => Extract(Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData), "XFEstudio", "XFEEDToolBox", "native-support"), Embedded.Value); private static Payload[] ReadEmbedded() { var assembly = typeof(NativeSupportPackage).Assembly; return ResourcePaths.Select(path => { using var stream = assembly.GetManifestResourceStream(ResourcePrefix + path) ?? throw new InvalidDataException($"Embedded native support is incomplete: {path}."); using var output = new MemoryStream(); stream.CopyTo(output); var bytes = output.ToArray(); if (bytes.Length == 0) throw new InvalidDataException($"Embedded native support is empty: {path}."); return new Payload(path, bytes, SHA256.HashData(bytes)); }).ToArray(); } // Kept independent of the native build so cache behavior can be tested with isolated payloads. internal static string ExtractPackage(string cacheRoot, IReadOnlyDictionary resources) { if (resources.Count != ResourcePaths.Length || ResourcePaths.Any(path => !resources.ContainsKey(path))) throw new InvalidDataException("Native support must contain the complete, fixed resource set."); var payloads = ResourcePaths.Select(path => { var bytes = resources[path]; if (bytes.Length == 0) throw new InvalidDataException($"Native support is empty: {path}."); return new Payload(path, bytes, SHA256.HashData(bytes)); }).ToArray(); return Extract(cacheRoot, payloads); } private static string Extract(string cacheRoot, Payload[] payloads) { using var identity = IncrementalHash.CreateHash(HashAlgorithmName.SHA256); foreach (var payload in payloads) { identity.AppendData(Encoding.UTF8.GetBytes(payload.Path + '\0')); identity.AppendData(payload.Hash); } var directory = Path.Combine(Path.GetFullPath(cacheRoot), Convert.ToHexStringLower(identity.GetHashAndReset())); using var cacheLock = new CacheLock(directory); EnsureDirectory(cacheRoot); EnsureDirectory(directory); foreach (var payload in payloads) { var destination = Path.Combine(directory, payload.Path.Replace('/', Path.DirectorySeparatorChar)); EnsureDirectory(Path.GetDirectoryName(destination)!); RejectLink(destination); if (Matches(destination, payload.Hash)) continue; var temporary = destination + "." + Guid.NewGuid().ToString("N") + ".tmp"; try { using (var file = new FileStream(temporary, FileMode.CreateNew, FileAccess.Write, FileShare.None)) { file.Write(payload.Bytes); file.Flush(flushToDisk: true); } // Concurrent processes may have completed the same immutable payload meanwhile. if (!Matches(destination, payload.Hash)) File.Move(temporary, destination, overwrite: true); } finally { if (File.Exists(temporary)) File.Delete(temporary); } if (!Matches(destination, payload.Hash)) throw new InvalidDataException($"Native support cache verification failed: {payload.Path}."); } return directory; } private sealed class CacheLock : IDisposable { private readonly Mutex mutex; public CacheLock(string directory) { var identity = OperatingSystem.IsWindows() ? directory.ToUpperInvariant() : directory; mutex = new Mutex(false, "XFEEDToolBox.NativeSupport." + Convert.ToHexStringLower(SHA256.HashData(Encoding.UTF8.GetBytes(identity)))); try { if (!mutex.WaitOne(TimeSpan.FromSeconds(30))) throw new TimeoutException("Another process is still preparing the native support cache."); } catch (AbandonedMutexException) { } // Each file is verified again after an interrupted extraction. catch { mutex.Dispose(); throw; } } public void Dispose() { mutex.ReleaseMutex(); mutex.Dispose(); } } private static bool Matches(string path, byte[] expected) { try { using var file = new FileStream(path, FileMode.Open, FileAccess.Read, FileShare.Read | FileShare.Delete); return CryptographicOperations.FixedTimeEquals(SHA256.HashData(file), expected); } catch (FileNotFoundException) { return false; } } private static void EnsureDirectory(string path) { System.IO.Directory.CreateDirectory(path); RejectLink(path); } private static void RejectLink(string path) { if ((File.Exists(path) || System.IO.Directory.Exists(path)) && (File.GetAttributes(path) & FileAttributes.ReparsePoint) != 0) throw new InvalidDataException("Native support cache paths cannot be links: " + path); } }