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

XFEWarframe

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

公开
关注 0 Fork 0 Star 0
UTF-8
using System.Collections.Concurrent;
using System.Net;
using System.Net.Security;
using System.Net.Sockets;
using System.Security.Authentication;
using System.Security.Cryptography.X509Certificates;
using System.Text;
using System.Threading.Channels;
using Newtonsoft.Json.Linq;
using XFEWarframe.Core.Data;

namespace XFEWarframe.Core.Chat;

/// <summary>In-process Warframe IRC transport. HTTP and chat share the same account store.</summary>
public sealed partial class IrcServer(StateStore store, IrcServerOptions options, X509Certificate2? certificate = null, Action<string>? log = null) : IAsyncDisposable
{
    private const string ServerName = "XFEWarframe";
    private const int MaxLineBytes = 4096;
    private static readonly UTF8Encoding Utf8 = new(false, true);
    private readonly SemaphoreSlim gate = new(1, 1);
    private readonly ConcurrentDictionary<long, Connection> connections = new();
    private readonly ConcurrentDictionary<long, Task> workers = new();
    private readonly Dictionary<string, Connection> registered = new(StringComparer.OrdinalIgnoreCase);
    private readonly Dictionary<string, ChatChannel> channels = new(StringComparer.OrdinalIgnoreCase);
    private readonly List<TcpListener> listeners = [];
    private readonly List<Task> acceptors = [];
    private CancellationTokenSource? lifetime;
    private CancellationTokenRegistration stopRegistration;
    private Task? heartbeat;
    private long nextId;
    private bool started;

    public int ConnectionCount => connections.Count;
    public Task Completion => Task.WhenAll(acceptors.Append(heartbeat ?? Task.CompletedTask));
    public IReadOnlyList<IPEndPoint> Endpoints => listeners.Select(x => (IPEndPoint)x.LocalEndpoint).ToArray();

    public void Start(CancellationToken cancellationToken = default)
    {
        if (started) throw new InvalidOperationException("IRC server has already started");
        options.Validate();
        if (!options.Enabled) return;
        if (options.TlsPorts.Length > 0 && certificate is null) throw new InvalidOperationException("IRC TLS requires a server certificate");
        lifetime = CancellationTokenSource.CreateLinkedTokenSource(cancellationToken);
        try
        {
            var address = IPAddress.Parse(options.ListenAddress);
            // Bind every port before accepting anyone. A conflict fails startup visibly.
            foreach (var port in options.Ports.Concat(options.TlsPorts))
            {
                var listener = new TcpListener(address, port);
                listener.Server.ExclusiveAddressUse = true;
                if (address.Equals(IPAddress.IPv6Any)) listener.Server.DualMode = true;
                try { listener.Start(); }
                catch { listener.Stop(); throw; }
                listeners.Add(listener);
            }
            started = true;
            stopRegistration = lifetime.Token.Register(StopSockets);
            foreach (var listener in listeners)
                acceptors.Add(Accept(listener, options.TlsPorts.Contains(((IPEndPoint)listener.LocalEndpoint).Port), lifetime.Token));
            heartbeat = Heartbeat(lifetime.Token);
            log?.Invoke($"IRC listening on {options.ListenAddress}; TCP {string.Join(',', options.Ports)}; TLS {string.Join(',', options.TlsPorts)}");
        }
        catch
        {
            StopSockets();
            lifetime.Dispose(); lifetime = null;
            throw;
        }
    }

    private async Task Accept(TcpListener listener, bool tls, CancellationToken cancellationToken)
    {
        try
        {
            while (!cancellationToken.IsCancellationRequested)
            {
                var socket = await listener.AcceptTcpClientAsync(cancellationToken);
                socket.NoDelay = true;
                var remote = ((IPEndPoint)socket.Client.RemoteEndPoint!).Address;
                if (remote.IsIPv4MappedToIPv6) remote = remote.MapToIPv4();
                var client = new Connection(Interlocked.Increment(ref nextId), socket, remote, tls, cancellationToken);
                // Acceptors share this gate so the global and per-address limits are atomic.
                try { await gate.WaitAsync(cancellationToken); }
                catch { client.Close(); client.Lifetime.Dispose(); throw; }
                try
                {
                    if (connections.Count >= options.MaxConnections || connections.Values.Count(x => x.Remote.Equals(remote)) >= 32)
                    { client.Close(); client.Lifetime.Dispose(); continue; }
                    connections[client.Id] = client;
                    var task = Run(client);
                    workers[client.Id] = task;
                    _ = task.ContinueWith(_ => workers.TryRemove(client.Id, out var ignored), TaskScheduler.Default);
                }
                finally { gate.Release(); }
            }
        }
        catch (Exception ex) when (cancellationToken.IsCancellationRequested && ex is OperationCanceledException or SocketException or ObjectDisposedException) { }
        catch (Exception ex)
        {
            log?.Invoke($"IRC listener stopped unexpectedly ({ex.GetType().Name})");
            lifetime?.Cancel();
            throw;
        }
    }

