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 9691a7ff5 Fix sparse TAR entry framing (f014) (#871)
9691a7ff5 is described below

commit 9691a7ff5b63796b9138c8e57e6e535b4a963443
Author: Gary Gregory <[email protected]>
AuthorDate: Fri Dec 4 10:30:18 2026 -0500

    Fix sparse TAR entry framing (f014) (#871)
    
    Account for PAX sparse-map bytes when validating stored data lengths.
    Skip unreferenced stored bytes before record padding and reject
    truncated sparse payloads while preserving declared entry sizes.
    
    Add regression coverage for GNU/PAX formats, fragment boundaries,
    read and skip modes, truncation, byte counts, and cleared current
    entries.
    
    Update Javadoc.
---
 src/changes/changes.xml                            |   1 +
 .../archivers/tar/TarArchiveInputStream.java       |  37 +-
 .../tar/TarArchiveInputStreamSparseTest.java       | 480 +++++++++++++++++++++
 3 files changed, 514 insertions(+), 4 deletions(-)

diff --git a/src/changes/changes.xml b/src/changes/changes.xml
index dc66eefa1..d9ebb3372 100644
--- a/src/changes/changes.xml
+++ b/src/changes/changes.xml
@@ -120,6 +120,7 @@ The <action> type attribute can be add,update,fix,remove.
       <action type="fix" dev="ggregory" due-to="Gary Gregory">[TAR] 
TarArchiveOutputStream now throws ArchiveException instead of 
IllegalArgumetException/IllegalStateException.</action>
       <action type="fix" dev="ggregory" due-to="Gary Gregory">[TAR] 
TarArchiveInputStream now throws ArchiveException instead of 
IllegalArgumetException/IllegalStateException.</action>
       <action type="fix" dev="ggregory" due-to="Gary Gregory">[TAR] TarUtils 
now throws ArchiveException instead of 
IllegalArgumetException/IllegalStateException.</action>
+      <action type="fix" dev="ggregory">[TAR] Account for sparse maps and 
unreferenced stored bytes when advancing TarArchiveInputStream entries, 
preserving declared entry sizes and detecting truncated sparse 
payloads.</action>
       <!-- FIX ar -->
       <action type="fix" dev="ggregory" due-to="Gary Gregory">[AR] 
ArArchiveInputStream.readGNUStringTable(byte[], int, int) now provides a better 
exception message, wrapping the underlying exception.</action>
       <action type="fix" dev="ggregory" due-to="Gary Gregory">[AR] 
ArArchiveInputStream.read(byte[], int, int) now throws ArchiveException instead 
of ArithmeticException.</action>
diff --git 
a/src/main/java/org/apache/commons/compress/archivers/tar/TarArchiveInputStream.java
 
b/src/main/java/org/apache/commons/compress/archivers/tar/TarArchiveInputStream.java
index b03447299..67f99ad9d 100644
--- 
a/src/main/java/org/apache/commons/compress/archivers/tar/TarArchiveInputStream.java
+++ 
b/src/main/java/org/apache/commons/compress/archivers/tar/TarArchiveInputStream.java
@@ -151,7 +151,7 @@ public static boolean matches(final byte[] signature, final 
int length) {
     /** True if stream is at EOF. */
     private boolean atEof;
 
-    /** How far into the entry the stream is at. */
+    /** Physical bytes read from the current entry, including an in-data 
sparse map but excluding synthesized holes. */
     private long entryOffset;
 
     /** The meta-data about the current entry. */
@@ -362,6 +362,10 @@ public int available() throws IOException {
     private void buildSparseInputStreams() throws IOException {
         final List<InputStream> sparseInputStreams = new ArrayList<>();
         final List<TarArchiveStructSparse> sparseHeaders = 
currEntry.getOrderedSparseHeaders();
+        // PAX 1.X sparse maps are part of the stored size and have already 
been read through afterRead.
+        // Keep the entry's declared size intact for callers and record 
padding.
+        final long sparseDataSize = 
ArchiveException.requireNonNegative(currEntry.getSize() - entryOffset,
+                "Corrupted TAR archive. Sparse headers are larger than the 
entry size.");
         // Stream doesn't need to be closed at all as it doesn't use any 
resources
         final InputStream zeroInputStream = new 
TarArchiveSparseZeroInputStream(); // NOSONAR
         // logical offset into the extracted entry
@@ -382,11 +386,11 @@ private void buildSparseInputStreams() throws IOException 
{
             }
             // only store the input streams with non-zero size
             if (sparseHeader.getNumbytes() > 0) {
-                dataBytes += sparseHeader.getNumbytes();
+                dataBytes = ArchiveException.addExact(dataBytes, 
sparseHeader.getNumbytes());
                 // the non-hole blocks are read from the underlying stream, so 
their total size must not
-                // exceed the entry's stored size, otherwise reading this 
entry would consume bytes that
+                // exceed the entry's remaining stored size, otherwise reading 
this entry would consume bytes that
                 // belong to following entries
-                if (dataBytes > currEntry.getSize()) {
+                if (dataBytes > sparseDataSize) {
                     throw new ArchiveException("Corrupted TAR archive. Sparse 
blocks for '%s' are larger than the entry size.", currEntry.getName());
                 }
                 // @formatter:off
@@ -502,6 +506,7 @@ public TarArchiveEntry getNextEntry() throws IOException {
             // If there is a current entry, skip any unread data and padding
             if (currentInputStream != null) {
                 IOUtils.consume(currentInputStream); // Skip to end of current 
entry
+                skipSparseEntryData(); // Skip stored bytes not referenced by 
the sparse map
                 skipRecordPadding(); // Skip padding to align to the next 
record
             }
             // Read the next header record
@@ -765,6 +770,30 @@ private void skipRecordPadding() throws IOException {
         }
     }
 
+    /**
+     * Skips any stored bytes left after consuming a sparse entry's fragments.
+     * <p>
+     * Sparse maps may reference fewer bytes than the entry's declared stored 
size. Such bytes still belong to the current entry and must be consumed before
+     * record padding and the next header. The physical byte count includes 
any PAX 1.X sparse map stored in the entry's data.
+     * </p>
+     *
+     * @throws IOException if the archive is truncated or another I/O error 
occurs.
+     */
+    private void skipSparseEntryData() throws IOException {
+        if (currEntry != null && currEntry.isSparse()) {
+            final long remaining = currEntry.getSize() - entryOffset;
+            if (remaining > 0) {
+                final long skipped = IOUtils.skip(in, remaining);
+                count(skipped);
+                entryOffset += skipped;
+                if (skipped != remaining) {
+                    throw new EOFException(String.format("Truncated TAR 
archive: Failed to skip %,d trailing sparse-entry bytes for entry '%s'",
+                            remaining, currEntry.getName()));
+                }
+            }
+        }
+    }
+
     /**
      * Tries to read the next record rewinding the stream if it is not an EOF 
record.
      * <p>
diff --git 
a/src/test/java/org/apache/commons/compress/archivers/tar/TarArchiveInputStreamSparseTest.java
 
b/src/test/java/org/apache/commons/compress/archivers/tar/TarArchiveInputStreamSparseTest.java
new file mode 100644
index 000000000..f778d32a5
--- /dev/null
+++ 
b/src/test/java/org/apache/commons/compress/archivers/tar/TarArchiveInputStreamSparseTest.java
@@ -0,0 +1,480 @@
+/*
+ * 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.archivers.tar;
+
+import static org.junit.jupiter.api.Assertions.assertArrayEquals;
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertNotNull;
+import static org.junit.jupiter.api.Assertions.assertNull;
+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.EOFException;
+import java.io.IOException;
+import java.io.InputStream;
+import java.nio.charset.StandardCharsets;
+import java.util.ArrayList;
+import java.util.Arrays;
+import java.util.List;
+import java.util.stream.Stream;
+
+import org.apache.commons.compress.archivers.ArchiveException;
+import org.apache.commons.io.IOUtils;
+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 physical entry boundaries independently of the logical sparse 
contents. */
+class TarArchiveInputStreamSparseTest {
+
+    /** Ways a caller can consume the logical entry before advancing. */
+    private enum ReadMode {
+        UNREAD, PARTIAL, FULL, SINGLE_BYTES, SKIP_PARTIAL, SKIP_FULL
+    }
+
+    /** Sparse formats with different locations for the sparse map. */
+    private enum SparseFormat {
+        OLD_GNU, OLD_GNU_EXTENDED, PAX_0_0, PAX_0_1, PAX_1_0
+    }
+
+    private static final int RECORD_SIZE = TarConstants.DEFAULT_RCDSIZE;
+    private static final int HOLE_SIZE = 8;
+    private static final byte[] TAIL_DATA = "tail 
data".getBytes(StandardCharsets.US_ASCII);
+
+    private static void appendPadded(final ByteArrayOutputStream out, final 
byte[] bytes) throws IOException {
+        out.write(bytes);
+        out.write(new byte[(RECORD_SIZE - bytes.length % RECORD_SIZE) % 
RECORD_SIZE]);
+    }
+
+    private static void appendPaxHeaders(final ByteArrayOutputStream out, 
final String pax) throws IOException {
+        final byte[] bytes = pax.getBytes(StandardCharsets.US_ASCII);
+        out.write(header("PaxHeaders/sparse", bytes.length, 
TarConstants.LF_PAX_EXTENDED_HEADER_LC));
+        appendPadded(out, bytes);
+    }
+
+    private static void appendSparseEntry(final ByteArrayOutputStream out, 
final SparseFormat format, final String name, final int dataSize,
+            final int slackSize, final int emptyMapEntries) throws IOException 
{
+        final int realSize = dataSize + 2 * HOLE_SIZE;
+        final ByteArrayOutputStream body = new ByteArrayOutputStream();
+        if (format == SparseFormat.PAX_1_0) {
+            appendPadded(body, pax1Map(dataSize, emptyMapEntries));
+        }
+        final byte[] data = new byte[dataSize];
+        Arrays.fill(data, (byte) 'A');
+        body.write(data);
+        final byte[] slack = new byte[slackSize];
+        if (slackSize >= RECORD_SIZE) {
+            // A complete header, and optionally content, that must never 
become a separate entry.
+            final byte[] hiddenData = "hidden 
data".getBytes(StandardCharsets.US_ASCII);
+            final boolean hasContent = slackSize >= 2 * RECORD_SIZE;
+            System.arraycopy(header("HIDDEN", hasContent ? hiddenData.length : 
0, TarConstants.LF_NORMAL), 0, slack, 0, RECORD_SIZE);
+            if (hasContent) {
+                System.arraycopy(hiddenData, 0, slack, RECORD_SIZE, 
hiddenData.length);
+            }
+        }
+        body.write(slack);
+        final boolean oldGnu = format == SparseFormat.OLD_GNU || format == 
SparseFormat.OLD_GNU_EXTENDED;
+        final byte[] entryHeader = header(name, body.size(), oldGnu ? 
TarConstants.LF_GNUTYPE_SPARSE : TarConstants.LF_NORMAL);
+        final byte[] extension = new byte[RECORD_SIZE];
+        if (oldGnu) {
+            TarUtils.formatNameBytes(TarConstants.MAGIC_GNU, entryHeader, 
TarConstants.MAGIC_OFFSET, TarConstants.MAGICLEN);
+            TarUtils.formatNameBytes(TarConstants.VERSION_GNU_SPACE, 
entryHeader, TarConstants.VERSION_OFFSET, TarConstants.VERSIONLEN);
+            // Old GNU headers store four sparse pairs at byte 386, the 
extension flag at 482, and the real size at 483.
+            sparsePair(entryHeader, 386, HOLE_SIZE, dataSize);
+            TarUtils.formatLongOctalBytes(realSize, entryHeader, 483, 
TarConstants.REALSIZELEN_GNU);
+            if (format == SparseFormat.OLD_GNU_EXTENDED) {
+                entryHeader[482] = 1;
+                sparsePair(extension, 0, realSize, 0);
+            } else {
+                sparsePair(entryHeader, 410, realSize, 0);
+            }
+            updateChecksum(entryHeader);
+        } else {
+            String pax;
+            if (format == SparseFormat.PAX_1_0) {
+                pax = pax1Headers(name, realSize);
+            } else {
+                pax = paxRecord("GNU.sparse.size", Integer.toString(realSize));
+                if (format == SparseFormat.PAX_0_1) {
+                    pax += paxRecord("GNU.sparse.map", HOLE_SIZE + "," + 
dataSize + "," + realSize + ",0");
+                } else {
+                    pax += paxRecord("GNU.sparse.offset", 
Integer.toString(HOLE_SIZE)) + paxRecord("GNU.sparse.numbytes", 
Integer.toString(dataSize))
+                            + paxRecord("GNU.sparse.offset", 
Integer.toString(realSize)) + paxRecord("GNU.sparse.numbytes", "0");
+                }
+            }
+            appendPaxHeaders(out, pax);
+        }
+        out.write(entryHeader);
+        if (format == SparseFormat.OLD_GNU_EXTENDED) {
+            // Extended sparse headers are metadata outside the entry's stored 
size.
+            out.write(extension);
+        }
+        appendPadded(out, body.toByteArray());
+    }
+
+    private static void appendTail(final ByteArrayOutputStream out) throws 
IOException {
+        out.write(header("tail.txt", TAIL_DATA.length, 
TarConstants.LF_NORMAL));
+        appendPadded(out, TAIL_DATA);
+        out.write(new byte[2 * RECORD_SIZE]);
+    }
+
+    private static byte[] archive(final SparseFormat format, final int 
dataSize, final int slackSize) throws IOException {
+        final ByteArrayOutputStream out = new ByteArrayOutputStream();
+        appendSparseEntry(out, format, "sparse.bin", dataSize, slackSize, 0);
+        appendTail(out);
+        return out.toByteArray();
+    }
+
+    private static void consumeEntry(final TarArchiveInputStream in, final 
ReadMode mode, final byte[] expected) throws IOException {
+        final int partialSize = HOLE_SIZE + 1;
+        switch (mode) {
+        case PARTIAL:
+            final byte[] prefix = new byte[partialSize];
+            assertEquals(prefix.length, IOUtils.read(in, prefix));
+            assertArrayEquals(Arrays.copyOf(expected, partialSize), prefix);
+            break;
+        case FULL:
+            assertArrayEquals(expected, IOUtils.toByteArray(in));
+            assertEquals(-1, in.read());
+            break;
+        case SINGLE_BYTES:
+            for (final byte value : expected) {
+                assertEquals(value & 0xff, in.read());
+            }
+            assertEquals(-1, in.read());
+            break;
+        case SKIP_PARTIAL:
+            assertEquals(partialSize, in.skip(partialSize));
+            break;
+        case SKIP_FULL:
+            assertEquals(expected.length, in.skip(Long.MAX_VALUE));
+            assertEquals(-1, in.read());
+            break;
+        case UNREAD:
+            break;
+        default:
+            throw new IllegalArgumentException("Unexpected read mode: " + 
mode);
+        }
+    }
+
+    private static byte[] expandedData(final int dataSize) {
+        final byte[] expected = new byte[dataSize + 2 * HOLE_SIZE];
+        Arrays.fill(expected, HOLE_SIZE, HOLE_SIZE + dataSize, (byte) 'A');
+        return expected;
+    }
+
+    private static Stream<Arguments> formatsAndReadModes() {
+        return Arrays.stream(SparseFormat.values()).flatMap(format -> 
Arrays.stream(ReadMode.values()).map(mode -> Arguments.of(format, mode)));
+    }
+
+    private static Stream<Arguments> fragmentBoundaries() {
+        return Arrays.stream(ReadMode.values()).flatMap(mode -> Stream.of(0, 
1, RECORD_SIZE).map(slack -> Arguments.of(mode, slack)));
+    }
+
+    private static byte[] header(final String name, final long size, final 
byte type) throws IOException {
+        final TarArchiveEntry entry = new TarArchiveEntry(name, type);
+        entry.setSize(size);
+        final byte[] header = new byte[RECORD_SIZE];
+        entry.writeEntryHeader(header);
+        return header;
+    }
+
+    private static String pax1Headers(final String name, final int realSize) {
+        return paxRecord("GNU.sparse.major", "1") + 
paxRecord("GNU.sparse.minor", "0") + paxRecord("GNU.sparse.name", name)
+                + paxRecord("GNU.sparse.realsize", Integer.toString(realSize));
+    }
+
+    private static byte[] pax1Map(final int dataSize, final int emptyEntries) {
+        final StringBuilder map = new StringBuilder().append(2 + 
emptyEntries).append('\n');
+        for (int i = 0; i < emptyEntries; i++) {
+            map.append("0\n0\n");
+        }
+        return 
map.append(HOLE_SIZE).append('\n').append(dataSize).append('\n').append(dataSize
 + 2 * HOLE_SIZE).append("\n0\n").toString()
+                .getBytes(StandardCharsets.US_ASCII);
+    }
+
+    private static String paxRecord(final String key, final String value) {
+        final String body = " " + key + "=" + value + "\n";
+        int length = body.length() + 1;
+        while (length != body.length() + Integer.toString(length).length()) {
+            length = body.length() + Integer.toString(length).length();
+        }
+        return length + body;
+    }
+
+    private static Stream<Arguments> sparseBoundaries() {
+        final List<Arguments> cases = new ArrayList<>();
+        for (final SparseFormat format : SparseFormat.values()) {
+            for (final ReadMode mode : ReadMode.values()) {
+                // Include record-aligned and unaligned data, hidden headers 
with and without content, all-hole files, and no slack.
+                for (final int[] sizes : new int[][] {{512, 512}, {512, 1024}, 
{5, 7}, {0, 512}, {512, 0}, {5, 0}}) {
+                    cases.add(Arguments.of(format, mode, sizes[0], sizes[1]));
+                }
+            }
+        }
+        return cases.stream();
+    }
+
+    private static void sparsePair(final byte[] header, final int offset, 
final long position, final long length) throws ArchiveException {
+        TarUtils.formatLongOctalBytes(position, header, offset, 
TarConstants.SPARSE_OFFSET_LEN);
+        TarUtils.formatLongOctalBytes(length, header, offset + 
TarConstants.SPARSE_OFFSET_LEN, TarConstants.SPARSE_NUMBYTES_LEN);
+    }
+
+    @Test
+    void testConsecutiveSparseEntries() throws IOException {
+        final ByteArrayOutputStream out = new ByteArrayOutputStream();
+        for (final SparseFormat format : SparseFormat.values()) {
+            appendSparseEntry(out, format, format.name(), 5, RECORD_SIZE, 0);
+        }
+        appendTail(out);
+        try (TarArchiveInputStream in = 
TarArchiveInputStream.builder().setByteArray(out.toByteArray()).get()) {
+            for (final SparseFormat format : SparseFormat.values()) {
+                assertEquals(format.name(), in.getNextEntry().getName());
+                assertArrayEquals(expandedData(5), IOUtils.toByteArray(in));
+            }
+            assertEquals("tail.txt", in.getNextEntry().getName());
+            assertArrayEquals(TAIL_DATA, IOUtils.toByteArray(in));
+            assertNull(in.getNextEntry());
+        }
+    }
+
+    @Test
+    void testEmptySparseMapSkipsStoredData() throws IOException {
+        final ByteArrayOutputStream out = new ByteArrayOutputStream();
+        appendPaxHeaders(out, pax1Headers("empty", 0));
+        out.write(header("empty", 2 * RECORD_SIZE, TarConstants.LF_NORMAL));
+        appendPadded(out, "0\n".getBytes(StandardCharsets.US_ASCII));
+        out.write(header("HIDDEN", 0, TarConstants.LF_NORMAL));
+        appendTail(out);
+        try (TarArchiveInputStream in = 
TarArchiveInputStream.builder().setByteArray(out.toByteArray()).get()) {
+            assertEquals(2 * RECORD_SIZE, in.getNextEntry().getSize());
+            assertEquals(-1, in.read());
+            assertEquals("tail.txt", in.getNextEntry().getName());
+            assertArrayEquals(TAIL_DATA, IOUtils.toByteArray(in));
+            assertNull(in.getNextEntry());
+        }
+    }
+
+    @ParameterizedTest
+    @MethodSource("fragmentBoundaries")
+    void testMultipleFragmentsBeforeSparseLeftover(final ReadMode mode, final 
int slackSize) throws IOException {
+        final ByteArrayOutputStream out = new ByteArrayOutputStream();
+        appendPaxHeaders(out, pax1Headers("sparse.bin", 18));
+        final int storedSize = RECORD_SIZE + 4 + slackSize;
+        out.write(header("sparse.bin", storedSize, TarConstants.LF_NORMAL));
+        appendPadded(out, 
"2\n8\n2\n16\n2\n".getBytes(StandardCharsets.US_ASCII));
+        final byte[] data = new byte[4 + slackSize];
+        System.arraycopy("ABCD".getBytes(StandardCharsets.US_ASCII), 0, data, 
0, 4);
+        if (slackSize == RECORD_SIZE) {
+            System.arraycopy(header("HIDDEN", 0, TarConstants.LF_NORMAL), 0, 
data, 4, RECORD_SIZE);
+        }
+        appendPadded(out, data);
+        appendTail(out);
+        final byte[] expected = new byte[18];
+        expected[8] = 'A';
+        expected[9] = 'B';
+        expected[16] = 'C';
+        expected[17] = 'D';
+        final byte[] archive = out.toByteArray();
+        try (TarFile file = TarFile.builder().setByteArray(archive).get();
+                TarArchiveInputStream in = 
TarArchiveInputStream.builder().setByteArray(archive).get()) {
+            assertEquals(2, file.getEntries().size());
+            final TarArchiveEntry entry = in.getNextEntry();
+            assertEquals(storedSize, entry.getSize());
+            assertEquals(expected.length, entry.getRealSize());
+            try (InputStream contents = 
file.getInputStream(file.getEntries().get(0))) {
+                assertArrayEquals(expected, IOUtils.toByteArray(contents));
+            }
+            consumeEntry(in, mode, expected);
+            assertEquals("tail.txt", in.getNextEntry().getName());
+            assertEquals(archive.length - 3 * RECORD_SIZE, in.getBytesRead());
+            assertArrayEquals(TAIL_DATA, IOUtils.toByteArray(in));
+            assertNull(in.getNextEntry());
+        }
+    }
+
+    @Test
+    void testNextEntryAfterClearingCurrentEntry() throws IOException {
+        final ByteArrayOutputStream out = new ByteArrayOutputStream();
+        out.write(header("empty", 0, TarConstants.LF_NORMAL));
+        appendTail(out);
+        try (TarArchiveInputStream in = 
TarArchiveInputStream.builder().setByteArray(out.toByteArray()).get()) {
+            assertEquals("empty", in.getNextEntry().getName());
+            assertEquals(-1, in.read());
+            in.setCurrentEntry(null);
+            assertEquals("tail.txt", in.getNextEntry().getName());
+            assertArrayEquals(TAIL_DATA, IOUtils.toByteArray(in));
+            assertNull(in.getNextEntry());
+        }
+    }
+
+    @ParameterizedTest
+    @ValueSource(ints = {0, 124, 150, 300})
+    void testPax1MapSizeAndDeclaredSizeArePreserved(final int emptyMapEntries) 
throws IOException {
+        final byte[] map = pax1Map(RECORD_SIZE, emptyMapEntries);
+        if (emptyMapEntries == 124) {
+            assertEquals(RECORD_SIZE, map.length, "Exercise a map ending 
exactly at the record boundary");
+        }
+        final int mapSize = (map.length + RECORD_SIZE - 1) / RECORD_SIZE * 
RECORD_SIZE;
+        final int storedSize = mapSize + RECORD_SIZE + 7;
+        final ByteArrayOutputStream out = new ByteArrayOutputStream();
+        appendSparseEntry(out, SparseFormat.PAX_1_0, "sparse.bin", 
RECORD_SIZE, 7, emptyMapEntries);
+        appendTail(out);
+        try (TarArchiveInputStream in = 
TarArchiveInputStream.builder().setByteArray(out.toByteArray()).get()) {
+            final TarArchiveEntry entry = in.getNextEntry();
+            assertEquals(storedSize, entry.getSize());
+            assertEquals(RECORD_SIZE + 2 * HOLE_SIZE, entry.getRealSize());
+            assertEquals(3 * RECORD_SIZE + mapSize, in.getBytesRead());
+            assertArrayEquals(expandedData(RECORD_SIZE), 
IOUtils.toByteArray(in));
+            assertEquals("tail.txt", in.getNextEntry().getName());
+            assertEquals(storedSize, entry.getSize());
+            assertArrayEquals(TAIL_DATA, IOUtils.toByteArray(in));
+            assertNull(in.getNextEntry());
+        }
+    }
+
+    @Test
+    void testRejectsPax1FragmentsExceedingRemainingSize() throws IOException {
+        final ByteArrayOutputStream out = new ByteArrayOutputStream();
+        appendPaxHeaders(out, pax1Headers("sparse.bin", 6));
+        out.write(header("sparse.bin", RECORD_SIZE + 3, 
TarConstants.LF_NORMAL));
+        appendPadded(out, 
"2\n0\n2\n4\n2\n".getBytes(StandardCharsets.US_ASCII));
+        appendPadded(out, new byte[4]);
+        appendTail(out);
+        final byte[] archive = out.toByteArray();
+        try (TarArchiveInputStream in = 
TarArchiveInputStream.builder().setByteArray(archive).get()) {
+            assertThrows(ArchiveException.class, in::getNextEntry);
+        }
+        assertThrows(ArchiveException.class, () -> {
+            try (TarFile ignored = 
TarFile.builder().setByteArray(archive).get()) {
+                // Construction must reject the map before any entry data is 
exposed.
+            }
+        });
+    }
+
+    @Test
+    void testRejectsSparseMapLargerThanPaxSize() throws IOException {
+        final ByteArrayOutputStream out = new ByteArrayOutputStream();
+        // The PAX size is smaller than the raw header's size, which bounds 
the map-reading stream.
+        appendPaxHeaders(out, pax1Headers("empty", 0) + paxRecord("size", 
"2"));
+        out.write(header("empty", RECORD_SIZE, TarConstants.LF_NORMAL));
+        appendPadded(out, "0\n".getBytes(StandardCharsets.US_ASCII));
+        appendTail(out);
+        try (TarArchiveInputStream in = 
TarArchiveInputStream.builder().setByteArray(out.toByteArray()).get()) {
+            assertThrows(ArchiveException.class, in::getNextEntry);
+        }
+    }
+
+    @Test
+    void testShortReadsWithoutUnderlyingSkip() throws IOException {
+        final byte[] archive = archive(SparseFormat.PAX_1_0, RECORD_SIZE, 
RECORD_SIZE);
+        try (InputStream raw = new ByteArrayInputStream(archive) {
+            @Override
+            public synchronized int read(final byte[] bytes, final int offset, 
final int length) {
+                return super.read(bytes, offset, Math.min(length, 1));
+            }
+
+            @Override
+            public synchronized long skip(final long count) {
+                throw new AssertionError("Sparse entry skipping must read and 
verify the physical bytes");
+            }
+        }; TarArchiveInputStream in = 
TarArchiveInputStream.builder().setInputStream(raw).get()) {
+            assertEquals("sparse.bin", in.getNextEntry().getName());
+            assertEquals("tail.txt", in.getNextEntry().getName());
+            assertEquals(archive.length - 3 * RECORD_SIZE, in.getBytesRead());
+            assertArrayEquals(TAIL_DATA, IOUtils.toByteArray(in));
+            assertNull(in.getNextEntry());
+        }
+    }
+
+    @ParameterizedTest
+    @MethodSource("sparseBoundaries")
+    void testSparseEntryBoundaries(final SparseFormat format, final ReadMode 
mode, final int dataSize, final int slackSize) throws IOException {
+        final byte[] archive = archive(format, dataSize, slackSize);
+        final byte[] expected = expandedData(dataSize);
+        try (TarFile file = TarFile.builder().setByteArray(archive).get();
+                TarArchiveInputStream in = 
TarArchiveInputStream.builder().setByteArray(archive).get()) {
+            assertEquals(2, file.getEntries().size());
+            final TarArchiveEntry entry = in.getNextEntry();
+            assertNotNull(entry);
+            assertEquals("sparse.bin", entry.getName());
+            assertTrue(entry.isSparse());
+            assertEquals(dataSize + slackSize + (format == 
SparseFormat.PAX_1_0 ? RECORD_SIZE : 0), entry.getSize());
+            assertEquals(expected.length, entry.getRealSize());
+            try (InputStream contents = 
file.getInputStream(file.getEntries().get(0))) {
+                assertArrayEquals(expected, IOUtils.toByteArray(contents));
+            }
+            consumeEntry(in, mode, expected);
+            assertEquals("tail.txt", in.getNextEntry().getName());
+            assertEquals(archive.length - 3 * RECORD_SIZE, in.getBytesRead());
+            assertArrayEquals(TAIL_DATA, IOUtils.toByteArray(in));
+            assertNull(in.getNextEntry());
+            assertEquals(archive.length, in.getBytesRead());
+        }
+    }
+
+    @ParameterizedTest
+    @EnumSource(SparseFormat.class)
+    void testTruncatedFragment(final SparseFormat format) throws IOException {
+        final byte[] complete = archive(format, RECORD_SIZE, RECORD_SIZE);
+        final byte[] truncated = Arrays.copyOf(complete, complete.length - 5 * 
RECORD_SIZE - 1);
+        try (TarArchiveInputStream in = 
TarArchiveInputStream.builder().setByteArray(truncated).get()) {
+            in.getNextEntry();
+            assertThrows(EOFException.class, in::getNextEntry);
+        }
+    }
+
+    @ParameterizedTest
+    @EnumSource(SparseFormat.class)
+    void testTruncatedPaddingAfterSparseData(final SparseFormat format) throws 
IOException {
+        final byte[] complete = archive(format, 5, 7);
+        final byte[] truncated = Arrays.copyOf(complete, complete.length - 4 * 
RECORD_SIZE - 1);
+        try (TarArchiveInputStream in = 
TarArchiveInputStream.builder().setByteArray(truncated).get()) {
+            in.getNextEntry();
+            final EOFException exception = assertThrows(EOFException.class, 
in::getNextEntry);
+            assertTrue(exception.getMessage().contains("record padding"));
+            assertEquals(truncated.length, in.getBytesRead());
+        }
+    }
+
+    @ParameterizedTest
+    @MethodSource("formatsAndReadModes")
+    void testTruncatedSparseLeftover(final SparseFormat format, final ReadMode 
mode) throws IOException {
+        final byte[] complete = archive(format, RECORD_SIZE, RECORD_SIZE);
+        final byte[] truncated = Arrays.copyOf(complete, complete.length - 4 * 
RECORD_SIZE - 500);
+        try (TarArchiveInputStream in = 
TarArchiveInputStream.builder().setByteArray(truncated).get()) {
+            in.getNextEntry();
+            consumeEntry(in, mode, expandedData(RECORD_SIZE));
+            final EOFException exception = assertThrows(EOFException.class, 
in::getNextEntry);
+            assertTrue(exception.getMessage().contains("trailing sparse-entry 
bytes"));
+            assertEquals(truncated.length, in.getBytesRead());
+        }
+    }
+
+    private static void updateChecksum(final byte[] header) throws 
ArchiveException {
+        Arrays.fill(header, TarConstants.CHKSUM_OFFSET, 
TarConstants.CHKSUM_OFFSET + TarConstants.CHKSUMLEN, (byte) ' ');
+        TarUtils.formatCheckSumOctalBytes(TarUtils.computeCheckSum(header), 
header, TarConstants.CHKSUM_OFFSET, TarConstants.CHKSUMLEN);
+    }
+}

Reply via email to