| | | 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.Diagnostics; |
| | | 5 | | using System.Diagnostics.CodeAnalysis; |
| | | 6 | | using System.IO; |
| | | 7 | | using System.Runtime.ExceptionServices; |
| | | 8 | | using System.Threading; |
| | | 9 | | using System.Threading.Tasks; |
| | | 10 | | |
| | | 11 | | namespace System.Net.WebSockets |
| | | 12 | | { |
| | | 13 | | /// <summary>Provides a <see cref="Stream"/> that delegates to a wrapped <see cref="WebSocket"/>.</summary> |
| | | 14 | | public class WebSocketStream : Stream |
| | | 15 | | { |
| | | 16 | | /// <summary>The default number of seconds before canceling CloseAsync operation issued during stream disposal.< |
| | | 17 | | private const int DefaultCloseTimeoutSeconds = 16; |
| | | 18 | | |
| | | 19 | | /// <summary>Whether the stream has been disposed.</summary> |
| | | 20 | | private bool _disposed; |
| | | 21 | | |
| | | 22 | | /// <summary> |
| | | 23 | | /// Initializes a new instance of the <see cref="WebSocketStream"/> class using a specified <see cref="WebSocket |
| | | 24 | | /// </summary> |
| | | 25 | | /// <param name="webSocket">The <see cref="WebSocket"/> wrapped by this instance.</param> |
| | 0 | 26 | | private WebSocketStream(WebSocket webSocket) => WebSocket = webSocket; |
| | | 27 | | |
| | | 28 | | /// <summary>Creates a <see cref="WebSocketStream"/> that delegates to a wrapped <see cref="WebSocket"/>.</summa |
| | | 29 | | /// <param name="webSocket">The wrapped <see cref="WebSocket"/>.</param> |
| | | 30 | | /// <param name="writeMessageType">The type of messages that should be written as part of <see cref="M:Stream.Wr |
| | | 31 | | /// <param name="ownsWebSocket"> |
| | | 32 | | /// <see langword="true"/> if disposing the <see cref="Stream"/> should close the underlying <see cref="WebSocke |
| | | 33 | | /// </param> |
| | | 34 | | /// <returns>A new instance of <see cref="WebSocketStream"/> that forwards reads and writes on the <see cref="St |
| | | 35 | | public static WebSocketStream Create(WebSocket webSocket, WebSocketMessageType writeMessageType, bool ownsWebSoc |
| | 0 | 36 | | { |
| | 0 | 37 | | ArgumentNullException.ThrowIfNull(webSocket); |
| | 0 | 38 | | ManagedWebSocket.ThrowIfInvalidMessageType(writeMessageType); |
| | | 39 | | |
| | 0 | 40 | | return new ReadWriteStream( |
| | 0 | 41 | | webSocket, |
| | 0 | 42 | | writeMessageType, |
| | 0 | 43 | | closeTimeout: ownsWebSocket ? TimeSpan.FromSeconds(DefaultCloseTimeoutSeconds) : null); |
| | 0 | 44 | | } |
| | | 45 | | |
| | | 46 | | /// <summary>Creates a <see cref="WebSocketStream"/> that delegates to a wrapped <see cref="WebSocket"/>.</summa |
| | | 47 | | /// <param name="webSocket">The wrapped <see cref="WebSocket"/>.</param> |
| | | 48 | | /// <param name="writeMessageType">The type of messages that should be written as part of <see cref="M:Stream.Wr |
| | | 49 | | /// <param name="closeTimeout">The amount of time that disposing the <see cref="WebSocketStream"/> will wait for |
| | | 50 | | /// <returns>A new instance of <see cref="WebSocketStream"/> that forwards reads and writes on the <see cref="St |
| | | 51 | | public static WebSocketStream Create(WebSocket webSocket, WebSocketMessageType writeMessageType, TimeSpan closeT |
| | 0 | 52 | | { |
| | 0 | 53 | | ArgumentNullException.ThrowIfNull(webSocket); |
| | 0 | 54 | | ManagedWebSocket.ThrowIfInvalidMessageType(writeMessageType); |
| | 0 | 55 | | if (closeTimeout < TimeSpan.Zero && closeTimeout != Timeout.InfiniteTimeSpan) |
| | 0 | 56 | | { |
| | 0 | 57 | | throw new ArgumentOutOfRangeException(nameof(closeTimeout), SR.net_WebSockets_TimeoutOutOfRange); |
| | | 58 | | } |
| | | 59 | | |
| | 0 | 60 | | return new ReadWriteStream(webSocket, writeMessageType, closeTimeout); |
| | 0 | 61 | | } |
| | | 62 | | |
| | | 63 | | /// <summary>Creates a <see cref="WebSocketStream"/> that writes a single message to the underlying <see cref="W |
| | | 64 | | /// <param name="webSocket">The wrapped <see cref="WebSocket"/>.</param> |
| | | 65 | | /// <param name="writeMessageType"> |
| | | 66 | | /// The type of messages that should be written as part of <see cref="M:Stream.WriteAsync"/> calls. |
| | | 67 | | /// Each write on the <see cref="Stream"/> results in writing a partial message to the underlying <see cref="Web |
| | | 68 | | /// When the <see cref="Stream"/> is disposed, it will write an empty message to the underlying <see cref="WebSo |
| | | 69 | | /// </param> |
| | | 70 | | /// <returns>A new instance of <see cref="WebSocketStream"/> that forwards writes on the <see cref="Stream"/> to |
| | | 71 | | public static WebSocketStream CreateWritableMessageStream(WebSocket webSocket, WebSocketMessageType writeMessage |
| | 0 | 72 | | { |
| | 0 | 73 | | ArgumentNullException.ThrowIfNull(webSocket); |
| | 0 | 74 | | ManagedWebSocket.ThrowIfInvalidMessageType(writeMessageType); |
| | | 75 | | |
| | 0 | 76 | | return new WriteMessageStream(webSocket, writeMessageType); |
| | 0 | 77 | | } |
| | | 78 | | |
| | | 79 | | /// <summary>Creates a <see cref="WebSocketStream"/> that reads a single message from the underlying <see cref=" |
| | | 80 | | /// <param name="webSocket">The wrapped <see cref="WebSocket"/>.</param> |
| | | 81 | | /// <returns>A new instance of <see cref="WebSocketStream"/> that forwards reads on the <see cref="Stream"/> to |
| | | 82 | | /// <remarks> |
| | | 83 | | /// Reads on the <see cref="Stream"/> will read a single message from the underlying <see cref="WebSocket"/>. Th |
| | | 84 | | /// 0 bytes read once all data has been consumed from the next message received in the <see cref="WebSocket"/>. |
| | | 85 | | /// </remarks> |
| | | 86 | | public static WebSocketStream CreateReadableMessageStream(WebSocket webSocket) |
| | 0 | 87 | | { |
| | 0 | 88 | | ArgumentNullException.ThrowIfNull(webSocket); |
| | | 89 | | |
| | 0 | 90 | | return new ReadMessageStream(webSocket); |
| | 0 | 91 | | } |
| | | 92 | | |
| | | 93 | | /// <summary>Gets the underlying <see cref="WebSocket"/> wrapped by this <see cref="WebSocketStream"/>.</summary |
| | | 94 | | /// <remarks>The <see cref="WebSocket"/> used to construct this instance.</remarks> |
| | 0 | 95 | | public WebSocket WebSocket { get; } |
| | | 96 | | |
| | | 97 | | /// <inheritdoc /> |
| | 0 | 98 | | public override bool CanRead => !_disposed && WebSocket.State is WebSocketState.Open or WebSocketState.CloseSent |
| | | 99 | | |
| | | 100 | | /// <inheritdoc /> |
| | 0 | 101 | | public override bool CanWrite => !_disposed && WebSocket.State is WebSocketState.Open or WebSocketState.CloseRec |
| | | 102 | | |
| | | 103 | | /// <inheritdoc /> |
| | 0 | 104 | | public override bool CanSeek => false; |
| | | 105 | | |
| | | 106 | | /// <inheritdoc /> |
| | | 107 | | protected override void Dispose(bool disposing) |
| | 0 | 108 | | { |
| | 0 | 109 | | if (disposing) |
| | 0 | 110 | | { |
| | | 111 | | // There are no synchronous operations on WebSocket, so we're forced to do sync-over-async. |
| | 0 | 112 | | DisposeAsync().AsTask().GetAwaiter().GetResult(); |
| | 0 | 113 | | } |
| | 0 | 114 | | } |
| | | 115 | | |
| | | 116 | | /// <inheritdoc /> |
| | 0 | 117 | | public override void Flush() { } |
| | | 118 | | |
| | | 119 | | /// <inheritdoc /> |
| | | 120 | | public override Task FlushAsync(CancellationToken cancellationToken) => |
| | 0 | 121 | | cancellationToken.IsCancellationRequested ? Task.FromCanceled(cancellationToken) : |
| | 0 | 122 | | Task.CompletedTask; |
| | | 123 | | |
| | | 124 | | /// <inheritdoc /> |
| | | 125 | | public override Task<int> ReadAsync(byte[] buffer, int offset, int count, CancellationToken cancellationToken) |
| | 0 | 126 | | { |
| | 0 | 127 | | ValidateBufferArguments(buffer, offset, count); |
| | | 128 | | |
| | 0 | 129 | | return ReadAsync(buffer.AsMemory(offset, count), cancellationToken).AsTask(); |
| | 0 | 130 | | } |
| | | 131 | | |
| | | 132 | | /// <inheritdoc /> |
| | | 133 | | public override ValueTask<int> ReadAsync(Memory<byte> buffer, CancellationToken cancellationToken = default) => |
| | 0 | 134 | | ValueTask.FromException<int>(ExceptionDispatchInfo.SetCurrentStackTrace(new NotSupportedException())); |
| | | 135 | | |
| | | 136 | | /// <inheritdoc /> |
| | | 137 | | public override IAsyncResult BeginRead(byte[] buffer, int offset, int count, AsyncCallback? callback, object? st |
| | 0 | 138 | | TaskToAsyncResult.Begin(ReadAsync(buffer, offset, count), callback, state); |
| | | 139 | | |
| | | 140 | | /// <inheritdoc /> |
| | | 141 | | public override int EndRead(IAsyncResult asyncResult) => |
| | 0 | 142 | | TaskToAsyncResult.End<int>(asyncResult); |
| | | 143 | | |
| | | 144 | | /// <inheritdoc /> |
| | | 145 | | public override Task WriteAsync(byte[] buffer, int offset, int count, CancellationToken cancellationToken) |
| | 0 | 146 | | { |
| | 0 | 147 | | ValidateBufferArguments(buffer, offset, count); |
| | | 148 | | |
| | 0 | 149 | | return WriteAsync(buffer.AsMemory(offset, count), cancellationToken).AsTask(); |
| | 0 | 150 | | } |
| | | 151 | | |
| | | 152 | | /// <inheritdoc /> |
| | | 153 | | public override ValueTask WriteAsync(ReadOnlyMemory<byte> buffer, CancellationToken cancellationToken = default) |
| | 0 | 154 | | ValueTask.FromException(ExceptionDispatchInfo.SetCurrentStackTrace(new NotSupportedException())); |
| | | 155 | | |
| | | 156 | | /// <inheritdoc /> |
| | | 157 | | public override IAsyncResult BeginWrite(byte[] buffer, int offset, int count, AsyncCallback? callback, object? s |
| | 0 | 158 | | TaskToAsyncResult.Begin(WriteAsync(buffer, offset, count), callback, state); |
| | | 159 | | |
| | | 160 | | /// <inheritdoc /> |
| | | 161 | | public override void EndWrite(IAsyncResult asyncResult) => |
| | 0 | 162 | | TaskToAsyncResult.End(asyncResult); |
| | | 163 | | |
| | | 164 | | /// <inheritdoc /> |
| | | 165 | | public override int Read(byte[] buffer, int offset, int count) => |
| | 0 | 166 | | ReadAsync(buffer, offset, count, default).GetAwaiter().GetResult(); |
| | | 167 | | |
| | | 168 | | /// <inheritdoc /> |
| | | 169 | | public override void Write(byte[] buffer, int offset, int count) => |
| | 0 | 170 | | WriteAsync(buffer, offset, count, default).GetAwaiter().GetResult(); |
| | | 171 | | |
| | | 172 | | /// <inheritdoc /> |
| | 0 | 173 | | public override long Length => throw new NotSupportedException(); |
| | | 174 | | |
| | | 175 | | /// <inheritdoc /> |
| | | 176 | | public override long Position |
| | | 177 | | { |
| | 0 | 178 | | get => throw new NotSupportedException(); |
| | 0 | 179 | | set => throw new NotSupportedException(); |
| | | 180 | | } |
| | | 181 | | |
| | | 182 | | /// <inheritdoc /> |
| | 0 | 183 | | public override long Seek(long offset, SeekOrigin origin) => throw new NotSupportedException(); |
| | | 184 | | |
| | | 185 | | /// <inheritdoc /> |
| | 0 | 186 | | public override void SetLength(long value) => throw new NotSupportedException(); |
| | | 187 | | |
| | | 188 | | /// <summary>Provides stream that wraps a <see cref="WebSocket"/> and forwards reads/writes.</summary> |
| | 0 | 189 | | private sealed class ReadWriteStream(WebSocket webSocket, WebSocketMessageType writeMessageType, TimeSpan? close |
| | | 190 | | { |
| | 0 | 191 | | private readonly WebSocketMessageType _messageType = writeMessageType; |
| | 0 | 192 | | private readonly TimeSpan? _closeTimeout = closeTimeout; |
| | | 193 | | |
| | | 194 | | /// <inheritdoc /> |
| | | 195 | | public override ValueTask WriteAsync(ReadOnlyMemory<byte> buffer, CancellationToken cancellationToken = defa |
| | 0 | 196 | | { |
| | 0 | 197 | | if (_disposed) |
| | 0 | 198 | | { |
| | 0 | 199 | | return ValueTask.FromException(ExceptionDispatchInfo.SetCurrentStackTrace(new ObjectDisposedExceptio |
| | | 200 | | } |
| | | 201 | | |
| | 0 | 202 | | if (!CanWrite) |
| | 0 | 203 | | { |
| | 0 | 204 | | return ValueTask.FromException(ExceptionDispatchInfo.SetCurrentStackTrace(new NotSupportedException( |
| | | 205 | | } |
| | | 206 | | |
| | 0 | 207 | | if (cancellationToken.IsCancellationRequested) |
| | 0 | 208 | | { |
| | 0 | 209 | | return ValueTask.FromCanceled(cancellationToken); |
| | | 210 | | } |
| | | 211 | | |
| | 0 | 212 | | return WebSocket.SendAsync(buffer, _messageType, endOfMessage: true, cancellationToken); |
| | 0 | 213 | | } |
| | | 214 | | |
| | | 215 | | /// <inheritdoc /> |
| | | 216 | | public override async ValueTask<int> ReadAsync(Memory<byte> buffer, CancellationToken cancellationToken = de |
| | 0 | 217 | | { |
| | 0 | 218 | | ObjectDisposedException.ThrowIf(_disposed, this); |
| | | 219 | | |
| | 0 | 220 | | if (!CanRead) |
| | 0 | 221 | | { |
| | 0 | 222 | | throw new NotSupportedException(SR.NotReadableStream); |
| | | 223 | | } |
| | | 224 | | |
| | 0 | 225 | | cancellationToken.ThrowIfCancellationRequested(); |
| | | 226 | | |
| | 0 | 227 | | while (WebSocket.State < WebSocketState.CloseReceived) |
| | 0 | 228 | | { |
| | 0 | 229 | | ValueWebSocketReceiveResult result = await WebSocket.ReceiveAsync(buffer, cancellationToken).Configu |
| | 0 | 230 | | if (result.MessageType is WebSocketMessageType.Close) |
| | 0 | 231 | | { |
| | 0 | 232 | | break; |
| | | 233 | | } |
| | | 234 | | |
| | 0 | 235 | | if (result.Count > 0 || buffer.IsEmpty) |
| | 0 | 236 | | { |
| | 0 | 237 | | return result.Count; |
| | | 238 | | } |
| | 0 | 239 | | } |
| | | 240 | | |
| | 0 | 241 | | return 0; |
| | 0 | 242 | | } |
| | | 243 | | |
| | | 244 | | /// <inheritdoc /> |
| | | 245 | | public override async ValueTask DisposeAsync() |
| | 0 | 246 | | { |
| | 0 | 247 | | if (!_disposed) |
| | 0 | 248 | | { |
| | 0 | 249 | | _disposed = true; |
| | | 250 | | |
| | 0 | 251 | | if (_closeTimeout is { } timeout) |
| | 0 | 252 | | { |
| | 0 | 253 | | if (WebSocket.State is < WebSocketState.Closed) |
| | 0 | 254 | | { |
| | 0 | 255 | | CancellationTokenSource? cts = null; |
| | | 256 | | CancellationToken ct; |
| | | 257 | | |
| | 0 | 258 | | if (timeout == default) |
| | 0 | 259 | | { |
| | 0 | 260 | | ct = new CancellationToken(canceled: true); |
| | 0 | 261 | | } |
| | 0 | 262 | | else if (timeout == Timeout.InfiniteTimeSpan) |
| | 0 | 263 | | { |
| | 0 | 264 | | ct = CancellationToken.None; |
| | 0 | 265 | | } |
| | | 266 | | else |
| | 0 | 267 | | { |
| | 0 | 268 | | cts = new CancellationTokenSource(timeout); |
| | 0 | 269 | | ct = cts.Token; |
| | 0 | 270 | | } |
| | | 271 | | |
| | | 272 | | try |
| | 0 | 273 | | { |
| | 0 | 274 | | await WebSocket.CloseAsync(WebSocketCloseStatus.NormalClosure, null, ct).ConfigureAwait( |
| | 0 | 275 | | } |
| | | 276 | | finally |
| | 0 | 277 | | { |
| | 0 | 278 | | cts?.Dispose(); |
| | 0 | 279 | | } |
| | 0 | 280 | | } |
| | | 281 | | |
| | 0 | 282 | | WebSocket.Dispose(); |
| | 0 | 283 | | } |
| | 0 | 284 | | } |
| | 0 | 285 | | } |
| | | 286 | | } |
| | | 287 | | |
| | | 288 | | /// <summary>Provides a stream that wraps a <see cref="WebSocket"/> and writes a single message.</summary> |
| | 0 | 289 | | private sealed class WriteMessageStream(WebSocket webSocket, WebSocketMessageType writeMessageType) : WebSocketS |
| | | 290 | | { |
| | 0 | 291 | | private readonly WebSocketMessageType _messageType = writeMessageType; |
| | | 292 | | |
| | | 293 | | /// <inheritdoc /> |
| | 0 | 294 | | public override bool CanRead => false; |
| | | 295 | | |
| | | 296 | | /// <inheritdoc /> |
| | | 297 | | public override ValueTask WriteAsync(ReadOnlyMemory<byte> buffer, CancellationToken cancellationToken = defa |
| | 0 | 298 | | { |
| | 0 | 299 | | if (_disposed) |
| | 0 | 300 | | { |
| | 0 | 301 | | return ValueTask.FromException(ExceptionDispatchInfo.SetCurrentStackTrace(new ObjectDisposedExceptio |
| | | 302 | | } |
| | | 303 | | |
| | 0 | 304 | | if (!CanWrite) |
| | 0 | 305 | | { |
| | 0 | 306 | | return ValueTask.FromException(ExceptionDispatchInfo.SetCurrentStackTrace(new NotSupportedException( |
| | | 307 | | } |
| | | 308 | | |
| | 0 | 309 | | if (cancellationToken.IsCancellationRequested) |
| | 0 | 310 | | { |
| | 0 | 311 | | return ValueTask.FromCanceled(cancellationToken); |
| | | 312 | | } |
| | | 313 | | |
| | 0 | 314 | | return WebSocket.SendAsync(buffer, _messageType, endOfMessage: false, cancellationToken); |
| | 0 | 315 | | } |
| | | 316 | | |
| | | 317 | | public override ValueTask DisposeAsync() |
| | 0 | 318 | | { |
| | 0 | 319 | | if (!_disposed) |
| | 0 | 320 | | { |
| | 0 | 321 | | _disposed = true; |
| | 0 | 322 | | return WebSocket.SendAsync(ReadOnlyMemory<byte>.Empty, _messageType, endOfMessage: true, Cancellatio |
| | | 323 | | } |
| | | 324 | | |
| | 0 | 325 | | return default; |
| | 0 | 326 | | } |
| | | 327 | | } |
| | | 328 | | |
| | | 329 | | /// <summary>Provides a stream that wraps a <see cref="WebSocket"/> and reads a single message.</summary> |
| | 0 | 330 | | private sealed class ReadMessageStream(WebSocket webSocket) : WebSocketStream(webSocket) |
| | | 331 | | { |
| | | 332 | | /// <summary>Whether we've seen and end-of-message marker.</summary> |
| | | 333 | | private bool _eof; |
| | | 334 | | |
| | | 335 | | /// <inheritdoc /> |
| | 0 | 336 | | public override bool CanWrite => false; |
| | | 337 | | |
| | | 338 | | /// <inheritdoc /> |
| | | 339 | | public override async ValueTask<int> ReadAsync(Memory<byte> buffer, CancellationToken cancellationToken = de |
| | 0 | 340 | | { |
| | 0 | 341 | | ObjectDisposedException.ThrowIf(_disposed, this); |
| | | 342 | | |
| | 0 | 343 | | if (!CanRead) |
| | 0 | 344 | | { |
| | 0 | 345 | | throw new NotSupportedException(SR.NotReadableStream); |
| | | 346 | | } |
| | | 347 | | |
| | 0 | 348 | | cancellationToken.ThrowIfCancellationRequested(); |
| | | 349 | | |
| | 0 | 350 | | while (!_eof && WebSocket.State < WebSocketState.CloseReceived) |
| | 0 | 351 | | { |
| | 0 | 352 | | ValueWebSocketReceiveResult result = await WebSocket.ReceiveAsync(buffer, cancellationToken).Configu |
| | 0 | 353 | | if (result.MessageType is WebSocketMessageType.Close) |
| | 0 | 354 | | { |
| | 0 | 355 | | break; |
| | | 356 | | } |
| | | 357 | | |
| | 0 | 358 | | if (result.EndOfMessage) |
| | 0 | 359 | | { |
| | 0 | 360 | | _eof = true; |
| | 0 | 361 | | } |
| | | 362 | | |
| | 0 | 363 | | if (result.Count > 0 || buffer.IsEmpty) |
| | 0 | 364 | | { |
| | 0 | 365 | | return result.Count; |
| | | 366 | | } |
| | 0 | 367 | | } |
| | | 368 | | |
| | 0 | 369 | | return 0; |
| | 0 | 370 | | } |
| | | 371 | | |
| | | 372 | | /// <inheritdoc /> |
| | | 373 | | public override ValueTask DisposeAsync() |
| | 0 | 374 | | { |
| | 0 | 375 | | _disposed = true; |
| | 0 | 376 | | if (!_eof && WebSocket.State < WebSocketState.CloseReceived) |
| | 0 | 377 | | { |
| | 0 | 378 | | WebSocket.Abort(); |
| | 0 | 379 | | } |
| | 0 | 380 | | return default; |
| | 0 | 381 | | } |
| | | 382 | | } |
| | | 383 | | } |
| | | 384 | | } |
| | | 385 | | |