using System.Net; using System.Net.Sockets; namespace UCVL.VPNPlus; // Management sockets connect to Qingdao directly. The HTTPS authority remains // the platform hostname for SNI, virtual hosting and certificate validation. internal static class PlatformBootstrapTransport { internal const string Host = "vpn.ucvl.cn"; internal static readonly IPAddress ManagementAddress = IPAddress.Parse("47.104.134.190"); internal static SocketsHttpHandler CreateHandler() => new() { UseProxy = false, UseCookies = false, AllowAutoRedirect = false, ConnectTimeout = TimeSpan.FromSeconds(10), AutomaticDecompression = DecompressionMethods.All, ConnectCallback = (context, token) => { ValidateRequest(context.InitialRequestMessage.RequestUri!, context.InitialRequestMessage.Headers.Host); return ConnectAsync(context.DnsEndPoint, token, OpenSocketAsync); }, }; internal static void ValidateRequest(Uri uri, string? hostHeader = null) { if (!uri.IsAbsoluteUri || uri.Scheme != Uri.UriSchemeHttps || uri.Port != 443 || !string.Equals(uri.Host, Host, StringComparison.OrdinalIgnoreCase) || uri.UserInfo.Length != 0 || (hostHeader is not null && !string.Equals(hostHeader, Host, StringComparison.OrdinalIgnoreCase) && !string.Equals(hostHeader, Host + ":443", StringComparison.OrdinalIgnoreCase))) throw new InvalidOperationException("管理接口地址不在允许范围内。"); } internal static ValueTask ConnectAsync(DnsEndPoint endpoint, CancellationToken token, Func> connect) { if (!string.Equals(endpoint.Host, Host, StringComparison.OrdinalIgnoreCase) || endpoint.Port != 443) throw new InvalidOperationException("管理接口连接目标不在允许范围内。"); token.ThrowIfCancellationRequested(); return connect(ManagementAddress, endpoint.Port, token); } private static async ValueTask OpenSocketAsync(IPAddress address, int port, CancellationToken token) { var socket = new Socket(address.AddressFamily, SocketType.Stream, ProtocolType.Tcp); try { socket.NoDelay = true; await socket.ConnectAsync(new IPEndPoint(address, port), token).ConfigureAwait(false); token.ThrowIfCancellationRequested(); return new NetworkStream(socket, ownsSocket: true); } catch { socket.Dispose(); throw; } } }