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

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


The following commit(s) were added to refs/heads/main by this push:
     new e60606722b Allow HTTP upgrade during async processing and fix upgrade 
clean-up
e60606722b is described below

commit e60606722bdd2decfafdff19b612c7a8c0e94d6b
Author: Mark Thomas <[email protected]>
AuthorDate: Wed Nov 25 16:48:09 2026 +0000

    Allow HTTP upgrade during async processing and fix upgrade clean-up
    
    - Allow HttpServletRequest.upgrade() after startAsync() provided it is
      called before complete() or dispatch() and before an async error. The
      upgrade takes place when the async processing completes.
    - Reject a second call to upgrade().
    - Complete an upgrade requested during async processing regardless of
      keep-alive (or fail it if the protocol is paused) and do not add a
      Connection: close header to a 101 response.
    - Destroy the HttpUpgradeHandler if upgrade() fails because the protocol
      (AJP, HTTP/2) does not support it, and if a failure occurs between
      releasing the HTTP processor and creating the upgrade processor.
    - Do not let a failure in HttpUpgradeHandler.destroy() prevent the
      processor being released and only call destroy() if init() was called.
    - Add tests for the above including access logging, non-blocking I/O,
      timeouts, errors and client disconnects.
    
    Co-Authored-By: Claude Sonnet 5.5 <[email protected]>
    
    # Conflicts:
    #       webapps/docs/changelog.xml
---
 .../catalina/connector/LocalStrings.properties     |    5 +-
 java/org/apache/catalina/connector/Request.java    |   52 +-
 java/org/apache/coyote/AbstractProtocol.java       |   82 +-
 java/org/apache/coyote/LocalStrings.properties     |    1 +
 java/org/apache/coyote/http11/Http11Processor.java |   32 +-
 test/org/apache/coyote/ajp/TestAjpProcessor.java   |   95 ++
 .../upgrade/TestUpgradeProcessorCreateFailure.java |  202 ++++
 .../http11/upgrade/TestUpgradeValidation.java      | 1203 +++++++++++++++++++-
 test/org/apache/coyote/http2/TestHttp2Upgrade.java |  166 +++
 webapps/docs/changelog.xml                         |   41 +
 10 files changed, 1848 insertions(+), 31 deletions(-)

diff --git a/java/org/apache/catalina/connector/LocalStrings.properties 
b/java/org/apache/catalina/connector/LocalStrings.properties
index 25500521d4..09e927b647 100644
--- a/java/org/apache/catalina/connector/LocalStrings.properties
+++ b/java/org/apache/catalina/connector/LocalStrings.properties
@@ -70,8 +70,11 @@ coyoteRequest.sessionEndAccessFail=Exception triggered 
ending access to session
 coyoteRequest.setAttribute.namenull=Cannot call setAttribute with a null name
 coyoteRequest.tooManyLocales=More than the maximum allowed number of locales, 
[{0}], were detected. Use the maxLocaleCount attribute of the connector to 
resolve this if the application should accept more locales.
 coyoteRequest.trailersNotReady=It is illegal to call getTrailerFields() before 
isTrailerFieldsReady() has returned true
-coyoteRequest.upgradeAfterAsync=Unable to upgrade the request because async 
processing has been started
+coyoteRequest.upgradeAfterAsyncEnd=Unable to upgrade the request because async 
processing is completing or dispatching. The request must be upgraded before 
AsyncContext.complete() or AsyncContext.dispatch() is called
+coyoteRequest.upgradeAfterAsyncError=Unable to upgrade the request because an 
error has occurred during async processing
 coyoteRequest.upgradeAfterCommit=Unable to upgrade the request because the 
response has been committed
+coyoteRequest.upgradeAfterUpgrade=Unable to upgrade the request because 
upgrade() has already been called for this request
+coyoteRequest.upgradeHandlerDestroyFail=Failed to destroy the 
HttpUpgradeHandler instance after the request could not be upgraded
 coyoteRequest.uploadCreate=Creating the temporary upload location [{0}] as it 
is required by the servlet [{1}]
 coyoteRequest.uploadCreateFail=Failed to create the upload location [{0}]
 coyoteRequest.uploadLocationInvalid=The temporary upload location [{0}] is not 
valid
diff --git a/java/org/apache/catalina/connector/Request.java 
b/java/org/apache/catalina/connector/Request.java
index 43e7d28fc1..b4559aec35 100644
--- a/java/org/apache/catalina/connector/Request.java
+++ b/java/org/apache/catalina/connector/Request.java
@@ -1642,6 +1642,16 @@ public class Request implements HttpServletRequest {
         return asyncContext.isStarted();
     }
 
