-
Notifications
You must be signed in to change notification settings - Fork 4.9k
/
Copy pathHttpConnectionPool.cs
1948 lines (1672 loc) · 89 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;
using System.Collections.Generic;
using System.Diagnostics;
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.InteropServices;
using System.Security.Authentication;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.Extensions.Internal;
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 HashSet<HttpAuthority>? _altSvcBlocklist;
private CancellationTokenSource? _altSvcBlocklistTimerCancellation;
private volatile bool _altSvcEnabled = true;
/// <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;
/// <summary>List of idle connections stored in the pool.</summary>
private readonly List<CachedConnection> _idleConnections = new List<CachedConnection>();
/// <summary>The maximum number of connections allowed to be associated with the pool.</summary>
private readonly int _maxConnections;
private bool _http2Enabled;
// This array must be treated as immutable. It can only be replaced with a new value in AddHttp2Connection method.
private volatile Http2Connection[]? _http2Connections;
private SemaphoreSlim? _http2ConnectionCreateLock;
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>Queue of waiters waiting for a connection. Created on demand.</summary>
private Queue<TaskCompletionSourceWithCancellation<HttpConnection?>>? _waiters;
/// <summary>The number of connections associated with the pool. Some of these may be in <see cref="_idleConnections"/>, others may be in use.</summary>
private int _associatedConnectionCount;
/// <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>
/// <param name="maxConnections">The maximum number of connections allowed to be associated with the pool at any given time.</param>
public HttpConnectionPool(HttpConnectionPoolManager poolManager, HttpConnectionKind kind, string? host, int port, string? sslHostName, Uri? proxyUri, int maxConnections)
{
_poolManager = poolManager;
_kind = kind;
_proxyUri = proxyUri;
_maxConnections = maxConnections;
if (host != null)
{
_originAuthority = new HttpAuthority(host, port);
}
_http2Enabled = _poolManager.Settings._maxHttpVersion >= HttpVersion.Version20;
_http3Enabled = _poolManager.Settings._maxHttpVersion >= Http3Connection.HttpVersion30 && (_poolManager.Settings._quicImplementationProvider ?? QuicImplementationProviders.Default).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);
_http2Enabled = false;
_http3Enabled = false;
break;
default:
Debug.Fail("Unkown 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.IdnHost}:{_originAuthority.Port}" :
_originAuthority.IdnHost;
// 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 (_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();
}
if (NetEventSource.Log.IsEnabled()) Trace($"{this}");
}
private static readonly List<SslApplicationProtocol> s_http3ApplicationProtocols = new List<SslApplicationProtocol>() { Http3Connection.Http3ApplicationProtocol };
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;
public bool AnyProxyKind => (_proxyUri != null);
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(_kind == HttpConnectionKind.Https ? "https://" : "http://")
.Append(_originAuthority.IdnHost);
if (_originAuthority.Port != (_kind == HttpConnectionKind.Https ? DefaultHttpsPort : DefaultHttpPort))
{
sb
.Append(':')
.Append(_originAuthority.Port.ToString(CultureInfo.InvariantCulture));
}
_http2AltSvcOriginUri = Encoding.ASCII.GetBytes(sb.ToString());
}
return _http2AltSvcOriginUri;
}
}
public bool EnableMultipleHttp2Connections => _poolManager.Settings.EnableMultipleHttp2Connections;
/// <summary>Object used to synchronize access to state in the pool.</summary>
private object SyncObj => _idleConnections;
private ValueTask<(HttpConnectionBase? connection, bool isNewConnection, HttpResponseMessage? failureResponse)>
GetConnectionAsync(HttpRequestMessage request, bool async, CancellationToken cancellationToken)
{
// Do not even attempt at getting/creating a connection if it's already obvious we cannot provided the one requested.
if (request.VersionPolicy != HttpVersionPolicy.RequestVersionOrLower)
{
if (request.Version.Major == 3 && !_http3Enabled)
{
return ValueTask.FromException<(HttpConnectionBase? connection, bool isNewConnection, HttpResponseMessage? failureResponse)>(
new HttpRequestException(SR.Format(SR.net_http_requested_version_not_enabled, request.Version, request.VersionPolicy, 3)));
}
if (request.Version.Major == 2 && !_http2Enabled)
{
return ValueTask.FromException<(HttpConnectionBase? connection, bool isNewConnection, HttpResponseMessage? failureResponse)>(
new HttpRequestException(SR.Format(SR.net_http_requested_version_not_enabled, request.Version, request.VersionPolicy, 2)));
}
}
// Either H3 explicitly requested or secured upgraded allowed.
if (_http3Enabled && (request.Version.Major >= 3 || (request.VersionPolicy == HttpVersionPolicy.RequestVersionOrHigher && IsSecure)))
{
HttpAuthority? authority = _http3Authority;
// H3 is explicitly requested, assume prenegotiated H3.
if (request.Version.Major >= 3 && request.VersionPolicy != HttpVersionPolicy.RequestVersionOrLower)
{
authority = authority ?? _originAuthority;
}
if (authority != null)
{
if (IsAltSvcBlocked(authority))
{
return ValueTask.FromException<(HttpConnectionBase? connection, bool isNewConnection, HttpResponseMessage? failureResponse)>(
new HttpRequestException(SR.Format(SR.net_http_requested_version_cannot_establish, request.Version, request.VersionPolicy, 3)));
}
return GetHttp3ConnectionAsync(request, authority, cancellationToken);
}
}
// If we got here, we cannot provide HTTP/3 connection. Do not continue if downgrade is not allowed.
if (request.Version.Major >= 3 && request.VersionPolicy != HttpVersionPolicy.RequestVersionOrLower)
{
return ValueTask.FromException<(HttpConnectionBase? connection, bool isNewConnection, HttpResponseMessage? failureResponse)>(
new HttpRequestException(SR.Format(SR.net_http_requested_version_cannot_establish, request.Version, request.VersionPolicy, 3)));
}
if (_http2Enabled && (request.Version.Major >= 2 || (request.VersionPolicy == HttpVersionPolicy.RequestVersionOrHigher && IsSecure)) &&
// If the connection is not secured and downgrade is possible, prefer HTTP/1.1.
(request.VersionPolicy != HttpVersionPolicy.RequestVersionOrLower || IsSecure))
{
return GetHttp2ConnectionAsync(request, async, cancellationToken);
}
// If we got here, we cannot provide HTTP/2 connection. Do not continue if downgrade is not allowed.
if (request.Version.Major >= 2 && request.VersionPolicy != HttpVersionPolicy.RequestVersionOrLower)
{
return ValueTask.FromException<(HttpConnectionBase? connection, bool isNewConnection, HttpResponseMessage? failureResponse)>(
new HttpRequestException(SR.Format(SR.net_http_requested_version_cannot_establish, request.Version, request.VersionPolicy, 2)));
}
return GetHttpConnectionAsync(request, async, cancellationToken);
}
private ValueTask<HttpConnection?> GetOrReserveHttp11ConnectionAsync(bool async, CancellationToken cancellationToken)
{
if (cancellationToken.IsCancellationRequested)
{
return ValueTask.FromCanceled<HttpConnection?>(cancellationToken);
}
TimeSpan pooledConnectionLifetime = _poolManager.Settings._pooledConnectionLifetime;
long nowTicks = Environment.TickCount64;
List<CachedConnection> list = _idleConnections;
// Try to find a usable cached connection.
// If we can't find one, we will either wait for one to become available (if at the connection limit)
// or just increment the connection count and return null so the caller can create a new connection.
TaskCompletionSourceWithCancellation<HttpConnection?> waiter;
while (true)
{
CachedConnection cachedConnection;
lock (SyncObj)
{
if (list.Count > 0)
{
// We have a cached connection that we can attempt to use.
// Test it below outside the lock, to avoid doing expensive validation while holding the lock.
cachedConnection = list[list.Count - 1];
list.RemoveAt(list.Count - 1);
}
else
{
// No valid cached connections.
if (_associatedConnectionCount < _maxConnections)
{
// We are under the connection limit, so just increment the count and return null
// to indicate to the caller that they should create a new connection.
IncrementConnectionCountNoLock();
return new ValueTask<HttpConnection?>((HttpConnection?)null);
}
else
{
// We've reached the connection limit and need to wait for an existing connection
// to become available, or to be closed so that we can create a new connection.
// Enqueue a waiter that will be signalled when this happens.
// Break out of the loop and then do the actual wait below.
waiter = EnqueueWaiter();
break;
}
// Note that we don't check for _disposed. We may end up disposing the
// created connection when it's returned, but we don't want to block use
// of the pool if it's already been disposed, as there's a race condition
// between getting a pool and someone disposing of it, and we don't want
// to complicate the logic about trying to get a different pool when the
// retrieved one has been disposed of. In the future we could alternatively
// try returning such connections to whatever pool is currently considered
// current for that endpoint, if there is one.
}
}
HttpConnection conn = cachedConnection._connection;
if (!conn.LifetimeExpired(nowTicks, pooledConnectionLifetime))
{
// Check to see if we've received anything on the connection; if we have, that's
// either erroneous data (we shouldn't have received anything yet) or the connection
// has been closed; either way, we can't use it. If this is an async request, we
// perform an async read on the stream, since we're going to need to read from it
// anyway, and in doing so we can avoid the extra syscall. For sync requests, we
// try to directly poll the socket rather than doing an async read, so that we can
// issue an appropriate sync read when we actually need it. We don't have the
// underlying socket in all cases, though, so PollRead may fall back to an async
// read in some cases.
bool validConnection = async ?
!conn.EnsureReadAheadAndPollRead() :
!conn.PollRead();
if (validConnection)
{
// We found a valid connection. Return it.
if (NetEventSource.Log.IsEnabled()) conn.Trace("Found usable connection in pool.");
return new ValueTask<HttpConnection?>(conn);
}
}
// We got a connection, but it was already closed by the server or the
// server sent unexpected data or the connection is too old. In any case,
// we can't use the connection, so get rid of it and loop around to try again.
if (NetEventSource.Log.IsEnabled()) conn.Trace("Found invalid connection in pool.");
conn.Dispose();
}
// We are at the connection limit. Wait for an available connection or connection count (indicated by null).
if (NetEventSource.Log.IsEnabled()) Trace("Connection limit reached, waiting for available connection.");
if (HttpTelemetry.Log.IsEnabled())
{
return WaitOnWaiterWithTelemetryAsync(waiter, async, cancellationToken);
}
else
{
return async ?
waiter.WaitWithCancellationAsync(cancellationToken) :
new ValueTask<HttpConnection?>(waiter.Task.GetAwaiter().GetResult());
}
static async ValueTask<HttpConnection?> WaitOnWaiterWithTelemetryAsync(TaskCompletionSourceWithCancellation<HttpConnection?> waiter, bool async, CancellationToken cancellationToken)
{
ValueStopwatch stopwatch = ValueStopwatch.StartNew();
HttpConnection? connection;
if (async)
{
connection = await waiter.WaitWithCancellationAsync(cancellationToken).ConfigureAwait(false);
}
else
{
connection = waiter.Task.GetAwaiter().GetResult();
}
HttpTelemetry.Log.Http11RequestLeftQueue(stopwatch.GetElapsedTime().TotalMilliseconds);
return connection;
}
}
private async ValueTask<(HttpConnectionBase? connection, bool isNewConnection, HttpResponseMessage? failureResponse)>
GetHttpConnectionAsync(HttpRequestMessage request, bool async, CancellationToken cancellationToken)
{
HttpConnection? connection = await GetOrReserveHttp11ConnectionAsync(async, cancellationToken).ConfigureAwait(false);
if (connection != null)
{
return (connection, false, null);
}
if (NetEventSource.Log.IsEnabled()) Trace("Creating new connection for pool.");
try
{
HttpResponseMessage? failureResponse;
(connection, failureResponse) = await CreateHttp11ConnectionAsync(request, async, cancellationToken).ConfigureAwait(false);
if (connection == null)
{
Debug.Assert(failureResponse != null);
DecrementConnectionCount();
}
return (connection, true, failureResponse);
}
catch
{
DecrementConnectionCount();
throw;
}
}
private async ValueTask<(HttpConnectionBase? connection, bool isNewConnection, HttpResponseMessage? failureResponse)>
GetHttp2ConnectionAsync(HttpRequestMessage request, bool async, CancellationToken cancellationToken)
{
Debug.Assert(_kind == HttpConnectionKind.Https || _kind == HttpConnectionKind.SslProxyTunnel || _kind == HttpConnectionKind.Http);
// See if we have an HTTP2 connection
Http2Connection? http2Connection = GetExistingHttp2Connection();
if (http2Connection != null)
{
// Connection exists and it is still good to use.
if (NetEventSource.Log.IsEnabled()) Trace("Using existing HTTP2 connection.");
_usedSinceLastCleanup = true;
return (http2Connection, false, null);
}
// Ensure that the connection creation semaphore is created
if (_http2ConnectionCreateLock == null)
{
lock (SyncObj)
{
if (_http2ConnectionCreateLock == null)
{
_http2ConnectionCreateLock = new SemaphoreSlim(1);
}
}
}
// Try to establish an HTTP2 connection
Stream? stream = null;
SslStream? sslStream = null;
TransportContext? transportContext = null;
// Serialize creation attempt
await _http2ConnectionCreateLock.WaitAsync(cancellationToken).ConfigureAwait(false);
try
{
http2Connection = GetExistingHttp2Connection();
if (http2Connection != null)
{
return (http2Connection, false, null);
}
// Recheck if HTTP2 has been disabled by a previous attempt.
if (_http2Enabled)
{
if (NetEventSource.Log.IsEnabled())
{
Trace("Attempting new HTTP2 connection.");
}
HttpResponseMessage? failureResponse;
(stream, transportContext, failureResponse) =
await ConnectAsync(request, async, cancellationToken).ConfigureAwait(false);
if (failureResponse != null)
{
return (null, true, failureResponse);
}
Debug.Assert(stream != null);
sslStream = stream as SslStream;
if (_kind == HttpConnectionKind.Http)
{
http2Connection = await ConstructHttp2Connection(stream, request, cancellationToken).ConfigureAwait(false);
if (NetEventSource.Log.IsEnabled())
{
Trace("New unencrypted HTTP2 connection established.");
}
return (http2Connection, true, null);
}
Debug.Assert(sslStream != null);
if (sslStream.NegotiatedApplicationProtocol == SslApplicationProtocol.Http2)
{
// The server accepted our request for HTTP2.
if (sslStream.SslProtocol < SslProtocols.Tls12)
{
sslStream.Dispose();
throw new HttpRequestException(SR.Format(SR.net_ssl_http2_requires_tls12, sslStream.SslProtocol));
}
http2Connection = await ConstructHttp2Connection(stream, request, cancellationToken).ConfigureAwait(false);
if (NetEventSource.Log.IsEnabled())
{
Trace("New HTTP2 connection established.");
}
return (http2Connection, true, null);
}
}
}
finally
{
_http2ConnectionCreateLock.Release();
}
if (sslStream != null)
{
// We established an SSL connection, but the server denied our request for HTTP2.
// Continue as an HTTP/1.1 connection.
if (NetEventSource.Log.IsEnabled())
{
Trace("Server does not support HTTP2; disabling HTTP2 use and proceeding with HTTP/1.1 connection");
}
bool canUse = true;
lock (SyncObj)
{
_http2Enabled = false;
if (request.Version.Major >= 2 && request.VersionPolicy != HttpVersionPolicy.RequestVersionOrLower)
{
sslStream.Close();
throw new HttpRequestException(SR.Format(SR.net_http_requested_version_server_refused, request.Version, request.VersionPolicy));
}
if (_associatedConnectionCount < _maxConnections)
{
IncrementConnectionCountNoLock();
}
else
{
// We are in the weird situation of having established a new HTTP 1.1 connection
// when we were already at the maximum for HTTP 1.1 connections.
// Just discard this connection and get another one from the pool.
// This should be a really rare situation to get into, since it would require
// the user to make multiple HTTP 1.1-only requests first before attempting an
// HTTP2 request, and the server failing to accept HTTP2.
canUse = false;
}
}
if (canUse)
{
return (await ConstructHttp11Connection(stream!, transportContext, request, cancellationToken).ConfigureAwait(false), true, null);
}
else
{
if (NetEventSource.Log.IsEnabled())
{
Trace("Discarding downgraded HTTP/1.1 connection because connection limit is exceeded");
}
stream!.Dispose();
}
}
// If we reach this point, it means we need to fall back to a (new or existing) HTTP/1.1 connection.
return await GetHttpConnectionAsync(request, async, cancellationToken).ConfigureAwait(false);
}
private Http2Connection? GetExistingHttp2Connection()
{
Http2Connection[]? localConnections = _http2Connections;
if (localConnections == null)
{
return null;
}
for (int i = 0; i < localConnections.Length; i++)
{
Http2Connection http2Connection = localConnections[i];
TimeSpan pooledConnectionLifetime = _poolManager.Settings._pooledConnectionLifetime;
if (http2Connection.LifetimeExpired(Environment.TickCount64, pooledConnectionLifetime))
{
// Connection expired.
http2Connection.Dispose();
InvalidateHttp2Connection(http2Connection);
}
else if (!EnableMultipleHttp2Connections || http2Connection.CanAddNewStream)
{
return http2Connection;
}
}
return null;
}
private void AddHttp2Connection(Http2Connection newConnection)
{
lock (SyncObj)
{
Http2Connection[]? localHttp2Connections = _http2Connections;
int newCollectionSize = localHttp2Connections == null ? 1 : localHttp2Connections.Length + 1;
Http2Connection[] newHttp2Connections = new Http2Connection[newCollectionSize];
newHttp2Connections[0] = newConnection;
if (localHttp2Connections != null)
{
Array.Copy(localHttp2Connections, 0, newHttp2Connections, 1, localHttp2Connections.Length);
}
_http2Connections = newHttp2Connections;
}
}
private async ValueTask<(HttpConnectionBase? connection, bool isNewConnection, HttpResponseMessage? failureResponse)>
GetHttp3ConnectionAsync(HttpRequestMessage request, HttpAuthority authority, CancellationToken cancellationToken)
{
Debug.Assert(_kind == HttpConnectionKind.Https);
Debug.Assert(_http3Enabled == true);
Http3Connection? http3Connection = Volatile.Read(ref _http3Connection);
if (http3Connection != null)
{
TimeSpan pooledConnectionLifetime = _poolManager.Settings._pooledConnectionLifetime;
if (http3Connection.LifetimeExpired(Environment.TickCount64, pooledConnectionLifetime) || http3Connection.Authority != authority)
{
// Connection expired.
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, false, null);
}
}
// Ensure that the connection creation semaphore is created
if (_http3ConnectionCreateLock == null)
{
lock (SyncObj)
{
if (_http3ConnectionCreateLock == null)
{
_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, false, null);
}
if (NetEventSource.Log.IsEnabled())
{
Trace("Attempting new HTTP3 connection.");
}
QuicConnection quicConnection;
try
{
quicConnection = await ConnectHelper.ConnectQuicAsync(Settings._quicImplementationProvider ?? QuicImplementationProviders.Default, new DnsEndPoint(authority.IdnHost, authority.Port), _sslOptionsHttp3, cancellationToken).ConfigureAwait(false);
}
catch
{
// Disables HTTP/3 until server announces it can handle it via Alt-Svc.
BlocklistAuthority(authority);
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
http3Connection = new Http3Connection(this, _originAuthority, authority, quicConnection);
_http3Connection = http3Connection;
if (NetEventSource.Log.IsEnabled())
{
Trace("New HTTP3 connection established.");
}
return (http3Connection, true, null);
}
finally
{
_http3ConnectionCreateLock.Release();
}
}
public async ValueTask<HttpResponseMessage> SendWithRetryAsync(HttpRequestMessage request, bool async, bool doRequestAuth, CancellationToken cancellationToken)
{
while (true)
{
// Loop on connection failures and retry if possible.
(HttpConnectionBase? connection, bool isNewConnection, HttpResponseMessage? failureResponse) = await GetConnectionAsync(request, async, cancellationToken).ConfigureAwait(false);
if (failureResponse != null)
{
// Proxy tunnel failure; return proxy response
Debug.Assert(isNewConnection);
Debug.Assert(connection == null);
return failureResponse;
}
HttpResponseMessage response;
try
{
if (connection is HttpConnection)
{
((HttpConnection)connection).Acquire();
try
{
response = await (doRequestAuth && Settings._credentials != null ?
AuthenticationHelper.SendWithNtConnectionAuthAsync(request, async, Settings._credentials, (HttpConnection)connection, this, cancellationToken) :
SendWithNtProxyAuthAsync((HttpConnection)connection, request, async, cancellationToken)).ConfigureAwait(false);
}
finally
{
((HttpConnection)connection).Release();
}
}
else
{
response = await connection!.SendAsync(request, async, cancellationToken).ConfigureAwait(false);
}
}
catch (HttpRequestException e) when (e.AllowRetry == RequestRetryType.RetryOnLowerHttpVersion)
{
// Throw since fallback is not allowed by the version policy.
if (request.VersionPolicy != HttpVersionPolicy.RequestVersionOrLower)
{
throw new HttpRequestException(SR.Format(SR.net_http_requested_version_server_refused, request.Version, request.VersionPolicy), e);
}
if (NetEventSource.Log.IsEnabled())
{
Trace($"Retrying request after exception on existing connection: {e}");
}
// Eat exception and try again on a lower protocol version.
Debug.Assert(connection is HttpConnection == false, $"{nameof(RequestRetryType.RetryOnLowerHttpVersion)} should not be thrown by HTTP/1 connections.");
request.Version = HttpVersion.Version11;
continue;
}
catch (HttpRequestException e) when (!isNewConnection && e.AllowRetry == RequestRetryType.RetryOnSameOrNextProxy)
{
if (NetEventSource.Log.IsEnabled())
{
Trace($"Retrying request after exception on existing connection: {e}");
}
// Eat exception and try again.
continue;
}
catch (HttpRequestException e) when (e.AllowRetry == RequestRetryType.RetryOnNextConnection)
{
if (NetEventSource.Log.IsEnabled())
{
Trace($"Retrying request on another HTTP/2 connection after active streams limit is reached on existing one: {e}");
}
// Eat exception and try again.
continue;
}
// Check for the Alt-Svc header, to upgrade to HTTP/3.
if (_altSvcEnabled && response.Headers.TryGetValues(KnownHeaders.AltSvc.Descriptor, out IEnumerable<string>? altSvcHeaderValues))
{
HandleAltSvc(altSvcHeaderValues, response.Headers.Age);
}
// 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 is Http3Connection h3Connection && h3Connection.Authority != _originAuthority)
{
response.Dispose();
BlocklistAuthority(h3Connection.Authority);
continue;
}
return response;
}
}
/// <summary>
/// Inspects a collection of Alt-Svc headers to find the first eligible upgrade path.
/// </summary>
/// <remarks>TODO: common case will likely be a single value. Optimize for that.</remarks>
internal void HandleAltSvc(IEnumerable<string> altSvcHeaderValues, TimeSpan? responseAge)
{
HttpAuthority? nextAuthority = null;
TimeSpan nextAuthorityMaxAge = default;
bool nextAuthorityPersist = false;
foreach (string altSvcHeaderValue in altSvcHeaderValues)
{
int parseIdx = 0;
if (AltSvcHeaderParser.Parser.TryParseValue(altSvcHeaderValue, null, ref parseIdx, out object? parsedValue))
{
var value = (AltSvcHeaderValue?)parsedValue;
// 'clear' should be the only value present.
if (value == AltSvcHeaderValue.Clear)
{
ExpireAltSvcAuthority();
Debug.Assert(_authorityExpireTimer != null);
_authorityExpireTimer.Change(Timeout.Infinite, Timeout.Infinite);
break;
}
if (nextAuthority == null && value != null && value.AlpnProtocolName == "h3")
{
var authority = new HttpAuthority(value.Host!, value.Port);
if (IsAltSvcBlocked(authority))
{
// Skip authorities in our blocklist.
continue;
}
TimeSpan authorityMaxAge = value.MaxAge;
if (responseAge != null)
{
authorityMaxAge -= responseAge.GetValueOrDefault();
}
if (authorityMaxAge > TimeSpan.Zero)
{
nextAuthority = authority;
nextAuthorityMaxAge = authorityMaxAge;
nextAuthorityPersist = value.Persist;
}
}