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 a2b631b448 Decompress WebSocket messages that have no handler to keep 
the window in step
a2b631b448 is described below

commit a2b631b448777f9285bfb20d419cfb43775c3342
Author: Mark Thomas <[email protected]>
AuthorDate: Wed Nov 25 11:30:53 2026 +0000

    Decompress WebSocket messages that have no handler to keep the window in
    step
    
    When permessage-deflate is used with context takeover, a compressed
    message
    for which there was no message handler was skipped without being passed
    through the transformation. The LZ77 window then no longer matched the
    sender's so later messages were decoded incorrectly. Pass the data
    through
    the transformation and discard the result.
    
    Co-Authored-By: Claude Sonnet 5.5 <[email protected]>
---
 java/org/apache/tomcat/websocket/WsFrameBase.java |  38 +++--
 test/org/apache/tomcat/websocket/TestWsFrame.java | 197 ++++++++++++++++++++++
 webapps/docs/changelog.xml                        |  11 ++
 3 files changed, 235 insertions(+), 11 deletions(-)

diff --git a/java/org/apache/tomcat/websocket/WsFrameBase.java 
b/java/org/apache/tomcat/websocket/WsFrameBase.java
index 7adc1819f2..65448a4f98 100644
--- a/java/org/apache/tomcat/websocket/WsFrameBase.java
+++ b/java/org/apache/tomcat/websocket/WsFrameBase.java
@@ -73,6 +73,8 @@ public abstract class WsFrameBase {
     // consistently for the entire message
     private MessageHandler binaryMsgHandler = null;
     private MessageHandler textMsgHandler = null;
+    // Allocated on first use. Receives the output of the transformation for 
messages that are discarded
+    private ByteBuffer discardBuffer = null;
 
     // Attributes of the current frame
     private boolean fin = false;
@@ -683,20 +685,34 @@ public abstract class WsFrameBase {
     }
 
 
-    private boolean swallowInput() {
-        long toSkip = Math.min(payloadLength - payloadWritten, 
inputBuffer.remaining());
-        inputBuffer.position(inputBuffer.position() + (int) toSkip);
-        payloadWritten += toSkip;
-        if (payloadWritten == payloadLength) {
-            if (continuationExpected) {
-                newFrame();
-            } else {
-                newMessage();
+    /**
+     * Discards the message data when there is no message handler for the 
message type. The data is still passed through
+     * the transformation so that any state it maintains, such as the LZ77 
window used by permessage-deflate when
+     * context takeover is in use, remains in step with the sender.
+     */
+    private boolean swallowInput() throws IOException {
+        if (discardBuffer == null) {
+            discardBuffer = ByteBuffer.allocate(Constants.DEFAULT_BUFFER_SIZE);
+        }
+        discardBuffer.clear();
+        TransformationResult tr = transformation.getMoreData(opCode, fin, rsv, 
discardBuffer);
+        while (!TransformationResult.END_OF_FRAME.equals(tr)) {
+            if (TransformationResult.UNDERFLOW.equals(tr)) {
+                // Ran out of input data - get some more
+                return false;
             }
-            return true;
+            // Ran out of space in the buffer - discard what has been 
transformed so far
+            discardBuffer.clear();
+            tr = transformation.getMoreData(opCode, fin, rsv, discardBuffer);
+        }
+        discardBuffer.clear();
+
+        if (continuationExpected) {
+            newFrame();
         } else {
-            return false;
+            newMessage();
         }
+        return true;
     }
 
 
diff --git a/test/org/apache/tomcat/websocket/TestWsFrame.java 
b/test/org/apache/tomcat/websocket/TestWsFrame.java
index 3b84c2aedf..b2da2883b5 100644
--- a/test/org/apache/tomcat/websocket/TestWsFrame.java
+++ b/test/org/apache/tomcat/websocket/TestWsFrame.java
@@ -16,9 +16,17 @@
  */
 package org.apache.tomcat.websocket;
 
+import java.io.ByteArrayOutputStream;
 import java.io.IOException;
 import java.nio.ByteBuffer;
+import java.nio.charset.StandardCharsets;
+import java.util.ArrayList;
+import java.util.Collections;
+import java.util.List;
+import java.util.zip.Deflater;
 
+import jakarta.websocket.Extension.Parameter;
+import jakarta.websocket.MessageHandler;
 import jakarta.websocket.RemoteEndpoint;
 
 import org.junit.Assert;
@@ -106,12 +114,201 @@ public class TestWsFrame {
     }
 
 
+    /*
+     * With permessage-deflate and context takeover, the LZ77 window includes 
all previous messages. A compressed
+     * message for which there is no message handler must still be 
decompressed (and discarded) so that the window
+     * is correct for the messages that follow.
+     */
+    @Test
+    public void testCompressedMessageWithoutHandlerKeepsWindowBinary() throws 
Exception {
+        doTestCompressedMessageWithoutHandler(Constants.OPCODE_BINARY, true);
+    }
+
+
+    @Test
+    public void testUncompressedMessageWithoutHandler() throws Exception {
+        doTestCompressedMessageWithoutHandler(Constants.OPCODE_BINARY, false);
+    }
+
+
+    private static void doTestCompressedMessageWithoutHandler(byte 
skippedOpCode, boolean compressSkipped)
+            throws Exception {
+        String repeated = "THE QUICK BROWN FOX JUMPS OVER THE LAZY DOG. ";
+        byte[] skipped = (repeated + repeated + 
"first").getBytes(StandardCharsets.UTF_8);
+        String expected = repeated + repeated + "second";
+
+        // Compress with a single Deflater so the second message can refer 
back to the first
+        Deflater deflater = new Deflater(Deflater.DEFAULT_COMPRESSION, true);
+        byte[] skippedFrame;
+        byte[] textFrame;
+        try {
+            if (compressSkipped) {
+                skippedFrame = createFrame(skippedOpCode, true, 
deflateMessage(deflater, skipped));
+            } else {
+                // Uncompressed messages are not part of the LZ77 window
+                skippedFrame = createFrame(skippedOpCode, false, skipped);
+            }
+            byte[] second = expected.getBytes(StandardCharsets.UTF_8);
+            byte[] compressedSecond = deflateMessage(deflater, second);
+            if (compressSkipped) {
+                // Check the test is exercising back-references into the first 
message
+                Assert.assertTrue(compressedSecond.length < second.length / 3);
+            }
+            textFrame = createFrame(Constants.OPCODE_TEXT, true, 
compressedSecond);
+        } finally {
+            deflater.end();
+        }
+
+        List<List<Parameter>> preferences = new ArrayList<>();
+        preferences.add(Collections.emptyList());
+        // Receiving as a client so the frames do not need to be masked
+        PerMessageDeflate perMessageDeflate = 
PerMessageDeflate.build(preferences, false);
+        Assert.assertNotNull(perMessageDeflate);
+
+        List<String> received = new ArrayList<>();
+        MessageHandler.Whole<String> textHandler = received::add;
+
+        WsSession wsSession = EasyMock.createNiceMock(WsSession.class);
+        
EasyMock.expect(Integer.valueOf(wsSession.getMaxBinaryMessageBufferSize())).andStubReturn(Integer.valueOf(8192));
+        
EasyMock.expect(Integer.valueOf(wsSession.getMaxTextMessageBufferSize())).andStubReturn(Integer.valueOf(8192));
+        
EasyMock.expect(wsSession.getBinaryMessageHandler()).andStubReturn(null);
+        
EasyMock.expect(wsSession.getTextMessageHandler()).andStubReturn(textHandler);
+        EasyMock.replay(wsSession);
+
+        TestFrame frame = new TestFrame(wsSession, perMessageDeflate);
+        frame.process(skippedFrame);
+        Assert.assertTrue("No handler so no message expected", 
received.isEmpty());
+        frame.process(textFrame);
+
+        Assert.assertEquals(1, received.size());
+        Assert.assertEquals(expected, received.get(0));
+    }
+
+
+    /*
+     * The skipped message is fragmented over several frames and the data is 
delivered a few bytes at a time so that
+     * the frames are split across reads.
+     */
+    @Test
+    public void testFragmentedCompressedMessageWithoutHandler() throws 
Exception {
+        doTestCompressedMessagesWithoutHandler(3, 7, 1);
+    }
+
+
+    /*
+     * The decompressed size of the skipped message is much larger than the 
buffer used to discard the data.
+     */
+    @Test
+    public void testLargeCompressedMessageWithoutHandler() throws Exception {
+        doTestCompressedMessagesWithoutHandler(1, Integer.MAX_VALUE, 2000);
+    }
+
+
+    private static void doTestCompressedMessagesWithoutHandler(int fragments, 
int chunkSize, int repeat)
+            throws Exception {
+        String repeated = "THE QUICK BROWN FOX JUMPS OVER THE LAZY DOG. ";
+        byte[] skipped = (repeated.repeat(repeat) + 
"first").getBytes(StandardCharsets.UTF_8);
+        String expected = repeated + "second";
+
+        Deflater deflater = new Deflater(Deflater.DEFAULT_COMPRESSION, true);
+        ByteArrayOutputStream wire = new ByteArrayOutputStream();
+        try {
+            byte[] compressed = deflateMessage(deflater, skipped);
+            int fragmentSize = (compressed.length + fragments - 1) / fragments;
+            for (int i = 0; i < fragments; i++) {
+                int start = i * fragmentSize;
+                int end = Math.min(compressed.length, start + fragmentSize);
+                byte[] fragment = java.util.Arrays.copyOfRange(compressed, 
start, end);
+                boolean first = i == 0;
+                boolean last = i == fragments - 1;
+                wire.write(createFrame(first ? Constants.OPCODE_BINARY : 
Constants.OPCODE_CONTINUATION, last, first,
+                        fragment));
+            }
+            wire.write(createFrame(Constants.OPCODE_TEXT, true,
+                    deflateMessage(deflater, 
expected.getBytes(StandardCharsets.UTF_8))));
+        } finally {
+            deflater.end();
+        }
+
+        List<List<Parameter>> preferences = new ArrayList<>();
+        preferences.add(Collections.emptyList());
+        PerMessageDeflate perMessageDeflate = 
PerMessageDeflate.build(preferences, false);
+        Assert.assertNotNull(perMessageDeflate);
+
+        List<String> received = new ArrayList<>();
+        MessageHandler.Whole<String> textHandler = received::add;
+
+        WsSession wsSession = EasyMock.createNiceMock(WsSession.class);
+        
EasyMock.expect(Integer.valueOf(wsSession.getMaxBinaryMessageBufferSize())).andStubReturn(Integer.valueOf(8192));
+        
EasyMock.expect(Integer.valueOf(wsSession.getMaxTextMessageBufferSize())).andStubReturn(Integer.valueOf(8192));
+        
EasyMock.expect(wsSession.getBinaryMessageHandler()).andStubReturn(null);
+        
EasyMock.expect(wsSession.getTextMessageHandler()).andStubReturn(textHandler);
+        EasyMock.replay(wsSession);
+
+        TestFrame frame = new TestFrame(wsSession, perMessageDeflate);
+        byte[] data = wire.toByteArray();
+        for (int i = 0; i < data.length; i += chunkSize) {
+            frame.process(java.util.Arrays.copyOfRange(data, i, (int) 
Math.min(data.length, (long) i + chunkSize)));
+        }
+
+        Assert.assertEquals(1, received.size());
+        Assert.assertEquals(expected, received.get(0));
+    }
+
+
+    private static byte[] deflateMessage(Deflater deflater, byte[] data) {
+        deflater.setInput(data);
+        ByteArrayOutputStream baos = new ByteArrayOutputStream();
+        byte[] buf = new byte[1024];
+        int n;
+        while ((n = deflater.deflate(buf, 0, buf.length, Deflater.SYNC_FLUSH)) 
> 0) {
+            baos.write(buf, 0, n);
+        }
+        byte[] result = baos.toByteArray();
+        // Remove the trailing 0x00 0x00 0xFF 0xFF added by the sync flush 
(RFC 7692, section 7.2.1)
+        Assert.assertTrue(result.length >= 4);
+        return java.util.Arrays.copyOf(result, result.length - 4);
+    }
+
+
+    private static byte[] createFrame(int opCode, boolean compressed, byte[] 
payload) {
+        return createFrame(opCode, true, compressed, payload);
+    }
+
+
+    private static byte[] createFrame(int opCode, boolean fin, boolean 
compressed, byte[] payload) {
+        ByteArrayOutputStream baos = new ByteArrayOutputStream();
+        baos.write((fin ? 0x80 : 0x00) | (compressed ? 0x40 : 0x00) | opCode);
+        if (payload.length <= 125) {
+            baos.write(payload.length);
+        } else {
+            baos.write(126);
+            baos.write(payload.length >>> 8);
+            baos.write(payload.length & 0xFF);
+        }
+        baos.write(payload, 0, payload.length);
+        return baos.toByteArray();
+    }
+
+
     private static class TestFrame extends WsFrameBase {
 
         TestFrame(WsSession wsSession) {
             super(wsSession, null);
         }
 
+        TestFrame(WsSession wsSession, Transformation transformation) {
+            super(wsSession, transformation);
+        }
+
+        void process(byte[] data) throws IOException {
+            // Retain any data from previous calls that has not yet been 
processed
+            inputBuffer.compact();
+            inputBuffer.put(data);
+            inputBuffer.flip();
+            processInputBuffer();
+        }
+
         void processPing() throws IOException {
             inputBuffer.clear();
             inputBuffer.put((byte) 0x89);
diff --git a/webapps/docs/changelog.xml b/webapps/docs/changelog.xml
index ad52bf6520..ef68bc2bfb 100644
--- a/webapps/docs/changelog.xml
+++ b/webapps/docs/changelog.xml
@@ -320,6 +320,17 @@
       </fix>
     </changelog>
   </subsection>
+  <subsection name="WebSocket">
+    <changelog>
+      <fix>
+        Fix the handling of compressed WebSocket messages for which there is no
+        message handler when the <code>permessage-deflate</code> extension is
+        used with context takeover. Such messages are now decompressed and
+        discarded so that later messages are decompressed using the correct
+        window. (markt)
+      </fix>
+    </changelog>
+  </subsection>
   <subsection name="Tribes">
     <changelog>
       <docs>


---------------------------------------------------------------------
To unsubscribe, e-mail: [email protected]
For additional commands, e-mail: [email protected]

Reply via email to