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

commit 5dcb9ecae31ae46652f17d4802714a4ac97d0d6f
Author: Mark Thomas <[email protected]>
AuthorDate: Wed Nov 25 23:20:42 2026 +0000

    Bind the web application context when calling AsyncListener.onError()
    
    AsyncContextImpl.setErrorState() is called from several places and not all 
of
    them bind the web application's context. In particular, when an asynchronous
    dispatch fails, onError() was called using the class loader of the container
    thread rather than the web application's. Bind the context around the 
listener
    calls, as is already done for onComplete() and onTimeout().
    
    Co-Authored-By: Claude Sonnet 5.5 <[email protected]>
---
 .../org/apache/catalina/core/AsyncContextImpl.java | 25 +++++---
 .../apache/catalina/core/TestAsyncContextImpl.java | 70 ++++++++++++++++++++++
 webapps/docs/changelog.xml                         |  5 ++
 3 files changed, 92 insertions(+), 8 deletions(-)

diff --git a/java/org/apache/catalina/core/AsyncContextImpl.java 
b/java/org/apache/catalina/core/AsyncContextImpl.java
index b55d75d13d..375c347191 100644
--- a/java/org/apache/catalina/core/AsyncContextImpl.java
+++ b/java/org/apache/catalina/core/AsyncContextImpl.java
@@ -565,14 +565,23 @@ public class AsyncContextImpl implements AsyncContext, 
AsyncContextCallback {
             AsyncEvent errorEvent =
                     new AsyncEvent(event.getAsyncContext(), 
event.getSuppliedRequest(), event.getSuppliedResponse(), t);
             List<AsyncListenerWrapper> listenersCopy = new 
ArrayList<>(listeners);
-            for (AsyncListenerWrapper listener : listenersCopy) {
-                try {
-                    listener.fireOnError(errorEvent);
-                } catch (Throwable t2) {
-                    ExceptionUtils.handleThrowable(t2);
-                    log.warn(sm.getString("asyncContextImpl.onErrorError", 
listener.getClass().getName()), t2);
-                } finally {
-                    hasOnErrorReturned.set(true);
+            // The listeners are application code so need the application's 
context. Not all callers have bound it.
+            Context context = this.context;
+            ClassLoader oldCL = context == null ? null : context.bind(null);
+            try {
+                for (AsyncListenerWrapper listener : listenersCopy) {
+                    try {
+                        listener.fireOnError(errorEvent);
+                    } catch (Throwable t2) {
+                        ExceptionUtils.handleThrowable(t2);
+                        log.warn(sm.getString("asyncContextImpl.onErrorError", 
listener.getClass().getName()), t2);
+                    } finally {
+                        hasOnErrorReturned.set(true);
+                    }
+                }
+            } finally {
+                if (context != null) {
+                    context.unbind(oldCL);
                 }
             }
         }
diff --git a/test/org/apache/catalina/core/TestAsyncContextImpl.java 
b/test/org/apache/catalina/core/TestAsyncContextImpl.java
index 33573f7d59..25b18bc675 100644
--- a/test/org/apache/catalina/core/TestAsyncContextImpl.java
+++ b/test/org/apache/catalina/core/TestAsyncContextImpl.java
@@ -2865,6 +2865,76 @@ public class TestAsyncContextImpl extends TomcatBaseTest 
{
     }
 
 
+    /*
+     * AsyncListener.onError() is application code so must be called using the 
web application's class loader when an
+     * asynchronous dispatch fails.
+     */
+    @Test
+    public void testAsyncDispatchFailureListenerClassLoader() throws Exception 
{
+        Tomcat tomcat = getTomcatInstance();
+        Context context = tomcat.addContext("/test", null);
+        // Disable class path scanning - it slows the tests down by almost an 
order of magnitude
+        ((StandardJarScanner) context.getJarScanner()).setScanClassPath(false);
+
+        AtomicReference<ClassLoader> webappClassLoader = new 
AtomicReference<>();
+        AtomicReference<ClassLoader> listenerClassLoader = new 
AtomicReference<>();
+        CountDownLatch completed = new CountDownLatch(1);
+
+        Wrapper start = Tomcat.addServlet(context, "start", new HttpServlet() {
+            private static final long serialVersionUID = 1L;
+
+            @Override
+            protected void doGet(HttpServletRequest req, HttpServletResponse 
resp) {
+                
webappClassLoader.set(Thread.currentThread().getContextClassLoader());
+                AsyncContext ac = req.startAsync();
+                ac.addListener(new AsyncListener() {
+                    @Override
+                    public void onComplete(AsyncEvent event) {
+                        completed.countDown();
+                    }
+
+                    @Override
+                    public void onTimeout(AsyncEvent event) {
+                        // NO-OP
+                    }
+
+                    @Override
+                    public void onError(AsyncEvent event) {
+                        
listenerClassLoader.set(Thread.currentThread().getContextClassLoader());
+                    }
+
+                    @Override
+                    public void onStartAsync(AsyncEvent event) {
+                        // NO-OP
+                    }
+                });
+                ac.dispatch("/failing");
+            }
+        });
+        start.setAsyncSupported(true);
+        context.addServletMapping("/start", "start");
+
+        Wrapper failing = Tomcat.addServlet(context, "failing", new 
HttpServlet() {
+            private static final long serialVersionUID = 1L;
+
+            @Override
+            protected void doGet(HttpServletRequest req, HttpServletResponse 
resp) throws ServletException {
+                throw new ServletException("Expected");
+            }
+        });
+        failing.setAsyncSupported(true);
+        context.addServletMapping("/failing", "failing");
+        tomcat.start();
+
+        int rc = getUrl("http://localhost:"; + getPort() + "/test/start", new 
ByteChunk(), null);
+
+        Assert.assertEquals(500, rc);
+        Assert.assertTrue("onComplete() must be called", completed.await(5, 
TimeUnit.SECONDS));
+        Assert.assertNotNull(listenerClassLoader.get());
+        Assert.assertSame(webappClassLoader.get(), listenerClassLoader.get());
+    }
+
+
     /*
      * A failed dispatch must not change the state of the request. The 
application must be able to recover from the
      * failure. In particular, the async attributes that record the original 
request must not have been set by the
diff --git a/webapps/docs/changelog.xml b/webapps/docs/changelog.xml
index eb0f50e520..5eba44f610 100644
--- a/webapps/docs/changelog.xml
+++ b/webapps/docs/changelog.xml
@@ -296,6 +296,11 @@
         error. Fire <code>AsyncListener.onError()</code>, generate the error
         response and complete the request. (markt)
       </fix>
+      <fix>
+        Ensure that the web application's class loader and naming context are
+        bound when <code>AsyncListener.onError()</code> is called for a failed
+        asynchronous dispatch. (markt)
+      </fix>
     </changelog>
   </subsection>
   <subsection name="Coyote">


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

Reply via email to