-
Notifications
You must be signed in to change notification settings - Fork 4
/
WebSocket.cs
1598 lines (1445 loc) · 68.9 KB
/
WebSocket.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
#region Related components
using System;
using System.Linq;
using System.IO;
using System.Net;
using System.Net.Sockets;
using System.Net.WebSockets;
using System.Net.Security;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading;
using System.Threading.Tasks;
using System.Collections.Generic;
using System.Collections.Concurrent;
using System.Security.Authentication;
using System.Security.Cryptography.X509Certificates;
using System.Runtime.InteropServices;
using Microsoft.Extensions.Logging;
using net.vieapps.Components.WebSockets.Exceptions;
using net.vieapps.Components.Utility;
#endregion
#if !SIGN
[assembly: System.Runtime.CompilerServices.InternalsVisibleTo("VIEApps.Components.XUnitTests")]
#endif
namespace net.vieapps.Components.WebSockets
{
/// <summary>
/// The centralized point for working with WebSocket
/// </summary>
public class WebSocket : IDisposable, IAsyncDisposable
{
#region Properties
readonly ConcurrentDictionary<Guid, ManagedWebSocket> _websockets = new ConcurrentDictionary<Guid, ManagedWebSocket>();
readonly ILogger _logger = null;
readonly Func<MemoryStream> _recycledStreamFactory = null;
readonly CancellationTokenSource _processingCTS = null;
CancellationTokenSource _listeningCTS = null;
TcpListener _tcpListener = null;
/// <summary>
/// Gets or Sets the SSL certificate for securing connections (server)
/// </summary>
public X509Certificate2 Certificate { get; set; }
/// <summary>
/// Gets or Sets the SSL protocol for securing connections with SSL Certificate (server)
/// </summary>
public SslProtocols SslProtocol { get; set; } = SslProtocols.Tls12;
/// <summary>
/// Gets or Sets the collection of supported sub-protocol (server)
/// </summary>
public IEnumerable<string> SupportedSubProtocols { get; set; } = new string[0];
/// <summary>
/// Gets or Sets the keep-alive interval for sending ping messages (server)
/// </summary>
public TimeSpan KeepAliveInterval { get; set; } = TimeSpan.FromSeconds(60);
/// <summary>
/// Gets or Sets a value that specifies whether the listener is disable the Nagle algorithm or not (default is true - means disable for better performance)
/// </summary>
/// <remarks>
/// Set to true to send a message immediately with the least amount of latency (typical usage for chat)
/// This will disable Nagle's algorithm which can cause high tcp latency for small packets sent infrequently
/// However, if you are streaming large packets or sending large numbers of small packets frequently it is advisable to set NoDelay to false
/// This way data will be bundled into larger packets for better throughput
/// </remarks>
public bool NoDelay { get; set; } = true;
/// <summary>
/// Gets or Sets await interval between two rounds of receiving messages
/// </summary>
public TimeSpan ReceivingAwaitInterval { get; set; } = TimeSpan.Zero;
/// <summary>
/// Gets the state that determines the WebSocket object was disposed or not
/// </summary>
public bool IsDisposed { get; private set; } = false;
#endregion
#region Event Handlers
/// <summary>
/// Event to fire when got an error while processing
/// </summary>
public event Action<ManagedWebSocket, Exception> ErrorHandler;
/// <summary>
/// Gets or Sets the action to run when got an error while processing
/// </summary>
public Action<ManagedWebSocket, Exception> OnError
{
set => this.ErrorHandler += value;
get => this.ErrorHandler;
}
/// <summary>
/// Event to fire when a connection is established
/// </summary>
public event Action<ManagedWebSocket> ConnectionEstablishedHandler;
/// <summary>
/// Gets or Sets the action to run when a connection is established
/// </summary>
public Action<ManagedWebSocket> OnConnectionEstablished
{
set => this.ConnectionEstablishedHandler += value;
get => this.ConnectionEstablishedHandler;
}
/// <summary>
/// Event to fire when a connection is broken
/// </summary>
public event Action<ManagedWebSocket> ConnectionBrokenHandler;
/// <summary>
/// Gets or Sets the action to run when a connection is broken
/// </summary>
public Action<ManagedWebSocket> OnConnectionBroken
{
set => this.ConnectionBrokenHandler += value;
get => this.ConnectionBrokenHandler;
}
/// <summary>
/// Event to fire when a message is received
/// </summary>
public event Action<ManagedWebSocket, WebSocketReceiveResult, byte[]> MessageReceivedHandler;
/// <summary>
/// Gets or Sets the action to run when a message is received
/// </summary>
public Action<ManagedWebSocket, WebSocketReceiveResult, byte[]> OnMessageReceived
{
set => this.MessageReceivedHandler += value;
get => this.MessageReceivedHandler;
}
#endregion
/// <summary>
/// Creates new an instance of the centralized <see cref="WebSocket">WebSocket</see>
/// </summary>
/// <param name="cancellationToken">The cancellation token</param>
public WebSocket(CancellationToken cancellationToken)
: this(null, cancellationToken) { }
/// <summary>
/// Creates new an instance of the centralized <see cref="WebSocket">WebSocket</see>
/// </summary>
/// <param name="loggerFactory">The logger factory</param>
/// <param name="cancellationToken">The cancellation token</param>
public WebSocket(ILoggerFactory loggerFactory, CancellationToken cancellationToken)
: this(loggerFactory, null, cancellationToken) { }
/// <summary>
/// Creates new an instance of the centralized <see cref="WebSocket">WebSocket</see>
/// </summary>
/// <param name="loggerFactory">The logger factory</param>
/// <param name="recycledStreamFactory">Used to get a recyclable memory stream (this can be used with the Microsoft.IO.RecyclableMemoryStreamManager class)</param>
/// <param name="cancellationToken">The cancellation token</param>
public WebSocket(ILoggerFactory loggerFactory = null, Func<MemoryStream> recycledStreamFactory = null, CancellationToken cancellationToken = default)
{
Logger.AssignLoggerFactory(loggerFactory);
this._logger = Logger.CreateLogger<WebSocket>();
this._recycledStreamFactory = recycledStreamFactory ?? WebSocketHelper.GetRecyclableMemoryStreamFactory();
this._processingCTS = CancellationTokenSource.CreateLinkedTokenSource(cancellationToken);
}
/// <summary>
/// Gets or sets the size (length) of the protocol buffer used to receive and parse frames, the default is 16kb, the minimum is 1kb (1024 bytes)
/// </summary>
public static int ReceiveBufferSize
{
get => WebSocketHelper.ReceiveBufferSize;
set => WebSocketHelper.ReceiveBufferSize = value >= 1024 ? value : WebSocketHelper.ReceiveBufferSize;
}
/// <summary>
/// Gets or sets the agent name of the protocol for working with related headers
/// </summary>
public static string AgentName
{
get => WebSocketHelper.AgentName;
set => WebSocketHelper.AgentName = !string.IsNullOrWhiteSpace(value) ? value : WebSocketHelper.AgentName;
}
#region Listen for client requests as server
/// <summary>
/// Starts to listen for client requests as a WebSocket server
/// </summary>
/// <param name="port">The port for listening</param>
/// <param name="certificate">The SSL Certificate to secure connections</param>
/// <param name="onSuccess">Action to fire when start successful</param>
/// <param name="onFailure">Action to fire when failed to start</param>
/// <param name="getPingPayload">The function to get the custom 'PING' playload to send a 'PING' message</param>
/// <param name="getPongPayload">The function to get the custom 'PONG' playload to response to a 'PING' message</param>
/// <param name="onPong">The action to run when a 'PONG' message has been sent</param>
public void StartListen(int port = 46429, X509Certificate2 certificate = null, Action onSuccess = null, Action<Exception> onFailure = null, Func<ManagedWebSocket, byte[]> getPingPayload = null, Func<ManagedWebSocket, byte[], byte[]> getPongPayload = null, Action<ManagedWebSocket, byte[]> onPong = null)
{
// check
if (this._tcpListener != null)
{
try
{
onSuccess?.Invoke();
}
catch (Exception ex)
{
if (this._logger.IsEnabled(LogLevel.Debug))
this._logger.Log(LogLevel.Error, $"Error occurred while calling the handler => {ex.Message}", ex);
}
return;
}
// set X.509 certificate
this.Certificate = certificate ?? this.Certificate;
// open the listener and listen for incoming requests
try
{
// open the listener
this._tcpListener = new TcpListener(IPAddress.IPv6Any, port > IPEndPoint.MinPort && port < IPEndPoint.MaxPort ? port : 46429);
this._tcpListener.Server.SetOptions(this.NoDelay, true);
this._tcpListener.Start(512);
if (this._logger.IsEnabled(LogLevel.Debug))
{
var platform = RuntimeInformation.IsOSPlatform(OSPlatform.Windows)
? "Windows"
: RuntimeInformation.IsOSPlatform(OSPlatform.OSX)
? "macOS"
: RuntimeInformation.IsOSPlatform(OSPlatform.Linux)
? "Linux"
#if NETSTANDARD2_0
: "Generic OS";
#else
: RuntimeInformation.IsOSPlatform(OSPlatform.FreeBSD) ? "FreeBSD" : "Generic OS";
#endif
platform += $" {RuntimeInformation.OSArchitecture.ToString().ToLower()} ({RuntimeInformation.FrameworkDescription.Trim()}) - SSL: {this.Certificate != null}";
if (this.Certificate != null)
platform += $" ({this.Certificate.GetNameInfo(X509NameType.DnsName, false)} :: Issued by {this.Certificate.GetNameInfo(X509NameType.DnsName, true)})";
this._logger.LogInformation($"The listener is started => {this._tcpListener.Server.LocalEndPoint}\r\nPlatform: {platform}\r\nPowered by {WebSocketHelper.AgentName} v{this.GetType().Assembly.GetVersion()}");
}
// callback when success
try
{
onSuccess?.Invoke();
}
catch (Exception ex)
{
if (this._logger.IsEnabled(LogLevel.Debug))
this._logger.Log(LogLevel.Error, $"Error occurred while calling the handler => {ex.Message}", ex);
}
// listen for incoming connection requests
this.Listen(getPingPayload, getPongPayload, onPong);
}
catch (SocketException ex)
{
var message = $"Error occurred while listening on port \"{(port > IPEndPoint.MinPort && port < IPEndPoint.MaxPort ? port : 46429)}\". Make sure another application is not running and consuming this port.";
if (this._logger.IsEnabled(LogLevel.Debug))
this._logger.Log(LogLevel.Error, message, ex);
try
{
onFailure?.Invoke(new ListenerSocketException(message, ex));
}
catch (Exception e)
{
if (this._logger.IsEnabled(LogLevel.Debug))
this._logger.Log(LogLevel.Error, $"Error occurred while calling the handler => {e.Message}", e);
}
}
catch (Exception ex)
{
if (this._logger.IsEnabled(LogLevel.Debug))
this._logger.Log(LogLevel.Error, $"Got an unexpected error while listening: {ex.Message}", ex);
try
{
onFailure?.Invoke(ex);
}
catch (Exception e)
{
if (this._logger.IsEnabled(LogLevel.Debug))
this._logger.Log(LogLevel.Error, $"Error occurred while calling the handler => {e.Message}", e);
}
}
}
/// <summary>
/// Starts to listen for client requests as a WebSocket server
/// </summary>
/// <param name="port">The port for listening</param>
/// <param name="onSuccess">Action to fire when start successful</param>
/// <param name="onFailure">Action to fire when failed to start</param>
/// <param name="getPingPayload">The function to get the custom 'PING' playload to send a 'PING' message</param>
/// <param name="getPongPayload">The function to get the custom 'PONG' playload to response to a 'PING' message</param>
/// <param name="onPong">The action to run when a 'PONG' message has been sent</param>
public void StartListen(int port, Action onSuccess, Action<Exception> onFailure, Func<ManagedWebSocket, byte[]> getPingPayload, Func<ManagedWebSocket, byte[], byte[]> getPongPayload, Action<ManagedWebSocket, byte[]> onPong)
=> this.StartListen(port, null, onSuccess, onFailure, getPingPayload, getPongPayload, onPong);
/// <summary>
/// Starts to listen for client requests as a WebSocket server
/// </summary>
/// <param name="port">The port for listening</param>
/// <param name="onSuccess">Action to fire when start successful</param>
/// <param name="onFailure">Action to fire when failed to start</param>
public void StartListen(int port, Action onSuccess, Action<Exception> onFailure)
=> this.StartListen(port, onSuccess, onFailure, null, null, null);
/// <summary>
/// Starts to listen for client requests as a WebSocket server
/// </summary>
/// <param name="port">The port for listening</param>
/// <param name="getPingPayload">The function to get the custom 'PING' playload to send a 'PING' message</param>
/// <param name="getPongPayload">The function to get the custom 'PONG' playload to response to a 'PING' message</param>
/// <param name="onPong">The action to run when a 'PONG' message has been sent</param>
public void StartListen(int port, Func<ManagedWebSocket, byte[]> getPingPayload, Func<ManagedWebSocket, byte[], byte[]> getPongPayload, Action<ManagedWebSocket, byte[]> onPong)
=> this.StartListen(port, null, null, getPingPayload, getPongPayload, onPong);
/// <summary>
/// Starts to listen for client requests as a WebSocket server
/// </summary>
/// <param name="port">The port for listening</param>
public void StartListen(int port)
=> this.StartListen(port, null, null, null);
/// <summary>
/// Stops listen
/// </summary>
/// <param name="cancelPendings">true to cancel the pending connections</param>
public void StopListen(bool cancelPendings = true)
{
// cancel all pending connections
if (cancelPendings)
this._listeningCTS?.Cancel();
// dispose
try
{
this._tcpListener?.Server?.Close();
this._tcpListener?.Stop();
}
catch (Exception ex)
{
this._logger.Log(LogLevel.Debug, LogLevel.Error, $"Got an unexpected error when stop the listener: {ex.Message}", ex);
}
finally
{
this._tcpListener = null;
}
}
Task Listen(Func<ManagedWebSocket, byte[]> getPingPayload, Func<ManagedWebSocket, byte[], byte[]> getPongPayload, Action<ManagedWebSocket, byte[]> onPong)
{
this._listeningCTS = CancellationTokenSource.CreateLinkedTokenSource(this._processingCTS.Token);
return this.ListenAsync(getPingPayload, getPongPayload, onPong);
}
async Task ListenAsync(Func<ManagedWebSocket, byte[]> getPingPayload, Func<ManagedWebSocket, byte[], byte[]> getPongPayload, Action<ManagedWebSocket, byte[]> onPong)
{
try
{
while (!this._listeningCTS.IsCancellationRequested)
this.AcceptClient(await this._tcpListener.AcceptTcpClientAsync().WithCancellationToken(this._listeningCTS.Token).ConfigureAwait(false), getPingPayload, getPongPayload, onPong);
}
catch (Exception ex)
{
this.StopListen(false);
if (ex is OperationCanceledException || ex is TaskCanceledException || ex is ObjectDisposedException || ex is SocketException || ex is IOException)
this._logger.LogDebug($"The listener is stopped {(this._logger.IsEnabled(LogLevel.Debug) ? $"({ex.GetType()})" : "")}");
else
this._logger.LogError($"The listener is stopped ({ex.Message})", ex);
}
}
void AcceptClient(TcpClient tcpClient, Func<ManagedWebSocket, byte[]> getPingPayload, Func<ManagedWebSocket, byte[], byte[]> getPongPayload, Action<ManagedWebSocket, byte[]> onPong)
=> this.AcceptClientAsync(tcpClient, getPingPayload, getPongPayload, onPong).Run();
async Task AcceptClientAsync(TcpClient tcpClient, Func<ManagedWebSocket, byte[]> getPingPayload, Func<ManagedWebSocket, byte[], byte[]> getPongPayload, Action<ManagedWebSocket, byte[]> onPong)
{
ManagedWebSocket websocket = null;
try
{
// set optins
tcpClient.Client.SetOptions(this.NoDelay);
// get stream
var id = Guid.NewGuid();
var endpoint = tcpClient.Client.RemoteEndPoint;
Stream stream = null;
if (this.Certificate != null)
try
{
Events.Log.AttemptingToSecureConnection(id);
if (this._logger.IsEnabled(LogLevel.Trace))
this._logger.Log(LogLevel.Debug, $"Attempting to secure the connection ({id} @ {endpoint})");
stream = new SslStream(tcpClient.GetStream(), false);
await (stream as SslStream).AuthenticateAsServerAsync(
serverCertificate: this.Certificate,
clientCertificateRequired: false,
enabledSslProtocols: this.SslProtocol,
checkCertificateRevocation: false
).WithCancellationToken(this._listeningCTS.Token).ConfigureAwait(false);
Events.Log.ConnectionSecured(id);
if (this._logger.IsEnabled(LogLevel.Trace))
this._logger.Log(LogLevel.Debug, $"The connection successfully secured ({id} @ {endpoint})");
}
catch (OperationCanceledException)
{
return;
}
catch (Exception ex)
{
Events.Log.ServerSslCertificateError(id, ex.ToString());
if (ex is AuthenticationException)
throw;
throw new AuthenticationException($"Cannot secure the connection: {ex.Message}", ex);
}
else
{
Events.Log.ConnectionNotSecured(id);
if (this._logger.IsEnabled(LogLevel.Trace))
this._logger.Log(LogLevel.Debug, $"Use insecured connection ({id} @ {endpoint})");
stream = tcpClient.GetStream();
}
// parse request
if (this._logger.IsEnabled(LogLevel.Trace))
this._logger.Log(LogLevel.Debug, $"The connection is opened, then parse the request ({id} @ {endpoint})");
var header = await stream.ReadHeaderAsync(this._listeningCTS.Token).ConfigureAwait(false);
if (this._logger.IsEnabled(LogLevel.Trace))
this._logger.Log(LogLevel.Debug, $"Handshake request ({id} @ {endpoint}) => \r\n{header.Trim()}");
var isWebSocketRequest = false;
var path = string.Empty;
var match = new Regex(@"^GET(.*)HTTP\/1\.1", RegexOptions.IgnoreCase).Match(header);
if (match.Success)
{
isWebSocketRequest = new Regex("Upgrade: WebSocket", RegexOptions.IgnoreCase).Match(header).Success;
if (isWebSocketRequest)
path = match.Groups[1].Value.Trim();
}
// verify request
if (!isWebSocketRequest)
{
if (this._logger.IsEnabled(LogLevel.Trace))
this._logger.Log(LogLevel.Debug, $"The request contains no WebSocket upgrade request, then ignore ({id} @ {endpoint})");
stream.Close();
tcpClient.Close();
return;
}
// accept the request
Events.Log.AcceptWebSocketStarted(id);
if (this._logger.IsEnabled(LogLevel.Trace))
this._logger.Log(LogLevel.Debug, $"The request has requested an upgrade to WebSocket protocol, negotiating WebSocket handshake ({id} @ {endpoint})");
var options = new WebSocketOptions
{
KeepAliveInterval = this.KeepAliveInterval.Ticks < 0 ? TimeSpan.FromSeconds(60) : this.KeepAliveInterval,
GetPingPayload = getPingPayload,
GetPongPayload = getPongPayload,
OnPong = onPong
};
try
{
// check the version (support version 13 and above)
match = new Regex("Sec-WebSocket-Version: (.*)").Match(header);
if (!match.Success || !Int32.TryParse(match.Groups[1].Value, out var version))
throw new VersionNotSupportedException("Unable to find \"Sec-WebSocket-Version\" in the upgrade request");
else if (version < 13)
throw new VersionNotSupportedException($"WebSocket Version {version} is not supported, must be 13 or above");
// get the request key
match = new Regex("Sec-WebSocket-Key: (.*)").Match(header);
var requestKey = match.Success
? match.Groups[1].Value.Trim()
: throw new KeyMissingException("Unable to find \"Sec-WebSocket-Key\" in the upgrade request");
// negotiate subprotocol
match = new Regex("Sec-WebSocket-Protocol: (.*)").Match(header);
options.SubProtocol = match.Success
? match.Groups[1].Value?.Trim().Split(new[] { ',', ' ' }, StringSplitOptions.RemoveEmptyEntries).NegotiateSubProtocol(this.SupportedSubProtocols)
: null;
// handshake
var handshake =
$"HTTP/1.1 101 Switching Protocols\r\n" +
$"Connection: Upgrade\r\n" +
$"Upgrade: websocket\r\n" +
$"Server: {WebSocketHelper.AgentName}\r\n" +
$"Date: {DateTime.Now.ToHttpString()}\r\n" +
$"Sec-WebSocket-Accept: {requestKey.ComputeAcceptKey()}\r\n";
if (!string.IsNullOrWhiteSpace(options.SubProtocol))
handshake += $"Sec-WebSocket-Protocol: {options.SubProtocol}\r\n";
options.AdditionalHeaders?.ForEach(kvp => handshake += $"{kvp.Key}: {kvp.Value}\r\n");
Events.Log.SendingHandshake(id, handshake);
await stream.WriteHeaderAsync(handshake, this._listeningCTS.Token).ConfigureAwait(false);
Events.Log.HandshakeSent(id, handshake);
if (this._logger.IsEnabled(LogLevel.Trace))
this._logger.Log(LogLevel.Debug, $"Handshake response ({id} @ {endpoint}) => \r\n{handshake.Trim()}");
}
catch (VersionNotSupportedException ex)
{
Events.Log.WebSocketVersionNotSupported(id, ex.ToString());
await stream.WriteHeaderAsync($"HTTP/1.1 426 Upgrade Required\r\nSec-WebSocket-Version: 13\r\nException: {ex.Message}", this._listeningCTS.Token).ConfigureAwait(false);
throw;
}
catch (Exception ex)
{
Events.Log.BadRequest(id, ex.ToString());
await stream.WriteHeaderAsync($"HTTP/1.1 400 Bad Request\r\nException: {ex.Message}", this._listeningCTS.Token).ConfigureAwait(false);
throw;
}
Events.Log.ServerHandshakeSuccess(id);
if (this._logger.IsEnabled(LogLevel.Trace))
this._logger.Log(LogLevel.Debug, $"WebSocket handshake response has been sent, the stream is ready ({id} @ {endpoint})");
// update the connected WebSocket connection
match = new Regex("Sec-WebSocket-Extensions: (.*)").Match(header);
options.Extensions = match.Success
? match.Groups[1].Value.Trim()
: null;
match = new Regex("Host: (.*)").Match(header);
var host = match.Success
? match.Groups[1].Value.Trim()
: string.Empty;
// add into the collection
websocket = new WebSocketImplementation(id, false, this._recycledStreamFactory, stream, options, new Uri($"ws{(this.Certificate != null ? "s" : "")}://{host}{path}"), endpoint, tcpClient.Client.LocalEndPoint, header.ToDictionary());
await this.AddWebSocketAsync(websocket).ConfigureAwait(false);
if (this._logger.IsEnabled(LogLevel.Trace))
this._logger.Log(LogLevel.Debug, $"The server WebSocket connection was successfully established ({websocket.ID} @ {websocket.RemoteEndPoint})\r\n- URI: {websocket.RequestUri}\r\n- Headers:\r\n\t{websocket.Headers.ToString("\r\n\t", kvp => $"{kvp.Key}: {kvp.Value}")}");
// callback
try
{
this.ConnectionEstablishedHandler?.Invoke(websocket);
}
catch (Exception e)
{
if (this._logger.IsEnabled(LogLevel.Debug))
this._logger.Log(LogLevel.Error, $"Error occurred while calling the handler => {e.Message}", e);
}
// receive messages
this.Receive(websocket);
}
catch (Exception ex)
{
if (ex is OperationCanceledException || ex is TaskCanceledException || ex is ObjectDisposedException || ex is SocketException || ex is IOException)
{
// normal, do nothing
}
else
{
if (this._logger.IsEnabled(LogLevel.Debug))
this._logger.Log(LogLevel.Error, $"Error occurred while accepting an incoming connection request: {ex.Message}", ex);
try
{
this.ErrorHandler?.Invoke(websocket, ex);
}
catch (Exception e)
{
if (this._logger.IsEnabled(LogLevel.Debug))
this._logger.Log(LogLevel.Error, $"Error occurred while calling the handler => {e.Message}", e);
}
}
}
}
#endregion
#region Connect to remote endpoints as client
async Task ConnectAsync(Uri uri, WebSocketOptions options, Action<ManagedWebSocket> onSuccess = null, Action<Exception> onFailure = null)
{
if (this._logger.IsEnabled(LogLevel.Trace))
this._logger.Log(LogLevel.Debug, $"Attempting to connect ({uri})");
try
{
// connect the TCP client
var id = Guid.NewGuid();
var tcpClient = new TcpClient();
tcpClient.Client.SetOptions(options.NoDelay);
if (IPAddress.TryParse(uri.Host, out var ipAddress))
{
Events.Log.ClientConnectingToIPAddress(id, ipAddress.ToString(), uri.Port);
await tcpClient.ConnectAsync(address: ipAddress, port: uri.Port).WithCancellationToken(this._processingCTS.Token).ConfigureAwait(false);
}
else
{
Events.Log.ClientConnectingToHost(id, uri.Host, uri.Port);
await tcpClient.ConnectAsync(host: uri.Host, port: uri.Port).WithCancellationToken(this._processingCTS.Token).ConfigureAwait(false);
}
var endpoint = tcpClient.Client.RemoteEndPoint;
if (this._logger.IsEnabled(LogLevel.Trace))
this._logger.Log(LogLevel.Debug, $"The endpoint ({uri}) is connected ({id} @ {endpoint})");
// get the connected stream
Stream stream = null;
if (uri.Scheme.IsEquals("wss") || uri.Scheme.IsEquals("https"))
try
{
Events.Log.AttemptingToSecureConnection(id);
if (this._logger.IsEnabled(LogLevel.Trace))
this._logger.Log(LogLevel.Debug, $"Attempting to secure the connection ({id} @ {endpoint})");
stream = new SslStream(
innerStream: tcpClient.GetStream(),
leaveInnerStreamOpen: false,
userCertificateValidationCallback: (sender, certificate, chain, sslPolicyErrors) => sslPolicyErrors == SslPolicyErrors.None || options.IgnoreCertificateErrors || RuntimeInformation.IsOSPlatform(OSPlatform.Linux),
userCertificateSelectionCallback: (sender, host, certificates, certificate, issuers) => this.Certificate
);
await (stream as SslStream).AuthenticateAsClientAsync(targetHost: uri.Host).WithCancellationToken(this._processingCTS.Token).ConfigureAwait(false);
Events.Log.ConnectionSecured(id);
if (this._logger.IsEnabled(LogLevel.Trace))
this._logger.Log(LogLevel.Debug, $"The connection successfully secured ({id} @ {endpoint})");
}
catch (OperationCanceledException)
{
throw;
}
catch (Exception ex)
{
Events.Log.ClientSslCertificateError(id, ex.ToString());
if (ex is AuthenticationException)
throw;
throw new AuthenticationException($"Cannot secure the connection: {ex.Message}", ex);
}
else
{
Events.Log.ConnectionNotSecured(id);
if (this._logger.IsEnabled(LogLevel.Trace))
this._logger.Log(LogLevel.Debug, $"Use insecured connection ({id} @ {endpoint})");
stream = tcpClient.GetStream();
}
// send handshake
if (this._logger.IsEnabled(LogLevel.Trace))
this._logger.Log(LogLevel.Debug, $"Negotiating WebSocket handshake ({id} @ {endpoint})");
var requestAcceptKey = CryptoService.GenerateRandomKey(16).ToBase64();
var handshake =
$"GET {uri.PathAndQuery} HTTP/1.1\r\n" +
$"Host: {uri.Host}:{uri.Port}\r\n" +
$"Origin: {uri.Scheme.Replace("ws", "http")}://{uri.Host}{(uri.Port != 80 && uri.Port != 443 ? $":{uri.Port}" : "")}\r\n" +
$"Connection: Upgrade\r\n" +
$"Upgrade: websocket\r\n" +
$"User-Agent: Mozilla/5.0 ({WebSocketHelper.AgentName}/{RuntimeInformation.FrameworkDescription.Trim()}/{(RuntimeInformation.IsOSPlatform(OSPlatform.OSX) ? "Macintosh; Mac OS X; " : "")}{RuntimeInformation.OSDescription.Trim()})\r\n" +
$"Date: {DateTime.Now.ToHttpString()}\r\n" +
$"Sec-WebSocket-Version: 13\r\n" +
$"Sec-WebSocket-Key: {requestAcceptKey}\r\n";
if (!string.IsNullOrWhiteSpace(options.SubProtocol))
handshake += $"Sec-WebSocket-Protocol: {options.SubProtocol}\r\n";
if (!string.IsNullOrWhiteSpace(options.Extensions))
handshake += $"Sec-WebSocket-Extensions: {options.Extensions}\r\n";
options.AdditionalHeaders?.ForEach(kvp => handshake += $"{kvp.Key}: {kvp.Value}\r\n");
Events.Log.SendingHandshake(id, handshake);
await stream.WriteHeaderAsync(handshake, this._processingCTS.Token).ConfigureAwait(false);
Events.Log.HandshakeSent(id, handshake);
if (this._logger.IsEnabled(LogLevel.Trace))
this._logger.Log(LogLevel.Debug, $"Handshake request ({id} @ {endpoint}) => \r\n{handshake.Trim()}");
// read response
Events.Log.ReadingResponse(id);
var response = string.Empty;
try
{
response = await stream.ReadHeaderAsync(this._processingCTS.Token).ConfigureAwait(false);
if (this._logger.IsEnabled(LogLevel.Trace))
this._logger.Log(LogLevel.Debug, $"Handshake response ({id} @ {endpoint}) => \r\n{response.Trim()}");
}
catch (Exception ex)
{
Events.Log.ReadResponseError(id, ex.ToString());
throw new HandshakeFailedException("Handshake unexpected failure", ex);
}
// get the response code
var match = new Regex(@"HTTP\/1\.1 (.*)", RegexOptions.IgnoreCase).Match(response);
var responseCode = match.Success
? match.Groups[1].Value.Trim()
: null;
// throw if got invalid response code
if (!"101 Switching Protocols".IsEquals(responseCode) && !"101 Web Socket Protocol Handshake".IsEquals(responseCode))
{
var lines = response.Split(new[] { "\r\n" }, StringSplitOptions.None);
for (var index = 0; index < lines.Length; index++)
if (string.IsNullOrWhiteSpace(lines[index])) // if there is more to the message than just the header
{
var builder = new StringBuilder();
for (var idx = index + 1; idx < lines.Length - 1; idx++)
builder.AppendLine(lines[idx]);
throw new InvalidResponseCodeException(responseCode, builder.ToString(), response);
}
}
// check the accepted key
match = new Regex("Sec-WebSocket-Accept: (.*)").Match(response);
var actualAcceptKey = match.Success
? match.Groups[1].Value.Trim()
: null;
var expectedAcceptKey = requestAcceptKey.ComputeAcceptKey();
if (!expectedAcceptKey.IsEquals(actualAcceptKey))
{
var warning = $"Handshake failed because the accept key {(actualAcceptKey == null ? "was not found" : $"from the server \"{actualAcceptKey}\" was not the expected \"{expectedAcceptKey}\"")}";
Events.Log.HandshakeFailure(id, warning);
throw new HandshakeFailedException(warning);
}
Events.Log.ClientHandshakeSuccess(id);
if (this._logger.IsEnabled(LogLevel.Trace))
this._logger.Log(LogLevel.Debug, $"Handshake success ({id} @ {endpoint})");
// get the accepted sub-protocol
match = new Regex("Sec-WebSocket-Protocol: (.*)").Match(response);
options.SubProtocol = match.Success
? match.Groups[1].Value?.Trim()
: null;
// update the connected WebSocket connection
var websocket = new WebSocketImplementation(id, true, this._recycledStreamFactory, stream, options, uri, endpoint, tcpClient.Client.LocalEndPoint, handshake.ToDictionary());
await this.AddWebSocketAsync(websocket).ConfigureAwait(false);
if (this._logger.IsEnabled(LogLevel.Trace))
this._logger.Log(LogLevel.Debug, $"The client WebSocket connection was successfully established ({websocket.ID} @ {websocket.RemoteEndPoint})\r\n- URI: {websocket.RequestUri}\r\n- Headers:\r\n\t{websocket.Headers.ToString("\r\n\t", kvp => $"{kvp.Key}: {kvp.Value}")}");
// callback
try
{
this.ConnectionEstablishedHandler?.Invoke(websocket);
onSuccess?.Invoke(websocket);
}
catch (Exception ex)
{
if (this._logger.IsEnabled(LogLevel.Debug))
this._logger.Log(LogLevel.Error, $"Error occurred while calling the handler => {ex.Message}", ex);
}
// receive messages
this.Receive(websocket);
}
catch (OperationCanceledException)
{
return;
}
catch (Exception ex)
{
if (this._logger.IsEnabled(LogLevel.Debug))
this._logger.Log(LogLevel.Error, $"Could not connect ({uri}): {ex.Message}", ex);
try
{
onFailure?.Invoke(ex);
}
catch (Exception e)
{
if (this._logger.IsEnabled(LogLevel.Debug))
this._logger.Log(LogLevel.Error, $"Error occurred while calling the handler => {e.Message}", e);
}
}
}
/// <summary>
/// Connects to a remote endpoint as a WebSocket client
/// </summary>
/// <param name="uri">The address of the remote endpoint to connect to</param>
/// <param name="options">The options</param>
/// <param name="onSuccess">Action to fire when connect successful</param>
/// <param name="onFailure">Action to fire when failed to connect</param>
public void Connect(Uri uri, WebSocketOptions options, Action<ManagedWebSocket> onSuccess = null, Action<Exception> onFailure = null)
=> this.ConnectAsync(uri, options ?? new WebSocketOptions(), onSuccess, onFailure).Run();
/// <summary>
/// Connects to a remote endpoint as a WebSocket client
/// </summary>
/// <param name="uri">The address of the remote endpoint to connect to</param>
/// <param name="subProtocol">The sub-protocol</param>
/// <param name="onSuccess">Action to fire when connect successful</param>
/// <param name="onFailure">Action to fire when failed to connect</param>
public void Connect(Uri uri, string subProtocol = null, Action<ManagedWebSocket> onSuccess = null, Action<Exception> onFailure = null)
=> this.Connect(uri, new WebSocketOptions { SubProtocol = subProtocol }, onSuccess, onFailure);
/// <summary>
/// Connects to a remote endpoint as a WebSocket client
/// </summary>
/// <param name="location">The address of the remote endpoint to connect to</param>
/// <param name="subProtocol">The sub-protocol</param>
/// <param name="onSuccess">Action to fire when connect successful</param>
/// <param name="onFailure">Action to fire when failed to connect</param>
public void Connect(string location, string subProtocol = null, Action<ManagedWebSocket> onSuccess = null, Action<Exception> onFailure = null)
=> this.Connect(new Uri(location), subProtocol, onSuccess, onFailure);
/// <summary>
/// Connects to a remote endpoint as a WebSocket client
/// </summary>
/// <param name="location">The address of the remote endpoint to connect to</param>
/// <param name="onSuccess">Action to fire when connect successful</param>
/// <param name="onFailure">Action to fire when failed to connect</param>
public void Connect(string location, Action<ManagedWebSocket> onSuccess, Action<Exception> onFailure)
=> this.Connect(location, null, onSuccess, onFailure);
#endregion
#region Wrap a WebSocket connection
/// <summary>
/// Wraps a <see cref="System.Net.WebSockets.WebSocket">WebSocket</see> connection of ASP.NET / ASP.NET Core and acts like a <see cref="WebSocket">WebSocket</see> server
/// </summary>
/// <param name="webSocket">The <see cref="System.Net.WebSockets.WebSocket">WebSocket</see> connection of ASP.NET / ASP.NET Core</param>
/// <param name="requestUri">The original request URI of the <see cref="System.Net.WebSockets.WebSocket">WebSocket</see> connection</param>
/// <param name="remoteEndPoint">The remote endpoint of the <see cref="System.Net.WebSockets.WebSocket">WebSocket</see> connection</param>
/// <param name="localEndPoint">The local endpoint of the <see cref="System.Net.WebSockets.WebSocket">WebSocket</see> connection</param>
/// <param name="headers">The collection that presents the headers of the client that made this request to the <see cref="System.Net.WebSockets.WebSocket">WebSocket</see> connection</param>
/// <param name="onSuccess">The action to run when the <see cref="System.Net.WebSockets.WebSocket">WebSocket</see> connection is wrap success</param>
/// <returns>A task that run the receiving process when wrap successful or an exception when failed</returns>
public Task WrapAsync(System.Net.WebSockets.WebSocket webSocket, Uri requestUri, EndPoint remoteEndPoint = null, EndPoint localEndPoint = null, Dictionary<string, string> headers = null, Action<ManagedWebSocket> onSuccess = null)
{
try
{
// create
var websocket = new WebSocketWrapper(webSocket, requestUri, remoteEndPoint, localEndPoint, headers);
this.AddWebSocket(websocket);
if (this._logger.IsEnabled(LogLevel.Trace))
this._logger.Log(LogLevel.Debug, $"Wrap a WebSocket connection [{webSocket.GetType()}] successful ({websocket.ID} @ {websocket.RemoteEndPoint})\r\n- URI: {websocket.RequestUri}\r\n- Headers:\r\n\t{websocket.Headers.ToString("\r\n\t", kvp => $"{kvp.Key}: {kvp.Value}")}");
// callback
try
{
this.ConnectionEstablishedHandler?.Invoke(websocket);
onSuccess?.Invoke(websocket);
}
catch (Exception ex)
{
if (this._logger.IsEnabled(LogLevel.Debug))
this._logger.Log(LogLevel.Error, $"Error occurred while calling the handler => {ex.Message}", ex);
}
// receive messages
return this.ReceiveAsync(websocket);
}
catch (Exception ex)
{
if (this._logger.IsEnabled(LogLevel.Debug))
this._logger.Log(LogLevel.Error, $"Unable to wrap a WebSocket connection [{webSocket.GetType()}]: {ex.Message}", ex);
return Task.FromException(new WrapWebSocketFailedException($"Unable to wrap a WebSocket connection [{webSocket.GetType()}]", ex));
}
}
/// <summary>
/// Wraps a <see cref="System.Net.WebSockets.WebSocket">WebSocket</see> connection of ASP.NET / ASP.NET Core and acts like a <see cref="WebSocket">WebSocket</see> server
/// </summary>
/// <param name="webSocket">The <see cref="System.Net.WebSockets.WebSocket">WebSocket</see> connection of ASP.NET / ASP.NET Core</param>
/// <param name="requestUri">The original request URI of the <see cref="System.Net.WebSockets.WebSocket">WebSocket</see> connection</param>
/// <param name="remoteEndPoint">The remote endpoint of the <see cref="System.Net.WebSockets.WebSocket">WebSocket</see> connection</param>
/// <returns>A task that run the receiving process when wrap successful or an exception when failed</returns>
public Task WrapAsync(System.Net.WebSockets.WebSocket webSocket, Uri requestUri, EndPoint remoteEndPoint)
=> this.WrapAsync(webSocket, requestUri, remoteEndPoint, null, new Dictionary<string, string>(), null);
#endregion
#region Receive messages
void Receive(ManagedWebSocket websocket)
=> this.ReceiveAsync(websocket).Run();
async Task ReceiveAsync(ManagedWebSocket websocket)
{
var buffer = new ArraySegment<byte>(new byte[WebSocketHelper.ReceiveBufferSize]);
while (!this._processingCTS.IsCancellationRequested)
{
// receive message from the WebSocket connection
WebSocketReceiveResult result = null;
try
{
result = await websocket.ReceiveAsync(buffer, this._processingCTS.Token).ConfigureAwait(false);
}
catch (Exception ex)
{
var closeStatus = WebSocketCloseStatus.InternalServerError;
var closeStatusDescription = $"Got an unexpected error: {ex.Message}";
if (ex is OperationCanceledException || ex is TaskCanceledException || ex is ObjectDisposedException || ex is WebSocketException || ex is SocketException || ex is IOException)
{
closeStatus = websocket.IsClient ? WebSocketCloseStatus.NormalClosure : WebSocketCloseStatus.EndpointUnavailable;
closeStatusDescription = websocket.IsClient ? "Disconnected" : "Service is unavailable";
}
await this.CloseWebSocketAsync(websocket, closeStatus, closeStatusDescription).ConfigureAwait(false);
try
{
this.ConnectionBrokenHandler?.Invoke(websocket);
}
catch (Exception e)
{
if (this._logger.IsEnabled(LogLevel.Debug))
this._logger.Log(LogLevel.Error, $"Error occurred while calling the handler => {e.Message}", e);
}
if (ex is OperationCanceledException || ex is TaskCanceledException || ex is ObjectDisposedException || ex is WebSocketException || ex is SocketException || ex is IOException)
{
if (this._logger.IsEnabled(LogLevel.Trace))
this._logger.Log(LogLevel.Debug, $"Stop receiving process when got an error: {ex.Message} ({ex.GetType().GetTypeName(true)})");
}
else
{
if (this._logger.IsEnabled(LogLevel.Debug))
this._logger.Log(LogLevel.Error, closeStatusDescription, ex);
try
{
this.ErrorHandler?.Invoke(websocket, ex);
}
catch (Exception e)
{
if (this._logger.IsEnabled(LogLevel.Debug))
this._logger.Log(LogLevel.Error, $"Error occurred while calling the handler => {e.Message}", e);
}
}
return;
}
// message to close
if (result.MessageType == WebSocketMessageType.Close)
{
if (this._logger.IsEnabled(LogLevel.Trace))
this._logger.Log(LogLevel.Debug, $"The remote endpoint is initiated to close - Status: {result.CloseStatus} - Description: {result.CloseStatusDescription ?? "N/A"} ({websocket.ID} @ {websocket.RemoteEndPoint})");
await this.CloseWebSocketAsync(websocket).ConfigureAwait(false);
try
{
this.ConnectionBrokenHandler?.Invoke(websocket);
}
catch (Exception ex)
{
if (this._logger.IsEnabled(LogLevel.Debug))
this._logger.Log(LogLevel.Error, $"Error occurred while calling the handler => {ex.Message}", ex);
}
return;
}
// exceed buffer size
if (result.Count > WebSocketHelper.ReceiveBufferSize)
{
var message = $"WebSocket frame cannot exceed buffer size of {WebSocketHelper.ReceiveBufferSize:#,##0} bytes";
if (this._logger.IsEnabled(LogLevel.Trace))
this._logger.Log(LogLevel.Debug, $"Close the connection because {message} ({websocket.ID} @ {websocket.RemoteEndPoint})");
await websocket.CloseAsync(WebSocketCloseStatus.MessageTooBig, $"{message}, send multiple frames instead.", CancellationToken.None).ConfigureAwait(false);
await this.CloseWebSocketAsync(websocket).ConfigureAwait(false);
try
{
this.ConnectionBrokenHandler?.Invoke(websocket);
this.ErrorHandler?.Invoke(websocket, new BufferOverflowException(message));
}
catch (Exception ex)
{
if (this._logger.IsEnabled(LogLevel.Debug))
this._logger.Log(LogLevel.Error, $"Error occurred while calling the handler => {ex.Message}", ex);
}
return;
}
// got a message
if (result.Count > 0)
{
if (this._logger.IsEnabled(LogLevel.Trace))
this._logger.Log(LogLevel.Debug, $"A message was received - Type: {result.MessageType} - EoM: {result.EndOfMessage} - Length: {result.Count:#,##0} ({websocket.ID} @ {websocket.RemoteEndPoint})");
try
{
this.MessageReceivedHandler?.Invoke(websocket, result, buffer.Take(result.Count));
}
catch (Exception ex)
{
if (this._logger.IsEnabled(LogLevel.Debug))
this._logger.Log(LogLevel.Error, $"Error occurred while calling the handler => {ex.Message}", ex);
}
}
// wait for next round
if (this.ReceivingAwaitInterval.Ticks > 0)
try
{
await Task.Delay(this.ReceivingAwaitInterval, this._processingCTS.Token).ConfigureAwait(false);
}
catch
{
await this.CloseWebSocketAsync(websocket, websocket.IsClient ? WebSocketCloseStatus.NormalClosure : WebSocketCloseStatus.EndpointUnavailable, websocket.IsClient ? "Disconnected" : "Service is unavailable").ConfigureAwait(false);
try
{