This is an automated email from the ASF dual-hosted git repository.

markt-asf pushed a commit to branch main
in repository https://gitbox.apache.org/repos/asf/tomcat.git


The following commit(s) were added to refs/heads/main by this push:
     new a19ec329fc Apply HTTP/2 timeouts while waiting for the connection 
preface
a19ec329fc is described below

commit a19ec329fc453d9ff669fe5ea66da5da5dcc4b43
Author: Mark Thomas <[email protected]>
AuthorDate: Mon Nov 23 11:45:43 2026 +0000

    Apply HTTP/2 timeouts while waiting for the connection preface
    
    When the connection preface is read asynchronously, init() returns before
    the preface has been received. The read and write timeouts were removed
    at that point so a client that did not send a complete preface was never
    timed out.
    
    Remove the timeouts only once the preface has been received. For direct
    HTTP/2 connections and connections that used ALPN, upgradeDispatch()
    continues after init() returns and started reading frames, which replaced
    the read timeout. Do not process OPEN_READ events until the preface has
    been received.
    
    Co-Authored-By: Claude Sonnet 5.5 <[email protected]>
---
 .../apache/coyote/http2/Http2UpgradeHandler.java   |  38 +++++-
 .../coyote/http2/TestHttp2ConnectionTimeouts.java  | 152 +++++++++++++++++++++
 webapps/docs/changelog.xml                         |   5 +
 3 files changed, 189 insertions(+), 6 deletions(-)

diff --git a/java/org/apache/coyote/http2/Http2UpgradeHandler.java 
b/java/org/apache/coyote/http2/Http2UpgradeHandler.java
index 3d8ba101b4..0c044c4baf 100644
--- a/java/org/apache/coyote/http2/Http2UpgradeHandler.java
+++ b/java/org/apache/coyote/http2/Http2UpgradeHandler.java
@@ -153,6 +153,9 @@ class Http2UpgradeHandler extends AbstractStream implements 
InternalHttpUpgradeH
     // Simple state machine (sequence of states)
     private final AtomicReference<ConnectionState> connectionState = new 
AtomicReference<>(ConnectionState.NEW);
     private volatile long pausedNanoTime = Long.MAX_VALUE;
+    // Set once the client's connection preface has been received. When the 
preface is read asynchronously, a call to
+    // upgradeDispatch() may be made before this is the case.
+    private volatile boolean prefaceReceived = false;
 
     /**
      * Remote settings are settings defined by the client and sent to Tomcat 
that Tomcat must use when communicating
@@ -318,8 +321,11 @@ class Http2UpgradeHandler extends AbstractStream 
implements InternalHttpUpgradeH
         // Send the initial settings frame
         writeSettings();
 
-        // Make sure the client has sent a valid connection preface before we
-        // send the response to the original request over HTTP/2.
+        /*
+         * Make sure the client has sent a valid connection preface before we 
send the response to the original request
+         * over HTTP/2. Note that in the async case, the call below will 
return immediately and there will be a call
+         * back once the preface has been fully read.
+         */
         try {
             parser.readConnectionPreface(webConnection, stream);
         } catch (Http2Exception e) {
@@ -333,10 +339,6 @@ class Http2UpgradeHandler extends AbstractStream 
implements InternalHttpUpgradeH
             log.trace(sm.getString("upgradeHandler.prefaceReceived", 
connectionId));
         }
 
-        // Allow streams and connection to determine timeouts
-        socketWrapper.setReadTimeout(-1);
-        socketWrapper.setWriteTimeout(-1);
-
         processConnection(webConnection, stream);
     }
 
