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

CalvinKirs pushed a commit to branch master
in repository https://gitbox.apache.org/repos/asf/doris.git


The following commit(s) were added to refs/heads/master by this push:
     new bdddd95867c [fix](fe) Enforce max_allowed_packet for incoming MySQL 
packets (#70420)
bdddd95867c is described below

commit bdddd95867ca9795bff3ef5fe7f00f979102b599
Author: Calvin Kirs <[email protected]>
AuthorDate: Tue Nov 17 09:55:30 2026 +0800

    [fix](fe) Enforce max_allowed_packet for incoming MySQL packets (#70420)
    
    ### Background
    
    FE reassembles MySQL physical frames into a logical packet before
    parsing handshake responses or commands. The existing
    `max_allowed_packet` variable defaults to 16 MiB and previously applied
    only to prepared-statement long data.
    
    ### What problem does this PR solve?
    
    Issue Number: None
    Related PR: None
    PR Type: Bugfix
    
    Problem Summary:
    
    Incoming logical packets did not honor `max_allowed_packet`:
    continuation frames were appended without checking their accumulated
    payload size. Check the total before reading each payload or growing its
    buffer, using the same logical-packet reader for plaintext and decrypted
    TLS traffic. Oversized packets return `ER_NET_PACKET_TOO_LARGE` (1153)
    and close the connection. TLS record refills also stop after inbound
    closure while preserving any remaining plaintext.
    
    ### Details
    
    - **Change map:** Three production files (+90/-128) and one test file
    (+227); no generated files or docs. `MysqlChannel` shares plaintext/TLS
    framing, checks cumulative payload size and buffer capacity, and handles
    rejection and TLS EOF. The other production changes add the standard
    MySQL error code and update the existing variable's comment.
    - **Frequency:** Whenever an incoming logical packet exceeds the
    configured limit; the TLS EOF case occurs when a peer sends
    `close_notify` while FE is reading a packet.
    - **Root cause:** The receive path enforced physical framing but did not
    compare the reassembled size with `max_allowed_packet`. The TLS refill
    loop also treated a closed engine with no application bytes as an open
    empty record.
    - **Why existing tests missed it:** Receive-side continuation limits and
    consumed TLS `CLOSED` records were not covered.
    - **Fix:** Use long arithmetic to check cumulative size before payload
    reads and allocation, bound buffer growth, and close even if writing the
    ERR response fails. Preserve buffered plaintext and distinguish
    established TLS EOF from an open empty record.
    - **Other paths and branches:** Handshake responses, commands and LOCAL
    INFILE share the receive check. Raw TLS handshake records retain
    separate framing; prepared-statement long-data handling keeps its
    existing limit.
    - **Behavior change:** The existing 16 MiB default now applies to
    incoming logical packets. Raise `GLOBAL max_allowed_packet` before
    opening connections that require larger requests; session changes apply
    to subsequent packets on that session.
    
    ### Testing
    
    All validation ran locally:
    
    - The oversized-header regression fails on the original implementation
    and passes with this fix.
    - `bash run-fe-ut.sh --run
    
org.apache.doris.mysql.MysqlChannelTest,org.apache.doris.mysql.MysqlProtoTest,org.apache.doris.mysql.protocol.MysqlProtocolAdapterTest`:
    32 tests passed, with no failures, errors or skips. Coverage includes
    continuation boundaries, rejection before body reads, failed ERR writes,
    TLS fragmentation/coalescing and TLS inbound closure.
    - `DISABLE_BUILD_UI=ON FE_MAVEN_THREADS=4 bash build.sh --fe
    --exclude-obs-dependencies --exclude-cos-dependencies`: passed,
    including Checkstyle. Separate Checkstyle checks for `fe-common` and
    `fe-core` also passed.
    - Connector/J 8.0.27, 8.0.33, 8.4.0 and 9.7.0: 104 compatibility cases
    passed, with no failures or skips, including real TLS and cross-FE
    forwarding. Both FEs used this patch; BE used an existing 4.1.3 binary.
    Test users/databases were cleaned up and authentication configuration
    was restored.
    - Real socket checks over plaintext and TLS: oversized handshake
    continuations are rejected after the header without sending the
    continuation body; exactly 16 MiB succeeds and the connection remains
    usable; one byte over the limit returns 1153.
    - `git diff --check`: passed.
    
    ### Release note
    
    Incoming MySQL logical packets now honor `max_allowed_packet` over
    plaintext and TLS. Its default remains 16 MiB. Oversized packets receive
    error 1153 and the connection closes; increase `GLOBAL
    max_allowed_packet` before opening new connections when larger requests
    are needed.
    
    ### Check List (For Author)
    
    - Behavior changed: Yes (see Details).
    - Does this need documentation: No; the existing variable and default
    are unchanged, and the newly enforced behavior is described in the
    release note.
    - Pre-submission status: Ready.
    
    ### AI Disclosure
    
    - Tool: Codex (GPT-6).
    - Generated: Code, tests and this description.
    - Human review: Pending maintainer review.
---
 .../java/org/apache/doris/common/ErrorCode.java    |   2 +
 .../java/org/apache/doris/mysql/MysqlChannel.java  | 214 ++++++++-----------
 .../java/org/apache/doris/qe/SessionVariable.java  |   2 +-
 .../org/apache/doris/mysql/MysqlChannelTest.java   | 227 +++++++++++++++++++++
 4 files changed, 317 insertions(+), 128 deletions(-)

diff --git a/fe/fe-common/src/main/java/org/apache/doris/common/ErrorCode.java 
b/fe/fe-common/src/main/java/org/apache/doris/common/ErrorCode.java
index bb7c1c994be..86bb870adce 100644
--- a/fe/fe-common/src/main/java/org/apache/doris/common/ErrorCode.java
+++ b/fe/fe-common/src/main/java/org/apache/doris/common/ErrorCode.java
@@ -60,6 +60,8 @@ public enum ErrorCode {
             + "table '%s'"),
     ERR_NOT_ALLOWED_COMMAND(1148, new byte[]{'4', '2', '0', '0', '0'}, "The 
used command is not allowed"
             + " with this MySQL version"),
+    ERR_NET_PACKET_TOO_LARGE(1153, new byte[]{'0', '8', 'S', '0', '1'},
+            "Got a packet bigger than 'max_allowed_packet' bytes"),
     ERR_WRONG_COLUMN_NAME(1166, new byte[]{'4', '2', '0', '0', '0'}, 
"Incorrect column name '%s'. Column regex is '%s'"),
     ERR_UNKNOWN_SYSTEM_VARIABLE(1193, new byte[]{'H', 'Y', '0', '0', '0'}, 
"Unknown system variable '%s',"
                     + "the similar variables are %s"),
diff --git a/fe/fe-core/src/main/java/org/apache/doris/mysql/MysqlChannel.java 
b/fe/fe-core/src/main/java/org/apache/doris/mysql/MysqlChannel.java
index 28c85afeca9..f6ded5bf421 100644
--- a/fe/fe-core/src/main/java/org/apache/doris/mysql/MysqlChannel.java
+++ b/fe/fe-core/src/main/java/org/apache/doris/mysql/MysqlChannel.java
@@ -18,6 +18,7 @@
 package org.apache.doris.mysql;
 
 import org.apache.doris.common.ConnectionException;
+import org.apache.doris.common.ErrorCode;
 import org.apache.doris.common.util.NetUtils;
 import org.apache.doris.qe.ConnectContext;
 import org.apache.doris.qe.ConnectProcessor;
@@ -231,13 +232,6 @@ public class MysqlChannel implements BytesChannel {
         if (!dstBuf.hasRemaining()) {
             return 0;
         }
-        if (remainingBuffer != null && remainingBuffer.hasRemaining()) {
-            int oldLen = dstBuf.position();
-            while (dstBuf.hasRemaining()) {
-                dstBuf.put(remainingBuffer.get());
-            }
-            return dstBuf.position() - oldLen;
-        }
         try {
             while (dstBuf.remaining() != 0) {
                 int ret = Channels.readBlocking(conn.getSourceChannel(), 
dstBuf, context.getNetReadTimeout(),
@@ -326,145 +320,111 @@ public class MysqlChannel implements BytesChannel {
     // NOTE: all of the following code is assumed that the channel is in block 
mode.
     // if in handshaking mode we return a packet with header otherwise without 
header.
     public ByteBuffer fetchOnePacket() throws IOException {
-        int readLen;
+        if (context.isKilled()) {
+            return null;
+        }
+        if (isSslHandshaking) {
+            return readSslPacket();
+        }
         ByteBuffer result = defaultBuffer;
         result.clear();
 
         while (true) {
-            int packetLen;
-            // one SSL packet may include multiple Mysql packets, we use 
remainingBuffer to store them.
-            if ((isSslMode || isSslHandshaking) && 
!remainingBuffer.hasRemaining()) {
-                if (remainingBuffer.position() != 0) {
-                    remainingBuffer.clear();
-                    remainingBuffer.flip();
-                }
-                sslHeaderByteBuffer.clear();
-                readLen = readAll(sslHeaderByteBuffer, true);
-                if (readLen != SSL_PACKET_HEADER_LEN) {
-                    // remote has close this channel
-                    if (LOG.isDebugEnabled()) {
-                        LOG.debug("Receive ssl packet header failed, remote 
may close the channel.");
-                    }
-                    return null;
-                }
-                // when handshaking and ssl mode, sslengine unwrap need a 
packet with header.
-                result.put(sslHeaderByteBuffer.array());
-                packetLen = packetLen(true);
-            } else {
-                headerByteBuffer.clear();
-                readLen = readAll(headerByteBuffer, true);
-                if (readLen != PACKET_HEADER_LEN) {
-                    // remote has close this channel
-                    if (LOG.isDebugEnabled()) {
-                        LOG.debug("Receive packet header failed, remote may 
close the channel.");
-                    }
-                    return null;
-                }
-                if (packetId() != sequenceId) {
-                    LOG.warn("receive packet sequence id[" + packetId() + "] 
want to get[" + sequenceId + "]");
-                    throw new IOException("Bad packet sequence.");
-                }
-                packetLen = packetLen(false);
+            headerByteBuffer.clear();
+            if (readMysqlData(headerByteBuffer) != PACKET_HEADER_LEN) {
+                return null;
             }
-            result = expandPacket(result, packetLen);
-
-            // read one physical packet
-            // before read, set limit to make read only one packet
-            result.limit(result.position() + packetLen);
-            readLen = readAll(result, false);
-            if (isSslMode && remainingBuffer.position() == 0 && 
result.hasRemaining()) {
-                int available = result.limit();
-                if (available < PACKET_HEADER_LEN) {
-                    LOG.warn("SSL mode: invalid mysql packet header, available 
bytes: " + available);
-                    throw new IOException("Invalid mysql packet header.");
-                }
-                byte[] header = result.array();
-                int mysqlPacketLength = (header[0] & 0xFF) | ((header[1] & 
0xFF) << 8) | ((header[2] & 0xFF) << 16);
-                if (mysqlPacketLength > MAX_PHYSICAL_PACKET_LENGTH) {
-                    LOG.warn("SSL mode: mysql packet length(" + 
mysqlPacketLength + ") is larger than max physical "
-                            + "packet length(" + MAX_PHYSICAL_PACKET_LENGTH + 
")");
-                    throw new IOException("Mysql packet too large.");
-                }
-                int packetId = header[3] & 0xFF;
-                if (packetId != sequenceId) {
-                    LOG.warn("receive packet sequence id[" + packetId + "] 
want to get[" + sequenceId + "]");
-                    throw new IOException("Bad packet sequence.");
-                }
-                // remove mysql packet header
-                result.position(4);
-                result.compact();
-                // when encounter large sql query, one mysql packet will be 
packed as multiple ssl packets.
-                // we need to read all ssl packets to combine the complete 
mysql packet.
-                while (mysqlPacketLength > result.position()) {
-                    sslHeaderByteBuffer.clear();
-                    readLen = readAll(sslHeaderByteBuffer, true);
-                    if (readLen != SSL_PACKET_HEADER_LEN) {
-                        // remote has close this channel
-                        if (LOG.isDebugEnabled()) {
-                            LOG.debug("Receive ssl packet header failed, 
remote may close the channel.");
-                        }
-                        return null;
-                    }
-                    tempBuffer.clear();
-                    tempBuffer.put(sslHeaderByteBuffer.array());
-                    packetLen = packetLen(true);
-                    LOG.info("one ssl packet length is: " + packetLen);
-                    tempBuffer = expandPacket(tempBuffer, packetLen);
-                    result = expandPacket(result, tempBuffer.capacity());
-                    // read one physical packet
-                    // before read, set limit to make read only one packet
-                    tempBuffer.limit(tempBuffer.position() + packetLen);
-                    readLen = readAll(tempBuffer, false);
-                    result.put(tempBuffer);
-                    result.limit(result.position());
-                    LOG.info("result is pos: " + result.position() + ", limit: 
"
-                            + result.limit() + "capacity: " + 
result.capacity());
-                }
-                if (mysqlPacketLength < result.position()) {
-                    LOG.info("one SSL packet has multiple mysql packets.");
-                    LOG.info("mysql packet length is " + mysqlPacketLength + 
", result is pos: "
-                            + result.position() + ", limit: " + result.limit() 
+ "capacity: " + result.capacity());
-                    result.flip();
-                    result.position(mysqlPacketLength);
-                    remainingBuffer.clear();
-                    remainingBuffer.put(result);
-                    remainingBuffer.flip();
-                }
-                result.position(mysqlPacketLength);
+            if (packetId() != sequenceId) {
+                LOG.warn("receive packet sequence id[" + packetId() + "] want 
to get[" + sequenceId + "]");
+                throw new IOException("Bad packet sequence.");
             }
-            if (readLen != packetLen) {
-                LOG.warn("Length of received packet content(" + readLen
-                        + ") is not equal with length in head.(" + packetLen + 
")");
+            int packetLen = packetLen(false);
+            result = expandPacket(result, packetLen);
+            if (readMysqlData(result) != packetLen) {
                 return null;
             }
-            if (!isSslHandshaking) {
-                accSequenceId();
-                wireSequenceId = sequenceId;
-            }
+            accSequenceId();
+            wireSequenceId = sequenceId;
             if (packetLen != MAX_PHYSICAL_PACKET_LENGTH) {
                 result.flip();
-                break;
+                return result;
             }
         }
-        return result;
+    }
+
+    // TLS records may split a MySQL header or body, or contain several MySQL 
packets.
+    private int readMysqlData(ByteBuffer dst) throws IOException {
+        if (!isSslMode) {
+            return readAll(dst, false);
+        }
+        int start = dst.position();
+        while (dst.hasRemaining()) {
+            if (!remainingBuffer.hasRemaining()) {
+                ByteBuffer record = readSslPacket();
+                if (record == null) {
+                    return dst.position() - start;
+                }
+                remainingBuffer = record;
+            }
+            int limit = remainingBuffer.limit();
+            remainingBuffer.limit(remainingBuffer.position() + 
Math.min(dst.remaining(), remainingBuffer.remaining()));
+            dst.put(remainingBuffer);
+            remainingBuffer.limit(limit);
+        }
+        return dst.position() - start;
+    }
+
+    // Handshake callers need the raw record, including its header; 
established TLS returns plaintext.
+    private ByteBuffer readSslPacket() throws IOException {
+        if (isSslMode && sslEngine.isInboundDone()) {
+            return null;
+        }
+        sslHeaderByteBuffer.clear();
+        if (readAll(sslHeaderByteBuffer, true) != SSL_PACKET_HEADER_LEN) {
+            return null;
+        }
+        int packetLen = packetLen(true);
+        int recordLength = SSL_PACKET_HEADER_LEN + packetLen;
+        if (tempBuffer.capacity() < recordLength) {
+            tempBuffer = ByteBuffer.allocate(recordLength);
+        }
+        tempBuffer.clear();
+        tempBuffer.put(sslHeaderByteBuffer.array());
+        tempBuffer.limit(recordLength);
+        if (readAll(tempBuffer, false) != packetLen) {
+            return null;
+        }
+        if (!isSslMode) {
+            tempBuffer.flip();
+        }
+        return tempBuffer;
     }
 
     @NotNull
-    private ByteBuffer expandPacket(ByteBuffer result, int packetLen) {
-        if ((result.capacity() - result.position()) < packetLen) {
-            // byte buffer is not enough, new one packet
-            ByteBuffer tmp;
-            if (packetLen < MAX_PHYSICAL_PACKET_LENGTH) {
-                // last packet, enough to this packet is OK.
-                tmp = ByteBuffer.allocate(packetLen + result.position());
-            } else {
-                // already have packet, to allocate two packet.
-                tmp = ByteBuffer.allocate(2 * packetLen + result.position());
+    private ByteBuffer expandPacket(ByteBuffer result, int packetLen) throws 
IOException {
+        long required = (long) result.position() + packetLen;
+        int maxPacketSize = context.getSessionVariable().getMaxAllowedPacket();
+        if (required > maxPacketSize) {
+            String message = 
ErrorCode.ERR_NET_PACKET_TOO_LARGE.formatErrorMsg();
+            int errorSequenceId = (sequenceId + 1) & 0xff;
+            reset();
+            setSequenceId(errorSequenceId);
+            context.getState().setError(ErrorCode.ERR_NET_PACKET_TOO_LARGE, 
message);
+            try {
+                MysqlProto.sendResponsePacket(context);
+            } finally {
+                context.setKilled();
+                close();
             }
+            throw new IOException(message);
+        }
+        if ((result.capacity() - result.position()) < packetLen) {
+            long capacity = packetLen < MAX_PHYSICAL_PACKET_LENGTH ? required 
: required + packetLen;
+            ByteBuffer tmp = ByteBuffer.allocate((int) Math.min(capacity, 
maxPacketSize));
             tmp.put(result.array(), 0, result.position());
             result = tmp;
         }
-        result.limit(result.position() + packetLen);
+        result.limit((int) required);
         return result;
     }
 
diff --git a/fe/fe-core/src/main/java/org/apache/doris/qe/SessionVariable.java 
b/fe/fe-core/src/main/java/org/apache/doris/qe/SessionVariable.java
index 1050f4c29e4..7544a5948da 100644
--- a/fe/fe-core/src/main/java/org/apache/doris/qe/SessionVariable.java
+++ b/fe/fe-core/src/main/java/org/apache/doris/qe/SessionVariable.java
@@ -1378,7 +1378,7 @@ public class SessionVariable implements Serializable, 
Writable {
     @VarAttrDef.VarAttr(name = SQL_SELECT_LIMIT, needForward = true, 
affectQueryResultInExecution = true)
     private long sqlSelectLimit = Long.MAX_VALUE;
 
-    // this is used to make c3p0 library happy
+    // Maximum incoming MySQL logical packet and prepared-statement long-data 
size, in bytes.
     @VarAttrDef.VarAttr(name = MAX_ALLOWED_PACKET)
     public int maxAllowedPacket = 16777216;
 
diff --git 
a/fe/fe-core/src/test/java/org/apache/doris/mysql/MysqlChannelTest.java 
b/fe/fe-core/src/test/java/org/apache/doris/mysql/MysqlChannelTest.java
index fe796991efe..180e36658bc 100644
--- a/fe/fe-core/src/test/java/org/apache/doris/mysql/MysqlChannelTest.java
+++ b/fe/fe-core/src/test/java/org/apache/doris/mysql/MysqlChannelTest.java
@@ -27,13 +27,240 @@ import org.mockito.ArgumentMatchers;
 import org.mockito.Mockito;
 import org.xnio.StreamConnection;
 import org.xnio.conduits.ConduitStreamSinkChannel;
+import org.xnio.conduits.ConduitStreamSourceChannel;
 
+import java.io.ByteArrayOutputStream;
 import java.io.IOException;
 import java.nio.ByteBuffer;
+import java.util.Arrays;
+import java.util.concurrent.atomic.AtomicBoolean;
+import javax.net.ssl.SSLEngine;
+import javax.net.ssl.SSLEngineResult;
+import javax.net.ssl.SSLSession;
 
 public class MysqlChannelTest {
 
     StreamConnection streamConnection = Mockito.mock(StreamConnection.class);
+    private ConnectContext receivingContext;
+    private ByteArrayOutputStream response;
+
+    @Test
+    public void testOversizedPacketRejectedBeforeBody() throws IOException {
+        for (boolean writeFails : new boolean[]{false, true}) {
+            ByteBuffer input = ByteBuffer.allocate(4);
+            putHeader(input, 9, 1);
+            input.flip();
+            MysqlChannel channel = receivingChannel(input, 8);
+            channel.setSequenceId(1);
+            if (writeFails) {
+                ConduitStreamSinkChannel sink = 
streamConnection.getSinkChannel();
+                Mockito.doThrow(new IOException("write failed")).when(sink)
+                        .write(ArgumentMatchers.any(ByteBuffer.class));
+            }
+
+            Assertions.assertThrows(IOException.class, 
channel::fetchOnePacket);
+            Assertions.assertEquals(4, input.position());
+            
Mockito.verify(streamConnection.getSourceChannel()).read(ArgumentMatchers.any(ByteBuffer.class));
+            Assertions.assertTrue(receivingContext.isKilled());
+            Mockito.verify(streamConnection).close();
+            Assertions.assertNull(channel.fetchOnePacket());
+            if (writeFails) {
+                continue;
+            }
+            assertPacketTooLarge(2);
+        }
+    }
+
+    @Test
+    public void testContinuationPacketLimit() throws IOException {
+        int fullLength = MysqlChannel.MAX_PHYSICAL_PACKET_LENGTH;
+        int maxLength = fullLength + 8;
+        for (int tailLength : new int[]{0, 8, 9}) {
+            ByteBuffer input = ByteBuffer.allocate(fullLength + 8 + 
tailLength);
+            putHeader(input, fullLength, 1);
+            input.position(fullLength + 4);
+            putHeader(input, tailLength, 2);
+            input.position(input.capacity());
+            input.flip();
+            MysqlChannel channel = receivingChannel(input, maxLength);
+            channel.setSequenceId(1);
+
+            if (tailLength < 9) {
+                ByteBuffer packet = channel.fetchOnePacket();
+                Assertions.assertEquals(fullLength + tailLength, 
packet.remaining());
+                Assertions.assertTrue(packet.capacity() <= maxLength);
+                Assertions.assertEquals(input.limit(), input.position());
+                Assertions.assertFalse(receivingContext.isKilled());
+                Mockito.verify(streamConnection, Mockito.never()).close();
+                continue;
+            }
+            Assertions.assertThrows(IOException.class, 
channel::fetchOnePacket);
+            Assertions.assertEquals(fullLength + 8, input.position());
+            Mockito.verify(streamConnection.getSourceChannel(), 
Mockito.times(3))
+                    .read(ArgumentMatchers.any(ByteBuffer.class));
+            Assertions.assertTrue(receivingContext.isKilled());
+            Mockito.verify(streamConnection).close();
+            assertPacketTooLarge(3);
+        }
+    }
+
+    @Test
+    public void testSslPacketLimitAcrossRecords() throws IOException {
+        byte[] handshakeRecord = {0x16, 3, 3, 0, 2, 1, 0};
+        MysqlChannel handshake = 
receivingChannel(ByteBuffer.wrap(handshakeRecord), 1);
+        handshake.initSslBuffer();
+        handshake.setSslHandshaking(true);
+        handshake.setSequenceId(1);
+        Assertions.assertEquals(ByteBuffer.wrap(handshakeRecord), 
handshake.fetchOnePacket());
+        Assertions.assertEquals(1, handshake.sequenceId);
+        Assertions.assertFalse(receivingContext.isKilled());
+        Assertions.assertEquals(0, response.size());
+        Mockito.verify(streamConnection, Mockito.never()).close();
+
+        ByteBuffer first = ByteBuffer.allocate(9);
+        putHeader(first, 5, 1);
+        first.put(new byte[]{1, 2, 3, 4, 5});
+        ByteBuffer lastRecord = ByteBuffer.allocate(16);
+        lastRecord.put(first.array(), 6, 3);
+        putHeader(lastRecord, 5, 2);
+        lastRecord.put(new byte[]{6, 7, 8, 9, 10});
+        putHeader(lastRecord, 6, 3);
+        ByteArrayOutputStream wire = new ByteArrayOutputStream();
+        putSslRecord(wire, Arrays.copyOfRange(first.array(), 0, 2));
+        putSslRecord(wire, Arrays.copyOfRange(first.array(), 2, 6));
+        putSslRecord(wire, lastRecord.array());
+        MysqlChannel channel = 
receivingChannel(ByteBuffer.wrap(wire.toByteArray()), 5);
+        channel.initSslBuffer();
+        SSLEngine engine = mockSslEngine();
+        // Leave cryptography to JSSE; exercise the real TLS-record and MySQL 
framing with plaintext records.
+        Mockito.when(engine.unwrap(ArgumentMatchers.any(ByteBuffer.class), 
ArgumentMatchers.any(ByteBuffer.class)))
+                .thenAnswer(inv -> {
+                    ByteBuffer src = inv.getArgument(0);
+                    ByteBuffer dst = inv.getArgument(1);
+                    int consumed = src.remaining();
+                    src.position(src.position() + 5);
+                    int produced = src.remaining();
+                    dst.put(src);
+                    return new SSLEngineResult(SSLEngineResult.Status.OK,
+                            SSLEngineResult.HandshakeStatus.NOT_HANDSHAKING, 
consumed, produced);
+                });
+        Mockito.when(engine.wrap(ArgumentMatchers.any(ByteBuffer.class), 
ArgumentMatchers.any(ByteBuffer.class)))
+                .thenAnswer(inv -> {
+                    ByteBuffer src = inv.getArgument(0);
+                    ByteBuffer dst = inv.getArgument(1);
+                    int length = src.remaining();
+                    dst.put(src);
+                    return new SSLEngineResult(SSLEngineResult.Status.OK,
+                            SSLEngineResult.HandshakeStatus.NOT_HANDSHAKING, 
length, length);
+                });
+        channel.setSslEngine(engine);
+        channel.setSslMode(true);
+        channel.setSequenceId(1);
+
+        ByteBuffer packet = channel.fetchOnePacket();
+        byte[] payload = new byte[packet.remaining()];
+        packet.get(payload);
+        Assertions.assertArrayEquals(new byte[]{1, 2, 3, 4, 5}, payload);
+        packet = channel.fetchOnePacket();
+        packet.get(payload);
+        Assertions.assertArrayEquals(new byte[]{6, 7, 8, 9, 10}, payload);
+        Assertions.assertThrows(IOException.class, channel::fetchOnePacket);
+        Mockito.verify(streamConnection).close();
+        assertPacketTooLarge(4);
+    }
+
+    @Test
+    public void testSslCloseNotifyStopsReading() throws IOException {
+        ByteBuffer input = ByteBuffer.wrap(new byte[]{0x17, 3, 3, 0, 1, 0, 
0x15, 3, 3, 0, 2, 1, 0});
+        MysqlChannel channel = receivingChannel(input, 16);
+        channel.initSslBuffer();
+        SSLEngine engine = mockSslEngine();
+        AtomicBoolean inboundDone = new AtomicBoolean();
+        Mockito.when(engine.isInboundDone()).thenAnswer(inv -> 
inboundDone.get());
+        Mockito.when(engine.unwrap(ArgumentMatchers.any(ByteBuffer.class), 
ArgumentMatchers.any(ByteBuffer.class)))
+                .thenAnswer(inv -> {
+                    ByteBuffer src = inv.getArgument(0);
+                    int consumed = src.remaining();
+                    boolean closed = src.get(0) == 0x15;
+                    src.position(src.limit());
+                    inboundDone.set(closed);
+                    // An empty application record keeps TLS open; 
close_notify ends inbound data.
+                    return new SSLEngineResult(closed ? 
SSLEngineResult.Status.CLOSED : SSLEngineResult.Status.OK,
+                            SSLEngineResult.HandshakeStatus.NOT_HANDSHAKING, 
consumed, 0);
+                });
+        channel.setSslEngine(engine);
+        channel.setSslMode(true);
+
+        Assertions.assertNull(channel.fetchOnePacket());
+        Assertions.assertTrue(inboundDone.get());
+        Assertions.assertEquals(input.limit(), input.position());
+        Mockito.verify(streamConnection.getSourceChannel(), Mockito.times(4))
+                .read(ArgumentMatchers.any(ByteBuffer.class));
+    }
+
+    private static SSLEngine mockSslEngine() {
+        SSLEngine engine = Mockito.mock(SSLEngine.class);
+        SSLSession session = Mockito.mock(SSLSession.class);
+        Mockito.when(engine.getSession()).thenReturn(session);
+        Mockito.when(session.getApplicationBufferSize()).thenReturn(16384);
+        Mockito.when(session.getPacketBufferSize()).thenReturn(16384);
+        return engine;
+    }
+
+    private MysqlChannel receivingChannel(ByteBuffer input, int maxPacketSize) 
throws IOException {
+        streamConnection = Mockito.mock(StreamConnection.class);
+        Mockito.when(streamConnection.getPeerAddress())
+                .thenReturn(new java.net.InetSocketAddress("127.0.0.1", 
12345));
+        ConduitStreamSourceChannel source = 
Mockito.mock(ConduitStreamSourceChannel.class);
+        Mockito.when(streamConnection.getSourceChannel()).thenReturn(source);
+        
Mockito.when(source.read(ArgumentMatchers.any(ByteBuffer.class))).thenAnswer(inv
 -> {
+            if (!input.hasRemaining()) {
+                return -1;
+            }
+            ByteBuffer dst = inv.getArgument(0);
+            int length = Math.min(dst.remaining(), input.remaining());
+            int limit = input.limit();
+            input.limit(input.position() + length);
+            dst.put(input);
+            input.limit(limit);
+            return length;
+        });
+        ConduitStreamSinkChannel sink = 
Mockito.mock(ConduitStreamSinkChannel.class);
+        Mockito.when(streamConnection.getSinkChannel()).thenReturn(sink);
+        response = new ByteArrayOutputStream();
+        
Mockito.when(sink.write(ArgumentMatchers.any(ByteBuffer.class))).thenAnswer(inv 
-> {
+            ByteBuffer buffer = inv.getArgument(0);
+            byte[] bytes = new byte[buffer.remaining()];
+            buffer.get(bytes);
+            response.write(bytes);
+            return bytes.length;
+        });
+        Mockito.when(sink.flush()).thenReturn(true);
+        receivingContext = new ConnectContext(streamConnection);
+        receivingContext.getSessionVariable().maxAllowedPacket = maxPacketSize;
+        return receivingContext.getMysqlChannel();
+    }
+
+    private void assertPacketTooLarge(int sequenceId) {
+        ByteBuffer packet = ByteBuffer.wrap(response.toByteArray());
+        packet.position(3);
+        Assertions.assertEquals(sequenceId, packet.get() & 0xff);
+        Assertions.assertEquals(0xff, packet.get() & 0xff);
+        Assertions.assertEquals(1153, (packet.get() & 0xff) | ((packet.get() & 
0xff) << 8));
+    }
+
+    private static void putHeader(ByteBuffer buffer, int length, int 
sequenceId) {
+        buffer.put((byte) length).put((byte) (length >> 8)).put((byte) (length 
>> 16)).put((byte) sequenceId);
+    }
+
+    private static void putSslRecord(ByteArrayOutputStream output, byte[] 
payload) {
+        output.write(0x17);
+        output.write(3);
+        output.write(3);
+        output.write(payload.length >> 8);
+        output.write(payload.length);
+        output.write(payload, 0, payload.length);
+    }
 
     @Test
     public void testSendAfterException() throws IOException {


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

Reply via email to