Skip to content

Commit a19ec32

Browse files
markt-asfclaude
andcommitted
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 <noreply@anthropic.com>
1 parent 9e13426 commit a19ec32

3 files changed

Lines changed: 189 additions & 6 deletions

File tree

‎java/org/apache/coyote/http2/Http2UpgradeHandler.java‎

Lines changed: 32 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -153,6 +153,9 @@ class Http2UpgradeHandler extends AbstractStream implements InternalHttpUpgradeH
153153
// Simple state machine (sequence of states)
154154
private final AtomicReference<ConnectionState> connectionState = new AtomicReference<>(ConnectionState.NEW);
155155
private volatile long pausedNanoTime = Long.MAX_VALUE;
156+
// Set once the client's connection preface has been received. When the preface is read asynchronously, a call to
157+
// upgradeDispatch() may be made before this is the case.
158+
private volatile boolean prefaceReceived = false;
156159

157160
/**
158161
* Remote settings are settings defined by the client and sent to Tomcat that Tomcat must use when communicating
@@ -318,8 +321,11 @@ public void init(WebConnection webConnection) {
318321
// Send the initial settings frame
319322
writeSettings();
320323

321-
// Make sure the client has sent a valid connection preface before we
322-
// send the response to the original request over HTTP/2.
324+
/*
325+
* Make sure the client has sent a valid connection preface before we send the response to the original request
326+
* over HTTP/2. Note that in the async case, the call below will return immediately and there will be a call
327+
* back once the preface has been fully read.
328+
*/
323329
try {
324330
parser.readConnectionPreface(webConnection, stream);
325331
} catch (Http2Exception e) {
@@ -333,10 +339,6 @@ public void init(WebConnection webConnection) {
333339
log.trace(sm.getString("upgradeHandler.prefaceReceived", connectionId));
334340
}
335341

336-
// Allow streams and connection to determine timeouts
337-
socketWrapper.setReadTimeout(-1);
338-
socketWrapper.setWriteTimeout(-1);
339-
340342
processConnection(webConnection, stream);
341343
}
342344

