This is an automated email from the ASF dual-hosted git repository. markt-asf pushed a commit to branch 10.1.x in repository https://gitbox.apache.org/repos/asf/tomcat.git
commit 0161485a23a78b4b125072adf5682f740e31713b Author: Vladimir Zhilin <[email protected]> AuthorDate: Mon Nov 30 11:44:42 2026 +0100 Return the HTTP/2 connection window reserved by a stream that is reset before it writes (#1277) * Release connection window reserved by a stream reset before it writes StreamOutputBuffer.flush() reserves HTTP/2 connection flow control window and then calls writeBody(), which sends nothing if the stream can no longer write. If the stream was reset between the two, the reserved window was lost and the connection could stall waiting for a window update the client had no reason to send. writeBody() now reports whether it wrote, and flush() releases the reservation when it did not. The sendfile path uses the same release method. Co-Authored-By: Claude Opus 5.5 <[email protected]> --- .../coyote/http2/Http2AsyncUpgradeHandler.java | 11 +- .../apache/coyote/http2/Http2UpgradeHandler.java | 38 +++- java/org/apache/coyote/http2/Stream.java | 6 +- test/org/apache/coyote/http2/Http2TestBase.java | 8 +- .../http2/TestHttp2ConnectionWindowReset.java | 215 +++++++++++++++++++++ webapps/docs/changelog.xml | 6 + 6 files changed, 271 insertions(+), 13 deletions(-) diff --git a/java/org/apache/coyote/http2/Http2AsyncUpgradeHandler.java b/java/org/apache/coyote/http2/Http2AsyncUpgradeHandler.java index d55154d139..fc9763a375 100644 --- a/java/org/apache/coyote/http2/Http2AsyncUpgradeHandler.java +++ b/java/org/apache/coyote/http2/Http2AsyncUpgradeHandler.java @@ -238,7 +238,7 @@ public class Http2AsyncUpgradeHandler extends Http2UpgradeHandler { @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))); @@ -264,6 +264,7 @@ public class Http2AsyncUpgradeHandler extends Http2UpgradeHandler { data.limit(orgLimit); handleAsyncException(); } + return writable; } @@ -412,13 +413,7 @@ public class Http2AsyncUpgradeHandler extends Http2UpgradeHandler { 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 878772dfd2..779156eab3 100644 --- a/java/org/apache/coyote/http2/Http2UpgradeHandler.java +++ b/java/org/apache/coyote/http2/Http2UpgradeHandler.java @@ -1211,7 +1211,22 @@ class Http2UpgradeHandler extends AbstractStream implements InternalHttpUpgradeH } - 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))); @@ -1244,6 +1259,7 @@ class Http2UpgradeHandler extends AbstractStream implements InternalHttpUpgradeH socketWrapper.getLock().unlock(); } } + return writable; } @@ -2415,6 +2431,26 @@ class Http2UpgradeHandler extends AbstractStream implements InternalHttpUpgradeH } + /** + * 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 + * <a href="https://www.rfc-editor.org/rfc/rfc9113#section-6.9.1">section 6.9.1</a> 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 a44b93a68b..e2fbd13bc9 100644 --- a/java/org/apache/coyote/http2/Stream.java +++ b/java/org/apache/coyote/http2/Stream.java @@ -1344,8 +1344,10 @@ class Stream extends AbstractNonZeroStream implements HeaderEmitter { 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 99b655de19..ec12075e15 100644 --- a/test/org/apache/coyote/http2/Http2TestBase.java +++ b/test/org/apache/coyote/http2/Http2TestBase.java @@ -642,7 +642,7 @@ public abstract class Http2TestBase extends TomcatBaseTest { 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 @@ public abstract class Http2TestBase extends TomcatBaseTest { } } - 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 0000000000..50740a4086 --- /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<String,CountDownLatch> 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 8c92ba1789..c303962d11 100644 --- a/webapps/docs/changelog.xml +++ b/webapps/docs/changelog.xml @@ -399,6 +399,12 @@ waiting to be processed continues to count towards the limit on the number of concurrent streams until that work has been processed. (markt) </fix> + <fix> + 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) + </fix> </changelog> </subsection> <subsection name="Jasper"> --------------------------------------------------------------------- To unsubscribe, e-mail: [email protected] For additional commands, e-mail: [email protected]
