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
22 changes: 20 additions & 2 deletions java/org/apache/coyote/http2/Stream.java
Original file line number Diff line number Diff line change
Expand Up @@ -67,6 +67,8 @@ class Stream extends AbstractNonZeroStream implements HeaderEmitter {
private static final int HEADER_STATE_REGULAR = 2;
private static final int HEADER_STATE_TRAILER = 3;

private static final long CONTENT_LENGTH_UNRESOLVED = -2;

private static final MimeHeaders ACK_HEADERS;

private static final Integer HTTP_UPGRADE_STREAM = Integer.valueOf(1);
Expand All @@ -87,6 +89,12 @@ class Stream extends AbstractNonZeroStream implements HeaderEmitter {
}

private volatile long contentLengthReceived = 0;
/*
* Content length declared by the request headers. Resolved on the connection thread once the request headers are
* complete because the container thread may modify the request headers (e.g. RemoteIpValve) while the connection
* thread is still checking received DATA frames against the declared length.
*/
private volatile long contentLengthHeader = CONTENT_LENGTH_UNRESOLVED;

private final Http2UpgradeHandler handler;
private final WindowAllocationManager allocationManager = new WindowAllocationManager(this);
Expand Down Expand Up @@ -674,7 +682,13 @@ final boolean receivedEndOfHeaders() throws StreamException {
if (cookieHeader != null) {
coyoteRequest.getMimeHeaders().addValue("cookie").setString(cookieHeader.toString());
}
return headerState == HEADER_STATE_REGULAR || headerState == HEADER_STATE_PSEUDO;

if (headerState == HEADER_STATE_REGULAR || headerState == HEADER_STATE_PSEUDO) {
// Request headers (not trailers). Must be resolved before the stream is passed to a container thread.
contentLengthHeader = getContentLengthLong();
return true;
}
return false;
}


Expand Down Expand Up @@ -814,7 +828,11 @@ final void receivedEndOfStream() throws Http2Exception {
inputBuffer.notifyEof();
}

final long getContentLengthLong() throws Http2Exception {
final long getContentLengthLong() throws StreamException {
long contentLength = contentLengthHeader;
if (contentLength != CONTENT_LENGTH_UNRESOLVED) {
return contentLength;
}
try {
return coyoteRequest.getContentLengthLong();
} catch (Exception e) {
Expand Down
98 changes: 98 additions & 0 deletions test/org/apache/coyote/http2/TestStream.java
Original file line number Diff line number Diff line change
Expand Up @@ -42,9 +42,13 @@
import org.junit.Test;

import org.apache.catalina.Context;
import org.apache.catalina.connector.Response;
import org.apache.catalina.startup.Tomcat;
import org.apache.catalina.valves.ValveBase;
import org.apache.coyote.ActionCode;
import org.apache.coyote.AsyncContextCallback;
import org.apache.tomcat.util.http.Method;
import org.apache.tomcat.util.http.MimeHeaders;
import org.apache.tomcat.util.net.SocketEvent;
import org.apache.tomcat.util.net.SocketWrapperBase;
import org.easymock.EasyMock;
Expand Down Expand Up @@ -409,6 +413,100 @@ private static void jitter(int maxSpins) {
}


/*
* https://bz.apache.org/bugzilla/show_bug.cgi?id=70366
*
* The declared content length must not depend on the request headers once they have been passed to the container
* thread, as components such as RemoteIpValve modify the headers while request body DATA frames are still being
* received. The test removes the header so the declared length is not found, which disabled the check that the
* request body does not exceed the declared length.
*/
@Test
public void testContentLengthIndependentOfHeaderChanges() throws Exception {

enableHttp2();

Tomcat tomcat = getTomcatInstance();

CountDownLatch headerRemoved = new CountDownLatch(1);
Context ctxt = getProgrammaticRootContext();
ctxt.getPipeline().addValve(new ValveBase() {
@Override
public void invoke(org.apache.catalina.connector.Request request, Response response)
throws IOException, ServletException {
request.getCoyoteRequest().getMimeHeaders().removeHeader("content-length");
headerRemoved.countDown();
getNext().invoke(request, response);
}
});
Tomcat.addServlet(ctxt, "simple", new SimpleServlet());
ctxt.addServletMapping("/simple", "simple");
Tomcat.addServlet(ctxt, "readBody", new ReadBody());
ctxt.addServletMapping("/readBody", "readBody");

tomcat.start();

openClientConnection();
doHttpUpgrade();
sendClientPreface();
validateHttp2InitialResponse();

byte[] headersFrameHeader = new byte[9];
ByteBuffer headersPayload = ByteBuffer.allocate(128);
MimeHeaders headers = new MimeHeaders();
headers.addValue(":method").setString(Method.POST);
headers.addValue(":scheme").setString("http");
headers.addValue(":path").setString("/readBody");
headers.addValue(":authority").setString("localhost:" + getPort());
headers.addValue("content-length").setLong(128);
hpackEncoder.encode(headers, headersPayload);
headersPayload.flip();
ByteUtil.setThreeBytes(headersFrameHeader, 0, headersPayload.limit());
headersFrameHeader[3] = FrameType.HEADERS.getIdByte();
// Flags. end of headers (0x04)
headersFrameHeader[4] = 0x04;
ByteUtil.set31Bits(headersFrameHeader, 5, 3);
writeFrame(headersFrameHeader, headersPayload);

Assert.assertTrue(headerRemoved.await(10, TimeUnit.SECONDS));

// More data than the declared content length
byte[] dataFrameHeader = new byte[9];
ByteBuffer dataPayload = ByteBuffer.allocate(256);
while (dataPayload.hasRemaining()) {
dataPayload.put((byte) 'x');
}
dataPayload.flip();
ByteUtil.setThreeBytes(dataFrameHeader, 0, dataPayload.limit());
// Flags. end of stream (0x01)
dataFrameHeader[4] = 0x01;
ByteUtil.set31Bits(dataFrameHeader, 5, 3);
writeFrame(dataFrameHeader, dataPayload);

// Expect a reset due to a protocol error. Window updates and other frames may be seen first.
do {
parser.readFrame();
} while (!output.getTrace().contains("3-RST-") && !output.getTrace().contains("3-EndOfStream"));
String trace = output.getTrace();
Assert.assertTrue(trace, trace.contains("3-RST-[1]"));
}


private static final class ReadBody extends HttpServlet {

private static final long serialVersionUID = 1L;

@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
byte[] body = request.getInputStream().readAllBytes();
response.setContentType("text/plain");
response.setCharacterEncoding("UTF-8");
response.getWriter().write(Integer.toString(body.length));
}
}


private static void awaitBarrier(CyclicBarrier barrier) {
try {
barrier.await(15, TimeUnit.SECONDS);
Expand Down
8 changes: 8 additions & 0 deletions webapps/docs/changelog.xml
Original file line number Diff line number Diff line change
Expand Up @@ -374,6 +374,14 @@
that is in asynchronous mode are released if the connection thread
raises a stream error for that stream. (markt)
</fix>
<fix>
<bug>70366</bug>: When using HTTP/2, determine the content length of a
request once the request headers have been received rather than reading
the request headers while the container thread may be modifying them.
This could cause valid requests to be reset if the headers were modified
by a component such as the <code>RemoteIpValve</code>. Pull request
<pr>1266</pr> provided by Arturo Bernal.
</fix>
</changelog>
</subsection>
<subsection name="Jasper">
Expand Down
Loading