This is an automated email from the ASF dual-hosted git repository.
yiguolei pushed a commit to branch branch-4.1
in repository https://gitbox.apache.org/repos/asf/doris.git
The following commit(s) were added to refs/heads/branch-4.1 by this push:
new c6f5af33e83 branch-4.1: [fix](fe) Enforce max_allowed_packet for
incoming MySQL packets (#71096)
c6f5af33e83 is described below
commit c6f5af33e83256425f7ef0b994648649aff7de98
Author: Calvin Kirs <[email protected]>
AuthorDate: Wed Dec 2 11:32:21 2026 +0800
branch-4.1: [fix](fe) Enforce max_allowed_packet for incoming MySQL packets
(#71096)
https://github.com/apache/doris/pull/70420
---
.../java/org/apache/doris/common/ErrorCode.java | 2 +
.../java/org/apache/doris/mysql/MysqlChannel.java | 212 +++++++---------
.../java/org/apache/doris/qe/SessionVariable.java | 2 +-
.../org/apache/doris/mysql/MysqlChannelTest.java | 273 +++++++++++++++++++--
4 files changed, 338 insertions(+), 151 deletions(-)
diff --git a/fe/fe-core/src/main/java/org/apache/doris/common/ErrorCode.java
b/fe/fe-core/src/main/java/org/apache/doris/common/ErrorCode.java
index b0748cef9a3..da732f8a998 100644
--- a/fe/fe-core/src/main/java/org/apache/doris/common/ErrorCode.java
+++ b/fe/fe-core/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 73fd522c22b..39c9d90cba4 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;
@@ -225,13 +226,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(),
@@ -320,144 +314,110 @@ 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();
- }
+ accSequenceId();
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 0e7622fcf60..25a02dba4f0 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
@@ -1340,7 +1340,7 @@ public class SessionVariable implements Serializable,
Writable {
@VariableMgr.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.
@VariableMgr.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 78d18b58bad..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
@@ -21,42 +21,267 @@ package org.apache.doris.mysql;
import org.apache.doris.common.jmockit.Deencapsulation;
import org.apache.doris.qe.ConnectContext;
-import mockit.Delegate;
-import mockit.Expectations;
-import mockit.Mocked;
-import org.junit.Assert;
-import org.junit.Test;
+import org.junit.jupiter.api.Assertions;
+import org.junit.jupiter.api.Test;
+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 {
- @Mocked
- StreamConnection streamConnection;
+ 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 {
+ // Mock StreamConnection.getPeerAddress() to avoid NPE in MysqlChannel
constructor
+ Mockito.when(streamConnection.getPeerAddress())
+ .thenReturn(new java.net.InetSocketAddress("127.0.0.1",
12345));
+
// Mock.
- new Expectations() {
- {
- streamConnection.getSinkChannel().write((ByteBuffer) any);
+ ConduitStreamSinkChannel mockSinkChannel =
Mockito.mock(ConduitStreamSinkChannel.class);
+
Mockito.when(streamConnection.getSinkChannel()).thenReturn(mockSinkChannel);
+
Mockito.when(mockSinkChannel.write(ArgumentMatchers.any(ByteBuffer.class)))
// The first call to `write()` throws IOException.
- result = new IOException();
+ .thenThrow(new IOException())
// The second call to `write()` executes normally.
- result = new Delegate() {
- int fakeRead(ByteBuffer buffer) {
- int writeLen = buffer.remaining();
- buffer.position(buffer.limit());
- return writeLen;
- }
- };
-
- streamConnection.getSinkChannel().flush();
- result = true;
- }
- };
+ .thenAnswer(inv -> {
+ ByteBuffer buffer = inv.getArgument(0);
+ int writeLen = buffer.remaining();
+ buffer.position(buffer.limit());
+ return writeLen;
+ });
+ Mockito.when(mockSinkChannel.flush()).thenReturn(true);
ConnectContext ctx = new ConnectContext(streamConnection);
MysqlChannel mysqlChannel = new MysqlChannel(streamConnection, ctx);
@@ -71,7 +296,7 @@ public class MysqlChannelTest {
buf.flip();
try {
mysqlChannel.sendOnePacket(buf);
- Assert.fail();
+ Assertions.fail();
} catch (IOException ignore) {
// do nothing
}
---------------------------------------------------------------------
To unsubscribe, e-mail: [email protected]
For additional commands, e-mail: [email protected]