This is an automated email from the ASF dual-hosted git repository.

markt-asf pushed a commit to branch 11.0.x
in repository https://gitbox.apache.org/repos/asf/tomcat.git


The following commit(s) were added to refs/heads/11.0.x by this push:
     new ae1db890e2 Clean up HTTP/2 streams once an asynchronous sendfile 
response has finished
ae1db890e2 is described below

commit ae1db890e20eed4625ba8aae4b008fc29675b492
Author: Mark Thomas <[email protected]>
AuthorDate: Tue Dec 1 10:57:50 2026 +0000

    Clean up HTTP/2 streams once an asynchronous sendfile response has finished
    
    When an asynchronous sendfile write was pending, StreamProcessor returned
    SocketState.SENDFILE and skipped the clean-up that follows CLOSED. The
    stream, processor, request and response were retained until the stream was
    pruned from the connection.
    
    Perform the clean-up when the sendfile operation finishes, whether the
    response was completely sent, the stream was reset or the write failed.
    Defer the clean-up (closing as well as recycling) while a write is still
    pending so the request and response are not recycled, and possibly re-used
    for another stream, while the write still uses them.
    
    Also:
    - Handle an in-line completion, on the thread that is still processing the
      event, by deferring the clean-up to process()
    - Perform the deferred clean-up when the connection is closed since the
      pending write will then never be notified
    - Treat any exception that escapes the completion handler as a failed write
      so the stream is not left waiting indefinitely
    - Do not return the request and response to the pool after a failed write
    
    Based on a fix by remm.
    
    Co-Authored-By: Claude Sonnet 5.5 <[email protected]>
---
 .../coyote/http2/Http2AsyncUpgradeHandler.java     |  35 +-
 .../apache/coyote/http2/Http2UpgradeHandler.java   |  15 +
 java/org/apache/coyote/http2/SendfileData.java     |   8 +
 java/org/apache/coyote/http2/Stream.java           |  25 +
 java/org/apache/coyote/http2/StreamProcessor.java  | 226 ++++--
 .../org/apache/coyote/http2/TestHttp2Sendfile.java | 788 ++++++++++++++++++++-
 webapps/docs/changelog.xml                         |  13 +
 7 files changed, 1035 insertions(+), 75 deletions(-)

diff --git a/java/org/apache/coyote/http2/Http2AsyncUpgradeHandler.java 
b/java/org/apache/coyote/http2/Http2AsyncUpgradeHandler.java
index 770d57f0ec..47c68afca0 100644
--- a/java/org/apache/coyote/http2/Http2AsyncUpgradeHandler.java
+++ b/java/org/apache/coyote/http2/Http2AsyncUpgradeHandler.java
@@ -34,6 +34,7 @@ import jakarta.servlet.http.WebConnection;
 import org.apache.coyote.Adapter;
 import org.apache.coyote.ProtocolException;
 import org.apache.coyote.Request;
+import org.apache.tomcat.util.ExceptionUtils;
 import org.apache.tomcat.util.http.MimeHeaders;
 import org.apache.tomcat.util.net.SendfileState;
 import org.apache.tomcat.util.net.SocketWrapperBase;
@@ -415,6 +416,16 @@ public class Http2AsyncUpgradeHandler extends 
Http2UpgradeHandler {
         releaseConnectionAllocation(unused);
     }
 
+    /*
+     * The sendfile operation has finished, one way or another. Nothing will 
use the request, the response or the stream
+     * for the operation after this point so the processor can complete any 
clean-up it has had to defer.
+     */
+    private void sendfileFinished(SendfileData sendfile) {
+        sendfile.complete = true;
+        sendfile.processor.sendfileComplete();
+    }
+
+
     /**
      * Completion handler for asynchronous sendfile operations.
      */
@@ -427,6 +438,21 @@ public class Http2AsyncUpgradeHandler extends 
Http2UpgradeHandler {
 
         @Override
         public void completed(Long nBytes, SendfileData sendfile) {
+            try {
+                doCompleted(nBytes, sendfile);
+            } catch (Throwable t) {
+                ExceptionUtils.handleThrowable(t);
+                /*
+                 * An exception that escapes (e.g. a RuntimeException thrown 
by application code when the trailer fields
+                 * are written) would leave the operation neither completed 
nor failed. Nothing else would end it, so
+                 * the response would never be finished and the stream never 
cleaned up. Treat it as a failed write.
+                 */
+                failed(t, sendfile);
+            }
+        }
+
+
+        private void doCompleted(Long nBytes, SendfileData sendfile) {
             CompletionState completionState = null;
             long bytesWritten = nBytes.longValue() - 9;
 
@@ -441,7 +467,9 @@ public class Http2AsyncUpgradeHandler extends 
Http2UpgradeHandler {
                         sendfile.stream.getOutputBuffer().end();
                     } catch (IOException ioe) {
                         failed(ioe, sendfile);
+                        return;
                     }
+                    sendfileFinished(sendfile);
                     return;
                 }
                 sendfile.streamReservation -= (int) bytesWritten;
@@ -463,8 +491,9 @@ public class Http2AsyncUpgradeHandler extends 
Http2UpgradeHandler {
                         failed(ioe, sendfile);
                     } else {
                         // The stream has been cancelled (reset by the client 
or timed out). That is a stream level
-                        // failure that does not affect the connection.
+                        // failure that does not affect the connection. 
Nothing more will be written.
                         releaseReservation(sendfile);
+                        sendfileFinished(sendfile);
                     }
                     return;
                 }
@@ -513,6 +542,7 @@ public class Http2AsyncUpgradeHandler extends 
Http2UpgradeHandler {
                 } else {
                     // The stream has been reset. Nothing more will be written 
so return the unused reservation.
                     releaseReservation(sendfile);
+                    sendfileFinished(sendfile);
                     return;
                 }
                 // Update bytesWritten for start of next loop iteration
@@ -522,6 +552,8 @@ public class Http2AsyncUpgradeHandler extends 
Http2UpgradeHandler {
 
         @Override
         public void failed(Throwable t, SendfileData sendfile) {
+            // Set first. Closing the connection triggers events that clean up 
the stream.
+            sendfile.failed = true;
             applicationErrorCompletion.failed(t, null);
             /*
              * Sendfile writes are asynchronous. The application thread has 
already returned so no other thread will
@@ -530,6 +562,7 @@ public class Http2AsyncUpgradeHandler extends 
Http2UpgradeHandler {
              * slot and file descriptor.
              */
             close();
+            sendfileFinished(sendfile);
         }
     }
 
diff --git a/java/org/apache/coyote/http2/Http2UpgradeHandler.java 
b/java/org/apache/coyote/http2/Http2UpgradeHandler.java
index 79c363256b..fac1f5b2d8 100644
--- a/java/org/apache/coyote/http2/Http2UpgradeHandler.java
+++ b/java/org/apache/coyote/http2/Http2UpgradeHandler.java
@@ -1800,6 +1800,21 @@ class Http2UpgradeHandler extends AbstractStream 
implements InternalHttpUpgradeH
         } catch (Exception e) {
             log.debug(sm.getString("upgradeHandler.socketCloseFailed"), e);
         }
+        /*
+         * Closing the socket cancels its registration with the poller so an 
asynchronous write (e.g. sendfile) that was
+         * pending will never be notified. Tell the processors that deferred 
their clean-up until such a write finished
+         * that it never will.
+         */
+        for (AbstractNonZeroStream stream : streams.values()) {
+            if (stream instanceof Stream) {
+                ((Stream) stream).connectionClosed();
+            }
+        }
+    }
+
+
+    boolean isConnectionClosed() {
+        return connectionState.get() == ConnectionState.CLOSED;
     }
 
 
