XFE Git
XFE Studio Git
Git 首页 全局搜索
XFE 主站 文档 NuGet

XFEWarframe

【WinUI】基于Warframe游戏本体的公开服务器以及安装器

公开
关注 0 Fork 0 Star 0
UTF-8
using System.ComponentModel;
using System.Diagnostics;
using System.Runtime.InteropServices;
using System.Runtime.Versioning;
using System.Text;
using System.Text.Json;

namespace XFEWarframe.Client;

[SupportedOSPlatform("windows")]
public sealed class GameLauncher
{
    public int Launch(string directory, string language = "en", bool dx12 = false, CancellationToken cancellation = default) =>
        Launch(directory, language, dx12, cancellation, null);

    public int Launch(string directory, string language, bool dx12, CancellationToken cancellation, string? serverUrl, bool gameTestControl = false)
    {
        if (!Environment.Is64BitProcess) throw new PlatformNotSupportedException("请使用 x64 启动器。");
        directory = ClientInstaller.ValidateGame(directory);
        ClientInstaller.EnsureStopped(directory);
        using var operation = ClientInstaller.Lock(directory);
        var configuration = ClientInstaller.VerifyInstalled(directory);
        // A one-run server override supports isolated game checks without changing the installation.
        if (serverUrl is not null) configuration.ServerUrl = ClientProtocol.NormalizeServer(serverUrl);
        var server = ServerConnection.ReadAsync(configuration.ServerUrl, cancellation).GetAwaiter().GetResult();
        configuration.GameServerUrl = server.GameUrl;
        configuration.ServerName = server.ServerName;
        configuration.EnableGameTestControl = gameTestControl;
        configuration.Language = language;
        configuration.DirectX12 = dx12;
        if (gameTestControl && (!new Uri(configuration.GameServerUrl).IsLoopback || !new Uri(configuration.ServerUrl).IsLoopback))
            throw new ArgumentException("游戏测试接口仅用于本机隔离服务器。");
        if (!new[] { "en", "zh", "tc", "de", "es", "fr", "it", "ja", "ko", "pl", "pt", "ru", "th", "tr", "uk" }.Contains(language))
            throw new ArgumentException("不支持的客户端语言。");
        var executable = Path.Combine(directory, "Warframe.x64.exe");
        var dll = ClientInstaller.Managed(directory, ClientInstaller.BridgeFile);
        using var binary = new BinaryImage(dll);
        var initializeRva = binary.ExportRva("XfeInitialize");
        var startup = new Win32.Startup { Size = Marshal.SizeOf<Win32.Startup>() };
        var command = new StringBuilder($"\"{executable}\" -cluster:public -allowmultiple -language:{language} -graphicsDriver:{(dx12 ? "dx12" : "dx11")}");
        if (!Win32.CreateProcess(executable, command, 0, 0, false, 4, 0, directory, ref startup, out var process)) throw new Win32Exception();
        nint memory = 0;
        var resumed = false;
        var launchConfig = ClientInstaller.Managed(directory, $"launch-{process.ProcessId}.json");
        try
        {
            File.WriteAllText(launchConfig, JsonSerializer.Serialize(configuration, ClientJson.Default.ClientConfiguration));
            // Load explicitly through ntdll. This works before the suspended executable's entry point,
            // including builds that no longer import the old proxy DLLs used by InstallHelper.
            var localNtdll = Win32.GetModuleHandle("ntdll.dll");
            var remoteNtdll = RemoteModules.FindImageBase(process.Process, "ntdll.dll", cancellation);
            var loader = remoteNtdll + (Win32.GetProcAddress(localNtdll, "LdrLoadDll") - localNtdll);
            byte[] code = [0x48,0x83,0xEC,0x28,0x31,0xC9,0x31,0xD2,0x4C,0x8D,0x05,0x1B,0,0,0,0x4C,0x8D,0x4C,0x24,0x20,0x48,0x8B,0x05,7,0,0,0,0xFF,0xD0,0x48,0x83,0xC4,0x28,0xC3,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0];
            var pathBytes = Encoding.Unicode.GetBytes(dll + '\0');
            if (pathBytes.Length > 32000) throw new PathTooLongException();
            memory = Win32.VirtualAllocEx(process.Process, 0, (nuint)(code.Length + pathBytes.Length), 0x3000, 4);
            if (memory == 0) throw new Win32Exception();
            BitConverter.TryWriteBytes(code.AsSpan(0x22), (long)loader);
            BitConverter.TryWriteBytes(code.AsSpan(0x2A), checked((ushort)(pathBytes.Length - 2)));
            BitConverter.TryWriteBytes(code.AsSpan(0x2C), checked((ushort)pathBytes.Length));
            BitConverter.TryWriteBytes(code.AsSpan(0x32), (long)(memory + code.Length));
            Write(process.Process, memory, [.. code, .. pathBytes]);
            if (!Win32.VirtualProtectEx(process.Process, memory, (nuint)(code.Length + pathBytes.Length), 0x20, out _)) throw new Win32Exception();
            if (!Win32.FlushInstructionCache(process.Process, memory, (nuint)code.Length)) throw new Win32Exception();
            var status = RunThread(process.Process, memory, 0, cancellation);
            if ((status & 0x80000000) != 0) throw new IOException($"兼容组件加载失败,NTSTATUS 0x{status:X8}。");
            Win32.VirtualFreeEx(process.Process, memory, 0, 0x8000); memory = 0;
            var module = RemoteModules.FindImageBase(process.Process, ClientInstaller.BridgeFile, cancellation);
            var configBytes = Encoding.Unicode.GetBytes(launchConfig + '\0');
            memory = Win32.VirtualAllocEx(process.Process, 0, (nuint)configBytes.Length, 0x3000, 4);
            if (memory == 0) throw new Win32Exception();
            Write(process.Process, memory, configBytes);
            status = RunThread(process.Process, module + initializeRva, memory, cancellation);
            if (status != 0) throw new IOException($"兼容组件初始化失败({status}),请查看 XFEWarframe\\logs。");
            cancellation.ThrowIfCancellationRequested();
            if (Win32.ResumeThread(process.Thread) == uint.MaxValue) throw new Win32Exception();
            resumed = true;
            GameExitDiagnostics.Observe(process.ProcessId, directory, configuration.BuildLabel);
            return process.ProcessId;
        }
        finally
        {
            // On failure only terminate the suspended process created by this call.
            if (!resumed) { Win32.TerminateProcess(process.Process, 1); Win32.WaitForSingleObject(process.Process, 5000); }
            if (memory != 0) Win32.VirtualFreeEx(process.Process, memory, 0, 0x8000);
            Win32.CloseHandle(process.Thread); Win32.CloseHandle(process.Process);
            if (File.Exists(launchConfig)) File.Delete(launchConfig);
        }
    }
    private static void Write(nint process, nint destination, byte[] data)
    {
        if (!Win32.WriteProcessMemory(process, destination, data, (nuint)data.Length, out var written) || written != (nuint)data.Length)
            throw new Win32Exception();
    }
    private static uint RunThread(nint process, nint address, nint argument, CancellationToken cancellation)
    {
        var thread = Win32.CreateRemoteThread(process, 0, 0, address, argument, 0, out _);
        if (thread == 0) throw new Win32Exception();
        try
        {
            var timer = Stopwatch.StartNew();
            while (true)
            {
                cancellation.ThrowIfCancellationRequested();
                var result = Win32.WaitForSingleObject(thread, 200);
                if (result == 0) break;
                if (result != 258) throw new Win32Exception();
                if (timer.Elapsed > TimeSpan.FromSeconds(45)) throw new TimeoutException("客户端组件加载超时,已停止本次启动。");
            }
            if (!Win32.GetExitCodeThread(thread, out var code)) throw new Win32Exception();
            return code;
        }
        finally { Win32.CloseHandle(thread); }
    }
}

