diff --git a/java/org/apache/catalina/connector/CoyoteAdapter.java b/java/org/apache/catalina/connector/CoyoteAdapter.java index 12d670afff10..3c3f1fddf314 100644 --- a/java/org/apache/catalina/connector/CoyoteAdapter.java +++ b/java/org/apache/catalina/connector/CoyoteAdapter.java @@ -238,10 +238,20 @@ public boolean asyncDispatch(org.apache.coyote.Request req, org.apache.coyote.Re } if (request.isAsyncDispatching()) { - connector.getService().getContainer().getPipeline().getFirst().invoke(request, response); - if (response.isError()) { + try { + connector.getService().getContainer().getPipeline().getFirst().invoke(request, response); Throwable t = (Throwable) request.getAttribute(RequestDispatcher.ERROR_EXCEPTION); - asyncConImpl.setErrorState(t, true); + /* + * An error response does not start async error handling if the listeners have already been + * notified that the dispatch completed the async processing, or if it has no exception and the + * dispatch started a new async cycle and ended it with complete() or dispatch() (BZ 70362). + */ + if (response.isError() && !asyncConImpl.isCompletedByDispatch() && + (t != null || !(request.isAsyncCompleting() || request.isAsyncDispatching()))) { + asyncConImpl.setErrorState(t, true); + } + } finally { + asyncConImpl.fireDeferredOnComplete(); } } diff --git a/java/org/apache/catalina/core/AsyncContextImpl.java b/java/org/apache/catalina/core/AsyncContextImpl.java index 655215eed320..6ab795e4a0bb 100644 --- a/java/org/apache/catalina/core/AsyncContextImpl.java +++ b/java/org/apache/catalina/core/AsyncContextImpl.java @@ -126,6 +126,8 @@ public class AsyncContextImpl implements AsyncContext, AsyncContextCallback { private volatile boolean hasOriginalRequestAndResponse = true; private final AtomicBoolean hasErrorProcessingStarted = new AtomicBoolean(false); private final AtomicBoolean hasOnErrorReturned = new AtomicBoolean(false); + private volatile boolean completedByDispatch = false; + private volatile boolean completionDeferred = false; /* * ThreadLocal for passing over-ridden URL encoding state when dispatching. @@ -362,6 +364,8 @@ public void recycle() { timeout = -1; hasErrorProcessingStarted.set(false); hasOnErrorReturned.set(false); + completedByDispatch = false; + completionDeferred = false; } private void clearServletRequestResponse() { @@ -402,6 +406,8 @@ public void setStarted(Context context, ServletRequest request, ServletResponse this.servletResponse = response; this.hasOriginalRequestAndResponse = originalRequestResponse; this.event = new AsyncEvent(this, request, response); + this.completedByDispatch = false; + this.completionDeferred = false; List listenersCopy = new ArrayList<>(listeners); listeners.clear(); @@ -444,7 +450,16 @@ protected void doInternalDispatch() throws ServletException, IOException { dispatch = null; runnable.run(); if (!request.isAsync()) { - fireOnComplete(); + if (isUnreportedFailure()) { + /* + * The dispatch recorded a failure and returned. CoyoteAdapter starts async error handling which + * notifies the listeners of the failure before it completes the async processing. + */ + completionDeferred = true; + } else { + completedByDispatch = true; + fireOnComplete(); + } } } catch (RuntimeException x) { AtomicBoolean result = new AtomicBoolean(); @@ -456,7 +471,16 @@ protected void doInternalDispatch() throws ServletException, IOException { * information required to determine that onComplete() needs to be called. */ if (!result.get()) { - fireOnComplete(); + if (hasErrorProcessingStarted.get()) { + completedByDispatch = true; + fireOnComplete(); + } else { + /* + * CoyoteAdapter starts async error handling for the exception, which notifies the listeners of it + * before it completes the async processing. If it does not, it calls fireDeferredOnComplete(). + */ + completionDeferred = true; + } } if (x.getCause() instanceof ServletException) { throw (ServletException) x.getCause(); @@ -469,6 +493,40 @@ protected void doInternalDispatch() throws ServletException, IOException { } + /* + * Has the dispatch recorded a failure (an error response with an exception) that will start async error handling + * once the dispatch returns? + */ + private boolean isUnreportedFailure() { + return !hasErrorProcessingStarted.get() && request.getResponse().isError() && + request.getAttribute(RequestDispatcher.ERROR_EXCEPTION) != null; + } + + + /** + * Has the most recent dispatch completed the asynchronous processing? If it has, the listeners have been notified + * that the processing is complete. + * + * @return {@code true} if the most recent dispatch completed the asynchronous processing, otherwise {@code false} + */ + public boolean isCompletedByDispatch() { + return completedByDispatch; + } + + + /** + * Notifies the listeners that the most recent dispatch completed the asynchronous processing if that notification + * was deferred for async error handling that has not started. Called once the dispatch has returned. + */ + public void fireDeferredOnComplete() { + if (completionDeferred) { + completionDeferred = false; + completedByDispatch = true; + fireOnComplete(); + } + } + + @Override public long getTimeout() { check(); @@ -509,6 +567,8 @@ public void setErrorState(Throwable t, boolean fireOnError) { // Skip duplicate error processing return; } + // The error processing completes the async processing + completionDeferred = false; if (t != null) { request.setAttribute(RequestDispatcher.ERROR_EXCEPTION, t); } diff --git a/test/org/apache/catalina/core/TestAsyncContextImpl.java b/test/org/apache/catalina/core/TestAsyncContextImpl.java index fd1bb765dcfe..896839390cf5 100644 --- a/test/org/apache/catalina/core/TestAsyncContextImpl.java +++ b/test/org/apache/catalina/core/TestAsyncContextImpl.java @@ -18,7 +18,9 @@ import java.io.IOException; import java.io.InputStream; +import java.io.OutputStream; import java.io.PrintWriter; +import java.net.Socket; import java.net.URI; import java.net.URISyntaxException; import java.nio.charset.StandardCharsets; @@ -2403,6 +2405,317 @@ public void testTimeoutDispatchCustomErrorPage() throws Exception { } + /* + * https://bz.apache.org/bugzilla/show_bug.cgi?id=70362 + * + * dispatch() is called on the request thread. + */ + @Test + public void testSendErrorOnAsyncDispatchCompletesOnce() throws Exception { + doTestBug70362(Bug70362Mode.SEND_ERROR, HttpServletResponse.SC_SERVICE_UNAVAILABLE, "onComplete-", null); + } + + + /* + * https://bz.apache.org/bugzilla/show_bug.cgi?id=70362 + * + * dispatch() is called from start() before the request thread exits service(). + */ + @Test + public void testSendErrorOnAsyncDispatchFromStartBeforeExitCompletesOnce() throws Exception { + doTestBug70362(Bug70362Mode.SEND_ERROR_START_BEFORE_EXIT, HttpServletResponse.SC_SERVICE_UNAVAILABLE, + "onComplete-", null); + } + + + /* + * https://bz.apache.org/bugzilla/show_bug.cgi?id=70362 + * + * dispatch() is called from start() after the request thread has exited service(). + */ + @Test + public void testSendErrorOnAsyncDispatchFromStartAfterExitCompletesOnce() throws Exception { + doTestBug70362(Bug70362Mode.SEND_ERROR_START_AFTER_EXIT, HttpServletResponse.SC_SERVICE_UNAVAILABLE, + "onComplete-", null); + } + + + /* + * https://bz.apache.org/bugzilla/show_bug.cgi?id=70362 + * + * The dispatch calls sendError(), starts a new asynchronous cycle and completes it. + */ + @Test + public void testSendErrorThenCompleteOnAsyncDispatchCompletesOnce() throws Exception { + doTestBug70362(Bug70362Mode.SEND_ERROR_RESTART_COMPLETE, HttpServletResponse.SC_SERVICE_UNAVAILABLE, + "onComplete-", null); + } + + + /* + * https://bz.apache.org/bugzilla/show_bug.cgi?id=70362 + * + * The dispatch calls sendError(), starts a new asynchronous cycle and dispatches it. + */ + @Test + public void testSendErrorThenDispatchOnAsyncDispatchCompletesOnce() throws Exception { + doTestBug70362(Bug70362Mode.SEND_ERROR_RESTART_DISPATCH, HttpServletResponse.SC_SERVICE_UNAVAILABLE, + "onComplete-", null); + } + + + /* + * https://bz.apache.org/bugzilla/show_bug.cgi?id=70362 + * + * An exception thrown by the dispatch is reported to the listeners before completion. + */ + @Test + public void testExceptionOnAsyncDispatchStartsErrorHandling() throws Exception { + doTestBug70362(Bug70362Mode.THROW, HttpServletResponse.SC_INTERNAL_SERVER_ERROR, "onError-onComplete-", + ServletException.class); + } + + + /* + * https://bz.apache.org/bugzilla/show_bug.cgi?id=70362 + * + * A failure recorded on the request by a dispatch that then returns normally (as InputBuffer does for a read + * failure the application swallows) is reported to the listeners before completion. + */ + @Test + public void testRecordedFailureOnAsyncDispatchStartsErrorHandling() throws Exception { + doTestBug70362(Bug70362Mode.RECORDED_FAILURE, HttpServletResponse.SC_INTERNAL_SERVER_ERROR, + "onError-onComplete-", IOException.class); + } + + + /* + * https://bz.apache.org/bugzilla/show_bug.cgi?id=66875 + * + * A failure the dispatch handled itself, writing the response, does not start async error handling. + */ + @Test + public void testHandledFailureOnAsyncDispatchCompletesOnce() throws Exception { + doTestBug70362(Bug70362Mode.HANDLED_FAILURE, HttpServletResponse.SC_INTERNAL_SERVER_ERROR, "onComplete-", + null); + } + + + /* + * https://bz.apache.org/bugzilla/show_bug.cgi?id=70362 + * + * The client has gone when the dispatch writes the response and the dispatch throws the resulting IOException. + */ + @Test + public void testIoErrorOnAsyncDispatchStartsErrorHandling() throws Exception { + doTestBug70362(Bug70362Mode.IO_ERROR, -1, "onError-onComplete-", IOException.class); + } + + + private void doTestBug70362(Bug70362Mode mode, int expectedStatus, String expectedTrack, + Class expectedThrowable) throws Exception { + resetTracker(); + bug70362Throwable = null; + Tomcat tomcat = getTomcatInstance(); + Context context = getProgrammaticRootContext(); + Bug70362Servlet servlet = new Bug70362Servlet(mode); + Wrapper wrapper = Tomcat.addServlet(context, "bug70362", servlet); + wrapper.setAsyncSupported(true); + context.addServletMapping("/bug70362", "bug70362"); + TesterAccessLogValve alv = new TesterAccessLogValve(); + context.getPipeline().addValve(alv); + tomcat.start(); + + if (mode == Bug70362Mode.IO_ERROR) { + try (Socket socket = new Socket("localhost", getPort())) { + OutputStream os = socket.getOutputStream(); + os.write(("GET /bug70362 HTTP/1.1" + CRLF + "Host: localhost" + CRLF + CRLF) + .getBytes(StandardCharsets.ISO_8859_1)); + os.flush(); + Assert.assertTrue(servlet.asyncStartedLatch.await(10, TimeUnit.SECONDS)); + // Reset the connection on close so the writes of the dispatch fail + socket.setSoLinger(true, 0); + } + servlet.clientClosedLatch.countDown(); + } else { + int rc = getUrl("http://localhost:" + getPort() + "/bug70362", new ByteChunk(), null); + Assert.assertEquals(expectedStatus, rc); + } + + // The access log entry is made once processing of the request has ended, after all listener events + int count = 0; + while (alv.getEntryCount() < 1 && count < 200) { + Thread.sleep(50); + count++; + } + Assert.assertEquals(1, alv.getEntryCount()); + Assert.assertEquals(expectedTrack, getTrack()); + Assert.assertEquals(0, ((StandardContext) context).getInProgressAsyncCount()); + if (expectedThrowable == null) { + Assert.assertNull(bug70362Throwable); + } else { + Assert.assertNotNull(bug70362Throwable); + Assert.assertTrue(bug70362Throwable.toString(), expectedThrowable.isInstance(bug70362Throwable)); + if (mode != Bug70362Mode.IO_ERROR) { + Assert.assertEquals(Bug70362Servlet.MESSAGE, bug70362Throwable.getMessage()); + } + } + } + + + private enum Bug70362Mode { + SEND_ERROR, + SEND_ERROR_START_BEFORE_EXIT, + SEND_ERROR_START_AFTER_EXIT, + SEND_ERROR_RESTART_COMPLETE, + SEND_ERROR_RESTART_DISPATCH, + THROW, + RECORDED_FAILURE, + HANDLED_FAILURE, + IO_ERROR + } + + + private static volatile Throwable bug70362Throwable; + + + public static class Bug70362Listener implements AsyncListener { + + @Override + public void onComplete(AsyncEvent event) throws IOException { + track("onComplete-"); + } + + @Override + public void onTimeout(AsyncEvent event) throws IOException { + track("onTimeout-"); + } + + @Override + public void onError(AsyncEvent event) throws IOException { + track("onError-"); + bug70362Throwable = event.getThrowable(); + } + + @Override + public void onStartAsync(AsyncEvent event) throws IOException { + // NO-OP + } + } + + + public static class Bug70362Servlet extends HttpServlet { + + private static final long serialVersionUID = 1L; + + static final String MESSAGE = "Bug70362"; + + private final Bug70362Mode mode; + final transient CountDownLatch asyncStartedLatch = new CountDownLatch(1); + final transient CountDownLatch clientClosedLatch = new CountDownLatch(1); + + Bug70362Servlet(Bug70362Mode mode) { + this.mode = mode; + } + + @Override + protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { + if (req.getDispatcherType() == DispatcherType.ASYNC) { + switch (mode) { + case THROW: + throw new ServletException(MESSAGE); + case RECORDED_FAILURE: + req.setAttribute(RequestDispatcher.ERROR_EXCEPTION, new IOException(MESSAGE)); + resp.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR); + break; + case HANDLED_FAILURE: + // The application handled the failure and wrote the response itself, as in BZ 66875 + req.setAttribute(RequestDispatcher.ERROR_EXCEPTION, new IOException(MESSAGE)); + resp.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR); + resp.getWriter().print(MESSAGE); + break; + case SEND_ERROR_RESTART_COMPLETE: { + resp.sendError(HttpServletResponse.SC_SERVICE_UNAVAILABLE); + AsyncContext asyncContext = req.startAsync(); + asyncContext.addListener(new Bug70362Listener()); + asyncContext.complete(); + break; + } + case SEND_ERROR_RESTART_DISPATCH: { + if (req.getAttribute(MESSAGE) == null) { + req.setAttribute(MESSAGE, Boolean.TRUE); + resp.sendError(HttpServletResponse.SC_SERVICE_UNAVAILABLE); + AsyncContext asyncContext = req.startAsync(); + asyncContext.addListener(new Bug70362Listener()); + asyncContext.dispatch(); + } + break; + } + case IO_ERROR: { + OutputStream os = resp.getOutputStream(); + byte[] data = TestCoyoteAdapter.TEXT_8K.getBytes(StandardCharsets.UTF_8); + for (int i = 0; i < 1024; i++) { + os.write(data); + os.flush(); + } + break; + } + default: + resp.sendError(HttpServletResponse.SC_SERVICE_UNAVAILABLE); + } + return; + } + + AsyncContext asyncContext = req.startAsync(); + asyncContext.setTimeout(0); + asyncContext.addListener(new Bug70362Listener()); + switch (mode) { + case SEND_ERROR_START_BEFORE_EXIT: { + // dispatch() is called while the request is still in the STARTING state + CountDownLatch dispatchedLatch = new CountDownLatch(1); + asyncContext.start(() -> { + asyncContext.dispatch(); + dispatchedLatch.countDown(); + }); + try { + Assert.assertTrue(dispatchedLatch.await(10, TimeUnit.SECONDS)); + } catch (InterruptedException e) { + throw new ServletException(e); + } + break; + } + case SEND_ERROR_START_AFTER_EXIT: + asyncContext.start(() -> { + try { + /* + * There is no signal for the request moving from STARTING to STARTED after service() + * exits so wait, as TestAsyncContextStateChanges does. + */ + Thread.sleep(1000); + } catch (InterruptedException e) { + // Ignore + } + asyncContext.dispatch(); + }); + break; + case IO_ERROR: + asyncContext.start(() -> { + try { + clientClosedLatch.await(10, TimeUnit.SECONDS); + } catch (InterruptedException e) { + // Ignore + } + asyncContext.dispatch(); + }); + asyncStartedLatch.countDown(); + break; + default: + asyncContext.dispatch(); + } + } + } + + public static class Bug58751AsyncServlet extends HttpServlet { private static final long serialVersionUID = 1L; diff --git a/webapps/docs/changelog.xml b/webapps/docs/changelog.xml index afcb5326be44..773a8a8e4883 100644 --- a/webapps/docs/changelog.xml +++ b/webapps/docs/changelog.xml @@ -241,6 +241,18 @@ Expand the user name normalisation options available in the LockOutRealm. (markt) + + 70362: Do not notify AsyncListeners of an error + after they have been notified of completion by an asynchronous dispatch, + and do not start asynchronous error handling for an error response + without an exception (e.g. from sendError()) when the + dispatch completed the asynchronous processing or started a new + asynchronous cycle and ended it with complete() or + dispatch(). A failure that an asynchronous dispatch + records, or an exception it throws after an I/O error, is reported to + the listeners before completion. Regression in the fix for + 66875. Patch provided by Scott Murphy Heiberg. +