This is an automated email from the ASF dual-hosted git repository.
markt-asf pushed a commit to branch 11.0.x
in repository https://gitbox.apache.org/repos/asf/tomcat.git
The following commit(s) were added to refs/heads/11.0.x by this push:
new d7a72b050b Avoid unbounded recursion when writing a large batched
WebSocket message
d7a72b050b is described below
commit d7a72b050b9f1a5badc016c76aea9687e0bdc3b5
Author: Mark Thomas <[email protected]>
AuthorDate: Mon Nov 30 10:42:37 2026 +0000
Avoid unbounded recursion when writing a large batched WebSocket message
OutputBufferSendHandler wrote each output buffer sized chunk from the
completion of the previous one. When writes completed inline, as they do
with
blocking writes, the stack grew with the size of the message. Depending on
the
connector, a large message could trigger a StackOverflowError or stall until
the write timed out. Handle the completion of each chunk in a loop rather
than
by recursing.
Co-Authored-By: Claude Sonnet 5.5 <[email protected]>
---
.../tomcat/websocket/WsRemoteEndpointImplBase.java | 26 ++++++++
.../tomcat/websocket/TestWsRemoteEndpoint.java | 75 ++++++++++++++++++++++
webapps/docs/changelog.xml | 5 ++
3 files changed, 106 insertions(+)
diff --git a/java/org/apache/tomcat/websocket/WsRemoteEndpointImplBase.java
b/java/org/apache/tomcat/websocket/WsRemoteEndpointImplBase.java
index eaacc96992..f9c9e84bfc 100644
--- a/java/org/apache/tomcat/websocket/WsRemoteEndpointImplBase.java
+++ b/java/org/apache/tomcat/websocket/WsRemoteEndpointImplBase.java
@@ -33,6 +33,7 @@ import java.util.concurrent.Future;
import java.util.concurrent.Semaphore;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicBoolean;
+import java.util.concurrent.atomic.AtomicInteger;
import java.util.concurrent.locks.ReentrantLock;
import javax.naming.NamingException;
@@ -1037,6 +1038,8 @@ public abstract class WsRemoteEndpointImplBase implements
RemoteEndpoint {
private final boolean flushRequired;
private final WsRemoteEndpointImplBase endpoint;
private volatile int maskIndex = 0;
+ private volatile SendResult pendingResult;
+ private final AtomicInteger pendingResults = new AtomicInteger();
OutputBufferSendHandler(SendHandler completion, boolean blocking, long
writeTimeoutExpiry,
ByteBuffer headerBuffer, ByteBuffer payload, byte[] mask,
ByteBuffer outputBuffer, boolean flushRequired,
@@ -1112,6 +1115,29 @@ public abstract class WsRemoteEndpointImplBase
implements RemoteEndpoint {
// ------------------------------------------------- SendHandler
methods
@Override
public void onResult(SendResult result) {
+ /*
+ * If a write completes inline, this method is called from within
the call that started that write, which
+ * was itself started from this method. Handling each result by
recursing would use stack proportional to
+ * the size of the message. Instead, the result is recorded and
handled by the loop below, which is
+ * running further up the stack (possibly on another thread). Only
one write is ever outstanding so there
+ * is at most one result waiting to be handled.
+ */
+ pendingResult = result;
+ if (pendingResults.getAndIncrement() != 0) {
+ return;
+ }
+ do {
+ try {
+ handleResult(pendingResult);
+ } catch (Throwable t) {
+ pendingResults.set(0);
+ throw t;
+ }
+ } while (pendingResults.decrementAndGet() > 0);
+ }
+
+
+ private void handleResult(SendResult result) {
if (result.isOK()) {
if (outputBuffer.hasRemaining()) {
endpoint.doWrite(this, blocking, writeTimeoutExpiry,
outputBuffer);
diff --git a/test/org/apache/tomcat/websocket/TestWsRemoteEndpoint.java
b/test/org/apache/tomcat/websocket/TestWsRemoteEndpoint.java
index 39db87646c..1f586c46b7 100644
--- a/test/org/apache/tomcat/websocket/TestWsRemoteEndpoint.java
+++ b/test/org/apache/tomcat/websocket/TestWsRemoteEndpoint.java
@@ -25,12 +25,20 @@ import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.TimeUnit;
+import java.util.concurrent.atomic.AtomicLong;
+import jakarta.servlet.ServletContextEvent;
import jakarta.websocket.ClientEndpointConfig.Builder;
import jakarta.websocket.ContainerProvider;
+import jakarta.websocket.DeploymentException;
import jakarta.websocket.Endpoint;
+import jakarta.websocket.EndpointConfig;
+import jakarta.websocket.MessageHandler;
+import jakarta.websocket.OnOpen;
import jakarta.websocket.Session;
import jakarta.websocket.WebSocketContainer;
+import jakarta.websocket.server.ServerContainer;
+import jakarta.websocket.server.ServerEndpoint;
import org.junit.Assert;
import org.junit.Test;
@@ -44,6 +52,8 @@ import
org.apache.tomcat.websocket.TesterMessageCountClient.AsyncText;
import
org.apache.tomcat.websocket.TesterMessageCountClient.TesterAnnotatedEndpoint;
import org.apache.tomcat.websocket.TesterMessageCountClient.TesterEndpoint;
import
org.apache.tomcat.websocket.TesterMessageCountClient.TesterProgrammaticEndpoint;
+import org.apache.tomcat.websocket.server.Constants;
+import org.apache.tomcat.websocket.server.WsContextListener;
public class TestWsRemoteEndpoint extends WebSocketBaseTest {
@@ -244,4 +254,69 @@ public class TestWsRemoteEndpoint extends
WebSocketBaseTest {
Assert.assertEquals(1, messages.size());
Assert.assertEquals(TesterEchoServer.WriterError.RESULT_PASS,
messages.get(0));
}
+
+ /*
+ * A large message sent with batching enabled is written to the socket in
output buffer sized chunks. The handling
+ * of the completion of each chunk must not use stack proportional to the
number of chunks.
+ */
+ @Test
+ public void testLargeBatchedBlockingSend() throws Exception {
+ startServer(LargeMessageConfig.class);
+
+ CountDownLatch latch = new CountDownLatch(1);
+ AtomicLong received = new AtomicLong();
+ Endpoint endpoint = new Endpoint() {
+ @Override
+ public void onOpen(Session session, EndpointConfig config) {
+ session.addMessageHandler(ByteBuffer.class, new
MessageHandler.Partial<ByteBuffer>() {
+ @Override
+ public void onMessage(ByteBuffer data, boolean last) {
+ received.addAndGet(data.remaining());
+ if (last) {
+ latch.countDown();
+ }
+ }
+ });
+ }
+ };
+
+ WebSocketContainer wsContainer =
ContainerProvider.getWebSocketContainer();
+ wsContainer.connectToServer(endpoint, Builder.create().build(),
+ new URI("ws://localhost:" + getPort() +
LargeMessageEndpoint.PATH));
+
+ Assert.assertTrue(latch.await(30, TimeUnit.SECONDS));
+ Assert.assertEquals(LargeMessageEndpoint.SIZE, received.get());
+ }
+
+
+ @ServerEndpoint(LargeMessageEndpoint.PATH)
+ public static class LargeMessageEndpoint {
+
+ public static final String PATH = "/large";
+ // Many times the output buffer size
+ public static final int SIZE = 32 * 1024 * 1024;
+
+ @OnOpen
+ public void onOpen(Session session) throws Exception {
+ session.getBasicRemote().setBatchingAllowed(true);
+ session.getBasicRemote().sendBinary(ByteBuffer.allocate(SIZE));
+ session.getBasicRemote().flushBatch();
+ }
+ }
+
+
+ public static class LargeMessageConfig extends WsContextListener {
+
+ @Override
+ public void contextInitialized(ServletContextEvent sce) {
+ super.contextInitialized(sce);
+ ServerContainer sc = (ServerContainer) sce.getServletContext()
+
.getAttribute(Constants.SERVER_CONTAINER_SERVLET_CONTEXT_ATTRIBUTE);
+ try {
+ sc.addEndpoint(LargeMessageEndpoint.class);
+ } catch (DeploymentException e) {
+ throw new IllegalStateException(e);
+ }
+ }
+ }
}
diff --git a/webapps/docs/changelog.xml b/webapps/docs/changelog.xml
index af89408d84..bd27796e10 100644
--- a/webapps/docs/changelog.xml
+++ b/webapps/docs/changelog.xml
@@ -447,6 +447,11 @@
</subsection>
<subsection name="WebSocket">
<changelog>
+ <fix>
+ Avoid using stack proportional to the message size when a large
+ WebSocket message is written in blocking mode with batching enabled.
+ (markt)
+ </fix>
<fix>
Fix the handling of compressed WebSocket messages for which there is no
message handler when the <code>permessage-deflate</code> extension is
---------------------------------------------------------------------
To unsubscribe, e-mail: [email protected]
For additional commands, e-mail: [email protected]