+    private boolean isAsyncError() {
+        if (asyncContext == null) {
+            return false;
+        }
+
+        AtomicBoolean result = new AtomicBoolean(false);
+        coyoteRequest.action(ActionCode.ASYNC_IS_ERROR, result);
+        return result.get();
+    }
+
     /**
      * Check if async dispatch is in progress.
      *
@@ -1922,8 +1932,20 @@ public class Request implements HttpServletRequest {
     @Override
     public <T extends HttpUpgradeHandler> T upgrade(Class<T> 
httpUpgradeHandlerClass)
             throws IOException, ServletException {
-        if (isAsyncStarted()) {
-            throw new 
IllegalStateException(sm.getString("coyoteRequest.upgradeAfterAsync"));
+        if (upgradeRequested) {
+            throw new 
IllegalStateException(sm.getString("coyoteRequest.upgradeAfterUpgrade"));
+        }
+        /*
+         * Upgrade is permitted while asynchronous processing is in progress. 
The upgrade completes the asynchronous
+         * processing so it must be called before the application calls 
AsyncContext.complete() or
+         * AsyncContext.dispatch().
+         */
+        if (isAsyncCompleting() || isAsyncDispatching()) {
+            throw new 
IllegalStateException(sm.getString("coyoteRequest.upgradeAfterAsyncEnd"));
+        }
+        // An error has occurred (e.g. AsyncListener.onError() is being 
called) so upgrading is no longer appropriate
+        if (isAsyncError()) {
+            throw new 
IllegalStateException(sm.getString("coyoteRequest.upgradeAfterAsyncError"));
         }
         if (response.isCommitted()) {
             throw new 
IllegalStateException(sm.getString("coyoteRequest.upgradeAfterCommit"));
@@ -1943,10 +1965,18 @@ public class Request implements HttpServletRequest {
         } catch (ReflectiveOperationException | NamingException | 
IllegalArgumentException | SecurityException e) {
             throw new ServletException(e);
         }
-        UpgradeToken upgradeToken = new UpgradeToken(handler, getContext(), 
instanceManager,
-                getUpgradeProtocolName(httpUpgradeHandlerClass));
+        try {
+            UpgradeToken upgradeToken = new UpgradeToken(handler, 
getContext(), instanceManager,
+                    getUpgradeProtocolName(httpUpgradeHandlerClass));
 
-        coyoteRequest.action(ActionCode.UPGRADE, upgradeToken);
+            // This will fail if the protocol does not support HTTP upgrade
+            coyoteRequest.action(ActionCode.UPGRADE, upgradeToken);
+        } catch (Throwable t) {
+            ExceptionUtils.handleThrowable(t);
+            // The handler has been created but nothing will use it so it 
needs to be destroyed
+            destroyUpgradeHandler(instanceManager, handler);
+            throw t;
+        }
         upgradeRequested = true;
 
         // Output required by RFC2616. Protocol specific headers should have
@@ -1957,6 +1987,18 @@ public class Request implements HttpServletRequest {
     }
 
 
+    private void destroyUpgradeHandler(InstanceManager instanceManager, 
HttpUpgradeHandler handler) {
+        if (instanceManager != null) {
+            try {
+                instanceManager.destroyInstance(handler);
+            } catch (Throwable t) {
+                ExceptionUtils.handleThrowable(t);
+                
log.warn(sm.getString("coyoteRequest.upgradeHandlerDestroyFail"), t);
+            }
+        }
+    }
+
+
     private String getUpgradeProtocolName(Class<? extends HttpUpgradeHandler> 
httpUpgradeHandlerClass) {
         // Ideal - the caller has already explicitly set the selected protocol
         // on the response
diff --git a/java/org/apache/coyote/AbstractProtocol.java 
b/java/org/apache/coyote/AbstractProtocol.java
index 5089e529b1..0554119d3f 100644
--- a/java/org/apache/coyote/AbstractProtocol.java
+++ b/java/org/apache/coyote/AbstractProtocol.java
@@ -42,6 +42,7 @@ import jakarta.servlet.http.HttpUpgradeHandler;
 import jakarta.servlet.http.WebConnection;
 
 import org.apache.coyote.http11.upgrade.InternalHttpUpgradeHandler;
+import org.apache.coyote.http11.upgrade.UpgradeProcessorBase;
 import org.apache.juli.logging.Log;
 import org.apache.tomcat.InstanceManager;
 import org.apache.tomcat.util.ExceptionUtils;
@@ -1267,6 +1268,14 @@ public abstract class AbstractProtocol<S> implements 
ProtocolHandler, MBeanRegis
                 return SocketState.CLOSED;
             }
 
+            /*
+             * Tracks an HTTP upgrade for which the processor that was 
handling the HTTP request has been released but
+             * the upgrade processor that takes ownership of the 
HttpUpgradeHandler has not yet been created. If
+             * something goes wrong in that window there is no processor that 
cleanUpIfUpgrade() can use to find the
+             * handler.
+             */
+            UpgradeToken pendingUpgradeToken = null;
+
             try {
                 if (processor == null) {
                     String negotiatedProtocol = 
wrapper.getNegotiatedProtocol();
@@ -1336,6 +1345,8 @@ public abstract class AbstractProtocol<S> implements 
ProtocolHandler, MBeanRegis
                             if (upgradeProtocol != null) {
                                 // Release the Http11 processor to be re-used
                                 release(processor);
+                                // Make sure the released processor is not 
used or released again if the next step fails
+                                processor = null;
                                 // Create the upgrade processor
                                 processor = 
upgradeProtocol.getProcessor(wrapper, getProtocol().getAdapter());
                             } else {
@@ -1350,8 +1361,16 @@ public abstract class AbstractProtocol<S> implements 
ProtocolHandler, MBeanRegis
                             HttpUpgradeHandler httpUpgradeHandler = 
upgradeToken.httpUpgradeHandler();
                             // Release the Http11 processor to be re-used
                             release(processor);
+                            /*
+                             * The released processor no longer references the 
upgrade token. Make sure it is not used
+                             * or released again and that the handler is 
cleaned up if the next step fails.
+                             */
+                            processor = null;
+                            pendingUpgradeToken = upgradeToken;
                             // Create the upgrade processor
                             processor = 
getProtocol().createUpgradeProcessor(wrapper, upgradeToken);
+                            // The upgrade processor now owns the upgrade token
+                            pendingUpgradeToken = null;
                             if (getLog().isTraceEnabled()) {
                                 getLog().trace(
                                         
sm.getString("abstractConnectionHandler.upgradeCreate", processor, wrapper));
@@ -1483,6 +1502,7 @@ public abstract class AbstractProtocol<S> implements 
ProtocolHandler, MBeanRegis
             // Processors handling upgrades require additional clean-up
             // before release.
             cleanUpIfUpgrade(processor);
+            cleanUpUpgradeToken(pendingUpgradeToken, false);
             // Make sure socket/processor is removed from the list of current
             // connections
             release(processor);
@@ -1492,24 +1512,56 @@ public abstract class AbstractProtocol<S> implements 
ProtocolHandler, MBeanRegis
 
         private void cleanUpIfUpgrade(Processor processor) {
             if (processor != null && processor.isUpgrade()) {
-                UpgradeToken upgradeToken = processor.getUpgradeToken();
-                HttpUpgradeHandler httpUpgradeHandler = 
upgradeToken.httpUpgradeHandler();
-                InstanceManager instanceManager = 
upgradeToken.instanceManager();
-                if (instanceManager == null) {
-                    httpUpgradeHandler.destroy();
-                } else {
-                    ClassLoader oldCL = upgradeToken.contextBind().bind(null);
+                /*
+                 * Only an upgrade processor means the upgrade has been 
completed and the handler initialised. If the
+                 * processor is anything else (an HTTP processor that still 
holds the upgrade token) the upgrade was
+                 * abandoned before the handler was initialised.
+                 */
+                cleanUpUpgradeToken(processor.getUpgradeToken(), processor 
instanceof UpgradeProcessorBase);
+            }
+        }
+
+
+        /**
+         * Clean up the handler for an upgrade.
+         *
+         * @param upgradeToken The upgrade token for the upgrade
+         * @param initialised  Has the handler been (or at least started to 
be) initialised? {@link
+         *                         HttpUpgradeHandler#destroy()} must not be 
called if it has not as handlers may rely
+         *                         on state set during initialisation.
+         */
+        private void cleanUpUpgradeToken(UpgradeToken upgradeToken, boolean 
initialised) {
+            if (upgradeToken == null) {
+                return;
+            }
+            HttpUpgradeHandler httpUpgradeHandler = 
upgradeToken.httpUpgradeHandler();
+            InstanceManager instanceManager = upgradeToken.instanceManager();
+            ClassLoader oldCL = null;
+            if (instanceManager != null) {
+                oldCL = upgradeToken.contextBind().bind(null);
+            }
+            try {
+                if (initialised) {
+                    /*
+                     * An exception here must not prevent the rest of the 
clean-up or the release of the processor
+                     * which is what de-registers it (and its statistics).
+                     */
                     try {
                         httpUpgradeHandler.destroy();
-                    } finally {
-                        try {
-                            
instanceManager.destroyInstance(httpUpgradeHandler);
-                        } catch (Throwable t) {
-                            ExceptionUtils.handleThrowable(t);
-                            
getLog().error(sm.getString("abstractConnectionHandler.error"), t);
-                        }
-                        upgradeToken.contextBind().unbind(oldCL);
+                    } catch (Throwable t) {
+                        ExceptionUtils.handleThrowable(t);
+                        
getLog().error(sm.getString("abstractConnectionHandler.upgradeDestroyFail"), t);
+                    }
+                }
+            } finally {
+                if (instanceManager != null) {
+                    try {
+                        instanceManager.destroyInstance(httpUpgradeHandler);
+                    } catch (Throwable t) {
+                        ExceptionUtils.handleThrowable(t);
+                        
getLog().error(sm.getString("abstractConnectionHandler.error"), t);
                     }
+                    upgradeToken.contextBind().unbind(oldCL);
                 }
             }
         }
diff --git a/java/org/apache/coyote/LocalStrings.properties 
b/java/org/apache/coyote/LocalStrings.properties
index bf625956e7..d53bf1e67d 100644
--- a/java/org/apache/coyote/LocalStrings.properties
+++ b/java/org/apache/coyote/LocalStrings.properties
@@ -24,6 +24,7 @@ abstractConnectionHandler.processorPop=Popped processor [{0}] 
from cache
 abstractConnectionHandler.protocolexception.debug=ProtocolExceptions are 
normal, ignored
 abstractConnectionHandler.socketexception.debug=SocketExceptions are normal, 
ignored
 abstractConnectionHandler.upgradeCreate=Created upgrade processor [{0}] for 
socket wrapper [{1}]
+abstractConnectionHandler.upgradeDestroyFail=Failed to destroy the 
HttpUpgradeHandler
 
 abstractProcessor.asyncFail=Unable to write async data
 abstractProcessor.fallToDebug=\n\
diff --git a/java/org/apache/coyote/http11/Http11Processor.java 
b/java/org/apache/coyote/http11/Http11Processor.java
index 8b2931a626..df0d2dc849 100644
--- a/java/org/apache/coyote/http11/Http11Processor.java
+++ b/java/org/apache/coyote/http11/Http11Processor.java
@@ -1049,8 +1049,12 @@ public class Http11Processor extends AbstractProcessor {
             keepAlive = false;
         }
         if (!keepAlive) {
-            // Avoid adding the close header twice
-            if (!connectionClosePresent) {
+            /*
+             * Avoid adding the close header twice. Do not add it to a 
response that switches protocols. The connection
+             * is not going to be closed, it is going to be used for the new 
protocol and the Connection header that is
+             * required for the protocol switch is already present.
+             */
+            if (!connectionClosePresent && statusCode != 
HttpServletResponse.SC_SWITCHING_PROTOCOLS) {
                 
headers.addValue(Constants.CONNECTION).setString(Constants.CLOSE);
             }
         } else if (!getErrorState().isError()) {
@@ -1118,6 +1122,10 @@ public class Http11Processor extends AbstractProcessor {
             if (!getErrorState().isError()) {
                 setErrorState(ErrorState.CLOSE_CLEAN, null);
             }
+            if (!keepAlive && !isConnectionToken(headers, Constants.CLOSE)) {
+                // The close header was not added above because the response 
was expected to be a protocol switch
+                
headers.addValue(Constants.CONNECTION).setString(Constants.CLOSE);
+            }
         }
 
         writeHeaders(response.getStatus(), headers);
@@ -1225,6 +1233,26 @@ public class Http11Processor extends AbstractProcessor {
 
     @Override
     protected SocketState dispatchEndRequest() {
+        if (isUpgrade()) {
+            if (protocol.isPaused()) {
+                /*
+                 * As when the upgrade is requested outside of asynchronous 
processing, the connection is closed rather
+                 * than upgraded if the protocol is paused. The 
HttpUpgradeHandler is destroyed as part of closing the
+                 * connection.
+                 */
+                return SocketState.CLOSED;
+            }
+            /*
+             * The upgrade was requested during asynchronous processing. 
Whether keep-alive is enabled is irrelevant as
+             * the connection is being handed over to the upgrade processor, 
as it is when the upgrade is requested
+             * outside of asynchronous processing. Finish the request so any 
unread request body is swallowed and any
+             * pipelined (or upgraded protocol) data is retained as leftover 
input.
+             */
+            endRequest();
+            inputBuffer.nextRequest();
+            outputBuffer.nextRequest();
+            return SocketState.UPGRADING;
+        }
         if (!keepAlive || protocol.isPaused()) {
             return SocketState.CLOSED;
         } else {
diff --git a/test/org/apache/coyote/ajp/TestAjpProcessor.java 
b/test/org/apache/coyote/ajp/TestAjpProcessor.java
index dd5cdb0fbb..813aa84426 100644
--- a/test/org/apache/coyote/ajp/TestAjpProcessor.java
+++ b/test/org/apache/coyote/ajp/TestAjpProcessor.java
@@ -19,10 +19,17 @@ package org.apache.coyote.ajp;
 import java.io.IOException;
 import java.util.List;
 import java.util.concurrent.CopyOnWriteArrayList;
+import java.util.concurrent.CountDownLatch;
+import java.util.concurrent.TimeUnit;
+import java.util.concurrent.atomic.AtomicBoolean;
+import java.util.concurrent.atomic.AtomicReference;
 
+import jakarta.annotation.PreDestroy;
 import jakarta.servlet.http.HttpServlet;
 import jakarta.servlet.http.HttpServletRequest;
 import jakarta.servlet.http.HttpServletResponse;
+import jakarta.servlet.http.HttpUpgradeHandler;
+import jakarta.servlet.http.WebConnection;
 
 import org.junit.Assert;
 import org.junit.Test;
@@ -103,6 +110,94 @@ public class TestAjpProcessor extends AjpBaseTest {
     }
 
 
+    /*
+     * HTTP upgrade is not supported by AJP. The attempt to upgrade must fail 
and the HttpUpgradeHandler instance, that
+     * has been created by the time the failure is detected, must be destroyed 
rather than leaked.
+     */
+    @Test
+    public void testUpgradeNotSupported() throws Exception {
+        Tomcat tomcat = getTomcatInstance();
+
+        // No file system docBase required
+        Context ctx = getProgrammaticRootContext();
+
+        UpgradeAttemptServlet servlet = new UpgradeAttemptServlet();
+        Tomcat.addServlet(ctx, "servlet", servlet);
+        ctx.addServletMapping("/", "servlet");
+
+        tomcat.start();
+
+        SimpleAjpClient ajpClient = new SimpleAjpClient();
+        ajpClient.setPort(getPort());
+        ajpClient.connect();
+
+        TesterAjpMessage forwardMessage = ajpClient.createForwardMessage();
+        forwardMessage.end();
+        TesterAjpMessage responseHeaders = 
ajpClient.sendMessage(forwardMessage);
+        TestAbstractAjpProcessor.validateResponseHeaders(responseHeaders, 200, 
"200");
+
+        Assert.assertTrue(servlet.attempted.await(5, TimeUnit.SECONDS));
+        Assert.assertTrue("The upgrade attempt must fail", 
servlet.failure.get() != null);
+        Assert.assertTrue(servlet.failure.get().toString(),
+                servlet.failure.get() instanceof 
UnsupportedOperationException);
+        Assert.assertTrue("The HttpUpgradeHandler must have been created", 
UpgradeAttemptHandler.created.get());
+        Assert.assertTrue("The HttpUpgradeHandler must be destroyed", 
UpgradeAttemptHandler.destroyed.get());
+        Assert.assertFalse("The HttpUpgradeHandler must not be initialised", 
UpgradeAttemptHandler.initialised.get());
+        Assert.assertFalse("destroy() must not be called if init() was not 
called",
+                UpgradeAttemptHandler.destroyMethodCalled.get());
+
+        ajpClient.disconnect();
+    }
+
+
+    static final class UpgradeAttemptServlet extends HttpServlet {
+
+        private static final long serialVersionUID = 1L;
+
+        private final transient CountDownLatch attempted = new 
CountDownLatch(1);
+        private final transient AtomicReference<Throwable> failure = new 
AtomicReference<>();
+
+        @Override
+        protected void service(HttpServletRequest req, HttpServletResponse 
resp) throws IOException {
+            try {
+                req.upgrade(UpgradeAttemptHandler.class);
+            } catch (Throwable t) {
+                failure.set(t);
+            }
+            resp.setStatus(HttpServletResponse.SC_OK);
+            attempted.countDown();
+        }
+    }
+
+
+    public static class UpgradeAttemptHandler implements HttpUpgradeHandler {
+
+        static final AtomicBoolean created = new AtomicBoolean();
+        static final AtomicBoolean initialised = new AtomicBoolean();
+        static final AtomicBoolean destroyed = new AtomicBoolean();
+        static final AtomicBoolean destroyMethodCalled = new AtomicBoolean();
+
+        public UpgradeAttemptHandler() {
+            created.set(true);
+        }
+
+        @Override
+        public void init(WebConnection connection) {
+            initialised.set(true);
+        }
+
+        @Override
+        public void destroy() {
+            destroyMethodCalled.set(true);
+        }
+
+        @PreDestroy
+        public void preDestroy() {
+            destroyed.set(true);
+        }
+    }
+
+
     static final class RecordingServlet extends HttpServlet {
 
         private static final long serialVersionUID = 1L;
diff --git 
a/test/org/apache/coyote/http11/upgrade/TestUpgradeProcessorCreateFailure.java 
b/test/org/apache/coyote/http11/upgrade/TestUpgradeProcessorCreateFailure.java
new file mode 100644
index 0000000000..e561869a5c
--- /dev/null
+++ 
b/test/org/apache/coyote/http11/upgrade/TestUpgradeProcessorCreateFailure.java
@@ -0,0 +1,202 @@
+/*
+ *  Licensed to the Apache Software Foundation (ASF) under one or more
+ *  contributor license agreements.  See the NOTICE file distributed with
+ *  this work for additional information regarding copyright ownership.
+ *  The ASF licenses this file to You under the Apache License, Version 2.0
+ *  (the "License"); you may not use this file except in compliance with
+ *  the License.  You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ *  Unless required by applicable law or agreed to in writing, software
+ *  distributed under the License is distributed on an "AS IS" BASIS,
+ *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ *  See the License for the specific language governing permissions and
+ *  limitations under the License.
+ */
+package org.apache.coyote.http11.upgrade;
+
+import java.io.BufferedReader;
+import java.io.IOException;
+import java.io.InputStreamReader;
+import java.io.OutputStreamWriter;
+import java.io.Writer;
+import java.lang.reflect.Field;
+import java.net.Socket;
+import java.nio.charset.StandardCharsets;
+import java.util.concurrent.atomic.AtomicBoolean;
+import java.util.concurrent.atomic.AtomicInteger;
+
+import javax.net.SocketFactory;
+
+import jakarta.annotation.PreDestroy;
+import jakarta.servlet.ServletException;
+import jakarta.servlet.http.HttpServlet;
+import jakarta.servlet.http.HttpServletRequest;
+import jakarta.servlet.http.HttpServletResponse;
+import jakarta.servlet.http.HttpUpgradeHandler;
+import jakarta.servlet.http.WebConnection;
+
+import org.junit.Assert;
+import org.junit.Before;
+import org.junit.Test;
+
+import static org.apache.catalina.startup.SimpleHttpClient.CRLF;
+import org.apache.catalina.Context;
+import org.apache.catalina.startup.Tomcat;
+import org.apache.catalina.startup.TomcatBaseTest;
+import org.apache.coyote.AbstractProtocol;
+import org.apache.coyote.Processor;
+import org.apache.coyote.UpgradeToken;
+import org.apache.coyote.http11.Http11NioProtocol;
+import org.apache.tomcat.util.net.SocketWrapperBase;
+
+/**
+ * Tests the clean-up when the HTTP upgrade fails after the processor that 
handled the HTTP request has been released
+ * but before the upgrade processor has taken ownership of the {@link 
HttpUpgradeHandler}.
+ */
+public class TestUpgradeProcessorCreateFailure extends TomcatBaseTest {
+
+    private static final AtomicBoolean handlerCreated = new AtomicBoolean();
+    private static final AtomicBoolean handlerInitialised = new 
AtomicBoolean();
+    private static final AtomicBoolean handlerDestroyed = new AtomicBoolean();
+    private static final AtomicBoolean handlerDestroyMethodCalled = new 
AtomicBoolean();
+    private static final AtomicInteger createUpgradeProcessorCalls = new 
AtomicInteger();
+
+
+    @Before
+    public void resetFlags() {
+        handlerCreated.set(false);
+        handlerInitialised.set(false);
+        handlerDestroyed.set(false);
+        handlerDestroyMethodCalled.set(false);
+        createUpgradeProcessorCalls.set(0);
+    }
+
+
+    @Override
+    protected String getProtocol() {
+        return FailingUpgradeProtocol.class.getName();
+    }
+
+
+    @Test
+    public void testCreateUpgradeProcessorFails() throws Exception {
+        Tomcat tomcat = getTomcatInstance();
+
+        // No file system docBase required
+        Context ctx = getProgrammaticRootContext();
+
+        Tomcat.addServlet(ctx, "servlet", new UpgradeServlet());
+        ctx.addServletMapping("/", "servlet");
+
+        tomcat.start();
+
+        Socket socket = SocketFactory.getDefault().createSocket("localhost", 
getPort());
+        socket.setSoTimeout(5000);
+        try {
+            Writer writer = new OutputStreamWriter(socket.getOutputStream(), 
StandardCharsets.UTF_8);
+            BufferedReader reader =
+                    new BufferedReader(new 
InputStreamReader(socket.getInputStream(), StandardCharsets.UTF_8));
+            writer.write("GET / HTTP/1.1" + CRLF);
+            writer.write("Host: whatever" + CRLF);
+            writer.write("Connection: Upgrade" + CRLF);
+            writer.write("Upgrade: test" + CRLF);
+            writer.write(CRLF);
+            writer.flush();
+
+            // The 101 response is sent before the upgrade processor is 
created. Then the connection is closed.
+            String line = reader.readLine();
+            while (line != null) {
+                line = reader.readLine();
+            }
+        } catch (IOException ioe) {
+            // Connection reset is also a closed connection
+        } finally {
+            socket.close();
+        }
+
+        Assert.assertEquals(1, createUpgradeProcessorCalls.get());
+        Assert.assertTrue("The HttpUpgradeHandler must have been created", 
handlerCreated.get());
+
+        int count = 0;
+        while (!handlerDestroyed.get() && count < 50) {
+            Thread.sleep(100);
+            count++;
+        }
+        Assert.assertTrue("The HttpUpgradeHandler must be destroyed", 
handlerDestroyed.get());
+        Assert.assertFalse("The HttpUpgradeHandler must not be initialised", 
handlerInitialised.get());
+        Assert.assertFalse("destroy() must not be called if init() was not 
called", handlerDestroyMethodCalled.get());
+
+        // The processor that handled the HTTP request must only have been 
recycled once
+        Assert.assertEquals("The processor was released more than once", 1, 
getRecycledProcessorCount());
+    }
+
+
+    private int getRecycledProcessorCount() throws Exception {
+        Object protocol = 
getTomcatInstance().getConnector().getProtocolHandler();
+        Field handlerField = 
AbstractProtocol.class.getDeclaredField("handler");
+        handlerField.setAccessible(true);
+        Object handler = handlerField.get(protocol);
+        Field recycledField = null;
+        for (Class<?> clazz = handler.getClass(); clazz != null && 
recycledField == null; clazz = clazz.getSuperclass()) {
+            try {
+                recycledField = clazz.getDeclaredField("recycledProcessors");
+            } catch (NoSuchFieldException e) {
+                // Try the super class
+            }
+        }
+        Assert.assertNotNull(recycledField);
+        recycledField.setAccessible(true);
+        Object recycled = recycledField.get(handler);
+        Field sizeField = recycled.getClass().getDeclaredField("size");
+        sizeField.setAccessible(true);
+        return ((java.util.concurrent.atomic.AtomicInteger) 
sizeField.get(recycled)).get();
+    }
+
+
+    public static class FailingUpgradeProtocol extends Http11NioProtocol {
+
+        @Override
+        protected Processor createUpgradeProcessor(SocketWrapperBase<?> 
socket, UpgradeToken upgradeToken) {
+            createUpgradeProcessorCalls.incrementAndGet();
+            throw new IllegalStateException("Deliberate failure creating the 
upgrade processor");
+        }
+    }
+
+
+    private static class UpgradeServlet extends HttpServlet {
+
+        private static final long serialVersionUID = 1L;
+
+        @Override
+        protected void doGet(HttpServletRequest req, HttpServletResponse resp) 
throws ServletException, IOException {
+            resp.setHeader("Upgrade", "test");
+            resp.setHeader("Connection", "upgrade");
+            req.upgrade(TestHandler.class);
+        }
+    }
+
+
+    public static class TestHandler implements HttpUpgradeHandler {
+
+        public TestHandler() {
+            handlerCreated.set(true);
+        }
+
+        @Override
+        public void init(WebConnection connection) {
+            handlerInitialised.set(true);
+        }
+
+        @Override
+        public void destroy() {
+            handlerDestroyMethodCalled.set(true);
+        }
+
+        @PreDestroy
+        public void preDestroy() {
+            handlerDestroyed.set(true);
+        }
+    }
+}
diff --git a/test/org/apache/coyote/http11/upgrade/TestUpgradeValidation.java 
b/test/org/apache/coyote/http11/upgrade/TestUpgradeValidation.java
index 60b08591c9..1f11db4a38 100644
--- a/test/org/apache/coyote/http11/upgrade/TestUpgradeValidation.java
+++ b/test/org/apache/coyote/http11/upgrade/TestUpgradeValidation.java
@@ -17,6 +17,7 @@
 package org.apache.coyote.http11.upgrade;
 
 import java.io.BufferedReader;
+import java.io.CharArrayWriter;
 import java.io.IOException;
 import java.io.InputStreamReader;
 import java.io.OutputStreamWriter;
@@ -25,18 +26,31 @@ import java.lang.reflect.Field;
 import java.net.Socket;
 import java.net.SocketTimeoutException;
 import java.nio.charset.StandardCharsets;
+import java.util.ArrayList;
+import java.util.Arrays;
+import java.util.Collections;
+import java.util.List;
 import java.util.Map;
+import java.util.Set;
+import java.util.concurrent.CopyOnWriteArrayList;
 import java.util.concurrent.CountDownLatch;
 import java.util.concurrent.TimeUnit;
 import java.util.concurrent.atomic.AtomicBoolean;
+import java.util.concurrent.atomic.AtomicInteger;
+import java.util.concurrent.atomic.AtomicReference;
 
 import javax.net.SocketFactory;
 
 import jakarta.annotation.PreDestroy;
 import jakarta.servlet.AsyncContext;
+import jakarta.servlet.AsyncEvent;
+import jakarta.servlet.AsyncListener;
+import jakarta.servlet.DispatcherType;
+import jakarta.servlet.ReadListener;
 import jakarta.servlet.ServletException;
 import jakarta.servlet.ServletInputStream;
 import jakarta.servlet.ServletOutputStream;
+import jakarta.servlet.WriteListener;
 import jakarta.servlet.http.HttpServlet;
 import jakarta.servlet.http.HttpServletRequest;
 import jakarta.servlet.http.HttpServletResponse;
@@ -49,8 +63,10 @@ import org.junit.Test;
 
 import static org.apache.catalina.startup.SimpleHttpClient.CRLF;
 import org.apache.catalina.Context;
+import org.apache.catalina.connector.Connector;
 import org.apache.catalina.startup.Tomcat;
 import org.apache.catalina.startup.TomcatBaseTest;
+import org.apache.catalina.valves.AbstractAccessLogValve;
 import org.apache.coyote.http11.AbstractHttp11Protocol;
 
 /**
@@ -60,21 +76,38 @@ import org.apache.coyote.http11.AbstractHttp11Protocol;
 public class TestUpgradeValidation extends TomcatBaseTest {
 
     private static final String MESSAGE = "This is a test.";
+    private static final String GREETING = "Greeting from the handler.";
 
     private static final AtomicBoolean handlerInitCalled = new AtomicBoolean();
     private static final AtomicBoolean handlerDestroyed = new AtomicBoolean();
+    private static final AtomicBoolean handlerDestroyMethodCalled = new 
AtomicBoolean();
     private static final AtomicBoolean handlerInstantiated = new 
AtomicBoolean();
     private static final AtomicBoolean iseThrown = new AtomicBoolean();
+    private static final AtomicBoolean asyncCompleteCalled = new 
AtomicBoolean();
+    private static final AtomicInteger greetingHandlersCreated = new 
AtomicInteger();
+    private static final AtomicReference<String> bodyRead = new 
AtomicReference<>();
+    private static volatile Connector connectorToPause;
+    private CapturingAccessLogValve accessLog;
+    private static final String UNCOMMITTED_DATA = "This data must not be 
sent.";
+    private static final int PARTIAL_READ_SIZE = 5;
     private static volatile CountDownLatch upgradeCalled = new 
CountDownLatch(1);
+    private static volatile CountDownLatch clientDisconnected = new 
CountDownLatch(1);
 
 
     @Before
     public void resetFlags() {
         handlerInitCalled.set(false);
         handlerDestroyed.set(false);
+        handlerDestroyMethodCalled.set(false);
         handlerInstantiated.set(false);
         iseThrown.set(false);
+        asyncCompleteCalled.set(false);
+        greetingHandlersCreated.set(0);
+        bodyRead.set(null);
         upgradeCalled = new CountDownLatch(1);
+        clientDisconnected = new CountDownLatch(1);
+        connectorToPause = null;
+        accessLog = null;
     }
 
 
@@ -169,18 +202,579 @@ public class TestUpgradeValidation extends 
TomcatBaseTest {
 
 
     /*
-     * Calling upgrade() after startAsync() must fail and must not affect the 
async processing.
+     * upgrade() may be called after startAsync() on the container thread 
provided it is called before complete(). The
+     * upgrade completes the asynchronous processing.
      */
     @Test
     public void testUpgradeAfterStartAsync() throws Exception {
         Response response = doRequest(Mode.ASYNC_THEN_UPGRADE, "test");
 
+        Assert.assertFalse("upgrade() must not throw IllegalStateException", 
iseThrown.get());
+        assertEchoUpgrade(response);
+        Assert.assertTrue("AsyncListener.onComplete() must be called", 
asyncCompleteCalled.get());
+    }
+
+
+    /*
+     * As above but upgrade() and complete() are called from an application 
thread.
+     */
+    @Test
+    public void testUpgradeAfterStartAsyncAppThread() throws Exception {
+        Response response = doRequest(Mode.ASYNC_THEN_UPGRADE_APP_THREAD, 
"test");
+
+        Assert.assertTrue(upgradeCalled.await(5, TimeUnit.SECONDS));
+        Assert.assertFalse("upgrade() must not throw IllegalStateException", 
iseThrown.get());
+        assertEchoUpgrade(response);
+        Assert.assertTrue("AsyncListener.onComplete() must be called", 
asyncCompleteCalled.get());
+    }
+
+
+    /*
+     * upgrade() must be called before complete(). Calling it afterwards must 
fail and must not affect the completion
+     * of the async processing.
+     */
+    @Test
+    public void testUpgradeAfterAsyncComplete() throws Exception {
+        Response response = doRequest(Mode.ASYNC_COMPLETE_THEN_UPGRADE, 
"test");
+
         Assert.assertTrue("upgrade() must throw IllegalStateException", 
iseThrown.get());
         Assert.assertEquals("200", response.status);
         Assert.assertFalse("HttpUpgradeHandler must not be created", 
handlerInstantiated.get());
         Assert.assertTrue(getUpgradeGroupInfos().isEmpty());
 
-        response.socket.close();
+        response.socket.close();
+    }
+
+
+    /*
+     * As above but complete() and upgrade() are called from an application 
thread. By the time upgrade() is called the
+     * request has been recycled.
+     */
+    @Test
+    public void testUpgradeAfterAsyncCompleteAppThread() throws Exception {
+        Response response = 
doRequest(Mode.ASYNC_COMPLETE_THEN_UPGRADE_APP_THREAD, "test");
+
+        Assert.assertEquals("200", response.status);
+        Assert.assertTrue(upgradeCalled.await(5, TimeUnit.SECONDS));
+        Assert.assertTrue("upgrade() must throw IllegalStateException", 
iseThrown.get());
+        Assert.assertFalse("HttpUpgradeHandler must not be created", 
handlerInstantiated.get());
+        Assert.assertTrue(getUpgradeGroupInfos().isEmpty());
+
+        response.socket.close();
+    }
+
+
+    /*
+     * The application calls upgrade() after startAsync() but never calls 
complete(). The async processing times out.
+     * The upgrade must be abandoned and the handler cleaned up.
+     */
+    @Test
+    public void testUpgradeAfterStartAsyncTimeout() throws Exception {
+        Response response = doRequest(Mode.ASYNC_THEN_UPGRADE_TIMEOUT, "test");
+
+        Assert.assertNotEquals("101", response.status);
+        assertConnectionClosed(response);
+        assertCleanedUp();
+        Assert.assertTrue(getUpgradeGroupInfos().isEmpty());
+    }
+
+
+    /*
+     * As testNoResponseHeader() but the upgrade is requested after 
startAsync(). The upgrade must be abandoned, the
+     * handler cleaned up and no per-protocol state may be created for the 
(client controlled) request header.
+     */
+    @Test
+    public void testAsyncNoResponseHeader() throws Exception {
+        Response response = doRequest(Mode.ASYNC_NO_RESPONSE_HEADER, 
"user-token");
+
+        Assert.assertEquals("500", response.status);
+        assertConnectionClosed(response);
+        assertCleanedUp();
+        Assert.assertTrue(getUpgradeGroupInfos().isEmpty());
+    }
+
+
+    /*
+     * The complete request body is read using non-blocking I/O before the 
upgrade.
+     */
+    @Test
+    public void testAsyncUpgradeAfterCompleteNonBlockingRead() throws 
Exception {
+        String body = "0123456789";
+        Response response = doRequest(Mode.ASYNC_READ_COMPLETE_THEN_UPGRADE, 
"test", body);
+
+        Assert.assertFalse("upgrade() must not throw IllegalStateException", 
iseThrown.get());
+        Assert.assertEquals(body, bodyRead.get());
+        assertEchoUpgrade(response);
+    }
+
+
+    /*
+     * Only part of the request body is read using non-blocking I/O before the 
upgrade. The remainder of the request
+     * body must not be passed to the upgraded protocol as if it had been sent 
by the client using that protocol.
+     */
+    @Test
+    public void testAsyncUpgradeAfterPartialNonBlockingRead() throws Exception 
{
+        String body = "0123456789ABCDEFGHIJ";
+        Response response = doRequest(Mode.ASYNC_READ_PARTIAL_THEN_UPGRADE, 
"test", body);
+
+        Assert.assertFalse("upgrade() must not throw IllegalStateException", 
iseThrown.get());
+        Assert.assertEquals(body.substring(0, PARTIAL_READ_SIZE), 
bodyRead.get());
+        // The echo would return the unread body first if it had been passed 
to the handler
+        assertEchoUpgrade(response);
+    }
+
+
+    /*
+     * As above but the request body is not read at all.
+     */
+    @Test
+    public void testAsyncUpgradeWithUnreadRequestBody() throws Exception {
+        Response response = doRequest(Mode.ASYNC_UNREAD_BODY_THEN_UPGRADE, 
"test", "0123456789ABCDEFGHIJ");
+
+        Assert.assertFalse("upgrade() must not throw IllegalStateException", 
iseThrown.get());
+        assertEchoUpgrade(response);
+    }
+
+
+    /*
+     * Response data has been written, using non-blocking I/O, but not 
committed. It must be discarded as part of the
+     * upgrade.
+     */
+    @Test
+    public void testAsyncUpgradeAfterUncommittedNonBlockingWrite() throws 
Exception {
+        Response response = 
doRequest(Mode.ASYNC_WRITE_UNCOMMITTED_THEN_UPGRADE, "test");
+
+        Assert.assertFalse("upgrade() must not throw IllegalStateException", 
iseThrown.get());
+        // The first data received on the upgraded connection must be from the 
handler. If the data written before the
+        // upgrade was sent, it would be received first.
+        assertEchoUpgrade(response);
+    }
+
+
+    /*
+     * Response data has been written, using non-blocking I/O, and the 
response committed. The upgrade must fail and
+     * must not affect the response.
+     */
+    @Test
+    public void testAsyncUpgradeAfterCommittedNonBlockingWrite() throws 
Exception {
+        Response response = doRequest(Mode.ASYNC_WRITE_COMMITTED_THEN_UPGRADE, 
"test");
+
+        Assert.assertEquals("200", response.status);
+        Assert.assertTrue(upgradeCalled.await(5, TimeUnit.SECONDS));
+        Assert.assertTrue("upgrade() must throw IllegalStateException", 
iseThrown.get());
+        Assert.assertEquals("HttpUpgradeHandler must not be created", 0, 
greetingHandlersCreated.get());
+        Assert.assertTrue(getUpgradeGroupInfos().isEmpty());
+
+        response.socket.close();
+    }
+
+
+    /*
+     * upgrade() must be called before dispatch(). The dispatch must not be 
affected.
+     */
+    @Test
+    public void testUpgradeAfterAsyncDispatch() throws Exception {
+        Response response = doRequest(Mode.ASYNC_DISPATCH_THEN_UPGRADE, 
"test");
+
+        Assert.assertEquals("200", response.status);
+        Assert.assertTrue("upgrade() must throw IllegalStateException", 
iseThrown.get());
+        Assert.assertEquals("HttpUpgradeHandler must not be created", 0, 
greetingHandlersCreated.get());
+        Assert.assertTrue(getUpgradeGroupInfos().isEmpty());
+
+        response.socket.close();
+    }
+
+
+    /*
+     * upgrade() can only be called once. The second call must fail without 
creating another handler (which would
+     * never be destroyed) and without affecting the upgrade.
+     */
+    @Test
+    public void testAsyncDoubleUpgrade() throws Exception {
+        Response response = doRequest(Mode.ASYNC_DOUBLE_UPGRADE, "test");
+
+        Assert.assertTrue("The second upgrade() must throw 
IllegalStateException", iseThrown.get());
+        Assert.assertEquals("Only one HttpUpgradeHandler must be created", 1, 
greetingHandlersCreated.get());
+        assertEchoUpgrade(response);
+    }
+
+
+    @Test
+    public void testDoubleUpgrade() throws Exception {
+        Response response = doRequest(Mode.DOUBLE_UPGRADE, "test");
+
+        Assert.assertTrue("The second upgrade() must throw 
IllegalStateException", iseThrown.get());
+        Assert.assertEquals("Only one HttpUpgradeHandler must be created", 1, 
greetingHandlersCreated.get());
+        assertEchoUpgrade(response);
+    }
+
+
+    /*
+     * The client disconnects after the application has called upgrade() but 
before the asynchronous processing is
+     * completed. The response (and so the upgrade) can't be completed. The 
HttpUpgradeHandler instance that was
+     * created must still be destroyed rather than being leaked.
+     */
+    @Test
+    public void testAsyncUpgradeClientDisconnect() throws Exception {
+        startServer(Mode.ASYNC_UPGRADE_CLIENT_DISCONNECT);
+
+        Socket socket = SocketFactory.getDefault().createSocket("localhost", 
getPort());
+        Writer writer = new OutputStreamWriter(socket.getOutputStream(), 
StandardCharsets.UTF_8);
+        writer.write("GET / HTTP/1.1" + CRLF);
+        writer.write("Host: whatever" + CRLF);
+        writer.write("Connection: Upgrade" + CRLF);
+        writer.write("Upgrade: test" + CRLF);
+        writer.write(CRLF);
+        writer.flush();
+
+        Assert.assertTrue(upgradeCalled.await(5, TimeUnit.SECONDS));
+        Assert.assertTrue("The HttpUpgradeHandler instance must have been 
created", handlerInstantiated.get());
+
+        // Abort the connection (RST) so any attempt to write the response 
fails
+        socket.setSoLinger(true, 0);
+        socket.close();
+        // Give the RST time to arrive then let the application complete the 
asynchronous processing
+        Thread.sleep(500);
+        clientDisconnected.countDown();
+
+        int count = 0;
+        while (!handlerDestroyed.get() && count < 50) {
+            Thread.sleep(100);
+            count++;
+        }
+        assertCleanedUp();
+        Assert.assertTrue(getUpgradeGroupInfos().isEmpty());
+    }
+
+
+    /*
+     * The application calls upgrade() from AsyncListener.onTimeout() and then 
completes the asynchronous processing.
+     * The upgrade must succeed.
+     */
+    @Test
+    public void testAsyncUpgradeInOnTimeout() throws Exception {
+        Response response = doRequest(Mode.ASYNC_UPGRADE_IN_TIMEOUT, "test");
+
+        Assert.assertTrue(upgradeCalled.await(5, TimeUnit.SECONDS));
+        Assert.assertFalse("upgrade() must not throw IllegalStateException", 
iseThrown.get());
+        assertEchoUpgrade(response);
+        Assert.assertTrue("AsyncListener.onComplete() must be called", 
asyncCompleteCalled.get());
+    }
+
+
+    /*
+     * The application calls upgrade() from AsyncListener.onTimeout() but does 
not complete the asynchronous
+     * processing. The timeout is then handled as an error so the upgrade must 
be abandoned and the handler cleaned up.
+     */
+    @Test
+    public void testAsyncUpgradeInOnTimeoutWithoutComplete() throws Exception {
+        Response response = 
doRequest(Mode.ASYNC_UPGRADE_IN_TIMEOUT_NO_COMPLETE, "test");
+
+        Assert.assertTrue(upgradeCalled.await(5, TimeUnit.SECONDS));
+        Assert.assertFalse("upgrade() must not throw IllegalStateException", 
iseThrown.get());
+        Assert.assertEquals("500", response.status);
+        assertConnectionClosed(response);
+        assertCleanedUp();
+        Assert.assertTrue(getUpgradeGroupInfos().isEmpty());
+    }
+
+
+    /*
+     * The protocol is paused after the application has called upgrade() but 
before the asynchronous processing
+     * completes. As when upgrade is requested without async, the connection 
is closed rather than upgraded and the
+     * handler must be cleaned up.
+     */
+    @Test
+    public void testAsyncUpgradeWhileProtocolPaused() throws Exception {
+        connectorToPause = getTomcatInstance().getConnector();
+
+        Response response = doRequest(Mode.ASYNC_UPGRADE_THEN_PAUSE, "test");
+
+        Assert.assertTrue(upgradeCalled.await(5, TimeUnit.SECONDS));
+        // The 101 headers are sent before the connection is closed
+        assertConnectionClosed(response);
+        awaitHandlerDestroyed();
+        assertCleanedUp();
+        Assert.assertTrue(getUpgradeGroupInfos().isEmpty());
+    }
+
+
+    /*
+     * The servlet throws an exception after calling startAsync() and 
upgrade(). The upgrade must be abandoned.
+     */
+    @Test
+    public void testAsyncUpgradeThenException() throws Exception {
+        Response response = doRequest(Mode.ASYNC_UPGRADE_THEN_EXCEPTION, 
"test");
+
+        Assert.assertNotEquals("101", response.status);
+        assertConnectionClosed(response);
+        awaitHandlerDestroyed();
+        assertCleanedUp();
+        Assert.assertTrue(getUpgradeGroupInfos().isEmpty());
+    }
+
+
+    /*
+     * As above but an AsyncListener completes the asynchronous processing 
from onError().
+     */
+    @Test
+    public void testAsyncUpgradeThenExceptionListenerCompletes() throws 
Exception {
+        Response response = 
doRequest(Mode.ASYNC_UPGRADE_ERROR_LISTENER_COMPLETE, "test");
+
+        Assert.assertTrue(upgradeCalled.await(5, TimeUnit.SECONDS));
+        Assert.assertNotEquals("101", response.status);
+        assertConnectionClosed(response);
+        awaitHandlerDestroyed();
+        assertCleanedUp();
+        Assert.assertTrue(getUpgradeGroupInfos().isEmpty());
+    }
+
+
+    /*
+     * The servlet throws an exception and an AsyncListener attempts to handle 
the error, from onError(), by upgrading
+     * the connection. Once an error has occurred an upgrade is not permitted. 
The attempt must fail and no handler may
+     * be created.
+     */
+    @Test
+    public void testAsyncUpgradeInOnError() throws Exception {
+        Response response = doRequest(Mode.ASYNC_UPGRADE_IN_ERROR_LISTENER, 
"test");
+
+        Assert.assertTrue(upgradeCalled.await(5, TimeUnit.SECONDS));
+        Assert.assertTrue("upgrade() must throw IllegalStateException", 
iseThrown.get());
+        Assert.assertNotEquals("101", response.status);
+        Assert.assertFalse("HttpUpgradeHandler must not be created", 
handlerInstantiated.get());
+        Assert.assertTrue(getUpgradeGroupInfos().isEmpty());
+
+        response.socket.close();
+    }
+
+
+    /*
+     * A successful upgrade (without async) must be written to the access log 
once with the 101 status and no response
+     * body.
+     */
+    @Test
+    public void testAccessLogUpgrade() throws Exception {
+        accessLog = new CapturingAccessLogValve();
+
+        Response response = doRequest(Mode.ECHO_RESPONSE_HEADER, "test");
+        Assert.assertEquals("101", response.status);
+
+        awaitAccessLogEntries(1);
+        Assert.assertEquals(Collections.singletonList("101 0"), 
accessLog.entries);
+
+        response.socket.close();
+    }
+
+
+    /*
+     * As above but the upgrade is requested after startAsync(). The request 
must be logged once, when the asynchronous
+     * processing completes, not once for the initial processing and again for 
the completion.
+     */
+    @Test
+    public void testAccessLogAsyncUpgrade() throws Exception {
+        accessLog = new CapturingAccessLogValve();
+
+        Response response = doRequest(Mode.ASYNC_THEN_UPGRADE, "test");
+        assertEchoUpgrade(response);
+
+        awaitAccessLogEntries(1);
+        // Allow time for any (unexpected) duplicate entry
+        Thread.sleep(500);
+        Assert.assertEquals(Collections.singletonList("101 0"), 
accessLog.entries);
+    }
+
+
+    /*
+     * An async upgrade that fails is logged once with the error status.
+     */
+    @Test
+    public void testAccessLogAsyncUpgradeTimeout() throws Exception {
+        accessLog = new CapturingAccessLogValve();
+
+        Response response = doRequest(Mode.ASYNC_THEN_UPGRADE_TIMEOUT, "test");
+        assertConnectionClosed(response);
+
+        awaitAccessLogEntries(1);
+        Thread.sleep(500);
+        Assert.assertEquals(accessLog.entries.toString(), 1, 
accessLog.entries.size());
+        Assert.assertTrue(accessLog.entries.toString(), 
accessLog.entries.get(0).startsWith("500 "));
+    }
+
+
+    private void awaitAccessLogEntries(int expected) throws 
InterruptedException {
+        int count = 0;
+        while (accessLog.entries.size() < expected && count < 50) {
+            Thread.sleep(100);
+            count++;
+        }
+    }
+
+
+    private void awaitHandlerDestroyed() throws InterruptedException {
+        int count = 0;
+        while (!handlerDestroyed.get() && count < 50) {
+            Thread.sleep(100);
+            count++;
+        }
+    }
+
+
+    /*
+     * The application's HttpUpgradeHandler.destroy() throws an exception. The 
failure must not prevent the rest of the
+     * clean-up: the instance must still be destroyed and, more importantly, 
the processor must still be released which
+     * de-registers the connection from the per-protocol statistics. If it is 
not, the connection is leaked.
+     */
+    @Test
+    public void testDestroyThrowsException() throws Exception {
+        Response response = doRequest(Mode.DESTROY_THROWS, "test");
+
+        Assert.assertEquals("101", response.status);
+        response.writer.write(MESSAGE + CRLF);
+        response.writer.flush();
+        Assert.assertEquals(MESSAGE, response.reader.readLine());
+
+        Object groupInfo = getUpgradeGroupInfos().get("test");
+        Assert.assertNotNull(groupInfo);
+        Assert.assertEquals("The active connection must be registered", 1, 
getActiveUpgradeInfoCount(groupInfo));
+
+        response.socket.close();
+
+        int count = 0;
+        while (getActiveUpgradeInfoCount(groupInfo) != 0 && count < 50) {
+            Thread.sleep(100);
+            count++;
+        }
+        Assert.assertTrue("destroy() must be called after init()", 
handlerDestroyMethodCalled.get());
+        Assert.assertTrue("The handler instance must be destroyed", 
handlerDestroyed.get());
+        Assert.assertEquals("The processor must be released", 0, 
getActiveUpgradeInfoCount(groupInfo));
+    }
+
+
+    /*
+     * The upgraded connection must be removed from the per-protocol 
statistics when it closes. If it is not, the
+     * connection (and everything it references) is leaked.
+     */
+    @Test
+    public void testAsyncUpgradeInfoRemovedWhenConnectionCloses() throws 
Exception {
+        Response response = doRequest(Mode.ASYNC_THEN_UPGRADE, "test");
+
+        Assert.assertEquals("101", response.status);
+        Assert.assertEquals(GREETING, response.reader.readLine());
+        response.writer.write(MESSAGE + CRLF);
+        response.writer.flush();
+        Assert.assertEquals(MESSAGE, response.reader.readLine());
+
+        Map<String,?> infos = getUpgradeGroupInfos();
+        Assert.assertEquals(infos.toString(), 1, infos.size());
+        Object groupInfo = infos.get("test");
+        Assert.assertNotNull(groupInfo);
+        Assert.assertEquals("The active connection must be registered", 1, 
getActiveUpgradeInfoCount(groupInfo));
+
+        response.socket.close();
+
+        // Closing the connection is detected asynchronously
+        int count = 0;
+        while (getActiveUpgradeInfoCount(groupInfo) != 0 && count < 100) {
+            Thread.sleep(100);
+            count++;
+        }
+        Assert.assertEquals("The closed connection must be removed", 0, 
getActiveUpgradeInfoCount(groupInfo));
+        // The group is reused rather than a new one being created for each 
connection
+        Assert.assertEquals(1, getUpgradeGroupInfos().size());
+    }
+
+
+    /*
+     * The per-protocol state is keyed by the protocol name from the response 
(chosen by the application) and not the
+     * request (chosen by the client) so a client can't cause an unbounded 
number of entries to be created. Check that
+     * this is also the case when the upgrade is requested after startAsync().
+     */
+    @Test
+    public void testAsyncUpgradeGroupInfoNotKeyedByRequestHeader() throws 
Exception {
+        startServer(Mode.ASYNC_THEN_UPGRADE_DIFFERENT_HEADER);
+
+        for (String requestToken : new String[] { "client-token-1", 
"client-token-2", "client-token-3" }) {
+            Response response = sendRequest(requestToken, null);
+            Assert.assertEquals("101", response.status);
+            Assert.assertEquals("app-token", response.upgradeHeader);
+            Assert.assertEquals(GREETING, response.reader.readLine());
+            response.socket.close();
+        }
+
+        Map<String,?> infos = getUpgradeGroupInfos();
+        Assert.assertEquals(infos.toString(), 1, infos.size());
+        Assert.assertTrue(infos.toString(), infos.containsKey("app-token"));
+    }
+
+
+    /*
+     * The upgrade must not depend on keep-alive being enabled for the 
request. Here the connector only allows a single
+     * request per connection so keep-alive is disabled before the application 
is called. The response must not tell
+     * the client that the connection is going to be closed as the client is 
expecting the Connection header to
+     * contain upgrade (as set by the application).
+     */
+    @Test
+    public void testUpgradeWithKeepAliveDisabled() throws Exception {
+        
Assert.assertTrue(getTomcatInstance().getConnector().setProperty("maxKeepAliveRequests",
 "1"));
+
+        Response response = doRequest(Mode.ECHO_RESPONSE_HEADER, "test");
+
+        Assert.assertEquals("101", response.status);
+        Assert.assertEquals(Collections.singletonList("upgrade"), 
response.connectionHeaders);
+        response.writer.write(MESSAGE + CRLF);
+        response.writer.flush();
+        Assert.assertEquals(MESSAGE, response.reader.readLine());
+        Assert.assertTrue(getUpgradeGroupInfos().containsKey("test"));
+
+        response.socket.close();
+    }
+
+
+    /*
+     * As above but the upgrade is requested after startAsync() so completion 
of the upgrade is triggered by the
+     * completion of the asynchronous processing.
+     */
+    @Test
+    public void testAsyncUpgradeWithKeepAliveDisabled() throws Exception {
+        
Assert.assertTrue(getTomcatInstance().getConnector().setProperty("maxKeepAliveRequests",
 "1"));
+
+        Response response = doRequest(Mode.ASYNC_THEN_UPGRADE, "test");
+
+        Assert.assertFalse("upgrade() must not throw IllegalStateException", 
iseThrown.get());
+        Assert.assertEquals(Collections.singletonList("upgrade"), 
response.connectionHeaders);
+        assertEchoUpgrade(response);
+    }
+
+
+    /*
+     * With keep-alive enabled the response must only have the Connection 
header set by the application.
+     */
+    @Test
+    public void testUpgradeConnectionHeaderKeepAliveEnabled() throws Exception 
{
+        Response response = doRequest(Mode.ECHO_RESPONSE_HEADER, "test");
+
+        Assert.assertEquals("101", response.status);
+        Assert.assertEquals(Collections.singletonList("upgrade"), 
response.connectionHeaders);
+
+        response.socket.close();
+    }
+
+
+    /*
+     * The upgrade fails (no Upgrade header) with keep-alive disabled. This is 
not a protocol switch so the response
+     * must indicate that the connection will be closed.
+     */
+    @Test
+    public void testFailedUpgradeWithKeepAliveDisabled() throws Exception {
+        
Assert.assertTrue(getTomcatInstance().getConnector().setProperty("maxKeepAliveRequests",
 "1"));
+
+        Response response = doRequest(Mode.NO_RESPONSE_HEADER, "test");
+
+        Assert.assertEquals("500", response.status);
+        Assert.assertEquals(Collections.singletonList("close"), 
response.connectionHeaders);
+        assertConnectionClosed(response);
+        assertCleanedUp();
     }
 
 
@@ -247,8 +841,25 @@ public class TestUpgradeValidation extends TomcatBaseTest {
     }
 
 
+    private void assertEchoUpgrade(Response response) throws Exception {
+        Assert.assertEquals("101", response.status);
+        Assert.assertEquals("test", response.upgradeHeader);
+
+        // The handler writes first so this also checks the upgrade was not 
delayed until the client sent data
+        Assert.assertEquals(GREETING, response.reader.readLine());
+        response.writer.write(MESSAGE + CRLF);
+        response.writer.flush();
+        Assert.assertEquals(MESSAGE, response.reader.readLine());
+        Assert.assertTrue(getUpgradeGroupInfos().containsKey("test"));
+
+        response.socket.close();
+    }
+
+
     private void assertCleanedUp() {
         Assert.assertFalse("HttpUpgradeHandler.init() must not be called", 
handlerInitCalled.get());
+        Assert.assertFalse("HttpUpgradeHandler.destroy() must not be called if 
init() was not called",
+                handlerDestroyMethodCalled.get());
         Assert.assertTrue("The HttpUpgradeHandler instance must be destroyed", 
handlerDestroyed.get());
     }
 
@@ -269,6 +880,13 @@ public class TestUpgradeValidation extends TomcatBaseTest {
     }
 
 
+    private int getActiveUpgradeInfoCount(Object groupInfo) throws Exception {
+        Field field = UpgradeGroupInfo.class.getDeclaredField("upgradeInfos");
+        field.setAccessible(true);
+        return ((Set<?>) field.get(groupInfo)).size();
+    }
+
+
     @SuppressWarnings("unchecked")
     private Map<String,?> getUpgradeGroupInfos() throws Exception {
         AbstractHttp11Protocol<?> protocol =
@@ -280,6 +898,17 @@ public class TestUpgradeValidation extends TomcatBaseTest {
 
 
     private Response doRequest(Mode mode, String requestUpgrade) throws 
Exception {
+        return doRequest(mode, requestUpgrade, null);
+    }
+
+
+    private Response doRequest(Mode mode, String requestUpgrade, String body) 
throws Exception {
+        startServer(mode);
+        return sendRequest(requestUpgrade, body);
+    }
+
+
+    private void startServer(Mode mode) throws Exception {
         Tomcat tomcat = getTomcatInstance();
 
         // No file system docBase required
@@ -288,37 +917,57 @@ public class TestUpgradeValidation extends TomcatBaseTest 
{
         Tomcat.addServlet(ctx, "servlet", new 
UpgradeServlet(mode)).setAsyncSupported(true);
         ctx.addServletMapping("/", "servlet");
 
+        if (accessLog != null) {
+            ctx.getPipeline().addValve(accessLog);
+        }
+
         tomcat.start();
+    }
+
 
+    private Response sendRequest(String requestUpgrade, String body) throws 
Exception {
         Socket socket = SocketFactory.getDefault().createSocket("localhost", 
getPort());
         socket.setSoTimeout(5000);
 
         Writer writer = new OutputStreamWriter(socket.getOutputStream(), 
StandardCharsets.UTF_8);
         BufferedReader reader = new BufferedReader(new 
InputStreamReader(socket.getInputStream(), StandardCharsets.UTF_8));
 
-        writer.write("GET / HTTP/1.1" + CRLF);
+        if (body == null) {
+            writer.write("GET / HTTP/1.1" + CRLF);
+        } else {
+            writer.write("POST / HTTP/1.1" + CRLF);
+        }
         writer.write("Host: whatever" + CRLF);
         writer.write("Connection: Upgrade" + CRLF);
         writer.write("Upgrade: " + requestUpgrade + CRLF);
+        if (body != null) {
+            writer.write("Content-Length: " + body.length() + CRLF);
+        }
         writer.write(CRLF);
+        if (body != null) {
+            writer.write(body);
+        }
         writer.flush();
 
         String statusLine = reader.readLine();
         if (statusLine == null) {
             // Connection closed without a response
-            return new Response(socket, writer, reader, null, null);
+            return new Response(socket, writer, reader, null, null, 
Collections.emptyList());
         }
 
         String upgradeHeader = null;
+        List<String> connectionHeaders = new ArrayList<>();
         String line = reader.readLine();
         while (line != null && line.length() > 0) {
             if (line.regionMatches(true, 0, "Upgrade:", 0, 8)) {
                 upgradeHeader = line.substring(8).trim();
+            } else if (line.regionMatches(true, 0, "Connection:", 0, 11)) {
+                connectionHeaders.add(line.substring(11).trim());
             }
             line = reader.readLine();
         }
 
-        return new Response(socket, writer, reader, getStatusCode(statusLine), 
upgradeHeader);
+        return new Response(socket, writer, reader, getStatusCode(statusLine), 
upgradeHeader, connectionHeaders);
     }
 
 
@@ -328,13 +977,16 @@ public class TestUpgradeValidation extends TomcatBaseTest 
{
         private final BufferedReader reader;
         private final String status;
         private final String upgradeHeader;
+        private final List<String> connectionHeaders;
 
-        Response(Socket socket, Writer writer, BufferedReader reader, String 
status, String upgradeHeader) {
+        Response(Socket socket, Writer writer, BufferedReader reader, String 
status, String upgradeHeader,
+                List<String> connectionHeaders) {
             this.socket = socket;
             this.writer = writer;
             this.reader = reader;
             this.status = status;
             this.upgradeHeader = upgradeHeader;
+            this.connectionHeaders = connectionHeaders;
         }
     }
 
@@ -345,6 +997,28 @@ public class TestUpgradeValidation extends TomcatBaseTest {
         DIFFERENT_RESPONSE_HEADER,
         UPGRADE_THEN_ASYNC,
         ASYNC_THEN_UPGRADE,
+        ASYNC_THEN_UPGRADE_APP_THREAD,
+        ASYNC_COMPLETE_THEN_UPGRADE,
+        ASYNC_COMPLETE_THEN_UPGRADE_APP_THREAD,
+        ASYNC_THEN_UPGRADE_TIMEOUT,
+        ASYNC_THEN_UPGRADE_DIFFERENT_HEADER,
+        ASYNC_NO_RESPONSE_HEADER,
+        ASYNC_READ_COMPLETE_THEN_UPGRADE,
+        ASYNC_READ_PARTIAL_THEN_UPGRADE,
+        ASYNC_UNREAD_BODY_THEN_UPGRADE,
+        ASYNC_WRITE_UNCOMMITTED_THEN_UPGRADE,
+        ASYNC_WRITE_COMMITTED_THEN_UPGRADE,
+        ASYNC_DISPATCH_THEN_UPGRADE,
+        ASYNC_DOUBLE_UPGRADE,
+        ASYNC_UPGRADE_CLIENT_DISCONNECT,
+        ASYNC_UPGRADE_IN_TIMEOUT,
+        ASYNC_UPGRADE_THEN_PAUSE,
+        ASYNC_UPGRADE_THEN_EXCEPTION,
+        ASYNC_UPGRADE_ERROR_LISTENER_COMPLETE,
+        ASYNC_UPGRADE_IN_ERROR_LISTENER,
+        ASYNC_UPGRADE_IN_TIMEOUT_NO_COMPLETE,
+        DOUBLE_UPGRADE,
+        DESTROY_THROWS,
         EXCEPTION_AFTER_UPGRADE,
         COMMIT_THEN_UPGRADE,
         STATUS_CHANGED_AFTER_UPGRADE
@@ -361,8 +1035,19 @@ public class TestUpgradeValidation extends TomcatBaseTest 
{
             this.mode = mode;
         }
 
+        @Override
+        protected void doPost(HttpServletRequest req, HttpServletResponse 
resp) throws ServletException, IOException {
+            doGet(req, resp);
+        }
+
         @Override
         protected void doGet(HttpServletRequest req, HttpServletResponse resp) 
throws ServletException, IOException {
+            if (req.getDispatcherType() == DispatcherType.ASYNC) {
+                // The target of the dispatch
+                resp.setContentType("text/plain");
+                resp.getWriter().write("dispatched");
+                return;
+            }
             switch (mode) {
                 case NO_RESPONSE_HEADER:
                     req.upgrade(TestHandler.class);
@@ -370,6 +1055,7 @@ public class TestUpgradeValidation extends TomcatBaseTest {
                 case ECHO_RESPONSE_HEADER:
                     // Only a single protocol is requested so it is safe to 
echo it
                     resp.setHeader("Upgrade", req.getHeader("Upgrade"));
+                    resp.setHeader("Connection", "upgrade");
                     req.upgrade(EchoHandler.class);
                     break;
                 case DIFFERENT_RESPONSE_HEADER:
@@ -385,15 +1071,365 @@ public class TestUpgradeValidation extends 
TomcatBaseTest {
                         iseThrown.set(true);
                     }
                     break;
-                case ASYNC_THEN_UPGRADE:
+                case ASYNC_THEN_UPGRADE: {
+                    resp.setHeader("Upgrade", req.getHeader("Upgrade"));
+                    resp.setHeader("Connection", "upgrade");
+                    AsyncContext ac = req.startAsync();
+                    ac.addListener(new CompleteListener());
+                    try {
+                        req.upgrade(GreetingEchoHandler.class);
+                    } catch (IllegalStateException ise) {
+                        iseThrown.set(true);
+                    }
+                    ac.complete();
+                    break;
+                }
+                case ASYNC_THEN_UPGRADE_APP_THREAD: {
+                    resp.setHeader("Upgrade", req.getHeader("Upgrade"));
+                    AsyncContext ac = req.startAsync();
+                    ac.addListener(new CompleteListener());
+                    new Thread(() -> {
+                        try {
+                            req.upgrade(GreetingEchoHandler.class);
+                        } catch (IllegalStateException ise) {
+                            iseThrown.set(true);
+                        } catch (IOException | ServletException e) {
+                            throw new IllegalStateException(e);
+                        } finally {
+                            upgradeCalled.countDown();
+                        }
+                        ac.complete();
+                    }).start();
+                    break;
+                }
+                case ASYNC_COMPLETE_THEN_UPGRADE: {
+                    resp.setHeader("Upgrade", req.getHeader("Upgrade"));
                     AsyncContext ac = req.startAsync();
+                    ac.complete();
                     try {
                         req.upgrade(TestHandler.class);
                     } catch (IllegalStateException ise) {
                         iseThrown.set(true);
                     }
+                    break;
+                }
+                case ASYNC_COMPLETE_THEN_UPGRADE_APP_THREAD: {
+                    resp.setHeader("Upgrade", req.getHeader("Upgrade"));
+                    AsyncContext ac = req.startAsync();
+                    new Thread(() -> {
+                        try {
+                            ac.complete();
+                            // Allow the container to complete the processing 
and recycle the request
+                            Thread.sleep(500);
+                            req.upgrade(TestHandler.class);
+                        } catch (IllegalStateException ise) {
+                            iseThrown.set(true);
+                        } catch (InterruptedException | IOException | 
ServletException e) {
+                            throw new IllegalStateException(e);
+                        } finally {
+                            upgradeCalled.countDown();
+                        }
+                    }).start();
+                    break;
+                }
+                case ASYNC_THEN_UPGRADE_TIMEOUT: {
+                    resp.setHeader("Upgrade", req.getHeader("Upgrade"));
+                    AsyncContext ac = req.startAsync();
+                    ac.setTimeout(500);
+                    // Never completed
+                    req.upgrade(TestHandler.class);
+                    break;
+                }
+                case ASYNC_THEN_UPGRADE_DIFFERENT_HEADER: {
+                    resp.setHeader("Upgrade", "app-token");
+                    AsyncContext ac = req.startAsync();
+                    req.upgrade(GreetingEchoHandler.class);
+                    ac.complete();
+                    break;
+                }
+                case ASYNC_NO_RESPONSE_HEADER: {
+                    AsyncContext ac = req.startAsync();
+                    req.upgrade(TestHandler.class);
+                    ac.complete();
+                    break;
+                }
+                case ASYNC_READ_COMPLETE_THEN_UPGRADE: {
+                    resp.setHeader("Upgrade", req.getHeader("Upgrade"));
+                    AsyncContext ac = req.startAsync();
+                    ServletInputStream sis = req.getInputStream();
+                    sis.setReadListener(new ReadListener() {
+                        private final StringBuilder sb = new StringBuilder();
+
+                        @Override
+                        public void onDataAvailable() throws IOException {
+                            byte[] buffer = new byte[1024];
+                            while (sis.isReady() && !sis.isFinished()) {
+                                int read = sis.read(buffer);
+                                if (read > 0) {
+                                    sb.append(new String(buffer, 0, read, 
StandardCharsets.UTF_8));
+                                }
+                            }
+                        }
+
+                        @Override
+                        public void onAllDataRead() throws IOException {
+                            bodyRead.set(sb.toString());
+                            try {
+                                req.upgrade(GreetingEchoHandler.class);
+                            } catch (IllegalStateException | ServletException 
e) {
+                                iseThrown.set(true);
+                            }
+                            ac.complete();
+                        }
+
+                        @Override
+                        public void onError(Throwable t) {
+                            ac.complete();
+                        }
+                    });
+                    break;
+                }
+                case ASYNC_READ_PARTIAL_THEN_UPGRADE: {
+                    resp.setHeader("Upgrade", req.getHeader("Upgrade"));
+                    AsyncContext ac = req.startAsync();
+                    ServletInputStream sis = req.getInputStream();
+                    sis.setReadListener(new ReadListener() {
+                        private boolean upgraded = false;
+
+                        @Override
+                        public void onDataAvailable() throws IOException {
+                            if (upgraded) {
+                                return;
+                            }
+                            if (sis.isReady()) {
+                                // Read only part of the body
+                                byte[] buffer = new byte[PARTIAL_READ_SIZE];
+                                int read = sis.read(buffer);
+                                bodyRead.set(new String(buffer, 0, read, 
StandardCharsets.UTF_8));
+                            }
+                            upgraded = true;
+                            try {
+                                req.upgrade(GreetingEchoHandler.class);
+                            } catch (IllegalStateException | ServletException 
e) {
+                                iseThrown.set(true);
+                            }
+                            ac.complete();
+                        }
+
+                        @Override
+                        public void onAllDataRead() {
+                            // NO-OP
+                        }
+
+                        @Override
+                        public void onError(Throwable t) {
+                            ac.complete();
+                        }
+                    });
+                    break;
+                }
+                case ASYNC_UNREAD_BODY_THEN_UPGRADE: {
+                    resp.setHeader("Upgrade", req.getHeader("Upgrade"));
+                    AsyncContext ac = req.startAsync();
+                    // The request body is not read at all
+                    req.upgrade(GreetingEchoHandler.class);
+                    ac.complete();
+                    break;
+                }
+                case ASYNC_WRITE_UNCOMMITTED_THEN_UPGRADE: {
+                    resp.setHeader("Upgrade", req.getHeader("Upgrade"));
+                    AsyncContext ac = req.startAsync();
+                    ServletOutputStream sos = resp.getOutputStream();
+                    sos.setWriteListener(new WriteListener() {
+                        private boolean written = false;
+
+                        @Override
+                        public void onWritePossible() throws IOException {
+                            if (!written) {
+                                written = true;
+                                // Small enough to remain in the response 
buffer. Nothing is committed.
+                                
sos.write(UNCOMMITTED_DATA.getBytes(StandardCharsets.UTF_8));
+                                Assert.assertFalse(resp.isCommitted());
+                                try {
+                                    req.upgrade(GreetingEchoHandler.class);
+                                } catch (IllegalStateException | 
ServletException e) {
+                                    iseThrown.set(true);
+                                }
+                                ac.complete();
+                            }
+                        }
+
+                        @Override
+                        public void onError(Throwable t) {
+                            ac.complete();
+                        }
+                    });
+                    break;
+                }
+                case ASYNC_WRITE_COMMITTED_THEN_UPGRADE: {
+                    resp.setHeader("Upgrade", req.getHeader("Upgrade"));
+                    AsyncContext ac = req.startAsync();
+                    ServletOutputStream sos = resp.getOutputStream();
+                    sos.setWriteListener(new WriteListener() {
+                        private boolean written = false;
+
+                        @Override
+                        public void onWritePossible() throws IOException {
+                            if (!written) {
+                                written = true;
+                                // Much larger than the response buffer so the 
response is committed
+                                byte[] data = new byte[64 * 1024];
+                                Arrays.fill(data, (byte) 'x');
+                                sos.write(data);
+                                Assert.assertTrue(resp.isCommitted());
+                                try {
+                                    req.upgrade(GreetingEchoHandler.class);
+                                } catch (IllegalStateException | 
ServletException e) {
+                                    iseThrown.set(true);
+                                }
+                                upgradeCalled.countDown();
+                            }
+                            if (sos.isReady()) {
+                                ac.complete();
+                            }
+                        }
+
+                        @Override
+                        public void onError(Throwable t) {
+                            ac.complete();
+                        }
+                    });
+                    break;
+                }
+                case ASYNC_DISPATCH_THEN_UPGRADE: {
+                    resp.setHeader("Upgrade", req.getHeader("Upgrade"));
+                    AsyncContext ac = req.startAsync();
+                    ac.dispatch("/dispatched");
+                    try {
+                        req.upgrade(GreetingEchoHandler.class);
+                    } catch (IllegalStateException ise) {
+                        iseThrown.set(true);
+                    }
+                    break;
+                }
+                case ASYNC_DOUBLE_UPGRADE: {
+                    resp.setHeader("Upgrade", req.getHeader("Upgrade"));
+                    AsyncContext ac = req.startAsync();
+                    req.upgrade(GreetingEchoHandler.class);
+                    try {
+                        req.upgrade(GreetingEchoHandler.class);
+                    } catch (IllegalStateException ise) {
+                        iseThrown.set(true);
+                    }
                     ac.complete();
                     break;
+                }
+                case ASYNC_UPGRADE_CLIENT_DISCONNECT: {
+                    resp.setHeader("Upgrade", req.getHeader("Upgrade"));
+                    resp.setHeader("Connection", "upgrade");
+                    AsyncContext ac = req.startAsync();
+                    req.upgrade(TestHandler.class);
+                    upgradeCalled.countDown();
+                    // Wait for the client to go away before completing so the 
response can't be written
+                    new Thread(() -> {
+                        try {
+                            clientDisconnected.await(10, TimeUnit.SECONDS);
+                        } catch (InterruptedException e) {
+                            // Ignore. Complete anyway.
+                        }
+                        ac.complete();
+                    }).start();
+                    break;
+                }
+                case ASYNC_UPGRADE_IN_TIMEOUT:
+                case ASYNC_UPGRADE_IN_TIMEOUT_NO_COMPLETE: {
+                    boolean complete = (mode == Mode.ASYNC_UPGRADE_IN_TIMEOUT);
+                    Class<? extends HttpUpgradeHandler> handlerClass =
+                            complete ? GreetingEchoHandler.class : 
TestHandler.class;
+                    AsyncContext ac = req.startAsync();
+                    ac.setTimeout(500);
+                    ac.addListener(new AsyncListener() {
+                        @Override
+                        public void onTimeout(AsyncEvent event) throws 
IOException {
+                            HttpServletRequest asyncReq = (HttpServletRequest) 
event.getSuppliedRequest();
+                            HttpServletResponse asyncResp = 
(HttpServletResponse) event.getSuppliedResponse();
+                            asyncResp.setHeader("Upgrade", 
asyncReq.getHeader("Upgrade"));
+                            asyncResp.setHeader("Connection", "upgrade");
+                            try {
+                                asyncReq.upgrade(handlerClass);
+                            } catch (IllegalStateException | ServletException 
e) {
+                                iseThrown.set(true);
+                            }
+                            upgradeCalled.countDown();
+                            if (complete) {
+                                event.getAsyncContext().complete();
+                            }
+                        }
+
+                        @Override
+                        public void onComplete(AsyncEvent event) {
+                            asyncCompleteCalled.set(true);
+                        }
+
+                        @Override
+                        public void onError(AsyncEvent event) {
+                            // NO-OP
+                        }
+
+                        @Override
+                        public void onStartAsync(AsyncEvent event) {
+                            // NO-OP
+                        }
+                    });
+                    break;
+                }
+                case ASYNC_UPGRADE_THEN_PAUSE: {
+                    resp.setHeader("Upgrade", req.getHeader("Upgrade"));
+                    resp.setHeader("Connection", "upgrade");
+                    AsyncContext ac = req.startAsync();
+                    req.upgrade(TestHandler.class);
+                    upgradeCalled.countDown();
+                    new Thread(() -> {
+                        // The protocol is paused before the asynchronous 
processing completes
+                        connectorToPause.pause();
+                        ac.complete();
+                    }).start();
+                    break;
+                }
+                case ASYNC_UPGRADE_THEN_EXCEPTION: {
+                    resp.setHeader("Upgrade", req.getHeader("Upgrade"));
+                    resp.setHeader("Connection", "upgrade");
+                    req.startAsync();
+                    req.upgrade(TestHandler.class);
+                    throw new ServletException("Deliberate failure after 
upgrade");
+                }
+                case ASYNC_UPGRADE_ERROR_LISTENER_COMPLETE: {
+                    resp.setHeader("Upgrade", req.getHeader("Upgrade"));
+                    resp.setHeader("Connection", "upgrade");
+                    AsyncContext ac = req.startAsync();
+                    ac.addListener(new ErrorListener(false));
+                    req.upgrade(TestHandler.class);
+                    throw new ServletException("Deliberate failure after 
upgrade");
+                }
+                case ASYNC_UPGRADE_IN_ERROR_LISTENER: {
+                    AsyncContext ac = req.startAsync();
+                    ac.addListener(new ErrorListener(true));
+                    throw new ServletException("Deliberate failure before 
upgrade");
+                }
+                case DESTROY_THROWS:
+                    resp.setHeader("Upgrade", req.getHeader("Upgrade"));
+                    resp.setHeader("Connection", "upgrade");
+                    req.upgrade(DestroyFailsHandler.class);
+                    break;
+                case DOUBLE_UPGRADE:
+                    resp.setHeader("Upgrade", req.getHeader("Upgrade"));
+                    req.upgrade(GreetingEchoHandler.class);
+                    try {
+                        req.upgrade(GreetingEchoHandler.class);
+                    } catch (IllegalStateException ise) {
+                        iseThrown.set(true);
+                    }
+                    break;
                 case COMMIT_THEN_UPGRADE:
                     // Once committed, the Upgrade header can no longer be set 
so the validation at commit time has
                     // already been missed
@@ -433,7 +1469,7 @@ public class TestUpgradeValidation extends TomcatBaseTest {
 
         @Override
         public void destroy() {
-            // NO-OP
+            handlerDestroyMethodCalled.set(true);
         }
 
         @PreDestroy
@@ -443,6 +1479,91 @@ public class TestUpgradeValidation extends TomcatBaseTest 
{
     }
 
 
+    /*
+     * Completes the asynchronous processing when an error occurs, optionally 
after calling upgrade().
+     */
+    private static class ErrorListener implements AsyncListener {
+
+        private final boolean upgrade;
+
+        ErrorListener(boolean upgrade) {
+            this.upgrade = upgrade;
+        }
+
+        @Override
+        public void onError(AsyncEvent event) throws IOException {
+            if (upgrade) {
+                HttpServletRequest asyncReq = (HttpServletRequest) 
event.getSuppliedRequest();
+                HttpServletResponse asyncResp = (HttpServletResponse) 
event.getSuppliedResponse();
+                asyncResp.setHeader("Upgrade", asyncReq.getHeader("Upgrade"));
+                asyncResp.setHeader("Connection", "upgrade");
+                try {
+                    asyncReq.upgrade(TestHandler.class);
+                } catch (IllegalStateException | ServletException e) {
+                    iseThrown.set(true);
+                }
+            }
+            upgradeCalled.countDown();
+            event.getAsyncContext().complete();
+        }
+
+        @Override
+        public void onComplete(AsyncEvent event) {
+            asyncCompleteCalled.set(true);
+        }
+
+        @Override
+        public void onTimeout(AsyncEvent event) {
+            // NO-OP
+        }
+
+        @Override
+        public void onStartAsync(AsyncEvent event) {
+            // NO-OP
+        }
+    }
+
+
+    private static class CapturingAccessLogValve extends 
AbstractAccessLogValve {
+
+        private final List<String> entries = new CopyOnWriteArrayList<>();
+
+        CapturingAccessLogValve() {
+            // Status code and bytes sent
+            setPattern("%s %B");
+        }
+
+        @Override
+        protected void log(CharArrayWriter message) {
+            entries.add(message.toString().trim());
+        }
+    }
+
+
+    private static class CompleteListener implements AsyncListener {
+
+        @Override
+        public void onComplete(AsyncEvent event) {
+            asyncCompleteCalled.set(true);
+        }
+
+        @Override
+        public void onTimeout(AsyncEvent event) {
+            // NO-OP
+        }
+
+        @Override
+        public void onError(AsyncEvent event) {
+            // NO-OP
+        }
+
+        @Override
+        public void onStartAsync(AsyncEvent event) {
+            // NO-OP
+        }
+    }
+
+
     public static class EchoHandler implements HttpUpgradeHandler {
 
         @Override
@@ -465,4 +1586,70 @@ public class TestUpgradeValidation extends TomcatBaseTest 
{
             // NO-OP
         }
     }
+
+
+    /*
+     * Echoes data until the client closes the connection. destroy() always 
fails.
+     */
+    public static class DestroyFailsHandler implements HttpUpgradeHandler {
+
+        @Override
+        public void init(WebConnection connection) {
+            try (ServletInputStream sis = connection.getInputStream();
+                    ServletOutputStream sos = connection.getOutputStream()) {
+                byte[] buffer = new byte[8192];
+                int read;
+                while ((read = sis.read(buffer)) >= 0) {
+                    sos.write(buffer, 0, read);
+                    sos.flush();
+                }
+            } catch (IOException ioe) {
+                throw new IllegalStateException(ioe);
+            }
+        }
+
+        @Override
+        public void destroy() {
+            handlerDestroyMethodCalled.set(true);
+            throw new IllegalStateException("Deliberate failure in destroy()");
+        }
+
+        @PreDestroy
+        public void preDestroy() {
+            handlerDestroyed.set(true);
+        }
+    }
+
+
+    /*
+     * Writes before it reads so a test can tell whether the upgrade was 
completed before the client sent any data.
+     */
+    public static class GreetingEchoHandler implements HttpUpgradeHandler {
+
+        public GreetingEchoHandler() {
+            greetingHandlersCreated.incrementAndGet();
+        }
+
+        @Override
+        public void init(WebConnection connection) {
+            try (ServletInputStream sis = connection.getInputStream();
+                    ServletOutputStream sos = connection.getOutputStream()) {
+                sos.write((GREETING + CRLF).getBytes(StandardCharsets.UTF_8));
+                sos.flush();
+                byte[] buffer = new byte[8192];
+                int read;
+                while ((read = sis.read(buffer)) >= 0) {
+                    sos.write(buffer, 0, read);
+                    sos.flush();
+                }
+            } catch (IOException ioe) {
+                throw new IllegalStateException(ioe);
+            }
+        }
+
+        @Override
+        public void destroy() {
+            // NO-OP
+        }
+    }
 }
diff --git a/test/org/apache/coyote/http2/TestHttp2Upgrade.java 
b/test/org/apache/coyote/http2/TestHttp2Upgrade.java
new file mode 100644
index 0000000000..12fb74ceba
--- /dev/null
+++ b/test/org/apache/coyote/http2/TestHttp2Upgrade.java
@@ -0,0 +1,166 @@
+/*
+ *  Licensed to the Apache Software Foundation (ASF) under one or more
+ *  contributor license agreements.  See the NOTICE file distributed with
+ *  this work for additional information regarding copyright ownership.
+ *  The ASF licenses this file to You under the Apache License, Version 2.0
+ *  (the "License"); you may not use this file except in compliance with
+ *  the License.  You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ *  Unless required by applicable law or agreed to in writing, software
+ *  distributed under the License is distributed on an "AS IS" BASIS,
+ *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ *  See the License for the specific language governing permissions and
+ *  limitations under the License.
+ */
+package org.apache.coyote.http2;
+
+import java.io.IOException;
+import java.nio.ByteBuffer;
+import java.nio.charset.StandardCharsets;
+import java.util.concurrent.CountDownLatch;
+import java.util.concurrent.TimeUnit;
+import java.util.concurrent.atomic.AtomicBoolean;
+import java.util.concurrent.atomic.AtomicReference;
+
+import jakarta.annotation.PreDestroy;
+import jakarta.servlet.http.HttpServlet;
+import jakarta.servlet.http.HttpServletRequest;
+import jakarta.servlet.http.HttpServletResponse;
+import jakarta.servlet.http.HttpUpgradeHandler;
+import jakarta.servlet.http.WebConnection;
+
+import org.junit.Assert;
+import org.junit.Test;
+
+import org.apache.catalina.Context;
+import org.apache.catalina.LifecycleException;
+import org.apache.catalina.startup.Tomcat;
+
+public class TestHttp2Upgrade extends Http2TestBase {
+
+    private final UpgradeAttemptServlet servlet = new UpgradeAttemptServlet();
+
+    /*
+     * HTTP upgrade (HttpServletRequest.upgrade()) is not supported over 
HTTP/2. The attempt to upgrade must fail and
+     * the HttpUpgradeHandler instance, that has been created by the time the 
failure is detected, must be destroyed
+     * rather than leaked.
+     */
+    @Test
+    public void testUpgradeNotSupported() throws Exception {
+        http2Connect();
+
+        byte[] frameHeader = new byte[9];
+        ByteBuffer headersPayload = ByteBuffer.allocate(128);
+        buildGetRequest(frameHeader, headersPayload, null, 3, "/upgrade");
+        writeFrame(frameHeader, headersPayload);
+
+        // Response headers and body
+        parser.readFrame();
+        parser.readFrame();
+
+        Assert.assertTrue(servlet.attempted.await(5, TimeUnit.SECONDS));
+        Assert.assertNotNull("The upgrade attempt must fail", 
servlet.failure.get());
+        Assert.assertTrue(servlet.failure.get().toString(),
+                servlet.failure.get() instanceof 
UnsupportedOperationException);
+        Assert.assertTrue("The HttpUpgradeHandler must have been created", 
UpgradeAttemptHandler.created.get());
+        Assert.assertTrue("The HttpUpgradeHandler must be destroyed", 
UpgradeAttemptHandler.destroyed.get());
+        Assert.assertFalse("The HttpUpgradeHandler must not be initialised", 
UpgradeAttemptHandler.initialised.get());
+        Assert.assertFalse("destroy() must not be called if init() was not 
called",
+                UpgradeAttemptHandler.destroyMethodCalled.get());
+    }
+
+
+    /*
+     * The h2c upgrade response (101) must not contain a Connection: close 
header when keep-alive is disabled for the
+     * request. The Connection header must be the Upgrade header required for 
the protocol switch.
+     */
+    @Test
+    public void testH2cUpgradeWithKeepAliveDisabled() throws Exception {
+        enableHttp2();
+        
Assert.assertTrue(getTomcatInstance().getConnector().setProperty("maxKeepAliveRequests",
 "1"));
+        configureAndStartWebApplication();
+        openClientConnection();
+        doHttpUpgrade(DEFAULT_CONNECTION_HEADER_VALUE, "h2c", 
EMPTY_HTTP2_SETTINGS_HEADER, false);
+
+        String[] headers = readHttpResponseHeaders();
+        Assert.assertTrue(headers[0], headers[0].startsWith("HTTP/1.1 101 "));
+        boolean upgradeFound = false;
+        for (String header : headers) {
+            Assert.assertFalse(header, header.equalsIgnoreCase("Connection: 
close"));
+            if (header.equalsIgnoreCase("Connection: Upgrade")) {
+                upgradeFound = true;
+            }
+        }
+        Assert.assertTrue("Connection: Upgrade not found", upgradeFound);
+
+        // The upgrade must have completed
+        sendClientPreface();
+        validateHttp2InitialResponse();
+    }
+
+
+    @Override
+    protected void configureAndStartWebApplication() throws LifecycleException 
{
+        Tomcat tomcat = getTomcatInstance();
+
+        Context ctxt = getProgrammaticRootContext();
+        Tomcat.addServlet(ctxt, "simple", new SimpleServlet());
+        ctxt.addServletMapping("/simple", "simple");
+        Tomcat.addServlet(ctxt, "upgrade", servlet);
+        ctxt.addServletMapping("/upgrade", "upgrade");
+
+        tomcat.start();
+    }
+
+
+    private static class UpgradeAttemptServlet extends HttpServlet {
+
+        private static final long serialVersionUID = 1L;
+
+        private final transient CountDownLatch attempted = new 
CountDownLatch(1);
+        private final transient AtomicReference<Throwable> failure = new 
AtomicReference<>();
+
+        @Override
+        protected void doGet(HttpServletRequest req, HttpServletResponse resp) 
throws IOException {
+            try {
+                req.upgrade(UpgradeAttemptHandler.class);
+            } catch (Throwable t) {
+                failure.set(t);
+            }
+            resp.setContentType("text/plain");
+            resp.setContentLength(2);
+            
resp.getOutputStream().write("OK".getBytes(StandardCharsets.ISO_8859_1));
+            attempted.countDown();
+        }
+    }
+
+
+    public static class UpgradeAttemptHandler implements HttpUpgradeHandler {
+
+        static final AtomicBoolean created = new AtomicBoolean();
+        static final AtomicBoolean initialised = new AtomicBoolean();
+        static final AtomicBoolean destroyed = new AtomicBoolean();
+        static final AtomicBoolean destroyMethodCalled = new AtomicBoolean();
+
+        public UpgradeAttemptHandler() {
+            created.set(true);
+        }
+
+        @Override
+        public void init(WebConnection connection) {
+            initialised.set(true);
+        }
+
+        @Override
+        public void destroy() {
+            destroyMethodCalled.set(true);
+        }
+
+        @PreDestroy
+        public void preDestroy() {
+            destroyed.set(true);
+        }
+    }
+}
diff --git a/webapps/docs/changelog.xml b/webapps/docs/changelog.xml
index 82fb94b0ee..81514f66d0 100644
--- a/webapps/docs/changelog.xml
+++ b/webapps/docs/changelog.xml
@@ -258,6 +258,27 @@
         500 response rather than processing it using a URL that the remaining
         rewrite rules have not been applied to. (markt)
       </fix>
+      <update>
+        Allow <code>HttpServletRequest.upgrade()</code> to be called after
+        <code>startAsync()</code> provided it is called before
+        <code>AsyncContext.complete()</code> or
+        <code>AsyncContext.dispatch()</code> and before an asynchronous error
+        has occurred. The upgrade takes place when the
+        asynchronous processing completes, regardless of whether keep-alive is
+        enabled for the request. (markt)
+      </update>
+      <fix>
+        Ensure that <code>HttpServletRequest.upgrade()</code> can only be 
called
+        once per request. A second call previously created a second
+        <code>HttpUpgradeHandler</code> instance that was never destroyed.
+        (markt)
+      </fix>
+      <fix>
+        Ensure that the <code>HttpUpgradeHandler</code> instance created by
+        <code>HttpServletRequest.upgrade()</code> is destroyed if the upgrade
+        fails because the protocol in use, such as AJP or HTTP/2, does not
+        support HTTP upgrade. (markt)
+      </fix>
     </changelog>
   </subsection>
   <subsection name="Coyote">
@@ -420,6 +441,26 @@
         application still owned them. The stream is now closed once 
asynchronous
         processing ends. (markt)
       </fix>
+      <fix>
+        Do not add a <code>Connection: close</code> header to an HTTP
+        <code>101</code> (switching protocols) response when keep-alive has 
been
+        disabled for the request. The header contradicted the
+        <code>Connection: upgrade</code> header required by the protocol being
+        switched to and could cause the client to reject the upgrade. (markt)
+      </fix>
+      <fix>
+        Ensure that the <code>HttpUpgradeHandler</code> instance is destroyed,
+        and that the processor that handled the HTTP request is not released
+        twice, if a failure occurs after the HTTP request has been processed 
but
+        before the upgrade processor has taken ownership of the handler. 
(markt)
+      </fix>
+      <fix>
+        Ensure that an exception thrown by
+        <code>HttpUpgradeHandler.destroy()</code> does not prevent the
+        connection and its processor from being cleaned up. Also ensure that
+        <code>destroy()</code> is only called if <code>init()</code> was called
+        for the handler. (markt)
+      </fix>
     </changelog>
   </subsection>
   <subsection name="Jasper">


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

Reply via email to