This is an automated email from the ASF dual-hosted git repository.
garydgregory pushed a commit to branch master
in repository https://gitbox.apache.org/repos/asf/commons-compress.git
The following commit(s) were added to refs/heads/master by this push:
new 52a08948b Harden decompression defaults and validate .Z code widths
(#859)
52a08948b is described below
commit 52a08948b8120004901eaa2911993a65dbf8bbb0
Author: Gary Gregory <[email protected]>
AuthorDate: Mon Nov 30 16:22:44 2026 -0500
Harden decompression defaults and validate .Z code widths (#859)
Default CompressorStreamFactory, LZMA, XZ, and Pack200 input streams
to a 1 GiB memory limit while preserving explicit overrides. Initialize
concrete builder defaults through the setter.
Reject .Z code widths outside 9–16 bits before allocating decoding
tables, independently of the configured memory limit.
Document limit accounting, explicit unlimited operation, and the
inherited XZ limit for ZIP entries. Add per-format FIX release notes.
Add regression coverage for defaults, overrides, boundary conditions,
concatenated XZ streams, and ZIP entries. Run oversized-header tests
in a separate JVM with a bounded heap.
---
src/changes/changes.xml | 9 +
.../compressors/AbstractCompressorBuilder.java | 4 +-
.../compressors/CompressorStreamFactory.java | 27 +-
.../lzma/LZMACompressorInputStream.java | 10 +-
.../pack200/Pack200CompressorInputStream.java | 8 +-
.../compressors/xz/XZCompressorInputStream.java | 18 +-
.../compressors/z/ZCompressorInputStream.java | 16 +-
src/site/xdoc/examples.xml | 18 ++
src/site/xdoc/pack200.xml | 3 +-
.../compressors/AbstractCompressorBuilderTest.java | 34 ++-
.../compressors/CompressorMemoryLimitTest.java | 277 +++++++++++++++++++++
.../compress/compressors/DetectCompressorTest.java | 2 +-
.../compressors/z/ZCompressorInputStreamTest.java | 43 ++++
13 files changed, 446 insertions(+), 23 deletions(-)
diff --git a/src/changes/changes.xml b/src/changes/changes.xml
index 6b14b8aaf..e0d6ee919 100644
--- a/src/changes/changes.xml
+++ b/src/changes/changes.xml
@@ -96,6 +96,7 @@ The <action> type attribute can be add,update,fix,remove.
<action type="fix" dev="pkarwasz" due-to="KALI 834X, Gary Gregory">[Zip]
Fix Zip rcount field width in x0015 and x0016 certificate id extra fields
(#787).</action>
<action type="fix" dev="ggregory" due-to="KALI 834X, Gary Gregory">[Zip]
Reject negative ZIP64 offsets in positionAtCentralDirectory64 (#794).</action>
<action type="fix" dev="ggregory" due-to="Gary Gregory">[Zip]
UnshrinkingInputStreamnow now throws CompressorException instead of
IllegalArgumetException/IllegalStateException.</action>
+ <action type="fix" dev="ggregory">[Zip] Apply the 1 GiB XZ decoder
memory limit when reading XZ-compressed entries with ZipFile or
ZipArchiveInputStream; these ZIP APIs do not expose a memory-limit
override.</action>
<!-- FIX TAR -->
<action type="fix" dev="pkarwasz" due-to="Tyler Nighswander, Piotr P.
Karwasz, Gary Gregory">>[TAR] Uniform handling of special tar records in
TarFile and TarArchiveInputStream.</action>
<action type="fix" dev="ggregory" due-to="Gary Gregory, Stanislav
Fort">[TAR] TarArchiveOutputStream now throws a ArchiveException instead of an
OutOfMemoryError.</action>
@@ -138,6 +139,7 @@ The <action> type attribute can be add,update,fix,remove.
<action type="fix" dev="ppkarwasz" due-to="Raeps">[Pack200] Extract
duplicate code in org.apache.commons.compress.harmony.pack200.IntList.</action>
<action type="fix" dev="pkarwasz" due-to="Piotr P. Karwasz">[Pack200]
Simplify `PackingUtils` by leveraging Commons IO.</action>
<action type="fix" dev="ggregory" due-to="Claude Security, Gary
Gregory">[Pack200] Avoid copying the complete in-memory cache when opening its
input view.</action>
+ <action type="fix" dev="ggregory">[Pack200] Default the in-memory
generated JAR cache limit to 1 GiB; explicit negative limits retain unlimited
caching and the temporary-file strategy is unaffected.</action>
<!-- FIX cpio -->
<action type="fix" dev="ggregory" due-to="Stan, Gary Gregory">[Cpio]
CpioArchiveEntry now throws ArchiveException instead of Arithmetic
exception.</action>
<action type="fix" dev="ggregory" due-to="Stan, Gary Gregory">[Cpio]
CpioArchiveInputStream.getNextEntry() now throws a MemoryLimitException instead
of OutOfMemoryError when it can't process input greater than available
memory.</action>
@@ -168,8 +170,14 @@ The <action> type attribute can be add,update,fix,remove.
<!-- FIX lz4 -->
<action type="fix" dev="ggregory" due-to="Gary Gregory">[LZ4]
BlockLZ4CompressorOutputStream now throws CompressorException instead of
IllegalArgumetException/IllegalStateException.</action>
<action type="fix" dev="ggregory" due-to="KALI 834X, Gary Gregory">[LZ4]
Avoid unbounded recursion on empty frames in framed lz4 decoders
(#803).</action>
+ <!-- FIX lzma -->
+ <action type="fix" dev="ggregory">[LZMA] Default
LZMACompressorInputStream builders and constructors without an explicit memory
limit to 1 GiB; explicit -1 retains unlimited operation.</action>
<!-- FIX lzw -->
<action type="fix" dev="ggregory" due-to="Gary Gregory">[LZW]
LZWInputStream now throws CompressorException instead of
IllegalArgumetException/IllegalStateException.</action>
+ <!-- FIX xz -->
+ <action type="fix" dev="ggregory">[XZ] Default XZCompressorInputStream
builders and constructors without an explicit memory limit to 1 GiB; explicit
-1 retains unlimited operation.</action>
+ <!-- FIX z -->
+ <action type="fix" dev="ggregory">[Z] Reject maximum code widths outside
9 to 16 bits before allocating LZW tables, independently of the configured
memory limit.</action>
<!-- FIX lha -->
<action type="fix" dev="ggregory" due-to="Fredrik Kjellberg, Gary
Gregory">[LHA] Add tests for lh5 decompression (#807).</action>
<!-- FIX general -->
@@ -210,6 +218,7 @@ The <action> type attribute can be add,update,fix,remove.
<action type="fix" dev="ggregory" due-to="Gary Gregory">Add and use
ArchiveException.requireNonNegative(long, Supplier<String>)</action>
<action type="fix" dev="ggregory" due-to="Gary
Gregory">ArchiveStreamFactory now throws ArchiveException instead of
IllegalArgumetException/IllegalStateException.</action>
<action type="fix" dev="ggregory" due-to="Gary Gregory">ExactMath now
throws ArchiveException instead of
IllegalArgumetException/IllegalStateException.</action>
+ <action type="fix" dev="ggregory">[Compressors] Default
CompressorStreamFactory constructors without an explicit memory limit to 1 GiB
for Z, LZMA, XZ, and Pack200; explicit -1 retains unlimited operation.</action>
<!-- ADD -->
<action type="add" dev="ggregory" due-to="Gary Gregory">Add
MemoryLimitException.MemoryLimitException(long, long).</action>
<action type="add" dev="ggregory" due-to="Gary Gregory">Add
CompressException.CompressException(String, Object...).</action>
diff --git
a/src/main/java/org/apache/commons/compress/compressors/AbstractCompressorBuilder.java
b/src/main/java/org/apache/commons/compress/compressors/AbstractCompressorBuilder.java
index 185ae8e3d..291211619 100644
---
a/src/main/java/org/apache/commons/compress/compressors/AbstractCompressorBuilder.java
+++
b/src/main/java/org/apache/commons/compress/compressors/AbstractCompressorBuilder.java
@@ -51,8 +51,8 @@ public int getMemoryLimitKiB() {
* Sets the memory limit in kibibytes (KiB).
*
* <p>
- * The default is {@code -1}, meaning no configured limit. The memory
covered by this setting depends on the compressor implementation. See the
concrete
- * builder for details.
+ * The default and the memory covered by this setting depend on the
compressor implementation. The base builder's no-argument constructor uses
+ * {@code -1}, meaning no configured limit. See the concrete builder for
details.
* </p>
*
* @param memoryLimitKiB The memory limit in kibibytes, or {@code -1} for
no configured limit.
diff --git
a/src/main/java/org/apache/commons/compress/compressors/CompressorStreamFactory.java
b/src/main/java/org/apache/commons/compress/compressors/CompressorStreamFactory.java
index 0ae35af8c..5458aea59 100644
---
a/src/main/java/org/apache/commons/compress/compressors/CompressorStreamFactory.java
+++
b/src/main/java/org/apache/commons/compress/compressors/CompressorStreamFactory.java
@@ -106,6 +106,19 @@ public class CompressorStreamFactory implements
CompressorStreamProvider {
*/
public static final String BZIP2 = "bzip2";
+ /**
+ * Default memory limit of 1 GiB, expressed in kibibytes (KiB).
+ *
+ * <p>
+ * Since 1.29.0, factory constructors without an explicit limit and the
LZMA, XZ, and Pack200 input stream builders use this limit. It covers estimated
+ * decoder memory for Z, LZMA, and XZ, and generated JAR bytes cached in
memory for Pack200. It is not a total JVM memory budget and cannot prevent every
+ * {@link OutOfMemoryError}. Use an explicit limit suited to the
application, or {@code -1} for no configured limit.
+ * </p>
+ *
+ * @since 1.29.0
+ */
+ public static final int DEFAULT_MEMORY_LIMIT_KIB = 1024 * 1024;
+
/**
* Constant (value {@value}) used to identify the GZIP compression
algorithm.
*
@@ -503,22 +516,22 @@ private static String youNeed(final String name, final
String url) {
private final int memoryLimitInKb;
/**
- * Constructs an instance with the decompress Concatenated option set to
false.
+ * Constructs an instance with the decompress Concatenated option set to
false and the memory limit set to {@link #DEFAULT_MEMORY_LIMIT_KIB}.
*/
public CompressorStreamFactory() {
this.decompressUntilEof = null;
- this.memoryLimitInKb = -1;
+ this.memoryLimitInKb = DEFAULT_MEMORY_LIMIT_KIB;
}
/**
- * Constructs an instance with the provided decompress Concatenated option.
+ * Constructs an instance with the provided decompress Concatenated option
and the memory limit set to {@link #DEFAULT_MEMORY_LIMIT_KIB}.
*
* @param decompressUntilEOF if true, decompress until the end of the
input; if false, stop after the first stream and leave the input position to
point to
* the next byte after the stream. This setting
applies to the gzip, bzip2 and XZ formats only.
* @since 1.10
*/
public CompressorStreamFactory(final boolean decompressUntilEOF) {
- this(decompressUntilEOF, -1);
+ this(decompressUntilEOF, DEFAULT_MEMORY_LIMIT_KIB);
}
/**
@@ -527,9 +540,9 @@ public CompressorStreamFactory(final boolean
decompressUntilEOF) {
* @param decompressUntilEOF if true, decompress until the end of the
input; if false, stop after the first stream and leave the input position to
point to
* the next byte after the stream. This setting
applies to the gzip, bzip2 and XZ formats only.
* @param memoryLimitInKb Some streams require allocation of
potentially significant byte arrays/tables, and they can offer checks to
prevent OOMs on
- * corrupt files. Set the maximum allowed memory
allocation in KiB. For Pack200, this limits only the generated JAR bytes
- * cached in memory, excluding unpacker working
memory, unused buffer capacity, and temporary allocations. A negative value
- * leaves the Pack200 cache unlimited.
+ * corrupt files. Sets the maximum allowed
estimated memory usage in KiB for Z, LZMA, and XZ. Use {@code -1} for no
configured
+ * limit. For Pack200, this limits only the
generated JAR bytes cached in memory, excluding unpacker working memory, unused
+ * buffer capacity, and temporary allocations. A
negative value leaves the Pack200 cache unlimited.
*
* @since 1.14
*/
diff --git
a/src/main/java/org/apache/commons/compress/compressors/lzma/LZMACompressorInputStream.java
b/src/main/java/org/apache/commons/compress/compressors/lzma/LZMACompressorInputStream.java
index 952ba1e22..97f0a89d9 100644
---
a/src/main/java/org/apache/commons/compress/compressors/lzma/LZMACompressorInputStream.java
+++
b/src/main/java/org/apache/commons/compress/compressors/lzma/LZMACompressorInputStream.java
@@ -24,6 +24,7 @@
import org.apache.commons.compress.MemoryLimitException;
import org.apache.commons.compress.compressors.AbstractCompressorBuilder;
import org.apache.commons.compress.compressors.CompressorInputStream;
+import org.apache.commons.compress.compressors.CompressorStreamFactory;
import org.apache.commons.compress.utils.InputStreamStatistics;
import org.apache.commons.io.IOUtils;
import org.apache.commons.io.input.BoundedInputStream;
@@ -43,7 +44,8 @@ public class LZMACompressorInputStream extends
CompressorInputStream implements
*
* <p>
* The {@linkplain #setMemoryLimitKiB(int) memory limit} applies to
estimated working memory and is expressed in kibibytes (KiB). The default is
- * {@code -1}, meaning no limit. Construction throws {@link
MemoryLimitException} if the estimated memory usage exceeds the configured
limit.
+ * {@link CompressorStreamFactory#DEFAULT_MEMORY_LIMIT_KIB} (1 GiB) since
1.29.0. Use {@code -1} for no configured limit. Construction throws
+ * {@link MemoryLimitException} if the estimated memory usage exceeds the
configured limit.
* </p>
*
* <p>
@@ -67,7 +69,7 @@ public static class Builder extends
AbstractCompressorBuilder<LZMACompressorInpu
* Constructs a new instance.
*/
public Builder() {
- // Default constructor
+
super.setMemoryLimitKiB(CompressorStreamFactory.DEFAULT_MEMORY_LIMIT_KIB);
}
@Override
@@ -128,6 +130,10 @@ private LZMACompressorInputStream(final Builder builder)
throws IOException {
/**
* Creates a new input stream that decompresses LZMA-compressed data from
the specified input stream.
*
+ * <p>
+ * Since 1.29.0, uses {@link
CompressorStreamFactory#DEFAULT_MEMORY_LIMIT_KIB}. Use {@link #builder()} to
configure a different limit.
+ * </p>
+ *
* @param inputStream where to read the compressed data.
* @throws IOException if the input is not in the .lzma format, the input
is corrupt or truncated, the .lzma headers specify sizes that are not supported
by
* this implementation, or the underlying {@code
inputStream} throws an exception.
diff --git
a/src/main/java/org/apache/commons/compress/compressors/pack200/Pack200CompressorInputStream.java
b/src/main/java/org/apache/commons/compress/compressors/pack200/Pack200CompressorInputStream.java
index fa2bcdfd2..dec746b92 100644
---
a/src/main/java/org/apache/commons/compress/compressors/pack200/Pack200CompressorInputStream.java
+++
b/src/main/java/org/apache/commons/compress/compressors/pack200/Pack200CompressorInputStream.java
@@ -30,6 +30,7 @@
import org.apache.commons.compress.MemoryLimitException;
import org.apache.commons.compress.compressors.AbstractCompressorBuilder;
import org.apache.commons.compress.compressors.CompressorInputStream;
+import org.apache.commons.compress.compressors.CompressorStreamFactory;
import org.apache.commons.compress.java.util.jar.Pack200;
import org.apache.commons.io.IOUtils;
import org.apache.commons.io.build.AbstractOrigin;
@@ -43,7 +44,8 @@
* </p>
*
* <p>
- * To build an instance, use {@link Builder}.
+ * To build an instance, use {@link Builder}. Since 1.29.0, builders and
constructors use {@link CompressorStreamFactory#DEFAULT_MEMORY_LIMIT_KIB} to
limit
+ * the generated JAR bytes cached in memory. Use the builder to configure a
different limit. {@link Pack200Strategy#TEMP_FILE} is unaffected.
* </p>
*
* @NotThreadSafe
@@ -57,7 +59,7 @@ public class Pack200CompressorInputStream extends
CompressorInputStream {
*
* <p>
* The {@linkplain #setMemoryLimitKiB(int) memory limit} applies only to
{@link Pack200Strategy#IN_MEMORY}; {@link Pack200Strategy#TEMP_FILE} is
unaffected.
- * The default is {@code -1}. Any negative value means no limit, and zero
permits no cached bytes.
+ * The default is {@link CompressorStreamFactory#DEFAULT_MEMORY_LIMIT_KIB}
(1 GiB). Any negative value means no limit, and zero permits no cached bytes.
* </p>
*
* <p>
@@ -93,7 +95,7 @@ public static class Builder extends
AbstractCompressorBuilder<Pack200CompressorI
* Constructs a new builder of {@link Pack200CompressorInputStream}.
*/
public Builder() {
- // empty
+
super.setMemoryLimitKiB(CompressorStreamFactory.DEFAULT_MEMORY_LIMIT_KIB);
}
/**
diff --git
a/src/main/java/org/apache/commons/compress/compressors/xz/XZCompressorInputStream.java
b/src/main/java/org/apache/commons/compress/compressors/xz/XZCompressorInputStream.java
index 6f6d21681..fb71afb9e 100644
---
a/src/main/java/org/apache/commons/compress/compressors/xz/XZCompressorInputStream.java
+++
b/src/main/java/org/apache/commons/compress/compressors/xz/XZCompressorInputStream.java
@@ -24,6 +24,7 @@
import org.apache.commons.compress.MemoryLimitException;
import org.apache.commons.compress.compressors.AbstractCompressorBuilder;
import org.apache.commons.compress.compressors.CompressorInputStream;
+import org.apache.commons.compress.compressors.CompressorStreamFactory;
import org.apache.commons.compress.utils.InputStreamStatistics;
import org.apache.commons.io.IOUtils;
import org.apache.commons.io.input.BoundedInputStream;
@@ -42,7 +43,6 @@
* XZCompressorInputStream s = XZCompressorInputStream.builder()
* .setPath(path)
* .setDecompressConcatenated(false)
- * .setMemoryLimitKiB(-1)
* .get();
* }
* </pre>
@@ -57,8 +57,9 @@ public class XZCompressorInputStream extends
CompressorInputStream implements In
* Builds a new {@link XZCompressorInputStream}.
*
* <p>
- * The {@linkplain #setMemoryLimitKiB(int) memory limit} applies when
reading blocks and is expressed in kibibytes (KiB). The default is {@code -1},
- * meaning no limit. Reading throws {@link MemoryLimitException} if the
estimated memory usage exceeds the configured limit.
+ * The {@linkplain #setMemoryLimitKiB(int) memory limit} applies when
reading blocks and is expressed in kibibytes (KiB). The default is
+ * {@link CompressorStreamFactory#DEFAULT_MEMORY_LIMIT_KIB} (1 GiB) since
1.29.0. Use {@code -1} for no configured limit. Reading throws
+ * {@link MemoryLimitException} if the estimated memory usage exceeds the
configured limit.
* </p>
*
* <p>
@@ -68,7 +69,6 @@ public class XZCompressorInputStream extends
CompressorInputStream implements In
* XZCompressorInputStream s = XZCompressorInputStream.builder()
* .setPath(path)
* .setDecompressConcatenated(false)
- * .setMemoryLimitKiB(-1)
* .get();
* }
* </pre>
@@ -86,7 +86,7 @@ public static class Builder extends
AbstractCompressorBuilder<XZCompressorInputS
* Constructs a new instance.
*/
public Builder() {
- // Default constructor
+
super.setMemoryLimitKiB(CompressorStreamFactory.DEFAULT_MEMORY_LIMIT_KIB);
}
@Override
@@ -169,6 +169,10 @@ private XZCompressorInputStream(final Builder builder)
throws IOException {
/**
* Creates a new input stream that decompresses XZ-compressed data from
the specified input stream. This doesn't support concatenated .xz files.
*
+ * <p>
+ * Since 1.29.0, uses {@link
CompressorStreamFactory#DEFAULT_MEMORY_LIMIT_KIB}. Use {@link #builder()} to
configure a different limit.
+ * </p>
+ *
* @param inputStream where to read the compressed data.
* @throws IOException if the input is not in the .xz format, the input is
corrupt or truncated, the .xz headers specify options that are not supported by
* this implementation, or the underlying {@code
inputStream} throws an exception
@@ -180,6 +184,10 @@ public XZCompressorInputStream(final InputStream
inputStream) throws IOException
/**
* Creates a new input stream that decompresses XZ-compressed data from
the specified input stream.
*
+ * <p>
+ * Since 1.29.0, uses {@link
CompressorStreamFactory#DEFAULT_MEMORY_LIMIT_KIB}. Use {@link #builder()} to
configure a different limit.
+ * </p>
+ *
* @param inputStream where to read the compressed data.
* @param decompressConcatenated if true, decompress until the end of the
input; if false, stop after the first .xz stream and leave the input position to
* point to the next byte after the .xz
stream
diff --git
a/src/main/java/org/apache/commons/compress/compressors/z/ZCompressorInputStream.java
b/src/main/java/org/apache/commons/compress/compressors/z/ZCompressorInputStream.java
index 36162d7cd..275acd2ba 100644
---
a/src/main/java/org/apache/commons/compress/compressors/z/ZCompressorInputStream.java
+++
b/src/main/java/org/apache/commons/compress/compressors/z/ZCompressorInputStream.java
@@ -28,6 +28,11 @@
/**
* Input stream that decompresses .Z files.
*
+ * <p>
+ * Supports maximum code widths from 9 to 16 bits. Unsupported widths are
rejected before allocating the decoding tables, independently of the configured
+ * memory limit. The tables require at most 384 KiB, excluding array and
object overhead.
+ * </p>
+ *
* @NotThreadSafe
* @since 1.7
*/
@@ -36,6 +41,12 @@ public class ZCompressorInputStream extends LZWInputStream {
private static final int MAGIC_1 = 0x1f;
private static final int MAGIC_2 = 0x9d;
private static final int BLOCK_MODE_MASK = 0x80;
+
+ /**
+ * Maximum supported .Z code size in bits.
+ */
+ private static final int MAX_CODE_SIZE = 16;
+
private static final int MAX_CODE_SIZE_MASK = 0x1f;
/**
@@ -68,7 +79,7 @@ public ZCompressorInputStream(final InputStream inputStream)
throws IOException
* Constructs a new instance.
*
* @param inputStream The underlying input stream.
- * @param memoryLimitInKiB maximum allowed estimated memory usage in
kibibytes.
+ * @param memoryLimitInKiB maximum allowed estimated table memory usage in
kibibytes; a negative value means no configured limit.
* @throws IOException if an I/O error occurs.
*/
public ZCompressorInputStream(final InputStream inputStream, final int
memoryLimitInKiB) throws IOException {
@@ -81,6 +92,9 @@ public ZCompressorInputStream(final InputStream inputStream,
final int memoryLim
}
blockMode = (thirdByte & BLOCK_MODE_MASK) != 0;
maxCodeSize = thirdByte & MAX_CODE_SIZE_MASK;
+ if (maxCodeSize < DEFAULT_CODE_SIZE || maxCodeSize > MAX_CODE_SIZE) {
+ throw new CompressorException("Unsupported .Z maximum code size
%d; expected 9 to 16", maxCodeSize);
+ }
if (blockMode) {
setClearCode(DEFAULT_CODE_SIZE);
}
diff --git a/src/site/xdoc/examples.xml b/src/site/xdoc/examples.xml
index 3f4c5fd8a..03aaea472 100644
--- a/src/site/xdoc/examples.xml
+++ b/src/site/xdoc/examples.xml
@@ -102,6 +102,24 @@ CompressorInputStream input = new CompressorStreamFactory()
generated JAR bytes cached in memory when unpacking Pack200. For
Pack200,
unpacker working memory, unused buffer capacity, and temporary
allocations
are not included in the limit.</p>
+ <p>Since 1.29.0, factory constructors without an explicit memory limit,
+ and LZMA, XZ, and Pack200 input stream builders and constructors
without
+ an explicit limit, default to 1 GiB (1,048,576 KiB). Configure a
different
+ limit with <code>new CompressorStreamFactory(false, limitKiB)</code> or
+ the input stream builder's <code>setMemoryLimitKiB(limitKiB)</code>
method.
+ Set the limit to <code>-1</code> to retain unlimited operation.</p>
+ <p>XZ-compressed ZIP entries read by <code>ZipFile</code> or
+ <code>ZipArchiveInputStream</code> also use the XZ decoder's default
+ limit. Those ZIP APIs do not expose a memory-limit override.</p>
+ <p>The limit covers estimated decoder memory for Z, LZMA, and XZ, and
+ generated JAR bytes cached in memory for Pack200. Pack200's
+ <code>TEMP_FILE</code> strategy is unaffected. This is not a total JVM
+ memory budget: smaller heaps, concurrent streams, and allocations
outside
+ the estimate can still exhaust memory. Applications should select
limits
+ appropriate to their available resources and also bound output and
processing time.</p>
+ <p>Z decompression supports maximum code widths from 9 to 16 bits and
+ rejects unsupported widths before allocating tables, even with an
unlimited
+ memory setting. Its tables require at most 384 KiB, excluding object
and array overhead.</p>
<p>Since Compress 1.19 <code>SevenZFile</code> also has an
optional constructor to pass an upper memory limit which is supported
in LZMA compressed streams. Since Compress 1.21 this setting
diff --git a/src/site/xdoc/pack200.xml b/src/site/xdoc/pack200.xml
index 5b574e449..14c3e19df 100644
--- a/src/site/xdoc/pack200.xml
+++ b/src/site/xdoc/pack200.xml
@@ -62,7 +62,8 @@
<p>Since 1.29.0,
<code>Pack200CompressorInputStream.Builder.setMemoryLimitKiB</code>
can limit the size of the generated JAR cached by the in-memory
strategy.
- A negative value, including the default of -1, leaves the cache
unlimited.
+ The default is 1 GiB (1,048,576 KiB). Set a negative value, such as -1,
+ to leave the cache unlimited.
If a write would exceed the limit, construction throws
<code>MemoryLimitException</code> and closes the source stream. The
limit
counts JAR bytes, including headers and possibly compressed entries; it
diff --git
a/src/test/java/org/apache/commons/compress/compressors/AbstractCompressorBuilderTest.java
b/src/test/java/org/apache/commons/compress/compressors/AbstractCompressorBuilderTest.java
index 68f045b0c..d64d51054 100644
---
a/src/test/java/org/apache/commons/compress/compressors/AbstractCompressorBuilderTest.java
+++
b/src/test/java/org/apache/commons/compress/compressors/AbstractCompressorBuilderTest.java
@@ -34,6 +34,7 @@
import
org.apache.commons.compress.compressors.pack200.Pack200CompressorInputStream;
import org.apache.commons.compress.compressors.xz.XZCompressorInputStream;
import org.apache.commons.io.IOUtils;
+import org.junit.jupiter.api.Test;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.EnumSource;
@@ -42,6 +43,17 @@
*/
class AbstractCompressorBuilderTest extends AbstractTest {
+ /**
+ * Uses the base builder's default configuration.
+ */
+ private static class CustomBuilder extends
AbstractCompressorBuilder<CompressorInputStream, CustomBuilder> {
+
+ @Override
+ public CompressorInputStream get() {
+ throw new UnsupportedOperationException();
+ }
+ }
+
private enum Format {
LZMA("bla.tar.lzma"), PACK200("bla.pack"), XZ("bla.tar.xz"),
XZ_CONCATENATED("bla.tar.xz");
@@ -71,11 +83,30 @@ private byte[] decompress(final AbstractCompressorBuilder<?
extends CompressorIn
}
}
+ @Test
+ void testCustomBuilderRetainsUnlimitedDefault() {
+ assertEquals(-1, new CustomBuilder().getMemoryLimitKiB());
+ }
+
+ @ParameterizedTest
+ @EnumSource(value = Format.class, names = { "LZMA", "XZ",
"XZ_CONCATENATED" })
+ void testMemoryLimitBoundary(final Format format) throws IOException {
+ final AbstractCompressorBuilder<? extends CompressorInputStream, ?>
builder = builder(format);
+ final byte[] expected = decompress(builder);
+ builder.setMemoryLimitKiB(0);
+ final MemoryLimitException exception =
assertThrows(MemoryLimitException.class, () -> decompress(builder));
+ final int requiredKiB =
Math.toIntExact(exception.getMemoryNeededInKb());
+ builder.setMemoryLimitKiB(requiredKiB);
+ assertArrayEquals(expected, decompress(builder));
+ builder.setMemoryLimitKiB(requiredKiB - 1);
+ assertThrows(MemoryLimitException.class, () -> decompress(builder));
+ }
+
@ParameterizedTest
@EnumSource(Format.class)
void testMemoryLimit(final Format format) throws IOException {
final AbstractCompressorBuilder<? extends CompressorInputStream, ?>
builder = builder(format);
- assertEquals(-1, builder.getMemoryLimitKiB());
+ assertEquals(CompressorStreamFactory.DEFAULT_MEMORY_LIMIT_KIB,
builder.getMemoryLimitKiB());
final byte[] expected = decompress(builder);
assertTrue(expected.length > 0);
assertSame(builder, builder.setMemoryLimitKiB(0));
@@ -87,4 +118,5 @@ void testMemoryLimit(final Format format) throws IOException
{
assertSame(builder, builder.setMemoryLimitKiB(-1));
assertArrayEquals(expected, decompress(builder));
}
+
}
diff --git
a/src/test/java/org/apache/commons/compress/compressors/CompressorMemoryLimitTest.java
b/src/test/java/org/apache/commons/compress/compressors/CompressorMemoryLimitTest.java
new file mode 100644
index 000000000..ddfdaff02
--- /dev/null
+++
b/src/test/java/org/apache/commons/compress/compressors/CompressorMemoryLimitTest.java
@@ -0,0 +1,277 @@
+/*
+ * 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
+ *
+ * https://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.commons.compress.compressors;
+
+import static org.junit.jupiter.api.Assertions.assertArrayEquals;
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertInstanceOf;
+import static org.junit.jupiter.api.Assertions.assertThrows;
+import static org.junit.jupiter.api.Assertions.assertTrue;
+
+import java.io.ByteArrayInputStream;
+import java.io.ByteArrayOutputStream;
+import java.io.IOException;
+import java.io.InputStream;
+import java.io.SequenceInputStream;
+import java.nio.charset.StandardCharsets;
+import java.nio.file.Files;
+import java.nio.file.Path;
+import java.nio.file.Paths;
+import java.util.Arrays;
+import java.util.concurrent.TimeUnit;
+import java.util.zip.CRC32;
+
+import org.apache.commons.compress.AbstractTest;
+import org.apache.commons.compress.MemoryLimitException;
+import org.apache.commons.compress.archivers.zip.ZipArchiveEntry;
+import org.apache.commons.compress.archivers.zip.ZipArchiveInputStream;
+import org.apache.commons.compress.archivers.zip.ZipFile;
+import org.apache.commons.compress.compressors.lzma.LZMACompressorInputStream;
+import
org.apache.commons.compress.compressors.pack200.Pack200CompressorInputStream;
+import org.apache.commons.compress.compressors.xz.XZCompressorInputStream;
+import org.apache.commons.compress.compressors.z.ZCompressorInputStream;
+import org.apache.commons.io.IOUtils;
+import org.apache.commons.io.channels.ByteArraySeekableByteChannel;
+import org.apache.commons.lang3.SystemUtils;
+import org.junit.jupiter.api.Test;
+import org.junit.jupiter.api.io.TempDir;
+import org.junit.jupiter.params.ParameterizedTest;
+import org.junit.jupiter.params.provider.ValueSource;
+import org.tukaani.xz.LZMA2Options;
+import org.tukaani.xz.LZMAOutputStream;
+
+/**
+ * Tests default memory limits through the public entry points.
+ */
+class CompressorMemoryLimitTest extends AbstractTest {
+
+ /**
+ * Runs large-header regressions in a separate JVM with a small heap.
+ */
+ public static class LargeHeaderProbe {
+
+ private static void assertFactoryLimit(final CompressorStreamFactory
factory, final String name, final byte[] bytes, final boolean autoDetect)
+ throws Exception {
+ if (CompressorStreamFactory.XZ.equals(name)) {
+ for (final boolean skip : new boolean[] { false, true }) {
+ try (InputStream input = create(factory, name, bytes,
autoDetect)) {
+ final MemoryLimitException exception =
assertThrows(MemoryLimitException.class, () -> {
+ if (skip) {
+ input.skip(1);
+ } else {
+ input.read();
+ }
+ });
+
assertEquals(CompressorStreamFactory.DEFAULT_MEMORY_LIMIT_KIB,
exception.getMemoryLimitInKb());
+ }
+ }
+ } else {
+ final CompressorException exception =
assertThrows(CompressorException.class, () -> create(factory, name, bytes,
autoDetect));
+ if (CompressorStreamFactory.LZMA.equals(name)) {
+ final MemoryLimitException cause =
assertInstanceOf(MemoryLimitException.class, exception.getCause());
+
assertEquals(CompressorStreamFactory.DEFAULT_MEMORY_LIMIT_KIB,
cause.getMemoryLimitInKb());
+ } else {
+ assertInstanceOf(CompressorException.class,
exception.getCause());
+ }
+ }
+ }
+
+ private static byte[] largeLzmaHeader() {
+ final byte[] bytes = new byte[13];
+ bytes[0] = 0x5d;
+ bytes[4] = 0x60; // 1.5 GiB dictionary, little endian.
+ Arrays.fill(bytes, 5, 13, (byte) 0xff); // Unknown uncompressed
size.
+ return bytes;
+ }
+
+ private static byte[] largeXzHeader() {
+ final byte[] bytes = { (byte) 0xfd, 0x37, 0x7a, 0x58, 0x5a, 0, 0,
0, 0, 0, 0, 0,
+ 2, 0, 0x21, 1, 37, 0, 0, 0, 0, 0, 0, 0 };
+ // One LZMA2 filter, dictionary property 37 (1.5 GiB), with valid
header checksums.
+ writeCrc(bytes, 6, 2, 8);
+ writeCrc(bytes, 12, 8, 20);
+ return bytes;
+ }
+
+ public static void main(final String[] args) throws Exception {
+ final byte[] z = { 0x1f, (byte) 0x9d, (byte) 0x9e, 0 };
+ final byte[] lzma = largeLzmaHeader();
+ final byte[] xz = largeXzHeader();
+ for (final CompressorStreamFactory factory : defaultFactories()) {
+ for (final boolean autoDetect : new boolean[] { false, true })
{
+ assertFactoryLimit(factory, CompressorStreamFactory.Z, z,
autoDetect);
+ assertFactoryLimit(factory, CompressorStreamFactory.LZMA,
lzma, autoDetect);
+ assertFactoryLimit(factory, CompressorStreamFactory.XZ,
xz, autoDetect);
+ }
+ }
+ for (int codeSize = 18; codeSize <= 31; codeSize++) {
+ z[2] = (byte) (0x80 | codeSize);
+ assertThrows(CompressorException.class, () -> new
ZCompressorInputStream(new ByteArrayInputStream(z)));
+ assertThrows(CompressorException.class, () -> new
ZCompressorInputStream(new ByteArrayInputStream(z), -1));
+ }
+ assertThrows(MemoryLimitException.class, () -> new
LZMACompressorInputStream(new ByteArrayInputStream(lzma)));
+ assertThrows(MemoryLimitException.class, () ->
LZMACompressorInputStream.builder().setByteArray(lzma).get());
+ try (InputStream input = new XZCompressorInputStream(new
ByteArrayInputStream(xz))) {
+ assertThrows(MemoryLimitException.class, () -> input.read());
+ }
+ for (final boolean concatenated : new boolean[] { false, true }) {
+ try (InputStream input =
XZCompressorInputStream.builder().setByteArray(xz).setDecompressConcatenated(concatenated).get())
{
+ assertThrows(MemoryLimitException.class, () ->
input.read());
+ }
+ }
+ final byte[] firstStream = readAllBytes("bla.tar.xz");
+ try (InputStream source = new SequenceInputStream(new
ByteArrayInputStream(firstStream), new ByteArrayInputStream(xz));
+ InputStream input =
XZCompressorInputStream.builder().setInputStream(source).setDecompressConcatenated(true).get())
{
+ assertThrows(MemoryLimitException.class, () ->
IOUtils.toByteArray(input));
+ }
+ try (InputStream source = new SequenceInputStream(new
ByteArrayInputStream(firstStream), new ByteArrayInputStream(xz));
+ InputStream input = new
CompressorStreamFactory(true).createCompressorInputStream(CompressorStreamFactory.XZ,
source)) {
+ assertThrows(MemoryLimitException.class, () ->
IOUtils.toByteArray(input));
+ }
+ testExplicitLargeLimit();
+ testXzZipEntries();
+ }
+
+ private static void testExplicitLargeLimit() throws Exception {
+ // A known one-byte output lets xz-java reduce the actual
dictionary allocation to 4 KiB,
+ // while its estimate still reflects the large dictionary declared
in the header.
+ final ByteArrayOutputStream output = new ByteArrayOutputStream();
+ final LZMA2Options options = new LZMA2Options();
+ options.setDictSize(4096);
+ try (LZMAOutputStream encoder = new LZMAOutputStream(output,
options, 1)) {
+ encoder.write(42);
+ }
+ final byte[] packed = output.toByteArray();
+ System.arraycopy(largeLzmaHeader(), 1, packed, 1, 4);
+ assertThrows(MemoryLimitException.class, () ->
LZMACompressorInputStream.builder().setByteArray(packed).get());
+ for (final int limit : new int[] { -1, Integer.MAX_VALUE }) {
+ try (InputStream input =
LZMACompressorInputStream.builder().setByteArray(packed).setMemoryLimitKiB(limit).get())
{
+ assertArrayEquals(new byte[] { 42 },
IOUtils.toByteArray(input));
+ }
+ for (final boolean autoDetect : new boolean[] { false, true })
{
+ try (InputStream input = create(new
CompressorStreamFactory(false, limit), CompressorStreamFactory.LZMA, packed,
autoDetect)) {
+ assertArrayEquals(new byte[] { 42 },
IOUtils.toByteArray(input));
+ }
+ }
+ }
+ }
+
+ private static void testXzZipEntries() throws IOException {
+ final byte[] packed =
readAllBytes("org/apache/commons/compress/zip/test-method-xz.zip");
+ final int offset;
+ try (ByteArraySeekableByteChannel channel =
ByteArraySeekableByteChannel.wrap(packed);
+ ZipFile zip = ZipFile.builder().setChannel(channel).get())
{
+ offset =
Math.toIntExact(zip.getEntry("LICENSE.txt").getDataOffset());
+ }
+ final byte[] xz = largeXzHeader();
+ System.arraycopy(xz, 0, packed, offset, xz.length);
+ try (ByteArraySeekableByteChannel channel =
ByteArraySeekableByteChannel.wrap(packed);
+ ZipFile zip = ZipFile.builder().setChannel(channel).get())
{
+ final ZipArchiveEntry entry = zip.getEntry("LICENSE.txt");
+ try (InputStream input = zip.getInputStream(entry)) {
+ assertThrows(MemoryLimitException.class, () ->
input.read());
+ }
+ }
+ try (ZipArchiveInputStream input = new ZipArchiveInputStream(new
ByteArrayInputStream(packed))) {
+ input.getNextEntry();
+ assertThrows(MemoryLimitException.class, () -> input.read());
+ }
+ }
+
+ private static void writeCrc(final byte[] bytes, final int start,
final int length, final int destination) {
+ final CRC32 crc = new CRC32();
+ crc.update(bytes, start, length);
+ final long value = crc.getValue();
+ for (int i = 0; i < 4; i++) {
+ bytes[destination + i] = (byte) (value >>> (8 * i));
+ }
+ }
+ }
+
+ private static InputStream create(final CompressorStreamFactory factory,
final String name, final byte[] packed, final boolean autoDetect)
+ throws CompressorException {
+ final InputStream source = new ByteArrayInputStream(packed);
+ return autoDetect ? factory.createCompressorInputStream(source) :
factory.createCompressorInputStream(name, source);
+ }
+
+ private static CompressorStreamFactory[] defaultFactories() {
+ return new CompressorStreamFactory[] { new CompressorStreamFactory(),
new CompressorStreamFactory(false), new CompressorStreamFactory(true),
+ CompressorStreamFactory.getSingleton() };
+ }
+
+ @Test
+ void testLargeHeadersWithBoundedHeap(@TempDir final Path directory) throws
Exception {
+ final Path output = directory.resolve("large-headers.log");
+ final String java = Paths.get(System.getProperty("java.home"), "bin",
SystemUtils.IS_OS_WINDOWS ? "java.exe" : "java").toString();
+ final String classpath =
System.getProperty("surefire.test.class.path",
System.getProperty("java.class.path"));
+ final Process process = new ProcessBuilder(java, "-Xmx64m", "-cp",
classpath, LargeHeaderProbe.class.getName())
+
.redirectErrorStream(true).redirectOutput(output.toFile()).start();
+ try {
+ assertTrue(process.waitFor(30, TimeUnit.SECONDS), "Large-header
probe timed out");
+ assertEquals(0, process.exitValue(), () -> {
+ try {
+ return new String(Files.readAllBytes(output),
StandardCharsets.UTF_8);
+ } catch (final IOException e) {
+ return e.toString();
+ }
+ });
+ } finally {
+ process.destroyForcibly();
+ }
+ }
+
+ @ParameterizedTest
+ @ValueSource(strings = { "Z", "lzma", "xz", "pack" })
+ void testFactoryDefaultsAndExplicitLimits(final String extension) throws
Exception {
+ final String resource = "pack".equals(extension) ? "bla.pack" :
"bla.tar." + extension;
+ final String name = "pack".equals(extension) ?
CompressorStreamFactory.PACK200 : extension;
+ final byte[] packed = readAllBytes(resource);
+ final byte[] expected;
+ try (InputStream input = create(new CompressorStreamFactory(false,
-1), name, packed, false)) {
+ expected = IOUtils.toByteArray(input);
+ }
+ for (final boolean autoDetect : new boolean[] { false, true }) {
+ for (final CompressorStreamFactory factory : defaultFactories()) {
+ try (InputStream input = create(factory, name, packed,
autoDetect)) {
+ assertArrayEquals(expected, IOUtils.toByteArray(input));
+ }
+ }
+ for (final int limit : new int[] { -1, 100_000 }) {
+ try (InputStream input = create(new
CompressorStreamFactory(false, limit), name, packed, autoDetect)) {
+ assertArrayEquals(expected, IOUtils.toByteArray(input));
+ }
+ }
+ }
+ }
+
+ @Test
+ void testPack200Constructors() throws IOException {
+ final byte[] expected;
+ try (InputStream input =
Pack200CompressorInputStream.builder().setPath(getPath("bla.pack")).get()) {
+ expected = IOUtils.toByteArray(input);
+ }
+ try (InputStream input = new
Pack200CompressorInputStream(getFile("bla.pack"))) {
+ assertArrayEquals(expected, IOUtils.toByteArray(input));
+ }
+ try (InputStream source = new
ByteArrayInputStream(readAllBytes("bla.pack"));
+ InputStream input = new Pack200CompressorInputStream(source)) {
+ assertArrayEquals(expected, IOUtils.toByteArray(input));
+ }
+ }
+}
diff --git
a/src/test/java/org/apache/commons/compress/compressors/DetectCompressorTest.java
b/src/test/java/org/apache/commons/compress/compressors/DetectCompressorTest.java
index 77ddd04c4..fb90ad8dc 100644
---
a/src/test/java/org/apache/commons/compress/compressors/DetectCompressorTest.java
+++
b/src/test/java/org/apache/commons/compress/compressors/DetectCompressorTest.java
@@ -361,6 +361,6 @@ void testXZMemoryLimitOnSkip() throws Exception {
@Test
void testZMemoryLimit() throws Exception {
- assertThrows(MemoryLimitException.class, () ->
createInputStream("COMPRESS-386", 100));
+ assertThrows(MemoryLimitException.class, () ->
createInputStream("bla.tar.Z", 100));
}
}
diff --git
a/src/test/java/org/apache/commons/compress/compressors/z/ZCompressorInputStreamTest.java
b/src/test/java/org/apache/commons/compress/compressors/z/ZCompressorInputStreamTest.java
index 55b6499f9..74941a1fb 100644
---
a/src/test/java/org/apache/commons/compress/compressors/z/ZCompressorInputStreamTest.java
+++
b/src/test/java/org/apache/commons/compress/compressors/z/ZCompressorInputStreamTest.java
@@ -18,6 +18,7 @@
*/
package org.apache.commons.compress.compressors.z;
+import static org.junit.jupiter.api.Assertions.assertArrayEquals;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertThrows;
@@ -33,9 +34,12 @@
import org.apache.commons.compress.AbstractTest;
import org.apache.commons.compress.CompressException;
+import org.apache.commons.compress.MemoryLimitException;
import org.apache.commons.compress.compressors.CompressorException;
import org.apache.commons.io.IOUtils;
import org.junit.jupiter.api.Test;
+import org.junit.jupiter.params.ParameterizedTest;
+import org.junit.jupiter.params.provider.ValueSource;
/**
* Tests for class {@link ZCompressorInputStream}.
@@ -75,6 +79,45 @@ void testInvalidMaxCodeSize() throws IOException {
}));
}
+ @ParameterizedTest
+ @ValueSource(ints = { 0, 8, 17 })
+ void testUnsupportedCodeSizes(final int codeSize) {
+ // Even if validation regresses, the largest table here is only 768
KiB.
+ for (final int blockMode : new int[] { 0, 0x80 }) {
+ final byte[] header = { 0x1f, (byte) 0x9d, (byte) (blockMode |
codeSize) };
+ for (final int limit : new int[] { -1, 0, Integer.MAX_VALUE }) {
+ assertThrows(CompressorException.class, () -> new
ZCompressorInputStream(new ByteArrayInputStream(header), limit));
+ }
+ }
+ }
+
+ @ParameterizedTest
+ @ValueSource(ints = { 9, 16 })
+ void testSupportedCodeSizesAndMemoryLimit(final int codeSize) throws
IOException {
+ final int requiredKiB = (1 << codeSize) * 6 / 1024;
+ for (final int blockMode : new int[] { 0, 0x80 }) {
+ final byte[] header = { 0x1f, (byte) 0x9d, (byte) (blockMode |
codeSize) };
+ final MemoryLimitException exception =
assertThrows(MemoryLimitException.class,
+ () -> new ZCompressorInputStream(new
ByteArrayInputStream(header), requiredKiB - 1));
+ assertEquals(requiredKiB, exception.getMemoryNeededInKb());
+ assertEquals(requiredKiB - 1, exception.getMemoryLimitInKb());
+ for (final int limit : new int[] { -1, -2, requiredKiB,
Integer.MAX_VALUE }) {
+ try (InputStream input = new ZCompressorInputStream(new
ByteArrayInputStream(header), limit)) {
+ assertEquals(-1, input.read());
+ }
+ }
+ }
+ }
+
+ @Test
+ void testUnlimitedDecompression() throws IOException {
+ final byte[] packed = AbstractTest.readAllBytes("bla.tar.Z");
+ try (InputStream defaults = new ZCompressorInputStream(new
ByteArrayInputStream(packed));
+ InputStream unlimited = new ZCompressorInputStream(new
ByteArrayInputStream(packed), -1)) {
+ assertArrayEquals(IOUtils.toByteArray(defaults),
IOUtils.toByteArray(unlimited));
+ }
+ }
+
@Test
void testMultiByteReadConsistentlyReturnsMinusOneAtEof() throws
IOException {
final File input = AbstractTest.getFile("bla.tar.Z");