    private async Task Run(Connection client)
    {
        Task? writer = null;
        Stream? transport = null;
        try
        {
            Stream stream = client.Socket.GetStream(); transport = stream;
            if (client.Tls)
            {
                var secure = new SslStream(stream, leaveInnerStreamOpen: false);
                stream = secure; transport = secure;
                using var handshake = CancellationTokenSource.CreateLinkedTokenSource(client.Lifetime.Token);
                handshake.CancelAfter(TimeSpan.FromSeconds(options.RegistrationTimeoutSeconds));
                await secure.AuthenticateAsServerAsync(new SslServerAuthenticationOptions
                {
                    ServerCertificate = certificate,
                    EnabledSslProtocols = SslProtocols.Tls12 | SslProtocols.Tls13,
                    ClientCertificateRequired = false,
                    CertificateRevocationCheckMode = X509RevocationMode.NoCheck
                }, handshake.Token);
            }
            writer = Write(client, stream);
            // The native client waits for this identd notice before sending NICK/USER.
            client.Send($"NOTICE * :Auth {client.Challenge:x8}:*** skipping identd (disabled by server administrator)");
            using var reader = new StreamReader(stream, Utf8, detectEncodingFromByteOrderMarks: false, bufferSize: 1024, leaveOpen: true);
            var buffer = new char[1024];
            var pending = new StringBuilder();
            while (!client.Lifetime.IsCancellationRequested)
            {
                var read = await reader.ReadAsync(buffer.AsMemory(), client.Lifetime.Token);
                if (read == 0) break;
                for (var i = 0; i < read; i++)
                {
                    if (buffer[i] != '\n')
                    {
                        pending.Append(buffer[i]);
                        if (pending.Length > MaxLineBytes) throw new InvalidDataException("IRC line too long");
                        continue;
                    }
                    var line = pending.ToString().TrimEnd('\r'); pending.Clear();
                    if (Utf8.GetByteCount(line) > MaxLineBytes || line.Contains('\r') || line.Contains('\0'))
                        throw new InvalidDataException("Invalid IRC frame");
                    await gate.WaitAsync(client.Lifetime.Token);
                    try
                    {
                        client.LastReceived = DateTimeOffset.UtcNow;
                        if (!await Process(client, line)) return;
                    }
                    finally { gate.Release(); }
                }
            }
        }
        catch (Exception ex) when (ex is IOException or SocketException or AuthenticationException or OperationCanceledException or ObjectDisposedException or DecoderFallbackException)
        { /* Disconnects and malformed frames do not expose credentials or message bodies in logs. */ }
        catch (Exception ex) { log?.Invoke($"IRC connection failed ({ex.GetType().Name})"); }
        finally
        {
            client.Outgoing.Writer.TryComplete();
            if (writer is not null)
            {
                try { await writer.WaitAsync(TimeSpan.FromSeconds(2)); }
                catch (Exception ex) when (ex is TimeoutException or OperationCanceledException or IOException or ObjectDisposedException) { }
            }
            client.Close();
            if (transport is not null)
            {
                try { await transport.DisposeAsync(); }
                catch (Exception ex) when (ex is IOException or ObjectDisposedException) { }
            }
            await gate.WaitAsync();
            try
            {
                RemoveFromChannels(client);
                if (client.Identity is { } identity && registered.TryGetValue(identity.Id, out var owner) && ReferenceEquals(owner, client))
                {
                    registered.Remove(identity.Id);
                    // A previous connection must never mark a newer login/reconnection as dropped.
                    await store.Update(state =>
                    {
                        if (state["accounts"]?[identity.Id] is Newtonsoft.Json.Linq.JObject account && account.Value<long>("Nonce") == identity.Nonce)
                            account["Dropped"] = true;
                        return true;
                    });
                }
            }
            catch (Exception ex) { log?.Invoke($"IRC disconnect cleanup failed ({ex.GetType().Name})"); }
            finally
            {
                connections.TryRemove(client.Id, out _);
                gate.Release();
                client.Lifetime.Dispose();
            }
        }
    }

    private static async Task Write(Connection client, Stream stream)
    {
        try
        {
            await foreach (var line in client.Outgoing.Reader.ReadAllAsync(client.Lifetime.Token))
            {
                using var timeout = CancellationTokenSource.CreateLinkedTokenSource(client.Lifetime.Token);
                timeout.CancelAfter(TimeSpan.FromSeconds(10));
                await stream.WriteAsync(Utf8.GetBytes(line + "\r\n"), timeout.Token);
            }
        }
        catch (Exception ex) when (ex is IOException or SocketException or OperationCanceledException or ObjectDisposedException)
        { client.Close(); }
    }

