This repository has been archived by the owner on Jan 23, 2023. It is now read-only.
/
WinHttpHandler.cs
1393 lines (1229 loc) · 54 KB
/
WinHttpHandler.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.
// See the LICENSE file in the project root for more information.
using System.Collections.Generic;
using System.Diagnostics;
using System.Globalization;
using System.IO;
using System.Net.Security;
using System.Runtime.InteropServices;
using System.Security.Authentication;
using System.Security.Cryptography.X509Certificates;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using SafeWinHttpHandle = Interop.WinHttp.SafeWinHttpHandle;
namespace System.Net.Http
{
#if HTTP_DLL
internal enum WindowsProxyUsePolicy
#else
public enum WindowsProxyUsePolicy
#endif
{
DoNotUseProxy = 0, // Don't use a proxy at all.
UseWinHttpProxy = 1, // Use configuration as specified by "netsh winhttp" machine config command. Automatic detect not supported.
UseWinInetProxy = 2, // WPAD protocol and PAC files supported.
UseCustomProxy = 3 // Use the custom proxy specified in the Proxy property.
}
#if HTTP_DLL
internal enum CookieUsePolicy
#else
public enum CookieUsePolicy
#endif
{
IgnoreCookies = 0,
UseInternalCookieStoreOnly = 1,
UseSpecifiedCookieContainer = 2
}
#if HTTP_DLL
internal class WinHttpHandler : HttpMessageHandler
#else
public class WinHttpHandler : HttpMessageHandler
#endif
{
#if NET46
internal static readonly Version HttpVersion20 = new Version(2, 0);
internal static readonly Version HttpVersionUnknown = new Version(0, 0);
#else
internal static Version HttpVersion20 => HttpVersionInternal.Version20;
internal static Version HttpVersionUnknown => HttpVersionInternal.Unknown;
#endif
private static readonly TimeSpan s_maxTimeout = TimeSpan.FromMilliseconds(int.MaxValue);
[ThreadStatic]
private static StringBuilder t_requestHeadersBuilder;
private object _lockObject = new object();
private bool _doManualDecompressionCheck = false;
private WinInetProxyHelper _proxyHelper = null;
private bool _automaticRedirection = HttpHandlerDefaults.DefaultAutomaticRedirection;
private int _maxAutomaticRedirections = HttpHandlerDefaults.DefaultMaxAutomaticRedirections;
private DecompressionMethods _automaticDecompression = HttpHandlerDefaults.DefaultAutomaticDecompression;
private CookieUsePolicy _cookieUsePolicy = CookieUsePolicy.UseInternalCookieStoreOnly;
private CookieContainer _cookieContainer = null;
private SslProtocols _sslProtocols = SslProtocols.None; // Use most secure protocols available.
private Func<
HttpRequestMessage,
X509Certificate2,
X509Chain,
SslPolicyErrors,
bool> _serverCertificateValidationCallback = null;
private bool _checkCertificateRevocationList = false;
private ClientCertificateOption _clientCertificateOption = ClientCertificateOption.Manual;
private X509Certificate2Collection _clientCertificates = null; // Only create collection when required.
private ICredentials _serverCredentials = null;
private bool _preAuthenticate = false;
private WindowsProxyUsePolicy _windowsProxyUsePolicy = WindowsProxyUsePolicy.UseWinHttpProxy;
private ICredentials _defaultProxyCredentials = null;
private IWebProxy _proxy = null;
private int _maxConnectionsPerServer = int.MaxValue;
private TimeSpan _sendTimeout = TimeSpan.FromSeconds(30);
private TimeSpan _receiveHeadersTimeout = TimeSpan.FromSeconds(30);
private TimeSpan _receiveDataTimeout = TimeSpan.FromSeconds(30);
private int _maxResponseHeadersLength = HttpHandlerDefaults.DefaultMaxResponseHeadersLength;
private int _maxResponseDrainSize = 64 * 1024;
private IDictionary<String, Object> _properties; // Only create dictionary when required.
private volatile bool _operationStarted;
private volatile bool _disposed;
private SafeWinHttpHandle _sessionHandle;
private WinHttpAuthHelper _authHelper = new WinHttpAuthHelper();
public WinHttpHandler()
{
}
#region Properties
public bool AutomaticRedirection
{
get
{
return _automaticRedirection;
}
set
{
CheckDisposedOrStarted();
_automaticRedirection = value;
}
}
public int MaxAutomaticRedirections
{
get
{
return _maxAutomaticRedirections;
}
set
{
if (value <= 0)
{
throw new ArgumentOutOfRangeException(
nameof(value),
value,
SR.Format(SR.net_http_value_must_be_greater_than, 0));
}
CheckDisposedOrStarted();
_maxAutomaticRedirections = value;
}
}
public DecompressionMethods AutomaticDecompression
{
get
{
return _automaticDecompression;
}
set
{
CheckDisposedOrStarted();
_automaticDecompression = value;
}
}
public CookieUsePolicy CookieUsePolicy
{
get
{
return _cookieUsePolicy;
}
set
{
if (value != CookieUsePolicy.IgnoreCookies
&& value != CookieUsePolicy.UseInternalCookieStoreOnly
&& value != CookieUsePolicy.UseSpecifiedCookieContainer)
{
throw new ArgumentOutOfRangeException(nameof(value));
}
CheckDisposedOrStarted();
_cookieUsePolicy = value;
}
}
public CookieContainer CookieContainer
{
get
{
return _cookieContainer;
}
set
{
CheckDisposedOrStarted();
_cookieContainer = value;
}
}
public SslProtocols SslProtocols
{
get
{
return _sslProtocols;
}
set
{
CheckDisposedOrStarted();
_sslProtocols = value;
}
}
public Func<
HttpRequestMessage,
X509Certificate2,
X509Chain,
SslPolicyErrors,
bool> ServerCertificateValidationCallback
{
get
{
return _serverCertificateValidationCallback;
}
set
{
CheckDisposedOrStarted();
_serverCertificateValidationCallback = value;
}
}
public bool CheckCertificateRevocationList
{
get
{
return _checkCertificateRevocationList;
}
set
{
CheckDisposedOrStarted();
_checkCertificateRevocationList = value;
}
}
public ClientCertificateOption ClientCertificateOption
{
get
{
return _clientCertificateOption;
}
set
{
if (value != ClientCertificateOption.Manual
&& value != ClientCertificateOption.Automatic)
{
throw new ArgumentOutOfRangeException(nameof(value));
}
CheckDisposedOrStarted();
_clientCertificateOption = value;
}
}
public X509Certificate2Collection ClientCertificates
{
get
{
if (_clientCertificateOption != ClientCertificateOption.Manual)
{
throw new InvalidOperationException(SR.Format(SR.net_http_invalid_enable_first, "ClientCertificateOptions", "Manual"));
}
if (_clientCertificates == null)
{
_clientCertificates = new X509Certificate2Collection();
}
return _clientCertificates;
}
}
public bool PreAuthenticate
{
get
{
return _preAuthenticate;
}
set
{
_preAuthenticate = value;
}
}
public ICredentials ServerCredentials
{
get
{
return _serverCredentials;
}
set
{
_serverCredentials = value;
}
}
public WindowsProxyUsePolicy WindowsProxyUsePolicy
{
get
{
return _windowsProxyUsePolicy;
}
set
{
if (value != WindowsProxyUsePolicy.DoNotUseProxy &&
value != WindowsProxyUsePolicy.UseWinHttpProxy &&
value != WindowsProxyUsePolicy.UseWinInetProxy &&
value != WindowsProxyUsePolicy.UseCustomProxy)
{
throw new ArgumentOutOfRangeException(nameof(value));
}
CheckDisposedOrStarted();
_windowsProxyUsePolicy = value;
}
}
public ICredentials DefaultProxyCredentials
{
get
{
return _defaultProxyCredentials;
}
set
{
CheckDisposedOrStarted();
_defaultProxyCredentials = value;
}
}
public IWebProxy Proxy
{
get
{
return _proxy;
}
set
{
CheckDisposedOrStarted();
_proxy = value;
}
}
public int MaxConnectionsPerServer
{
get
{
return _maxConnectionsPerServer;
}
set
{
if (value < 1)
{
// In WinHTTP, setting this to 0 results in it being reset to 2.
// So, we'll only allow settings above 0.
throw new ArgumentOutOfRangeException(
nameof(value),
value,
SR.Format(SR.net_http_value_must_be_greater_than, 0));
}
CheckDisposedOrStarted();
_maxConnectionsPerServer = value;
}
}
public TimeSpan SendTimeout
{
get
{
return _sendTimeout;
}
set
{
if (value != Timeout.InfiniteTimeSpan && (value <= TimeSpan.Zero || value > s_maxTimeout))
{
throw new ArgumentOutOfRangeException(nameof(value));
}
CheckDisposedOrStarted();
_sendTimeout = value;
}
}
public TimeSpan ReceiveHeadersTimeout
{
get
{
return _receiveHeadersTimeout;
}
set
{
if (value != Timeout.InfiniteTimeSpan && (value <= TimeSpan.Zero || value > s_maxTimeout))
{
throw new ArgumentOutOfRangeException(nameof(value));
}
CheckDisposedOrStarted();
_receiveHeadersTimeout = value;
}
}
public TimeSpan ReceiveDataTimeout
{
get
{
return _receiveDataTimeout;
}
set
{
if (value != Timeout.InfiniteTimeSpan && (value <= TimeSpan.Zero || value > s_maxTimeout))
{
throw new ArgumentOutOfRangeException(nameof(value));
}
CheckDisposedOrStarted();
_receiveDataTimeout = value;
}
}
public int MaxResponseHeadersLength
{
get
{
return _maxResponseHeadersLength;
}
set
{
if (value <= 0)
{
throw new ArgumentOutOfRangeException(
nameof(value),
value,
SR.Format(SR.net_http_value_must_be_greater_than, 0));
}
CheckDisposedOrStarted();
_maxResponseHeadersLength = value;
}
}
public int MaxResponseDrainSize
{
get
{
return _maxResponseDrainSize;
}
set
{
if (value <= 0)
{
throw new ArgumentOutOfRangeException(
nameof(value),
value,
SR.Format(SR.net_http_value_must_be_greater_than, 0));
}
CheckDisposedOrStarted();
_maxResponseDrainSize = value;
}
}
public IDictionary<string, object> Properties
{
get
{
if (_properties == null)
{
_properties = new Dictionary<String, object>();
}
return _properties;
}
}
#endregion
protected override void Dispose(bool disposing)
{
if (!_disposed)
{
_disposed = true;
if (disposing && _sessionHandle != null)
{
SafeWinHttpHandle.DisposeAndClearHandle(ref _sessionHandle);
}
}
base.Dispose(disposing);
}
#if HTTP_DLL
protected internal override Task<HttpResponseMessage> SendAsync(
HttpRequestMessage request,
CancellationToken cancellationToken)
#else
protected override Task<HttpResponseMessage> SendAsync(
HttpRequestMessage request,
CancellationToken cancellationToken)
#endif
{
if (request == null)
{
throw new ArgumentNullException(nameof(request), SR.net_http_handler_norequest);
}
// Check for invalid combinations of properties.
if (_proxy != null && _windowsProxyUsePolicy != WindowsProxyUsePolicy.UseCustomProxy)
{
throw new InvalidOperationException(SR.net_http_invalid_proxyusepolicy);
}
if (_windowsProxyUsePolicy == WindowsProxyUsePolicy.UseCustomProxy && _proxy == null)
{
throw new InvalidOperationException(SR.net_http_invalid_proxy);
}
if (_cookieUsePolicy == CookieUsePolicy.UseSpecifiedCookieContainer &&
_cookieContainer == null)
{
throw new InvalidOperationException(SR.net_http_invalid_cookiecontainer);
}
CheckDisposed();
SetOperationStarted();
TaskCompletionSource<HttpResponseMessage> tcs = new TaskCompletionSource<HttpResponseMessage>();
// Create state object and save current values of handler settings.
var state = new WinHttpRequestState();
state.Tcs = tcs;
state.CancellationToken = cancellationToken;
state.RequestMessage = request;
state.Handler = this;
state.CheckCertificateRevocationList = _checkCertificateRevocationList;
state.ServerCertificateValidationCallback = _serverCertificateValidationCallback;
state.WindowsProxyUsePolicy = _windowsProxyUsePolicy;
state.Proxy = _proxy;
state.ServerCredentials = _serverCredentials;
state.DefaultProxyCredentials = _defaultProxyCredentials;
state.PreAuthenticate = _preAuthenticate;
Task.Factory.StartNew(
s => {
var whrs = (WinHttpRequestState)s;
whrs.Handler.StartRequest(whrs);
},
state,
CancellationToken.None,
TaskCreationOptions.DenyChildAttach,
TaskScheduler.Default);
return tcs.Task;
}
private static bool IsChunkedModeForSend(HttpRequestMessage requestMessage)
{
bool chunkedMode = requestMessage.Headers.TransferEncodingChunked.HasValue &&
requestMessage.Headers.TransferEncodingChunked.Value;
HttpContent requestContent = requestMessage.Content;
if (requestContent != null)
{
if (requestContent.Headers.ContentLength.HasValue)
{
if (chunkedMode)
{
// Deal with conflict between 'Content-Length' vs. 'Transfer-Encoding: chunked' semantics.
// Current .NET Desktop HttpClientHandler allows both headers to be specified but ends up
// stripping out 'Content-Length' and using chunked semantics. WinHttpHandler will maintain
// the same behavior.
requestContent.Headers.ContentLength = null;
}
}
else
{
if (!chunkedMode)
{
// Neither 'Content-Length' nor 'Transfer-Encoding: chunked' semantics was given.
// Current .NET Desktop HttpClientHandler uses 'Content-Length' semantics and
// buffers the content as well in some cases. But the WinHttpHandler can't access
// the protected internal TryComputeLength() method of the content. So, it
// will use'Transfer-Encoding: chunked' semantics.
chunkedMode = true;
requestMessage.Headers.TransferEncodingChunked = true;
}
}
}
else if (chunkedMode)
{
throw new InvalidOperationException(SR.net_http_chunked_not_allowed_with_empty_content);
}
return chunkedMode;
}
private static void AddRequestHeaders(
SafeWinHttpHandle requestHandle,
HttpRequestMessage requestMessage,
CookieContainer cookies)
{
// Get a StringBuilder to use for creating the request headers.
// We cache one in TLS to avoid creating a new one for each request.
StringBuilder requestHeadersBuffer = t_requestHeadersBuilder;
if (requestHeadersBuffer != null)
{
requestHeadersBuffer.Clear();
}
else
{
t_requestHeadersBuilder = requestHeadersBuffer = new StringBuilder();
}
// Manually add cookies.
if (cookies != null && cookies.Count > 0)
{
string cookieHeader = WinHttpCookieContainerAdapter.GetCookieHeader(requestMessage.RequestUri, cookies);
if (!string.IsNullOrEmpty(cookieHeader))
{
requestHeadersBuffer.AppendLine(cookieHeader);
}
}
// Serialize general request headers.
requestHeadersBuffer.AppendLine(requestMessage.Headers.ToString());
// Serialize entity-body (content) headers.
if (requestMessage.Content != null)
{
// TODO (#5523): Content-Length header isn't getting correctly placed using ToString()
// This is a bug in HttpContentHeaders that needs to be fixed.
if (requestMessage.Content.Headers.ContentLength.HasValue)
{
long contentLength = requestMessage.Content.Headers.ContentLength.Value;
requestMessage.Content.Headers.ContentLength = null;
requestMessage.Content.Headers.ContentLength = contentLength;
}
requestHeadersBuffer.AppendLine(requestMessage.Content.Headers.ToString());
}
// Add request headers to WinHTTP request handle.
if (!Interop.WinHttp.WinHttpAddRequestHeaders(
requestHandle,
requestHeadersBuffer,
(uint)requestHeadersBuffer.Length,
Interop.WinHttp.WINHTTP_ADDREQ_FLAG_ADD))
{
WinHttpException.ThrowExceptionUsingLastError(nameof(Interop.WinHttp.WinHttpAddRequestHeaders));
}
}
private void EnsureSessionHandleExists(WinHttpRequestState state)
{
if (_sessionHandle == null)
{
lock (_lockObject)
{
if (_sessionHandle == null)
{
SafeWinHttpHandle sessionHandle;
uint accessType;
// If a custom proxy is specified and it is really the system web proxy
// (initial WebRequest.DefaultWebProxy) then we need to update the settings
// since that object is only a sentinel.
if (state.WindowsProxyUsePolicy == WindowsProxyUsePolicy.UseCustomProxy)
{
Debug.Assert(state.Proxy != null);
try
{
state.Proxy.GetProxy(state.RequestMessage.RequestUri);
}
catch (PlatformNotSupportedException)
{
// This is the system web proxy.
state.WindowsProxyUsePolicy = WindowsProxyUsePolicy.UseWinInetProxy;
state.Proxy = null;
}
}
if (state.WindowsProxyUsePolicy == WindowsProxyUsePolicy.DoNotUseProxy ||
state.WindowsProxyUsePolicy == WindowsProxyUsePolicy.UseCustomProxy)
{
// Either no proxy at all or a custom IWebProxy proxy is specified.
// For a custom IWebProxy, we'll need to calculate and set the proxy
// on a per request handle basis using the request Uri. For now,
// we set the session handle to have no proxy.
accessType = Interop.WinHttp.WINHTTP_ACCESS_TYPE_NO_PROXY;
}
else if (state.WindowsProxyUsePolicy == WindowsProxyUsePolicy.UseWinHttpProxy)
{
// Use WinHTTP per-machine proxy settings which are set using the "netsh winhttp" command.
accessType = Interop.WinHttp.WINHTTP_ACCESS_TYPE_DEFAULT_PROXY;
}
else
{
// Use WinInet per-user proxy settings.
accessType = Interop.WinHttp.WINHTTP_ACCESS_TYPE_AUTOMATIC_PROXY;
}
WinHttpTraceHelper.Trace("WinHttpHandler.EnsureSessionHandleExists: proxy accessType={0}", accessType);
sessionHandle = Interop.WinHttp.WinHttpOpen(
IntPtr.Zero,
accessType,
Interop.WinHttp.WINHTTP_NO_PROXY_NAME,
Interop.WinHttp.WINHTTP_NO_PROXY_BYPASS,
(int)Interop.WinHttp.WINHTTP_FLAG_ASYNC);
if (sessionHandle.IsInvalid)
{
int lastError = Marshal.GetLastWin32Error();
WinHttpTraceHelper.Trace("WinHttpHandler.EnsureSessionHandleExists: error={0}", lastError);
if (lastError != Interop.WinHttp.ERROR_INVALID_PARAMETER)
{
ThrowOnInvalidHandle(sessionHandle, nameof(Interop.WinHttp.WinHttpOpen));
}
// We must be running on a platform earlier than Win8.1/Win2K12R2 which doesn't support
// WINHTTP_ACCESS_TYPE_AUTOMATIC_PROXY. So, we'll need to read the Wininet style proxy
// settings ourself using our WinInetProxyHelper object.
_proxyHelper = new WinInetProxyHelper();
sessionHandle = Interop.WinHttp.WinHttpOpen(
IntPtr.Zero,
_proxyHelper.ManualSettingsOnly ? Interop.WinHttp.WINHTTP_ACCESS_TYPE_NAMED_PROXY : Interop.WinHttp.WINHTTP_ACCESS_TYPE_NO_PROXY,
_proxyHelper.ManualSettingsOnly ? _proxyHelper.Proxy : Interop.WinHttp.WINHTTP_NO_PROXY_NAME,
_proxyHelper.ManualSettingsOnly ? _proxyHelper.ProxyBypass : Interop.WinHttp.WINHTTP_NO_PROXY_BYPASS,
(int)Interop.WinHttp.WINHTTP_FLAG_ASYNC);
ThrowOnInvalidHandle(sessionHandle, nameof(Interop.WinHttp.WinHttpOpen));
}
uint optionAssuredNonBlockingTrue = 1; // TRUE
if (!Interop.WinHttp.WinHttpSetOption(
sessionHandle,
Interop.WinHttp.WINHTTP_OPTION_ASSURED_NON_BLOCKING_CALLBACKS,
ref optionAssuredNonBlockingTrue,
(uint)sizeof(uint)))
{
// This option is not available on downlevel Windows versions. While it improves
// performance, we can ignore the error that the option is not available.
int lastError = Marshal.GetLastWin32Error();
if (lastError != Interop.WinHttp.ERROR_WINHTTP_INVALID_OPTION)
{
throw WinHttpException.CreateExceptionUsingError(lastError, nameof(Interop.WinHttp.WinHttpSetOption));
}
}
SetSessionHandleOptions(sessionHandle);
_sessionHandle = sessionHandle;
}
}
}
}
private async void StartRequest(WinHttpRequestState state)
{
if (state.CancellationToken.IsCancellationRequested)
{
state.Tcs.TrySetCanceled(state.CancellationToken);
state.ClearSendRequestState();
return;
}
SafeWinHttpHandle connectHandle = null;
try
{
EnsureSessionHandleExists(state);
// Specify an HTTP server.
connectHandle = Interop.WinHttp.WinHttpConnect(
_sessionHandle,
state.RequestMessage.RequestUri.Host,
(ushort)state.RequestMessage.RequestUri.Port,
0);
ThrowOnInvalidHandle(connectHandle, nameof(Interop.WinHttp.WinHttpConnect));
connectHandle.SetParentHandle(_sessionHandle);
// Try to use the requested version if a known/supported version was explicitly requested.
// Otherwise, we simply use winhttp's default.
string httpVersion = null;
if (state.RequestMessage.Version == HttpVersionInternal.Version10)
{
httpVersion = "HTTP/1.0";
}
else if (state.RequestMessage.Version == HttpVersionInternal.Version11)
{
httpVersion = "HTTP/1.1";
}
// Turn off additional URI reserved character escaping (percent-encoding). This matches
// .NET Framework behavior. System.Uri establishes the baseline rules for percent-encoding
// of reserved characters.
uint flags = Interop.WinHttp.WINHTTP_FLAG_ESCAPE_DISABLE;
if (state.RequestMessage.RequestUri.Scheme == UriScheme.Https)
{
flags |= Interop.WinHttp.WINHTTP_FLAG_SECURE;
}
// Create an HTTP request handle.
state.RequestHandle = Interop.WinHttp.WinHttpOpenRequest(
connectHandle,
state.RequestMessage.Method.Method,
state.RequestMessage.RequestUri.PathAndQuery,
httpVersion,
Interop.WinHttp.WINHTTP_NO_REFERER,
Interop.WinHttp.WINHTTP_DEFAULT_ACCEPT_TYPES,
flags);
ThrowOnInvalidHandle(state.RequestHandle, nameof(Interop.WinHttp.WinHttpOpenRequest));
state.RequestHandle.SetParentHandle(connectHandle);
// Set callback function.
SetStatusCallback(state.RequestHandle, WinHttpRequestCallback.StaticCallbackDelegate);
// Set needed options on the request handle.
SetRequestHandleOptions(state);
bool chunkedModeForSend = IsChunkedModeForSend(state.RequestMessage);
AddRequestHeaders(
state.RequestHandle,
state.RequestMessage,
_cookieUsePolicy == CookieUsePolicy.UseSpecifiedCookieContainer ? _cookieContainer : null);
uint proxyAuthScheme = 0;
uint serverAuthScheme = 0;
state.RetryRequest = false;
// The only way to abort pending async operations in WinHTTP is to close the WinHTTP handle.
// We will detect a cancellation request on the cancellation token by registering a callback.
// If the callback is invoked, then we begin the abort process by disposing the handle. This
// will have the side-effect of WinHTTP cancelling any pending I/O and accelerating its callbacks
// on the handle and thus releasing the awaiting tasks in the loop below. This helps to provide
// a more timely, cooperative, cancellation pattern.
using (state.CancellationToken.Register(s => ((WinHttpRequestState)s).RequestHandle.Dispose(), state))
{
do
{
_authHelper.PreAuthenticateRequest(state, proxyAuthScheme);
await InternalSendRequestAsync(state);
if (state.RequestMessage.Content != null)
{
await InternalSendRequestBodyAsync(state, chunkedModeForSend).ConfigureAwait(false);
}
bool receivedResponse = await InternalReceiveResponseHeadersAsync(state) != 0;
if (receivedResponse)
{
// If we're manually handling cookies, we need to add them to the container after
// each response has been received.
if (state.Handler.CookieUsePolicy == CookieUsePolicy.UseSpecifiedCookieContainer)
{
WinHttpCookieContainerAdapter.AddResponseCookiesToContainer(state);
}
_authHelper.CheckResponseForAuthentication(
state,
ref proxyAuthScheme,
ref serverAuthScheme);
}
} while (state.RetryRequest);
}
state.CancellationToken.ThrowIfCancellationRequested();
// Since the headers have been read, set the "receive" timeout to be based on each read
// call of the response body data. WINHTTP_OPTION_RECEIVE_TIMEOUT sets a timeout on each
// lower layer winsock read.
uint optionData = unchecked((uint)_receiveDataTimeout.TotalMilliseconds);
SetWinHttpOption(state.RequestHandle, Interop.WinHttp.WINHTTP_OPTION_RECEIVE_TIMEOUT, ref optionData);
HttpResponseMessage responseMessage = WinHttpResponseParser.CreateResponseMessage(state, _doManualDecompressionCheck);
state.Tcs.TrySetResult(responseMessage);
// HttpStatusCode cast is needed for 308 Moved Permenantly, which we support but is not included in NetStandard status codes.
if (WinHttpTraceHelper.IsTraceEnabled() &&
((responseMessage.StatusCode >= HttpStatusCode.MultipleChoices && responseMessage.StatusCode <= HttpStatusCode.SeeOther) ||
(responseMessage.StatusCode >= HttpStatusCode.RedirectKeepVerb && responseMessage.StatusCode <= (HttpStatusCode)308)) &&
state.RequestMessage.RequestUri.Scheme == Uri.UriSchemeHttps && responseMessage.Headers.Location?.Scheme == Uri.UriSchemeHttp)
{
WinHttpTraceHelper.Trace("WinHttpHandler.SendAsync: Insecure https to http redirect from {0} to {1} blocked.",
state.RequestMessage.RequestUri.ToString(), responseMessage.Headers.Location.ToString());
}
}
catch (Exception ex)
{
HandleAsyncException(state, state.SavedException ?? ex);
}
finally
{
SafeWinHttpHandle.DisposeAndClearHandle(ref connectHandle);
state.ClearSendRequestState();
}
}
private void SetSessionHandleOptions(SafeWinHttpHandle sessionHandle)
{
SetSessionHandleConnectionOptions(sessionHandle);
SetSessionHandleTlsOptions(sessionHandle);
SetSessionHandleTimeoutOptions(sessionHandle);
}
private void SetSessionHandleConnectionOptions(SafeWinHttpHandle sessionHandle)
{
uint optionData = (uint)_maxConnectionsPerServer;
SetWinHttpOption(sessionHandle, Interop.WinHttp.WINHTTP_OPTION_MAX_CONNS_PER_SERVER, ref optionData);
SetWinHttpOption(sessionHandle, Interop.WinHttp.WINHTTP_OPTION_MAX_CONNS_PER_1_0_SERVER, ref optionData);
}
private void SetSessionHandleTlsOptions(SafeWinHttpHandle sessionHandle)
{
uint optionData = 0;
SslProtocols sslProtocols =
(_sslProtocols == SslProtocols.None) ? SecurityProtocol.DefaultSecurityProtocols : _sslProtocols;
#pragma warning disable 0618 // SSL2/SSL3 are deprecated
if ((sslProtocols & SslProtocols.Ssl2) != 0)
{
optionData |= Interop.WinHttp.WINHTTP_FLAG_SECURE_PROTOCOL_SSL2;
}
if ((sslProtocols & SslProtocols.Ssl3) != 0)
{
optionData |= Interop.WinHttp.WINHTTP_FLAG_SECURE_PROTOCOL_SSL3;
}
#pragma warning restore 0618
if ((sslProtocols & SslProtocols.Tls) != 0)
{
optionData |= Interop.WinHttp.WINHTTP_FLAG_SECURE_PROTOCOL_TLS1;
}
if ((sslProtocols & SslProtocols.Tls11) != 0)
{
optionData |= Interop.WinHttp.WINHTTP_FLAG_SECURE_PROTOCOL_TLS1_1;
}
if ((sslProtocols & SslProtocols.Tls12) != 0)
{
optionData |= Interop.WinHttp.WINHTTP_FLAG_SECURE_PROTOCOL_TLS1_2;
}
SetWinHttpOption(sessionHandle, Interop.WinHttp.WINHTTP_OPTION_SECURE_PROTOCOLS, ref optionData);
}
private void SetSessionHandleTimeoutOptions(SafeWinHttpHandle sessionHandle)
{
if (!Interop.WinHttp.WinHttpSetTimeouts(
sessionHandle,
0,
0,
(int)_sendTimeout.TotalMilliseconds,
(int)_receiveHeadersTimeout.TotalMilliseconds))
{
WinHttpException.ThrowExceptionUsingLastError(nameof(Interop.WinHttp.WinHttpSetTimeouts));
}
}
private void SetRequestHandleOptions(WinHttpRequestState state)
{
SetRequestHandleProxyOptions(state);
SetRequestHandleDecompressionOptions(state.RequestHandle);
SetRequestHandleRedirectionOptions(state.RequestHandle);
SetRequestHandleCookieOptions(state.RequestHandle);
SetRequestHandleTlsOptions(state.RequestHandle);
SetRequestHandleClientCertificateOptions(state.RequestHandle, state.RequestMessage.RequestUri);
SetRequestHandleCredentialsOptions(state);
SetRequestHandleBufferingOptions(state.RequestHandle);
SetRequestHandleHttp2Options(state.RequestHandle, state.RequestMessage.Version);
}
private void SetRequestHandleProxyOptions(WinHttpRequestState state)
{
// We've already set the proxy on the session handle if we're using no proxy or default proxy settings.
// We only need to change it on the request handle if we have a specific IWebProxy or need to manually
// implement Wininet-style auto proxy detection.
if (state.WindowsProxyUsePolicy == WindowsProxyUsePolicy.UseCustomProxy ||
state.WindowsProxyUsePolicy == WindowsProxyUsePolicy.UseWinInetProxy)
{
var proxyInfo = new Interop.WinHttp.WINHTTP_PROXY_INFO();
bool updateProxySettings = false;
Uri uri = state.RequestMessage.RequestUri;
try
{