Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
38 changes: 37 additions & 1 deletion java/org/apache/coyote/http2/Http2UpgradeHandler.java
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand Down Expand Up @@ -172,6 +173,8 @@ class Http2UpgradeHandler extends AbstractStream implements InternalHttpUpgradeH
private HpackEncoder hpackEncoder;

private final ConcurrentNavigableMap<Integer,AbstractNonZeroStream> streams = new ConcurrentSkipListMap<>();
// Priorities received in PRIORITY_UPDATE frames for streams that are still idle (RFC 9218, section 7)
private final ConcurrentNavigableMap<Integer,Priority> idleStreamPriorities = new ConcurrentSkipListMap<>();

/**
* Count of currently active remote-initiated streams.
Expand Down Expand Up @@ -1943,13 +1946,23 @@ 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<Integer,Priority> 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();

if (connectionState.get().isNewStreamAllowed()) {
if (streamId > maxProcessedStreamId) {
stream = createRemoteStream(streamId);
stream.setIdleStreamPriority(idleStreamPriority);
activeRemoteStreamCount.incrementAndGet();
maxProcessedStreamId = streamId;
} else {
Expand Down Expand Up @@ -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
}
}

Expand Down
2 changes: 2 additions & 0 deletions java/org/apache/coyote/http2/LocalStrings.properties
Original file line number Diff line number Diff line change
Expand Up @@ -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.
Expand Down
17 changes: 17 additions & 0 deletions java/org/apache/coyote/http2/Stream.java
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand Down Expand Up @@ -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) {
Expand Down Expand Up @@ -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
Expand Down
166 changes: 165 additions & 1 deletion test/org/apache/coyote/http2/TestRfc9218.java
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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<Header> 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<Header> 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();

/*
Expand Down Expand Up @@ -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<Header> 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();
Expand Down
7 changes: 7 additions & 0 deletions webapps/docs/changelog.xml
Original file line number Diff line number Diff line change
Expand Up @@ -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)
</fix>
<fix>
Do not close an HTTP/2 connection when a <code>PRIORITY_UPDATE</code>
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 <pr>1272</pr> provided by Arturo Bernal.
</fix>
</changelog>
</subsection>
<subsection name="Jasper">
Expand Down
Loading