Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

WebSocket Destination state abort Close fix #2091

Open
wants to merge 1 commit into
base: develop
Choose a base branch
from
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
38 changes: 34 additions & 4 deletions src/Ocelot/WebSockets/WebSocketsProxyMiddleware.cs
Original file line number Diff line number Diff line change
Expand Up @@ -52,14 +52,22 @@ private static async Task PumpWebSocket(WebSocket source, WebSocket destination,
}
catch (OperationCanceledException)
{
await destination.CloseOutputAsync(WebSocketCloseStatus.EndpointUnavailable, null, cancellationToken);
await TryCloseWebSocket(
destination,
WebSocketCloseStatus.EndpointUnavailable,
null,
cancellationToken);
return;
}
catch (WebSocketException e)
{
if (e.WebSocketErrorCode == WebSocketError.ConnectionClosedPrematurely)
{
await destination.CloseOutputAsync(WebSocketCloseStatus.EndpointUnavailable, null, cancellationToken);
await TryCloseWebSocket(
destination,
WebSocketCloseStatus.EndpointUnavailable,
null,
cancellationToken);
return;
}

Expand All @@ -68,11 +76,18 @@ private static async Task PumpWebSocket(WebSocket source, WebSocket destination,

if (result.MessageType == WebSocketMessageType.Close)
{
await destination.CloseOutputAsync(source.CloseStatus.Value, source.CloseStatusDescription, cancellationToken);
await TryCloseWebSocket(
destination,
source.CloseStatus.Value,
source.CloseStatusDescription,
cancellationToken);
return;
}

await destination.SendAsync(new ArraySegment<byte>(buffer, 0, result.Count), result.MessageType, result.EndOfMessage, cancellationToken);
if (destination.State == WebSocketState.Open)
{
await destination.SendAsync(new ArraySegment<byte>(buffer, 0, result.Count), result.MessageType, result.EndOfMessage, cancellationToken);
}
}
}

Expand Down Expand Up @@ -154,5 +169,20 @@ await Task.WhenAll(
PumpWebSocket(server, client.ToWebSocket(), DefaultWebSocketBufferSize, context.RequestAborted));
}
}

private static async Task<bool> TryCloseWebSocket(
WebSocket webSocket,
WebSocketCloseStatus closeStatus,
string statusDescription,
CancellationToken cancellationToken)
{
if (webSocket.State == WebSocketState.Open || webSocket.State == WebSocketState.CloseReceived)
{
await webSocket.CloseOutputAsync(closeStatus, statusDescription, cancellationToken);
return true;
}

return false;
}
}
}