    private async Task Heartbeat(CancellationToken cancellationToken)
    {
        using var timer = new PeriodicTimer(TimeSpan.FromSeconds(1));
        try
        {
            while (await timer.WaitForNextTickAsync(cancellationToken))
            {
                await gate.WaitAsync(cancellationToken);
                try
                {
                    var now = DateTimeOffset.UtcNow;
                    foreach (var client in connections.Values)
                    {
                        if (client.Lifetime.IsCancellationRequested) continue;
                        if (client.Identity is null)
                        {
                            if ((now - client.Connected).TotalSeconds >= options.RegistrationTimeoutSeconds) client.Close();
                        }
                        else if (!await Refresh(client)) continue;
                        else if (client.PendingPing is not null)
                        {
                            if ((now - client.PingSent).TotalSeconds >= options.PingTimeoutSeconds) client.Close();
                        }
                        else if ((now - client.LastReceived).TotalSeconds >= options.PingIntervalSeconds)
                        {
                            if (!await Refresh(client)) continue;
                            client.PendingPing = Guid.NewGuid().ToString("N"); client.PingSent = now;
                            client.Send($"PING :{client.PendingPing}");
                        }
                    }
                }
                finally { gate.Release(); }
            }
        }
        catch (OperationCanceledException) when (cancellationToken.IsCancellationRequested) { }
    }

    private async Task<bool> Refresh(Connection client)
    {
        if (client.Identity is not { } old || client.Lifetime.IsCancellationRequested) return false;
        var current = await store.Project(s => ChatIdentity.FromState(s, old.Id));
        if (current is null || current.Nonce != old.Nonce || current.Name != old.Name)
        { client.Close(); return false; }
        client.Identity = current;
        foreach (var channel in client.Channels.ToArray())
            if (!current.CanJoin(channel)) Part(client, channel, "Membership changed");
        return true;
    }

    private void StopSockets()
    {
        foreach (var listener in listeners) listener.Stop();
        foreach (var client in connections.Values) client.Close();
    }

    public async ValueTask DisposeAsync()
    {
        if (lifetime is null) return;
        await lifetime.CancelAsync();
        StopSockets();
        try { await Task.WhenAll(acceptors); }
        finally
        {
            if (heartbeat is not null) await heartbeat;
            await Task.WhenAll(workers.Values);
            stopRegistration.Dispose(); lifetime.Dispose(); lifetime = null;
        }
    }

    private sealed class Connection(long id, TcpClient socket, IPAddress remote, bool tls, CancellationToken cancellationToken)
    {
        public long Id { get; } = id;
        public TcpClient Socket { get; } = socket;
        public IPAddress Remote { get; } = remote;
        public bool Tls { get; } = tls;
        public uint Challenge { get; } = (uint)System.Security.Cryptography.RandomNumberGenerator.GetInt32(int.MaxValue);
        public CancellationTokenSource Lifetime { get; } = CancellationTokenSource.CreateLinkedTokenSource(cancellationToken);
        public Channel<string> Outgoing { get; } = Channel.CreateBounded<string>(new BoundedChannelOptions(256) { SingleReader = true, FullMode = BoundedChannelFullMode.Wait });
        public DateTimeOffset Connected { get; } = DateTimeOffset.UtcNow;
        public DateTimeOffset LastReceived { get; set; } = DateTimeOffset.UtcNow;
        public DateTimeOffset WindowStarted { get; set; } = DateTimeOffset.UtcNow;
        public int WindowCommands { get; set; }
        public DateTimeOffset PingSent { get; set; }
        public string? PendingPing { get; set; }
        public string? RequestedNick { get; set; }
        public string? AccountId { get; set; }
        public string? Credential { get; set; }
        public ChatIdentity? Identity { get; set; }
        public bool Verified { get; set; }
        public bool PlatformSuffix => RequestedNick is { Length: > 0 } nick && nick[^1] is >= '\ue000' and <= '\ue005';
        public string? Away { get; set; }
        public HashSet<string> Channels { get; } = new(StringComparer.OrdinalIgnoreCase);
        public void Send(string line) { if (!Outgoing.Writer.TryWrite(line)) Close(); }
        public void Close()
        {
            try { Lifetime.Cancel(); } catch (ObjectDisposedException) { }
            Socket.Dispose();
        }
    }

    private sealed class ChatChannel(string name)
    {
        public string Name { get; } = name;
        public string Topic { get; set; } = "";
        public HashSet<Connection> Members { get; } = [];
    }
}