You are viewing a plain text version of this content. The canonical link for it is here.
Posted to commits@ignite.apache.org by ni...@apache.org on 2022/04/01 12:03:54 UTC
[ignite] branch master updated: IGNITE-7153 Fix parser to handle incomplete Redis packet (#9925)
This is an automated email from the ASF dual-hosted git repository.
nizhikov pushed a commit to branch master
in repository https://gitbox.apache.org/repos/asf/ignite.git
The following commit(s) were added to refs/heads/master by this push:
new 2cc50e5 IGNITE-7153 Fix parser to handle incomplete Redis packet (#9925)
2cc50e5 is described below
commit 2cc50e5bde0ada28e2f8de58cec0ed476a56a6c1
Author: Nikolay <ni...@apache.org>
AuthorDate: Fri Apr 1 15:03:30 2022 +0300
IGNITE-7153 Fix parser to handle incomplete Redis packet (#9925)
---
.../client/suite/IgniteClientTestSuite.java | 2 +
.../rest/protocols/tcp/TcpRedisParserSelfTest.java | 89 +++++++++++++++++
.../tcp/redis/RedisProtocolConnectSelfTest.java | 22 +++++
.../rest/protocols/tcp/GridTcpRestParser.java | 107 ++++++++++++++++++++-
.../rest/protocols/tcp/redis/GridRedisMessage.java | 15 ++-
.../tcp/redis/GridRedisProtocolParser.java | 64 ++++++++----
6 files changed, 273 insertions(+), 26 deletions(-)
diff --git a/modules/clients/src/test/java/org/apache/ignite/internal/client/suite/IgniteClientTestSuite.java b/modules/clients/src/test/java/org/apache/ignite/internal/client/suite/IgniteClientTestSuite.java
index c7ec89b..fa4629b 100644
--- a/modules/clients/src/test/java/org/apache/ignite/internal/client/suite/IgniteClientTestSuite.java
+++ b/modules/clients/src/test/java/org/apache/ignite/internal/client/suite/IgniteClientTestSuite.java
@@ -74,6 +74,7 @@ import org.apache.ignite.internal.processors.rest.RestProcessorMultiStartSelfTes
import org.apache.ignite.internal.processors.rest.RestProcessorStartSelfTest;
import org.apache.ignite.internal.processors.rest.TaskCommandHandlerSelfTest;
import org.apache.ignite.internal.processors.rest.TcpRestUnmarshalVulnerabilityTest;
+import org.apache.ignite.internal.processors.rest.protocols.tcp.TcpRedisParserSelfTest;
import org.apache.ignite.internal.processors.rest.protocols.tcp.TcpRestParserSelfTest;
import org.apache.ignite.internal.processors.rest.protocols.tcp.redis.RedisProtocolConnectSelfTest;
import org.apache.ignite.internal.processors.rest.protocols.tcp.redis.RedisProtocolGetAllAsArrayTest;
@@ -92,6 +93,7 @@ import org.junit.runners.Suite;
// Parser standalone test.
TcpRestParserSelfTest.class,
+ TcpRedisParserSelfTest.class,
// Test memcache protocol with custom test client.
RestMemcacheProtocolSelfTest.class,
diff --git a/modules/clients/src/test/java/org/apache/ignite/internal/processors/rest/protocols/tcp/TcpRedisParserSelfTest.java b/modules/clients/src/test/java/org/apache/ignite/internal/processors/rest/protocols/tcp/TcpRedisParserSelfTest.java
new file mode 100644
index 0000000..f700f28
--- /dev/null
+++ b/modules/clients/src/test/java/org/apache/ignite/internal/processors/rest/protocols/tcp/TcpRedisParserSelfTest.java
@@ -0,0 +1,89 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.apache.ignite.internal.processors.rest.protocols.tcp;
+
+import java.nio.ByteBuffer;
+import java.util.function.Consumer;
+import org.apache.commons.lang3.RandomStringUtils;
+import org.apache.ignite.internal.processors.rest.client.message.GridClientMessage;
+import org.apache.ignite.internal.processors.rest.protocols.tcp.redis.GridRedisMessage;
+import org.junit.Test;
+
+import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.assertNotNull;
+import static org.junit.Assert.assertNull;
+
+/**
+ * Test Redis request parser.
+ * @see <a href="https://redis.io/docs/reference/protocol-spec/">Redis protocol specification.</a>
+ */
+public class TcpRedisParserSelfTest {
+ /** Test check parser works with the message splitted to several network packets. */
+ @Test
+ public void testSplitedPacketParse() throws Exception {
+ String cmd = "SET";
+ String var = "var";
+ String data = RandomStringUtils.randomAscii(10);
+
+ String fullMsg = "*3\r\n" +
+ "$" + cmd.length() + "\r\n" + cmd + "\r\n" +
+ "$" + var.length() + "\r\n" + var + "\r\n" +
+ "$" + data.length() + "\r\n" + data + "\r\n";
+
+ Consumer<GridClientMessage> checker = m -> {
+ GridRedisMessage msg = (GridRedisMessage)m;
+
+ assertNotNull(msg);
+
+ assertEquals(3, msg.fullLength());
+ assertEquals(3, msg.messageSize());
+ assertEquals(cmd, msg.aux(0));
+ assertEquals(var, msg.aux(1));
+ assertEquals(data, msg.aux(2));
+ };
+
+ for (int i = 1; i < fullMsg.length() - 1; i++) {
+ String packet0 = fullMsg.substring(0, i);
+ String packet1 = fullMsg.substring(i);
+
+ GridTcpRestParser.ParserState state = new GridTcpRestParser.ParserState();
+
+ state.packetType(GridClientPacketType.REDIS);
+
+ assertNull(GridTcpRestParser.parseRedisPacket(ByteBuffer.wrap(packet0.getBytes()), state));
+
+ checker.accept(GridTcpRestParser.parseRedisPacket(ByteBuffer.wrap(packet1.getBytes()), state));
+ }
+
+ for (int i = 1; i < fullMsg.length() - 2; i++) {
+ for (int j = i; j < fullMsg.length() - 1; j++) {
+ String packet0 = fullMsg.substring(0, i);
+ String packet1 = fullMsg.substring(i, j);
+ String packet2 = fullMsg.substring(j);
+
+ GridTcpRestParser.ParserState state = new GridTcpRestParser.ParserState();
+
+ state.packetType(GridClientPacketType.REDIS);
+
+ assertNull(GridTcpRestParser.parseRedisPacket(ByteBuffer.wrap(packet0.getBytes()), state));
+ assertNull(GridTcpRestParser.parseRedisPacket(ByteBuffer.wrap(packet1.getBytes()), state));
+ checker.accept(GridTcpRestParser.parseRedisPacket(ByteBuffer.wrap(packet2.getBytes()), state));
+ }
+ }
+ }
+}
diff --git a/modules/clients/src/test/java/org/apache/ignite/internal/processors/rest/protocols/tcp/redis/RedisProtocolConnectSelfTest.java b/modules/clients/src/test/java/org/apache/ignite/internal/processors/rest/protocols/tcp/redis/RedisProtocolConnectSelfTest.java
index 0cff7f8..b22f823 100644
--- a/modules/clients/src/test/java/org/apache/ignite/internal/processors/rest/protocols/tcp/redis/RedisProtocolConnectSelfTest.java
+++ b/modules/clients/src/test/java/org/apache/ignite/internal/processors/rest/protocols/tcp/redis/RedisProtocolConnectSelfTest.java
@@ -17,10 +17,13 @@
package org.apache.ignite.internal.processors.rest.protocols.tcp.redis;
+import org.apache.commons.lang3.RandomStringUtils;
import org.junit.Assert;
import org.junit.Test;
import redis.clients.jedis.Jedis;
+import static org.apache.ignite.internal.util.IgniteUtils.KB;
+
/**
* Tests for Connection commands of Redis protocol.
*/
@@ -74,4 +77,23 @@ public class RedisProtocolConnectSelfTest extends RedisCommonAbstractTest {
Assert.assertEquals("v0", jedis.get("k0"));
}
}
+
+ /** */
+ @Test
+ public void testSetGetLongString() {
+ try (Jedis jedis = pool.getResource()) {
+ for (int len : new int[] {8, 16, 32}) {
+ String key = "b" + len;
+ String val = RandomStringUtils.randomAscii((int)(len * KB));
+
+ jedis.set(key.getBytes(), val.getBytes());
+ Assert.assertArrayEquals(val.getBytes(), jedis.get(key.getBytes()));
+
+ key += "-str";
+
+ jedis.set(key, val);
+ Assert.assertEquals(val, jedis.get(key));
+ }
+ }
+ }
}
diff --git a/modules/core/src/main/java/org/apache/ignite/internal/processors/rest/protocols/tcp/GridTcpRestParser.java b/modules/core/src/main/java/org/apache/ignite/internal/processors/rest/protocols/tcp/GridTcpRestParser.java
index 91d0acd..0b8714a 100644
--- a/modules/core/src/main/java/org/apache/ignite/internal/processors/rest/protocols/tcp/GridTcpRestParser.java
+++ b/modules/core/src/main/java/org/apache/ignite/internal/processors/rest/protocols/tcp/GridTcpRestParser.java
@@ -21,7 +21,6 @@ import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.nio.ByteBuffer;
-import java.nio.charset.Charset;
import java.util.Date;
import java.util.UUID;
import org.apache.ignite.IgniteCheckedException;
@@ -44,6 +43,7 @@ import org.apache.ignite.marshaller.Marshaller;
import org.apache.ignite.marshaller.jdk.JdkMarshaller;
import org.jetbrains.annotations.Nullable;
+import static java.nio.charset.StandardCharsets.UTF_8;
import static org.apache.ignite.internal.processors.rest.protocols.tcp.GridMemcachedMessage.BOOLEAN_FLAG;
import static org.apache.ignite.internal.processors.rest.protocols.tcp.GridMemcachedMessage.BYTE_ARR_FLAG;
import static org.apache.ignite.internal.processors.rest.protocols.tcp.GridMemcachedMessage.BYTE_FLAG;
@@ -68,9 +68,6 @@ import static org.apache.ignite.internal.util.nio.GridNioSessionMetaKey.PARSER_S
* Parser for extended memcache protocol. Handles parsing and encoding activity.
*/
public class GridTcpRestParser implements GridNioParser {
- /** UTF-8 charset. */
- private static final Charset UTF_8 = Charset.forName("UTF-8");
-
/** JDK marshaller. */
private final Marshaller marsh;
@@ -156,7 +153,7 @@ public class GridTcpRestParser implements GridNioParser {
break;
case REDIS:
- res = GridRedisProtocolParser.readArray(buf);
+ res = parseRedisPacket(buf, state);
break;
@@ -247,6 +244,106 @@ public class GridTcpRestParser implements GridNioParser {
}
/**
+ * Parses redis protocol message.
+ *
+ * @param buf Buffer containing not parsed bytes.
+ * @param state Current parser state.
+ * @return Parsed packet(s)
+ * @throws IOException If packet cannot be parsed.
+ * @throws IgniteCheckedException If deserialization error occurred.
+ */
+ static GridClientMessage parseRedisPacket(
+ ByteBuffer buf,
+ ParserState state
+ ) throws IOException, IgniteCheckedException {
+ assert state.packetType() == GridClientPacketType.REDIS;
+
+ // If previous data exists add it to buf.
+ if (state.buffer().size() > 0) {
+ byte[] tail = state.buffer().toByteArray();
+
+ buf = ByteBuffer.allocate(tail.length + buf.remaining())
+ .put(tail)
+ .put(buf);
+
+ buf.rewind();
+ }
+
+ int i;
+ int arrLen;
+ GridRedisMessage msg;
+
+ if (state.packet() == null) {
+ i = 0;
+
+ if (!GridRedisProtocolParser.ensureArrayStart(buf)) {
+ saveTail(state.buffer(), buf);
+
+ return null;
+ }
+
+ arrLen = GridRedisProtocolParser.readInt(buf);
+
+ if (arrLen == GridRedisProtocolParser.ERROR_INT) {
+ buf.rewind();
+
+ saveTail(state.buffer(), buf);
+
+ return null;
+ }
+
+ msg = new GridRedisMessage(arrLen);
+
+ state.packet(msg);
+ }
+ else {
+ msg = (GridRedisMessage)state.packet();
+
+ i = msg.messageSize();
+ arrLen = msg.fullLength();
+ }
+
+ for (; i < arrLen; i++) {
+ int pos = buf.position();
+
+ String str = GridRedisProtocolParser.readBulkStr(buf);
+
+ if (str == null) {
+ buf.position(pos);
+
+ saveTail(state.buffer(), buf);
+
+ return null;
+ }
+
+ msg.append(str);
+ }
+
+ return msg;
+ }
+
+ /** */
+ private static void saveTail(ByteArrayOutputStream os, ByteBuffer buf) throws IOException {
+ os.reset();
+
+ if (!buf.hasRemaining())
+ return;
+
+ if (buf.hasArray()) {
+ os.write(buf.array(), buf.position(), buf.remaining());
+
+ buf.position(buf.position() + buf.remaining());
+ }
+ else {
+ byte[] data = new byte[buf.remaining()];
+
+ buf.get(data);
+
+ os.write(data);
+ }
+ }
+
+ /**
* Parses memcache protocol message.
*
* @param ses Session.
diff --git a/modules/core/src/main/java/org/apache/ignite/internal/processors/rest/protocols/tcp/redis/GridRedisMessage.java b/modules/core/src/main/java/org/apache/ignite/internal/processors/rest/protocols/tcp/redis/GridRedisMessage.java
index 72c57f1..9c349b8 100644
--- a/modules/core/src/main/java/org/apache/ignite/internal/processors/rest/protocols/tcp/redis/GridRedisMessage.java
+++ b/modules/core/src/main/java/org/apache/ignite/internal/processors/rest/protocols/tcp/redis/GridRedisMessage.java
@@ -51,6 +51,9 @@ public class GridRedisMessage implements GridClientMessage {
/** Request message parts. */
private final transient List<String> msgParts;
+ /** Count of message parts . */
+ private final transient int fullLen;
+
/** Response. */
private ByteBuffer response;
@@ -66,14 +69,20 @@ public class GridRedisMessage implements GridClientMessage {
/**
* Constructor.
*
- * @param msgLen Length of the Redis message (command with parameters).
+ * @param fullLen Length of the Redis message (command with parameters).
*/
- public GridRedisMessage(int msgLen) {
- msgParts = new ArrayList<>(msgLen);
+ public GridRedisMessage(int fullLen) {
+ this.fullLen = fullLen;
+ msgParts = new ArrayList<>(fullLen);
cacheName = DFLT_CACHE_NAME;
}
+ /** @return Full message length; */
+ public int fullLength() {
+ return fullLen;
+ }
+
/**
* Appends the specified part to the message.
*
diff --git a/modules/core/src/main/java/org/apache/ignite/internal/processors/rest/protocols/tcp/redis/GridRedisProtocolParser.java b/modules/core/src/main/java/org/apache/ignite/internal/processors/rest/protocols/tcp/redis/GridRedisProtocolParser.java
index 8ce7428..f55b3a2 100644
--- a/modules/core/src/main/java/org/apache/ignite/internal/processors/rest/protocols/tcp/redis/GridRedisProtocolParser.java
+++ b/modules/core/src/main/java/org/apache/ignite/internal/processors/rest/protocols/tcp/redis/GridRedisProtocolParser.java
@@ -68,26 +68,28 @@ public class GridRedisProtocolParser {
private static final byte[] OK = "OK".getBytes();
/**
- * Reads an array into {@link GridRedisMessage}.
- *
+ * Error while reading int.
+ * {@code -1} used to mark null array.
+ * @see #NIL
+ */
+ public static final int ERROR_INT = -2;
+
+ /**
+ * Checks first byte is {@link #ARRAY}.
* @param buf Buffer.
- * @return {@link GridRedisMessage}.
- * @throws IgniteCheckedException
+ * @return {@code False} if no data available in buffer.
+ * @throws IgniteCheckedException If failed.
*/
- public static GridRedisMessage readArray(ByteBuffer buf) throws IgniteCheckedException {
+ public static boolean ensureArrayStart(ByteBuffer buf) throws IgniteCheckedException {
+ if (!buf.hasRemaining())
+ return false;
+
byte b = buf.get();
if (b != ARRAY)
throw new IgniteCheckedException("Invalid request byte! " + b);
- int arrLen = elCnt(buf);
-
- GridRedisMessage msg = new GridRedisMessage(arrLen);
-
- for (int i = 0; i < arrLen; i++)
- msg.append(readBulkStr(buf));
-
- return msg;
+ return true;
}
/**
@@ -95,21 +97,37 @@ public class GridRedisProtocolParser {
*
* @param buf Buffer.
* @return Bulk string.
- * @throws IgniteCheckedException
+ * @throws IgniteCheckedException If failed.
*/
public static String readBulkStr(ByteBuffer buf) throws IgniteCheckedException {
+ if (!buf.hasRemaining())
+ return null;
+
byte b = buf.get();
if (b != BULK_STRING)
throw new IgniteCheckedException("Invalid bulk string prefix! " + b);
- int len = elCnt(buf);
+ if (!buf.hasRemaining())
+ return null;
+
+ int len = readInt(buf);
+
+ if (len == ERROR_INT || buf.remaining() < len)
+ return null;
+
byte[] bulkStr = new byte[len];
buf.get(bulkStr, 0, len);
- if (buf.get() != CR || buf.get() != LF)
- throw new IgniteCheckedException("Invalid request syntax!");
+ if (buf.remaining() < 2)
+ return null;
+
+ byte b0 = buf.get();
+ byte b1 = buf.get();
+
+ if (b0 != CR || b1 != LF)
+ throw new IgniteCheckedException("Invalid request syntax[len=" + len + ']');
return new String(bulkStr);
}
@@ -120,16 +138,26 @@ public class GridRedisProtocolParser {
* @param buf Buffer.
* @return Count of elements.
*/
- private static int elCnt(ByteBuffer buf) throws IgniteCheckedException {
+ public static int readInt(ByteBuffer buf) throws IgniteCheckedException {
+ if (!buf.hasRemaining())
+ return ERROR_INT;
+
byte[] arrLen = new byte[9];
int idx = 0;
byte b = buf.get();
+
while (b != CR) {
+ if (!buf.hasRemaining())
+ return ERROR_INT;
+
arrLen[idx++] = b;
b = buf.get();
}
+ if (!buf.hasRemaining())
+ return ERROR_INT;
+
if (buf.get() != LF)
throw new IgniteCheckedException("Invalid request syntax!");