| | | 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.ComponentModel; |
| | | 6 | | using System.IO; |
| | | 7 | | using System.Runtime.InteropServices; |
| | | 8 | | using System.Threading; |
| | | 9 | | using System.Threading.Tasks; |
| | | 10 | | |
| | | 11 | | namespace System.Net.WebSockets |
| | | 12 | | { |
| | | 13 | | public abstract class WebSocket : IDisposable |
| | | 14 | | { |
| | | 15 | | public abstract WebSocketCloseStatus? CloseStatus { get; } |
| | | 16 | | public abstract string? CloseStatusDescription { get; } |
| | | 17 | | public abstract string? SubProtocol { get; } |
| | | 18 | | public abstract WebSocketState State { get; } |
| | | 19 | | |
| | | 20 | | public abstract void Abort(); |
| | | 21 | | public abstract Task CloseAsync(WebSocketCloseStatus closeStatus, |
| | | 22 | | string? statusDescription, |
| | | 23 | | CancellationToken cancellationToken); |
| | | 24 | | public abstract Task CloseOutputAsync(WebSocketCloseStatus closeStatus, |
| | | 25 | | string? statusDescription, |
| | | 26 | | CancellationToken cancellationToken); |
| | | 27 | | public abstract void Dispose(); |
| | | 28 | | public abstract Task<WebSocketReceiveResult> ReceiveAsync(ArraySegment<byte> buffer, |
| | | 29 | | CancellationToken cancellationToken); |
| | | 30 | | public abstract Task SendAsync(ArraySegment<byte> buffer, |
| | | 31 | | WebSocketMessageType messageType, |
| | | 32 | | bool endOfMessage, |
| | | 33 | | CancellationToken cancellationToken); |
| | | 34 | | |
| | | 35 | | public virtual async ValueTask<ValueWebSocketReceiveResult> ReceiveAsync(Memory<byte> buffer, CancellationToken |
| | 0 | 36 | | { |
| | 0 | 37 | | if (MemoryMarshal.TryGetArray(buffer, out ArraySegment<byte> arraySegment)) |
| | 0 | 38 | | { |
| | 0 | 39 | | WebSocketReceiveResult r = await ReceiveAsync(arraySegment, cancellationToken).ConfigureAwait(false); |
| | 0 | 40 | | return new ValueWebSocketReceiveResult(r.Count, r.MessageType, r.EndOfMessage); |
| | | 41 | | } |
| | | 42 | | |
| | 0 | 43 | | byte[] array = ArrayPool<byte>.Shared.Rent(buffer.Length); |
| | | 44 | | try |
| | 0 | 45 | | { |
| | 0 | 46 | | WebSocketReceiveResult r = await ReceiveAsync(new ArraySegment<byte>(array, 0, buffer.Length), cancellat |
| | 0 | 47 | | new Span<byte>(array, 0, r.Count).CopyTo(buffer.Span); |
| | 0 | 48 | | return new ValueWebSocketReceiveResult(r.Count, r.MessageType, r.EndOfMessage); |
| | | 49 | | } |
| | | 50 | | finally |
| | 0 | 51 | | { |
| | 0 | 52 | | ArrayPool<byte>.Shared.Return(array); |
| | 0 | 53 | | } |
| | 0 | 54 | | } |
| | | 55 | | |
| | | 56 | | public virtual ValueTask SendAsync(ReadOnlyMemory<byte> buffer, WebSocketMessageType messageType, bool endOfMess |
| | 0 | 57 | | MemoryMarshal.TryGetArray(buffer, out ArraySegment<byte> arraySegment) ? |
| | 0 | 58 | | new ValueTask(SendAsync(arraySegment, messageType, endOfMessage, cancellationToken)) : |
| | 0 | 59 | | SendWithArrayPoolAsync(buffer, messageType, endOfMessage, cancellationToken); |
| | | 60 | | |
| | | 61 | | public virtual ValueTask SendAsync(ReadOnlyMemory<byte> buffer, WebSocketMessageType messageType, WebSocketMessa |
| | 0 | 62 | | { |
| | 0 | 63 | | return SendAsync(buffer, messageType, (messageFlags & WebSocketMessageFlags.EndOfMessage) != 0, cancellation |
| | 0 | 64 | | } |
| | | 65 | | |
| | | 66 | | private async ValueTask SendWithArrayPoolAsync( |
| | | 67 | | ReadOnlyMemory<byte> buffer, |
| | | 68 | | WebSocketMessageType messageType, |
| | | 69 | | bool endOfMessage, |
| | | 70 | | CancellationToken cancellationToken) |
| | 0 | 71 | | { |
| | 0 | 72 | | byte[] array = ArrayPool<byte>.Shared.Rent(buffer.Length); |
| | | 73 | | try |
| | 0 | 74 | | { |
| | 0 | 75 | | buffer.Span.CopyTo(array); |
| | 0 | 76 | | await SendAsync(new ArraySegment<byte>(array, 0, buffer.Length), messageType, endOfMessage, cancellation |
| | 0 | 77 | | } |
| | | 78 | | finally |
| | 0 | 79 | | { |
| | 0 | 80 | | ArrayPool<byte>.Shared.Return(array); |
| | 0 | 81 | | } |
| | 0 | 82 | | } |
| | | 83 | | |
| | | 84 | | public static TimeSpan DefaultKeepAliveInterval |
| | | 85 | | { |
| | | 86 | | // In the .NET Framework, this pulls the value from a P/Invoke. Here we just hardcode it to a reasonable de |
| | 0 | 87 | | get { return WebSocketDefaults.DefaultClientKeepAliveInterval; } |
| | | 88 | | } |
| | | 89 | | |
| | | 90 | | protected static void ThrowOnInvalidState(WebSocketState state, params WebSocketState[] validStates) |
| | 0 | 91 | | { |
| | 0 | 92 | | string validStatesText = string.Empty; |
| | | 93 | | |
| | 0 | 94 | | if (validStates != null && validStates.Length > 0) |
| | 0 | 95 | | { |
| | 0 | 96 | | foreach (WebSocketState currentState in validStates) |
| | 0 | 97 | | { |
| | 0 | 98 | | if (state == currentState) |
| | 0 | 99 | | { |
| | 0 | 100 | | return; |
| | | 101 | | } |
| | 0 | 102 | | } |
| | | 103 | | |
| | 0 | 104 | | validStatesText = string.Join(", ", validStates); |
| | 0 | 105 | | } |
| | | 106 | | |
| | 0 | 107 | | throw new WebSocketException(WebSocketError.InvalidState, SR.Format(SR.net_WebSockets_InvalidState, state, v |
| | 0 | 108 | | } |
| | | 109 | | |
| | | 110 | | protected static bool IsStateTerminal(WebSocketState state) => |
| | 0 | 111 | | state == WebSocketState.Closed || state == WebSocketState.Aborted; |
| | | 112 | | |
| | | 113 | | public static ArraySegment<byte> CreateClientBuffer(int receiveBufferSize, int sendBufferSize) |
| | 0 | 114 | | { |
| | 0 | 115 | | ArgumentOutOfRangeException.ThrowIfNegativeOrZero(receiveBufferSize); |
| | 0 | 116 | | ArgumentOutOfRangeException.ThrowIfNegativeOrZero(sendBufferSize); |
| | 0 | 117 | | return new ArraySegment<byte>(new byte[Math.Max(receiveBufferSize, sendBufferSize)]); |
| | 0 | 118 | | } |
| | | 119 | | |
| | | 120 | | public static ArraySegment<byte> CreateServerBuffer(int receiveBufferSize) |
| | 0 | 121 | | { |
| | 0 | 122 | | ArgumentOutOfRangeException.ThrowIfNegativeOrZero(receiveBufferSize); |
| | 0 | 123 | | return new ArraySegment<byte>(new byte[receiveBufferSize]); |
| | 0 | 124 | | } |
| | | 125 | | |
| | | 126 | | /// <summary>Creates a <see cref="WebSocket"/> that operates on a <see cref="Stream"/> representing a web socket |
| | | 127 | | /// <param name="stream">The <see cref="Stream"/> for the connection.</param> |
| | | 128 | | /// <param name="isServer"><code>true</code> if this is the server-side of the connection; <code>false</code> if |
| | | 129 | | /// <param name="subProtocol">The agreed upon sub-protocol that was used when creating the connection.</param> |
| | | 130 | | /// <param name="keepAliveInterval">The keep-alive interval to use, or <see cref="Timeout.InfiniteTimeSpan"/> to |
| | | 131 | | /// <returns>The created <see cref="WebSocket"/>.</returns> |
| | | 132 | | public static WebSocket CreateFromStream(Stream stream, bool isServer, string? subProtocol, TimeSpan keepAliveIn |
| | 0 | 133 | | { |
| | 0 | 134 | | ArgumentNullException.ThrowIfNull(stream); |
| | | 135 | | |
| | 0 | 136 | | if (!stream.CanRead || !stream.CanWrite) |
| | 0 | 137 | | { |
| | 0 | 138 | | throw new ArgumentException(!stream.CanRead ? SR.NotReadableStream : SR.NotWriteableStream, nameof(strea |
| | | 139 | | } |
| | | 140 | | |
| | 0 | 141 | | if (subProtocol != null) |
| | 0 | 142 | | { |
| | 0 | 143 | | WebSocketValidate.ValidateSubprotocol(subProtocol); |
| | 0 | 144 | | } |
| | | 145 | | |
| | 0 | 146 | | if (keepAliveInterval != Timeout.InfiniteTimeSpan && keepAliveInterval < TimeSpan.Zero) |
| | 0 | 147 | | { |
| | 0 | 148 | | throw new ArgumentOutOfRangeException(nameof(keepAliveInterval), keepAliveInterval, |
| | 0 | 149 | | SR.Format(SR.net_WebSockets_ArgumentOutOfRange_TooSmall, |
| | 0 | 150 | | 0)); |
| | | 151 | | } |
| | | 152 | | |
| | 0 | 153 | | return new ManagedWebSocket(stream, isServer, subProtocol, keepAliveInterval, WebSocketDefaults.DefaultKeepA |
| | 0 | 154 | | } |
| | | 155 | | |
| | | 156 | | /// <summary>Creates a <see cref="WebSocket"/> that operates on a <see cref="Stream"/> representing a web socket |
| | | 157 | | /// <param name="stream">The <see cref="Stream"/> for the connection.</param> |
| | | 158 | | /// <param name="options">The options with which the websocket must be created.</param> |
| | | 159 | | public static WebSocket CreateFromStream(Stream stream, WebSocketCreationOptions options) |
| | 8642 | 160 | | { |
| | 8642 | 161 | | ArgumentNullException.ThrowIfNull(stream); |
| | 8642 | 162 | | ArgumentNullException.ThrowIfNull(options); |
| | | 163 | | |
| | 8642 | 164 | | if (!stream.CanRead || !stream.CanWrite) |
| | 0 | 165 | | throw new ArgumentException(!stream.CanRead ? SR.NotReadableStream : SR.NotWriteableStream, nameof(strea |
| | | 166 | | |
| | 8642 | 167 | | return new ManagedWebSocket(stream, options); |
| | 8642 | 168 | | } |
| | | 169 | | |
| | | 170 | | [EditorBrowsable(EditorBrowsableState.Never)] |
| | | 171 | | [Obsolete("This API supports the .NET Framework infrastructure and is not intended to be used directly from your |
| | 0 | 172 | | public static bool IsApplicationTargeting45() => true; |
| | | 173 | | |
| | | 174 | | [EditorBrowsable(EditorBrowsableState.Never)] |
| | | 175 | | [Obsolete("This API supports the .NET Framework infrastructure and is not intended to be used directly from your |
| | | 176 | | public static void RegisterPrefixes() |
| | 0 | 177 | | { |
| | | 178 | | // The current WebRequest implementation in the libraries does not support upgrading |
| | | 179 | | // web socket connections. For now, we throw. |
| | 0 | 180 | | throw new PlatformNotSupportedException(); |
| | | 181 | | } |
| | | 182 | | |
| | | 183 | | [EditorBrowsable(EditorBrowsableState.Never)] |
| | | 184 | | public static WebSocket CreateClientWebSocket(Stream innerStream, |
| | | 185 | | string? subProtocol, int receiveBufferSize, int sendBufferSize, |
| | | 186 | | TimeSpan keepAliveInterval, bool useZeroMaskingKey, ArraySegment<byte> internalBuffer) |
| | 0 | 187 | | { |
| | 0 | 188 | | ArgumentNullException.ThrowIfNull(innerStream); |
| | | 189 | | |
| | 0 | 190 | | if (!innerStream.CanRead || !innerStream.CanWrite) |
| | 0 | 191 | | { |
| | 0 | 192 | | throw new ArgumentException(!innerStream.CanRead ? SR.NotReadableStream : SR.NotWriteableStream, nameof( |
| | | 193 | | } |
| | | 194 | | |
| | 0 | 195 | | if (subProtocol != null) |
| | 0 | 196 | | { |
| | 0 | 197 | | WebSocketValidate.ValidateSubprotocol(subProtocol); |
| | 0 | 198 | | } |
| | | 199 | | |
| | 0 | 200 | | if (keepAliveInterval != Timeout.InfiniteTimeSpan && keepAliveInterval < TimeSpan.Zero) |
| | 0 | 201 | | { |
| | 0 | 202 | | throw new ArgumentOutOfRangeException(nameof(keepAliveInterval), keepAliveInterval, |
| | 0 | 203 | | SR.Format(SR.net_WebSockets_ArgumentOutOfRange_TooSmall, |
| | 0 | 204 | | 0)); |
| | | 205 | | } |
| | | 206 | | |
| | 0 | 207 | | ArgumentOutOfRangeException.ThrowIfNegativeOrZero(receiveBufferSize); |
| | 0 | 208 | | ArgumentOutOfRangeException.ThrowIfNegativeOrZero(sendBufferSize); |
| | | 209 | | |
| | | 210 | | // Ignore useZeroMaskingKey. ManagedWebSocket doesn't currently support that debugging option. |
| | | 211 | | // Ignore internalBuffer. ManagedWebSocket uses its own small buffer for headers/control messages. |
| | 0 | 212 | | return new ManagedWebSocket(innerStream, false, subProtocol, keepAliveInterval, WebSocketDefaults.DefaultKee |
| | 0 | 213 | | } |
| | | 214 | | } |
| | | 215 | | } |
| | | 216 | | |