internal static class Win32
{
    [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Unicode)] internal struct Startup
    {
        public int Size; public string? Reserved, Desktop, Title;
        public int X, Y, XSize, YSize, XCountChars, YCountChars, FillAttribute, Flags;
        public short ShowWindow, ReservedSize; public nint ReservedPointer, Input, Output, Error;
    }
    [StructLayout(LayoutKind.Sequential)] internal struct ProcessInfo { public nint Process, Thread; public int ProcessId, ThreadId; }
    [DllImport("kernel32", EntryPoint = "CreateProcessW", CharSet = CharSet.Unicode, SetLastError = true)] [return: MarshalAs(UnmanagedType.Bool)] internal static extern bool CreateProcess(string app, StringBuilder command, nint processAttributes, nint threadAttributes, [MarshalAs(UnmanagedType.Bool)] bool inherit, uint flags, nint environment, string directory, ref Startup startup, out ProcessInfo process);
    [DllImport("kernel32", EntryPoint = "GetModuleHandleW", CharSet = CharSet.Unicode)] internal static extern nint GetModuleHandle(string name);
    [DllImport("kernel32", CharSet = CharSet.Ansi, ExactSpelling = true)] internal static extern nint GetProcAddress(nint module, string name);
    [DllImport("kernel32", SetLastError = true)] internal static extern nint VirtualAllocEx(nint process, nint address, nuint size, uint type, uint protect);
    [DllImport("kernel32", SetLastError = true)] [return: MarshalAs(UnmanagedType.Bool)] internal static extern bool VirtualFreeEx(nint process, nint address, nuint size, uint type);
    [DllImport("kernel32", SetLastError = true)] [return: MarshalAs(UnmanagedType.Bool)] internal static extern bool VirtualProtectEx(nint process, nint address, nuint size, uint protection, out uint old);
    [DllImport("kernel32", SetLastError = true)] [return: MarshalAs(UnmanagedType.Bool)] internal static extern bool WriteProcessMemory(nint process, nint address, byte[] bytes, nuint size, out nuint written);
    [DllImport("kernel32", SetLastError = true)] [return: MarshalAs(UnmanagedType.Bool)] internal static extern bool FlushInstructionCache(nint process, nint address, nuint size);
    [DllImport("kernel32", SetLastError = true)] internal static extern nint CreateRemoteThread(nint process, nint attributes, nuint stackSize, nint start, nint parameter, uint flags, out uint id);
    [DllImport("kernel32", SetLastError = true)] internal static extern uint WaitForSingleObject(nint handle, uint milliseconds);
    [DllImport("kernel32", SetLastError = true)] [return: MarshalAs(UnmanagedType.Bool)] internal static extern bool GetExitCodeThread(nint thread, out uint code);
    [DllImport("kernel32", SetLastError = true)] internal static extern uint ResumeThread(nint thread);
    [DllImport("kernel32", SetLastError = true)] [return: MarshalAs(UnmanagedType.Bool)] internal static extern bool TerminateProcess(nint process, uint code);
    [DllImport("kernel32")] [return: MarshalAs(UnmanagedType.Bool)] internal static extern bool CloseHandle(nint handle);
}