-
Notifications
You must be signed in to change notification settings - Fork 5.4k
Expand file tree
/
Copy pathQuicTestBase.cs
More file actions
334 lines (285 loc) · 13.4 KB
/
QuicTestBase.cs
File metadata and controls
334 lines (285 loc) · 13.4 KB
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
// 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.Net.Quic.Implementations;
using System.Net.Security;
using System.Security.Cryptography.X509Certificates;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using Xunit;
using Xunit.Abstractions;
using System.Diagnostics.Tracing;
using System.Net.Sockets;
namespace System.Net.Quic.Tests
{
public abstract class QuicTestBase<T>
where T : IQuicImplProviderFactory, new()
{
private static readonly byte[] s_ping = Encoding.UTF8.GetBytes("PING");
private static readonly byte[] s_pong = Encoding.UTF8.GetBytes("PONG");
private static readonly IQuicImplProviderFactory s_factory = new T();
public static QuicImplementationProvider ImplementationProvider { get; } = s_factory.GetProvider();
public static bool IsSupported => ImplementationProvider.IsSupported;
public static bool IsMockProvider => typeof(T) == typeof(MockProviderFactory);
public static bool IsMsQuicProvider => typeof(T) == typeof(MsQuicProviderFactory);
public static SslApplicationProtocol ApplicationProtocol { get; } = new SslApplicationProtocol("quictest");
public X509Certificate2 ServerCertificate = System.Net.Test.Common.Configuration.Certificates.GetServerCertificate();
public X509Certificate2 ClientCertificate = System.Net.Test.Common.Configuration.Certificates.GetClientCertificate();
public ITestOutputHelper _output;
public const int PassingTestTimeoutMilliseconds = 4 * 60 * 1000;
public static TimeSpan PassingTestTimeout => TimeSpan.FromMilliseconds(PassingTestTimeoutMilliseconds);
public QuicTestBase(ITestOutputHelper output)
{
_output = output;
}
public bool RemoteCertificateValidationCallback(object sender, X509Certificate? certificate, X509Chain? chain, SslPolicyErrors sslPolicyErrors)
{
Assert.Equal(ServerCertificate.GetCertHash(), certificate?.GetCertHash());
return true;
}
public SslServerAuthenticationOptions GetSslServerAuthenticationOptions()
{
return new SslServerAuthenticationOptions()
{
ApplicationProtocols = new List<SslApplicationProtocol>() { ApplicationProtocol },
ServerCertificate = ServerCertificate
};
}
public SslClientAuthenticationOptions GetSslClientAuthenticationOptions()
{
return new SslClientAuthenticationOptions()
{
ApplicationProtocols = new List<SslApplicationProtocol>() { ApplicationProtocol },
RemoteCertificateValidationCallback = RemoteCertificateValidationCallback,
TargetHost = "localhost"
};
}
public QuicClientConnectionOptions CreateQuicClientOptions()
{
return new QuicClientConnectionOptions()
{
ClientAuthenticationOptions = GetSslClientAuthenticationOptions()
};
}
internal QuicConnection CreateQuicConnection(IPEndPoint endpoint)
{
return new QuicConnection(ImplementationProvider, endpoint, GetSslClientAuthenticationOptions());
}
internal QuicConnection CreateQuicConnection(QuicClientConnectionOptions clientOptions)
{
return new QuicConnection(ImplementationProvider, clientOptions);
}
internal QuicListenerOptions CreateQuicListenerOptions()
{
return new QuicListenerOptions()
{
ListenEndPoint = new IPEndPoint(IPAddress.Loopback, 0),
ServerAuthenticationOptions = GetSslServerAuthenticationOptions()
};
}
internal QuicListener CreateQuicListener(int maxUnidirectionalStreams = 100, int maxBidirectionalStreams = 100)
{
var options = CreateQuicListenerOptions();
options.MaxUnidirectionalStreams = maxUnidirectionalStreams;
options.MaxBidirectionalStreams = maxBidirectionalStreams;
return CreateQuicListener(options);
}
internal QuicListener CreateQuicListener(IPEndPoint endpoint)
{
var options = new QuicListenerOptions()
{
ListenEndPoint = endpoint,
ServerAuthenticationOptions = GetSslServerAuthenticationOptions()
};
return CreateQuicListener(options);
}
private QuicListener CreateQuicListener(QuicListenerOptions options) => new QuicListener(ImplementationProvider, options);
internal Task<(QuicConnection, QuicConnection)> CreateConnectedQuicConnection(QuicListener listener) => CreateConnectedQuicConnection(null, listener);
internal async Task<(QuicConnection, QuicConnection)> CreateConnectedQuicConnection(QuicClientConnectionOptions? clientOptions, QuicListenerOptions listenerOptions)
{
using (QuicListener listener = CreateQuicListener(listenerOptions))
{
clientOptions ??= new QuicClientConnectionOptions()
{
ClientAuthenticationOptions = GetSslClientAuthenticationOptions()
};
clientOptions.RemoteEndPoint = listener.ListenEndPoint;
return await CreateConnectedQuicConnection(clientOptions, listener);
}
}
internal async Task<(QuicConnection, QuicConnection)> CreateConnectedQuicConnection(QuicClientConnectionOptions? clientOptions = null, QuicListener? listener = null)
{
int retry = 3;
int delay = 25;
bool disposeListener = false;
if (listener == null)
{
listener = CreateQuicListener();
disposeListener = true;
}
clientOptions ??= CreateQuicClientOptions();
if (clientOptions.RemoteEndPoint == null)
{
clientOptions.RemoteEndPoint = listener.ListenEndPoint;
}
QuicConnection clientConnection = null;
ValueTask<QuicConnection> serverTask = listener.AcceptConnectionAsync();
while (retry > 0)
{
clientConnection = CreateQuicConnection(clientOptions);
retry--;
try
{
await clientConnection.ConnectAsync().ConfigureAwait(false);
break;
}
catch (QuicException ex) when (ex.HResult == (int)SocketError.ConnectionRefused)
{
_output.WriteLine($"ConnectAsync to {clientConnection.RemoteEndPoint} failed with {ex.Message}");
await Task.Delay(delay);
delay *= 2;
if (retry == 0)
{
Debug.Fail($"ConnectAsync to {clientConnection.RemoteEndPoint} failed with {ex.Message}");
throw ex;
}
}
}
QuicConnection serverConnection = await serverTask.ConfigureAwait(false);
if (disposeListener)
{
listener.Dispose();
}
Assert.True(serverConnection.Connected);
Assert.True(clientConnection.Connected);
return (clientConnection, serverTask.Result);
}
internal async Task PingPong(QuicConnection client, QuicConnection server)
{
using QuicStream clientStream = client.OpenBidirectionalStream();
ValueTask t = clientStream.WriteAsync(s_ping);
using QuicStream serverStream = await server.AcceptStreamAsync();
byte[] buffer = new byte[s_ping.Length];
int remains = s_ping.Length;
while (remains > 0)
{
int readLength = await serverStream.ReadAsync(buffer, buffer.Length - remains, remains);
Assert.True(readLength > 0);
remains -= readLength;
}
Assert.Equal(s_ping, buffer);
await t;
t = serverStream.WriteAsync(s_pong);
remains = s_pong.Length;
while (remains > 0)
{
int readLength = await clientStream.ReadAsync(buffer, buffer.Length - remains, remains);
Assert.True(readLength > 0);
remains -= readLength;
}
Assert.Equal(s_pong, buffer);
await t;
}
internal async Task RunClientServer(Func<QuicConnection, Task> clientFunction, Func<QuicConnection, Task> serverFunction, int iterations = 1, int millisecondsTimeout = PassingTestTimeoutMilliseconds, QuicListenerOptions listenerOptions = null)
{
const long ClientCloseErrorCode = 11111;
const long ServerCloseErrorCode = 22222;
using QuicListener listener = CreateQuicListener(listenerOptions ?? CreateQuicListenerOptions());
using var serverFinished = new SemaphoreSlim(0);
using var clientFinished = new SemaphoreSlim(0);
for (int i = 0; i < iterations; ++i)
{
(QuicConnection clientConnection, QuicConnection serverConnection) = await CreateConnectedQuicConnection(listener);
using (clientConnection)
using (serverConnection)
{
await new[]
{
Task.Run(async () =>
{
await serverFunction(serverConnection);
serverFinished.Release();
await clientFinished.WaitAsync();
}),
Task.Run(async () =>
{
await clientFunction(clientConnection);
clientFinished.Release();
await serverFinished.WaitAsync();
})
}.WhenAllOrAnyFailed(millisecondsTimeout);
await serverConnection.CloseAsync(ServerCloseErrorCode);
await clientConnection.CloseAsync(ClientCloseErrorCode);
}
}
}
internal async Task RunStreamClientServer(Func<QuicStream, Task> clientFunction, Func<QuicStream, Task> serverFunction, bool bidi, int iterations, int millisecondsTimeout)
{
byte[] buffer = new byte[1] { 42 };
await RunClientServer(
clientFunction: async connection =>
{
await using QuicStream stream = bidi ? connection.OpenBidirectionalStream() : connection.OpenUnidirectionalStream();
// Open(Bi|Uni)directionalStream only allocates ID. We will force stream opening
// by Writing there and receiving data on the other side.
await stream.WriteAsync(buffer);
await clientFunction(stream);
stream.Shutdown();
await stream.ShutdownCompleted();
},
serverFunction: async connection =>
{
await using QuicStream stream = await connection.AcceptStreamAsync();
Assert.Equal(1, await stream.ReadAsync(buffer));
await serverFunction(stream);
stream.Shutdown();
await stream.ShutdownCompleted();
},
iterations,
millisecondsTimeout
);
}
internal Task RunBidirectionalClientServer(Func<QuicStream, Task> clientFunction, Func<QuicStream, Task> serverFunction, int iterations = 1, int millisecondsTimeout = PassingTestTimeoutMilliseconds)
=> RunStreamClientServer(clientFunction, serverFunction, bidi: true, iterations, millisecondsTimeout);
internal Task RunUnirectionalClientServer(Func<QuicStream, Task> clientFunction, Func<QuicStream, Task> serverFunction, int iterations = 1, int millisecondsTimeout = PassingTestTimeoutMilliseconds)
=> RunStreamClientServer(clientFunction, serverFunction, bidi: false, iterations, millisecondsTimeout);
internal static async Task<int> ReadAll(QuicStream stream, byte[] buffer)
{
Memory<byte> memory = buffer;
int bytesRead = 0;
while (true)
{
int res = await stream.ReadAsync(memory);
if (res == 0)
{
break;
}
bytesRead += res;
memory = memory[res..];
}
return bytesRead;
}
internal static async Task<int> WriteForever(QuicStream stream)
{
Memory<byte> buffer = new byte[] { 123 };
while (true)
{
await stream.WriteAsync(buffer);
}
}
}
public interface IQuicImplProviderFactory
{
QuicImplementationProvider GetProvider();
}
public sealed class MsQuicProviderFactory : IQuicImplProviderFactory
{
public QuicImplementationProvider GetProvider() => QuicImplementationProviders.MsQuic;
}
public sealed class MockProviderFactory : IQuicImplProviderFactory
{
public QuicImplementationProvider GetProvider() => QuicImplementationProviders.Mock;
}
}