diff --git a/src/main/java/org/codehaus/plexus/archiver/AbstractUnArchiver.java b/src/main/java/org/codehaus/plexus/archiver/AbstractUnArchiver.java
index e117800a..cabfd62e 100644
--- a/src/main/java/org/codehaus/plexus/archiver/AbstractUnArchiver.java
+++ b/src/main/java/org/codehaus/plexus/archiver/AbstractUnArchiver.java
@@ -20,12 +20,22 @@
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
+import java.nio.file.FileSystemLoopException;
import java.nio.file.Files;
+import java.nio.file.InvalidPathException;
+import java.nio.file.LinkOption;
+import java.nio.file.NoSuchFileException;
+import java.nio.file.NotDirectoryException;
import java.nio.file.Path;
+import java.nio.file.attribute.BasicFileAttributes;
+import java.util.ArrayDeque;
import java.util.ArrayList;
import java.util.Date;
+import java.util.Deque;
+import java.util.LinkedHashMap;
import java.util.List;
import java.util.Locale;
+import java.util.Map;
import java.util.concurrent.atomic.AtomicInteger;
import org.codehaus.plexus.archiver.util.ArchiveEntryUtils;
@@ -34,7 +44,7 @@
import org.codehaus.plexus.components.io.filemappers.FileMapper;
import org.codehaus.plexus.components.io.fileselectors.FileSelector;
import org.codehaus.plexus.components.io.resources.PlexusIoResource;
-import org.codehaus.plexus.util.FileUtils;
+import org.codehaus.plexus.util.Os;
import org.codehaus.plexus.util.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
@@ -47,6 +57,9 @@
* @author Emmanuel Venisse
*/
public abstract class AbstractUnArchiver implements UnArchiver, FinalizerEnabled {
+ /** Whether to apply Windows-specific path and reparse point handling. */
+ private static final boolean IS_WINDOWS = Os.isFamily(Os.FAMILY_WINDOWS);
+
private final Logger logger = LoggerFactory.getLogger(getClass());
protected Logger getLogger() {
@@ -65,6 +78,17 @@ protected Logger getLogger() {
private List finalizers;
+ /** Directory spellings are reused only after a fresh NOFOLLOW identity check, within one extraction. */
+ private Map resolvedDirectories;
+
+ /**
+ * A directory whose real path can be reused during the current extraction.
+ *
+ * @param fileKey the filesystem identity checked on each cache lookup
+ * @param path the real path observed for that identity
+ */
+ private record ResolvedDirectory(Object fileKey, Path path) {}
+
private FileSelector[] fileSelectors;
/**
@@ -142,32 +166,42 @@ public void setFileMappers(final FileMapper[] fileMappers) {
@Override
public final void extract() throws ArchiverException {
- validate();
- deferredSymlinks = new DeferredSymlinks(getLogger());
+ resolvedDirectories = new LinkedHashMap<>(16, 0.75f, true);
try {
- execute();
- deferredSymlinks.resolve();
- } catch (IOException e) {
- throw new ArchiverException("Error while copying symbolic link targets", e);
+ validate();
+ deferredSymlinks = new DeferredSymlinks(getLogger());
+ try {
+ execute();
+ deferredSymlinks.resolve();
+ } catch (IOException e) {
+ throw new ArchiverException("Error while copying symbolic link targets", e);
+ } finally {
+ deferredSymlinks = null;
+ }
+ runArchiveFinalizers();
} finally {
- deferredSymlinks = null;
+ resolvedDirectories = null;
}
- runArchiveFinalizers();
}
@Override
public final void extract(final String path, final File outputDirectory) throws ArchiverException {
- validate(path, outputDirectory);
- deferredSymlinks = new DeferredSymlinks(getLogger());
+ resolvedDirectories = new LinkedHashMap<>(16, 0.75f, true);
try {
- execute(path, outputDirectory);
- deferredSymlinks.resolve();
- } catch (IOException e) {
- throw new ArchiverException("Error while copying symbolic link targets", e);
+ validate(path, outputDirectory);
+ deferredSymlinks = new DeferredSymlinks(getLogger());
+ try {
+ execute(path, outputDirectory);
+ deferredSymlinks.resolve();
+ } catch (IOException e) {
+ throw new ArchiverException("Error while copying symbolic link targets", e);
+ } finally {
+ deferredSymlinks = null;
+ }
+ runArchiveFinalizers();
} finally {
- deferredSymlinks = null;
+ resolvedDirectories = null;
}
- runArchiveFinalizers();
}
@Override
@@ -215,14 +249,19 @@ protected void validate() throws ArchiverException {
throw new ArchiverException("You must choose between a destination directory and a destination file.");
}
- if (destDirectory != null && !destDirectory.isDirectory()) {
- destFile = destDirectory;
- destDirectory = null;
- }
+ try {
+ // Use the same link/.. semantics for classification and extraction, retaining the configured spelling.
+ if (destDirectory != null && !Files.isDirectory(resolveExtractionRoot(destDirectory))) {
+ destFile = destDirectory;
+ destDirectory = null;
+ }
- if (destFile != null && destFile.isDirectory()) {
- destDirectory = destFile;
- destFile = null;
+ if (destFile != null && Files.isDirectory(resolveExtractionRoot(destFile))) {
+ destDirectory = destFile;
+ destFile = null;
+ }
+ } catch (IOException e) {
+ throw new ArchiverException("Cannot resolve extraction destination", e);
}
}
@@ -309,23 +348,13 @@ protected void extractFile(
}
}
- // Hmm. Symlinks re-evaluate back to the original file here. Unsure if this is a good thing...
- final File targetFileName = FileUtils.resolveFile(dir, entryName);
-
- // Make sure that the resolved path of the extracted file doesn't escape the destination directory
- // getCanonicalFile().toPath() is used instead of getCanonicalPath() (returns String),
- // because "/opt/directory".startsWith("/opt/dir") would return false negative.
- Path canonicalDirPath = dir.getCanonicalFile().toPath();
- Path canonicalDestPath = targetFileName.getCanonicalFile().toPath();
-
- if (!canonicalDestPath.startsWith(canonicalDirPath)) {
- throw new ArchiverException("Entry is outside of the target directory (" + entryName + ")");
- }
-
- // don't allow override target symlink by standard file
- if (StringUtils.isEmpty(symlinkDestination) && Files.isSymbolicLink(canonicalDestPath)) {
+ final boolean symlink = !StringUtils.isEmpty(symlinkDestination);
+ PathUse use = isDirectory && !symlink ? PathUse.DIRECTORY_ENTRY : PathUse.OTHER_ENTRY;
+ final Path destination = resolveExtractionPath(dir, entryName, use);
+ if (!symlink && Files.isSymbolicLink(destination)) {
throw new ArchiverException("Entry is outside of the target directory (" + entryName + ")");
}
+ final File targetFileName = destination.toFile();
try {
if (!shouldExtractEntry(dir, targetFileName, entryName, entryDate)) {
@@ -338,8 +367,8 @@ protected void extractFile(
dirF.mkdirs();
}
- if (!StringUtils.isEmpty(symlinkDestination)) {
- if (!createSymlinkEntry(canonicalDirPath, targetFileName, symlinkDestination, entryName)) {
+ if (symlink) {
+ if (!createSymlinkEntry(resolveExtractionRoot(dir), targetFileName, symlinkDestination, entryName)) {
return;
}
} else if (isDirectory) {
@@ -358,6 +387,248 @@ protected void extractFile(
}
}
+ /**
+ * Resolves the trusted root, following each link before processing subsequent parent components.
+ * @param directory the configured root, whose original spelling remains available to extraction hooks
+ * @return the physical root, including any not-yet-existing suffix
+ * @throws IOException if an existing component cannot be resolved
+ */
+ protected final Path resolveExtractionRoot(File directory) throws IOException {
+ return resolvePath(directory.toPath(), PathUse.ROOT);
+ }
+
+ /**
+ * Resolves the mapped entry name and checks containment of its canonical destination.
+ * @param directory the trusted extraction root
+ * @param name the mapped destination name
+ * @return the contained destination, using the existing canonical-file semantics for a final symbolic link
+ * @throws IOException if an existing component cannot be resolved
+ * @throws ArchiverException if the name is invalid, the destination is outside the root, or it ends at a
+ * redirected Windows reparse point
+ */
+ protected final Path resolveExtractionPath(File directory, String name) throws IOException {
+ return resolveExtractionPath(directory, name, PathUse.OTHER_ENTRY);
+ }
+
+ /** Determines how to handle a symbolic link or Windows reparse point at the final component. */
+ private enum PathUse {
+ /** Follow the configured extraction root to its physical location. */
+ ROOT,
+ /** Allow a junction to an existing directory. */
+ DIRECTORY_ENTRY,
+ /** Reject a redirected Windows reparse point. */
+ OTHER_ENTRY
+ }
+
+ /**
+ * Parses a mapped name using either slash for absolute paths and native separators for relative paths.
+ * Windows drive-relative names use the working directory of the named drive.
+ *
+ * @param name the entry name after applying file mappers
+ * @return the parsed path, which may still be relative to the extraction root
+ * @throws ArchiverException if the host cannot represent the name
+ */
+ private static Path mappedEntryPath(String name) {
+ Path entry;
+ try {
+ // Preserve the previous resolver's portable absolute names and platform-native relative names.
+ Path portable = Path.of(name.replace('/', File.separatorChar).replace('\\', File.separatorChar));
+ if (portable.isAbsolute()) {
+ return portable;
+ }
+ entry = Path.of(name);
+ } catch (InvalidPathException e) {
+ throw new ArchiverException("Invalid archive entry name (" + name + ")", e);
+ }
+ Path entryRoot = entry.getRoot();
+ // A Windows drive-relative name (C:file) starts at that drive's working directory.
+ if (entryRoot != null && entryRoot.toString().endsWith(":")) {
+ return entry.toAbsolutePath();
+ }
+ return entry;
+ }
+
+ /**
+ * Resolves a mapped entry against the physical extraction root and verifies containment.
+ *
+ * @param directory the configured extraction root
+ * @param name the mapped entry name
+ * @param use how to handle the entry's final component
+ * @return the resolved destination inside or equal to the extraction root
+ * @throws IOException if the root or an existing component cannot be resolved
+ * @throws ArchiverException if the name is invalid, the destination is outside the root, or the entry
+ * would replace a redirected Windows reparse point
+ */
+ private Path resolveExtractionPath(File directory, String name, PathUse use) throws IOException {
+ Path root = resolveExtractionRoot(directory);
+ Path entry = mappedEntryPath(name);
+ // Only rootless entries can start at the resolved root. Windows rooted paths can be non-absolute.
+ Path destination =
+ entry.getRoot() == null ? resolvePath(root, entry, use) : resolvePath(root.resolve(entry), use);
+ if (!destination.startsWith(root)) {
+ throw new ArchiverException("Entry is outside of the target directory (" + name + ")");
+ }
+ return destination;
+ }
+
+ /**
+ * Resolves a path starting at its filesystem root. Intermediate links are followed before processing
+ * a subsequent {@code ..}, even when the leaf is missing.
+ *
+ * @param path the path to resolve, relative to the working directory if necessary
+ * @param use how to handle the final component
+ * @return the resolved absolute path, including any missing suffix
+ * @throws IOException if an existing component cannot be resolved
+ * @throws ArchiverException if the entry would replace a redirected Windows reparse point
+ */
+ private Path resolvePath(Path path, PathUse use) throws IOException {
+ Path absolute = path.toAbsolutePath();
+ return resolvePath(absolute.getRoot(), absolute, use);
+ }
+
+ /**
+ * Resolves the name components from a known physical prefix. An ordinary existing directory can be
+ * verified in one real-path lookup. The component walk handles aliases, missing parents and the
+ * entry's final component.
+ *
+ * @param current the physical starting directory or filesystem root
+ * @param path the path whose name components remain to be resolved
+ * @param use how to handle the final component
+ * @return the resolved absolute path, including any missing suffix
+ * @throws IOException if a parent is not a directory, the link expansion limit is exceeded,
+ * or an existing component cannot be resolved
+ * @throws ArchiverException if the entry would replace a redirected Windows reparse point
+ */
+ private Path resolvePath(Path current, Path path, PathUse use) throws IOException {
+ Path prefix = use == PathUse.ROOT ? path : path.getParent();
+ if (prefix != null) {
+ Path directory = current.resolve(prefix);
+ if (isOrdinaryDirectory(directory)) {
+ if (use == PathUse.ROOT) {
+ return directory;
+ }
+ current = directory;
+ path = path.getFileName();
+ }
+ }
+ Deque remaining = new ArrayDeque<>();
+ path.forEach(remaining::addLast);
+ int links = 0;
+ while (!remaining.isEmpty()) {
+ Path name = remaining.removeFirst();
+ if (name.toString().isEmpty() || name.toString().equals(".")) {
+ continue;
+ }
+ if (name.toString().equals("..")) {
+ if (current.getParent() != null) {
+ current = current.getParent();
+ }
+ continue;
+ }
+ Path candidate = current.resolve(name);
+ BasicFileAttributes attributes;
+ try {
+ attributes = Files.readAttributes(candidate, BasicFileAttributes.class, LinkOption.NOFOLLOW_LINKS);
+ } catch (NoSuchFileException ignored) {
+ current = candidate;
+ continue;
+ }
+ if (attributes.isSymbolicLink()) {
+ if (remaining.isEmpty() && use != PathUse.ROOT) {
+ // Keep the existing canonical-file treatment of a final link, including a dangling link.
+ return candidate.toFile().getCanonicalFile().toPath();
+ }
+ if (++links > 64) {
+ throw new FileSystemLoopException(path.toString());
+ }
+ // Resolve the target against the physical parent. Do not normalize away link/.. components.
+ Path target = current.resolve(Files.readSymbolicLink(candidate)).toAbsolutePath();
+ for (int i = target.getNameCount() - 1; i >= 0; i--) {
+ remaining.addFirst(target.getName(i));
+ }
+ current = target.getRoot();
+ } else if (IS_WINDOWS && attributes.isOther()) {
+ // Windows reports junctions as "other", and from JDK 26 they no longer report as directories.
+ current = candidate.toRealPath();
+ boolean directoryRequired = !remaining.isEmpty();
+ if (use != PathUse.ROOT
+ && remaining.stream()
+ .allMatch(component -> component.toString().equals("."))
+ && !current.equals(candidate.toRealPath(LinkOption.NOFOLLOW_LINKS))) {
+ if (use != PathUse.DIRECTORY_ENTRY) {
+ throw new ArchiverException(
+ "Cannot extract to a redirected Windows reparse point (" + candidate + ")");
+ }
+ directoryRequired = true;
+ }
+ if (directoryRequired
+ && !Files.readAttributes(current, BasicFileAttributes.class)
+ .isDirectory()) {
+ throw new NotDirectoryException(candidate.toString());
+ }
+ } else {
+ if (!remaining.isEmpty() && !attributes.isDirectory()) {
+ throw new NotDirectoryException(candidate.toString());
+ }
+ // With no unresolved parent links or dots, this also handles Windows casing and short names.
+ current = resolveDirectory(candidate, attributes);
+ }
+ }
+ return current;
+ }
+
+ /**
+ * Checks whether the directory spelling exactly matches its current real path, including case on Windows.
+ *
+ * @param directory the absolute path of the root or entry parent
+ * @return {@code true} if the path names a directory with that spelling and the component walk can be skipped
+ */
+ private static boolean isOrdinaryDirectory(Path directory) {
+ try {
+ Path real = directory.toRealPath();
+ // Windows Path.equals folds case; on Unix it compares the underlying filename bytes.
+ boolean sameSpelling = IS_WINDOWS ? directory.toString().equals(real.toString()) : directory.equals(real);
+ return sameSpelling && Files.isDirectory(directory, LinkOption.NOFOLLOW_LINKS);
+ } catch (IOException ignored) {
+ // The walk handles missing components, link expansion limits, and filesystem-specific errors.
+ return false;
+ }
+ }
+
+ /**
+ * Resolves one existing component. An ordinary directory's real path can be reused when the
+ * freshly read file key matches the cached identity.
+ *
+ * @param candidate the component under its resolved parent
+ * @param attributes the attributes read without following the final link
+ * @return the component's real path
+ * @throws IOException if the real path cannot be obtained
+ */
+ private Path resolveDirectory(Path candidate, BasicFileAttributes attributes) throws IOException {
+ Object key = attributes.fileKey();
+ // Reparse points and providers without file identities need fresh resolution. Do not cache file leaves.
+ if (resolvedDirectories == null || !attributes.isDirectory() || attributes.isOther() || key == null) {
+ return candidate.toRealPath();
+ }
+ ResolvedDirectory cached = resolvedDirectories.get(candidate);
+ if (cached != null && key.equals(cached.fileKey())) {
+ return cached.path();
+ }
+ Path resolved = candidate.toRealPath();
+ // Only retain spellings that already match the resolved path; aliases still need fresh resolution.
+ if (candidate.equals(resolved)) {
+ resolvedDirectories.put(candidate, new ResolvedDirectory(key, resolved));
+ if (resolvedDirectories.size() > 1024) {
+ var oldest = resolvedDirectories.keySet().iterator();
+ oldest.next();
+ oldest.remove();
+ }
+ } else {
+ resolvedDirectories.remove(candidate);
+ }
+ return resolved;
+ }
+
/**
* Creates a symbolic link. Visible for testing, so a test can simulate a file system that refuses links.
*
@@ -429,24 +700,20 @@ protected boolean shouldExtractEntry(File targetDirectory, File targetFileName,
return true;
}
- boolean entryIsDirectory =
- entryName.endsWith("/"); // directory entries always end with '/', regardless of the OS.
- String canonicalDestPath = targetFileName.getCanonicalPath();
- String suffix = (entryIsDirectory ? "/" : "");
- String relativeCanonicalDestPath =
- canonicalDestPath.replace(targetDirectory.getCanonicalPath() + File.separatorChar, "") + suffix;
+ Path requestedPath = resolveExtractionRoot(targetDirectory).resolve(mappedEntryPath(entryName));
+ String requestedName = requestedPath.toString();
+ String existingName =
+ existingEntrySpelling(requestedPath, targetFileName.toPath()).toString();
boolean fileOnDiskIsOlderThanEntry = targetFileName.lastModified() < entryDate.getTime();
- boolean differentCasing =
- !normalizedFileSeparator(entryName).equals(normalizedFileSeparator(relativeCanonicalDestPath));
// Warn for case (4) and (5) if the file system is case-insensitive
- if (differentCasing) {
+ if (!requestedName.equals(existingName) && requestedName.equalsIgnoreCase(existingName)) {
String casingMessage = String.format(
Locale.ENGLISH,
"Archive entry '%s' and existing file '%s' names differ only by case."
+ " This may lead to an unexpected outcome on case-insensitive filesystems.",
entryName,
- canonicalDestPath);
+ existingName);
getLogger().warn(casingMessage);
casingMessageEmitted.incrementAndGet();
}
@@ -456,7 +723,24 @@ protected boolean shouldExtractEntry(File targetDirectory, File targetFileName,
return isOverwrite() || fileOnDiskIsOlderThanEntry;
}
- private String normalizedFileSeparator(String pathOrEntry) {
- return pathOrEntry.replace("/", File.separator);
+ /**
+ * Looks up the spelling used on disk for the case-mismatch warning. On Windows the lookup keeps
+ * junction names in the requested path. If that spelling cannot be looked up, it uses the resolved destination.
+ *
+ * @param requestedPath the path with the spelling supplied by the entry or mapper
+ * @param destination the existing destination selected by the resolver
+ * @return the path spelling to compare with the requested name
+ * @throws IOException if the destination spelling cannot be determined
+ */
+ private Path existingEntrySpelling(Path requestedPath, Path destination) throws IOException {
+ if (IS_WINDOWS) {
+ try {
+ // Look up each name as stored on disk, keeping the junction name in the path.
+ return requestedPath.toRealPath(LinkOption.NOFOLLOW_LINKS);
+ } catch (IOException ignored) {
+ // A mapped name such as missing/../file may exist only at its resolved destination.
+ }
+ }
+ return resolvePath(destination, PathUse.OTHER_ENTRY);
}
}
diff --git a/src/site/markdown/extraction-paths.md b/src/site/markdown/extraction-paths.md
new file mode 100644
index 00000000..5f251fb5
--- /dev/null
+++ b/src/site/markdown/extraction-paths.md
@@ -0,0 +1,40 @@
+# Extraction paths and symbolic links
+
+Extractors resolve existing path components before checking that output stays
+inside the destination directory. Symbolic links are followed before processing
+subsequent `..` components, including when the output file does not exist yet.
+The same rules resolve the configured destination directory and classify it as
+a file or directory.
+
+For an existing root or entry parent, the resolver checks whether its spelling
+matches its current physical directory. A match lets it skip the component
+walk for that directory. Otherwise it walks the components and reuses cached
+directories only after a fresh check of their filesystem identity without
+following symbolic links. The cache lasts for one extraction. Resolution
+stops after 64 symbolic-link expansions, rejecting cyclic or excessively long
+paths.
+
+## Archive formats and compatibility
+
+TAR, including its compressed variants, and ZIP-based formats such as JAR,
+WAR, and EAR use the shared entry extractor.
+
+- Intermediate symbolic links are followed before
+ subsequent parent components are processed. Containment is checked even
+ when the destination leaf does not exist. The overwrite check and the write
+ both use the resolved destination.
+- On Windows, a drive-relative mapper result such as `C:out\file` is relative
+ to the working directory of that drive. Its resolved destination must still
+ be inside the extraction directory.
+- On Windows, an existing NTFS junction can serve as an extraction directory
+ when its resolved target is inside the extraction root. For example, if
+ `assets` is such a junction, both the directory entry `assets/` and the file
+ entry `assets/logo.png` are accepted. The file can also be extracted when
+ the archive omits the directory entry. A regular-file or symbolic-link entry
+ named `assets` cannot replace the junction. The same containment check
+ applies to the directory entry and to entries beneath it.
+
+Standalone GZIP, BZIP2, Snappy, XZ, and Zstandard extractors use the shared
+destination validation and may report invalid destination paths during
+validation. Each uses a format-specific stream copy to its configured output
+file. The per-entry rules above apply to the archive readers.
diff --git a/src/site/site.xml b/src/site/site.xml
index dd5b761c..4e34d884 100644
--- a/src/site/site.xml
+++ b/src/site/site.xml
@@ -4,6 +4,7 @@