-
Notifications
You must be signed in to change notification settings - Fork 4.9k
/
Copy pathHttp2LoopbackServer.cs
272 lines (220 loc) · 10.2 KB
/
Http2LoopbackServer.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
// 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.IO;
using System.Net.Security;
using System.Net.Sockets;
using System.Security.Authentication;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using Xunit;
namespace System.Net.Test.Common
{
public class Http2LoopbackServer : GenericLoopbackServer, IDisposable
{
private Socket _listenSocket;
private Http2Options _options;
private Uri _uri;
private List<Http2LoopbackConnection> _connections = new List<Http2LoopbackConnection>();
public bool AllowMultipleConnections { get; set; }
private Http2LoopbackConnection Connection
{
get
{
RemoveInvalidConnections();
return _connections[0];
}
}
public static readonly TimeSpan Timeout = TimeSpan.FromSeconds(30);
public override Uri Address
{
get
{
var localEndPoint = (IPEndPoint)_listenSocket.LocalEndPoint;
string host = _options.Address.AddressFamily == AddressFamily.InterNetworkV6 ?
$"[{localEndPoint.Address}]" :
localEndPoint.Address.ToString();
string scheme = _options.UseSsl ? "https" : "http";
_uri = new Uri($"{scheme}://{host}:{localEndPoint.Port}/");
return _uri;
}
}
public static Http2LoopbackServer CreateServer()
{
return new Http2LoopbackServer(new Http2Options());
}
public static Http2LoopbackServer CreateServer(Http2Options options)
{
return new Http2LoopbackServer(options);
}
private Http2LoopbackServer(Http2Options options)
{
_options = options;
_listenSocket = new Socket(_options.Address.AddressFamily, SocketType.Stream, ProtocolType.Tcp);
_listenSocket.Bind(new IPEndPoint(_options.Address, 0));
_listenSocket.Listen(_options.ListenBacklog);
}
private void RemoveInvalidConnections()
{
_connections.RemoveAll((c) => c.IsInvalid);
}
public async Task<Http2LoopbackConnection> AcceptConnectionAsync()
{
RemoveInvalidConnections();
if (!AllowMultipleConnections && _connections.Count != 0)
{
throw new InvalidOperationException("Connection already established. Set `AllowMultipleConnections = true` to bypass.");
}
Socket connectionSocket = await _listenSocket.AcceptAsync().ConfigureAwait(false);
Http2LoopbackConnection connection = new Http2LoopbackConnection(connectionSocket, _options);
_connections.Add(connection);
return connection;
}
public override async Task<GenericLoopbackConnection> EstablishGenericConnectionAsync()
{
return await EstablishConnectionAsync();
}
public async Task<Http2LoopbackConnection> EstablishConnectionAsync(params SettingsEntry[] settingsEntries)
{
(Http2LoopbackConnection connection, _) = await EstablishConnectionGetSettingsAsync(settingsEntries).ConfigureAwait(false);
return connection;
}
public async Task<(Http2LoopbackConnection, SettingsFrame)> EstablishConnectionGetSettingsAsync(params SettingsEntry[] settingsEntries)
{
Http2LoopbackConnection connection = await AcceptConnectionAsync().ConfigureAwait(false);
// Receive the initial client settings frame.
Frame receivedFrame = await connection.ReadFrameAsync(Timeout).ConfigureAwait(false);
Assert.Equal(FrameType.Settings, receivedFrame.Type);
Assert.Equal(FrameFlags.None, receivedFrame.Flags);
Assert.Equal(0, receivedFrame.StreamId);
var clientSettingsFrame = (SettingsFrame)receivedFrame;
// Receive the initial client window update frame.
receivedFrame = await connection.ReadFrameAsync(Timeout).ConfigureAwait(false);
Assert.Equal(FrameType.WindowUpdate, receivedFrame.Type);
Assert.Equal(FrameFlags.None, receivedFrame.Flags);
Assert.Equal(0, receivedFrame.StreamId);
// Send the initial server settings frame.
SettingsFrame settingsFrame = new SettingsFrame(settingsEntries);
await connection.WriteFrameAsync(settingsFrame).ConfigureAwait(false);
// Send the client settings frame ACK.
Frame settingsAck = new Frame(0, FrameType.Settings, FrameFlags.Ack, 0);
await connection.WriteFrameAsync(settingsAck).ConfigureAwait(false);
// The client will send us a SETTINGS ACK eventually, but not necessarily right away.
await connection.ExpectSettingsAckAsync();
return (connection, clientSettingsFrame);
}
public override void Dispose()
{
if (_listenSocket != null)
{
_listenSocket.Dispose();
_listenSocket = null;
}
}
//
// GenericLoopbackServer implementation
//
public override async Task<HttpRequestData> HandleRequestAsync(HttpStatusCode statusCode = HttpStatusCode.OK, IList<HttpHeaderData> headers = null, string content = "")
{
Http2LoopbackConnection connection = await EstablishConnectionAsync().ConfigureAwait(false);
(int streamId, HttpRequestData requestData) = await connection.ReadAndParseRequestHeaderAsync().ConfigureAwait(false);
// We are about to close the connection, after we send the response.
// So, send a GOAWAY frame now so the client won't inadvertantly try to reuse the connection.
await connection.SendGoAway(streamId).ConfigureAwait(false);
if (string.IsNullOrEmpty(content))
{
await connection.SendResponseHeadersAsync(streamId, endStream: true, statusCode, isTrailingHeader: false, headers : headers).ConfigureAwait(false);
}
else
{
await connection.SendResponseHeadersAsync(streamId, endStream: false, statusCode, isTrailingHeader: false, headers : headers).ConfigureAwait(false);
await connection.SendResponseBodyAsync(streamId, Encoding.ASCII.GetBytes(content)).ConfigureAwait(false);
}
await connection.WaitForConnectionShutdownAsync().ConfigureAwait(false);
return requestData;
}
public override async Task AcceptConnectionAsync(Func<GenericLoopbackConnection, Task> funcAsync)
{
using (Http2LoopbackConnection connection = await EstablishConnectionAsync().ConfigureAwait(false))
{
await funcAsync(connection).ConfigureAwait(false);
}
}
public static Task CreateClientAndServerAsync(Func<Uri, Task> clientFunc, Func<Http2LoopbackServer, Task> serverFunc, int timeout = 60_000)
{
return CreateClientAndServerAsync(clientFunc, serverFunc, null, timeout);
}
public static async Task CreateClientAndServerAsync(Func<Uri, Task> clientFunc, Func<Http2LoopbackServer, Task> serverFunc, Http2Options http2Options, int timeout = 60_000)
{
using (var server = Http2LoopbackServer.CreateServer(http2Options ?? new Http2Options()))
{
Task clientTask = clientFunc(server.Address);
Task serverTask = serverFunc(server);
await new Task[] { clientTask, serverTask }.WhenAllOrAnyFailed(timeout).ConfigureAwait(false);
}
}
}
public class Http2Options : GenericLoopbackOptions
{
public int ListenBacklog { get; set; } = 1;
public bool ClientCertificateRequired { get; set; }
public Http2Options()
{
UseSsl = PlatformDetection.SupportsAlpn && !Capability.Http2ForceUnencryptedLoopback();
SslProtocols = SslProtocols.Tls12;
}
}
public sealed class Http2LoopbackServerFactory : LoopbackServerFactory
{
public static readonly Http2LoopbackServerFactory Singleton = new Http2LoopbackServerFactory();
public static async Task CreateServerAsync(Func<Http2LoopbackServer, Uri, Task> funcAsync, int millisecondsTimeout = 60_000)
{
using (var server = Http2LoopbackServer.CreateServer())
{
await funcAsync(server, server.Address).TimeoutAfter(millisecondsTimeout).ConfigureAwait(false);
}
}
public override GenericLoopbackServer CreateServer(GenericLoopbackOptions options = null)
{
Http2Options http2Options = new Http2Options();
if (options != null)
{
http2Options.Address = options.Address;
http2Options.UseSsl = options.UseSsl;
http2Options.SslProtocols = options.SslProtocols;
}
return Http2LoopbackServer.CreateServer(http2Options);
}
public override async Task CreateServerAsync(Func<GenericLoopbackServer, Uri, Task> funcAsync, int millisecondsTimeout = 60_000, GenericLoopbackOptions options = null)
{
using (var server = CreateServer(options))
{
await funcAsync(server, server.Address).TimeoutAfter(millisecondsTimeout).ConfigureAwait(false);
}
}
public override Version Version => HttpVersion20.Value;
}
public enum ProtocolErrors
{
NO_ERROR = 0x0,
PROTOCOL_ERROR = 0x1,
INTERNAL_ERROR = 0x2,
FLOW_CONTROL_ERROR = 0x3,
SETTINGS_TIMEOUT = 0x4,
STREAM_CLOSED = 0x5,
FRAME_SIZE_ERROR = 0x6,
REFUSED_STREAM = 0x7,
CANCEL = 0x8,
COMPRESSION_ERROR = 0x9,
CONNECT_ERROR = 0xa,
ENHANCE_YOUR_CALM = 0xb,
INADEQUATE_SECURITY = 0xc,
HTTP_1_1_REQUIRED = 0xd
}
public static class HttpVersion20
{
public static readonly Version Value = new Version(2, 0);
}
}