diff --git a/java/org/apache/coyote/http2/SendfileData.java 
b/java/org/apache/coyote/http2/SendfileData.java
index 63f178d02f..d53e23b4cd 100644
--- a/java/org/apache/coyote/http2/SendfileData.java
+++ b/java/org/apache/coyote/http2/SendfileData.java
@@ -22,6 +22,14 @@ import java.nio.file.Path;
 class SendfileData {
     Path path;
     Stream stream;
+    // The processor that owns this sendfile operation. It performs the stream 
clean-up when the write completes.
+    StreamProcessor processor;
+    // Set once the sendfile operation has finished: the final write completed 
and END_STREAM was sent, or the
+    // operation was abandoned (the stream was reset or a write failed)
+    volatile boolean complete;
+    // Set if a write failed. The write may not have released everything it 
used so the request and response must not be
+    // re-used.
+    volatile boolean failed;
     // Note: a mapped buffer is a special construct with an underlying file
     // that doesn't need to be closed
     MappedByteBuffer mappedBuffer;
diff --git a/java/org/apache/coyote/http2/Stream.java 
b/java/org/apache/coyote/http2/Stream.java
index a1338833b9..cc63624187 100644
--- a/java/org/apache/coyote/http2/Stream.java
+++ b/java/org/apache/coyote/http2/Stream.java
@@ -942,6 +942,31 @@ class Stream extends AbstractNonZeroStream implements 
HeaderEmitter {
     }
 
 
+    /*
+     * Called once the connection has been closed. Pending asynchronous writes 
will not be notified.
+     */
+    final void connectionClosed() {
+        StreamProcessor processor = streamProcessor;
+        if (processor != null) {
+            processor.connectionClosed();
+        }
+    }
+
+
+    final boolean isRecycled() {
+        return recycled;
+    }
+
+
+    /*
+     * Package private only so that tests can obtain the processor for a 
stream without using reflection. Not used by
+     * production code.
+     */
+    final StreamProcessor getStreamProcessor() {
+        return streamProcessor;
+    }
+
+
     final void setStreamProcessor(StreamProcessor streamProcessor) {
         this.streamProcessor = streamProcessor;
     }
diff --git a/java/org/apache/coyote/http2/StreamProcessor.java 
b/java/org/apache/coyote/http2/StreamProcessor.java
index d49039e97f..578c4b44c6 100644
--- a/java/org/apache/coyote/http2/StreamProcessor.java
+++ b/java/org/apache/coyote/http2/StreamProcessor.java
@@ -65,6 +65,16 @@ class StreamProcessor extends AbstractProcessor implements 
NonPipeliningProcesso
     private final Stream stream;
     // True while this processor is registered as a waiting processor. Only 
modified while holding processLock.
     private volatile boolean waiting = false;
+    /*
+     * True while the superclass is processing an event (service(), 
dispatch(), asyncDispatch() etc.), during which the
+     * adapter is using the request and response. Used to detect a sendfile 
write that completes in-line.
+     */
+    private volatile boolean processing = false;
+    /*
+     * True once the clean-up of the stream has been deferred until an 
asynchronous sendfile write finishes. Volatile as
+     * it is read, without holding processLock, when the connection is closed.
+     */
+    private volatile boolean sendfileCleanupDeferred = false;
     private SendfileData sendfileData = null;
     private SendfileState sendfileState = null;
 
@@ -111,6 +121,7 @@ class StreamProcessor extends AbstractProcessor implements 
NonPipeliningProcesso
                 }
                 SocketState state = SocketState.CLOSED;
                 boolean reuseRequestAndResponse = false;
