-
Notifications
You must be signed in to change notification settings - Fork 180
/
AsyncTcpSocketSession.cs
529 lines (457 loc) · 19.6 KB
/
AsyncTcpSocketSession.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
using System;
using System.IO;
using System.Net;
using System.Net.Security;
using System.Net.Sockets;
using System.Security.Cryptography.X509Certificates;
using System.Threading;
using System.Threading.Tasks;
using Cowboy.Buffer;
using Logrila.Logging;
namespace Cowboy.Sockets
{
public sealed class AsyncTcpSocketSession
{
#region Fields
private static readonly ILog _log = Logger.Get<AsyncTcpSocketSession>();
private TcpClient _tcpClient;
private readonly AsyncTcpSocketServerConfiguration _configuration;
private readonly ISegmentBufferManager _bufferManager;
private readonly IAsyncTcpSocketServerEventDispatcher _dispatcher;
private readonly AsyncTcpSocketServer _server;
private readonly string _sessionKey;
private Stream _stream;
private ArraySegment<byte> _receiveBuffer = default(ArraySegment<byte>);
private int _receiveBufferOffset = 0;
private IPEndPoint _remoteEndPoint;
private IPEndPoint _localEndPoint;
private int _state;
private const int _none = 0;
private const int _connecting = 1;
private const int _connected = 2;
private const int _disposed = 5;
#endregion
#region Constructors
public AsyncTcpSocketSession(
TcpClient tcpClient,
AsyncTcpSocketServerConfiguration configuration,
ISegmentBufferManager bufferManager,
IAsyncTcpSocketServerEventDispatcher dispatcher,
AsyncTcpSocketServer server)
{
if (tcpClient == null)
throw new ArgumentNullException("tcpClient");
if (configuration == null)
throw new ArgumentNullException("configuration");
if (bufferManager == null)
throw new ArgumentNullException("bufferManager");
if (dispatcher == null)
throw new ArgumentNullException("dispatcher");
if (server == null)
throw new ArgumentNullException("server");
_tcpClient = tcpClient;
_configuration = configuration;
_bufferManager = bufferManager;
_dispatcher = dispatcher;
_server = server;
_sessionKey = Guid.NewGuid().ToString();
this.StartTime = DateTime.UtcNow;
SetSocketOptions();
_remoteEndPoint = this.RemoteEndPoint;
_localEndPoint = this.LocalEndPoint;
}
#endregion
#region Properties
public string SessionKey { get { return _sessionKey; } }
public DateTime StartTime { get; private set; }
public TimeSpan ConnectTimeout { get { return _configuration.ConnectTimeout; } }
private bool Connected { get { return _tcpClient != null && _tcpClient.Client.Connected; } }
public IPEndPoint RemoteEndPoint { get { return Connected ? (IPEndPoint)_tcpClient.Client.RemoteEndPoint : _remoteEndPoint; } }
public IPEndPoint LocalEndPoint { get { return Connected ? (IPEndPoint)_tcpClient.Client.LocalEndPoint : _localEndPoint; } }
public Socket Socket { get { return Connected ? _tcpClient.Client : null; } }
public Stream Stream { get { return _stream; } }
public AsyncTcpSocketServer Server { get { return _server; } }
public TcpSocketConnectionState State
{
get
{
switch (_state)
{
case _none:
return TcpSocketConnectionState.None;
case _connecting:
return TcpSocketConnectionState.Connecting;
case _connected:
return TcpSocketConnectionState.Connected;
case _disposed:
return TcpSocketConnectionState.Closed;
default:
return TcpSocketConnectionState.Closed;
}
}
}
public override string ToString()
{
return string.Format("SessionKey[{0}], RemoteEndPoint[{1}], LocalEndPoint[{2}]",
this.SessionKey, this.RemoteEndPoint, this.LocalEndPoint);
}
#endregion
#region Process
internal async Task Start()
{
int origin = Interlocked.CompareExchange(ref _state, _connecting, _none);
if (origin == _disposed)
{
throw new ObjectDisposedException("This tcp socket session has been disposed when connecting.");
}
else if (origin != _none)
{
throw new InvalidOperationException("This tcp socket session is in invalid state when connecting.");
}
try
{
var negotiator = NegotiateStream(_tcpClient.GetStream());
if (!negotiator.Wait(ConnectTimeout))
{
await Close(false); // ssl negotiation timeout
throw new TimeoutException(string.Format(
"Negotiate SSL/TSL with remote [{0}] timeout [{1}].", this.RemoteEndPoint, ConnectTimeout));
}
_stream = negotiator.Result;
if (_receiveBuffer == default(ArraySegment<byte>))
_receiveBuffer = _bufferManager.BorrowBuffer();
_receiveBufferOffset = 0;
if (Interlocked.CompareExchange(ref _state, _connected, _connecting) != _connecting)
{
await Close(false); // connected with wrong state
throw new ObjectDisposedException("This tcp socket session has been disposed after connected.");
}
_log.DebugFormat("Session started for [{0}] on [{1}] in dispatcher [{2}] with session count [{3}].",
this.RemoteEndPoint,
this.StartTime.ToString(@"yyyy-MM-dd HH:mm:ss.fffffff"),
_dispatcher.GetType().Name,
this.Server.SessionCount);
bool isErrorOccurredInUserSide = false;
try
{
await _dispatcher.OnSessionStarted(this);
}
catch (Exception ex) // catch all exceptions from out-side
{
isErrorOccurredInUserSide = true;
await HandleUserSideError(ex);
}
if (!isErrorOccurredInUserSide)
{
await Process();
}
else
{
await Close(true); // user side handle tcp connection error occurred
}
}
catch (Exception ex) // catch exceptions then log then re-throw
{
_log.Error(string.Format("Session [{0}] exception occurred, [{1}].", this, ex.Message), ex);
await Close(true); // handle tcp connection error occurred
throw;
}
}
private async Task Process()
{
try
{
int frameLength;
byte[] payload;
int payloadOffset;
int payloadCount;
int consumedLength = 0;
while (State == TcpSocketConnectionState.Connected)
{
int receiveCount = await _stream.ReadAsync(
_receiveBuffer.Array,
_receiveBuffer.Offset + _receiveBufferOffset,
_receiveBuffer.Count - _receiveBufferOffset);
if (receiveCount == 0)
break;
SegmentBufferDeflector.ReplaceBuffer(_bufferManager, ref _receiveBuffer, ref _receiveBufferOffset, receiveCount);
consumedLength = 0;
while (true)
{
frameLength = 0;
payload = null;
payloadOffset = 0;
payloadCount = 0;
if (_configuration.FrameBuilder.Decoder.TryDecodeFrame(
_receiveBuffer.Array,
_receiveBuffer.Offset + consumedLength,
_receiveBufferOffset - consumedLength,
out frameLength, out payload, out payloadOffset, out payloadCount))
{
try
{
await _dispatcher.OnSessionDataReceived(this, payload, payloadOffset, payloadCount);
}
catch (Exception ex) // catch all exceptions from out-side
{
await HandleUserSideError(ex);
}
finally
{
consumedLength += frameLength;
}
}
else
{
break;
}
}
if (_receiveBuffer != null && _receiveBuffer.Array != null)
{
SegmentBufferDeflector.ShiftBuffer(_bufferManager, consumedLength, ref _receiveBuffer, ref _receiveBufferOffset);
}
}
}
catch (ObjectDisposedException)
{
// looking forward to a graceful quit from the ReadAsync but the inside EndRead will raise the ObjectDisposedException,
// so a gracefully close for the socket should be a Shutdown, but we cannot avoid the Close triggers this happen.
}
catch (Exception ex)
{
await HandleReceiveOperationException(ex);
}
finally
{
await Close(true); // read async buffer returned, remote notifies closed
}
}
private void SetSocketOptions()
{
_tcpClient.ReceiveBufferSize = _configuration.ReceiveBufferSize;
_tcpClient.SendBufferSize = _configuration.SendBufferSize;
_tcpClient.ReceiveTimeout = (int)_configuration.ReceiveTimeout.TotalMilliseconds;
_tcpClient.SendTimeout = (int)_configuration.SendTimeout.TotalMilliseconds;
_tcpClient.NoDelay = _configuration.NoDelay;
_tcpClient.LingerState = _configuration.LingerState;
if (_configuration.KeepAlive)
{
_tcpClient.Client.SetSocketOption(
SocketOptionLevel.Socket,
SocketOptionName.KeepAlive,
(int)_configuration.KeepAliveInterval.TotalMilliseconds);
}
_tcpClient.Client.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ReuseAddress, _configuration.ReuseAddress);
}
private async Task<Stream> NegotiateStream(Stream stream)
{
if (!_configuration.SslEnabled)
return stream;
var validateRemoteCertificate = new RemoteCertificateValidationCallback(
(object sender,
X509Certificate certificate,
X509Chain chain,
SslPolicyErrors sslPolicyErrors)
=>
{
if (sslPolicyErrors == SslPolicyErrors.None)
return true;
if (_configuration.SslPolicyErrorsBypassed)
return true;
else
_log.ErrorFormat("Session [{0}] error occurred when validating remote certificate: [{1}], [{2}].",
this, this.RemoteEndPoint, sslPolicyErrors);
return false;
});
var sslStream = new SslStream(
stream,
false,
validateRemoteCertificate,
null,
_configuration.SslEncryptionPolicy);
if (!_configuration.SslClientCertificateRequired)
{
await sslStream.AuthenticateAsServerAsync(
_configuration.SslServerCertificate); // The X509Certificate used to authenticate the server.
}
else
{
await sslStream.AuthenticateAsServerAsync(
_configuration.SslServerCertificate, // The X509Certificate used to authenticate the server.
_configuration.SslClientCertificateRequired, // A Boolean value that specifies whether the client must supply a certificate for authentication.
_configuration.SslEnabledProtocols, // The SslProtocols value that represents the protocol used for authentication.
_configuration.SslCheckCertificateRevocation); // A Boolean value that specifies whether the certificate revocation list is checked during authentication.
}
// When authentication succeeds, you must check the IsEncrypted and IsSigned properties
// to determine what security services are used by the SslStream.
// Check the IsMutuallyAuthenticated property to determine whether mutual authentication occurred.
_log.DebugFormat(
"Ssl Stream: SslProtocol[{0}], IsServer[{1}], IsAuthenticated[{2}], IsEncrypted[{3}], IsSigned[{4}], IsMutuallyAuthenticated[{5}], "
+ "HashAlgorithm[{6}], HashStrength[{7}], KeyExchangeAlgorithm[{8}], KeyExchangeStrength[{9}], CipherAlgorithm[{10}], CipherStrength[{11}].",
sslStream.SslProtocol,
sslStream.IsServer,
sslStream.IsAuthenticated,
sslStream.IsEncrypted,
sslStream.IsSigned,
sslStream.IsMutuallyAuthenticated,
sslStream.HashAlgorithm,
sslStream.HashStrength,
sslStream.KeyExchangeAlgorithm,
sslStream.KeyExchangeStrength,
sslStream.CipherAlgorithm,
sslStream.CipherStrength);
return sslStream;
}
#endregion
#region Close
public async Task Close()
{
await Close(true); // close by external
}
private async Task Close(bool shallNotifyUserSide)
{
if (Interlocked.Exchange(ref _state, _disposed) == _disposed)
{
return;
}
Shutdown();
if (shallNotifyUserSide)
{
_log.DebugFormat("Session closed for [{0}] on [{1}] in dispatcher [{2}] with session count [{3}].",
this.RemoteEndPoint,
DateTime.UtcNow.ToString(@"yyyy-MM-dd HH:mm:ss.fffffff"),
_dispatcher.GetType().Name,
this.Server.SessionCount - 1);
try
{
await _dispatcher.OnSessionClosed(this);
}
catch (Exception ex) // catch all exceptions from out-side
{
await HandleUserSideError(ex);
}
}
Clean();
}
public void Shutdown()
{
// The correct way to shut down the connection (especially if you are in a full-duplex conversation)
// is to call socket.Shutdown(SocketShutdown.Send) and give the remote party some time to close
// their send channel. This ensures that you receive any pending data instead of slamming the
// connection shut. ObjectDisposedException should never be part of the normal application flow.
if (_tcpClient != null && _tcpClient.Connected)
{
_tcpClient.Client.Shutdown(SocketShutdown.Send);
}
}
private void Clean()
{
try
{
try
{
if (_stream != null)
{
_stream.Dispose();
}
}
catch { }
try
{
if (_tcpClient != null)
{
_tcpClient.Close();
}
}
catch { }
}
catch { }
finally
{
_stream = null;
_tcpClient = null;
}
if (_receiveBuffer != default(ArraySegment<byte>))
_configuration.BufferManager.ReturnBuffer(_receiveBuffer);
_receiveBuffer = default(ArraySegment<byte>);
_receiveBufferOffset = 0;
}
#endregion
#region Exception Handler
private async Task HandleSendOperationException(Exception ex)
{
if (IsSocketTimeOut(ex))
{
await CloseIfShould(ex);
throw new TcpSocketException(ex.Message, new TimeoutException(ex.Message, ex));
}
await CloseIfShould(ex);
throw new TcpSocketException(ex.Message, ex);
}
private async Task HandleReceiveOperationException(Exception ex)
{
if (IsSocketTimeOut(ex))
{
await CloseIfShould(ex);
throw new TcpSocketException(ex.Message, new TimeoutException(ex.Message, ex));
}
await CloseIfShould(ex);
throw new TcpSocketException(ex.Message, ex);
}
private bool IsSocketTimeOut(Exception ex)
{
return ex is IOException
&& ex.InnerException != null
&& ex.InnerException is SocketException
&& (ex.InnerException as SocketException).SocketErrorCode == SocketError.TimedOut;
}
private async Task<bool> CloseIfShould(Exception ex)
{
if (ex is ObjectDisposedException
|| ex is InvalidOperationException
|| ex is SocketException
|| ex is IOException
|| ex is NullReferenceException // buffer array operation
|| ex is ArgumentException // buffer array operation
)
{
_log.Error(ex.Message, ex);
await Close(true); // catch specified exception then intend to close the session
return true;
}
return false;
}
private async Task HandleUserSideError(Exception ex)
{
_log.Error(string.Format("Session [{0}] error occurred in user side [{1}].", this, ex.Message), ex);
await Task.CompletedTask;
}
#endregion
#region Send
public async Task SendAsync(byte[] data)
{
await SendAsync(data, 0, data.Length);
}
public async Task SendAsync(byte[] data, int offset, int count)
{
BufferValidator.ValidateBuffer(data, offset, count, "data");
if (State != TcpSocketConnectionState.Connected)
{
throw new InvalidOperationException("This session has not connected.");
}
try
{
byte[] frameBuffer;
int frameBufferOffset;
int frameBufferLength;
_configuration.FrameBuilder.Encoder.EncodeFrame(data, offset, count, out frameBuffer, out frameBufferOffset, out frameBufferLength);
await _stream.WriteAsync(frameBuffer, frameBufferOffset, frameBufferLength);
}
catch (Exception ex)
{
await HandleSendOperationException(ex);
}
}
#endregion
}
}