You are viewing a plain text version of this content. The canonical link for it is here.
Posted to commits@commons.apache.org by gg...@apache.org on 2022/03/18 18:59:00 UTC
[commons-compress] 01/03: Sort members.
This is an automated email from the ASF dual-hosted git repository.
ggregory pushed a commit to branch master
in repository https://gitbox.apache.org/repos/asf/commons-compress.git
commit 5ad1584bdf634011295e1656dbf337c00776f2b9
Author: Gary Gregory <ga...@gmail.com>
AuthorDate: Fri Mar 18 14:50:39 2022 -0400
Sort members.
---
.../compress/archivers/tar/TarArchiveEntry.java | 2314 ++++++++++----------
1 file changed, 1157 insertions(+), 1157 deletions(-)
diff --git a/src/main/java/org/apache/commons/compress/archivers/tar/TarArchiveEntry.java b/src/main/java/org/apache/commons/compress/archivers/tar/TarArchiveEntry.java
index 7f7bf3f..40eb4f2 100644
--- a/src/main/java/org/apache/commons/compress/archivers/tar/TarArchiveEntry.java
+++ b/src/main/java/org/apache/commons/compress/archivers/tar/TarArchiveEntry.java
@@ -200,6 +200,73 @@ public class TarArchiveEntry implements ArchiveEntry, TarConstants, EntryStreamO
*/
public static final long UNKNOWN = -1L;
+ /** Maximum length of a user's name in the tar file */
+ public static final int MAX_NAMELEN = 31;
+
+ /** Default permissions bits for directories */
+ public static final int DEFAULT_DIR_MODE = 040755;
+
+ /** Default permissions bits for files */
+ public static final int DEFAULT_FILE_MODE = 0100644;
+
+ /** Convert millis to seconds */
+ public static final int MILLIS_PER_SECOND = 1000;
+
+ private static FileTime fileTimeFromOptionalSeconds(long seconds) {
+ if (seconds <= 0) {
+ return null;
+ }
+ return FileTime.from(seconds, TimeUnit.SECONDS);
+ }
+
+ /**
+ * Strips Windows' drive letter as well as any leading slashes, turns path separators into forward slashes.
+ */
+ private static String normalizeFileName(String fileName, final boolean preserveAbsolutePath) {
+ if (!preserveAbsolutePath) {
+ final String property = System.getProperty("os.name");
+ if (property != null) {
+ final String osName = property.toLowerCase(Locale.ROOT);
+
+ // Strip off drive letters!
+ // REVIEW Would a better check be "(File.separator == '\')"?
+
+ if (osName.startsWith("windows")) {
+ if (fileName.length() > 2) {
+ final char ch1 = fileName.charAt(0);
+ final char ch2 = fileName.charAt(1);
+
+ if (ch2 == ':' && (ch1 >= 'a' && ch1 <= 'z' || ch1 >= 'A' && ch1 <= 'Z')) {
+ fileName = fileName.substring(2);
+ }
+ }
+ } else if (osName.contains("netware")) {
+ final int colon = fileName.indexOf(':');
+ if (colon != -1) {
+ fileName = fileName.substring(colon + 1);
+ }
+ }
+ }
+ }
+
+ fileName = fileName.replace(File.separatorChar, '/');
+
+ // No absolute pathnames
+ // Windows (and Posix?) paths can start with "\\NetworkDrive\",
+ // so we loop on starting /'s.
+ while (!preserveAbsolutePath && fileName.startsWith("/")) {
+ fileName = fileName.substring(1);
+ }
+ return fileName;
+ }
+
+ private static Instant parseInstantFromDecimalSeconds(final String value) {
+ final BigDecimal epochSeconds = new BigDecimal(value);
+ final long seconds = epochSeconds.longValue();
+ final long nanos = epochSeconds.remainder(BigDecimal.ONE).movePointRight(9).longValue();
+ return Instant.ofEpochSecond(seconds, nanos);
+ }
+
/** The entry's name. */
private String name = "";
@@ -223,7 +290,6 @@ public class TarArchiveEntry implements ArchiveEntry, TarConstants, EntryStreamO
* Corresponds to the POSIX {@code mtime} attribute.
*/
private FileTime mTime;
-
/**
* The entry's status change time.
* Corresponds to the POSIX {@code ctime} attribute.
@@ -259,6 +325,7 @@ public class TarArchiveEntry implements ArchiveEntry, TarConstants, EntryStreamO
/** The entry's magic tag. */
private String magic = MAGIC_POSIX;
+
/** The version of the format */
private String version = VERSION_POSIX;
@@ -302,18 +369,6 @@ public class TarArchiveEntry implements ArchiveEntry, TarConstants, EntryStreamO
/** Extra, user supplied pax headers */
private final Map<String,String> extraPaxHeaders = new HashMap<>();
- /** Maximum length of a user's name in the tar file */
- public static final int MAX_NAMELEN = 31;
-
- /** Default permissions bits for directories */
- public static final int DEFAULT_DIR_MODE = 040755;
-
- /** Default permissions bits for files */
- public static final int DEFAULT_FILE_MODE = 0100644;
-
- /** Convert millis to seconds */
- public static final int MILLIS_PER_SECOND = 1000;
-
private long dataOffset = EntryStreamOffsets.OFFSET_UNKNOWN;
/**
@@ -333,84 +388,64 @@ public class TarArchiveEntry implements ArchiveEntry, TarConstants, EntryStreamO
}
/**
- * Construct an entry with only a name. This allows the programmer
- * to construct the entry's header "by hand". File is set to null.
- *
- * <p>The entry's name will be the value of the {@code name}
- * argument with all file separators replaced by forward slashes
- * and leading slashes as well as Windows drive letters stripped.</p>
+ * Construct an entry from an archive's header bytes. File is set
+ * to null.
*
- * @param name the entry name
+ * @param headerBuf The header bytes from a tar archive entry.
+ * @throws IllegalArgumentException if any of the numeric fields have an invalid format
*/
- public TarArchiveEntry(final String name) {
- this(name, false);
+ public TarArchiveEntry(final byte[] headerBuf) {
+ this(false);
+ parseTarHeader(headerBuf);
}
/**
- * Construct an entry with only a name. This allows the programmer
- * to construct the entry's header "by hand". File is set to null.
- *
- * <p>The entry's name will be the value of the {@code name}
- * argument with all file separators replaced by forward slashes.
- * Leading slashes and Windows drive letters are stripped if
- * {@code preserveAbsolutePath} is {@code false}.</p>
- *
- * @param name the entry name
- * @param preserveAbsolutePath whether to allow leading slashes
- * or drive letters in the name.
+ * Construct an entry from an archive's header bytes. File is set
+ * to null.
*
- * @since 1.1
+ * @param headerBuf The header bytes from a tar archive entry.
+ * @param encoding encoding to use for file names
+ * @since 1.4
+ * @throws IllegalArgumentException if any of the numeric fields have an invalid format
+ * @throws IOException on error
*/
- public TarArchiveEntry(String name, final boolean preserveAbsolutePath) {
- this(preserveAbsolutePath);
-
- name = normalizeFileName(name, preserveAbsolutePath);
- final boolean isDir = name.endsWith("/");
-
- this.name = name;
- this.mode = isDir ? DEFAULT_DIR_MODE : DEFAULT_FILE_MODE;
- this.linkFlag = isDir ? LF_DIR : LF_NORMAL;
- this.mTime = FileTime.from(Instant.now());
- this.userName = "";
+ public TarArchiveEntry(final byte[] headerBuf, final ZipEncoding encoding)
+ throws IOException {
+ this(headerBuf, encoding, false);
}
/**
- * Construct an entry with a name and a link flag.
- *
- * <p>The entry's name will be the value of the {@code name}
- * argument with all file separators replaced by forward slashes
- * and leading slashes as well as Windows drive letters
- * stripped.</p>
+ * Construct an entry from an archive's header bytes. File is set
+ * to null.
*
- * @param name the entry name
- * @param linkFlag the entry link flag.
+ * @param headerBuf The header bytes from a tar archive entry.
+ * @param encoding encoding to use for file names
+ * @param lenient when set to true illegal values for group/userid, mode, device numbers and timestamp will be
+ * ignored and the fields set to {@link #UNKNOWN}. When set to false such illegal fields cause an exception instead.
+ * @since 1.19
+ * @throws IllegalArgumentException if any of the numeric fields have an invalid format
+ * @throws IOException on error
*/
- public TarArchiveEntry(final String name, final byte linkFlag) {
- this(name, linkFlag, false);
+ public TarArchiveEntry(final byte[] headerBuf, final ZipEncoding encoding, final boolean lenient)
+ throws IOException {
+ this(Collections.emptyMap(), headerBuf, encoding, lenient);
}
/**
- * Construct an entry with a name and a link flag.
- *
- * <p>The entry's name will be the value of the {@code name}
- * argument with all file separators replaced by forward slashes.
- * Leading slashes and Windows drive letters are stripped if
- * {@code preserveAbsolutePath} is {@code false}.</p>
- *
- * @param name the entry name
- * @param linkFlag the entry link flag.
- * @param preserveAbsolutePath whether to allow leading slashes
- * or drive letters in the name.
- *
- * @since 1.5
+ * Construct an entry from an archive's header bytes for random access tar. File is set to null.
+ * @param headerBuf the header bytes from a tar archive entry.
+ * @param encoding encoding to use for file names.
+ * @param lenient when set to true illegal values for group/userid, mode, device numbers and timestamp will be
+ * ignored and the fields set to {@link #UNKNOWN}. When set to false such illegal fields cause an exception instead.
+ * @param dataOffset position of the entry data in the random access file.
+ * @since 1.21
+ * @throws IllegalArgumentException if any of the numeric fields have an invalid format.
+ * @throws IOException on error.
*/
- public TarArchiveEntry(final String name, final byte linkFlag, final boolean preserveAbsolutePath) {
- this(name, preserveAbsolutePath);
- this.linkFlag = linkFlag;
- if (linkFlag == LF_GNUTYPE_LONGNAME) {
- magic = MAGIC_GNU;
- version = VERSION_GNU_SPACE;
- }
+ public TarArchiveEntry(final byte[] headerBuf, final ZipEncoding encoding, final boolean lenient,
+ final long dataOffset) throws IOException {
+ this(headerBuf, encoding, lenient);
+ setDataOffset(dataOffset);
}
/**
@@ -438,25 +473,6 @@ public class TarArchiveEntry implements ArchiveEntry, TarConstants, EntryStreamO
/**
* Construct an entry for a file. File is set to file, and the
* header is constructed from information from the file.
- * The name is set from the normalized file path.
- *
- * <p>The entry's name will be the value of the {@code file}'s
- * path with all file separators replaced by forward slashes and
- * leading slashes as well as Windows drive letters stripped. The
- * name will end in a slash if the {@code file} represents a
- * directory.</p>
- *
- * @param file The file that the entry represents.
- * @throws IOException if an I/O error occurs
- * @since 1.21
- */
- public TarArchiveEntry(final Path file) throws IOException {
- this(file, file.toString());
- }
-
- /**
- * Construct an entry for a file. File is set to file, and the
- * header is constructed from information from the file.
*
* <p>The entry's name will be the value of the {@code fileName}
* argument with all file separators replaced by forward slashes
@@ -499,24 +515,79 @@ public class TarArchiveEntry implements ArchiveEntry, TarConstants, EntryStreamO
}
/**
+ * Construct an entry from an archive's header bytes. File is set to null.
+ *
+ * @param globalPaxHeaders the parsed global PAX headers, or null if this is the first one.
+ * @param headerBuf The header bytes from a tar archive entry.
+ * @param encoding encoding to use for file names
+ * @param lenient when set to true illegal values for group/userid, mode, device numbers and timestamp will be
+ * ignored and the fields set to {@link #UNKNOWN}. When set to false such illegal fields cause an exception instead.
+ * @since 1.22
+ * @throws IllegalArgumentException if any of the numeric fields have an invalid format
+ * @throws IOException on error
+ */
+ public TarArchiveEntry(final Map<String, String> globalPaxHeaders, final byte[] headerBuf,
+ final ZipEncoding encoding, final boolean lenient) throws IOException {
+ this(false);
+ parseTarHeader(globalPaxHeaders, headerBuf, encoding, false, lenient);
+ }
+
+ /**
+ * Construct an entry from an archive's header bytes for random access tar. File is set to null.
+ * @param globalPaxHeaders the parsed global PAX headers, or null if this is the first one.
+ * @param headerBuf the header bytes from a tar archive entry.
+ * @param encoding encoding to use for file names.
+ * @param lenient when set to true illegal values for group/userid, mode, device numbers and timestamp will be
+ * ignored and the fields set to {@link #UNKNOWN}. When set to false such illegal fields cause an exception instead.
+ * @param dataOffset position of the entry data in the random access file.
+ * @since 1.22
+ * @throws IllegalArgumentException if any of the numeric fields have an invalid format.
+ * @throws IOException on error.
+ */
+ public TarArchiveEntry(final Map<String, String> globalPaxHeaders, final byte[] headerBuf,
+ final ZipEncoding encoding, final boolean lenient, final long dataOffset) throws IOException {
+ this(globalPaxHeaders,headerBuf, encoding, lenient);
+ setDataOffset(dataOffset);
+ }
+
+ /**
* Construct an entry for a file. File is set to file, and the
* header is constructed from information from the file.
+ * The name is set from the normalized file path.
*
- * <p>The entry's name will be the value of the {@code fileName}
- * argument with all file separators replaced by forward slashes
- * and leading slashes as well as Windows drive letters stripped.
- * The name will end in a slash if the {@code file} represents a
+ * <p>The entry's name will be the value of the {@code file}'s
+ * path with all file separators replaced by forward slashes and
+ * leading slashes as well as Windows drive letters stripped. The
+ * name will end in a slash if the {@code file} represents a
* directory.</p>
*
- * @param file The file that the entry represents.
- * @param fileName the name to be used for the entry.
- * @param linkOptions options indicating how symbolic links are handled.
+ * @param file The file that the entry represents.
* @throws IOException if an I/O error occurs
* @since 1.21
*/
- public TarArchiveEntry(final Path file, final String fileName, final LinkOption... linkOptions) throws IOException {
- final String normalizedName = normalizeFileName(fileName, false);
- this.file = file;
+ public TarArchiveEntry(final Path file) throws IOException {
+ this(file, file.toString());
+ }
+
+ /**
+ * Construct an entry for a file. File is set to file, and the
+ * header is constructed from information from the file.
+ *
+ * <p>The entry's name will be the value of the {@code fileName}
+ * argument with all file separators replaced by forward slashes
+ * and leading slashes as well as Windows drive letters stripped.
+ * The name will end in a slash if the {@code file} represents a
+ * directory.</p>
+ *
+ * @param file The file that the entry represents.
+ * @param fileName the name to be used for the entry.
+ * @param linkOptions options indicating how symbolic links are handled.
+ * @throws IOException if an I/O error occurs
+ * @since 1.21
+ */
+ public TarArchiveEntry(final Path file, final String fileName, final LinkOption... linkOptions) throws IOException {
+ final String normalizedName = normalizeFileName(fileName, false);
+ this.file = file;
this.linkOptions = linkOptions == null ? IOUtils.EMPTY_LINK_OPTIONS : linkOptions;
readFileMode(file, normalizedName, linkOptions);
@@ -526,164 +597,108 @@ public class TarArchiveEntry implements ArchiveEntry, TarConstants, EntryStreamO
preserveAbsolutePath = false;
}
- private void readOsSpecificProperties(final Path file, final LinkOption... options) throws IOException {
- final Set<String> availableAttributeViews = file.getFileSystem().supportedFileAttributeViews();
- if (availableAttributeViews.contains("posix")) {
- final PosixFileAttributes posixFileAttributes = Files.readAttributes(file, PosixFileAttributes.class, options);
- setLastModifiedTime(posixFileAttributes.lastModifiedTime());
- setCreationTime(posixFileAttributes.creationTime());
- setLastAccessTime(posixFileAttributes.lastAccessTime());
- this.userName = posixFileAttributes.owner().getName();
- this.groupName = posixFileAttributes.group().getName();
- if (availableAttributeViews.contains("unix")) {
- this.userId = ((Number) Files.getAttribute(file, "unix:uid", options)).longValue();
- this.groupId = ((Number) Files.getAttribute(file, "unix:gid", options)).longValue();
- try {
- setStatusChangeTime((FileTime) Files.getAttribute(file, "unix:ctime", options));
- } catch (final IllegalArgumentException ex) { // NOSONAR
- // ctime is not supported
- }
- }
- } else if (availableAttributeViews.contains("dos")) {
- final DosFileAttributes dosFileAttributes = Files.readAttributes(file, DosFileAttributes.class, options);
- setLastModifiedTime(dosFileAttributes.lastModifiedTime());
- setCreationTime(dosFileAttributes.creationTime());
- setLastAccessTime(dosFileAttributes.lastAccessTime());
- this.userName = Files.getOwner(file, options).getName();
- } else {
- final BasicFileAttributes basicFileAttributes = Files.readAttributes(file, BasicFileAttributes.class, options);
- setLastModifiedTime(basicFileAttributes.lastModifiedTime());
- setCreationTime(basicFileAttributes.creationTime());
- setLastAccessTime(basicFileAttributes.lastAccessTime());
- this.userName = Files.getOwner(file, options).getName();
- }
- }
-
- private void readFileMode(final Path file, final String normalizedName, final LinkOption... options) throws IOException {
- if (Files.isDirectory(file, options)) {
- this.mode = DEFAULT_DIR_MODE;
- this.linkFlag = LF_DIR;
-
- final int nameLength = normalizedName.length();
- if (nameLength == 0 || normalizedName.charAt(nameLength - 1) != '/') {
- this.name = normalizedName + "/";
- } else {
- this.name = normalizedName;
- }
- } else {
- this.mode = DEFAULT_FILE_MODE;
- this.linkFlag = LF_NORMAL;
- this.name = normalizedName;
- this.size = Files.size(file);
- }
- }
-
/**
- * Construct an entry from an archive's header bytes. File is set
- * to null.
+ * Construct an entry with only a name. This allows the programmer
+ * to construct the entry's header "by hand". File is set to null.
*
- * @param headerBuf The header bytes from a tar archive entry.
- * @throws IllegalArgumentException if any of the numeric fields have an invalid format
- */
- public TarArchiveEntry(final byte[] headerBuf) {
- this(false);
- parseTarHeader(headerBuf);
- }
-
- /**
- * Construct an entry from an archive's header bytes. File is set
- * to null.
+ * <p>The entry's name will be the value of the {@code name}
+ * argument with all file separators replaced by forward slashes
+ * and leading slashes as well as Windows drive letters stripped.</p>
*
- * @param headerBuf The header bytes from a tar archive entry.
- * @param encoding encoding to use for file names
- * @since 1.4
- * @throws IllegalArgumentException if any of the numeric fields have an invalid format
- * @throws IOException on error
+ * @param name the entry name
*/
- public TarArchiveEntry(final byte[] headerBuf, final ZipEncoding encoding)
- throws IOException {
- this(headerBuf, encoding, false);
+ public TarArchiveEntry(final String name) {
+ this(name, false);
}
/**
- * Construct an entry from an archive's header bytes. File is set
- * to null.
+ * Construct an entry with only a name. This allows the programmer
+ * to construct the entry's header "by hand". File is set to null.
*
- * @param headerBuf The header bytes from a tar archive entry.
- * @param encoding encoding to use for file names
- * @param lenient when set to true illegal values for group/userid, mode, device numbers and timestamp will be
- * ignored and the fields set to {@link #UNKNOWN}. When set to false such illegal fields cause an exception instead.
- * @since 1.19
- * @throws IllegalArgumentException if any of the numeric fields have an invalid format
- * @throws IOException on error
+ * <p>The entry's name will be the value of the {@code name}
+ * argument with all file separators replaced by forward slashes.
+ * Leading slashes and Windows drive letters are stripped if
+ * {@code preserveAbsolutePath} is {@code false}.</p>
+ *
+ * @param name the entry name
+ * @param preserveAbsolutePath whether to allow leading slashes
+ * or drive letters in the name.
+ *
+ * @since 1.1
*/
- public TarArchiveEntry(final byte[] headerBuf, final ZipEncoding encoding, final boolean lenient)
- throws IOException {
- this(Collections.emptyMap(), headerBuf, encoding, lenient);
+ public TarArchiveEntry(String name, final boolean preserveAbsolutePath) {
+ this(preserveAbsolutePath);
+
+ name = normalizeFileName(name, preserveAbsolutePath);
+ final boolean isDir = name.endsWith("/");
+
+ this.name = name;
+ this.mode = isDir ? DEFAULT_DIR_MODE : DEFAULT_FILE_MODE;
+ this.linkFlag = isDir ? LF_DIR : LF_NORMAL;
+ this.mTime = FileTime.from(Instant.now());
+ this.userName = "";
}
/**
- * Construct an entry from an archive's header bytes. File is set to null.
+ * Construct an entry with a name and a link flag.
*
- * @param globalPaxHeaders the parsed global PAX headers, or null if this is the first one.
- * @param headerBuf The header bytes from a tar archive entry.
- * @param encoding encoding to use for file names
- * @param lenient when set to true illegal values for group/userid, mode, device numbers and timestamp will be
- * ignored and the fields set to {@link #UNKNOWN}. When set to false such illegal fields cause an exception instead.
- * @since 1.22
- * @throws IllegalArgumentException if any of the numeric fields have an invalid format
- * @throws IOException on error
+ * <p>The entry's name will be the value of the {@code name}
+ * argument with all file separators replaced by forward slashes
+ * and leading slashes as well as Windows drive letters
+ * stripped.</p>
+ *
+ * @param name the entry name
+ * @param linkFlag the entry link flag.
*/
- public TarArchiveEntry(final Map<String, String> globalPaxHeaders, final byte[] headerBuf,
- final ZipEncoding encoding, final boolean lenient) throws IOException {
- this(false);
- parseTarHeader(globalPaxHeaders, headerBuf, encoding, false, lenient);
+ public TarArchiveEntry(final String name, final byte linkFlag) {
+ this(name, linkFlag, false);
}
/**
- * Construct an entry from an archive's header bytes for random access tar. File is set to null.
- * @param headerBuf the header bytes from a tar archive entry.
- * @param encoding encoding to use for file names.
- * @param lenient when set to true illegal values for group/userid, mode, device numbers and timestamp will be
- * ignored and the fields set to {@link #UNKNOWN}. When set to false such illegal fields cause an exception instead.
- * @param dataOffset position of the entry data in the random access file.
- * @since 1.21
- * @throws IllegalArgumentException if any of the numeric fields have an invalid format.
- * @throws IOException on error.
+ * Construct an entry with a name and a link flag.
+ *
+ * <p>The entry's name will be the value of the {@code name}
+ * argument with all file separators replaced by forward slashes.
+ * Leading slashes and Windows drive letters are stripped if
+ * {@code preserveAbsolutePath} is {@code false}.</p>
+ *
+ * @param name the entry name
+ * @param linkFlag the entry link flag.
+ * @param preserveAbsolutePath whether to allow leading slashes
+ * or drive letters in the name.
+ *
+ * @since 1.5
*/
- public TarArchiveEntry(final byte[] headerBuf, final ZipEncoding encoding, final boolean lenient,
- final long dataOffset) throws IOException {
- this(headerBuf, encoding, lenient);
- setDataOffset(dataOffset);
+ public TarArchiveEntry(final String name, final byte linkFlag, final boolean preserveAbsolutePath) {
+ this(name, preserveAbsolutePath);
+ this.linkFlag = linkFlag;
+ if (linkFlag == LF_GNUTYPE_LONGNAME) {
+ magic = MAGIC_GNU;
+ version = VERSION_GNU_SPACE;
+ }
}
/**
- * Construct an entry from an archive's header bytes for random access tar. File is set to null.
- * @param globalPaxHeaders the parsed global PAX headers, or null if this is the first one.
- * @param headerBuf the header bytes from a tar archive entry.
- * @param encoding encoding to use for file names.
- * @param lenient when set to true illegal values for group/userid, mode, device numbers and timestamp will be
- * ignored and the fields set to {@link #UNKNOWN}. When set to false such illegal fields cause an exception instead.
- * @param dataOffset position of the entry data in the random access file.
- * @since 1.22
- * @throws IllegalArgumentException if any of the numeric fields have an invalid format.
- * @throws IOException on error.
+ * add a PAX header to this entry. If the header corresponds to an existing field in the entry,
+ * that field will be set; otherwise the header will be added to the extraPaxHeaders Map
+ * @param name The full name of the header to set.
+ * @param value value of header.
+ * @since 1.15
*/
- public TarArchiveEntry(final Map<String, String> globalPaxHeaders, final byte[] headerBuf,
- final ZipEncoding encoding, final boolean lenient, final long dataOffset) throws IOException {
- this(globalPaxHeaders,headerBuf, encoding, lenient);
- setDataOffset(dataOffset);
+ public void addPaxHeader(final String name, final String value) {
+ try {
+ processPaxHeader(name,value);
+ } catch (IOException ex) {
+ throw new IllegalArgumentException("Invalid input", ex);
+ }
}
/**
- * Determine if the two entries are equal. Equality is determined
- * by the header names being equal.
- *
- * @param it Entry to be checked for equality.
- * @return True if the entries are equal.
+ * clear all extra PAX headers.
+ * @since 1.15
*/
- public boolean equals(final TarArchiveEntry it) {
- return it != null && getName().equals(it.getName());
+ public void clearExtraPaxHeaders() {
+ extraPaxHeaders.clear();
}
/**
@@ -702,116 +717,181 @@ public class TarArchiveEntry implements ArchiveEntry, TarConstants, EntryStreamO
}
/**
- * Hashcodes are based on entry names.
+ * Determine if the two entries are equal. Equality is determined
+ * by the header names being equal.
*
- * @return the entry hashcode
+ * @param it Entry to be checked for equality.
+ * @return True if the entries are equal.
*/
- @Override
- public int hashCode() {
- return getName().hashCode();
+ public boolean equals(final TarArchiveEntry it) {
+ return it != null && getName().equals(it.getName());
}
/**
- * Determine if the given entry is a descendant of this entry.
- * Descendancy is determined by the name of the descendant
- * starting with this entry's name.
+ * Evaluate an entry's header format from a header buffer.
*
- * @param desc Entry to be checked as a descendent of this.
- * @return True if entry is a descendant of this.
+ * @param header The tar entry header buffer to evaluate the format for.
+ * @return format type
*/
- public boolean isDescendent(final TarArchiveEntry desc) {
- return desc.getName().startsWith(getName());
- }
-
- /**
- * Get this entry's name.
- *
- * <p>This method returns the raw name as it is stored inside of the archive.</p>
- *
- * @return This entry's name.
- */
- @Override
- public String getName() {
- return name;
+ private int evaluateType(final Map<String, String> globalPaxHeaders, final byte[] header) {
+ if (ArchiveUtils.matchAsciiBuffer(MAGIC_GNU, header, MAGIC_OFFSET, MAGICLEN)) {
+ return FORMAT_OLDGNU;
+ }
+ if (ArchiveUtils.matchAsciiBuffer(MAGIC_POSIX, header, MAGIC_OFFSET, MAGICLEN)) {
+ if (isXstar(globalPaxHeaders, header)) {
+ return FORMAT_XSTAR;
+ }
+ return FORMAT_POSIX;
+ }
+ return 0;
+ }
+
+ private int fill(final byte value, final int offset, final byte[] outbuf, final int length) {
+ for (int i = 0; i < length; i++) {
+ outbuf[offset + i] = value;
+ }
+ return offset + length;
+ }
+
+ private int fill(final int value, final int offset, final byte[] outbuf, final int length) {
+ return fill((byte) value, offset, outbuf, length);
+ }
+
+ void fillGNUSparse0xData(final Map<String, String> headers) {
+ paxGNUSparse = true;
+ realSize = Integer.parseInt(headers.get("GNU.sparse.size"));
+ if (headers.containsKey("GNU.sparse.name")) {
+ // version 0.1
+ name = headers.get("GNU.sparse.name");
+ }
+ }
+
+ void fillGNUSparse1xData(final Map<String, String> headers) throws IOException {
+ paxGNUSparse = true;
+ paxGNU1XSparse = true;
+ if (headers.containsKey("GNU.sparse.name")) {
+ name = headers.get("GNU.sparse.name");
+ }
+ if (headers.containsKey("GNU.sparse.realsize")) {
+ try {
+ realSize = Integer.parseInt(headers.get("GNU.sparse.realsize"));
+ } catch (NumberFormatException ex) {
+ throw new IOException("Corrupted TAR archive. GNU.sparse.realsize header for "
+ + name + " contains non-numeric value");
+ }
+ }
+ }
+
+ void fillStarSparseData(final Map<String, String> headers) throws IOException {
+ starSparse = true;
+ if (headers.containsKey("SCHILY.realsize")) {
+ try {
+ realSize = Long.parseLong(headers.get("SCHILY.realsize"));
+ } catch (NumberFormatException ex) {
+ throw new IOException("Corrupted TAR archive. SCHILY.realsize header for "
+ + name + " contains non-numeric value");
+ }
+ }
}
/**
- * Set this entry's name.
+ * Get this entry's creation time.
*
- * @param name This entry's new name.
+ * @since 1.22
+ * @return This entry's computed creation time.
*/
- public void setName(final String name) {
- this.name = normalizeFileName(name, this.preserveAbsolutePath);
+ public FileTime getCreationTime() {
+ return birthTime;
}
/**
- * Set the mode for this entry
- *
- * @param mode the mode for this entry
+ * {@inheritDoc}
+ * @since 1.21
*/
- public void setMode(final int mode) {
- this.mode = mode;
+ @Override
+ public long getDataOffset() {
+ return dataOffset;
}
/**
- * Get this entry's link name.
+ * Get this entry's major device number.
*
- * @return This entry's link name.
+ * @return This entry's major device number.
+ * @since 1.4
*/
- public String getLinkName() {
- return linkName;
+ public int getDevMajor() {
+ return devMajor;
}
/**
- * Set this entry's link name.
- *
- * @param link the link name to use.
+ * Get this entry's minor device number.
*
- * @since 1.1
+ * @return This entry's minor device number.
+ * @since 1.4
*/
- public void setLinkName(final String link) {
- this.linkName = link;
+ public int getDevMinor() {
+ return devMinor;
}
/**
- * Get this entry's user id.
+ * If this entry represents a file, and the file is a directory, return
+ * an array of TarEntries for this entry's children.
*
- * @return This entry's user id.
- * @deprecated use #getLongUserId instead as user ids can be
- * bigger than {@link Integer#MAX_VALUE}
+ * <p>This method is only useful for entries created from a {@code
+ * File} or {@code Path} but not for entries read from an archive.</p>
+ *
+ * @return An array of TarEntry's for this entry's children.
*/
- @Deprecated
- public int getUserId() {
- return (int) (userId & 0xffffffff);
+ public TarArchiveEntry[] getDirectoryEntries() {
+ if (file == null || !isDirectory()) {
+ return EMPTY_TAR_ARCHIVE_ENTRY_ARRAY;
+ }
+
+ final List<TarArchiveEntry> entries = new ArrayList<>();
+ try (DirectoryStream<Path> dirStream = Files.newDirectoryStream(file)) {
+ final Iterator<Path> iterator = dirStream.iterator();
+ while (iterator.hasNext()) {
+ final Path p = iterator.next();
+ entries.add(new TarArchiveEntry(p));
+ }
+ } catch (final IOException e) {
+ return EMPTY_TAR_ARCHIVE_ENTRY_ARRAY;
+ }
+ return entries.toArray(EMPTY_TAR_ARCHIVE_ENTRY_ARRAY);
}
/**
- * Set this entry's user id.
- *
- * @param userId This entry's new user id.
+ * get named extra PAX header
+ * @param name The full name of an extended PAX header to retrieve
+ * @return The value of the header, if any.
+ * @since 1.15
*/
- public void setUserId(final int userId) {
- setUserId((long) userId);
+ public String getExtraPaxHeader(final String name) {
+ return extraPaxHeaders.get(name);
}
/**
- * Get this entry's user id.
- *
- * @return This entry's user id.
- * @since 1.10
+ * get extra PAX Headers
+ * @return read-only map containing any extra PAX Headers
+ * @since 1.15
*/
- public long getLongUserId() {
- return userId;
+ public Map<String, String> getExtraPaxHeaders() {
+ return Collections.unmodifiableMap(extraPaxHeaders);
}
/**
- * Set this entry's user id.
+ * Get this entry's file.
*
- * @param userId This entry's new user id.
- * @since 1.10
+ * <p>This method is only useful for entries created from a {@code
+ * File} or {@code Path} but not for entries read from an archive.</p>
+ *
+ * @return this entry's file or null if the entry was not created from a file.
*/
- public void setUserId(final long userId) {
- this.userId = userId;
+ public File getFile() {
+ if (file == null) {
+ return null;
+ }
+ return file.toFile();
}
/**
@@ -827,165 +907,197 @@ public class TarArchiveEntry implements ArchiveEntry, TarConstants, EntryStreamO
}
/**
- * Set this entry's group id.
+ * Get this entry's group name.
*
- * @param groupId This entry's new group id.
+ * @return This entry's group name.
*/
- public void setGroupId(final int groupId) {
- setGroupId((long) groupId);
+ public String getGroupName() {
+ return groupName;
}
/**
- * Get this entry's group id.
+ * Get this entry's last access time.
*
- * @since 1.10
- * @return This entry's group id.
+ * @since 1.22
+ * @return This entry's last access time.
*/
- public long getLongGroupId() {
- return groupId;
+ public FileTime getLastAccessTime() {
+ return aTime;
}
/**
- * Set this entry's group id.
+ * Get this entry's modification time.
+ * This is equivalent to {@link TarArchiveEntry#getLastModifiedTime()}, but precision is truncated to milliseconds.
*
- * @since 1.10
- * @param groupId This entry's new group id.
+ * @return This entry's modification time.
+ * @see TarArchiveEntry#getLastModifiedTime()
*/
- public void setGroupId(final long groupId) {
- this.groupId = groupId;
+ @Override
+ public Date getLastModifiedDate() {
+ return getModTime();
}
/**
- * Get this entry's user name.
+ * Get this entry's modification time.
*
- * @return This entry's user name.
+ * @since 1.22
+ * @return This entry's modification time.
*/
- public String getUserName() {
- return userName;
+ public FileTime getLastModifiedTime() {
+ return mTime;
}
/**
- * Set this entry's user name.
+ * Get this entry's link name.
*
- * @param userName This entry's new user name.
+ * @return This entry's link name.
*/
- public void setUserName(final String userName) {
- this.userName = userName;
+ public String getLinkName() {
+ return linkName;
}
/**
- * Get this entry's group name.
+ * Get this entry's group id.
*
- * @return This entry's group name.
+ * @since 1.10
+ * @return This entry's group id.
*/
- public String getGroupName() {
- return groupName;
+ public long getLongGroupId() {
+ return groupId;
}
/**
- * Set this entry's group name.
+ * Get this entry's user id.
*
- * @param groupName This entry's new group name.
+ * @return This entry's user id.
+ * @since 1.10
*/
- public void setGroupName(final String groupName) {
- this.groupName = groupName;
+ public long getLongUserId() {
+ return userId;
}
/**
- * Convenience method to set this entry's group and user ids.
+ * Get this entry's mode.
*
- * @param userId This entry's new user id.
- * @param groupId This entry's new group id.
+ * @return This entry's mode.
*/
- public void setIds(final int userId, final int groupId) {
- setUserId(userId);
- setGroupId(groupId);
+ public int getMode() {
+ return mode;
}
/**
- * Convenience method to set this entry's group and user names.
+ * Get this entry's modification time.
+ * This is equivalent to {@link TarArchiveEntry#getLastModifiedTime()}, but precision is truncated to milliseconds.
*
- * @param userName This entry's new user name.
- * @param groupName This entry's new group name.
+ * @return This entry's modification time.
+ * @see TarArchiveEntry#getLastModifiedTime()
*/
- public void setNames(final String userName, final String groupName) {
- setUserName(userName);
- setGroupName(groupName);
+ public Date getModTime() {
+ return new Date(mTime.toMillis());
}
/**
- * Set this entry's modification time. The parameter passed
- * to this method is in "Java time".
+ * Get this entry's name.
*
- * @param time This entry's new modification time.
- * @see TarArchiveEntry#setLastModifiedTime(FileTime)
- */
- public void setModTime(final long time) {
- setLastModifiedTime(FileTime.fromMillis(time));
- }
-
- /**
- * Set this entry's modification time.
+ * <p>This method returns the raw name as it is stored inside of the archive.</p>
*
- * @param time This entry's new modification time.
- * @see TarArchiveEntry#setLastModifiedTime(FileTime)
+ * @return This entry's name.
*/
- public void setModTime(final Date time) {
- setLastModifiedTime(FileTime.fromMillis(time.getTime()));
+ @Override
+ public String getName() {
+ return name;
}
/**
- * Set this entry's modification time.
+ * Get this entry's sparse headers ordered by offset with all empty sparse sections at the start filtered out.
*
- * @param time This entry's new modification time.
+ * @return immutable list of this entry's sparse headers, never null
* @since 1.21
- * @see TarArchiveEntry#setLastModifiedTime(FileTime)
+ * @throws IOException if the list of sparse headers contains blocks that overlap
*/
- public void setModTime(final FileTime time) {
- setLastModifiedTime(time);
+ public List<TarArchiveStructSparse> getOrderedSparseHeaders() throws IOException {
+ if (sparseHeaders == null || sparseHeaders.isEmpty()) {
+ return Collections.emptyList();
+ }
+ final List<TarArchiveStructSparse> orderedAndFiltered = sparseHeaders.stream()
+ .filter(s -> s.getOffset() > 0 || s.getNumbytes() > 0)
+ .sorted(Comparator.comparingLong(TarArchiveStructSparse::getOffset))
+ .collect(Collectors.toList());
+
+ final int numberOfHeaders = orderedAndFiltered.size();
+ for (int i = 0; i < numberOfHeaders; i++) {
+ final TarArchiveStructSparse str = orderedAndFiltered.get(i);
+ if (i + 1 < numberOfHeaders
+ && str.getOffset() + str.getNumbytes() > orderedAndFiltered.get(i + 1).getOffset()) {
+ throw new IOException("Corrupted TAR archive. Sparse blocks for "
+ + getName() + " overlap each other.");
+ }
+ if (str.getOffset() + str.getNumbytes() < 0) {
+ // integer overflow?
+ throw new IOException("Unreadable TAR archive. Offset and numbytes for sparse block in "
+ + getName() + " too large.");
+ }
+ }
+ if (!orderedAndFiltered.isEmpty()) {
+ final TarArchiveStructSparse last = orderedAndFiltered.get(numberOfHeaders - 1);
+ if (last.getOffset() + last.getNumbytes() > getRealSize()) {
+ throw new IOException("Corrupted TAR archive. Sparse block extends beyond real size of the entry");
+ }
+ }
+
+ return orderedAndFiltered;
}
/**
- * Get this entry's modification time.
- * This is equivalent to {@link TarArchiveEntry#getLastModifiedTime()}, but precision is truncated to milliseconds.
+ * Get this entry's file.
*
- * @return This entry's modification time.
- * @see TarArchiveEntry#getLastModifiedTime()
+ * <p>This method is only useful for entries created from a {@code
+ * File} or {@code Path} but not for entries read from an archive.</p>
+ *
+ * @return this entry's file or null if the entry was not created from a file.
+ * @since 1.21
*/
- public Date getModTime() {
- return new Date(mTime.toMillis());
+ public Path getPath() {
+ return file;
}
/**
- * Get this entry's modification time.
- * This is equivalent to {@link TarArchiveEntry#getLastModifiedTime()}, but precision is truncated to milliseconds.
+ * Get this entry's real file size in case of a sparse file.
*
- * @return This entry's modification time.
- * @see TarArchiveEntry#getLastModifiedTime()
+ * <p>This is the size a file would take on disk if the entry was expanded.</p>
+ *
+ * <p>If the file is not a sparse file, return size instead of realSize.</p>
+ *
+ * @return This entry's real file size, if the file is not a sparse file, return size instead of realSize.
*/
- @Override
- public Date getLastModifiedDate() {
- return getModTime();
+ public long getRealSize() {
+ if (!isSparse()) {
+ return getSize();
+ }
+ return realSize;
}
/**
- * Get this entry's modification time.
+ * Get this entry's file size.
*
- * @since 1.22
- * @return This entry's modification time.
+ * <p>This is the size the entry's data uses inside of the archive. Usually this is the same as {@link
+ * #getRealSize}, but it doesn't take the "holes" into account when the entry represents a sparse file.
+ *
+ * @return This entry's file size.
*/
- public FileTime getLastModifiedTime() {
- return mTime;
+ @Override
+ public long getSize() {
+ return size;
}
/**
- * Set this entry's modification time.
+ * Get this entry's sparse headers
*
- * @param time This entry's new modification time.
- * @since 1.22
+ * @return This entry's sparse headers
+ * @since 1.20
*/
- public void setLastModifiedTime(final FileTime time) {
- mTime = Objects.requireNonNull(time, "Time must not be null");
+ public List<TarArchiveStructSparse> getSparseHeaders() {
+ return sparseHeaders;
}
/**
@@ -999,53 +1111,54 @@ public class TarArchiveEntry implements ArchiveEntry, TarConstants, EntryStreamO
}
/**
- * Set this entry's status change time.
+ * Get this entry's user id.
*
- * @param time This entry's new status change time.
- * @since 1.22
+ * @return This entry's user id.
+ * @deprecated use #getLongUserId instead as user ids can be
+ * bigger than {@link Integer#MAX_VALUE}
*/
- public void setStatusChangeTime(final FileTime time) {
- cTime = time;
+ @Deprecated
+ public int getUserId() {
+ return (int) (userId & 0xffffffff);
}
/**
- * Get this entry's last access time.
+ * Get this entry's user name.
*
- * @since 1.22
- * @return This entry's last access time.
+ * @return This entry's user name.
*/
- public FileTime getLastAccessTime() {
- return aTime;
+ public String getUserName() {
+ return userName;
}
/**
- * Set this entry's last access time.
+ * Hashcodes are based on entry names.
*
- * @param time This entry's new last access time.
- * @since 1.22
+ * @return the entry hashcode
*/
- public void setLastAccessTime(final FileTime time) {
- aTime = time;
+ @Override
+ public int hashCode() {
+ return getName().hashCode();
}
/**
- * Get this entry's creation time.
+ * Check if this is a block device entry.
*
- * @since 1.22
- * @return This entry's computed creation time.
+ * @since 1.2
+ * @return whether this is a block device
*/
- public FileTime getCreationTime() {
- return birthTime;
+ public boolean isBlockDevice() {
+ return linkFlag == LF_BLK;
}
/**
- * Set this entry's creation time.
+ * Check if this is a character device entry.
*
- * @param time This entry's new creation time.
- * @since 1.22
+ * @since 1.2
+ * @return whether this is a character device
*/
- public void setCreationTime(final FileTime time) {
- birthTime = time;
+ public boolean isCharacterDevice() {
+ return linkFlag == LF_CHR;
}
/**
@@ -1060,220 +1173,155 @@ public class TarArchiveEntry implements ArchiveEntry, TarConstants, EntryStreamO
}
/**
- * Get this entry's file.
+ * Determine if the given entry is a descendant of this entry.
+ * Descendancy is determined by the name of the descendant
+ * starting with this entry's name.
*
- * <p>This method is only useful for entries created from a {@code
- * File} or {@code Path} but not for entries read from an archive.</p>
+ * @param desc Entry to be checked as a descendent of this.
+ * @return True if entry is a descendant of this.
+ */
+ public boolean isDescendent(final TarArchiveEntry desc) {
+ return desc.getName().startsWith(getName());
+ }
+
+ /**
+ * Return whether or not this entry represents a directory.
*
- * @return this entry's file or null if the entry was not created from a file.
+ * @return True if this entry is a directory.
*/
- public File getFile() {
- if (file == null) {
- return null;
+ @Override
+ public boolean isDirectory() {
+ if (file != null) {
+ return Files.isDirectory(file, linkOptions);
}
- return file.toFile();
+
+ if (linkFlag == LF_DIR) {
+ return true;
+ }
+
+ return !isPaxHeader() && !isGlobalPaxHeader() && getName().endsWith("/");
}
/**
- * Get this entry's file.
- *
- * <p>This method is only useful for entries created from a {@code
- * File} or {@code Path} but not for entries read from an archive.</p>
+ * Indicates in case of an oldgnu sparse file if an extension
+ * sparse header follows.
*
- * @return this entry's file or null if the entry was not created from a file.
- * @since 1.21
+ * @return true if an extension oldgnu sparse header follows.
*/
- public Path getPath() {
- return file;
+ public boolean isExtended() {
+ return isExtended;
}
/**
- * Get this entry's mode.
+ * Check if this is a FIFO (pipe) entry.
*
- * @return This entry's mode.
+ * @since 1.2
+ * @return whether this is a FIFO entry
*/
- public int getMode() {
- return mode;
+ public boolean isFIFO() {
+ return linkFlag == LF_FIFO;
}
/**
- * Get this entry's file size.
- *
- * <p>This is the size the entry's data uses inside of the archive. Usually this is the same as {@link
- * #getRealSize}, but it doesn't take the "holes" into account when the entry represents a sparse file.
+ * Check if this is a "normal file"
*
- * @return This entry's file size.
+ * @since 1.2
+ * @return whether this is a "normal file"
*/
- @Override
- public long getSize() {
- return size;
+ public boolean isFile() {
+ if (file != null) {
+ return Files.isRegularFile(file, linkOptions);
+ }
+ if (linkFlag == LF_OLDNORM || linkFlag == LF_NORMAL) {
+ return true;
+ }
+ return !getName().endsWith("/");
}
/**
- * Set this entry's sparse headers
- * @param sparseHeaders The new sparse headers
- * @since 1.20
+ * Check if this is a Pax header.
+ *
+ * @return {@code true} if this is a Pax header.
+ *
+ * @since 1.1
*/
- public void setSparseHeaders(final List<TarArchiveStructSparse> sparseHeaders) {
- this.sparseHeaders = sparseHeaders;
+ public boolean isGlobalPaxHeader() {
+ return linkFlag == LF_PAX_GLOBAL_EXTENDED_HEADER;
}
/**
- * Get this entry's sparse headers
+ * Indicate if this entry is a GNU long linkname block
*
- * @return This entry's sparse headers
- * @since 1.20
- */
- public List<TarArchiveStructSparse> getSparseHeaders() {
- return sparseHeaders;
- }
-
- /**
- * Get this entry's sparse headers ordered by offset with all empty sparse sections at the start filtered out.
- *
- * @return immutable list of this entry's sparse headers, never null
- * @since 1.21
- * @throws IOException if the list of sparse headers contains blocks that overlap
- */
- public List<TarArchiveStructSparse> getOrderedSparseHeaders() throws IOException {
- if (sparseHeaders == null || sparseHeaders.isEmpty()) {
- return Collections.emptyList();
- }
- final List<TarArchiveStructSparse> orderedAndFiltered = sparseHeaders.stream()
- .filter(s -> s.getOffset() > 0 || s.getNumbytes() > 0)
- .sorted(Comparator.comparingLong(TarArchiveStructSparse::getOffset))
- .collect(Collectors.toList());
-
- final int numberOfHeaders = orderedAndFiltered.size();
- for (int i = 0; i < numberOfHeaders; i++) {
- final TarArchiveStructSparse str = orderedAndFiltered.get(i);
- if (i + 1 < numberOfHeaders
- && str.getOffset() + str.getNumbytes() > orderedAndFiltered.get(i + 1).getOffset()) {
- throw new IOException("Corrupted TAR archive. Sparse blocks for "
- + getName() + " overlap each other.");
- }
- if (str.getOffset() + str.getNumbytes() < 0) {
- // integer overflow?
- throw new IOException("Unreadable TAR archive. Offset and numbytes for sparse block in "
- + getName() + " too large.");
- }
- }
- if (!orderedAndFiltered.isEmpty()) {
- final TarArchiveStructSparse last = orderedAndFiltered.get(numberOfHeaders - 1);
- if (last.getOffset() + last.getNumbytes() > getRealSize()) {
- throw new IOException("Corrupted TAR archive. Sparse block extends beyond real size of the entry");
- }
- }
-
- return orderedAndFiltered;
- }
-
- /**
- * Get if this entry is a sparse file with 1.X PAX Format or not
- *
- * @return True if this entry is a sparse file with 1.X PAX Format
- * @since 1.20
- */
- public boolean isPaxGNU1XSparse() {
- return paxGNU1XSparse;
- }
-
- /**
- * Set this entry's file size.
- *
- * @param size This entry's new file size.
- * @throws IllegalArgumentException if the size is < 0.
- */
- public void setSize(final long size) {
- if (size < 0){
- throw new IllegalArgumentException("Size is out of range: "+size);
- }
- this.size = size;
- }
-
- /**
- * Get this entry's major device number.
- *
- * @return This entry's major device number.
- * @since 1.4
+ * @return true if this is a long name extension provided by GNU tar
*/
- public int getDevMajor() {
- return devMajor;
+ public boolean isGNULongLinkEntry() {
+ return linkFlag == LF_GNUTYPE_LONGLINK;
}
/**
- * Set this entry's major device number.
+ * Indicate if this entry is a GNU long name block
*
- * @param devNo This entry's major device number.
- * @throws IllegalArgumentException if the devNo is < 0.
- * @since 1.4
+ * @return true if this is a long name extension provided by GNU tar
*/
- public void setDevMajor(final int devNo) {
- if (devNo < 0){
- throw new IllegalArgumentException("Major device number is out of "
- + "range: " + devNo);
- }
- this.devMajor = devNo;
+ public boolean isGNULongNameEntry() {
+ return linkFlag == LF_GNUTYPE_LONGNAME;
}
/**
- * Get this entry's minor device number.
+ * Indicate if this entry is a GNU sparse block.
*
- * @return This entry's minor device number.
- * @since 1.4
+ * @return true if this is a sparse extension provided by GNU tar
*/
- public int getDevMinor() {
- return devMinor;
+ public boolean isGNUSparse() {
+ return isOldGNUSparse() || isPaxGNUSparse();
}
- /**
- * Set this entry's minor device number.
- *
- * @param devNo This entry's minor device number.
- * @throws IllegalArgumentException if the devNo is < 0.
- * @since 1.4
- */
- public void setDevMinor(final int devNo) {
- if (devNo < 0){
- throw new IllegalArgumentException("Minor device number is out of "
- + "range: " + devNo);
+ private boolean isInvalidPrefix(final byte[] header) {
+ // prefix[130] is is guaranteed to be '\0' with XSTAR/XUSTAR
+ if (header[XSTAR_PREFIX_OFFSET + 130] != 0) {
+ // except when typeflag is 'M'
+ if (header[LF_OFFSET] == LF_MULTIVOLUME) {
+ // We come only here if we try to read in a GNU/xstar/xustar multivolume archive starting past volume #0
+ // As of 1.22, commons-compress does not support multivolume tar archives.
+ // If/when it does, this should work as intended.
+ if ((header[XSTAR_MULTIVOLUME_OFFSET] & 0x80) == 0
+ && header[XSTAR_MULTIVOLUME_OFFSET + 11] != ' ') {
+ return true;
+ }
+ } else {
+ return true;
+ }
}
- this.devMinor = devNo;
- }
-
- /**
- * Indicates in case of an oldgnu sparse file if an extension
- * sparse header follows.
- *
- * @return true if an extension oldgnu sparse header follows.
- */
- public boolean isExtended() {
- return isExtended;
+ return false;
}
- /**
- * Get this entry's real file size in case of a sparse file.
- *
- * <p>This is the size a file would take on disk if the entry was expanded.</p>
- *
- * <p>If the file is not a sparse file, return size instead of realSize.</p>
- *
- * @return This entry's real file size, if the file is not a sparse file, return size instead of realSize.
- */
- public long getRealSize() {
- if (!isSparse()) {
- return getSize();
+ private boolean isInvalidXtarTime(final byte[] buffer, final int offset, final int length) {
+ // If atime[0]...atime[10] or ctime[0]...ctime[10] is not a POSIX octal number it cannot be 'xstar'.
+ if ((buffer[offset] & 0x80) == 0) {
+ final int lastIndex = length - 1;
+ for (int i = 0; i < lastIndex; i++) {
+ final byte b = buffer[offset + i];
+ if (b < '0' || b > '7') {
+ return true;
+ }
+ }
+ // Check for both POSIX compliant end of number characters if not using base 256
+ final byte b = buffer[offset + lastIndex];
+ if (b != ' ' && b != 0) {
+ return true;
+ }
}
- return realSize;
+ return false;
}
/**
- * Indicate if this entry is a GNU sparse block.
+ * Check if this is a link entry.
*
- * @return true if this is a sparse extension provided by GNU tar
+ * @since 1.2
+ * @return whether this is a link entry
*/
- public boolean isGNUSparse() {
- return isOldGNUSparse() || isPaxGNUSparse();
+ public boolean isLink() {
+ return linkFlag == LF_LINK;
}
/**
@@ -1288,6 +1336,16 @@ public class TarArchiveEntry implements ArchiveEntry, TarConstants, EntryStreamO
}
/**
+ * Get if this entry is a sparse file with 1.X PAX Format or not
+ *
+ * @return True if this entry is a sparse file with 1.X PAX Format
+ * @since 1.20
+ */
+ public boolean isPaxGNU1XSparse() {
+ return paxGNU1XSparse;
+ }
+
+ /**
* Indicate if this entry is a GNU sparse block using one of the
* PAX formats.
*
@@ -1299,245 +1357,261 @@ public class TarArchiveEntry implements ArchiveEntry, TarConstants, EntryStreamO
}
/**
- * Indicate if this entry is a star sparse block using PAX headers.
+ * Check if this is a Pax header.
+ *
+ * @return {@code true} if this is a Pax header.
+ *
+ * @since 1.1
*
- * @return true if this is a sparse extension provided by star
- * @since 1.11
*/
- public boolean isStarSparse() {
- return starSparse;
+ public boolean isPaxHeader() {
+ return linkFlag == LF_PAX_EXTENDED_HEADER_LC
+ || linkFlag == LF_PAX_EXTENDED_HEADER_UC;
}
/**
- * Indicate if this entry is a GNU long linkname block
+ * Check whether this is a sparse entry.
*
- * @return true if this is a long name extension provided by GNU tar
+ * @return whether this is a sparse entry
+ * @since 1.11
*/
- public boolean isGNULongLinkEntry() {
- return linkFlag == LF_GNUTYPE_LONGLINK;
+ public boolean isSparse() {
+ return isGNUSparse() || isStarSparse();
}
/**
- * Indicate if this entry is a GNU long name block
+ * Indicate if this entry is a star sparse block using PAX headers.
*
- * @return true if this is a long name extension provided by GNU tar
+ * @return true if this is a sparse extension provided by star
+ * @since 1.11
*/
- public boolean isGNULongNameEntry() {
- return linkFlag == LF_GNUTYPE_LONGNAME;
+ public boolean isStarSparse() {
+ return starSparse;
}
/**
- * Check if this is a Pax header.
- *
- * @return {@code true} if this is a Pax header.
- *
- * @since 1.1
- *
+ * {@inheritDoc}
+ * @since 1.21
*/
- public boolean isPaxHeader() {
- return linkFlag == LF_PAX_EXTENDED_HEADER_LC
- || linkFlag == LF_PAX_EXTENDED_HEADER_UC;
+ @Override
+ public boolean isStreamContiguous() {
+ return true;
}
/**
- * Check if this is a Pax header.
- *
- * @return {@code true} if this is a Pax header.
+ * Check if this is a symbolic link entry.
*
- * @since 1.1
+ * @since 1.2
+ * @return whether this is a symbolic link
*/
- public boolean isGlobalPaxHeader() {
- return linkFlag == LF_PAX_GLOBAL_EXTENDED_HEADER;
+ public boolean isSymbolicLink() {
+ return linkFlag == LF_SYMLINK;
}
/**
- * Return whether or not this entry represents a directory.
+ * Check for XSTAR / XUSTAR format.
*
- * @return True if this entry is a directory.
+ * Use the same logic found in star version 1.6 in {@code header.c}, function {@code isxmagic(TCB *ptb)}.
*/
- @Override
- public boolean isDirectory() {
- if (file != null) {
- return Files.isDirectory(file, linkOptions);
+ private boolean isXstar(final Map<String, String> globalPaxHeaders, final byte[] header) {
+ // Check if this is XSTAR
+ if (ArchiveUtils.matchAsciiBuffer(MAGIC_XSTAR, header, XSTAR_MAGIC_OFFSET, XSTAR_MAGIC_LEN)) {
+ return true;
}
- if (linkFlag == LF_DIR) {
- return true;
- }
+ /*
+ If SCHILY.archtype is present in the global PAX header, we can use it to identify the type of archive.
- return !isPaxHeader() && !isGlobalPaxHeader() && getName().endsWith("/");
- }
+ Possible values for XSTAR:
+ - xustar: 'xstar' format without "tar" signature at header offset 508.
+ - exustar: 'xustar' format variant that always includes x-headers and g-headers.
+ */
+ final String archType = globalPaxHeaders.get("SCHILY.archtype");
+ if (archType != null) {
+ return "xustar".equals(archType) || "exustar".equals(archType);
+ }
- /**
- * Check if this is a "normal file"
- *
- * @since 1.2
- * @return whether this is a "normal file"
- */
- public boolean isFile() {
- if (file != null) {
- return Files.isRegularFile(file, linkOptions);
+ // Check if this is XUSTAR
+ if (isInvalidPrefix(header)) {
+ return false;
}
- if (linkFlag == LF_OLDNORM || linkFlag == LF_NORMAL) {
- return true;
+ if (isInvalidXtarTime(header, XSTAR_ATIME_OFFSET, ATIMELEN_XSTAR)) {
+ return false;
+ }
+ if (isInvalidXtarTime(header, XSTAR_CTIME_OFFSET, CTIMELEN_XSTAR)) {
+ return false;
}
- return !getName().endsWith("/");
- }
- /**
- * Check if this is a symbolic link entry.
- *
- * @since 1.2
- * @return whether this is a symbolic link
- */
- public boolean isSymbolicLink() {
- return linkFlag == LF_SYMLINK;
+ return true;
}
- /**
- * Check if this is a link entry.
- *
- * @since 1.2
- * @return whether this is a link entry
- */
- public boolean isLink() {
- return linkFlag == LF_LINK;
+ private long parseOctalOrBinary(final byte[] header, final int offset, final int length, final boolean lenient) {
+ if (lenient) {
+ try {
+ return TarUtils.parseOctalOrBinary(header, offset, length);
+ } catch (final IllegalArgumentException ex) { //NOSONAR
+ return UNKNOWN;
+ }
+ }
+ return TarUtils.parseOctalOrBinary(header, offset, length);
}
/**
- * Check if this is a character device entry.
+ * Parse an entry's header information from a header buffer.
*
- * @since 1.2
- * @return whether this is a character device
+ * @param header The tar entry header buffer to get information from.
+ * @throws IllegalArgumentException if any of the numeric fields have an invalid format
*/
- public boolean isCharacterDevice() {
- return linkFlag == LF_CHR;
+ public void parseTarHeader(final byte[] header) {
+ try {
+ parseTarHeader(header, TarUtils.DEFAULT_ENCODING);
+ } catch (final IOException ex) { // NOSONAR
+ try {
+ parseTarHeader(header, TarUtils.DEFAULT_ENCODING, true, false);
+ } catch (final IOException ex2) {
+ // not really possible
+ throw new RuntimeException(ex2); //NOSONAR
+ }
+ }
}
/**
- * Check if this is a block device entry.
+ * Parse an entry's header information from a header buffer.
*
- * @since 1.2
- * @return whether this is a block device
+ * @param header The tar entry header buffer to get information from.
+ * @param encoding encoding to use for file names
+ * @since 1.4
+ * @throws IllegalArgumentException if any of the numeric fields
+ * have an invalid format
+ * @throws IOException on error
*/
- public boolean isBlockDevice() {
- return linkFlag == LF_BLK;
+ public void parseTarHeader(final byte[] header, final ZipEncoding encoding)
+ throws IOException {
+ parseTarHeader(header, encoding, false, false);
}
- /**
- * Check if this is a FIFO (pipe) entry.
- *
- * @since 1.2
- * @return whether this is a FIFO entry
- */
- public boolean isFIFO() {
- return linkFlag == LF_FIFO;
+ private void parseTarHeader(final byte[] header, final ZipEncoding encoding,
+ final boolean oldStyle, final boolean lenient)
+ throws IOException {
+ parseTarHeader(Collections.emptyMap(), header, encoding, oldStyle, lenient);
}
- /**
- * Check whether this is a sparse entry.
- *
- * @return whether this is a sparse entry
- * @since 1.11
- */
- public boolean isSparse() {
- return isGNUSparse() || isStarSparse();
+ private void parseTarHeader(final Map<String, String> globalPaxHeaders, final byte[] header,
+ final ZipEncoding encoding, final boolean oldStyle, final boolean lenient)
+ throws IOException {
+ try {
+ parseTarHeaderUnwrapped(globalPaxHeaders, header, encoding, oldStyle, lenient);
+ } catch (IllegalArgumentException ex) {
+ throw new IOException("Corrupted TAR archive.", ex);
+ }
}
- /**
- * {@inheritDoc}
- * @since 1.21
- */
- @Override
- public long getDataOffset() {
- return dataOffset;
- }
+ private void parseTarHeaderUnwrapped(final Map<String, String> globalPaxHeaders, final byte[] header,
+ final ZipEncoding encoding, final boolean oldStyle, final boolean lenient)
+ throws IOException {
+ int offset = 0;
- /**
- * Set the offset of the data for the tar entry.
- * @param dataOffset the position of the data in the tar.
- * @since 1.21
- */
- public void setDataOffset(final long dataOffset) {
- if (dataOffset < 0) {
- throw new IllegalArgumentException("The offset can not be smaller than 0");
+ name = oldStyle ? TarUtils.parseName(header, offset, NAMELEN)
+ : TarUtils.parseName(header, offset, NAMELEN, encoding);
+ offset += NAMELEN;
+ mode = (int) parseOctalOrBinary(header, offset, MODELEN, lenient);
+ offset += MODELEN;
+ userId = (int) parseOctalOrBinary(header, offset, UIDLEN, lenient);
+ offset += UIDLEN;
+ groupId = (int) parseOctalOrBinary(header, offset, GIDLEN, lenient);
+ offset += GIDLEN;
+ size = TarUtils.parseOctalOrBinary(header, offset, SIZELEN);
+ if (size < 0) {
+ throw new IOException("broken archive, entry with negative size");
+ }
+ offset += SIZELEN;
+ mTime = FileTime.from(parseOctalOrBinary(header, offset, MODTIMELEN, lenient), TimeUnit.SECONDS);
+ offset += MODTIMELEN;
+ checkSumOK = TarUtils.verifyCheckSum(header);
+ offset += CHKSUMLEN;
+ linkFlag = header[offset++];
+ linkName = oldStyle ? TarUtils.parseName(header, offset, NAMELEN)
+ : TarUtils.parseName(header, offset, NAMELEN, encoding);
+ offset += NAMELEN;
+ magic = TarUtils.parseName(header, offset, MAGICLEN);
+ offset += MAGICLEN;
+ version = TarUtils.parseName(header, offset, VERSIONLEN);
+ offset += VERSIONLEN;
+ userName = oldStyle ? TarUtils.parseName(header, offset, UNAMELEN)
+ : TarUtils.parseName(header, offset, UNAMELEN, encoding);
+ offset += UNAMELEN;
+ groupName = oldStyle ? TarUtils.parseName(header, offset, GNAMELEN)
+ : TarUtils.parseName(header, offset, GNAMELEN, encoding);
+ offset += GNAMELEN;
+ if (linkFlag == LF_CHR || linkFlag == LF_BLK) {
+ devMajor = (int) parseOctalOrBinary(header, offset, DEVLEN, lenient);
+ offset += DEVLEN;
+ devMinor = (int) parseOctalOrBinary(header, offset, DEVLEN, lenient);
+ offset += DEVLEN;
+ } else {
+ offset += 2 * DEVLEN;
}
- this.dataOffset = dataOffset;
- }
- /**
- * {@inheritDoc}
- * @since 1.21
- */
- @Override
- public boolean isStreamContiguous() {
- return true;
+ final int type = evaluateType(globalPaxHeaders, header);
+ switch (type) {
+ case FORMAT_OLDGNU: {
+ aTime = fileTimeFromOptionalSeconds(parseOctalOrBinary(header, offset, ATIMELEN_GNU, lenient));
+ offset += ATIMELEN_GNU;
+ cTime = fileTimeFromOptionalSeconds(parseOctalOrBinary(header, offset, CTIMELEN_GNU, lenient));
+ offset += CTIMELEN_GNU;
+ offset += OFFSETLEN_GNU;
+ offset += LONGNAMESLEN_GNU;
+ offset += PAD2LEN_GNU;
+ sparseHeaders =
+ new ArrayList<>(TarUtils.readSparseStructs(header, offset, SPARSE_HEADERS_IN_OLDGNU_HEADER));
+ offset += SPARSELEN_GNU;
+ isExtended = TarUtils.parseBoolean(header, offset);
+ offset += ISEXTENDEDLEN_GNU;
+ realSize = TarUtils.parseOctal(header, offset, REALSIZELEN_GNU);
+ offset += REALSIZELEN_GNU; // NOSONAR - assignment as documentation
+ break;
+ }
+ case FORMAT_XSTAR: {
+ final String xstarPrefix = oldStyle
+ ? TarUtils.parseName(header, offset, PREFIXLEN_XSTAR)
+ : TarUtils.parseName(header, offset, PREFIXLEN_XSTAR, encoding);
+ offset += PREFIXLEN_XSTAR;
+ if (!xstarPrefix.isEmpty()) {
+ name = xstarPrefix + "/" + name;
+ }
+ aTime = fileTimeFromOptionalSeconds(parseOctalOrBinary(header, offset, ATIMELEN_XSTAR, lenient));
+ offset += ATIMELEN_XSTAR;
+ cTime = fileTimeFromOptionalSeconds(parseOctalOrBinary(header, offset, CTIMELEN_XSTAR, lenient));
+ offset += CTIMELEN_XSTAR; // NOSONAR - assignment as documentation
+ break;
+ }
+ case FORMAT_POSIX:
+ default: {
+ final String prefix = oldStyle
+ ? TarUtils.parseName(header, offset, PREFIXLEN)
+ : TarUtils.parseName(header, offset, PREFIXLEN, encoding);
+ offset += PREFIXLEN; // NOSONAR - assignment as documentation
+ // SunOS tar -E does not add / to directory names, so fix
+ // up to be consistent
+ if (isDirectory() && !name.endsWith("/")){
+ name = name + "/";
+ }
+ if (!prefix.isEmpty()){
+ name = prefix + "/" + name;
+ }
+ }
+ }
}
/**
- * get extra PAX Headers
- * @return read-only map containing any extra PAX Headers
+ * process one pax header, using the entries extraPaxHeaders map as source for extra headers
+ * used when handling entries for sparse files.
+ * @param key
+ * @param val
* @since 1.15
*/
- public Map<String, String> getExtraPaxHeaders() {
- return Collections.unmodifiableMap(extraPaxHeaders);
- }
-
- /**
- * clear all extra PAX headers.
- * @since 1.15
- */
- public void clearExtraPaxHeaders() {
- extraPaxHeaders.clear();
- }
-
- /**
- * add a PAX header to this entry. If the header corresponds to an existing field in the entry,
- * that field will be set; otherwise the header will be added to the extraPaxHeaders Map
- * @param name The full name of the header to set.
- * @param value value of header.
- * @since 1.15
- */
- public void addPaxHeader(final String name, final String value) {
- try {
- processPaxHeader(name,value);
- } catch (IOException ex) {
- throw new IllegalArgumentException("Invalid input", ex);
- }
- }
-
- /**
- * get named extra PAX header
- * @param name The full name of an extended PAX header to retrieve
- * @return The value of the header, if any.
- * @since 1.15
- */
- public String getExtraPaxHeader(final String name) {
- return extraPaxHeaders.get(name);
- }
-
- /**
- * Update the entry using a map of pax headers.
- * @param headers
- * @since 1.15
- */
- void updateEntryFromPaxHeaders(final Map<String, String> headers) throws IOException {
- for (final Map.Entry<String, String> ent : headers.entrySet()) {
- final String key = ent.getKey();
- final String val = ent.getValue();
- processPaxHeader(key, val, headers);
- }
- }
-
- /**
- * process one pax header, using the entries extraPaxHeaders map as source for extra headers
- * used when handling entries for sparse files.
- * @param key
- * @param val
- * @since 1.15
- */
- private void processPaxHeader(final String key, final String val) throws IOException {
- processPaxHeader(key, val, extraPaxHeaders);
+ private void processPaxHeader(final String key, final String val) throws IOException {
+ processPaxHeader(key, val, extraPaxHeaders);
}
/**
@@ -1643,491 +1717,417 @@ public class TarArchiveEntry implements ArchiveEntry, TarConstants, EntryStreamO
}
}
- private static Instant parseInstantFromDecimalSeconds(final String value) {
- final BigDecimal epochSeconds = new BigDecimal(value);
- final long seconds = epochSeconds.longValue();
- final long nanos = epochSeconds.remainder(BigDecimal.ONE).movePointRight(9).longValue();
- return Instant.ofEpochSecond(seconds, nanos);
+ private void readFileMode(final Path file, final String normalizedName, final LinkOption... options) throws IOException {
+ if (Files.isDirectory(file, options)) {
+ this.mode = DEFAULT_DIR_MODE;
+ this.linkFlag = LF_DIR;
+
+ final int nameLength = normalizedName.length();
+ if (nameLength == 0 || normalizedName.charAt(nameLength - 1) != '/') {
+ this.name = normalizedName + "/";
+ } else {
+ this.name = normalizedName;
+ }
+ } else {
+ this.mode = DEFAULT_FILE_MODE;
+ this.linkFlag = LF_NORMAL;
+ this.name = normalizedName;
+ this.size = Files.size(file);
+ }
+ }
+
+ private void readOsSpecificProperties(final Path file, final LinkOption... options) throws IOException {
+ final Set<String> availableAttributeViews = file.getFileSystem().supportedFileAttributeViews();
+ if (availableAttributeViews.contains("posix")) {
+ final PosixFileAttributes posixFileAttributes = Files.readAttributes(file, PosixFileAttributes.class, options);
+ setLastModifiedTime(posixFileAttributes.lastModifiedTime());
+ setCreationTime(posixFileAttributes.creationTime());
+ setLastAccessTime(posixFileAttributes.lastAccessTime());
+ this.userName = posixFileAttributes.owner().getName();
+ this.groupName = posixFileAttributes.group().getName();
+ if (availableAttributeViews.contains("unix")) {
+ this.userId = ((Number) Files.getAttribute(file, "unix:uid", options)).longValue();
+ this.groupId = ((Number) Files.getAttribute(file, "unix:gid", options)).longValue();
+ try {
+ setStatusChangeTime((FileTime) Files.getAttribute(file, "unix:ctime", options));
+ } catch (final IllegalArgumentException ex) { // NOSONAR
+ // ctime is not supported
+ }
+ }
+ } else if (availableAttributeViews.contains("dos")) {
+ final DosFileAttributes dosFileAttributes = Files.readAttributes(file, DosFileAttributes.class, options);
+ setLastModifiedTime(dosFileAttributes.lastModifiedTime());
+ setCreationTime(dosFileAttributes.creationTime());
+ setLastAccessTime(dosFileAttributes.lastAccessTime());
+ this.userName = Files.getOwner(file, options).getName();
+ } else {
+ final BasicFileAttributes basicFileAttributes = Files.readAttributes(file, BasicFileAttributes.class, options);
+ setLastModifiedTime(basicFileAttributes.lastModifiedTime());
+ setCreationTime(basicFileAttributes.creationTime());
+ setLastAccessTime(basicFileAttributes.lastAccessTime());
+ this.userName = Files.getOwner(file, options).getName();
+ }
}
/**
- * If this entry represents a file, and the file is a directory, return
- * an array of TarEntries for this entry's children.
- *
- * <p>This method is only useful for entries created from a {@code
- * File} or {@code Path} but not for entries read from an archive.</p>
+ * Set this entry's creation time.
*
- * @return An array of TarEntry's for this entry's children.
+ * @param time This entry's new creation time.
+ * @since 1.22
*/
- public TarArchiveEntry[] getDirectoryEntries() {
- if (file == null || !isDirectory()) {
- return EMPTY_TAR_ARCHIVE_ENTRY_ARRAY;
- }
+ public void setCreationTime(final FileTime time) {
+ birthTime = time;
+ }
- final List<TarArchiveEntry> entries = new ArrayList<>();
- try (DirectoryStream<Path> dirStream = Files.newDirectoryStream(file)) {
- final Iterator<Path> iterator = dirStream.iterator();
- while (iterator.hasNext()) {
- final Path p = iterator.next();
- entries.add(new TarArchiveEntry(p));
- }
- } catch (final IOException e) {
- return EMPTY_TAR_ARCHIVE_ENTRY_ARRAY;
+ /**
+ * Set the offset of the data for the tar entry.
+ * @param dataOffset the position of the data in the tar.
+ * @since 1.21
+ */
+ public void setDataOffset(final long dataOffset) {
+ if (dataOffset < 0) {
+ throw new IllegalArgumentException("The offset can not be smaller than 0");
}
- return entries.toArray(EMPTY_TAR_ARCHIVE_ENTRY_ARRAY);
+ this.dataOffset = dataOffset;
}
/**
- * Write an entry's header information to a header buffer.
- *
- * <p>This method does not use the star/GNU tar/BSD tar extensions.</p>
+ * Set this entry's major device number.
*
- * @param outbuf The tar entry header buffer to fill in.
+ * @param devNo This entry's major device number.
+ * @throws IllegalArgumentException if the devNo is < 0.
+ * @since 1.4
*/
- public void writeEntryHeader(final byte[] outbuf) {
- try {
- writeEntryHeader(outbuf, TarUtils.DEFAULT_ENCODING, false);
- } catch (final IOException ex) { // NOSONAR
- try {
- writeEntryHeader(outbuf, TarUtils.FALLBACK_ENCODING, false);
- } catch (final IOException ex2) {
- // impossible
- throw new RuntimeException(ex2); //NOSONAR
- }
+ public void setDevMajor(final int devNo) {
+ if (devNo < 0){
+ throw new IllegalArgumentException("Major device number is out of "
+ + "range: " + devNo);
}
+ this.devMajor = devNo;
}
/**
- * Write an entry's header information to a header buffer.
+ * Set this entry's minor device number.
*
- * @param outbuf The tar entry header buffer to fill in.
- * @param encoding encoding to use when writing the file name.
- * @param starMode whether to use the star/GNU tar/BSD tar
- * extension for numeric fields if their value doesn't fit in the
- * maximum size of standard tar archives
+ * @param devNo This entry's minor device number.
+ * @throws IllegalArgumentException if the devNo is < 0.
* @since 1.4
- * @throws IOException on error
*/
- public void writeEntryHeader(final byte[] outbuf, final ZipEncoding encoding,
- final boolean starMode) throws IOException {
- int offset = 0;
-
- offset = TarUtils.formatNameBytes(name, outbuf, offset, NAMELEN,
- encoding);
- offset = writeEntryHeaderField(mode, outbuf, offset, MODELEN, starMode);
- offset = writeEntryHeaderField(userId, outbuf, offset, UIDLEN,
- starMode);
- offset = writeEntryHeaderField(groupId, outbuf, offset, GIDLEN,
- starMode);
- offset = writeEntryHeaderField(size, outbuf, offset, SIZELEN, starMode);
- offset = writeEntryHeaderField(mTime.to(TimeUnit.SECONDS), outbuf, offset,
- MODTIMELEN, starMode);
-
- final int csOffset = offset;
-
- offset = fill((byte) ' ', offset, outbuf, CHKSUMLEN);
-
- outbuf[offset++] = linkFlag;
- offset = TarUtils.formatNameBytes(linkName, outbuf, offset, NAMELEN,
- encoding);
- offset = TarUtils.formatNameBytes(magic, outbuf, offset, MAGICLEN);
- offset = TarUtils.formatNameBytes(version, outbuf, offset, VERSIONLEN);
- offset = TarUtils.formatNameBytes(userName, outbuf, offset, UNAMELEN,
- encoding);
- offset = TarUtils.formatNameBytes(groupName, outbuf, offset, GNAMELEN,
- encoding);
- offset = writeEntryHeaderField(devMajor, outbuf, offset, DEVLEN,
- starMode);
- offset = writeEntryHeaderField(devMinor, outbuf, offset, DEVLEN,
- starMode);
-
- if (starMode) {
- // skip prefix
- offset = fill(0, offset, outbuf, PREFIXLEN_XSTAR);
- offset = writeEntryHeaderOptionalTimeField(aTime, offset, outbuf, ATIMELEN_XSTAR);
- offset = writeEntryHeaderOptionalTimeField(cTime, offset, outbuf, CTIMELEN_XSTAR);
- // 8-byte fill
- offset = fill(0, offset, outbuf, 8);
- // Do not write MAGIC_XSTAR because it causes issues with some TAR tools
- // This makes it effectively XUSTAR, which guarantees compatibility with USTAR
- offset = fill(0, offset, outbuf, XSTAR_MAGIC_LEN);
+ public void setDevMinor(final int devNo) {
+ if (devNo < 0){
+ throw new IllegalArgumentException("Minor device number is out of "
+ + "range: " + devNo);
}
-
- offset = fill(0, offset, outbuf, outbuf.length - offset); // NOSONAR - assignment as documentation
-
- final long chk = TarUtils.computeCheckSum(outbuf);
-
- TarUtils.formatCheckSumOctalBytes(chk, outbuf, csOffset, CHKSUMLEN);
+ this.devMinor = devNo;
}
- private int writeEntryHeaderOptionalTimeField(FileTime time, int offset, byte[] outbuf, int fieldLength) {
- if (time != null) {
- offset = writeEntryHeaderField(time.to(TimeUnit.SECONDS), outbuf, offset, fieldLength, true);
- } else {
- offset = fill(0, offset, outbuf, fieldLength);
- }
- return offset;
+ /**
+ * Set this entry's group id.
+ *
+ * @param groupId This entry's new group id.
+ */
+ public void setGroupId(final int groupId) {
+ setGroupId((long) groupId);
}
- private int fill(final int value, final int offset, final byte[] outbuf, final int length) {
- return fill((byte) value, offset, outbuf, length);
+ /**
+ * Set this entry's group id.
+ *
+ * @since 1.10
+ * @param groupId This entry's new group id.
+ */
+ public void setGroupId(final long groupId) {
+ this.groupId = groupId;
}
- private int fill(final byte value, final int offset, final byte[] outbuf, final int length) {
- for (int i = 0; i < length; i++) {
- outbuf[offset + i] = value;
- }
- return offset + length;
+ /**
+ * Set this entry's group name.
+ *
+ * @param groupName This entry's new group name.
+ */
+ public void setGroupName(final String groupName) {
+ this.groupName = groupName;
}
- private int writeEntryHeaderField(final long value, final byte[] outbuf, final int offset,
- final int length, final boolean starMode) {
- if (!starMode && (value < 0
- || value >= 1L << 3 * (length - 1))) {
- // value doesn't fit into field when written as octal
- // number, will be written to PAX header or causes an
- // error
- return TarUtils.formatLongOctalBytes(0, outbuf, offset, length);
- }
- return TarUtils.formatLongOctalOrBinaryBytes(value, outbuf, offset,
- length);
+ /**
+ * Convenience method to set this entry's group and user ids.
+ *
+ * @param userId This entry's new user id.
+ * @param groupId This entry's new group id.
+ */
+ public void setIds(final int userId, final int groupId) {
+ setUserId(userId);
+ setGroupId(groupId);
}
/**
- * Parse an entry's header information from a header buffer.
+ * Set this entry's last access time.
*
- * @param header The tar entry header buffer to get information from.
- * @throws IllegalArgumentException if any of the numeric fields have an invalid format
+ * @param time This entry's new last access time.
+ * @since 1.22
*/
- public void parseTarHeader(final byte[] header) {
- try {
- parseTarHeader(header, TarUtils.DEFAULT_ENCODING);
- } catch (final IOException ex) { // NOSONAR
- try {
- parseTarHeader(header, TarUtils.DEFAULT_ENCODING, true, false);
- } catch (final IOException ex2) {
- // not really possible
- throw new RuntimeException(ex2); //NOSONAR
- }
- }
+ public void setLastAccessTime(final FileTime time) {
+ aTime = time;
}
/**
- * Parse an entry's header information from a header buffer.
+ * Set this entry's modification time.
*
- * @param header The tar entry header buffer to get information from.
- * @param encoding encoding to use for file names
- * @since 1.4
- * @throws IllegalArgumentException if any of the numeric fields
- * have an invalid format
- * @throws IOException on error
+ * @param time This entry's new modification time.
+ * @since 1.22
*/
- public void parseTarHeader(final byte[] header, final ZipEncoding encoding)
- throws IOException {
- parseTarHeader(header, encoding, false, false);
+ public void setLastModifiedTime(final FileTime time) {
+ mTime = Objects.requireNonNull(time, "Time must not be null");
}
- private void parseTarHeader(final byte[] header, final ZipEncoding encoding,
- final boolean oldStyle, final boolean lenient)
- throws IOException {
- parseTarHeader(Collections.emptyMap(), header, encoding, oldStyle, lenient);
+ /**
+ * Set this entry's link name.
+ *
+ * @param link the link name to use.
+ *
+ * @since 1.1
+ */
+ public void setLinkName(final String link) {
+ this.linkName = link;
}
- private void parseTarHeader(final Map<String, String> globalPaxHeaders, final byte[] header,
- final ZipEncoding encoding, final boolean oldStyle, final boolean lenient)
- throws IOException {
- try {
- parseTarHeaderUnwrapped(globalPaxHeaders, header, encoding, oldStyle, lenient);
- } catch (IllegalArgumentException ex) {
- throw new IOException("Corrupted TAR archive.", ex);
- }
+ /**
+ * Set the mode for this entry
+ *
+ * @param mode the mode for this entry
+ */
+ public void setMode(final int mode) {
+ this.mode = mode;
}
- private void parseTarHeaderUnwrapped(final Map<String, String> globalPaxHeaders, final byte[] header,
- final ZipEncoding encoding, final boolean oldStyle, final boolean lenient)
- throws IOException {
- int offset = 0;
+ /**
+ * Set this entry's modification time.
+ *
+ * @param time This entry's new modification time.
+ * @see TarArchiveEntry#setLastModifiedTime(FileTime)
+ */
+ public void setModTime(final Date time) {
+ setLastModifiedTime(FileTime.fromMillis(time.getTime()));
+ }
- name = oldStyle ? TarUtils.parseName(header, offset, NAMELEN)
- : TarUtils.parseName(header, offset, NAMELEN, encoding);
- offset += NAMELEN;
- mode = (int) parseOctalOrBinary(header, offset, MODELEN, lenient);
- offset += MODELEN;
- userId = (int) parseOctalOrBinary(header, offset, UIDLEN, lenient);
- offset += UIDLEN;
- groupId = (int) parseOctalOrBinary(header, offset, GIDLEN, lenient);
- offset += GIDLEN;
- size = TarUtils.parseOctalOrBinary(header, offset, SIZELEN);
- if (size < 0) {
- throw new IOException("broken archive, entry with negative size");
- }
- offset += SIZELEN;
- mTime = FileTime.from(parseOctalOrBinary(header, offset, MODTIMELEN, lenient), TimeUnit.SECONDS);
- offset += MODTIMELEN;
- checkSumOK = TarUtils.verifyCheckSum(header);
- offset += CHKSUMLEN;
- linkFlag = header[offset++];
- linkName = oldStyle ? TarUtils.parseName(header, offset, NAMELEN)
- : TarUtils.parseName(header, offset, NAMELEN, encoding);
- offset += NAMELEN;
- magic = TarUtils.parseName(header, offset, MAGICLEN);
- offset += MAGICLEN;
- version = TarUtils.parseName(header, offset, VERSIONLEN);
- offset += VERSIONLEN;
- userName = oldStyle ? TarUtils.parseName(header, offset, UNAMELEN)
- : TarUtils.parseName(header, offset, UNAMELEN, encoding);
- offset += UNAMELEN;
- groupName = oldStyle ? TarUtils.parseName(header, offset, GNAMELEN)
- : TarUtils.parseName(header, offset, GNAMELEN, encoding);
- offset += GNAMELEN;
- if (linkFlag == LF_CHR || linkFlag == LF_BLK) {
- devMajor = (int) parseOctalOrBinary(header, offset, DEVLEN, lenient);
- offset += DEVLEN;
- devMinor = (int) parseOctalOrBinary(header, offset, DEVLEN, lenient);
- offset += DEVLEN;
- } else {
- offset += 2 * DEVLEN;
- }
+ /**
+ * Set this entry's modification time.
+ *
+ * @param time This entry's new modification time.
+ * @since 1.21
+ * @see TarArchiveEntry#setLastModifiedTime(FileTime)
+ */
+ public void setModTime(final FileTime time) {
+ setLastModifiedTime(time);
+ }
- final int type = evaluateType(globalPaxHeaders, header);
- switch (type) {
- case FORMAT_OLDGNU: {
- aTime = fileTimeFromOptionalSeconds(parseOctalOrBinary(header, offset, ATIMELEN_GNU, lenient));
- offset += ATIMELEN_GNU;
- cTime = fileTimeFromOptionalSeconds(parseOctalOrBinary(header, offset, CTIMELEN_GNU, lenient));
- offset += CTIMELEN_GNU;
- offset += OFFSETLEN_GNU;
- offset += LONGNAMESLEN_GNU;
- offset += PAD2LEN_GNU;
- sparseHeaders =
- new ArrayList<>(TarUtils.readSparseStructs(header, offset, SPARSE_HEADERS_IN_OLDGNU_HEADER));
- offset += SPARSELEN_GNU;
- isExtended = TarUtils.parseBoolean(header, offset);
- offset += ISEXTENDEDLEN_GNU;
- realSize = TarUtils.parseOctal(header, offset, REALSIZELEN_GNU);
- offset += REALSIZELEN_GNU; // NOSONAR - assignment as documentation
- break;
- }
- case FORMAT_XSTAR: {
- final String xstarPrefix = oldStyle
- ? TarUtils.parseName(header, offset, PREFIXLEN_XSTAR)
- : TarUtils.parseName(header, offset, PREFIXLEN_XSTAR, encoding);
- offset += PREFIXLEN_XSTAR;
- if (!xstarPrefix.isEmpty()) {
- name = xstarPrefix + "/" + name;
- }
- aTime = fileTimeFromOptionalSeconds(parseOctalOrBinary(header, offset, ATIMELEN_XSTAR, lenient));
- offset += ATIMELEN_XSTAR;
- cTime = fileTimeFromOptionalSeconds(parseOctalOrBinary(header, offset, CTIMELEN_XSTAR, lenient));
- offset += CTIMELEN_XSTAR; // NOSONAR - assignment as documentation
- break;
- }
- case FORMAT_POSIX:
- default: {
- final String prefix = oldStyle
- ? TarUtils.parseName(header, offset, PREFIXLEN)
- : TarUtils.parseName(header, offset, PREFIXLEN, encoding);
- offset += PREFIXLEN; // NOSONAR - assignment as documentation
- // SunOS tar -E does not add / to directory names, so fix
- // up to be consistent
- if (isDirectory() && !name.endsWith("/")){
- name = name + "/";
- }
- if (!prefix.isEmpty()){
- name = prefix + "/" + name;
- }
- }
- }
+ /**
+ * Set this entry's modification time. The parameter passed
+ * to this method is in "Java time".
+ *
+ * @param time This entry's new modification time.
+ * @see TarArchiveEntry#setLastModifiedTime(FileTime)
+ */
+ public void setModTime(final long time) {
+ setLastModifiedTime(FileTime.fromMillis(time));
}
- private static FileTime fileTimeFromOptionalSeconds(long seconds) {
- if (seconds <= 0) {
- return null;
- }
- return FileTime.from(seconds, TimeUnit.SECONDS);
+ /**
+ * Set this entry's name.
+ *
+ * @param name This entry's new name.
+ */
+ public void setName(final String name) {
+ this.name = normalizeFileName(name, this.preserveAbsolutePath);
}
- private long parseOctalOrBinary(final byte[] header, final int offset, final int length, final boolean lenient) {
- if (lenient) {
- try {
- return TarUtils.parseOctalOrBinary(header, offset, length);
- } catch (final IllegalArgumentException ex) { //NOSONAR
- return UNKNOWN;
- }
+ /**
+ * Convenience method to set this entry's group and user names.
+ *
+ * @param userName This entry's new user name.
+ * @param groupName This entry's new group name.
+ */
+ public void setNames(final String userName, final String groupName) {
+ setUserName(userName);
+ setGroupName(groupName);
+ }
+
+ /**
+ * Set this entry's file size.
+ *
+ * @param size This entry's new file size.
+ * @throws IllegalArgumentException if the size is < 0.
+ */
+ public void setSize(final long size) {
+ if (size < 0){
+ throw new IllegalArgumentException("Size is out of range: "+size);
}
- return TarUtils.parseOctalOrBinary(header, offset, length);
+ this.size = size;
+ }
+
+ /**
+ * Set this entry's sparse headers
+ * @param sparseHeaders The new sparse headers
+ * @since 1.20
+ */
+ public void setSparseHeaders(final List<TarArchiveStructSparse> sparseHeaders) {
+ this.sparseHeaders = sparseHeaders;
+ }
+
+ /**
+ * Set this entry's status change time.
+ *
+ * @param time This entry's new status change time.
+ * @since 1.22
+ */
+ public void setStatusChangeTime(final FileTime time) {
+ cTime = time;
}
/**
- * Strips Windows' drive letter as well as any leading slashes, turns path separators into forward slashes.
+ * Set this entry's user id.
+ *
+ * @param userId This entry's new user id.
*/
- private static String normalizeFileName(String fileName, final boolean preserveAbsolutePath) {
- if (!preserveAbsolutePath) {
- final String property = System.getProperty("os.name");
- if (property != null) {
- final String osName = property.toLowerCase(Locale.ROOT);
-
- // Strip off drive letters!
- // REVIEW Would a better check be "(File.separator == '\')"?
-
- if (osName.startsWith("windows")) {
- if (fileName.length() > 2) {
- final char ch1 = fileName.charAt(0);
- final char ch2 = fileName.charAt(1);
+ public void setUserId(final int userId) {
+ setUserId((long) userId);
+ }
- if (ch2 == ':' && (ch1 >= 'a' && ch1 <= 'z' || ch1 >= 'A' && ch1 <= 'Z')) {
- fileName = fileName.substring(2);
- }
- }
- } else if (osName.contains("netware")) {
- final int colon = fileName.indexOf(':');
- if (colon != -1) {
- fileName = fileName.substring(colon + 1);
- }
- }
- }
- }
+ /**
+ * Set this entry's user id.
+ *
+ * @param userId This entry's new user id.
+ * @since 1.10
+ */
+ public void setUserId(final long userId) {
+ this.userId = userId;
+ }
- fileName = fileName.replace(File.separatorChar, '/');
+ /**
+ * Set this entry's user name.
+ *
+ * @param userName This entry's new user name.
+ */
+ public void setUserName(final String userName) {
+ this.userName = userName;
+ }
- // No absolute pathnames
- // Windows (and Posix?) paths can start with "\\NetworkDrive\",
- // so we loop on starting /'s.
- while (!preserveAbsolutePath && fileName.startsWith("/")) {
- fileName = fileName.substring(1);
+ /**
+ * Update the entry using a map of pax headers.
+ * @param headers
+ * @since 1.15
+ */
+ void updateEntryFromPaxHeaders(final Map<String, String> headers) throws IOException {
+ for (final Map.Entry<String, String> ent : headers.entrySet()) {
+ final String key = ent.getKey();
+ final String val = ent.getValue();
+ processPaxHeader(key, val, headers);
}
- return fileName;
}
/**
- * Evaluate an entry's header format from a header buffer.
+ * Write an entry's header information to a header buffer.
*
- * @param header The tar entry header buffer to evaluate the format for.
- * @return format type
+ * <p>This method does not use the star/GNU tar/BSD tar extensions.</p>
+ *
+ * @param outbuf The tar entry header buffer to fill in.
*/
- private int evaluateType(final Map<String, String> globalPaxHeaders, final byte[] header) {
- if (ArchiveUtils.matchAsciiBuffer(MAGIC_GNU, header, MAGIC_OFFSET, MAGICLEN)) {
- return FORMAT_OLDGNU;
- }
- if (ArchiveUtils.matchAsciiBuffer(MAGIC_POSIX, header, MAGIC_OFFSET, MAGICLEN)) {
- if (isXstar(globalPaxHeaders, header)) {
- return FORMAT_XSTAR;
+ public void writeEntryHeader(final byte[] outbuf) {
+ try {
+ writeEntryHeader(outbuf, TarUtils.DEFAULT_ENCODING, false);
+ } catch (final IOException ex) { // NOSONAR
+ try {
+ writeEntryHeader(outbuf, TarUtils.FALLBACK_ENCODING, false);
+ } catch (final IOException ex2) {
+ // impossible
+ throw new RuntimeException(ex2); //NOSONAR
}
- return FORMAT_POSIX;
}
- return 0;
}
/**
- * Check for XSTAR / XUSTAR format.
+ * Write an entry's header information to a header buffer.
*
- * Use the same logic found in star version 1.6 in {@code header.c}, function {@code isxmagic(TCB *ptb)}.
+ * @param outbuf The tar entry header buffer to fill in.
+ * @param encoding encoding to use when writing the file name.
+ * @param starMode whether to use the star/GNU tar/BSD tar
+ * extension for numeric fields if their value doesn't fit in the
+ * maximum size of standard tar archives
+ * @since 1.4
+ * @throws IOException on error
*/
- private boolean isXstar(final Map<String, String> globalPaxHeaders, final byte[] header) {
- // Check if this is XSTAR
- if (ArchiveUtils.matchAsciiBuffer(MAGIC_XSTAR, header, XSTAR_MAGIC_OFFSET, XSTAR_MAGIC_LEN)) {
- return true;
- }
+ public void writeEntryHeader(final byte[] outbuf, final ZipEncoding encoding,
+ final boolean starMode) throws IOException {
+ int offset = 0;
- /*
- If SCHILY.archtype is present in the global PAX header, we can use it to identify the type of archive.
+ offset = TarUtils.formatNameBytes(name, outbuf, offset, NAMELEN,
+ encoding);
+ offset = writeEntryHeaderField(mode, outbuf, offset, MODELEN, starMode);
+ offset = writeEntryHeaderField(userId, outbuf, offset, UIDLEN,
+ starMode);
+ offset = writeEntryHeaderField(groupId, outbuf, offset, GIDLEN,
+ starMode);
+ offset = writeEntryHeaderField(size, outbuf, offset, SIZELEN, starMode);
+ offset = writeEntryHeaderField(mTime.to(TimeUnit.SECONDS), outbuf, offset,
+ MODTIMELEN, starMode);
- Possible values for XSTAR:
- - xustar: 'xstar' format without "tar" signature at header offset 508.
- - exustar: 'xustar' format variant that always includes x-headers and g-headers.
- */
- final String archType = globalPaxHeaders.get("SCHILY.archtype");
- if (archType != null) {
- return "xustar".equals(archType) || "exustar".equals(archType);
- }
+ final int csOffset = offset;
- // Check if this is XUSTAR
- if (isInvalidPrefix(header)) {
- return false;
- }
- if (isInvalidXtarTime(header, XSTAR_ATIME_OFFSET, ATIMELEN_XSTAR)) {
- return false;
- }
- if (isInvalidXtarTime(header, XSTAR_CTIME_OFFSET, CTIMELEN_XSTAR)) {
- return false;
- }
+ offset = fill((byte) ' ', offset, outbuf, CHKSUMLEN);
- return true;
- }
+ outbuf[offset++] = linkFlag;
+ offset = TarUtils.formatNameBytes(linkName, outbuf, offset, NAMELEN,
+ encoding);
+ offset = TarUtils.formatNameBytes(magic, outbuf, offset, MAGICLEN);
+ offset = TarUtils.formatNameBytes(version, outbuf, offset, VERSIONLEN);
+ offset = TarUtils.formatNameBytes(userName, outbuf, offset, UNAMELEN,
+ encoding);
+ offset = TarUtils.formatNameBytes(groupName, outbuf, offset, GNAMELEN,
+ encoding);
+ offset = writeEntryHeaderField(devMajor, outbuf, offset, DEVLEN,
+ starMode);
+ offset = writeEntryHeaderField(devMinor, outbuf, offset, DEVLEN,
+ starMode);
- private boolean isInvalidPrefix(final byte[] header) {
- // prefix[130] is is guaranteed to be '\0' with XSTAR/XUSTAR
- if (header[XSTAR_PREFIX_OFFSET + 130] != 0) {
- // except when typeflag is 'M'
- if (header[LF_OFFSET] == LF_MULTIVOLUME) {
- // We come only here if we try to read in a GNU/xstar/xustar multivolume archive starting past volume #0
- // As of 1.22, commons-compress does not support multivolume tar archives.
- // If/when it does, this should work as intended.
- if ((header[XSTAR_MULTIVOLUME_OFFSET] & 0x80) == 0
- && header[XSTAR_MULTIVOLUME_OFFSET + 11] != ' ') {
- return true;
- }
- } else {
- return true;
- }
+ if (starMode) {
+ // skip prefix
+ offset = fill(0, offset, outbuf, PREFIXLEN_XSTAR);
+ offset = writeEntryHeaderOptionalTimeField(aTime, offset, outbuf, ATIMELEN_XSTAR);
+ offset = writeEntryHeaderOptionalTimeField(cTime, offset, outbuf, CTIMELEN_XSTAR);
+ // 8-byte fill
+ offset = fill(0, offset, outbuf, 8);
+ // Do not write MAGIC_XSTAR because it causes issues with some TAR tools
+ // This makes it effectively XUSTAR, which guarantees compatibility with USTAR
+ offset = fill(0, offset, outbuf, XSTAR_MAGIC_LEN);
}
- return false;
- }
- private boolean isInvalidXtarTime(final byte[] buffer, final int offset, final int length) {
- // If atime[0]...atime[10] or ctime[0]...ctime[10] is not a POSIX octal number it cannot be 'xstar'.
- if ((buffer[offset] & 0x80) == 0) {
- final int lastIndex = length - 1;
- for (int i = 0; i < lastIndex; i++) {
- final byte b = buffer[offset + i];
- if (b < '0' || b > '7') {
- return true;
- }
- }
- // Check for both POSIX compliant end of number characters if not using base 256
- final byte b = buffer[offset + lastIndex];
- if (b != ' ' && b != 0) {
- return true;
- }
- }
- return false;
- }
+ offset = fill(0, offset, outbuf, outbuf.length - offset); // NOSONAR - assignment as documentation
- void fillGNUSparse0xData(final Map<String, String> headers) {
- paxGNUSparse = true;
- realSize = Integer.parseInt(headers.get("GNU.sparse.size"));
- if (headers.containsKey("GNU.sparse.name")) {
- // version 0.1
- name = headers.get("GNU.sparse.name");
- }
+ final long chk = TarUtils.computeCheckSum(outbuf);
+
+ TarUtils.formatCheckSumOctalBytes(chk, outbuf, csOffset, CHKSUMLEN);
}
- void fillGNUSparse1xData(final Map<String, String> headers) throws IOException {
- paxGNUSparse = true;
- paxGNU1XSparse = true;
- if (headers.containsKey("GNU.sparse.name")) {
- name = headers.get("GNU.sparse.name");
- }
- if (headers.containsKey("GNU.sparse.realsize")) {
- try {
- realSize = Integer.parseInt(headers.get("GNU.sparse.realsize"));
- } catch (NumberFormatException ex) {
- throw new IOException("Corrupted TAR archive. GNU.sparse.realsize header for "
- + name + " contains non-numeric value");
- }
+ private int writeEntryHeaderField(final long value, final byte[] outbuf, final int offset,
+ final int length, final boolean starMode) {
+ if (!starMode && (value < 0
+ || value >= 1L << 3 * (length - 1))) {
+ // value doesn't fit into field when written as octal
+ // number, will be written to PAX header or causes an
+ // error
+ return TarUtils.formatLongOctalBytes(0, outbuf, offset, length);
}
+ return TarUtils.formatLongOctalOrBinaryBytes(value, outbuf, offset,
+ length);
}
- void fillStarSparseData(final Map<String, String> headers) throws IOException {
- starSparse = true;
- if (headers.containsKey("SCHILY.realsize")) {
- try {
- realSize = Long.parseLong(headers.get("SCHILY.realsize"));
- } catch (NumberFormatException ex) {
- throw new IOException("Corrupted TAR archive. SCHILY.realsize header for "
- + name + " contains non-numeric value");
- }
+ private int writeEntryHeaderOptionalTimeField(FileTime time, int offset, byte[] outbuf, int fieldLength) {
+ if (time != null) {
+ offset = writeEntryHeaderField(time.to(TimeUnit.SECONDS), outbuf, offset, fieldLength, true);
+ } else {
+ offset = fill(0, offset, outbuf, fieldLength);
}
+ return offset;
}
}