-
Notifications
You must be signed in to change notification settings - Fork 4.8k
/
SocketsHttpHandlerTest.cs
4550 lines (3817 loc) · 216 KB
/
SocketsHttpHandlerTest.cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.IO.Pipes;
using System.Linq;
using System.Net.Http.Headers;
using System.Net.Security;
using System.Net.Sockets;
using System.Net.Test.Common;
using System.Numerics;
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Security.Authentication;
using System.Security.Cryptography.X509Certificates;
using System.Security.Principal;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.DotNet.RemoteExecutor;
using Microsoft.DotNet.XUnitExtensions;
using Xunit;
using Xunit.Abstractions;
namespace System.Net.Http.Functional.Tests
{
using Configuration = System.Net.Test.Common.Configuration;
[ConditionalClass(typeof(PlatformDetection), nameof(PlatformDetection.IsNotBrowser))]
public sealed class SocketsHttpHandler_HttpClientHandler_Asynchrony_Test : HttpClientHandler_Asynchrony_Test
{
public SocketsHttpHandler_HttpClientHandler_Asynchrony_Test(ITestOutputHelper output) : base(output) { }
[OuterLoop("Relies on finalization")]
[Fact]
public async Task ReadAheadTaskOnScavenge_ExceptionsAreObserved()
{
bool seenUnobservedExceptions = false;
EventHandler<UnobservedTaskExceptionEventArgs> eventHandler = (_, e) =>
{
if (e.Exception.InnerException?.Message == nameof(ReadAheadTaskOnScavenge_ExceptionsAreObserved))
{
seenUnobservedExceptions = true;
}
};
TaskScheduler.UnobservedTaskException += eventHandler;
try
{
for (int i = 0; i < 3; i++)
{
await MakeARequestWithoutDisposingTheHandlerAsync();
GC.Collect();
GC.WaitForPendingFinalizers();
await Task.Delay(1000);
}
}
finally
{
TaskScheduler.UnobservedTaskException -= eventHandler;
}
Assert.False(seenUnobservedExceptions);
static async Task MakeARequestWithoutDisposingTheHandlerAsync()
{
var cts = new CancellationTokenSource();
var requestCompleted = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously);
var handler = new SocketsHttpHandler();
handler.ConnectCallback = async (_, _) =>
{
cts.Cancel();
await requestCompleted.Task;
Task completedWhenFinalized = new SetOnFinalized().CompletedWhenFinalized.Task;
return new DelegateDelegatingStream(Stream.Null)
{
ReadAsyncMemoryFunc = async (_, _) =>
{
await completedWhenFinalized.WaitAsync(TestHelper.PassingTestTimeout);
throw new Exception(nameof(ReadAheadTaskOnScavenge_ExceptionsAreObserved));
}
};
};
handler.PooledConnectionIdleTimeout = TimeSpan.FromSeconds(1);
var client = new HttpClient(handler);
await Assert.ThrowsAsync<TaskCanceledException>(() => client.GetStringAsync("http://foo", cts.Token));
requestCompleted.SetResult();
}
}
[Fact]
public async Task ExecutionContext_Suppressed_Success()
{
await LoopbackServerFactory.CreateClientAndServerAsync(
uri => Task.Run(() =>
{
using (ExecutionContext.SuppressFlow())
using (HttpClient client = CreateHttpClient())
{
client.GetStringAsync(uri).GetAwaiter().GetResult();
}
}),
async server =>
{
await server.AcceptConnectionSendResponseAndCloseAsync();
});
}
[OuterLoop("Relies on finalization")]
[Fact]
public async Task ExecutionContext_HttpConnectionLifetimeDoesntKeepContextAlive()
{
var clientCompleted = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously);
await LoopbackServer.CreateClientAndServerAsync(async uri =>
{
try
{
using (HttpClient client = CreateHttpClient())
{
(Task completedWhenFinalized, Task getRequest) = MakeHttpRequestWithTcsSetOnFinalizationInAsyncLocal(client, uri);
await getRequest;
for (int i = 0; i < 3; i++)
{
GC.Collect();
GC.WaitForPendingFinalizers();
}
await completedWhenFinalized.WaitAsync(TestHelper.PassingTestTimeout);
}
}
finally
{
clientCompleted.SetResult();
}
}, async server =>
{
await server.AcceptConnectionAsync(async connection =>
{
await connection.ReadRequestHeaderAndSendResponseAsync();
await clientCompleted.Task;
});
});
}
[MethodImpl(MethodImplOptions.NoInlining)] // avoid JIT extending lifetime of the finalizable object
private static (Task completedOnFinalized, Task getRequest) MakeHttpRequestWithTcsSetOnFinalizationInAsyncLocal(HttpClient client, Uri uri)
{
// Put something in ExecutionContext, start the HTTP request, then undo the EC change.
var al = new AsyncLocal<SetOnFinalized>() { Value = new SetOnFinalized() };
TaskCompletionSource tcs = al.Value.CompletedWhenFinalized;
Task t = client.GetStringAsync(uri);
al.Value = null;
// Return a task that will complete when the SetOnFinalized is finalized,
// as well as a task to wait on for the get request; for the get request,
// we return a continuation to avoid any test-altering issues related to
// the state machine holding onto stuff.
t = t.ContinueWith(p => p.GetAwaiter().GetResult());
return (tcs.Task, t);
}
private sealed class SetOnFinalized
{
public readonly TaskCompletionSource CompletedWhenFinalized = new(TaskCreationOptions.RunContinuationsAsynchronously);
~SetOnFinalized() => CompletedWhenFinalized.SetResult();
}
}
[ConditionalClass(typeof(PlatformDetection), nameof(PlatformDetection.IsNotBrowser))]
public sealed class SocketsHttpHandler_HttpProtocolTests : HttpProtocolTests
{
public SocketsHttpHandler_HttpProtocolTests(ITestOutputHelper output) : base(output) { }
[Fact]
public async Task DefaultRequestHeaders_SentUnparsed()
{
await LoopbackServer.CreateClientAndServerAsync(async uri =>
{
using (HttpClient client = CreateHttpClient())
{
client.DefaultRequestHeaders.TryAddWithoutValidation("Accept-Language", "en-US,en;q=0.5"); // validation would add spaces
client.DefaultRequestHeaders.TryAddWithoutValidation("From", "invalidemail"); // would fail to parse if validated
var m = new HttpRequestMessage(HttpMethod.Get, uri) { Version = UseVersion };
(await client.SendAsync(TestAsync, m)).Dispose();
}
}, async server =>
{
List<string> headers = await server.AcceptConnectionSendResponseAndCloseAsync();
Assert.Contains(headers, header => header.Contains("Accept-Language: en-US,en;q=0.5"));
Assert.Contains(headers, header => header.Contains("From: invalidemail"));
});
}
}
[ConditionalClass(typeof(PlatformDetection), nameof(PlatformDetection.IsNotBrowser))]
public sealed class SocketsHttpHandler_HttpProtocolTests_Dribble : HttpProtocolTests_Dribble
{
public SocketsHttpHandler_HttpProtocolTests_Dribble(ITestOutputHelper output) : base(output) { }
}
public sealed class SocketsHttpHandler_DiagnosticsTest_Http11 : DiagnosticsTest
{
public SocketsHttpHandler_DiagnosticsTest_Http11(ITestOutputHelper output) : base(output) { }
}
public sealed class SocketsHttpHandler_DiagnosticsTest_Http2 : DiagnosticsTest
{
public SocketsHttpHandler_DiagnosticsTest_Http2(ITestOutputHelper output) : base(output) { }
protected override Version UseVersion => HttpVersion.Version20;
}
public sealed class SocketsHttpHandler_HttpClient_SelectedSites_Test : HttpClient_SelectedSites_Test
{
public SocketsHttpHandler_HttpClient_SelectedSites_Test(ITestOutputHelper output) : base(output) { }
}
#if !TARGETS_BROWSER
public sealed class SocketsHttpHandler_HttpClientEKUTest : HttpClientEKUTest
{
public SocketsHttpHandler_HttpClientEKUTest(ITestOutputHelper output) : base(output) { }
}
#endif
[SkipOnPlatform(TestPlatforms.Browser, "AutomaticDecompression not supported on Browser")]
public sealed class SocketsHttpHandler_HttpClientHandler_Decompression_Tests : HttpClientHandler_Decompression_Test
{
public SocketsHttpHandler_HttpClientHandler_Decompression_Tests(ITestOutputHelper output) : base(output) { }
}
[SkipOnPlatform(TestPlatforms.Browser, "Certificates are not supported on Browser")]
public sealed class SocketsHttpHandler_HttpClientHandler_DangerousAcceptAllCertificatesValidator_Test : HttpClientHandler_DangerousAcceptAllCertificatesValidator_Test
{
public SocketsHttpHandler_HttpClientHandler_DangerousAcceptAllCertificatesValidator_Test(ITestOutputHelper output) : base(output) { }
}
[SkipOnPlatform(TestPlatforms.Browser, "Certificates are not supported on Browser")]
public sealed class SocketsHttpHandler_HttpClientHandler_ClientCertificates_Test : HttpClientHandler_ClientCertificates_Test
{
public SocketsHttpHandler_HttpClientHandler_ClientCertificates_Test(ITestOutputHelper output) : base(output) { }
}
[SkipOnPlatform(TestPlatforms.Browser, "Proxy is not supported on Browser")]
public sealed class SocketsHttpHandler_HttpClientHandler_DefaultProxyCredentials_Test : HttpClientHandler_DefaultProxyCredentials_Test
{
public SocketsHttpHandler_HttpClientHandler_DefaultProxyCredentials_Test(ITestOutputHelper output) : base(output) { }
}
public sealed class SocketsHttpHandler_HttpClientHandler_Finalization_Http11_Test : HttpClientHandler_Finalization_Test
{
public SocketsHttpHandler_HttpClientHandler_Finalization_Http11_Test(ITestOutputHelper output) : base(output) { }
}
public sealed class SocketsHttpHandler_HttpClientHandler_Finalization_Http2_Test : HttpClientHandler_Finalization_Test
{
public SocketsHttpHandler_HttpClientHandler_Finalization_Http2_Test(ITestOutputHelper output) : base(output) { }
protected override Version UseVersion => HttpVersion.Version20;
}
[SkipOnPlatform(TestPlatforms.Browser, "MaxConnectionsPerServer not supported on Browser")]
public sealed class SocketsHttpHandler_HttpClientHandler_MaxConnectionsPerServer_Test : HttpClientHandler_MaxConnectionsPerServer_Test
{
public SocketsHttpHandler_HttpClientHandler_MaxConnectionsPerServer_Test(ITestOutputHelper output) : base(output) { }
[ConditionalTheory(typeof(RemoteExecutor), nameof(RemoteExecutor.IsSupported))]
[InlineData(true)]
[InlineData(false)]
public void AppContextSetData_SetDefaultMaxConnectionsPerServer(bool asInt)
{
RemoteExecutor.Invoke(static (asInt) =>
{
const int testValue = 123;
object data = asInt == Boolean.TrueString ? testValue : testValue.ToString();
AppContext.SetData("System.Net.SocketsHttpHandler.MaxConnectionsPerServer", data);
var handler = new HttpClientHandler();
Assert.Equal(testValue, handler.MaxConnectionsPerServer);
}, asInt.ToString()).Dispose();
}
[OuterLoop("Incurs a small delay")]
[Theory]
[InlineData(0)]
[InlineData(1)]
public async Task SmallConnectionLifetimeWithMaxConnections_PendingRequestUsesDifferentConnection(int lifetimeMilliseconds)
{
using (var handler = new SocketsHttpHandler())
{
handler.PooledConnectionLifetime = TimeSpan.FromMilliseconds(lifetimeMilliseconds);
handler.MaxConnectionsPerServer = 1;
using (HttpClient client = CreateHttpClient(handler))
{
await LoopbackServer.CreateServerAsync(async (server, uri) =>
{
Task<string> request1 = client.GetStringAsync(uri);
Task<string> request2 = client.GetStringAsync(uri);
await server.AcceptConnectionAsync(async connection =>
{
Task secondResponse = server.AcceptConnectionAsync(connection2 =>
connection2.ReadRequestHeaderAndSendCustomResponseAsync(LoopbackServer.GetConnectionCloseResponse()));
// Wait a small amount of time before sending the first response, so the connection lifetime will expire.
Debug.Assert(lifetimeMilliseconds < 100);
await Task.Delay(1000);
// Second request should not have completed yet, as we haven't completed the first yet.
Assert.False(request2.IsCompleted);
Assert.False(secondResponse.IsCompleted);
// Send the first response and wait for the first request to complete.
await connection.ReadRequestHeaderAndSendResponseAsync();
await request1;
// Now the second request should complete.
await secondResponse.WaitAsync(TestHelper.PassingTestTimeout);
});
});
}
}
}
}
[SkipOnPlatform(TestPlatforms.Browser, "Certificates are not supported on Browser")]
public sealed class SocketsHttpHandler_HttpClientHandler_ServerCertificates_Test : HttpClientHandler_ServerCertificates_Test
{
public SocketsHttpHandler_HttpClientHandler_ServerCertificates_Test(ITestOutputHelper output) : base(output) { }
}
[SkipOnPlatform(TestPlatforms.Browser, "ResponseDrainTimeout is not supported on Browser")]
public sealed class SocketsHttpHandler_HttpClientHandler_ResponseDrain_Test : HttpClientHandler_ResponseDrain_Test
{
protected override void SetResponseDrainTimeout(HttpClientHandler handler, TimeSpan time)
{
SocketsHttpHandler s = (SocketsHttpHandler)GetUnderlyingSocketsHttpHandler(handler);
Assert.NotNull(s);
s.ResponseDrainTimeout = time;
}
public SocketsHttpHandler_HttpClientHandler_ResponseDrain_Test(ITestOutputHelper output) : base(output) { }
[Fact]
public void MaxResponseDrainSize_Roundtrips()
{
using (var handler = new SocketsHttpHandler())
{
Assert.Equal(1024 * 1024, handler.MaxResponseDrainSize);
handler.MaxResponseDrainSize = 0;
Assert.Equal(0, handler.MaxResponseDrainSize);
handler.MaxResponseDrainSize = int.MaxValue;
Assert.Equal(int.MaxValue, handler.MaxResponseDrainSize);
}
}
[Fact]
public void MaxResponseDrainSize_InvalidArgument_Throws()
{
using (var handler = new SocketsHttpHandler())
{
Assert.Equal(1024 * 1024, handler.MaxResponseDrainSize);
AssertExtensions.Throws<ArgumentOutOfRangeException>("value", () => handler.MaxResponseDrainSize = -1);
AssertExtensions.Throws<ArgumentOutOfRangeException>("value", () => handler.MaxResponseDrainSize = int.MinValue);
Assert.Equal(1024 * 1024, handler.MaxResponseDrainSize);
}
}
[Fact]
public void MaxResponseDrainSize_SetAfterUse_Throws()
{
using (var handler = new SocketsHttpHandler())
using (HttpClient client = CreateHttpClient(handler))
{
handler.MaxResponseDrainSize = 1;
_ = client.GetAsync($"http://{Guid.NewGuid():N}"); // ignoring failure
Assert.Equal(1, handler.MaxResponseDrainSize);
Assert.Throws<InvalidOperationException>(() => handler.MaxResponseDrainSize = 1);
}
}
[Fact]
public void ResponseDrainTimeout_Roundtrips()
{
using (var handler = new SocketsHttpHandler())
{
Assert.Equal(TimeSpan.FromSeconds(2), handler.ResponseDrainTimeout);
handler.ResponseDrainTimeout = TimeSpan.Zero;
Assert.Equal(TimeSpan.Zero, handler.ResponseDrainTimeout);
handler.ResponseDrainTimeout = TimeSpan.FromTicks(int.MaxValue);
Assert.Equal(TimeSpan.FromTicks(int.MaxValue), handler.ResponseDrainTimeout);
}
}
[Fact]
public void MaxResponseDraiTime_InvalidArgument_Throws()
{
using (var handler = new SocketsHttpHandler())
{
Assert.Equal(TimeSpan.FromSeconds(2), handler.ResponseDrainTimeout);
AssertExtensions.Throws<ArgumentOutOfRangeException>("value", () => handler.ResponseDrainTimeout = TimeSpan.FromSeconds(-1));
AssertExtensions.Throws<ArgumentOutOfRangeException>("value", () => handler.ResponseDrainTimeout = TimeSpan.MaxValue);
AssertExtensions.Throws<ArgumentOutOfRangeException>("value", () => handler.ResponseDrainTimeout = TimeSpan.FromSeconds(int.MaxValue));
Assert.Equal(TimeSpan.FromSeconds(2), handler.ResponseDrainTimeout);
}
}
[Fact]
public void ResponseDrainTimeout_SetAfterUse_Throws()
{
using (var handler = new SocketsHttpHandler())
using (HttpClient client = CreateHttpClient(handler))
{
handler.ResponseDrainTimeout = TimeSpan.FromSeconds(42);
_ = client.GetAsync($"http://{Guid.NewGuid():N}"); // ignoring failure
Assert.Equal(TimeSpan.FromSeconds(42), handler.ResponseDrainTimeout);
Assert.Throws<InvalidOperationException>(() => handler.ResponseDrainTimeout = TimeSpan.FromSeconds(42));
}
}
[OuterLoop]
[Theory]
[InlineData(1024 * 1024 * 2, 9_500, 1024 * 1024 * 3, LoopbackServer.ContentMode.ContentLength)]
[InlineData(1024 * 1024 * 2, 9_500, 1024 * 1024 * 3, LoopbackServer.ContentMode.SingleChunk)]
[InlineData(1024 * 1024 * 2, 9_500, 1024 * 1024 * 13, LoopbackServer.ContentMode.BytePerChunk)]
public async Task GetAsyncWithMaxConnections_DisposeBeforeReadingToEnd_DrainsRequestsUnderMaxDrainSizeAndReusesConnection(int totalSize, int readSize, int maxDrainSize, LoopbackServer.ContentMode mode)
{
await LoopbackServer.CreateClientAndServerAsync(
async url =>
{
var handler = new SocketsHttpHandler();
handler.MaxResponseDrainSize = maxDrainSize;
handler.ResponseDrainTimeout = Timeout.InfiniteTimeSpan;
// Set MaxConnectionsPerServer to 1. This will ensure we will wait for the previous request to drain (or fail to)
handler.MaxConnectionsPerServer = 1;
using (HttpClient client = CreateHttpClient(handler))
{
HttpResponseMessage response1 = await client.GetAsync(url, HttpCompletionOption.ResponseHeadersRead);
ValidateResponseHeaders(response1, totalSize, mode);
// Read part but not all of response
Stream responseStream = await response1.Content.ReadAsStreamAsync(TestAsync);
await ReadToByteCount(responseStream, readSize);
response1.Dispose();
// Issue another request. We'll confirm that it comes on the same connection.
HttpResponseMessage response2 = await client.GetAsync(url);
ValidateResponseHeaders(response2, totalSize, mode);
Assert.Equal(totalSize, (await response2.Content.ReadAsStringAsync()).Length);
}
},
async server =>
{
string content = new string('a', totalSize);
string response = LoopbackServer.GetContentModeResponse(mode, content);
await server.AcceptConnectionAsync(async connection =>
{
server.ListenSocket.Close(); // Shut down the listen socket so attempts at additional connections would fail on the client
await connection.ReadRequestHeaderAndSendCustomResponseAsync(response);
await connection.ReadRequestHeaderAndSendCustomResponseAsync(response);
});
});
}
[OuterLoop]
[Theory]
[InlineData(100_000, 0, LoopbackServer.ContentMode.ContentLength)]
[InlineData(100_000, 0, LoopbackServer.ContentMode.SingleChunk)]
[InlineData(100_000, 0, LoopbackServer.ContentMode.BytePerChunk)]
public async Task GetAsyncWithMaxConnections_DisposeLargerThanMaxDrainSize_KillsConnection(int totalSize, int maxDrainSize, LoopbackServer.ContentMode mode)
{
await LoopbackServer.CreateClientAndServerAsync(
async url =>
{
var handler = new SocketsHttpHandler();
handler.MaxResponseDrainSize = maxDrainSize;
handler.ResponseDrainTimeout = Timeout.InfiniteTimeSpan;
// Set MaxConnectionsPerServer to 1. This will ensure we will wait for the previous request to drain (or fail to)
handler.MaxConnectionsPerServer = 1;
using (HttpClient client = CreateHttpClient(handler))
{
HttpResponseMessage response1 = await client.GetAsync(url, HttpCompletionOption.ResponseHeadersRead);
ValidateResponseHeaders(response1, totalSize, mode);
response1.Dispose();
// Issue another request. We'll confirm that it comes on a new connection.
HttpResponseMessage response2 = await client.GetAsync(url);
ValidateResponseHeaders(response2, totalSize, mode);
Assert.Equal(totalSize, (await response2.Content.ReadAsStringAsync()).Length);
}
},
async server =>
{
string content = new string('a', totalSize);
await server.AcceptConnectionAsync(async connection =>
{
await connection.ReadRequestHeaderAsync();
try
{
await connection.WriteStringAsync(LoopbackServer.GetContentModeResponse(mode, content, connectionClose: false));
}
catch (Exception) { } // Eat errors from client disconnect.
await server.AcceptConnectionSendCustomResponseAndCloseAsync(LoopbackServer.GetContentModeResponse(mode, content, connectionClose: true));
});
});
}
[OuterLoop]
[Theory]
[InlineData(LoopbackServer.ContentMode.ContentLength)]
[InlineData(LoopbackServer.ContentMode.SingleChunk)]
[InlineData(LoopbackServer.ContentMode.BytePerChunk)]
public async Task GetAsyncWithMaxConnections_DrainTakesLongerThanTimeout_KillsConnection(LoopbackServer.ContentMode mode)
{
const int ContentLength = 10_000;
await LoopbackServer.CreateClientAndServerAsync(
async url =>
{
var handler = new SocketsHttpHandler();
handler.MaxResponseDrainSize = int.MaxValue;
handler.ResponseDrainTimeout = TimeSpan.FromMilliseconds(1);
// Set MaxConnectionsPerServer to 1. This will ensure we will wait for the previous request to drain (or fail to)
handler.MaxConnectionsPerServer = 1;
using (HttpClient client = CreateHttpClient(handler))
{
client.Timeout = Timeout.InfiniteTimeSpan;
HttpResponseMessage response1 = await client.GetAsync(url, HttpCompletionOption.ResponseHeadersRead);
ValidateResponseHeaders(response1, ContentLength, mode);
response1.Dispose();
// Issue another request. We'll confirm that it comes on a new connection.
HttpResponseMessage response2 = await client.GetAsync(url);
ValidateResponseHeaders(response2, ContentLength, mode);
Assert.Equal(ContentLength, (await response2.Content.ReadAsStringAsync()).Length);
}
},
async server =>
{
string content = new string('a', ContentLength);
await server.AcceptConnectionAsync(async connection =>
{
string response = LoopbackServer.GetContentModeResponse(mode, content, connectionClose: false);
await connection.ReadRequestHeaderAsync();
try
{
// Write out only part of the response
await connection.WriteStringAsync(response.Substring(0, response.Length / 2));
}
catch (Exception) { } // Eat errors from client disconnect.
response = LoopbackServer.GetContentModeResponse(mode, content, connectionClose: true);
await server.AcceptConnectionSendCustomResponseAndCloseAsync(response);
});
});
}
}
[ConditionalClass(typeof(PlatformDetection), nameof(PlatformDetection.IsNotBrowser))]
public sealed class SocketsHttpHandler_PostScenarioTest : PostScenarioTest
{
public SocketsHttpHandler_PostScenarioTest(ITestOutputHelper output) : base(output) { }
[Theory]
[InlineData(false)]
[InlineData(true)]
public async Task DisposeTargetStream_ThrowsObjectDisposedException(bool knownLength)
{
var tcs = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously);
await LoopbackServerFactory.CreateClientAndServerAsync(async uri =>
{
try
{
using (HttpClient client = CreateHttpClient())
{
Task t = client.PostAsync(uri, new DisposeStreamWhileCopyingContent(knownLength));
Assert.IsType<ObjectDisposedException>((await Assert.ThrowsAsync<HttpRequestException>(() => t)).InnerException);
}
}
finally
{
tcs.SetResult();
}
}, server => tcs.Task);
}
private sealed class DisposeStreamWhileCopyingContent : HttpContent
{
private readonly bool _knownLength;
public DisposeStreamWhileCopyingContent(bool knownLength) => _knownLength = knownLength;
protected override async Task SerializeToStreamAsync(Stream stream, TransportContext context)
{
await stream.WriteAsync(new byte[42], 0, 42);
stream.Dispose();
}
protected override bool TryComputeLength(out long length)
{
if (_knownLength)
{
length = 42;
return true;
}
else
{
length = 0;
return false;
}
}
}
}
[ConditionalClass(typeof(PlatformDetection), nameof(PlatformDetection.IsBrowserDomSupportedOrNotBrowser))]
public sealed class SocketsHttpHandler_ResponseStreamTest : ResponseStreamTest
{
public SocketsHttpHandler_ResponseStreamTest(ITestOutputHelper output) : base(output) { }
}
[ActiveIssue("https://github.com/dotnet/runtime/issues/37669", TestPlatforms.Browser)]
public sealed class SocketsHttpHandler_HttpClientHandler_SslProtocols_Test : HttpClientHandler_SslProtocols_Test
{
public SocketsHttpHandler_HttpClientHandler_SslProtocols_Test(ITestOutputHelper output) : base(output) { }
}
[SkipOnPlatform(TestPlatforms.Browser, "UseProxy not supported on Browser")]
public sealed class SocketsHttpHandler_HttpClientHandler_Proxy_Test : HttpClientHandler_Proxy_Test
{
public SocketsHttpHandler_HttpClientHandler_Proxy_Test(ITestOutputHelper output) : base(output) { }
[Theory]
[InlineData(true)]
[InlineData(false)]
public async Task Proxy_Https_Succeeds(bool secureUri)
{
var releaseServer = new TaskCompletionSource();
await LoopbackServer.CreateClientAndServerAsync(async uri =>
{
bool validationCalled = false;
using SocketsHttpHandler handler = CreateSocketsHttpHandler(allowAllCertificates: true);
handler.Proxy = new UseSpecifiedUriWebProxy(uri, new NetworkCredential("abc", "password"));
handler.SslOptions.RemoteCertificateValidationCallback = (sender, certificate, chain, error) =>
{
validationCalled = true;
return true;
};
using (HttpClient client = CreateHttpClient(handler))
{
HttpResponseMessage response = await client.GetAsync(secureUri ? "https://foo.bar/" : "http://foo.bar/");
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
Assert.True(validationCalled);
}
}, server => server.AcceptConnectionAsync(async connection =>
{
await connection.ReadRequestHeaderAndSendResponseAsync();
if (secureUri)
{
// client will send CONNECT and if that succeeds it will negotiate TLS
var sslConnection = await LoopbackServer.Connection.CreateAsync(null, connection.Stream, new LoopbackServer.Options { UseSsl = true });
await sslConnection.ReadRequestHeaderAndSendResponseAsync();
}
}),
new LoopbackServer.Options { UseSsl = true });
}
}
public abstract class SocketsHttpHandler_TrailingHeaders_Test : HttpClientHandlerTestBase
{
public SocketsHttpHandler_TrailingHeaders_Test(ITestOutputHelper output) : base(output) { }
protected static byte[] DataBytes = "data"u8.ToArray();
protected static readonly IList<HttpHeaderData> TrailingHeaders = new HttpHeaderData[] {
new HttpHeaderData("MyCoolTrailerHeader", "amazingtrailer"),
new HttpHeaderData("EmptyHeader", ""),
new HttpHeaderData("Accept-Encoding", "identity,gzip"),
new HttpHeaderData("Hello", "World") };
protected static Frame MakeDataFrame(int streamId, byte[] data, bool endStream = false) =>
new DataFrame(data, (endStream ? FrameFlags.EndStream : FrameFlags.None), 0, streamId);
}
[ActiveIssue("https://github.com/dotnet/runtime/issues/54156", TestPlatforms.Browser)]
public class SocketsHttpHandler_Http1_TrailingHeaders_Test : SocketsHttpHandler_TrailingHeaders_Test
{
public SocketsHttpHandler_Http1_TrailingHeaders_Test(ITestOutputHelper output) : base(output) { }
[Theory]
[InlineData(false)]
[InlineData(true)]
public async Task GetAsyncDefaultCompletionOption_TrailingHeaders_Available(bool includeTrailerHeader)
{
await LoopbackServer.CreateServerAsync(async (server, url) =>
{
using (HttpClientHandler handler = CreateHttpClientHandler())
using (HttpClient client = CreateHttpClient(handler))
{
Task<HttpResponseMessage> getResponseTask = client.GetAsync(url);
await TestHelper.WhenAllCompletedOrAnyFailed(
getResponseTask,
server.AcceptConnectionSendCustomResponseAndCloseAsync(
"HTTP/1.1 200 OK\r\n" +
LoopbackServer.CorsHeaders +
"Connection: close\r\n" +
"Transfer-Encoding: chunked\r\n" +
(includeTrailerHeader ? "Trailer: MyCoolTrailerHeader, Hello\r\n" : "") +
"\r\n" +
"4\r\n" +
"data\r\n" +
"0\r\n" +
"MyCoolTrailerHeader: amazingtrailer\r\n" +
"Accept-encoding: identity,gzip\r\n" +
"Hello: World\r\n" +
"\r\n"));
using (HttpResponseMessage response = await getResponseTask)
{
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
Assert.Contains("chunked", response.Headers.GetValues("Transfer-Encoding"));
// Check the Trailer header.
if (includeTrailerHeader)
{
Assert.Contains("MyCoolTrailerHeader", response.Headers.GetValues("Trailer"));
Assert.Contains("Hello", response.Headers.GetValues("Trailer"));
}
Assert.Contains("amazingtrailer", response.TrailingHeaders.GetValues("MyCoolTrailerHeader"));
Assert.Contains("World", response.TrailingHeaders.GetValues("Hello"));
Assert.Contains("identity,gzip", response.TrailingHeaders.GetValues("Accept-encoding"));
string data = await response.Content.ReadAsStringAsync();
Assert.Contains("data", data);
// Trailers should not be part of the content data.
Assert.DoesNotContain("MyCoolTrailerHeader", data);
Assert.DoesNotContain("amazingtrailer", data);
Assert.DoesNotContain("Hello", data);
Assert.DoesNotContain("World", data);
}
}
});
}
[Fact]
public async Task GetAsyncResponseHeadersReadOption_TrailingHeaders_Available()
{
await LoopbackServer.CreateServerAsync(async (server, url) =>
{
using (HttpClientHandler handler = CreateHttpClientHandler())
using (HttpClient client = CreateHttpClient(handler))
{
Task<HttpResponseMessage> getResponseTask = client.GetAsync(url, HttpCompletionOption.ResponseHeadersRead);
await TestHelper.WhenAllCompletedOrAnyFailed(
getResponseTask,
server.AcceptConnectionSendCustomResponseAndCloseAsync(
"HTTP/1.1 200 OK\r\n" +
LoopbackServer.CorsHeaders +
"Connection: close\r\n" +
"Transfer-Encoding: chunked\r\n" +
"Trailer: MyCoolTrailerHeader\r\n" +
"\r\n" +
"4\r\n" +
"data\r\n" +
"0\r\n" +
"MyCoolTrailerHeader: amazingtrailer\r\n" +
"Hello: World\r\n" +
"\r\n"));
using (HttpResponseMessage response = await getResponseTask)
{
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
Assert.Contains("chunked", response.Headers.GetValues("Transfer-Encoding"));
Assert.Contains("MyCoolTrailerHeader", response.Headers.GetValues("Trailer"));
// Pending read on the response content.
var trailingHeaders = response.TrailingHeaders;
Assert.Empty(trailingHeaders);
Stream stream = await response.Content.ReadAsStreamAsync(TestAsync);
Byte[] data = new Byte[100];
// Read some data, preferably whole body.
int readBytes = await stream.ReadAsync(data, 0, 4);
// Intermediate test - haven't reached stream EOF yet.
Assert.Empty(response.TrailingHeaders);
if (readBytes == 4)
{
// If we consumed whole content, check content.
Assert.Contains("data", System.Text.Encoding.Default.GetString(data));
}
// Read data until EOF is reached
while (stream.Read(data, 0, data.Length) != 0)
;
Assert.Same(trailingHeaders, response.TrailingHeaders);
Assert.Contains("amazingtrailer", response.TrailingHeaders.GetValues("MyCoolTrailerHeader"));
Assert.Contains("World", response.TrailingHeaders.GetValues("Hello"));
}
}
});
}
[Theory]
[InlineData(1024, 1023)]
[InlineData(1024, 1024)]
[InlineData(1024, 1025)]
[InlineData(1024 * 1024, 1024 * 1024)]
[InlineData(1024 * 1024, 1024 * 1024 + 1)]
public async Task GetAsync_TrailingHeadersLimitExceeded_Throws(int maxResponseHeadersLength, int responseHeadersLength)
{
Assert.Equal(0, maxResponseHeadersLength % 1024);
var sb = new StringBuilder()
.Append("HTTP/1.1 200 OK\r\n")
.Append("Connection: close\r\n")
.Append("Transfer-Encoding: chunked\r\n\r\n");
// Both regular and trailing response headers count against the same length limit
int headerBytesRemaining = responseHeadersLength - sb.Length;
sb.Append("0\r\n"); // chunked content
const string HeaderLine = "Test: value";
while (headerBytesRemaining > HeaderLine.Length * 2)
{
sb.Append(HeaderLine).Append("\r\n");
headerBytesRemaining -= (HeaderLine.Length + 2);
}
sb.Append("Test: ");
sb.Append('a', headerBytesRemaining - "Test: \r\n\r\n".Length);
sb.Append("\r\n");
sb.Append("\r\n");
string response = sb.ToString();
await LoopbackServer.CreateClientAndServerAsync(
async uri =>
{
using HttpClientHandler handler = CreateHttpClientHandler();
using HttpClient client = CreateHttpClient(handler);
handler.MaxResponseHeadersLength = maxResponseHeadersLength / 1024;
if (responseHeadersLength > maxResponseHeadersLength)
{
HttpRequestException exception = await Assert.ThrowsAsync<HttpRequestException>(() => client.GetAsync(uri));
Assert.Contains("exceeded", exception.Message);
}
else
{
(await client.GetAsync(uri)).Dispose();
}
},
async server =>
{
try
{
await server.AcceptConnectionSendCustomResponseAndCloseAsync(response);
}
catch { }
});
}
[Theory]
[InlineData("Age", "1")]
// [SuppressMessage("Microsoft.Security", "CS002:SecretInNextLine", Justification="Suppression approved. Unit test dummy authorisation header.")]
[InlineData("Authorization", "Basic YWxhZGRpbjpvcGVuc2VzYW1l")]
[InlineData("Cache-Control", "no-cache")]
[InlineData("Content-Encoding", "gzip")]
[InlineData("Content-Length", "22")]
[InlineData("Content-type", "foo/bar")]
[InlineData("Content-Range", "bytes 200-1000/67589")]
[InlineData("Date", "Wed, 21 Oct 2015 07:28:00 GMT")]
[InlineData("Expect", "100-continue")]
[InlineData("Expires", "Wed, 21 Oct 2015 07:28:00 GMT")]
[InlineData("Host", "foo")]
[InlineData("If-Match", "Wed, 21 Oct 2015 07:28:00 GMT")]
[InlineData("If-Modified-Since", "Wed, 21 Oct 2015 07:28:00 GMT")]
[InlineData("If-None-Match", "*")]
[InlineData("If-Range", "Wed, 21 Oct 2015 07:28:00 GMT")]
[InlineData("If-Unmodified-Since", "Wed, 21 Oct 2015 07:28:00 GMT")]
[InlineData("Location", "/index.html")]
[InlineData("Max-Forwards", "2")]
[InlineData("Pragma", "no-cache")]
[InlineData("Range", "5/10")]
[InlineData("Retry-After", "20")]
[InlineData("Set-Cookie", "foo=bar")]
[InlineData("TE", "boo")]
[InlineData("Transfer-Encoding", "chunked")]
[InlineData("Transfer-Encoding", "gzip")]
[InlineData("Vary", "*")]
[InlineData("Warning", "300 - \"Be Warned!\"")]
public async Task GetAsync_ForbiddenTrailingHeaders_Ignores(string name, string value)
{
await LoopbackServer.CreateClientAndServerAsync(async url =>
{
using (HttpClientHandler handler = CreateHttpClientHandler())
using (HttpClient client = CreateHttpClient(handler))
{
HttpResponseMessage response = await client.GetAsync(url);
Assert.Contains("amazingtrailer", response.TrailingHeaders.GetValues("MyCoolTrailerHeader"));
Assert.False(response.TrailingHeaders.TryGetValues(name, out IEnumerable<string> values));
Assert.Contains("Loopback", response.TrailingHeaders.GetValues("Server"));
}
}, server => server.AcceptConnectionSendCustomResponseAndCloseAsync(
"HTTP/1.1 200 OK\r\n" +
LoopbackServer.CorsHeaders +
"Connection: close\r\n" +
"Transfer-Encoding: chunked\r\n" +
$"Trailer: Set-Cookie, MyCoolTrailerHeader, {name}, Hello\r\n" +
"\r\n" +
"4\r\n" +
"data\r\n" +
"0\r\n" +
"Set-Cookie: yummy\r\n" +
"MyCoolTrailerHeader: amazingtrailer\r\n" +
$"{name}: {value}\r\n" +
"Server: Loopback\r\n" +
$"{name}: {value}\r\n" +
"\r\n"));
}
[Fact]
public async Task GetAsync_NoTrailingHeaders_EmptyCollection()
{
await LoopbackServer.CreateServerAsync(async (server, url) =>
{
using (HttpClientHandler handler = CreateHttpClientHandler())
using (HttpClient client = CreateHttpClient(handler))
{
Task<HttpResponseMessage> getResponseTask = client.GetAsync(url);
await TestHelper.WhenAllCompletedOrAnyFailed(
getResponseTask,
server.AcceptConnectionSendCustomResponseAndCloseAsync(
"HTTP/1.1 200 OK\r\n" +
"Connection: close\r\n" +
LoopbackServer.CorsHeaders +
"Transfer-Encoding: chunked\r\n" +
"Trailer: MyCoolTrailerHeader\r\n" +
"\r\n" +
"4\r\n" +
"data\r\n" +
"0\r\n" +
"\r\n"));
using (HttpResponseMessage response = await getResponseTask)
{
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
Assert.Contains("chunked", response.Headers.GetValues("Transfer-Encoding"));
Assert.NotNull(response.TrailingHeaders);
Assert.Equal(0, response.TrailingHeaders.Count());
Assert.Same(response.TrailingHeaders, response.TrailingHeaders);
}
}
});
}
}
// TODO: make generic to support HTTP/2 and HTTP/3.
public sealed class SocketsHttpHandler_Http2_TrailingHeaders_Test : SocketsHttpHandler_TrailingHeaders_Test
{
public SocketsHttpHandler_Http2_TrailingHeaders_Test(ITestOutputHelper output) : base(output) { }