-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathManagedWebSocket.cs
1605 lines (1430 loc) · 80.8 KB
/
ManagedWebSocket.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
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
#nullable enable
using System.Buffers;
using System.Diagnostics;
using System.IO;
using System.Numerics;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Security.Cryptography;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
namespace System.Net.WebSockets
{
/// <summary>A managed implementation of a web socket that sends and receives data via a <see cref="Stream"/>.</summary>
/// <remarks>
/// Thread-safety:
/// - It's acceptable to call ReceiveAsync and SendAsync in parallel. One of each may run concurrently.
/// - It's acceptable to have a pending ReceiveAsync while CloseOutputAsync or CloseAsync is called.
/// - Attempting to invoke any other operations in parallel may corrupt the instance. Attempting to invoke
/// a send operation while another is in progress or a receive operation while another is in progress will
/// result in an exception.
/// </remarks>
internal sealed partial class ManagedWebSocket : WebSocket
{
/// <summary>Creates a <see cref="ManagedWebSocket"/> from a <see cref="Stream"/> connected to a websocket endpoint.</summary>
/// <param name="stream">The connected Stream.</param>
/// <param name="isServer">true if this is the server-side of the connection; false if this is the client-side of the connection.</param>
/// <param name="subprotocol">The agreed upon subprotocol for the connection.</param>
/// <param name="keepAliveInterval">The interval to use for keep-alive pings.</param>
/// <returns>The created <see cref="ManagedWebSocket"/> instance.</returns>
public static ManagedWebSocket CreateFromConnectedStream(
Stream stream, bool isServer, string? subprotocol, TimeSpan keepAliveInterval)
{
return new ManagedWebSocket(stream, isServer, subprotocol, keepAliveInterval);
}
/// <summary>Thread-safe random number generator used to generate masks for each send.</summary>
private static readonly RandomNumberGenerator s_random = RandomNumberGenerator.Create();
/// <summary>Encoding for the payload of text messages: UTF8 encoding that throws if invalid bytes are discovered, per the RFC.</summary>
private static readonly UTF8Encoding s_textEncoding = new UTF8Encoding(encoderShouldEmitUTF8Identifier: false, throwOnInvalidBytes: true);
/// <summary>Valid states to be in when calling SendAsync.</summary>
private static readonly WebSocketState[] s_validSendStates = { WebSocketState.Open, WebSocketState.CloseReceived };
/// <summary>Valid states to be in when calling ReceiveAsync.</summary>
private static readonly WebSocketState[] s_validReceiveStates = { WebSocketState.Open, WebSocketState.CloseSent };
/// <summary>Valid states to be in when calling CloseOutputAsync.</summary>
private static readonly WebSocketState[] s_validCloseOutputStates = { WebSocketState.Open, WebSocketState.CloseReceived };
/// <summary>Valid states to be in when calling CloseAsync.</summary>
private static readonly WebSocketState[] s_validCloseStates = { WebSocketState.Open, WebSocketState.CloseReceived, WebSocketState.CloseSent };
#pragma warning disable CA1823 // not used by System.Net.WebSockets.WebSocketProtocol.dll
/// <summary>Successfully completed task representing a close message.</summary>
private static readonly Task<WebSocketReceiveResult> s_cachedCloseTask = Task.FromResult(new WebSocketReceiveResult(0, WebSocketMessageType.Close, true));
#pragma warning restore CA1823
/// <summary>The maximum size in bytes of a message frame header that includes mask bytes.</summary>
internal const int MaxMessageHeaderLength = 14;
/// <summary>The maximum size of a control message payload.</summary>
private const int MaxControlPayloadLength = 125;
/// <summary>Length of the mask XOR'd with the payload data.</summary>
private const int MaskLength = 4;
/// <summary>The stream used to communicate with the remote server.</summary>
private readonly Stream _stream;
/// <summary>
/// true if this is the server-side of the connection; false if it's client.
/// This impacts masking behavior: clients always mask payloads they send and
/// expect to always receive unmasked payloads, whereas servers always send
/// unmasked payloads and expect to always receive masked payloads.
/// </summary>
private readonly bool _isServer;
/// <summary>The agreed upon subprotocol with the server.</summary>
private readonly string? _subprotocol;
/// <summary>Timer used to send periodic pings to the server, at the interval specified</summary>
private readonly Timer? _keepAliveTimer;
/// <summary>CancellationTokenSource used to abort all current and future operations when anything is canceled or any error occurs.</summary>
private readonly CancellationTokenSource _abortSource = new CancellationTokenSource();
/// <summary>Buffer used for reading data from the network.</summary>
private readonly Memory<byte> _receiveBuffer;
/// <summary>
/// Tracks the state of the validity of the UTF8 encoding of text payloads. Text may be split across fragments.
/// </summary>
private readonly Utf8MessageState _utf8TextState = new Utf8MessageState();
/// <summary>
/// Semaphore used to ensure that calls to SendFrameAsync don't run concurrently.
/// </summary>
private readonly SemaphoreSlim _sendFrameAsyncLock = new SemaphoreSlim(1, 1);
// We maintain the current WebSocketState in _state. However, we separately maintain _sentCloseFrame and _receivedCloseFrame
// as there isn't a strict ordering between CloseSent and CloseReceived. If we receive a close frame from the server, we need to
// transition to CloseReceived even if we're currently in CloseSent, and if we send a close frame, we need to transition to
// CloseSent even if we're currently in CloseReceived.
/// <summary>The current state of the web socket in the protocol.</summary>
private WebSocketState _state = WebSocketState.Open;
/// <summary>true if Dispose has been called; otherwise, false.</summary>
private bool _disposed;
/// <summary>Whether we've ever sent a close frame.</summary>
private bool _sentCloseFrame;
/// <summary>Whether we've ever received a close frame.</summary>
private bool _receivedCloseFrame;
/// <summary>The reason for the close, as sent by the server, or null if not yet closed.</summary>
private WebSocketCloseStatus? _closeStatus;
/// <summary>A description of the close reason as sent by the server, or null if not yet closed.</summary>
private string? _closeStatusDescription;
/// <summary>
/// The last header received in a ReceiveAsync. If ReceiveAsync got a header but then
/// returned fewer bytes than was indicated in the header, subsequent ReceiveAsync calls
/// will use the data from the header to construct the subsequent receive results, and
/// the payload length in this header will be decremented to indicate the number of bytes
/// remaining to be received for that header. As a result, between fragments, the payload
/// length in this header should be 0.
/// </summary>
private MessageHeader _lastReceiveHeader = new MessageHeader { Opcode = MessageOpcode.Text, Fin = true };
/// <summary>The offset of the next available byte in the _receiveBuffer.</summary>
private int _receiveBufferOffset;
/// <summary>The number of bytes available in the _receiveBuffer.</summary>
private int _receiveBufferCount;
/// <summary>
/// When dealing with partially read fragments of binary/text messages, a mask previously received may still
/// apply, and the first new byte received may not correspond to the 0th position in the mask. This value is
/// the next offset into the mask that should be applied.
/// </summary>
private int _receivedMaskOffsetOffset;
/// <summary>
/// Temporary send buffer. This should be released back to the ArrayPool once it's
/// no longer needed for the current send operation. It is stored as an instance
/// field to minimize needing to pass it around and to avoid it becoming a field on
/// various async state machine objects.
/// </summary>
private byte[]? _sendBuffer;
/// <summary>
/// Whether the last SendAsync had endOfMessage==false. We need to track this so that we
/// can send the subsequent message with a continuation opcode if the last message was a fragment.
/// </summary>
private bool _lastSendWasFragment;
/// <summary>
/// The task returned from the last ReceiveAsync(ArraySegment, ...) operation to not complete synchronously.
/// If this is not null and not completed when a subsequent ReceiveAsync is issued, an exception occurs.
/// </summary>
private Task _lastReceiveAsync = Task.CompletedTask;
/// <summary>Lock used to protect update and check-and-update operations on _state.</summary>
private object StateUpdateLock => _abortSource;
/// <summary>
/// We need to coordinate between receives and close operations happening concurrently, as a ReceiveAsync may
/// be pending while a Close{Output}Async is issued, which itself needs to loop until a close frame is received.
/// As such, we need thread-safety in the management of <see cref="_lastReceiveAsync"/>.
/// </summary>
private object ReceiveAsyncLock => _utf8TextState; // some object, as we're simply lock'ing on it
/// <summary>Initializes the websocket.</summary>
/// <param name="stream">The connected Stream.</param>
/// <param name="isServer">true if this is the server-side of the connection; false if this is the client-side of the connection.</param>
/// <param name="subprotocol">The agreed upon subprotocol for the connection.</param>
/// <param name="keepAliveInterval">The interval to use for keep-alive pings.</param>
private ManagedWebSocket(Stream stream, bool isServer, string? subprotocol, TimeSpan keepAliveInterval)
{
Debug.Assert(StateUpdateLock != null, $"Expected {nameof(StateUpdateLock)} to be non-null");
Debug.Assert(ReceiveAsyncLock != null, $"Expected {nameof(ReceiveAsyncLock)} to be non-null");
Debug.Assert(StateUpdateLock != ReceiveAsyncLock, "Locks should be different objects");
Debug.Assert(stream != null, $"Expected non-null stream");
Debug.Assert(stream.CanRead, $"Expected readable stream");
Debug.Assert(stream.CanWrite, $"Expected writeable stream");
Debug.Assert(keepAliveInterval == Timeout.InfiniteTimeSpan || keepAliveInterval >= TimeSpan.Zero, $"Invalid keepalive interval: {keepAliveInterval}");
_stream = stream;
_isServer = isServer;
_subprotocol = subprotocol;
// Create a buffer just large enough to handle received packet headers (at most 14 bytes) and
// control payloads (at most 125 bytes). Message payloads are read directly into the buffer
// supplied to ReceiveAsync.
const int ReceiveBufferMinLength = MaxControlPayloadLength;
_receiveBuffer = new byte[ReceiveBufferMinLength];
// Set up the abort source so that if it's triggered, we transition the instance appropriately.
// There's no need to store the resulting CancellationTokenRegistration, as this instance owns
// the CancellationTokenSource, and the lifetime of that CTS matches the lifetime of the registration.
_abortSource.Token.UnsafeRegister(static s =>
{
var thisRef = (ManagedWebSocket)s!;
lock (thisRef.StateUpdateLock)
{
WebSocketState state = thisRef._state;
if (state != WebSocketState.Closed && state != WebSocketState.Aborted)
{
thisRef._state = state != WebSocketState.None && state != WebSocketState.Connecting ?
WebSocketState.Aborted :
WebSocketState.Closed;
}
}
}, this);
// Now that we're opened, initiate the keep alive timer to send periodic pings.
// We use a weak reference from the timer to the web socket to avoid a cycle
// that could keep the web socket rooted in erroneous cases.
if (keepAliveInterval > TimeSpan.Zero)
{
_keepAliveTimer = new Timer(static s =>
{
var wr = (WeakReference<ManagedWebSocket>)s!;
if (wr.TryGetTarget(out ManagedWebSocket? thisRef))
{
thisRef.SendKeepAliveFrameAsync();
}
}, new WeakReference<ManagedWebSocket>(this), keepAliveInterval, keepAliveInterval);
}
}
public override void Dispose()
{
lock (StateUpdateLock)
{
DisposeCore();
}
}
private void DisposeCore()
{
Debug.Assert(Monitor.IsEntered(StateUpdateLock), $"Expected {nameof(StateUpdateLock)} to be held");
if (!_disposed)
{
_disposed = true;
_keepAliveTimer?.Dispose();
_stream?.Dispose();
if (_state < WebSocketState.Aborted)
{
_state = WebSocketState.Closed;
}
}
}
public override WebSocketCloseStatus? CloseStatus => _closeStatus;
public override string? CloseStatusDescription => _closeStatusDescription;
public override WebSocketState State => _state;
public override string? SubProtocol => _subprotocol;
public override Task SendAsync(ArraySegment<byte> buffer, WebSocketMessageType messageType, bool endOfMessage, CancellationToken cancellationToken)
{
if (messageType != WebSocketMessageType.Text && messageType != WebSocketMessageType.Binary)
{
throw new ArgumentException("",
nameof(messageType));
}
WebSocketValidate.ValidateArraySegment(buffer, nameof(buffer));
return SendPrivateAsync(buffer, messageType, endOfMessage, cancellationToken).AsTask();
}
private ValueTask SendPrivateAsync(ReadOnlyMemory<byte> buffer, WebSocketMessageType messageType, bool endOfMessage, CancellationToken cancellationToken)
{
if (messageType != WebSocketMessageType.Text && messageType != WebSocketMessageType.Binary)
{
throw new ArgumentException();
}
try
{
WebSocketValidate.ThrowIfInvalidState(_state, _disposed, s_validSendStates);
}
catch (Exception exc)
{
return new ValueTask(Task.FromException(exc));
}
MessageOpcode opcode =
_lastSendWasFragment ? MessageOpcode.Continuation :
messageType == WebSocketMessageType.Binary ? MessageOpcode.Binary :
MessageOpcode.Text;
ValueTask t = SendFrameAsync(opcode, endOfMessage, buffer, cancellationToken);
_lastSendWasFragment = !endOfMessage;
return t;
}
public override Task<WebSocketReceiveResult> ReceiveAsync(ArraySegment<byte> buffer, CancellationToken cancellationToken)
{
WebSocketValidate.ValidateArraySegment(buffer, nameof(buffer));
try
{
WebSocketValidate.ThrowIfInvalidState(_state, _disposed, s_validReceiveStates);
Debug.Assert(!Monitor.IsEntered(StateUpdateLock), $"{nameof(StateUpdateLock)} must never be held when acquiring {nameof(ReceiveAsyncLock)}");
lock (ReceiveAsyncLock) // synchronize with receives in CloseAsync
{
ThrowIfOperationInProgress(_lastReceiveAsync.IsCompleted);
Task<WebSocketReceiveResult> t = ReceiveAsyncPrivate<WebSocketReceiveResultGetter, WebSocketReceiveResult>(buffer, cancellationToken).AsTask();
_lastReceiveAsync = t;
return t;
}
}
catch (Exception exc)
{
return Task.FromException<WebSocketReceiveResult>(exc);
}
}
public override Task CloseAsync(WebSocketCloseStatus closeStatus, string? statusDescription, CancellationToken cancellationToken)
{
WebSocketValidate.ValidateCloseStatus(closeStatus, statusDescription);
try
{
WebSocketValidate.ThrowIfInvalidState(_state, _disposed, s_validCloseStates);
}
catch (Exception exc)
{
return Task.FromException(exc);
}
return CloseAsyncPrivate(closeStatus, statusDescription, cancellationToken);
}
public override Task CloseOutputAsync(WebSocketCloseStatus closeStatus, string? statusDescription, CancellationToken cancellationToken)
{
WebSocketValidate.ValidateCloseStatus(closeStatus, statusDescription);
return CloseOutputAsyncCore(closeStatus, statusDescription, cancellationToken);
}
private async Task CloseOutputAsyncCore(WebSocketCloseStatus closeStatus, string? statusDescription, CancellationToken cancellationToken)
{
WebSocketValidate.ThrowIfInvalidState(_state, _disposed, s_validCloseOutputStates);
await SendCloseFrameAsync(closeStatus, statusDescription, cancellationToken).ConfigureAwait(false);
// If we already received a close frame, since we've now also sent one, we're now closed.
lock (StateUpdateLock)
{
Debug.Assert(_sentCloseFrame);
if (_receivedCloseFrame)
{
DisposeCore();
}
}
}
public override void Abort()
{
_abortSource.Cancel();
Dispose(); // forcibly tear down connection
}
/// <summary>Sends a websocket frame to the network.</summary>
/// <param name="opcode">The opcode for the message.</param>
/// <param name="endOfMessage">The value of the FIN bit for the message.</param>
/// <param name="payloadBuffer">The buffer containing the payload data fro the message.</param>
/// <param name="cancellationToken">The CancellationToken to use to cancel the websocket.</param>
private ValueTask SendFrameAsync(MessageOpcode opcode, bool endOfMessage, ReadOnlyMemory<byte> payloadBuffer, CancellationToken cancellationToken)
{
// If a cancelable cancellation token was provided, that would require registering with it, which means more state we have to
// pass around (the CancellationTokenRegistration), so if it is cancelable, just immediately go to the fallback path.
// Similarly, it should be rare that there are multiple outstanding calls to SendFrameAsync, but if there are, again
// fall back to the fallback path.
return cancellationToken.CanBeCanceled || !_sendFrameAsyncLock.Wait(0, default) ?
SendFrameFallbackAsync(opcode, endOfMessage, payloadBuffer, cancellationToken) :
SendFrameLockAcquiredNonCancelableAsync(opcode, endOfMessage, payloadBuffer);
}
/// <summary>Sends a websocket frame to the network. The caller must hold the sending lock.</summary>
/// <param name="opcode">The opcode for the message.</param>
/// <param name="endOfMessage">The value of the FIN bit for the message.</param>
/// <param name="payloadBuffer">The buffer containing the payload data fro the message.</param>
private ValueTask SendFrameLockAcquiredNonCancelableAsync(MessageOpcode opcode, bool endOfMessage, ReadOnlyMemory<byte> payloadBuffer)
{
Debug.Assert(_sendFrameAsyncLock.CurrentCount == 0, "Caller should hold the _sendFrameAsyncLock");
// If we get here, the cancellation token is not cancelable so we don't have to worry about it,
// and we own the semaphore, so we don't need to asynchronously wait for it.
ValueTask writeTask = default;
bool releaseSendBufferAndSemaphore = true;
try
{
// Write the payload synchronously to the buffer, then write that buffer out to the network.
int sendBytes = WriteFrameToSendBuffer(opcode, endOfMessage, payloadBuffer.Span);
writeTask = _stream.WriteAsync(new ReadOnlyMemory<byte>(_sendBuffer, 0, sendBytes));
// If the operation happens to complete synchronously (or, more specifically, by
// the time we get from the previous line to here), release the semaphore, return
// the task, and we're done.
if (writeTask.IsCompleted)
{
return writeTask;
}
// Up until this point, if an exception occurred (such as when accessing _stream or when
// calling GetResult), we want to release the semaphore and the send buffer. After this point,
// both need to be held until writeTask completes.
releaseSendBufferAndSemaphore = false;
}
catch (Exception exc)
{
return new ValueTask(Task.FromException(
exc is OperationCanceledException ? exc :
_state == WebSocketState.Aborted ? CreateOperationCanceledException(exc) :
new WebSocketException(WebSocketError.ConnectionClosedPrematurely, exc)));
}
finally
{
if (releaseSendBufferAndSemaphore)
{
ReleaseSendBuffer();
_sendFrameAsyncLock.Release();
}
}
return WaitForWriteTaskAsync(writeTask);
}
private async ValueTask WaitForWriteTaskAsync(ValueTask writeTask)
{
try
{
await writeTask.ConfigureAwait(false);
}
catch (Exception exc) when (!(exc is OperationCanceledException))
{
throw _state == WebSocketState.Aborted ?
CreateOperationCanceledException(exc) :
new WebSocketException(WebSocketError.ConnectionClosedPrematurely, exc);
}
finally
{
ReleaseSendBuffer();
_sendFrameAsyncLock.Release();
}
}
private async ValueTask SendFrameFallbackAsync(MessageOpcode opcode, bool endOfMessage, ReadOnlyMemory<byte> payloadBuffer, CancellationToken cancellationToken)
{
await _sendFrameAsyncLock.WaitAsync(cancellationToken).ConfigureAwait(false);
try
{
int sendBytes = WriteFrameToSendBuffer(opcode, endOfMessage, payloadBuffer.Span);
using (cancellationToken.Register(static s => ((ManagedWebSocket)s!).Abort(), this))
{
await _stream.WriteAsync(new ReadOnlyMemory<byte>(_sendBuffer, 0, sendBytes), cancellationToken).ConfigureAwait(false);
}
}
catch (Exception exc) when (!(exc is OperationCanceledException))
{
throw _state == WebSocketState.Aborted ?
CreateOperationCanceledException(exc, cancellationToken) :
new WebSocketException(WebSocketError.ConnectionClosedPrematurely, exc);
}
finally
{
ReleaseSendBuffer();
_sendFrameAsyncLock.Release();
}
}
/// <summary>Writes a frame into the send buffer, which can then be sent over the network.</summary>
private int WriteFrameToSendBuffer(MessageOpcode opcode, bool endOfMessage, ReadOnlySpan<byte> payloadBuffer)
{
// Ensure we have a _sendBuffer.
AllocateSendBuffer(payloadBuffer.Length + MaxMessageHeaderLength);
Debug.Assert(_sendBuffer != null);
// Write the message header data to the buffer.
int headerLength;
int? maskOffset = null;
if (_isServer)
{
// The server doesn't send a mask, so the mask offset returned by WriteHeader
// is actually the end of the header.
headerLength = WriteHeader(opcode, _sendBuffer, payloadBuffer, endOfMessage, useMask: false);
}
else
{
// We need to know where the mask starts so that we can use the mask to manipulate the payload data,
// and we need to know the total length for sending it on the wire.
maskOffset = WriteHeader(opcode, _sendBuffer, payloadBuffer, endOfMessage, useMask: true);
headerLength = maskOffset.GetValueOrDefault() + MaskLength;
}
// Write the payload
if (payloadBuffer.Length > 0)
{
payloadBuffer.CopyTo(new Span<byte>(_sendBuffer, headerLength, payloadBuffer.Length));
// If we added a mask to the header, XOR the payload with the mask. We do the manipulation in the send buffer so as to avoid
// changing the data in the caller-supplied payload buffer.
if (maskOffset.HasValue)
{
ApplyMask(new Span<byte>(_sendBuffer, headerLength, payloadBuffer.Length), _sendBuffer, maskOffset.Value, 0);
}
}
// Return the number of bytes in the send buffer
return headerLength + payloadBuffer.Length;
}
private void SendKeepAliveFrameAsync()
{
bool acquiredLock = _sendFrameAsyncLock.Wait(0);
if (acquiredLock)
{
// This exists purely to keep the connection alive; don't wait for the result, and ignore any failures.
// The call will handle releasing the lock. We send a pong rather than ping, since it's allowed by
// the RFC as a unidirectional heartbeat and we're not interested in waiting for a response.
ValueTask t = SendFrameLockAcquiredNonCancelableAsync(MessageOpcode.Pong, true, ReadOnlyMemory<byte>.Empty);
if (t.IsCompletedSuccessfully)
{
t.GetAwaiter().GetResult();
}
else
{
// "Observe" any exception, ignoring it to prevent the unobserved exception event from being raised.
t.AsTask().ContinueWith(static p => { _ = p.Exception; },
CancellationToken.None,
TaskContinuationOptions.OnlyOnFaulted | TaskContinuationOptions.ExecuteSynchronously,
TaskScheduler.Default);
}
}
else
{
// If the lock is already held, something is already getting sent,
// so there's no need to send a keep-alive ping.
}
}
private static int WriteHeader(MessageOpcode opcode, byte[] sendBuffer, ReadOnlySpan<byte> payload, bool endOfMessage, bool useMask)
{
// Client header format:
// 1 bit - FIN - 1 if this is the final fragment in the message (it could be the only fragment), otherwise 0
// 1 bit - RSV1 - Reserved - 0
// 1 bit - RSV2 - Reserved - 0
// 1 bit - RSV3 - Reserved - 0
// 4 bits - Opcode - How to interpret the payload
// - 0x0 - continuation
// - 0x1 - text
// - 0x2 - binary
// - 0x8 - connection close
// - 0x9 - ping
// - 0xA - pong
// - (0x3 to 0x7, 0xB-0xF - reserved)
// 1 bit - Masked - 1 if the payload is masked, 0 if it's not. Must be 1 for the client
// 7 bits, 7+16 bits, or 7+64 bits - Payload length
// - For length 0 through 125, 7 bits storing the length
// - For lengths 126 through 2^16, 7 bits storing the value 126, followed by 16 bits storing the length
// - For lengths 2^16+1 through 2^64, 7 bits storing the value 127, followed by 64 bytes storing the length
// 0 or 4 bytes - Mask, if Masked is 1 - random value XOR'd with each 4 bytes of the payload, round-robin
// Length bytes - Payload data
Debug.Assert(sendBuffer.Length >= MaxMessageHeaderLength, $"Expected sendBuffer to be at least {MaxMessageHeaderLength}, got {sendBuffer.Length}");
sendBuffer[0] = (byte)opcode; // 4 bits for the opcode
if (endOfMessage)
{
sendBuffer[0] |= 0x80; // 1 bit for FIN
}
// Store the payload length.
int maskOffset;
if (payload.Length <= 125)
{
sendBuffer[1] = (byte)payload.Length;
maskOffset = 2; // no additional payload length
}
else if (payload.Length <= ushort.MaxValue)
{
sendBuffer[1] = 126;
sendBuffer[2] = (byte)(payload.Length / 256);
sendBuffer[3] = unchecked((byte)payload.Length);
maskOffset = 2 + sizeof(ushort); // additional 2 bytes for 16-bit length
}
else
{
sendBuffer[1] = 127;
int length = payload.Length;
for (int i = 9; i >= 2; i--)
{
sendBuffer[i] = unchecked((byte)length);
length = length / 256;
}
maskOffset = 2 + sizeof(ulong); // additional 8 bytes for 64-bit length
}
if (useMask)
{
// Generate the mask.
sendBuffer[1] |= 0x80;
WriteRandomMask(sendBuffer, maskOffset);
}
// Return the position of the mask.
return maskOffset;
}
/// <summary>Writes a 4-byte random mask to the specified buffer at the specified offset.</summary>
/// <param name="buffer">The buffer to which to write the mask.</param>
/// <param name="offset">The offset into the buffer at which to write the mask.</param>
private static void WriteRandomMask(byte[] buffer, int offset) =>
s_random.GetBytes(buffer, offset, MaskLength);
/// <summary>
/// Receive the next text, binary, continuation, or close message, returning information about it and
/// writing its payload into the supplied buffer. Other control messages may be consumed and processed
/// as part of this operation, but data about them will not be returned.
/// </summary>
/// <param name="payloadBuffer">The buffer into which payload data should be written.</param>
/// <param name="cancellationToken">The CancellationToken used to cancel the websocket.</param>
/// <param name="resultGetter">Used to get the result. Allows the same method to be used with both WebSocketReceiveResult and ValueWebSocketReceiveResult.</param>
/// <returns>Information about the received message.</returns>
private async ValueTask<TWebSocketReceiveResult> ReceiveAsyncPrivate<TWebSocketReceiveResultGetter, TWebSocketReceiveResult>(
Memory<byte> payloadBuffer,
CancellationToken cancellationToken,
TWebSocketReceiveResultGetter resultGetter = default)
where TWebSocketReceiveResultGetter : struct, IWebSocketReceiveResultGetter<TWebSocketReceiveResult> // constrained to avoid boxing and enable inlining
{
// This is a long method. While splitting it up into pieces would arguably help with readability, doing so would
// also result in more allocations, as each async method that yields ends up with multiple allocations. The impact
// of those allocations is amortized across all of the awaits in the method, and since we generally expect a receive
// operation to require at most a single yield (while waiting for data to arrive), it's more efficient to have
// everything in the one method. We do separate out pieces for handling close and ping/pong messages, as we expect
// those to be much less frequent (e.g. we should only get one close per websocket), and thus we can afford to pay
// a bit more for readability and maintainability.
CancellationTokenRegistration registration = cancellationToken.Register(static s => ((ManagedWebSocket)s!).Abort(), this);
try
{
while (true) // in case we get control frames that should be ignored from the user's perspective
{
// Get the last received header. If its payload length is non-zero, that means we previously
// received the header but were only able to read a part of the fragment, so we should skip
// reading another header and just proceed to use that same header and read more data associated
// with it. If instead its payload length is zero, then we've completed the processing of
// thta message, and we should read the next header.
MessageHeader header = _lastReceiveHeader;
if (header.PayloadLength == 0)
{
if (_receiveBufferCount < (_isServer ? MaxMessageHeaderLength : (MaxMessageHeaderLength - MaskLength)))
{
// Make sure we have the first two bytes, which includes the start of the payload length.
if (_receiveBufferCount < 2)
{
await EnsureBufferContainsAsync(2, cancellationToken, throwOnPrematureClosure: true).ConfigureAwait(false);
}
// Then make sure we have the full header based on the payload length.
// If this is the server, we also need room for the received mask.
long payloadLength = _receiveBuffer.Span[_receiveBufferOffset + 1] & 0x7F;
if (_isServer || payloadLength > 125)
{
int minNeeded =
2 +
(_isServer ? MaskLength : 0) +
(payloadLength <= 125 ? 0 : payloadLength == 126 ? sizeof(ushort) : sizeof(ulong)); // additional 2 or 8 bytes for 16-bit or 64-bit length
await EnsureBufferContainsAsync(minNeeded, cancellationToken).ConfigureAwait(false);
}
}
string? headerErrorMessage = TryParseMessageHeaderFromReceiveBuffer(out header);
if (headerErrorMessage != null)
{
await CloseWithReceiveErrorAndThrowAsync(WebSocketCloseStatus.ProtocolError, WebSocketError.Faulted, headerErrorMessage).ConfigureAwait(false);
}
_receivedMaskOffsetOffset = 0;
}
// If the header represents a ping or a pong, it's a control message meant
// to be transparent to the user, so handle it and then loop around to read again.
// Alternatively, if it's a close message, handle it and exit.
if (header.Opcode == MessageOpcode.Ping || header.Opcode == MessageOpcode.Pong)
{
await HandleReceivedPingPongAsync(header, cancellationToken).ConfigureAwait(false);
continue;
}
else if (header.Opcode == MessageOpcode.Close)
{
await HandleReceivedCloseAsync(header, cancellationToken).ConfigureAwait(false);
return resultGetter.GetResult(0, WebSocketMessageType.Close, true, _closeStatus, _closeStatusDescription);
}
// If this is a continuation, replace the opcode with the one of the message it's continuing
if (header.Opcode == MessageOpcode.Continuation)
{
header.Opcode = _lastReceiveHeader.Opcode;
}
// The message should now be a binary or text message. Handle it by reading the payload and returning the contents.
Debug.Assert(header.Opcode == MessageOpcode.Binary || header.Opcode == MessageOpcode.Text, $"Unexpected opcode {header.Opcode}");
// If there's no data to read, return an appropriate result.
if (header.PayloadLength == 0 || payloadBuffer.Length == 0)
{
_lastReceiveHeader = header;
return resultGetter.GetResult(
0,
header.Opcode == MessageOpcode.Text ? WebSocketMessageType.Text : WebSocketMessageType.Binary,
header.Fin && header.PayloadLength == 0,
null, null);
}
// Otherwise, read as much of the payload as we can efficiently, and update the header to reflect how much data
// remains for future reads. We first need to copy any data that may be lingering in the receive buffer
// into the destination; then to minimize ReceiveAsync calls, we want to read as much as we can, stopping
// only when we've either read the whole message or when we've filled the payload buffer.
// First copy any data lingering in the receive buffer.
int totalBytesReceived = 0;
if (_receiveBufferCount > 0)
{
int receiveBufferBytesToCopy = Math.Min(payloadBuffer.Length, (int)Math.Min(header.PayloadLength, _receiveBufferCount));
Debug.Assert(receiveBufferBytesToCopy > 0);
_receiveBuffer.Span.Slice(_receiveBufferOffset, receiveBufferBytesToCopy).CopyTo(payloadBuffer.Span);
ConsumeFromBuffer(receiveBufferBytesToCopy);
totalBytesReceived += receiveBufferBytesToCopy;
Debug.Assert(
_receiveBufferCount == 0 ||
totalBytesReceived == payloadBuffer.Length ||
totalBytesReceived == header.PayloadLength);
}
// Then read directly into the payload buffer until we've hit a limit.
while (totalBytesReceived < payloadBuffer.Length &&
totalBytesReceived < header.PayloadLength)
{
int numBytesRead = await _stream.ReadAsync(payloadBuffer.Slice(
totalBytesReceived,
(int)Math.Min(payloadBuffer.Length, header.PayloadLength) - totalBytesReceived), cancellationToken).ConfigureAwait(false);
if (numBytesRead <= 0)
{
ThrowIfEOFUnexpected(throwOnPrematureClosure: true);
break;
}
totalBytesReceived += numBytesRead;
}
if (_isServer)
{
_receivedMaskOffsetOffset = ApplyMask(payloadBuffer.Span.Slice(0, totalBytesReceived), header.Mask, _receivedMaskOffsetOffset);
}
header.PayloadLength -= totalBytesReceived;
// If this a text message, validate that it contains valid UTF8.
if (header.Opcode == MessageOpcode.Text &&
!TryValidateUtf8(payloadBuffer.Span.Slice(0, totalBytesReceived), header.Fin && header.PayloadLength == 0, _utf8TextState))
{
await CloseWithReceiveErrorAndThrowAsync(WebSocketCloseStatus.InvalidPayloadData, WebSocketError.Faulted).ConfigureAwait(false);
}
_lastReceiveHeader = header;
return resultGetter.GetResult(
totalBytesReceived,
header.Opcode == MessageOpcode.Text ? WebSocketMessageType.Text : WebSocketMessageType.Binary,
header.Fin && header.PayloadLength == 0,
null, null);
}
}
catch (Exception exc) when (!(exc is OperationCanceledException))
{
if (_state == WebSocketState.Aborted)
{
throw new OperationCanceledException(nameof(WebSocketState.Aborted), exc);
}
_abortSource.Cancel();
if (exc is WebSocketException)
{
throw;
}
throw new WebSocketException(WebSocketError.ConnectionClosedPrematurely, exc);
}
finally
{
registration.Dispose();
}
}
/// <summary>Processes a received close message.</summary>
/// <param name="header">The message header.</param>
/// <param name="cancellationToken">The CancellationToken used to cancel the websocket operation.</param>
/// <returns>The received result message.</returns>
private async ValueTask HandleReceivedCloseAsync(MessageHeader header, CancellationToken cancellationToken)
{
lock (StateUpdateLock)
{
_receivedCloseFrame = true;
if (_sentCloseFrame && _state < WebSocketState.Closed)
{
_state = WebSocketState.Closed;
}
else if (_state < WebSocketState.CloseReceived)
{
_state = WebSocketState.CloseReceived;
}
}
WebSocketCloseStatus closeStatus = WebSocketCloseStatus.NormalClosure;
string closeStatusDescription = string.Empty;
// Handle any payload by parsing it into the close status and description.
if (header.PayloadLength == 1)
{
// The close payload length can be 0 or >= 2, but not 1.
await CloseWithReceiveErrorAndThrowAsync(WebSocketCloseStatus.ProtocolError, WebSocketError.Faulted).ConfigureAwait(false);
}
else if (header.PayloadLength >= 2)
{
if (_receiveBufferCount < header.PayloadLength)
{
await EnsureBufferContainsAsync((int)header.PayloadLength, cancellationToken).ConfigureAwait(false);
}
if (_isServer)
{
ApplyMask(_receiveBuffer.Span.Slice(_receiveBufferOffset, (int)header.PayloadLength), header.Mask, 0);
}
closeStatus = (WebSocketCloseStatus)(_receiveBuffer.Span[_receiveBufferOffset] << 8 | _receiveBuffer.Span[_receiveBufferOffset + 1]);
if (!IsValidCloseStatus(closeStatus))
{
await CloseWithReceiveErrorAndThrowAsync(WebSocketCloseStatus.ProtocolError, WebSocketError.Faulted).ConfigureAwait(false);
}
if (header.PayloadLength > 2)
{
try
{
closeStatusDescription = s_textEncoding.GetString(_receiveBuffer.Span.Slice(_receiveBufferOffset + 2, (int)header.PayloadLength - 2));
}
catch (DecoderFallbackException exc)
{
await CloseWithReceiveErrorAndThrowAsync(WebSocketCloseStatus.ProtocolError, WebSocketError.Faulted, innerException: exc).ConfigureAwait(false);
}
}
ConsumeFromBuffer((int)header.PayloadLength);
}
// Store the close status and description onto the instance.
_closeStatus = closeStatus;
_closeStatusDescription = closeStatusDescription;
if (!_isServer && _sentCloseFrame)
{
await WaitForServerToCloseConnectionAsync(cancellationToken).ConfigureAwait(false);
}
}
/// <summary>Issues a read on the stream to wait for EOF.</summary>
private async ValueTask WaitForServerToCloseConnectionAsync(CancellationToken cancellationToken)
{
// Per RFC 6455 7.1.1, try to let the server close the connection. We give it up to a second.
// We simply issue a read and don't care what we get back; we could validate that we don't get
// additional data, but at this point we're about to close the connection and we're just stalling
// to try to get the server to close first.
ValueTask<int> finalReadTask = _stream.ReadAsync(_receiveBuffer, cancellationToken);
if (!finalReadTask.IsCompletedSuccessfully)
{
const int WaitForCloseTimeoutMs = 1_000; // arbitrary amount of time to give the server (same as netfx)
using (var finalCts = new CancellationTokenSource(WaitForCloseTimeoutMs))
using (finalCts.Token.Register(static s => ((ManagedWebSocket)s!).Abort(), this))
{
try
{
await finalReadTask.ConfigureAwait(false);
}
catch
{
// Eat any resulting exceptions. We were going to close the connection, anyway.
}
}
}
}
/// <summary>Processes a received ping or pong message.</summary>
/// <param name="header">The message header.</param>
/// <param name="cancellationToken">The CancellationToken used to cancel the websocket operation.</param>
private async ValueTask HandleReceivedPingPongAsync(MessageHeader header, CancellationToken cancellationToken)
{
// Consume any (optional) payload associated with the ping/pong.
if (header.PayloadLength > 0 && _receiveBufferCount < header.PayloadLength)
{
await EnsureBufferContainsAsync((int)header.PayloadLength, cancellationToken).ConfigureAwait(false);
}
// If this was a ping, send back a pong response.
if (header.Opcode == MessageOpcode.Ping)
{
if (_isServer)
{
ApplyMask(_receiveBuffer.Span.Slice(_receiveBufferOffset, (int)header.PayloadLength), header.Mask, 0);
}
await SendFrameAsync(
MessageOpcode.Pong,
endOfMessage: true,
_receiveBuffer.Slice(_receiveBufferOffset, (int)header.PayloadLength),
cancellationToken).ConfigureAwait(false);
}
// Regardless of whether it was a ping or pong, we no longer need the payload.
if (header.PayloadLength > 0)
{
ConsumeFromBuffer((int)header.PayloadLength);
}
}
/// <summary>Check whether a close status is valid according to the RFC.</summary>
/// <param name="closeStatus">The status to validate.</param>
/// <returns>true if the status if valid; otherwise, false.</returns>
private static bool IsValidCloseStatus(WebSocketCloseStatus closeStatus)
{
// 0-999: "not used"
// 1000-2999: reserved for the protocol; we need to check individual codes manually
// 3000-3999: reserved for use by higher-level code
// 4000-4999: reserved for private use
// 5000-: not mentioned in RFC
if (closeStatus < (WebSocketCloseStatus)1000 || closeStatus >= (WebSocketCloseStatus)5000)
{
return false;
}
if (closeStatus >= (WebSocketCloseStatus)3000)
{
return true;
}
switch (closeStatus) // check for the 1000-2999 range known codes
{
case WebSocketCloseStatus.EndpointUnavailable:
case WebSocketCloseStatus.InternalServerError:
case WebSocketCloseStatus.InvalidMessageType:
case WebSocketCloseStatus.InvalidPayloadData:
case WebSocketCloseStatus.MandatoryExtension:
case WebSocketCloseStatus.MessageTooBig:
case WebSocketCloseStatus.NormalClosure:
case WebSocketCloseStatus.PolicyViolation:
case WebSocketCloseStatus.ProtocolError:
return true;
default:
return false;
}
}
/// <summary>Send a close message to the server and throw an exception, in response to getting bad data from the server.</summary>
/// <param name="closeStatus">The close status code to use.</param>
/// <param name="error">The error reason.</param>
/// <param name="errorMessage">An optional error message to include in the thrown exception.</param>
/// <param name="innerException">An optional inner exception to include in the thrown exception.</param>
private async ValueTask CloseWithReceiveErrorAndThrowAsync(
WebSocketCloseStatus closeStatus, WebSocketError error, string? errorMessage = null, Exception? innerException = null)
{
// Close the connection if it hasn't already been closed
if (!_sentCloseFrame)
{
await CloseOutputAsync(closeStatus, string.Empty, default).ConfigureAwait(false);
}
// Dump our receive buffer; we're in a bad state to do any further processing
_receiveBufferCount = 0;
// Let the caller know we've failed
throw errorMessage != null ?
new WebSocketException(error, errorMessage, innerException) :
new WebSocketException(error, innerException);
}
/// <summary>Parses a message header from the buffer. This assumes the header is in the buffer.</summary>
/// <param name="resultHeader">The read header.</param>
/// <returns>null if a valid header was read; non-null containing the string error message to use if the header was invalid.</returns>
private string? TryParseMessageHeaderFromReceiveBuffer(out MessageHeader resultHeader)
{
Debug.Assert(_receiveBufferCount >= 2, $"Expected to at least have the first two bytes of the header.");
MessageHeader header = default;
Span<byte> receiveBufferSpan = _receiveBuffer.Span;
header.Fin = (receiveBufferSpan[_receiveBufferOffset] & 0x80) != 0;
bool reservedSet = (receiveBufferSpan[_receiveBufferOffset] & 0x70) != 0;
header.Opcode = (MessageOpcode)(receiveBufferSpan[_receiveBufferOffset] & 0xF);
bool masked = (receiveBufferSpan[_receiveBufferOffset + 1] & 0x80) != 0;
header.PayloadLength = receiveBufferSpan[_receiveBufferOffset + 1] & 0x7F;
ConsumeFromBuffer(2);
// Read the remainder of the payload length, if necessary
if (header.PayloadLength == 126)
{
Debug.Assert(_receiveBufferCount >= 2, $"Expected to have two bytes for the payload length.");
header.PayloadLength = (receiveBufferSpan[_receiveBufferOffset] << 8) | receiveBufferSpan[_receiveBufferOffset + 1];
ConsumeFromBuffer(2);