diff --git a/client/src/main/java/org/asynchttpclient/netty/handler/WebSocketHandler.java b/client/src/main/java/org/asynchttpclient/netty/handler/WebSocketHandler.java index bffca101e..03d1e5e2f 100755 --- a/client/src/main/java/org/asynchttpclient/netty/handler/WebSocketHandler.java +++ b/client/src/main/java/org/asynchttpclient/netty/handler/WebSocketHandler.java @@ -18,6 +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.TooLongFrameException; import io.netty.handler.codec.compression.DecompressionException; import io.netty.handler.codec.http.HttpHeaderValues; @@ -28,6 +29,8 @@ import io.netty.handler.codec.http.websocketx.CloseWebSocketFrame; import io.netty.handler.codec.http.websocketx.WebSocketCloseStatus; import io.netty.handler.codec.http.websocketx.WebSocketFrame; +import io.netty.util.ReferenceCountUtil; +import io.netty.util.concurrent.ScheduledFuture; import org.asynchttpclient.AsyncHandler.State; import org.asynchttpclient.AsyncHttpClientConfig; import org.asynchttpclient.HttpResponseStatus; @@ -40,6 +43,7 @@ import org.asynchttpclient.ws.WebSocketUpgradeHandler; import java.io.IOException; +import java.util.concurrent.TimeUnit; import static io.netty.handler.codec.http.HttpHeaderNames.CONNECTION; import static io.netty.handler.codec.http.HttpHeaderNames.SEC_WEBSOCKET_ACCEPT; @@ -54,6 +58,9 @@ @Sharable 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; + public WebSocketHandler(AsyncHttpClientConfig config, ChannelManager channelManager, NettyRequestSender requestSender) { super(config, channelManager, requestSender); } @@ -92,6 +99,10 @@ private void upgrade(Channel channel, NettyResponseFuture future, WebSocketUp final NettyWebSocket webSocket = new NettyWebSocket(channel, responseHeaders); handler.setWebSocket(webSocket); channelManager.upgradePipelineForWebSockets(channel.pipeline()); + if (future.isDone()) { + // A message too big came along with the upgrade response and failed the upgrade. + return; + } // We don't need to synchronize as replacing the "ws-decoder" will // process using the same thread. @@ -144,6 +155,10 @@ 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. + return; + } WebSocketFrame frame = (WebSocketFrame) e; NettyWebSocket webSocket = getNettyWebSocket(future); // retain because we might buffer the frame @@ -164,15 +179,76 @@ public void handleRead(Channel channel, NettyResponseFuture future, Object e) @Override public void exceptionCaught(ChannelHandlerContext ctx, Throwable e) { // RFC 6455 section 7.4.1: 1009 for a message too big to process, whether the aggregator refused it or the - // inflater did. Queued before the close below. + // inflater did. Throwable cause = getCause(e); - if ((cause instanceof TooLongFrameException && ctx.pipeline().get(WS_FRAME_AGGREGATOR) != null) - || (cause instanceof DecompressionException && ctx.pipeline().get(WS_DECODER_HANDLER) != null)) { - ctx.writeAndFlush(new CloseWebSocketFrame(WebSocketCloseStatus.MESSAGE_TOO_BIG)); + boolean tooBig = (cause instanceof TooLongFrameException && ctx.pipeline().get(WS_FRAME_AGGREGATOR) != null) + || (cause instanceof DecompressionException && ctx.pipeline().get(WS_DECODER_HANDLER) != null); + 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) { + Channels.silentlyCloseChannel(ctx.channel()); + } + return; + } + if (tooBig) { + closeWithMessageTooBig(ctx, e); + return; } super.exceptionCaught(ctx, e); } + private static boolean isClosingWithMessageTooBig(Channel channel) { + return channel.pipeline().get(DiscardInbound.class) != null; + } + + /** + * 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. + */ + private void closeWithMessageTooBig(ChannelHandlerContext ctx, Throwable e) { + ctx.pipeline().addBefore(WS_DECODER_HANDLER, null, new DiscardInbound()); + Channel channel = ctx.channel(); + 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); + + Object attribute = Channels.getAttribute(channel); + if (!(attribute instanceof NettyResponseFuture)) { + return; + } + NettyResponseFuture future = (NettyResponseFuture) attribute; + logger.warn("onError", e); + try { + NettyWebSocket webSocket = getNettyWebSocket(future); + if (webSocket != null) { + webSocket.markClosing(); + } + if (!future.isDone()) { + // The message came along with the upgrade response, before onOpen: the upgrade fails instead, and + // upgrade() does not open the WebSocket. As for any upgrade that fails, the listeners get onError and + // no onClose. + future.abort(e); + Channels.setDiscard(channel); + } else if (webSocket != null) { + webSocket.onError(e); + } + } catch (Throwable t) { + logger.error("onError", t); + } + } + + 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); diff --git a/client/src/main/java/org/asynchttpclient/netty/request/body/Http2BodyWriter.java b/client/src/main/java/org/asynchttpclient/netty/request/body/Http2BodyWriter.java index e54b6df62..fc0972da8 100644 --- a/client/src/main/java/org/asynchttpclient/netty/request/body/Http2BodyWriter.java +++ b/client/src/main/java/org/asynchttpclient/netty/request/body/Http2BodyWriter.java @@ -126,6 +126,7 @@ default void onResume(Runnable resume) { // writer until written; released by finish() if still set when the pump ends. private ByteBuf pending; private boolean done; + private boolean sourceClosed; // flush() can synchronously fire channelWritabilityChanged. Prevent that callback from re-entering the // pump, and remember permanently once the terminal frame has been emitted so later callbacks cannot write @@ -254,6 +255,8 @@ private void pump() { // First iteration (toWrite == null): nothing written yet, loop to read the second chunk. } } catch (Throwable t) { + // Released before the request fails, so that whoever learns of the failure can delete a file body. + closeSource(); future.abort(t); finish(t); } finally { @@ -313,11 +316,7 @@ private void finish(Throwable cause) { resumeHandler = null; } - try { - source.close(); - } catch (Throwable t) { - LOGGER.warn("Failed to close HTTP/2 request body source", t); - } + closeSource(); if (cause != null) { LOGGER.debug("HTTP/2 request body streaming failed; closing stream", cause); @@ -328,6 +327,18 @@ private void finish(Throwable cause) { } } + private void closeSource() { + if (sourceClosed) { + return; + } + sourceClosed = true; + try { + source.close(); + } catch (Throwable t) { + LOGGER.warn("Failed to close HTTP/2 request body source", t); + } + } + /** * Resumes the parked pump when the stream channel becomes writable again. */ diff --git a/client/src/main/java/org/asynchttpclient/netty/ws/NettyWebSocket.java b/client/src/main/java/org/asynchttpclient/netty/ws/NettyWebSocket.java index 581b2b0f0..793b580f9 100755 --- a/client/src/main/java/org/asynchttpclient/netty/ws/NettyWebSocket.java +++ b/client/src/main/java/org/asynchttpclient/netty/ws/NettyWebSocket.java @@ -226,6 +226,15 @@ public boolean isReady() { return ready; } + /** + * Refuses further sends once the client has sent a close frame of its own and waits for the server to close the + * connection, and drops the frames buffered for a WebSocket that will not open. + */ + public void markClosing() { + closing = true; + releaseBufferedFrames(); + } + public void bufferFrame(WebSocketFrame frame) { if (bufferedFrames == null) { bufferedFrames = new ArrayList<>(1); diff --git a/client/src/test/java/org/asynchttpclient/filter/FailedReplayHttp2Test.java b/client/src/test/java/org/asynchttpclient/filter/FailedReplayHttp2Test.java index 754ce6219..39923b7a1 100644 --- a/client/src/test/java/org/asynchttpclient/filter/FailedReplayHttp2Test.java +++ b/client/src/test/java/org/asynchttpclient/filter/FailedReplayHttp2Test.java @@ -41,12 +41,14 @@ import io.netty.pkitesting.X509Bundle; import io.netty.util.ReferenceCountUtil; import org.asynchttpclient.AsyncHttpClient; +import org.asynchttpclient.exception.FilterException; import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.ExtendWith; import java.io.File; +import java.io.IOException; import java.net.InetSocketAddress; import java.nio.file.Files; import java.util.concurrent.ExecutionException; @@ -72,7 +74,7 @@ public class FailedReplayHttp2Test { private Channel serverChannel; private SslContext serverSslCtx; private int serverPort; - // The server deletes it once it has received the request body, before it answers with a 307. + // The client deletes it once the 307 arrives. private volatile File body; @BeforeEach @@ -101,7 +103,7 @@ protected void initChannel(Channel ch) { .addLast(new Http2MultiplexHandler(new ChannelInitializer() { @Override protected void initChannel(Http2StreamChannel streamCh) { - streamCh.pipeline().addLast(new DeletingRedirectHandler()); + streamCh.pipeline().addLast(new RedirectHandler()); } })); } @@ -137,11 +139,27 @@ public FilterContext filter(FilterContext ctx) { : ctx; } }; + // The server could see the end of the body before the client closed the file, which Windows refuses to + // delete while it is open. Response filters run after the last write of the body has closed it. + ResponseFilter deleteBodyOnRedirect = new ResponseFilter() { + @Override + public FilterContext filter(FilterContext ctx) throws FilterException { + if (ctx.getResponseStatus() != null && ctx.getResponseStatus().getStatusCode() == 307) { + try { + Files.delete(body.toPath()); + } catch (IOException e) { + throw new FilterException("Could not delete the request body", e); + } + } + return ctx; + } + }; try (AsyncHttpClient client = asyncHttpClient(config() .setUseInsecureTrustManager(true) .setHttp2Enabled(true) .setFollowRedirect(true) + .addResponseFilter(deleteBodyOnRedirect) .addIOExceptionFilter(replayOnce))) { String base = "https://localhost:" + serverPort; // The redirect refuses to resend the missing file with an IOException, which the filter replays. @@ -155,8 +173,8 @@ public FilterContext filter(FilterContext ctx) { } } - /** Deletes the body file once a request on /redirect has ended, then answers with a 307. Answers 200 otherwise. */ - private final class DeletingRedirectHandler extends SimpleChannelInboundHandler { + /** Answers a request on /redirect with a 307 once it has ended, and 200 otherwise. */ + private final class RedirectHandler extends SimpleChannelInboundHandler { private boolean redirect; @@ -176,7 +194,6 @@ protected void channelRead0(ChannelHandlerContext ctx, Http2StreamFrame frame) t return; } if (redirect) { - Files.delete(body.toPath()); ctx.write(new DefaultHttp2HeadersFrame(new DefaultHttp2Headers().status("307").set("location", "/target"), false)); ctx.writeAndFlush(new DefaultHttp2DataFrame(Unpooled.copiedBuffer("moved", US_ASCII), true)); diff --git a/client/src/test/java/org/asynchttpclient/filter/FailedReplayTest.java b/client/src/test/java/org/asynchttpclient/filter/FailedReplayTest.java index 8b55d64a8..7760351d3 100644 --- a/client/src/test/java/org/asynchttpclient/filter/FailedReplayTest.java +++ b/client/src/test/java/org/asynchttpclient/filter/FailedReplayTest.java @@ -22,6 +22,7 @@ import org.asynchttpclient.AsyncHttpClient; import org.asynchttpclient.ListenableFuture; import org.asynchttpclient.Response; +import org.asynchttpclient.exception.FilterException; import org.eclipse.jetty.server.Request; import org.eclipse.jetty.server.Server; import org.eclipse.jetty.server.ServerConnector; @@ -53,7 +54,7 @@ */ public class FailedReplayTest extends AbstractBasicTest { - // The handler deletes it once it has read the request body, before it answers with a 307. + // The client deletes it once the 307 arrives. private volatile File body; @Override @@ -88,7 +89,6 @@ public void handle(String target, Request baseRequest, HttpServletRequest reques baseRequest.setHandled(true); request.getInputStream().readAllBytes(); if ("/redirect".equals(target)) { - Files.delete(body.toPath()); response.setStatus(307); response.setHeader("Location", "/target"); } else { @@ -111,12 +111,28 @@ public FilterContext filter(FilterContext ctx) { : ctx; } }; + // The server could see the end of the body before the client closed the file, which Windows refuses to + // delete while it is open. Response filters run after the last write of the body has closed it. + ResponseFilter deleteBodyOnRedirect = new ResponseFilter() { + @Override + public FilterContext filter(FilterContext ctx) throws FilterException { + if (ctx.getResponseStatus() != null && ctx.getResponseStatus().getStatusCode() == 307) { + try { + Files.delete(body.toPath()); + } catch (IOException e) { + throw new FilterException("Could not delete the request body", e); + } + } + return ctx; + } + }; // One connection: the request sent from onThrowable needs the permit of the one the replay came from. try (AsyncHttpClient client = asyncHttpClient(config() .setUseInsecureTrustManager(true) .setFollowRedirect(true) .setMaxConnections(1) + .addResponseFilter(deleteBodyOnRedirect) .addIOExceptionFilter(replayOnce))) { String base = "https://localhost:" + port1; CompletableFuture> next = new CompletableFuture<>(); diff --git a/client/src/test/java/org/asynchttpclient/netty/request/body/Http2BodyWriterTest.java b/client/src/test/java/org/asynchttpclient/netty/request/body/Http2BodyWriterTest.java index 209274dd8..12a4e6666 100644 --- a/client/src/test/java/org/asynchttpclient/netty/request/body/Http2BodyWriterTest.java +++ b/client/src/test/java/org/asynchttpclient/netty/request/body/Http2BodyWriterTest.java @@ -275,6 +275,7 @@ public void failingSourceFailsTheRequestWithItsErrorBeforeClosingTheStream() { NettyResponseFuture future = new NettyResponseFuture<>(null, handler, null, 0, null, null, null); IOException failure = new IOException("read failed"); AtomicInteger closed = new AtomicInteger(); + Runnable onClose = mock(Runnable.class); Http2BodyWriter.start(channel, new Http2BodyWriter.ChunkSource() { private boolean first = true; @@ -291,12 +292,15 @@ public ByteBuf nextChunk(ByteBufAllocator alloc) throws IOException { @Override public void close() { closed.incrementAndGet(); + onClose.run(); } }, future); assertTrue(future.isDone()); assertEquals(1, closed.get()); - InOrder order = inOrder(handler, channel); + // The source is released before the request fails, so that whoever learns of the failure can delete a file. + InOrder order = inOrder(onClose, handler, channel); + order.verify(onClose).run(); order.verify(handler).onThrowable(failure); order.verify(channel).close(); } diff --git a/client/src/test/java/org/asynchttpclient/ws/WebSocketMessageTooBigTest.java b/client/src/test/java/org/asynchttpclient/ws/WebSocketMessageTooBigTest.java index 58d9fd4f6..d6aa72313 100644 --- a/client/src/test/java/org/asynchttpclient/ws/WebSocketMessageTooBigTest.java +++ b/client/src/test/java/org/asynchttpclient/ws/WebSocketMessageTooBigTest.java @@ -15,7 +15,10 @@ */ package org.asynchttpclient.ws; +import io.netty.handler.codec.TooLongFrameException; import org.asynchttpclient.AsyncHttpClient; +import org.asynchttpclient.ListenableFuture; +import org.asynchttpclient.Response; import org.eclipse.jetty.server.handler.AbstractHandler; import org.eclipse.jetty.servlet.ServletContextHandler; import org.eclipse.jetty.websocket.api.Session; @@ -24,13 +27,31 @@ import org.junit.jupiter.api.Test; import org.junit.jupiter.api.Timeout; +import java.io.ByteArrayOutputStream; import java.io.IOException; +import java.io.InputStream; +import java.io.OutputStream; +import java.net.InetAddress; +import java.net.ServerSocket; +import java.net.Socket; +import java.util.List; +import java.util.Locale; import java.util.concurrent.CompletableFuture; +import java.util.concurrent.CopyOnWriteArrayList; +import java.util.concurrent.ExecutionException; import java.util.concurrent.TimeUnit; +import java.util.concurrent.atomic.AtomicBoolean; +import java.util.concurrent.atomic.AtomicInteger; +import static java.nio.charset.StandardCharsets.US_ASCII; import static org.asynchttpclient.Dsl.asyncHttpClient; import static org.asynchttpclient.Dsl.config; +import static org.asynchttpclient.ws.WebSocketUtils.getAcceptKey; import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertInstanceOf; +import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.junit.jupiter.api.Assertions.assertTrue; public class WebSocketMessageTooBigTest extends AbstractBasicWebSocketTest { @@ -76,4 +97,227 @@ public void aMessageOverTheBufferLimitClosesWith1009() throws Exception { assertEquals(1009, serverCloseCode.get(10, TimeUnit.SECONDS)); } } + + /** + * 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. + */ + @Test + @Timeout(unit = TimeUnit.MILLISECONDS, value = 30000) + public void aMessageOverTheBufferLimitEndsTheWebSocketOnce() throws Exception { + try (ServerSocket server = new ServerSocket(0, 1, InetAddress.getLoopbackAddress())) { + CompletableFuture clientCloseCode = CompletableFuture.supplyAsync(() -> { + try (Socket socket = server.accept()) { + upgrade(socket, new byte[0]); + // The client's first frame says its listener has the WebSocket. + readFrame(socket.getInputStream()); + ByteArrayOutputStream frames = new ByteArrayOutputStream(); + frames.write(tooBigMessage()); + frames.write(frame(0x81, "after".getBytes(US_ASCII))); + // 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()); + } catch (IOException e) { + throw new IllegalStateException(e); + } + }); + + List texts = new CopyOnWriteArrayList<>(); + AtomicInteger errors = new AtomicInteger(); + AtomicInteger closes = new AtomicInteger(); + AtomicBoolean openAfterError = new AtomicBoolean(true); + CompletableFuture sendAfterErrorFailed = new CompletableFuture<>(); + CompletableFuture> next = new CompletableFuture<>(); + CompletableFuture closed = new CompletableFuture<>(); + try (AsyncHttpClient client = asyncHttpClient(config().setWebSocketMaxBufferSize(64).setMaxConnections(1))) { + client.prepareGet("ws://127.0.0.1:" + server.getLocalPort() + '/').execute(new WebSocketUpgradeHandler.Builder() + .addWebSocketListener(new WebSocketListener() { + private volatile WebSocket webSocket; + + @Override + public void onOpen(WebSocket websocket) { + webSocket = websocket; + websocket.sendTextFrame("ready"); + } + + @Override + public void onTextFrame(String payload, boolean finalFragment, int rsv) { + texts.add(payload); + } + + @Override + 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()); + } + + @Override + public void onClose(WebSocket websocket, int code, String reason) { + closes.incrementAndGet(); + 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. + next.get(10, TimeUnit.SECONDS).get(10, TimeUnit.SECONDS); + assertTrue(sendAfterErrorFailed.get(10, TimeUnit.SECONDS), "a frame was sent after the close frame"); + } + assertEquals(1, errors.get()); + assertEquals(1, closes.get()); + assertFalse(openAfterError.get(), "still open after the close frame"); + assertTrue(texts.isEmpty(), "delivered after onError: " + texts); + } + } + + /** + * A message too big that comes along with the upgrade response fails the upgrade, before the WebSocket opens, and + * the frames before it are dropped. + */ + @Test + @Timeout(unit = TimeUnit.MILLISECONDS, value = 30000) + public void aMessageOverTheBufferLimitWithTheUpgradeResponseFailsTheUpgrade() throws Exception { + try (ServerSocket server = new ServerSocket(0, 1, InetAddress.getLoopbackAddress())) { + CompletableFuture clientCloseCode = CompletableFuture.supplyAsync(() -> { + try (Socket socket = server.accept()) { + ByteArrayOutputStream frames = new ByteArrayOutputStream(); + frames.write(frame(0x81, "early".getBytes(US_ASCII))); + frames.write(tooBigMessage()); + upgrade(socket, frames.toByteArray()); + int code = readCloseCode(socket.getInputStream()); + // Returns once the client has closed the connection in turn. + socket.shutdownOutput(); + while (socket.getInputStream().read() >= 0) { + // Nothing else is expected. + } + return code; + } catch (IOException e) { + throw new IllegalStateException(e); + } + }); + + AtomicBoolean opened = new AtomicBoolean(); + AtomicInteger errors = new AtomicInteger(); + AtomicInteger closes = new AtomicInteger(); + List texts = new CopyOnWriteArrayList<>(); + try (AsyncHttpClient client = asyncHttpClient(config().setWebSocketMaxBufferSize(64).setIoThreadsCount(1))) { + ExecutionException thrown = assertThrows(ExecutionException.class, () -> client + .prepareGet("ws://127.0.0.1:" + server.getLocalPort() + '/') + .execute(new WebSocketUpgradeHandler.Builder().addWebSocketListener(new WebSocketListener() { + @Override + public void onOpen(WebSocket websocket) { + opened.set(true); + } + + @Override + public void onTextFrame(String payload, boolean finalFragment, int rsv) { + texts.add(payload); + } + + @Override + public void onClose(WebSocket websocket, int code, String reason) { + closes.incrementAndGet(); + } + + @Override + public void onError(Throwable t) { + errors.incrementAndGet(); + } + }).build()).get(10, TimeUnit.SECONDS)); + + assertInstanceOf(TooLongFrameException.class, thrown.getCause()); + assertEquals(1009, clientCloseCode.get(10, TimeUnit.SECONDS)); + // The only event loop runs this request after it has handled the closed connection. + client.prepareGet("http://127.0.0.1:" + port1 + '/').execute().get(10, TimeUnit.SECONDS); + } + assertFalse(opened.get(), "opened after the upgrade failed"); + assertEquals(1, errors.get()); + assertEquals(0, closes.get()); + assertTrue(texts.isEmpty(), "delivered after the upgrade failed: " + texts); + } + } + + /** 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(); + ByteArrayOutputStream head = new ByteArrayOutputStream(); + while (!head.toString(US_ASCII).endsWith("\r\n\r\n")) { + int b = in.read(); + if (b < 0) { + throw new IOException("Upgrade request ended early"); + } + head.write(b); + } + String key = null; + for (String line : head.toString(US_ASCII).split("\r\n")) { + if (line.toLowerCase(Locale.ROOT).startsWith("sec-websocket-key:")) { + key = line.substring(line.indexOf(':') + 1).trim(); + } + } + if (key == null) { + throw new IOException("No Sec-WebSocket-Key in " + head); + } + ByteArrayOutputStream response = new ByteArrayOutputStream(); + response.write(("HTTP/1.1 101 Switching Protocols\r\nUpgrade: websocket\r\nConnection: Upgrade\r\n" + + "Sec-WebSocket-Accept: " + getAcceptKey(key) + "\r\n\r\n").getBytes(US_ASCII)); + response.write(frames); + OutputStream out = socket.getOutputStream(); + out.write(response.toByteArray()); + out.flush(); + } + + /** Two text fragments of 40 bytes each: over a 64-byte buffer once aggregated. */ + private static byte[] tooBigMessage() throws IOException { + byte[] fragment = "x".repeat(40).getBytes(US_ASCII); + ByteArrayOutputStream message = new ByteArrayOutputStream(); + message.write(frame(0x01, fragment)); + message.write(frame(0x80, fragment)); + return message.toByteArray(); + } + + private static byte[] frame(int finAndOpcode, byte[] payload) { + byte[] frame = new byte[2 + payload.length]; + frame[0] = (byte) finAndOpcode; + frame[1] = (byte) payload.length; + System.arraycopy(payload, 0, frame, 2, payload.length); + return frame; + } + + /** Reads client frames until a close frame, and returns its status code. */ + private static int readCloseCode(InputStream in) throws IOException { + while (true) { + int first = in.read(); + if (first < 0) { + throw new IOException("Connection closed before a close frame"); + } + int opcode = first & 0x0F; + byte[] payload = readPayload(in); + if (opcode == 0x8) { + return ((payload[0] & 0xFF) << 8) | (payload[1] & 0xFF); + } + } + } + + private static void readFrame(InputStream in) throws IOException { + if (in.read() < 0) { + throw new IOException("Connection closed"); + } + readPayload(in); + } + + /** Reads the rest of a masked client frame with a payload under 126 bytes, unmasked. */ + private static byte[] readPayload(InputStream in) throws IOException { + int length = in.read() & 0x7F; + byte[] mask = in.readNBytes(4); + byte[] payload = in.readNBytes(length); + for (int i = 0; i < payload.length; i++) { + payload[i] ^= mask[i % 4]; + } + return payload; + } }