GV

GeezerVison

The World Wide Web, restored to 800 pixels of glory.

Home|About|Gaming cabinet|Archives|How it works|Starter sites

On this site

  • Sign in
  • ActionsCI/CD and automation
  • CodespacesCloud development environments
  • All Features
  • Documentation
  • Training
  • Certifications
  • Build with Copilot
  • Customize Copilot
  • Integrations
  • Trending repos
  • GitHub Sponsors
  • Developer articles
  • Enterprises

This view

  • Original page
  • New address

GeezerVison is showing github.com — Fix JdkZlibDecompressor losing the tail of highly compressible streams by renechoi · Pull Request #17191 · netty/netty

Fix JdkZlibDecompressor losing the tail of highly compressible streams #17191

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

Sign up for GitHub

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
normanmaurer merged 2 commits into netty:4.2 from renechoi:fix/jdkzlib-decompressor-tail-loss
Aug 3, 2026

Uh oh!

There was an error while loading. Please reload this page.

Merged

Fix JdkZlibDecompressor losing the tail of highly compressible streams #17191

Show file tree
Hide file tree
Changes from 1 commit
Commits
Show all changes
2 commits
Select commit Hold shift + click to select a range
7dbaebb
Fix JdkZlibDecompressor losing the tail of highly compressible streams
renechoi Aug 3, 2026
5285742
Close the ByteArrayOutputStream in the JDK decompression test helper
renechoi Aug 3, 2026
File filter
Filter by extension

Clear filters
Conversations
Failed to load comments.
Loading

Uh oh!

There was an error while loading. Please reload this page.

Jump to
Jump to file
Failed to load files.
Loading

Uh oh!

There was an error while loading. Please reload this page.

Diff view
Diff view
Next Next commit
Fix JdkZlibDecompressor losing the tail of highly compressible streams
### Motivation

`JdkZlibDecompressor#processOutput` sizes every output buffer as
`inflater.getRemaining() << 1`. The number of remaining input bytes is only a
hint: the inflater may still hold decoded data that did not fit into the
previous output buffer, and by then it may have pulled the last input bytes
into its internal state, so `getRemaining()` is `0` and the proposed buffer has
zero capacity. `inflate(...)` cannot make progress with it, and because
`status()` maps `inflater.needsInput()` straight to `NEED_INPUT`, the caller is
asked for more input instead of draining the pending output. At the end of the
stream `endOfInput()` then fails with `Compressed stream ended before the
end-of-stream marker`, even though the stream was complete and valid.

Measured with 100000 bytes of `'a'` deflated raw (115 bytes, ratio ~870:1):
only 99848 bytes are produced, the remaining 152 bytes stay inside the
`Inflater`, and the call throws. The legacy `JdkZlibDecoder` decodes the same
bytes to all 100000, because it inflates into one buffer that it keeps
expanding, so `inflate(...)` always has room. `ZlibWrapper.ZLIB` and
`ZlibWrapper.GZIP` hide the problem, as their trailer keeps `getRemaining()`
above zero until the inflater is finished.

### Modification

- Never propose a zero-sized output buffer: `processOutput` floors the proposed
  capacity at `MIN_OUTPUT_BUFFER_SIZE` (512 bytes). `maxAllocation` still caps
  it exactly as before.
- Remember whether the last `inflate(...)` filled the output buffer completely
  and, if it did, report `NEED_OUTPUT` from `status()`, so pending output is
  drained before more input is requested. `needsInput()` only says that all
  input bytes were consumed, not that all output was produced.

### Result

A valid deflate stream is fully decompressed regardless of its compression
ratio.
  • Loading branch information

Uh oh!

There was an error while loading. Please reload this page.

@renechoi
renechoi committed Aug 3, 2026
commit 7dbaebba7c4e5c8d274b718896828a700af98afa

There are no files selected for viewing