@@ -347,6 +349,17 @@ class Http2UpgradeHandler extends AbstractStream 
implements InternalHttpUpgradeH
      * @param stream        the initial stream
      */
     protected void processConnection(WebConnection webConnection, Stream 
stream) {
+        /*
+         * The connection preface has been received. Allow streams and 
connection to determine timeouts.
+         *
+         * This must not be done before the preface has been received. If the 
preface is read asynchronously,
+         * init() returns before the preface has been received and the read 
and write timeouts must remain in place
+         * until it has.
+         */
+        socketWrapper.setReadTimeout(-1);
+        socketWrapper.setWriteTimeout(-1);
+        prefaceReceived = true;
+
         // Send a ping to get an idea of round trip time as early as possible
         try {
             pingManager.sendPing(true);
@@ -437,6 +450,19 @@ class Http2UpgradeHandler extends AbstractStream 
implements InternalHttpUpgradeH
         try {
             switch (status) {
                 case OPEN_READ:
+                    if (!prefaceReceived) {
+                        /*
+                         * The connection preface is being read asynchronously 
(a direct HTTP/2 connection or a
+                         * connection that used ALPN) and has not been 
received yet. The read for it is already
+                         * pending and, once it has completed, frame 
processing will be started by a further call to
+                         * this method.
+                         *
+                         * Do not start reading frames now. Starting a read 
here would replace the read timeout that
+                         * applies while waiting for the preface.
+                         */
+                        result = SocketState.ASYNC_IO;
+                        break;
+                    }
                     socketWrapper.getLock().lock();
                     try {
                         if (socketWrapper.canWrite()) {
diff --git a/test/org/apache/coyote/http2/TestHttp2ConnectionTimeouts.java 
b/test/org/apache/coyote/http2/TestHttp2ConnectionTimeouts.java
index c18fa3b1b6..d26b64f0d8 100644
--- a/test/org/apache/coyote/http2/TestHttp2ConnectionTimeouts.java
+++ b/test/org/apache/coyote/http2/TestHttp2ConnectionTimeouts.java
@@ -16,6 +16,15 @@
  */
 package org.apache.coyote.http2;
 
+import java.io.IOException;
+import java.io.InputStream;
+import java.net.SocketTimeoutException;
+import java.nio.charset.StandardCharsets;
+
+import javax.net.ssl.SSLParameters;
+import javax.net.ssl.SSLSocket;
+
+import org.junit.Assert;
 import org.junit.Test;
 
 public class TestHttp2ConnectionTimeouts extends Http2TestBase {
@@ -34,4 +43,147 @@ public class TestHttp2ConnectionTimeouts extends 
Http2TestBase {
         // Wait for timeout - should receive GoAway frame
         handleGoAwayResponse(1, Http2Error.NO_ERROR);
     }
+
+
+    /*
+     * The client has sent the HTTP upgrade request but then sends nothing. 
The timeouts must apply while the server is
+     * waiting for the connection preface (regardless of whether the preface 
is read synchronously or asynchronously).
+     */
+    @Test
+    public void testNoPrefaceTimeout() throws Exception {
+        startAndUpgrade(2000, 25000);
+
+        assertServerClosesConnection();
+    }
+
+
+    @Test
+    public void testPartialPrefaceTimeout() throws Exception {
+        startAndUpgrade(2000, 25000);
+
+        // Start of the connection preface but not all of it
+        os.write(Http2Parser.CLIENT_PREFACE_START, 0, 10);
+        os.flush();
+
+        assertServerClosesConnection();
+    }
+
+
+    /*
+     * The client sends the connection preface string but not the SETTINGS 
frame that must follow it.
+     */
+    @Test
+    public void testPrefaceWithoutSettingsTimeout() throws Exception {
+        startAndUpgrade(2000, 25000);
+
+        os.write(Http2Parser.CLIENT_PREFACE_START);
+        os.flush();
+
+        assertServerClosesConnection();
+    }
+
+
+    /*
+     * A client that takes some time to send the preface, but sends it before 
the timeout, must not be affected.
+     */
+    @Test
+    public void testSlowPrefaceWithinTimeout() throws Exception {
+        startAndUpgrade(5000, 25000);
+
+        Thread.sleep(1000);
+
+        sendClientPreface();
+        validateHttp2InitialResponse();
+    }
+
+
+    /*
+     * The timeouts used while waiting for the connection preface must not 
remain in place once it has been received. An
+     * idle connection must be left to the connection and stream timeouts (the 
keep-alive timeout in this case).
+     */
+    @Test
+    public void testPrefaceTimeoutNotAppliedAfterPreface() throws Exception {
+        startAndUpgrade(2000, 25000);
+
+        sendClientPreface();
+        validateHttp2InitialResponse();
+
+        // Idle for longer than the read timeout
+        Thread.sleep(4000);
+
+        // The connection must still be open
+        sendPing();
+        parser.readFrame();
+        Assert.assertEquals("0-Ping-Ack-[0,0,0,0,0,0,0,0]\n", 
output.getTrace());
+    }
+
+
+    /*
+     * A direct HTTP/2 connection (no HTTP upgrade). The client sends the 
start of the connection preface (which is
+     * required to identify the connection as HTTP/2) but not the SETTINGS 
frame that must follow it.
+     */
+    @Test
+    public void testDirectConnectionNoSettingsTimeout() throws Exception {
+        enableHttp2(200, false, 2000, 2000, 25000, 5000, 5000);
+        configureAndStartWebApplication();
+        openClientConnection(false);
+        // Long enough that, if the server does not close the connection, the 
test fails rather than hangs
+        s.setSoTimeout(20000);
+
+        os.write("PRI * 
HTTP/2.0\r\n\r\nSM\r\n\r\n".getBytes(StandardCharsets.ISO_8859_1));
+        os.flush();
+
+        assertServerClosesConnection();
+    }
+
+
+    /*
+     * A connection that used ALPN to negotiate HTTP/2. The client completes 
the TLS handshake and then sends nothing.
+     */
+    @Test
+    public void testAlpnNoPrefaceTimeout() throws Exception {
+        enableHttp2(200, true, 2000, 2000, 25000, 5000, 5000);
+        configureAndStartWebApplication();
+        openClientConnection(true);
+        s.setSoTimeout(20000);
+
+        SSLSocket sslSocket = (SSLSocket) s;
+        SSLParameters parameters = sslSocket.getSSLParameters();
+        parameters.setApplicationProtocols(new String[] { "h2" });
+        sslSocket.setSSLParameters(parameters);
+        sslSocket.startHandshake();
+        Assert.assertEquals("h2", sslSocket.getApplicationProtocol());
+
+        assertServerClosesConnection();
+    }
+
+
+    private void startAndUpgrade(long readTimeout, long keepAliveTimeout) 
throws Exception {
+        enableHttp2(200, false, readTimeout, readTimeout, keepAliveTimeout, 
5000, 5000);
+        configureAndStartWebApplication();
+        openClientConnection(false);
+        // Long enough that, if the server does not close the connection, the 
test fails rather than hangs
+        s.setSoTimeout(20000);
+        doHttpUpgrade();
+    }
+
+
+    /*
+     * The server has not been sent a valid connection preface so it is 
expected to close the connection once the read
+     * timeout expires. The client is not sending anything so the only way the 
connection can end is for the server to
+     * end it.
+     */
+    private void assertServerClosesConnection() throws IOException {
+        InputStream is = s.getInputStream();
+        byte[] buffer = new byte[1024];
+        try {
+            while (is.read(buffer) != -1) {
+                // Discard whatever the server sends (the SETTINGS frame, 
possibly a GOAWAY frame)
+            }
+        } catch (SocketTimeoutException e) {
+            Assert.fail("The server did not close the connection although the 
client did not send a valid preface");
+        } catch (IOException e) {
+            // Connection reset. That is also the server closing the 
connection.
+        }
+    }
 }
diff --git a/webapps/docs/changelog.xml b/webapps/docs/changelog.xml
index afcb5326be..5bffc73185 100644
--- a/webapps/docs/changelog.xml
+++ b/webapps/docs/changelog.xml
@@ -374,6 +374,11 @@
         that is in asynchronous mode are released if the connection thread
         raises a stream error for that stream. (markt)
       </fix>
+      <fix>
+        When using HTTP/2 with asynchronous IO, apply the configured read and
+        write timeouts while waiting for the client to send the HTTP/2
+        connection preface. (markt)
+      </fix>
     </changelog>
   </subsection>
   <subsection name="Jasper">


---------------------------------------------------------------------
To unsubscribe, e-mail: [email protected]
For additional commands, e-mail: [email protected]

Reply via email to