using System; using System.Buffers; using System.Collections.Generic; using System.IO; using System.Linq; using System.Net; using System.Net.Sockets; using System.Runtime.InteropServices; using System.Text; using System.Threading; using System.Threading.Tasks; class Program { static string USER = "user"; static string PASS = "pass"; static long _connectionSeq; static async Task Main() { int port = 8888; RegisterGlobalExceptionHandlers(); Log.Info("=== LOCAL PROXY ==="); Log.Info($"http://127.0.0.1:{port}"); Log.Info($"login: {USER}"); Log.Info($"pass : {PASS}"); var listener = new TcpListener(IPAddress.Any, port); listener.Start(); Log.Info($"Listening on {listener.LocalEndpoint}"); while (true) { try { var client = await listener.AcceptTcpClientAsync(); var connectionId = Interlocked.Increment(ref _connectionSeq); Log.Info($"[conn:{connectionId}] accepted from {client.Client.RemoteEndPoint}"); _ = Task.Run(() => HandleClient(client, connectionId)); } catch (Exception ex) { Log.Error("AcceptTcpClientAsync failed", ex); } } } static void RegisterGlobalExceptionHandlers() { AppDomain.CurrentDomain.UnhandledException += (_, args) => Log.Error("Unhandled exception", args.ExceptionObject as Exception); TaskScheduler.UnobservedTaskException += (_, args) => { Log.Error("Unobserved task exception", args.Exception); args.SetObserved(); }; } static async Task HandleClient(TcpClient client, long connectionId) { using (client) { try { var stream = client.GetStream(); var request = await ReadHeaders(stream, $"conn:{connectionId} client-request"); if (request == null) { Log.Warn($"[conn:{connectionId}] empty or invalid request"); return; } Log.Info($"[conn:{connectionId}] {request.Method} {request.Target}"); if (!CheckAuth(request.Raw)) { Log.Warn($"[conn:{connectionId}] proxy auth failed"); await Write407(stream); return; } if (request.Method == "CONNECT") await HandleConnect(stream, request.Target, connectionId); else await HandleHttp(stream, request, connectionId); } catch (Exception ex) { Log.Error($"[conn:{connectionId}] client handling failed", ex); } finally { Log.Info($"[conn:{connectionId}] closed"); } } } // ================= HTTP ================= static async Task HandleHttp(NetworkStream clientStream, HttpRequest req, long connectionId) { var proxyUri = WinHttpHelper.GetProxyForUrl(new Uri(req.Url)); Log.Info($"[conn:{connectionId}] HTTP upstream {proxyUri.Host}:{proxyUri.Port} for {req.Url}"); using var upstream = new TcpClient(); await upstream.ConnectAsync(proxyUri.Host, proxyUri.Port); var upstreamStream = upstream.GetStream(); await upstreamStream.WriteAsync(req.RawBytes); await Pump(upstreamStream, clientStream, $"conn:{connectionId} HTTP upstream->client"); } // ================= CONNECT ================= static async Task HandleConnect(NetworkStream clientStream, string target, long connectionId) { var parts = target.Split(':'); if (parts.Length != 2 || !int.TryParse(parts[1], out int port)) { Log.Error($"[conn:{connectionId}] invalid CONNECT target: {target}"); await clientStream.WriteAsync(Encoding.ASCII.GetBytes("HTTP/1.1 400 Bad Request\r\n\r\n")); return; } string host = parts[0]; var proxyUri = WinHttpHelper.GetProxyForUrl(new Uri($"https://{host}:{port}")); Log.Info($"[conn:{connectionId}] CONNECT {host}:{port} via {proxyUri.Host}:{proxyUri.Port}"); using var upstream = new TcpClient(); await upstream.ConnectAsync(proxyUri.Host, proxyUri.Port); var upstreamStream = upstream.GetStream(); string connectReq = $"CONNECT {host}:{port} HTTP/1.1\r\nHost: {host}:{port}\r\n\r\n"; await upstreamStream.WriteAsync(Encoding.ASCII.GetBytes(connectReq)); var resp = await ReadHeaders(upstreamStream, $"conn:{connectionId} upstream-connect-response"); if (resp == null || !resp.Raw.Contains("200")) { Log.Error($"[conn:{connectionId}] upstream CONNECT rejected"); await clientStream.WriteAsync(Encoding.ASCII.GetBytes("HTTP/1.1 502 Bad Gateway\r\n\r\n")); return; } await clientStream.WriteAsync(Encoding.ASCII.GetBytes("HTTP/1.1 200 Connection Established\r\n\r\n")); var t1 = Pump(upstreamStream, clientStream, $"conn:{connectionId} tunnel upstream->client"); var t2 = Pump(clientStream, upstreamStream, $"conn:{connectionId} tunnel client->upstream"); await Task.WhenAny(t1, t2); } // ================= AUTH ================= static bool CheckAuth(string raw) { string expected = Convert.ToBase64String(Encoding.ASCII.GetBytes($"{USER}:{PASS}")); return raw.Contains($"Proxy-Authorization: Basic {expected}"); } static async Task Write407(NetworkStream stream) { string resp = "HTTP/1.1 407 Proxy Authentication Required\r\n" + "Proxy-Authenticate: Basic realm=\"proxy\"\r\n\r\n"; await stream.WriteAsync(Encoding.ASCII.GetBytes(resp)); } // ================= PARSER ================= class HttpRequest { public string Method; public string Target; public string Url; public string Raw; public byte[] RawBytes; } static async Task ReadHeaders(Stream stream, string context) { try { var buffer = new byte[8192]; int read = await stream.ReadAsync(buffer); if (read <= 0) return null; string raw = Encoding.ASCII.GetString(buffer, 0, read); var lines = raw.Split("\r\n"); var first = lines[0].Split(' ', StringSplitOptions.RemoveEmptyEntries); if (first.Length < 2) { Log.Error($"[{context}] invalid request line: {lines[0]}"); return null; } var req = new HttpRequest { Method = first[0], Target = first[1], Raw = raw, RawBytes = buffer.Take(read).ToArray() }; if (req.Method != "CONNECT") { string host = lines .FirstOrDefault(l => l.StartsWith("Host:", StringComparison.OrdinalIgnoreCase)) ?.Split(':', 2)[1] .Trim(); req.Url = req.Target.StartsWith("http", StringComparison.OrdinalIgnoreCase) ? req.Target : $"http://{host}{req.Target}"; } return req; } catch (Exception ex) { Log.Error($"[{context}] failed to read/parse headers", ex); return null; } } // ================= STREAM ================= static async Task Pump(Stream from, Stream to, string context) { var buffer = ArrayPool.Shared.Rent(8192); try { while (true) { int read = await from.ReadAsync(buffer); if (read <= 0) break; await to.WriteAsync(buffer.AsMemory(0, read)); } } catch (Exception ex) { Log.Error($"[{context}] stream pump failed", ex); } finally { ArrayPool.Shared.Return(buffer); } } } // ================= WINHTTP ================= static class WinHttpHelper { [DllImport("winhttp.dll", SetLastError = true)] static extern IntPtr WinHttpOpen(string agent, int accessType, string proxy, string bypass, int flags); [DllImport("winhttp.dll", SetLastError = true)] static extern bool WinHttpGetProxyForUrl( IntPtr hSession, string url, ref WINHTTP_AUTOPROXY_OPTIONS options, out WINHTTP_PROXY_INFO proxyInfo); [DllImport("winhttp.dll")] static extern bool WinHttpCloseHandle(IntPtr handle); public static Uri GetProxyForUrl(Uri url) { IntPtr session = WinHttpOpen("proxy", 0, null, null, 0); if (session == IntPtr.Zero) { Log.Error("WinHttpOpen failed"); return url; } var options = new WINHTTP_AUTOPROXY_OPTIONS { dwFlags = 0x00000001 | 0x00000002, dwAutoDetectFlags = 0x00000001 | 0x00000002 }; if (WinHttpGetProxyForUrl(session, url.ToString(), ref options, out var info)) { string proxy = PtrToString(info.lpszProxy); if (!string.IsNullOrEmpty(proxy)) { var first = proxy.Split(';')[0]; WinHttpCloseHandle(session); return new Uri(Normalize(first)); } } else { Log.Error($"WinHttpGetProxyForUrl failed for {url} (Win32={Marshal.GetLastWin32Error()})"); } WinHttpCloseHandle(session); return url; } static string PtrToString(IntPtr ptr) { if (ptr == IntPtr.Zero) return null; return Marshal.PtrToStringUni(ptr); } static string Normalize(string proxy) { if (!proxy.StartsWith("http")) return "http://" + proxy; return proxy; } struct WINHTTP_AUTOPROXY_OPTIONS { public int dwFlags; public int dwAutoDetectFlags; public IntPtr lpszAutoConfigUrl; public IntPtr lpvReserved; public int dwReserved; public bool fAutoLogonIfChallenged; } struct WINHTTP_PROXY_INFO { public int dwAccessType; public IntPtr lpszProxy; public IntPtr lpszProxyBypass; } } static class Log { static readonly object _sync = new(); public static void Info(string message) => Write("INF", message); public static void Warn(string message) => Write("WRN", message); public static void Error(string message, Exception ex = null) { Write("ERR", ex == null ? message : $"{message}{Environment.NewLine}{ex}"); } static void Write(string level, string message) { lock (_sync) { Console.WriteLine($"[{DateTime.Now:yyyy-MM-dd HH:mm:ss.fff}] [{level}] {message}"); } } }