diff --git a/java/org/apache/coyote/http2/Http2AsyncUpgradeHandler.java b/java/org/apache/coyote/http2/Http2AsyncUpgradeHandler.java index 07572fb64ce8..770d57f0ec90 100644 --- a/java/org/apache/coyote/http2/Http2AsyncUpgradeHandler.java +++ b/java/org/apache/coyote/http2/Http2AsyncUpgradeHandler.java @@ -237,7 +237,7 @@ protected HeaderFrameBuffers getHeaderFrameBuffers(int initialPayloadSize) { @Override - void writeBody(Stream stream, ByteBuffer data, int len, boolean finished) throws IOException { + boolean writeBody(Stream stream, ByteBuffer data, int len, boolean finished) throws IOException { if (log.isTraceEnabled()) { log.trace(sm.getString("upgradeHandler.writeBody", connectionId, stream.getIdAsString(), Integer.toString(len), Boolean.valueOf(finished))); @@ -263,6 +263,7 @@ void writeBody(Stream stream, ByteBuffer data, int len, boolean finished) throws data.limit(orgLimit); handleAsyncException(); } + return writable; } @@ -411,13 +412,7 @@ private void releaseReservation(SendfileData sendfile) { int unused = sendfile.connectionReservation; sendfile.connectionReservation = 0; sendfile.streamReservation = 0; - if (unused > 0) { - try { - incrementWindowSize(unused); - } catch (Http2Exception e) { - closeConnection(e); - } - } + releaseConnectionAllocation(unused); } /** diff --git a/java/org/apache/coyote/http2/Http2UpgradeHandler.java b/java/org/apache/coyote/http2/Http2UpgradeHandler.java index e03c87b9bb0e..bcc541aa8cdb 100644 --- a/java/org/apache/coyote/http2/Http2UpgradeHandler.java +++ b/java/org/apache/coyote/http2/Http2UpgradeHandler.java @@ -1191,7 +1191,22 @@ protected HpackEncoder getHpackEncoder() { } - void writeBody(Stream stream, ByteBuffer data, int len, boolean finished) throws IOException { + /** + * Writes a DATA frame for the given stream. The connection flow control window for the data must already have + * been allocated to the stream. + * + * @param stream The stream the data is for + * @param data The data to write + * @param len The number of bytes of data to write + * @param finished Whether this is the last DATA frame for the stream + * + * @return {@code true} if the frame was written (or an attempt was made to write it) and {@code false} if the + * stream could no longer be written to so the data was not written and the connection flow control + * window allocated to it was not used + * + * @throws IOException If an I/O error occurs while writing the frame + */ + boolean writeBody(Stream stream, ByteBuffer data, int len, boolean finished) throws IOException { if (log.isTraceEnabled()) { log.trace(sm.getString("upgradeHandler.writeBody", connectionId, stream.getIdAsString(), Integer.toString(len), Boolean.valueOf(finished))); @@ -1224,6 +1239,7 @@ void writeBody(Stream stream, ByteBuffer data, int len, boolean finished) throws socketWrapper.getLock().unlock(); } } + return writable; } @@ -2332,6 +2348,26 @@ public void onSwallowedUnknownFrame(int streamId, int frameTypeId, int flags, in } + /** + * Releases connection flow control window that was allocated to a stream that will not use it, for example because + * the stream was reset after the window was allocated, so that the window is available to other streams. The + * client only counts the data the server sends against the window (see + * section 6.9.1 of RFC 9113) so window that is + * allocated but not used must be released, or the server's view of the window will be smaller than the client's. + * + * @param allocation The number of bytes of the connection window to release + */ + void releaseConnectionAllocation(int allocation) { + if (allocation > 0) { + try { + incrementWindowSize(allocation); + } catch (Http2Exception e) { + closeConnection(e); + } + } + } + + void replaceStream(AbstractNonZeroStream original, AbstractNonZeroStream replacement) { AbstractNonZeroStream current = streams.get(original.getIdentifier()); /* diff --git a/java/org/apache/coyote/http2/Stream.java b/java/org/apache/coyote/http2/Stream.java index f2bf048676ba..82f2d4035e7a 100644 --- a/java/org/apache/coyote/http2/Stream.java +++ b/java/org/apache/coyote/http2/Stream.java @@ -1259,8 +1259,10 @@ private boolean flush(boolean writeInProgress, boolean block) throws IOException return true; } // Do the write - handler.writeBody(Stream.this, buffer, connectionReservation, !writeInProgress && closed && - left == connectionReservation && coyoteResponse.getTrailerFields() == null); + if (!handler.writeBody(Stream.this, buffer, connectionReservation, !writeInProgress && closed && + left == connectionReservation && coyoteResponse.getTrailerFields() == null)) { + handler.releaseConnectionAllocation(connectionReservation); + } streamReservation -= connectionReservation; left -= connectionReservation; } diff --git a/test/org/apache/coyote/http2/Http2TestBase.java b/test/org/apache/coyote/http2/Http2TestBase.java index 42a8d4e18ec3..6a8c2ce7b6f8 100644 --- a/test/org/apache/coyote/http2/Http2TestBase.java +++ b/test/org/apache/coyote/http2/Http2TestBase.java @@ -642,7 +642,7 @@ protected void enableHttp2(long maxConcurrentStreams, boolean tls, long readTime Tomcat tomcat = getTomcatInstance(); Connector connector = tomcat.getConnector(); Assert.assertTrue(connector.setProperty("useAsyncIO", Boolean.toString(useAsyncIO))); - http2Protocol = new UpgradableHttp2Protocol(); + http2Protocol = createHttp2Protocol(); // Short timeouts for now. May need to increase these for CI systems. http2Protocol.setReadTimeout(readTimeout); http2Protocol.setWriteTimeout(writeTimeout); @@ -658,7 +658,11 @@ protected void enableHttp2(long maxConcurrentStreams, boolean tls, long readTime } } - private static class UpgradableHttp2Protocol extends Http2Protocol { + protected Http2Protocol createHttp2Protocol() { + return new UpgradableHttp2Protocol(); + } + + protected static class UpgradableHttp2Protocol extends Http2Protocol { @Override public String getHttpUpgradeName(boolean isSSLEnabled) { return "h2c"; diff --git a/test/org/apache/coyote/http2/TestHttp2ConnectionWindowReset.java b/test/org/apache/coyote/http2/TestHttp2ConnectionWindowReset.java new file mode 100644 index 000000000000..50740a40862f --- /dev/null +++ b/test/org/apache/coyote/http2/TestHttp2ConnectionWindowReset.java @@ -0,0 +1,215 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.apache.coyote.http2; + +import java.io.IOException; +import java.io.OutputStream; +import java.nio.ByteBuffer; +import java.util.concurrent.ConcurrentHashMap; +import java.util.concurrent.CountDownLatch; +import java.util.concurrent.TimeUnit; + +import jakarta.servlet.ServletException; +import jakarta.servlet.http.HttpServlet; +import jakarta.servlet.http.HttpServletRequest; +import jakarta.servlet.http.HttpServletResponse; + +import org.junit.Assert; +import org.junit.Test; + +import org.apache.catalina.Context; +import org.apache.catalina.LifecycleException; +import org.apache.catalina.startup.Tomcat; +import org.apache.coyote.Adapter; +import org.apache.coyote.Request; +import org.apache.coyote.http11.upgrade.InternalHttpUpgradeHandler; +import org.apache.tomcat.util.net.SocketWrapperBase; + +/* + * A stream that is reset after it has been allocated connection flow control window, but before it writes the data, + * must return that window to the connection. Otherwise the connection window is permanently smaller than the client + * believes it to be (RFC 9113, section 6.9.1). + * + * The test handlers reset the stream (as if the client's RST_STREAM had been processed) as soon as + * reserveWindowSize() has allocated window to it, i.e. just before the stream writes the data. + */ +public class TestHttp2ConnectionWindowReset extends Http2TestBase { + + private static final int BODY_SIZE = 1024; + + private static volatile Http2UpgradeHandler handler; + private static volatile int resetStreamId; + private static final ConcurrentHashMap bodyWritten = new ConcurrentHashMap<>(); + + + @Test + public void testResetAfterConnectionWindowReserved() throws Exception { + reset(3); + http2Connect(); + + long windowBefore = handler.getWindowSize(); + sendBodyRequest(3, BODY_SIZE); + awaitBodyWritten(3); + + // The reservation was taken directly from the connection window + Assert.assertEquals("Connection window reserved by the reset stream was not returned", windowBefore, + handler.getWindowSize()); + } + + + @Test + public void testResetAfterConnectionWindowAllocatedFromBacklog() throws Exception { + reset(5); + http2Connect(); + + // Stream 3 uses the whole connection window + sendBodyRequest(3, (int) handler.getWindowSize()); + while (!output.getTrace().contains("3-EndOfStream")) { + parser.readFrame(); + } + awaitBodyWritten(3); + Assert.assertEquals(0, handler.getWindowSize()); + + // Stream 5 has to wait in the backlog for an allocation + sendBodyRequest(5, BODY_SIZE); + int count = 0; + while (!isInBacklog(5) && count < 100) { + Thread.sleep(100); + count++; + } + Assert.assertTrue(isInBacklog(5)); + + // The window update is allocated to stream 5, which is then reset before it writes + sendWindowUpdate(0, BODY_SIZE); + awaitBodyWritten(5); + + Assert.assertEquals("Connection window allocated to the reset stream was not returned", BODY_SIZE, + handler.getWindowSize()); + } + + + private static boolean isInBacklog(int streamId) { + Stream stream = handler.getStream(streamId); + return stream != null && stream.getConnectionAllocationRequested() > 0; + } + + + private static void reset(int streamId) { + handler = null; + resetStreamId = streamId; + bodyWritten.clear(); + } + + + private void sendBodyRequest(int streamId, int size) throws IOException { + bodyWritten.put(Integer.toString(streamId), new CountDownLatch(1)); + byte[] frameHeader = new byte[9]; + ByteBuffer headersPayload = ByteBuffer.allocate(128); + buildGetRequest(frameHeader, headersPayload, null, streamId, "/body?size=" + size + "&id=" + streamId); + writeFrame(frameHeader, headersPayload); + } + + + private static void awaitBodyWritten(int streamId) throws InterruptedException { + Assert.assertTrue(bodyWritten.get(Integer.toString(streamId)).await(10, TimeUnit.SECONDS)); + } + + + @Override + protected Http2Protocol createHttp2Protocol() { + return new ResetAfterReservationProtocol(); + } + + + @Override + protected void configureAndStartWebApplication() throws LifecycleException { + Context ctxt = getProgrammaticRootContext(); + Tomcat.addServlet(ctxt, "simple", new SimpleServlet()); + ctxt.addServletMapping("/simple", "simple"); + Tomcat.addServlet(ctxt, "body", new BodyServlet()); + ctxt.addServletMapping("/body", "body"); + getTomcatInstance().start(); + } + + + private static class BodyServlet extends HttpServlet { + + private static final long serialVersionUID = 1L; + + @Override + protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { + try { + resp.setContentType("application/octet-stream"); + OutputStream os = resp.getOutputStream(); + os.write(new byte[Integer.parseInt(req.getParameter("size"))]); + os.flush(); + } finally { + bodyWritten.get(req.getParameter("id")).countDown(); + } + } + } + + + private static class ResetAfterReservationProtocol extends UpgradableHttp2Protocol { + + @Override + public InternalHttpUpgradeHandler getInternalUpgradeHandler(SocketWrapperBase socketWrapper, + Adapter adapter, Request coyoteRequest) { + Http2UpgradeHandler result = socketWrapper.hasAsyncIO() ? + new ResetAfterReservationAsyncHandler(this, adapter, coyoteRequest, socketWrapper) : + new ResetAfterReservationHandler(this, adapter, coyoteRequest, socketWrapper); + handler = result; + return result; + } + } + + + private static int afterReservation(Stream stream, int allocation) { + if (allocation > 0 && stream.getIdAsInt() == resetStreamId) { + stream.receiveReset(Http2Error.CANCEL.getCode()); + } + return allocation; + } + + + private static class ResetAfterReservationHandler extends Http2UpgradeHandler { + + ResetAfterReservationHandler(Http2Protocol protocol, Adapter adapter, Request coyoteRequest, + SocketWrapperBase socketWrapper) { + super(protocol, adapter, coyoteRequest, socketWrapper); + } + + @Override + int reserveWindowSize(Stream stream, int reservation, boolean block) throws IOException { + return afterReservation(stream, super.reserveWindowSize(stream, reservation, block)); + } + } + + + private static class ResetAfterReservationAsyncHandler extends Http2AsyncUpgradeHandler { + + ResetAfterReservationAsyncHandler(Http2Protocol protocol, Adapter adapter, Request coyoteRequest, + SocketWrapperBase socketWrapper) { + super(protocol, adapter, coyoteRequest, socketWrapper); + } + + @Override + int reserveWindowSize(Stream stream, int reservation, boolean block) throws IOException { + return afterReservation(stream, super.reserveWindowSize(stream, reservation, block)); + } + } +} diff --git a/webapps/docs/changelog.xml b/webapps/docs/changelog.xml index 93ecd8cfe214..161a1c03e903 100644 --- a/webapps/docs/changelog.xml +++ b/webapps/docs/changelog.xml @@ -522,6 +522,12 @@ waiting to be processed continues to count towards the limit on the number of concurrent streams until that work has been processed. (markt) + + Return the HTTP/2 connection flow control window reserved for a stream + that is reset before the reserved data is written. Previously that + window was lost, and the connection could stall waiting for a window + update the client had no reason to send. (markt) +