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 05e287f09 Preserve known input bounds when unpacking Pack200 (f002)
(#858)
05e287f09 is described below
commit 05e287f09bd37932471e641d784a4e1f08c255b7
Author: Gary Gregory <[email protected]>
AuthorDate: Mon Nov 30 07:16:58 2026 -0500
Preserve known input bounds when unpacking Pack200 (f002) (#858)
Carry forward bounds and consumed-byte counts when adding buffering.
Use BoundedInputStream builders and Files.size() for explicit I/O error
reporting. Keep inflated GZIP data unbounded when its size is unknown.
Correct Javadoc and add regression tests for truncated bands, partially
consumed streams, stream ownership, and highly compressible archives.
---
src/changes/changes.xml | 3 +-
.../compress/harmony/unpack200/Archive.java | 27 ++-
.../harmony/unpack200/Pack200UnpackerAdapter.java | 7 +-
.../harmony/unpack200/ArchiveBoundsTest.java | 260 +++++++++++++++++++++
4 files changed, 286 insertions(+), 11 deletions(-)
diff --git a/src/changes/changes.xml b/src/changes/changes.xml
index 50ef4b3d6..6b14b8aaf 100644
--- a/src/changes/changes.xml
+++ b/src/changes/changes.xml
@@ -132,7 +132,8 @@ The <action> type attribute can be add,update,fix,remove.
<action type="fix" dev="ggregory" due-to="KALI 834X, Gary
Gregory">[Unpack200] Reject negative counts in pack200
parseCPUTF8/SignatureReferences (#789).</action>
<action type="fix" dev="ggregory" due-to="KALI 834X, Gary
Gregory">[Unpack200] Reject out-of-range cpUTF8Prefix in CpBands.parseCpUtf8
(#800).</action>
<action type="fix" dev="ggregory" due-to="KALI 834X, Gary
Gregory">[Unpack200] Remove Error rethrow in pack200 ReferenceForm and
NewClassRefForm (unpack200 package) (#805).</action>
- <!-- FIX pack200 -->
+ <action type="fix" dev="ggregory" due-to="Gary Gregory">[Unpack200]
Preserve known input bounds when unpacking files and buffering streams.</action>
+ <!-- FIX pack200 -->
<action type="fix" dev="ggregory" due-to="Gary Gregory, Igor
Morgenstern">[Pack200] org.apache.commons.compress.harmony.pack200 now throws
Pack200Exception, IllegalArgumentException, IllegalStateException, instead of
other runtime exceptions and Error.</action>
<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>
diff --git
a/src/main/java/org/apache/commons/compress/harmony/unpack200/Archive.java
b/src/main/java/org/apache/commons/compress/harmony/unpack200/Archive.java
index 91b5cd3e8..164d82811 100644
--- a/src/main/java/org/apache/commons/compress/harmony/unpack200/Archive.java
+++ b/src/main/java/org/apache/commons/compress/harmony/unpack200/Archive.java
@@ -70,12 +70,20 @@ public class Archive {
private final boolean closeStreams;
/**
- * Creates an Archive with streams for the input and output files. Note:
If you use this method then calling {@link #setRemovePackFile(boolean)} will
have
- * no effect.
+ * Creates an Archive with streams for the input and output files.
*
- * @param inputStream The input stream, preferably a {@link
BoundedInputStream}. The bound can the file size.
+ * <p>
+ * A {@link BoundedInputStream} can supply a known input bound, such as
the file size. Its remaining allowance is preserved when buffering is added.
+ * For GZIP input, this bound applies to the compressed bytes, not the
decompressed Pack200 data.
+ * </p>
+ *
+ * <p>
+ * Calling {@link #unpack()} leaves both streams open.
+ * </p>
+ *
+ * @param inputStream The input stream, preferably a {@link
BoundedInputStream} with a known bound.
* @param outputStream The JAR output stream.
- * @throws IOException if an I/O error occurs
+ * @throws IOException if an I/O error occurs.
*/
public Archive(final InputStream inputStream, final JarOutputStream
outputStream) throws IOException {
this.inputStream =
Pack200UnpackerAdapter.newBoundedInputStream(inputStream);
@@ -184,14 +192,16 @@ public void setVerbose(final boolean verbose) {
/**
* Unpacks the Archive from the input file to the output file.
*
- * @throws Pack200Exception Never thrown.
- * @throws IOException if an I/O error has occurred.
+ * @throws Pack200Exception if the Pack200 data is invalid.
+ * @throws IOException if an I/O error has occurred.
*/
public void unpack() throws Pack200Exception, IOException {
outputStream.setComment("PACK200");
try {
if (!inputStream.markSupported()) {
- inputStream = new BoundedInputStream(new
BufferedInputStream(inputStream));
+ // Preserve the remaining allowance, including bytes consumed
before unpacking.
+ inputStream = BoundedInputStream.builder().setInputStream(new
BufferedInputStream(inputStream))
+
.setMaxCount(inputStream.getMaxCount()).setCount(inputStream.getCount()).get();
if (!inputStream.markSupported()) {
throw new IllegalStateException();
}
@@ -199,7 +209,8 @@ public void unpack() throws Pack200Exception, IOException {
inputStream.mark(2);
if ((inputStream.read() & 0xFF | (inputStream.read() & 0xFF) << 8)
== GZIPInputStream.GZIP_MAGIC) {
inputStream.reset();
- inputStream = new BoundedInputStream(new
BufferedInputStream(new GZIPInputStream(inputStream)));
+ // The compressed input retains its bound; the inflated length
is unknown.
+ inputStream = BoundedInputStream.builder().setInputStream(new
BufferedInputStream(new GZIPInputStream(inputStream))).get();
} else {
inputStream.reset();
}
diff --git
a/src/main/java/org/apache/commons/compress/harmony/unpack200/Pack200UnpackerAdapter.java
b/src/main/java/org/apache/commons/compress/harmony/unpack200/Pack200UnpackerAdapter.java
index 27bcb361d..a7c4f9e5d 100644
---
a/src/main/java/org/apache/commons/compress/harmony/unpack200/Pack200UnpackerAdapter.java
+++
b/src/main/java/org/apache/commons/compress/harmony/unpack200/Pack200UnpackerAdapter.java
@@ -171,9 +171,12 @@ public void unpack(final File file, final JarOutputStream
out) throws IOExceptio
if (out == null) {
throw new IllegalArgumentException("Must specify output stream.");
}
- final long size = file.length();
+ // Files.size() throws on I/O errors instead of returning zero, which
would become an empty input bound.
+ final long size = Files.size(file.toPath());
final int bufferSize = size > 0 && size < DEFAULT_BUFFER_SIZE ? (int)
size : DEFAULT_BUFFER_SIZE;
- try (InputStream in = new
BufferedInputStream(Files.newInputStream(file.toPath()), bufferSize)) {
+ try (InputStream in = BoundedInputStream.builder()
+ .setInputStream(new
BufferedInputStream(Files.newInputStream(file.toPath()), bufferSize))
+ .setMaxCount(size).get()) {
unpack(in, out);
}
}
diff --git
a/src/test/java/org/apache/commons/compress/harmony/unpack200/ArchiveBoundsTest.java
b/src/test/java/org/apache/commons/compress/harmony/unpack200/ArchiveBoundsTest.java
new file mode 100644
index 000000000..f17577762
--- /dev/null
+++
b/src/test/java/org/apache/commons/compress/harmony/unpack200/ArchiveBoundsTest.java
@@ -0,0 +1,260 @@
+/*
+ * 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.harmony.unpack200;
+
+import static org.junit.jupiter.api.Assertions.assertArrayEquals;
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertFalse;
+import static org.junit.jupiter.api.Assertions.assertNotNull;
+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.OutputStream;
+import java.nio.file.Files;
+import java.nio.file.Path;
+import java.util.Arrays;
+import java.util.concurrent.atomic.AtomicBoolean;
+import java.util.jar.JarEntry;
+import java.util.jar.JarFile;
+import java.util.jar.JarOutputStream;
+import java.util.stream.Stream;
+
+import org.apache.commons.compress.AbstractTempDirTest;
+import org.apache.commons.compress.harmony.pack200.Codec;
+import org.apache.commons.compress.harmony.pack200.Pack200Exception;
+import org.apache.commons.compress.harmony.pack200.PackingOptions;
+import org.apache.commons.compress.java.util.jar.Pack200;
+import org.apache.commons.io.IOUtils;
+import org.apache.commons.io.input.BoundedInputStream;
+import org.apache.commons.io.output.NullOutputStream;
+import org.junit.jupiter.api.Test;
+import org.junit.jupiter.params.ParameterizedTest;
+import org.junit.jupiter.params.provider.Arguments;
+import org.junit.jupiter.params.provider.EnumSource;
+import org.junit.jupiter.params.provider.MethodSource;
+import org.junit.jupiter.params.provider.ValueSource;
+
+/**
+ * Tests preservation of input bounds and decoding of GZIP input whose
inflated length is unknown.
+ */
+class ArchiveBoundsTest extends AbstractTempDirTest {
+
+ /**
+ * Input paths with different buffering and bound information.
+ */
+ private enum InputType {
+ FILE, ARCHIVE_FILE, STREAM, BOUNDED, NON_MARKING, NON_MARKING_BOUNDED
+ }
+
+ private static final int RESOURCE_SIZE = 256 * 1024;
+
+ /**
+ * Creates a small truncated segment whose UTF-8 count exceeds the
remaining input.
+ *
+ * @return The malformed segment.
+ * @throws IOException if encoding fails.
+ */
+ private static byte[] malformedPack() throws IOException {
+ final ByteArrayOutputStream out = new ByteArrayOutputStream();
+ out.write(new byte[] { (byte) 0xca, (byte) 0xfe, (byte) 0xd0, 0x0d });
+ // Version, options, UTF-8 count, remaining constant pool counts, and
class counts.
+ out.write(Codec.UNSIGNED5.encode(new int[] { 7, 150, 0, 64, 0, 0, 0,
0, 0, 0, 0, 0, 0, 52, 0 }));
+ out.write(0); // First cp_Utf8_prefix value, followed by missing band
data.
+ return out.toByteArray();
+ }
+
+ /**
+ * Supplies each entry path for both plain and GZIP input.
+ *
+ * @return The input combinations.
+ */
+ static Stream<Arguments> unpackInputs() {
+ return Arrays.stream(InputType.values()).flatMap(type ->
Stream.of(Arguments.of(type, false), Arguments.of(type, true)));
+ }
+
+ /**
+ * Checks every resource name and byte, including the number of output
entries.
+ *
+ * @param output The unpacked JAR.
+ * @param count The expected entry count.
+ * @throws IOException if reading fails.
+ */
+ private void assertResources(final Path output, final int count) throws
IOException {
+ try (JarFile jar = new JarFile(output.toFile())) {
+ assertEquals(count, jar.size());
+ final byte[] expected = new byte[RESOURCE_SIZE];
+ for (int i = 0; i < count; i++) {
+ final String name = "resource-" + i + ".txt";
+ final JarEntry entry = jar.getJarEntry(name);
+ assertNotNull(entry, name);
+ Arrays.fill(expected, (byte) ('A' + i % 26));
+ try (InputStream in = jar.getInputStream(entry)) {
+ assertArrayEquals(expected, IOUtils.toByteArray(in), name);
+ }
+ }
+ }
+ }
+
+ /**
+ * Packs repetitive resources with the project's own packer.
+ *
+ * @param gzip Whether to wrap the Pack200 output in GZIP.
+ * @param count The number of resources.
+ * @return The packed file.
+ * @throws IOException if packing fails.
+ */
+ private Path packResources(final boolean gzip, final int count) throws
IOException {
+ final Path jarPath = createTempPath("resources", ".jar");
+ try (JarOutputStream jar = new
JarOutputStream(Files.newOutputStream(jarPath))) {
+ final byte[] data = new byte[RESOURCE_SIZE];
+ for (int i = 0; i < count; i++) {
+ final JarEntry entry = new JarEntry("resource-" + i + ".txt");
+ entry.setTime(0);
+ jar.putNextEntry(entry);
+ Arrays.fill(data, (byte) ('A' + i % 26));
+ jar.write(data);
+ jar.closeEntry();
+ }
+ }
+ final Path packed = createTempPath("resources", gzip ? ".pack.gz" :
".pack");
+ final PackingOptions options = new PackingOptions();
+ options.setGzip(gzip);
+ try (JarFile jar = new JarFile(jarPath.toFile()); OutputStream out =
Files.newOutputStream(packed)) {
+ new org.apache.commons.compress.harmony.pack200.Archive(jar, out,
options).pack();
+ }
+ return packed;
+ }
+
+ @ParameterizedTest
+ @ValueSource(ints = { 0, 64 })
+ void testBoundedNonMarkingStreamRejectsBandBeyondRemainingInput(final int
prefixLength) throws IOException {
+ final byte[] malformed = malformedPack();
+ final byte[] data = new byte[prefixLength + malformed.length];
+ System.arraycopy(malformed, 0, data, prefixLength, malformed.length);
+ try (InputStream source = new ByteArrayInputStream(data) {
+ @Override
+ public boolean markSupported() {
+ return false;
+ }
+ }; BoundedInputStream in =
BoundedInputStream.builder().setInputStream(source).setMaxCount(data.length).get();
+ JarOutputStream out = new
JarOutputStream(NullOutputStream.INSTANCE)) {
+ IOUtils.skipFully(in, prefixLength);
+ final Pack200Exception exception =
assertThrows(Pack200Exception.class, () -> new Archive(in, out).unpack());
+ assertTrue(exception.getMessage().contains("Can't read beyond end
of stream"));
+ }
+ }
+
+ @Test
+ void testFileRejectsBandBeyondInputSize() throws IOException {
+ final Path input = createTempPath("truncated", ".pack");
+ Files.write(input, malformedPack());
+ try (JarOutputStream out = new
JarOutputStream(NullOutputStream.INSTANCE)) {
+ final Pack200Exception exception =
assertThrows(Pack200Exception.class, () ->
Pack200.newUnpacker().unpack(input.toFile(), out));
+ assertTrue(exception.getMessage().contains("Can't read beyond end
of stream"));
+ }
+ }
+
+ @ParameterizedTest
+ @EnumSource(InputType.class)
+ void testHighlyCompressibleGzipResources(final InputType type) throws
IOException {
+ // 20 MiB of valid resources exceeds both the rejected 16 MiB floor
and 100:1 ratio.
+ final int count = 80;
+ final Path packed = packResources(true, count);
+ assertTrue((long) RESOURCE_SIZE * count > 100 * Files.size(packed));
+ final Path output = createTempPath("inflated", ".jar");
+ unpack(packed, output, type);
+ assertResources(output, count);
+ }
+
+ @ParameterizedTest
+ @ValueSource(booleans = { false, true })
+ void testPartiallyReadBoundedStream(final boolean gzip) throws IOException
{
+ final Path packed = packResources(gzip, 8);
+ final byte[] contents = Files.readAllBytes(packed);
+ final int prefixLength = 64;
+ final byte[] data = new byte[prefixLength + contents.length];
+ System.arraycopy(contents, 0, data, prefixLength, contents.length);
+ final AtomicBoolean closed = new AtomicBoolean();
+ final Path output = createTempPath("partial", ".jar");
+ try (InputStream source = new ByteArrayInputStream(data) {
+ @Override
+ public void close() throws IOException {
+ closed.set(true);
+ super.close();
+ }
+
+ @Override
+ public boolean markSupported() {
+ return false;
+ }
+ }; BoundedInputStream in =
BoundedInputStream.builder().setInputStream(source).setMaxCount(data.length).get();
+ JarOutputStream out = new
JarOutputStream(Files.newOutputStream(output))) {
+ IOUtils.skipFully(in, prefixLength);
+ new Archive(in, out).unpack();
+ assertFalse(closed.get(), "Unpacking must leave the caller's input
open");
+ assertEquals(data.length, in.getCount());
+ }
+ assertTrue(closed.get());
+ assertResources(output, 8);
+ }
+
+ @ParameterizedTest
+ @MethodSource("unpackInputs")
+ void testUnpackResources(final InputType type, final boolean gzip) throws
IOException {
+ final Path packed = packResources(gzip, 8);
+ final Path output = createTempPath("unpacked", ".jar");
+ unpack(packed, output, type);
+ assertResources(output, 8);
+ }
+
+ /**
+ * Unpacks a file through the selected entry path.
+ *
+ * @param packed The packed file.
+ * @param output The destination JAR.
+ * @param type The entry path.
+ * @throws IOException if unpacking fails.
+ */
+ private void unpack(final Path packed, final Path output, final InputType
type) throws IOException {
+ if (type == InputType.ARCHIVE_FILE) {
+ new Archive(packed.toString(), output.toString()).unpack();
+ return;
+ }
+ try (JarOutputStream out = new
JarOutputStream(Files.newOutputStream(output))) {
+ if (type == InputType.FILE) {
+ Pack200.newUnpacker().unpack(packed.toFile(), out);
+ } else {
+ final byte[] data = Files.readAllBytes(packed);
+ try (InputStream source = new ByteArrayInputStream(data) {
+ @Override
+ public boolean markSupported() {
+ return type != InputType.NON_MARKING && type !=
InputType.NON_MARKING_BOUNDED;
+ }
+ }; InputStream in = type == InputType.BOUNDED || type ==
InputType.NON_MARKING_BOUNDED
+ ?
BoundedInputStream.builder().setInputStream(source).setMaxCount(data.length).get()
: source) {
+ Pack200.newUnpacker().unpack(in, out);
+ }
+ }
+ }
+ }
+}