Skip to content
Merged
Show file tree
Hide file tree
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
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,7 @@
import io.netty.channel.Channel;
import io.netty.channel.ChannelHandler.Sharable;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import io.netty.handler.codec.DecoderException;
import io.netty.handler.codec.TooLongFrameException;
import io.netty.handler.codec.compression.DecompressionException;
import io.netty.handler.codec.http.HttpHeaderValues;
Expand All @@ -27,9 +27,11 @@
import io.netty.handler.codec.http.HttpResponse;
import io.netty.handler.codec.http.LastHttpContent;
import io.netty.handler.codec.http.websocketx.CloseWebSocketFrame;
import io.netty.handler.codec.http.websocketx.WebSocket08FrameDecoder;
import io.netty.handler.codec.http.websocketx.WebSocketCloseStatus;
import io.netty.handler.codec.http.websocketx.WebSocketDecoderConfig;
import io.netty.handler.codec.http.websocketx.WebSocketFrame;
import io.netty.util.ReferenceCountUtil;
import io.netty.util.AttributeKey;
import io.netty.util.concurrent.ScheduledFuture;
import org.asynchttpclient.AsyncHandler.State;
import org.asynchttpclient.AsyncHttpClientConfig;
Expand Down Expand Up @@ -60,6 +62,7 @@ public final class WebSocketHandler extends AsyncHttpClientHandler {

// How long the server gets to close the connection after a 1009, before the client closes it itself.
private static final long CLOSE_HANDSHAKE_TIMEOUT_SECONDS = 10;
private static final AttributeKey<Boolean> CLOSING_WITH_MESSAGE_TOO_BIG = AttributeKey.valueOf("closingWithMessageTooBig");

public WebSocketHandler(AsyncHttpClientConfig config, ChannelManager channelManager, NettyRequestSender requestSender) {
super(config, channelManager, requestSender);
Expand Down Expand Up @@ -156,7 +159,9 @@ public void handleRead(Channel channel, NettyResponseFuture<?> future, Object e)

} else if (e instanceof WebSocketFrame) {
if (isClosingWithMessageTooBig(channel)) {
// Decoded from what the decoder already held when the 1009 was sent.
if (e instanceof CloseWebSocketFrame) {
getNettyWebSocket(future).handleFrame((CloseWebSocketFrame) e);
}
return;
}
WebSocketFrame frame = (WebSocketFrame) e;
Expand Down Expand Up @@ -186,7 +191,8 @@ public void exceptionCaught(ChannelHandlerContext ctx, Throwable e) {
if (isClosingWithMessageTooBig(ctx.channel())) {
// The listener already got onError for the 1009, and gets onClose once the connection is closed.
logger.debug("Exception while closing with 1009 on channel {}", ctx.channel(), cause);
if (!tooBig) {
// Closing on a bad frame would leave the server's input unread.
if (!(cause instanceof DecoderException)) {
Channels.silentlyCloseChannel(ctx.channel());
}
return;
Expand All @@ -199,24 +205,36 @@ public void exceptionCaught(ChannelHandlerContext ctx, Throwable e) {
}

private static boolean isClosingWithMessageTooBig(Channel channel) {
return channel.pipeline().get(DiscardInbound.class) != null;
return channel.hasAttr(CLOSING_WITH_MESSAGE_TOO_BIG);
}

/**
* Sends the 1009 and leaves closing the connection to the server, as RFC 6455 section 7.1.1 asks of a client,
* discarding what the server still sends until then. Closing it here instead would leave that input unread, so
* the connection would be reset, and the server could lose the close frame and report 1006.
* discarding what the server still sends until then except its close frame. Closing it here instead would leave
* that input unread, so the connection would be reset, and the server could lose the close frame and report 1006.
* The connection keeps its permit until it is closed.
*/
private void closeWithMessageTooBig(ChannelHandlerContext ctx, Throwable e) {
ctx.pipeline().addBefore(WS_DECODER_HANDLER, null, new DiscardInbound());
Channel channel = ctx.channel();
channel.attr(CLOSING_WITH_MESSAGE_TOO_BIG).set(Boolean.TRUE);
ctx.writeAndFlush(new CloseWebSocketFrame(WebSocketCloseStatus.MESSAGE_TOO_BIG));
ScheduledFuture<?> forceClose = ctx.executor().schedule(() -> Channels.silentlyCloseChannel(channel),
CLOSE_HANDSHAKE_TIMEOUT_SECONDS, TimeUnit.SECONDS);
channel.closeFuture().addListener(f -> forceClose.cancel(false));
// As abort() does: a listener that connects again from onError must not be refused this connection's permit.
Channels.releasePermit(channel);
notifyMessageTooBig(channel, e);

// The current decoder would answer a bad frame behind the message with a second close frame and close the
// connection. Replacing it hands the bytes it still holds to one that only throws.
ctx.pipeline().replace(WS_DECODER_HANDLER, WS_DECODER_HANDLER, new WebSocket08FrameDecoder(
WebSocketDecoderConfig.newBuilder()
.expectMaskedFrames(false)
.allowExtensions(config.isEnableWebSocketCompression())
.maxFramePayloadLength(config.getWebSocketMaxFrameSize())
.closeOnProtocolViolation(false)
.build()));
}

private void notifyMessageTooBig(Channel channel, Throwable e) {
Object attribute = Channels.getAttribute(channel);
if (!(attribute instanceof NettyResponseFuture<?>)) {
return;
Expand All @@ -242,13 +260,6 @@ private void closeWithMessageTooBig(ChannelHandlerContext ctx, Throwable e) {
}
}

private static final class DiscardInbound extends ChannelInboundHandlerAdapter {
@Override
public void channelRead(ChannelHandlerContext ctx, Object msg) {
ReferenceCountUtil.release(msg);
}
}

@Override
public void handleException(NettyResponseFuture<?> future, Throwable e) {
logger.warn("onError", e);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,7 @@
import org.asynchttpclient.AsyncHttpClient;
import org.asynchttpclient.ListenableFuture;
import org.asynchttpclient.Response;
import org.asynchttpclient.exception.TooManyConnectionsException;
import org.eclipse.jetty.server.handler.AbstractHandler;
import org.eclipse.jetty.servlet.ServletContextHandler;
import org.eclipse.jetty.websocket.api.Session;
Expand All @@ -34,6 +35,7 @@
import java.net.InetAddress;
import java.net.ServerSocket;
import java.net.Socket;
import java.net.SocketTimeoutException;
import java.util.List;
import java.util.Locale;
import java.util.concurrent.CompletableFuture;
Expand Down Expand Up @@ -100,8 +102,8 @@ public void aMessageOverTheBufferLimitClosesWith1009() throws Exception {

/**
* Frames the decoder already holds behind the message are not delivered after onError, the WebSocket refuses
* sends once the 1009 is out, a listener connecting again from onError gets this connection's permit, and a frame
* the decoder refuses while the client waits for the server to close ends the WebSocket once, with onClose.
* sends once the 1009 is out, the connection keeps its permit until it is closed, and a frame the decoder refuses
* while the client waits for the server to close gets no second close frame and ends the WebSocket once.
*/
@Test
@Timeout(unit = TimeUnit.MILLISECONDS, value = 30000)
Expand All @@ -118,7 +120,9 @@ public void aMessageOverTheBufferLimitEndsTheWebSocketOnce() throws Exception {
// A reserved opcode, which the decoder refuses with an exception of its own.
frames.write(frame(0x83, new byte[0]));
socket.getOutputStream().write(frames.toByteArray());
return readCloseCode(socket.getInputStream());
int code = readCloseCode(socket.getInputStream());
assertClientWaits(socket);
return code;
} catch (IOException e) {
throw new IllegalStateException(e);
}
Expand All @@ -129,6 +133,7 @@ public void aMessageOverTheBufferLimitEndsTheWebSocketOnce() throws Exception {
AtomicInteger closes = new AtomicInteger();
AtomicBoolean openAfterError = new AtomicBoolean(true);
CompletableFuture<Boolean> sendAfterErrorFailed = new CompletableFuture<>();
CompletableFuture<ListenableFuture<Response>> refused = new CompletableFuture<>();
CompletableFuture<ListenableFuture<Response>> next = new CompletableFuture<>();
CompletableFuture<Integer> closed = new CompletableFuture<>();
try (AsyncHttpClient client = asyncHttpClient(config().setWebSocketMaxBufferSize(64).setMaxConnections(1))) {
Expand All @@ -152,19 +157,22 @@ public void onError(Throwable t) {
errors.incrementAndGet();
openAfterError.set(webSocket.isOpen());
webSocket.sendTextFrame("late").addListener(f -> sendAfterErrorFailed.complete(!f.isSuccess()));
next.complete(client.prepareGet("http://localhost:" + port1 + '/').execute());
refused.complete(client.prepareGet("http://localhost:" + port1 + '/').execute());
}

@Override
public void onClose(WebSocket websocket, int code, String reason) {
closes.incrementAndGet();
next.complete(client.prepareGet("http://localhost:" + port1 + '/').execute());
closed.complete(code);
}
}).build()).get(10, TimeUnit.SECONDS);

assertEquals(1009, clientCloseCode.get(10, TimeUnit.SECONDS));
assertEquals(1006, closed.get(10, TimeUnit.SECONDS));
// Not refused for the permit of the connection that failed.
ExecutionException thrown = assertThrows(ExecutionException.class,
() -> refused.get(10, TimeUnit.SECONDS).get(10, TimeUnit.SECONDS));
assertInstanceOf(TooManyConnectionsException.class, thrown.getCause());
next.get(10, TimeUnit.SECONDS).get(10, TimeUnit.SECONDS);
assertTrue(sendAfterErrorFailed.get(10, TimeUnit.SECONDS), "a frame was sent after the close frame");
}
Expand Down Expand Up @@ -242,6 +250,52 @@ public void onError(Throwable t) {
}
}

@Test
@Timeout(unit = TimeUnit.MILLISECONDS, value = 30000)
public void theServerCloseFrameEndsTheWaitWithItsCode() throws Exception {
try (ServerSocket server = new ServerSocket(0, 1, InetAddress.getLoopbackAddress())) {
CompletableFuture<Integer> clientCloseCode = CompletableFuture.supplyAsync(() -> {
try (Socket socket = server.accept()) {
upgrade(socket, new byte[0]);
readFrame(socket.getInputStream());
socket.getOutputStream().write(tooBigMessage());
int code = readCloseCode(socket.getInputStream());
// Echoes the 1009 and leaves closing the connection to the client.
socket.getOutputStream().write(frame(0x88, new byte[]{0x03, (byte) 0xF1}));
while (socket.getInputStream().read() >= 0) {
// Nothing else is expected.
}
return code;
} catch (IOException e) {
throw new IllegalStateException(e);
}
});

CompletableFuture<Integer> closed = new CompletableFuture<>();
try (AsyncHttpClient client = asyncHttpClient(config().setWebSocketMaxBufferSize(64))) {
client.prepareGet("ws://127.0.0.1:" + server.getLocalPort() + '/').execute(new WebSocketUpgradeHandler.Builder()
.addWebSocketListener(new WebSocketListener() {
@Override
public void onOpen(WebSocket websocket) {
websocket.sendTextFrame("ready");
}

@Override
public void onClose(WebSocket websocket, int code, String reason) {
closed.complete(code);
}

@Override
public void onError(Throwable t) {
}
}).build()).get(10, TimeUnit.SECONDS);

assertEquals(1009, closed.get(10, TimeUnit.SECONDS));
assertEquals(1009, clientCloseCode.get(10, TimeUnit.SECONDS));
}
}
}

/** Answers the upgrade request on {@code socket} and writes {@code frames} in the same write. */
private static void upgrade(Socket socket, byte[] frames) throws IOException {
InputStream in = socket.getInputStream();
Expand Down Expand Up @@ -303,6 +357,12 @@ private static int readCloseCode(InputStream in) throws IOException {
}
}

/** Fails if the client sends anything else or closes the connection within half a second. */
private static void assertClientWaits(Socket socket) throws IOException {
socket.setSoTimeout(500);
assertThrows(SocketTimeoutException.class, () -> socket.getInputStream().read());
}

private static void readFrame(InputStream in) throws IOException {
if (in.read() < 0) {
throw new IOException("Connection closed");
Expand Down
Loading