This is an automated email from the ASF dual-hosted git repository. markt-asf pushed a commit to branch 10.1.x in repository https://gitbox.apache.org/repos/asf/tomcat.git
commit 29e51702f618b3647811f3e08782a6afac83aa7b Author: Mark Thomas <[email protected]> AuthorDate: Wed Dec 2 10:09:19 2026 +0000 Do not re-use an NIO2 channel while a sendfile operation is in progress An asynchronous sendfile operation does not hold the read or write permit or the socket wrapper lock, so the check that a closing NIO2 socket wrapper is idle before its channel is returned to the pool did not take it into account. The completion handler of the operation uses the channel, and the buffers that belong to it, until the operation has finished, so the channel could be reset and passed to a different connection while the handler was still using it. Treat a wrapper with a sendfile operation in progress as not idle. Make the reference to the sendfile data volatile as it is read and written by different threads. Co-Authored-By: Claude Sonnet 5.5 <[email protected]> --- java/org/apache/tomcat/util/net/Nio2Endpoint.java | 9 +- .../util/net/TestNio2SendfileChannelRecycle.java | 129 +++++++++++++++++++++ webapps/docs/changelog.xml | 5 + 3 files changed, 142 insertions(+), 1 deletion(-) diff --git a/java/org/apache/tomcat/util/net/Nio2Endpoint.java b/java/org/apache/tomcat/util/net/Nio2Endpoint.java index c4f11d0c28..438fa1a130 100644 --- a/java/org/apache/tomcat/util/net/Nio2Endpoint.java +++ b/java/org/apache/tomcat/util/net/Nio2Endpoint.java @@ -506,7 +506,7 @@ public class Nio2Endpoint extends AbstractJsseEndpoint<Nio2Channel,AsynchronousS private final SynchronizedStack<Nio2Channel> nioChannels; - private SendfileData sendfileData = null; + private volatile SendfileData sendfileData = null; private final CompletionHandler<Integer,ByteBuffer> readCompletionHandler; private boolean readInterest = false; // Guarded by readCompletionHandler @@ -997,6 +997,13 @@ public class Nio2Endpoint extends AbstractJsseEndpoint<Nio2Channel,AsynchronousS * channel. */ private boolean isIdle() { + /* + * An asynchronous sendfile operation does not hold the read or write permit or the socket wrapper lock but + * its completion handler uses the channel, and the buffers it owns, until the operation has finished. + */ + if (sendfileData != null) { + return false; + } boolean readFree = readPending.tryAcquire(); boolean writeFree = false; boolean lockFree = false; diff --git a/test/org/apache/tomcat/util/net/TestNio2SendfileChannelRecycle.java b/test/org/apache/tomcat/util/net/TestNio2SendfileChannelRecycle.java new file mode 100644 index 0000000000..1e9d2359ec --- /dev/null +++ b/test/org/apache/tomcat/util/net/TestNio2SendfileChannelRecycle.java @@ -0,0 +1,129 @@ +/* + * 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.tomcat.util.net; + +import java.io.File; +import java.io.IOException; +import java.io.InputStream; +import java.io.OutputStream; +import java.io.RandomAccessFile; +import java.lang.reflect.Method; +import java.net.Socket; +import java.nio.charset.StandardCharsets; + +import jakarta.servlet.ServletException; +import jakarta.servlet.http.HttpServlet; +import jakarta.servlet.http.HttpServletRequest; +import jakarta.servlet.http.HttpServletResponse; + +import org.junit.Assert; +import org.junit.Assume; +import org.junit.Test; + +import org.apache.catalina.Context; +import org.apache.catalina.Globals; +import org.apache.catalina.startup.Tomcat; +import org.apache.catalina.startup.TomcatBaseTest; +import org.apache.coyote.AbstractProtocol; +import org.apache.coyote.http11.Http11Nio2Protocol; + +public class TestNio2SendfileChannelRecycle extends TomcatBaseTest { + + /* + * An asynchronous sendfile operation does not hold the read or write permit or the socket wrapper lock but its + * completion handler uses the channel, and the buffers that belong to it, until the operation has finished. If the + * connection is closed while the operation is in progress the channel must not be reset and passed to a different + * connection. + */ + @Test + public void testChannelNotRecycledWhileSendfileInProgress() throws Exception { + Tomcat tomcat = getTomcatInstance(); + Assume.assumeTrue("NIO2 only", tomcat.getConnector().getProtocolHandler() instanceof Http11Nio2Protocol); + + File file = File.createTempFile("sendfile", ".bin", getTemporaryDirectory()); + file.deleteOnExit(); + try (RandomAccessFile raf = new RandomAccessFile(file, "rw")) { + // Much larger than the socket buffers so the write can't complete while the client is not reading + raf.setLength(256L * 1024 * 1024); + } + + Context ctx = getProgrammaticRootContext(); + Tomcat.addServlet(ctx, "sendfile", new SendfileServlet(file)); + ctx.addServletMappingDecoded("/sendfile", "sendfile"); + tomcat.start(); + + Method getEndpoint = AbstractProtocol.class.getDeclaredMethod("getEndpoint"); + getEndpoint.setAccessible(true); + Nio2Endpoint endpoint = (Nio2Endpoint) getEndpoint.invoke(tomcat.getConnector().getProtocolHandler()); + Assert.assertNull("The pool should be empty at the start", endpoint.getNioChannels().pop()); + + try (Socket socket = new Socket("localhost", getPort())) { + // Reset the connection when it is closed rather than closing it cleanly + socket.setSoLinger(true, 0); + OutputStream os = socket.getOutputStream(); + os.write(("GET /sendfile HTTP/1.1\r\nHost: localhost:" + getPort() + "\r\nConnection: close\r\n\r\n") + .getBytes(StandardCharsets.US_ASCII)); + os.flush(); + // Read the response headers so that we know sendfile is under way. Leave the body unread. + InputStream is = socket.getInputStream(); + StringBuilder headers = new StringBuilder(); + while (!headers.toString().endsWith("\r\n\r\n")) { + int b = is.read(); + Assert.assertTrue("Unexpected end of response", b != -1); + headers.append((char) b); + } + Assert.assertTrue(headers.toString(), headers.toString().startsWith("HTTP/1.1 200")); + // Give the server time to fill the socket buffers so the write is pending + Thread.sleep(1000); + } + + // Wait for the server to notice that the connection has been reset and close the socket + long end = System.currentTimeMillis() + 10000; + // The acceptor holds one connection permit so the count is 1 when there are no connections + while (endpoint.getConnectionCount() > 1 && System.currentTimeMillis() < end) { + Thread.sleep(50); + } + Assert.assertTrue("The connection was not closed", endpoint.getConnectionCount() <= 1); + // The close completes after the connection is counted as closed + Thread.sleep(500); + + Assert.assertNull("The channel of a connection with an unfinished sendfile operation must not be re-used", + endpoint.getNioChannels().pop()); + } + + + private static class SendfileServlet extends HttpServlet { + + private static final long serialVersionUID = 1L; + + private final File file; + + SendfileServlet(File file) { + this.file = file; + } + + @Override + protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { + Assert.assertEquals(Boolean.TRUE, req.getAttribute(Globals.SENDFILE_SUPPORTED_ATTR)); + resp.setContentType("application/octet-stream"); + resp.setContentLengthLong(file.length()); + req.setAttribute(Globals.SENDFILE_FILENAME_ATTR, file.getAbsolutePath()); + req.setAttribute(Globals.SENDFILE_FILE_START_ATTR, Long.valueOf(0)); + req.setAttribute(Globals.SENDFILE_FILE_END_ATTR, Long.valueOf(file.length())); + } + } +} diff --git a/webapps/docs/changelog.xml b/webapps/docs/changelog.xml index 90fb2e1891..f6c7d45782 100644 --- a/webapps/docs/changelog.xml +++ b/webapps/docs/changelog.xml @@ -472,6 +472,11 @@ error that occurred as the request started asynchronous processing. (markt) </fix> + <fix> + Do not return the channel of an NIO2 connection to the pool for re-use + if the connection is closed while an asynchronous sendfile operation on + it has not finished. (markt) + </fix> </changelog> </subsection> <subsection name="Jasper"> --------------------------------------------------------------------- To unsubscribe, e-mail: [email protected] For additional commands, e-mail: [email protected]