25 changes: 23 additions & 2 deletions 25 codec-compression/src/main/java/io/netty/handler/codec/compression/JdkZlibDecompressor.java
Show comments
View file
Open in desktop
Original file line number Diff line number Diff line change
Expand Up @@ -38,6 +38,14 @@ public final class JdkZlibDecompressor extends InputBufferingDecompressor {
private static final int FCOMMENT = 0x10;
private static final int FRESERVED = 0xE0;

/**
* Smallest output buffer we hand to {@link Inflater#inflate(byte[], int, int)}. The number of remaining input
* bytes is only a hint for how much output to expect: the inflater may still hold decoded data that did not fit
* into the previous output buffer, and by then it may have consumed all input bytes already
* ({@link Inflater#getRemaining()} == 0). Inflating into a zero-sized buffer can never make progress.
*/
private static final int MIN_OUTPUT_BUFFER_SIZE = 512;

private Inflater inflater;
private final int maxAllocation;
private final byte[] dictionary;
Expand Down Expand Up @@ -69,6 +77,12 @@ private enum GzipState {
* buffer too much (e.g. compact it).
*/
private boolean inputBufferInInflater;
/**
* If this is true, the last {@link Inflater#inflate(byte[], int, int)} filled the output buffer completely, so
* the inflater may still hold decoded data even if {@link Inflater#needsInput()} reports that all input was
* consumed.
*/
private boolean inflaterHasPendingOutput;

JdkZlibDecompressor(Builder builder, ByteBufAllocator allocator) {
super(allocator);
Expand Down Expand Up @@ -102,6 +116,8 @@ private enum GzipState {
public Status status() throws DecompressionException {
if (finished) {
return Status.COMPLETE;
} else if (inflaterHasPendingOutput) {
return Status.NEED_OUTPUT;
} else if (inflater == null || inflater.needsInput() || gzipState == GzipState.FOOTER_START) {
return Status.NEED_INPUT;
} else {
Expand Down Expand Up @@ -187,7 +203,7 @@ private void consumeInput(ByteBuf buf) {

@Override
ByteBuf processOutput(ByteBuf buf) throws DecompressionException {
int proposedCapacity = inflater.getRemaining() << 1;
int proposedCapacity = Math.max(inflater.getRemaining() << 1, MIN_OUTPUT_BUFFER_SIZE);
int targetCapacity = maxAllocation == 0
? proposedCapacity : Math.min(maxAllocation, proposedCapacity);
ByteBuf decompressed = allocator.heapBuffer(targetCapacity);
Expand All @@ -196,9 +212,10 @@ ByteBuf processOutput(ByteBuf buf) throws DecompressionException {
byte[] outArray = decompressed.array();
int writerIndex = decompressed.writerIndex();
int outIndex = decompressed.arrayOffset() + writerIndex;
int writableBytes = decompressed.writableBytes();
int outputLength;
try {
outputLength = inflater.inflate(outArray, outIndex, decompressed.writableBytes());
outputLength = inflater.inflate(outArray, outIndex, writableBytes);
} catch (DataFormatException e) {
throw new DecompressionException("decompression failure", e);
}
Expand Down Expand Up @@ -226,6 +243,10 @@ ByteBuf processOutput(ByteBuf buf) throws DecompressionException {
processInput(buf);
}
}
// If we filled the whole buffer the inflater may still have decoded data left that it could not write.
// In that case we must ask for another output buffer, as needsInput() only tells us that all input
// bytes were consumed, not that all output was produced.
inflaterHasPendingOutput = outputLength == writableBytes && !inflater.finished();
success = true;
return decompressed;
} finally {
Expand Down
66 changes: 66 additions & 0 deletions 66 ...compression/src/test/java/io/netty/handler/codec/compression/JdkZlibDecompressorTest.java
Show comments
View file
Open in desktop
Original file line number Diff line number Diff line change
Expand Up @@ -30,9 +30,12 @@
import java.io.IOException;
import java.util.Arrays;
import java.util.List;
import java.util.zip.Deflater;
import java.util.zip.DeflaterOutputStream;
import java.util.zip.GZIPInputStream;
import java.util.zip.GZIPOutputStream;
import java.util.zip.Inflater;
import java.util.zip.InflaterInputStream;

import static org.junit.jupiter.api.Assertions.assertArrayEquals;
import static org.junit.jupiter.api.Assertions.assertDoesNotThrow;
Expand Down Expand Up @@ -158,6 +161,18 @@ public void testDirectInputRetainedAcrossOutputChunks() throws Exception {
}
}

@Test
public void testHighlyCompressibleStreamIsFullyDecompressed() throws Exception {
// The tail of such a stream expands far beyond the number of remaining input bytes: the inflater pulls the
// last input bytes into its internal state while it still has to emit data. getRemaining() is 0 by then,
// so sizing the output buffer by it alone leaves the inflater without room to write the rest.
byte[] expected = new byte[100000];
Arrays.fill(expected, (byte) 'a');
byte[] compressed = compress(expected);
assertArrayEquals(expected, jdkDecompress(compressed));
assertArrayEquals(expected, decompress(createDecompressor().build(ByteBufAllocator.DEFAULT), compressed));
}

@Test
public void testBadSecondGzipMagicRejected() throws Exception {
assumeTrue(wrapper == ZlibWrapper.GZIP);
Expand Down Expand Up @@ -230,6 +245,57 @@ private static byte[] decompress(Decompressor decompressor, byte[] compressed) t
}
}

/**
* Compress with the wrapper this test instance runs with, using the JDK so that the input is known-good
* independently of netty's own encoders.
*/
private byte[] compress(byte[] data) throws IOException {
switch (wrapper) {
case GZIP:
return gzip(data);
case ZLIB:
return deflate(data);
case NONE:
return rawDeflate(data);
default:
throw new AssertionError("Unexpected wrapper: " + wrapper);
}
}

/** Decompress with the JDK, to prove the compressed input is valid. */
private byte[] jdkDecompress(byte[] compressed) throws IOException {
if (wrapper == ZlibWrapper.GZIP) {
return jdkGunzip(compressed);
}
Inflater inflater = new Inflater(wrapper == ZlibWrapper.NONE);
try {
InflaterInputStream input = new InflaterInputStream(new ByteArrayInputStream(compressed), inflater);
ByteArrayOutputStream output = new ByteArrayOutputStream();
byte[] buffer = new byte[256];
int read;
while ((read = input.read(buffer)) != -1) {
output.write(buffer, 0, read);
}
input.close();
Comment thread
normanmaurer marked this conversation as resolved.
Resolved

Uh oh!

There was an error while loading. Please reload this page.

return output.toByteArray();
} finally {
inflater.end();
}
}

private static byte[] rawDeflate(byte[] data) throws IOException {
Deflater deflater = new Deflater(Deflater.DEFAULT_COMPRESSION, true);
try {
ByteArrayOutputStream output = new ByteArrayOutputStream();
DeflaterOutputStream stream = new DeflaterOutputStream(output, deflater);
stream.write(data);
stream.close();
return output.toByteArray();
} finally {
deflater.end();
}
}

private static byte[] gzip(byte[] data) throws IOException {
ByteArrayOutputStream output = new ByteArrayOutputStream();
GZIPOutputStream gzip = new GZIPOutputStream(output);
Expand Down
Loading
Oops, something went wrong.

Uh oh!

There was an error while loading. Please reload this page.

Add this suggestion to a batch that can be applied as a single commit. This suggestion is invalid because no changes were made to the code. Suggestions cannot be applied while the pull request is closed. Suggestions cannot be applied while viewing a subset of changes. Only one suggestion per line can be applied in a batch. Add this suggestion to a batch that can be applied as a single commit. Applying suggestions on deleted lines is not supported. You must change the existing code in this line in order to create a valid suggestion. Outdated suggestions cannot be applied. This suggestion has been applied or marked resolved. Suggestions cannot be applied from pending reviews. Suggestions cannot be applied on multi-line comments. Suggestions cannot be applied while the pull request is queued to merge. Suggestion cannot be applied right now. Please check back later.
You are visitor 01402775 — GeezerVison does not store the pages you look up.
Best viewed with Netscape Navigator 4.7 or Internet Explorer 6 at 800×600. No cookies required.