Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -62,9 +62,14 @@
<Compile Include="$(CommonPath)Interop\Windows\Kernel32\Interop.FormatMessage.cs" Link="Common\Interop\Windows\Kernel32\Interop.FormatMessage.cs" />
<Compile Include="$(CommonPath)Interop\Windows\Kernel32\Interop.FILE_TIME.cs" Link="Common\Interop\Windows\Kernel32\Interop.FILE_TIME.cs" />
<Compile Include="$(CommonPath)Interop\Windows\Kernel32\Interop.FileOperations.cs" Link="Common\Interop\Windows\Kernel32\Interop.FileOperations.cs" />
<Compile Include="$(CommonPath)Interop\Windows\Kernel32\Interop.GET_FILEEX_INFO_LEVELS.cs" Link="Common\Interop\Windows\Kernel32\Interop.GET_FILEEX_INFO_LEVELS.cs" />
<Compile Include="$(CommonPath)Interop\Windows\Kernel32\Interop.GenericOperations.cs" Link="Common\Interop\Windows\Kernel32\Interop.GenericOperations.cs" />
<Compile Include="$(CommonPath)Interop\Windows\Kernel32\Interop.GetFileAttributesEx.cs" Link="Common\Interop\Windows\Kernel32\Interop.GetFileAttributesEx.cs" />
<Compile Include="$(CommonPath)Interop\Windows\Kernel32\Interop.GetFileInformationByHandle.cs" Link="Common\Interop\Windows\Kernel32\Interop.GetFileInformationByHandle.cs" />
<Compile Include="$(CommonPath)Interop\Windows\Kernel32\Interop.MAX_PATH.cs" Link="Common\Interop\Windows\Kernel32\Interop.MAX_PATH.cs" />
<Compile Include="$(CommonPath)Interop\Windows\Kernel32\Interop.SECURITY_ATTRIBUTES.cs" Link="Common\Interop\Windows\Kernel32\Interop.SECURITY_ATTRIBUTES.cs" />
<Compile Include="$(CommonPath)Interop\Windows\Kernel32\Interop.WIN32_FILE_ATTRIBUTE_DATA.cs" Link="Common\Interop\Windows\Kernel32\Interop.WIN32_FILE_ATTRIBUTE_DATA.cs" />
<Compile Include="$(CommonPath)Interop\Windows\Kernel32\Interop.WIN32_FIND_DATA.cs" Link="Common\Interop\Windows\Kernel32\Interop.WIN32_FIND_DATA.cs" />
</ItemGroup>

