using System.Net;
using System.Runtime.InteropServices;
using System.Text;
using System.Text.Json;
using System.Security.Cryptography;
using System.Security.Cryptography.X509Certificates;
using XFEExtension.NetCore.CyberComm;
using XFEExtension.NetCore.ServerInteractive.Utilities.Extensions;
using XFEExtension.NetCore.ServerInteractive.Utilities.Server;
using XFEWarframe.Core;
using XFEWarframe.Core.Chat;
using XFEWarframe.Core.Data;
using XFEWarframe.Server;
Console.OutputEncoding = Encoding.UTF8;
var root = Path.GetFullPath(args.FirstOrDefault(x => x.StartsWith("--root=", StringComparison.Ordinal))?[7..] ?? Path.Combine(AppContext.BaseDirectory, "runtime"));
if (args.Contains("--routes"))
{
Console.WriteLine(JsonSerializer.Serialize(new RouteCatalog().All, new JsonSerializerOptions { WriteIndented = true }));
return;
}
var options = ServerOptions.Load(root);
if (args.FirstOrDefault(x => x.StartsWith("--port=", StringComparison.Ordinal)) is string portArg)
{
if (!int.TryParse(portArg[7..], out var port) || port is < 1 or > 65535) throw new ArgumentException("Invalid --port");
options.ListenUrls = [$"http://127.0.0.1:{port}/"];
options.PublicUrl = $"http://127.0.0.1:{port}";
options.GameListenUrl = options.GamePublicUrl = null;
}
if (args.FirstOrDefault(x => x.StartsWith("--game-port=", StringComparison.Ordinal)) is string gamePortArg)
{
if (!int.TryParse(gamePortArg[12..], out var gamePort) || gamePort is < 1 or > 65535) throw new ArgumentException("Invalid --game-port");
options.GameListenUrl = $"https://127.0.0.1:{gamePort}/";
options.GamePublicUrl = $"https://127.0.0.1:{gamePort}";
}
if (args.Contains("--no-irc")) options.Irc.Enabled = false;
if (args.Contains("--no-official-events")) options.SyncOfficialEvents = false;
if (args.FirstOrDefault(x => x.StartsWith("--irc-port=", StringComparison.Ordinal)) is string ircPortArg)
{
if (!int.TryParse(ircPortArg[11..], out var ircPort) || ircPort is < 1 or > 65535) throw new ArgumentException("Invalid --irc-port");
options.Irc.Ports = [ircPort];
}
if (args.FirstOrDefault(x => x.StartsWith("--irc-tls-port=", StringComparison.Ordinal)) is string ircTlsPortArg)
{
if (!int.TryParse(ircTlsPortArg[15..], out var ircTlsPort) || ircTlsPort is < 1 or > 65535) throw new ArgumentException("Invalid --irc-tls-port");
options.Irc.TlsPorts = [ircTlsPort];
}
options.Validate();
// The bridge accepts the private server's certificate. Nothing is installed in the OS trust store.
using var generatedCertificate = options.TlsPfxPath is null && (options.GameListenUrl is not null || options.ListenUrls.Any(x => x.StartsWith("https:")) || options.Irc.Enabled && options.Irc.TlsPorts.Length > 0) ? CreateCertificate() : null;
using var ircCertificate = options.Irc.Enabled && options.Irc.TlsPorts.Length > 0 && options.TlsPfxPath is not null
? X509CertificateLoader.LoadPkcs12FromFile(Path.GetFullPath(options.TlsPfxPath, root), options.TlsPasswordEnvironmentVariable is null ? null : Environment.GetEnvironmentVariable(options.TlsPasswordEnvironmentVariable)) : null;
await using var store = new StateStore(Path.Combine(root, "data"));
var engine = new GameEngine(store, options);
using var shutdown = new CancellationTokenSource();
engine.ShutdownRequested += () => _ = Task.Run(async () => { await Task.Delay(500); shutdown.Cancel(); });
var logsDirectory = Path.Combine(root, "logs");
Directory.CreateDirectory(logsDirectory);
using var logFile = TextWriter.Synchronized(new StreamWriter(Path.Combine(logsDirectory, $"requests-{DateTime.UtcNow:yyyyMMdd}.jsonl"), append: true, Encoding.UTF8) { AutoFlush = true });
engine.RequestCompleted += log =>
{
logFile.WriteLine(JsonSerializer.Serialize(log));
// ServerInteractive already prefixes console lines with its timestamp and log level.
if (!log.Path.StartsWith("/control/")) Console.WriteLine($"{log.Status} {log.Method,-4} {log.Path} {log.DurationMs:0.0}ms");
};
var core = XFEServerCoreBuilder.CreateBuilder()
.AddParameter(nameof(GameBridge.Engine), engine)
.AddService<GameBridge>()
.Build(config =>
{
config.ServerCoreName = "XFEWarframe";
config.AcceptGet = true;
config.AcceptPost = true;
config.AcceptNonStandardJson = true;
foreach (var url in options.ListenUrls) config.BindIP(url);
if (options.GameListenUrl is not null && !options.ListenUrls.Contains(options.GameListenUrl)) config.BindIP(options.GameListenUrl);
config.TransportLimits = new CyberCommLimitOptions
{
MaxHttpBodyBytes = 16 * 1024 * 1024,
MaxConnections = 512,
MaxConnectionsPerIp = 64,
HandlerTimeout = TimeSpan.FromSeconds(60)
};
if (options.TlsPfxPath is not null) config.Tls = new CyberCommTlsOptions
{
PfxPath = Path.GetFullPath(options.TlsPfxPath, root),
PfxPassword = options.TlsPasswordEnvironmentVariable is null ? null : Environment.GetEnvironmentVariable(options.TlsPasswordEnvironmentVariable)
};
else if (generatedCertificate is not null) config.Tls = new CyberCommTlsOptions { Certificate = generatedCertificate };
});
core.ServerCoreError += (_, error) =>
{
var response = error.ReturnArgs?.Args.Context?.Response;
if (response is null || response.IsCompleted) return;
response.WriteTextAsync("{\"error\":\"Route not found\"}", HttpStatusCode.NotFound, "application/json; charset=utf-8").GetAwaiter().GetResult();
response.Complete();
};
await using var server = XFEServerBuilder.CreateBuilder().UseXFEServer().AddInitializer(new InstanceLogInitializer(Path.Combine(logsDirectory, "framework.log"))).AddServerCore(core).Build();
Console.CancelKeyPress += (_, e) => { e.Cancel = true; shutdown.Cancel(); };
using var signal = !OperatingSystem.IsWindows() ? PosixSignalRegistration.Create(PosixSignal.SIGTERM, ctx => { ctx.Cancel = true; shutdown.Cancel(); }) : null;
await using var chat = new IrcServer(store, options.Irc, ircCertificate ?? generatedCertificate, Console.WriteLine);
chat.Start(shutdown.Token);
Console.WriteLine("XFE WARFRAME · Native C# API server");
Console.WriteLine($"Listen: {string.Join(", ", options.ListenUrls)}");
Console.WriteLine($"Game: {options.GamePublicUrl ?? options.PublicUrl}");
Console.WriteLine($"Configuration: {Path.Combine(root, "server.json")}");
Console.WriteLine($"Migration: {engine.Routes.All.Count(x => x.Status == "ported")} ported / {engine.Routes.All.Count(x => x.Status == "partial")} partial / {engine.Routes.All.Count(x => x.Status == "pending")} pending");
Console.WriteLine("WinUI management uses the AdminToken in server.json. Ctrl+C stops gracefully.");
try
{
var eventSync = engine.OfficialEventSync.Run(shutdown.Token);
// A failed listener stops the whole host, preventing a healthy-looking API with dead chat.
async Task RunService(Task service) { try { await service; } finally { await shutdown.CancelAsync(); } }
if (options.Irc.Enabled) await Task.WhenAll(RunService(server.RunAsync(shutdown.Token)), RunService(chat.Completion), RunService(eventSync));
else await Task.WhenAll(RunService(server.RunAsync(shutdown.Token)), RunService(eventSync));
}
catch (OperationCanceledException) when (shutdown.IsCancellationRequested) { }
static X509Certificate2 CreateCertificate()
{
using var key = RSA.Create(2048);
var request = new CertificateRequest("CN=XFEWarframe Private Server", key, HashAlgorithmName.SHA256, RSASignaturePadding.Pkcs1);
request.CertificateExtensions.Add(new X509BasicConstraintsExtension(false, false, 0, true));
request.CertificateExtensions.Add(new X509KeyUsageExtension(X509KeyUsageFlags.DigitalSignature | X509KeyUsageFlags.KeyEncipherment, true));
request.CertificateExtensions.Add(new X509EnhancedKeyUsageExtension(new OidCollection { new("1.3.6.1.5.5.7.3.1") }, false));
var names = new SubjectAlternativeNameBuilder(); names.AddDnsName("localhost"); names.AddIpAddress(IPAddress.Loopback);
request.CertificateExtensions.Add(names.Build());
using var certificate = request.CreateSelfSigned(DateTimeOffset.UtcNow.AddMinutes(-5), DateTimeOffset.UtcNow.AddYears(1));
return X509CertificateLoader.LoadPkcs12(certificate.Export(X509ContentType.Pfx), null, X509KeyStorageFlags.DefaultKeySet);
}
using System.Net;
using System.Runtime.InteropServices;
using System.Text;
using System.Text.Json;
using System.Security.Cryptography;
using System.Security.Cryptography.X509Certificates;
using XFEExtension.NetCore.CyberComm;
using XFEExtension.NetCore.ServerInteractive.Utilities.Extensions;
using XFEExtension.NetCore.ServerInteractive.Utilities.Server;
using XFEWarframe.Core;
using XFEWarframe.Core.Chat;
using XFEWarframe.Core.Data;
using XFEWarframe.Server;
Console.OutputEncoding = Encoding.UTF8;
var root = Path.GetFullPath(args.FirstOrDefault(x => x.StartsWith("--root=", StringComparison.Ordinal))?[7..] ?? Path.Combine(AppContext.BaseDirectory, "runtime"));
if (args.Contains("--routes"))
{
Console.WriteLine(JsonSerializer.Serialize(new RouteCatalog().All, new JsonSerializerOptions { WriteIndented = true }));
return;
}
var options = ServerOptions.Load(root);
if (args.FirstOrDefault(x => x.StartsWith("--port=", StringComparison.Ordinal)) is string portArg)
{
if (!int.TryParse(portArg[7..], out var port) || port is < 1 or > 65535) throw new ArgumentException("Invalid --port");
options.ListenUrls = [$"http://127.0.0.1:{port}/"];
options.PublicUrl = $"http://127.0.0.1:{port}";
options.GameListenUrl = options.GamePublicUrl = null;
}
if (args.FirstOrDefault(x => x.StartsWith("--game-port=", StringComparison.Ordinal)) is string gamePortArg)
{
if (!int.TryParse(gamePortArg[12..], out var gamePort) || gamePort is < 1 or > 65535) throw new ArgumentException("Invalid --game-port");
options.GameListenUrl = $"https://127.0.0.1:{gamePort}/";
options.GamePublicUrl = $"https://127.0.0.1:{gamePort}";
}
if (args.Contains("--no-irc")) options.Irc.Enabled = false;
if (args.Contains("--no-official-events")) options.SyncOfficialEvents = false;
if (args.FirstOrDefault(x => x.StartsWith("--irc-port=", StringComparison.Ordinal)) is string ircPortArg)
{
if (!int.TryParse(ircPortArg[11..], out var ircPort) || ircPort is < 1 or > 65535) throw new ArgumentException("Invalid --irc-port");
options.Irc.Ports = [ircPort];
}
if (args.FirstOrDefault(x => x.StartsWith("--irc-tls-port=", StringComparison.Ordinal)) is string ircTlsPortArg)
{
if (!int.TryParse(ircTlsPortArg[15..], out var ircTlsPort) || ircTlsPort is < 1 or > 65535) throw new ArgumentException("Invalid --irc-tls-port");
options.Irc.TlsPorts = [ircTlsPort];
}
options.Validate();
// The bridge accepts the private server's certificate. Nothing is installed in the OS trust store.
using var generatedCertificate = options.TlsPfxPath is null && (options.GameListenUrl is not null || options.ListenUrls.Any(x => x.StartsWith("https:")) || options.Irc.Enabled && options.Irc.TlsPorts.Length > 0) ? CreateCertificate() : null;
using var ircCertificate = options.Irc.Enabled && options.Irc.TlsPorts.Length > 0 && options.TlsPfxPath is not null
? X509CertificateLoader.LoadPkcs12FromFile(Path.GetFullPath(options.TlsPfxPath, root), options.TlsPasswordEnvironmentVariable is null ? null : Environment.GetEnvironmentVariable(options.TlsPasswordEnvironmentVariable)) : null;
await using var store = new StateStore(Path.Combine(root, "data"));
var engine = new GameEngine(store, options);
using var shutdown = new CancellationTokenSource();
engine.ShutdownRequested += () => _ = Task.Run(async () => { await Task.Delay(500); shutdown.Cancel(); });
var logsDirectory = Path.Combine(root, "logs");
Directory.CreateDirectory(logsDirectory);
using var logFile = TextWriter.Synchronized(new StreamWriter(Path.Combine(logsDirectory, $"requests-{DateTime.UtcNow:yyyyMMdd}.jsonl"), append: true, Encoding.UTF8) { AutoFlush = true });
engine.RequestCompleted += log =>
{
logFile.WriteLine(JsonSerializer.Serialize(log));
// ServerInteractive already prefixes console lines with its timestamp and log level.
if (!log.Path.StartsWith("/control/")) Console.WriteLine($"{log.Status} {log.Method,-4} {log.Path} {log.DurationMs:0.0}ms");
};
var core = XFEServerCoreBuilder.CreateBuilder()
.AddParameter(nameof(GameBridge.Engine), engine)
.AddService<GameBridge>()
.Build(config =>
{
config.ServerCoreName = "XFEWarframe";
config.AcceptGet = true;
config.AcceptPost = true;
config.AcceptNonStandardJson = true;
foreach (var url in options.ListenUrls) config.BindIP(url);
if (options.GameListenUrl is not null && !options.ListenUrls.Contains(options.GameListenUrl)) config.BindIP(options.GameListenUrl);
config.TransportLimits = new CyberCommLimitOptions
{
MaxHttpBodyBytes = 16 * 1024 * 1024,
MaxConnections = 512,
MaxConnectionsPerIp = 64,
HandlerTimeout = TimeSpan.FromSeconds(60)
};
if (options.TlsPfxPath is not null) config.Tls = new CyberCommTlsOptions
{
PfxPath = Path.GetFullPath(options.TlsPfxPath, root),
PfxPassword = options.TlsPasswordEnvironmentVariable is null ? null : Environment.GetEnvironmentVariable(options.TlsPasswordEnvironmentVariable)
};
else if (generatedCertificate is not null) config.Tls = new CyberCommTlsOptions { Certificate = generatedCertificate };
});
core.ServerCoreError += (_, error) =>
{
var response = error.ReturnArgs?.Args.Context?.Response;
if (response is null || response.IsCompleted) return;
response.WriteTextAsync("{\"error\":\"Route not found\"}", HttpStatusCode.NotFound, "application/json; charset=utf-8").GetAwaiter().GetResult();
response.Complete();
};
await using var server = XFEServerBuilder.CreateBuilder().UseXFEServer().AddInitializer(new InstanceLogInitializer(Path.Combine(logsDirectory, "framework.log"))).AddServerCore(core).Build();
Console.CancelKeyPress += (_, e) => { e.Cancel = true; shutdown.Cancel(); };
using var signal = !OperatingSystem.IsWindows() ? PosixSignalRegistration.Create(PosixSignal.SIGTERM, ctx => { ctx.Cancel = true; shutdown.Cancel(); }) : null;
await using var chat = new IrcServer(store, options.Irc, ircCertificate ?? generatedCertificate, Console.WriteLine);
chat.Start(shutdown.Token);
Console.WriteLine("XFE WARFRAME · Native C# API server");
Console.WriteLine($"Listen: {string.Join(", ", options.ListenUrls)}");
Console.WriteLine($"Game: {options.GamePublicUrl ?? options.PublicUrl}");
Console.WriteLine($"Configuration: {Path.Combine(root, "server.json")}");
Console.WriteLine($"Migration: {engine.Routes.All.Count(x => x.Status == "ported")} ported / {engine.Routes.All.Count(x => x.Status == "partial")} partial / {engine.Routes.All.Count(x => x.Status == "pending")} pending");
Console.WriteLine("WinUI management uses the AdminToken in server.json. Ctrl+C stops gracefully.");
try
{
var eventSync = engine.OfficialEventSync.Run(shutdown.Token);
// A failed listener stops the whole host, preventing a healthy-looking API with dead chat.
async Task RunService(Task service) { try { await service; } finally { await shutdown.CancelAsync(); } }
if (options.Irc.Enabled) await Task.WhenAll(RunService(server.RunAsync(shutdown.Token)), RunService(chat.Completion), RunService(eventSync));
else await Task.WhenAll(RunService(server.RunAsync(shutdown.Token)), RunService(eventSync));
}
catch (OperationCanceledException) when (shutdown.IsCancellationRequested) { }
static X509Certificate2 CreateCertificate()
{
using var key = RSA.Create(2048);
var request = new CertificateRequest("CN=XFEWarframe Private Server", key, HashAlgorithmName.SHA256, RSASignaturePadding.Pkcs1);
request.CertificateExtensions.Add(new X509BasicConstraintsExtension(false, false, 0, true));
request.CertificateExtensions.Add(new X509KeyUsageExtension(X509KeyUsageFlags.DigitalSignature | X509KeyUsageFlags.KeyEncipherment, true));
request.CertificateExtensions.Add(new X509EnhancedKeyUsageExtension(new OidCollection { new("1.3.6.1.5.5.7.3.1") }, false));
var names = new SubjectAlternativeNameBuilder(); names.AddDnsName("localhost"); names.AddIpAddress(IPAddress.Loopback);
request.CertificateExtensions.Add(names.Build());
using var certificate = request.CreateSelfSigned(DateTimeOffset.UtcNow.AddMinutes(-5), DateTimeOffset.UtcNow.AddYears(1));
return X509CertificateLoader.LoadPkcs12(certificate.Export(X509ContentType.Pfx), null, X509KeyStorageFlags.DefaultKeySet);
}