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 bbd87321b Fix repeated reads and duplicate names for sparse TAR
entries (f015) (#872)
bbd87321b is described below
commit bbd87321b351c43c599c5acfaddf71eecc7ef6cd
Author: Gary Gregory <[email protected]>
AuthorDate: Fri Dec 4 16:32:34 2026 -0500
Fix repeated reads and duplicate names for sparse TAR entries (f015) (#872)
Build fresh fragment streams from each TarFile entry instead of
caching streams by name. Preserve eager validation and document
independent stream positions.
Add 91 regression cases covering sparse formats, repeated and
interleaved reads, duplicate names, and malformed sparse maps.
---
src/changes/changes.xml | 1 +
.../commons/compress/archivers/tar/TarFile.java | 45 +--
.../compress/archivers/tar/TarFileSparseTest.java | 380 +++++++++++++++++++++
3 files changed, 406 insertions(+), 20 deletions(-)
diff --git a/src/changes/changes.xml b/src/changes/changes.xml
index e9221c14b..6e1166530 100644
--- a/src/changes/changes.xml
+++ b/src/changes/changes.xml
@@ -121,6 +121,7 @@ The <action> type attribute can be add,update,fix,remove.
<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" due-to="Claude Security, Gary
Gregory">[TAR] Account for sparse maps and unreferenced stored bytes when
advancing TarArchiveInputStream entries, preserving declared entry sizes and
detecting truncated sparse payloads (f014).</action>
+ <action type="fix" dev="ggregory" due-to="Claude Security, Gary
Gregory">[TAR] Return independent streams for sparse TarFile entries,
supporting repeated reads and entries with duplicate names.</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/TarFile.java
b/src/main/java/org/apache/commons/compress/archivers/tar/TarFile.java
index 487eeda2a..e35ae79b8 100644
--- a/src/main/java/org/apache/commons/compress/archivers/tar/TarFile.java
+++ b/src/main/java/org/apache/commons/compress/archivers/tar/TarFile.java
@@ -173,8 +173,6 @@ public static Builder builder() {
*/
private final Map<String, String> globalPaxHeaders = new HashMap<>();
- private final Map<String, List<InputStream>> sparseInputStreams = new
HashMap<>();
-
private final int maxEntryNameLength;
private final long maxPaxHeaderSize;
@@ -347,15 +345,20 @@ public TarFile(final SeekableByteChannel archive, final
int blockSize, final int
}
/**
- * Build the input streams consisting of all-zero input streams and
non-zero input streams. When reading from the non-zero input streams, the data
is
- * actually read from the original input stream. The size of each input
stream is introduced by the sparse headers.
+ * Builds fresh fragment streams for a sparse entry's logical content.
+ *
+ * <p>
+ * Data fragments read from the archive channel, while holes supply zero
bytes. Empty fragments are omitted. Each call creates independent stream
+ * positions using the supplied entry's sparse headers and data offset,
allowing repeated reads and entries with duplicate names.
+ * </p>
*
- * @implNote Some all-zero input streams and non-zero input streams have
the size of 0. We DO NOT store the 0 size input streams because they are
- * meaningless.
+ * @param entry the sparse entry to read.
+ * @return the fragment streams in logical order.
+ * @throws IOException if the sparse headers are invalid.
*/
- private void buildSparseInputStreams() throws IOException {
+ private List<InputStream> buildSparseInputStreams(final TarArchiveEntry
entry) throws IOException {
final List<InputStream> streams = new ArrayList<>();
- final List<TarArchiveStructSparse> sparseHeaders =
currEntry.getOrderedSparseHeaders();
+ final List<TarArchiveStructSparse> sparseHeaders =
entry.getOrderedSparseHeaders();
// 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
@@ -376,10 +379,10 @@ private void buildSparseInputStreams() throws IOException
{
dataBytes = ArchiveException.addExact(dataBytes,
sparseHeader.getNumbytes());
// the non-hole blocks map onto real bytes of the archive, so
their total size must not
// exceed the entry's stored size, otherwise this entry would
reach into following entries
- if (dataBytes > currEntry.getSize()) {
- throw new ArchiveException("Corrupted TAR archive. Sparse
blocks for '%s' are larger than the entry size.", currEntry.getName());
+ if (dataBytes > entry.getSize()) {
+ throw new ArchiveException("Corrupted TAR archive. Sparse
blocks for '%s' are larger than the entry size.", entry.getName());
}
- final long start = currEntry.getDataOffset() +
sparseHeader.getOffset() - numberOfZeroBytesInSparseEntry;
+ final long start = entry.getDataOffset() +
sparseHeader.getOffset() - numberOfZeroBytesInSparseEntry;
if (start + sparseHeader.getNumbytes() < start) {
// possible integer overflow
throw new ArchiveException("Unreadable TAR archive, sparse
block offset or length too big");
@@ -388,7 +391,7 @@ private void buildSparseInputStreams() throws IOException {
}
offset = sparseHeader.getOffset() + sparseHeader.getNumbytes();
}
- sparseInputStreams.put(currEntry.getName(), streams);
+ return streams;
}
@Override
@@ -419,19 +422,22 @@ public List<TarArchiveEntry> getEntries() {
}
/**
- * Gets the input stream for the provided Tar Archive Entry.
+ * Gets a new input stream for the provided TAR archive entry.
+ *
+ * <p>
+ * Each stream has its own position within the entry. The caller is
responsible for closing the returned stream, which does not close this archive.
+ * </p>
*
* @param entry Entry to get the input stream from.
- * @return Input stream of the provided entry.
+ * @return A new input stream positioned at the beginning of the provided
entry.
* @throws IOException Corrupted TAR archive. Can't read entry.
*/
@Override
public InputStream getInputStream(final TarArchiveEntry entry) throws
IOException {
try {
- // Sparse entries are composed of multiple fragments: wrap them in
a SequenceInputStream
+ // Sparse fragment streams must be created per call, using this
entry's metadata rather than its non-unique name.
if (entry.isSparse()) {
- final List<InputStream> streams =
sparseInputStreams.get(entry.getName());
- return new SequenceInputStream(streams != null ?
Collections.enumeration(streams) : Collections.emptyEnumeration());
+ return new
SequenceInputStream(Collections.enumeration(buildSparseInputStreams(entry)));
}
// Regular entries are bounded: wrap in BoundedTarEntryInputStream
to enforce size and detect premature EOF
return new BoundedTarEntryInputStream(entry.getDataOffset(),
entry.getSize(), archive);
@@ -505,9 +511,8 @@ private TarArchiveEntry getNextTarEntry() throws
IOException {
currEntry.setSize(currEntry.getSize() - sparseHeadersSize);
currEntry.setDataOffset(currEntry.getDataOffset() +
sparseHeadersSize);
}
- // sparse headers are all done reading, we need to build
- // sparse input streams using these sparse headers
- buildSparseInputStreams();
+ // Validate eagerly; getInputStream builds fresh fragment streams
for each call.
+ buildSparseInputStreams(currEntry);
}
// Ensure directory names end with a slash
if (currEntry.isDirectory() && !currEntry.getName().endsWith("/")) {
diff --git
a/src/test/java/org/apache/commons/compress/archivers/tar/TarFileSparseTest.java
b/src/test/java/org/apache/commons/compress/archivers/tar/TarFileSparseTest.java
new file mode 100644
index 000000000..12a9d3e66
--- /dev/null
+++
b/src/test/java/org/apache/commons/compress/archivers/tar/TarFileSparseTest.java
@@ -0,0 +1,380 @@
+/*
+ * 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.assertNotSame;
+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.ByteArrayOutputStream;
+import java.io.IOException;
+import java.io.InputStream;
+import java.nio.charset.StandardCharsets;
+import java.nio.file.Files;
+import java.util.Arrays;
+import java.util.List;
+import java.util.stream.Stream;
+
+import org.apache.commons.compress.AbstractTest;
+import org.apache.commons.compress.archivers.ArchiveException;
+import org.apache.commons.compress.archivers.examples.Expander;
+import org.apache.commons.io.IOUtils;
+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 independent access to sparse TAR entries. */
+class TarFileSparseTest extends AbstractTest {
+
+ /** Sparse formats with maps in PAX records, entry headers, or entry data.
*/
+ 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 String ENTRY_NAME = "sparse.bin";
+ private static final long[][] FIRST_MAP = {{3, 2}, {8, 3}, {14, 0}};
+ private static final byte[] FIRST_DATA = {1, 2, 3, 4, 5};
+ private static final byte[] FIRST_CONTENT = {0, 0, 0, 1, 2, 0, 0, 0, 3, 4,
5, 0, 0, 0};
+ private static final long[][] SECOND_MAP = {{1, 3}, {10, 3}, {17, 0}};
+ private static final byte[] SECOND_DATA = {6, 7, 8, 9, 10, 11};
+ private static final byte[] SECOND_CONTENT = {0, 6, 7, 8, 0, 0, 0, 0, 0,
0, 9, 10, 11, 0, 0, 0, 0};
+
+ private static void appendPadded(final ByteArrayOutputStream out, final
byte[] data) throws IOException {
+ out.write(data);
+ out.write(new byte[(RECORD_SIZE - data.length % RECORD_SIZE) %
RECORD_SIZE]);
+ }
+
+ private static void appendSparseEntry(final ByteArrayOutputStream out,
final SparseFormat format, final int realSize, final long[][] map,
+ final byte[] data) throws IOException {
+ final ByteArrayOutputStream body = new ByteArrayOutputStream();
+ if (format == SparseFormat.PAX_1_0) {
+ final StringBuilder sparseMap = new
StringBuilder().append(map.length).append('\n');
+ for (final long[] block : map) {
+
sparseMap.append(block[0]).append('\n').append(block[1]).append('\n');
+ }
+ appendPadded(body,
sparseMap.toString().getBytes(StandardCharsets.US_ASCII));
+ }
+ body.write(data);
+ final boolean oldGnu = format == SparseFormat.OLD_GNU || format ==
SparseFormat.OLD_GNU_EXTENDED;
+ final byte[] entryHeader = header(ENTRY_NAME, body.size(), oldGnu ?
TarConstants.LF_GNUTYPE_SPARSE : TarConstants.LF_NORMAL);
+ final byte[] extension = new byte[RECORD_SIZE];
+ if (oldGnu) {
+ // Encode an empty pair so even an empty extension is
distinguishable from an EOF record.
+ sparsePair(extension, 0, new long[2]);
+ 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 386, an extension
flag at 482, and the real size at 483.
+ for (int i = 0; i < map.length; i++) {
+ if (format == SparseFormat.OLD_GNU_EXTENDED && i > 0) {
+ sparsePair(extension, (i - 1) * 24, map[i]);
+ } else {
+ sparsePair(entryHeader, 386 + i * 24, map[i]);
+ }
+ }
+ entryHeader[482] = (byte) (format == SparseFormat.OLD_GNU_EXTENDED
? 1 : 0);
+ TarUtils.formatLongOctalBytes(realSize, entryHeader, 483,
TarConstants.REALSIZELEN_GNU);
+ Arrays.fill(entryHeader, TarConstants.CHKSUM_OFFSET,
TarConstants.CHKSUM_OFFSET + TarConstants.CHKSUMLEN, (byte) ' ');
+
TarUtils.formatCheckSumOctalBytes(TarUtils.computeCheckSum(entryHeader),
entryHeader, TarConstants.CHKSUM_OFFSET, TarConstants.CHKSUMLEN);
+ } else {
+ final StringBuilder pax = new StringBuilder();
+ if (format == SparseFormat.PAX_1_0) {
+ pax.append(paxRecord("GNU.sparse.major",
"1")).append(paxRecord("GNU.sparse.minor", "0"))
+ .append(paxRecord("GNU.sparse.name",
ENTRY_NAME)).append(paxRecord("GNU.sparse.realsize",
Integer.toString(realSize)));
+ } else {
+ pax.append(paxRecord("GNU.sparse.size",
Integer.toString(realSize)));
+ if (format == SparseFormat.PAX_0_1) {
+ final StringBuilder sparseMap = new StringBuilder();
+ for (final long[] block : map) {
+ if (sparseMap.length() > 0) {
+ sparseMap.append(',');
+ }
+
sparseMap.append(block[0]).append(',').append(block[1]);
+ }
+ if (map.length > 0) {
+ pax.append(paxRecord("GNU.sparse.map",
sparseMap.toString()));
+ }
+ } else {
+ for (final long[] block : map) {
+ pax.append(paxRecord("GNU.sparse.offset",
Long.toString(block[0])))
+ .append(paxRecord("GNU.sparse.numbytes",
Long.toString(block[1])));
+ }
+ }
+ }
+ final byte[] paxData =
pax.toString().getBytes(StandardCharsets.US_ASCII);
+ out.write(header("PaxHeaders/sparse", paxData.length,
TarConstants.LF_PAX_EXTENDED_HEADER_LC));
+ appendPadded(out, paxData);
+ }
+ out.write(entryHeader);
+ if (format == SparseFormat.OLD_GNU_EXTENDED) {
+ out.write(extension);
+ }
+ appendPadded(out, body.toByteArray());
+ }
+
+ private static byte[] archive(final SparseFormat format, final boolean
duplicate) throws IOException {
+ final ByteArrayOutputStream out = new ByteArrayOutputStream();
+ appendSparseEntry(out, format, FIRST_CONTENT.length, FIRST_MAP,
FIRST_DATA);
+ if (duplicate) {
+ appendSparseEntry(out, format, SECOND_CONTENT.length, SECOND_MAP,
SECOND_DATA);
+ }
+ return finish(out);
+ }
+
+ private static byte[] finish(final ByteArrayOutputStream out) throws
IOException {
+ out.write(new byte[2 * RECORD_SIZE]);
+ return out.toByteArray();
+ }
+
+ private static Stream<Arguments> formatsAndReadOffsets() {
+ return Arrays.stream(SparseFormat.values()).flatMap(format ->
Stream.of(0, 1, 4, 9, FIRST_CONTENT.length).map(offset -> Arguments.of(format,
offset)));
+ }
+
+ private static Stream<Arguments> formatsAndReadOrders() {
+ return Arrays.stream(SparseFormat.values()).flatMap(format ->
Stream.of(false, true).map(reverse -> Arguments.of(format, reverse)));
+ }
+
+ 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 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 byte[] read(final TarFile file, final TarArchiveEntry
entry) throws IOException {
+ try (InputStream in = file.getInputStream(entry)) {
+ return IOUtils.toByteArray(in);
+ }
+ }
+
+ private static void sparsePair(final byte[] header, final int offset,
final long[] block) throws ArchiveException {
+ TarUtils.formatLongOctalBytes(block[0], header, offset,
TarConstants.SPARSE_OFFSET_LEN);
+ TarUtils.formatLongOctalBytes(block[1], header, offset +
TarConstants.SPARSE_OFFSET_LEN, TarConstants.SPARSE_NUMBYTES_LEN);
+ }
+
+ @ParameterizedTest
+ @EnumSource(SparseFormat.class)
+ void testAllHoles(final SparseFormat format) throws IOException {
+ final ByteArrayOutputStream out = new ByteArrayOutputStream();
+ appendSparseEntry(out, format, 12, new long[][] {{12, 0}}, new
byte[0]);
+ try (TarFile file = TarFile.builder().setByteArray(finish(out)).get())
{
+ final TarArchiveEntry entry = file.entries().get(0);
+ assertArrayEquals(new byte[12], read(file, entry));
+ assertArrayEquals(new byte[12], read(file, entry));
+ }
+ }
+
+ @ParameterizedTest
+ @EnumSource(SparseFormat.class)
+ void testClosingOneStreamDoesNotAffectAnother(final SparseFormat format)
throws IOException {
+ try (TarFile file = TarFile.builder().setByteArray(archive(format,
false)).get()) {
+ final TarArchiveEntry entry = file.entries().get(0);
+ try (InputStream second = file.getInputStream(entry)) {
+ try (InputStream first = file.getInputStream(entry)) {
+ assertEquals(FIRST_CONTENT[0], first.read());
+ }
+ assertArrayEquals(FIRST_CONTENT, IOUtils.toByteArray(second));
+ }
+ }
+ }
+
+ @ParameterizedTest
+ @EnumSource(SparseFormat.class)
+ void testDuplicateNamesAgreeWithStreamingReader(final SparseFormat format)
throws IOException {
+ try (TarArchiveInputStream in =
TarArchiveInputStream.builder().setByteArray(archive(format, true)).get()) {
+ assertEquals(ENTRY_NAME, in.getNextEntry().getName());
+ assertArrayEquals(FIRST_CONTENT, IOUtils.toByteArray(in));
+ assertEquals(ENTRY_NAME, in.getNextEntry().getName());
+ assertArrayEquals(SECOND_CONTENT, IOUtils.toByteArray(in));
+ assertNull(in.getNextEntry());
+ }
+ }
+
+ @ParameterizedTest
+ @MethodSource("formatsAndReadOrders")
+ void testDuplicateNamesInEitherReadOrder(final SparseFormat format, final
boolean reverse) throws IOException {
+ try (TarFile file = TarFile.builder().setByteArray(archive(format,
true)).get()) {
+ final List<? extends TarArchiveEntry> entries = file.entries();
+ assertEquals(2, entries.size());
+ assertNotSame(entries.get(0), entries.get(1));
+ // TarArchiveEntry.equals() compares names, so a HashMap keyed by
entries would also alias them.
+ assertEquals(entries.get(0), entries.get(1));
+ final byte[][] contents = {FIRST_CONTENT, SECOND_CONTENT};
+ for (int i = 0; i < 2; i++) {
+ final int index = reverse ? 1 - i : i;
+ assertArrayEquals(contents[index], read(file,
entries.get(index)));
+ }
+ assertArrayEquals(FIRST_CONTENT, read(file, entries.get(0)));
+ assertArrayEquals(SECOND_CONTENT, read(file, entries.get(1)));
+ }
+ }
+
+ @ParameterizedTest
+ @EnumSource(SparseFormat.class)
+ void testEmptySparseEntry(final SparseFormat format) throws IOException {
+ final ByteArrayOutputStream out = new ByteArrayOutputStream();
+ appendSparseEntry(out, format, 0, new long[0][], new byte[0]);
+ try (TarFile file = TarFile.builder().setByteArray(finish(out)).get())
{
+ final TarArchiveEntry entry = file.entries().get(0);
+ assertTrue(entry.isSparse());
+ assertArrayEquals(new byte[0], read(file, entry));
+ assertArrayEquals(new byte[0], read(file, entry));
+ }
+ }
+
+ @ParameterizedTest
+ @EnumSource(SparseFormat.class)
+ void testExpanderUsesLastDuplicateContent(final SparseFormat format)
throws IOException {
+ try (TarFile file = TarFile.builder().setByteArray(archive(format,
true)).get()) {
+ new Expander().expand(file, tempResultDir.toPath());
+ assertArrayEquals(SECOND_CONTENT,
Files.readAllBytes(tempResultDir.toPath().resolve(ENTRY_NAME)));
+ }
+ }
+
+ @ParameterizedTest
+ @EnumSource(SparseFormat.class)
+ void testInterleavedDuplicateEntries(final SparseFormat format) throws
IOException {
+ try (TarFile file = TarFile.builder().setByteArray(archive(format,
true)).get();
+ InputStream first = file.getInputStream(file.entries().get(0));
+ InputStream second =
file.getInputStream(file.entries().get(1))) {
+ for (int i = 0; i < SECOND_CONTENT.length; i++) {
+ assertEquals(i < FIRST_CONTENT.length ? FIRST_CONTENT[i] : -1,
first.read());
+ assertEquals(SECOND_CONTENT[i], second.read());
+ }
+ assertEquals(-1, second.read());
+ }
+ }
+
+ @ParameterizedTest
+ @EnumSource(SparseFormat.class)
+ void testInterleavedStreamsForSameEntry(final SparseFormat format) throws
IOException {
+ try (TarFile file = TarFile.builder().setByteArray(archive(format,
false)).get()) {
+ final TarArchiveEntry entry = file.entries().get(0);
+ try (InputStream first = file.getInputStream(entry); InputStream
second = file.getInputStream(entry)) {
+ for (final byte value : FIRST_CONTENT) {
+ assertEquals(value, first.read());
+ assertEquals(value, second.read());
+ }
+ assertEquals(-1, first.read());
+ assertEquals(-1, second.read());
+ }
+ }
+ }
+
+ @ParameterizedTest
+ @EnumSource(SparseFormat.class)
+ void testRegularAndSparseEntriesWithSameName(final SparseFormat format)
throws IOException {
+ final ByteArrayOutputStream out = new ByteArrayOutputStream();
+ out.write(header(ENTRY_NAME, FIRST_DATA.length,
TarConstants.LF_NORMAL));
+ appendPadded(out, FIRST_DATA);
+ appendSparseEntry(out, format, FIRST_CONTENT.length, FIRST_MAP,
FIRST_DATA);
+ out.write(header(ENTRY_NAME, SECOND_DATA.length,
TarConstants.LF_NORMAL));
+ appendPadded(out, SECOND_DATA);
+ try (TarFile file = TarFile.builder().setByteArray(finish(out)).get())
{
+ final List<? extends TarArchiveEntry> entries = file.entries();
+ assertEquals(3, entries.size());
+ assertArrayEquals(FIRST_DATA, read(file, entries.get(0)));
+ assertArrayEquals(FIRST_CONTENT, read(file, entries.get(1)));
+ assertArrayEquals(SECOND_DATA, read(file, entries.get(2)));
+ assertArrayEquals(FIRST_CONTENT, read(file, entries.get(1)));
+ }
+ }
+
+ @ParameterizedTest
+ @EnumSource(SparseFormat.class)
+ void testRejectsInvalidMapsDuringConstruction(final SparseFormat format)
throws IOException {
+ final long[][][] invalidMaps = {
+ {{3, 2}, {4, 3}}, // Overlapping blocks.
+ {{3, 6}}, // More physical data than the stored entry size.
+ {{13, 2}} // A block extends beyond the logical size.
+ };
+ for (final long[][] map : invalidMaps) {
+ final ByteArrayOutputStream out = new ByteArrayOutputStream();
+ appendSparseEntry(out, format, FIRST_CONTENT.length, map,
FIRST_DATA);
+ final byte[] bytes = finish(out);
+ assertThrows(ArchiveException.class, () -> {
+ try (TarFile ignored =
TarFile.builder().setByteArray(bytes).get()) {
+ // Construction must fail even when no entry stream is
requested.
+ }
+ }, Arrays.deepToString(map));
+ }
+ }
+
+ @ParameterizedTest
+ @EnumSource(SparseFormat.class)
+ void testRenamedEntries(final SparseFormat format) throws IOException {
+ try (TarFile file = TarFile.builder().setByteArray(archive(format,
true)).get()) {
+ final List<? extends TarArchiveEntry> entries = file.entries();
+ entries.get(0).setName("renamed.bin");
+ entries.get(1).setName("renamed.bin");
+ assertArrayEquals(FIRST_CONTENT, read(file, entries.get(0)));
+ assertArrayEquals(SECOND_CONTENT, read(file, entries.get(1)));
+ }
+ }
+
+ @ParameterizedTest
+ @MethodSource("formatsAndReadOffsets")
+ void testReopenAfterClosingStream(final SparseFormat format, final int
offset) throws IOException {
+ try (TarFile file = TarFile.builder().setByteArray(archive(format,
false)).get()) {
+ final TarArchiveEntry entry = file.entries().get(0);
+ try (InputStream first = file.getInputStream(entry)) {
+ final byte[] prefix = new byte[offset];
+ assertEquals(offset, IOUtils.read(first, prefix));
+ assertArrayEquals(Arrays.copyOf(FIRST_CONTENT, offset),
prefix);
+ }
+ assertArrayEquals(FIRST_CONTENT, read(file, entry));
+ assertArrayEquals(FIRST_CONTENT, read(file, entry));
+ }
+ }
+
+ @ParameterizedTest
+ @ValueSource(strings = {"pax_gnu_sparse.tar", "posix00_sparse.tar",
"posix01_sparse.tar", "posix10_sparse.tar", "oldgnu_sparse.tar",
"oldgnu_extended_sparse.tar"})
+ void testRepeatedReadsOfExistingFixtures(final String name) throws
IOException {
+ try (TarFile file = TarFile.builder().setPath(getPath(name)).get();
+ TarArchiveInputStream in =
TarArchiveInputStream.builder().setPath(getPath(name)).get()) {
+ for (final TarArchiveEntry entry : file.entries()) {
+ final TarArchiveEntry streamedEntry = in.getNextEntry();
+ assertNotNull(streamedEntry);
+ assertEquals(entry.getName(), streamedEntry.getName());
+ final byte[] expected = IOUtils.toByteArray(in);
+ assertEquals(entry.getRealSize(), expected.length);
+ assertArrayEquals(expected, read(file, entry), "First read of
" + entry.getName());
+ assertArrayEquals(expected, read(file, entry), "Second read of
" + entry.getName());
+ }
+ assertNull(in.getNextEntry());
+ }
+ }
+}