| | | 1 | | // Licensed to the .NET Foundation under one or more agreements. |
| | | 2 | | // The .NET Foundation licenses this file to you under the MIT license. |
| | | 3 | | |
| | | 4 | | using System.Collections.Generic; |
| | | 5 | | using System.Diagnostics; |
| | | 6 | | using System.Diagnostics.CodeAnalysis; |
| | | 7 | | using System.IO; |
| | | 8 | | using System.Net.Http.Headers; |
| | | 9 | | using System.Net.Http.HPack; |
| | | 10 | | using System.Net.Http.QPack; |
| | | 11 | | using System.Net.Quic; |
| | | 12 | | using System.Net.Security; |
| | | 13 | | using System.Net.Sockets; |
| | | 14 | | using System.Runtime.CompilerServices; |
| | | 15 | | using System.Runtime.ExceptionServices; |
| | | 16 | | using System.Security.Authentication; |
| | | 17 | | using System.Text; |
| | | 18 | | using System.Threading; |
| | | 19 | | using System.Threading.Tasks; |
| | | 20 | | |
| | | 21 | | namespace System.Net.Http |
| | | 22 | | { |
| | | 23 | | /// <summary>Provides a pool of connections to the same endpoint.</summary> |
| | | 24 | | internal sealed partial class HttpConnectionPool : IDisposable |
| | | 25 | | { |
| | | 26 | | /// <summary>The maximum number of times to retry a request after a failure on an established connection.</summa |
| | | 27 | | private const int MaxConnectionFailureRetries = 3; |
| | | 28 | | public const int DefaultHttpPort = 80; |
| | | 29 | | public const int DefaultHttpsPort = 443; |
| | | 30 | | |
| | 0 | 31 | | private static readonly List<SslApplicationProtocol> s_http3ApplicationProtocols = new List<SslApplicationProtoc |
| | 0 | 32 | | private static readonly List<SslApplicationProtocol> s_http2ApplicationProtocols = new List<SslApplicationProtoc |
| | 0 | 33 | | private static readonly List<SslApplicationProtocol> s_http2OnlyApplicationProtocols = new List<SslApplicationPr |
| | | 34 | | |
| | | 35 | | private readonly HttpConnectionPoolManager _poolManager; |
| | | 36 | | private readonly HttpConnectionKind _kind; |
| | | 37 | | private readonly Uri? _proxyUri; |
| | | 38 | | private readonly string? _telemetryServerAddress; |
| | | 39 | | |
| | | 40 | | /// <summary>The origin authority used to construct the <see cref="HttpConnectionPool"/>.</summary> |
| | | 41 | | private readonly HttpAuthority _originAuthority; |
| | | 42 | | |
| | | 43 | | /// <summary>The User-Agent header to use when creating a CONNECT tunnel.</summary> |
| | | 44 | | private string? _connectTunnelUserAgent; |
| | | 45 | | |
| | | 46 | | // These settings are advertised by the server via SETTINGS_MAX_HEADER_LIST_SIZE and SETTINGS_MAX_FIELD_SECTION_ |
| | | 47 | | // If we had previous connections to the same host in this pool, memorize the last value seen. |
| | | 48 | | // This value is used as an initial value for new connections before they have a chance to observe the SETTINGS |
| | | 49 | | // Doing so avoids immediately exceeding the server limit on the first request, potentially causing the connecti |
| | | 50 | | // 0 means there were no previous connections, or they hadn't advertised this limit. |
| | | 51 | | // There is no need to lock when updating these values - we're only interested in saving _a_ value, not necessar |
| | | 52 | | internal uint _lastSeenHttp2MaxHeaderListSize; |
| | | 53 | | internal uint _lastSeenHttp3MaxHeaderListSize; |
| | | 54 | | |
| | | 55 | | /// <summary>Options specialized and cached for this pool and its key.</summary> |
| | | 56 | | private readonly SslClientAuthenticationOptions? _sslOptionsHttp11; |
| | | 57 | | private readonly SslClientAuthenticationOptions? _sslOptionsHttp2; |
| | | 58 | | private readonly SslClientAuthenticationOptions? _sslOptionsHttp2Only; |
| | | 59 | | private SslClientAuthenticationOptions? _sslOptionsHttp3; |
| | | 60 | | private readonly SslClientAuthenticationOptions? _sslOptionsProxy; |
| | | 61 | | |
| | | 62 | | private readonly PreAuthCredentialCache? _preAuthCredentials; |
| | | 63 | | |
| | | 64 | | /// <summary>Whether the pool has been used since the last time a cleanup occurred.</summary> |
| | 0 | 65 | | private bool _usedSinceLastCleanup = true; |
| | | 66 | | /// <summary>Whether the pool has been disposed.</summary> |
| | | 67 | | private bool _disposed; |
| | | 68 | | |
| | | 69 | | /// <summary>Initializes the pool.</summary> |
| | | 70 | | /// <param name="poolManager">The manager associated with this pool.</param> |
| | | 71 | | /// <param name="kind">The kind of HTTP connections stored in this pool.</param> |
| | | 72 | | /// <param name="host">The host with which this pool is associated.</param> |
| | | 73 | | /// <param name="port">The port with which this pool is associated.</param> |
| | | 74 | | /// <param name="sslHostName">The SSL host with which this pool is associated.</param> |
| | | 75 | | /// <param name="proxyUri">The proxy this pool targets (optional).</param> |
| | | 76 | | /// <param name="telemetryServerAddress">The value of the 'server.address' tag to be emitted by Metrics and Dist |
| | 0 | 77 | | public HttpConnectionPool(HttpConnectionPoolManager poolManager, HttpConnectionKind kind, string? host, int port |
| | 0 | 78 | | { |
| | 0 | 79 | | _poolManager = poolManager; |
| | 0 | 80 | | _kind = kind; |
| | 0 | 81 | | _proxyUri = proxyUri; |
| | 0 | 82 | | _maxHttp11Connections = Settings._maxConnectionsPerServer; |
| | 0 | 83 | | _telemetryServerAddress = telemetryServerAddress; |
| | | 84 | | |
| | | 85 | | // The only case where 'host' will not be set is if this is a Proxy connection pool. |
| | 0 | 86 | | Debug.Assert(host is not null || (kind == HttpConnectionKind.Proxy && proxyUri is not null)); |
| | 0 | 87 | | _originAuthority = new HttpAuthority(host ?? proxyUri!.IdnHost, port); |
| | | 88 | | |
| | 0 | 89 | | _http2Enabled = _poolManager.Settings._maxHttpVersion >= HttpVersion.Version20; |
| | | 90 | | |
| | 0 | 91 | | if (GlobalHttpSettings.SocketsHttpHandler.AllowHttp3) |
| | 0 | 92 | | { |
| | 0 | 93 | | _http3Enabled = _poolManager.Settings._maxHttpVersion >= HttpVersion.Version30; |
| | 0 | 94 | | } |
| | | 95 | | |
| | 0 | 96 | | switch (kind) |
| | | 97 | | { |
| | | 98 | | case HttpConnectionKind.Http: |
| | 0 | 99 | | Debug.Assert(host != null); |
| | 0 | 100 | | Debug.Assert(port != 0); |
| | 0 | 101 | | Debug.Assert(sslHostName == null); |
| | 0 | 102 | | Debug.Assert(proxyUri == null); |
| | | 103 | | |
| | 0 | 104 | | _http3Enabled = false; |
| | 0 | 105 | | break; |
| | | 106 | | |
| | | 107 | | case HttpConnectionKind.Https: |
| | 0 | 108 | | Debug.Assert(host != null); |
| | 0 | 109 | | Debug.Assert(port != 0); |
| | 0 | 110 | | Debug.Assert(sslHostName != null); |
| | 0 | 111 | | Debug.Assert(proxyUri == null); |
| | 0 | 112 | | break; |
| | | 113 | | |
| | | 114 | | case HttpConnectionKind.Proxy: |
| | 0 | 115 | | Debug.Assert(host == null); |
| | 0 | 116 | | Debug.Assert(port == 0); |
| | 0 | 117 | | Debug.Assert(sslHostName == null); |
| | 0 | 118 | | Debug.Assert(proxyUri != null); |
| | | 119 | | |
| | 0 | 120 | | _http2Enabled = false; |
| | 0 | 121 | | _http3Enabled = false; |
| | 0 | 122 | | break; |
| | | 123 | | |
| | | 124 | | case HttpConnectionKind.ProxyTunnel: |
| | 0 | 125 | | Debug.Assert(host != null); |
| | 0 | 126 | | Debug.Assert(port != 0); |
| | 0 | 127 | | Debug.Assert(sslHostName == null); |
| | 0 | 128 | | Debug.Assert(proxyUri != null); |
| | | 129 | | |
| | 0 | 130 | | _http2Enabled = false; |
| | 0 | 131 | | _http3Enabled = false; |
| | 0 | 132 | | break; |
| | | 133 | | |
| | | 134 | | case HttpConnectionKind.SslProxyTunnel: |
| | 0 | 135 | | Debug.Assert(host != null); |
| | 0 | 136 | | Debug.Assert(port != 0); |
| | 0 | 137 | | Debug.Assert(sslHostName != null); |
| | 0 | 138 | | Debug.Assert(proxyUri != null); |
| | | 139 | | |
| | 0 | 140 | | _http3Enabled = false; // TODO: how do we tunnel HTTP3? |
| | 0 | 141 | | break; |
| | | 142 | | |
| | | 143 | | case HttpConnectionKind.ProxyConnect: |
| | 0 | 144 | | Debug.Assert(host != null); |
| | 0 | 145 | | Debug.Assert(port != 0); |
| | 0 | 146 | | Debug.Assert(sslHostName == null); |
| | 0 | 147 | | Debug.Assert(proxyUri != null); |
| | | 148 | | |
| | | 149 | | // Don't enforce the max connections limit on proxy tunnels; this would mean that connections to dif |
| | | 150 | | // would compete for the same limited number of connections. |
| | | 151 | | // We will still enforce this limit on the user of the tunnel (i.e. ProxyTunnel or SslProxyTunnel). |
| | 0 | 152 | | _maxHttp11Connections = int.MaxValue; |
| | | 153 | | |
| | 0 | 154 | | _http2Enabled = false; |
| | 0 | 155 | | _http3Enabled = false; |
| | 0 | 156 | | break; |
| | | 157 | | |
| | | 158 | | case HttpConnectionKind.SocksTunnel: |
| | | 159 | | case HttpConnectionKind.SslSocksTunnel: |
| | 0 | 160 | | Debug.Assert(host != null); |
| | 0 | 161 | | Debug.Assert(port != 0); |
| | 0 | 162 | | Debug.Assert(proxyUri != null); |
| | | 163 | | |
| | 0 | 164 | | _http3Enabled = false; // TODO: SOCKS supports UDP and may be used for HTTP3 |
| | 0 | 165 | | break; |
| | | 166 | | |
| | | 167 | | default: |
| | 0 | 168 | | Debug.Fail("Unknown HttpConnectionKind in HttpConnectionPool.ctor"); |
| | | 169 | | break; |
| | | 170 | | } |
| | | 171 | | |
| | 0 | 172 | | if (!_http3Enabled) |
| | 0 | 173 | | { |
| | | 174 | | // Avoid parsing Alt-Svc headers if they won't be used. |
| | 0 | 175 | | _altSvcEnabled = false; |
| | 0 | 176 | | } |
| | | 177 | | |
| | 0 | 178 | | string? hostHeader = null; |
| | 0 | 179 | | if (host is not null) |
| | 0 | 180 | | { |
| | | 181 | | // Precalculate ASCII bytes for Host header |
| | | 182 | | // Note that if _host is null, this is a (non-tunneled) proxy connection, and we can't cache the hostnam |
| | 0 | 183 | | hostHeader = IsDefaultPort |
| | 0 | 184 | | ? _originAuthority.HostValue |
| | 0 | 185 | | : $"{_originAuthority.HostValue}:{_originAuthority.Port}"; |
| | | 186 | | |
| | | 187 | | // Note the IDN hostname should always be ASCII, since it's already been IDNA encoded. |
| | 0 | 188 | | byte[] hostHeaderLine = new byte[6 + hostHeader.Length + 2]; // Host: foo\r\n |
| | 0 | 189 | | "Host: "u8.CopyTo(hostHeaderLine); |
| | 0 | 190 | | Encoding.ASCII.GetBytes(hostHeader, hostHeaderLine.AsSpan(6)); |
| | 0 | 191 | | hostHeaderLine[^2] = (byte)'\r'; |
| | 0 | 192 | | hostHeaderLine[^1] = (byte)'\n'; |
| | 0 | 193 | | _hostHeaderLineBytes = hostHeaderLine; |
| | | 194 | | |
| | 0 | 195 | | Debug.Assert(Encoding.ASCII.GetString(_hostHeaderLineBytes) == $"Host: {hostHeader}\r\n"); |
| | 0 | 196 | | } |
| | | 197 | | |
| | 0 | 198 | | if (sslHostName != null) |
| | 0 | 199 | | { |
| | 0 | 200 | | _sslOptionsHttp11 = ConstructSslOptions(poolManager, sslHostName); |
| | 0 | 201 | | _sslOptionsHttp11.ApplicationProtocols = null; |
| | | 202 | | |
| | 0 | 203 | | if (_http2Enabled) |
| | 0 | 204 | | { |
| | 0 | 205 | | _sslOptionsHttp2 = ConstructSslOptions(poolManager, sslHostName); |
| | 0 | 206 | | _sslOptionsHttp2.ApplicationProtocols = s_http2ApplicationProtocols; |
| | 0 | 207 | | _sslOptionsHttp2Only = ConstructSslOptions(poolManager, sslHostName); |
| | 0 | 208 | | _sslOptionsHttp2Only.ApplicationProtocols = s_http2OnlyApplicationProtocols; |
| | | 209 | | |
| | | 210 | | // Note: |
| | | 211 | | // The HTTP/2 specification states: |
| | | 212 | | // "A deployment of HTTP/2 over TLS 1.2 MUST disable renegotiation. |
| | | 213 | | // An endpoint MUST treat a TLS renegotiation as a connection error (Section 5.4.1) |
| | | 214 | | // of type PROTOCOL_ERROR." |
| | | 215 | | // which suggests we should do: |
| | | 216 | | // _sslOptionsHttp2.AllowRenegotiation = false; |
| | | 217 | | // However, if AllowRenegotiation is set to false, that will also prevent |
| | | 218 | | // renegotation if the server denies the HTTP/2 request and causes a |
| | | 219 | | // downgrade to HTTP/1.1, and the current APIs don't provide a mechanism |
| | | 220 | | // by which AllowRenegotiation could be set back to true in that case. |
| | | 221 | | // For now, if an HTTP/2 server erroneously issues a renegotiation, we'll |
| | | 222 | | // allow it. |
| | 0 | 223 | | } |
| | 0 | 224 | | } |
| | | 225 | | |
| | 0 | 226 | | if (hostHeader is not null) |
| | 0 | 227 | | { |
| | 0 | 228 | | if (_http2Enabled) |
| | 0 | 229 | | { |
| | 0 | 230 | | _http2EncodedAuthorityHostHeader = HPackEncoder.EncodeLiteralHeaderFieldWithoutIndexingToAllocatedAr |
| | 0 | 231 | | } |
| | | 232 | | |
| | 0 | 233 | | if (GlobalHttpSettings.SocketsHttpHandler.AllowHttp3 && _http3Enabled) |
| | 0 | 234 | | { |
| | 0 | 235 | | _http3EncodedAuthorityHostHeader = QPackEncoder.EncodeLiteralHeaderFieldWithStaticNameReferenceToArr |
| | 0 | 236 | | } |
| | 0 | 237 | | } |
| | | 238 | | |
| | | 239 | | // Set up for PreAuthenticate. Access to this cache is guarded by a lock on the cache itself. |
| | 0 | 240 | | if (_poolManager.Settings._preAuthenticate) |
| | 0 | 241 | | { |
| | 0 | 242 | | _preAuthCredentials = new PreAuthCredentialCache(); |
| | 0 | 243 | | } |
| | | 244 | | |
| | 0 | 245 | | _http11RequestQueue = new RequestQueue<HttpConnection>(); |
| | 0 | 246 | | if (_http2Enabled) |
| | 0 | 247 | | { |
| | 0 | 248 | | _http2RequestQueue = new RequestQueue<Http2Connection?>(); |
| | 0 | 249 | | } |
| | 0 | 250 | | if (GlobalHttpSettings.SocketsHttpHandler.AllowHttp3 && _http3Enabled) |
| | 0 | 251 | | { |
| | 0 | 252 | | _http3RequestQueue = new RequestQueue<Http3Connection?>(); |
| | 0 | 253 | | } |
| | | 254 | | |
| | 0 | 255 | | if (_proxyUri != null && HttpUtilities.IsSupportedSecureScheme(_proxyUri.Scheme)) |
| | 0 | 256 | | { |
| | 0 | 257 | | _sslOptionsProxy = ConstructSslOptions(poolManager, _proxyUri.IdnHost); |
| | 0 | 258 | | _sslOptionsProxy.ApplicationProtocols = null; |
| | 0 | 259 | | } |
| | | 260 | | |
| | 0 | 261 | | if (NetEventSource.Log.IsEnabled()) Trace($"{this}"); |
| | 0 | 262 | | } |
| | | 263 | | |
| | | 264 | | private static SslClientAuthenticationOptions ConstructSslOptions(HttpConnectionPoolManager poolManager, string |
| | 0 | 265 | | { |
| | 0 | 266 | | Debug.Assert(sslHostName != null); |
| | | 267 | | |
| | 0 | 268 | | SslClientAuthenticationOptions sslOptions = poolManager.Settings._sslOptions?.ShallowClone() ?? new SslClien |
| | | 269 | | |
| | | 270 | | // This is only set if we are underlying handler for HttpClientHandler |
| | 0 | 271 | | if (poolManager.Settings._clientCertificateOptions == ClientCertificateOption.Manual && sslOptions.LocalCert |
| | 0 | 272 | | (sslOptions.ClientCertificates == null || sslOptions.ClientCertificates.Count == 0)) |
| | 0 | 273 | | { |
| | | 274 | | // If we have no client certificates do not set callback when internal selection is used. |
| | | 275 | | // It breaks TLS resume on Linux |
| | 0 | 276 | | sslOptions.LocalCertificateSelectionCallback = null; |
| | 0 | 277 | | } |
| | | 278 | | |
| | | 279 | | // Set TargetHost for SNI |
| | 0 | 280 | | sslOptions.TargetHost = sslHostName; |
| | | 281 | | |
| | 0 | 282 | | return sslOptions; |
| | 0 | 283 | | } |
| | | 284 | | |
| | 0 | 285 | | public string? TelemetryServerAddress => _telemetryServerAddress; |
| | 0 | 286 | | public HttpAuthority OriginAuthority => _originAuthority; |
| | 0 | 287 | | public HttpConnectionSettings Settings => _poolManager.Settings; |
| | 0 | 288 | | public HttpConnectionKind Kind => _kind; |
| | 0 | 289 | | public bool IsSecure => _kind == HttpConnectionKind.Https || _kind == HttpConnectionKind.SslProxyTunnel || _kind |
| | 0 | 290 | | public Uri? ProxyUri => _proxyUri; |
| | 0 | 291 | | public ICredentials? ProxyCredentials => _poolManager.ProxyCredentials; |
| | 0 | 292 | | public PreAuthCredentialCache? PreAuthCredentials => _preAuthCredentials; |
| | 0 | 293 | | public bool IsDefaultPort => OriginAuthority.Port == (IsSecure ? DefaultHttpsPort : DefaultHttpPort); |
| | 0 | 294 | | private bool DoProxyAuth => (_kind == HttpConnectionKind.Proxy || _kind == HttpConnectionKind.ProxyConnect); |
| | | 295 | | |
| | | 296 | | /// <summary>Object used to synchronize access to state in the pool.</summary> |
| | | 297 | | private object SyncObj |
| | | 298 | | { |
| | | 299 | | get |
| | 0 | 300 | | { |
| | 0 | 301 | | Debug.Assert(!Monitor.IsEntered(_http11Connections)); |
| | 0 | 302 | | return _http11Connections; |
| | 0 | 303 | | } |
| | | 304 | | } |
| | | 305 | | |
| | 0 | 306 | | public bool HasSyncObjLock => Monitor.IsEntered(_http11Connections); |
| | | 307 | | |
| | | 308 | | // Overview of connection management (mostly HTTP version independent): |
| | | 309 | | // |
| | | 310 | | // Each version of HTTP (1.1, 2, 3) has its own connection pool, and each of these work in a similar manner, |
| | | 311 | | // allowing for differences between the versions (most notably, HTTP/1.1 is not multiplexed.) |
| | | 312 | | // |
| | | 313 | | // When a request is submitted for a particular version (e.g. HTTP/1.1), we first look in the pool for available |
| | | 314 | | // An "available" connection is one that is (hopefully) usable for a new request. |
| | | 315 | | // For HTTP/1.1, this is just an idle connection. |
| | | 316 | | // For HTTP2/3, this is a connection that (hopefully) has available streams to use for new requests. |
| | | 317 | | // If we find an available connection, we will attempt to validate it and then use it. |
| | | 318 | | // We check the lifetime of the connection and discard it if the lifetime is exceeded. |
| | | 319 | | // We check that the connection has not shut down; if so we discard it. |
| | | 320 | | // For HTTP2/3, we reserve a stream on the connection. If this fails, we cannot use the connection right no |
| | | 321 | | // If validation fails, we will attempt to find a different available connection. |
| | | 322 | | // |
| | | 323 | | // Once we have found a usable connection, we use it to process the request. |
| | | 324 | | // For HTTP/1.1, a connection can handle only a single request at a time, thus it is immediately removed fr |
| | | 325 | | // For HTTP2/3, a connection is only removed from the available list when it has no more available streams. |
| | | 326 | | // In either case, the connection still counts against the total associated connection count for the pool. |
| | | 327 | | // |
| | | 328 | | // If we cannot find a usable available connection, then the request is added the to the request queue for the a |
| | | 329 | | // |
| | | 330 | | // Whenever a request is queued, or an existing connection shuts down, we will check to see if we should inject |
| | | 331 | | // Injection policy depends on both user settings and some simple heuristics. |
| | | 332 | | // See comments on the relevant routines for details on connection injection policy. |
| | | 333 | | // |
| | | 334 | | // When a new connection is successfully created, or an existing unavailable connection becomes available again, |
| | | 335 | | // we will attempt to use this connection to handle any queued requests (subject to lifetime restrictions on exi |
| | | 336 | | // This may result in the connection becoming unavailable again, because it cannot handle any more requests at t |
| | | 337 | | // If not, we will return the connection to the pool as an available connection for use by new requests. |
| | | 338 | | // |
| | | 339 | | // When a connection shuts down, either gracefully (e.g. GOAWAY) or abortively (e.g. IOException), |
| | | 340 | | // we will remove it from the list of available connections, if it is present there. |
| | | 341 | | // If not, then it must be unavailable at the moment; we will detect this and ensure it is not added back to the |
| | | 342 | | |
| | | 343 | | public ValueTask<HttpResponseMessage> SendAsync(HttpRequestMessage request, bool async, bool doRequestAuth, Canc |
| | 0 | 344 | | { |
| | | 345 | | // We need the User-Agent header when we send a CONNECT request to the proxy. |
| | | 346 | | // We must read the header early, before we return the ownership of the request back to the user. |
| | 0 | 347 | | if ((Kind is HttpConnectionKind.ProxyTunnel or HttpConnectionKind.SslProxyTunnel) && |
| | 0 | 348 | | request.HasHeaders && |
| | 0 | 349 | | request.Headers.NonValidated.TryGetValues(HttpKnownHeaderNames.UserAgent, out HeaderStringValues userAge |
| | 0 | 350 | | { |
| | 0 | 351 | | _connectTunnelUserAgent = userAgent.ToString(); |
| | 0 | 352 | | } |
| | | 353 | | |
| | 0 | 354 | | if (doRequestAuth && Settings._credentials != null) |
| | 0 | 355 | | { |
| | 0 | 356 | | return AuthenticationHelper.SendWithRequestAuthAsync(request, async, Settings._credentials, Settings._pr |
| | | 357 | | } |
| | | 358 | | |
| | 0 | 359 | | return SendWithProxyAuthAsync(request, async, doRequestAuth, cancellationToken); |
| | 0 | 360 | | } |
| | | 361 | | |
| | | 362 | | public ValueTask<HttpResponseMessage> SendWithProxyAuthAsync(HttpRequestMessage request, bool async, bool doRequ |
| | 0 | 363 | | { |
| | 0 | 364 | | if (DoProxyAuth && ProxyCredentials is not null) |
| | 0 | 365 | | { |
| | 0 | 366 | | return AuthenticationHelper.SendWithProxyAuthAsync(request, _proxyUri!, async, ProxyCredentials, doReque |
| | | 367 | | } |
| | | 368 | | |
| | 0 | 369 | | return SendWithVersionDetectionAndRetryAsync(request, async, doRequestAuth, cancellationToken); |
| | 0 | 370 | | } |
| | | 371 | | |
| | | 372 | | private Task<HttpResponseMessage> SendWithNtConnectionAuthAsync(HttpConnection connection, HttpRequestMessage re |
| | 0 | 373 | | { |
| | 0 | 374 | | if (doRequestAuth && Settings._credentials != null) |
| | 0 | 375 | | { |
| | 0 | 376 | | return AuthenticationHelper.SendWithNtConnectionAuthAsync(request, async, Settings._credentials, Setting |
| | | 377 | | } |
| | | 378 | | |
| | 0 | 379 | | return SendWithNtProxyAuthAsync(connection, request, async, cancellationToken); |
| | 0 | 380 | | } |
| | | 381 | | |
| | | 382 | | public Task<HttpResponseMessage> SendWithNtProxyAuthAsync(HttpConnection connection, HttpRequestMessage request, |
| | 0 | 383 | | { |
| | 0 | 384 | | if (DoProxyAuth && ProxyCredentials is not null) |
| | 0 | 385 | | { |
| | 0 | 386 | | return AuthenticationHelper.SendWithNtProxyAuthAsync(request, ProxyUri!, async, ProxyCredentials, HttpHa |
| | | 387 | | } |
| | | 388 | | |
| | 0 | 389 | | return connection.SendAsync(request, async, cancellationToken); |
| | 0 | 390 | | } |
| | | 391 | | |
| | | 392 | | public async ValueTask<HttpResponseMessage> SendWithVersionDetectionAndRetryAsync(HttpRequestMessage request, bo |
| | 0 | 393 | | { |
| | 0 | 394 | | _usedSinceLastCleanup = true; |
| | | 395 | | |
| | | 396 | | // Loop on connection failures (or other problems like version downgrade) and retry if possible. |
| | 0 | 397 | | int retryCount = 0; |
| | 0 | 398 | | while (true) |
| | 0 | 399 | | { |
| | 0 | 400 | | HttpConnectionWaiter<HttpConnection>? http11ConnectionWaiter = null; |
| | 0 | 401 | | HttpConnectionWaiter<Http2Connection?>? http2ConnectionWaiter = null; |
| | | 402 | | try |
| | 0 | 403 | | { |
| | 0 | 404 | | HttpResponseMessage? response = null; |
| | | 405 | | |
| | | 406 | | // Use HTTP/3 if possible. |
| | 0 | 407 | | if (GlobalHttpSettings.SocketsHttpHandler.AllowHttp3 && // guard to enable trimming HTTP/3 support |
| | 0 | 408 | | _http3Enabled && |
| | 0 | 409 | | (request.Version.Major >= 3 || (request.VersionPolicy == HttpVersionPolicy.RequestVersionOrHighe |
| | 0 | 410 | | !request.IsExtendedConnectRequest) |
| | 0 | 411 | | { |
| | 0 | 412 | | Debug.Assert(async); |
| | 0 | 413 | | if (QuicConnection.IsSupported) |
| | 0 | 414 | | { |
| | 0 | 415 | | if (_sslOptionsHttp3 == null) |
| | 0 | 416 | | { |
| | | 417 | | // deferred creation. We use atomic exchange to be sure all threads point to single obje |
| | 0 | 418 | | SslClientAuthenticationOptions sslOptionsHttp3 = ConstructSslOptions(_poolManager, _sslO |
| | 0 | 419 | | sslOptionsHttp3.ApplicationProtocols = s_http3ApplicationProtocols; |
| | 0 | 420 | | Interlocked.CompareExchange(ref _sslOptionsHttp3, sslOptionsHttp3, null); |
| | 0 | 421 | | } |
| | | 422 | | |
| | 0 | 423 | | response = await TrySendUsingHttp3Async(request, cancellationToken).ConfigureAwait(false); |
| | 0 | 424 | | } |
| | | 425 | | else |
| | 0 | 426 | | { |
| | 0 | 427 | | _altSvcEnabled = false; |
| | 0 | 428 | | _http3Enabled = false; |
| | 0 | 429 | | } |
| | 0 | 430 | | } |
| | | 431 | | |
| | 0 | 432 | | if (response is null) |
| | 0 | 433 | | { |
| | | 434 | | // We could not use HTTP/3. Do not continue if downgrade is not allowed. |
| | 0 | 435 | | if (request.Version.Major >= 3 && request.VersionPolicy != HttpVersionPolicy.RequestVersionOrLow |
| | 0 | 436 | | { |
| | 0 | 437 | | ThrowGetVersionException(request, 3); |
| | 0 | 438 | | } |
| | | 439 | | |
| | | 440 | | // Use HTTP/2 if possible. |
| | 0 | 441 | | if (_http2Enabled && |
| | 0 | 442 | | (request.Version.Major >= 2 || (request.VersionPolicy == HttpVersionPolicy.RequestVersionOrH |
| | 0 | 443 | | (request.VersionPolicy != HttpVersionPolicy.RequestVersionOrLower || IsSecure)) // prefer HT |
| | 0 | 444 | | { |
| | 0 | 445 | | if (!TryGetPooledHttp2Connection(request, out Http2Connection? connection, out http2Connecti |
| | 0 | 446 | | http2ConnectionWaiter != null) |
| | 0 | 447 | | { |
| | 0 | 448 | | connection = await http2ConnectionWaiter.WaitForConnectionAsync(request, this, async, ca |
| | 0 | 449 | | } |
| | | 450 | | |
| | 0 | 451 | | Debug.Assert(connection is not null || !_http2Enabled); |
| | 0 | 452 | | if (connection is not null) |
| | 0 | 453 | | { |
| | 0 | 454 | | if (request.IsExtendedConnectRequest) |
| | 0 | 455 | | { |
| | 0 | 456 | | await connection.InitialSettingsReceived.WaitWithCancellationAsync(cancellationToken |
| | 0 | 457 | | if (!connection.IsConnectEnabled) |
| | 0 | 458 | | { |
| | 0 | 459 | | HttpRequestException exception = new(HttpRequestError.ExtendedConnectNotSupporte |
| | 0 | 460 | | exception.Data["SETTINGS_ENABLE_CONNECT_PROTOCOL"] = false; |
| | 0 | 461 | | throw exception; |
| | | 462 | | } |
| | 0 | 463 | | } |
| | | 464 | | |
| | 0 | 465 | | response = await connection.SendAsync(request, async, cancellationToken).ConfigureAwait( |
| | 0 | 466 | | } |
| | 0 | 467 | | } |
| | | 468 | | |
| | 0 | 469 | | if (response is null) |
| | 0 | 470 | | { |
| | | 471 | | // We could not use HTTP/2. Do not continue if downgrade is not allowed. |
| | 0 | 472 | | if (request.Version.Major >= 2 && request.VersionPolicy != HttpVersionPolicy.RequestVersionO |
| | 0 | 473 | | { |
| | 0 | 474 | | ThrowGetVersionException(request, 2); |
| | 0 | 475 | | } |
| | | 476 | | |
| | | 477 | | // Use HTTP/1.x. |
| | 0 | 478 | | if (!TryGetPooledHttp11Connection(request, async, out HttpConnection? connection, out http11 |
| | 0 | 479 | | { |
| | 0 | 480 | | connection = await http11ConnectionWaiter.WaitForConnectionAsync(request, this, async, c |
| | 0 | 481 | | } |
| | | 482 | | |
| | 0 | 483 | | connection.Acquire(); // In case we are doing Windows (i.e. connection-based) auth, we need |
| | | 484 | | try |
| | 0 | 485 | | { |
| | 0 | 486 | | response = await SendWithNtConnectionAuthAsync(connection, request, async, doRequestAuth |
| | 0 | 487 | | } |
| | | 488 | | finally |
| | 0 | 489 | | { |
| | 0 | 490 | | connection.Release(); |
| | 0 | 491 | | } |
| | 0 | 492 | | } |
| | 0 | 493 | | } |
| | | 494 | | |
| | 0 | 495 | | ProcessAltSvc(response); |
| | 0 | 496 | | return response; |
| | | 497 | | } |
| | 0 | 498 | | catch (HttpRequestException e) when (e.AllowRetry == RequestRetryType.RetryOnConnectionFailure) |
| | 0 | 499 | | { |
| | 0 | 500 | | Debug.Assert(retryCount >= 0 && retryCount <= MaxConnectionFailureRetries); |
| | | 501 | | |
| | 0 | 502 | | if (retryCount == MaxConnectionFailureRetries) |
| | 0 | 503 | | { |
| | 0 | 504 | | if (NetEventSource.Log.IsEnabled()) |
| | 0 | 505 | | { |
| | 0 | 506 | | Trace($"MaxConnectionFailureRetries limit of {MaxConnectionFailureRetries} hit. Retryable re |
| | 0 | 507 | | } |
| | | 508 | | |
| | 0 | 509 | | throw; |
| | | 510 | | } |
| | | 511 | | |
| | 0 | 512 | | retryCount++; |
| | | 513 | | |
| | 0 | 514 | | if (NetEventSource.Log.IsEnabled()) |
| | 0 | 515 | | { |
| | 0 | 516 | | Trace($"Retry attempt {retryCount} after connection failure. Connection exception: {e}"); |
| | 0 | 517 | | } |
| | | 518 | | |
| | | 519 | | // Eat exception and try again. |
| | 0 | 520 | | } |
| | 0 | 521 | | catch (HttpRequestException e) when (e.AllowRetry == RequestRetryType.RetryOnLowerHttpVersion) |
| | 0 | 522 | | { |
| | | 523 | | // Throw if fallback is not allowed by the version policy. |
| | 0 | 524 | | if (request.VersionPolicy != HttpVersionPolicy.RequestVersionOrLower) |
| | 0 | 525 | | { |
| | 0 | 526 | | throw new HttpRequestException(HttpRequestError.VersionNegotiationError, SR.Format(SR.net_http_r |
| | | 527 | | } |
| | | 528 | | |
| | 0 | 529 | | if (NetEventSource.Log.IsEnabled()) |
| | 0 | 530 | | { |
| | 0 | 531 | | Trace($"Retrying request because server requested version fallback: {e}"); |
| | 0 | 532 | | } |
| | | 533 | | |
| | | 534 | | // Eat exception and try again on a lower protocol version. |
| | 0 | 535 | | request.Version = HttpVersion.Version11; |
| | 0 | 536 | | } |
| | | 537 | | finally |
| | 0 | 538 | | { |
| | | 539 | | // We never cancel both attempts at the same time. When downgrade happens, it's possible that both w |
| | | 540 | | // but in that case http2ConnectionWaiter.ConnectionCancellationTokenSource shall be null. |
| | 0 | 541 | | Debug.Assert(http11ConnectionWaiter is null || http2ConnectionWaiter?.ConnectionCancellationTokenSou |
| | 0 | 542 | | http11ConnectionWaiter?.SetTimeoutToPendingConnectionAttempt(this, cancellationToken.IsCancellationR |
| | 0 | 543 | | http2ConnectionWaiter?.SetTimeoutToPendingConnectionAttempt(this, cancellationToken.IsCancellationRe |
| | 0 | 544 | | } |
| | 0 | 545 | | } |
| | 0 | 546 | | } |
| | | 547 | | |
| | | 548 | | private async ValueTask<(Stream, TransportContext?, Activity?, IPEndPoint?)> ConnectAsync(HttpRequestMessage req |
| | 0 | 549 | | { |
| | 0 | 550 | | Stream? stream = null; |
| | 0 | 551 | | IPEndPoint? remoteEndPoint = null; |
| | 0 | 552 | | Exception? exception = null; |
| | 0 | 553 | | TransportContext? transportContext = null; |
| | | 554 | | |
| | 0 | 555 | | Activity? activity = ConnectionSetupDistributedTracing.StartConnectionSetupActivity(IsSecure, _telemetryServ |
| | | 556 | | |
| | | 557 | | try |
| | 0 | 558 | | { |
| | 0 | 559 | | switch (_kind) |
| | | 560 | | { |
| | | 561 | | case HttpConnectionKind.Http: |
| | | 562 | | case HttpConnectionKind.Https: |
| | | 563 | | case HttpConnectionKind.ProxyConnect: |
| | 0 | 564 | | stream = await ConnectToTcpHostAsync(_originAuthority.IdnHost, _originAuthority.Port, request, a |
| | | 565 | | // remoteEndPoint is returned for diagnostic purposes. |
| | 0 | 566 | | remoteEndPoint = GetRemoteEndPoint(stream); |
| | 0 | 567 | | if (_kind == HttpConnectionKind.ProxyConnect && _sslOptionsProxy != null) |
| | 0 | 568 | | { |
| | 0 | 569 | | stream = await ConnectHelper.EstablishSslConnectionAsync(_sslOptionsProxy, request, async, s |
| | 0 | 570 | | } |
| | 0 | 571 | | break; |
| | | 572 | | |
| | | 573 | | case HttpConnectionKind.Proxy: |
| | 0 | 574 | | stream = await ConnectToTcpHostAsync(_proxyUri!.IdnHost, _proxyUri.Port, request, async, cancell |
| | | 575 | | // remoteEndPoint is returned for diagnostic purposes. |
| | 0 | 576 | | remoteEndPoint = GetRemoteEndPoint(stream); |
| | 0 | 577 | | if (_sslOptionsProxy != null) |
| | 0 | 578 | | { |
| | 0 | 579 | | stream = await ConnectHelper.EstablishSslConnectionAsync(_sslOptionsProxy, request, async, s |
| | 0 | 580 | | } |
| | 0 | 581 | | break; |
| | | 582 | | |
| | | 583 | | case HttpConnectionKind.ProxyTunnel: |
| | | 584 | | case HttpConnectionKind.SslProxyTunnel: |
| | 0 | 585 | | stream = await EstablishProxyTunnelAsync(async, cancellationToken).ConfigureAwait(false); |
| | | 586 | | |
| | 0 | 587 | | if (stream is HttpContentStream contentStream && contentStream._connection?._stream is Stream in |
| | 0 | 588 | | { |
| | 0 | 589 | | remoteEndPoint = GetRemoteEndPoint(innerStream); |
| | 0 | 590 | | } |
| | | 591 | | |
| | 0 | 592 | | break; |
| | | 593 | | |
| | | 594 | | case HttpConnectionKind.SocksTunnel: |
| | | 595 | | case HttpConnectionKind.SslSocksTunnel: |
| | 0 | 596 | | stream = await EstablishSocksTunnel(request, async, cancellationToken).ConfigureAwait(false); |
| | | 597 | | // remoteEndPoint is returned for diagnostic purposes. |
| | 0 | 598 | | remoteEndPoint = GetRemoteEndPoint(stream); |
| | 0 | 599 | | break; |
| | | 600 | | } |
| | | 601 | | |
| | 0 | 602 | | Debug.Assert(stream != null); |
| | | 603 | | |
| | 0 | 604 | | if (IsSecure) |
| | 0 | 605 | | { |
| | 0 | 606 | | SslStream? sslStream = stream as SslStream; |
| | 0 | 607 | | if (sslStream == null) |
| | 0 | 608 | | { |
| | 0 | 609 | | sslStream = await ConnectHelper.EstablishSslConnectionAsync(GetSslOptionsForRequest(request), re |
| | 0 | 610 | | } |
| | | 611 | | else |
| | 0 | 612 | | { |
| | 0 | 613 | | if (NetEventSource.Log.IsEnabled()) |
| | 0 | 614 | | { |
| | 0 | 615 | | Trace($"Connected with custom SslStream: alpn='${sslStream.NegotiatedApplicationProtocol}'") |
| | 0 | 616 | | } |
| | 0 | 617 | | } |
| | 0 | 618 | | transportContext = sslStream.TransportContext; |
| | 0 | 619 | | stream = sslStream; |
| | 0 | 620 | | } |
| | 0 | 621 | | } |
| | 0 | 622 | | catch (Exception ex) when (activity is not null) |
| | 0 | 623 | | { |
| | 0 | 624 | | exception = ex; |
| | 0 | 625 | | throw; |
| | | 626 | | } |
| | | 627 | | finally |
| | 0 | 628 | | { |
| | 0 | 629 | | if (activity is not null) |
| | 0 | 630 | | { |
| | 0 | 631 | | ConnectionSetupDistributedTracing.StopConnectionSetupActivity(activity, exception, remoteEndPoint); |
| | 0 | 632 | | } |
| | 0 | 633 | | } |
| | | 634 | | |
| | 0 | 635 | | return (stream, transportContext, activity, remoteEndPoint); |
| | | 636 | | |
| | 0 | 637 | | static IPEndPoint? GetRemoteEndPoint(Stream stream) => (stream as NetworkStream)?.Socket?.RemoteEndPoint as |
| | 0 | 638 | | } |
| | | 639 | | |
| | | 640 | | private async ValueTask<Stream> ConnectToTcpHostAsync(string host, int port, HttpRequestMessage initialRequest, |
| | 0 | 641 | | { |
| | 0 | 642 | | cancellationToken.ThrowIfCancellationRequested(); |
| | | 643 | | |
| | 0 | 644 | | var endPoint = new DnsEndPoint(host, port); |
| | 0 | 645 | | Stream? stream = null; |
| | | 646 | | try |
| | 0 | 647 | | { |
| | | 648 | | // If a ConnectCallback was supplied, use that to establish the connection. |
| | 0 | 649 | | if (Settings._connectCallback != null) |
| | 0 | 650 | | { |
| | 0 | 651 | | ValueTask<Stream> streamTask = Settings._connectCallback(new SocketsHttpConnectionContext(endPoint, |
| | | 652 | | |
| | 0 | 653 | | if (!async && !streamTask.IsCompleted) |
| | 0 | 654 | | { |
| | | 655 | | // User-provided ConnectCallback is completing asynchronously but the user is making a synchrono |
| | | 656 | | // set it up so that synchronous requests are made on a handler with a synchronously-completing |
| | | 657 | | // we could add a Boolean to SocketsHttpConnectionContext (https://github.com/dotnet/runtime/iss |
| | | 658 | | // this request is sync or async. |
| | 0 | 659 | | Trace($"{nameof(SocketsHttpHandler.ConnectCallback)} completing asynchronously for a synchronous |
| | 0 | 660 | | } |
| | | 661 | | |
| | 0 | 662 | | stream = await streamTask.ConfigureAwait(false) ?? throw new HttpRequestException(SR.net_http_null_f |
| | 0 | 663 | | } |
| | | 664 | | else |
| | 0 | 665 | | { |
| | | 666 | | // Otherwise, create and connect a socket using default settings. |
| | 0 | 667 | | Socket socket = new Socket(SocketType.Stream, ProtocolType.Tcp) { NoDelay = true }; |
| | | 668 | | try |
| | 0 | 669 | | { |
| | 0 | 670 | | if (async) |
| | 0 | 671 | | { |
| | 0 | 672 | | await socket.ConnectAsync(endPoint, cancellationToken).ConfigureAwait(false); |
| | 0 | 673 | | } |
| | | 674 | | else |
| | 0 | 675 | | { |
| | | 676 | | using (cancellationToken.UnsafeRegister(static s => ((Socket)s!).Dispose(), socket)) |
| | 0 | 677 | | { |
| | 0 | 678 | | socket.Connect(endPoint); |
| | 0 | 679 | | } |
| | 0 | 680 | | } |
| | | 681 | | |
| | 0 | 682 | | stream = new NetworkStream(socket, ownsSocket: true); |
| | 0 | 683 | | } |
| | 0 | 684 | | catch |
| | 0 | 685 | | { |
| | 0 | 686 | | socket.Dispose(); |
| | 0 | 687 | | throw; |
| | | 688 | | } |
| | 0 | 689 | | } |
| | | 690 | | |
| | 0 | 691 | | return stream; |
| | | 692 | | } |
| | 0 | 693 | | catch (Exception ex) |
| | 0 | 694 | | { |
| | 0 | 695 | | throw ex is OperationCanceledException oce && oce.CancellationToken == cancellationToken ? |
| | 0 | 696 | | CancellationHelper.CreateOperationCanceledException(innerException: null, cancellationToken) : |
| | 0 | 697 | | ConnectHelper.CreateWrappedException(ex, host, port, cancellationToken); |
| | | 698 | | } |
| | 0 | 699 | | } |
| | | 700 | | |
| | | 701 | | private SslClientAuthenticationOptions GetSslOptionsForRequest(HttpRequestMessage request) |
| | 0 | 702 | | { |
| | 0 | 703 | | if (_http2Enabled) |
| | 0 | 704 | | { |
| | 0 | 705 | | if (request.Version.Major >= 2 && request.VersionPolicy != HttpVersionPolicy.RequestVersionOrLower) |
| | 0 | 706 | | { |
| | 0 | 707 | | return _sslOptionsHttp2Only!; |
| | | 708 | | } |
| | | 709 | | |
| | 0 | 710 | | if (request.Version.Major >= 2 || request.VersionPolicy == HttpVersionPolicy.RequestVersionOrHigher) |
| | 0 | 711 | | { |
| | 0 | 712 | | return _sslOptionsHttp2!; |
| | | 713 | | } |
| | 0 | 714 | | } |
| | 0 | 715 | | return _sslOptionsHttp11!; |
| | 0 | 716 | | } |
| | | 717 | | |
| | | 718 | | private async ValueTask<Stream> ApplyPlaintextFilterAsync(bool async, Stream stream, Version httpVersion, HttpRe |
| | 0 | 719 | | { |
| | 0 | 720 | | if (Settings._plaintextStreamFilter is null) |
| | 0 | 721 | | { |
| | 0 | 722 | | return stream; |
| | | 723 | | } |
| | | 724 | | |
| | | 725 | | Stream newStream; |
| | | 726 | | try |
| | 0 | 727 | | { |
| | 0 | 728 | | ValueTask<Stream> streamTask = Settings._plaintextStreamFilter(new SocketsHttpPlaintextStreamFilterConte |
| | | 729 | | |
| | 0 | 730 | | if (!async && !streamTask.IsCompleted) |
| | 0 | 731 | | { |
| | | 732 | | // User-provided PlaintextStreamFilter is completing asynchronously but the user is making a synchro |
| | | 733 | | // set it up so that synchronous requests are made on a handler with a synchronously-completing Plai |
| | | 734 | | // we could add a Boolean to SocketsHttpPlaintextStreamFilterContext (https://github.com/dotnet/runt |
| | | 735 | | // this request is sync or async. |
| | 0 | 736 | | Trace($"{nameof(SocketsHttpHandler.PlaintextStreamFilter)} completing asynchronously for a synchrono |
| | 0 | 737 | | } |
| | | 738 | | |
| | 0 | 739 | | newStream = await streamTask.ConfigureAwait(false); |
| | 0 | 740 | | } |
| | 0 | 741 | | catch (OperationCanceledException oce) when (oce.CancellationToken == cancellationToken) |
| | 0 | 742 | | { |
| | 0 | 743 | | stream.Dispose(); |
| | 0 | 744 | | throw; |
| | | 745 | | } |
| | 0 | 746 | | catch (Exception e) |
| | 0 | 747 | | { |
| | 0 | 748 | | stream.Dispose(); |
| | 0 | 749 | | throw new HttpRequestException(SR.net_http_exception_during_plaintext_filter, e); |
| | | 750 | | } |
| | | 751 | | |
| | 0 | 752 | | if (newStream == null) |
| | 0 | 753 | | { |
| | 0 | 754 | | stream.Dispose(); |
| | 0 | 755 | | throw new HttpRequestException(SR.net_http_null_from_plaintext_filter); |
| | | 756 | | } |
| | | 757 | | |
| | 0 | 758 | | return newStream; |
| | 0 | 759 | | } |
| | | 760 | | |
| | | 761 | | private async ValueTask<Stream> EstablishProxyTunnelAsync(bool async, CancellationToken cancellationToken) |
| | 0 | 762 | | { |
| | | 763 | | // Send a CONNECT request to the proxy server to establish a tunnel. |
| | 0 | 764 | | HttpRequestMessage tunnelRequest = new HttpRequestMessage(HttpMethod.Connect, _proxyUri); |
| | 0 | 765 | | tunnelRequest.Headers.Host = $"{_originAuthority.IdnHost}:{_originAuthority.Port}"; // This specifies des |
| | | 766 | | |
| | 0 | 767 | | if (_connectTunnelUserAgent is not null) |
| | 0 | 768 | | { |
| | 0 | 769 | | tunnelRequest.Headers.TryAddWithoutValidation(KnownHeaders.UserAgent.Descriptor, _connectTunnelUserAgent |
| | 0 | 770 | | } |
| | | 771 | | |
| | 0 | 772 | | HttpResponseMessage tunnelResponse = await _poolManager.SendProxyConnectAsync(tunnelRequest, _proxyUri!, asy |
| | | 773 | | |
| | 0 | 774 | | if (!tunnelResponse.IsSuccessStatusCode) |
| | 0 | 775 | | { |
| | 0 | 776 | | tunnelResponse.Dispose(); |
| | 0 | 777 | | throw new HttpRequestException(HttpRequestError.ProxyTunnelError, SR.Format(SR.net_http_proxy_tunnel_ret |
| | | 778 | | } |
| | | 779 | | |
| | | 780 | | try |
| | 0 | 781 | | { |
| | 0 | 782 | | return tunnelResponse.Content.ReadAsStream(cancellationToken); |
| | | 783 | | } |
| | 0 | 784 | | catch |
| | 0 | 785 | | { |
| | 0 | 786 | | tunnelResponse.Dispose(); |
| | 0 | 787 | | throw; |
| | | 788 | | } |
| | 0 | 789 | | } |
| | | 790 | | |
| | | 791 | | private async ValueTask<Stream> EstablishSocksTunnel(HttpRequestMessage request, bool async, CancellationToken c |
| | 0 | 792 | | { |
| | 0 | 793 | | Debug.Assert(_proxyUri != null); |
| | | 794 | | |
| | 0 | 795 | | Stream stream = await ConnectToTcpHostAsync(_proxyUri.IdnHost, _proxyUri.Port, request, async, cancellationT |
| | | 796 | | |
| | | 797 | | try |
| | 0 | 798 | | { |
| | 0 | 799 | | await SocksHelper.EstablishSocksTunnelAsync(stream, _originAuthority.IdnHost, _originAuthority.Port, _pr |
| | 0 | 800 | | } |
| | 0 | 801 | | catch (Exception e) when (e is not OperationCanceledException) |
| | 0 | 802 | | { |
| | 0 | 803 | | Debug.Assert(e is not HttpRequestException); |
| | 0 | 804 | | throw new HttpRequestException(HttpRequestError.ProxyTunnelError, SR.net_http_proxy_tunnel_error, e); |
| | | 805 | | } |
| | | 806 | | |
| | 0 | 807 | | return stream; |
| | 0 | 808 | | } |
| | | 809 | | |
| | | 810 | | private CancellationTokenSource GetConnectTimeoutCancellationTokenSource<T>(HttpConnectionWaiter<T> waiter) |
| | | 811 | | where T : HttpConnectionBase? |
| | 0 | 812 | | { |
| | 0 | 813 | | var cts = new CancellationTokenSource(Settings._connectTimeout); |
| | | 814 | | |
| | 0 | 815 | | lock (waiter) |
| | 0 | 816 | | { |
| | | 817 | | // After a request completes (or is canceled), it will call into SetTimeoutToPendingConnectionAttempt, |
| | | 818 | | // which will no-op if ConnectionCancellationTokenSource is not set, assuming that the connection attemp |
| | | 819 | | // As the initiating request for this connection attempt may complete concurrently at any time, |
| | | 820 | | // there is a race condition where the first call to SetTimeoutToPendingConnectionAttempt may happen |
| | | 821 | | // before we were able to set the CTS, so no timeout will be applied even though the request is already |
| | 0 | 822 | | waiter.ConnectionCancellationTokenSource = cts; |
| | | 823 | | |
| | | 824 | | // To fix that, we check whether the waiter already completed now that we're holding a lock. |
| | | 825 | | // If it had, call SetTimeoutToPendingConnectionAttempt again now that the CTS is set. |
| | 0 | 826 | | if (waiter.Task.IsCompleted) |
| | 0 | 827 | | { |
| | 0 | 828 | | waiter.SetTimeoutToPendingConnectionAttempt(this, requestCancelled: waiter.Task.IsCanceled); |
| | 0 | 829 | | waiter.ConnectionCancellationTokenSource = null; |
| | 0 | 830 | | } |
| | 0 | 831 | | } |
| | | 832 | | |
| | 0 | 833 | | return cts; |
| | 0 | 834 | | } |
| | | 835 | | |
| | | 836 | | private static Exception CreateConnectTimeoutException(OperationCanceledException oce) |
| | 0 | 837 | | { |
| | | 838 | | // The pattern for request timeouts (on HttpClient) is to throw an OCE with an inner exception of TimeoutExc |
| | | 839 | | // Do the same for ConnectTimeout-based timeouts. |
| | 0 | 840 | | TimeoutException te = new TimeoutException(SR.net_http_connect_timedout, oce.InnerException); |
| | 0 | 841 | | Exception newException = CancellationHelper.CreateOperationCanceledException(te, oce.CancellationToken); |
| | 0 | 842 | | ExceptionDispatchInfo.SetCurrentStackTrace(newException); |
| | 0 | 843 | | return newException; |
| | 0 | 844 | | } |
| | | 845 | | |
| | | 846 | | [DoesNotReturn] |
| | | 847 | | private static void ThrowGetVersionException(HttpRequestMessage request, int desiredVersion, Exception? inner = |
| | 0 | 848 | | { |
| | 0 | 849 | | Debug.Assert(desiredVersion == 2 || desiredVersion == 3); |
| | | 850 | | |
| | 0 | 851 | | HttpRequestException ex = new(HttpRequestError.VersionNegotiationError, SR.Format(SR.net_http_requested_vers |
| | 0 | 852 | | if (request.IsExtendedConnectRequest && desiredVersion == 2) |
| | 0 | 853 | | { |
| | 0 | 854 | | ex.Data["HTTP2_ENABLED"] = false; |
| | 0 | 855 | | } |
| | | 856 | | |
| | 0 | 857 | | throw ex; |
| | | 858 | | } |
| | | 859 | | |
| | | 860 | | private bool CheckExpirationOnGet(HttpConnectionBase connection) |
| | 0 | 861 | | { |
| | 0 | 862 | | Debug.Assert(!HasSyncObjLock); |
| | | 863 | | |
| | 0 | 864 | | TimeSpan pooledConnectionLifetime = _poolManager.Settings._pooledConnectionLifetime; |
| | 0 | 865 | | if (pooledConnectionLifetime != Timeout.InfiniteTimeSpan) |
| | 0 | 866 | | { |
| | 0 | 867 | | return connection.GetLifetimeTicks(Environment.TickCount64) > pooledConnectionLifetime.TotalMilliseconds |
| | | 868 | | } |
| | | 869 | | |
| | 0 | 870 | | return false; |
| | 0 | 871 | | } |
| | | 872 | | |
| | | 873 | | private bool CheckExpirationOnReturn(HttpConnectionBase connection) |
| | 0 | 874 | | { |
| | 0 | 875 | | TimeSpan lifetime = _poolManager.Settings._pooledConnectionLifetime; |
| | 0 | 876 | | if (lifetime != Timeout.InfiniteTimeSpan) |
| | 0 | 877 | | { |
| | 0 | 878 | | return lifetime == TimeSpan.Zero || connection.GetLifetimeTicks(Environment.TickCount64) > lifetime.Tota |
| | | 879 | | } |
| | | 880 | | |
| | 0 | 881 | | return false; |
| | 0 | 882 | | } |
| | | 883 | | |
| | | 884 | | /// <summary> |
| | | 885 | | /// Disposes the connection pool. This is only needed when the pool currently contains |
| | | 886 | | /// or has associated connections. |
| | | 887 | | /// </summary> |
| | | 888 | | public void Dispose() |
| | 0 | 889 | | { |
| | 0 | 890 | | List<HttpConnectionBase>? toDispose = null; |
| | | 891 | | |
| | 0 | 892 | | lock (SyncObj) |
| | 0 | 893 | | { |
| | 0 | 894 | | if (_disposed) |
| | 0 | 895 | | { |
| | 0 | 896 | | return; |
| | | 897 | | } |
| | | 898 | | |
| | 0 | 899 | | _disposed = true; |
| | 0 | 900 | | _http11RequestQueueIsEmptyAndNotDisposed = false; |
| | | 901 | | |
| | 0 | 902 | | if (NetEventSource.Log.IsEnabled()) Trace("Disposing the pool."); |
| | | 903 | | |
| | 0 | 904 | | if (_availableHttp2Connections is not null) |
| | 0 | 905 | | { |
| | 0 | 906 | | toDispose = [.. _availableHttp2Connections]; |
| | 0 | 907 | | _associatedHttp2ConnectionCount -= _availableHttp2Connections.Count; |
| | 0 | 908 | | _availableHttp2Connections.Clear(); |
| | 0 | 909 | | } |
| | | 910 | | |
| | 0 | 911 | | if (GlobalHttpSettings.SocketsHttpHandler.AllowHttp3 && _availableHttp3Connections is not null) |
| | 0 | 912 | | { |
| | 0 | 913 | | toDispose ??= new(); |
| | 0 | 914 | | toDispose.AddRange(_availableHttp3Connections); |
| | 0 | 915 | | _associatedHttp3ConnectionCount -= _availableHttp3Connections.Count; |
| | 0 | 916 | | _availableHttp3Connections.Clear(); |
| | 0 | 917 | | } |
| | | 918 | | |
| | 0 | 919 | | if (_authorityExpireTimer != null) |
| | 0 | 920 | | { |
| | 0 | 921 | | _authorityExpireTimer.Dispose(); |
| | 0 | 922 | | _authorityExpireTimer = null; |
| | 0 | 923 | | } |
| | | 924 | | |
| | 0 | 925 | | if (_altSvcBlocklistTimerCancellation != null) |
| | 0 | 926 | | { |
| | 0 | 927 | | _altSvcBlocklistTimerCancellation.Cancel(); |
| | 0 | 928 | | _altSvcBlocklistTimerCancellation.Dispose(); |
| | 0 | 929 | | _altSvcBlocklistTimerCancellation = null; |
| | 0 | 930 | | } |
| | | 931 | | |
| | 0 | 932 | | Debug.Assert((_availableHttp2Connections?.Count ?? 0) == 0, $"Expected {nameof(_availableHttp2Connection |
| | 0 | 933 | | } |
| | | 934 | | |
| | | 935 | | // Dispose connections outside the lock to avoid lock re-entrancy issues. |
| | | 936 | | |
| | | 937 | | // This will trigger the disposal of Http11 connections. |
| | | 938 | | // Note: Http11 connections will decrement the _associatedHttp11ConnectionCount when disposed. |
| | | 939 | | // Http2 connections will not, hence the difference in handing _associatedHttp2ConnectionCount. |
| | 0 | 940 | | ProcessHttp11RequestQueue(null); |
| | | 941 | | |
| | 0 | 942 | | toDispose?.ForEach(c => c.Dispose()); |
| | 0 | 943 | | } |
| | | 944 | | |
| | | 945 | | /// <summary> |
| | | 946 | | /// Removes any unusable connections from the pool, and if the pool |
| | | 947 | | /// is then empty and stale, disposes of it. |
| | | 948 | | /// </summary> |
| | | 949 | | /// <returns> |
| | | 950 | | /// true if the pool disposes of itself; otherwise, false. |
| | | 951 | | /// </returns> |
| | | 952 | | public bool CleanCacheAndDisposeIfUnused() |
| | 0 | 953 | | { |
| | 0 | 954 | | TimeSpan pooledConnectionLifetime = _poolManager.Settings._pooledConnectionLifetime; |
| | 0 | 955 | | TimeSpan pooledConnectionIdleTimeout = _poolManager.Settings._pooledConnectionIdleTimeout; |
| | 0 | 956 | | long nowTicks = Environment.TickCount64; |
| | | 957 | | |
| | 0 | 958 | | List<HttpConnectionBase>? toDispose = null; |
| | | 959 | | |
| | 0 | 960 | | lock (SyncObj) |
| | 0 | 961 | | { |
| | | 962 | | // If there are now no connections associated with this pool, we can dispose of it. We |
| | | 963 | | // avoid aggressively cleaning up pools that have recently been used but currently aren't; |
| | | 964 | | // if a pool was used since the last time we cleaned up, give it another chance. New pools |
| | | 965 | | // start out saying they've recently been used, to give them a bit of breathing room and time |
| | | 966 | | // for the initial collection to be added to it. |
| | 0 | 967 | | if (!_usedSinceLastCleanup && _associatedHttp11ConnectionCount == 0 && _associatedHttp2ConnectionCount = |
| | 0 | 968 | | { |
| | 0 | 969 | | _disposed = true; |
| | 0 | 970 | | return true; // Pool is disposed of. It should be removed. |
| | | 971 | | } |
| | | 972 | | |
| | | 973 | | // Reset the cleanup flag. Any pools that are empty and not used since the last cleanup |
| | | 974 | | // will be purged next time around. |
| | 0 | 975 | | _usedSinceLastCleanup = false; |
| | | 976 | | |
| | 0 | 977 | | ScavengeHttp11ConnectionStack(this, _http11Connections, ref toDispose, nowTicks, pooledConnectionLifetim |
| | | 978 | | |
| | 0 | 979 | | if (_availableHttp2Connections is not null) |
| | 0 | 980 | | { |
| | 0 | 981 | | int removed = ScavengeHttp2ConnectionList(_availableHttp2Connections, ref toDispose, nowTicks, poole |
| | 0 | 982 | | _associatedHttp2ConnectionCount -= removed; |
| | | 983 | | |
| | | 984 | | // Note: Http11 connections will decrement the _associatedHttp11ConnectionCount when disposed. |
| | | 985 | | // Http2 connections will not, hence the difference in handing _associatedHttp2ConnectionCount. |
| | 0 | 986 | | } |
| | 0 | 987 | | if (GlobalHttpSettings.SocketsHttpHandler.AllowHttp3 && _availableHttp3Connections is not null) |
| | 0 | 988 | | { |
| | 0 | 989 | | int removed = ScavengeHttp3ConnectionList(_availableHttp3Connections, ref toDispose, nowTicks, poole |
| | 0 | 990 | | _associatedHttp3ConnectionCount -= removed; |
| | | 991 | | |
| | | 992 | | // Note: Http11 connections will decrement the _associatedHttp11ConnectionCount when disposed. |
| | | 993 | | // Http3 connections will not, hence the difference in handing _associatedHttp3ConnectionCount. |
| | 0 | 994 | | } |
| | 0 | 995 | | } |
| | | 996 | | |
| | | 997 | | // Dispose the stale connections outside the pool lock, to avoid holding the lock too long. |
| | | 998 | | // Dispose them asynchronously to not to block the caller on closing the SslStream or NetworkStream. |
| | 0 | 999 | | if (toDispose is not null) |
| | 0 | 1000 | | { |
| | 0 | 1001 | | Task.Factory.StartNew(static s => ((List<HttpConnectionBase>)s!).ForEach(c => c.Dispose()), toDispose, |
| | 0 | 1002 | | CancellationToken.None, TaskCreationOptions.DenyChildAttach, TaskScheduler.Default); |
| | 0 | 1003 | | } |
| | | 1004 | | |
| | | 1005 | | // Pool is active. Should not be removed. |
| | 0 | 1006 | | return false; |
| | 0 | 1007 | | } |
| | | 1008 | | |
| | | 1009 | | // For diagnostic purposes |
| | | 1010 | | public override string ToString() => |
| | 0 | 1011 | | $"{nameof(HttpConnectionPool)} " + |
| | 0 | 1012 | | (_proxyUri == null ? |
| | 0 | 1013 | | (_sslOptionsHttp11 == null ? |
| | 0 | 1014 | | $"http://{_originAuthority}" : |
| | 0 | 1015 | | $"https://{_originAuthority}" + (_sslOptionsHttp11.TargetHost != _originAuthority.IdnHost ? $", SSL |
| | 0 | 1016 | | (_sslOptionsHttp11 == null ? |
| | 0 | 1017 | | $"Proxy {_proxyUri}" : |
| | 0 | 1018 | | $"https://{_originAuthority}/ tunnelled via Proxy {_proxyUri}" + (_sslOptionsHttp11.TargetHost != _o |
| | | 1019 | | |
| | | 1020 | | public void Trace(string? message, [CallerMemberName] string? memberName = null) => |
| | 0 | 1021 | | NetEventSource.Log.HandlerMessage( |
| | 0 | 1022 | | GetHashCode(), // pool ID |
| | 0 | 1023 | | 0, // connection ID |
| | 0 | 1024 | | 0, // request ID |
| | 0 | 1025 | | memberName, // method name |
| | 0 | 1026 | | message); // message |
| | | 1027 | | } |
| | | 1028 | | } |