using System.IO.Compression; using System.Net; using System.Text; using XFEExtension.NetCore.ServerInteractive.Implements.CoreService; using XFEWarframe.Core; namespace XFEWarframe.Server; /// ServerInteractive is the sole HTTP/TLS listener and request dispatcher. public sealed class GameBridge : ServerCoreStandardServiceBase { public GameEngine Engine { get; set; } = null!; public override Dictionary> AsyncEntryPoints => new() { ["**"] = Dispatch }; public override HashSet NoLogEntryPoints => ["**"]; private async Task Dispatch() { var body = Args.RequestBody ?? ""; var encoding = Args.RequestHeaders["Content-Encoding"]; if (encoding is "gzip" or "deflate") { using var input = new MemoryStream(Args.Context!.Body.ToArray()); using Stream decoder = encoding == "gzip" ? new GZipStream(input, CompressionMode.Decompress) : new ZLibStream(input, CompressionMode.Decompress); using var output = new MemoryStream(); var buffer = new byte[8192]; try { int read; while ((read = await decoder.ReadAsync(buffer)) > 0) { if (output.Length + read > 16 * 1024 * 1024) { await Args.ReplyAndClose("{\"error\":\"Body too large\"}", HttpStatusCode.RequestEntityTooLarge, "application/json"); return; } output.Write(buffer, 0, read); } body = Encoding.UTF8.GetString(output.ToArray()); } catch (InvalidDataException) { await Args.ReplyAndClose("{\"error\":\"Invalid compressed body\"}", HttpStatusCode.BadRequest, "application/json"); return; } } else if (!string.IsNullOrEmpty(encoding) && encoding is not ("identity" or "e" or "ezip")) { await Args.ReplyAndClose("{\"error\":\"Unsupported content encoding\"}", HttpStatusCode.UnsupportedMediaType, "application/json"); return; } var authorization = Args.RequestHeaders["Authorization"]; var token = authorization?.StartsWith("Bearer ", StringComparison.OrdinalIgnoreCase) == true ? authorization[7..] : null; var query = Args.QueryString.AllKeys.Where(x => x is not null).ToDictionary(x => x!, x => Args.QueryString[x] ?? "", StringComparer.Ordinal); var result = await Engine.Handle(new ApiRequest(Args.RequestMethod, Args.RequestUrl!.AbsolutePath, query, body, token, Args.ClientIP)); if (Args.Context is not null) { Args.Context.Response.Headers["Cache-Control"] = "no-store"; Args.Context.Response.Headers["X-Content-Type-Options"] = "nosniff"; } if (result.BinaryBody is not null && Args.Context is not null) { await Args.Context.Response.WriteAsync(result.BinaryBody, (HttpStatusCode)result.Status, result.ContentType); Args.Close((HttpStatusCode)result.Status); } else await Args.ReplyAndClose(result.Body, (HttpStatusCode)result.Status, result.ContentType); } }