-
Notifications
You must be signed in to change notification settings - Fork 4
/
HttpConnection.cs
282 lines (239 loc) · 12.5 KB
/
HttpConnection.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
// The Sisk Framework source code
// Copyright (c) 2024- PROJECT PRINCIPIUM and all Sisk contributors
//
// The code below is licensed under the MIT license as
// of the date of its publication, available at
//
// File name: HttpConnection.cs
// Repository: https://github.com/sisk-http/core
using System.Net;
using System.Net.Security;
using System.Net.Sockets;
using Sisk.Core.Http;
using Sisk.Ssl.HttpSerializer;
namespace Sisk.Ssl;
internal class HttpConnection : IDisposable {
private static readonly Random clientIdRngGenerator = new Random ();
private int connectionCloseState = -1;
private bool disposedValue;
private readonly int clientId = clientIdRngGenerator.Next ();
private int iteration = 0;
private readonly DateTime createdAt = DateTime.Now;
// do not dispose parent on Dispose ()
public SslProxy Parent { get; }
public TcpClient Client { get; }
public DateTime CreatedAt { get => this.createdAt; }
public int ClientId { get => this.clientId; }
public int Iteration { get => this.iteration; }
public int CloseState { get => this.connectionCloseState; }
public HttpConnection ( SslProxy parent, TcpClient client ) {
this.Client = client;
this.Parent = parent;
}
public void HandleConnection () {
this.Client.NoDelay = true;
if (this.disposedValue)
return;
Logger.LogInformation ( $"#{this.clientId} open" );
try {
using (var tcpStream = this.Client.GetStream ())
using (var sslStream = new SslStream ( tcpStream, true ))
using (var gatewayClient = new TcpClient ()) {
try {
gatewayClient.Connect ( this.Parent.GatewayEndpoint );
gatewayClient.NoDelay = true;
gatewayClient.SendTimeout = (int) this.Parent.GatewayTimeout.TotalMilliseconds;
gatewayClient.ReceiveTimeout = (int) this.Parent.GatewayTimeout.TotalMilliseconds;
}
catch (Exception ex) {
this.connectionCloseState = 1;
Logger.LogInformation ( $"#{this.clientId}: Gateway connect exception: {ex.Message}" );
HttpResponseWriter.TryWriteHttp1DefaultResponse (
new HttpStatusInformation ( 502 ),
"The host service ins't working.",
sslStream );
return;
}
// used by header values
Span<byte> secHXl1 = stackalloc byte [ 4096 ];
// used by request path
Span<byte> secHXl2 = stackalloc byte [ 2048 ];
// used by header name
Span<byte> secHLg1 = stackalloc byte [ 512 ];
// used by response reason message
Span<byte> secHL21 = stackalloc byte [ 256 ];
// used by request method and response status code
Span<byte> secHSm1 = stackalloc byte [ 8 ];
// used by request and respones protocol
Span<byte> secHSm2 = stackalloc byte [ 8 ];
HttpRequestReaderSpan reqReaderMemory = new HttpRequestReaderSpan () {
MethodBuffer = secHSm1,
PathBuffer = secHXl2,
ProtocolBuffer = secHSm2,
PsHeaderName = secHLg1,
PsHeaderValue = secHXl1
};
HttpResponseReaderSpan resReaderMemory = new HttpResponseReaderSpan () {
ProtocolBuffer = secHSm2,
StatusCodeBuffer = secHSm1,
StatusReasonBuffer = secHL21,
PsHeaderName = secHLg1,
PsHeaderValue = secHXl1
};
using (var gatewayStream = gatewayClient.GetStream ()) {
try {
sslStream.AuthenticateAsServer (
serverCertificate: this.Parent.ServerCertificate,
clientCertificateRequired: this.Parent.ClientCertificateRequired,
enabledSslProtocols: this.Parent.AllowedProtocols,
checkCertificateRevocation: this.Parent.CheckCertificateRevocation );
}
catch (Exception ex) {
Logger.LogInformation ( $"#{this.clientId}: SslAuthentication failed: {ex.Message}" );
this.connectionCloseState = 2;
// write an error on the http stream
HttpResponseWriter.TryWriteHttp1DefaultResponse (
new HttpStatusInformation ( 400 ),
"The plain HTTP request was sent to an HTTPS port.",
sslStream );
return;
}
while (this.Client.Connected && !this.disposedValue) {
try {
if (!HttpRequestReader.TryReadHttp1Request (
this.clientId,
sslStream,
reqReaderMemory,
this.Parent.GatewayHostname,
out var method,
out var path,
out var proto,
out var forwardedFor,
out var reqContentLength,
out var headers,
out var expectContinue )) {
Logger.LogInformation ( $"#{this.clientId}: couldn't read request" );
this.connectionCloseState = 9;
HttpResponseWriter.TryWriteHttp1DefaultResponse (
new HttpStatusInformation ( 400 ),
"The server received an invalid HTTP message.",
sslStream );
return;
}
Logger.LogInformation ( $"#{this.clientId} >> {method} {path}" );
if (this.Parent.ProxyAuthorization is not null) {
headers.Add ( (HttpKnownHeaderNames.ProxyAuthorization, this.Parent.ProxyAuthorization.ToString ()) );
}
string clientIpAddress = ((IPEndPoint) this.Client.Client.LocalEndPoint!).Address.ToString ();
if (forwardedFor is not null) {
headers.Add ( (HttpKnownHeaderNames.XForwardedFor, forwardedFor + ", " + clientIpAddress) );
}
else {
headers.Add ( (HttpKnownHeaderNames.XForwardedFor, clientIpAddress) );
}
if (!HttpRequestWriter.TryWriteHttpV1Request ( this.clientId, gatewayStream, method, path, headers )) {
HttpResponseWriter.TryWriteHttp1DefaultResponse (
new HttpStatusInformation ( 502 ),
"The host service ins't working.",
sslStream );
this.connectionCloseState = 3;
return;
}
if (expectContinue) {
goto readGatewayResponse;
}
redirClientContent:
if (reqContentLength > 0) {
if (!SerializerUtils.CopyStream ( sslStream, gatewayStream, reqContentLength, CancellationToken.None )) {
// client couldn't send the full content
break;
}
}
readGatewayResponse:
if (!HttpResponseReader.TryReadHttp1Response (
this.clientId,
gatewayStream,
resReaderMemory,
out var resStatusCode,
out var resStatusDescr,
out var resHeaders,
out var resContentLength,
out var isChunked,
out var gatewayAllowsKeepAlive,
out var isWebSocket )) {
HttpResponseWriter.TryWriteHttp1DefaultResponse (
new HttpStatusInformation ( 502 ),
"The host service ins't working.",
sslStream );
this.connectionCloseState = 4;
return;
}
Logger.LogInformation ( $"#{this.clientId} << {resStatusCode} {resStatusDescr}" );
// TODO: check if client wants to keep alive
if (gatewayAllowsKeepAlive && this.Parent.KeepAliveEnabled) {
;
}
else {
resHeaders.Add ( ("Connection", "close") );
}
#if VERBOSE
if (!expectContinue)
resHeaders.Add ( ("X-Debug-Connection-Id", this.clientId.ToString ()) );
#endif
HttpResponseWriter.TryWriteHttp1Response ( this.clientId, sslStream, resStatusCode, resStatusDescr, resHeaders );
if (expectContinue && resStatusCode == "100") {
expectContinue = false;
goto redirClientContent;
}
if (isWebSocket) {
AutoResetEvent waitEvent = new AutoResetEvent ( false );
Logger.LogInformation ( $"#{this.clientId} << entering ws" );
SerializerUtils.CopyBlocking ( gatewayStream, sslStream, waitEvent );
SerializerUtils.CopyBlocking ( sslStream, gatewayStream, waitEvent );
waitEvent.WaitOne ();
}
else if (resContentLength > 0) {
Logger.LogInformation ( $"#{this.clientId} << {resContentLength} bytes written" );
SerializerUtils.CopyStream ( gatewayStream, sslStream, resContentLength, CancellationToken.None );
}
else if (isChunked) {
AutoResetEvent waitEvent = new AutoResetEvent ( false );
Logger.LogInformation ( $"#{this.clientId} << entering chunked data" );
SerializerUtils.CopyUntilBlocking ( gatewayStream, sslStream, Constants.CHUNKED_EOF, waitEvent );
waitEvent.WaitOne ();
}
tcpStream.Flush ();
if (!gatewayAllowsKeepAlive || !this.Parent.KeepAliveEnabled) {
this.connectionCloseState = 5;
break;
}
}
catch {
this.connectionCloseState = 6;
return;
}
finally {
this.iteration++;
}
}
}
}
}
finally {
Logger.LogInformation ( $"#{this.clientId} closed. State = {this.connectionCloseState}" );
}
}
protected virtual void Dispose ( bool disposing ) {
if (!this.disposedValue) {
if (disposing) {
this.Client.Close ();
}
this.disposedValue = true;
}
}
public void Dispose () {
// Não altere este código. Coloque o código de limpeza no método 'Dispose(bool disposing)'
this.Dispose ( disposing: true );
GC.SuppressFinalize ( this );
}
}