forked from fpanettieri/unity-socket.io-DEPRECATED
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathWebSocket.cs
More file actions
2188 lines (1867 loc) · 63.6 KB
/
Copy pathWebSocket.cs
File metadata and controls
2188 lines (1867 loc) · 63.6 KB
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 License
/*
* WebSocket.cs
*
* A C# implementation of the WebSocket interface.
*
* This code is derived from WebSocket.java
* (http://github.com/adamac/Java-WebSocket-client).
*
* The MIT License
*
* Copyright (c) 2009 Adam MacBeth
* Copyright (c) 2010-2014 sta.blockhead
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
#endregion
using System;
using System.Collections;
using System.Collections.Generic;
using System.Collections.Specialized;
using System.Diagnostics;
using System.IO;
using System.Net.Sockets;
using System.Net.Security;
using System.Security.Cryptography;
using System.Text;
using System.Threading;
using WebSocketSharp.Net;
using WebSocketSharp.Net.WebSockets;
namespace WebSocketSharp
{
/// <summary>
/// Implements the WebSocket interface.
/// </summary>
/// <remarks>
/// The WebSocket class provides a set of methods and properties for two-way communication using
/// the WebSocket protocol (<see href="http://tools.ietf.org/html/rfc6455">RFC 6455</see>).
/// </remarks>
public class WebSocket : IDisposable
{
#region Private Const Fields
private const string _guid = "258EAFA5-E914-47DA-95CA-C5AB0DC85B11";
private const string _version = "13";
#endregion
#region Private Fields
private AuthenticationChallenge _authChallenge;
private string _base64Key;
private RemoteCertificateValidationCallback
_certValidationCallback;
private bool _client;
private Action _closeContext;
private CompressionMethod _compression;
private WebSocketContext _context;
private CookieCollection _cookies;
private NetworkCredential _credentials;
private string _extensions;
private AutoResetEvent _exitReceiving;
private object _forConn;
private object _forEvent;
private object _forMessageEventQueue;
private object _forSend;
private Func<WebSocketContext, string>
_handshakeRequestChecker;
private volatile Logger _logger;
private Queue<MessageEventArgs> _messageEventQueue;
private uint _nonceCount;
private string _origin;
private NameValueCollection _customHeaders;
private bool _preAuth;
private string _protocol;
private string [] _protocols;
private volatile WebSocketState _readyState;
private AutoResetEvent _receivePong;
private bool _secure;
private WebSocketStream _stream;
private TcpClient _tcpClient;
private Uri _uri;
#endregion
#region Internal Const Fields
internal const int FragmentLength = 1016; // Max value is int.MaxValue - 14.
#endregion
#region Internal Constructors
// As server
internal WebSocket (HttpListenerWebSocketContext context, string protocol, Logger logger)
{
_context = context;
_protocol = protocol;
_logger = logger;
_closeContext = context.Close;
_secure = context.IsSecureConnection;
_stream = context.Stream;
init ();
}
// As server
internal WebSocket (TcpListenerWebSocketContext context, string protocol, Logger logger)
{
_context = context;
_protocol = protocol;
_logger = logger;
_closeContext = context.Close;
_secure = context.IsSecureConnection;
_stream = context.Stream;
init ();
}
#endregion
#region Public Constructors
/// <summary>
/// Initializes a new instance of the <see cref="WebSocket"/> class with the specified
/// WebSocket URL and subprotocols.
/// </summary>
/// <param name="url">
/// A <see cref="string"/> that represents the WebSocket URL to connect.
/// </param>
/// <param name="protocols">
/// An array of <see cref="string"/> that contains the WebSocket subprotocols if any.
/// Each value of <paramref name="protocols"/> must be a token defined in
/// <see href="http://tools.ietf.org/html/rfc2616#section-2.2">RFC 2616</see>.
/// </param>
/// <exception cref="ArgumentException">
/// <para>
/// <paramref name="url"/> is invalid.
/// </para>
/// <para>
/// -or-
/// </para>
/// <para>
/// <paramref name="protocols"/> is invalid.
/// </para>
/// </exception>
/// <exception cref="ArgumentNullException">
/// <paramref name="url"/> is <see langword="null"/>.
/// </exception>
public WebSocket (string url, params string [] protocols)
{
if (url == null)
throw new ArgumentNullException ("url");
string msg;
if (!url.TryCreateWebSocketUri (out _uri, out msg))
throw new ArgumentException (msg, "url");
if (protocols != null && protocols.Length > 0) {
msg = protocols.CheckIfValidProtocols ();
if (msg != null)
throw new ArgumentException (msg, "protocols");
_protocols = protocols;
}
_base64Key = CreateBase64Key ();
_client = true;
_logger = new Logger ();
_secure = _uri.Scheme == "wss";
init ();
}
#endregion
#region Internal Properties
internal CookieCollection CookieCollection {
get {
return _cookies;
}
}
// As server
internal Func<WebSocketContext, string> CustomHandshakeRequestChecker {
get {
return _handshakeRequestChecker ?? (context => null);
}
set {
_handshakeRequestChecker = value;
}
}
internal bool IsConnected {
get {
return _readyState == WebSocketState.Open || _readyState == WebSocketState.Closing;
}
}
#endregion
#region Public Properties
/// <summary>
/// Gets or sets the compression method used to compress the message on the WebSocket
/// connection.
/// </summary>
/// <value>
/// One of the <see cref="CompressionMethod"/> enum values, indicates the compression method
/// used to compress the message. The default value is <see cref="CompressionMethod.None"/>.
/// </value>
public CompressionMethod Compression {
get {
return _compression;
}
set {
lock (_forConn) {
var msg = checkIfAvailable ("Set operation of Compression", false, false);
if (msg != null) {
_logger.Error (msg);
error (msg);
return;
}
_compression = value;
}
}
}
/// <summary>
/// Gets the HTTP cookies included in the WebSocket connection request and response.
/// </summary>
/// <value>
/// An IEnumerable<Cookie> instance that provides an enumerator which supports the
/// iteration over the collection of the cookies.
/// </value>
public IEnumerable<Cookie> Cookies {
get {
lock (_cookies.SyncRoot) {
foreach (Cookie cookie in _cookies)
yield return cookie;
}
}
}
/// <summary>
/// Gets the credentials for the HTTP authentication (Basic/Digest).
/// </summary>
/// <value>
/// A <see cref="NetworkCredential"/> that represents the credentials for the HTTP
/// authentication. The default value is <see langword="null"/>.
/// </value>
public NetworkCredential Credentials {
get {
return _credentials;
}
}
/// <summary>
/// Gets the WebSocket extensions selected by the server.
/// </summary>
/// <value>
/// A <see cref="string"/> that represents the extensions if any. The default value is
/// <see cref="String.Empty"/>.
/// </value>
public string Extensions {
get {
return _extensions ?? String.Empty;
}
}
/// <summary>
/// Gets a value indicating whether the WebSocket connection is alive.
/// </summary>
/// <value>
/// <c>true</c> if the connection is alive; otherwise, <c>false</c>.
/// </value>
public bool IsAlive {
get {
return Ping ();
}
}
/// <summary>
/// Gets a value indicating whether the WebSocket connection is secure.
/// </summary>
/// <value>
/// <c>true</c> if the connection is secure; otherwise, <c>false</c>.
/// </value>
public bool IsSecure {
get {
return _secure;
}
}
/// <summary>
/// Gets the logging functions.
/// </summary>
/// <remarks>
/// The default logging level is <see cref="LogLevel.Error"/>. If you would like to change it,
/// you should set the <c>Log.Level</c> property to any of the <see cref="LogLevel"/> enum
/// values.
/// </remarks>
/// <value>
/// A <see cref="Logger"/> that provides the logging functions.
/// </value>
public Logger Log {
get {
return _logger;
}
internal set {
_logger = value;
}
}
/// <summary>
/// Gets or sets the value of the Origin header to send with the WebSocket connection request
/// to the server.
/// </summary>
/// <remarks>
/// The <see cref="WebSocket"/> sends the Origin header if this property has any.
/// </remarks>
/// <value>
/// <para>
/// A <see cref="string"/> that represents the value of the
/// <see href="http://tools.ietf.org/html/rfc6454#section-7">HTTP Origin
/// header</see> to send. The default value is <see langword="null"/>.
/// </para>
/// <para>
/// The Origin header has the following syntax:
/// <c><scheme>://<host>[:<port>]</c>
/// </para>
/// </value>
public string Origin {
get {
return _origin;
}
set {
lock (_forConn) {
var msg = checkIfAvailable ("Set operation of Origin", false, false);
if (msg == null) {
if (value.IsNullOrEmpty ()) {
_origin = value;
return;
}
Uri origin;
if (!Uri.TryCreate (value, UriKind.Absolute, out origin) || origin.Segments.Length > 1)
msg = "The syntax of Origin must be '<scheme>://<host>[:<port>]'.";
}
if (msg != null) {
_logger.Error (msg);
error (msg);
return;
}
_origin = value.TrimEnd ('/');
}
}
}
/// <summary>
/// Gets the WebSocket subprotocol selected by the server.
/// </summary>
/// <value>
/// A <see cref="string"/> that represents the subprotocol if any. The default value is
/// <see cref="String.Empty"/>.
/// </value>
public string Protocol {
get {
return _protocol ?? String.Empty;
}
internal set {
_protocol = value;
}
}
/// <summary>
/// Gets the state of the WebSocket connection.
/// </summary>
/// <value>
/// One of the <see cref="WebSocketState"/> enum values, indicates the state of the WebSocket
/// connection. The default value is <see cref="WebSocketState.Connecting"/>.
/// </value>
public WebSocketState ReadyState {
get {
return _readyState;
}
}
/// <summary>
/// Gets or sets the callback used to validate the certificate supplied by the server.
/// </summary>
/// <remarks>
/// If the value of this property is <see langword="null"/>, the validation does nothing with
/// the server certificate, always returns valid.
/// </remarks>
/// <value>
/// A <see cref="RemoteCertificateValidationCallback"/> delegate that references the method(s)
/// used to validate the server certificate. The default value is <see langword="null"/>.
/// </value>
public RemoteCertificateValidationCallback ServerCertificateValidationCallback {
get {
return _certValidationCallback;
}
set {
lock (_forConn) {
var msg = checkIfAvailable (
"Set operation of ServerCertificateValidationCallback", false, false);
if (msg != null) {
_logger.Error (msg);
error (msg);
return;
}
_certValidationCallback = value;
}
}
}
/// <summary>
/// Gets the WebSocket URL to connect.
/// </summary>
/// <value>
/// A <see cref="Uri"/> that represents the WebSocket URL to connect.
/// </value>
public Uri Url {
get {
return _client
? _uri
: _context.RequestUri;
}
}
#endregion
#region Public Events
/// <summary>
/// Occurs when the WebSocket connection has been closed.
/// </summary>
public event EventHandler<CloseEventArgs> OnClose;
/// <summary>
/// Occurs when the <see cref="WebSocket"/> gets an error.
/// </summary>
public event EventHandler<ErrorEventArgs> OnError;
/// <summary>
/// Occurs when the <see cref="WebSocket"/> receives a message.
/// </summary>
public event EventHandler<MessageEventArgs> OnMessage;
/// <summary>
/// Occurs when the WebSocket connection has been established.
/// </summary>
public event EventHandler OnOpen;
#endregion
#region Private Methods
private bool acceptCloseFrame (WebSocketFrame frame)
{
var payload = frame.PayloadData;
close (payload, !payload.ContainsReservedCloseStatusCode, false);
return false;
}
private bool acceptDataFrame (WebSocketFrame frame)
{
var e = frame.IsCompressed
? new MessageEventArgs (
frame.Opcode, frame.PayloadData.ApplicationData.Decompress (_compression))
: new MessageEventArgs (frame.Opcode, frame.PayloadData);
enqueueToMessageEventQueue (e);
return true;
}
private void acceptException (Exception exception, string message)
{
var code = CloseStatusCode.Abnormal;
var reason = message;
if (exception is WebSocketException) {
var wsex = (WebSocketException) exception;
code = wsex.Code;
reason = wsex.Message;
}
if (code == CloseStatusCode.Abnormal || code == CloseStatusCode.TlsHandshakeFailure)
_logger.Fatal (exception.ToString ());
else
_logger.Error (reason);
error (message ?? code.GetMessage ());
if (_readyState == WebSocketState.Connecting && !_client)
Close (HttpStatusCode.BadRequest);
else
close (code, reason ?? code.GetMessage (), false);
}
private bool acceptFragmentedFrame (WebSocketFrame frame)
{
return frame.IsContinuation // Not first fragment
? true
: acceptFragments (frame);
}
private bool acceptFragments (WebSocketFrame first)
{
using (var concatenated = new MemoryStream ()) {
concatenated.WriteBytes (first.PayloadData.ApplicationData);
if (!concatenateFragmentsInto (concatenated))
return false;
byte [] data;
if (_compression != CompressionMethod.None) {
data = concatenated.DecompressToArray (_compression);
}
else {
concatenated.Close ();
data = concatenated.ToArray ();
}
enqueueToMessageEventQueue (new MessageEventArgs (first.Opcode, data));
return true;
}
}
private bool acceptFrame (WebSocketFrame frame)
{
return frame.IsCompressed && _compression == CompressionMethod.None
? acceptUnsupportedFrame (
frame,
CloseStatusCode.IncorrectData,
"A compressed data has been received without available decompression method.")
: frame.IsFragmented
? acceptFragmentedFrame (frame)
: frame.IsData
? acceptDataFrame (frame)
: frame.IsPing
? acceptPingFrame (frame)
: frame.IsPong
? acceptPongFrame (frame)
: frame.IsClose
? acceptCloseFrame (frame)
: acceptUnsupportedFrame (frame, CloseStatusCode.PolicyViolation, null);
}
// As server
private bool acceptHandshake ()
{
_logger.Debug (
String.Format (
"A WebSocket connection request from {0}:\n{1}", _context.UserEndPoint, _context));
var msg = checkIfValidHandshakeRequest (_context);
if (msg != null) {
_logger.Error (msg);
error ("An error has occurred while connecting.");
Close (HttpStatusCode.BadRequest);
return false;
}
if (_protocol != null &&
!_context.SecWebSocketProtocols.Contains (protocol => protocol == _protocol))
_protocol = null;
var extensions = _context.Headers ["Sec-WebSocket-Extensions"];
if (extensions != null && extensions.Length > 0)
acceptSecWebSocketExtensionsHeader (extensions);
return send (createHandshakeResponse ());
}
private bool acceptPingFrame (WebSocketFrame frame)
{
var mask = _client ? Mask.Mask : Mask.Unmask;
if (send (WebSocketFrame.CreatePongFrame (mask, frame.PayloadData)))
_logger.Trace ("Returned a Pong.");
return true;
}
private bool acceptPongFrame (WebSocketFrame frame)
{
_receivePong.Set ();
_logger.Trace ("Received a Pong.");
return true;
}
// As server
private void acceptSecWebSocketExtensionsHeader (string value)
{
var extensions = new StringBuilder (32);
var compress = false;
foreach (var extension in value.SplitHeaderValue (',')) {
var trimed = extension.Trim ();
var unprefixed = trimed.RemovePrefix ("x-webkit-");
if (!compress && unprefixed.IsCompressionExtension ()) {
var method = unprefixed.ToCompressionMethod ();
if (method != CompressionMethod.None) {
_compression = method;
compress = true;
extensions.Append (trimed + ", ");
}
}
}
var len = extensions.Length;
if (len > 0) {
extensions.Length = len - 2;
_extensions = extensions.ToString ();
}
}
private bool acceptUnsupportedFrame (WebSocketFrame frame, CloseStatusCode code, string reason)
{
_logger.Debug ("Unsupported frame:\n" + frame.PrintToString (false));
acceptException (new WebSocketException (code, reason), null);
return false;
}
private string checkIfAvailable (
string operation, bool availableAsServer, bool availableAsConnected)
{
return !_client && !availableAsServer
? operation + " isn't available as a server."
: !availableAsConnected
? _readyState.CheckIfConnectable ()
: null;
}
private string checkIfCanConnect ()
{
return !_client && _readyState == WebSocketState.Closed
? "Connect isn't available to reconnect as a server."
: _readyState.CheckIfConnectable ();
}
// As server
private string checkIfValidHandshakeRequest (WebSocketContext context)
{
var headers = context.Headers;
return context.RequestUri == null
? "Invalid request url."
: !context.IsWebSocketRequest
? "Not WebSocket connection request."
: !validateSecWebSocketKeyHeader (headers ["Sec-WebSocket-Key"])
? "Invalid Sec-WebSocket-Key header."
: !validateSecWebSocketVersionClientHeader (headers ["Sec-WebSocket-Version"])
? "Invalid Sec-WebSocket-Version header."
: CustomHandshakeRequestChecker (context);
}
// As client
private string checkIfValidHandshakeResponse (HandshakeResponse response)
{
var headers = response.Headers;
return response.IsUnauthorized
? String.Format ("HTTP {0} authorization is required.", response.AuthChallenge.Scheme)
: !response.IsWebSocketResponse
? "Not WebSocket connection response."
: !validateSecWebSocketAcceptHeader (headers ["Sec-WebSocket-Accept"])
? "Invalid Sec-WebSocket-Accept header."
: !validateSecWebSocketProtocolHeader (headers ["Sec-WebSocket-Protocol"])
? "Invalid Sec-WebSocket-Protocol header."
: !validateSecWebSocketExtensionsHeader (headers ["Sec-WebSocket-Extensions"])
? "Invalid Sec-WebSocket-Extensions header."
: !validateSecWebSocketVersionServerHeader (headers ["Sec-WebSocket-Version"])
? "Invalid Sec-WebSocket-Version header."
: null;
}
private void close (CloseStatusCode code, string reason, bool wait)
{
close (new PayloadData (((ushort) code).Append (reason)), !code.IsReserved (), wait);
}
private void close (PayloadData payload, bool send, bool wait)
{
lock (_forConn) {
if (_readyState == WebSocketState.Closing || _readyState == WebSocketState.Closed) {
_logger.Info ("Closing the WebSocket connection has already been done.");
return;
}
_readyState = WebSocketState.Closing;
}
_logger.Trace ("Start closing handshake.");
var e = new CloseEventArgs (payload);
e.WasClean =
_client
? closeHandshake (
send ? WebSocketFrame.CreateCloseFrame (Mask.Mask, payload).ToByteArray () : null,
wait ? 5000 : 0,
closeClientResources)
: closeHandshake (
send ? WebSocketFrame.CreateCloseFrame (Mask.Unmask, payload).ToByteArray () : null,
wait ? 1000 : 0,
closeServerResources);
_logger.Trace ("End closing handshake.");
_readyState = WebSocketState.Closed;
try {
OnClose.Emit (this, e);
}
catch (Exception ex) {
_logger.Fatal (ex.ToString ());
error ("An exception has occurred while OnClose.");
}
}
private void closeAsync (PayloadData payload, bool send, bool wait)
{
Action<PayloadData, bool, bool> closer = close;
closer.BeginInvoke (payload, send, wait, ar => closer.EndInvoke (ar), null);
}
// As client
private void closeClientResources ()
{
if (_stream != null) {
_stream.Dispose ();
_stream = null;
}
if (_tcpClient != null) {
_tcpClient.Close ();
_tcpClient = null;
}
}
private bool closeHandshake (byte [] frame, int timeout, Action release)
{
var sent = frame != null && _stream.Write (frame);
var received = timeout == 0 ||
(sent && _exitReceiving != null && _exitReceiving.WaitOne (timeout));
release ();
if (_receivePong != null) {
_receivePong.Close ();
_receivePong = null;
}
if (_exitReceiving != null) {
_exitReceiving.Close ();
_exitReceiving = null;
}
var result = sent && received;
_logger.Debug (
String.Format ("Was clean?: {0}\nsent: {1} received: {2}", result, sent, received));
return result;
}
// As server
private void closeServerResources ()
{
if (_closeContext == null)
return;
_closeContext ();
_closeContext = null;
_stream = null;
_context = null;
}
private bool concatenateFragmentsInto (Stream dest)
{
while (true) {
var frame = _stream.ReadFrame ();
if (frame.IsFinal) {
// FINAL
// CONT
if (frame.IsContinuation) {
dest.WriteBytes (frame.PayloadData.ApplicationData);
break;
}
// PING
if (frame.IsPing) {
acceptPingFrame (frame);
continue;
}
// PONG
if (frame.IsPong) {
acceptPongFrame (frame);
continue;
}
// CLOSE
if (frame.IsClose)
return acceptCloseFrame (frame);
}
else {
// MORE
// CONT
if (frame.IsContinuation) {
dest.WriteBytes (frame.PayloadData.ApplicationData);
continue;
}
}
// ?
return acceptUnsupportedFrame (
frame,
CloseStatusCode.IncorrectData,
"An incorrect data has been received while receiving fragmented data.");
}
return true;
}
private bool connect ()
{
lock (_forConn) {
var msg = _readyState.CheckIfConnectable ();
if (msg != null) {
_logger.Error (msg);
error (msg);
return false;
}
try {
if (_client ? doHandshake () : acceptHandshake ()) {
_readyState = WebSocketState.Open;
return true;
}
}
catch (Exception ex) {
acceptException (ex, "An exception has occurred while connecting.");
}
return false;
}
}
// As client
private string createExtensionsRequest ()
{
var extensions = new StringBuilder (32);
if (_compression != CompressionMethod.None)
extensions.Append (_compression.ToExtensionString ());
return extensions.Length > 0
? extensions.ToString ()
: null;
}
// As client
private HandshakeRequest createHandshakeRequest ()
{
var path = _uri.PathAndQuery;
var host = _uri.Port == 80 ? _uri.DnsSafeHost : _uri.Authority;
var req = new HandshakeRequest (path);
var headers = req.Headers;
headers ["Host"] = host;
if (!_origin.IsNullOrEmpty ())
headers ["Origin"] = _origin;
headers ["Sec-WebSocket-Key"] = _base64Key;
if (_protocols != null)
headers ["Sec-WebSocket-Protocol"] = _protocols.ToString (", ");
var extensions = createExtensionsRequest ();
if (extensions != null)
headers ["Sec-WebSocket-Extensions"] = extensions;
headers ["Sec-WebSocket-Version"] = _version;
AuthenticationResponse authRes = null;
if (_authChallenge != null && _credentials != null) {
authRes = new AuthenticationResponse (_authChallenge, _credentials, _nonceCount);
_nonceCount = authRes.NonceCount;
}
else if (_preAuth)
authRes = new AuthenticationResponse (_credentials);
if (authRes != null)
headers ["Authorization"] = authRes.ToString ();
// add custom headers
if (_customHeaders != null) {
headers.Add(_customHeaders);
}
if (_cookies.Count > 0)
req.SetCookies (_cookies);
return req;
}
// As server
private HandshakeResponse createHandshakeResponse ()
{
var res = new HandshakeResponse (HttpStatusCode.SwitchingProtocols);
var headers = res.Headers;
headers ["Sec-WebSocket-Accept"] = CreateResponseKey (_base64Key);
if (_protocol != null)
headers ["Sec-WebSocket-Protocol"] = _protocol;
if (_extensions != null)
headers ["Sec-WebSocket-Extensions"] = _extensions;
if (_cookies.Count > 0)
res.SetCookies (_cookies);
return res;
}
// As server
private HandshakeResponse createHandshakeResponse (HttpStatusCode code)
{
var res = HandshakeResponse.CreateCloseResponse (code);
res.Headers ["Sec-WebSocket-Version"] = _version;
return res;
}
private MessageEventArgs dequeueFromMessageEventQueue ()
{
lock (_forMessageEventQueue)
return _messageEventQueue.Count > 0
? _messageEventQueue.Dequeue ()
: null;
}
// As client
private bool doHandshake ()
{
setClientStream ();
var res = sendHandshakeRequest ();
var msg = checkIfValidHandshakeResponse (res);
if (msg != null) {
_logger.Error (msg);
msg = "An error has occurred while connecting.";
error (msg);
close (CloseStatusCode.Abnormal, msg, false);
return false;
}