using System.Collections.Concurrent; using System.Net; using System.Net.Sockets; using LumaTunnel.Client.Core.Abstractions; using LumaTunnel.Shared.Models; namespace LumaTunnel.Client.Core.Proxy; public sealed class ProxyEngineService( IRoutingService routing, IProxyConnector directConnector, ITunnelService tunnelService) : IProxyEngineService { private readonly ConcurrentDictionary _connections = new(); private readonly SemaphoreSlim _lifecycleGate = new(1, 1); private CancellationTokenSource? _cancellation; private TcpListener? _httpListener; private TcpListener? _socksListener; private Task? _httpTask; private Task? _socksTask; public bool IsRunning => _cancellation is { IsCancellationRequested: false }; public IReadOnlyCollection Connections => _connections.Values.Select(static item => item.Snapshot()).ToArray(); public event EventHandler? ConnectionsChanged; public async Task StartAsync(ProxyEngineOptions options, CancellationToken cancellationToken = default) { ArgumentNullException.ThrowIfNull(options); if (!IPAddress.IsLoopback(options.ListenAddress)) throw new InvalidOperationException("LumaTunnel local proxy listeners may only bind to a loopback address."); await _lifecycleGate.WaitAsync(cancellationToken).ConfigureAwait(false); try { if (IsRunning) return; routing.Mode = options.Mode; var cancellation = new CancellationTokenSource(); var http = new TcpListener(options.ListenAddress, options.HttpPort); var socks = new TcpListener(options.ListenAddress, options.SocksPort); try { http.Start(128); socks.Start(128); } catch { http.Stop(); socks.Stop(); cancellation.Dispose(); throw; } _cancellation = cancellation; _httpListener = http; _socksListener = socks; _httpTask = AcceptLoopAsync(http, "HTTP", HandleHttpClientAsync, cancellation.Token); _socksTask = AcceptLoopAsync(socks, "SOCKS5", HandleSocksClientAsync, cancellation.Token); } finally { _lifecycleGate.Release(); } } public async Task StopAsync(CancellationToken cancellationToken = default) { await _lifecycleGate.WaitAsync(cancellationToken).ConfigureAwait(false); try { var cancellation = _cancellation; _cancellation = null; if (cancellation is null) return; cancellation.Cancel(); _httpListener?.Stop(); _socksListener?.Stop(); var loops = new[] { _httpTask, _socksTask }.Where(static task => task is not null).Cast(); await Task.WhenAny(Task.WhenAll(loops), Task.Delay(TimeSpan.FromSeconds(2), cancellationToken)).ConfigureAwait(false); cancellation.Dispose(); } finally { _lifecycleGate.Release(); } } public async ValueTask DisposeAsync() { await StopAsync().ConfigureAwait(false); _lifecycleGate.Dispose(); GC.SuppressFinalize(this); } private static async Task AcceptLoopAsync(TcpListener listener, string protocol, Func handler, CancellationToken cancellationToken) { while (!cancellationToken.IsCancellationRequested) { try { var client = await listener.AcceptTcpClientAsync(cancellationToken).ConfigureAwait(false); client.NoDelay = true; _ = RunClientAsync(client, protocol, handler, cancellationToken); } catch (OperationCanceledException) when (cancellationToken.IsCancellationRequested) { break; } catch (SocketException) when (cancellationToken.IsCancellationRequested) { break; } } } private static async Task RunClientAsync(TcpClient client, string protocol, Func handler, CancellationToken cancellationToken) { using (client) { try { await handler(client, cancellationToken).ConfigureAwait(false); } catch (OperationCanceledException) when (cancellationToken.IsCancellationRequested) { } catch (IOException) { } catch (SocketException) { } } } private async Task HandleHttpClientAsync(TcpClient client, CancellationToken cancellationToken) { var clientStream = client.GetStream(); var request = await HttpProxyParser.ReadRequestAsync(clientStream, cancellationToken).ConfigureAwait(false); if (request is null) return; ProxyTarget target; if (request.IsConnect) { if (!HttpProxyParser.TryParseAuthority(request.RequestTarget, 443, out target)) { await HttpProxyParser.WriteErrorAsync(clientStream, 400, "Bad Request", cancellationToken).ConfigureAwait(false); return; } } else if (Uri.TryCreate(request.RequestTarget, UriKind.Absolute, out var absoluteUri) && absoluteUri.Scheme is "http" or "https") { target = new ProxyTarget(absoluteUri.Host, absoluteUri.IsDefaultPort ? (absoluteUri.Scheme == "https" ? 443 : 80) : absoluteUri.Port); request = request with { RewrittenHeader = HttpProxyParser.RewriteForOrigin(request, absoluteUri) }; } else if (request.Headers.TryGetValue("Host", out var host) && HttpProxyParser.TryParseAuthority(host, 80, out target)) { request = request with { RewrittenHeader = HttpProxyParser.RewriteForOrigin(request, null) }; } else { await HttpProxyParser.WriteErrorAsync(clientStream, 400, "Bad Request", cancellationToken).ConfigureAwait(false); return; } var route = routing.Resolve(target); Stream remote; try { remote = await GetConnector(route).ConnectAsync(target, cancellationToken).ConfigureAwait(false); } catch { await HttpProxyParser.WriteErrorAsync(clientStream, 502, "Bad Gateway", cancellationToken).ConfigureAwait(false); return; } await using (remote.ConfigureAwait(false)) { if (request.IsConnect) await clientStream.WriteAsync("HTTP/1.1 200 Connection Established\r\nProxy-Agent: LumaTunnel/0.1\r\n\r\n"u8.ToArray(), cancellationToken).ConfigureAwait(false); else await remote.WriteAsync(request.RewrittenHeader, cancellationToken).ConfigureAwait(false); if (!request.Remaining.IsEmpty) await remote.WriteAsync(request.Remaining, cancellationToken).ConfigureAwait(false); var connection = AddConnection("HTTP", target, route); try { await ProxyRelay.RunAsync(client, remote, connection.AddUpload, connection.AddDownload, cancellationToken).ConfigureAwait(false); } finally { RemoveConnection(connection.Id); } } } private async Task HandleSocksClientAsync(TcpClient client, CancellationToken cancellationToken) { var stream = client.GetStream(); var target = await Socks5Protocol.NegotiateAsync(stream, cancellationToken).ConfigureAwait(false); if (target is null) return; var route = routing.Resolve(target); Stream remote; try { remote = await GetConnector(route).ConnectAsync(target, cancellationToken).ConfigureAwait(false); } catch { await Socks5Protocol.WriteReplyAsync(stream, 0x05, null, cancellationToken).ConfigureAwait(false); return; } await using (remote.ConfigureAwait(false)) { await Socks5Protocol.WriteReplyAsync(stream, 0x00, client.Client.LocalEndPoint as IPEndPoint, cancellationToken).ConfigureAwait(false); var connection = AddConnection("SOCKS5", target, route); try { await ProxyRelay.RunAsync(client, remote, connection.AddUpload, connection.AddDownload, cancellationToken).ConfigureAwait(false); } finally { RemoveConnection(connection.Id); } } } private IProxyConnector GetConnector(RouteAction action) => action == RouteAction.Direct ? directConnector : (IProxyConnector)tunnelService; private MutableConnection AddConnection(string protocol, ProxyTarget target, RouteAction route) { var item = new MutableConnection(Guid.NewGuid(), protocol, target, route); _connections[item.Id] = item; ConnectionsChanged?.Invoke(this, EventArgs.Empty); return item; } private void RemoveConnection(Guid id) { _connections.TryRemove(id, out _); ConnectionsChanged?.Invoke(this, EventArgs.Empty); } private sealed class MutableConnection(Guid id, string protocol, ProxyTarget target, RouteAction route) { private long _upload; private long _download; public Guid Id { get; } = id; public DateTimeOffset StartedAtUtc { get; } = DateTimeOffset.UtcNow; public void AddUpload(int bytes) => Interlocked.Add(ref _upload, bytes); public void AddDownload(int bytes) => Interlocked.Add(ref _download, bytes); public ProxyConnectionInfo Snapshot() => new(Id, protocol, target, route, StartedAtUtc, Interlocked.Read(ref _upload), Interlocked.Read(ref _download)); } }