Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
42 changes: 42 additions & 0 deletions client-v2/src/main/java/com/clickhouse/client/api/Client.java
Original file line number Diff line number Diff line change
Expand Up @@ -326,6 +326,9 @@ public static class Builder {
ClientConfigProperties.CA_CERTIFICATE,
ClientConfigProperties.SSL_CERTIFICATE,
};
// 1 MiB matches the server default max_compress_block_size. A smaller limit rejects ordinary blocks.
private static final int MIN_COMPRESSION_BLOCK_SIZE = 1024 * 1024;
private static final int MAX_COMPRESSION_BLOCK_SIZE = 0x40000000;

public Builder() {
this.endpoints = new LinkedHashSet<>();
Expand Down Expand Up @@ -705,6 +708,20 @@ public Builder setLZ4UncompressedBufferSize(int size) {
return this;
}

/**
* Sets the maximum compressed or uncompressed native block size that the client will allocate while reading.
* The default is 64 MiB. Allowed values are 1 MiB through the 1 GiB ClickHouse protocol limit.
*
* @param size maximum block size in bytes
* @return this builder
*/
public Builder setMaxCompressionBlockSize(int size) {
ValidationUtils.checkRange(size, MIN_COMPRESSION_BLOCK_SIZE, MAX_COMPRESSION_BLOCK_SIZE,
ClientConfigProperties.COMPRESSION_MAX_BLOCK_SIZE.getKey());
this.configuration.put(ClientConfigProperties.COMPRESSION_MAX_BLOCK_SIZE.getKey(), String.valueOf(size));
return this;
}

/**
* Disable native compression. If set to true then native compression will be disabled.
* If from some reason the native compressor is not working then it can be disabled.
Expand Down Expand Up @@ -1390,6 +1407,14 @@ public Client build() {
throw new IllegalArgumentException("At least one endpoint is required");
}

String maxCompressionBlockSize =
configuration.get(ClientConfigProperties.COMPRESSION_MAX_BLOCK_SIZE.getKey());
if (maxCompressionBlockSize != null) {
ValidationUtils.checkRange(Integer.parseInt(maxCompressionBlockSize),
MIN_COMPRESSION_BLOCK_SIZE, MAX_COMPRESSION_BLOCK_SIZE,
ClientConfigProperties.COMPRESSION_MAX_BLOCK_SIZE.getKey());
}

CredentialsManager cManager = new CredentialsManager(this.configuration);

// A textual 'ssl_context' can never be a live context (also rejected in setOption).
Expand Down Expand Up @@ -2202,6 +2227,8 @@ public CompletableFuture<Records> queryRecords(String sqlQuery, Map<String, Obje
try {

return new Records(response, newBinaryFormatReader(response));
} catch (DataTransferException e) {
throw e;
} catch (Exception e) {
throw new ClientException("Failed to get query response", e);
}
Expand Down Expand Up @@ -2246,7 +2273,12 @@ public List<GenericRecord> queryAll(String sqlQuery, Map<String, Object> params,
return records;
}
} catch (ExecutionException e) {
if (e.getCause() instanceof DataTransferException) {
throw (DataTransferException) e.getCause();
}
throw new ClientException("Failed to get query response", e.getCause());
} catch (DataTransferException e) {
throw e;
} catch (Exception e) {
throw new ClientException("Failed to get query response", e);
}
Expand Down Expand Up @@ -2322,7 +2354,12 @@ record = allocator == null ? clazz.getDeclaredConstructor().newInstance() : allo
return records;
}
} catch (ExecutionException e) {
if (e.getCause() instanceof DataTransferException) {
throw (DataTransferException) e.getCause();
}
throw new ClientException("Failed to get query response", e.getCause());
} catch (DataTransferException e) {
throw e;
} catch (Exception e) {
throw new ClientException("Failed to get query response", e);
}
Expand Down Expand Up @@ -2402,9 +2439,14 @@ private TableSchema getTableSchemaImpl(
} catch (TimeoutException e) {
throw new ClientException("Operation has likely timed out after " + getOperationTimeout() + " milliseconds.", e);
} catch (ExecutionException e) {
if (e.getCause() instanceof DataTransferException) {
throw (DataTransferException) e.getCause();
}
throw new ClientException("Failed to get table schema", e.getCause());
} catch (ServerException e) {
throw e;
} catch (DataTransferException e) {
throw e;
} catch (Exception e) {
throw new ClientException("Failed to get table schema", e);
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -102,6 +102,9 @@ public enum ClientConfigProperties {

COMPRESSION_LZ4_UNCOMPRESSED_BUF_SIZE("compression.lz4.uncompressed_buffer_size", Integer.class, String.valueOf(CompressedBlockOutputStream.UNCOMPRESSED_BUFF_SIZE)),

// Default 64 MiB. Allowed range is 1 MiB through the 1 GiB protocol limit.
COMPRESSION_MAX_BLOCK_SIZE("compression.max_block_size", Integer.class, "67108864"),

COMPRESSION_METHOD("compression.method", CompressionMethod.class, CompressionMethod.ZSTD.name()),

DISABLE_NATIVE_COMPRESSION("disable_native_compression", Boolean.class, "false"),
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@

import com.clickhouse.client.api.ClientConfigProperties;
import com.clickhouse.client.api.ClientException;
import com.clickhouse.client.api.DataTransferException;
import com.clickhouse.client.api.DataTypeUtils;
import com.clickhouse.client.api.data_formats.ClickHouseBinaryFormatReader;
import com.clickhouse.client.api.internal.DataTypeConverter;
Expand Down Expand Up @@ -139,6 +140,8 @@ public boolean readToPOJO(Map<String, POJOFieldDeserializer> deserializers, Obje
return false;
}
throw e;
} catch (DataTransferException e) {
throw e;
} catch (Exception e) {
throw new ClientException("Failed to set value of '" + column.getColumnName(), e);
}
Expand Down
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
package com.clickhouse.client.api.data_formats.internal;

import com.clickhouse.client.api.ClientException;
import com.clickhouse.client.api.DataTransferException;
import com.clickhouse.client.api.DataTypeUtils;
import com.clickhouse.client.api.query.NullValueException;
import com.clickhouse.data.ClickHouseColumn;
Expand Down Expand Up @@ -302,6 +303,8 @@ private <T> T readValue(ClickHouseColumn column, Class<?> typeHint, boolean stri
}
} catch (EOFException e) {
throw e;
} catch (DataTransferException e) {
throw e;
} catch (Exception e) {
log.debug("Failed to read value for column {}, {}", column.getColumnName(), e.getLocalizedMessage());
throw new ClientException("Failed to read value for column " + column.getColumnName(), e);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,8 @@ class CompressedBlockEntity implements HttpEntity {

private final int bufferSize;

private final int maxBlockSize;

private final boolean isResponse;

private final boolean serverCompression;
Expand All @@ -34,10 +36,12 @@ class CompressedBlockEntity implements HttpEntity {
private final CompressionMethod compressionMethod;

CompressedBlockEntity(HttpEntity httpEntity, boolean useHttpCompression, boolean serverCompression, boolean clientCompression,
int bufferSize, boolean isResponse, LZ4Factory lz4Factory, CompressionMethod compressMethod) {
int bufferSize, int maxBlockSize, boolean isResponse, LZ4Factory lz4Factory,
CompressionMethod compressMethod) {
this.httpEntity = httpEntity;
this.useHttpCompression = useHttpCompression;
this.bufferSize = bufferSize;
this.maxBlockSize = maxBlockSize;
this.serverCompression = serverCompression;
this.clientCompression = clientCompression;
this.isResponse = isResponse;
Expand Down Expand Up @@ -68,7 +72,7 @@ public InputStream getContent() throws IOException, UnsupportedOperationExceptio
}
} else {
return new CompressedBlockInputStream(httpEntity.getContent(), lz4Factory.fastDecompressor(),
bufferSize);
bufferSize, maxBlockSize);
}
} else {
return httpEntity.getContent();
Expand Down
Original file line number Diff line number Diff line change
@@ -1,9 +1,9 @@
package com.clickhouse.client.api.internal;

import com.clickhouse.client.api.ClientException;
import com.clickhouse.client.api.DataTransferException;
import com.clickhouse.data.ClickHouseByteUtils;
import com.clickhouse.data.ClickHouseCityHash;
import com.clickhouse.data.ClickHouseUtils;
import com.github.luben.zstd.Zstd;
import net.jpountz.lz4.LZ4FastDecompressor;
import org.slf4j.Logger;
Expand All @@ -13,6 +13,7 @@
import java.io.IOException;
import java.io.InputStream;
import java.nio.ByteBuffer;
import java.util.Objects;

public class CompressedBlockInputStream extends InputStream {

Expand All @@ -25,12 +26,27 @@ public class CompressedBlockInputStream extends InputStream {

private final byte[] tmpBuffer = new byte[1];

private final int maxBlockSize;

public CompressedBlockInputStream(InputStream in, LZ4FastDecompressor decompressor, int bufferSize) {
this(in, decompressor, bufferSize, DEFAULT_MAX_BLOCK_SIZE);
}

public CompressedBlockInputStream(InputStream in, LZ4FastDecompressor decompressor, int bufferSize,
int maxBlockSize) {
super();
Objects.requireNonNull(in, "in is null");
Objects.requireNonNull(decompressor, "decompressor is null");
if (bufferSize <= 0) {
throw new IllegalArgumentException("bufferSize must be greater than 0");
}
if (maxBlockSize < 9 || maxBlockSize > MAX_COMPRESSED_BLOCK_SIZE) {
throw new IllegalArgumentException("Invalid maxBlockSize: " + maxBlockSize);
}
LOG.debug("Using decompressor with buffer size {}", bufferSize);
this.decompressor = decompressor;
this.in = in;
this.maxBlockSize = maxBlockSize;
this.buffer = ByteBuffer.allocate(bufferSize);
this.buffer.limit(0);
}
Expand Down Expand Up @@ -70,8 +86,20 @@ public int read(byte[] b, int off, int len) throws IOException {
static final byte MAGIC_NONE = (byte) 0x02;
static final int HEADER_LENGTH = 25;
static final int MAGIC_NUM_POS = 16;
// ClickHouse DBMS_MAX_COMPRESSED_SIZE (CompressionInfo.h): exactly 1 GiB (2^30).
// The server accepts this value and rejects one byte more, for both the compressed-size
// and the decompressed-size fields. This is the protocol ceiling, not a normal block
// (the server writes at most max_compress_block_size, 1 MiB by default).
// Both fields are UInt32 and are read here as a signed int, so a value >= 2 GiB arrives
// negative and fails the < 0 check. If the server raises DBMS_MAX_COMPRESSED_SIZE, raise
// these caps as well; a valid larger block would otherwise be rejected as corrupted.
// A limit >= 2 GiB also requires reading the fields as unsigned.
static final int MAX_COMPRESSED_BLOCK_SIZE = 0x40000000;
static final int MAX_UNCOMPRESSED_BLOCK_SIZE = 0x40000000;
static final int DEFAULT_MAX_BLOCK_SIZE = 64 * 1024 * 1024;

final byte[] headerBuff = new byte[HEADER_LENGTH];
private int headerBytesRead;

/**
* Method ensures to read all bytes from the input stream.
Expand All @@ -80,15 +108,28 @@ public int read(byte[] b, int off, int len) throws IOException {
*/
private boolean readFully(byte[] b, int off, int len) throws IOException {
int n = 0;
if (b == headerBuff) {
headerBytesRead = 0;
}
while (n < len) {
int count = in.read(b, off + n, len - n);
int count;
try {
count = in.read(b, off + n, len - n);
} catch (EOFException ex) {
throw new DataTransferException("Incomplete read: " + n + " of " + len, ex);
} catch (IOException ex) {
throw new DataTransferException("Incomplete read: " + n + " of " + len, ex);
Comment thread
chernser marked this conversation as resolved.
Resolved
}
if (count < 0) {
if (n == 0) {
return false;
}
throw new IOException(ClickHouseUtils.format("Incomplete read: %s of %s", n, len));
throw new DataTransferException("Incomplete read: " + n + " of " + len);
}
n += count;
if (b == headerBuff) {
headerBytesRead = n;
}
}

return true;
Expand All @@ -98,6 +139,10 @@ public byte[] getHeaderBuffer() {
return headerBuff;
}

public int getHeaderBytesRead() {
return headerBytesRead;
}

public InputStream getInputStream() {
return in;
}
Expand Down Expand Up @@ -126,6 +171,21 @@ private int refill() throws IOException {
int uncompressedSize = getInt32(headerBuff, 21);

int offset = 9;
if (compressedSizeWithHeader < offset || compressedSizeWithHeader > MAX_COMPRESSED_BLOCK_SIZE) {
throw new DataTransferException("Corrupted stream: invalid compressed block size " + compressedSizeWithHeader);
}
if (compressedSizeWithHeader > maxBlockSize) {
throw new DataTransferException("Corrupted stream: compressed block size " + compressedSizeWithHeader
+ " exceeds configured limit " + maxBlockSize);
}

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Block size cap rejects valid blocks

Medium Severity

The read path applies maxBlockSize to compressedSizeWithHeader, which includes the 9-byte inner header and can exceed uncompressed size for incompressible LZ4/ZSTD data. The documented 1 MiB minimum is meant to match server max_compress_block_size (uncompressed), so a client set to that minimum can reject ordinary incompressible 1 MiB blocks with a DataTransferException.

Additional Locations (1)
Fix in Cursor Fix in Web

Reviewed by Cursor Bugbot for commit 6af4087. Configure here.

if (uncompressedSize < 0 || uncompressedSize > MAX_UNCOMPRESSED_BLOCK_SIZE) {
throw new DataTransferException("Corrupted stream: invalid uncompressed block size " + uncompressedSize);
}
if (uncompressedSize > maxBlockSize) {
throw new DataTransferException("Corrupted stream: uncompressed block size " + uncompressedSize
+ " exceeds configured limit " + maxBlockSize);
}

final byte[] block = new byte[compressedSizeWithHeader];
block[0] = magicNumber;
setInt32(block, 1, compressedSizeWithHeader);
Expand All @@ -135,7 +195,7 @@ private int refill() throws IOException {

readFully = readFully(block, offset, remaining);
if (!readFully) {
throw new EOFException("Unexpected end of stream");
throw new DataTransferException("Unexpected end of stream");
}

long[] real = ClickHouseCityHash.cityHash128(block, 0, compressedSizeWithHeader);
Expand All @@ -149,14 +209,26 @@ private int refill() throws IOException {

switch (magicNumber) {
case MAGIC_LZ4: {
decompressor.decompress(block, offset, buffer.array(), 0, uncompressedSize);
int consumed = decompressor.decompress(block, offset, buffer.array(), 0, uncompressedSize);
if (consumed != remaining) {
throw new DataTransferException("Corrupted stream: LZ4 compressed size mismatch (expected "
+ remaining + ", consumed " + consumed + ")");
}
break;
}
case MAGIC_ZSTD_3: {
Zstd.decompressByteArray(buffer.array(), 0, uncompressedSize, block, offset, remaining);
long decompressed = Zstd.decompressByteArray(buffer.array(), 0, uncompressedSize, block, offset, remaining);
if (decompressed != uncompressedSize) {
throw new DataTransferException("Corrupted stream: ZSTD decompressed size mismatch (expected "
+ uncompressedSize + ", got " + decompressed + ")");
}
break;
}
case MAGIC_NONE:
if (remaining != uncompressedSize) {
throw new DataTransferException("Corrupted stream: uncompressed block size mismatch (expected "
+ uncompressedSize + ", got " + remaining + ")");
}
// block is not compressed - just put it.
System.arraycopy(block, offset, buffer.array(), 0, uncompressedSize);
break;
Expand Down
Loading
Loading