@@ -347,6 +349,17 @@ public void init(WebConnection webConnection) {
347349
* @param stream the initial stream
348350
*/
349351
protected void processConnection(WebConnection webConnection, Stream stream) {
352+
/*
353+
* The connection preface has been received. Allow streams and connection to determine timeouts.
354+
*
355+
* This must not be done before the preface has been received. If the preface is read asynchronously,
356+
* init() returns before the preface has been received and the read and write timeouts must remain in place
357+
* until it has.
358+
*/
359+
socketWrapper.setReadTimeout(-1);
360+
socketWrapper.setWriteTimeout(-1);
361+
prefaceReceived = true;
362+
350363
// Send a ping to get an idea of round trip time as early as possible
351364
try {
352365
pingManager.sendPing(true);
@@ -437,6 +450,19 @@ public SocketState upgradeDispatch(SocketEvent status) {
437450
try {
438451
switch (status) {
439452
case OPEN_READ:
453+
if (!prefaceReceived) {
454+
/*
455+
* The connection preface is being read asynchronously (a direct HTTP/2 connection or a
456+
* connection that used ALPN) and has not been received yet. The read for it is already
457+
* pending and, once it has completed, frame processing will be started by a further call to
458+
* this method.
459+
*
460+
* Do not start reading frames now. Starting a read here would replace the read timeout that
461+
* applies while waiting for the preface.
462+
*/
463+
result = SocketState.ASYNC_IO;
464+
break;
465+
}
440466
socketWrapper.getLock().lock();
441467
try {
442468
if (socketWrapper.canWrite()) {

‎test/org/apache/coyote/http2/TestHttp2ConnectionTimeouts.java‎

Lines changed: 152 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -16,6 +16,15 @@
1616
*/
1717
package org.apache.coyote.http2;
1818

19+
import java.io.IOException;
20+
import java.io.InputStream;
21+
import java.net.SocketTimeoutException;
22+
import java.nio.charset.StandardCharsets;
23+
24+
import javax.net.ssl.SSLParameters;
25+
import javax.net.ssl.SSLSocket;
26+
27+
import org.junit.Assert;
1928
import org.junit.Test;
2029

2130
public class TestHttp2ConnectionTimeouts extends Http2TestBase {
@@ -34,4 +43,147 @@ public void testConnectionTimeout() throws Exception {
3443
// Wait for timeout - should receive GoAway frame
3544
handleGoAwayResponse(1, Http2Error.NO_ERROR);
3645
}
46+
47+
48+
/*
49+
* The client has sent the HTTP upgrade request but then sends nothing. The timeouts must apply while the server is
50+
* waiting for the connection preface (regardless of whether the preface is read synchronously or asynchronously).
51+
*/
52+
@Test
53+
public void testNoPrefaceTimeout() throws Exception {
54+
startAndUpgrade(2000, 25000);
55+
56+
assertServerClosesConnection();
57+
}
58+
59+
60+
@Test
61+
public void testPartialPrefaceTimeout() throws Exception {
62+
startAndUpgrade(2000, 25000);
63+
64+
// Start of the connection preface but not all of it
65+
os.write(Http2Parser.CLIENT_PREFACE_START, 0, 10);
66+
os.flush();
67+
68+
assertServerClosesConnection();
69+
}
70+
71+
72+
/*
73+
* The client sends the connection preface string but not the SETTINGS frame that must follow it.
74+
*/
75+
@Test
76+
public void testPrefaceWithoutSettingsTimeout() throws Exception {
77+
startAndUpgrade(2000, 25000);
78+
79+
os.write(Http2Parser.CLIENT_PREFACE_START);
80+
os.flush();
81+
82+
assertServerClosesConnection();
83+
}
84+
85+
86+
/*
87+
* A client that takes some time to send the preface, but sends it before the timeout, must not be affected.
88+
*/
89+
@Test
90+
public void testSlowPrefaceWithinTimeout() throws Exception {
91+
startAndUpgrade(5000, 25000);
92+
93+
Thread.sleep(1000);
94+
95+
sendClientPreface();
96+
validateHttp2InitialResponse();
97+
}
98+
99+
100+
/*
101+
* The timeouts used while waiting for the connection preface must not remain in place once it has been received. An
102+
* idle connection must be left to the connection and stream timeouts (the keep-alive timeout in this case).
103+
*/
104+
@Test
105+
public void testPrefaceTimeoutNotAppliedAfterPreface() throws Exception {
106+
startAndUpgrade(2000, 25000);
107+
108+
sendClientPreface();
109+
validateHttp2InitialResponse();
110+
111+
// Idle for longer than the read timeout
112+
Thread.sleep(4000);
113+
114+
// The connection must still be open
115+
sendPing();
116+
parser.readFrame();
117+
Assert.assertEquals("0-Ping-Ack-[0,0,0,0,0,0,0,0]\n", output.getTrace());
118+
}
119+
120+
121+
/*
122+
* A direct HTTP/2 connection (no HTTP upgrade). The client sends the start of the connection preface (which is
123+
* required to identify the connection as HTTP/2) but not the SETTINGS frame that must follow it.
124+
*/
125+
@Test
126+
public void testDirectConnectionNoSettingsTimeout() throws Exception {
127+
enableHttp2(200, false, 2000, 2000, 25000, 5000, 5000);
128+
configureAndStartWebApplication();
129+
openClientConnection(false);
130+
// Long enough that, if the server does not close the connection, the test fails rather than hangs
131+
s.setSoTimeout(20000);
132+
133+
os.write("PRI * HTTP/2.0\r\n\r\nSM\r\n\r\n".getBytes(StandardCharsets.ISO_8859_1));
134+
os.flush();
135+
136+
assertServerClosesConnection();
137+
}
138+
139+
140+
/*
141+
* A connection that used ALPN to negotiate HTTP/2. The client completes the TLS handshake and then sends nothing.
142+
*/
143+
@Test
144+
public void testAlpnNoPrefaceTimeout() throws Exception {
145+
enableHttp2(200, true, 2000, 2000, 25000, 5000, 5000);
146+
configureAndStartWebApplication();
147+
openClientConnection(true);
148+
s.setSoTimeout(20000);
149+
150+
SSLSocket sslSocket = (SSLSocket) s;
151+
SSLParameters parameters = sslSocket.getSSLParameters();
152+
parameters.setApplicationProtocols(new String[] { "h2" });
153+
sslSocket.setSSLParameters(parameters);
154+
sslSocket.startHandshake();
155+
Assert.assertEquals("h2", sslSocket.getApplicationProtocol());
156+
157+
assertServerClosesConnection();
158+
}
159+
160+
161+
private void startAndUpgrade(long readTimeout, long keepAliveTimeout) throws Exception {
162+
enableHttp2(200, false, readTimeout, readTimeout, keepAliveTimeout, 5000, 5000);
163+
configureAndStartWebApplication();
164+
openClientConnection(false);
165+
// Long enough that, if the server does not close the connection, the test fails rather than hangs
166+
s.setSoTimeout(20000);
167+
doHttpUpgrade();
168+
}
169+
170+
171+
/*
172+
* The server has not been sent a valid connection preface so it is expected to close the connection once the read
173+
* timeout expires. The client is not sending anything so the only way the connection can end is for the server to
174+
* end it.
175+
*/
176+
private void assertServerClosesConnection() throws IOException {
177+
InputStream is = s.getInputStream();
178+
byte[] buffer = new byte[1024];
179+
try {
180+
while (is.read(buffer) != -1) {
181+
// Discard whatever the server sends (the SETTINGS frame, possibly a GOAWAY frame)
182+
}
183+
} catch (SocketTimeoutException e) {
184+
Assert.fail("The server did not close the connection although the client did not send a valid preface");
185+
} catch (IOException e) {
186+
// Connection reset. That is also the server closing the connection.
187+
}
188+
}
37189
}

‎webapps/docs/changelog.xml‎

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -374,6 +374,11 @@
374374
that is in asynchronous mode are released if the connection thread
375375
raises a stream error for that stream. (markt)
376376
</fix>
377+
<fix>
378+
When using HTTP/2 with asynchronous IO, apply the configured read and
379+
write timeouts while waiting for the client to send the HTTP/2
380+
connection preface. (markt)
381+
</fix>
377382
</changelog>
378383
</subsection>
379384
<subsection name="Jasper">

0 commit comments

Comments
 (0)