This is an automated email from the ASF dual-hosted git repository.

markt-asf pushed a commit to branch 9.0.x
in repository https://gitbox.apache.org/repos/asf/tomcat.git


The following commit(s) were added to refs/heads/9.0.x by this push:
     new 41124ba870 Avoid unbounded recursion when writing a large batched 
WebSocket message
41124ba870 is described below

commit 41124ba870110a115b89a75b5c48191486b8da7c
Author: Mark Thomas <[email protected]>
AuthorDate: Mon Nov 30 11:02:08 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 632a8420b6..fba0904726 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;
@@ -1046,6 +1047,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,
@@ -1121,6 +1124,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 3ce01689c0..65888146c8 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 javax.servlet.ServletContextEvent;
 import javax.websocket.ClientEndpointConfig.Builder;
 import javax.websocket.ContainerProvider;
+import javax.websocket.DeploymentException;
 import javax.websocket.Endpoint;
+import javax.websocket.EndpointConfig;
+import javax.websocket.MessageHandler;
+import javax.websocket.OnOpen;
 import javax.websocket.Session;
 import javax.websocket.WebSocketContainer;
+import javax.websocket.server.ServerContainer;
+import javax.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 e40dd3e1dc..82fb062edf 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]

Reply via email to