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

XFESystem

【Rust】XFE系统,基于Rust和汇编

公开
关注 0 Fork 0 Star 0
UTF-8
using System.Globalization;
using System.Net;
using System.Text;
using Org.BouncyCastle.Crypto.Digests;
using XFESystem.Browser;
using XFESystem.NativeRuntime.Application.Network;
using XFESystem.NativeRuntime.Application.Security;
using XFESystem.Tls;
using WebResponse = XFESystem.Browser.WebResponse;

namespace XFESystem.NativeRuntime.Application.Web;

/// <summary>Guest e1000/TCP plus managed TLS. No host socket, proxy, cache or certificate bypass.</summary>
internal sealed class NativeWebTransport : IWebRequestTransport, IWebTransportCapabilities, IWebCookieStore, IBrowserRandomSource
{
    private static readonly object gate = new();
    private static TlsCertificateValidator? certificates;
    private static int requestId;
    private static readonly NativeHttpConnectionPool connections = new();
    private static readonly BrowserCookieStore cookies = new();
    public string ReadDocumentCookies(Uri address) => cookies.ReadDocumentCookies(address);
    public void WriteDocumentCookie(Uri address, string value) => cookies.WriteDocumentCookie(address, value);
    public bool IsNative => true;
    public bool SupportsHttp => true;
    public bool SupportsHttps => true;
    public void FillRandom(Span<byte> bytes) => NativeTlsSecurity.Fill(bytes);

    internal NativeWebTransport() => NativeNetwork.ConfigureEntropy(NativeTlsSecurity.Random32);

    private static TlsCertificateValidator Roots()
    {
        if (certificates is not null) return certificates;
        long started = NativePlatform.Milliseconds();
        NativePlatform.Write("XFE_NATIVE_TLS_TRUST_IMPORT_BEGIN\n");
        using var stream = typeof(NativeWebTransport).Assembly.GetManifestResourceStream("Security/MozillaRoots.pem")
            ?? throw new IOException("The explicit trusted root snapshot is missing.");
        using var reader = new StreamReader(stream, Encoding.ASCII);
        certificates = TlsCertificateValidator.FromPem(reader.ReadToEnd());
        NativePlatform.Write("XFE_NATIVE_TLS_PREREQUISITES|Clock|CMOS_UTC|EntropyCapabilities|" + NativeTlsSecurity.Capabilities +
            "|RootSnapshot|Mozilla20260925|HostCertificateStore|0|ImportMilliseconds|" + (NativePlatform.Milliseconds() - started) + "\n");
        return certificates;
    }

    public WebResponse Get(Uri address, BrowserLimits limits) => GetWithHeaders(address, limits, null);
    public WebResponse Get(Uri address, BrowserLimits limits, IReadOnlyDictionary<string, string> headers) => GetWithHeaders(address, limits, BrowserRequestHeaders.Copy(headers));
    private static WebResponse GetWithHeaders(Uri address, BrowserLimits limits, IReadOnlyDictionary<string, string>? additionalHeaders)
    {
        try { return GetCore(address, limits, additionalHeaders); }
        catch (Exception error) when (error is not OutOfMemoryException and not StackOverflowException)
        {
            var details = new StringBuilder();
            for (Exception? current = error; current is not null && details.Length < 8192; current = current.InnerException)
                details.Append(current.GetType().FullName).Append(": ").Append(current.Message).Append('\n').Append(current.StackTrace).Append('\n');
            NativePlatform.Write("XFE_NATIVE_WEB_ERROR_BEGIN\n" + details + "XFE_NATIVE_WEB_ERROR_END\n");
            throw;
        }
    }

