diff --git a/java/org/apache/coyote/http2/Stream.java b/java/org/apache/coyote/http2/Stream.java index 6893955b05bc..69e145a15794 100644 --- a/java/org/apache/coyote/http2/Stream.java +++ b/java/org/apache/coyote/http2/Stream.java @@ -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); @@ -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); @@ -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; } @@ -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) { diff --git a/test/org/apache/coyote/http2/TestStream.java b/test/org/apache/coyote/http2/TestStream.java index 2e238d6f220d..d7c3ed313f97 100644 --- a/test/org/apache/coyote/http2/TestStream.java +++ b/test/org/apache/coyote/http2/TestStream.java @@ -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; @@ -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); diff --git a/webapps/docs/changelog.xml b/webapps/docs/changelog.xml index afcb5326be44..3b1d4d8d7452 100644 --- a/webapps/docs/changelog.xml +++ b/webapps/docs/changelog.xml @@ -374,6 +374,14 @@ that is in asynchronous mode are released if the connection thread raises a stream error for that stream. (markt) + + 70366: 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 RemoteIpValve. Pull request + 1266 provided by Arturo Bernal. +