| | | 1 | | // Licensed to the .NET Foundation under one or more agreements. |
| | | 2 | | // The .NET Foundation licenses this file to you under the MIT license. |
| | | 3 | | |
| | | 4 | | using System.Buffers; |
| | | 5 | | using System.Buffers.Binary; |
| | | 6 | | using System.Diagnostics; |
| | | 7 | | using System.IO; |
| | | 8 | | using System.Net.WebSockets.Compression; |
| | | 9 | | using System.Numerics; |
| | | 10 | | using System.Runtime.CompilerServices; |
| | | 11 | | using System.Runtime.ExceptionServices; |
| | | 12 | | using System.Runtime.InteropServices; |
| | | 13 | | using System.Security.Cryptography; |
| | | 14 | | using System.Text; |
| | | 15 | | using System.Text.Unicode; |
| | | 16 | | using System.Threading; |
| | | 17 | | using System.Threading.Tasks; |
| | | 18 | | |
| | | 19 | | namespace System.Net.WebSockets |
| | | 20 | | { |
| | | 21 | | /// <summary>A managed implementation of a web socket that sends and receives data via a <see cref="Stream"/>.</summ |
| | | 22 | | /// <remarks> |
| | | 23 | | /// Thread-safety: |
| | | 24 | | /// - It's acceptable to call ReceiveAsync and SendAsync in parallel. One of each may run concurrently. |
| | | 25 | | /// - It's acceptable to have a pending ReceiveAsync while CloseOutputAsync or CloseAsync is called. |
| | | 26 | | /// - Attempting to invoke any other operations in parallel may corrupt the instance. Attempting to invoke |
| | | 27 | | /// a send operation while another is in progress or a receive operation while another is in progress will |
| | | 28 | | /// result in an exception. |
| | | 29 | | /// </remarks> |
| | | 30 | | internal sealed partial class ManagedWebSocket : WebSocket |
| | | 31 | | { |
| | | 32 | | /// <summary>Encoding for the payload of text messages: UTF-8 encoding that throws if invalid bytes are discover |
| | 1 | 33 | | private static readonly UTF8Encoding s_textEncoding = new UTF8Encoding(encoderShouldEmitUTF8Identifier: false, t |
| | | 34 | | |
| | | 35 | | /// <summary>The maximum size in bytes of a message frame header that includes mask bytes.</summary> |
| | | 36 | | internal const int MaxMessageHeaderLength = 14; |
| | | 37 | | /// <summary>The maximum size of a control message payload.</summary> |
| | | 38 | | private const int MaxControlPayloadLength = 125; |
| | | 39 | | /// <summary>Length of the mask XOR'd with the payload data.</summary> |
| | | 40 | | private const int MaskLength = 4; |
| | | 41 | | |
| | | 42 | | /// <summary>The stream used to communicate with the remote server.</summary> |
| | | 43 | | private readonly Stream _stream; |
| | | 44 | | /// <summary> |
| | | 45 | | /// true if this is the server-side of the connection; false if it's client. |
| | | 46 | | /// This impacts masking behavior: clients always mask payloads they send and |
| | | 47 | | /// expect to always receive unmasked payloads, whereas servers always send |
| | | 48 | | /// unmasked payloads and expect to always receive masked payloads. |
| | | 49 | | /// </summary> |
| | | 50 | | private readonly bool _isServer; |
| | | 51 | | /// <summary>The agreed upon subprotocol with the server.</summary> |
| | | 52 | | private readonly string? _subprotocol; |
| | | 53 | | /// <summary>Timer used to send periodic pings to the server, at the interval specified</summary> |
| | | 54 | | private readonly Timer? _keepAliveTimer; |
| | | 55 | | /// <summary>Buffer used for reading data from the network.</summary> |
| | | 56 | | private readonly Memory<byte> _receiveBuffer; |
| | | 57 | | /// <summary> |
| | | 58 | | /// Tracks the state of the validity of the UTF-8 encoding of text payloads. Text may be split across fragments |
| | | 59 | | /// </summary> |
| | 8642 | 60 | | private readonly Utf8MessageState _utf8TextState = new Utf8MessageState(); |
| | | 61 | | /// <summary> |
| | | 62 | | /// Mutex used to ensure that calls to SendFrameAsync don't run concurrently. We don't support multiple concurr |
| | | 63 | | /// but this is needed to support SendAsync concurrently with keep-alive pings and CloseAsync. |
| | | 64 | | /// </summary> |
| | 8642 | 65 | | private readonly AsyncMutex _sendMutex = new AsyncMutex(); |
| | | 66 | | /// <summary> |
| | | 67 | | /// Mutex used to ensure that calls to ReceiveAsyncPrivate don't run concurrently. We don't support multiple co |
| | | 68 | | /// but this is needed to support SendAsync concurrently with keep-alive pings and CloseAsync. |
| | | 69 | | /// </summary> |
| | 8642 | 70 | | private readonly AsyncMutex _receiveMutex = new AsyncMutex(); |
| | | 71 | | |
| | | 72 | | // We maintain the current WebSocketState in _state. However, we separately maintain _sentCloseFrame and _recei |
| | | 73 | | // as there isn't a strict ordering between CloseSent and CloseReceived. If we receive a close frame from the s |
| | | 74 | | // transition to CloseReceived even if we're currently in CloseSent, and if we send a close frame, we need to tr |
| | | 75 | | // CloseSent even if we're currently in CloseReceived. |
| | | 76 | | |
| | | 77 | | /// <summary>The current state of the web socket in the protocol.</summary> |
| | 8642 | 78 | | private WebSocketState _state = WebSocketState.Open; |
| | | 79 | | /// <summary>true if Dispose has been called; otherwise, false.</summary> |
| | | 80 | | private bool _disposed; |
| | | 81 | | /// <summary>Whether we've ever sent a close frame.</summary> |
| | | 82 | | private bool _sentCloseFrame; |
| | | 83 | | /// <summary>Whether we've ever received a close frame.</summary> |
| | | 84 | | private bool _receivedCloseFrame; |
| | | 85 | | /// <summary>The reason for the close, as sent by the server, or null if not yet closed.</summary> |
| | | 86 | | private WebSocketCloseStatus? _closeStatus; |
| | | 87 | | /// <summary>A description of the close reason as sent by the server, or null if not yet closed.</summary> |
| | | 88 | | private string? _closeStatusDescription; |
| | | 89 | | |
| | | 90 | | /// <summary> |
| | | 91 | | /// The last header received in a ReceiveAsync. If ReceiveAsync got a header but then |
| | | 92 | | /// returned fewer bytes than was indicated in the header, subsequent ReceiveAsync calls |
| | | 93 | | /// will use the data from the header to construct the subsequent receive results, and |
| | | 94 | | /// the payload length in this header will be decremented to indicate the number of bytes |
| | | 95 | | /// remaining to be received for that header. As a result, between fragments, the payload |
| | | 96 | | /// length in this header should be 0. |
| | | 97 | | /// </summary> |
| | 8642 | 98 | | private MessageHeader _lastReceiveHeader = new MessageHeader { Opcode = MessageOpcode.Text, Fin = true, Processe |
| | | 99 | | /// <summary>The offset of the next available byte in the _receiveBuffer.</summary> |
| | | 100 | | private int _receiveBufferOffset; |
| | | 101 | | /// <summary>The number of bytes available in the _receiveBuffer.</summary> |
| | | 102 | | private int _receiveBufferCount; |
| | | 103 | | /// <summary> |
| | | 104 | | /// When dealing with partially read fragments of binary/text messages, a mask previously received may still |
| | | 105 | | /// apply, and the first new byte received may not correspond to the 0th position in the mask. This value is |
| | | 106 | | /// the next offset into the mask that should be applied. |
| | | 107 | | /// </summary> |
| | | 108 | | private int _receivedMaskOffsetOffset; |
| | | 109 | | /// <summary> |
| | | 110 | | /// Temporary send buffer. This should be released back to the ArrayPool once it's |
| | | 111 | | /// no longer needed for the current send operation. It is stored as an instance |
| | | 112 | | /// field to minimize needing to pass it around and to avoid it becoming a field on |
| | | 113 | | /// various async state machine objects. |
| | | 114 | | /// </summary> |
| | | 115 | | private byte[]? _sendBuffer; |
| | | 116 | | /// <summary> |
| | | 117 | | /// Whether the last SendAsync had endOfMessage==false. We need to track this so that we |
| | | 118 | | /// can send the subsequent message with a continuation opcode if the last message was a fragment. |
| | | 119 | | /// </summary> |
| | | 120 | | private bool _lastSendWasFragment; |
| | | 121 | | /// <summary> |
| | | 122 | | /// Whether the last SendAsync had <seealso cref="WebSocketMessageFlags.DisableCompression" /> flag set. |
| | | 123 | | /// </summary> |
| | | 124 | | private bool _lastSendHadDisableCompression; |
| | | 125 | | |
| | | 126 | | /// <summary>Lock used to protect update and check-and-update operations on _state.</summary> |
| | 56604 | 127 | | private object StateUpdateLock => _sendMutex; |
| | | 128 | | |
| | | 129 | | private readonly WebSocketInflater? _inflater; |
| | | 130 | | private readonly WebSocketDeflater? _deflater; |
| | | 131 | | |
| | | 132 | | private readonly KeepAlivePingState? _keepAlivePingState; |
| | | 133 | | |
| | | 134 | | /// <summary>Initializes the websocket.</summary> |
| | | 135 | | /// <param name="stream">The connected Stream.</param> |
| | | 136 | | /// <param name="isServer">true if this is the server-side of the connection; false if this is the client-side o |
| | | 137 | | /// <param name="subprotocol">The agreed upon subprotocol for the connection.</param> |
| | | 138 | | /// <param name="keepAliveInterval">The interval to use for keep-alive pings.</param> |
| | | 139 | | /// <param name="keepAliveTimeout">The timeout to use when waiting for keep-alive pong response.</param> |
| | 8642 | 140 | | internal ManagedWebSocket(Stream stream, bool isServer, string? subprotocol, TimeSpan keepAliveInterval, TimeSpa |
| | 8642 | 141 | | { |
| | 8642 | 142 | | Debug.Assert(StateUpdateLock != null, $"Expected {nameof(StateUpdateLock)} to be non-null"); |
| | 8642 | 143 | | Debug.Assert(stream != null, $"Expected non-null {nameof(stream)}"); |
| | 8642 | 144 | | Debug.Assert(stream.CanRead, $"Expected readable {nameof(stream)}"); |
| | 8642 | 145 | | Debug.Assert(stream.CanWrite, $"Expected writeable {nameof(stream)}"); |
| | 8642 | 146 | | Debug.Assert(keepAliveInterval == Timeout.InfiniteTimeSpan || keepAliveInterval >= TimeSpan.Zero, $"Invalid |
| | 8642 | 147 | | Debug.Assert(keepAliveTimeout == Timeout.InfiniteTimeSpan || keepAliveTimeout >= TimeSpan.Zero, $"Invalid {n |
| | | 148 | | |
| | 8642 | 149 | | _stream = stream; |
| | 8642 | 150 | | _isServer = isServer; |
| | 8642 | 151 | | _subprotocol = subprotocol; |
| | | 152 | | |
| | 8642 | 153 | | if (NetEventSource.Log.IsEnabled()) |
| | 0 | 154 | | { |
| | 0 | 155 | | NetEventSource.Associate(this, stream); |
| | 0 | 156 | | NetEventSource.Associate(this, _sendMutex); |
| | 0 | 157 | | NetEventSource.Associate(this, _receiveMutex); |
| | 0 | 158 | | } |
| | | 159 | | |
| | | 160 | | // Create a buffer just large enough to handle received packet headers (at most 14 bytes) and |
| | | 161 | | // control payloads (at most 125 bytes). Message payloads are read directly into the buffer |
| | | 162 | | // supplied to ReceiveAsync. |
| | | 163 | | const int ReceiveBufferMinLength = MaxControlPayloadLength; |
| | 8642 | 164 | | _receiveBuffer = new byte[ReceiveBufferMinLength]; |
| | | 165 | | |
| | | 166 | | // Now that we're opened, initiate the keep alive timer to send periodic pings. |
| | | 167 | | // We use a weak reference from the timer to the web socket to avoid a cycle |
| | | 168 | | // that could keep the web socket rooted in erroneous cases. |
| | 8642 | 169 | | if (keepAliveInterval > TimeSpan.Zero) |
| | 0 | 170 | | { |
| | 0 | 171 | | long heartBeatIntervalMs = (long)keepAliveInterval.TotalMilliseconds; |
| | 0 | 172 | | if (keepAliveTimeout > TimeSpan.Zero) |
| | 0 | 173 | | { |
| | 0 | 174 | | _keepAlivePingState = new KeepAlivePingState(keepAliveInterval, keepAliveTimeout, this); |
| | 0 | 175 | | heartBeatIntervalMs = _keepAlivePingState.HeartBeatIntervalMs; |
| | | 176 | | |
| | 0 | 177 | | if (NetEventSource.Log.IsEnabled()) |
| | 0 | 178 | | { |
| | 0 | 179 | | NetEventSource.Associate(this, _keepAlivePingState); |
| | | 180 | | |
| | 0 | 181 | | NetEventSource.Trace(this, |
| | 0 | 182 | | $"Enabling Ping/Pong Keep-Alive strategy: ping delay={_keepAlivePingState.DelayMs}ms, timeou |
| | 0 | 183 | | } |
| | 0 | 184 | | } |
| | 0 | 185 | | else if (NetEventSource.Log.IsEnabled()) |
| | 0 | 186 | | { |
| | 0 | 187 | | NetEventSource.Trace(this, $"Enabling Unsolicited Pong Keep-Alive strategy: heartbeat={heartBeatInte |
| | 0 | 188 | | } |
| | | 189 | | |
| | 0 | 190 | | _keepAliveTimer = new Timer(static s => |
| | 0 | 191 | | { |
| | 0 | 192 | | var wr = (WeakReference<ManagedWebSocket>)s!; |
| | 0 | 193 | | if (wr.TryGetTarget(out ManagedWebSocket? thisRef)) |
| | 0 | 194 | | { |
| | 0 | 195 | | thisRef.HeartBeat(); |
| | 0 | 196 | | } |
| | 0 | 197 | | }, new WeakReference<ManagedWebSocket>(this), heartBeatIntervalMs, heartBeatIntervalMs); |
| | 0 | 198 | | } |
| | 8642 | 199 | | } |
| | | 200 | | |
| | | 201 | | /// <summary>Initializes the websocket.</summary> |
| | | 202 | | /// <param name="stream">The connected Stream.</param> |
| | | 203 | | /// <param name="options">The options with which the websocket must be created.</param> |
| | | 204 | | internal ManagedWebSocket(Stream stream, WebSocketCreationOptions options) |
| | 8642 | 205 | | : this(stream, options.IsServer, options.SubProtocol, options.KeepAliveInterval, options.KeepAliveTimeout) |
| | 8642 | 206 | | { |
| | 8642 | 207 | | var deflateOptions = options.DangerousDeflateOptions; |
| | | 208 | | |
| | 8642 | 209 | | if (deflateOptions is not null) |
| | 2025 | 210 | | { |
| | 2025 | 211 | | if (options.IsServer) |
| | 265 | 212 | | { |
| | 265 | 213 | | _inflater = new WebSocketInflater(deflateOptions.ClientMaxWindowBits, deflateOptions.ClientContextTa |
| | 265 | 214 | | _deflater = new WebSocketDeflater(deflateOptions.ServerMaxWindowBits, deflateOptions.ServerContextTa |
| | 265 | 215 | | } |
| | | 216 | | else |
| | 1760 | 217 | | { |
| | 1760 | 218 | | _inflater = new WebSocketInflater(deflateOptions.ServerMaxWindowBits, deflateOptions.ServerContextTa |
| | 1760 | 219 | | _deflater = new WebSocketDeflater(deflateOptions.ClientMaxWindowBits, deflateOptions.ClientContextTa |
| | 1760 | 220 | | } |
| | 2025 | 221 | | } |
| | 8642 | 222 | | } |
| | | 223 | | |
| | | 224 | | public override void Dispose() |
| | 8677 | 225 | | { |
| | 8677 | 226 | | if (NetEventSource.Log.IsEnabled()) NetEventSource.Trace(this); |
| | | 227 | | |
| | 8677 | 228 | | lock (StateUpdateLock) |
| | 8677 | 229 | | { |
| | 8677 | 230 | | DisposeCore(); |
| | 8677 | 231 | | } |
| | 8677 | 232 | | } |
| | | 233 | | |
| | | 234 | | private void DisposeCore() |
| | 9930 | 235 | | { |
| | 9930 | 236 | | Debug.Assert(Monitor.IsEntered(StateUpdateLock), $"Expected {nameof(StateUpdateLock)} to be held"); |
| | | 237 | | |
| | 9930 | 238 | | if (NetEventSource.Log.IsEnabled()) NetEventSource.Trace(this, $"{nameof(_disposed)}={_disposed}"); |
| | | 239 | | |
| | 9930 | 240 | | if (!_disposed) |
| | 8642 | 241 | | { |
| | 8642 | 242 | | _disposed = true; |
| | 8642 | 243 | | _keepAliveTimer?.Dispose(); |
| | 8642 | 244 | | _stream.Dispose(); |
| | | 245 | | |
| | 8642 | 246 | | WebSocketState state = _state; |
| | 8642 | 247 | | if (state < WebSocketState.Aborted) |
| | 1345 | 248 | | { |
| | 1345 | 249 | | _state = WebSocketState.Closed; |
| | 1345 | 250 | | } |
| | | 251 | | |
| | 8642 | 252 | | if (NetEventSource.Log.IsEnabled()) NetEventSource.Trace(this, $"State transition from {state} to {_stat |
| | | 253 | | |
| | 8642 | 254 | | DisposeSafe(_inflater, _receiveMutex); |
| | 8642 | 255 | | DisposeSafe(_deflater, _sendMutex); |
| | 8642 | 256 | | } |
| | 9930 | 257 | | } |
| | | 258 | | |
| | | 259 | | private static void DisposeSafe(IDisposable? resource, AsyncMutex mutex) |
| | 17284 | 260 | | { |
| | 17284 | 261 | | if (resource is not null) |
| | 4050 | 262 | | { |
| | 4050 | 263 | | Task lockTask = mutex.EnterAsync(CancellationToken.None); |
| | | 264 | | |
| | 4050 | 265 | | if (lockTask.IsCompleted) |
| | 2855 | 266 | | { |
| | 2855 | 267 | | if (NetEventSource.Log.IsEnabled()) NetEventSource.MutexEntered(mutex); |
| | | 268 | | |
| | 2855 | 269 | | resource.Dispose(); |
| | 2855 | 270 | | mutex.Exit(); |
| | | 271 | | |
| | 2855 | 272 | | if (NetEventSource.Log.IsEnabled()) NetEventSource.MutexExited(mutex); |
| | 2855 | 273 | | } |
| | | 274 | | else |
| | 1195 | 275 | | { |
| | 1195 | 276 | | lockTask.GetAwaiter().UnsafeOnCompleted(() => |
| | 1195 | 277 | | { |
| | 1195 | 278 | | if (NetEventSource.Log.IsEnabled()) NetEventSource.MutexEntered(mutex); |
| | 1195 | 279 | | |
| | 1195 | 280 | | resource.Dispose(); |
| | 1195 | 281 | | mutex.Exit(); |
| | 1195 | 282 | | |
| | 1195 | 283 | | if (NetEventSource.Log.IsEnabled()) NetEventSource.MutexExited(mutex); |
| | 2390 | 284 | | }); |
| | 1195 | 285 | | } |
| | 4050 | 286 | | } |
| | 17284 | 287 | | } |
| | | 288 | | |
| | 0 | 289 | | public override WebSocketCloseStatus? CloseStatus => _closeStatus; |
| | | 290 | | |
| | 0 | 291 | | public override string? CloseStatusDescription => _closeStatusDescription; |
| | | 292 | | |
| | 11253 | 293 | | public override WebSocketState State => _state; |
| | | 294 | | |
| | 0 | 295 | | public override string? SubProtocol => _subprotocol; |
| | | 296 | | |
| | | 297 | | public override Task SendAsync(ArraySegment<byte> buffer, WebSocketMessageType messageType, bool endOfMessage, C |
| | 0 | 298 | | { |
| | 0 | 299 | | if (NetEventSource.Log.IsEnabled()) NetEventSource.Trace(this); |
| | | 300 | | |
| | 0 | 301 | | ThrowIfInvalidMessageType(messageType); |
| | | 302 | | |
| | 0 | 303 | | WebSocketValidate.ValidateArraySegment(buffer, nameof(buffer)); |
| | | 304 | | |
| | 0 | 305 | | return SendAsync(buffer, messageType, endOfMessage ? WebSocketMessageFlags.EndOfMessage : default, cancellat |
| | 0 | 306 | | } |
| | | 307 | | |
| | | 308 | | public override ValueTask SendAsync(ReadOnlyMemory<byte> buffer, WebSocketMessageType messageType, bool endOfMes |
| | 236 | 309 | | SendAsync(buffer, messageType, endOfMessage ? WebSocketMessageFlags.EndOfMessage : default, cancellationToke |
| | | 310 | | |
| | | 311 | | public override ValueTask SendAsync(ReadOnlyMemory<byte> buffer, WebSocketMessageType messageType, WebSocketMess |
| | 236 | 312 | | { |
| | 236 | 313 | | if (NetEventSource.Log.IsEnabled()) NetEventSource.Trace(this); |
| | | 314 | | |
| | 236 | 315 | | ThrowIfInvalidMessageType(messageType); |
| | | 316 | | |
| | | 317 | | try |
| | 236 | 318 | | { |
| | 236 | 319 | | ThrowIfInvalidState(WebSocketStateHelper.ValidSendStates); |
| | 219 | 320 | | } |
| | 17 | 321 | | catch (Exception exc) |
| | 17 | 322 | | { |
| | 17 | 323 | | if (NetEventSource.Log.IsEnabled()) NetEventSource.TraceException(this, exc); |
| | 17 | 324 | | return ValueTask.FromException(exc); |
| | | 325 | | } |
| | | 326 | | |
| | 219 | 327 | | bool endOfMessage = (messageFlags & WebSocketMessageFlags.EndOfMessage) != 0; |
| | 219 | 328 | | bool disableCompression = (messageFlags & WebSocketMessageFlags.DisableCompression) != 0; |
| | | 329 | | MessageOpcode opcode; |
| | | 330 | | |
| | 219 | 331 | | if (_lastSendWasFragment) |
| | 0 | 332 | | { |
| | 0 | 333 | | if (_lastSendHadDisableCompression != disableCompression) |
| | 0 | 334 | | { |
| | 0 | 335 | | throw new ArgumentException(SR.net_WebSockets_Argument_MessageFlagsHasDifferentCompressionOptions, n |
| | | 336 | | } |
| | 0 | 337 | | opcode = MessageOpcode.Continuation; |
| | 0 | 338 | | } |
| | | 339 | | else |
| | 219 | 340 | | { |
| | 219 | 341 | | opcode = messageType == WebSocketMessageType.Binary ? MessageOpcode.Binary : MessageOpcode.Text; |
| | 219 | 342 | | } |
| | | 343 | | |
| | 219 | 344 | | ValueTask t = SendFrameAsync(opcode, endOfMessage, disableCompression, buffer, cancellationToken); |
| | 219 | 345 | | _lastSendWasFragment = !endOfMessage; |
| | 219 | 346 | | _lastSendHadDisableCompression = disableCompression; |
| | | 347 | | |
| | 219 | 348 | | return t; |
| | 236 | 349 | | } |
| | | 350 | | |
| | | 351 | | public override Task<WebSocketReceiveResult> ReceiveAsync(ArraySegment<byte> buffer, CancellationToken cancellat |
| | 0 | 352 | | { |
| | 0 | 353 | | if (NetEventSource.Log.IsEnabled()) NetEventSource.Trace(this); |
| | | 354 | | |
| | 0 | 355 | | WebSocketValidate.ValidateArraySegment(buffer, nameof(buffer)); |
| | | 356 | | |
| | | 357 | | try |
| | 0 | 358 | | { |
| | 0 | 359 | | ThrowIfInvalidState(WebSocketStateHelper.ValidReceiveStates); |
| | | 360 | | |
| | 0 | 361 | | return ReceiveAsyncPrivate<WebSocketReceiveResult>(buffer, cancellationToken).AsTask(); |
| | | 362 | | } |
| | 0 | 363 | | catch (Exception exc) |
| | 0 | 364 | | { |
| | 0 | 365 | | if (NetEventSource.Log.IsEnabled()) NetEventSource.TraceException(this, exc); |
| | 0 | 366 | | return Task.FromException<WebSocketReceiveResult>(exc); |
| | | 367 | | } |
| | 0 | 368 | | } |
| | | 369 | | |
| | | 370 | | public override ValueTask<ValueWebSocketReceiveResult> ReceiveAsync(Memory<byte> buffer, CancellationToken cance |
| | 22941 | 371 | | { |
| | 22941 | 372 | | if (NetEventSource.Log.IsEnabled()) NetEventSource.Trace(this); |
| | | 373 | | |
| | | 374 | | try |
| | 22941 | 375 | | { |
| | 22941 | 376 | | ThrowIfInvalidState(WebSocketStateHelper.ValidReceiveStates); |
| | | 377 | | |
| | 22893 | 378 | | return ReceiveAsyncPrivate<ValueWebSocketReceiveResult>(buffer, cancellationToken); |
| | | 379 | | } |
| | 48 | 380 | | catch (Exception exc) |
| | 48 | 381 | | { |
| | 48 | 382 | | if (NetEventSource.Log.IsEnabled()) NetEventSource.TraceException(this, exc); |
| | 48 | 383 | | return ValueTask.FromException<ValueWebSocketReceiveResult>(exc); |
| | | 384 | | } |
| | 22941 | 385 | | } |
| | | 386 | | |
| | | 387 | | public override Task CloseAsync(WebSocketCloseStatus closeStatus, string? statusDescription, CancellationToken c |
| | 5618 | 388 | | { |
| | 5618 | 389 | | if (NetEventSource.Log.IsEnabled()) NetEventSource.Trace(this); |
| | | 390 | | |
| | 5618 | 391 | | WebSocketValidate.ValidateCloseStatus(closeStatus, statusDescription); |
| | | 392 | | |
| | | 393 | | try |
| | 5618 | 394 | | { |
| | 5618 | 395 | | ThrowIfInvalidState(WebSocketStateHelper.ValidCloseStates); |
| | 5618 | 396 | | } |
| | 0 | 397 | | catch (Exception exc) |
| | 0 | 398 | | { |
| | 0 | 399 | | if (NetEventSource.Log.IsEnabled()) NetEventSource.TraceException(this, exc); |
| | 0 | 400 | | return Task.FromException(exc); |
| | | 401 | | } |
| | | 402 | | |
| | 5618 | 403 | | return CloseAsyncPrivate(closeStatus, statusDescription, cancellationToken); |
| | 5618 | 404 | | } |
| | | 405 | | |
| | | 406 | | public override Task CloseOutputAsync(WebSocketCloseStatus closeStatus, string? statusDescription, CancellationT |
| | 126 | 407 | | { |
| | 126 | 408 | | if (NetEventSource.Log.IsEnabled()) NetEventSource.Trace(this); |
| | | 409 | | |
| | 126 | 410 | | WebSocketValidate.ValidateCloseStatus(closeStatus, statusDescription); |
| | 126 | 411 | | return CloseOutputAsyncCore(closeStatus, statusDescription, enterReceiveMutex: true, cancellationToken: canc |
| | 126 | 412 | | } |
| | | 413 | | |
| | | 414 | | private async Task CloseOutputAsyncCore(WebSocketCloseStatus closeStatus, string? statusDescription, bool enterR |
| | 2718 | 415 | | { |
| | 2718 | 416 | | if (NetEventSource.Log.IsEnabled()) NetEventSource.Trace(this); |
| | | 417 | | |
| | 2718 | 418 | | ThrowIfInvalidState(WebSocketStateHelper.ValidCloseOutputStates); |
| | | 419 | | |
| | 2684 | 420 | | await SendCloseFrameAsync(closeStatus, statusDescription, cancellationToken).ConfigureAwait(false); |
| | | 421 | | |
| | | 422 | | // Polite EOF wait under the receive mutex; avoids racing the receive loop on the stream. |
| | 2684 | 423 | | if (!_isServer && _receivedCloseFrame) |
| | 1193 | 424 | | { |
| | 1193 | 425 | | await WaitForServerToCloseConnectionAsync(enterReceiveMutex, cancellationToken).ConfigureAwait(false); |
| | 1193 | 426 | | } |
| | | 427 | | |
| | | 428 | | // If we already received a close frame, since we've now also sent one, we're now closed. |
| | 2684 | 429 | | lock (StateUpdateLock) |
| | 2684 | 430 | | { |
| | 2684 | 431 | | Debug.Assert(_sentCloseFrame); |
| | 2684 | 432 | | if (_receivedCloseFrame) |
| | 1218 | 433 | | { |
| | 1218 | 434 | | DisposeCore(); |
| | 1218 | 435 | | } |
| | 2684 | 436 | | } |
| | 2684 | 437 | | } |
| | | 438 | | |
| | | 439 | | public override void Abort() |
| | 0 | 440 | | { |
| | 0 | 441 | | if (NetEventSource.Log.IsEnabled()) NetEventSource.Trace(this); |
| | | 442 | | |
| | 0 | 443 | | OnAborted(); |
| | 0 | 444 | | Dispose(); // forcibly tear down connection |
| | 0 | 445 | | } |
| | | 446 | | |
| | | 447 | | private void OnAborted() |
| | 8543 | 448 | | { |
| | 8543 | 449 | | if (NetEventSource.Log.IsEnabled()) NetEventSource.Trace(this); |
| | | 450 | | |
| | 8543 | 451 | | lock (StateUpdateLock) |
| | 8543 | 452 | | { |
| | 8543 | 453 | | OnAbortedCore(); |
| | 8543 | 454 | | } |
| | 8543 | 455 | | } |
| | | 456 | | |
| | | 457 | | private void OnAbortedCore() |
| | 8543 | 458 | | { |
| | 8543 | 459 | | Debug.Assert(Monitor.IsEntered(StateUpdateLock), $"Expected {nameof(StateUpdateLock)} to be held"); |
| | | 460 | | |
| | 8543 | 461 | | WebSocketState state = _state; |
| | 8543 | 462 | | if (state is not WebSocketState.Closed and not WebSocketState.Aborted) |
| | 7297 | 463 | | { |
| | 7297 | 464 | | _state = state is not WebSocketState.None and not WebSocketState.Connecting ? |
| | 7297 | 465 | | WebSocketState.Aborted : |
| | 7297 | 466 | | WebSocketState.Closed; |
| | 7297 | 467 | | } |
| | | 468 | | |
| | 8543 | 469 | | if (NetEventSource.Log.IsEnabled()) NetEventSource.Trace(this, $"State transition from {state} to {_state}") |
| | 8543 | 470 | | } |
| | | 471 | | |
| | | 472 | | /// <summary>Sends a websocket frame to the network.</summary> |
| | | 473 | | /// <param name="opcode">The opcode for the message.</param> |
| | | 474 | | /// <param name="endOfMessage">The value of the FIN bit for the message.</param> |
| | | 475 | | /// <param name="disableCompression">Disables compression for the message.</param> |
| | | 476 | | /// <param name="payloadBuffer">The buffer containing the payload data from the message.</param> |
| | | 477 | | /// <param name="cancellationToken">The CancellationToken to use to cancel the websocket.</param> |
| | | 478 | | private ValueTask SendFrameAsync(MessageOpcode opcode, bool endOfMessage, bool disableCompression, ReadOnlyMemor |
| | 37439 | 479 | | { |
| | 37439 | 480 | | if (NetEventSource.Log.IsEnabled()) NetEventSource.SendFrameAsyncStarted(this, opcode.ToString(), payloadBuf |
| | | 481 | | |
| | | 482 | | // If a cancelable cancellation token was provided, that would require registering with it, which means more |
| | | 483 | | // pass around (the CancellationTokenRegistration), so if it is cancelable, just immediately go to the fallb |
| | | 484 | | // Similarly, it should be rare that there are multiple outstanding calls to SendFrameAsync, but if there ar |
| | | 485 | | // fall back to the fallback path. |
| | 37439 | 486 | | Task lockTask = _sendMutex.EnterAsync(cancellationToken); |
| | 37439 | 487 | | return cancellationToken.CanBeCanceled || !lockTask.IsCompletedSuccessfully ? |
| | 37439 | 488 | | SendFrameFallbackAsync(opcode, endOfMessage, disableCompression, payloadBuffer, lockTask, cancellationTo |
| | 37439 | 489 | | SendFrameLockAcquiredNonCancelableAsync(opcode, endOfMessage, disableCompression, payloadBuffer); |
| | 37439 | 490 | | } |
| | | 491 | | |
| | | 492 | | /// <summary>Sends a websocket frame to the network. The caller must hold the sending lock.</summary> |
| | | 493 | | /// <param name="opcode">The opcode for the message.</param> |
| | | 494 | | /// <param name="endOfMessage">The value of the FIN bit for the message.</param> |
| | | 495 | | /// <param name="disableCompression">Disables compression for the message.</param> |
| | | 496 | | /// <param name="payloadBuffer">The buffer containing the payload data fro the message.</param> |
| | | 497 | | private ValueTask SendFrameLockAcquiredNonCancelableAsync(MessageOpcode opcode, bool endOfMessage, bool disableC |
| | 3681 | 498 | | { |
| | 3681 | 499 | | Debug.Assert(_sendMutex.IsHeld, $"Caller should hold the {nameof(_sendMutex)}"); |
| | | 500 | | |
| | 3681 | 501 | | if (NetEventSource.Log.IsEnabled()) NetEventSource.MutexEntered(_sendMutex); |
| | | 502 | | |
| | | 503 | | // If we get here, the cancellation token is not cancelable so we don't have to worry about it, |
| | | 504 | | // and we own the semaphore, so we don't need to asynchronously wait for it. |
| | 3681 | 505 | | ValueTask writeTask = default; |
| | 3681 | 506 | | bool releaseSendBufferAndSemaphore = true; |
| | | 507 | | try |
| | 3681 | 508 | | { |
| | | 509 | | // Write the payload synchronously to the buffer, then write that buffer out to the network. |
| | 3681 | 510 | | int sendBytes = WriteFrameToSendBuffer(opcode, endOfMessage, disableCompression, payloadBuffer.Span); |
| | 3681 | 511 | | writeTask = _stream.WriteAsync(new ReadOnlyMemory<byte>(_sendBuffer, 0, sendBytes)); |
| | | 512 | | |
| | | 513 | | // If the operation happens to complete synchronously (or, more specifically, by |
| | | 514 | | // the time we get from the previous line to here), release the semaphore, return |
| | | 515 | | // the task, and we're done. |
| | 3681 | 516 | | if (writeTask.IsCompleted) |
| | 3681 | 517 | | { |
| | 3681 | 518 | | writeTask.GetAwaiter().GetResult(); |
| | 3681 | 519 | | Task flushTask = _stream.FlushAsync(); |
| | 3681 | 520 | | if (flushTask.IsCompleted) |
| | 290 | 521 | | { |
| | 290 | 522 | | flushTask.GetAwaiter().GetResult(); |
| | 290 | 523 | | return ValueTask.CompletedTask; |
| | | 524 | | } |
| | | 525 | | else |
| | 3391 | 526 | | { |
| | 3391 | 527 | | releaseSendBufferAndSemaphore = false; |
| | 3391 | 528 | | return WaitForWriteTaskAsync(new ValueTask(flushTask), shouldFlush: false); |
| | | 529 | | } |
| | | 530 | | } |
| | | 531 | | |
| | | 532 | | // Up until this point, if an exception occurred (such as when accessing _stream or when |
| | | 533 | | // calling GetResult), we want to release the semaphore and the send buffer. After this point, |
| | | 534 | | // both need to be held until writeTask completes. |
| | 0 | 535 | | releaseSendBufferAndSemaphore = false; |
| | 0 | 536 | | } |
| | 0 | 537 | | catch (Exception exc) |
| | 0 | 538 | | { |
| | 0 | 539 | | if (NetEventSource.Log.IsEnabled()) NetEventSource.TraceException(this, exc); |
| | | 540 | | |
| | 0 | 541 | | return ValueTask.FromException( |
| | 0 | 542 | | exc is OperationCanceledException ? exc : |
| | 0 | 543 | | _state == WebSocketState.Aborted ? CreateOperationCanceledException(exc) : |
| | 0 | 544 | | ExceptionDispatchInfo.SetCurrentStackTrace(new WebSocketException(WebSocketError.ConnectionClosedPre |
| | | 545 | | } |
| | | 546 | | finally |
| | 3681 | 547 | | { |
| | 3681 | 548 | | if (releaseSendBufferAndSemaphore) |
| | 290 | 549 | | { |
| | 290 | 550 | | ReleaseSendBuffer(); |
| | 290 | 551 | | _sendMutex.Exit(); |
| | | 552 | | |
| | 290 | 553 | | if (NetEventSource.Log.IsEnabled()) |
| | 0 | 554 | | { |
| | 0 | 555 | | NetEventSource.MutexExited(_sendMutex); |
| | 0 | 556 | | NetEventSource.SendFrameAsyncCompleted(this); |
| | 0 | 557 | | } |
| | 290 | 558 | | } |
| | 3681 | 559 | | } |
| | | 560 | | |
| | 0 | 561 | | return WaitForWriteTaskAsync(writeTask, shouldFlush: true); |
| | 3681 | 562 | | } |
| | | 563 | | |
| | | 564 | | private async ValueTask WaitForWriteTaskAsync(ValueTask writeTask, bool shouldFlush) |
| | 3391 | 565 | | { |
| | | 566 | | try |
| | 3391 | 567 | | { |
| | 3391 | 568 | | await writeTask.ConfigureAwait(false); |
| | 3391 | 569 | | if (shouldFlush) |
| | 0 | 570 | | { |
| | 0 | 571 | | await _stream.FlushAsync().ConfigureAwait(false); |
| | 0 | 572 | | } |
| | 3391 | 573 | | } |
| | 0 | 574 | | catch (Exception exc) |
| | 0 | 575 | | { |
| | 0 | 576 | | if (NetEventSource.Log.IsEnabled()) NetEventSource.TraceException(this, exc); |
| | | 577 | | |
| | 0 | 578 | | if (exc is OperationCanceledException) |
| | 0 | 579 | | { |
| | 0 | 580 | | throw; |
| | | 581 | | } |
| | | 582 | | |
| | 0 | 583 | | throw _state == WebSocketState.Aborted ? |
| | 0 | 584 | | CreateOperationCanceledException(exc) : |
| | 0 | 585 | | new WebSocketException(WebSocketError.ConnectionClosedPrematurely, exc); |
| | | 586 | | } |
| | | 587 | | finally |
| | 3391 | 588 | | { |
| | 3391 | 589 | | ReleaseSendBuffer(); |
| | 3391 | 590 | | _sendMutex.Exit(); |
| | | 591 | | |
| | 3391 | 592 | | if (NetEventSource.Log.IsEnabled()) |
| | 0 | 593 | | { |
| | 0 | 594 | | NetEventSource.MutexExited(_sendMutex); |
| | 0 | 595 | | NetEventSource.SendFrameAsyncCompleted(this); |
| | 0 | 596 | | } |
| | 3391 | 597 | | } |
| | 3391 | 598 | | } |
| | | 599 | | |
| | | 600 | | private async ValueTask SendFrameFallbackAsync(MessageOpcode opcode, bool endOfMessage, bool disableCompression, |
| | 33758 | 601 | | { |
| | | 602 | | // Register for cancellation before waiting on the lock so that if cancellation races with |
| | | 603 | | // acquiring the mutex, we still abort the connection, just as we would if cancellation raced |
| | | 604 | | // with the write itself. Without this, a cancellation that fires while we're waiting to enter |
| | | 605 | | // the mutex would propagate out without transitioning the WebSocket to the Aborted state. |
| | 33758 | 606 | | using (cancellationToken.Register(static s => ((ManagedWebSocket)s!).Abort(), this)) |
| | 33758 | 607 | | { |
| | | 608 | | try |
| | 33758 | 609 | | { |
| | 33758 | 610 | | await lockTask.ConfigureAwait(false); |
| | 33758 | 611 | | } |
| | 0 | 612 | | catch (Exception exc) |
| | 0 | 613 | | { |
| | 0 | 614 | | if (NetEventSource.Log.IsEnabled()) NetEventSource.TraceException(this, exc); |
| | 0 | 615 | | throw; |
| | | 616 | | } |
| | | 617 | | |
| | 33758 | 618 | | if (NetEventSource.Log.IsEnabled()) NetEventSource.MutexEntered(_sendMutex); |
| | | 619 | | |
| | | 620 | | try |
| | 33758 | 621 | | { |
| | 33758 | 622 | | int sendBytes = WriteFrameToSendBuffer(opcode, endOfMessage, disableCompression, payloadBuffer.Span) |
| | 33758 | 623 | | await _stream.WriteAsync(new ReadOnlyMemory<byte>(_sendBuffer, 0, sendBytes), cancellationToken).Con |
| | 33758 | 624 | | await _stream.FlushAsync(cancellationToken).ConfigureAwait(false); |
| | 33758 | 625 | | } |
| | 0 | 626 | | catch (Exception exc) |
| | 0 | 627 | | { |
| | 0 | 628 | | if (NetEventSource.Log.IsEnabled()) NetEventSource.TraceException(this, exc); |
| | | 629 | | |
| | 0 | 630 | | if (exc is OperationCanceledException) |
| | 0 | 631 | | { |
| | 0 | 632 | | throw; |
| | | 633 | | } |
| | | 634 | | |
| | 0 | 635 | | throw _state == WebSocketState.Aborted ? |
| | 0 | 636 | | CreateOperationCanceledException(exc, cancellationToken) : |
| | 0 | 637 | | new WebSocketException(WebSocketError.ConnectionClosedPrematurely, exc); |
| | | 638 | | } |
| | | 639 | | finally |
| | 33758 | 640 | | { |
| | 33758 | 641 | | ReleaseSendBuffer(); |
| | 33758 | 642 | | _sendMutex.Exit(); |
| | | 643 | | |
| | 33758 | 644 | | if (NetEventSource.Log.IsEnabled()) |
| | 0 | 645 | | { |
| | 0 | 646 | | NetEventSource.MutexExited(_sendMutex); |
| | 0 | 647 | | NetEventSource.SendFrameAsyncCompleted(this); |
| | 0 | 648 | | } |
| | 33758 | 649 | | } |
| | 33758 | 650 | | } |
| | 33758 | 651 | | } |
| | | 652 | | |
| | | 653 | | /// <summary>Writes a frame into the send buffer, which can then be sent over the network.</summary> |
| | | 654 | | private int WriteFrameToSendBuffer(MessageOpcode opcode, bool endOfMessage, bool disableCompression, ReadOnlySpa |
| | 37439 | 655 | | { |
| | 37439 | 656 | | ThrowIfDisposed(); |
| | | 657 | | |
| | 37439 | 658 | | if (_deflater is not null && !disableCompression) |
| | 37 | 659 | | { |
| | 37 | 660 | | payloadBuffer = _deflater.Deflate(payloadBuffer, endOfMessage); |
| | 37 | 661 | | } |
| | 37439 | 662 | | int payloadLength = payloadBuffer.Length; |
| | | 663 | | |
| | | 664 | | // Ensure we have a _sendBuffer |
| | 37439 | 665 | | AllocateSendBuffer(payloadLength + MaxMessageHeaderLength); |
| | 37439 | 666 | | Debug.Assert(_sendBuffer != null); |
| | | 667 | | |
| | | 668 | | // Write the message header data to the buffer. |
| | | 669 | | int headerLength; |
| | 37439 | 670 | | int? maskOffset = null; |
| | 37439 | 671 | | if (_isServer) |
| | 31604 | 672 | | { |
| | | 673 | | // The server doesn't send a mask, so the mask offset returned by WriteHeader |
| | | 674 | | // is actually the end of the header. |
| | 31604 | 675 | | headerLength = WriteHeader(opcode, _sendBuffer, payloadBuffer, endOfMessage, useMask: false, compressed: |
| | 31604 | 676 | | } |
| | | 677 | | else |
| | 5835 | 678 | | { |
| | | 679 | | // We need to know where the mask starts so that we can use the mask to manipulate the payload data, |
| | | 680 | | // and we need to know the total length for sending it on the wire. |
| | 5835 | 681 | | maskOffset = WriteHeader(opcode, _sendBuffer, payloadBuffer, endOfMessage, useMask: true, compressed: _d |
| | 5835 | 682 | | headerLength = maskOffset.GetValueOrDefault() + MaskLength; |
| | 5835 | 683 | | } |
| | | 684 | | |
| | | 685 | | // Write the payload |
| | 37439 | 686 | | if (payloadBuffer.Length > 0) |
| | 36997 | 687 | | { |
| | 36997 | 688 | | payloadBuffer.CopyTo(new Span<byte>(_sendBuffer, headerLength, payloadLength)); |
| | | 689 | | |
| | | 690 | | // Release the deflater buffer if any, we're not going to need the payloadBuffer anymore. |
| | 36997 | 691 | | _deflater?.ReleaseBuffer(); |
| | | 692 | | |
| | | 693 | | // If we added a mask to the header, XOR the payload with the mask. We do the manipulation in the send |
| | | 694 | | // changing the data in the caller-supplied payload buffer. |
| | 36997 | 695 | | if (maskOffset.HasValue) |
| | 5393 | 696 | | { |
| | 5393 | 697 | | ApplyMask(new Span<byte>(_sendBuffer, headerLength, payloadLength), _sendBuffer, maskOffset.Value, 0 |
| | 5393 | 698 | | } |
| | 36997 | 699 | | } |
| | | 700 | | |
| | | 701 | | // Return the number of bytes in the send buffer |
| | 37439 | 702 | | return headerLength + payloadLength; |
| | 37439 | 703 | | } |
| | | 704 | | |
| | | 705 | | private static int WriteHeader(MessageOpcode opcode, byte[] sendBuffer, ReadOnlySpan<byte> payload, bool endOfMe |
| | 37439 | 706 | | { |
| | | 707 | | // Client header format: |
| | | 708 | | // 1 bit - FIN - 1 if this is the final fragment in the message (it could be the only fragment), otherwise 0 |
| | | 709 | | // 1 bit - RSV1 - Reserved - 0 |
| | | 710 | | // 1 bit - RSV2 - Reserved - 0 |
| | | 711 | | // 1 bit - RSV3 - Reserved - 0 |
| | | 712 | | // 4 bits - Opcode - How to interpret the payload |
| | | 713 | | // - 0x0 - continuation |
| | | 714 | | // - 0x1 - text |
| | | 715 | | // - 0x2 - binary |
| | | 716 | | // - 0x8 - connection close |
| | | 717 | | // - 0x9 - ping |
| | | 718 | | // - 0xA - pong |
| | | 719 | | // - (0x3 to 0x7, 0xB-0xF - reserved) |
| | | 720 | | // 1 bit - Masked - 1 if the payload is masked, 0 if it's not. Must be 1 for the client |
| | | 721 | | // 7 bits, 7+16 bits, or 7+64 bits - Payload length |
| | | 722 | | // - For length 0 through 125, 7 bits storing the length |
| | | 723 | | // - For lengths 126 through 2^16, 7 bits storing the value 126, followed by 16 bits storing the length |
| | | 724 | | // - For lengths 2^16+1 through 2^64, 7 bits storing the value 127, followed by 64 bytes storing the len |
| | | 725 | | // 0 or 4 bytes - Mask, if Masked is 1 - random value XOR'd with each 4 bytes of the payload, round-robin |
| | | 726 | | // Length bytes - Payload data |
| | | 727 | | |
| | 37439 | 728 | | Debug.Assert(sendBuffer.Length >= MaxMessageHeaderLength, $"Expected {nameof(sendBuffer)} to be at least {Ma |
| | | 729 | | |
| | 37439 | 730 | | sendBuffer[0] = (byte)opcode; // 4 bits for the opcode |
| | 37439 | 731 | | if (endOfMessage) |
| | 37255 | 732 | | { |
| | 37255 | 733 | | sendBuffer[0] |= 0x80; // 1 bit for FIN |
| | 37255 | 734 | | } |
| | 37439 | 735 | | if (compressed && opcode != MessageOpcode.Continuation) |
| | 37 | 736 | | { |
| | | 737 | | // Per-Message Deflate flag needs to be set only in the first frame |
| | 37 | 738 | | sendBuffer[0] |= 0b_0100_0000; |
| | 37 | 739 | | } |
| | | 740 | | |
| | | 741 | | // Store the payload length. |
| | | 742 | | int maskOffset; |
| | 37439 | 743 | | if (payload.Length <= 125) |
| | 37414 | 744 | | { |
| | 37414 | 745 | | sendBuffer[1] = (byte)payload.Length; |
| | 37414 | 746 | | maskOffset = 2; // no additional payload length |
| | 37414 | 747 | | } |
| | 25 | 748 | | else if (payload.Length <= ushort.MaxValue) |
| | 25 | 749 | | { |
| | 25 | 750 | | sendBuffer[1] = 126; |
| | 25 | 751 | | BinaryPrimitives.WriteUInt16BigEndian(sendBuffer.AsSpan(2), (ushort)payload.Length); |
| | 25 | 752 | | maskOffset = 2 + sizeof(ushort); // additional 2 bytes for 16-bit length |
| | 25 | 753 | | } |
| | | 754 | | else |
| | 0 | 755 | | { |
| | 0 | 756 | | sendBuffer[1] = 127; |
| | 0 | 757 | | BinaryPrimitives.WriteUInt64BigEndian(sendBuffer.AsSpan(2), (ulong)payload.Length); |
| | 0 | 758 | | maskOffset = 2 + sizeof(ulong); // additional 8 bytes for 64-bit length |
| | 0 | 759 | | } |
| | | 760 | | |
| | 37439 | 761 | | if (useMask) |
| | 5835 | 762 | | { |
| | | 763 | | // Generate the mask. |
| | 5835 | 764 | | sendBuffer[1] |= 0x80; |
| | 5835 | 765 | | WriteRandomMask(sendBuffer, maskOffset); |
| | 5835 | 766 | | } |
| | | 767 | | |
| | | 768 | | // Return the position of the mask. |
| | 37439 | 769 | | return maskOffset; |
| | 37439 | 770 | | } |
| | | 771 | | |
| | | 772 | | /// <summary>Writes a 4-byte random mask to the specified buffer at the specified offset.</summary> |
| | | 773 | | /// <param name="buffer">The buffer to which to write the mask.</param> |
| | | 774 | | /// <param name="offset">The offset into the buffer at which to write the mask.</param> |
| | | 775 | | private static void WriteRandomMask(byte[] buffer, int offset) => |
| | 5835 | 776 | | RandomNumberGenerator.Fill(buffer.AsSpan(offset, MaskLength)); |
| | | 777 | | |
| | | 778 | | /// <summary> |
| | | 779 | | /// Receive the next text, binary, continuation, or close message, returning information about it and |
| | | 780 | | /// writing its payload into the supplied buffer. Other control messages may be consumed and processed |
| | | 781 | | /// as part of this operation, but data about them will not be returned. |
| | | 782 | | /// </summary> |
| | | 783 | | /// <param name="payloadBuffer">The buffer into which payload data should be written.</param> |
| | | 784 | | /// <param name="cancellationToken">The CancellationToken used to cancel the websocket.</param> |
| | | 785 | | /// <returns>Information about the received message.</returns> |
| | | 786 | | [AsyncMethodBuilder(typeof(PoolingAsyncValueTaskMethodBuilder<>))] |
| | | 787 | | [RuntimeAsyncMethodGeneration(false)] |
| | | 788 | | private async ValueTask<TResult> ReceiveAsyncPrivate<TResult>(Memory<byte> payloadBuffer, CancellationToken canc |
| | 344880 | 789 | | { |
| | | 790 | | // This is a long method. While splitting it up into pieces would arguably help with readability, doing so |
| | | 791 | | // also result in more allocations, as each async method that yields ends up with multiple allocations. The |
| | | 792 | | // of those allocations is amortized across all of the awaits in the method, and since we generally expect a |
| | | 793 | | // operation to require at most a single yield (while waiting for data to arrive), it's more efficient to ha |
| | | 794 | | // everything in the one method. We do separate out pieces for handling close and ping/pong messages, as we |
| | | 795 | | // those to be much less frequent (e.g. we should only get one close per websocket), and thus we can afford |
| | | 796 | | // a bit more for readability and maintainability. |
| | | 797 | | |
| | 344880 | 798 | | if (NetEventSource.Log.IsEnabled()) NetEventSource.ReceiveAsyncPrivateStarted(this, payloadBuffer.Length); |
| | | 799 | | |
| | 344880 | 800 | | CancellationTokenRegistration registration = default; |
| | | 801 | | try |
| | 344880 | 802 | | { |
| | 344880 | 803 | | registration = cancellationToken.Register(static s => ((ManagedWebSocket)s!).Abort(), this); |
| | | 804 | | |
| | 344880 | 805 | | await _receiveMutex.EnterAsync(cancellationToken).ConfigureAwait(false); |
| | 344880 | 806 | | if (NetEventSource.Log.IsEnabled()) NetEventSource.MutexEntered(_receiveMutex); |
| | | 807 | | |
| | | 808 | | try |
| | 344880 | 809 | | { |
| | 344880 | 810 | | ThrowIfDisposed(); |
| | | 811 | | |
| | 375067 | 812 | | while (true) // in case we get control frames that should be ignored from the user's perspective |
| | 375067 | 813 | | { |
| | | 814 | | // Get the last received header. If its payload length is non-zero, that means we previously |
| | | 815 | | // received the header but were only able to read a part of the fragment, so we should skip |
| | | 816 | | // reading another header and just proceed to use that same header and read more data associated |
| | | 817 | | // with it. If instead its payload length is zero, then we've completed the processing of |
| | | 818 | | // that message, and we should read the next header. |
| | 375067 | 819 | | MessageHeader header = _lastReceiveHeader; |
| | 375067 | 820 | | if (header.Processed) |
| | 366294 | 821 | | { |
| | 366294 | 822 | | if (NetEventSource.Log.IsEnabled()) NetEventSource.Trace(this, "Reading the next frame heade |
| | | 823 | | |
| | 366294 | 824 | | if (_receiveBufferCount < (_isServer ? MaxMessageHeaderLength : (MaxMessageHeaderLength - Ma |
| | 67478 | 825 | | { |
| | | 826 | | // Make sure we have the first two bytes, which includes the start of the payload length |
| | 67478 | 827 | | if (_receiveBufferCount < 2) |
| | 25776 | 828 | | { |
| | 25776 | 829 | | if (payloadBuffer.IsEmpty) |
| | 6290 | 830 | | { |
| | | 831 | | // The caller has issued a zero-byte read. The only meaningful reason to do tha |
| | | 832 | | // wait for data to be available without actually consuming any of it. If we jus |
| | | 833 | | // our internal buffer, the underlying stream might end up renting and/or pinnin |
| | | 834 | | // for the duration of the operation, which isn't necessary when we don't actual |
| | | 835 | | // consume anything. Instead, we issue a zero-byte read against the underlying s |
| | | 836 | | // given that the receive buffer currently stores fewer than the minimum number |
| | | 837 | | // necessary for a header, it's safe to issue a read (if there were at least the |
| | | 838 | | // number of bytes available, we could end up issuing a read that would erroneou |
| | | 839 | | // for data that would never arrive). Once that read completes, we can proceed w |
| | | 840 | | // other reads necessary, and they'll have a reduced chance of pinning the recei |
| | 6290 | 841 | | await _stream.ReadAsync(Memory<byte>.Empty, cancellationToken).ConfigureAwait(fa |
| | 6290 | 842 | | } |
| | | 843 | | |
| | 25776 | 844 | | await EnsureBufferContainsAsync(2, cancellationToken).ConfigureAwait(false); |
| | 24846 | 845 | | } |
| | | 846 | | |
| | | 847 | | // Then make sure we have the full header based on the payload length. |
| | | 848 | | // If this is the server, we also need room for the received mask. |
| | 66548 | 849 | | long payloadLength = _receiveBuffer.Span[_receiveBufferOffset + 1] & 0x7F; |
| | 66548 | 850 | | if (_isServer || payloadLength > 125) |
| | 49815 | 851 | | { |
| | 49815 | 852 | | int minNeeded = |
| | 49815 | 853 | | 2 + |
| | 49815 | 854 | | (_isServer ? MaskLength : 0) + |
| | 49815 | 855 | | (payloadLength <= 125 ? 0 : payloadLength == 126 ? sizeof(ushort) : sizeof(ulong |
| | 49815 | 856 | | await EnsureBufferContainsAsync(minNeeded, cancellationToken).ConfigureAwait(false); |
| | 49783 | 857 | | } |
| | 66516 | 858 | | } |
| | | 859 | | |
| | 365332 | 860 | | string? headerErrorMessage = TryParseMessageHeaderFromReceiveBuffer(out header); |
| | 365332 | 861 | | if (headerErrorMessage != null) |
| | 4491 | 862 | | { |
| | 4491 | 863 | | await CloseWithReceiveErrorAndThrowAsync(WebSocketCloseStatus.ProtocolError, WebSocketEr |
| | 0 | 864 | | } |
| | 360841 | 865 | | _receivedMaskOffsetOffset = 0; |
| | | 866 | | |
| | 360841 | 867 | | if (NetEventSource.Log.IsEnabled()) |
| | 0 | 868 | | { |
| | 0 | 869 | | NetEventSource.Trace(this, $"Next frame opcode={header.Opcode}, fin={header.Fin}, compre |
| | 0 | 870 | | } |
| | | 871 | | |
| | 360841 | 872 | | if (header.PayloadLength == 0 && header.Compressed) |
| | 672 | 873 | | { |
| | | 874 | | // In the rare case where we receive a compressed message with no payload |
| | | 875 | | // we need to tell the inflater about it, because the receive code bellow will |
| | | 876 | | // not try to do anything when PayloadLength == 0. |
| | 672 | 877 | | _inflater!.AddBytes(0, endOfMessage: header.Fin); |
| | 672 | 878 | | } |
| | 360841 | 879 | | } |
| | | 880 | | |
| | | 881 | | // If the header represents a ping or a pong, it's a control message meant |
| | | 882 | | // to be transparent to the user, so handle it and then loop around to read again. |
| | | 883 | | // Alternatively, if it's a close message, handle it and exit. |
| | 369614 | 884 | | if (header.Opcode == MessageOpcode.Ping || header.Opcode == MessageOpcode.Pong) |
| | 30208 | 885 | | { |
| | 30208 | 886 | | await HandleReceivedPingPongAsync(header, cancellationToken).ConfigureAwait(false); |
| | 30187 | 887 | | continue; |
| | | 888 | | } |
| | 339406 | 889 | | else if (header.Opcode == MessageOpcode.Close) |
| | 1301 | 890 | | { |
| | 1301 | 891 | | await HandleReceivedCloseAsync(header, cancellationToken).ConfigureAwait(false); |
| | 45 | 892 | | return GetReceiveResult<TResult>(0, WebSocketMessageType.Close, true); |
| | | 893 | | } |
| | | 894 | | |
| | | 895 | | // If this is a continuation, replace the opcode with the one of the message it's continuing |
| | 338105 | 896 | | if (header.Opcode == MessageOpcode.Continuation) |
| | 76756 | 897 | | { |
| | 76756 | 898 | | header.Opcode = _lastReceiveHeader.Opcode; |
| | 76756 | 899 | | header.Compressed = _lastReceiveHeader.Compressed; |
| | 76756 | 900 | | } |
| | | 901 | | |
| | | 902 | | // The message should now be a binary or text message. Handle it by reading the payload and ret |
| | 338105 | 903 | | Debug.Assert(header.Opcode == MessageOpcode.Binary || header.Opcode == MessageOpcode.Text, $"Une |
| | | 904 | | |
| | | 905 | | // If there's no data to read, return an appropriate result. |
| | 338105 | 906 | | if (header.Processed || payloadBuffer.Length == 0) |
| | 79354 | 907 | | { |
| | 79354 | 908 | | _lastReceiveHeader = header; |
| | 79354 | 909 | | return GetReceiveResult<TResult>( |
| | 79354 | 910 | | count: 0, |
| | 79354 | 911 | | messageType: header.Opcode == MessageOpcode.Text ? WebSocketMessageType.Text : WebSocket |
| | 79354 | 912 | | endOfMessage: header.EndOfMessage); |
| | | 913 | | } |
| | | 914 | | |
| | | 915 | | // Otherwise, read as much of the payload as we can efficiently, and update the header to reflec |
| | | 916 | | // remains for future reads. We first need to copy any data that may be lingering in the receiv |
| | | 917 | | // into the destination; then to minimize ReceiveAsync calls, we want to read as much as we can, |
| | | 918 | | // only when we've either read the whole message or when we've filled the payload buffer. |
| | | 919 | | |
| | | 920 | | // First copy any data lingering in the receive buffer. |
| | 258751 | 921 | | int totalBytesReceived = 0; |
| | | 922 | | |
| | | 923 | | // Only start a new receive if we haven't received the entire frame. |
| | 258751 | 924 | | if (header.PayloadLength > 0) |
| | 258205 | 925 | | { |
| | 258205 | 926 | | if (header.Compressed) |
| | 165 | 927 | | { |
| | 165 | 928 | | Debug.Assert(_inflater is not null); |
| | 165 | 929 | | _inflater.Prepare(header.PayloadLength, payloadBuffer.Length); |
| | 165 | 930 | | } |
| | | 931 | | |
| | | 932 | | // Read directly into the appropriate buffer until we've hit a limit. |
| | 258205 | 933 | | int limit = (int)Math.Min(header.Compressed ? _inflater!.Span.Length : payloadBuffer.Length, |
| | | 934 | | |
| | 258205 | 935 | | if (_receiveBufferCount > 0) |
| | 246024 | 936 | | { |
| | 246024 | 937 | | int receiveBufferBytesToCopy = Math.Min(limit, _receiveBufferCount); |
| | | 938 | | |
| | 246024 | 939 | | _receiveBuffer.Span.Slice(_receiveBufferOffset, receiveBufferBytesToCopy).CopyTo( |
| | 246024 | 940 | | header.Compressed ? _inflater!.Span : payloadBuffer.Span); |
| | 246024 | 941 | | ConsumeFromBuffer(receiveBufferBytesToCopy); |
| | 246024 | 942 | | totalBytesReceived += receiveBufferBytesToCopy; |
| | 246024 | 943 | | } |
| | | 944 | | |
| | 258205 | 945 | | if (totalBytesReceived < limit) |
| | 12941 | 946 | | { |
| | 12941 | 947 | | int bytesToRead = limit - totalBytesReceived; |
| | 12941 | 948 | | Memory<byte> readBuffer = header.Compressed ? |
| | 12941 | 949 | | _inflater!.Memory.Slice(totalBytesReceived, bytesToRead) : |
| | 12941 | 950 | | payloadBuffer.Slice(totalBytesReceived, bytesToRead); |
| | | 951 | | |
| | 12941 | 952 | | int numBytesRead = await _stream.ReadAtLeastAsync( |
| | 12941 | 953 | | readBuffer, bytesToRead, throwOnEndOfStream: false, cancellationToken).ConfigureAwai |
| | | 954 | | |
| | 12941 | 955 | | if (NetEventSource.Log.IsEnabled()) NetEventSource.Trace(this, $"bytesRead={numBytesRead |
| | | 956 | | |
| | 12941 | 957 | | if (numBytesRead < bytesToRead) |
| | 561 | 958 | | { |
| | 561 | 959 | | ThrowEOFUnexpected(); |
| | 0 | 960 | | } |
| | 12380 | 961 | | _keepAlivePingState?.OnDataReceived(); |
| | 12380 | 962 | | totalBytesReceived += numBytesRead; |
| | 12380 | 963 | | } |
| | | 964 | | |
| | 257644 | 965 | | if (_isServer) |
| | 249853 | 966 | | { |
| | 249853 | 967 | | _receivedMaskOffsetOffset = ApplyMask(header.Compressed ? |
| | 249853 | 968 | | _inflater!.Span.Slice(0, totalBytesReceived) : |
| | 249853 | 969 | | payloadBuffer.Span.Slice(0, totalBytesReceived), header.Mask, _receivedMaskOffsetOff |
| | 249853 | 970 | | } |
| | | 971 | | |
| | 257644 | 972 | | header.PayloadLength -= totalBytesReceived; |
| | | 973 | | |
| | 257644 | 974 | | if (header.Compressed) |
| | 136 | 975 | | { |
| | 136 | 976 | | _inflater!.AddBytes(totalBytesReceived, endOfMessage: header.Fin && header.PayloadLength |
| | 136 | 977 | | } |
| | 257644 | 978 | | } |
| | | 979 | | |
| | 258190 | 980 | | if (header.Compressed) |
| | 682 | 981 | | { |
| | | 982 | | // In case of compression totalBytesReceived should actually represent how much we've |
| | | 983 | | // inflated, rather than how much we've read from the stream. |
| | 682 | 984 | | header.Processed = _inflater!.Inflate(payloadBuffer.Span, out totalBytesReceived) && header. |
| | 653 | 985 | | } |
| | | 986 | | else |
| | 257508 | 987 | | { |
| | | 988 | | // Without compression the frame is processed as soon as we've received everything |
| | 257508 | 989 | | header.Processed = header.PayloadLength == 0; |
| | 257508 | 990 | | } |
| | | 991 | | |
| | | 992 | | // If this a text message, validate that it contains valid UTF8. |
| | 258161 | 993 | | if (header.Opcode == MessageOpcode.Text && |
| | 258161 | 994 | | !TryValidateUtf8(payloadBuffer.Span.Slice(0, totalBytesReceived), header.EndOfMessage, _utf8 |
| | 1223 | 995 | | { |
| | 1223 | 996 | | await CloseWithReceiveErrorAndThrowAsync(WebSocketCloseStatus.InvalidPayloadData, WebSocketE |
| | 0 | 997 | | } |
| | | 998 | | |
| | 256938 | 999 | | if (header.Processed) |
| | 251656 | 1000 | | { |
| | 251656 | 1001 | | if (NetEventSource.Log.IsEnabled()) NetEventSource.Trace(this, "Data frame fully processed") |
| | 251656 | 1002 | | } |
| | | 1003 | | |
| | 256938 | 1004 | | _lastReceiveHeader = header; |
| | 256938 | 1005 | | return GetReceiveResult<TResult>( |
| | 256938 | 1006 | | totalBytesReceived, |
| | 256938 | 1007 | | header.Opcode == MessageOpcode.Text ? WebSocketMessageType.Text : WebSocketMessageType.Binar |
| | 256938 | 1008 | | header.EndOfMessage); |
| | | 1009 | | } |
| | | 1010 | | } |
| | | 1011 | | finally |
| | 344880 | 1012 | | { |
| | 344880 | 1013 | | _receiveMutex.Exit(); |
| | 344880 | 1014 | | if (NetEventSource.Log.IsEnabled()) NetEventSource.MutexExited(_receiveMutex); |
| | 344880 | 1015 | | } |
| | | 1016 | | } |
| | 8543 | 1017 | | catch (Exception exc) |
| | 8543 | 1018 | | { |
| | 8543 | 1019 | | if (NetEventSource.Log.IsEnabled()) NetEventSource.TraceException(this, exc); |
| | | 1020 | | |
| | 8543 | 1021 | | if (exc is OperationCanceledException) |
| | 0 | 1022 | | { |
| | 0 | 1023 | | throw; |
| | | 1024 | | } |
| | | 1025 | | |
| | 8543 | 1026 | | if (_state == WebSocketState.Aborted) |
| | 0 | 1027 | | { |
| | 0 | 1028 | | Exception inner = exc; |
| | 0 | 1029 | | if (_keepAlivePingState?.Exception is not null) |
| | 0 | 1030 | | { |
| | | 1031 | | // exception was most likely caused by us aborting the connection due to |
| | | 1032 | | // keep-alive timeout; but let's surface both just in case |
| | 0 | 1033 | | inner = ExceptionDispatchInfo.SetCurrentStackTrace( |
| | 0 | 1034 | | new AggregateException(_keepAlivePingState.Exception, exc)); |
| | 0 | 1035 | | } |
| | | 1036 | | |
| | 0 | 1037 | | throw new OperationCanceledException(nameof(WebSocketState.Aborted), inner); |
| | | 1038 | | } |
| | 8543 | 1039 | | OnAborted(); |
| | | 1040 | | |
| | 8543 | 1041 | | if (exc is WebSocketException) |
| | 8543 | 1042 | | { |
| | 8543 | 1043 | | throw; |
| | | 1044 | | } |
| | | 1045 | | |
| | 0 | 1046 | | throw new WebSocketException(WebSocketError.ConnectionClosedPrematurely, exc); |
| | | 1047 | | } |
| | | 1048 | | finally |
| | 344880 | 1049 | | { |
| | 344880 | 1050 | | registration.Dispose(); |
| | 344880 | 1051 | | if (NetEventSource.Log.IsEnabled()) NetEventSource.ReceiveAsyncPrivateCompleted(this); |
| | 344880 | 1052 | | } |
| | 336337 | 1053 | | } |
| | | 1054 | | |
| | | 1055 | | /// <summary> |
| | | 1056 | | /// Returns either <see cref="ValueWebSocketReceiveResult"/> or <see cref="WebSocketReceiveResult"/>. |
| | | 1057 | | /// </summary> |
| | | 1058 | | [MethodImpl(MethodImplOptions.AggressiveInlining)] |
| | | 1059 | | private TResult GetReceiveResult<TResult>(int count, WebSocketMessageType messageType, bool endOfMessage) |
| | 336337 | 1060 | | { |
| | 336337 | 1061 | | if (typeof(TResult) == typeof(ValueWebSocketReceiveResult)) |
| | 336337 | 1062 | | { |
| | | 1063 | | // Although it might seem that this will incur boxing of the struct, |
| | | 1064 | | // the JIT is smart enough to figure out it is unncessessary and will emit |
| | | 1065 | | // bytecode that returns the ValueWebSocketReceiveResult directly. |
| | 336337 | 1066 | | return (TResult)(object)new ValueWebSocketReceiveResult(count, messageType, endOfMessage); |
| | | 1067 | | } |
| | | 1068 | | |
| | 0 | 1069 | | return (TResult)(object)new WebSocketReceiveResult(count, messageType, endOfMessage, _closeStatus, _closeSta |
| | 336337 | 1070 | | } |
| | | 1071 | | |
| | | 1072 | | /// <summary>Processes a received close message.</summary> |
| | | 1073 | | /// <param name="header">The message header.</param> |
| | | 1074 | | /// <param name="cancellationToken">The CancellationToken used to cancel the websocket operation.</param> |
| | | 1075 | | /// <returns>The received result message.</returns> |
| | | 1076 | | private async ValueTask HandleReceivedCloseAsync(MessageHeader header, CancellationToken cancellationToken) |
| | 1301 | 1077 | | { |
| | 1301 | 1078 | | lock (StateUpdateLock) |
| | 1301 | 1079 | | { |
| | 1301 | 1080 | | _receivedCloseFrame = true; |
| | 1301 | 1081 | | WebSocketState state = _state; |
| | 1301 | 1082 | | if (_sentCloseFrame && state < WebSocketState.Closed) |
| | 47 | 1083 | | { |
| | 47 | 1084 | | _state = WebSocketState.Closed; |
| | 47 | 1085 | | } |
| | 1254 | 1086 | | else if (state < WebSocketState.CloseReceived) |
| | 1254 | 1087 | | { |
| | 1254 | 1088 | | _state = WebSocketState.CloseReceived; |
| | 1254 | 1089 | | } |
| | | 1090 | | |
| | 1301 | 1091 | | if (NetEventSource.Log.IsEnabled()) NetEventSource.Trace(this, $"State transition from {state} to {_stat |
| | 1301 | 1092 | | } |
| | | 1093 | | |
| | 1301 | 1094 | | WebSocketCloseStatus closeStatus = WebSocketCloseStatus.NormalClosure; |
| | 1301 | 1095 | | string closeStatusDescription = string.Empty; |
| | | 1096 | | |
| | | 1097 | | // Handle any payload by parsing it into the close status and description. |
| | 1301 | 1098 | | if (header.PayloadLength == 1) |
| | 29 | 1099 | | { |
| | | 1100 | | // The close payload length can be 0 or >= 2, but not 1. |
| | 29 | 1101 | | await CloseWithReceiveErrorAndThrowAsync(WebSocketCloseStatus.ProtocolError, WebSocketError.Faulted, SR. |
| | 0 | 1102 | | } |
| | 1272 | 1103 | | else if (header.PayloadLength >= 2) |
| | 1230 | 1104 | | { |
| | 1230 | 1105 | | if (_receiveBufferCount < header.PayloadLength) |
| | 1167 | 1106 | | { |
| | 1167 | 1107 | | await EnsureBufferContainsAsync((int)header.PayloadLength, cancellationToken).ConfigureAwait(false); |
| | 1153 | 1108 | | } |
| | | 1109 | | |
| | 1216 | 1110 | | if (_isServer) |
| | 27 | 1111 | | { |
| | 27 | 1112 | | ApplyMask(_receiveBuffer.Span.Slice(_receiveBufferOffset, (int)header.PayloadLength), header.Mask, 0 |
| | 27 | 1113 | | } |
| | | 1114 | | |
| | 1216 | 1115 | | closeStatus = (WebSocketCloseStatus)BinaryPrimitives.ReadUInt16BigEndian(_receiveBuffer.Span.Slice(_rece |
| | 1216 | 1116 | | if (!IsValidCloseStatus(closeStatus)) |
| | 1201 | 1117 | | { |
| | 1201 | 1118 | | await CloseWithReceiveErrorAndThrowAsync(WebSocketCloseStatus.ProtocolError, WebSocketError.Faulted, |
| | 0 | 1119 | | } |
| | | 1120 | | |
| | 15 | 1121 | | if (header.PayloadLength > 2) |
| | 14 | 1122 | | { |
| | | 1123 | | try |
| | 14 | 1124 | | { |
| | 14 | 1125 | | closeStatusDescription = s_textEncoding.GetString(_receiveBuffer.Span.Slice(_receiveBufferOffset |
| | 2 | 1126 | | } |
| | 12 | 1127 | | catch (DecoderFallbackException exc) |
| | 12 | 1128 | | { |
| | 12 | 1129 | | await CloseWithReceiveErrorAndThrowAsync(WebSocketCloseStatus.ProtocolError, WebSocketError.Faul |
| | 0 | 1130 | | } |
| | 2 | 1131 | | } |
| | 3 | 1132 | | ConsumeFromBuffer((int)header.PayloadLength); |
| | 3 | 1133 | | } |
| | | 1134 | | |
| | | 1135 | | // Store the close status and description onto the instance. |
| | 45 | 1136 | | _closeStatus = closeStatus; |
| | 45 | 1137 | | _closeStatusDescription = closeStatusDescription; |
| | | 1138 | | |
| | 45 | 1139 | | if (!_isServer && _sentCloseFrame) |
| | 18 | 1140 | | { |
| | 18 | 1141 | | await WaitForServerToCloseConnectionAsync(enterMutex: false, cancellationToken).ConfigureAwait(false); |
| | 18 | 1142 | | } |
| | 45 | 1143 | | } |
| | | 1144 | | |
| | | 1145 | | /// <summary>Issues a read on the stream to wait for EOF, optionally acquiring <see cref="_receiveMutex"/> first |
| | | 1146 | | private async ValueTask WaitForServerToCloseConnectionAsync(bool enterMutex, CancellationToken cancellationToken |
| | 1246 | 1147 | | { |
| | 1246 | 1148 | | bool mutexEntered = false; |
| | 1246 | 1149 | | Task? task = null; |
| | | 1150 | | try |
| | 1246 | 1151 | | { |
| | 1246 | 1152 | | if (enterMutex) |
| | 36 | 1153 | | { |
| | 36 | 1154 | | await _receiveMutex.EnterAsync(cancellationToken).ConfigureAwait(false); |
| | 36 | 1155 | | mutexEntered = true; |
| | 36 | 1156 | | if (NetEventSource.Log.IsEnabled()) NetEventSource.MutexEntered(_receiveMutex); |
| | 36 | 1157 | | } |
| | | 1158 | | |
| | 1246 | 1159 | | Debug.Assert(_receiveMutex.IsHeld, $"Expected {nameof(_receiveMutex)} to be held"); |
| | | 1160 | | |
| | 1246 | 1161 | | if (NetEventSource.Log.IsEnabled()) NetEventSource.Trace(this); |
| | | 1162 | | |
| | | 1163 | | // Per RFC 6455 7.1.1, try to let the server close the connection. We give it up to a second. |
| | | 1164 | | // We simply issue a read and don't care what we get back; we could validate that we don't get |
| | | 1165 | | // additional data, but at this point we're about to close the connection and we're just stalling |
| | | 1166 | | // to try to get the server to close first. |
| | 1246 | 1167 | | ValueTask<int> finalReadTask = _stream.ReadAsync(_receiveBuffer, cancellationToken); |
| | | 1168 | | |
| | | 1169 | | const int WaitForCloseTimeoutMs = 1_000; // arbitrary amount of time to give the server |
| | 1246 | 1170 | | task = finalReadTask.AsTask(); |
| | | 1171 | | |
| | | 1172 | | #pragma warning disable CA2016 // Token was already provided to the ReadAsync |
| | 1246 | 1173 | | await task.WaitAsync(TimeSpan.FromMilliseconds(WaitForCloseTimeoutMs)).ConfigureAwait(false); |
| | | 1174 | | #pragma warning restore CA2016 |
| | 1246 | 1175 | | } |
| | 0 | 1176 | | catch |
| | 0 | 1177 | | { |
| | 0 | 1178 | | if (task is not null) |
| | 0 | 1179 | | { |
| | 0 | 1180 | | LogExceptions(task); |
| | 0 | 1181 | | } |
| | 0 | 1182 | | Abort(); |
| | 0 | 1183 | | } |
| | | 1184 | | finally |
| | 1246 | 1185 | | { |
| | 1246 | 1186 | | if (mutexEntered) |
| | 36 | 1187 | | { |
| | 36 | 1188 | | _receiveMutex.Exit(); |
| | 36 | 1189 | | if (NetEventSource.Log.IsEnabled()) NetEventSource.MutexExited(_receiveMutex); |
| | 36 | 1190 | | } |
| | 1246 | 1191 | | } |
| | 1246 | 1192 | | } |
| | | 1193 | | |
| | | 1194 | | /// <summary>Processes a received ping or pong message.</summary> |
| | | 1195 | | /// <param name="header">The message header.</param> |
| | | 1196 | | /// <param name="cancellationToken">The CancellationToken used to cancel the websocket operation.</param> |
| | | 1197 | | private async ValueTask HandleReceivedPingPongAsync(MessageHeader header, CancellationToken cancellationToken) |
| | 30208 | 1198 | | { |
| | 30208 | 1199 | | Debug.Assert(_receiveMutex.IsHeld, $"Caller should hold the {nameof(_receiveMutex)}"); |
| | | 1200 | | |
| | 30208 | 1201 | | if (NetEventSource.Log.IsEnabled()) NetEventSource.Trace(this); |
| | | 1202 | | |
| | | 1203 | | // Consume any (optional) payload associated with the ping/pong. |
| | 30208 | 1204 | | if (header.PayloadLength > 0 && _receiveBufferCount < header.PayloadLength) |
| | 2045 | 1205 | | { |
| | 2045 | 1206 | | await EnsureBufferContainsAsync((int)header.PayloadLength, cancellationToken).ConfigureAwait(false); |
| | 2024 | 1207 | | } |
| | | 1208 | | |
| | 30187 | 1209 | | bool processPing = header.Opcode == MessageOpcode.Ping; |
| | | 1210 | | |
| | 30187 | 1211 | | bool processPong = header.Opcode == MessageOpcode.Pong && _keepAlivePingState is not null |
| | 30187 | 1212 | | && header.PayloadLength == KeepAlivePingState.PingPayloadSize; |
| | | 1213 | | |
| | 30187 | 1214 | | if ((processPing || processPong) && _isServer) |
| | 28534 | 1215 | | { |
| | 28534 | 1216 | | ApplyMask(_receiveBuffer.Span.Slice(_receiveBufferOffset, (int)header.PayloadLength), header.Mask, 0); |
| | 28534 | 1217 | | } |
| | | 1218 | | |
| | | 1219 | | // If this was a ping, send back a pong response. |
| | 30187 | 1220 | | if (processPing) |
| | 28971 | 1221 | | { |
| | 28971 | 1222 | | if (NetEventSource.Log.IsEnabled()) NetEventSource.Trace(this, "Processing incoming Ping"); |
| | | 1223 | | |
| | 28971 | 1224 | | await SendFrameAsync( |
| | 28971 | 1225 | | MessageOpcode.Pong, |
| | 28971 | 1226 | | endOfMessage: true, |
| | 28971 | 1227 | | disableCompression: true, |
| | 28971 | 1228 | | _receiveBuffer.Slice(_receiveBufferOffset, (int)header.PayloadLength), |
| | 28971 | 1229 | | cancellationToken).ConfigureAwait(false); |
| | 28971 | 1230 | | } |
| | 1216 | 1231 | | else if (processPong) |
| | 0 | 1232 | | { |
| | 0 | 1233 | | if (NetEventSource.Log.IsEnabled()) NetEventSource.Trace(this, "Processing incoming Pong"); |
| | | 1234 | | |
| | 0 | 1235 | | long pongPayload = BinaryPrimitives.ReadInt64BigEndian(_receiveBuffer.Span.Slice(_receiveBufferOffset, ( |
| | 0 | 1236 | | lock (StateUpdateLock) |
| | 0 | 1237 | | { |
| | 0 | 1238 | | _keepAlivePingState!.OnPongResponseReceived(pongPayload); |
| | 0 | 1239 | | } |
| | 0 | 1240 | | } |
| | | 1241 | | else |
| | 1216 | 1242 | | { |
| | 1216 | 1243 | | if (NetEventSource.Log.IsEnabled()) NetEventSource.Trace(this, "Received Unsolicited Pong. Skipping."); |
| | 1216 | 1244 | | } |
| | | 1245 | | |
| | | 1246 | | // Regardless of whether it was a ping or pong, we no longer need the payload. |
| | 30187 | 1247 | | if (header.PayloadLength > 0) |
| | 29662 | 1248 | | { |
| | 29662 | 1249 | | ConsumeFromBuffer((int)header.PayloadLength); |
| | 29662 | 1250 | | } |
| | 30187 | 1251 | | } |
| | | 1252 | | |
| | | 1253 | | /// <summary>Check whether a close status is valid according to the RFC.</summary> |
| | | 1254 | | /// <param name="closeStatus">The status to validate.</param> |
| | | 1255 | | /// <returns>true if the status if valid; otherwise, false.</returns> |
| | | 1256 | | private static bool IsValidCloseStatus(WebSocketCloseStatus closeStatus) |
| | 1216 | 1257 | | { |
| | | 1258 | | // 0-999: "not used" |
| | | 1259 | | // 1000-2999: reserved for the protocol; we need to check individual codes manually |
| | | 1260 | | // 3000-3999: reserved for use by higher-level code |
| | | 1261 | | // 4000-4999: reserved for private use |
| | | 1262 | | // 5000-: not mentioned in RFC |
| | | 1263 | | |
| | 1216 | 1264 | | if (closeStatus < (WebSocketCloseStatus)1000 || closeStatus >= (WebSocketCloseStatus)5000) |
| | 1028 | 1265 | | { |
| | 1028 | 1266 | | return false; |
| | | 1267 | | } |
| | | 1268 | | |
| | 188 | 1269 | | if (closeStatus >= (WebSocketCloseStatus)3000) |
| | 15 | 1270 | | { |
| | 15 | 1271 | | return true; |
| | | 1272 | | } |
| | | 1273 | | |
| | 173 | 1274 | | switch (closeStatus) // check for the 1000-2999 range known codes |
| | | 1275 | | { |
| | | 1276 | | case WebSocketCloseStatus.EndpointUnavailable: |
| | | 1277 | | case WebSocketCloseStatus.InternalServerError: |
| | | 1278 | | case WebSocketCloseStatus.InvalidMessageType: |
| | | 1279 | | case WebSocketCloseStatus.InvalidPayloadData: |
| | | 1280 | | case WebSocketCloseStatus.MandatoryExtension: |
| | | 1281 | | case WebSocketCloseStatus.MessageTooBig: |
| | | 1282 | | case WebSocketCloseStatus.NormalClosure: |
| | | 1283 | | case WebSocketCloseStatus.PolicyViolation: |
| | | 1284 | | case WebSocketCloseStatus.ProtocolError: |
| | | 1285 | | case (WebSocketCloseStatus)1012: // ServiceRestart |
| | | 1286 | | case (WebSocketCloseStatus)1013: // TryAgainLater |
| | | 1287 | | case (WebSocketCloseStatus)1014: // BadGateway |
| | 0 | 1288 | | return true; |
| | | 1289 | | |
| | | 1290 | | default: |
| | 173 | 1291 | | return false; |
| | | 1292 | | } |
| | 1216 | 1293 | | } |
| | | 1294 | | |
| | | 1295 | | /// <summary>Send a close message to the server and throw an exception, in response to getting bad data from the |
| | | 1296 | | /// <param name="closeStatus">The close status code to use.</param> |
| | | 1297 | | /// <param name="error">The error reason.</param> |
| | | 1298 | | /// <param name="errorMessage">An optional error message to include in the thrown exception.</param> |
| | | 1299 | | /// <param name="innerException">An optional inner exception to include in the thrown exception.</param> |
| | | 1300 | | private async ValueTask CloseWithReceiveErrorAndThrowAsync( |
| | | 1301 | | WebSocketCloseStatus closeStatus, WebSocketError error, string? errorMessage = null, Exception? innerExcepti |
| | 6956 | 1302 | | { |
| | 6956 | 1303 | | Debug.Assert(_receiveMutex.IsHeld, $"Caller should hold the {nameof(_receiveMutex)}"); |
| | | 1304 | | |
| | 6956 | 1305 | | if (NetEventSource.Log.IsEnabled()) NetEventSource.Trace(this, errorMessage); |
| | | 1306 | | |
| | | 1307 | | // Caller holds _receiveMutex; don't re-enter it for the EOF wait. |
| | 6956 | 1308 | | if (!_sentCloseFrame) |
| | 2592 | 1309 | | { |
| | 2592 | 1310 | | await CloseOutputAsyncCore(closeStatus, string.Empty, enterReceiveMutex: false, cancellationToken: defau |
| | 2592 | 1311 | | } |
| | | 1312 | | |
| | | 1313 | | // Dump our receive buffer; we're in a bad state to do any further processing |
| | 6956 | 1314 | | _receiveBufferCount = 0; |
| | | 1315 | | |
| | | 1316 | | // Let the caller know we've failed |
| | 6956 | 1317 | | throw errorMessage != null ? |
| | 6956 | 1318 | | new WebSocketException(error, errorMessage, innerException) : |
| | 6956 | 1319 | | new WebSocketException(error, innerException); |
| | | 1320 | | } |
| | | 1321 | | |
| | | 1322 | | /// <summary>Parses a message header from the buffer. This assumes the header is in the buffer.</summary> |
| | | 1323 | | /// <param name="resultHeader">The read header.</param> |
| | | 1324 | | /// <returns>null if a valid header was read; non-null containing the string error message to use if the header |
| | | 1325 | | private string? TryParseMessageHeaderFromReceiveBuffer(out MessageHeader resultHeader) |
| | 365332 | 1326 | | { |
| | 365332 | 1327 | | Debug.Assert(_receiveBufferCount >= 2, "Expected to at least have the first two bytes of the header."); |
| | | 1328 | | |
| | 365332 | 1329 | | MessageHeader header = default; |
| | 365332 | 1330 | | Span<byte> receiveBufferSpan = _receiveBuffer.Span; |
| | | 1331 | | |
| | 365332 | 1332 | | header.Fin = (receiveBufferSpan[_receiveBufferOffset] & 0x80) != 0; |
| | 365332 | 1333 | | bool reservedSet = (receiveBufferSpan[_receiveBufferOffset] & 0b_0011_0000) != 0; |
| | 365332 | 1334 | | header.Opcode = (MessageOpcode)(receiveBufferSpan[_receiveBufferOffset] & 0xF); |
| | 365332 | 1335 | | header.Compressed = (receiveBufferSpan[_receiveBufferOffset] & 0b_0100_0000) != 0; |
| | | 1336 | | |
| | 365332 | 1337 | | bool masked = (receiveBufferSpan[_receiveBufferOffset + 1] & 0x80) != 0; |
| | 365332 | 1338 | | header.PayloadLength = receiveBufferSpan[_receiveBufferOffset + 1] & 0x7F; |
| | | 1339 | | |
| | 365332 | 1340 | | ConsumeFromBuffer(2); |
| | | 1341 | | |
| | | 1342 | | // Read the remainder of the payload length, if necessary |
| | 365332 | 1343 | | if (header.PayloadLength == 126) |
| | 256 | 1344 | | { |
| | 256 | 1345 | | Debug.Assert(_receiveBufferCount >= 2, "Expected to have two bytes for the payload length."); |
| | 256 | 1346 | | header.PayloadLength = BinaryPrimitives.ReadUInt16BigEndian(receiveBufferSpan.Slice(_receiveBufferOffset |
| | 256 | 1347 | | ConsumeFromBuffer(2); |
| | 256 | 1348 | | } |
| | 365076 | 1349 | | else if (header.PayloadLength == 127) |
| | 431 | 1350 | | { |
| | 431 | 1351 | | Debug.Assert(_receiveBufferCount >= 8, "Expected to have eight bytes for the payload length."); |
| | 431 | 1352 | | header.PayloadLength = BinaryPrimitives.ReadInt64BigEndian(receiveBufferSpan.Slice(_receiveBufferOffset) |
| | 431 | 1353 | | ConsumeFromBuffer(8); |
| | 431 | 1354 | | } |
| | | 1355 | | |
| | 365332 | 1356 | | if (reservedSet) |
| | 1732 | 1357 | | { |
| | 1732 | 1358 | | resultHeader = default; |
| | 1732 | 1359 | | return SR.net_Websockets_ReservedBitsSet; |
| | | 1360 | | } |
| | | 1361 | | |
| | 363600 | 1362 | | if (header.PayloadLength < 0) |
| | 186 | 1363 | | { |
| | | 1364 | | // as per RFC, if payload length is a 64-bit integer, the most significant bit MUST be 0 |
| | | 1365 | | // frame-payload-length-63 = %x0000000000000000-7FFFFFFFFFFFFFFF; 64 bits in length |
| | 186 | 1366 | | resultHeader = default; |
| | 186 | 1367 | | return SR.net_Websockets_InvalidPayloadLength; |
| | | 1368 | | } |
| | | 1369 | | |
| | 363414 | 1370 | | if (header.Compressed && _inflater is null) |
| | 166 | 1371 | | { |
| | 166 | 1372 | | resultHeader = default; |
| | 166 | 1373 | | return SR.net_Websockets_PerMessageCompressedFlagWhenNotEnabled; |
| | | 1374 | | } |
| | | 1375 | | |
| | 363248 | 1376 | | if (masked) |
| | 278681 | 1377 | | { |
| | 278681 | 1378 | | if (!_isServer) |
| | 363 | 1379 | | { |
| | 363 | 1380 | | resultHeader = default; |
| | 363 | 1381 | | return SR.net_Websockets_ClientReceivedMaskedFrame; |
| | | 1382 | | } |
| | 278318 | 1383 | | header.Mask = CombineMaskBytes(receiveBufferSpan, _receiveBufferOffset); |
| | | 1384 | | |
| | | 1385 | | // Consume the mask bytes |
| | 278318 | 1386 | | ConsumeFromBuffer(4); |
| | 278318 | 1387 | | } |
| | 84567 | 1388 | | else if (_isServer) |
| | 721 | 1389 | | { |
| | 721 | 1390 | | resultHeader = default; |
| | 721 | 1391 | | return SR.net_Websockets_ServerReceivedUnmaskedFrame; |
| | | 1392 | | } |
| | | 1393 | | |
| | | 1394 | | // Do basic validation of the header |
| | 362164 | 1395 | | switch (header.Opcode) |
| | | 1396 | | { |
| | | 1397 | | case MessageOpcode.Continuation: |
| | 76939 | 1398 | | if (_lastReceiveHeader.Fin) |
| | 178 | 1399 | | { |
| | | 1400 | | // Can't continue from a final message |
| | 178 | 1401 | | resultHeader = default; |
| | 178 | 1402 | | return SR.net_Websockets_ContinuationFromFinalFrame; |
| | | 1403 | | } |
| | 76761 | 1404 | | if (header.Compressed) |
| | 5 | 1405 | | { |
| | | 1406 | | // Must not mark continuations as compressed |
| | 5 | 1407 | | resultHeader = default; |
| | 5 | 1408 | | return SR.net_Websockets_PerMessageCompressedFlagInContinuation; |
| | | 1409 | | } |
| | | 1410 | | |
| | | 1411 | | // Set the compressed flag from the previous header so the receive procedure can use it |
| | | 1412 | | // directly without needing to check the previous header in case of continuations. |
| | 76756 | 1413 | | header.Compressed = _lastReceiveHeader.Compressed; |
| | 76756 | 1414 | | break; |
| | | 1415 | | |
| | | 1416 | | case MessageOpcode.Binary: |
| | | 1417 | | case MessageOpcode.Text: |
| | 253197 | 1418 | | if (!_lastReceiveHeader.Fin) |
| | 621 | 1419 | | { |
| | | 1420 | | // Must continue from a non-final message |
| | 621 | 1421 | | resultHeader = default; |
| | 621 | 1422 | | return SR.net_Websockets_NonContinuationAfterNonFinalFrame; |
| | | 1423 | | } |
| | 252576 | 1424 | | break; |
| | | 1425 | | |
| | | 1426 | | case MessageOpcode.Close: |
| | | 1427 | | case MessageOpcode.Ping: |
| | | 1428 | | case MessageOpcode.Pong: |
| | 31669 | 1429 | | if (header.PayloadLength > MaxControlPayloadLength || !header.Fin) |
| | 160 | 1430 | | { |
| | | 1431 | | // Invalid control messgae |
| | 160 | 1432 | | resultHeader = default; |
| | 160 | 1433 | | return SR.net_Websockets_InvalidControlMessage; |
| | | 1434 | | } |
| | 31509 | 1435 | | break; |
| | | 1436 | | |
| | | 1437 | | default: |
| | | 1438 | | // Unknown opcode |
| | 359 | 1439 | | resultHeader = default; |
| | 359 | 1440 | | return SR.Format(SR.net_Websockets_UnknownOpcode, header.Opcode); |
| | | 1441 | | } |
| | | 1442 | | |
| | | 1443 | | // Return the read header |
| | 360841 | 1444 | | header.Processed = header.PayloadLength == 0 && !header.Compressed; |
| | 360841 | 1445 | | resultHeader = header; |
| | 360841 | 1446 | | return null; |
| | 365332 | 1447 | | } |
| | | 1448 | | |
| | | 1449 | | /// <summary>Send a close message, then receive until we get a close response message.</summary> |
| | | 1450 | | /// <param name="closeStatus">The close status to send.</param> |
| | | 1451 | | /// <param name="statusDescription">The close status description to send.</param> |
| | | 1452 | | /// <param name="cancellationToken">The CancellationToken to use to cancel the websocket.</param> |
| | | 1453 | | private async Task CloseAsyncPrivate(WebSocketCloseStatus closeStatus, string? statusDescription, CancellationTo |
| | 5618 | 1454 | | { |
| | 5618 | 1455 | | if (NetEventSource.Log.IsEnabled()) NetEventSource.CloseAsyncPrivateStarted(this); |
| | | 1456 | | try |
| | 5618 | 1457 | | { |
| | | 1458 | | // Send the close message. Skip sending a close frame if we're currently in a CloseSent state, |
| | | 1459 | | // for example having just done a CloseOutputAsync. |
| | 5618 | 1460 | | if (!_sentCloseFrame) |
| | 5565 | 1461 | | { |
| | 5565 | 1462 | | await SendCloseFrameAsync(closeStatus, statusDescription, cancellationToken).ConfigureAwait(false); |
| | 5565 | 1463 | | } |
| | | 1464 | | |
| | | 1465 | | // We should now either be in a CloseSent case (because we just sent one), or in a Closed state, in case |
| | | 1466 | | // there was a concurrent receive that ended up handling an immediate close frame response from the serv |
| | | 1467 | | // Of course it could also be Aborted if something happened concurrently to cause things to blow up. |
| | 5618 | 1468 | | Debug.Assert( |
| | 5618 | 1469 | | State == WebSocketState.CloseSent || |
| | 5618 | 1470 | | State == WebSocketState.Closed || |
| | 5618 | 1471 | | State == WebSocketState.Aborted, |
| | 5618 | 1472 | | $"Unexpected state {State}."); |
| | | 1473 | | |
| | | 1474 | | // We only need to wait for a received close frame if we are in the CloseSent State. If we are in the Cl |
| | | 1475 | | // State then it means we already received a close frame. If we are in the Aborted State, then we should |
| | | 1476 | | // wait for a close frame as per RFC 6455 Section 7.1.7 "Fail the WebSocket Connection". |
| | 5618 | 1477 | | if (State == WebSocketState.CloseSent) |
| | 5601 | 1478 | | { |
| | 5601 | 1479 | | if (NetEventSource.Log.IsEnabled()) NetEventSource.Trace(this, "Waiting for a close frame"); |
| | | 1480 | | |
| | | 1481 | | // Wait until we've received a close response |
| | 5601 | 1482 | | byte[] closeBuffer = ArrayPool<byte>.Shared.Rent(MaxMessageHeaderLength + MaxControlPayloadLength); |
| | | 1483 | | try |
| | 5601 | 1484 | | { |
| | | 1485 | | // Loop until we've received a close frame. |
| | 322005 | 1486 | | while (!_receivedCloseFrame) |
| | 321987 | 1487 | | { |
| | | 1488 | | // Enter the receive lock in order to get a consistent view of whether we've received a clos |
| | | 1489 | | // frame. If we haven't, issue a receive. Since that receive will try to take the same |
| | | 1490 | | // non-entrant receive lock, we then exit the lock before waiting for the receive to complet |
| | | 1491 | | // as it will always complete asynchronously and only after we've exited the lock. |
| | 321987 | 1492 | | ValueTask<ValueWebSocketReceiveResult> receiveTask = default; |
| | | 1493 | | try |
| | 321987 | 1494 | | { |
| | 321987 | 1495 | | await _receiveMutex.EnterAsync(cancellationToken).ConfigureAwait(false); |
| | 321987 | 1496 | | if (NetEventSource.Log.IsEnabled()) NetEventSource.MutexEntered(_receiveMutex); |
| | | 1497 | | |
| | | 1498 | | try |
| | 321987 | 1499 | | { |
| | 321987 | 1500 | | if (!_receivedCloseFrame) |
| | 321987 | 1501 | | { |
| | 321987 | 1502 | | receiveTask = ReceiveAsyncPrivate<ValueWebSocketReceiveResult>(closeBuffer, canc |
| | 321987 | 1503 | | } |
| | 321987 | 1504 | | } |
| | | 1505 | | finally |
| | 321987 | 1506 | | { |
| | 321987 | 1507 | | _receiveMutex.Exit(); |
| | 321987 | 1508 | | if (NetEventSource.Log.IsEnabled()) NetEventSource.MutexExited(_receiveMutex); |
| | 321987 | 1509 | | } |
| | 321987 | 1510 | | } |
| | 0 | 1511 | | catch (OperationCanceledException) |
| | 0 | 1512 | | { |
| | | 1513 | | // If waiting on the receive lock was canceled, abort the connection, as we would do |
| | | 1514 | | // as part of the receive itself. |
| | 0 | 1515 | | Abort(); |
| | 0 | 1516 | | throw; |
| | | 1517 | | } |
| | | 1518 | | |
| | | 1519 | | // Wait for the receive to complete if we issued one. |
| | 321987 | 1520 | | await receiveTask.ConfigureAwait(false); |
| | 316404 | 1521 | | } |
| | 18 | 1522 | | } |
| | | 1523 | | finally |
| | 5601 | 1524 | | { |
| | 5601 | 1525 | | ArrayPool<byte>.Shared.Return(closeBuffer); |
| | 5601 | 1526 | | } |
| | 18 | 1527 | | } |
| | | 1528 | | |
| | | 1529 | | // Polite EOF wait under the receive mutex; avoids racing the receive loop on the stream. |
| | 35 | 1530 | | if (!_isServer && _receivedCloseFrame) |
| | 35 | 1531 | | { |
| | 35 | 1532 | | await WaitForServerToCloseConnectionAsync(enterMutex: true, cancellationToken).ConfigureAwait(false) |
| | 35 | 1533 | | } |
| | | 1534 | | |
| | | 1535 | | // We're closed. Close the connection and update the status. |
| | 35 | 1536 | | lock (StateUpdateLock) |
| | 35 | 1537 | | { |
| | 35 | 1538 | | DisposeCore(); |
| | 35 | 1539 | | } |
| | 35 | 1540 | | } |
| | 5583 | 1541 | | catch (Exception exc) |
| | 5583 | 1542 | | { |
| | 5583 | 1543 | | if (NetEventSource.Log.IsEnabled()) NetEventSource.TraceException(this, exc); |
| | 5583 | 1544 | | throw; |
| | | 1545 | | } |
| | | 1546 | | finally |
| | 5618 | 1547 | | { |
| | 5618 | 1548 | | if (NetEventSource.Log.IsEnabled()) NetEventSource.CloseAsyncPrivateCompleted(this); |
| | 5618 | 1549 | | } |
| | 35 | 1550 | | } |
| | | 1551 | | |
| | | 1552 | | |
| | | 1553 | | /// <summary>Sends a close message to the server.</summary> |
| | | 1554 | | /// <param name="closeStatus">The close status to send.</param> |
| | | 1555 | | /// <param name="closeStatusDescription">The close status description to send.</param> |
| | | 1556 | | /// <param name="cancellationToken">The CancellationToken to use to cancel the websocket.</param> |
| | | 1557 | | private async ValueTask SendCloseFrameAsync(WebSocketCloseStatus closeStatus, string? closeStatusDescription, Ca |
| | 8249 | 1558 | | { |
| | | 1559 | | // Close payload is two bytes containing the close status followed by a UTF8-encoding of the status descript |
| | | 1560 | | |
| | 8249 | 1561 | | byte[]? buffer = null; |
| | | 1562 | | try |
| | 8249 | 1563 | | { |
| | 8249 | 1564 | | int count = 2; |
| | 8249 | 1565 | | if (string.IsNullOrEmpty(closeStatusDescription)) |
| | 5266 | 1566 | | { |
| | 5266 | 1567 | | buffer = ArrayPool<byte>.Shared.Rent(count); |
| | 5266 | 1568 | | } |
| | | 1569 | | else |
| | 2983 | 1570 | | { |
| | 2983 | 1571 | | count += s_textEncoding.GetByteCount(closeStatusDescription); |
| | 2983 | 1572 | | buffer = ArrayPool<byte>.Shared.Rent(count); |
| | 2983 | 1573 | | int encodedLength = s_textEncoding.GetBytes(closeStatusDescription, 0, closeStatusDescription.Length |
| | 2983 | 1574 | | Debug.Assert(count - 2 == encodedLength, $"{nameof(s_textEncoding.GetByteCount)} and {nameof(s_textE |
| | 2983 | 1575 | | } |
| | | 1576 | | |
| | 8249 | 1577 | | BinaryPrimitives.WriteUInt16BigEndian(buffer, (ushort)closeStatus); |
| | | 1578 | | |
| | 8249 | 1579 | | await SendFrameAsync(MessageOpcode.Close, endOfMessage: true, disableCompression: true, new Memory<byte> |
| | 8249 | 1580 | | } |
| | | 1581 | | finally |
| | 8249 | 1582 | | { |
| | 8249 | 1583 | | if (buffer != null) |
| | 8249 | 1584 | | { |
| | 8249 | 1585 | | ArrayPool<byte>.Shared.Return(buffer); |
| | 8249 | 1586 | | } |
| | 8249 | 1587 | | } |
| | | 1588 | | |
| | 8249 | 1589 | | lock (StateUpdateLock) |
| | 8249 | 1590 | | { |
| | 8249 | 1591 | | _sentCloseFrame = true; |
| | 8249 | 1592 | | WebSocketState state = _state; |
| | 8249 | 1593 | | if (_receivedCloseFrame && state < WebSocketState.Closed) |
| | 1235 | 1594 | | { |
| | 1235 | 1595 | | _state = WebSocketState.Closed; |
| | 1235 | 1596 | | } |
| | 7014 | 1597 | | else if (state < WebSocketState.CloseSent) |
| | 7014 | 1598 | | { |
| | 7014 | 1599 | | _state = WebSocketState.CloseSent; |
| | 7014 | 1600 | | } |
| | | 1601 | | |
| | 8249 | 1602 | | if (NetEventSource.Log.IsEnabled()) NetEventSource.Trace(this, $"State transition from {state} to {_stat |
| | 8249 | 1603 | | } |
| | 8249 | 1604 | | } |
| | | 1605 | | |
| | | 1606 | | private void ConsumeFromBuffer(int count) |
| | 920026 | 1607 | | { |
| | 920026 | 1608 | | Debug.Assert(count >= 0, $"Expected non-negative {nameof(count)}, got {count}"); |
| | 920026 | 1609 | | Debug.Assert(count <= _receiveBufferCount, $"Trying to consume {count}, which is more than exists {_receiveB |
| | 920026 | 1610 | | _receiveBufferCount -= count; |
| | 920026 | 1611 | | _receiveBufferOffset += count; |
| | 920026 | 1612 | | } |
| | | 1613 | | |
| | | 1614 | | [AsyncMethodBuilder(typeof(PoolingAsyncValueTaskMethodBuilder))] |
| | | 1615 | | [RuntimeAsyncMethodGeneration(false)] |
| | | 1616 | | private async ValueTask EnsureBufferContainsAsync(int minimumRequiredBytes, CancellationToken cancellationToken) |
| | 78803 | 1617 | | { |
| | 78803 | 1618 | | Debug.Assert(minimumRequiredBytes <= _receiveBuffer.Length, $"Requested number of bytes {minimumRequiredByte |
| | | 1619 | | |
| | | 1620 | | // If we don't have enough data in the buffer to satisfy the minimum required, read some more. |
| | 78803 | 1621 | | if (_receiveBufferCount < minimumRequiredBytes) |
| | 42360 | 1622 | | { |
| | | 1623 | | // If there's any data in the buffer, shift it down. |
| | 42360 | 1624 | | if (_receiveBufferCount > 0) |
| | 19994 | 1625 | | { |
| | 19994 | 1626 | | _receiveBuffer.Span.Slice(_receiveBufferOffset, _receiveBufferCount).CopyTo(_receiveBuffer.Span); |
| | 19994 | 1627 | | } |
| | 42360 | 1628 | | _receiveBufferOffset = 0; |
| | | 1629 | | |
| | 42360 | 1630 | | int bytesToRead = minimumRequiredBytes - _receiveBufferCount; |
| | 42360 | 1631 | | int numRead = await _stream.ReadAtLeastAsync( |
| | 42360 | 1632 | | _receiveBuffer.Slice(_receiveBufferCount), bytesToRead, throwOnEndOfStream: false, cancellationToken |
| | 42360 | 1633 | | _receiveBufferCount += numRead; |
| | | 1634 | | |
| | 42360 | 1635 | | if (NetEventSource.Log.IsEnabled()) NetEventSource.Trace(this, $"bytesRead={numRead}"); |
| | | 1636 | | |
| | 42360 | 1637 | | if (numRead < bytesToRead) |
| | 997 | 1638 | | { |
| | 997 | 1639 | | ThrowEOFUnexpected(); |
| | 0 | 1640 | | } |
| | 41363 | 1641 | | _keepAlivePingState?.OnDataReceived(); |
| | 41363 | 1642 | | } |
| | 77806 | 1643 | | } |
| | | 1644 | | |
| | | 1645 | | private void ThrowEOFUnexpected() |
| | 1558 | 1646 | | { |
| | | 1647 | | // The connection closed before we were able to read everything we needed. |
| | | 1648 | | // If it was due to us being disposed, fail with the correct exception. |
| | | 1649 | | // Otherwise, it was due to the connection being closed and it wasn't expected. |
| | 1558 | 1650 | | ThrowIfDisposed(); |
| | 1558 | 1651 | | throw new WebSocketException(WebSocketError.ConnectionClosedPrematurely); |
| | | 1652 | | } |
| | | 1653 | | |
| | | 1654 | | /// <summary>Gets a send buffer from the pool.</summary> |
| | | 1655 | | private void AllocateSendBuffer(int minLength) |
| | 37439 | 1656 | | { |
| | 37439 | 1657 | | Debug.Assert(_sendBuffer == null); // would only fail if had some catastrophic error previously that prevent |
| | 37439 | 1658 | | _sendBuffer = ArrayPool<byte>.Shared.Rent(minLength); |
| | 37439 | 1659 | | } |
| | | 1660 | | |
| | | 1661 | | /// <summary>Releases the send buffer to the pool.</summary> |
| | | 1662 | | private void ReleaseSendBuffer() |
| | 37439 | 1663 | | { |
| | 37439 | 1664 | | Debug.Assert(_sendMutex.IsHeld, $"Caller should hold the {nameof(_sendMutex)}"); |
| | | 1665 | | |
| | 37439 | 1666 | | if (_sendBuffer is byte[] toReturn) |
| | 37439 | 1667 | | { |
| | 37439 | 1668 | | _sendBuffer = null; |
| | 37439 | 1669 | | ArrayPool<byte>.Shared.Return(toReturn); |
| | 37439 | 1670 | | } |
| | 37439 | 1671 | | } |
| | | 1672 | | |
| | | 1673 | | private static int CombineMaskBytes(ReadOnlySpan<byte> buffer, int maskOffset) => |
| | 283711 | 1674 | | BitConverter.ToInt32(buffer.Slice(maskOffset)); |
| | | 1675 | | |
| | | 1676 | | /// <summary>Applies a mask to a portion of a byte array.</summary> |
| | | 1677 | | /// <param name="toMask">The buffer to which the mask should be applied.</param> |
| | | 1678 | | /// <param name="mask">The array containing the mask to apply.</param> |
| | | 1679 | | /// <param name="maskOffset">The offset into <paramref name="mask"/> of the mask to apply of length <see cref="M |
| | | 1680 | | /// <param name="maskOffsetIndex">The next position offset from <paramref name="maskOffset"/> of which by to app |
| | | 1681 | | /// <returns>The updated maskOffsetOffset value.</returns> |
| | | 1682 | | private static int ApplyMask(Span<byte> toMask, byte[] mask, int maskOffset, int maskOffsetIndex) |
| | 5393 | 1683 | | { |
| | 5393 | 1684 | | Debug.Assert(maskOffsetIndex < MaskLength, $"Unexpected {nameof(maskOffsetIndex)}: {maskOffsetIndex}"); |
| | 5393 | 1685 | | Debug.Assert(mask.Length >= MaskLength + maskOffset, $"Unexpected inputs: {mask.Length}, {maskOffset}"); |
| | 5393 | 1686 | | return ApplyMask(toMask, CombineMaskBytes(mask, maskOffset), maskOffsetIndex); |
| | 5393 | 1687 | | } |
| | | 1688 | | |
| | | 1689 | | /// <summary>Applies a mask to a portion of a byte array.</summary> |
| | | 1690 | | /// <param name="toMask">The buffer to which the mask should be applied.</param> |
| | | 1691 | | /// <param name="mask">The four-byte mask, stored as an Int32.</param> |
| | | 1692 | | /// <param name="maskIndex">The index into the mask.</param> |
| | | 1693 | | /// <returns>The next index into the mask to be used for future applications of the mask.</returns> |
| | | 1694 | | private static int ApplyMask(Span<byte> toMask, int mask, int maskIndex) |
| | 283807 | 1695 | | { |
| | 283807 | 1696 | | Debug.Assert(maskIndex < sizeof(int)); |
| | | 1697 | | |
| | 283807 | 1698 | | if (toMask.Length >= sizeof(int)) |
| | 23060 | 1699 | | { |
| | 23060 | 1700 | | int rolledMask = BitConverter.IsLittleEndian ? |
| | 23060 | 1701 | | (int)BitOperations.RotateRight((uint)mask, maskIndex * 8) : |
| | 23060 | 1702 | | (int)BitOperations.RotateLeft((uint)mask, maskIndex * 8); |
| | | 1703 | | |
| | | 1704 | | // Process Vector<byte>.Count bytes at a time. |
| | 23060 | 1705 | | if (Vector.IsHardwareAccelerated && toMask.Length >= Vector<byte>.Count) |
| | 289 | 1706 | | { |
| | 289 | 1707 | | Vector<byte> maskVector = Vector.AsVectorByte(new Vector<int>(rolledMask)); |
| | | 1708 | | do |
| | 895 | 1709 | | { |
| | 895 | 1710 | | (new Vector<byte>(toMask) ^ maskVector).CopyTo(toMask); |
| | 895 | 1711 | | toMask = toMask.Slice(Vector<byte>.Count); |
| | 895 | 1712 | | } |
| | 895 | 1713 | | while (toMask.Length >= Vector<byte>.Count); |
| | 289 | 1714 | | } |
| | | 1715 | | |
| | | 1716 | | // Process 4 bytes at a time. |
| | 70523 | 1717 | | while (toMask.Length >= sizeof(int)) |
| | 47463 | 1718 | | { |
| | 47463 | 1719 | | BitConverter.TryWriteBytes(toMask, BitConverter.ToInt32(toMask) ^ rolledMask); |
| | 47463 | 1720 | | toMask = toMask.Slice(sizeof(int)); |
| | 47463 | 1721 | | } |
| | 23060 | 1722 | | } |
| | | 1723 | | |
| | | 1724 | | // Process 1 byte at a time, using the mask byte at native memory offset maskIndex. |
| | 1162036 | 1725 | | for (int i = 0; i < toMask.Length; i++) |
| | 297211 | 1726 | | { |
| | 297211 | 1727 | | toMask[i] ^= (byte)(mask >> ((BitConverter.IsLittleEndian ? maskIndex : 3 - maskIndex) * 8)); |
| | 297211 | 1728 | | maskIndex = (maskIndex + 1) & 3; |
| | 297211 | 1729 | | } |
| | | 1730 | | |
| | 283807 | 1731 | | return maskIndex; |
| | 283807 | 1732 | | } |
| | | 1733 | | |
| | | 1734 | | /// <summary>Aborts the websocket and throws an exception if an existing operation is in progress.</summary> |
| | | 1735 | | private void ThrowIfOperationInProgress(bool operationCompleted, [CallerMemberName] string? methodName = null) |
| | | 1736 | | { |
| | | 1737 | | if (!operationCompleted) |
| | | 1738 | | { |
| | | 1739 | | Abort(); |
| | | 1740 | | ThrowOperationInProgress(methodName); |
| | | 1741 | | } |
| | | 1742 | | } |
| | | 1743 | | |
| | | 1744 | | private static void ThrowOperationInProgress(string? methodName) => throw new InvalidOperationException(SR.Forma |
| | | 1745 | | |
| | | 1746 | | /// <summary>Creates an OperationCanceledException instance, using a default message and the specified inner exc |
| | | 1747 | | private static OperationCanceledException CreateOperationCanceledException(Exception innerException, Cancellatio |
| | 0 | 1748 | | { |
| | 0 | 1749 | | return (OperationCanceledException)ExceptionDispatchInfo.SetCurrentStackTrace(new OperationCanceledException |
| | 0 | 1750 | | new OperationCanceledException().Message, |
| | 0 | 1751 | | innerException, |
| | 0 | 1752 | | cancellationToken)); |
| | 0 | 1753 | | } |
| | | 1754 | | |
| | 383877 | 1755 | | private void ThrowIfDisposed() => ThrowIfInvalidState(validStates: ManagedWebSocketStates.All); |
| | | 1756 | | |
| | | 1757 | | private void ThrowIfInvalidState(ManagedWebSocketStates validStates) |
| | 415390 | 1758 | | { |
| | 415390 | 1759 | | bool disposed = _disposed; |
| | 415390 | 1760 | | WebSocketState state = _state; |
| | 415390 | 1761 | | Exception? keepAliveException = null; |
| | | 1762 | | |
| | 415390 | 1763 | | if (_keepAlivePingState is not null) |
| | 0 | 1764 | | { |
| | | 1765 | | // we need to take a lock to maintain consistency |
| | 0 | 1766 | | lock (StateUpdateLock) |
| | 0 | 1767 | | { |
| | 0 | 1768 | | disposed = _disposed; |
| | 0 | 1769 | | state = _state; |
| | 0 | 1770 | | keepAliveException = _keepAlivePingState.Exception; |
| | 0 | 1771 | | } |
| | 0 | 1772 | | } |
| | | 1773 | | |
| | 415390 | 1774 | | if (NetEventSource.Log.IsEnabled()) NetEventSource.Trace(this, $"_state={state}, _disposed={disposed}, _keep |
| | | 1775 | | |
| | 415390 | 1776 | | WebSocketStateHelper.ThrowIfInvalidState(state, disposed, keepAliveException, validStates); |
| | 415291 | 1777 | | } |
| | | 1778 | | |
| | | 1779 | | // From https://github.com/aspnet/WebSockets/blob/aa63e27fce2e9202698053620679a9a1059b501e/src/Microsoft.AspNetC |
| | | 1780 | | // Performs a stateful validation of UTF-8 bytes. |
| | | 1781 | | // It checks for valid formatting, overlong encodings, surrogates, and value ranges. |
| | | 1782 | | private static bool TryValidateUtf8(ReadOnlySpan<byte> span, bool endOfMessage, Utf8MessageState state) |
| | 255771 | 1783 | | { |
| | | 1784 | | // If no prior segment spilled over and this one is the last, we can validate it efficiently as a complete m |
| | 255771 | 1785 | | if (endOfMessage && !state.SequenceInProgress) |
| | 248351 | 1786 | | { |
| | 248351 | 1787 | | return Utf8.IsValid(span); |
| | | 1788 | | } |
| | | 1789 | | |
| | 15105 | 1790 | | for (int i = 0; i < span.Length;) |
| | 6836 | 1791 | | { |
| | | 1792 | | // Have we started a character sequence yet? |
| | 6836 | 1793 | | if (!state.SequenceInProgress) |
| | 6706 | 1794 | | { |
| | | 1795 | | // Skip past ASCII bytes. |
| | 6706 | 1796 | | int firstNonAscii = span.Slice(i).IndexOfAnyExceptInRange((byte)0, (byte)127); |
| | 6706 | 1797 | | if (firstNonAscii < 0) |
| | 6188 | 1798 | | { |
| | 6188 | 1799 | | break; |
| | | 1800 | | } |
| | 518 | 1801 | | i += firstNonAscii; |
| | | 1802 | | |
| | | 1803 | | // The first byte tells us how many bytes are in the sequence. |
| | 518 | 1804 | | state.SequenceInProgress = true; |
| | 518 | 1805 | | byte b = span[i]; |
| | 518 | 1806 | | i++; |
| | 518 | 1807 | | Debug.Assert((b & 0x80) != 0, "Should have already skipped past ASCII"); |
| | 518 | 1808 | | if ((b & 0xC0) == 0x80) |
| | 133 | 1809 | | { |
| | | 1810 | | // Misplaced 10bbbbbb continuation byte. This cannot be the first byte. |
| | 133 | 1811 | | return false; |
| | | 1812 | | } |
| | 385 | 1813 | | else if ((b & 0xE0) == 0xC0) // 110bbbbb 10bbbbbb |
| | 167 | 1814 | | { |
| | 167 | 1815 | | state.AdditionalBytesExpected = 1; |
| | 167 | 1816 | | state.CurrentDecodeBits = b & 0x1F; |
| | 167 | 1817 | | state.ExpectedValueMin = 0x80; |
| | 167 | 1818 | | } |
| | 218 | 1819 | | else if ((b & 0xF0) == 0xE0) // 1110bbbb 10bbbbbb 10bbbbbb |
| | 34 | 1820 | | { |
| | 34 | 1821 | | state.AdditionalBytesExpected = 2; |
| | 34 | 1822 | | state.CurrentDecodeBits = b & 0xF; |
| | 34 | 1823 | | state.ExpectedValueMin = 0x800; |
| | 34 | 1824 | | } |
| | 184 | 1825 | | else if ((b & 0xF8) == 0xF0) // 11110bbb 10bbbbbb 10bbbbbb 10bbbbbb |
| | 61 | 1826 | | { |
| | 61 | 1827 | | state.AdditionalBytesExpected = 3; |
| | 61 | 1828 | | state.CurrentDecodeBits = b & 0x7; |
| | 61 | 1829 | | state.ExpectedValueMin = 0x10000; |
| | 61 | 1830 | | } |
| | | 1831 | | else // 111110bb & 1111110b & 11111110 && 11111111 are not valid |
| | 123 | 1832 | | { |
| | 123 | 1833 | | return false; |
| | | 1834 | | } |
| | 262 | 1835 | | } |
| | | 1836 | | |
| | 527 | 1837 | | while (state.AdditionalBytesExpected > 0 && i < span.Length) |
| | 255 | 1838 | | { |
| | 255 | 1839 | | byte b = span[i]; |
| | 255 | 1840 | | if ((b & 0xC0) != 0x80) |
| | 112 | 1841 | | { |
| | 112 | 1842 | | return false; |
| | | 1843 | | } |
| | | 1844 | | |
| | 143 | 1845 | | i++; |
| | 143 | 1846 | | state.AdditionalBytesExpected--; |
| | | 1847 | | |
| | | 1848 | | // Each continuation byte carries 6 bits of data 0x10bbbbbb. |
| | 143 | 1849 | | state.CurrentDecodeBits = (state.CurrentDecodeBits << 6) | (b & 0x3F); |
| | | 1850 | | |
| | 143 | 1851 | | if (state.AdditionalBytesExpected == 1 && state.CurrentDecodeBits >= 0x360 && state.CurrentDecodeBit |
| | 1 | 1852 | | { |
| | | 1853 | | // This is going to end up in the range of 0xD800-0xDFFF UTF-16 surrogates that are not allowed |
| | 1 | 1854 | | return false; |
| | | 1855 | | } |
| | | 1856 | | |
| | 142 | 1857 | | if (state.AdditionalBytesExpected == 2 && state.CurrentDecodeBits >= 0x110) |
| | 7 | 1858 | | { |
| | | 1859 | | // This is going to be out of the upper Unicode bound 0x10FFFF. |
| | 7 | 1860 | | return false; |
| | | 1861 | | } |
| | 135 | 1862 | | } |
| | | 1863 | | |
| | 272 | 1864 | | if (state.AdditionalBytesExpected == 0) |
| | 119 | 1865 | | { |
| | 119 | 1866 | | state.SequenceInProgress = false; |
| | 119 | 1867 | | if (state.CurrentDecodeBits < state.ExpectedValueMin) |
| | 7 | 1868 | | { |
| | | 1869 | | // Overlong encoding (e.g. using 2 bytes to encode something that only needed 1). |
| | 7 | 1870 | | return false; |
| | | 1871 | | } |
| | 112 | 1872 | | } |
| | 265 | 1873 | | } |
| | | 1874 | | |
| | 7037 | 1875 | | return !endOfMessage || !state.SequenceInProgress; |
| | 255771 | 1876 | | } |
| | | 1877 | | |
| | | 1878 | | // "Observe" either a ValueTask result, or any exception, logging and ignoring it |
| | | 1879 | | // to prevent the unobserved exception event from being raised. |
| | | 1880 | | private void LogExceptions(ValueTask t) |
| | 0 | 1881 | | { |
| | 0 | 1882 | | if (t.IsCompletedSuccessfully) |
| | 0 | 1883 | | { |
| | 0 | 1884 | | t.GetAwaiter().GetResult(); |
| | 0 | 1885 | | } |
| | | 1886 | | else |
| | 0 | 1887 | | { |
| | 0 | 1888 | | LogExceptions(t.AsTask()); |
| | 0 | 1889 | | } |
| | 0 | 1890 | | } |
| | | 1891 | | |
| | | 1892 | | // "Observe" and log any exception, ignoring it to prevent the unobserved task |
| | | 1893 | | // exception event from being raised. |
| | | 1894 | | private void LogExceptions(Task t) |
| | 0 | 1895 | | { |
| | 0 | 1896 | | if (t.IsCompleted) |
| | 0 | 1897 | | { |
| | 0 | 1898 | | if (t.IsFaulted) |
| | 0 | 1899 | | { |
| | 0 | 1900 | | LogFaulted(t, this); |
| | 0 | 1901 | | } |
| | 0 | 1902 | | } |
| | | 1903 | | else |
| | 0 | 1904 | | { |
| | 0 | 1905 | | t.ContinueWith( |
| | 0 | 1906 | | LogFaulted, |
| | 0 | 1907 | | this, |
| | 0 | 1908 | | CancellationToken.None, |
| | 0 | 1909 | | TaskContinuationOptions.OnlyOnFaulted | TaskContinuationOptions.ExecuteSynchronously, |
| | 0 | 1910 | | TaskScheduler.Default); |
| | 0 | 1911 | | } |
| | | 1912 | | |
| | | 1913 | | static void LogFaulted(Task task, object? thisObj) |
| | 0 | 1914 | | { |
| | 0 | 1915 | | Debug.Assert(task.IsFaulted); |
| | | 1916 | | |
| | | 1917 | | // accessing exception to observe it regardless of whether the tracing is enabled |
| | 0 | 1918 | | Exception e = task.Exception!.InnerException!; |
| | | 1919 | | |
| | 0 | 1920 | | if (NetEventSource.Log.IsEnabled()) NetEventSource.TraceException(thisObj, e); |
| | 0 | 1921 | | } |
| | 0 | 1922 | | } |
| | | 1923 | | |
| | | 1924 | | internal static void ThrowIfInvalidMessageType(WebSocketMessageType messageType, [CallerArgumentExpression(nameo |
| | 236 | 1925 | | { |
| | 236 | 1926 | | if (messageType is not (WebSocketMessageType.Text or WebSocketMessageType.Binary)) |
| | 0 | 1927 | | { |
| | 0 | 1928 | | ThrowInvalidMessageType(messageType, paramName); |
| | 0 | 1929 | | } |
| | | 1930 | | |
| | | 1931 | | static void ThrowInvalidMessageType(WebSocketMessageType messageType, string? paramName) => |
| | 0 | 1932 | | throw new ArgumentException(SR.Format( |
| | 0 | 1933 | | SR.net_WebSockets_Argument_InvalidMessageType, |
| | 0 | 1934 | | messageType, nameof(SendAsync), nameof(WebSocketMessageType.Binary), nameof(WebSocketMessageType.Tex |
| | 0 | 1935 | | paramName); |
| | 236 | 1936 | | } |
| | | 1937 | | |
| | | 1938 | | private sealed class Utf8MessageState |
| | | 1939 | | { |
| | | 1940 | | internal bool SequenceInProgress; |
| | | 1941 | | internal int AdditionalBytesExpected; |
| | | 1942 | | internal int ExpectedValueMin; |
| | | 1943 | | internal int CurrentDecodeBits; |
| | | 1944 | | } |
| | | 1945 | | |
| | | 1946 | | private enum MessageOpcode : byte |
| | | 1947 | | { |
| | | 1948 | | Continuation = 0x0, |
| | | 1949 | | Text = 0x1, |
| | | 1950 | | Binary = 0x2, |
| | | 1951 | | Close = 0x8, |
| | | 1952 | | Ping = 0x9, |
| | | 1953 | | Pong = 0xA |
| | | 1954 | | } |
| | | 1955 | | |
| | | 1956 | | [StructLayout(LayoutKind.Auto)] |
| | | 1957 | | private struct MessageHeader |
| | | 1958 | | { |
| | | 1959 | | internal MessageOpcode Opcode; |
| | | 1960 | | internal bool Fin; |
| | | 1961 | | internal long PayloadLength; |
| | | 1962 | | internal bool Compressed; |
| | | 1963 | | internal int Mask; |
| | | 1964 | | |
| | | 1965 | | /// <summary> |
| | | 1966 | | /// Returns if frame has been received and processed. |
| | | 1967 | | /// </summary> |
| | 2097230 | 1968 | | internal bool Processed { get; set; } |
| | | 1969 | | |
| | | 1970 | | /// <summary> |
| | | 1971 | | /// Returns if message has been received and processed. |
| | | 1972 | | /// </summary> |
| | 592063 | 1973 | | internal bool EndOfMessage => Fin && Processed && PayloadLength == 0; |
| | | 1974 | | } |
| | | 1975 | | } |
| | | 1976 | | } |
| | | 1977 | | |