    private static WebResponse GetCore(Uri address, BrowserLimits limits, IReadOnlyDictionary<string, string>? additionalHeaders)
    {
        ArgumentNullException.ThrowIfNull(address); ArgumentNullException.ThrowIfNull(limits);
        if (limits.NetworkTimeout <= TimeSpan.Zero || limits.NetworkTimeout > TimeSpan.FromMinutes(2))
            throw new ArgumentOutOfRangeException(nameof(limits));
        long deadline = checked(NativePlatform.Milliseconds() + (long)limits.NetworkTimeout.TotalMilliseconds);
        if (!Monitor.TryEnter(gate, Remaining(deadline))) throw new TimeoutException("The native web transport ownership deadline expired.");
        try
        {
            Uri target = address;
            for (int redirects = 0; ; redirects++)
            {
                ValidateAddress(target);
                int id = ++requestId;
                string host = target.IdnHost;
                string authority = target.IsDefaultPort ? host : host + ":" + target.Port.ToString(CultureInfo.InvariantCulture);
                string headers = "GET " + target.PathAndQuery + " HTTP/1.1\r\nHost: " + authority +
                    "\r\nUser-Agent: " + BrowserIdentity.UserAgent + "\r\n" +
                    (additionalHeaders?.ContainsKey("accept") == true ? "" : "Accept: text/html,application/xhtml+xml,text/css,application/javascript,text/plain,*/*;q=0.5\r\n") +
                    (additionalHeaders?.ContainsKey("accept-language") == true ? "" : "Accept-Language: zh-CN,zh;q=0.9,en;q=0.8\r\n") + "Accept-Encoding: identity\r\n" +
                    (additionalHeaders is null ? "" : string.Concat(additionalHeaders.Select(field => field.Key + ": " + field.Value + "\r\n"))) +
                    (cookies.RequestHeader(target) is { Length: > 0 } cookie ? "Cookie: " + cookie + "\r\n" : "") + "Connection: keep-alive\r\n\r\n";
                NativePlatform.Write("XFE_NATIVE_WEB_REQUEST|" + id + "|" + target.AbsoluteUri + "\n");
                long started = NativePlatform.Milliseconds();
                var (response, verified, protocol, reused) = Request(target, headers, limits, deadline);
                foreach (string cookieHeader in response.SetCookies) cookies.Receive(target, cookieHeader);
                bool binary = response.ContentType.StartsWith("image/", StringComparison.OrdinalIgnoreCase);
                string body = binary ? "" : NativeHttpProtocol.DecodeBody(response);
                if (body.Length > limits.MaximumHtmlCharacters) throw new BrowserLimitException("The decoded response exceeds its character limit.");
                NativePlatform.Write("XFE_NATIVE_WEB_TIMING|RequestId|" + id + "|TotalMilliseconds|" +
                    (NativePlatform.Milliseconds() - started) + "|ConnectionReused|" + (reused ? 1 : 0) + "\n");
                EmitResponse(id, target, headers, response, body, verified, protocol);
                if (response.StatusCode is 301 or 302 or 303 or 307 or 308)
                {
                    if (redirects >= limits.MaximumRedirects) throw new IOException("The HTTP redirect limit was reached.");
                    if (string.IsNullOrWhiteSpace(response.Location) || !Uri.TryCreate(target, response.Location, out var next))
                        throw new IOException("The redirect Location is invalid.");
                    ValidateAddress(next);
                    if (additionalHeaders is not null && next.GetLeftPart(UriPartial.Authority) != address.GetLeftPart(UriPartial.Authority))
                        throw new NotSupportedException("Cross-origin script redirects require CORS support.");
                    if (target.Scheme == "https" && next.Scheme != "https") throw new IOException("HTTPS redirects cannot downgrade to HTTP.");
                    target = next; continue;
                }
                return new(target, response.StatusCode, response.ContentType, body, verified, response.ContentSecurityPolicy, Hash(body), binary ? response.Body : null,
                    response.Headers.TryGetValue("x-content-type-options", out var sniff) && sniff.Split(',')[0].Trim().Equals("nosniff", StringComparison.OrdinalIgnoreCase));
            }
        }
        finally { Monitor.Exit(gate); }
    }

