| | | 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.Metrics; |
| | | 10 | | using System.Net.Security; |
| | | 11 | | using System.Runtime.CompilerServices; |
| | | 12 | | using System.Text; |
| | | 13 | | using System.Threading; |
| | | 14 | | using System.Threading.Tasks; |
| | | 15 | | |
| | | 16 | | namespace System.Net.Http |
| | | 17 | | { |
| | | 18 | | internal abstract class HttpConnectionBase : IDisposable, IHttpTrace |
| | | 19 | | { |
| | | 20 | | protected readonly HttpConnectionPool _pool; |
| | | 21 | | |
| | 0 | 22 | | private static long s_connectionCounter = -1; |
| | | 23 | | |
| | | 24 | | // May be null if none of the counters were enabled when the connection was established. |
| | | 25 | | private ConnectionMetrics? _connectionMetrics; |
| | | 26 | | |
| | | 27 | | // Indicates whether we've counted this connection as established, so that we can |
| | | 28 | | // avoid decrementing the counter once it's closed in case telemetry was enabled in between. |
| | | 29 | | private bool _httpTelemetryMarkedConnectionAsOpened; |
| | | 30 | | |
| | 0 | 31 | | private readonly long _creationTickCount = Environment.TickCount64; |
| | | 32 | | private long? _idleSinceTickCount; |
| | | 33 | | |
| | | 34 | | /// <summary>Cached string for the last Date header received on this connection.</summary> |
| | | 35 | | private string? _lastDateHeaderValue; |
| | | 36 | | /// <summary>Cached string for the last Server header received on this connection.</summary> |
| | | 37 | | private string? _lastServerHeaderValue; |
| | | 38 | | |
| | 0 | 39 | | public long Id { get; } = Interlocked.Increment(ref s_connectionCounter); |
| | | 40 | | |
| | 0 | 41 | | public Activity? ConnectionSetupActivity { get; private set; } |
| | | 42 | | |
| | 0 | 43 | | public HttpConnectionBase(HttpConnectionPool pool) |
| | 0 | 44 | | { |
| | 0 | 45 | | Debug.Assert(this is HttpConnection or Http2Connection or Http3Connection); |
| | 0 | 46 | | Debug.Assert(pool != null); |
| | 0 | 47 | | _pool = pool; |
| | 0 | 48 | | } |
| | | 49 | | |
| | | 50 | | public HttpConnectionBase(HttpConnectionPool pool, Activity? connectionSetupActivity, IPEndPoint? remoteEndPoint |
| | 0 | 51 | | : this(pool) |
| | 0 | 52 | | { |
| | 0 | 53 | | MarkConnectionAsEstablished(connectionSetupActivity, remoteEndPoint); |
| | 0 | 54 | | } |
| | | 55 | | |
| | | 56 | | protected void MarkConnectionAsEstablished(Activity? connectionSetupActivity, IPEndPoint? remoteEndPoint) |
| | 0 | 57 | | { |
| | 0 | 58 | | ConnectionSetupActivity = connectionSetupActivity; |
| | 0 | 59 | | if (GlobalHttpSettings.MetricsHandler.IsGloballyEnabled) |
| | 0 | 60 | | { |
| | 0 | 61 | | Debug.Assert(_pool.Settings._metrics is not null); |
| | | 62 | | |
| | 0 | 63 | | SocketsHttpHandlerMetrics metrics = _pool.Settings._metrics!; |
| | 0 | 64 | | if (metrics.OpenConnections.Enabled || metrics.ConnectionDuration.Enabled) |
| | 0 | 65 | | { |
| | | 66 | | // While requests may report HTTP/1.0 as the protocol, we treat all HTTP/1.X connections as HTTP/1.1 |
| | 0 | 67 | | string protocol = |
| | 0 | 68 | | this is HttpConnection ? "1.1" : |
| | 0 | 69 | | this is Http2Connection ? "2" : |
| | 0 | 70 | | "3"; |
| | | 71 | | |
| | 0 | 72 | | Debug.Assert(_pool.TelemetryServerAddress is not null, "TelemetryServerAddress should not be null wh |
| | 0 | 73 | | _connectionMetrics = new ConnectionMetrics( |
| | 0 | 74 | | metrics, |
| | 0 | 75 | | protocol, |
| | 0 | 76 | | _pool.IsSecure ? "https" : "http", |
| | 0 | 77 | | _pool.TelemetryServerAddress, |
| | 0 | 78 | | _pool.OriginAuthority.Port, |
| | 0 | 79 | | remoteEndPoint?.Address?.ToString()); |
| | | 80 | | |
| | 0 | 81 | | _connectionMetrics.ConnectionEstablished(); |
| | 0 | 82 | | } |
| | 0 | 83 | | } |
| | | 84 | | |
| | 0 | 85 | | _idleSinceTickCount = _creationTickCount; |
| | | 86 | | |
| | 0 | 87 | | if (HttpTelemetry.Log.IsEnabled()) |
| | 0 | 88 | | { |
| | 0 | 89 | | _httpTelemetryMarkedConnectionAsOpened = true; |
| | | 90 | | |
| | 0 | 91 | | string scheme = _pool.IsSecure ? "https" : "http"; |
| | 0 | 92 | | string host = _pool.OriginAuthority.HostValue; |
| | 0 | 93 | | int port = _pool.OriginAuthority.Port; |
| | | 94 | | |
| | 0 | 95 | | if (this is HttpConnection) HttpTelemetry.Log.Http11ConnectionEstablished(Id, scheme, host, port, remote |
| | 0 | 96 | | else if (this is Http2Connection) HttpTelemetry.Log.Http20ConnectionEstablished(Id, scheme, host, port, |
| | 0 | 97 | | else HttpTelemetry.Log.Http30ConnectionEstablished(Id, scheme, host, port, remoteEndPoint); |
| | 0 | 98 | | } |
| | 0 | 99 | | } |
| | | 100 | | |
| | | 101 | | public void MarkConnectionAsClosed() |
| | 0 | 102 | | { |
| | 0 | 103 | | if (GlobalHttpSettings.MetricsHandler.IsGloballyEnabled) _connectionMetrics?.ConnectionClosed(durationMs: En |
| | | 104 | | |
| | 0 | 105 | | if (HttpTelemetry.Log.IsEnabled()) |
| | 0 | 106 | | { |
| | | 107 | | // Only decrement the connection count if we counted this connection |
| | 0 | 108 | | if (_httpTelemetryMarkedConnectionAsOpened) |
| | 0 | 109 | | { |
| | 0 | 110 | | if (this is HttpConnection) HttpTelemetry.Log.Http11ConnectionClosed(Id); |
| | 0 | 111 | | else if (this is Http2Connection) HttpTelemetry.Log.Http20ConnectionClosed(Id); |
| | 0 | 112 | | else HttpTelemetry.Log.Http30ConnectionClosed(Id); |
| | 0 | 113 | | } |
| | 0 | 114 | | } |
| | 0 | 115 | | } |
| | | 116 | | |
| | | 117 | | public void MarkConnectionAsIdle() |
| | 0 | 118 | | { |
| | 0 | 119 | | _idleSinceTickCount = Environment.TickCount64; |
| | 0 | 120 | | if (GlobalHttpSettings.MetricsHandler.IsGloballyEnabled) _connectionMetrics?.IdleStateChanged(idle: true); |
| | 0 | 121 | | } |
| | | 122 | | |
| | | 123 | | public void MarkConnectionAsNotIdle() |
| | 0 | 124 | | { |
| | 0 | 125 | | _idleSinceTickCount = null; |
| | 0 | 126 | | if (GlobalHttpSettings.MetricsHandler.IsGloballyEnabled) _connectionMetrics?.IdleStateChanged(idle: false); |
| | 0 | 127 | | } |
| | | 128 | | |
| | | 129 | | /// <summary>Uses <see cref="HeaderDescriptor.GetHeaderValue"/>, but first special-cases several known headers f |
| | | 130 | | public string GetResponseHeaderValueWithCaching(HeaderDescriptor descriptor, ReadOnlySpan<byte> value, Encoding? |
| | 0 | 131 | | { |
| | 0 | 132 | | return |
| | 0 | 133 | | descriptor.Equals(KnownHeaders.Date) ? GetOrAddCachedValue(ref _lastDateHeaderValue, descriptor, value, |
| | 0 | 134 | | descriptor.Equals(KnownHeaders.Server) ? GetOrAddCachedValue(ref _lastServerHeaderValue, descriptor, val |
| | 0 | 135 | | descriptor.GetHeaderValue(value, valueEncoding); |
| | | 136 | | |
| | | 137 | | static string GetOrAddCachedValue([NotNull] ref string? cache, HeaderDescriptor descriptor, ReadOnlySpan<byt |
| | 0 | 138 | | { |
| | 0 | 139 | | string? lastValue = cache; |
| | 0 | 140 | | if (lastValue is null || !Ascii.Equals(value, lastValue)) |
| | 0 | 141 | | { |
| | 0 | 142 | | cache = lastValue = descriptor.GetHeaderValue(value, encoding); |
| | 0 | 143 | | } |
| | 0 | 144 | | Debug.Assert(cache is not null); |
| | 0 | 145 | | return lastValue; |
| | 0 | 146 | | } |
| | 0 | 147 | | } |
| | | 148 | | |
| | | 149 | | public abstract void Trace(string message, [CallerMemberName] string? memberName = null); |
| | | 150 | | |
| | | 151 | | protected void TraceConnection(Stream stream) |
| | 0 | 152 | | { |
| | 0 | 153 | | if (stream is SslStream sslStream) |
| | 0 | 154 | | { |
| | | 155 | | #pragma warning disable SYSLIB0058 // Use NegotiatedCipherSuite. |
| | 0 | 156 | | Trace( |
| | 0 | 157 | | $"{this}. Id:{Id}, " + |
| | 0 | 158 | | $"SslProtocol:{sslStream.SslProtocol}, NegotiatedApplicationProtocol:{sslStream.NegotiatedApplicatio |
| | 0 | 159 | | $"NegotiatedCipherSuite:{sslStream.NegotiatedCipherSuite}, CipherAlgorithm:{sslStream.CipherAlgorith |
| | 0 | 160 | | $"HashAlgorithm:{sslStream.HashAlgorithm}, HashStrength:{sslStream.HashStrength}, " + |
| | 0 | 161 | | $"KeyExchangeAlgorithm:{sslStream.KeyExchangeAlgorithm}, KeyExchangeStrength:{sslStream.KeyExchangeS |
| | 0 | 162 | | $"LocalCertificate:{sslStream.LocalCertificate}, RemoteCertificate:{sslStream.RemoteCertificate}"); |
| | | 163 | | #pragma warning restore SYSLIB0058 // Use NegotiatedCipherSuite. |
| | 0 | 164 | | } |
| | | 165 | | else |
| | 0 | 166 | | { |
| | 0 | 167 | | Trace($"{this}. Id:{Id}"); |
| | 0 | 168 | | } |
| | 0 | 169 | | } |
| | | 170 | | |
| | 0 | 171 | | public long GetLifetimeTicks(long nowTicks) => nowTicks - _creationTickCount; |
| | | 172 | | |
| | 0 | 173 | | public long GetIdleTicks(long nowTicks) => _idleSinceTickCount is long idleSinceTickCount ? nowTicks - idleSince |
| | | 174 | | |
| | | 175 | | /// <summary>Check whether a connection is still usable, or should be scavenged.</summary> |
| | | 176 | | /// <returns>True if connection can be used.</returns> |
| | 0 | 177 | | public virtual bool CheckUsabilityOnScavenge() => true; |
| | | 178 | | |
| | 0 | 179 | | internal static bool IsDigit(byte c) => (uint)(c - '0') <= '9' - '0'; |
| | | 180 | | |
| | | 181 | | internal static int ParseStatusCode(ReadOnlySpan<byte> value) |
| | 0 | 182 | | { |
| | | 183 | | byte status1, status2, status3; |
| | 0 | 184 | | if (value.Length != 3 || |
| | 0 | 185 | | !IsDigit(status1 = value[0]) || |
| | 0 | 186 | | !IsDigit(status2 = value[1]) || |
| | 0 | 187 | | !IsDigit(status3 = value[2])) |
| | 0 | 188 | | { |
| | 0 | 189 | | throw new HttpRequestException(HttpRequestError.InvalidResponse, SR.Format(SR.net_http_invalid_response_ |
| | | 190 | | } |
| | | 191 | | |
| | 0 | 192 | | return 100 * (status1 - '0') + 10 * (status2 - '0') + (status3 - '0'); |
| | 0 | 193 | | } |
| | | 194 | | |
| | | 195 | | /// <summary>Awaits a task, logging any resulting exceptions (which are otherwise ignored).</summary> |
| | | 196 | | internal void LogExceptions(Task task) |
| | 0 | 197 | | { |
| | 0 | 198 | | if (task.IsCompleted) |
| | 0 | 199 | | { |
| | 0 | 200 | | if (task.IsFaulted) |
| | 0 | 201 | | { |
| | 0 | 202 | | LogFaulted(this, task); |
| | 0 | 203 | | } |
| | 0 | 204 | | } |
| | | 205 | | else |
| | 0 | 206 | | { |
| | 0 | 207 | | task.ContinueWith(static (t, state) => LogFaulted((HttpConnectionBase)state!, t), this, |
| | 0 | 208 | | CancellationToken.None, TaskContinuationOptions.ExecuteSynchronously | TaskContinuationOptions.OnlyO |
| | 0 | 209 | | } |
| | | 210 | | |
| | | 211 | | static void LogFaulted(HttpConnectionBase connection, Task task) |
| | 0 | 212 | | { |
| | 0 | 213 | | Debug.Assert(task.IsFaulted); |
| | 0 | 214 | | Exception? e = task.Exception!.InnerException; // Access Exception even if not tracing, to avoid TaskSch |
| | 0 | 215 | | if (NetEventSource.Log.IsEnabled()) connection.Trace($"Exception from asynchronous processing: {e}"); |
| | 0 | 216 | | } |
| | 0 | 217 | | } |
| | | 218 | | |
| | | 219 | | public abstract void Dispose(); |
| | | 220 | | |
| | | 221 | | /// <summary> |
| | | 222 | | /// Called by <see cref="HttpConnectionPool.CleanCacheAndDisposeIfUnused"/> while holding the lock. |
| | | 223 | | /// </summary> |
| | | 224 | | public bool IsUsable(long nowTicks, TimeSpan pooledConnectionLifetime, TimeSpan pooledConnectionIdleTimeout) |
| | 0 | 225 | | { |
| | | 226 | | // Validate that the connection hasn't been idle in the pool for longer than is allowed. |
| | 0 | 227 | | if (pooledConnectionIdleTimeout != Timeout.InfiniteTimeSpan) |
| | 0 | 228 | | { |
| | 0 | 229 | | long idleTicks = GetIdleTicks(nowTicks); |
| | 0 | 230 | | if (idleTicks > pooledConnectionIdleTimeout.TotalMilliseconds) |
| | 0 | 231 | | { |
| | 0 | 232 | | if (NetEventSource.Log.IsEnabled()) Trace($"Scavenging connection. Idle {TimeSpan.FromMilliseconds(i |
| | 0 | 233 | | return false; |
| | | 234 | | } |
| | 0 | 235 | | } |
| | | 236 | | |
| | | 237 | | // Validate that the connection lifetime has not been exceeded. |
| | 0 | 238 | | if (pooledConnectionLifetime != Timeout.InfiniteTimeSpan) |
| | 0 | 239 | | { |
| | 0 | 240 | | long lifetimeTicks = GetLifetimeTicks(nowTicks); |
| | 0 | 241 | | if (lifetimeTicks > pooledConnectionLifetime.TotalMilliseconds) |
| | 0 | 242 | | { |
| | 0 | 243 | | if (NetEventSource.Log.IsEnabled()) Trace($"Scavenging connection. Lifetime {TimeSpan.FromMillisecon |
| | 0 | 244 | | return false; |
| | | 245 | | } |
| | 0 | 246 | | } |
| | | 247 | | |
| | 0 | 248 | | if (!CheckUsabilityOnScavenge()) |
| | 0 | 249 | | { |
| | 0 | 250 | | if (NetEventSource.Log.IsEnabled()) Trace($"Scavenging connection. Keep-Alive timeout exceeded, unexpect |
| | 0 | 251 | | return false; |
| | | 252 | | } |
| | | 253 | | |
| | 0 | 254 | | return true; |
| | 0 | 255 | | } |
| | | 256 | | } |
| | | 257 | | } |