using System.Collections.Concurrent; using System.Diagnostics; using System.Net; using System.Net.Sockets; using System.Security.Cryptography; using System.Text; using System.Text.Json; using System.Text.Json.Nodes; namespace XFEWarframe.Client.Runtime; /// Local API inside the C# runtime. No URL ACLs, browser pages or native OpenWF dependency. public sealed class RuntimeControlServer : IAsyncDisposable { public const string Version = "1.4.18"; private readonly TcpListener listener; private readonly CancellationTokenSource lifetime = new(); private readonly SemaphoreSlim clients = new(8, 8); private readonly ConcurrentDictionary requests = new(); private readonly object settingsGate = new(); private readonly string settingsPath, sessionPath; private readonly ClientConfiguration configuration; private readonly Action applySettings; private readonly RuntimeLogBuffer logs; private readonly Task accepting; private RuntimeSettings settings = new(); private int nextRequest; private readonly bool multiAbilitiesAvailable; private readonly Func>? gameControl; private readonly Func>? visualControl; private readonly Func? visualStatus; private readonly GameLoginQueue? gameLogin; public RuntimeSession Session { get; } public RuntimeSettings Settings => Volatile.Read(ref settings); public RuntimeControlServer(string gameDirectory, ClientConfiguration configuration, RuntimeLogBuffer logs, Action applySettings, int preferredPort = 6155, string? discoveryDirectory = null, bool multiAbilitiesAvailable = false, Func>? gameControl = null, Func>? visualControl = null, Func? visualStatus = null, GameLoginQueue? gameLogin = null) { this.configuration = configuration; this.logs = logs; this.applySettings = applySettings; this.multiAbilitiesAvailable = multiAbilitiesAvailable; this.visualControl = visualControl; this.visualStatus = visualStatus; this.gameLogin = gameLogin; this.gameControl = configuration.EnableGameTestControl && IsLocalServer(configuration.ServerUrl) && IsLocalServer(configuration.GameServerUrl) ? gameControl : null; gameDirectory = Path.GetFullPath(gameDirectory); settingsPath = Path.Combine(gameDirectory, "XFEWarframe", "runtime-settings.json"); try { if (File.Exists(settingsPath)) { if (new FileInfo(settingsPath).Length > 65536) throw new InvalidDataException("Runtime settings exceed 64 KB."); settings = JsonSerializer.Deserialize(File.ReadAllText(settingsPath), RuntimeJson.Default.RuntimeSettings) ?? new(); } } catch (Exception ex) when (ex is IOException or JsonException or InvalidDataException) { logs.Add("运行时设置未加载:" + ex.GetType().Name); } applySettings(settings); listener = new(IPAddress.Loopback, preferredPort); try { listener.Start(8); } catch (SocketException) when (preferredPort != 0) { listener = new(IPAddress.Loopback, 0); listener.Start(8); } var directory = discoveryDirectory ?? RuntimeDiscovery.DirectoryFor(gameDirectory); Session = new(Guid.NewGuid().ToString("N"), Environment.ProcessId, gameDirectory, $"http://127.0.0.1:{((IPEndPoint)listener.LocalEndpoint).Port}", Convert.ToHexStringLower(RandomNumberGenerator.GetBytes(32)), DateTimeOffset.UtcNow); sessionPath = Path.Combine(directory, Session.Instance + ".json"); try { Directory.CreateDirectory(directory); File.WriteAllText(sessionPath, JsonSerializer.Serialize(Session, RuntimeJson.Default.RuntimeSession)); accepting = AcceptAsync(); } catch { listener.Stop(); throw; } } public RuntimeStatus Status() { using var process = Process.GetCurrentProcess(); var cards = visualControl is not null ? visualStatus?.Invoke() : null; return new(Session.Instance, Session.ProcessId, Version, configuration.BuildLabel, configuration.ServerName, configuration.ServerUrl, Session.StartedAt, process.WorkingSet64, GC.GetTotalMemory(false), Settings, [new("status", true), new("logs", true), new("settings", true), new("save_config", true), new("disable_overlay", true), new("client_http_logging", true), new("game_login", gameLogin is not null, gameLogin is not null ? "native-profile-login" : "compatible-login-binding-required"), new("original_mod_cards", visualControl is not null && (cards?.Available ?? true), cards?.Reason ?? (visualControl is not null ? "native-render-cache" : "visual-binding-unavailable")), new("camera", false, "engine-binding-missing"), new("teleport", false, "engine-binding-missing"), new("scripts", false, "engine-binding-missing"), new("metadata", false, "engine-binding-missing"), new("hotfix", false, "format-not-implemented"), new("game_test_control", this.gameControl is not null, this.gameControl is not null ? "local-engine-test-only" : "launch-opt-in-required"), new("experimental_multi_abilities", multiAbilitiesAvailable, multiAbilitiesAvailable ? "experimental-2026.08.19.11.06" : "compatible-binding-required"), new("pet_fetch_300m", multiAbilitiesAvailable, multiAbilitiesAvailable ? "native-fetch-trigger" : "compatible-binding-required")]); } private static bool IsLocalServer(string value) => Uri.TryCreate(value, UriKind.Absolute, out var uri) && uri.Scheme is "http" or "https" && uri.IsLoopback; private async Task AcceptAsync() { while (!lifetime.IsCancellationRequested) { TcpClient client; try { client = await listener.AcceptTcpClientAsync(lifetime.Token).ConfigureAwait(false); } catch (Exception ex) when (ex is OperationCanceledException or SocketException or ObjectDisposedException) { break; } if (!clients.Wait(0)) { client.Dispose(); continue; } var key = Interlocked.Increment(ref nextRequest); var task = ServeAsync(client); requests[key] = task; _ = task.ContinueWith(completed => { requests.TryRemove(key, out _); }, CancellationToken.None, TaskContinuationOptions.ExecuteSynchronously, TaskScheduler.Default); } } private async Task ServeAsync(TcpClient client) { using (client) using (var timeout = CancellationTokenSource.CreateLinkedTokenSource(lifetime.Token)) { timeout.CancelAfter(TimeSpan.FromSeconds(4)); try { using var stream = client.GetStream(); var bytes = new byte[8192]; var count = 0; var end = -1; while (end < 0) { if (count == bytes.Length) { await Error(stream, 431, "请求头过大。", timeout.Token); return; } var read = await stream.ReadAsync(bytes.AsMemory(count), timeout.Token).ConfigureAwait(false); if (read == 0) return; count += read; end = bytes.AsSpan(0, count).IndexOf("\r\n\r\n"u8); } var lines = Encoding.ASCII.GetString(bytes, 0, end).Split("\r\n"); var first = lines[0].Split(' '); if (first.Length != 3 || first[2] != "HTTP/1.1" || !first[1].StartsWith('/') || first[1].StartsWith("//", StringComparison.Ordinal)) { await Error(stream, 400, "无效 HTTP 请求。", timeout.Token); return; } var headers = new Dictionary(StringComparer.OrdinalIgnoreCase); foreach (var line in lines.Skip(1)) { var colon = line.IndexOf(':'); if (colon <= 0 || !headers.TryAdd(line[..colon], line[(colon + 1)..].Trim())) { await Error(stream, 400, "无效或重复请求头。", timeout.Token); return; } } if (headers.ContainsKey("Origin") || headers.ContainsKey("Transfer-Encoding") || headers.GetValueOrDefault("Host") != new Uri(Session.Endpoint).Authority) { await Error(stream, 403, "仅接受本机桌面客户端请求。", timeout.Token); return; } var expected = Encoding.ASCII.GetBytes("Bearer " + Session.Token); var actual = Encoding.ASCII.GetBytes(headers.GetValueOrDefault("Authorization") ?? ""); if (!CryptographicOperations.FixedTimeEquals(expected, actual)) { await Error(stream, 401, "运行时连接凭据无效。", timeout.Token); return; } if (!int.TryParse(headers.GetValueOrDefault("Content-Length", "0"), out var length) || length is < 0 or > 65536) { await Error(stream, 413, "请求内容过大。", timeout.Token); return; } var body = new byte[length]; var buffered = Math.Min(count - end - 4, length); bytes.AsSpan(end + 4, buffered).CopyTo(body); await stream.ReadExactlyAsync(body.AsMemory(buffered), timeout.Token).ConfigureAwait(false); var target = first[1]; var path = target.Split('?')[0]; if (Settings.ClientHttpLogging) logs.Add(first[0] + " " + path); // Never log authorization, query strings or request bodies. try { string response; try { response = visualControl is not null && path.StartsWith("/runtime/v1/visuals/", StringComparison.Ordinal) ? await visualControl(first[0] + " " + path[20..], body, timeout.Token).ConfigureAwait(false) : gameControl is not null && path.StartsWith("/runtime/v1/game/", StringComparison.Ordinal) ? await gameControl(first[0] + " " + path[17..], body, timeout.Token).ConfigureAwait(false) : Dispatch(first[0], path, target, body); } finally { CryptographicOperations.ZeroMemory(body); } await Reply(stream, 200, response, timeout.Token).ConfigureAwait(false); } catch (RuntimeRequestException ex) { await Error(stream, ex.Status, ex.Message, timeout.Token); } catch (InvalidOperationException ex) { await Error(stream, 409, ex.Message, timeout.Token); } catch (Exception ex) when (ex is JsonException or InvalidDataException or ArgumentException) { await Error(stream, 400, "设置或参数无效。", timeout.Token); } catch (IOException) { await Error(stream, 500, "无法保存运行时设置;当前设置仍保留在内存中。", timeout.Token); } catch (UnauthorizedAccessException) { await Error(stream, 500, "没有运行时设置文件的写入权限。", timeout.Token); } } catch (Exception ex) when (ex is IOException or SocketException or OperationCanceledException or ObjectDisposedException) { } finally { clients.Release(); } } } private string Dispatch(string method, string path, string target, byte[] body) { if (gameLogin is not null && (path is "/runtime/v1/account/login" or "/runtime/v1/account/login/cancel")) { GameLoginStatus result; if (path.EndsWith("/cancel", StringComparison.Ordinal) && method == "POST") { var data = JsonNode.Parse(body) as JsonObject; var id = data?["requestId"]?.GetValue(); if (data?.Count != 1 || !Guid.TryParseExact(id, "N", out _)) throw new ArgumentException("Invalid request ID."); result = gameLogin.Cancel(id!); } else if (path == "/runtime/v1/account/login" && method == "GET") result = gameLogin.Status; else if (path == "/runtime/v1/account/login" && method == "POST") { var request = JsonSerializer.Deserialize(body, RuntimeJson.Default.GameLoginRequest) ?? throw new ArgumentException("Login request required."); request.Validate(); if (request.ServerUrl != ClientProtocol.NormalizeServer(configuration.ServerUrl)) throw new RuntimeRequestException(403, "游戏与启动器账号的服务器不一致。"); result = gameLogin.Submit(request); } else throw new RuntimeRequestException(405, "仅支持 GET 和 POST。"); return JsonSerializer.Serialize(result, RuntimeJson.Default.GameLoginStatus); } if (method == "GET") { if (path is "/ping" or "/status" or "/runtime/v1/status") return JsonSerializer.Serialize(Status(), RuntimeJson.Default.RuntimeStatus); if (path == "/runtime/v1/logs") { var query = target.Contains('?') ? target[(target.IndexOf('?') + 1)..] : ""; if (query.Length > 0 && (!query.StartsWith("after=", StringComparison.Ordinal) || !long.TryParse(query[6..], out var cursor) || cursor < 0)) throw new RuntimeRequestException(400, "日志游标无效。"); var after = query.Length == 0 ? 0 : long.Parse(query[6..], System.Globalization.CultureInfo.InvariantCulture); return JsonSerializer.Serialize(logs.Read(after), RuntimeJson.Default.RuntimeLogs); } } else if (method == "POST") { if (path == "/runtime/v1/settings") { var patch = JsonNode.Parse(body) as JsonObject ?? throw new InvalidDataException(); if (patch.Count is < 1 or > 2 || patch.Any(x => x.Key is not ("disableOverlay" or "clientHttpLogging") || x.Value?.GetValueKind() is not JsonValueKind.True and not JsonValueKind.False)) throw new RuntimeRequestException(400, "不支持的设置或设置类型。"); lock (settingsGate) { var next = new RuntimeSettings(patch["disableOverlay"]?.GetValue() ?? Settings.DisableOverlay, patch["clientHttpLogging"]?.GetValue() ?? Settings.ClientHttpLogging); applySettings(next); Volatile.Write(ref settings, next); } return JsonSerializer.Serialize(Settings, RuntimeJson.Default.RuntimeSettings); } if (path == "/runtime/v1/save") { lock (settingsGate) { if (File.Exists(settingsPath) && new FileInfo(settingsPath).Length > 65536) throw new InvalidDataException(); var document = File.Exists(settingsPath) ? JsonNode.Parse(File.ReadAllText(settingsPath)) as JsonObject ?? throw new InvalidDataException() : new JsonObject(); document["disableOverlay"] = Settings.DisableOverlay; document["clientHttpLogging"] = Settings.ClientHttpLogging; Directory.CreateDirectory(Path.GetDirectoryName(settingsPath)!); File.WriteAllText(settingsPath + ".tmp", document.ToJsonString()); if (File.Exists(settingsPath)) File.Replace(settingsPath + ".tmp", settingsPath, settingsPath + ".bak"); else File.Move(settingsPath + ".tmp", settingsPath); } return JsonSerializer.Serialize(new RuntimeSaved(true), RuntimeJson.Default.RuntimeSaved); } if (path == "/runtime/v1/logs/clear") { logs.Clear(); return JsonSerializer.Serialize(new RuntimeSaved(true), RuntimeJson.Default.RuntimeSaved); } } else throw new RuntimeRequestException(405, "仅支持 GET 和 POST。"); throw new RuntimeRequestException(404, "运行时未提供此接口。"); } private static Task Error(Stream stream, int status, string message, CancellationToken cancellation) => Reply(stream, status, JsonSerializer.Serialize(new RuntimeError(message), RuntimeJson.Default.RuntimeError), cancellation); private static async Task Reply(Stream stream, int status, string json, CancellationToken cancellation) { var body = Encoding.UTF8.GetBytes(json); var header = Encoding.ASCII.GetBytes($"HTTP/1.1 {status} Response\r\nContent-Type: application/json; charset=utf-8\r\nContent-Length: {body.Length}\r\nConnection: close\r\nCache-Control: no-store\r\nX-Content-Type-Options: nosniff\r\n\r\n"); await stream.WriteAsync(header, cancellation).ConfigureAwait(false); await stream.WriteAsync(body, cancellation).ConfigureAwait(false); } public async ValueTask DisposeAsync() { await lifetime.CancelAsync(); listener.Stop(); await accepting.ConfigureAwait(false); await Task.WhenAll(requests.Values).ConfigureAwait(false); try { File.Delete(sessionPath); } catch (IOException) { } lifetime.Dispose(); clients.Dispose(); } private sealed class RuntimeRequestException(int status, string message) : Exception(message) { public int Status => status; } }