+                boolean cleanupDeferred = false;
                 try {
                     if (event == SocketEvent.ERROR) {
                         /*
@@ -123,7 +134,12 @@ class StreamProcessor extends AbstractProcessor implements 
NonPipeliningProcesso
                             
request.setAttribute(RequestDispatcher.ERROR_EXCEPTION, streamError);
                         }
                     }
-                    state = process(socketWrapper, event);
+                    processing = true;
+                    try {
+                        state = process(socketWrapper, event);
+                    } finally {
+                        processing = false;
+                    }
                     /*
                      * The request and response may only be returned to the 
pool for re-use if the stream ended cleanly.
                      * If the stream ended with either a timeout or an error 
that prevents further I/O (e.g. an
@@ -135,6 +151,27 @@ class StreamProcessor extends AbstractProcessor implements 
NonPipeliningProcesso
                     if (SocketEvent.TIMEOUT != event) {
                         reuseRequestAndResponse = 
getErrorState().isIoAllowed();
                     }
+                    /*
+                     * If an asynchronous sendfile write is still in progress, 
the response has not been written and the
+                     * write still uses the request, the response and the 
stream. They can't be closed (that could send a
+                     * reset before the response has been written) or recycled 
(that could return the request and
+                     * response to the pool for re-use) until the write has 
finished. The clean-up is performed then.
+                     * See sendfileComplete(). Decide once, here, as the write 
may finish while this method is running.
+                     */
+                    if (state == SocketState.CLOSED && isSendfileInProgress()) 
{
+                        /*
+                         * Record the deferral first, then check if the 
connection has been closed. Closing the
+                         * connection sets its state first, then looks for 
deferred clean-ups. At least one of the two
+                         * sees the other. If the connection is closed, the 
write won't be notified so there is nothing
+                         * to wait for.
+                         */
+                        sendfileCleanupDeferred = true;
+                        cleanupDeferred = !handler.isConnectionClosed();
+                    }
+                    if (sendfileData != null && sendfileData.failed) {
+                        // A failed write may not have released everything it 
used
+                        reuseRequestAndResponse = false;
+                    }
 
                     if (state == SocketState.LONG) {
                         waiting = true;
@@ -144,44 +181,8 @@ class StreamProcessor extends AbstractProcessor implements 
NonPipeliningProcesso
                     } else if (state == SocketState.CLOSED) {
                         waiting = false;
                         
handler.getProtocol().getHttp11Protocol().removeWaitingProcessor(this);
-                        if (!stream.isInputFinished() && 
getErrorState().isIoAllowed() && stream.canReset()) {
-                            // The request has been processed but the request 
body has not been
-                            // fully read. This typically occurs when Tomcat 
rejects an upload
-                            // of some form (e.g. PUT or POST). Need to tell 
the client not to
-                            // send any more data on this stream (reset). If 
the stream can no
-                            // longer be reset (e.g. a reset has already been 
sent) there is
-                            // nothing to send. The final else block performs 
the clean-up.
-                            StreamException se =
-                                    new 
StreamException(sm.getString("streamProcessor.cancel", stream.getConnectionId(),
-                                            stream.getIdAsString()), 
Http2Error.NO_ERROR, stream.getIdAsInt());
-                            stream.close(se);
-                        } else if (!getErrorState().isConnectionIoAllowed()) {
-                            ConnectionException ce = new ConnectionException(
-                                    
sm.getString("streamProcessor.error.connection", stream.getConnectionId(),
-                                            stream.getIdAsString()),
-                                    Http2Error.INTERNAL_ERROR);
-                            stream.close(ce);
-                        } else if (!getErrorState().isIoAllowed()) {
-                            StreamException se = stream.getResetException();
-                            if (se == null && stream.canReset()) {
-                                se = new StreamException(
-                                        
sm.getString("streamProcessor.error.stream", stream.getConnectionId(),
-                                                stream.getIdAsString()),
-                                        Http2Error.INTERNAL_ERROR, 
stream.getIdAsInt());
-                            }
-                            /*
-                             * If the stream is already closed (e.g. the 
client has already reset it), se will be null
-                             * and there is no need to send a reset in 
response. Still need to call close to perform the necessary clean-up.
-                             */
-                            stream.close(se);
-                        } else {
-                            if (!stream.isActive()) {
-                                /*
-                                 * Still need to call close to perform the 
necessary clean-up but no need to send reset
-                                 * since the stream is not active so pass null.
-                                 */
-                                stream.close(null);
-                            }
+                        if (!cleanupDeferred) {
+                            closeStream();
                         }
                     }
                 } catch (Exception e) {
@@ -195,7 +196,7 @@ class StreamProcessor extends AbstractProcessor implements 
NonPipeliningProcesso
                     state = SocketState.CLOSED;
                     reuseRequestAndResponse = false;
                 } finally {
-                    if (state == SocketState.CLOSED) {
+                    if (state == SocketState.CLOSED && !cleanupDeferred) {
                         /*
                          * Recycle this processor before the stream is 
recycled as recycling the stream will add the
                          * request and the response to the pool for re-use (if 
re-use is enabled) and the request
@@ -239,6 +240,7 @@ class StreamProcessor extends AbstractProcessor implements 
NonPipeliningProcesso
                             .longValue();
             sendfileData.left = sendfileData.end - sendfileData.pos;
             sendfileData.stream = stream;
+            sendfileData.processor = this;
         }
     }
 
@@ -464,6 +466,145 @@ class StreamProcessor extends AbstractProcessor 
implements NonPipeliningProcesso
     }
 
 
+    /*
+     * Closes the stream once the request has been processed and the response 
written. This sends any reset that is
+     * required and performs the stream clean-up. The caller must hold 
processLock and is responsible for recycling the
+     * processor and the stream afterwards.
+     */
+    private void closeStream() {
+        if (!stream.isInputFinished() && getErrorState().isIoAllowed() && 
stream.canReset()) {
+            // The request has been processed but the request body has not been
+            // fully read. This typically occurs when Tomcat rejects an upload
+            // of some form (e.g. PUT or POST). Need to tell the client not to
+            // send any more data on this stream (reset). If the stream can no
+            // longer be reset (e.g. a reset has already been sent) there is
+            // nothing to send. The final else block performs the clean-up.
+            StreamException se =
+                    new StreamException(sm.getString("streamProcessor.cancel", 
stream.getConnectionId(),
+                            stream.getIdAsString()), Http2Error.NO_ERROR, 
stream.getIdAsInt());
+            stream.close(se);
+        } else if (!getErrorState().isConnectionIoAllowed()) {
+            ConnectionException ce = new ConnectionException(
+                    sm.getString("streamProcessor.error.connection", 
stream.getConnectionId(),
+                            stream.getIdAsString()),
+                    Http2Error.INTERNAL_ERROR);
+            stream.close(ce);
+        } else if (!getErrorState().isIoAllowed()) {
+            StreamException se = stream.getResetException();
+            if (se == null && stream.canReset()) {
+                se = new StreamException(
+                        sm.getString("streamProcessor.error.stream", 
stream.getConnectionId(),
+                                stream.getIdAsString()),
+                        Http2Error.INTERNAL_ERROR, stream.getIdAsInt());
+            }
+            /*
+             * If the stream is already closed (e.g. the client has already 
reset it), se will be null
+             * and there is no need to send a reset in response. Still need to 
call close to perform the necessary clean-up.
+             */
+            stream.close(se);
+        } else {
+            if (!stream.isActive()) {
+                /*
+                 * Still need to call close to perform the necessary clean-up 
but no need to send reset
+                 * since the stream is not active so pass null.
+                 */
+                stream.close(null);
+            }
+        }
+    }
+
+
+    /*
+     * True if an asynchronous sendfile write has been started and has not yet 
finished. While this is true the write
+     * uses the request, the response and the stream.
+     */
+    private boolean isSendfileInProgress() {
+        return sendfileState == SendfileState.PENDING && sendfileData != null 
&& !sendfileData.complete;
+    }
+
+
+    /*
+     * Package private only so that tests can wait for this state rather than 
sleep and hope that it has been reached.
+     * Not used by production code.
+     *
+     * Returns true if an asynchronous sendfile write has been started, has 
not finished and processing of the event
+     * that started it has finished. In that state the write is pending with 
the poller (or on the thread that is
+     * completing it). The lock is only tried, not waited for: if it is held, 
an event is being processed and this
+     * state has not been reached (or is about to change).
+     */
+    boolean isSendfilePending() {
+        if (!processLock.tryLock()) {
+            return false;
+        }
+        try {
+            return isSendfileInProgress();
+        } finally {
+            processLock.unlock();
+        }
+    }
+
+
+    /*
+     * Package private only so that tests can wait for this state rather than 
sleep and hope that it has been reached.
+     * Not used by production code.
+     *
+     * Returns true if the clean-up of the stream has been deferred until a 
pending asynchronous sendfile write
+     * finishes.
+     */
+    boolean isSendfileCleanupDeferred() {
+        return sendfileCleanupDeferred;
+    }
+
+
+    /*
+     * Called once the connection has been closed. Closing the socket cancels 
its registration with the poller so a
+     * sendfile write that is pending is never notified. If the clean-up of 
this stream was deferred until it finished,
+     * trigger it now. This is an event, processed on a container thread, 
since this method may be called while the
+     * connection holds locks that a thread processing a stream may need.
+     */
+    final void connectionClosed() {
+        if (sendfileCleanupDeferred && !stream.isRecycled()) {
+            processSocketEvent(SocketEvent.ERROR, true);
+        }
+    }
+
+
+    /*
+     * Called when an asynchronous sendfile operation has finished, either 
because the last write has completed and
+     * END_STREAM has been written or because the operation was abandoned (the 
stream was reset or a write failed).
+     * Nothing will use the request, response or stream for the operation 
after this call.
+     *
+     * When sendfile is pending service() returns SocketState.SENDFILE, which 
means the clean-up that follows
+     * SocketState.CLOSED is not performed. It is performed here instead. The 
same applies if an event closed the stream
+     * while the operation was in progress since that clean-up is deferred 
until now.
+     */
+    final void sendfileComplete() {
+        processLock.lock();
+        try {
+            if (processing) {
+                // The operation finished in-line. process() will perform the 
clean-up once the event has been
+                // processed.
+                return;
+            }
+            if (stream.isRecycled()) {
+                // Already cleaned up
+                return;
+            }
+            
handler.getProtocol().getHttp11Protocol().removeWaitingProcessor(this);
+            request.updateCounters();
+            if (stream.equals(handler.getStream(stream.getIdAsInt()))) {
+                // Not closed yet. If it has already been closed (and 
replaced) only the recycling is left to do.
+                closeStream();
+            }
+            recycle();
+            // A failed write may not have released everything it used so 
don't re-use the request and response
+            stream.recycle(getErrorState().isIoAllowed() && !(sendfileData != 
null && sendfileData.failed));
+        } finally {
+            processLock.unlock();
+        }
+    }
+
+
     @Override
     public final void recycle() {
         // StreamProcessor instances are not re-used.
@@ -525,6 +666,11 @@ class StreamProcessor extends AbstractProcessor implements 
NonPipeliningProcesso
         }
 
         if (sendfileState == SendfileState.PENDING) {
+            if (sendfileData != null && sendfileData.complete) {
+                // The sendfile completed in-line. The stream needs the normal 
CLOSED clean-up.
+                request.updateCounters();
+                return SocketState.CLOSED;
+            }
             return SocketState.SENDFILE;
         } else if (isAsync() && getErrorState().isIoAllowed()) {
             /*
diff --git a/test/org/apache/coyote/http2/TestHttp2Sendfile.java 
b/test/org/apache/coyote/http2/TestHttp2Sendfile.java
index 28c8953927..cd98243d26 100644
--- a/test/org/apache/coyote/http2/TestHttp2Sendfile.java
+++ b/test/org/apache/coyote/http2/TestHttp2Sendfile.java
@@ -16,6 +16,7 @@
  */
 package org.apache.coyote.http2;
 
+import java.io.CharArrayWriter;
 import java.io.File;
 import java.io.IOException;
 import java.io.InputStream;
@@ -25,8 +26,12 @@ import java.net.SocketTimeoutException;
 import java.nio.ByteBuffer;
 import java.util.ArrayList;
 import java.util.Collection;
+import java.util.Collections;
 import java.util.List;
 
+import jakarta.servlet.AsyncContext;
+import jakarta.servlet.AsyncEvent;
+import jakarta.servlet.AsyncListener;
 import jakarta.servlet.ServletException;
 import jakarta.servlet.http.HttpServlet;
 import jakarta.servlet.http.HttpServletRequest;
@@ -40,7 +45,12 @@ import org.junit.runners.Parameterized.Parameters;
 
 import org.apache.catalina.Context;
 import org.apache.catalina.Globals;
+import org.apache.catalina.Wrapper;
+import org.apache.catalina.servlets.DefaultServlet;
 import org.apache.catalina.startup.Tomcat;
+import org.apache.catalina.valves.AbstractAccessLogValve;
+import org.apache.tomcat.util.http.Method;
+import org.apache.tomcat.util.net.SocketEvent;
 
 /**
  * Tests for failures during HTTP/2 sendfile writes. Sendfile is only used 
with asynchronous IO so the tests only run
@@ -51,7 +61,14 @@ public class TestHttp2Sendfile extends Http2TestBase {
     // Large enough that it can't be buffered by the OS socket buffers 
(loopback)
     private static final long FILE_SIZE = 64L * 1024 * 1024;
 
+    // Only used by the test that relies on the write timeout firing
     private static final long WRITE_TIMEOUT = 2000;
+    // Used by every other test so that the write timeout can't fire while the 
test waits for a condition
+    private static final long LONG_WRITE_TIMEOUT = 30000;
+    // The maximum time to wait for any condition
+    private static final long WAIT_LIMIT = 10000;
+    // The number of consecutive 10ms samples for which there must be no 
progress for a write to be considered stalled
+    private static final int STALL_SAMPLES = 20;
     private static final long KEEP_ALIVE_TIMEOUT = 30000;
 
     /*
@@ -70,6 +87,8 @@ public class TestHttp2Sendfile extends Http2TestBase {
     }
 
     private File file;
+    private String sendfilePath = "/sendfile";
+    private volatile Http2UpgradeHandler handler;
 
 
     @Before
@@ -90,6 +109,467 @@ public class TestHttp2Sendfile extends Http2TestBase {
     }
 
 
+    @Override
+    protected Http2Protocol createHttp2Protocol() {
+        return new UpgradableHttp2Protocol() {
+            @Override
+            public org.apache.coyote.http11.upgrade.InternalHttpUpgradeHandler 
getInternalUpgradeHandler(
+                    org.apache.tomcat.util.net.SocketWrapperBase<?> 
socketWrapper, org.apache.coyote.Adapter adapter,
+                    org.apache.coyote.Request coyoteRequest) {
+                org.apache.coyote.http11.upgrade.InternalHttpUpgradeHandler 
result =
+                        super.getInternalUpgradeHandler(socketWrapper, 
adapter, coyoteRequest);
+                handler = (Http2UpgradeHandler) result;
+                return result;
+            }
+        };
+    }
+
+
+    /*
+     * A response written with sendfile must be cleaned up (the processor, 
request and response recycled) once it has
+     * been written, the same as any other response.
+     */
+    @Test
+    public void testSendfileResponseCleanedUp() throws Exception {
+        doCleanUpTest("/sendfile", 20);
+    }
+
+
+    /*
+     * As above but the response is completed, and sendfile used, as part of 
an asynchronous dispatch rather than in
+     * service().
+     */
+    @Test
+    public void testAsyncSendfileResponseCleanedUp() throws Exception {
+        doCleanUpTest("/asyncsendfile", 20);
+    }
+
+
+    /*
+     * As above but the response is completed, and sendfile used, while 
processing an asynchronous timeout event.
+     */
+    @Test
+    public void testAsyncTimeoutSendfileResponseCleanedUp() throws Exception {
+        doCleanUpTest("/asynctimeoutsendfile", 5);
+    }
+
+
+    /*
+     * Control for the test above. A response that does not use sendfile.
+     */
+    @Test
+    public void testNonSendfileResponseCleanedUp() throws Exception {
+        doCleanUpTest("/simple", 20);
+    }
+
+
+    private void doCleanUpTest(String path, int requests) throws Exception {
+        // Small file. Sendfile is used for any file the servlet chooses to 
send this way.
+        try (RandomAccessFile raf = new RandomAccessFile(file, "rw")) {
+            raf.setLength(100 * 1024);
+        }
+        enableHttp2(200, false, 30000, 30000, KEEP_ALIVE_TIMEOUT, 30000, 
30000);
+
+        Tomcat tomcat = getTomcatInstance();
+        Context ctxt = getProgrammaticRootContext();
+        Tomcat.addServlet(ctxt, "simple", new SimpleServlet());
+        ctxt.addServletMapping("/simple", "simple");
+        Tomcat.addServlet(ctxt, "sendfile", new SendfileServlet(file));
+        ctxt.addServletMapping("/sendfile", "sendfile");
+        Wrapper asyncWrapper =
+                Tomcat.addServlet(ctxt, "asyncsendfile", new 
AsyncSendfileServlet(file));
+        asyncWrapper.setAsyncSupported(true);
+        ctxt.addServletMapping("/asyncsendfile", "asyncsendfile");
+        Wrapper asyncTimeoutWrapper =
+                Tomcat.addServlet(ctxt, "asynctimeoutsendfile", new 
AsyncTimeoutSendfileServlet(file));
+        asyncTimeoutWrapper.setAsyncSupported(true);
+        ctxt.addServletMapping("/asynctimeoutsendfile", 
"asynctimeoutsendfile");
+        /*
+         * The access log is written once the adapter has finished with the 
request and response. If the request was
+         * recycled before then, the URI is empty.
+         */
+        CharArrayWriter accessLog = new CharArrayWriter();
+        AbstractAccessLogValve valve = new AbstractAccessLogValve() {
+            @Override
+            public void log(CharArrayWriter message) {
+                synchronized (accessLog) {
+                    accessLog.append(message.toString());
+                }
+            }
+        };
+        valve.setPattern("%U|");
+        tomcat.getHost().getPipeline().addValve(valve);
+        tomcat.start();
+
+        openClientConnection();
+        doHttpUpgrade();
+        sendClientPreface();
+        validateHttp2InitialResponse();
+        // Plenty of window for every response
+        sendWindowUpdate(0, 10 * 1024 * 1024);
+        output.setTraceBody(false);
+
+        List<Stream> streams = new ArrayList<>();
+        for (int i = 0; i < requests; i++) {
+            int streamId = 3 + 2 * i;
+            byte[] frameHeader = new byte[9];
+            ByteBuffer headersPayload = ByteBuffer.allocate(128);
+            buildGetRequest(frameHeader, headersPayload, null, streamId, path);
+            writeFrame(frameHeader, headersPayload);
+            // Stream window is the default (65535) so the 100KiB file needs 
stream window updates
+            long end = System.currentTimeMillis() + 15000;
+            Stream stream = null;
+            while (!output.getTrace().contains(streamId + "-EndOfStream") && 
System.currentTimeMillis() < end) {
+                parser.readFrame();
+                if (stream == null) {
+                    // Keep a reference. The handler stops returning the 
stream once it has been closed.
+                    stream = handler.getStream(streamId);
+                }
+                if (output.getTrace().contains(streamId + "-Body-")) {
+                    sendWindowUpdate(streamId, 1024 * 1024);
+                }
+            }
+            Assert.assertTrue(output.getTrace(), 
output.getTrace().contains(streamId + "-EndOfStream"));
+            if (stream == null) {
+                // A small response that does not use sendfile can complete, 
and the stream be closed, before it is
+                // possible to obtain the stream. The control is only 
meaningful for the streams that are obtained.
+                Assert.assertFalse("Sendfile stream not found", 
"/sendfile".equals(path));
+            } else {
+                streams.add(stream);
+            }
+        }
+
+        Assert.assertEquals("Streams that were not recycled", 0, 
countNotRecycled(streams));
+
+        // Includes the two entries for the upgrade request and its response, 
which are for /simple
+        String expectedEntry = path + "|";
+        waitFor("Not all of the requests were logged", () -> {
+            synchronized (accessLog) {
+                return accessLog.toString().split("\\|", -1).length - 1 >= 
requests + 2;
+            }
+        });
+        String logged;
+        synchronized (accessLog) {
+            logged = accessLog.toString();
+        }
+        Assert.assertEquals(logged, requests + 2, logged.split("\\|", 
-1).length - 1);
+        Assert.assertFalse(logged, logged.startsWith("|") || 
logged.contains("||"));
+        Assert.assertTrue(logged, logged.contains(expectedEntry));
+    }
+
+
+    /*
+     * A completed sendfile response must perform the same stream clean-up as 
a response written through the normal
+     * path. Small range requests of a large file still use sendfile, so the 
stream must be closed once the response
+     * completes.
+     */
+    @Test
+    public void testCompletedRangeSendfileRecyclesStreams() throws Exception {
+        enableHttp2(200, false, 60000, 60000, 60000, 60000, 60000);
+
+        Tomcat tomcat = getTomcatInstance();
+        Context ctxt = tomcat.addContext("", 
file.getParentFile().getAbsolutePath());
+        Tomcat.addServlet(ctxt, "simple", new SimpleServlet());
+        ctxt.addServletMapping("/simple", "simple");
+        Tomcat.addServlet(ctxt, "default", new DefaultServlet());
+        ctxt.addServletMapping("/*", "default");
+        tomcat.start();
+
+        openClientConnection();
+        s.setSoTimeout(60000);
+        doHttpUpgrade();
+        sendClientPreface();
+        validateHttp2InitialResponse();
+
+        for (int i = 0; i < 100; i++) {
+            int streamId = 3 + i * 2;
+            byte[] frameHeader = new byte[9];
+            ByteBuffer headersPayload = ByteBuffer.allocate(256);
+            List<Header> headers = new ArrayList<>(5);
+            headers.add(new Header(":method", Method.GET));
+            headers.add(new Header(":scheme", "http"));
+            headers.add(new Header(":path", "/" + file.getName()));
+            headers.add(new Header(":authority", "localhost:" + getPort()));
+            headers.add(new Header("range", "bytes=0-49"));
+            buildGetRequest(frameHeader, headersPayload, null, headers, 
streamId);
+            output.clearTrace();
+            output.setTraceBody(false);
+            writeFrame(frameHeader, headersPayload);
+
+            boolean ended = false;
+            int frames = 0;
+            StringBuilder trace = new StringBuilder();
+            while (!ended && frames++ < 100) {
+                output.clearTrace();
+                parser.readFrame();
+                trace.append(output.getTrace());
+                ended = output.getTrace().contains(streamId + "-EndOfStream") 
||
+                        output.getTrace().contains(streamId + "-RST");
+            }
+            Assert.assertTrue(trace.toString(), 
trace.toString().contains(streamId + "-EndOfStream"));
+        }
+
+        Assert.assertNotNull(handler);
+
+        // Allow any asynchronous completion callbacks to finish. The handler 
only returns streams that have not been
+        // closed.
+        waitFor("Completed sendfile responses are not recycled: 100 range 
requests completed (END_STREAM received) " +
+                "but some of their Streams are still held in the connection's 
stream map", () -> {
+                    for (int i = 0; i < 100; i++) {
+                        if (handler.getStream(3 + i * 2) != null) {
+                            return false;
+                        }
+                    }
+                    return true;
+                });
+    }
+
+
+    /*
+     * A sendfile write for a file much larger than the socket buffers can't 
complete in-line. The completion is
+     * processed by a different thread to the one that processed the request 
and that thread must clean up the stream.
+     */
+    @Test
+    public void testSendfileCompletedByOtherThreadCleanedUp() throws Exception 
{
+        doCompletedByOtherThreadTest("/sendfile");
+    }
+
+
+    /*
+     * As above but the response is completed, and sendfile used, while 
processing an asynchronous dispatch.
+     */
+    @Test
+    public void testAsyncSendfileCompletedByOtherThreadCleanedUp() throws 
Exception {
+        doCompletedByOtherThreadTest("/asyncsendfile");
+    }
+
+
+    private void doCompletedByOtherThreadTest(String path) throws Exception {
+        sendfilePath = path;
+        // Allow the entire file to be sent without any further window updates 
from the client
+        startAndSendSendfileRequest(Integer.MAX_VALUE - 65535, 30000);
+        output.setTraceBody(false);
+
+        // Don't read anything until the write is pending. The file is much 
larger than the socket buffers so it can't
+        // be completed in-line. The write is then completed by a different 
thread to the one that processed the
+        // request.
+        Stream stream = awaitStream(3);
+        awaitSendfilePending(stream);
+
+        int frames = 0;
+        boolean ended = false;
+        while (!ended && frames++ < 10000) {
+            output.clearTrace();
+            parser.readFrame();
+            ended = output.getTrace().contains("3-EndOfStream");
+        }
+        Assert.assertTrue("Response not completed", ended);
+        Assert.assertEquals("Stream that was not recycled", 0, 
countNotRecycled(Collections.singletonList(stream)));
+    }
+
+
+    /*
+     * The client resets the stream while an asynchronous sendfile write is 
pending (the client has stopped reading so
+     * the write can't complete). The pending write still uses the request and 
response so the stream must not be
+     * recycled, and the request and response must not be returned to the pool 
for re-use by another stream, until the
+     * write has finished.
+     */
+    @Test
+    public void testSendfileResetDefersRecycleUntilWriteFinishes() throws 
Exception {
+        startAndSendSendfileRequest(Integer.MAX_VALUE - 65535, 30000);
+
+        // Read the headers and a few data frames so we know sendfile is under 
way
+        for (int i = 0; i < 5; i++) {
+            output.clearTrace();
+            parser.readFrame();
+        }
+        Stream stream = awaitStream(3);
+
+        // Stop reading. The sendfile write is pending (the file is much 
larger than the socket buffers) and, once the
+        // buffers are full, stalled. Then reset the stream.
+        StreamProcessor processor = awaitSendfileStalled(stream);
+        sendRst(3, Http2Error.CANCEL.getCode());
+
+        // Once the reset has been processed the clean-up is deferred until 
the write finishes
+        waitFor("The clean-up was not deferred", 
processor::isSendfileCleanupDeferred);
+        Assert.assertFalse("The stream was recycled while a sendfile write was 
pending", stream.isRecycled());
+
+        // Read again so that the pending write finishes
+        readUntil("The write did not finish", stream::isRecycled);
+        Assert.assertNull("The stream was recycled but not closed", 
handler.getStream(3));
+        // Control for testSendfileWriteTimeoutClosesConnection(). A write 
that was cancelled, not failed, is returned to
+        // the pool. The pool is last in, first out.
+        Assert.assertSame("The request was not returned to the pool", 
stream.getCoyoteRequest(),
+                http2Protocol.popRequestAndResponse());
+    }
+
+
+    /*
+     * An event ends the processing of a request while the sendfile write is 
still pending and the stream is still
+     * active (the client has not reset it and the response has not been 
written). The stream must not be closed, and
+     * in particular no reset may be sent, before the response has been 
written. Once it has, the stream must be closed
+     * as well as recycled, so the connection doesn't continue to hold a 
recycled stream.
+     */
+    @Test
+    public void testEventWhileSendfilePendingClosesStreamAfterResponse() 
throws Exception {
+        startAndSendSendfileRequest(Integer.MAX_VALUE - 65535, 30000);
+        output.setTraceBody(false);
+
+        // Read the headers and a few data frames so we know sendfile is under 
way
+        for (int i = 0; i < 5; i++) {
+            output.clearTrace();
+            parser.readFrame();
+        }
+        Stream stream = awaitStream(3);
+
+        // Stop reading. The sendfile write is pending.
+        StreamProcessor processor = awaitSendfilePending(stream);
+        Assert.assertTrue(stream.isActive());
+
+        // Process an event that ends the processing of the request. This is a 
white box test. There is no event that
+        // can be triggered from the client that does this while the stream is 
still active.
+        processor.process(SocketEvent.ERROR);
+
+        // The write is still pending so the stream must still be open, active 
and not recycled
+        Assert.assertTrue(stream.isActive());
+        Assert.assertTrue(processor.isSendfileCleanupDeferred());
+        Assert.assertFalse("The stream was recycled while a sendfile write was 
pending", stream.isRecycled());
+        Assert.assertSame("The stream was closed while a sendfile write was 
pending", stream, handler.getStream(3));
+
+        // Read the whole response. The stream must not be reset before it has 
been written.
+        boolean ended = false;
+        int frames = 0;
+        while (!ended && frames++ < 10000) {
+            output.clearTrace();
+            parser.readFrame();
+            Assert.assertFalse(output.getTrace(), 
output.getTrace().contains("3-RST"));
+            ended = output.getTrace().contains("3-EndOfStream");
+        }
+        Assert.assertTrue("Response not completed", ended);
+
+        // Once the response has been written the stream must be recycled and 
closed (replaced)
+        Assert.assertEquals("Stream that was not recycled", 0, 
countNotRecycled(Collections.singletonList(stream)));
+        Assert.assertNull("The stream was recycled but not closed", 
handler.getStream(3));
+    }
+
+
+    /*
+     * The connection is closed while a sendfile write is pending (here by the 
client closing its end of the
+     * connection). The pending write may never complete, or fail, because the 
socket has been closed so the clean-up
+     * that is deferred until the write finishes must still be performed.
+     */
+    @Test
+    public void testConnectionClosedWhileSendfilePendingCleansUp() throws 
Exception {
+        startAndSendSendfileRequest(Integer.MAX_VALUE - 65535, 30000);
+
+        // Read the headers and a few data frames so we know sendfile is under 
way
+        for (int i = 0; i < 5; i++) {
+            output.clearTrace();
+            parser.readFrame();
+        }
+        Stream stream = awaitStream(3);
+
+        // Stop reading. The sendfile write is pending.
+        awaitSendfilePending(stream);
+
+        // Close the connection from the client side
+        s.close();
+
+        Assert.assertEquals("Stream that was not recycled", 0, 
countNotRecycled(Collections.singletonList(stream)));
+    }
+
+
+    /*
+     * As above but the server closes the connection (e.g. due to a connection 
error or a timeout). This cancels the
+     * socket's registration with the poller so the pending write is never 
notified.
+     */
+    @Test
+    public void testServerClosesConnectionWhileSendfilePendingCleansUp() 
throws Exception {
+        startAndSendSendfileRequest(Integer.MAX_VALUE - 65535, 30000);
+
+        // Read the headers and a few data frames so we know sendfile is under 
way
+        for (int i = 0; i < 5; i++) {
+            output.clearTrace();
+            parser.readFrame();
+        }
+        Stream stream = awaitStream(3);
+
+        // Stop reading. The sendfile write is pending.
+        awaitSendfilePending(stream);
+
+        handler.close();
+
+        Assert.assertEquals("Stream that was not recycled", 0, 
countNotRecycled(Collections.singletonList(stream)));
+    }
+
+
+    /*
+     * The client resets the stream while a sendfile write is pending. The 
clean-up is deferred until the write
+     * finishes. The server then closes the connection before it does. That 
cancels the socket's registration with the
+     * poller so the write is never notified. The connection closing must 
trigger the deferred clean-up even though the
+     * stream has already been reset (so the reset does not trigger another 
notification).
+     */
+    @Test
+    public void 
testServerClosesConnectionAfterResetWhileSendfilePendingCleansUp() throws 
Exception {
+        startAndSendSendfileRequest(Integer.MAX_VALUE - 65535, 30000);
+
+        // Read the headers and a few data frames so we know sendfile is under 
way
+        for (int i = 0; i < 5; i++) {
+            output.clearTrace();
+            parser.readFrame();
+        }
+        Stream stream = awaitStream(3);
+
+        // Stop reading. The sendfile write stalls. Then reset the stream.
+        StreamProcessor processor = awaitSendfileStalled(stream);
+        sendRst(3, Http2Error.CANCEL.getCode());
+
+        // The clean-up is deferred until the write finishes
+        waitFor("The clean-up was not deferred", 
processor::isSendfileCleanupDeferred);
+        Assert.assertFalse("The stream was recycled while a sendfile write was 
pending", stream.isRecycled());
+
+        handler.close();
+
+        Assert.assertEquals("Stream that was not recycled", 0, 
countNotRecycled(Collections.singletonList(stream)));
+    }
+
+
+    /*
+     * Completing the response with sendfile writes the trailer fields. If the 
application's code that provides them
+     * throws an exception, it must not leave the stream, and its request and 
response, waiting for a write that has
+     * finished.
+     */
+    @Test
+    public void testTrailerSupplierFailureAfterSendfileCleansUp() throws 
Exception {
+        sendfilePath = "/trailersendfile";
+        startAndSendSendfileRequest(Integer.MAX_VALUE - 65535, 30000);
+        output.setTraceBody(false);
+        // The client must be told, one way or another, that the response has 
failed rather than waiting
+        s.setSoTimeout(10000);
+
+        Stream stream = null;
+        int frames = 0;
+        boolean ended = false;
+        try {
+            while (!ended && frames++ < 10000) {
+                output.clearTrace();
+                parser.readFrame();
+                if (stream == null) {
+                    stream = handler.getStream(3);
+                }
+                ended = output.getTrace().contains("3-EndOfStream") || 
output.getTrace().contains("3-RST");
+            }
+        } catch (SocketTimeoutException e) {
+            Assert.fail("The client was left waiting for the rest of the 
response");
+        } catch (IOException e) {
+            // The connection has been closed. That is acceptable.
+        }
+        Assert.assertNotNull(stream);
+
+        Assert.assertEquals("Stream that was not recycled", 0, 
countNotRecycled(Collections.singletonList(stream)));
+    }
+
+
     /*
      * The client requests a file that is far larger than the TCP buffers, 
grants enough flow control window for the
      * whole file and then stops reading. The sendfile write times out. The 
server must close the connection rather than
@@ -100,11 +580,21 @@ public class TestHttp2Sendfile extends Http2TestBase {
     public void testSendfileWriteTimeoutClosesConnection() throws Exception {
         startAndSendSendfileRequest();
 
-        // Do not read anything. Wait for the write timeout to trigger. Allow 
plenty of time for the poller to notice.
-        Thread.sleep(WRITE_TIMEOUT * 3);
+        // Keep a reference. The handler stops returning the stream once it 
has been closed.
+        Stream stream = awaitStream(3);
+
+        // Do not read anything. Wait for the write timeout to trigger and the 
connection to be closed.
+        waitFor("The connection was not closed after the write timed out", 
handler::isConnectionClosed);
 
         // Now start reading again. All the buffered data should be received 
followed by the connection being closed.
         assertServerClosesConnection();
+
+        // The failed write must not leave the stream, and its request and 
response, unrecycled
+        Assert.assertEquals("Stream that was not recycled", 0, 
countNotRecycled(Collections.singletonList(stream)));
+        // The write failed. It may not have released everything it used so 
the request and response must not be
+        // available for re-use. The pool is last in, first out so, if it had 
been returned, it would be next out.
+        Assert.assertNotSame("The request was returned to the pool after a 
failed write", stream.getCoyoteRequest(),
+                http2Protocol.popRequestAndResponse());
     }
 
 
@@ -148,31 +638,30 @@ public class TestHttp2Sendfile extends Http2TestBase {
         // Smaller than the file but more than one frame
         int partialReservation = 100000;
         startAndSendSendfileRequest((int) (partialReservation - remaining), 
5000);
+        output.setTraceBody(false);
 
-        // Drain the data for the partial reservation. When the server goes 
quiet it is waiting for more window. Reset
-        // the stream before the connection write timeout fires, else the 
server will close the connection.
-        s.setSoTimeout(500);
-        try {
-            while (true) {
-                parser.readFrame();
-            }
-        } catch (SocketTimeoutException e) {
-            // Server is idle, waiting for window
+        // Read the data for the partial reservation. The server then waits in 
the backlog for more window. Clearing the
+        // trace resets the count of bytes read so don't clear it.
+        output.clearTrace();
+        while (output.getBytesRead() < partialReservation) {
+            parser.readFrame();
         }
-        s.setSoTimeout(60000);
+        Stream stream = awaitStream(3);
+        waitFor("The stream is not waiting in the backlog", () -> 
stream.getConnectionAllocationRequested() > 0);
+
         sendRst(3, Http2Error.CANCEL.getCode());
 
-        // Allow the server to process the reset
-        Thread.sleep(500);
+        // Wait for the server to process the reset
+        readUntil("The reset was not processed", stream::isRecycled);
 
         // Give the connection just enough window for the response to a new 
request.
         sendSimpleGetRequest(5);
         sendWindowUpdate(0, SimpleServlet.CONTENT_LENGTH);
 
-        int frames = 0;
+        long readEnd = System.currentTimeMillis() + WAIT_LIMIT;
         boolean ended = false;
         StringBuilder trace = new StringBuilder();
-        while (!ended && frames++ < 100) {
+        while (!ended && System.currentTimeMillis() < readEnd) {
             output.clearTrace();
             try {
                 parser.readFrame();
@@ -202,29 +691,28 @@ public class TestHttp2Sendfile extends Http2TestBase {
             parser.readFrame();
         }
 
+        Stream stream = awaitStream(3);
+        output.setTraceBody(false);
+
         // Cancel the stream. Do not return any window to the server for the 
data received.
         sendRst(3, Http2Error.CANCEL.getCode());
 
-        // Drain anything already in flight until the server goes quiet. This 
also allows any pending write to complete.
-        s.setSoTimeout(1000);
-        try {
-            while (true) {
-                parser.readFrame();
-            }
-        } catch (SocketTimeoutException e) {
-            // Server is idle
-        }
-        s.setSoTimeout(60000);
+        // Drain anything already in flight until the stream has been cleaned 
up. This also allows any pending write to
+        // complete.
+        readUntil("The stream was not cleaned up", stream::isRecycled);
+
+        // The stream was cancelled while sendfile was pending. It must still 
be cleaned up.
+        Assert.assertEquals("Stream that was not recycled", 0, 
countNotRecycled(Collections.singletonList(stream)));
 
-        // Request a small response on a new stream. It needs all of the 
connection window that is left.
+        // Request a small response on a new stream. It needs all of the 
connection window that is left. Frames for the
+        // cancelled stream that were already in flight may be read first.
         output.clearTrace();
-        output.setTraceBody(false);
         sendSimpleGetRequest(5);
 
-        int frames = 0;
+        long readEnd = System.currentTimeMillis() + WAIT_LIMIT;
         boolean ended = false;
         StringBuilder trace = new StringBuilder();
-        while (!ended && frames++ < 100) {
+        while (!ended && System.currentTimeMillis() < readEnd) {
             output.clearTrace();
             try {
                 parser.readFrame();
@@ -239,14 +727,141 @@ public class TestHttp2Sendfile extends Http2TestBase {
     }
 
 
+    private interface Condition {
+        boolean isMet() throws Exception;
+    }
+
+
+    /*
+     * Waits for the condition to be met. This polls so that the test 
continues as soon as the condition is met and
+     * there are no fixed delays that have to be long enough on the slowest 
system. Fails the test if the condition is not
+     * met within WAIT_LIMIT.
+     */
+    private void waitFor(String failureMessage, Condition condition) throws 
Exception {
+        long end = System.currentTimeMillis() + WAIT_LIMIT;
+        while (!condition.isMet()) {
+            if (System.currentTimeMillis() > end) {
+                Assert.fail(failureMessage);
+            }
+            Thread.sleep(10);
+        }
+    }
+
+
+    /*
+     * Reads frames until the condition is met. For use when the server only 
makes progress, so the condition can only
+     * become true, if the client reads. If there is nothing to read the 
condition is checked again.
+     */
+    private void readUntil(String failureMessage, Condition condition) throws 
Exception {
+        long end = System.currentTimeMillis() + WAIT_LIMIT;
+        s.setSoTimeout(250);
+        try {
+            while (!condition.isMet()) {
+                if (System.currentTimeMillis() > end) {
+                    Assert.fail(failureMessage);
+                }
+                try {
+                    output.clearTrace();
+                    parser.readFrame();
+                } catch (SocketTimeoutException e) {
+                    // Nothing to read at the moment. Check the condition 
again.
+                }
+            }
+        } finally {
+            s.setSoTimeout(60000);
+        }
+    }
+
+
+    /*
+     * The handler stops returning a stream once it has been closed so tests 
need to obtain, and keep a reference to,
+     * the Stream while it is open.
+     */
+    private Stream awaitStream(int streamId) throws Exception {
+        waitFor("Stream " + streamId + " was not created", () -> 
handler.getStream(streamId) != null);
+        return handler.getStream(streamId);
+    }
+
+
+    /*
+     * Waits until an asynchronous sendfile write has been started and the 
thread that started it has returned. The
+     * write is then pending until the client reads enough data (or the stream 
is cancelled, the connection is closed
+     * or the write fails). The test must not read, or the write might 
complete.
+     */
+    private StreamProcessor awaitSendfilePending(Stream stream) throws 
Exception {
+        waitFor("The sendfile write was not pending", () -> {
+            StreamProcessor processor = stream.getStreamProcessor();
+            return processor != null && processor.isSendfilePending();
+        });
+        return stream.getStreamProcessor();
+    }
+
+
+    /*
+     * Waits until an asynchronous sendfile write is pending (see 
awaitSendfilePending()) and has stopped making
+     * progress because the client is not reading and the socket buffers are 
full.
+     *
+     * A write is pending as soon as the thread that started it returns but 
the writes that complete it can carry on,
+     * on other threads, until the buffers are full. If the stream is reset 
during that time the write is cancelled
+     * rather than being left pending so tests that need the write to stay 
pending need to wait for it to stall. There
+     * is nothing on the server that says that the buffers are full so this 
waits for the number of bytes available to
+     * the client to stop changing. This is the one place that a (short) 
period of no change is waited for.
+     */
+    private StreamProcessor awaitSendfileStalled(Stream stream) throws 
Exception {
+        StreamProcessor processor = awaitSendfilePending(stream);
+        InputStream is = s.getInputStream();
+        long end = System.currentTimeMillis() + WAIT_LIMIT;
+        int previous = -1;
+        int stable = 0;
+        while (stable < STALL_SAMPLES) {
+            if (System.currentTimeMillis() > end) {
+                Assert.fail("The sendfile write did not stall");
+            }
+            Thread.sleep(10);
+            int available = is.available();
+            if (available == previous && processor.isSendfilePending()) {
+                stable++;
+            } else {
+                stable = 0;
+            }
+            previous = available;
+        }
+        return processor;
+    }
+
+
+    /*
+     * Returns the number of the given streams that have not been recycled, 
allowing time for the clean-up, which is
+     * performed asynchronously, to complete. The Stream objects are required, 
rather than the stream IDs, since once a
+     * stream has been closed the handler no longer returns it, whether or not 
it was recycled.
+     */
+    private int countNotRecycled(Collection<Stream> streams) throws Exception {
+        long end = System.currentTimeMillis() + WAIT_LIMIT;
+        int notRecycled;
+        while ((notRecycled = (int) streams.stream().filter(stream -> 
!stream.isRecycled()).count()) > 0 &&
+                System.currentTimeMillis() < end) {
+            Thread.sleep(10);
+        }
+        return notRecycled;
+    }
+
+
+    /*
+     * Used by the test that relies on the write timeout firing.
+     */
     private void startAndSendSendfileRequest() throws Exception {
-        startAndSendSendfileRequest(Integer.MAX_VALUE - 65535, 30000);
+        startAndSendSendfileRequest(Integer.MAX_VALUE - 65535, 30000, 
WRITE_TIMEOUT);
     }
 
 
     private void startAndSendSendfileRequest(int connectionWindowIncrement, 
long streamWriteTimeout) throws Exception {
-        // Short write timeout so the test completes quickly. Long stream 
timeouts so they do not interfere.
-        enableHttp2(200, false, 30000, WRITE_TIMEOUT, KEEP_ALIVE_TIMEOUT, 
30000, streamWriteTimeout);
+        startAndSendSendfileRequest(connectionWindowIncrement, 
streamWriteTimeout, LONG_WRITE_TIMEOUT);
+    }
+
+
+    private void startAndSendSendfileRequest(int connectionWindowIncrement, 
long streamWriteTimeout,
+            long writeTimeout) throws Exception {
+        enableHttp2(200, false, 30000, writeTimeout, KEEP_ALIVE_TIMEOUT, 
30000, streamWriteTimeout);
 
         Tomcat tomcat = getTomcatInstance();
         Context ctxt = getProgrammaticRootContext();
@@ -254,6 +869,15 @@ public class TestHttp2Sendfile extends Http2TestBase {
         ctxt.addServletMapping("/simple", "simple");
         Tomcat.addServlet(ctxt, "sendfile", new SendfileServlet(file));
         ctxt.addServletMapping("/sendfile", "sendfile");
+        Wrapper asyncSendfile = Tomcat.addServlet(ctxt, "asyncsendfile", new 
AsyncSendfileServlet(file));
+        asyncSendfile.setAsyncSupported(true);
+        ctxt.addServletMapping("/asyncsendfile", "asyncsendfile");
+        Wrapper asyncTimeoutSendfile =
+                Tomcat.addServlet(ctxt, "asynctimeoutsendfile", new 
AsyncTimeoutSendfileServlet(file));
+        asyncTimeoutSendfile.setAsyncSupported(true);
+        ctxt.addServletMapping("/asynctimeoutsendfile", 
"asynctimeoutsendfile");
+        Tomcat.addServlet(ctxt, "trailersendfile", new 
TrailerSendfileServlet(file));
+        ctxt.addServletMapping("/trailersendfile", "trailersendfile");
         tomcat.start();
 
         openClientConnection();
@@ -271,7 +895,7 @@ public class TestHttp2Sendfile extends Http2TestBase {
 
         byte[] frameHeader = new byte[9];
         ByteBuffer headersPayload = ByteBuffer.allocate(128);
-        buildGetRequest(frameHeader, headersPayload, null, 3, "/sendfile");
+        buildGetRequest(frameHeader, headersPayload, null, 3, sendfilePath);
         writeFrame(frameHeader, headersPayload);
     }
 
@@ -291,6 +915,102 @@ public class TestHttp2Sendfile extends Http2TestBase {
     }
 
 
+    private static class AsyncSendfileServlet extends HttpServlet {
+
+        private static final long serialVersionUID = 1L;
+
+        private final File file;
+
+        AsyncSendfileServlet(File file) {
+            this.file = file;
+        }
+
+        @Override
+        protected void doGet(HttpServletRequest req, HttpServletResponse resp) 
throws ServletException, IOException {
+            AsyncContext ac = req.startAsync();
+            ac.start(() -> {
+                try {
+                    req.setAttribute(Globals.SENDFILE_FILENAME_ATTR, 
file.getCanonicalPath());
+                    req.setAttribute(Globals.SENDFILE_FILE_START_ATTR, 
Long.valueOf(0));
+                    req.setAttribute(Globals.SENDFILE_FILE_END_ATTR, 
Long.valueOf(file.length()));
+                    resp.setContentType("application/octet-stream");
+                    resp.setContentLengthLong(file.length());
+                } catch (IOException e) {
+                    throw new IllegalStateException(e);
+                }
+                // Completing the request commits the response and uses 
sendfile during the asynchronous dispatch
+                ac.complete();
+            });
+        }
+    }
+
+
+    private static class AsyncTimeoutSendfileServlet extends HttpServlet {
+
+        private static final long serialVersionUID = 1L;
+
+        private final File file;
+
+        AsyncTimeoutSendfileServlet(File file) {
+            this.file = file;
+        }
+
+        @Override
+        protected void doGet(HttpServletRequest req, HttpServletResponse resp) 
throws ServletException, IOException {
+            AsyncContext ac = req.startAsync();
+            ac.setTimeout(200);
+            ac.addListener(new AsyncListener() {
+                @Override
+                public void onTimeout(AsyncEvent event) throws IOException {
+                    req.setAttribute(Globals.SENDFILE_FILENAME_ATTR, 
file.getCanonicalPath());
+                    req.setAttribute(Globals.SENDFILE_FILE_START_ATTR, 
Long.valueOf(0));
+                    req.setAttribute(Globals.SENDFILE_FILE_END_ATTR, 
Long.valueOf(file.length()));
+                    resp.setContentType("application/octet-stream");
+                    resp.setContentLengthLong(file.length());
+                    // Completing the request commits the response and uses 
sendfile while processing the timeout
+                    ac.complete();
+                }
+
+                @Override
+                public void onComplete(AsyncEvent event) {
+                }
+
+                @Override
+                public void onError(AsyncEvent event) {
+                }
+
+                @Override
+                public void onStartAsync(AsyncEvent event) {
+                }
+            });
+        }
+    }
+
+
+    private static class TrailerSendfileServlet extends HttpServlet {
+
+        private static final long serialVersionUID = 1L;
+
+        private final File file;
+
+        TrailerSendfileServlet(File file) {
+            this.file = file;
+        }
+
+        @Override
+        protected void doGet(HttpServletRequest req, HttpServletResponse resp) 
throws ServletException, IOException {
+            req.setAttribute(Globals.SENDFILE_FILENAME_ATTR, 
file.getCanonicalPath());
+            req.setAttribute(Globals.SENDFILE_FILE_START_ATTR, 
Long.valueOf(0));
+            req.setAttribute(Globals.SENDFILE_FILE_END_ATTR, 
Long.valueOf(file.length()));
+            resp.setContentType("application/octet-stream");
+            resp.setContentLengthLong(file.length());
+            resp.setTrailerFields(() -> {
+                throw new IllegalStateException("Test trailer supplier 
failure");
+            });
+        }
+    }
+
+
     private static class SendfileServlet extends HttpServlet {
 
         private static final long serialVersionUID = 1L;
diff --git a/webapps/docs/changelog.xml b/webapps/docs/changelog.xml
index 8047bb3a00..275dff19c0 100644
--- a/webapps/docs/changelog.xml
+++ b/webapps/docs/changelog.xml
@@ -231,6 +231,19 @@
   </subsection>
   <subsection name="Coyote">
     <changelog>
+      <fix>
+        Ensure that an HTTP/2 stream, its processor and its request and
+        response are cleaned up and recycled once a response written using
+        asynchronous sendfile has finished, whether the response was
+        completely sent, the stream was reset or the write failed. Previously
+        they were retained until the stream was pruned from the connection.
+        The clean-up is also deferred until a pending sendfile write has
+        finished so that the request and response are not recycled, and
+        possibly re-used for another stream, while the write still uses them.
+        An exception thrown while completing a sendfile write, such as from
+        the code that provides the trailer fields, now closes the connection
+        instead of leaving the stream waiting indefinitely. (remm/markt)
+      </fix>
       <fix>
         Improve the handling of operations on an NIO2 socket that is being
         closed. (markt)


---------------------------------------------------------------------
To unsubscribe, e-mail: [email protected]
For additional commands, e-mail: [email protected]

Reply via email to