generated from gemstone/gemtem
/
TlsServer.cs
1217 lines (1031 loc) · 51.6 KB
/
TlsServer.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
//******************************************************************************************************
// TlsServer.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:
// ----------------------------------------------------------------------------------------------------
// 07/12/2012 - Stephen C. Wills
// Generated original version of source code.
// 12/13/2012 - Starlynn Danyelle Gilliam
// Modified Header.
//
//******************************************************************************************************
using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Net.Security;
using System.Net.Sockets;
using System.Security;
using System.Security.Authentication;
using System.Security.Cryptography.X509Certificates;
using System.Security.Principal;
using System.Text;
using System.Threading;
using Gemstone.ActionExtensions;
using Gemstone.ArrayExtensions;
using Gemstone.IO;
using Gemstone.Net.Security;
using Gemstone.StringExtensions;
using Gemstone.Threading.SynchronizedOperations;
namespace Gemstone.Communication
{
/// <summary>
/// Represents a TCP-based communication server with SSL authentication and encryption.
/// </summary>
public class TlsServer : ServerBase
{
#region [ Members ]
// Nested Types
/// <summary>
/// Represents a socket that has been wrapped
/// in an <see cref="SslStream"/> for encryption.
/// </summary>
public sealed class TlsSocket : IDisposable
{
/// <summary>
/// Gets the <see cref="Socket"/> connected to the remote host.
/// </summary>
public Socket? Socket;
/// <summary>
/// Gets the stream through which data is passed when
/// sending to or receiving from the remote host.
/// </summary>
public SslStream? SslStream;
/// <summary>
/// The end point of the remote client connecting to this server.
/// </summary>
public IPEndPoint? RemoteEndPoint;
/// <summary>
/// Performs application-defined tasks associated with
/// freeing, releasing, or resetting unmanaged resources.
/// </summary>
public void Dispose()
{
Socket?.Dispose();
SslStream?.Dispose();
}
}
private class TlsClientInfo
{
public TransportProvider<TlsSocket> Client = new();
public Func<bool> CancelTimeout = () => false;
public int Sending;
public readonly object SendLock = new();
public readonly ConcurrentQueue<TlsServerPayload> SendQueue = new();
public ShortSynchronizedOperation DumpPayloadsOperation = default!;
public NegotiateStream? NegotiateStream;
public WindowsPrincipal? ClientPrincipal;
}
private class TlsServerPayload
{
// Per payload state
public byte[]? Data;
public int Offset;
public int Length;
public ManualResetEventSlim WaitHandle = new();
// Per client state
public TlsClientInfo? ClientInfo;
}
// Constants
/// <summary>
/// Specifies the default value for the <see cref="TrustedCertificatesPath"/> property.
/// </summary>
public readonly string DefaultTrustedCertificatesPath = FilePath.GetAbsolutePath(@"Certs\Remotes");
/// <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="ServerBase.ConfigurationString"/> property.
/// </summary>
public const string DefaultConfigurationString = "Port=8888";
// Fields
private readonly SimpleCertificateChecker m_defaultCertificateChecker;
private ICertificateChecker? m_certificateChecker;
private string? m_certificateFile;
private byte[] m_payloadMarker;
private EndianOrder m_payloadEndianOrder;
private IPStack m_ipStack;
private SocketAsyncEventArgs? m_acceptArgs;
private readonly ConcurrentDictionary<Guid, TlsClientInfo> m_clientInfoLookup;
private Dictionary<string, string> m_configData = DefaultConfigurationString.ParseKeyValuePairs();
private readonly EventHandler<SocketAsyncEventArgs> m_acceptHandler;
#endregion
#region [ Constructors ]
/// <summary>
/// Initializes a new instance of the <see cref="TcpServer"/> class.
/// </summary>
public TlsServer() : this(DefaultConfigurationString)
{
}
/// <summary>
/// Initializes a new instance of the <see cref="TcpServer"/> class.
/// </summary>
/// <param name="configString">Config string of the <see cref="TcpServer"/>. See <see cref="DefaultConfigurationString"/> for format.</param>
public TlsServer(string configString) : base(TransportProtocol.Tcp, configString)
{
m_defaultCertificateChecker = new SimpleCertificateChecker();
LocalCertificateSelectionCallback = DefaultLocalCertificateSelectionCallback!;
EnabledSslProtocols = SslProtocols.Tls12;
CheckCertificateRevocation = true;
TrustedCertificatesPath = DefaultTrustedCertificatesPath;
PayloadAware = DefaultPayloadAware;
m_payloadMarker = Payload.DefaultMarker;
m_payloadEndianOrder = EndianOrder.LittleEndian;
IntegratedSecurity = DefaultIntegratedSecurity;
IgnoreInvalidCredentials = DefaultIgnoreInvalidCredentials;
AllowDualStackSocket = DefaultAllowDualStackSocket;
MaxSendQueueSize = DefaultMaxSendQueueSize;
NoDelay = DefaultNoDelay;
m_clientInfoLookup = new ConcurrentDictionary<Guid, TlsClientInfo>();
m_acceptHandler = (_, args) => ProcessAccept(args);
}
#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 client Windows account credentials are used for authentication.
/// </summary>
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. When this is set
/// to true, if the client's credentials are invalid, the <see cref="TryGetClientPrincipal"/>
/// method will return true for that client, but the principal will still be null.
/// </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="TcpServer"/>.
/// </summary>
public Socket? Server { get; private set; }
/// <summary>
/// Gets or sets the certificate checker used to validate remote certificates.
/// </summary>
/// <remarks>
/// The certificate checker will only be used to validate certificates if
/// the <see cref="RemoteCertificateValidationCallback"/> is set to null.
/// </remarks>
public ICertificateChecker CertificateChecker
{
get => m_certificateChecker ?? m_defaultCertificateChecker;
set => m_certificateChecker = value;
}
/// <summary>
/// Gets or sets the callback used to validate remote certificates.
/// </summary>
public RemoteCertificateValidationCallback? RemoteCertificateValidationCallback { get; set; }
/// <summary>
/// Gets or sets the callback used to select local certificates.
/// </summary>
public LocalCertificateSelectionCallback? LocalCertificateSelectionCallback { get; set; }
/// <summary>
/// Gets or sets the path to the certificate used for authentication.
/// </summary>
public string? CertificateFile
{
get => m_certificateFile;
set
{
if (string.IsNullOrWhiteSpace(value))
{
m_certificateFile = null;
Certificate = null;
}
else
{
m_certificateFile = FilePath.GetAbsolutePath(value);
if (File.Exists(m_certificateFile))
Certificate = new X509Certificate2(m_certificateFile);
}
}
}
/// <summary>
/// Gets or sets the certificate used to identify this server.
/// </summary>
public X509Certificate? Certificate { get; set; }
/// <summary>
/// Gets or sets a set of flags which determine the enabled <see cref="SslProtocols"/>.
/// </summary>
/// <exception cref="SecurityException">Failed to write event log entry for security warning about use of less secure TLS/SSL protocols.</exception>
public SslProtocols EnabledSslProtocols { get; set; }
/// <summary>
/// Gets or sets a flag that determines whether a client certificate is required during authentication.
/// </summary>
public bool RequireClientCertificate { get; set; }
/// <summary>
/// Gets or sets a boolean value that determines whether the certificate revocation list is checked during authentication.
/// </summary>
public bool CheckCertificateRevocation { get; set; }
/// <summary>
/// Gets or sets the path to the directory containing the trusted certificates.
/// </summary>
public string TrustedCertificatesPath { get; set; }
/// <summary>
/// Gets or sets the set of valid policy errors when validating remote certificates.
/// </summary>
public SslPolicyErrors ValidPolicyErrors
{
get => m_defaultCertificateChecker.ValidPolicyErrors;
set => m_defaultCertificateChecker.ValidPolicyErrors = value;
}
/// <summary>
/// Gets or sets the set of valid chain flags used when validating remote certificates.
/// </summary>
public X509ChainStatusFlags ValidChainFlags
{
get => m_defaultCertificateChecker.ValidChainFlags;
set => m_defaultCertificateChecker.ValidChainFlags = value;
}
/// <summary>
/// Gets the descriptive status of the server.
/// </summary>
public override string Status
{
get
{
StringBuilder statusBuilder = new(base.Status);
int count = 0;
foreach (ConcurrentQueue<TlsServerPayload> sendQueue in m_clientInfoLookup.Values.Select(clientInfo => clientInfo.SendQueue))
{
statusBuilder.AppendFormat(" Queued payloads: {0} for client {1}", sendQueue.Count, ++count);
statusBuilder.AppendLine();
}
return statusBuilder.ToString();
}
}
#endregion
#region [ Methods ]
/// <summary>
/// Reads a number of bytes from the current received data buffer and writes those bytes into a byte array at the specified offset.
/// </summary>
/// <param name="clientID">ID of the client from which data buffer should be read.</param>
/// <param name="buffer">Destination buffer used to hold copied bytes.</param>
/// <param name="startIndex">0-based starting index into destination <paramref name="buffer"/> to begin writing data.</param>
/// <param name="length">The number of bytes to read from current received data buffer and write into <paramref name="buffer"/>.</param>
/// <returns>The number of bytes read.</returns>
/// <remarks>
/// This function should only be called from within the <see cref="ServerBase.ReceiveClientData"/> event handler. Calling this method
/// outside this event will have unexpected results.
/// </remarks>
/// <exception cref="InvalidOperationException">
/// No received data buffer has been defined to read -or-
/// Specified <paramref name="clientID"/> does not exist, cannot read buffer.
/// </exception>
/// <exception cref="ArgumentNullException"><paramref name="buffer"/> is null.</exception>
/// <exception cref="ArgumentOutOfRangeException">
/// <paramref name="startIndex"/> or <paramref name="length"/> is less than 0 -or-
/// <paramref name="startIndex"/> and <paramref name="length"/> will exceed <paramref name="buffer"/> length.
/// </exception>
public override int Read(Guid clientID, byte[] buffer, int startIndex, int length)
{
buffer.ValidateParameters(startIndex, length);
if (!m_clientInfoLookup.TryGetValue(clientID, out TlsClientInfo? clientInfo))
throw new InvalidOperationException("Specified client ID does not exist, cannot read buffer.");
TransportProvider<TlsSocket> tlsClient = clientInfo.Client;
if (tlsClient.ReceiveBuffer is null)
throw new InvalidOperationException("No received data buffer has been defined to read.");
int readIndex = ReadIndicies[clientID];
int sourceLength = tlsClient.BytesReceived - readIndex;
int readBytes = length > sourceLength ? sourceLength : length;
Buffer.BlockCopy(tlsClient.ReceiveBuffer, readIndex, buffer, startIndex, readBytes);
// Update read index for next call
readIndex += readBytes;
if (readIndex >= tlsClient.BytesReceived)
readIndex = 0;
ReadIndicies[clientID] = readIndex;
return readBytes;
}
/// <summary>
/// Stops the <see cref="TcpServer"/> synchronously and disconnects all connected clients.
/// </summary>
public override void Stop()
{
SocketAsyncEventArgs? acceptArgs = m_acceptArgs;
m_acceptArgs = null;
if (CurrentState != ServerState.Running)
return;
DisconnectAll(); // Disconnection all clients.
Server?.Close(); // Stop accepting new connections.
// Clean up accept args.
acceptArgs?.Dispose();
OnServerStopped();
}
/// <summary>
/// Starts the <see cref="TcpServer"/> synchronously and begins accepting client connections asynchronously.
/// </summary>
/// <exception cref="InvalidOperationException">Attempt is made to <see cref="Start()"/> the <see cref="TcpServer"/> when it is running.</exception>
public override void Start()
{
if (CurrentState != ServerState.NotRunning)
throw new InvalidOperationException("Server is currently running");
// Initialize if uninitialized.
if (!Initialized)
Initialize();
// Overwrite config file if integrated security exists in connection string.
if (m_configData.TryGetValue("integratedSecurity", out string? integratedSecuritySetting))
IntegratedSecurity = integratedSecuritySetting.ParseBoolean();
//m_integratedSecurity = false;
// Overwrite config file if max client connections exists in connection string.
if (m_configData.ContainsKey("maxClientConnections") && int.TryParse(m_configData["maxClientConnections"], out int maxClientConnections))
MaxClientConnections = maxClientConnections;
// Overwrite config file if max send queue size exists in connection string.
if (m_configData.ContainsKey("maxSendQueueSize") && int.TryParse(m_configData["maxSendQueueSize"], out int maxSendQueueSize))
MaxSendQueueSize = maxSendQueueSize;
// Overwrite config file if no delay exists in connection string.
if (m_configData.TryGetValue("noDelay", out string? noDelaySetting))
NoDelay = noDelaySetting.ParseBoolean();
// Bind server socket to local end-point and listen.
Server = Transport.CreateSocket(m_configData["interface"], int.Parse(m_configData["port"]), ProtocolType.Tcp, m_ipStack, AllowDualStackSocket);
Server.NoDelay = NoDelay;
Server.Listen(1);
// Begin accepting incoming connection asynchronously.
m_acceptArgs = new SocketAsyncEventArgs { AcceptSocket = null };
m_acceptArgs.SetBuffer(null, 0, 0);
m_acceptArgs.SocketFlags = SocketFlags.None;
m_acceptArgs.Completed += m_acceptHandler;
if (!Server.AcceptAsync(m_acceptArgs))
ThreadPool.QueueUserWorkItem(state => ProcessAccept((SocketAsyncEventArgs)state!), m_acceptArgs);
// Notify that the server has been started successfully.
OnServerStarted();
}
/// <summary>
/// Disconnects the specified connected client.
/// </summary>
/// <param name="clientID">ID of the client to be disconnected.</param>
/// <exception cref="InvalidOperationException">Client does not exist for the specified <paramref name="clientID"/>.</exception>
public override void DisconnectOne(Guid clientID)
{
if (!TryGetClient(clientID, out TransportProvider<TlsSocket>? tlsClient) || tlsClient is null)
return;
try
{
if (tlsClient.Provider?.Socket is { Connected: true })
tlsClient.Provider.Socket.Disconnect(false);
OnClientDisconnected(clientID);
tlsClient.Reset();
}
catch (Exception ex)
{
OnSendClientDataException(clientID, new InvalidOperationException($"Client disconnection exception: {ex.Message}", ex));
}
}
/// <summary>
/// Gets the <see cref="TransportProvider{TlsSocket}"/> object associated with the specified client ID.
/// </summary>
/// <param name="clientID">ID of the client.</param>
/// <param name="tlsClient">The TLS client.</param>
/// <returns>An <see cref="TransportProvider{TlsSocket}"/> object.</returns>
/// <exception cref="InvalidOperationException">Client does not exist for the specified <paramref name="clientID"/>.</exception>
public bool TryGetClient(Guid clientID, out TransportProvider<TlsSocket>? tlsClient)
{
bool clientExists = m_clientInfoLookup.TryGetValue(clientID, out TlsClientInfo? clientInfo);
tlsClient = clientExists ? clientInfo!.Client : null;
return clientExists;
}
/// <summary>
/// Gets the <see cref="WindowsPrincipal"/> object associated with the specified client ID.
/// </summary>
/// <param name="clientID">ID of the client.</param>
/// <param name="clientPrincipal">The principal of the client.</param>
/// <returns>A <see cref="WindowsPrincipal"/> object.</returns>
public bool TryGetClientPrincipal(Guid clientID, out WindowsPrincipal? clientPrincipal)
{
bool clientExists = m_clientInfoLookup.TryGetValue(clientID, out TlsClientInfo? clientInfo);
clientPrincipal = clientExists ? clientInfo!.ClientPrincipal : null;
return clientExists;
}
/// <summary>
/// Validates the specified <paramref name="configurationString"/>.
/// </summary>
/// <param name="configurationString">Configuration string to be validated.</param>
/// <exception cref="ArgumentException">Port property is missing.</exception>
/// <exception cref="ArgumentOutOfRangeException">Port property value is not between <see cref="Transport.PortRangeLow"/> and <see cref="Transport.PortRangeHigh"/>.</exception>
protected override void ValidateConfigurationString(string configurationString)
{
m_configData = configurationString.ParseKeyValuePairs();
// Derive desired IP stack based on specified "interface" setting, adding setting if it's not defined
m_ipStack = Transport.GetInterfaceIPStack(m_configData);
if (!m_configData.ContainsKey("port"))
throw new ArgumentException($"Port property is missing (Example: {DefaultConfigurationString})");
if (!Transport.IsPortNumberValid(m_configData["port"]))
throw new ArgumentOutOfRangeException(nameof(configurationString), $"Port number must be between {Transport.PortRangeLow} and {Transport.PortRangeHigh}");
}
/// <summary>
/// Sends data to the specified client asynchronously.
/// </summary>
/// <param name="clientID">ID of the client to which the data is to be sent.</param>
/// <param name="data">The buffer that contains the binary data to be sent.</param>
/// <param name="offset">The zero-based position in the <paramref name="data"/> at which to begin sending data.</param>
/// <param name="length">The number of bytes to be sent from <paramref name="data"/> starting at the <paramref name="offset"/>.</param>
/// <returns><see cref="WaitHandle"/> for the asynchronous operation.</returns>
protected override WaitHandle SendDataToAsync(Guid clientID, byte[] data, int offset, int length)
{
if (!m_clientInfoLookup.TryGetValue(clientID, out TlsClientInfo? clientInfo))
throw new InvalidOperationException($"No client found for ID {clientID}.");
ConcurrentQueue<TlsServerPayload> sendQueue = clientInfo.SendQueue;
// Execute operation to see if the client has reached the maximum send queue size.
clientInfo.DumpPayloadsOperation.TryRun();
// Prepare for payload-aware transmission.
if (PayloadAware)
Payload.AddHeader(ref data, ref offset, ref length, m_payloadMarker, m_payloadEndianOrder);
// Create payload and wait handle.
TlsServerPayload payload = new();
ManualResetEventSlim handle = new();
payload.Data = data;
payload.Offset = offset;
payload.Length = length;
payload.WaitHandle = handle;
payload.ClientInfo = clientInfo;
handle.Reset();
// Queue payload for sending.
sendQueue.Enqueue(payload);
lock (clientInfo.SendLock)
{
// Send next queued payload.
if (Interlocked.CompareExchange(ref clientInfo.Sending, 1, 0) == 0)
{
if (sendQueue.TryDequeue(out TlsServerPayload? dequeuedPayload))
ThreadPool.QueueUserWorkItem(state => SendPayload((TlsServerPayload)state!), dequeuedPayload);
else
Interlocked.Exchange(ref clientInfo.Sending, 0);
}
}
// Notify that the send operation has started.
OnSendClientDataStart(clientID);
// Return the async handle that can be used to wait for the async operation to complete.
return handle.WaitHandle;
}
/// <summary>
/// Callback method for asynchronous accept operation.
/// </summary>
private void ProcessAccept(SocketAsyncEventArgs acceptArgs)
{
TransportProvider<TlsSocket> client = new();
TlsClientInfo? clientInfo = null;
try
{
if (CurrentState == ServerState.NotRunning)
return;
// If acceptArgs was disposed, m_acceptArgs will either
// be null or another instance of SocketAsyncEventArgs.
// This check will tell us whether it's been disposed.
if (acceptArgs != m_acceptArgs)
return;
SocketError error = acceptArgs.SocketError;
if (error != SocketError.Success && error != SocketError.ConnectionReset)
{
// Error is unrecoverable.
// We need to make sure to restart the
// server before we throw the error.
ThreadPool.QueueUserWorkItem(_ => ReStart());
throw new SocketException((int)error);
}
// At this point, we have determined that the server is up and running.
// We need to make sure the acceptArgs.AcceptAsync() method is called or
// else the server will continue running but stop accepting connections
try
{
if (acceptArgs.SocketError != SocketError.Success)
throw new SocketException((int)error);
if (MaxClientConnections != -1 && ClientIDs.Length >= MaxClientConnections)
{
// Reject client connection since limit has been reached.
TerminateConnection(client, false);
}
else
{
// Process the newly connected client.
LoadTrustedCertificates();
NetworkStream netStream = new(acceptArgs.AcceptSocket!, true);
client.Provider = new TlsSocket
{
Socket = acceptArgs.AcceptSocket,
SslStream = new SslStream(netStream, false, RemoteCertificateValidationCallback ?? CertificateChecker.ValidateRemoteCertificate!, LocalCertificateSelectionCallback),
RemoteEndPoint = acceptArgs.AcceptSocket!.RemoteEndPoint as IPEndPoint
};
client.Provider.Socket!.ReceiveBufferSize = ReceiveBufferSize;
clientInfo = new TlsClientInfo { Client = client };
// Create operation to dump send queue payloads when the queue grows too large.
clientInfo.DumpPayloadsOperation = new ShortSynchronizedOperation(() =>
{
// Check to see if the client has reached the maximum send queue size.
if (MaxSendQueueSize > 0 && clientInfo.SendQueue.Count >= MaxSendQueueSize)
{
for (int i = 0; i < MaxSendQueueSize; i++)
{
if (clientInfo.SendQueue.TryDequeue(out TlsServerPayload? payload))
{
payload.WaitHandle.Set();
payload.WaitHandle.Dispose();
}
}
throw new InvalidOperationException($"Client {clientInfo.Client.ID} connected to TCP server reached maximum send queue size. {MaxSendQueueSize} payloads dumped from the queue.");
}
}, ex => OnSendClientDataException(clientInfo.Client.ID, ex));
clientInfo.CancelTimeout = new Action(() => client.Provider?.Socket.Dispose()).DelayAndExecute(15000);
client.Provider.SslStream.BeginAuthenticateAsServer(Certificate!, RequireClientCertificate, EnabledSslProtocols, CheckCertificateRevocation, ProcessTlsAuthentication, clientInfo);
}
}
finally
{
// Return to accepting new connections.
acceptArgs.AcceptSocket = null;
if (!(Server?.AcceptAsync(acceptArgs) ?? false))
ThreadPool.QueueUserWorkItem(_ => ProcessAccept(acceptArgs));
}
}
catch (ObjectDisposedException)
{
// m_acceptArgs may be disposed while in the middle of accepting a connection
}
catch (Exception ex)
{
// Exception occurred so make sure we cancel the timeout
clientInfo?.CancelTimeout.Invoke();
// Notify of the exception.
IPEndPoint? remoteEndPoint = client.Provider?.RemoteEndPoint;
string clientAddress = remoteEndPoint?.Address.ToString() ?? "UNKNOWN";
string errorMessage = $"Unable to accept connection to client [{clientAddress}]: {ex.Message}";
OnClientConnectingException(new Exception(errorMessage, ex));
TerminateConnection(client, false);
}
}
/// <summary>
/// Callback method for asynchronous authenticate operation.
/// </summary>
private void ProcessTlsAuthentication(IAsyncResult asyncResult)
{
TlsClientInfo clientInfo = (TlsClientInfo)asyncResult.AsyncState!;
TransportProvider<TlsSocket> client = clientInfo.Client;
SslStream? stream = client.Provider!.SslStream;
try
{
if (!clientInfo.CancelTimeout())
throw new SocketException((int)SocketError.TimedOut);
if (stream is null)
throw new InvalidOperationException("No stream available for authentication.");
stream.EndAuthenticateAsServer(asyncResult);
if (EnabledSslProtocols != SslProtocols.None)
{
if (!stream.IsAuthenticated)
throw new InvalidOperationException("Unable to authenticate.");
if (!stream.IsEncrypted)
throw new InvalidOperationException("Unable to encrypt data stream.");
}
if (IntegratedSecurity)
{
clientInfo.NegotiateStream = new NegotiateStream(stream, true);
clientInfo.CancelTimeout = new Action(() => client.Provider?.Socket?.Dispose()).DelayAndExecute(15000);
clientInfo.NegotiateStream.BeginAuthenticateAsServer(ProcessIntegratedSecurityAuthentication, clientInfo);
}
else
{
// We can proceed further with receiving data from the client.
m_clientInfoLookup.TryAdd(client.ID, clientInfo);
OnClientConnected(client.ID);
ReceivePayloadAsync(client);
}
}
catch (Exception ex)
{
// Exception occurred so make sure we cancel the timeout
clientInfo.CancelTimeout();
// Notify of the exception.
IPEndPoint? remoteEndPoint = client.Provider.RemoteEndPoint;
string clientAddress = remoteEndPoint?.Address.ToString() ?? "<undefined>";
string errorMessage = $"Unable to authenticate connection to client [{clientAddress}]: {CertificateChecker.ReasonForFailure ?? ex.Message}";
OnClientConnectingException(new Exception(errorMessage, ex));
TerminateConnection(client, false);
}
}
private void ProcessIntegratedSecurityAuthentication(IAsyncResult asyncResult)
{
TlsClientInfo clientInfo = (TlsClientInfo)asyncResult.AsyncState!;
TransportProvider<TlsSocket> client = clientInfo.Client;
NegotiateStream? negotiateStream = clientInfo.NegotiateStream;
IPEndPoint? remoteEndPoint = client.Provider!.RemoteEndPoint;
if (negotiateStream is null)
throw new InvalidOperationException("No stream available for authentication.");
try
{
if (!clientInfo.CancelTimeout())
throw new SocketException((int)SocketError.TimedOut);
try
{
negotiateStream.EndAuthenticateAsServer(asyncResult);
if (!Common.IsPosixEnvironment)
{
if (negotiateStream.RemoteIdentity is WindowsIdentity identity)
{
#pragma warning disable CA1416
WindowsPrincipal clientPrincipal = new(identity);
#pragma warning restore CA1416
clientInfo.ClientPrincipal = clientPrincipal;
}
}
}
catch (InvalidCredentialException)
{
if (!IgnoreInvalidCredentials)
throw;
}
// We can proceed further with receiving data from the client.
m_clientInfoLookup.TryAdd(client.ID, clientInfo);
OnClientConnected(client.ID);
ReceivePayloadAsync(client);
}
catch (Exception ex)
{
// Notify of the exception.
string clientAddress = remoteEndPoint?.Address.ToString() ?? "<undefined>";
string errorMessage = $"Unable to authenticate connection to client [{clientAddress}]: {ex.Message}";
OnClientConnectingException(new Exception(errorMessage, ex));
TerminateConnection(client, false);
}
finally
{
negotiateStream.Dispose();
}
}
/// <summary>
/// Asynchronous loop sends payloads on the socket.
/// </summary>
private void SendPayload(TlsServerPayload payload)
{
TlsClientInfo? clientInfo = null;
TransportProvider<TlsSocket>? client = null;
try
{
if (payload is null)
throw new NullReferenceException($"{nameof(TlsServerPayload)} was null in {nameof(TlsServer)}.{nameof(SendPayload)}");
clientInfo = payload.ClientInfo;
if (clientInfo is null)
throw new NullReferenceException($"{nameof(TlsServerPayload)}.{nameof(TlsServerPayload.ClientInfo)} was null in {nameof(TlsServer)}.{nameof(SendPayload)}");
client = clientInfo.Client;
byte[] data = payload.Data!;
int offset = payload.Offset;
int length = payload.Length;
// Send payload to the client asynchronously.
client.Provider!.SslStream?.BeginWrite(data, offset, length, ProcessSend, payload);
}
catch (Exception ex)
{
if (client is not null)
OnSendClientDataException(client.ID, ex);
if (clientInfo is not null)
{
// Assume process send was not able
// to continue the asynchronous loop.
Interlocked.Exchange(ref clientInfo.Sending, 0);
}
}
}
/// <summary>
/// Callback method for asynchronous send operation.
/// </summary>
private void ProcessSend(IAsyncResult asyncResult)
{
TlsServerPayload? payload = null;
TlsClientInfo? clientInfo = null;
TransportProvider<TlsSocket>? client = null;
ConcurrentQueue<TlsServerPayload>? sendQueue = null;
try
{
payload = (TlsServerPayload)asyncResult.AsyncState!;
if (payload is null)
throw new NullReferenceException($"{nameof(TlsServerPayload)} was null in {nameof(TlsServer)}.{nameof(ProcessSend)}");
clientInfo = payload.ClientInfo;
if (clientInfo is null)
throw new NullReferenceException($"{nameof(TlsServerPayload)}.{nameof(TlsServerPayload.ClientInfo)} was null in {nameof(TlsServer)}.{nameof(ProcessSend)}");
client = clientInfo.Client;
sendQueue = clientInfo.SendQueue;
ManualResetEventSlim handle = payload.WaitHandle;
// Set the wait handle to indicate
// the send operation is complete.
handle.Set();
// Update statistics and notify.
client.Provider!.SslStream?.EndWrite(asyncResult);
client.Statistics.UpdateBytesSent(payload.Length);
OnSendClientDataComplete(client.ID);
}
catch (Exception ex)
{
// Send operation failed to complete.
if (client is not null)
OnSendClientDataException(client.ID, ex);
}
finally
{
if (payload is not null && sendQueue is not null)
{
try
{
payload.ClientInfo = null;
// Begin sending next client payload.
if (sendQueue.TryDequeue(out payload))
{
ThreadPool.QueueUserWorkItem(state => SendPayload((TlsServerPayload)state!), payload);
}
else if (clientInfo is not null)
{
lock (clientInfo.SendLock)
{
if (sendQueue.TryDequeue(out payload))
ThreadPool.QueueUserWorkItem(state => SendPayload((TlsServerPayload)state!), payload);
else
Interlocked.Exchange(ref clientInfo.Sending, 0);
}
}
}
catch (Exception ex)
{
string errorMessage = $"Exception encountered while attempting to send next payload: {ex.Message}";
if (client is not null)
OnSendClientDataException(client.ID, new Exception(errorMessage, ex));
if (clientInfo is not null)
Interlocked.Exchange(ref clientInfo.Sending, 0);
}
}
}
}
/// <summary>
/// Initiate method for asynchronous receive operation of payload data.
/// </summary>
private void ReceivePayloadAsync(TransportProvider<TlsSocket> client)
{
// Initialize bytes received.
client.BytesReceived = 0;
// Initiate receiving.
if (PayloadAware)
{
// Payload boundaries are to be preserved.
client.SetReceiveBuffer(m_payloadMarker.Length + Payload.LengthSegment);
ReceivePayloadAwareAsync(client, true);
}
else