<!-- Unix specific files -->
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,16 @@ namespace System.Formats.Tar
// Unix specific methods for the TarEntry class.
public abstract partial class TarEntry
{
private static bool IsExistingNonLink(string path)
{
if (Interop.Sys.LStat(path, out Interop.Sys.FileStatus status) == 0)
{
return (status.Mode & Interop.Sys.FileTypes.S_IFMT) != Interop.Sys.FileTypes.S_IFLNK;
}

return false;
}

// Unix specific implementation of the method that extracts the current entry as a block device.
private void ExtractAsBlockDevice(string destinationFileName)
{
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,18 @@ namespace System.Formats.Tar
// Windows specific methods for the TarEntry class.
public abstract partial class TarEntry
{
private static bool IsExistingNonLink(string path)
{
Interop.Kernel32.WIN32_FILE_ATTRIBUTE_DATA data = default;
if (Interop.Kernel32.GetFileAttributesEx(path, Interop.Kernel32.GET_FILEEX_INFO_LEVELS.GetFileExInfoStandard, ref data))
{
FileAttributes attributes = (FileAttributes)data.dwFileAttributes;
return (attributes & FileAttributes.ReparsePoint) == 0;
}

return false;
}

#pragma warning disable IDE0060
// Throws on Windows. Block devices are not supported on this platform.
private void ExtractAsBlockDevice(string destinationFileName)
Expand Down
101 changes: 52 additions & 49 deletions src/libraries/System.Formats.Tar/src/System/Formats/Tar/TarEntry.cs
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@
using System.IO;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.Win32.SafeHandles;

namespace System.Formats.Tar
{
Expand Down Expand Up @@ -321,7 +322,7 @@ public Stream? DataStream
// Extracts the current entry to a location relative to the specified directory.
internal void ExtractRelativeToDirectory(string destinationDirectoryPath, bool overwrite, ref TarHelpers.ExtractState extractState)
{
(string destinationFullPath, string? linkTargetPath, bool deferred) = GetDestinationAndLinkPaths(destinationDirectoryPath);
(string destinationFullPath, string? linkTargetPath, bool deferred) = GetDestinationAndLinkPaths(destinationDirectoryPath, ref extractState);

if (deferred)
{
Expand Down Expand Up @@ -353,7 +354,7 @@ internal Task ExtractRelativeToDirectoryAsync(string destinationDirectoryPath, b
return Task.FromCanceled(cancellationToken);
}

(string destinationFullPath, string? linkTargetPath, bool deferred) = GetDestinationAndLinkPaths(destinationDirectoryPath);
(string destinationFullPath, string? linkTargetPath, bool deferred) = GetDestinationAndLinkPaths(destinationDirectoryPath, ref extractState);

if (deferred)
{
Expand All @@ -380,7 +381,7 @@ internal Task ExtractRelativeToDirectoryAsync(string destinationDirectoryPath, b

// Gets the sanitized paths for the file destination and link target paths to be used when extracting relative to a directory.
// Returns deferred=true when a symlink is deferred (placeholder file created, real link created after all entries are extracted).
private (string DestinationFullPath, string? LinkTargetPath, bool Deferred) GetDestinationAndLinkPaths(string destinationDirectoryPath)
private (string DestinationFullPath, string? LinkTargetPath, bool Deferred) GetDestinationAndLinkPaths(string destinationDirectoryPath, ref TarHelpers.ExtractState extractState)
{
Debug.Assert(!string.IsNullOrEmpty(destinationDirectoryPath));
Debug.Assert(Path.IsPathFullyQualified(destinationDirectoryPath));
Expand Down Expand Up @@ -429,7 +430,7 @@ internal Task ExtractRelativeToDirectoryAsync(string destinationDirectoryPath, b
string? linkDestination = GetFullDestinationPath(
destinationDirectoryPath,
Path.Join(destinationDirectoryPath, linkName));
if (linkDestination is null || FilePathEscapesDirectory(destinationDirectoryPath, linkDestination))
if (linkDestination is null || FilePathEscapesDirectory(destinationDirectoryPath, linkDestination, ref extractState))
{
throw new IOException(SR.Format(SR.TarExtractingResultsLinkOutside, linkName, destinationDirectoryPath));
}
Expand Down Expand Up @@ -500,48 +501,34 @@ private static void CreateSymlinkPlaceholderFile(string filePath, string linkTar
// Prevent an archive from escaping the extraction root through symlinks that were created by earlier entries in the same archive.
// This protection applies only to links introduced by the archive itself. It is not intended to defend against preexisting symlinks
// already present on disk before extraction
private static bool FilePathEscapesDirectory(string destinationDirectoryPath, string fileDestinationPath)
private static bool FilePathEscapesDirectory(string destinationDirectoryPath, string fileDestinationPath, ref TarHelpers.ExtractState extractState)
{
string resolvedDest = ResolvePhysicalPath(destinationDirectoryPath);
Debug.Assert(destinationDirectoryPath[^1] == Path.DirectorySeparatorChar);
Debug.Assert(fileDestinationPath.StartsWith(destinationDirectoryPath, StringComparison.Ordinal));

// Use the logical destination path for computing the relative path
string logicalDest = Path.GetFullPath(destinationDirectoryPath);
string logicalPrefix = logicalDest.EndsWith(Path.DirectorySeparatorChar)
? logicalDest
: logicalDest + Path.DirectorySeparatorChar;
// The destination root and its ancestors are trusted, and extraction never overwrites directories.
string resolvedDest = extractState.ResolvedDestinationDirectoryPath ??= ResolvePhysicalPath(destinationDirectoryPath);

string destPrefix = resolvedDest.EndsWith(Path.DirectorySeparatorChar)
? resolvedDest
: resolvedDest + Path.DirectorySeparatorChar;

// Normalize file path (resolves .. and . but not symlinks)
string normalizedFile = Path.GetFullPath(fileDestinationPath);

// Windows supports per-directory case sensitivity, so containment checks must use ordinal comparisons.
// Guard with StartsWith before computing relative path
if (!normalizedFile.StartsWith(logicalPrefix, StringComparison.Ordinal) &&
!normalizedFile.Equals(logicalDest, StringComparison.Ordinal))
{
return true;
}

// Walk relative components, resolving symlinks at each step
string relative = normalizedFile.Substring(logicalPrefix.Length)
.TrimStart(Path.DirectorySeparatorChar, Path.AltDirectorySeparatorChar);

string[] components = relative.Split(new char[] { Path.DirectorySeparatorChar, Path.AltDirectorySeparatorChar },
StringSplitOptions.RemoveEmptyEntries);
// GetFullDestinationPath has already normalized and checked the logical target.
ReadOnlySpan<char> relative = fileDestinationPath.AsSpan(destinationDirectoryPath.Length);
ReadOnlySpan<char> resolvedRoot = resolvedDest.AsSpan().TrimEnd(Path.DirectorySeparatorChar);

string current = resolvedDest;

foreach (string component in components)
foreach (Range range in relative.SplitAny(Path.DirectorySeparatorChar, Path.AltDirectorySeparatorChar))
{
current = Path.Combine(current, component);
ReadOnlySpan<char> component = relative[range];
if (component.IsEmpty)
{
continue;
}

current = Path.Join(current, component);
current = ResolveSymlink(current);

string normalizedCurrent = Path.GetFullPath(current);
if (!normalizedCurrent.StartsWith(destPrefix, StringComparison.Ordinal) &&
!normalizedCurrent.Equals(resolvedDest, StringComparison.Ordinal))
// Windows supports per-directory case sensitivity.
if (!current.AsSpan().StartsWith(resolvedRoot, StringComparison.Ordinal) ||
(current.Length > resolvedRoot.Length && current[resolvedRoot.Length] != Path.DirectorySeparatorChar))
{
return true;
}
Expand All @@ -552,13 +539,18 @@ private static bool FilePathEscapesDirectory(string destinationDirectoryPath, st

private static string ResolveSymlink(string path)
{
if (IsExistingNonLink(path))
{
return path;
}

var info = new FileInfo(path);

// Check LinkTarget first so dangling symlinks/junctions (whose final target doesn't exist yet)
// are still resolved to their raw target, rather than being treated as a non-link.
if (info.LinkTarget is null)
{
return Path.GetFullPath(path);
return info.FullName;
}

FileSystemInfo target = info.ResolveLinkTarget(returnFinalTarget: true) ?? info;
Expand All @@ -577,13 +569,18 @@ private static string ResolvePhysicalPath(string path)
return fullPath;
}

string[] components = fullPath.Substring(root.Length)
.Split(new char[] { Path.DirectorySeparatorChar, Path.AltDirectorySeparatorChar }, StringSplitOptions.RemoveEmptyEntries);
ReadOnlySpan<char> relative = fullPath.AsSpan(root.Length);
string current = root;
foreach (string component in components)
foreach (Range range in relative.SplitAny(Path.DirectorySeparatorChar, Path.AltDirectorySeparatorChar))
{
current = Path.Combine(current, component);
if (Path.Exists(current))
ReadOnlySpan<char> component = relative[range];
if (component.IsEmpty)
{
continue;
}

current = Path.Join(current, component);
if (!IsExistingNonLink(current) && Path.Exists(current))
{
current = ResolveSymlink(current);
}
Expand Down Expand Up @@ -779,9 +776,8 @@ private void ExtractAsRegularFile(string destinationFileName)
// Important: The DataStream will be written from its current position
DataStream?.CopyTo(fs);
}
AttemptSetLastWriteTime(fs.SafeFileHandle, ModificationTime);
}

AttemptSetLastWriteTime(destinationFileName, ModificationTime);
}

// Asynchronously extracts the current entry as a regular file into the specified destination.
Expand All @@ -806,16 +802,17 @@ private async Task ExtractAsRegularFileAsync(string destinationFileName, Cancell
// Important: The DataStream will be written from its current position
await DataStream.CopyToAsync(fs, cancellationToken).ConfigureAwait(false);
}
// Exposing the handle otherwise flushes buffered data synchronously.
await fs.FlushAsync(cancellationToken).ConfigureAwait(false);
AttemptSetLastWriteTime(fs.SafeFileHandle, ModificationTime);
}

AttemptSetLastWriteTime(destinationFileName, ModificationTime);
}

private static void AttemptSetLastWriteTime(string destinationFileName, DateTimeOffset lastWriteTime)
private static void AttemptSetLastWriteTime(SafeFileHandle fileHandle, DateTimeOffset lastWriteTime)
{
try
{
File.SetLastWriteTime(destinationFileName, lastWriteTime.UtcDateTime);
File.SetLastWriteTime(fileHandle, lastWriteTime.UtcDateTime);
}
catch
{
Expand All @@ -838,6 +835,12 @@ private FileStreamOptions CreateFileStreamOptions(bool isAsync)
Options = isAsync ? FileOptions.Asynchronous : FileOptions.None
};

if (_header._gnuSparseDataStream is null && fileStreamOptions.PreallocationSize < fileStreamOptions.BufferSize)
{
// Sizes 0 and 1 disable buffering needed by short-reading streams.
fileStreamOptions.BufferSize = (int)Math.Max(fileStreamOptions.PreallocationSize, 2);
}
Comment thread
JeremyKuhne marked this conversation as resolved.
Resolved

if (!OperatingSystem.IsWindows())
{
const UnixFileMode OwnershipPermissions =
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,12 @@ namespace System.Formats.Tar
/// </summary>
public static class TarFile
{
// Batch small archive writes. In warm paired runs, 32 KiB cut tiny-file async creation
// time by ~11% on Windows and ~5% on Linux versus 4 KiB. 64 KiB added ~2% for Windows SDK
// async creation and ~1-2% for tiny files on Windows, with no clear tiny-file gain on Linux.
// Prefer smaller per-archive allocations and avoid the large object heap costs of buffers >= 128 KiB.
private const int ArchiveBufferSize = 32 * 1024;

/// <inheritdoc cref="CreateFromDirectory(string, Stream, bool, TarEntryFormat)" />
public static void CreateFromDirectory(string sourceDirectoryName, Stream destination, bool includeBaseDirectory)
=> CreateFromDirectory(sourceDirectoryName, destination, includeBaseDirectory, TarEntryFormat.Pax);
Expand Down Expand Up @@ -194,7 +200,7 @@ public static void CreateFromDirectory(string sourceDirectoryName, string destin
}

// Throws if the destination file exists
using FileStream fs = new(destinationFileName, FileMode.CreateNew, FileAccess.Write);
using FileStream fs = new(destinationFileName, FileMode.CreateNew, FileAccess.Write, FileShare.Read, ArchiveBufferSize);

CreateFromDirectoryInternal(sourceDirectoryName, fs, includeBaseDirectory, leaveOpen: false, options);
}
Expand Down Expand Up @@ -538,6 +544,7 @@ private static async Task CreateFromDirectoryInternalAsync(string sourceDirector
{
Access = FileAccess.Write,
Mode = FileMode.CreateNew,
BufferSize = ArchiveBufferSize,
Options = FileOptions.Asynchronous,
};
// Throws if the destination file exists
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -28,6 +28,7 @@ internal struct ExtractState
internal SortedDictionary<string, UnixFileMode>? PendingModes;
internal Stack<(string, DateTimeOffset)> DirectoryModificationTimes;
internal TarHardLinkMode HardLinkMode;
internal string? ResolvedDestinationDirectoryPath;
// Allocated lazily on the first deferred symlink; most archives have none.
internal Dictionary<FileId, (string SymlinkPath, string LinkTarget)>? PendingLinks;

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -121,7 +121,7 @@ private TarEntry ConstructEntryForWriting(string fullPath, string entryName, Fil
if (entry.EntryType is TarEntryType.RegularFile or TarEntryType.V7RegularFile)
{
Debug.Assert(entry._header._dataStream == null);
entry._header._dataStream = new FileStream(fullPath, FileMode.Open, FileAccess.Read, FileShare.Read, 4096, fileOptions);
entry._header._dataStream = new FileStream(fullPath, FileMode.Open, FileAccess.Read, FileShare.Read, 0, fileOptions);
}

return entry;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -134,7 +134,8 @@ private TarEntry ConstructEntryForWriting(string fullPath, string entryName, Fil
Debug.Assert(entry._header._dataStream == null);
try
{
entry._header._dataStream = new FileStream(fullPath, FileMode.Open, FileAccess.Read, FileShare.Read, 4096, fileOptions);
entry._header._dataStream = new FileStream(fullPath, FileMode.Open, FileAccess.Read, FileShare.Read, 0,
fileOptions | FileOptions.SequentialScan);
}
catch (Exception e) when ((attributes & FileAttributes.ReparsePoint) != 0 && (e is IOException or UnauthorizedAccessException))
{
Expand Down
Loading
Loading