-
Notifications
You must be signed in to change notification settings - Fork 4.9k
/
Copy pathHttpConnectionPool.cs
2582 lines (2203 loc) · 119 KB
/
HttpConnectionPool.cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
using System.Collections.Generic;
using System.Diagnostics;
using System.Diagnostics.CodeAnalysis;
using System.Globalization;
using System.IO;
using System.Net.Http.Headers;
using System.Net.Http.HPack;
using System.Net.Http.QPack;
using System.Net.Quic;
using System.Net.Security;
using System.Net.Sockets;
using System.Runtime.CompilerServices;
using System.Runtime.ExceptionServices;
using System.Runtime.Versioning;
using System.Security.Authentication;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
namespace System.Net.Http
{
/// <summary>Provides a pool of connections to the same endpoint.</summary>
internal sealed class HttpConnectionPool : IDisposable
{
private static readonly bool s_isWindows7Or2008R2 = GetIsWindows7Or2008R2();
private readonly HttpConnectionPoolManager _poolManager;
private readonly HttpConnectionKind _kind;
private readonly Uri? _proxyUri;
/// <summary>The origin authority used to construct the <see cref="HttpConnectionPool"/>.</summary>
private readonly HttpAuthority? _originAuthority;
/// <summary>Initially set to null, this can be set to enable HTTP/3 based on Alt-Svc.</summary>
private volatile HttpAuthority? _http3Authority;
/// <summary>A timer to expire <see cref="_http3Authority"/> and return the pool to <see cref="_originAuthority"/>. Initialized on first use.</summary>
private Timer? _authorityExpireTimer;
/// <summary>If true, the <see cref="_http3Authority"/> will persist across a network change. If false, it will be reset to <see cref="_originAuthority"/>.</summary>
private bool _persistAuthority;
/// <summary>
/// When an Alt-Svc authority fails due to 421 Misdirected Request, it is placed in the blocklist to be ignored
/// for <see cref="AltSvcBlocklistTimeoutInMilliseconds"/> milliseconds. Initialized on first use.
/// </summary>
private volatile Dictionary<HttpAuthority, Exception?>? _altSvcBlocklist;
private CancellationTokenSource? _altSvcBlocklistTimerCancellation;
private volatile bool _altSvcEnabled = true;
/// <summary>The maximum number of times to retry a request after a failure on an established connection.</summary>
private const int MaxConnectionFailureRetries = 3;
/// <summary>
/// If <see cref="_altSvcBlocklist"/> exceeds this size, Alt-Svc will be disabled entirely for <see cref="AltSvcBlocklistTimeoutInMilliseconds"/> milliseconds.
/// This is to prevent a failing server from bloating the dictionary beyond a reasonable value.
/// </summary>
private const int MaxAltSvcIgnoreListSize = 8;
/// <summary>The time, in milliseconds, that an authority should remain in <see cref="_altSvcBlocklist"/>.</summary>
private const int AltSvcBlocklistTimeoutInMilliseconds = 10 * 60 * 1000;
// HTTP/1.1 connection pool
/// <summary>List of available HTTP/1.1 connections stored in the pool.</summary>
private readonly List<HttpConnection> _availableHttp11Connections = new List<HttpConnection>();
/// <summary>The maximum number of HTTP/1.1 connections allowed to be associated with the pool.</summary>
private readonly int _maxHttp11Connections;
/// <summary>The number of HTTP/1.1 connections associated with the pool, including in use, available, and pending.</summary>
private int _associatedHttp11ConnectionCount;
/// <summary>The number of HTTP/1.1 connections that are in the process of being established.</summary>
private int _pendingHttp11ConnectionCount;
/// <summary>Queue of requests waiting for an HTTP/1.1 connection.</summary>
private RequestQueue<HttpConnection> _http11RequestQueue;
// HTTP/2 connection pool
/// <summary>List of available HTTP/2 connections stored in the pool.</summary>
private List<Http2Connection>? _availableHttp2Connections;
/// <summary>The number of HTTP/2 connections associated with the pool, including in use, available, and pending.</summary>
private int _associatedHttp2ConnectionCount;
/// <summary>Indicates whether an HTTP/2 connection is in the process of being established.</summary>
private bool _pendingHttp2Connection;
/// <summary>Queue of requests waiting for an HTTP/2 connection.</summary>
private RequestQueue<Http2Connection?> _http2RequestQueue;
private bool _http2Enabled;
private byte[]? _http2AltSvcOriginUri;
internal readonly byte[]? _http2EncodedAuthorityHostHeader;
private readonly bool _http3Enabled;
private Http3Connection? _http3Connection;
private SemaphoreSlim? _http3ConnectionCreateLock;
internal readonly byte[]? _http3EncodedAuthorityHostHeader;
/// <summary>For non-proxy connection pools, this is the host name in bytes; for proxies, null.</summary>
private readonly byte[]? _hostHeaderValueBytes;
/// <summary>Options specialized and cached for this pool and its key.</summary>
private readonly SslClientAuthenticationOptions? _sslOptionsHttp11;
private readonly SslClientAuthenticationOptions? _sslOptionsHttp2;
private readonly SslClientAuthenticationOptions? _sslOptionsHttp2Only;
private readonly SslClientAuthenticationOptions? _sslOptionsHttp3;
/// <summary>Whether the pool has been used since the last time a cleanup occurred.</summary>
private bool _usedSinceLastCleanup = true;
/// <summary>Whether the pool has been disposed.</summary>
private bool _disposed;
public const int DefaultHttpPort = 80;
public const int DefaultHttpsPort = 443;
/// <summary>Initializes the pool.</summary>
/// <param name="poolManager">The manager associated with this pool.</param>
/// <param name="kind">The kind of HTTP connections stored in this pool.</param>
/// <param name="host">The host with which this pool is associated.</param>
/// <param name="port">The port with which this pool is associated.</param>
/// <param name="sslHostName">The SSL host with which this pool is associated.</param>
/// <param name="proxyUri">The proxy this pool targets (optional).</param>
public HttpConnectionPool(HttpConnectionPoolManager poolManager, HttpConnectionKind kind, string? host, int port, string? sslHostName, Uri? proxyUri)
{
_poolManager = poolManager;
_kind = kind;
_proxyUri = proxyUri;
_maxHttp11Connections = Settings._maxConnectionsPerServer;
if (host != null)
{
_originAuthority = new HttpAuthority(host, port);
}
_http2Enabled = _poolManager.Settings._maxHttpVersion >= HttpVersion.Version20;
if (IsHttp3Supported())
{
_http3Enabled = _poolManager.Settings._maxHttpVersion >= HttpVersion.Version30 && QuicConnection.IsSupported;
}
switch (kind)
{
case HttpConnectionKind.Http:
Debug.Assert(host != null);
Debug.Assert(port != 0);
Debug.Assert(sslHostName == null);
Debug.Assert(proxyUri == null);
_http3Enabled = false;
break;
case HttpConnectionKind.Https:
Debug.Assert(host != null);
Debug.Assert(port != 0);
Debug.Assert(sslHostName != null);
Debug.Assert(proxyUri == null);
break;
case HttpConnectionKind.Proxy:
Debug.Assert(host == null);
Debug.Assert(port == 0);
Debug.Assert(sslHostName == null);
Debug.Assert(proxyUri != null);
_http2Enabled = false;
_http3Enabled = false;
break;
case HttpConnectionKind.ProxyTunnel:
Debug.Assert(host != null);
Debug.Assert(port != 0);
Debug.Assert(sslHostName == null);
Debug.Assert(proxyUri != null);
_http2Enabled = false;
_http3Enabled = false;
break;
case HttpConnectionKind.SslProxyTunnel:
Debug.Assert(host != null);
Debug.Assert(port != 0);
Debug.Assert(sslHostName != null);
Debug.Assert(proxyUri != null);
_http3Enabled = false; // TODO: how do we tunnel HTTP3?
break;
case HttpConnectionKind.ProxyConnect:
Debug.Assert(host != null);
Debug.Assert(port != 0);
Debug.Assert(sslHostName == null);
Debug.Assert(proxyUri != null);
// Don't enforce the max connections limit on proxy tunnels; this would mean that connections to different origin servers
// would compete for the same limited number of connections.
// We will still enforce this limit on the user of the tunnel (i.e. ProxyTunnel or SslProxyTunnel).
_maxHttp11Connections = int.MaxValue;
_http2Enabled = false;
_http3Enabled = false;
break;
case HttpConnectionKind.SocksTunnel:
case HttpConnectionKind.SslSocksTunnel:
Debug.Assert(host != null);
Debug.Assert(port != 0);
Debug.Assert(proxyUri != null);
_http3Enabled = false; // TODO: SOCKS supports UDP and may be used for HTTP3
break;
default:
Debug.Fail("Unknown HttpConnectionKind in HttpConnectionPool.ctor");
break;
}
if (!_http3Enabled)
{
// Avoid parsing Alt-Svc headers if they won't be used.
_altSvcEnabled = false;
}
string? hostHeader = null;
if (_originAuthority != null)
{
// Precalculate ASCII bytes for Host header
// Note that if _host is null, this is a (non-tunneled) proxy connection, and we can't cache the hostname.
hostHeader =
(_originAuthority.Port != (sslHostName == null ? DefaultHttpPort : DefaultHttpsPort)) ?
$"{_originAuthority.HostValue}:{_originAuthority.Port}" :
_originAuthority.HostValue;
// Note the IDN hostname should always be ASCII, since it's already been IDNA encoded.
_hostHeaderValueBytes = Encoding.ASCII.GetBytes(hostHeader);
Debug.Assert(Encoding.ASCII.GetString(_hostHeaderValueBytes) == hostHeader);
if (sslHostName == null)
{
_http2EncodedAuthorityHostHeader = HPackEncoder.EncodeLiteralHeaderFieldWithoutIndexingToAllocatedArray(H2StaticTable.Authority, hostHeader);
_http3EncodedAuthorityHostHeader = QPackEncoder.EncodeLiteralHeaderFieldWithStaticNameReferenceToArray(H3StaticTable.Authority, hostHeader);
}
}
if (sslHostName != null)
{
_sslOptionsHttp11 = ConstructSslOptions(poolManager, sslHostName);
_sslOptionsHttp11.ApplicationProtocols = null;
if (_http2Enabled)
{
_sslOptionsHttp2 = ConstructSslOptions(poolManager, sslHostName);
_sslOptionsHttp2.ApplicationProtocols = s_http2ApplicationProtocols;
_sslOptionsHttp2Only = ConstructSslOptions(poolManager, sslHostName);
_sslOptionsHttp2Only.ApplicationProtocols = s_http2OnlyApplicationProtocols;
// Note:
// The HTTP/2 specification states:
// "A deployment of HTTP/2 over TLS 1.2 MUST disable renegotiation.
// An endpoint MUST treat a TLS renegotiation as a connection error (Section 5.4.1)
// of type PROTOCOL_ERROR."
// which suggests we should do:
// _sslOptionsHttp2.AllowRenegotiation = false;
// However, if AllowRenegotiation is set to false, that will also prevent
// renegotation if the server denies the HTTP/2 request and causes a
// downgrade to HTTP/1.1, and the current APIs don't provide a mechanism
// by which AllowRenegotiation could be set back to true in that case.
// For now, if an HTTP/2 server erroneously issues a renegotiation, we'll
// allow it.
Debug.Assert(hostHeader != null);
_http2EncodedAuthorityHostHeader = HPackEncoder.EncodeLiteralHeaderFieldWithoutIndexingToAllocatedArray(H2StaticTable.Authority, hostHeader);
_http3EncodedAuthorityHostHeader = QPackEncoder.EncodeLiteralHeaderFieldWithStaticNameReferenceToArray(H3StaticTable.Authority, hostHeader);
}
if (IsHttp3Supported())
{
if (_http3Enabled)
{
_sslOptionsHttp3 = ConstructSslOptions(poolManager, sslHostName);
_sslOptionsHttp3.ApplicationProtocols = s_http3ApplicationProtocols;
}
}
}
// Set up for PreAuthenticate. Access to this cache is guarded by a lock on the cache itself.
if (_poolManager.Settings._preAuthenticate)
{
PreAuthCredentials = new CredentialCache();
}
_http11RequestQueue = new RequestQueue<HttpConnection>();
if (_http2Enabled)
{
_http2RequestQueue = new RequestQueue<Http2Connection?>();
}
if (NetEventSource.Log.IsEnabled()) Trace($"{this}");
}
[SupportedOSPlatformGuard("linux")]
[SupportedOSPlatformGuard("macOS")]
[SupportedOSPlatformGuard("Windows")]
internal static bool IsHttp3Supported() => (OperatingSystem.IsLinux() && !OperatingSystem.IsAndroid()) || OperatingSystem.IsWindows() || OperatingSystem.IsMacOS();
private static readonly List<SslApplicationProtocol> s_http3ApplicationProtocols = new List<SslApplicationProtocol>() { SslApplicationProtocol.Http3 };
private static readonly List<SslApplicationProtocol> s_http2ApplicationProtocols = new List<SslApplicationProtocol>() { SslApplicationProtocol.Http2, SslApplicationProtocol.Http11 };
private static readonly List<SslApplicationProtocol> s_http2OnlyApplicationProtocols = new List<SslApplicationProtocol>() { SslApplicationProtocol.Http2 };
private static SslClientAuthenticationOptions ConstructSslOptions(HttpConnectionPoolManager poolManager, string sslHostName)
{
Debug.Assert(sslHostName != null);
SslClientAuthenticationOptions sslOptions = poolManager.Settings._sslOptions?.ShallowClone() ?? new SslClientAuthenticationOptions();
// Set TargetHost for SNI
sslOptions.TargetHost = sslHostName;
// Windows 7 and Windows 2008 R2 support TLS 1.1 and 1.2, but for legacy reasons by default those protocols
// are not enabled when a developer elects to use the system default. However, in .NET Core 2.0 and earlier,
// HttpClientHandler would enable them, due to being a wrapper for WinHTTP, which enabled them. Both for
// compatibility and because we prefer those higher protocols whenever possible, SocketsHttpHandler also
// pretends they're part of the default when running on Win7/2008R2.
if (s_isWindows7Or2008R2 && sslOptions.EnabledSslProtocols == SslProtocols.None)
{
if (NetEventSource.Log.IsEnabled())
{
NetEventSource.Info(poolManager, $"Win7OrWin2K8R2 platform, Changing default TLS protocols to {SecurityProtocol.DefaultSecurityProtocols}");
}
sslOptions.EnabledSslProtocols = SecurityProtocol.DefaultSecurityProtocols;
}
return sslOptions;
}
public HttpAuthority? OriginAuthority => _originAuthority;
public HttpConnectionSettings Settings => _poolManager.Settings;
public HttpConnectionKind Kind => _kind;
public bool IsSecure => _kind == HttpConnectionKind.Https || _kind == HttpConnectionKind.SslProxyTunnel || _kind == HttpConnectionKind.SslSocksTunnel;
public Uri? ProxyUri => _proxyUri;
public ICredentials? ProxyCredentials => _poolManager.ProxyCredentials;
public byte[]? HostHeaderValueBytes => _hostHeaderValueBytes;
public CredentialCache? PreAuthCredentials { get; }
/// <summary>
/// An ASCII origin string per RFC 6454 Section 6.2, in format <scheme>://<host>[:<port>]
/// </summary>
/// <remarks>
/// Used by <see cref="Http2Connection"/> to test ALTSVC frames for our origin.
/// </remarks>
public byte[] Http2AltSvcOriginUri
{
get
{
if (_http2AltSvcOriginUri == null)
{
var sb = new StringBuilder();
Debug.Assert(_originAuthority != null);
sb.Append(IsSecure ? "https://" : "http://")
.Append(_originAuthority.IdnHost);
if (_originAuthority.Port != (IsSecure ? DefaultHttpsPort : DefaultHttpPort))
{
sb.Append(CultureInfo.InvariantCulture, $":{_originAuthority.Port}");
}
_http2AltSvcOriginUri = Encoding.ASCII.GetBytes(sb.ToString());
}
return _http2AltSvcOriginUri;
}
}
private bool EnableMultipleHttp2Connections => _poolManager.Settings.EnableMultipleHttp2Connections;
/// <summary>Object used to synchronize access to state in the pool.</summary>
private object SyncObj
{
get
{
Debug.Assert(!Monitor.IsEntered(_availableHttp11Connections));
return _availableHttp11Connections;
}
}
private bool HasSyncObjLock => Monitor.IsEntered(_availableHttp11Connections);
// Overview of connection management (mostly HTTP version independent):
//
// Each version of HTTP (1.1, 2, 3) has its own connection pool, and each of these work in a similar manner,
// allowing for differences between the versions (most notably, HTTP/1.1 is not multiplexed.)
//
// When a request is submitted for a particular version (e.g. HTTP/1.1), we first look in the pool for available connections.
// An "available" connection is one that is (hopefully) usable for a new request.
// For HTTP/1.1, this is just an idle connection.
// For HTTP2/3, this is a connection that (hopefully) has available streams to use for new requests.
// If we find an available connection, we will attempt to validate it and then use it.
// We check the lifetime of the connection and discard it if the lifetime is exceeded.
// We check that the connection has not shut down; if so we discard it.
// For HTTP2/3, we reserve a stream on the connection. If this fails, we cannot use the connection right now.
// If validation fails, we will attempt to find a different available connection.
//
// Once we have found a usable connection, we use it to process the request.
// For HTTP/1.1, a connection can handle only a single request at a time, thus it is immediately removed from the list of available connections.
// For HTTP2/3, a connection is only removed from the available list when it has no more available streams.
// In either case, the connection still counts against the total associated connection count for the pool.
//
// If we cannot find a usable available connection, then the request is added the to the request queue for the appropriate version.
//
// Whenever a request is queued, or an existing connection shuts down, we will check to see if we should inject a new connection.
// Injection policy depends on both user settings and some simple heuristics.
// See comments on the relevant routines for details on connection injection policy.
//
// When a new connection is successfully created, or an existing unavailable connection becomes available again,
// we will attempt to use this connection to handle any queued requests (subject to lifetime restrictions on existing connections).
// This may result in the connection becoming unavailable again, because it cannot handle any more requests at the moment.
// If not, we will return the connection to the pool as an available connection for use by new requests.
//
// When a connection shuts down, either gracefully (e.g. GOAWAY) or abortively (e.g. IOException),
// we will remove it from the list of available connections, if it is present there.
// If not, then it must be unavailable at the moment; we will detect this and ensure it is not added back to the available pool.
[DoesNotReturn]
private static void ThrowGetVersionException(HttpRequestMessage request, int desiredVersion, Exception? inner = null)
{
Debug.Assert(desiredVersion == 2 || desiredVersion == 3);
throw new HttpRequestException(SR.Format(SR.net_http_requested_version_cannot_establish, request.Version, request.VersionPolicy, desiredVersion), inner);
}
private bool CheckExpirationOnGet(HttpConnectionBase connection)
{
TimeSpan pooledConnectionLifetime = _poolManager.Settings._pooledConnectionLifetime;
if (pooledConnectionLifetime != Timeout.InfiniteTimeSpan)
{
return connection.GetLifetimeTicks(Environment.TickCount64) > pooledConnectionLifetime.TotalMilliseconds;
}
return false;
}
private static Exception CreateConnectTimeoutException(OperationCanceledException oce)
{
// The pattern for request timeouts (on HttpClient) is to throw an OCE with an inner exception of TimeoutException.
// Do the same for ConnectTimeout-based timeouts.
TimeoutException te = new TimeoutException(SR.net_http_connect_timedout, oce.InnerException);
Exception newException = CancellationHelper.CreateOperationCanceledException(te, oce.CancellationToken);
ExceptionDispatchInfo.SetCurrentStackTrace(newException);
return newException;
}
private async Task AddHttp11ConnectionAsync(RequestQueue<HttpConnection>.QueueItem queueItem)
{
if (NetEventSource.Log.IsEnabled()) Trace("Creating new HTTP/1.1 connection for pool.");
HttpConnectionWaiter<HttpConnection> waiter = queueItem.Waiter;
HttpConnection? connection = null;
Exception? connectionException = null;
CancellationTokenSource cts = GetConnectTimeoutCancellationTokenSource();
waiter.ConnectionCancellationTokenSource = cts;
try
{
connection = await CreateHttp11ConnectionAsync(queueItem.Request, true, cts.Token).ConfigureAwait(false);
}
catch (Exception e)
{
connectionException = e is OperationCanceledException oce && oce.CancellationToken == cts.Token && !waiter.CancelledByOriginatingRequestCompletion ?
CreateConnectTimeoutException(oce) :
e;
}
finally
{
lock (waiter)
{
waiter.ConnectionCancellationTokenSource = null;
cts.Dispose();
}
}
if (connection is not null)
{
// Add the established connection to the pool.
ReturnHttp11Connection(connection, isNewConnection: true, queueItem.Waiter);
}
else
{
Debug.Assert(connectionException is not null);
HandleHttp11ConnectionFailure(waiter, connectionException);
}
}
private void CheckForHttp11ConnectionInjection()
{
Debug.Assert(HasSyncObjLock);
_http11RequestQueue.PruneCompletedRequestsFromHeadOfQueue(this);
// Determine if we can and should add a new connection to the pool.
bool willInject = _availableHttp11Connections.Count == 0 && // No available connections
_http11RequestQueue.Count > _pendingHttp11ConnectionCount && // More requests queued than pending connections
_associatedHttp11ConnectionCount < _maxHttp11Connections && // Under the connection limit
_http11RequestQueue.RequestsWithoutAConnectionAttempt > 0; // There are requests we haven't issued a connection attempt for
if (NetEventSource.Log.IsEnabled())
{
Trace($"Available HTTP/1.1 connections: {_availableHttp11Connections.Count}, Requests in the queue: {_http11RequestQueue.Count}, " +
$"Requests without a connection attempt: {_http11RequestQueue.RequestsWithoutAConnectionAttempt}, " +
$"Pending HTTP/1.1 connections: {_pendingHttp11ConnectionCount}, Total associated HTTP/1.1 connections: {_associatedHttp11ConnectionCount}, " +
$"Max HTTP/1.1 connection limit: {_maxHttp11Connections}, " +
$"Will inject connection: {willInject}.");
}
if (willInject)
{
_associatedHttp11ConnectionCount++;
_pendingHttp11ConnectionCount++;
RequestQueue<HttpConnection>.QueueItem queueItem = _http11RequestQueue.PeekNextRequestForConnectionAttempt();
// Queue the creation of the connection to escape the held lock
ThreadPool.QueueUserWorkItem(static state =>
{
_ = state.thisRef.AddHttp11ConnectionAsync(state.queueItem); // ignore returned task
}, (thisRef: this, queueItem), preferLocal: true);
}
}
private bool TryGetPooledHttp11Connection(HttpRequestMessage request, bool async, [NotNullWhen(true)] out HttpConnection? connection, [NotNullWhen(false)] out HttpConnectionWaiter<HttpConnection>? waiter)
{
while (true)
{
lock (SyncObj)
{
_usedSinceLastCleanup = true;
int availableConnectionCount = _availableHttp11Connections.Count;
if (availableConnectionCount > 0)
{
// We have a connection that we can attempt to use.
// Validate it below outside the lock, to avoid doing expensive operations while holding the lock.
connection = _availableHttp11Connections[availableConnectionCount - 1];
_availableHttp11Connections.RemoveAt(availableConnectionCount - 1);
}
else
{
// No available connections. Add to the request queue.
waiter = _http11RequestQueue.EnqueueRequest(request);
CheckForHttp11ConnectionInjection();
// There were no available idle connections. This request has been added to the request queue.
if (NetEventSource.Log.IsEnabled()) Trace($"No available HTTP/1.1 connections; request queued.");
connection = null;
return false;
}
}
if (CheckExpirationOnGet(connection))
{
if (NetEventSource.Log.IsEnabled()) connection.Trace("Found expired HTTP/1.1 connection in pool.");
connection.Dispose();
continue;
}
if (!connection.PrepareForReuse(async))
{
if (NetEventSource.Log.IsEnabled()) connection.Trace("Found invalid HTTP/1.1 connection in pool.");
connection.Dispose();
continue;
}
if (NetEventSource.Log.IsEnabled()) connection.Trace("Found usable HTTP/1.1 connection in pool.");
waiter = null;
return true;
}
}
private async Task HandleHttp11Downgrade(HttpRequestMessage request, Stream stream, TransportContext? transportContext, CancellationToken cancellationToken)
{
if (NetEventSource.Log.IsEnabled()) Trace("Server does not support HTTP2; disabling HTTP2 use and proceeding with HTTP/1.1 connection");
bool canUse = true;
HttpConnectionWaiter<Http2Connection?>? waiter = null;
lock (SyncObj)
{
Debug.Assert(_pendingHttp2Connection);
Debug.Assert(_associatedHttp2ConnectionCount > 0);
// Server does not support HTTP2. Disable further HTTP2 attempts.
_http2Enabled = false;
_associatedHttp2ConnectionCount--;
_pendingHttp2Connection = false;
if (_associatedHttp11ConnectionCount < _maxHttp11Connections)
{
_associatedHttp11ConnectionCount++;
_pendingHttp11ConnectionCount++;
}
else
{
// We are already at the limit for HTTP/1.1 connections, so do not proceed with this connection.
canUse = false;
}
_http2RequestQueue.TryDequeueWaiter(this, out waiter);
}
// Signal to any queued HTTP2 requests that they must downgrade.
while (waiter is not null)
{
if (NetEventSource.Log.IsEnabled()) Trace("Downgrading queued HTTP2 request to HTTP/1.1");
// We are done with the HTTP2 connection attempt, no point to cancel it.
Volatile.Write(ref waiter.ConnectionCancellationTokenSource, null);
// We don't care if this fails; that means the request was previously canceled or handeled by a different connection.
waiter.TrySetResult(null);
lock (SyncObj)
{
_http2RequestQueue.TryDequeueWaiter(this, out waiter);
}
}
if (!canUse)
{
if (NetEventSource.Log.IsEnabled()) Trace("Discarding downgraded HTTP/1.1 connection because HTTP/1.1 connection limit is exceeded");
stream.Dispose();
}
HttpConnection http11Connection;
try
{
// Note, the same CancellationToken from the original HTTP2 connection establishment still applies here.
http11Connection = await ConstructHttp11ConnectionAsync(true, stream, transportContext, request, cancellationToken).ConfigureAwait(false);
}
catch (OperationCanceledException oce) when (oce.CancellationToken == cancellationToken)
{
HandleHttp11ConnectionFailure(requestWaiter: null, CreateConnectTimeoutException(oce));
return;
}
catch (Exception e)
{
HandleHttp11ConnectionFailure(requestWaiter: null, e);
return;
}
ReturnHttp11Connection(http11Connection, isNewConnection: true);
}
private async Task AddHttp2ConnectionAsync(RequestQueue<Http2Connection?>.QueueItem queueItem)
{
if (NetEventSource.Log.IsEnabled()) Trace("Creating new HTTP/2 connection for pool.");
Http2Connection? connection = null;
Exception? connectionException = null;
HttpConnectionWaiter<Http2Connection?> waiter = queueItem.Waiter;
CancellationTokenSource cts = GetConnectTimeoutCancellationTokenSource();
waiter.ConnectionCancellationTokenSource = cts;
try
{
(Stream stream, TransportContext? transportContext) = await ConnectAsync(queueItem.Request, true, cts.Token).ConfigureAwait(false);
if (IsSecure)
{
SslStream sslStream = (SslStream)stream;
if (sslStream.NegotiatedApplicationProtocol == SslApplicationProtocol.Http2)
{
// The server accepted our request for HTTP2.
if (sslStream.SslProtocol < SslProtocols.Tls12)
{
stream.Dispose();
connectionException = new HttpRequestException(SR.Format(SR.net_ssl_http2_requires_tls12, sslStream.SslProtocol));
}
else
{
connection = await ConstructHttp2ConnectionAsync(stream, queueItem.Request, cts.Token).ConfigureAwait(false);
}
}
else
{
// We established an SSL connection, but the server denied our request for HTTP2.
await HandleHttp11Downgrade(queueItem.Request, stream, transportContext, cts.Token).ConfigureAwait(false);
return;
}
}
else
{
connection = await ConstructHttp2ConnectionAsync(stream, queueItem.Request, cts.Token).ConfigureAwait(false);
}
}
catch (Exception e)
{
connectionException = e is OperationCanceledException oce && oce.CancellationToken == cts.Token && !waiter.CancelledByOriginatingRequestCompletion ?
CreateConnectTimeoutException(oce) :
e;
}
finally
{
lock (waiter)
{
waiter.ConnectionCancellationTokenSource = null;
cts.Dispose();
}
}
if (connection is not null)
{
// Register for shutdown notification.
// Do this before we return the connection to the pool, because that may result in it being disposed.
ValueTask shutdownTask = connection.WaitForShutdownAsync();
// Add the new connection to the pool.
ReturnHttp2Connection(connection, isNewConnection: true, queueItem.Waiter);
// Wait for connection shutdown.
await shutdownTask.ConfigureAwait(false);
InvalidateHttp2Connection(connection);
}
else
{
Debug.Assert(connectionException is not null);
HandleHttp2ConnectionFailure(waiter, connectionException);
}
}
private void CheckForHttp2ConnectionInjection()
{
Debug.Assert(HasSyncObjLock);
_http2RequestQueue.PruneCompletedRequestsFromHeadOfQueue(this);
// Determine if we can and should add a new connection to the pool.
int availableHttp2ConnectionCount = _availableHttp2Connections?.Count ?? 0;
bool willInject = availableHttp2ConnectionCount == 0 && // No available connections
!_pendingHttp2Connection && // Only allow one pending HTTP2 connection at a time
_http2RequestQueue.Count > 0 && // There are requests left on the queue
(_associatedHttp2ConnectionCount == 0 || EnableMultipleHttp2Connections) && // We allow multiple connections, or don't have a connection currently
_http2RequestQueue.RequestsWithoutAConnectionAttempt > 0; // There are requests we haven't issued a connection attempt for
if (NetEventSource.Log.IsEnabled())
{
Trace($"Available HTTP/2.0 connections: {availableHttp2ConnectionCount}, " +
$"Pending HTTP/2.0 connection: {_pendingHttp2Connection}" +
$"Requests in the queue: {_http2RequestQueue.Count}, " +
$"Requests without a connection attempt: {_http2RequestQueue.RequestsWithoutAConnectionAttempt}, " +
$"Total associated HTTP/2.0 connections: {_associatedHttp2ConnectionCount}, " +
$"Will inject connection: {willInject}.");
}
if (willInject)
{
_associatedHttp2ConnectionCount++;
_pendingHttp2Connection = true;
RequestQueue<Http2Connection?>.QueueItem queueItem = _http2RequestQueue.PeekNextRequestForConnectionAttempt();
// Queue the creation of the connection to escape the held lock
ThreadPool.QueueUserWorkItem(static state =>
{
_ = state.thisRef.AddHttp2ConnectionAsync(state.queueItem); // ignore returned task
}, (thisRef: this, queueItem), preferLocal: true);
}
}
private bool TryGetPooledHttp2Connection(HttpRequestMessage request, bool async, [NotNullWhen(true)] out Http2Connection? connection, out HttpConnectionWaiter<Http2Connection?>? waiter)
{
Debug.Assert(_kind == HttpConnectionKind.Https || _kind == HttpConnectionKind.SslProxyTunnel || _kind == HttpConnectionKind.Http || _kind == HttpConnectionKind.SocksTunnel || _kind == HttpConnectionKind.SslSocksTunnel);
// Look for a usable connection.
while (true)
{
lock (SyncObj)
{
_usedSinceLastCleanup = true;
if (!_http2Enabled)
{
waiter = null;
connection = null;
return false;
}
int availableConnectionCount = _availableHttp2Connections?.Count ?? 0;
if (availableConnectionCount > 0)
{
// We have a connection that we can attempt to use.
// Validate it below outside the lock, to avoid doing expensive operations while holding the lock.
connection = _availableHttp2Connections![availableConnectionCount - 1];
}
else
{
// No available connections. Add to the request queue.
waiter = _http2RequestQueue.EnqueueRequest(request);
CheckForHttp2ConnectionInjection();
// There were no available connections. This request has been added to the request queue.
if (NetEventSource.Log.IsEnabled()) Trace($"No available HTTP/2 connections; request queued.");
connection = null;
return false;
}
}
if (CheckExpirationOnGet(connection))
{
if (NetEventSource.Log.IsEnabled()) connection.Trace("Found expired HTTP/2 connection in pool.");
InvalidateHttp2Connection(connection);
continue;
}
if (!connection.TryReserveStream())
{
if (NetEventSource.Log.IsEnabled()) connection.Trace("Found HTTP/2 connection in pool without available streams.");
bool found = false;
lock (SyncObj)
{
int index = _availableHttp2Connections.IndexOf(connection);
if (index != -1)
{
found = true;
_availableHttp2Connections.RemoveAt(index);
}
}
// If we didn't find the connection, then someone beat us to removing it (or it shut down)
if (found)
{
DisableHttp2Connection(connection);
}
continue;
}
if (NetEventSource.Log.IsEnabled()) connection.Trace("Found usable HTTP/2 connection in pool.");
waiter = null;
return true;
}
}
[SupportedOSPlatform("windows")]
[SupportedOSPlatform("linux")]
[SupportedOSPlatform("macos")]
private async ValueTask<Http3Connection> GetHttp3ConnectionAsync(HttpRequestMessage request, HttpAuthority authority, CancellationToken cancellationToken)
{
Debug.Assert(_kind == HttpConnectionKind.Https);
Debug.Assert(_http3Enabled);
Http3Connection? http3Connection = Volatile.Read(ref _http3Connection);
if (http3Connection != null)
{
if (CheckExpirationOnGet(http3Connection) || http3Connection.Authority != authority)
{
// Connection expired.
if (NetEventSource.Log.IsEnabled()) http3Connection.Trace("Found expired HTTP3 connection.");
http3Connection.Dispose();
InvalidateHttp3Connection(http3Connection);
}
else
{
// Connection exists and it is still good to use.
if (NetEventSource.Log.IsEnabled()) Trace("Using existing HTTP3 connection.");
_usedSinceLastCleanup = true;
return http3Connection;
}
}
// Ensure that the connection creation semaphore is created
if (_http3ConnectionCreateLock == null)
{
lock (SyncObj)
{
_http3ConnectionCreateLock ??= new SemaphoreSlim(1);
}
}
await _http3ConnectionCreateLock.WaitAsync(cancellationToken).ConfigureAwait(false);
try
{
if (_http3Connection != null)
{
// Someone beat us to creating the connection.
if (NetEventSource.Log.IsEnabled())
{
Trace("Using existing HTTP3 connection.");
}
return _http3Connection;
}
if (NetEventSource.Log.IsEnabled())
{
Trace("Attempting new HTTP3 connection.");
}
QuicConnection quicConnection;
try
{
quicConnection = await ConnectHelper.ConnectQuicAsync(request, new DnsEndPoint(authority.IdnHost, authority.Port), _poolManager.Settings._pooledConnectionIdleTimeout, _sslOptionsHttp3!, cancellationToken).ConfigureAwait(false);
}
catch (Exception e)
{
if (NetEventSource.Log.IsEnabled()) Trace($"QUIC connection failed: {e}");
// Disables HTTP/3 until server announces it can handle it via Alt-Svc.
BlocklistAuthority(authority, e);
throw;
}
//TODO: NegotiatedApplicationProtocol not yet implemented.
#if false
if (quicConnection.NegotiatedApplicationProtocol != SslApplicationProtocol.Http3)
{
BlocklistAuthority(authority);
throw new HttpRequestException("QUIC connected but no HTTP/3 indicated via ALPN.", null, RequestRetryType.RetryOnSameOrNextProxy);
}
#endif
// if the authority was sent as an option through alt-svc then include alt-used header
http3Connection = new Http3Connection(this, _originAuthority, authority, quicConnection, includeAltUsedHeader: _http3Authority == authority);
_http3Connection = http3Connection;
if (NetEventSource.Log.IsEnabled())
{
Trace("New HTTP3 connection established.");
}
return http3Connection;
}
finally
{
_http3ConnectionCreateLock.Release();
}
}
// Returns null if HTTP3 cannot be used.
[SupportedOSPlatform("windows")]
[SupportedOSPlatform("linux")]
[SupportedOSPlatform("macos")]
private async ValueTask<HttpResponseMessage?> TrySendUsingHttp3Async(HttpRequestMessage request, CancellationToken cancellationToken)
{
// Loop in case we get a 421 and need to send the request to a different authority.
while (true)
{
HttpAuthority? authority = _http3Authority;
// If H3 is explicitly requested, assume prenegotiated H3.
if (request.Version.Major >= 3 && request.VersionPolicy != HttpVersionPolicy.RequestVersionOrLower)
{
authority ??= _originAuthority;
}
if (authority == null)
{
return null;
}
Exception? reasonException;
if (IsAltSvcBlocked(authority, out reasonException))
{
ThrowGetVersionException(request, 3, reasonException);
}
long queueStartingTimestamp = HttpTelemetry.Log.IsEnabled() ? Stopwatch.GetTimestamp() : 0;
ValueTask<Http3Connection> connectionTask = GetHttp3ConnectionAsync(request, authority, cancellationToken);
if (HttpTelemetry.Log.IsEnabled() && connectionTask.IsCompleted)
{
// We avoid logging RequestLeftQueue if a stream was available immediately (synchronously)
queueStartingTimestamp = 0;
}
Http3Connection connection = await connectionTask.ConfigureAwait(false);
HttpResponseMessage response = await connection.SendAsync(request, queueStartingTimestamp, cancellationToken).ConfigureAwait(false);
// If an Alt-Svc authority returns 421, it means it can't actually handle the request.
// An authority is supposed to be able to handle ALL requests to the origin, so this is a server bug.
// In this case, we blocklist the authority and retry the request at the origin.
if (response.StatusCode == HttpStatusCode.MisdirectedRequest && connection.Authority != _originAuthority)
{
response.Dispose();
BlocklistAuthority(connection.Authority);
continue;
}
return response;
}
}
/// <summary>Check for the Alt-Svc header, to upgrade to HTTP/3.</summary>
private void ProcessAltSvc(HttpResponseMessage response)
{
if (_altSvcEnabled && response.Headers.TryGetValues(KnownHeaders.AltSvc.Descriptor, out IEnumerable<string>? altSvcHeaderValues))