    private static NativeHttpConnectionPool.Connection OpenConnection(Uri target, long deadline)
    {
        Stream tcp = NativeNetwork.OpenTcp(target.IdnHost, target.Port, Remaining(deadline));
        var bounded = new DeadlineStream(tcp, deadline);
        TlsClientConnection? tls = null;
        try
        {
            long started = NativePlatform.Milliseconds();
            if (target.Scheme == "https")
            {
                tls = new(bounded, target.IdnHost, Roots(), NativeTlsSecurity.Context);
                NativePlatform.Write("XFE_NATIVE_TLS_CONNECTED|Host|" + target.IdnHost + "|Verified|" +
                    (tls.CertificateValidated ? 1 : 0) + "|Protocol|" + tls.Protocol +
                    "|InitializationAndHandshakeMilliseconds|" + (NativePlatform.Milliseconds() - started) + "\n");
            }
            return new(target, tls?.Stream ?? bounded, bounded.SetDeadline, () =>
            {
                // Closing has the TCP stream's own finite close budget. A stale
                // HTTP deadline must not stop owner/resource cleanup.
                try { tls?.Dispose(); } finally { tcp.Dispose(); }
            }, tls?.CertificateValidated == true, tls?.Protocol ?? "HTTP");
        }
        catch { try { tls?.Dispose(); } finally { tcp.Dispose(); } throw; }
    }

    private static (NativeHttpResponse Response, bool Verified, string Protocol, bool Reused) Request(
        Uri target, string headers, BrowserLimits limits, long deadline)
    {
        byte[] request = Encoding.Latin1.GetBytes(headers);
        for (int attempt = 0; ; attempt++)
        {
            var connection = connections.Take(target, NativePlatform.Milliseconds(), deadline, () => OpenConnection(target, deadline), out bool reused);
            long received = 0;
            try
            {
                connection.Wire.Write(request, 0, request.Length); connection.Wire.Flush();
                var response = NativeHttpProtocol.ReadResponse((buffer, offset, count) =>
                {
                    int read = connection.Wire.Read(buffer, offset, count); received += read; return read;
                }, checked(limits.MaximumHtmlCharacters * 4));
                connections.Return(connection, response.CanReuseConnection, NativePlatform.Milliseconds());
                return (response, connection.CertificateValidated, connection.Protocol, reused);
            }
            catch (IOException) when (reused && attempt == 0 && received == 0 && NativePlatform.Milliseconds() < deadline)
            {
                // One idempotent GET retry for a silently closed idle socket.
                // Partial/malformed responses and fresh failures are not retried.
                connection.Close();
            }
            catch { connection.Close(); throw; }
        }
    }

