diff --git a/java/org/apache/coyote/http2/Http2UpgradeHandler.java b/java/org/apache/coyote/http2/Http2UpgradeHandler.java index 0c044c4baf09..fe7ae9765b91 100644 --- a/java/org/apache/coyote/http2/Http2UpgradeHandler.java +++ b/java/org/apache/coyote/http2/Http2UpgradeHandler.java @@ -24,6 +24,7 @@ import java.util.Comparator; import java.util.HashSet; import java.util.Iterator; +import java.util.NavigableMap; import java.util.Queue; import java.util.Set; import java.util.concurrent.ConcurrentLinkedQueue; @@ -172,6 +173,8 @@ class Http2UpgradeHandler extends AbstractStream implements InternalHttpUpgradeH private HpackEncoder hpackEncoder; private final ConcurrentNavigableMap streams = new ConcurrentSkipListMap<>(); + // Priorities received in PRIORITY_UPDATE frames for streams that are still idle (RFC 9218, section 7) + private final ConcurrentNavigableMap idleStreamPriorities = new ConcurrentSkipListMap<>(); /** * Count of currently active remote-initiated streams. @@ -1943,6 +1946,15 @@ public void headersStart(int streamId, boolean headersEndStream) throws Http2Exc if (stream == null) { // New stream + /* + * The stream is no longer idle and any lower numbered idle streams are implicitly closed. Remove any + * priorities retained for them. + */ + NavigableMap closedIdleStreamPriorities = + idleStreamPriorities.headMap(Integer.valueOf(streamId), true); + Priority idleStreamPriority = closedIdleStreamPriorities.get(Integer.valueOf(streamId)); + closedIdleStreamPriorities.clear(); + // Check the pause state before processing headers since the pause state // determines if a new stream is created or if this stream is ignored. checkPauseState(); @@ -1950,6 +1962,7 @@ public void headersStart(int streamId, boolean headersEndStream) throws Http2Exc if (connectionState.get().isNewStreamAllowed()) { if (streamId > maxProcessedStreamId) { stream = createRemoteStream(streamId); + stream.setIdleStreamPriority(idleStreamPriority); activeRemoteStreamCount.incrementAndGet(); maxProcessedStreamId = streamId; } else { @@ -2201,10 +2214,33 @@ public void incrementWindowSize(int streamId, int increment) throws Http2Excepti @Override public void priorityUpdate(int prioritizedStreamID, Priority p) throws Http2Exception { increaseOverheadCount(FrameType.PRIORITY_UPDATE); - AbstractNonZeroStream abstractNonZeroStream = getAbstractNonZeroStream(prioritizedStreamID, true); + AbstractNonZeroStream abstractNonZeroStream = getAbstractNonZeroStream(prioritizedStreamID); if (abstractNonZeroStream instanceof Stream stream) { stream.setUrgency(p.getUrgency()); stream.setIncremental(p.getIncremental()); + } else if (abstractNonZeroStream == null) { + if (prioritizedStreamID % 2 == 0) { + // Server push is not supported so any push stream is idle + throw new ConnectionException(sm.getString("upgradeHandler.priorityUpdate.idlePush", connectionId, + Integer.toString(prioritizedStreamID)), Http2Error.PROTOCOL_ERROR); + } + if (prioritizedStreamID > maxProcessedStreamId) { + /* + * The stream is idle. Retain the priority until the stream is opened. RFC 9218, section 7.1 limits the + * prioritized idle streams plus the active streams to the maximum number of concurrent streams. + */ + Integer key = Integer.valueOf(prioritizedStreamID); + if (!idleStreamPriorities.containsKey(key) && idleStreamPriorities.size() + + activeRemoteStreamCount.get() >= localSettings.getMaxConcurrentStreams()) { + throw new ConnectionException( + sm.getString("upgradeHandler.priorityUpdate.tooManyStreams", connectionId, + Integer.toString(prioritizedStreamID), + Long.toString(localSettings.getMaxConcurrentStreams())), + Http2Error.PROTOCOL_ERROR); + } + idleStreamPriorities.put(key, p); + } + // Otherwise the stream is closed and the frame is ignored } } diff --git a/java/org/apache/coyote/http2/LocalStrings.properties b/java/org/apache/coyote/http2/LocalStrings.properties index 84f9c6ccee2c..18a1b909f71d 100644 --- a/java/org/apache/coyote/http2/LocalStrings.properties +++ b/java/org/apache/coyote/http2/LocalStrings.properties @@ -157,6 +157,8 @@ upgradeHandler.noNewStreams=Connection [{0}], Stream [{1}], Stream ignored as no upgradeHandler.overheadChange=Connection [{0}], Stream [{1}], Frame type [{2}] resulted in new overhead count of [{3}] upgradeHandler.pause.entry=Connection [{0}] Pausing upgradeHandler.pingFailed=Connection [{0}] Failed to send ping to client +upgradeHandler.priorityUpdate.idlePush=Connection [{0}], PRIORITY_UPDATE frame received for idle push stream [{1}] +upgradeHandler.priorityUpdate.tooManyStreams=Connection [{0}], PRIORITY_UPDATE frame for idle stream [{1}] exceeds the maximum of [{2}] concurrent streams upgradeHandler.prefaceReceived=Connection [{0}], Connection preface received from client upgradeHandler.pruneIncomplete=Connection [{0}], Stream [{1}], Failed to fully prune the connection because there are [{2}] too many active streams upgradeHandler.pruneStart=Connection [{0}] Starting pruning of old streams. Limit is [{1}] and there are currently [{2}] streams. diff --git a/java/org/apache/coyote/http2/Stream.java b/java/org/apache/coyote/http2/Stream.java index 6893955b05bc..0f81d0f1bb14 100644 --- a/java/org/apache/coyote/http2/Stream.java +++ b/java/org/apache/coyote/http2/Stream.java @@ -109,6 +109,8 @@ class Stream extends AbstractNonZeroStream implements HeaderEmitter { private volatile int urgency = Priority.DEFAULT_URGENCY; private volatile boolean incremental = Priority.DEFAULT_INCREMENTAL; + // Priority received in a PRIORITY_UPDATE frame while this stream was idle + private Priority idleStreamPriority; private final Object recycledLock = new Object(); private volatile boolean recycled = false; @@ -641,6 +643,16 @@ public void validateHeaders() throws StreamException { final boolean receivedEndOfHeaders() throws StreamException { + /* + * RFC 9218, section 7. A PRIORITY_UPDATE frame received while the stream was idle is more recent than the + * priority header field so it is applied once all the header fields have been processed. + */ + if (idleStreamPriority != null) { + setUrgency(idleStreamPriority.getUrgency()); + setIncremental(idleStreamPriority.getIncremental()); + idleStreamPriority = null; + } + boolean missingHeader = false; if (coyoteRequest.getMethod() == null) { @@ -1110,6 +1122,11 @@ public void setIncremental(boolean incremental) { } + void setIdleStreamPriority(Priority idleStreamPriority) { + this.idleStreamPriority = idleStreamPriority; + } + + int decrementAndGetActiveRemoteStreamCount() { /* * Protect against mis-counting of active streams. This method should only be called once per stream but since diff --git a/test/org/apache/coyote/http2/TestRfc9218.java b/test/org/apache/coyote/http2/TestRfc9218.java index cd23a5df2e48..2902d79da413 100644 --- a/test/org/apache/coyote/http2/TestRfc9218.java +++ b/test/org/apache/coyote/http2/TestRfc9218.java @@ -17,11 +17,16 @@ package org.apache.coyote.http2; import java.io.IOException; +import java.nio.ByteBuffer; import java.nio.charset.StandardCharsets; +import java.util.ArrayList; +import java.util.List; import org.junit.Assert; import org.junit.Test; +import org.apache.tomcat.util.http.Method; + public class TestRfc9218 extends Http2TestBase { @Test @@ -193,7 +198,154 @@ public void testPriority() throws Exception { * 19 - 8k body left * 21 - 8k body left */ + @Test + public void testPriorityUpdateIdleStream() throws Exception { + http2Connect(); + + // RFC 9218, section 7 allows a PRIORITY_UPDATE frame to be sent before the stream it references is opened + sendPriorityUpdate(3, 0, false); + sendSimpleGetRequest(3); + readSimpleGetResponse(); + + Assert.assertEquals(getSimpleResponseTrace(3), output.getTrace()); + } + + + @Test + public void testPriorityUpdateIdleStreamApplied() throws Exception { + blockStreams(true); + + /* + * Stream 21 was given the highest urgency while idle. That overrides the lowest urgency in its priority header + * field so it is allocated the window ahead of stream 17. + */ + sendWindowUpdate(0, 1024); + parser.readFrame(); + + String trace = output.getTrace(); + Assert.assertEquals("21-Body-1024\n", trace); + output.clearTrace(); + } + + + @Test + public void testPriorityUpdateIdleStreamLimit() throws Exception { + connectWithMaxConcurrentStreams(2); + + sendPriorityUpdate(3, 0, false); + sendPriorityUpdate(5, 0, false); + // Updating a stream that has already been prioritized does not count towards the limit + sendPriorityUpdate(3, 1, false); + + // The connection is still open + sendPing(); + parser.readFrame(); + Assert.assertEquals("0-Ping-Ack-[0,0,0,0,0,0,0,0]\n", output.getTrace()); + output.clearTrace(); + + // Two prioritized idle streams plus zero active streams is the limit. A third must be rejected. + sendPriorityUpdate(7, 0, false); + + handleGoAwayResponse(1); + } + + + @Test + public void testPriorityUpdateIdlePushStream() throws Exception { + http2Connect(); + + // An idle request stream is accepted + sendPriorityUpdate(3, 0, false); + sendPing(); + parser.readFrame(); + Assert.assertEquals("0-Ping-Ack-[0,0,0,0,0,0,0,0]\n", output.getTrace()); + output.clearTrace(); + + // Server push is not supported so a push stream is always idle + sendPriorityUpdate(2, 0, false); + + handleGoAwayResponse(1); + } + + + @Test + public void testPriorityUpdateClosedStream() throws Exception { + /* + * Closed streams are pruned once there are more than five times the maximum concurrent streams. A limit of two + * rather than one allows for the previous stream still being counted as active when the next one starts. + */ + connectWithMaxConcurrentStreams(2); + // Each response uses 8k of the connection window + sendWindowUpdate(0, 1024 * 1024); + + // Use enough streams that the earliest closed streams are pruned + for (int i = 3; i < 43; i += 2) { + sendSimpleGetRequest(i); + readSimpleGetResponse(); + output.clearTrace(); + } + + // A PRIORITY_UPDATE frame for a closed stream is ignored + sendPriorityUpdate(3, 0, false); + sendSimpleGetRequest(43); + readSimpleGetResponse(); + + Assert.assertEquals(getSimpleResponseTrace(43), output.getTrace()); + } + + + @Test + public void testPriorityUpdateIdleStreamMalformedRequest() throws Exception { + connectWithMaxConcurrentStreams(2); + + sendPriorityUpdate(3, 0, false); + + // A connection-specific header field makes the request malformed so the stream is reset + List
headers = new ArrayList<>(5); + headers.add(new Header(":method", Method.GET)); + headers.add(new Header(":scheme", "http")); + headers.add(new Header(":path", "/simple")); + headers.add(new Header(":authority", "localhost:" + getPort())); + headers.add(new Header("connection", "keep-alive")); + sendGetRequest(3, headers); + parser.readFrame(); + Assert.assertEquals("3-RST-[1]\n", output.getTrace()); + output.clearTrace(); + + // Stream 3 is closed so it no longer counts towards the limit + sendPriorityUpdate(5, 0, false); + sendPriorityUpdate(7, 0, false); + sendSimpleGetRequest(5); + readSimpleGetResponse(); + + Assert.assertEquals(getSimpleResponseTrace(5), output.getTrace()); + } + + + private void sendGetRequest(int streamId, List
headers) throws IOException { + byte[] frameHeader = new byte[9]; + ByteBuffer headersPayload = ByteBuffer.allocate(128); + buildGetRequest(frameHeader, headersPayload, null, headers, streamId); + writeFrame(frameHeader, headersPayload); + } + + + private void connectWithMaxConcurrentStreams(long maxConcurrentStreams) throws Exception { + enableHttp2(maxConcurrentStreams); + configureAndStartWebApplication(); + openClientConnection(); + doHttpUpgrade(); + sendClientPreface(); + validateHttp2InitialResponse(maxConcurrentStreams); + } + + private void blockStreams() throws Exception { + blockStreams(false); + } + + + private void blockStreams(boolean prioritizeIdleStream) throws Exception { http2Connect(); /* @@ -229,7 +381,19 @@ private void blockStreams() throws Exception { // Send additional requests. Connection window is empty so only headers will be returned. sendSimpleGetRequest(19); - sendSimpleGetRequest(21); + if (prioritizeIdleStream) { + // Stream 21 is idle at this point + sendPriorityUpdate(21, 0, false); + List
headers = new ArrayList<>(5); + headers.add(new Header(":method", Method.GET)); + headers.add(new Header(":scheme", "http")); + headers.add(new Header(":path", "/simple")); + headers.add(new Header(":authority", "localhost:" + getPort())); + headers.add(new Header("priority", "u=7")); + sendGetRequest(21, headers); + } else { + sendSimpleGetRequest(21); + } // 19-headers, 21-headers parser.readFrame(); diff --git a/webapps/docs/changelog.xml b/webapps/docs/changelog.xml index f0d04f8c55be..0ef77f41f30f 100644 --- a/webapps/docs/changelog.xml +++ b/webapps/docs/changelog.xml @@ -397,6 +397,13 @@ Previously, a body packet that had not been read could be processed as the start of a new AJP request. (markt) + + Do not close an HTTP/2 connection when a PRIORITY_UPDATE + frame references a stream that has not yet been opened or has been + closed. The priority for a stream that has not yet been opened is + retained and applied when the stream is opened, as recommended by RFC + 9218. Pull request 1272 provided by Arturo Bernal. +