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

LumaTunnel

【WinUI】LumaTunnel 是一个面向个人多设备的 Windows 代理系统。客户端在本机提供 HTTP/HTTPS CONNECT 与 SOCKS5 TCP 代理,并通过一个受信任 TLS 证书保护的 WSS 会话,将多个 TCP 流复用到自建 Windows Server 节点。

公开
关注 0 Fork 0 Star 0
UTF-8
using System.Collections.Concurrent;
using System.Net.WebSockets;
using XFEExtension.NetCore.CyberComm;

namespace LumaTunnel.Server.Core.Runtime;

public sealed class TunnelConnectionManager : IAsyncDisposable
{
    private readonly ConcurrentDictionary<WebSocket, TunnelConnection> _connections = new();
    private readonly ServerRuntime _runtime;

    public TunnelConnectionManager(ServerRuntime runtime)
    {
        _runtime = runtime;
        runtime.Devices.DeviceRevoked += OnDeviceRevoked;
    }

    public int Count => _connections.Count;

    public bool TryAccept(CyberCommServerEventArgs args)
    {
        var path = args.RequestUrl?.AbsolutePath.TrimEnd('/');
        if (!string.Equals(path, "/tunnel/v1", StringComparison.OrdinalIgnoreCase))
            return false;

        var deviceId = args.WSHeader["X-Luma-Device-Id"];
        var authorization = args.WSHeader["Authorization"];
        var token = authorization?.StartsWith("Bearer ", StringComparison.OrdinalIgnoreCase) == true
            ? authorization[7..].Trim()
            : string.Empty;
        var requestedProtocol = args.WSHeader["Sec-WebSocket-Protocol"];

        if (string.IsNullOrWhiteSpace(deviceId)
            || !_runtime.Devices.Validate(deviceId, token, out _)
            || string.IsNullOrWhiteSpace(requestedProtocol)
            || !requestedProtocol.Split(',').Any(static protocol => protocol.Trim().Equals("lumatunnel.v1", StringComparison.Ordinal)))
        {
            _ = CloseSocketAsync(args.CurrentWebSocket, WebSocketCloseStatus.PolicyViolation, "Unauthorized tunnel client.");
            return true;
        }

        var connection = new TunnelConnection(args.CurrentWebSocket, deviceId, _runtime, OnConnectionTerminated);
        if (!_connections.TryAdd(args.CurrentWebSocket, connection))
        {
            _ = connection.DisposeAsync().AsTask();
            return true;
        }

        connection.Start();
        return true;
    }

    public void Receive(CyberCommServerEventArgs args)
    {
        if (!_connections.TryGetValue(args.CurrentWebSocket, out var connection))
            return;

        if (args.BinaryMessage is not { Length: > 0 } bytes || !connection.TryEnqueue(bytes))
            _ = connection.CloseAsync(WebSocketCloseStatus.InvalidPayloadData, "Invalid or overloaded tunnel frame.");
    }

    public void Closed(CyberCommServerEventArgs args)
    {
        if (_connections.TryRemove(args.CurrentWebSocket, out var connection))
            _ = connection.DisposeAsync().AsTask();
    }

    public async ValueTask DisposeAsync()
    {
        _runtime.Devices.DeviceRevoked -= OnDeviceRevoked;
        var connections = _connections.Values.ToArray();
        _connections.Clear();
        await Task.WhenAll(connections.Select(static connection => connection.CloseAsync(WebSocketCloseStatus.EndpointUnavailable, "Server is shutting down."))).ConfigureAwait(false);
    }

    private void OnDeviceRevoked(string deviceId)
    {
        foreach (var connection in _connections.Values.Where(connection => connection.DeviceId == deviceId))
            _ = connection.CloseAsync(WebSocketCloseStatus.PolicyViolation, "Device was revoked.");
    }

    private void OnConnectionTerminated(TunnelConnection connection) => _connections.TryRemove(connection.WebSocket, out _);

    private static async Task CloseSocketAsync(WebSocket socket, WebSocketCloseStatus status, string description)
    {
        try
        {
            if (socket.State is WebSocketState.Open or WebSocketState.CloseReceived)
                await socket.CloseAsync(status, description, CancellationToken.None).ConfigureAwait(false);
        }
        catch (WebSocketException)
        {
            socket.Abort();
        }
    }
}