    private static int Remaining(long deadline)
    {
        long remaining = deadline - NativePlatform.Milliseconds();
        if (remaining <= 0) throw new TimeoutException("The native web request deadline expired.");
        return (int)Math.Min(remaining, int.MaxValue);
    }
    private static void ValidateAddress(Uri address)
    {
        if (!address.IsAbsoluteUri || address.Scheme is not ("http" or "https") ||
            string.IsNullOrEmpty(address.Host) || !string.IsNullOrEmpty(address.UserInfo))
            throw new NotSupportedException("Only HTTP and HTTPS URLs without embedded credentials are supported.");
    }
    private static string Hash(string body) => Hash(Encoding.UTF8.GetBytes(body));
    private static string Hash(byte[] bytes)
    {
        byte[] digest = new byte[32];
        var sha = new Sha256Digest(); sha.BlockUpdate(bytes, 0, bytes.Length); sha.DoFinal(digest, 0);
        return Convert.ToHexString(digest).ToLowerInvariant();
    }
    internal static string Quote(string? value)
    {
        if (value is null) return "null";
        var builder = new StringBuilder("\"");
        foreach (char c in value)
            if (c is '\\' or '"') builder.Append('\\').Append(c);
            else if (c < 32) builder.Append("\\u").Append(((int)c).ToString("x4", CultureInfo.InvariantCulture));
            else builder.Append(c);
        return builder.Append('"').ToString();
    }
    private static void EmitResponse(int id, Uri address, string requestHeaders, NativeHttpResponse response, string body, bool verified, string protocol)
    {
        string title = ""; int start = body.IndexOf("<title", StringComparison.OrdinalIgnoreCase);
        if (start >= 0 && (start = body.IndexOf('>', start)) >= 0)
        { int end = body.IndexOf("</title", start, StringComparison.OrdinalIgnoreCase); if (end > start) title = WebUtility.HtmlDecode(body.Substring(start + 1, Math.Min(512, end - start - 1))); }
        string responseHeaders = response.StatusLine + "\r\n" + string.Join("\r\n", response.Headers.Select(pair => pair.Key + ": " + pair.Value));
        string json = "{\"Kind\":\"ActualGuestWebResponse\",\"RequestId\":" + id + ",\"RequestUri\":" + Quote(address.AbsoluteUri) +
            ",\"ResponseUri\":" + Quote(address.AbsoluteUri) + ",\"StatusCode\":" + response.StatusCode + ",\"ContentType\":" + Quote(response.ContentType) +
            ",\"CertificateValidated\":" + (verified ? "true" : "false") + ",\"NativeTransport\":true,\"Protocol\":" + Quote(protocol) +
            ",\"RequestHeaders\":" + Quote(NativeHttpProtocol.RedactSensitiveHeaders(requestHeaders)) + ",\"ResponseHeaders\":" + Quote(NativeHttpProtocol.RedactSensitiveHeaders(responseHeaders)) +
            ",\"SensitiveHeaderValuesRedacted\":true" +
            ",\"BodyBytes\":" + response.Body.Length + ",\"BodySha256\":" + Quote(Hash(body)) +
            ",\"RawBodySha256\":" + Quote(Hash(response.Body)) +
            ",\"BodyHashMeaning\":\"UTF8 of decoded HTML/text\",\"HtmlTitle\":" + Quote(title) +
            ",\"HasHtml\":" + (body.Contains("<html", StringComparison.OrdinalIgnoreCase) ? "true" : "false") +
            ",\"HasHead\":" + (body.Contains("<head", StringComparison.OrdinalIgnoreCase) ? "true" : "false") +
            ",\"Location\":" + Quote(response.Location) + "}";
        NativePlatform.Write("XFE_NATIVE_WEB_RESPONSE_BEGIN\n" + json + "\nXFE_NATIVE_WEB_RESPONSE_END\n");
    }

    private sealed class DeadlineStream(Stream inner, long deadline) : Stream
    {
        private long deadlineMilliseconds = deadline;
        public void SetDeadline(long value) => deadlineMilliseconds = value;
        public override bool CanRead => true; public override bool CanWrite => true; public override bool CanSeek => false;
        public override long Length => throw new NotSupportedException();
        public override long Position { get => throw new NotSupportedException(); set => throw new NotSupportedException(); }
        private void Check()
        {
            int left = Remaining(deadlineMilliseconds);
            if (!inner.CanTimeout) throw new IOException("The native TCP stream cannot enforce bounded web I/O.");
            inner.ReadTimeout = left; inner.WriteTimeout = left;
        }
        public override int Read(byte[] buffer, int offset, int count) { Check(); int read = inner.Read(buffer, offset, count); Check(); return read; }
        public override int Read(Span<byte> buffer) { Check(); int read = inner.Read(buffer); Check(); return read; }
        public override void Write(byte[] buffer, int offset, int count) { Check(); inner.Write(buffer, offset, count); Check(); }
        public override void Write(ReadOnlySpan<byte> buffer) { Check(); inner.Write(buffer); Check(); }
        public override void Flush() { Check(); inner.Flush(); }
        public override long Seek(long offset, SeekOrigin origin) => throw new NotSupportedException();
        public override void SetLength(long value) => throw new NotSupportedException();
    }
}