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
The following commit(s) were added to refs/heads/10.1.x by this push:
new c87f3c523a Avoid unbounded recursion when writing a large batched
WebSocket message
c87f3c523a is described below
commit c87f3c523a87847c9e31f750796752a97ff5ce1f
Author: Mark Thomas <[email protected]>
AuthorDate: Mon Nov 30 10:57:17 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 5e287038d3..d7fcc0c5a1 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.Lock;
import javax.naming.NamingException;
@@ -1047,6 +1048,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,
@@ -1122,6 +1125,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 05484d7412..2476209baa 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 {
@@ -238,4 +248,69 @@ public class TestWsRemoteEndpoint extends
WebSocketBaseTest {
Assert.assertEquals(0, messages.size());
}
+
+ /*
+ * 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 d3f46c0d45..8c92ba1789 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]