generated from gemstone/gemtem
/
TcpClient.cs
1550 lines (1331 loc) · 62.7 KB
/
TcpClient.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
//******************************************************************************************************
// TcpClient.cs - Gbtc
//
// Copyright © 2012, Grid Protection Alliance. All Rights Reserved.
//
// Licensed to the Grid Protection Alliance (GPA) under one or more contributor license agreements. See
// the NOTICE file distributed with this work for additional information regarding copyright ownership.
// The GPA licenses this file to you under the MIT License (MIT), the "License"; you may
// not use this file except in compliance with the License. You may obtain a copy of the License at:
//
// http://www.opensource.org/licenses/MIT
//
// Unless agreed to in writing, the subject software distributed under the License is distributed on an
// "AS-IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. Refer to the
// License for the specific language governing permissions and limitations.
//
// Code Modification History:
// ----------------------------------------------------------------------------------------------------
// 06/02/2006 - Pinal C. Patel
// Original version of source code generated.
// 09/06/2006 - J. Ritchie Carroll
// Added bypass optimizations for high-speed socket access.
// 12/01/2006 - Pinal C. Patel
// Modified code for handling "PayloadAware" transmissions.
// 09/27/2007 - J. Ritchie Carroll
// Added disconnect timeout overload.
// 09/29/2008 - J. Ritchie Carroll
// Converted to C#.
// 07/08/2009 - J. Ritchie Carroll
// Added WaitHandle return value from asynchronous connection.
// 07/15/2009 - Pinal C. Patel
// Modified Disconnect() to add error checking.
// 07/17/2009 - Pinal C. Patel
// Added support to specify a specific interface address on a multiple interface machine.
// 09/14/2009 - Stephen C. Wills
// Added new header and license agreement.
// 03/24/2010 - Pinal C. Patel
// Updated the interpretation of server property in ConnectionString to correctly interpret
// IPv6 IP addresses according to IETF - A Recommendation for IPv6 Address Text Representation.
// 11/29/2010 - Pinal C. Patel
// Corrected the implementation of ConnectAsync() method.
// 02/11/2011 - Pinal C. Patel
// Added IntegratedSecurity property to enable integrated windows authentication.
// 02/13/2011 - Pinal C. Patel
// Modified ConnectAsync() to handle loop-back address resolution failure on IPv6 enabled OSes.
// 09/21/2011 - J. Ritchie Carroll
// Added Mono implementation exception regions.
// 07/23/2012 - Stephen C. Wills
// Performed a full refactor to use the SocketAsyncEventArgs API calls.
// 10/31/2012 - Stephen C. Wills
// Replaced single-threaded BlockingCollection pattern with asynchronous loop pattern.
// 12/13/2012 - Starlynn Danyelle Gilliam
// Modified Header.
//
//******************************************************************************************************
using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Security;
using System.Net.Sockets;
using System.Security.Authentication;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading;
using Gemstone.ActionExtensions;
using Gemstone.ArrayExtensions;
using Gemstone.StringExtensions;
using Gemstone.Threading.SynchronizedOperations;
// ReSharper disable AccessToDisposedClosure
namespace Gemstone.Communication
{
/// <summary>
/// Represents a TCP-based communication client.
/// </summary>
/// <remarks>
/// The socket can be bound to a specified interface on a machine with multiple interfaces by
/// specifying the IP of the interface in the <see cref="ClientBase.ConnectionString"/>
/// (Example: "Server=localhost:8888; Interface=192.168.1.15")
/// </remarks>
/// <example>
/// This example shows how to use the <see cref="TcpClient"/> component:
/// <code>
/// using System;
/// using GSF;
/// using GSF.Communication;
/// using GSF.Security.Cryptography;
/// using GSF.IO.Compression;
///
/// class Program
/// {
/// static TcpClient s_client;
///
/// static void Main(string[] args)
/// {
/// // Initialize the client.
/// s_client = new TcpClient("Server=localhost:8888");
/// s_client.Handshake = false;
/// s_client.PayloadAware = false;
/// s_client.ReceiveTimeout = -1;
/// s_client.MaxConnectionAttempts = 5;
/// s_client.Encryption = CipherStrength.None;
/// s_client.Compression = CompressionStrength.NoCompression;
/// s_client.SecureSession = false;
/// s_client.Initialize();
/// // Register event handlers.
/// s_client.ConnectionAttempt += s_client_ConnectionAttempt;
/// s_client.ConnectionEstablished += s_client_ConnectionEstablished;
/// s_client.ConnectionTerminated += s_client_ConnectionTerminated;
/// s_client.ReceiveDataComplete += s_client_ReceiveDataComplete;
/// // Connect the client.
/// s_client.Connect();
///
/// // Transmit user input to the server.
/// string input;
/// while (string.Compare(input = Console.ReadLine(), "Exit", true) != 0)
/// {
/// s_client.Send(input);
/// }
///
/// // Disconnect the client on shutdown.
/// s_client.Dispose();
/// }
///
/// static void s_client_ConnectionAttempt(object? sender, EventArgs e)
/// {
/// Console.WriteLine("Client is connecting to server.");
/// }
///
/// static void s_client_ConnectionEstablished(object? sender, EventArgs e)
/// {
/// Console.WriteLine("Client connected to server.");
/// }
///
/// static void s_client_ConnectionTerminated(object? sender, EventArgs e)
/// {
/// Console.WriteLine("Client disconnected from server.");
/// }
///
/// static void s_client_ReceiveDataComplete(object? sender, EventArgs<byte[], int> e)
/// {
/// Console.WriteLine(string.Format("Received data - {0}.", s_client.TextEncoding.GetString(e.Argument1, 0, e.Argument2)));
/// }
/// }
/// </code>
/// </example>
// ReSharper disable UnusedVariable
public class TcpClient : ClientBase
{
#region [ Members ]
// Nested Types
private sealed class ConnectState : IDisposable
{
public Socket? Socket;
public NetworkStream? NetworkStream;
public NegotiateStream? NegotiateStream;
public readonly SocketAsyncEventArgs ConnectArgs = new();
public SocketAsyncEventArgs? ReceiveArgs;
public SocketAsyncEventArgs? SendArgs;
public int ConnectionAttempts;
public readonly CancellationToken Token = new();
public Func<bool> CancelTimeout = () => false;
public void Dispose()
{
ConnectArgs.Dispose();
ReceiveArgs?.Dispose();
SendArgs?.Dispose();
Socket?.Dispose();
NetworkStream?.Dispose();
NegotiateStream?.Dispose();
}
}
private sealed class ReceiveState : IDisposable
{
public Socket? Socket;
public SocketAsyncEventArgs? ReceiveArgs;
public SocketAsyncEventArgs? SendArgs;
public byte[]? Buffer;
public int Offset;
public int PayloadLength = -1;
public CancellationToken? Token;
public void Dispose()
{
Dispose(Socket);
Dispose(ReceiveArgs);
Dispose(SendArgs);
}
private static void Dispose(IDisposable? obj) => obj?.Dispose();
}
private sealed class SendState : IDisposable
{
public Socket? Socket;
public SocketAsyncEventArgs? ReceiveArgs;
public SocketAsyncEventArgs? SendArgs;
public readonly ConcurrentQueue<TcpClientPayload> SendQueue = new();
public TcpClientPayload? Payload;
public int Sending;
public CancellationToken? Token;
public void Dispose()
{
Dispose(Socket);
Dispose(ReceiveArgs);
Dispose(SendArgs);
while (SendQueue.TryDequeue(out TcpClientPayload? payload))
{
payload.WaitHandle.Set();
payload.WaitHandle.Dispose();
}
}
private static void Dispose(IDisposable? obj) => obj?.Dispose();
}
private class TcpClientPayload
{
public byte[]? Data;
public int Offset;
public int Length;
public readonly ManualResetEventSlim WaitHandle = new();
}
private class CancellationToken
{
private int m_cancelled;
public bool Cancelled => Interlocked.CompareExchange(ref m_cancelled, 0, 0) != 0;
public bool Cancel() => Interlocked.Exchange(ref m_cancelled, 1) != 0;
}
// Constants
/// <summary>
/// Specifies the default value for the <see cref="PayloadAware"/> property.
/// </summary>
public const bool DefaultPayloadAware = false;
/// <summary>
/// Specifies the default value for the <see cref="IntegratedSecurity"/> property.
/// </summary>
public const bool DefaultIntegratedSecurity = false;
/// <summary>
/// Specifies the default value for the <see cref="IgnoreInvalidCredentials"/> property.
/// </summary>
public const bool DefaultIgnoreInvalidCredentials = false;
/// <summary>
/// Specifies the default value for the <see cref="AllowDualStackSocket"/> property.
/// </summary>
public const bool DefaultAllowDualStackSocket = true;
/// <summary>
/// Specifies the default value for the <see cref="MaxSendQueueSize"/> property.
/// </summary>
public const int DefaultMaxSendQueueSize = 500000;
/// <summary>
/// Specifies the default value for the <see cref="NoDelay"/> property.
/// </summary>
public const bool DefaultNoDelay = false;
/// <summary>
/// Specifies the default value for the <see cref="ClientBase.ConnectionString"/> property.
/// </summary>
public const string DefaultConnectionString = "Server=localhost:8888";
// Fields
private byte[] m_payloadMarker;
private EndianOrder m_payloadEndianOrder;
private IPStack m_ipStack;
private readonly ShortSynchronizedOperation m_dumpPayloadsOperation;
private string[]? m_serverList;
private Dictionary<string, string> m_connectData = DefaultConnectionString.ParseKeyValuePairs();
private ManualResetEvent? m_connectWaitHandle;
private ConnectState? m_connectState;
private ReceiveState? m_receiveState;
private SendState? m_sendState;
private bool m_disposed;
#endregion
#region [ Constructors ]
/// <summary>
/// Initializes a new instance of the <see cref="TcpClient"/> class.
/// </summary>
public TcpClient() : this(DefaultConnectionString)
{
}
/// <summary>
/// Initializes a new instance of the <see cref="TcpClient"/> class.
/// </summary>
/// <param name="connectString">Connect string of the <see cref="TcpClient"/>. See <see cref="DefaultConnectionString"/> for format.</param>
public TcpClient(string connectString) : base(TransportProtocol.Tcp, connectString)
{
PayloadAware = DefaultPayloadAware;
m_payloadMarker = Payload.DefaultMarker;
m_payloadEndianOrder = EndianOrder.LittleEndian;
IntegratedSecurity = DefaultIntegratedSecurity;
IgnoreInvalidCredentials = DefaultIgnoreInvalidCredentials;
AllowDualStackSocket = DefaultAllowDualStackSocket;
MaxSendQueueSize = DefaultMaxSendQueueSize;
NoDelay = DefaultNoDelay;
m_dumpPayloadsOperation = new ShortSynchronizedOperation(DumpPayloads, OnSendDataException);
}
#endregion
#region [ Properties ]
/// <summary>
/// Gets or sets a boolean value that indicates whether the payload boundaries are to be preserved during transmission.
/// </summary>
public bool PayloadAware { get; set; }
/// <summary>
/// Gets or sets the byte sequence used to mark the beginning of a payload in a <see cref="PayloadAware"/> transmission.
/// </summary>
/// <remarks>
/// Setting property to <c>null</c> will create a zero-length payload marker.
/// </remarks>
public byte[]? PayloadMarker
{
get => m_payloadMarker;
set => m_payloadMarker = value ?? Array.Empty<byte>();
}
/// <summary>
/// Gets or sets the endian order to apply for encoding and decoding payload size in a <see cref="PayloadAware"/> transmission.
/// </summary>
/// <remarks>
/// Setting property to <c>null</c> will force use of little-endian encoding.
/// </remarks>
public EndianOrder? PayloadEndianOrder
{
get => m_payloadEndianOrder;
set => m_payloadEndianOrder = value ?? EndianOrder.LittleEndian;
}
/// <summary>
/// Gets or sets a boolean value that indicates whether the current Windows account credentials are used for authentication.
/// </summary>
/// <remarks>
/// This option is ignored under Mono deployments.
/// </remarks>
public bool IntegratedSecurity { get; set; }
/// <summary>
/// Gets or sets a boolean value that indicates whether the server
/// should ignore errors when the client's credentials are invalid.
/// </summary>
/// <remarks>
/// This property should only be set to true if there is an alternative by which
/// to authenticate the client when integrated security fails.
/// </remarks>
public bool IgnoreInvalidCredentials { get; set; }
/// <summary>
/// Gets or sets a boolean value that determines if dual-mode socket is allowed when endpoint address is IPv6.
/// </summary>
public bool AllowDualStackSocket { get; set; }
/// <summary>
/// Gets or sets the maximum size for the send queue before payloads are dumped from the queue.
/// </summary>
public int MaxSendQueueSize { get; set; }
/// <summary>
/// Gets or sets a boolean value that determines if small packets are delivered to the remote host without delay.
/// </summary>
public bool NoDelay { get; set; }
/// <summary>
/// Gets the <see cref="Socket"/> object for the <see cref="TcpClient"/>.
/// </summary>
public Socket? Client => m_connectState?.Socket;
/// <summary>
/// Gets the server URI of the <see cref="TcpClient"/>.
/// </summary>
public override string ServerUri => $"{TransportProtocol}://{ServerList[ServerIndex]}".ToLower();
/// <summary>
/// Gets or sets network credential that is used when
/// <see cref="IntegratedSecurity"/> is set to <c>true</c>.
/// </summary>
public NetworkCredential? NetworkCredential { get; set; }
/// <summary>
/// Determines whether the base class should track statistics.
/// </summary>
protected override bool TrackStatistics => false;
// Gets server connect data as an array - will always be at least one empty string, not null
private string[] ServerList
{
get
{
if (m_serverList is not null)
return m_serverList;
if (!m_connectData.TryGetValue("server", out string? serverList) || string.IsNullOrWhiteSpace(serverList))
return Array.Empty<string>();
return m_serverList = serverList.Split(new[] { ',' }, StringSplitOptions.RemoveEmptyEntries).Select(server => server.Trim()).ToArray();
}
}
/// <summary>
/// Gets the descriptive status of the client.
/// </summary>
public override string Status
{
get
{
SendState? sendState = m_sendState;
StringBuilder statusBuilder = new(base.Status);
if (sendState is not null)
statusBuilder.AppendLine($" Queued payloads: {sendState.SendQueue.Count:N0}");
return statusBuilder.ToString();
}
}
#endregion
#region [ Methods ]
/// <summary>
/// Connects the <see cref="TcpClient"/> to the server asynchronously.
/// </summary>
/// <exception cref="InvalidOperationException">Attempt is made to connect the <see cref="TcpClient"/> when it is not disconnected.</exception>
/// <returns><see cref="WaitHandle"/> for the asynchronous operation.</returns>
public override WaitHandle? ConnectAsync()
{
ConnectState? connectState = null;
if (CurrentState != ClientState.Disconnected || m_disposed)
return m_connectWaitHandle;
try
{
// If we do not already have a wait handle to use
// for connections, get one from the base class
m_connectWaitHandle ??= (ManualResetEvent?)base.ConnectAsync();
// Create state object for the asynchronous connection loop
connectState = new ConnectState();
// Store connectState in m_connectState so that calls to Disconnect
// and Dispose can dispose resources and cancel asynchronous loops
using (m_connectState)
{
m_connectState = connectState;
}
OnConnectionAttempt();
m_connectWaitHandle?.Reset();
// Overwrite config file if integrated security exists in connection string
if (m_connectData.TryGetValue("integratedSecurity", out string? integratedSecuritySetting))
IntegratedSecurity = integratedSecuritySetting.ParseBoolean();
//IntegratedSecurity = false;
// Overwrite config file if no delay exists in connection string.
if (m_connectData.TryGetValue("noDelay", out string? noDelaySetting))
NoDelay = noDelaySetting.ParseBoolean();
// Initialize state object for the asynchronous connection loop
Match endpoint = Regex.Match(ServerList[ServerIndex], Transport.EndpointFormatRegex);
connectState.ConnectArgs.RemoteEndPoint = Transport.CreateEndPoint(endpoint.Groups["host"].Value, int.Parse(endpoint.Groups["port"].Value), m_ipStack);
connectState.ConnectArgs.SocketFlags = SocketFlags.None;
connectState.ConnectArgs.UserToken = connectState;
connectState.ConnectArgs.Completed += (_, args) => ProcessConnect((ConnectState)args.UserToken!);
// Create client socket
connectState.Socket = Transport.CreateSocket(m_connectData["interface"], 0, ProtocolType.Tcp, m_ipStack, AllowDualStackSocket);
connectState.Socket.NoDelay = NoDelay;
// Initiate the asynchronous connection loop
ConnectAsync(connectState);
}
catch (Exception ex)
{
// Log exception during connection attempt
OnConnectionException(ex);
// Terminate the connection
if (connectState is not null)
TerminateConnection(connectState.Token);
// Ensure that the wait handle is set so that operations waiting
// for completion of the asynchronous connection loop can continue
m_connectWaitHandle?.Set();
}
finally
{
// If the operation was canceled during execution,
// make sure to dispose of erroneously allocated resources
if (connectState is { Token.Cancelled: true })
connectState.Dispose();
}
// Return the wait handle that signals completion
// of the asynchronous connection loop
return m_connectWaitHandle;
}
/// <summary>
/// Initiates an asynchronous connection attempt.
/// </summary>
private void ConnectAsync(ConnectState connectState)
{
if (connectState.Token.Cancelled)
return;
if (!(connectState.Socket?.ConnectAsync(connectState.ConnectArgs) ?? false))
ThreadPool.QueueUserWorkItem(_ => ProcessConnect(connectState));
}
/// <summary>
/// Callback method for asynchronous connect operation.
/// </summary>
private void ProcessConnect(ConnectState connectState)
{
ReceiveState? receiveState = null;
SendState? sendState = null;
try
{
// Quit if this connection loop has been canceled
if (connectState.Token.Cancelled)
return;
// Increment the number of connection attempts that
// have occurred in this asynchronous connection loop
connectState.ConnectionAttempts++;
// Check the SocketAsyncEventArgs for errors during the asynchronous connection attempt
if (connectState.ConnectArgs.SocketError != SocketError.Success)
throw new SocketException((int)connectState.ConnectArgs.SocketError);
if (connectState.Socket is null)
throw new InvalidOperationException("No socket available while attempting to process connection.");
// Set the size of the buffer used by the socket to store incoming data from the server
connectState.Socket.ReceiveBufferSize = ReceiveBufferSize;
if (IntegratedSecurity)
{
// Check the state of cancellation one more time before
// proceeding to the next step of the connection loop
if (connectState.Token.Cancelled)
return;
// Create the SslStream object used to perform
// send and receive operations on the socket
connectState.NetworkStream = new NetworkStream(connectState.Socket, false);
connectState.NegotiateStream = new NegotiateStream(connectState.NetworkStream, true);
connectState.CancelTimeout = new Action(() =>
{
SocketException ex = new((int)SocketError.TimedOut);
OnConnectionException(ex);
TerminateConnection(connectState.Token);
connectState.Dispose();
}).DelayAndExecute(15000);
try
{
connectState.NegotiateStream.BeginAuthenticateAsClient(NetworkCredential ?? (NetworkCredential)CredentialCache.DefaultCredentials, string.Empty, ProcessIntegratedSecurityAuthentication, connectState);
}
catch
{
connectState.CancelTimeout();
throw;
}
}
else
{
// Initialize the SocketAsyncEventArgs for receive operations
connectState.ReceiveArgs = new SocketAsyncEventArgs();
connectState.ReceiveArgs.SetBuffer(new byte[ReceiveBufferSize], 0, ReceiveBufferSize);
if (PayloadAware)
connectState.ReceiveArgs.Completed += (_, args) => ProcessReceivePayloadAware((ReceiveState)args.UserToken!);
else
connectState.ReceiveArgs.Completed += (_, args) => ProcessReceivePayloadUnaware((ReceiveState)args.UserToken!);
// Initialize the SocketAsyncEventArgs for send operations
connectState.SendArgs = new SocketAsyncEventArgs();
connectState.SendArgs.SetBuffer(new byte[SendBufferSize], 0, SendBufferSize);
connectState.SendArgs.Completed += (_, args) => ProcessSend((SendState)args.UserToken!);
// Initialize state object for the asynchronous send loop
sendState = new SendState
{
Token = connectState.Token,
Socket = connectState.Socket,
ReceiveArgs = connectState.ReceiveArgs,
SendArgs = connectState.SendArgs
};
sendState.SendArgs.UserToken = sendState;
// Store sendState in m_sendState so that calls to Disconnect
// and Dispose can dispose resources and cancel asynchronous loops
using (m_sendState)
{
m_sendState = sendState;
}
// Check the state of cancellation one more time before
// proceeding to the next step of the connection loop
if (connectState.Token.Cancelled)
return;
// Notify of established connection
m_connectWaitHandle?.Set();
OnConnectionEstablished();
// Initialize state object for the asynchronous receive loop
receiveState = new ReceiveState
{
Token = connectState.Token,
Socket = connectState.Socket,
Buffer = connectState.ReceiveArgs.Buffer,
ReceiveArgs = connectState.ReceiveArgs
};
receiveState.ReceiveArgs.UserToken = receiveState;
receiveState.SendArgs = connectState.SendArgs;
// Store receiveState in m_receiveState so that calls to Disconnect
// and Dispose can dispose resources and cancel asynchronous loops
using (m_receiveState)
{
m_receiveState = receiveState;
}
// Start receiving data
if (PayloadAware)
ReceivePayloadAwareAsync(receiveState);
else
ReceivePayloadUnawareAsync(receiveState);
// Further socket interactions are handled through the ReceiveArgs
// and SendArgs objects, so the ConnectArgs is no longer needed
connectState.ConnectArgs.Dispose();
}
}
catch (SocketException ex)
{
// Log exception during connection attempt
OnConnectionException(ex);
// If the connection is refused by the server,
// keep trying until we reach our maximum connection attempts
if (ex.SocketErrorCode == SocketError.ConnectionRefused && (MaxConnectionAttempts == -1 || connectState.ConnectionAttempts < MaxConnectionAttempts))
{
// Server is unavailable, so keep retrying connection to the server.
try
{
ConnectAsync(connectState);
}
catch
{
TerminateConnection(connectState.Token);
}
}
else
{
// For any other reason, clean-up as if the client was disconnected.
TerminateConnection(connectState.Token);
}
}
catch (Exception ex)
{
// Log exception during connection attempt
OnConnectionException(ex);
// Terminate the connection
TerminateConnection(connectState.Token);
}
finally
{
// If the operation was canceled during execution,
// make sure to dispose of erroneously allocated resources
if (connectState is { Token.Cancelled: true })
connectState.Dispose();
if (receiveState?.Token is { Cancelled: true })
receiveState.Dispose();
if (sendState?.Token is { Cancelled: true })
sendState.Dispose();
}
}
private void ProcessIntegratedSecurityAuthentication(IAsyncResult asyncResult)
{
ConnectState? connectState = null;
ReceiveState? receiveState = null;
SendState? sendState = null;
try
{
// Get the connect state from the async result
connectState = (ConnectState)asyncResult.AsyncState!;
if (connectState is null)
throw new InvalidOperationException("Connect state null while attempting to process integrated security authentication.");
// Attempt to cancel the timeout operation
if (!connectState.CancelTimeout())
return;
// Quit if this connection loop has been canceled
if (connectState.Token.Cancelled)
return;
try
{
// Complete the operation to authenticate with the server
connectState.NegotiateStream?.EndAuthenticateAsClient(asyncResult);
}
catch (InvalidCredentialException)
{
if (!IgnoreInvalidCredentials)
throw;
}
// Initialize the SocketAsyncEventArgs for receive operations
connectState.ReceiveArgs = new SocketAsyncEventArgs();
connectState.ReceiveArgs.SetBuffer(new byte[ReceiveBufferSize], 0, ReceiveBufferSize);
if (PayloadAware)
connectState.ReceiveArgs.Completed += (_, args) => ProcessReceivePayloadAware((ReceiveState)args.UserToken!);
else
connectState.ReceiveArgs.Completed += (_, args) => ProcessReceivePayloadUnaware((ReceiveState)args.UserToken!);
// Initialize the SocketAsyncEventArgs for send operations
connectState.SendArgs = new SocketAsyncEventArgs();
connectState.SendArgs.SetBuffer(new byte[SendBufferSize], 0, SendBufferSize);
connectState.SendArgs.Completed += (_, args) => ProcessSend((SendState)args.UserToken!);
// Initialize state object for the asynchronous send loop
sendState = new SendState
{
Token = connectState.Token,
Socket = connectState.Socket,
ReceiveArgs = connectState.ReceiveArgs,
SendArgs = connectState.SendArgs
};
sendState.SendArgs.UserToken = sendState;
// Store sendState in m_sendState so that calls to Disconnect
// and Dispose can dispose resources and cancel asynchronous loops
using (m_sendState)
{
m_sendState = sendState;
}
// Check the state of cancellation one more time before
// proceeding to the next step of the connection loop
if (connectState.Token.Cancelled)
return;
// Notify of established connection
// and begin receiving data.
m_connectWaitHandle?.Set();
OnConnectionEstablished();
// Initialize state object for the asynchronous receive loop
receiveState = new ReceiveState
{
Token = connectState.Token,
Socket = connectState.Socket,
Buffer = connectState.ReceiveArgs.Buffer,
ReceiveArgs = connectState.ReceiveArgs
};
receiveState.ReceiveArgs.UserToken = receiveState;
receiveState.SendArgs = connectState.SendArgs;
// Store receiveState in m_receiveState so that calls to Disconnect
// and Dispose can dispose resources and cancel asynchronous loops
using (m_receiveState)
{
m_receiveState = receiveState;
}
// Start receiving data
if (PayloadAware)
ReceivePayloadAwareAsync(receiveState);
else
ReceivePayloadUnawareAsync(receiveState);
// Further socket interactions are handled through the SslStream
// object, so the SocketAsyncEventArgs is no longer needed
connectState.ConnectArgs.Dispose();
}
catch (SocketException ex)
{
// Log exception during connection attempt
OnConnectionException(ex);
// If connectState is null, we cannot proceed
if (connectState is null)
return;
// If the connection is refused by the server,
// keep trying until we reach our maximum connection attempts
if (ex.SocketErrorCode == SocketError.ConnectionRefused && (MaxConnectionAttempts == -1 || connectState.ConnectionAttempts < MaxConnectionAttempts))
{
try
{
ConnectAsync(connectState);
}
catch
{
TerminateConnection(connectState.Token);
}
}
else
{
// For any other socket exception,
// terminate the connection
TerminateConnection(connectState.Token);
}
}
catch (Exception ex)
{
// Log exception during connection attempt
string errorMessage = $"Unable to authenticate connection to server: {ex.Message}";
OnConnectionException(new Exception(errorMessage, ex));
// Terminate the connection
if (connectState is not null)
TerminateConnection(connectState.Token);
}
finally
{
if (connectState is not null)
{
// If the operation was canceled during execution,
// make sure to dispose of erroneously allocated resources;
// otherwise, dispose of the NegotiateStream which is only used for authentication
if (connectState.Token.Cancelled)
{
connectState.Dispose();
}
else
{
connectState.NetworkStream?.Dispose();
connectState.NegotiateStream?.Dispose();
}
}
if (receiveState?.Token is { Cancelled: true })
receiveState.Dispose();
if (sendState?.Token is { Cancelled: true })
sendState.Dispose();
}
}
/// <summary>
/// Initiate method for asynchronous receive operation of payload data in "payload-aware" mode.
/// </summary>
private void ReceivePayloadAwareAsync(ReceiveState receiveState)
{
// Quit if this receive loop has been canceled
if (receiveState.Token is null || receiveState.Token.Cancelled || receiveState.ReceiveArgs is null)
return;
int length;
if (receiveState.PayloadLength < 0)
length = m_payloadMarker.Length + Payload.LengthSegment;
else
length = receiveState.PayloadLength;
if (receiveState.Buffer != receiveState.ReceiveArgs.Buffer)
receiveState.ReceiveArgs.SetBuffer(receiveState.Buffer, 0, length);
else
receiveState.ReceiveArgs.SetBuffer(receiveState.Offset, length - receiveState.Offset);
if (!(receiveState.Socket?.ReceiveAsync(receiveState.ReceiveArgs) ?? false))
ThreadPool.QueueUserWorkItem(_ => ProcessReceivePayloadAware(receiveState));
}
/// <summary>
/// Callback method for asynchronous receive operation of payload data in "payload-aware" mode.
/// </summary>
private void ProcessReceivePayloadAware(ReceiveState receiveState)
{
// Quit if this receive loop has been canceled
if (receiveState.Token is null || receiveState.Token.Cancelled || receiveState.ReceiveArgs is null)
return;
try
{
// Determine if the server disconnected gracefully
if (receiveState.ReceiveArgs.SocketError != SocketError.Success)
throw new SocketException((int)receiveState.ReceiveArgs.SocketError);
if (receiveState.ReceiveArgs.BytesTransferred == 0)
throw new SocketException((int)SocketError.Disconnecting);
// Update statistics and bytes received.
UpdateBytesReceived(receiveState.ReceiveArgs.BytesTransferred);
receiveState.Offset += receiveState.ReceiveArgs.BytesTransferred;
if (receiveState is { PayloadLength: < 0, Buffer: not null })
{
// If we haven't parsed the length of the payload yet, attempt to parse it
receiveState.PayloadLength = Payload.ExtractLength(receiveState.Buffer, receiveState.Offset, m_payloadMarker, m_payloadEndianOrder);
if (receiveState.PayloadLength > 0)
{
receiveState.Offset = 0;
if (receiveState.Buffer.Length < receiveState.PayloadLength)
receiveState.Buffer = new byte[receiveState.PayloadLength];
}
}
else if (receiveState.Offset == receiveState.PayloadLength)
{
// We've received the entire payload so notify the user
OnReceiveDataComplete(receiveState.Buffer, receiveState.PayloadLength);
// Reset payload length
receiveState.Offset = 0;
receiveState.PayloadLength = -1;
}
// Continue asynchronous loop
ReceivePayloadAwareAsync(receiveState);
}
catch (ObjectDisposedException)
{
// Make sure connection is terminated when client is disposed.
TerminateConnection(receiveState.Token);
}
catch (SocketException ex)
{
// Log exception during receive operation
OnReceiveDataException(ex);
// Terminate connection when socket exception is encountered
TerminateConnection(receiveState.Token);
}
catch (Exception ex)
{
try
{
// For any other exception, notify and resume
OnReceiveDataException(ex);
ReceivePayloadAwareAsync(receiveState);
}
catch
{
// Terminate connection if resume fails
TerminateConnection(receiveState.Token);
}
}
finally
{
// If the operation was canceled during execution,
// make sure to dispose of allocated resources
if (receiveState.Token.Cancelled)
receiveState.Dispose();
}
}
/// <summary>
/// Initiate method for asynchronous receive operation of payload data in "payload-unaware" mode.