diff --git a/src/main/java/io/github/ghosthack/turismo/http/HttpContext.java b/src/main/java/io/github/ghosthack/turismo/http/HttpContext.java index 58e0a66..422dc62 100644 --- a/src/main/java/io/github/ghosthack/turismo/http/HttpContext.java +++ b/src/main/java/io/github/ghosthack/turismo/http/HttpContext.java @@ -17,6 +17,7 @@ package io.github.ghosthack.turismo.http; import java.io.ByteArrayOutputStream; +import java.io.FilterInputStream; import java.io.FilterOutputStream; import java.io.IOException; import java.io.InputStream; @@ -72,6 +73,22 @@ public class HttpContext implements Context { public static final String DEFAULT_BINARY_CONTENT_TYPE = "application/octet-stream"; + /** + * Unread request bytes discarded so a keep-alive connection can + * carry the next request. The JDK server itself only discards about + * this much ({@code sun.net.httpserver.drainAmount}) and then waits + * until the declared length has arrived, which swallows a pipelined + * request. Anything larger is not waited on. + */ + private static final int MAX_DISCARD_BYTES = 64 * 1024; + + /** + * How long a response close may block while the JDK drains an unread + * body before that read is abandoned. Long enough for the response + * bytes already queued to be written, short of waiting out the body. + */ + private static final long DRAIN_ABORT_MILLIS = 200; + private final HttpExchange exchange; private int statusCode = 200; private final ByteArrayOutputStream buffer = new ByteArrayOutputStream(); @@ -81,6 +98,16 @@ public class HttpContext implements Context { /** Whether writing the streaming body to the client failed. */ private boolean writeFailed; private Map> queryParams; + /** The request body, wrapped so a partial read can be finished here. */ + private RequestBody requestBody; + /** Bytes of the request body the handler (or a discard) has read. */ + private long requestBodyRead; + /** Whether the request body was read through to EOF. */ + private boolean requestBodyEof; + /** The response must not leave this exchange on the keep-alive path. */ + private boolean dropConnection; + /** {@link #closeExchange()} has already run. */ + private boolean exchangeClosed; /** * Creates a context wrapping the given HTTP exchange. @@ -127,7 +154,10 @@ public String header(String name) { @Override public InputStream body() { - return exchange.getRequestBody(); + if (requestBody == null) { + requestBody = new RequestBody(exchange.getRequestBody()); + } + return requestBody; } /** @@ -227,6 +257,13 @@ public OutputStream output() { public OutputStream stream() throws IOException { if (stream == null) { rawOutput = true; + // Headers are sent now, before the handler returns. A body + // that is already too large to discard cannot stay on a + // keep-alive connection; a small one is discarded in finish + // if the handler never reads it. + if (unreadBodyTooLarge()) { + exchange.getResponseHeaders().set("Connection", "close"); + } defaultHeaders(allowsBody()); if (mayHaveBody()) { // The body is chunked, and a message with both framings @@ -235,6 +272,13 @@ public OutputStream stream() throws IOException { exchange.sendResponseHeaders(statusCode, 0); stream = new BodyStream(exchange.getResponseBody()); buffer.writeTo(stream); + } else if (unreadBodyTooLarge()) { + // No response body, so the JDK closes the exchange as + // soon as the headers are sent and would then wait for + // this unread request body + abortBlockingDrain(() -> + exchange.sendResponseHeaders(statusCode, -1)); + stream = OutputStream.nullOutputStream(); } else { exchange.sendResponseHeaders(statusCode, -1); stream = OutputStream.nullOutputStream(); @@ -262,36 +306,45 @@ public boolean isStreaming() { * one (204, 304); a HEAD response still carries the * {@code Content-Length} its GET would have. * + *

A request body that was not read through to EOF is discarded + * when the declared length is small enough to read safely, so the + * connection can be reused. A larger remainder, including a chunked + * body, is not waited on: the response carries + * {@code Connection: close} and the socket is dropped. That covers + * a 413, 405 or 404 and a successful handler that never reads the body. + * * @throws IOException if an I/O error occurs while sending */ public void finish() throws IOException { - if (stream != null) { - try { - // Not `stream`, whose close() only flushes - exchange.getResponseBody().close(); - } finally { - exchange.close(); - } - return; + try { + dropConnection = releaseUnreadBody(); + writeResponse(); + } finally { + closeExchange(); } - byte[] body = buffer.toByteArray(); - // No body for HEAD (including HEAD served by a GET route) or for - // status codes that forbid one - boolean sendBody = body.length > 0 && mayHaveBody(); - defaultHeaders(body.length > 0 && allowsBody()); - if (!sendBody && body.length > 0 && isHead() && allowsBody()) { - // The JDK server takes a HEAD length only from the headers - exchange.getResponseHeaders().set("Content-Length", - Integer.toString(body.length)); + } + + /** + * Closes the exchange. Safe to call more than once. When the request + * body is still unread and too large to discard, the JDK's drain is + * not waited out: it would hold the connection until the declared + * length arrived and a pipelined request would never be read. + */ + void closeExchange() { + if (exchangeClosed) { + exchange.close(); + return; } - exchange.sendResponseHeaders(statusCode, - sendBody ? body.length : -1); - if (sendBody) { - try (OutputStream os = exchange.getResponseBody()) { - os.write(body); + exchangeClosed = true; + try { + if (dropConnection || unreadBodyTooLarge()) { + abortBlockingDrain(exchange::close); + } else { + exchange.close(); } + } catch (IOException ignored) { + // Client may have disconnected } - exchange.close(); } /** @@ -328,6 +381,46 @@ private void defaultHeaders(boolean hasBody) { } } + /** + * The request body handed to handlers. Closing it does not close the + * JDK stream: that drain stops after about {@link #MAX_DISCARD_BYTES} + * and then blocks until {@code Content-Length} is satisfied, so a + * pipelined request is never read. {@link #finish()} discards a small + * remainder or drops the connection instead. + */ + private final class RequestBody extends FilterInputStream { + RequestBody(InputStream in) { + super(in); + } + + @Override + public int read() throws IOException { + int n = in.read(); + note(n); + return n; + } + + @Override + public int read(byte[] b, int off, int len) throws IOException { + int n = in.read(b, off, len); + note(n); + return n; + } + + private void note(int n) { + if (n < 0) { + requestBodyEof = true; + } else if (n > 0) { + requestBodyRead += n; + } + } + + @Override + public void close() { + // See the class comment. The bytes stay available to finish(). + } + } + /** * The streaming response body handed to handlers. Closing it flushes * what was written but leaves the chunked body open, so that only @@ -396,6 +489,181 @@ void flushStream() { } } + /** + * Sends the status and headers, then the buffered or streaming body. + * When {@link #dropConnection} is set, {@code Connection: close} is + * written with the headers and the unread request body is not drained. + */ + private void writeResponse() throws IOException { + if (stream != null) { + // Not `stream`, whose close() only flushes. Closing writes + // the chunk trailer and then drains the request body. + OutputStream raw = exchange.getResponseBody(); + if (dropConnection) { + abortBlockingDrain(raw::close); + } else { + raw.close(); + } + return; + } + byte[] body = buffer.toByteArray(); + // No body for HEAD (including HEAD served by a GET route) or for + // status codes that forbid one + boolean sendBody = body.length > 0 && mayHaveBody(); + defaultHeaders(body.length > 0 && allowsBody()); + if (dropConnection) { + exchange.getResponseHeaders().set("Connection", "close"); + } + if (!sendBody && body.length > 0 && isHead() && allowsBody()) { + // The JDK server takes a HEAD length only from the headers + exchange.getResponseHeaders().set("Content-Length", + Integer.toString(body.length)); + } + if (!sendBody) { + // A length of -1 makes the JDK close the exchange itself, + // which drains the request body, so that close has to be + // the one that is abandoned + if (dropConnection) { + abortBlockingDrain(() -> + exchange.sendResponseHeaders(statusCode, -1)); + } else { + exchange.sendResponseHeaders(statusCode, -1); + } + return; + } + exchange.sendResponseHeaders(statusCode, body.length); + OutputStream os = exchange.getResponseBody(); + os.write(body); + if (dropConnection) { + // The response is already written. Closing drains the + // request body and, once that blocks, has to be abandoned. + // Interrupting before close() aborts the socket immediately + // and a reset can discard the response the client has not + // read yet. + abortBlockingDrain(os::close); + } else { + os.close(); + } + } + + /** + * Discards a small unread remainder, or decides the connection has + * to be closed. Returns {@code true} when the body was not read + * through to EOF and must not be waited on. + */ + private boolean releaseUnreadBody() throws IOException { + if (requestBodyEof) { + return false; + } + Long declared = declaredBodyLength(); + if (declared == null) { + return true; + } + long remaining = declared - requestBodyRead; + if (remaining <= 0) { + return false; + } + if (remaining > MAX_DISCARD_BYTES) { + return true; + } + discard(remaining); + return !requestBodyEof; + } + + /** A declared length still unread, or a chunked body not read to EOF. */ + private boolean unreadBodyTooLarge() { + if (requestBodyEof) { + return false; + } + Long declared = declaredBodyLength(); + if (declared == null) { + return true; + } + return declared - requestBodyRead > MAX_DISCARD_BYTES; + } + + /** + * The declared length, {@code 0} when the request has no body, or + * {@code null} for a chunked body (no length to discard safely). + */ + private Long declaredBodyLength() { + Headers headers = exchange.getRequestHeaders(); + String encoding = headers.getFirst("Transfer-Encoding"); + if (encoding != null && encoding.equalsIgnoreCase("chunked")) { + return null; + } + String length = headers.getFirst("Content-Length"); + if (length == null || length.isBlank()) { + return 0L; + } + try { + long n = Long.parseLong(length.trim()); + return n < 0 ? null : n; + } catch (NumberFormatException e) { + return null; + } + } + + /** + * Reads the rest of a fixed-length body, including the read that + * reports EOF, so the bytes of a pipelined request stay unread. + */ + private void discard(long remaining) throws IOException { + InputStream in = body(); + byte[] buf = new byte[8192]; + while (remaining > 0) { + int n = in.read(buf, 0, (int) Math.min(buf.length, remaining)); + if (n < 0) { + return; + } + if (n == 0) { + throw new IOException("Unable to discard the request body"); + } + remaining -= n; + } + in.read(); + } + + /** + * Runs a close that writes the response and then drains the request + * body. If the drain is still blocked after {@link #DRAIN_ABORT_MILLIS} + * the read is interrupted, which drops the socket instead of waiting + * for the client to finish sending. + */ + private void abortBlockingDrain(IOAction action) throws IOException { + Thread self = Thread.currentThread(); + Thread watchdog = Thread.ofVirtual().start(() -> { + try { + Thread.sleep(DRAIN_ABORT_MILLIS); + } catch (InterruptedException e) { + return; + } + self.interrupt(); + }); + boolean shutdown = false; + try { + action.run(); + } finally { + watchdog.interrupt(); + try { + watchdog.join(); + } catch (InterruptedException e) { + shutdown = true; + } + // Drop the flag the drain abort set. A shutdown interrupt + // that arrived while waiting for the watchdog is kept. + Thread.interrupted(); + if (shutdown) { + Thread.currentThread().interrupt(); + } + } + } + + @FunctionalInterface + private interface IOAction { + void run() throws IOException; + } + private void checkNotCommitted() { if (stream != null) { throw new IllegalStateException( diff --git a/src/main/java/io/github/ghosthack/turismo/http/Server.java b/src/main/java/io/github/ghosthack/turismo/http/Server.java index 5c32a29..1720def 100644 --- a/src/main/java/io/github/ghosthack/turismo/http/Server.java +++ b/src/main/java/io/github/ghosthack/turismo/http/Server.java @@ -223,7 +223,9 @@ private void handle(HttpExchange exchange) { // Client may have disconnected } finally { if (!aborted) { - exchange.close(); + // finish() has usually closed it. This also covers a + // failure before then, without waiting out an unread body. + ctx.closeExchange(); } } } diff --git a/src/test/java/io/github/ghosthack/turismo/http/ServerKeepAliveTest.java b/src/test/java/io/github/ghosthack/turismo/http/ServerKeepAliveTest.java new file mode 100644 index 0000000..8f72951 --- /dev/null +++ b/src/test/java/io/github/ghosthack/turismo/http/ServerKeepAliveTest.java @@ -0,0 +1,507 @@ +package io.github.ghosthack.turismo.http; + +import static org.junit.jupiter.api.Assertions.*; + +import java.io.ByteArrayOutputStream; +import java.io.IOException; +import java.io.InputStream; +import java.io.OutputStream; +import java.io.UncheckedIOException; +import java.net.Socket; +import java.net.SocketException; +import java.net.SocketTimeoutException; +import java.nio.charset.StandardCharsets; +import java.util.ArrayList; +import java.util.List; + +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; + +import io.github.ghosthack.turismo.Turismo; + +/** + * An unread request body must not swallow the next request on a + * keep-alive connection. A small declared length is discarded; a larger + * one closes the socket instead of waiting for the client to finish. + */ +public class ServerKeepAliveTest { + + /** Above the JDK's ~64KB unread-body drain, below a typical socket buffer. */ + private static final int LARGE_BODY = 70 * 1024; + + private Server server; + + @BeforeEach + public void setUp() throws IOException { + server = new Server(Turismo.app(), "127.0.0.1", 0); + server.start(); + } + + @AfterEach + public void tearDown() { + server.stop(); + Turismo.reset(); + } + + @Test + public void testPipelinedGetAfterGet() throws Exception { + Turismo.get("/a", () -> Turismo.print("first")); + Turismo.get("/b", () -> Turismo.print("second")); + List responses = pipeline( + request("GET", "/a", null, null) + + request("GET", "/b", null, null)); + assertEquals(2, responses.size()); + assertEquals(200, responses.get(0).status); + assertEquals("first", responses.get(0).body); + assertFalse(responses.get(0).close); + assertEquals(200, responses.get(1).status); + assertEquals("second", responses.get(1).body); + } + + @Test + public void testSmallUnreadBodyIsDiscardedAndNextRequestAnswered() + throws Exception { + Turismo.post("/f", () -> Turismo.print("posted")); + Turismo.get("/next", () -> Turismo.print("next-ok")); + String body = "name=ada"; + List responses = pipeline( + request("POST", "/f", "text/plain", body) + + request("GET", "/next", null, null)); + assertEquals(2, responses.size()); + assertEquals(200, responses.get(0).status); + assertEquals("posted", responses.get(0).body); + assertFalse(responses.get(0).close); + assertEquals(200, responses.get(1).status); + assertEquals("next-ok", responses.get(1).body); + } + + @Test + public void testSmallFormPostKeepsTheConnection() throws Exception { + Turismo.post("/f", () -> Turismo.print("got " + Turismo.form("a"))); + Turismo.get("/next", () -> Turismo.print("next-ok")); + String body = "a=1"; + List responses = pipeline( + request("POST", "/f", + "application/x-www-form-urlencoded", body) + + request("GET", "/next", null, null)); + assertEquals(2, responses.size()); + assertEquals(200, responses.get(0).status); + assertEquals("got 1", responses.get(0).body); + assertEquals("next-ok", responses.get(1).body); + } + + @Test + public void testMethodNotAllowedDiscardsASmallBody() throws Exception { + Turismo.get("/only", () -> Turismo.print("get-ok")); + Turismo.get("/next", () -> Turismo.print("next-ok")); + String body = "ignored"; + List responses = pipeline( + request("POST", "/only", "text/plain", body) + + request("GET", "/next", null, null)); + assertEquals(2, responses.size()); + assertEquals(405, responses.get(0).status); + assertEquals("Method Not Allowed", responses.get(0).body); + assertFalse(responses.get(0).close); + assertEquals("next-ok", responses.get(1).body); + } + + @Test + public void testNotFoundDiscardsASmallBody() throws Exception { + Turismo.get("/next", () -> Turismo.print("next-ok")); + String body = "ignored"; + List responses = pipeline( + request("POST", "/missing", "text/plain", body) + + request("GET", "/next", null, null)); + assertEquals(2, responses.size()); + assertEquals(404, responses.get(0).status); + assertEquals("Not Found", responses.get(0).body); + assertFalse(responses.get(0).close); + assertEquals("next-ok", responses.get(1).body); + } + + @Test + public void testTooLargeFormClosesWithoutWaitingForTheBody() + throws Exception { + Turismo.app().setMaxFormSize(4); + Turismo.post("/f", () -> Turismo.print("got " + Turismo.form("a"))); + Turismo.get("/next", () -> Turismo.print("next-ok")); + // Declared far above the form limit, and above what is safe to + // discard. The follow-up is written where the body would be; the + // server must answer 413 and drop the socket rather than wait + // for the rest of the declared length. + Exchange exchange = readUntilClosed(requestWithLength("POST", "/f", + "application/x-www-form-urlencoded", 3_000_000, "a=1") + + request("GET", "/next", null, null)); + assertEquals(1, exchange.responses.size(), exchange.raw); + RawResponse tooLarge = exchange.responses.get(0); + assertEquals(413, tooLarge.status); + assertEquals("Content Too Large", tooLarge.body); + assertTrue(tooLarge.close); + assertNotEquals(Exchange.End.TIMEOUT, exchange.end); + assertFalse(exchange.raw.contains("next-ok")); + } + + @Test + public void testTooLargeFormOfDiscardableLengthKeepsTheConnection() + throws Exception { + Turismo.app().setMaxFormSize(4); + Turismo.post("/f", () -> Turismo.print("got " + Turismo.form("a"))); + Turismo.get("/next", () -> Turismo.print("next-ok")); + String body = "a=" + "x".repeat(98); + List responses = pipeline( + request("POST", "/f", + "application/x-www-form-urlencoded", body) + + request("GET", "/next", null, null)); + assertEquals(2, responses.size()); + assertEquals(413, responses.get(0).status); + assertEquals("Content Too Large", responses.get(0).body); + assertFalse(responses.get(0).close); + assertEquals("next-ok", responses.get(1).body); + } + + @Test + public void testMethodNotAllowedClosesALargeUnreadBody() throws Exception { + Turismo.get("/only", () -> Turismo.print("get-ok")); + Turismo.get("/next", () -> Turismo.print("next-ok")); + String body = "x".repeat(LARGE_BODY); + Exchange exchange = readUntilClosed( + request("POST", "/only", "text/plain", body) + + request("GET", "/next", null, null)); + assertEquals(1, exchange.responses.size(), exchange.raw); + assertEquals(405, exchange.responses.get(0).status); + assertEquals("Method Not Allowed", exchange.responses.get(0).body); + assertTrue(exchange.responses.get(0).close); + assertNotEquals(Exchange.End.TIMEOUT, exchange.end); + assertFalse(exchange.raw.contains("next-ok")); + } + + @Test + public void testNotFoundClosesALargeUnreadBody() throws Exception { + Turismo.get("/next", () -> Turismo.print("next-ok")); + String body = "x".repeat(LARGE_BODY); + Exchange exchange = readUntilClosed( + request("POST", "/missing", "text/plain", body) + + request("GET", "/next", null, null)); + assertEquals(1, exchange.responses.size(), exchange.raw); + assertEquals(404, exchange.responses.get(0).status); + assertTrue(exchange.responses.get(0).close); + assertNotEquals(Exchange.End.TIMEOUT, exchange.end); + assertFalse(exchange.raw.contains("next-ok")); + } + + @Test + public void testSuccessfulHandlerClosesWhenItIgnoresALargeBody() + throws Exception { + Turismo.post("/f", () -> Turismo.print("posted")); + Turismo.get("/next", () -> Turismo.print("next-ok")); + String body = "x".repeat(LARGE_BODY); + Exchange exchange = readUntilClosed( + request("POST", "/f", "text/plain", body) + + request("GET", "/next", null, null)); + assertEquals(1, exchange.responses.size(), exchange.raw); + assertEquals(200, exchange.responses.get(0).status); + assertEquals("posted", exchange.responses.get(0).body); + assertTrue(exchange.responses.get(0).close); + assertNotEquals(Exchange.End.TIMEOUT, exchange.end); + assertFalse(exchange.raw.contains("next-ok")); + } + + @Test + public void testFullyReadLargeBodyKeepsTheConnection() throws Exception { + Turismo.post("/f", () -> { + try { + Turismo.body().readAllBytes(); + } catch (IOException e) { + throw new UncheckedIOException(e); + } + Turismo.print("read"); + }); + Turismo.get("/next", () -> Turismo.print("next-ok")); + String body = "x".repeat(LARGE_BODY); + List responses = pipeline( + request("POST", "/f", "text/plain", body) + + request("GET", "/next", null, null)); + assertEquals(2, responses.size()); + assertEquals(200, responses.get(0).status); + assertEquals("read", responses.get(0).body); + assertFalse(responses.get(0).close); + assertEquals("next-ok", responses.get(1).body); + } + + @Test + public void testPartialReadOfASmallBodyStillKeepsTheConnection() + throws Exception { + Turismo.post("/f", () -> { + try { + Turismo.body().readNBytes(2); + } catch (IOException e) { + throw new UncheckedIOException(e); + } + Turismo.print("partial"); + }); + Turismo.get("/next", () -> Turismo.print("next-ok")); + List responses = pipeline( + request("POST", "/f", "text/plain", "hello") + + request("GET", "/next", null, null)); + assertEquals(2, responses.size()); + assertEquals("partial", responses.get(0).body); + assertFalse(responses.get(0).close); + assertEquals("next-ok", responses.get(1).body); + } + + @Test + public void testEmptyResponseClosesALargeUnreadBody() throws Exception { + Turismo.post("/f", () -> Turismo.status(204)); + String body = "x".repeat(LARGE_BODY); + Exchange exchange = readUntilClosed( + request("POST", "/f", "text/plain", body)); + assertEquals(1, exchange.responses.size()); + assertEquals(204, exchange.responses.get(0).status); + assertTrue(exchange.responses.get(0).close); + assertNotEquals(Exchange.End.TIMEOUT, exchange.end, exchange.raw); + } + + @Test + public void testEmptyResponseDoesNotWaitForABodyThatNeverArrives() + throws Exception { + Turismo.post("/f", () -> Turismo.status(204)); + Turismo.get("/next", () -> Turismo.print("next-ok")); + Exchange exchange = readUntilClosed(requestWithLength( + "POST", "/f", "text/plain", 3_000_000, "") + + request("GET", "/next", null, null)); + assertEquals(1, exchange.responses.size()); + assertEquals(204, exchange.responses.get(0).status); + assertTrue(exchange.responses.get(0).close, exchange.raw); + assertNotEquals(Exchange.End.TIMEOUT, exchange.end, exchange.raw); + assertFalse(exchange.raw.contains("next-ok")); + } + + @Test + public void testStreamingHandlerClosesALargeUnreadBody() throws Exception { + Turismo.post("/f", () -> { + try { + Turismo.stream().write("streamed".getBytes(StandardCharsets.UTF_8)); + } catch (IOException e) { + throw new UncheckedIOException(e); + } + }); + String body = "x".repeat(LARGE_BODY); + Exchange exchange = readUntilClosed( + request("POST", "/f", "text/plain", body)); + assertEquals(1, exchange.responses.size()); + assertEquals(200, exchange.responses.get(0).status); + assertEquals("streamed", exchange.responses.get(0).body); + assertTrue(exchange.responses.get(0).close); + assertNotEquals(Exchange.End.TIMEOUT, exchange.end); + } + + // --------------------------------------------------------------- + // Raw pipelined client + // --------------------------------------------------------------- + + /** Reads until two responses have arrived or the socket goes quiet. */ + private List pipeline(String raw) throws Exception { + Exchange exchange = read(raw, false); + assertNotEquals(Exchange.End.TIMEOUT, exchange.end, exchange.raw); + return exchange.responses; + } + + /** Reads until the server closes the socket, or the read times out. */ + private Exchange readUntilClosed(String raw) throws Exception { + return read(raw, true); + } + + /** + * Writes {@code raw} and reads the replies. The body is written on + * another thread so a server that closes early cannot deadlock a + * large upload. {@code untilClosed} waits for EOF or a reset instead + * of stopping at the second response. + */ + private Exchange read(String raw, boolean untilClosed) throws Exception { + try (Socket socket = new Socket("127.0.0.1", server.port())) { + socket.setSoTimeout(2_000); + Thread writer = Thread.ofVirtual().start(() -> { + try { + OutputStream out = socket.getOutputStream(); + out.write(raw.getBytes(StandardCharsets.ISO_8859_1)); + out.flush(); + } catch (IOException ignored) { + // The server dropped the socket on purpose + } + }); + InputStream in = socket.getInputStream(); + ByteArrayOutputStream got = new ByteArrayOutputStream(); + byte[] buf = new byte[8192]; + Exchange.End end = Exchange.End.TIMEOUT; + try { + while (untilClosed || parse(got.toByteArray()).size() < 2) { + int n = in.read(buf); + if (n < 0) { + end = Exchange.End.EOF; + break; + } + got.write(buf, 0, n); + } + if (end != Exchange.End.EOF) { + end = Exchange.End.COMPLETE; + } + } catch (SocketTimeoutException e) { + end = Exchange.End.TIMEOUT; + } catch (SocketException e) { + end = Exchange.End.RESET; + } + writer.join(2_000); + byte[] bytes = got.toByteArray(); + return new Exchange(parse(bytes), end, + new String(bytes, StandardCharsets.ISO_8859_1)); + } + } + + private static String request(String method, String path, + String type, String body) { + int length = body == null ? 0 : body.length(); + return requestWithLength(method, path, type, length, + body == null ? "" : body); + } + + private static String requestWithLength(String method, String path, + String type, int length, String sent) { + StringBuilder raw = new StringBuilder(); + raw.append(method).append(' ').append(path).append(" HTTP/1.1\r\n"); + raw.append("Host: localhost\r\n"); + if (type != null) { + raw.append("Content-Type: ").append(type).append("\r\n"); + } + if (length > 0 || "POST".equals(method)) { + raw.append("Content-Length: ").append(length).append("\r\n"); + } + raw.append("\r\n"); + raw.append(sent); + return raw.toString(); + } + + private static List parse(byte[] raw) { + List responses = new ArrayList<>(); + int offset = 0; + while (offset < raw.length) { + int headerEnd = indexOf(raw, offset, "\r\n\r\n"); + if (headerEnd < 0) { + break; + } + String head = new String(raw, offset, headerEnd - offset, + StandardCharsets.ISO_8859_1); + int lineEnd = head.indexOf("\r\n"); + String statusLine = lineEnd < 0 ? head : head.substring(0, lineEnd); + String[] parts = statusLine.split(" "); + if (parts.length < 2) { + break; + } + int status = Integer.parseInt(parts[1]); + boolean close = header(head, "Connection").stream() + .anyMatch(v -> v.equalsIgnoreCase("close")); + String transfer = header(head, "Transfer-Encoding").stream() + .findFirst().orElse(""); + int bodyStart = headerEnd + 4; + if (transfer.equalsIgnoreCase("chunked")) { + Chunk chunk = readChunks(raw, bodyStart); + if (chunk == null) { + break; + } + responses.add(new RawResponse(status, close, chunk.body)); + offset = chunk.next; + continue; + } + int length = contentLength(head); + if (raw.length < bodyStart + length) { + break; + } + String body = new String(raw, bodyStart, length, + StandardCharsets.UTF_8); + responses.add(new RawResponse(status, close, body)); + offset = bodyStart + length; + } + return responses; + } + + /** The decoded chunked body, or null if the terminator is not here yet. */ + private static Chunk readChunks(byte[] raw, int offset) { + ByteArrayOutputStream body = new ByteArrayOutputStream(); + int i = offset; + while (true) { + int line = indexOf(raw, i, "\r\n"); + if (line < 0) { + return null; + } + String sizeText = new String(raw, i, line - i, + StandardCharsets.ISO_8859_1); + int semi = sizeText.indexOf(';'); + if (semi >= 0) { + sizeText = sizeText.substring(0, semi); + } + int size; + try { + size = Integer.parseInt(sizeText.trim(), 16); + } catch (NumberFormatException e) { + return null; + } + int data = line + 2; + if (size == 0) { + int end = indexOf(raw, data, "\r\n"); + if (end < 0) { + return null; + } + return new Chunk(body.toString(StandardCharsets.UTF_8), + end + 2); + } + if (raw.length < data + size + 2) { + return null; + } + body.write(raw, data, size); + i = data + size + 2; + } + } + + private static int contentLength(String head) { + return header(head, "Content-Length").stream() + .map(Integer::parseInt) + .findFirst() + .orElse(0); + } + + private static List header(String head, String name) { + List values = new ArrayList<>(); + for (String line : head.split("\r\n")) { + int colon = line.indexOf(':'); + if (colon < 0) { + continue; + } + if (line.substring(0, colon).trim().equalsIgnoreCase(name)) { + values.add(line.substring(colon + 1).trim()); + } + } + return values; + } + + private static int indexOf(byte[] raw, int from, String needle) { + byte[] n = needle.getBytes(StandardCharsets.US_ASCII); + outer: + for (int i = from; i <= raw.length - n.length; i++) { + for (int j = 0; j < n.length; j++) { + if (raw[i + j] != n[j]) { + continue outer; + } + } + return i; + } + return -1; + } + + private record RawResponse(int status, boolean close, String body) { } + + private record Chunk(String body, int next) { } + + private record Exchange(List responses, End end, String raw) { + enum End { COMPLETE, EOF, RESET, TIMEOUT } + } +}