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 _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(); } } }