-
Notifications
You must be signed in to change notification settings - Fork 4.5k
/
HttpClientHandler.cs
377 lines (332 loc) · 14.4 KB
/
HttpClientHandler.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
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
using System.Globalization;
using System.Net.Security;
using System.Collections.Generic;
using System.Runtime.Versioning;
using System.Security.Authentication;
using System.Security.Cryptography.X509Certificates;
using System.Threading;
using System.Threading.Tasks;
using System.Diagnostics.Metrics;
#if TARGET_BROWSER
using System.Diagnostics;
using System.Net.Http.Metrics;
using HttpHandlerType = System.Net.Http.BrowserHttpHandler;
#else
using HttpHandlerType = System.Net.Http.SocketsHttpHandler;
#endif
namespace System.Net.Http
{
public partial class HttpClientHandler : HttpMessageHandler
{
private readonly HttpHandlerType _underlyingHandler;
#if TARGET_BROWSER
private IMeterFactory? _meterFactory;
private MetricsHandler? _metricsHandler;
private MetricsHandler Handler
{
get
{
if (_metricsHandler != null)
{
return _metricsHandler;
}
HttpMessageHandler handler = _underlyingHandler;
if (DiagnosticsHandler.IsGloballyEnabled())
{
handler = new DiagnosticsHandler(handler, DistributedContextPropagator.Current);
}
MetricsHandler metricsHandler = new MetricsHandler(handler, _meterFactory, out _);
// Ensure a single handler is used for all requests.
if (Interlocked.CompareExchange(ref _metricsHandler, metricsHandler, null) != null)
{
metricsHandler.Dispose();
}
return _metricsHandler;
}
}
#else
private HttpHandlerType Handler => _underlyingHandler;
#endif
private volatile bool _disposed;
public HttpClientHandler()
{
_underlyingHandler = new HttpHandlerType();
ClientCertificateOptions = ClientCertificateOption.Manual;
}
protected override void Dispose(bool disposing)
{
if (disposing && !_disposed)
{
_disposed = true;
_underlyingHandler.Dispose();
}
base.Dispose(disposing);
}
public virtual bool SupportsAutomaticDecompression => HttpHandlerType.SupportsAutomaticDecompression;
public virtual bool SupportsProxy => HttpHandlerType.SupportsProxy;
public virtual bool SupportsRedirectConfiguration => HttpHandlerType.SupportsRedirectConfiguration;
/// <summary>
/// Gets or sets the <see cref="IMeterFactory"/> to create a custom <see cref="Meter"/> for the <see cref="HttpClientHandler"/> instance.
/// </summary>
/// <remarks>
/// When <see cref="MeterFactory"/> is set to a non-<see langword="null"/> value, all metrics emitted by the <see cref="HttpClientHandler"/> instance
/// will be recorded using the <see cref="Meter"/> provided by the <see cref="IMeterFactory"/>.
/// </remarks>
[CLSCompliant(false)]
public IMeterFactory? MeterFactory
{
#if TARGET_BROWSER
get => _meterFactory;
set
{
ObjectDisposedException.ThrowIf(_disposed, this);
if (_metricsHandler != null)
{
throw new InvalidOperationException(SR.net_http_operation_started);
}
_meterFactory = value;
}
#else
get => _underlyingHandler.MeterFactory;
set => _underlyingHandler.MeterFactory = value;
#endif
}
[UnsupportedOSPlatform("browser")]
public bool UseCookies
{
get => _underlyingHandler.UseCookies;
set => _underlyingHandler.UseCookies = value;
}
[UnsupportedOSPlatform("browser")]
public CookieContainer CookieContainer
{
get => _underlyingHandler.CookieContainer;
set
{
ArgumentNullException.ThrowIfNull(value);
_underlyingHandler.CookieContainer = value;
}
}
[UnsupportedOSPlatform("browser")]
public DecompressionMethods AutomaticDecompression
{
get => _underlyingHandler.AutomaticDecompression;
set => _underlyingHandler.AutomaticDecompression = value;
}
[UnsupportedOSPlatform("browser")]
public bool UseProxy
{
get => _underlyingHandler.UseProxy;
set => _underlyingHandler.UseProxy = value;
}
[UnsupportedOSPlatform("browser")]
[UnsupportedOSPlatform("ios")]
[UnsupportedOSPlatform("tvos")]
public IWebProxy? Proxy
{
get => _underlyingHandler.Proxy;
set => _underlyingHandler.Proxy = value;
}
[UnsupportedOSPlatform("browser")]
public ICredentials? DefaultProxyCredentials
{
get => _underlyingHandler.DefaultProxyCredentials;
set => _underlyingHandler.DefaultProxyCredentials = value;
}
[UnsupportedOSPlatform("browser")]
public bool PreAuthenticate
{
get => _underlyingHandler.PreAuthenticate;
set => _underlyingHandler.PreAuthenticate = value;
}
[UnsupportedOSPlatform("browser")]
public bool UseDefaultCredentials
{
// SocketsHttpHandler doesn't have a separate UseDefaultCredentials property. There
// is just a Credentials property. So, we need to map the behavior.
get => _underlyingHandler.Credentials == CredentialCache.DefaultCredentials;
set
{
if (value)
{
_underlyingHandler.Credentials = CredentialCache.DefaultCredentials;
}
else
{
if (_underlyingHandler.Credentials == CredentialCache.DefaultCredentials)
{
// Only clear out the Credentials property if it was a DefaultCredentials.
_underlyingHandler.Credentials = null;
}
}
}
}
[UnsupportedOSPlatform("browser")]
public ICredentials? Credentials
{
get => _underlyingHandler.Credentials;
set => _underlyingHandler.Credentials = value;
}
public bool AllowAutoRedirect
{
get => _underlyingHandler.AllowAutoRedirect;
set => _underlyingHandler.AllowAutoRedirect = value;
}
[UnsupportedOSPlatform("browser")]
public int MaxAutomaticRedirections
{
get => _underlyingHandler.MaxAutomaticRedirections;
set => _underlyingHandler.MaxAutomaticRedirections = value;
}
[UnsupportedOSPlatform("browser")]
public int MaxConnectionsPerServer
{
get => _underlyingHandler.MaxConnectionsPerServer;
set => _underlyingHandler.MaxConnectionsPerServer = value;
}
public long MaxRequestContentBufferSize
{
// This property is not supported. In the .NET Framework it was only used when the handler needed to
// automatically buffer the request content. That only happened if neither 'Content-Length' nor
// 'Transfer-Encoding: chunked' request headers were specified. So, the handler thus needed to buffer
// in the request content to determine its length and then would choose 'Content-Length' semantics when
// POST'ing. In .NET Core, the handler will resolve the ambiguity by always choosing
// 'Transfer-Encoding: chunked'. The handler will never automatically buffer in the request content.
get
{
return 0; // Returning zero is appropriate since in .NET Framework it means no limit.
}
set
{
ArgumentOutOfRangeException.ThrowIfNegative(value);
if (value > HttpContent.MaxBufferSize)
{
throw new ArgumentOutOfRangeException(nameof(value), value,
SR.Format(CultureInfo.InvariantCulture, SR.net_http_content_buffersize_limit,
HttpContent.MaxBufferSize));
}
ObjectDisposedException.ThrowIf(_disposed, this);
// No-op on property setter.
}
}
[UnsupportedOSPlatform("browser")]
public int MaxResponseHeadersLength
{
get => _underlyingHandler.MaxResponseHeadersLength;
set => _underlyingHandler.MaxResponseHeadersLength = value;
}
public ClientCertificateOption ClientCertificateOptions
{
get => _underlyingHandler.ClientCertificateOptions;
set
{
switch (value)
{
case ClientCertificateOption.Manual:
#if !TARGET_BROWSER
ThrowForModifiedManagedSslOptionsIfStarted();
_underlyingHandler.SslOptions.LocalCertificateSelectionCallback = (sender, targetHost, localCertificates, remoteCertificate, acceptableIssuers) => CertificateHelper.GetEligibleClientCertificate(_underlyingHandler.SslOptions.ClientCertificates)!;
#endif
break;
case ClientCertificateOption.Automatic:
#if !TARGET_BROWSER
ThrowForModifiedManagedSslOptionsIfStarted();
_underlyingHandler.SslOptions.LocalCertificateSelectionCallback = (sender, targetHost, localCertificates, remoteCertificate, acceptableIssuers) => CertificateHelper.GetEligibleClientCertificate()!;
#endif
break;
default:
throw new ArgumentOutOfRangeException(nameof(value));
}
_underlyingHandler.ClientCertificateOptions = value;
}
}
[UnsupportedOSPlatform("browser")]
public X509CertificateCollection ClientCertificates
{
get
{
if (ClientCertificateOptions != ClientCertificateOption.Manual)
{
throw new InvalidOperationException(SR.Format(SR.net_http_invalid_enable_first, nameof(ClientCertificateOptions), nameof(ClientCertificateOption.Manual)));
}
return _underlyingHandler.SslOptions.ClientCertificates ??
(_underlyingHandler.SslOptions.ClientCertificates = new X509CertificateCollection());
}
}
[UnsupportedOSPlatform("browser")]
public Func<HttpRequestMessage, X509Certificate2?, X509Chain?, SslPolicyErrors, bool>? ServerCertificateCustomValidationCallback
{
#if TARGET_BROWSER
get => throw new PlatformNotSupportedException();
set => throw new PlatformNotSupportedException();
#else
get => (_underlyingHandler.SslOptions.RemoteCertificateValidationCallback?.Target as ConnectHelper.CertificateCallbackMapper)?.FromHttpClientHandler;
set
{
ThrowForModifiedManagedSslOptionsIfStarted();
_underlyingHandler.SslOptions.RemoteCertificateValidationCallback = value != null ?
new ConnectHelper.CertificateCallbackMapper(value).ForSocketsHttpHandler :
null;
}
#endif
}
[UnsupportedOSPlatform("browser")]
public bool CheckCertificateRevocationList
{
get => _underlyingHandler.SslOptions.CertificateRevocationCheckMode == X509RevocationMode.Online;
set
{
ThrowForModifiedManagedSslOptionsIfStarted();
_underlyingHandler.SslOptions.CertificateRevocationCheckMode = value ? X509RevocationMode.Online : X509RevocationMode.NoCheck;
}
}
[UnsupportedOSPlatform("browser")]
public SslProtocols SslProtocols
{
get => _underlyingHandler.SslOptions.EnabledSslProtocols;
set
{
ThrowForModifiedManagedSslOptionsIfStarted();
_underlyingHandler.SslOptions.EnabledSslProtocols = value;
}
}
public IDictionary<string, object?> Properties => _underlyingHandler.Properties;
//
// Attributes are commented out due to https://github.com/dotnet/arcade/issues/7585
// API compat will fail until this is fixed
//
//[UnsupportedOSPlatform("android")]
[UnsupportedOSPlatform("browser")]
//[UnsupportedOSPlatform("ios")]
//[UnsupportedOSPlatform("tvos")]
protected internal override HttpResponseMessage Send(HttpRequestMessage request, CancellationToken cancellationToken)
{
#if TARGET_BROWSER
throw new PlatformNotSupportedException();
#else
ArgumentNullException.ThrowIfNull(request);
return Handler.Send(request, cancellationToken);
#endif
}
protected internal override Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken)
{
ArgumentNullException.ThrowIfNull(request);
return Handler.SendAsync(request, cancellationToken);
}
// lazy-load the validator func so it can be trimmed by the ILLinker if it isn't used.
private static Func<HttpRequestMessage, X509Certificate2?, X509Chain?, SslPolicyErrors, bool>? s_dangerousAcceptAnyServerCertificateValidator;
[UnsupportedOSPlatform("browser")]
public static Func<HttpRequestMessage, X509Certificate2?, X509Chain?, SslPolicyErrors, bool> DangerousAcceptAnyServerCertificateValidator =>
Volatile.Read(ref s_dangerousAcceptAnyServerCertificateValidator) ??
Interlocked.CompareExchange(ref s_dangerousAcceptAnyServerCertificateValidator, delegate { return true; }, null) ??
s_dangerousAcceptAnyServerCertificateValidator;
private void ThrowForModifiedManagedSslOptionsIfStarted()
{
// Hack to trigger an InvalidOperationException if a property that's stored on
// SslOptions is changed, since SslOptions itself does not do any such checks.
_underlyingHandler.SslOptions = _underlyingHandler.SslOptions;
}
}
}