| | | 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; |
| | | 5 | | using System.Collections.Generic; |
| | | 6 | | using System.Collections.ObjectModel; |
| | | 7 | | using System.Diagnostics; |
| | | 8 | | using System.IO; |
| | | 9 | | using System.Net.WebSockets; |
| | | 10 | | using System.Security.Principal; |
| | | 11 | | using System.Threading; |
| | | 12 | | using System.Threading.Tasks; |
| | | 13 | | using CoreWCF.Runtime; |
| | | 14 | | using CoreWCF.Security; |
| | | 15 | | using Microsoft.AspNetCore.Http; |
| | | 16 | | |
| | | 17 | | namespace CoreWCF.Channels |
| | | 18 | | { |
| | | 19 | | internal abstract class WebSocketTransportDuplexSessionChannel : TransportDuplexSessionChannel |
| | | 20 | | { |
| | | 21 | | private WebSocket _webSocket = null; |
| | | 22 | | private int _cleanupStatus = WebSocketHelper.OperationNotStarted; |
| | 11 | 23 | | private readonly WebSocketCloseDetails _webSocketCloseDetails = new WebSocketCloseDetails(); |
| | 11 | 24 | | private bool _shouldDisposeWebSocketAfterClosed = true; |
| | | 25 | | |
| | | 26 | | public WebSocketTransportDuplexSessionChannel(IHttpTransportFactorySettings settings, EndpointAddress localAddre |
| | 11 | 27 | | : base(settings, localAddress, localVia, EndpointAddress.AnonymousAddress, settings.MessageVersion.Addressin |
| | | 28 | | { |
| | | 29 | | Fx.Assert(settings.WebSocketSettings != null, "IHttpTransportFactorySettings.WebSocketTransportSettings shou |
| | 11 | 30 | | WebSocketSettings = settings.WebSocketSettings; |
| | 11 | 31 | | TransferMode = settings.TransferMode; |
| | 11 | 32 | | MaxBufferSize = settings.MaxBufferSize; |
| | 11 | 33 | | TransportFactorySettings = settings; |
| | 11 | 34 | | } |
| | | 35 | | |
| | | 36 | | protected WebSocket WebSocket |
| | | 37 | | { |
| | | 38 | | get |
| | | 39 | | { |
| | 70 | 40 | | return _webSocket; |
| | | 41 | | } |
| | | 42 | | |
| | | 43 | | set |
| | | 44 | | { |
| | | 45 | | Fx.Assert(value != null, "value should not be null."); |
| | | 46 | | Fx.Assert(_webSocket == null, "webSocket should not be set before this set call."); |
| | 11 | 47 | | _webSocket = value; |
| | 11 | 48 | | } |
| | | 49 | | } |
| | | 50 | | |
| | 11 | 51 | | protected WebSocketTransportSettings WebSocketSettings { get; } |
| | | 52 | | |
| | 26 | 53 | | protected TransferMode TransferMode { get; } |
| | | 54 | | |
| | 11 | 55 | | protected int MaxBufferSize { get; } |
| | | 56 | | |
| | 11 | 57 | | protected ITransportFactorySettings TransportFactorySettings { get; } |
| | | 58 | | |
| | | 59 | | protected bool ShouldDisposeWebSocketAfterClosed |
| | | 60 | | { |
| | | 61 | | set |
| | | 62 | | { |
| | 11 | 63 | | _shouldDisposeWebSocketAfterClosed = value; |
| | 11 | 64 | | } |
| | | 65 | | } |
| | | 66 | | |
| | | 67 | | protected override void OnAbort() |
| | | 68 | | { |
| | | 69 | | //if (TD.WebSocketConnectionAbortedIsEnabled()) |
| | | 70 | | //{ |
| | | 71 | | // TD.WebSocketConnectionAborted( |
| | | 72 | | // this.EventTraceActivity, |
| | | 73 | | // this.WebSocket != null ? this.WebSocket.GetHashCode() : -1); |
| | | 74 | | //} |
| | | 75 | | |
| | 0 | 76 | | Cleanup(); |
| | 0 | 77 | | } |
| | | 78 | | |
| | | 79 | | public override T GetProperty<T>() |
| | | 80 | | { |
| | 12 | 81 | | if (typeof(T) == typeof(IWebSocketCloseDetails)) |
| | | 82 | | { |
| | 0 | 83 | | return _webSocketCloseDetails as T; |
| | | 84 | | } |
| | | 85 | | |
| | 12 | 86 | | return base.GetProperty<T>(); |
| | | 87 | | } |
| | | 88 | | |
| | | 89 | | protected override async Task CompleteCloseAsync(CancellationToken token) |
| | | 90 | | { |
| | | 91 | | //if (TD.WebSocketCloseSentIsEnabled()) |
| | | 92 | | //{ |
| | | 93 | | // TD.WebSocketCloseSent( |
| | | 94 | | // this.WebSocket.GetHashCode(), |
| | | 95 | | // this.webSocketCloseDetails.OutputCloseStatus.ToString(), |
| | | 96 | | // this.RemoteAddress != null ? this.RemoteAddress.ToString() : string.Empty); |
| | | 97 | | //} |
| | | 98 | | |
| | | 99 | | try |
| | | 100 | | { |
| | 11 | 101 | | await CloseInternalAsync(token); |
| | 11 | 102 | | } |
| | | 103 | | catch (Exception ex) |
| | | 104 | | { |
| | 0 | 105 | | if (Fx.IsFatal(ex)) |
| | | 106 | | { |
| | 0 | 107 | | throw; |
| | | 108 | | } |
| | | 109 | | |
| | 0 | 110 | | WebSocketHelper.ThrowCorrectException(ex, TimeoutHelper.GetOriginalTimeout(token), WebSocketHelper.Close |
| | 0 | 111 | | } |
| | | 112 | | |
| | | 113 | | //if (TD.WebSocketConnectionClosedIsEnabled()) |
| | | 114 | | //{ |
| | | 115 | | // TD.WebSocketConnectionClosed(this.WebSocket.GetHashCode()); |
| | | 116 | | //} |
| | 11 | 117 | | } |
| | | 118 | | |
| | | 119 | | protected override async Task CloseOutputSessionCoreAsync(CancellationToken token) |
| | | 120 | | { |
| | | 121 | | //if (TD.WebSocketCloseOutputSentIsEnabled()) |
| | | 122 | | //{ |
| | | 123 | | // TD.WebSocketCloseOutputSent( |
| | | 124 | | // this.WebSocket.GetHashCode(), |
| | | 125 | | // this.webSocketCloseDetails.OutputCloseStatus.ToString(), |
| | | 126 | | // this.RemoteAddress != null ? this.RemoteAddress.ToString() : string.Empty); |
| | | 127 | | //} |
| | | 128 | | try |
| | | 129 | | { |
| | 11 | 130 | | await CloseOutputAsync(CancellationToken.None); |
| | 11 | 131 | | } |
| | | 132 | | catch (Exception ex) |
| | | 133 | | { |
| | 0 | 134 | | if (Fx.IsFatal(ex)) |
| | | 135 | | { |
| | 0 | 136 | | throw; |
| | | 137 | | } |
| | | 138 | | |
| | 0 | 139 | | WebSocketHelper.ThrowCorrectException(ex, TimeoutHelper.GetOriginalTimeout(token), WebSocketHelper.Close |
| | 0 | 140 | | } |
| | 11 | 141 | | } |
| | | 142 | | |
| | | 143 | | protected override async Task OnCloseAsync(CancellationToken token) |
| | | 144 | | { |
| | | 145 | | try |
| | | 146 | | { |
| | 11 | 147 | | await base.OnCloseAsync(token); |
| | 11 | 148 | | } |
| | | 149 | | finally |
| | | 150 | | { |
| | 11 | 151 | | Cleanup(); |
| | | 152 | | } |
| | 11 | 153 | | } |
| | | 154 | | |
| | | 155 | | protected override void ReturnConnectionIfNecessary(bool abort, CancellationToken token) |
| | | 156 | | { |
| | 11 | 157 | | } |
| | | 158 | | |
| | | 159 | | protected override Task CloseOutputAsync(CancellationToken token) |
| | | 160 | | { |
| | 11 | 161 | | Task task = CloseOutputImplAsync(token); |
| | 11 | 162 | | return task.ContinueWith(t => |
| | 11 | 163 | | { |
| | 11 | 164 | | try |
| | 11 | 165 | | { |
| | 11 | 166 | | WebSocketHelper.ThrowExceptionOnTaskFailure(t, TimeoutHelper.GetOriginalTimeout(token), WebSocketHel |
| | 11 | 167 | | } |
| | 0 | 168 | | catch (Exception error) |
| | 11 | 169 | | { |
| | 0 | 170 | | Fx.Exception.TraceHandledException(error, TraceEventType.Information); |
| | 0 | 171 | | throw; |
| | 11 | 172 | | } |
| | 22 | 173 | | }); |
| | | 174 | | } |
| | | 175 | | |
| | | 176 | | [System.Diagnostics.CodeAnalysis.SuppressMessage("Usage", "CA2219:Do not raise exceptions in finally clauses", J |
| | | 177 | | protected override async Task OnSendCoreAsync(Message message, CancellationToken token) |
| | | 178 | | { |
| | | 179 | | Fx.Assert(message != null, "message should not be null."); |
| | | 180 | | |
| | 15 | 181 | | WebSocketMessageType outgoingMessageType = GetWebSocketMessageType(message); |
| | 15 | 182 | | if (IsStreamedOutput) |
| | | 183 | | { |
| | 6 | 184 | | WebSocketStream webSocketStream = new WebSocketStream(WebSocket, outgoingMessageType, token); |
| | 6 | 185 | | TimeoutStream timeoutStream = new TimeoutStream(webSocketStream, token); |
| | 6 | 186 | | await MessageEncoder.WriteMessageAsync(message, timeoutStream); |
| | 6 | 187 | | await webSocketStream.WriteEndOfMessageAsync(token); |
| | 6 | 188 | | } |
| | | 189 | | else |
| | | 190 | | { |
| | 9 | 191 | | ArraySegment<byte> messageData = EncodeMessage(message); |
| | 9 | 192 | | bool success = false; |
| | | 193 | | try |
| | | 194 | | { |
| | | 195 | | //if (TD.WebSocketAsyncWriteStartIsEnabled()) |
| | | 196 | | //{ |
| | | 197 | | // TD.WebSocketAsyncWriteStart( |
| | | 198 | | // this.WebSocket.GetHashCode(), |
| | | 199 | | // messageData.Count, |
| | | 200 | | // this.RemoteAddress != null ? this.RemoteAddress.ToString() : string.Empty); |
| | | 201 | | //} |
| | | 202 | | |
| | | 203 | | try |
| | | 204 | | { |
| | 9 | 205 | | await WebSocket.SendAsync(messageData, outgoingMessageType, true, token); |
| | 9 | 206 | | } |
| | | 207 | | catch (Exception ex) |
| | | 208 | | { |
| | 0 | 209 | | if (Fx.IsFatal(ex)) |
| | | 210 | | { |
| | 0 | 211 | | throw; |
| | | 212 | | } |
| | | 213 | | |
| | 0 | 214 | | WebSocketHelper.ThrowCorrectException(ex, TimeoutHelper.GetOriginalTimeout(token), WebSocketHelp |
| | 0 | 215 | | } |
| | | 216 | | |
| | | 217 | | //if (TD.WebSocketAsyncWriteStopIsEnabled()) |
| | | 218 | | //{ |
| | | 219 | | // TD.WebSocketAsyncWriteStop(this.webSocket.GetHashCode()); |
| | | 220 | | //} |
| | | 221 | | |
| | 9 | 222 | | success = true; |
| | 9 | 223 | | } |
| | | 224 | | finally |
| | | 225 | | { |
| | | 226 | | try |
| | | 227 | | { |
| | 9 | 228 | | BufferManager.ReturnBuffer(messageData.Array); |
| | 9 | 229 | | } |
| | 0 | 230 | | catch (Exception ex) |
| | | 231 | | { |
| | 0 | 232 | | if (Fx.IsFatal(ex) || success) |
| | | 233 | | { |
| | 0 | 234 | | throw; |
| | | 235 | | } |
| | | 236 | | |
| | 0 | 237 | | Fx.Exception.TraceUnhandledException(ex); |
| | 0 | 238 | | } |
| | | 239 | | } |
| | | 240 | | } |
| | 15 | 241 | | } |
| | | 242 | | |
| | | 243 | | protected override ArraySegment<byte> EncodeMessage(Message message) |
| | | 244 | | { |
| | 9 | 245 | | return MessageEncoder.WriteMessage(message, int.MaxValue, BufferManager, 0); |
| | | 246 | | } |
| | | 247 | | |
| | | 248 | | protected void Cleanup() |
| | | 249 | | { |
| | 11 | 250 | | if (Interlocked.CompareExchange(ref _cleanupStatus, WebSocketHelper.OperationFinished, WebSocketHelper.Opera |
| | | 251 | | { |
| | 11 | 252 | | OnCleanup(); |
| | | 253 | | } |
| | 11 | 254 | | } |
| | | 255 | | |
| | | 256 | | protected virtual void OnCleanup() |
| | | 257 | | { |
| | | 258 | | Fx.Assert(_cleanupStatus == WebSocketHelper.OperationFinished, |
| | | 259 | | "This method should only be called by this.Cleanup(). Make sure that you never call overriden OnCleanup( |
| | 11 | 260 | | if (_shouldDisposeWebSocketAfterClosed && _webSocket != null) |
| | | 261 | | { |
| | 11 | 262 | | _webSocket.Dispose(); |
| | | 263 | | } |
| | 11 | 264 | | } |
| | | 265 | | |
| | | 266 | | private static void ThrowOnPendingException(ref Exception pendingException) |
| | | 267 | | { |
| | 26 | 268 | | Exception exceptionToThrow = pendingException; |
| | | 269 | | |
| | 26 | 270 | | if (exceptionToThrow != null) |
| | | 271 | | { |
| | 0 | 272 | | pendingException = null; |
| | 0 | 273 | | throw Fx.Exception.AsError(exceptionToThrow); |
| | | 274 | | } |
| | 26 | 275 | | } |
| | | 276 | | |
| | | 277 | | private Task CloseInternalAsync(CancellationToken token) |
| | | 278 | | { |
| | | 279 | | try |
| | | 280 | | { |
| | 11 | 281 | | if (WebSocket.State == WebSocketState.Closed || WebSocket.State == WebSocketState.Aborted) |
| | 11 | 282 | | return Task.CompletedTask; |
| | | 283 | | |
| | 0 | 284 | | return WebSocket.CloseAsync(_webSocketCloseDetails.OutputCloseStatus, _webSocketCloseDetails.OutputClose |
| | | 285 | | } |
| | | 286 | | catch (Exception e) |
| | | 287 | | { |
| | 0 | 288 | | if (Fx.IsFatal(e)) |
| | | 289 | | { |
| | 0 | 290 | | throw; |
| | | 291 | | } |
| | | 292 | | |
| | 0 | 293 | | throw WebSocketHelper.ConvertAndTraceException(e); |
| | | 294 | | } |
| | 11 | 295 | | } |
| | | 296 | | |
| | | 297 | | private Task CloseOutputImplAsync(CancellationToken cancellationToken) |
| | | 298 | | { |
| | | 299 | | try |
| | | 300 | | { |
| | | 301 | | // Guard against calling CloseOutputAsync when the WebSocket has already sent or completed close. |
| | | 302 | | // This can happen if CloseAsync is called after the close handshake has already begun. |
| | 11 | 303 | | if (WebSocket.State == WebSocketState.Closed || |
| | 11 | 304 | | WebSocket.State == WebSocketState.Aborted || |
| | 11 | 305 | | WebSocket.State == WebSocketState.CloseSent) |
| | | 306 | | { |
| | 0 | 307 | | return Task.CompletedTask; |
| | | 308 | | } |
| | | 309 | | |
| | 11 | 310 | | return WebSocket.CloseOutputAsync(_webSocketCloseDetails.OutputCloseStatus, _webSocketCloseDetails.Outpu |
| | | 311 | | } |
| | | 312 | | catch (Exception e) |
| | | 313 | | { |
| | 0 | 314 | | if (Fx.IsFatal(e)) |
| | | 315 | | { |
| | 0 | 316 | | throw; |
| | | 317 | | } |
| | | 318 | | |
| | 0 | 319 | | throw WebSocketHelper.ConvertAndTraceException(e); |
| | | 320 | | } |
| | 11 | 321 | | } |
| | | 322 | | |
| | | 323 | | private static WebSocketMessageType GetWebSocketMessageType(Message message) |
| | | 324 | | { |
| | 15 | 325 | | WebSocketMessageType outgoingMessageType = WebSocketDefaults.DefaultWebSocketMessageType; |
| | 15 | 326 | | if (WebSocketMessageProperty.TryGet(message.Properties, out WebSocketMessageProperty webSocketMessagePropert |
| | | 327 | | { |
| | 0 | 328 | | outgoingMessageType = webSocketMessageProperty.MessageType; |
| | | 329 | | } |
| | | 330 | | |
| | 15 | 331 | | return outgoingMessageType; |
| | | 332 | | } |
| | | 333 | | |
| | | 334 | | protected class WebSocketMessageSource : IMessageSource |
| | | 335 | | { |
| | 0 | 336 | | private static readonly Action<object> s_onAsyncReceiveCancelled = Fx.ThunkCallback<object>(OnAsyncReceiveCa |
| | | 337 | | private MessageEncoder _encoder; |
| | | 338 | | private BufferManager _bufferManager; |
| | | 339 | | private EndpointAddress _localAddress; |
| | | 340 | | |
| | 0 | 341 | | public WebSocketMessageSource(EndpointAddress localAddress) |
| | | 342 | | { |
| | 0 | 343 | | _localAddress = localAddress; |
| | 0 | 344 | | } |
| | | 345 | | |
| | | 346 | | private Message _pendingMessage; |
| | | 347 | | private Exception _pendingException; |
| | | 348 | | private readonly WebSocketContext _context; |
| | | 349 | | private WebSocket _webSocket; |
| | | 350 | | private bool _closureReceived = false; |
| | | 351 | | private bool _useStreaming; |
| | | 352 | | private int _receiveBufferSize; |
| | | 353 | | private int _maxBufferSize; |
| | | 354 | | private long _maxReceivedMessageSize; |
| | | 355 | | private TaskCompletionSource<object> _streamWaitTask; |
| | | 356 | | private IDefaultCommunicationTimeouts _defaultTimeouts; |
| | | 357 | | private SecurityMessageProperty _handshakeSecurityMessageProperty; |
| | | 358 | | private WebSocketCloseDetails _closeDetails; |
| | | 359 | | private readonly ReadOnlyDictionary<string, object> _properties; |
| | | 360 | | private TimeSpan _asyncReceiveTimeout; |
| | | 361 | | private TaskCompletionSource<object> _receiveTask; |
| | | 362 | | private int _asyncReceiveState; |
| | | 363 | | |
| | 0 | 364 | | public WebSocketMessageSource(WebSocketTransportDuplexSessionChannel webSocketTransportDuplexSessionChannel, |
| | 0 | 365 | | bool useStreaming, IDefaultCommunicationTimeouts defaultTimeouts) |
| | | 366 | | { |
| | 0 | 367 | | Initialize(webSocketTransportDuplexSessionChannel, webSocket, useStreaming, defaultTimeouts); |
| | | 368 | | // TODO: Switch IMessageSource to use TimeSpan instead of CancellationToken. See Issue #283 |
| | 0 | 369 | | _asyncReceiveTimeout = TimeSpan.Zero; |
| | 0 | 370 | | StartNextReceiveAsync(); |
| | 0 | 371 | | } |
| | | 372 | | |
| | 11 | 373 | | public WebSocketMessageSource(WebSocketTransportDuplexSessionChannel webSocketTransportDuplexSessionChannel, |
| | 11 | 374 | | bool isStreamed, RemoteEndpointMessageProperty remoteEndpointMessageProperty, IDefaultCommunicationTimeo |
| | | 375 | | { |
| | 11 | 376 | | Initialize(webSocketTransportDuplexSessionChannel, context.WebSocket, isStreamed, defaultTimeouts); |
| | | 377 | | |
| | 11 | 378 | | IPrincipal user = requestContext?.User; |
| | 11 | 379 | | _context = new ServiceWebSocketContext(context, user); |
| | 11 | 380 | | RemoteEndpointMessageProperty = remoteEndpointMessageProperty; |
| | | 381 | | // Copy any string keyed items from requestContext to properties. This is an attempt to mimic HttpReques |
| | 11 | 382 | | var properties = new Dictionary<string, object>(); |
| | 44 | 383 | | foreach (KeyValuePair<object, object> kv in requestContext.Items) |
| | | 384 | | { |
| | 11 | 385 | | if (kv.Key is string key) |
| | | 386 | | { |
| | 11 | 387 | | properties[key] = kv.Value; |
| | | 388 | | } |
| | | 389 | | } |
| | | 390 | | |
| | 11 | 391 | | _properties = requestContext == null ? null : new ReadOnlyDictionary<string, object>(properties); |
| | | 392 | | |
| | 11 | 393 | | StartNextReceiveAsync(); |
| | 11 | 394 | | } |
| | | 395 | | |
| | | 396 | | private void Initialize(WebSocketTransportDuplexSessionChannel webSocketTransportDuplexSessionChannel, WebSo |
| | | 397 | | { |
| | 11 | 398 | | _webSocket = webSocket; |
| | 11 | 399 | | _encoder = webSocketTransportDuplexSessionChannel.MessageEncoder; |
| | 11 | 400 | | _bufferManager = webSocketTransportDuplexSessionChannel.BufferManager; |
| | 11 | 401 | | _localAddress = webSocketTransportDuplexSessionChannel.LocalAddress; |
| | 11 | 402 | | _maxBufferSize = webSocketTransportDuplexSessionChannel.MaxBufferSize; |
| | 11 | 403 | | _handshakeSecurityMessageProperty = webSocketTransportDuplexSessionChannel.RemoteSecurity; |
| | 11 | 404 | | _maxReceivedMessageSize = webSocketTransportDuplexSessionChannel.TransportFactorySettings.MaxReceivedMes |
| | 11 | 405 | | _receiveBufferSize = Math.Min(WebSocketHelper.GetReceiveBufferSize(_maxReceivedMessageSize), _maxBufferS |
| | 11 | 406 | | _useStreaming = useStreaming; |
| | 11 | 407 | | _defaultTimeouts = defaultTimeouts; |
| | 11 | 408 | | _closeDetails = webSocketTransportDuplexSessionChannel._webSocketCloseDetails; |
| | 11 | 409 | | _asyncReceiveState = AsyncReceiveState.Finished; |
| | 11 | 410 | | } |
| | | 411 | | |
| | 32 | 412 | | internal RemoteEndpointMessageProperty RemoteEndpointMessageProperty { get; } |
| | | 413 | | |
| | | 414 | | private static void OnAsyncReceiveCancelled(object target) |
| | | 415 | | { |
| | 0 | 416 | | WebSocketMessageSource messageSource = (WebSocketMessageSource)target; |
| | 0 | 417 | | messageSource.AsyncReceiveCancelled(); |
| | 0 | 418 | | } |
| | | 419 | | |
| | | 420 | | private void AsyncReceiveCancelled() |
| | | 421 | | { |
| | 0 | 422 | | if (Interlocked.CompareExchange(ref _asyncReceiveState, AsyncReceiveState.Cancelled, AsyncReceiveState.S |
| | | 423 | | { |
| | 0 | 424 | | _receiveTask.SetResult(null); |
| | | 425 | | } |
| | 0 | 426 | | } |
| | | 427 | | |
| | | 428 | | public async Task<Message> ReceiveAsync(CancellationToken token) |
| | | 429 | | { |
| | 26 | 430 | | if (!_receiveTask.Task.IsCompleted) |
| | | 431 | | { |
| | 26 | 432 | | using (token.Register(() => AsyncReceiveCancelled())) |
| | | 433 | | { |
| | 26 | 434 | | await _receiveTask.Task; |
| | 26 | 435 | | } |
| | | 436 | | } |
| | | 437 | | |
| | 26 | 438 | | if (_asyncReceiveState == AsyncReceiveState.Cancelled) |
| | | 439 | | { |
| | 0 | 440 | | throw Fx.Exception.AsError(WebSocketHelper.GetTimeoutException(null, TimeoutHelper.GetOriginalTimeou |
| | | 441 | | } |
| | | 442 | | else |
| | | 443 | | { |
| | | 444 | | Fx.Assert(_asyncReceiveState == AsyncReceiveState.Finished, "this.asyncReceiveState is not AsyncRece |
| | 26 | 445 | | Message message = GetPendingMessage(); |
| | | 446 | | |
| | 26 | 447 | | if (message != null) |
| | | 448 | | { |
| | | 449 | | // If we get any exception thrown out before that, the channel will be aborted thus no need to m |
| | 15 | 450 | | StartNextReceiveAsync(); |
| | | 451 | | } |
| | | 452 | | |
| | 26 | 453 | | return message; |
| | | 454 | | } |
| | 26 | 455 | | } |
| | | 456 | | |
| | | 457 | | public void UpdateOpenNotificationMessageProperties(MessageProperties messageProperties) |
| | | 458 | | { |
| | 1 | 459 | | AddMessageProperties(messageProperties, WebSocketDefaults.DefaultWebSocketMessageType); |
| | 1 | 460 | | } |
| | | 461 | | |
| | | 462 | | private async Task ReadBufferedMessageAsync() |
| | | 463 | | { |
| | 18 | 464 | | byte[] internalBuffer = null; |
| | | 465 | | try |
| | | 466 | | { |
| | 18 | 467 | | internalBuffer = _bufferManager.TakeBuffer(_receiveBufferSize); |
| | | 468 | | |
| | 18 | 469 | | int receivedByteCount = 0; |
| | 18 | 470 | | bool endOfMessage = false; |
| | 18 | 471 | | WebSocketReceiveResult result = null; |
| | | 472 | | do |
| | | 473 | | { |
| | | 474 | | try |
| | | 475 | | { |
| | | 476 | | //if (TD.WebSocketAsyncReadStartIsEnabled()) |
| | | 477 | | //{ |
| | | 478 | | // TD.WebSocketAsyncReadStart(this.webSocket.GetHashCode()); |
| | | 479 | | //} |
| | | 480 | | |
| | 18 | 481 | | Task<WebSocketReceiveResult> receiveTask = _webSocket.ReceiveAsync( |
| | 18 | 482 | | new ArraySegment<byte>(internalBuffer, receivedByteCount, in |
| | 18 | 483 | | CancellationToken.None); |
| | | 484 | | |
| | 18 | 485 | | await receiveTask.ConfigureAwait(false); |
| | | 486 | | |
| | 18 | 487 | | result = receiveTask.Result; |
| | 18 | 488 | | CheckCloseStatus(result); |
| | 18 | 489 | | endOfMessage = result.EndOfMessage; |
| | | 490 | | |
| | 18 | 491 | | receivedByteCount += result.Count; |
| | 18 | 492 | | if (receivedByteCount >= internalBuffer.Length && !result.EndOfMessage) |
| | | 493 | | { |
| | 0 | 494 | | if (internalBuffer.Length >= _maxBufferSize) |
| | | 495 | | { |
| | 0 | 496 | | _pendingException = Fx.Exception.AsError(new QuotaExceededException(SR.Format(SR.Max |
| | 0 | 497 | | return; |
| | | 498 | | } |
| | | 499 | | |
| | 0 | 500 | | int newSize = (int)Math.Min(((double)internalBuffer.Length) * 2, _maxBufferSize); |
| | | 501 | | Fx.Assert(newSize > 0, "buffer size should be larger than zero."); |
| | 0 | 502 | | byte[] newBuffer = _bufferManager.TakeBuffer(newSize); |
| | 0 | 503 | | Buffer.BlockCopy(internalBuffer, 0, newBuffer, 0, receivedByteCount); |
| | 0 | 504 | | _bufferManager.ReturnBuffer(internalBuffer); |
| | 0 | 505 | | internalBuffer = newBuffer; |
| | | 506 | | } |
| | | 507 | | |
| | | 508 | | //if (TD.WebSocketAsyncReadStopIsEnabled()) |
| | | 509 | | //{ |
| | | 510 | | // TD.WebSocketAsyncReadStop( |
| | | 511 | | // this.webSocket.GetHashCode(), |
| | | 512 | | // receivedByteCount, |
| | | 513 | | // TraceUtility.GetRemoteEndpointAddressPort(this.RemoteEndpointMessageProperty)); |
| | | 514 | | //} |
| | 18 | 515 | | } |
| | | 516 | | catch (AggregateException ex) |
| | | 517 | | { |
| | 0 | 518 | | WebSocketHelper.ThrowCorrectException(ex, TimeSpan.MaxValue, WebSocketHelper.ReceiveOperatio |
| | 0 | 519 | | } |
| | | 520 | | } |
| | 18 | 521 | | while (!endOfMessage && !_closureReceived); |
| | | 522 | | |
| | 18 | 523 | | byte[] buffer = null; |
| | 18 | 524 | | bool success = false; |
| | | 525 | | try |
| | | 526 | | { |
| | 18 | 527 | | buffer = _bufferManager.TakeBuffer(receivedByteCount); |
| | 18 | 528 | | Buffer.BlockCopy(internalBuffer, 0, buffer, 0, receivedByteCount); |
| | | 529 | | Fx.Assert(result != null, "Result should not be null"); |
| | 18 | 530 | | _pendingMessage = await PrepareMessageAsync(result, buffer, receivedByteCount); |
| | 18 | 531 | | success = true; |
| | 18 | 532 | | } |
| | | 533 | | finally |
| | | 534 | | { |
| | 18 | 535 | | if (buffer != null && (!success || _pendingMessage == null)) |
| | | 536 | | { |
| | 9 | 537 | | _bufferManager.ReturnBuffer(buffer); |
| | | 538 | | } |
| | | 539 | | } |
| | 18 | 540 | | } |
| | 0 | 541 | | catch (Exception ex) |
| | | 542 | | { |
| | 0 | 543 | | if (Fx.IsFatal(ex)) |
| | | 544 | | { |
| | 0 | 545 | | throw; |
| | | 546 | | } |
| | | 547 | | |
| | 0 | 548 | | _pendingException = WebSocketHelper.ConvertAndTraceException(ex, TimeSpan.MaxValue, WebSocketHelper. |
| | 0 | 549 | | } |
| | | 550 | | finally |
| | | 551 | | { |
| | 18 | 552 | | if (internalBuffer != null) |
| | | 553 | | { |
| | 18 | 554 | | _bufferManager.ReturnBuffer(internalBuffer); |
| | | 555 | | } |
| | | 556 | | } |
| | 18 | 557 | | } |
| | | 558 | | |
| | | 559 | | public async Task<bool> WaitForMessageAsync(CancellationToken token) |
| | | 560 | | { |
| | | 561 | | try |
| | | 562 | | { |
| | 0 | 563 | | _pendingMessage = await ReceiveAsync(token); |
| | 0 | 564 | | return true; |
| | | 565 | | } |
| | 0 | 566 | | catch (TimeoutException ex) |
| | | 567 | | { |
| | | 568 | | //if (TD.ReceiveTimeoutIsEnabled()) |
| | | 569 | | //{ |
| | | 570 | | // TD.ReceiveTimeout(ex.Message); |
| | | 571 | | //} |
| | | 572 | | |
| | 0 | 573 | | _pendingException = Fx.Exception.AsError(ex); |
| | 0 | 574 | | DiagnosticUtility.TraceHandledException(ex, TraceEventType.Information); |
| | 0 | 575 | | return false; |
| | | 576 | | } |
| | 0 | 577 | | } |
| | | 578 | | |
| | | 579 | | internal void FinishUsingMessageStream(Exception ex) |
| | | 580 | | { |
| | | 581 | | //// The pattern of the task here is: |
| | | 582 | | //// 1) Only one thread can get the stream and consume the stream. A new task will be created at the mom |
| | | 583 | | //// 2) Only one another thread can enter the lock and wait on the task |
| | | 584 | | //// 3) The cleanup on the stream will return the stream to message source. And the cleanup call is limi |
| | 6 | 585 | | if (ex != null && _pendingException == null) |
| | | 586 | | { |
| | 0 | 587 | | _pendingException = ex; |
| | | 588 | | } |
| | | 589 | | |
| | 6 | 590 | | _streamWaitTask.SetResult(null); |
| | 6 | 591 | | } |
| | | 592 | | |
| | | 593 | | internal void CheckCloseStatus(WebSocketReceiveResult result) |
| | | 594 | | { |
| | 70 | 595 | | if (result.MessageType == WebSocketMessageType.Close) |
| | | 596 | | { |
| | | 597 | | //if (TD.WebSocketCloseStatusReceivedIsEnabled()) |
| | | 598 | | //{ |
| | | 599 | | // TD.WebSocketCloseStatusReceived( |
| | | 600 | | // this.webSocket.GetHashCode(), |
| | | 601 | | // result.CloseStatus.ToString()); |
| | | 602 | | //} |
| | | 603 | | |
| | 11 | 604 | | _closureReceived = true; |
| | 11 | 605 | | _closeDetails.InputCloseStatus = result.CloseStatus; |
| | 11 | 606 | | _closeDetails.InputCloseStatusDescription = result.CloseStatusDescription; |
| | | 607 | | } |
| | 70 | 608 | | } |
| | | 609 | | |
| | | 610 | | private async void StartNextReceiveAsync() |
| | | 611 | | { |
| | | 612 | | Fx.Assert(_receiveTask == null || _receiveTask.Task.IsCompleted, "this.receiveTask is not completed."); |
| | 26 | 613 | | _receiveTask = new TaskCompletionSource<object>(); |
| | 26 | 614 | | int currentState = Interlocked.CompareExchange(ref _asyncReceiveState, AsyncReceiveState.Started, AsyncR |
| | | 615 | | Fx.Assert(currentState == AsyncReceiveState.Finished, "currentState is not AsyncReceiveState.Finished: " |
| | 26 | 616 | | if (currentState != AsyncReceiveState.Finished) |
| | | 617 | | { |
| | 0 | 618 | | throw Fx.Exception.AsError(new InvalidOperationException()); |
| | | 619 | | } |
| | | 620 | | |
| | | 621 | | try |
| | | 622 | | { |
| | 26 | 623 | | if (_useStreaming) |
| | | 624 | | { |
| | 8 | 625 | | if (_streamWaitTask != null) |
| | | 626 | | { |
| | | 627 | | //// Wait until the previous stream message finished. |
| | | 628 | | |
| | 6 | 629 | | await _streamWaitTask.Task.ConfigureAwait(false); |
| | | 630 | | } |
| | | 631 | | |
| | 8 | 632 | | _streamWaitTask = new TaskCompletionSource<object>(); |
| | | 633 | | } |
| | | 634 | | |
| | 26 | 635 | | if (_pendingException == null) |
| | | 636 | | { |
| | 26 | 637 | | if (!_useStreaming) |
| | | 638 | | { |
| | 18 | 639 | | await ReadBufferedMessageAsync().ConfigureAwait(false); |
| | | 640 | | } |
| | | 641 | | else |
| | | 642 | | { |
| | 8 | 643 | | byte[] buffer = _bufferManager.TakeBuffer(_receiveBufferSize); |
| | 8 | 644 | | bool success = false; |
| | | 645 | | try |
| | | 646 | | { |
| | | 647 | | //if (TD.WebSocketAsyncReadStartIsEnabled()) |
| | | 648 | | //{ |
| | | 649 | | // TD.WebSocketAsyncReadStart(this.webSocket.GetHashCode()); |
| | | 650 | | //} |
| | | 651 | | |
| | | 652 | | try |
| | | 653 | | { |
| | 8 | 654 | | Task<WebSocketReceiveResult> receiveTask = _webSocket.ReceiveAsync( |
| | 8 | 655 | | new ArraySegment<byte>(buffer, 0, _receiveBufferSize), |
| | 8 | 656 | | CancellationToken.None); |
| | | 657 | | |
| | 8 | 658 | | await receiveTask.ConfigureAwait(false); |
| | | 659 | | |
| | 8 | 660 | | WebSocketReceiveResult result = receiveTask.Result; |
| | 8 | 661 | | CheckCloseStatus(result); |
| | 8 | 662 | | _pendingMessage = await PrepareMessageAsync(result, buffer, result.Count); |
| | | 663 | | |
| | | 664 | | //if (TD.WebSocketAsyncReadStopIsEnabled()) |
| | | 665 | | //{ |
| | | 666 | | // TD.WebSocketAsyncReadStop( |
| | | 667 | | // this.webSocket.GetHashCode(), |
| | | 668 | | // result.Count, |
| | | 669 | | // TraceUtility.GetRemoteEndpointAddressPort(this.remoteEndpointMessageProper |
| | | 670 | | //} |
| | 8 | 671 | | } |
| | | 672 | | catch (AggregateException ex) |
| | | 673 | | { |
| | 0 | 674 | | WebSocketHelper.ThrowCorrectException(ex, _asyncReceiveTimeout, WebSocketHelper.Rece |
| | 0 | 675 | | } |
| | 8 | 676 | | success = true; |
| | 8 | 677 | | } |
| | 0 | 678 | | catch (Exception ex) |
| | | 679 | | { |
| | 0 | 680 | | if (Fx.IsFatal(ex)) |
| | | 681 | | { |
| | 0 | 682 | | throw; |
| | | 683 | | } |
| | | 684 | | |
| | 0 | 685 | | _pendingException = WebSocketHelper.ConvertAndTraceException(ex, _asyncReceiveTimeout, W |
| | 0 | 686 | | } |
| | | 687 | | finally |
| | | 688 | | { |
| | 8 | 689 | | if (!success) |
| | | 690 | | { |
| | 0 | 691 | | _bufferManager.ReturnBuffer(buffer); |
| | | 692 | | } |
| | | 693 | | } |
| | 8 | 694 | | } |
| | | 695 | | } |
| | 26 | 696 | | } |
| | | 697 | | finally |
| | | 698 | | { |
| | 26 | 699 | | if (Interlocked.CompareExchange(ref _asyncReceiveState, AsyncReceiveState.Finished, AsyncReceiveStat |
| | | 700 | | { |
| | 26 | 701 | | _receiveTask.SetResult(null); |
| | | 702 | | } |
| | | 703 | | } |
| | 26 | 704 | | } |
| | | 705 | | |
| | | 706 | | private void AddMessageProperties(MessageProperties messageProperties, WebSocketMessageType incomingMessageT |
| | | 707 | | { |
| | | 708 | | Fx.Assert(messageProperties != null, "messageProperties should not be null."); |
| | 16 | 709 | | WebSocketMessageProperty messageProperty = new WebSocketMessageProperty( |
| | 16 | 710 | | _context, |
| | 16 | 711 | | _webSocket.SubProtocol, |
| | 16 | 712 | | incomingMessageType, |
| | 16 | 713 | | _properties); |
| | 16 | 714 | | messageProperties.Add(WebSocketMessageProperty.Name, messageProperty); |
| | | 715 | | |
| | 16 | 716 | | if (RemoteEndpointMessageProperty != null) |
| | | 717 | | { |
| | 16 | 718 | | messageProperties.Add(RemoteEndpointMessageProperty.Name, RemoteEndpointMessageProperty); |
| | | 719 | | } |
| | | 720 | | |
| | 16 | 721 | | if (_handshakeSecurityMessageProperty != null) |
| | | 722 | | { |
| | 0 | 723 | | messageProperties.Security = (SecurityMessageProperty)_handshakeSecurityMessageProperty.CreateCopy() |
| | | 724 | | } |
| | 16 | 725 | | } |
| | | 726 | | |
| | | 727 | | private Message GetPendingMessage() |
| | | 728 | | { |
| | 26 | 729 | | ThrowOnPendingException(ref _pendingException); |
| | | 730 | | |
| | 26 | 731 | | if (_pendingMessage != null) |
| | | 732 | | { |
| | 15 | 733 | | Message pendingMessage = _pendingMessage; |
| | 15 | 734 | | _pendingMessage = null; |
| | 15 | 735 | | return pendingMessage; |
| | | 736 | | } |
| | | 737 | | |
| | 11 | 738 | | return null; |
| | | 739 | | } |
| | | 740 | | |
| | | 741 | | private async Task<Message> PrepareMessageAsync(WebSocketReceiveResult result, byte[] buffer, int count) |
| | | 742 | | { |
| | 26 | 743 | | if (result.MessageType != WebSocketMessageType.Close) |
| | | 744 | | { |
| | | 745 | | Message message; |
| | 15 | 746 | | if (_useStreaming) |
| | | 747 | | { |
| | 6 | 748 | | TimeoutHelper readTimeoutHelper = new TimeoutHelper(_defaultTimeouts.ReceiveTimeout); |
| | 6 | 749 | | message = await _encoder.ReadMessageAsync( |
| | 6 | 750 | | new MaxMessageSizeStream( |
| | 6 | 751 | | new TimeoutStream( |
| | 6 | 752 | | new WebSocketStream( |
| | 6 | 753 | | this, |
| | 6 | 754 | | new ArraySegment<byte>(buffer, 0, count), |
| | 6 | 755 | | _webSocket, |
| | 6 | 756 | | result.EndOfMessage, |
| | 6 | 757 | | _bufferManager, |
| | 6 | 758 | | new TimeoutHelper(_defaultTimeouts.CloseTimeout).GetCancellationToken()), |
| | 6 | 759 | | readTimeoutHelper.GetCancellationToken()), |
| | 6 | 760 | | _maxReceivedMessageSize), |
| | 6 | 761 | | _maxBufferSize); |
| | | 762 | | } |
| | | 763 | | else |
| | | 764 | | { |
| | 9 | 765 | | ArraySegment<byte> bytes = new ArraySegment<byte>(buffer, 0, count); |
| | 9 | 766 | | message = _encoder.ReadMessage(bytes, _bufferManager); |
| | | 767 | | } |
| | | 768 | | |
| | 15 | 769 | | if (message.Version.Addressing != AddressingVersion.None || !_localAddress.IsAnonymous) |
| | | 770 | | { |
| | 15 | 771 | | _localAddress.ApplyTo(message); |
| | | 772 | | } |
| | | 773 | | |
| | 15 | 774 | | if (message.Version.Addressing == AddressingVersion.None && message.Headers.Action == null) |
| | | 775 | | { |
| | 0 | 776 | | if (result.MessageType == WebSocketMessageType.Binary) |
| | | 777 | | { |
| | 0 | 778 | | message.Headers.Action = WebSocketTransportSettings.BinaryMessageReceivedAction; |
| | | 779 | | } |
| | | 780 | | else |
| | | 781 | | { |
| | | 782 | | // WebSocketMesssageType should always be binary or text at this moment. The layer below us |
| | | 783 | | Fx.Assert(result.MessageType == WebSocketMessageType.Text, "result.MessageType must be WebSo |
| | 0 | 784 | | message.Headers.Action = WebSocketTransportSettings.TextMessageReceivedAction; |
| | | 785 | | } |
| | | 786 | | } |
| | | 787 | | |
| | 15 | 788 | | if (message != null) |
| | | 789 | | { |
| | 15 | 790 | | AddMessageProperties(message.Properties, result.MessageType); |
| | | 791 | | } |
| | | 792 | | |
| | 15 | 793 | | return message; |
| | | 794 | | } |
| | | 795 | | |
| | 11 | 796 | | return null; |
| | 26 | 797 | | } |
| | | 798 | | |
| | | 799 | | private static class AsyncReceiveState |
| | | 800 | | { |
| | | 801 | | internal const int Started = 0; |
| | | 802 | | internal const int Finished = 1; |
| | | 803 | | internal const int Cancelled = 2; |
| | | 804 | | } |
| | | 805 | | } |
| | | 806 | | |
| | | 807 | | private class WebSocketStream : Stream |
| | | 808 | | { |
| | | 809 | | private readonly WebSocket _webSocket; |
| | | 810 | | private readonly WebSocketMessageSource _messageSource; |
| | | 811 | | private CancellationToken _closeToken; |
| | | 812 | | private ArraySegment<byte> _initialReadBuffer; |
| | | 813 | | private bool _endOfMessageReached = false; |
| | | 814 | | private readonly bool _isForRead; |
| | | 815 | | private bool _endofMessageReceived; |
| | | 816 | | private readonly WebSocketMessageType _outgoingMessageType; |
| | | 817 | | private readonly BufferManager _bufferManager; |
| | | 818 | | private int _messageSourceCleanState; |
| | | 819 | | private int _endOfMessageWritten; |
| | | 820 | | private int _readTimeout; |
| | | 821 | | private int _writeTimeout; |
| | | 822 | | |
| | | 823 | | public WebSocketStream( |
| | | 824 | | WebSocketMessageSource messageSource, |
| | | 825 | | ArraySegment<byte> initialBuffer, |
| | | 826 | | WebSocket webSocket, |
| | | 827 | | bool endofMessageReceived, |
| | | 828 | | BufferManager bufferManager, |
| | | 829 | | CancellationToken closeToken) |
| | 6 | 830 | | : this(webSocket, WebSocketDefaults.DefaultWebSocketMessageType, closeToken) |
| | | 831 | | { |
| | | 832 | | Fx.Assert(messageSource != null, "messageSource should not be null."); |
| | 6 | 833 | | _messageSource = messageSource; |
| | 6 | 834 | | _initialReadBuffer = initialBuffer; |
| | 6 | 835 | | _isForRead = true; |
| | 6 | 836 | | _endofMessageReceived = endofMessageReceived; |
| | 6 | 837 | | _bufferManager = bufferManager; |
| | 6 | 838 | | _messageSourceCleanState = WebSocketHelper.OperationNotStarted; |
| | 6 | 839 | | _endOfMessageWritten = WebSocketHelper.OperationNotStarted; |
| | 6 | 840 | | } |
| | | 841 | | |
| | 12 | 842 | | public WebSocketStream( |
| | 12 | 843 | | WebSocket webSocket, |
| | 12 | 844 | | WebSocketMessageType outgoingMessageType, |
| | 12 | 845 | | CancellationToken closeToken) |
| | | 846 | | { |
| | | 847 | | Fx.Assert(webSocket != null, "webSocket should not be null."); |
| | 12 | 848 | | _webSocket = webSocket; |
| | 12 | 849 | | _isForRead = false; |
| | 12 | 850 | | _outgoingMessageType = outgoingMessageType; |
| | 12 | 851 | | _messageSourceCleanState = WebSocketHelper.OperationFinished; |
| | 12 | 852 | | _closeToken = closeToken; |
| | 12 | 853 | | } |
| | | 854 | | |
| | | 855 | | public override bool CanRead |
| | | 856 | | { |
| | 0 | 857 | | get { return _isForRead; } |
| | | 858 | | } |
| | | 859 | | |
| | | 860 | | public override bool CanSeek |
| | | 861 | | { |
| | 0 | 862 | | get { return false; } |
| | | 863 | | } |
| | | 864 | | |
| | | 865 | | public override bool CanTimeout |
| | | 866 | | { |
| | | 867 | | get |
| | | 868 | | { |
| | 12 | 869 | | return true; |
| | | 870 | | } |
| | | 871 | | } |
| | | 872 | | |
| | | 873 | | public override bool CanWrite |
| | | 874 | | { |
| | 3 | 875 | | get { return !_isForRead; } |
| | | 876 | | } |
| | | 877 | | |
| | | 878 | | public override long Length |
| | | 879 | | { |
| | 0 | 880 | | get { throw Fx.Exception.AsError(new NotSupportedException(SR.SeekNotSupported)); } |
| | | 881 | | } |
| | | 882 | | |
| | | 883 | | public override long Position |
| | | 884 | | { |
| | | 885 | | get |
| | | 886 | | { |
| | 0 | 887 | | throw Fx.Exception.AsError(new NotSupportedException(SR.SeekNotSupported)); |
| | | 888 | | } |
| | | 889 | | |
| | | 890 | | set |
| | | 891 | | { |
| | 0 | 892 | | throw Fx.Exception.AsError(new NotSupportedException(SR.SeekNotSupported)); |
| | | 893 | | } |
| | | 894 | | } |
| | | 895 | | |
| | | 896 | | public override int ReadTimeout |
| | | 897 | | { |
| | | 898 | | get |
| | | 899 | | { |
| | 12 | 900 | | return _readTimeout; |
| | | 901 | | } |
| | | 902 | | |
| | | 903 | | set |
| | | 904 | | { |
| | | 905 | | Fx.Assert(value >= 0, "ReadTimeout should not be negative."); |
| | 12 | 906 | | _readTimeout = value; |
| | 12 | 907 | | } |
| | | 908 | | } |
| | | 909 | | |
| | | 910 | | public override int WriteTimeout |
| | | 911 | | { |
| | | 912 | | get |
| | | 913 | | { |
| | 0 | 914 | | return _writeTimeout; |
| | | 915 | | } |
| | | 916 | | |
| | | 917 | | set |
| | | 918 | | { |
| | | 919 | | Fx.Assert(value >= 0, "WriteTimeout should not be negative."); |
| | 12 | 920 | | _writeTimeout = value; |
| | 12 | 921 | | } |
| | | 922 | | } |
| | | 923 | | |
| | | 924 | | public override void Close() |
| | | 925 | | { |
| | 6 | 926 | | base.Close(); |
| | | 927 | | // There's no async close on Stream |
| | 6 | 928 | | CleanupAsync(_closeToken).GetAwaiter().GetResult(); |
| | 6 | 929 | | } |
| | | 930 | | |
| | | 931 | | public override void Flush() |
| | | 932 | | { |
| | 15 | 933 | | } |
| | | 934 | | |
| | | 935 | | public override IAsyncResult BeginRead(byte[] buffer, int offset, int count, AsyncCallback callback, object |
| | | 936 | | { |
| | 0 | 937 | | return ReadAsync(buffer, offset, count).ToApm(callback, state); |
| | | 938 | | } |
| | | 939 | | |
| | | 940 | | public override int EndRead(IAsyncResult asyncResult) |
| | | 941 | | { |
| | 0 | 942 | | return asyncResult.ToApmEnd<int>(); |
| | | 943 | | } |
| | | 944 | | |
| | | 945 | | public override int Read(byte[] buffer, int offset, int count) |
| | | 946 | | { |
| | 0 | 947 | | return ReadAsync(buffer, offset, count).GetAwaiter().GetResult(); |
| | | 948 | | } |
| | | 949 | | |
| | | 950 | | public override async Task<int> ReadAsync(byte[] buffer, int offset, int count, CancellationToken cancellati |
| | | 951 | | { |
| | | 952 | | Fx.Assert(_messageSource != null, "messageSource should not be null in read case."); |
| | | 953 | | Fx.Assert(cancellationToken.CanBeCanceled, "WebSocketStream should be wrapped by TimeoutStream which sho |
| | 245 | 954 | | cancellationToken.ThrowIfCancellationRequested(); |
| | | 955 | | |
| | 245 | 956 | | if (_endOfMessageReached) |
| | | 957 | | { |
| | 17 | 958 | | return 0; |
| | | 959 | | } |
| | | 960 | | |
| | 228 | 961 | | if (_initialReadBuffer.Count != 0) |
| | | 962 | | { |
| | 184 | 963 | | return GetBytesFromInitialReadBuffer(buffer, offset, count); |
| | | 964 | | } |
| | | 965 | | |
| | 44 | 966 | | int receivedBytes = 0; |
| | 44 | 967 | | if (_endofMessageReceived) |
| | | 968 | | { |
| | 0 | 969 | | _endOfMessageReached = true; |
| | | 970 | | } |
| | | 971 | | else |
| | | 972 | | { |
| | | 973 | | //if (TD.WebSocketAsyncReadStartIsEnabled()) |
| | | 974 | | //{ |
| | | 975 | | // TD.WebSocketAsyncReadStart(this.webSocket.GetHashCode()); |
| | | 976 | | //} |
| | | 977 | | |
| | 44 | 978 | | WebSocketReceiveResult result = null; |
| | | 979 | | try |
| | | 980 | | { |
| | 44 | 981 | | result = await _webSocket.ReceiveAsync(new ArraySegment<byte>(buffer, offset, count), cancellati |
| | 44 | 982 | | } |
| | | 983 | | catch (Exception ex) |
| | | 984 | | { |
| | 0 | 985 | | if (Fx.IsFatal(ex)) |
| | | 986 | | { |
| | 0 | 987 | | throw; |
| | | 988 | | } |
| | | 989 | | |
| | 0 | 990 | | WebSocketHelper.ThrowCorrectException(ex, TimeoutHelper.GetOriginalTimeout(cancellationToken), W |
| | 0 | 991 | | } |
| | | 992 | | |
| | 44 | 993 | | if (result.EndOfMessage) |
| | | 994 | | { |
| | 6 | 995 | | _endofMessageReceived = true; |
| | 6 | 996 | | _endOfMessageReached = true; |
| | | 997 | | } |
| | | 998 | | |
| | 44 | 999 | | receivedBytes = result.Count; |
| | 44 | 1000 | | CheckResultAndEnsureNotCloseMessage(_messageSource, result); |
| | | 1001 | | |
| | | 1002 | | //if (TD.WebSocketAsyncReadStopIsEnabled()) |
| | | 1003 | | //{ |
| | | 1004 | | // TD.WebSocketAsyncReadStop( |
| | | 1005 | | // this.webSocket.GetHashCode(), |
| | | 1006 | | // receivedBytes, |
| | | 1007 | | // this.messageSource != null ? TraceUtility.GetRemoteEndpointAddressPort(this.messageSource. |
| | | 1008 | | //} |
| | 44 | 1009 | | } |
| | | 1010 | | |
| | 44 | 1011 | | if (_endOfMessageReached) |
| | | 1012 | | { |
| | 6 | 1013 | | await CleanupAsync(cancellationToken); |
| | | 1014 | | } |
| | | 1015 | | |
| | 44 | 1016 | | return receivedBytes; |
| | 245 | 1017 | | } |
| | | 1018 | | |
| | | 1019 | | public override long Seek(long offset, SeekOrigin origin) |
| | | 1020 | | { |
| | 0 | 1021 | | throw Fx.Exception.AsError(new NotSupportedException()); |
| | | 1022 | | } |
| | | 1023 | | |
| | | 1024 | | public override void SetLength(long value) |
| | | 1025 | | { |
| | 0 | 1026 | | throw Fx.Exception.AsError(new NotSupportedException()); |
| | | 1027 | | } |
| | | 1028 | | |
| | | 1029 | | public override void Write(byte[] buffer, int offset, int count) |
| | | 1030 | | { |
| | 0 | 1031 | | WriteAsync(buffer, offset, count).GetAwaiter().GetResult(); |
| | 0 | 1032 | | } |
| | | 1033 | | |
| | | 1034 | | public override async Task WriteAsync(byte[] buffer, int offset, int count, CancellationToken cancellationTo |
| | | 1035 | | { |
| | 12 | 1036 | | if (_endOfMessageWritten == WebSocketHelper.OperationFinished) |
| | | 1037 | | { |
| | 0 | 1038 | | throw Fx.Exception.AsError(new InvalidOperationException(SR.WebSocketStreamWriteCalledAfterEOMSent)) |
| | | 1039 | | } |
| | | 1040 | | |
| | | 1041 | | Fx.Assert(cancellationToken.CanBeCanceled, "WebSocketStream should be wrapped by TimeoutStream which sho |
| | 12 | 1042 | | cancellationToken.ThrowIfCancellationRequested(); |
| | | 1043 | | |
| | 12 | 1044 | | cancellationToken.ThrowIfCancellationRequested(); |
| | | 1045 | | //if (TD.WebSocketAsyncWriteStartIsEnabled()) |
| | | 1046 | | //{ |
| | | 1047 | | // TD.WebSocketAsyncWriteStart( |
| | | 1048 | | // this.webSocket.GetHashCode(), |
| | | 1049 | | // count, |
| | | 1050 | | // this.messageSource != null ? TraceUtility.GetRemoteEndpointAddressPort(this.messageSource. |
| | | 1051 | | //} |
| | | 1052 | | |
| | | 1053 | | try |
| | | 1054 | | { |
| | 12 | 1055 | | await _webSocket.SendAsync(new ArraySegment<byte>(buffer, offset, count), _outgoingMessageType, fals |
| | 12 | 1056 | | } |
| | | 1057 | | catch (Exception ex) |
| | | 1058 | | { |
| | 0 | 1059 | | if (Fx.IsFatal(ex)) |
| | | 1060 | | { |
| | 0 | 1061 | | throw; |
| | | 1062 | | } |
| | | 1063 | | |
| | 0 | 1064 | | WebSocketHelper.ThrowCorrectException(ex, TimeoutHelper.GetOriginalTimeout(cancellationToken), WebSo |
| | 0 | 1065 | | } |
| | | 1066 | | |
| | | 1067 | | //if (TD.WebSocketAsyncWriteStopIsEnabled()) |
| | | 1068 | | //{ |
| | | 1069 | | // TD.WebSocketAsyncWriteStop(this.webSocket.GetHashCode()); |
| | | 1070 | | //} |
| | 12 | 1071 | | } |
| | | 1072 | | |
| | | 1073 | | public override IAsyncResult BeginWrite(byte[] buffer, int offset, int count, AsyncCallback callback, object |
| | | 1074 | | { |
| | 0 | 1075 | | return WriteAsync(buffer, offset, count).ToApm(callback, state); |
| | | 1076 | | } |
| | | 1077 | | |
| | | 1078 | | public override void EndWrite(IAsyncResult asyncResult) |
| | | 1079 | | { |
| | 0 | 1080 | | asyncResult.ToApmEnd(); |
| | 0 | 1081 | | } |
| | | 1082 | | |
| | | 1083 | | public async Task WriteEndOfMessageAsync(CancellationToken cancellationToken) |
| | | 1084 | | { |
| | | 1085 | | //if (TD.WebSocketAsyncWriteStartIsEnabled()) |
| | | 1086 | | //{ |
| | | 1087 | | // TD.WebSocketAsyncWriteStart( |
| | | 1088 | | // this.webSocket.GetHashCode(), |
| | | 1089 | | // 0, |
| | | 1090 | | // this.messageSource != null ? TraceUtility.GetRemoteEndpointAddressPort(this.messageSource. |
| | | 1091 | | //} |
| | | 1092 | | |
| | 6 | 1093 | | if (Interlocked.CompareExchange(ref _endOfMessageWritten, WebSocketHelper.OperationFinished, WebSocketHe |
| | | 1094 | | { |
| | | 1095 | | try |
| | | 1096 | | { |
| | 6 | 1097 | | await _webSocket.SendAsync(new ArraySegment<byte>(Array.Empty<byte>(), 0, 0), _outgoingMessageTy |
| | 6 | 1098 | | } |
| | | 1099 | | catch (Exception ex) |
| | | 1100 | | { |
| | 0 | 1101 | | if (Fx.IsFatal(ex)) |
| | | 1102 | | { |
| | 0 | 1103 | | throw; |
| | | 1104 | | } |
| | | 1105 | | |
| | 0 | 1106 | | WebSocketHelper.ThrowCorrectException(ex, TimeoutHelper.GetOriginalTimeout(cancellationToken), W |
| | 0 | 1107 | | } |
| | | 1108 | | } |
| | | 1109 | | |
| | | 1110 | | //if (TD.WebSocketAsyncWriteStopIsEnabled()) |
| | | 1111 | | //{ |
| | | 1112 | | // TD.WebSocketAsyncWriteStop(this.webSocket.GetHashCode()); |
| | | 1113 | | //} |
| | 6 | 1114 | | } |
| | | 1115 | | |
| | | 1116 | | private static void CheckResultAndEnsureNotCloseMessage(WebSocketMessageSource messageSource, WebSocketRecei |
| | | 1117 | | { |
| | 44 | 1118 | | messageSource.CheckCloseStatus(result); |
| | 44 | 1119 | | if (result.MessageType == WebSocketMessageType.Close) |
| | | 1120 | | { |
| | 0 | 1121 | | throw Fx.Exception.AsError(new ProtocolException(SR.WebSocketUnexpectedCloseMessageError)); |
| | | 1122 | | } |
| | 44 | 1123 | | } |
| | | 1124 | | |
| | | 1125 | | private int GetBytesFromInitialReadBuffer(byte[] buffer, int offset, int count) |
| | | 1126 | | { |
| | 184 | 1127 | | int bytesToCopy = _initialReadBuffer.Count > count ? count : _initialReadBuffer.Count; |
| | 184 | 1128 | | Buffer.BlockCopy(_initialReadBuffer.Array, _initialReadBuffer.Offset, buffer, offset, bytesToCopy); |
| | 184 | 1129 | | _initialReadBuffer = new ArraySegment<byte>(_initialReadBuffer.Array, _initialReadBuffer.Offset + bytesT |
| | 184 | 1130 | | return bytesToCopy; |
| | | 1131 | | } |
| | | 1132 | | |
| | | 1133 | | private async Task CleanupAsync(CancellationToken cancellationToken) |
| | | 1134 | | { |
| | 12 | 1135 | | if (_isForRead) |
| | | 1136 | | { |
| | 12 | 1137 | | if (Interlocked.CompareExchange(ref _messageSourceCleanState, WebSocketHelper.OperationFinished, Web |
| | | 1138 | | { |
| | 6 | 1139 | | Exception pendingException = null; |
| | | 1140 | | try |
| | | 1141 | | { |
| | 6 | 1142 | | if (!_endofMessageReceived && (_webSocket.State == WebSocketState.Open || _webSocket.State = |
| | | 1143 | | { |
| | | 1144 | | // Drain the reading stream |
| | | 1145 | | do |
| | | 1146 | | { |
| | | 1147 | | try |
| | | 1148 | | { |
| | 0 | 1149 | | WebSocketReceiveResult receiveResult = await _webSocket.ReceiveAsync(new ArraySe |
| | 0 | 1150 | | _endofMessageReceived = receiveResult.EndOfMessage; |
| | 0 | 1151 | | } |
| | | 1152 | | catch (Exception ex) |
| | | 1153 | | { |
| | 0 | 1154 | | if (Fx.IsFatal(ex)) |
| | | 1155 | | { |
| | 0 | 1156 | | throw; |
| | | 1157 | | } |
| | | 1158 | | |
| | 0 | 1159 | | WebSocketHelper.ThrowCorrectException(ex, TimeoutHelper.GetOriginalTimeout(cance |
| | 0 | 1160 | | } |
| | | 1161 | | } |
| | 0 | 1162 | | while (!_endofMessageReceived && (_webSocket.State == WebSocketState.Open || _webSocket. |
| | | 1163 | | } |
| | 6 | 1164 | | } |
| | 0 | 1165 | | catch (Exception ex) |
| | | 1166 | | { |
| | 0 | 1167 | | if (Fx.IsFatal(ex)) |
| | | 1168 | | { |
| | 0 | 1169 | | throw; |
| | | 1170 | | } |
| | | 1171 | | |
| | | 1172 | | // Not throwing out this exception during stream cleanup. The exception |
| | | 1173 | | // will be thrown out when we are trying to receive the next message using the same |
| | | 1174 | | // WebSocket object. |
| | 0 | 1175 | | pendingException = WebSocketHelper.ConvertAndTraceException(ex, TimeoutHelper.GetOriginalTim |
| | 0 | 1176 | | } |
| | | 1177 | | |
| | 6 | 1178 | | _bufferManager.ReturnBuffer(_initialReadBuffer.Array); |
| | | 1179 | | Fx.Assert(_messageSource != null, "messageSource should not be null."); |
| | 6 | 1180 | | _messageSource.FinishUsingMessageStream(pendingException); |
| | 6 | 1181 | | } |
| | | 1182 | | } |
| | | 1183 | | else |
| | | 1184 | | { |
| | 0 | 1185 | | if (Interlocked.CompareExchange(ref _endOfMessageWritten, WebSocketHelper.OperationFinished, WebSock |
| | | 1186 | | { |
| | 0 | 1187 | | await WriteEndOfMessageAsync(cancellationToken); |
| | | 1188 | | } |
| | | 1189 | | } |
| | 12 | 1190 | | } |
| | | 1191 | | } |
| | | 1192 | | |
| | | 1193 | | private class WebSocketCloseDetails : IWebSocketCloseDetails |
| | | 1194 | | { |
| | 11 | 1195 | | public WebSocketCloseStatus? InputCloseStatus { get; internal set; } |
| | | 1196 | | |
| | 11 | 1197 | | public string InputCloseStatusDescription { get; internal set; } |
| | | 1198 | | |
| | 22 | 1199 | | internal WebSocketCloseStatus OutputCloseStatus { get; private set; } = WebSocketCloseStatus.NormalClosure; |
| | | 1200 | | |
| | 11 | 1201 | | internal string OutputCloseStatusDescription { get; private set; } |
| | | 1202 | | |
| | | 1203 | | public void SetOutputCloseStatus(WebSocketCloseStatus closeStatus, string closeStatusDescription) |
| | | 1204 | | { |
| | 0 | 1205 | | OutputCloseStatus = closeStatus; |
| | 0 | 1206 | | OutputCloseStatusDescription = closeStatusDescription; |
| | 0 | 1207 | | } |
| | | 1208 | | } |
| | | 1209 | | } |
| | | 1210 | | } |