Skip to content
Merged
Show file tree
Hide file tree
Changes from 1 commit
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
Prev Previous commit
Next Next commit
Simplify TarHelpers.CreateDirectory.
  • Loading branch information
tmds committed Aug 17, 2022
commit 253e68abaae9f19d2907c4255059b618e4eea720
Original file line number Diff line number Diff line change
Expand Up @@ -47,57 +47,41 @@ public int Compare (string? x, string? y)

private static UnixFileMode UMask => s_umask.Value;

/*
Tar files are usually ordered: parent directories come before their child entries.

They may be unordered. In that case we need to create parent directories before
we know the proper permissions for these directories.

We create these directories with restrictive permissions. If we encounter an entry for
the directory later, we store the mode to apply it later.

If the archive doesn't have an entry for the parent directory, we use the default mask.

The pending modes to be applied are tracked through a reverse-sorted dictionary.
The reverse order is needed to apply permissions to children before their parent.
Otherwise we may apply a restrictive mask to the parent, that prevents us from
changing a child.
*/

// Use a reverse-sorted dictionary to apply permission to children before their parents.
// Otherwise we may apply a restrictive mask to the parent, that prevents us from changing a child.
internal static SortedDictionary<string, UnixFileMode>? CreatePendingModesDictionary()
=> new SortedDictionary<string, UnixFileMode>(s_reverseStringComparer);

internal static void CreateDirectory(string fullPath, UnixFileMode? mode, bool overwriteMetadata, SortedDictionary<string, UnixFileMode>? pendingModes)
{
// Restrictive mask for creating the missing parent directories while extracting.
// Minimal permissions required for extracting.
const UnixFileMode ExtractPermissions = UnixFileMode.UserRead | UnixFileMode.UserWrite | UnixFileMode.UserExecute;

Debug.Assert(pendingModes is not null);

if (Directory.Exists(fullPath))
{
// Apply permissions to an existing directory when we're overwriting metadata
// or the directory was created as a missing parent (stored in pendingModes).
Comment on lines -79 to -80
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

If the directory existed prior to TarFile.ExtractToDirectory(), with overwrite:false we don't throw exception? Documentation for overwriteFiles param says otherwise:

true to overwrite files and directories in destinationDirectoryName; false to avoid overwriting, and throw if any files or directories are found with existing names.

Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Yes.

The behavior is the same as tar. When not passing the --overwrite flag, t doesn't give an error when extracting a directory that already exists, and it does set the mode of that directory.

if (mode.HasValue)
// Apply permissions to an existing directory when we're overwriting metadata.
if (mode.HasValue && overwriteMetadata)
{
// Ensure we have sufficient permissions to extract in the directory.
bool hasExtractPermissions = (mode.Value & ExtractPermissions) == ExtractPermissions;
if (hasExtractPermissions)
{
bool removed = pendingModes.Remove(fullPath);
if (overwriteMetadata || removed)
{
UnixFileMode umask = UMask;
File.SetUnixFileMode(fullPath, mode.Value & ~umask);
}
pendingModes.Remove(fullPath);

UnixFileMode umask = UMask;
File.SetUnixFileMode(fullPath, mode.Value & ~umask);
}
else if (overwriteMetadata || pendingModes.ContainsKey(fullPath))
else
{
pendingModes[fullPath] = mode.Value;
}
}
return;
}

// Missing parents are created using default permissions.
if (mode.HasValue)
{
// Ensure we have sufficient permissions to extract in the directory.
Expand All @@ -106,33 +90,14 @@ internal static void CreateDirectory(string fullPath, UnixFileMode? mode, bool o
pendingModes[fullPath] = mode.Value;
mode = ExtractPermissions;
}
}
else
{
pendingModes.Add(fullPath, DefaultDirectoryMode);
mode = ExtractPermissions;
}

// Create missing parents with ExtractPermissions and add them to be set to
// DefaultDirectoryMode if they are not present in the archive later.
string parentDir = Path.GetDirectoryName(fullPath)!;
string rootDir = Path.GetPathRoot(parentDir)!;
Stack<string>? missingParents = null;
for (string dir = parentDir; dir != rootDir && !Directory.Exists(dir); dir = Path.GetDirectoryName(dir)!)
{
pendingModes.Add(dir, DefaultDirectoryMode);
missingParents ??= new Stack<string>();
missingParents.Push(dir);
Directory.CreateDirectory(fullPath, mode.Value);
}
if (missingParents is not null)
else
{
while (missingParents.TryPop(out string? dir))
{
Directory.CreateDirectory(dir, ExtractPermissions);
}
// Create directory using default permissions.
Directory.CreateDirectory(fullPath);
}

Directory.CreateDirectory(fullPath, mode.Value);
}

internal static void SetPendingModes(SortedDictionary<string, UnixFileMode>? pendingModes)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -216,20 +216,16 @@ public void UnixFileModes(bool overwrite)
Assert.True(File.Exists(filePath), $"{filePath}' does not exist.");
AssertFileModeEquals(filePath, TestPermission2);

// Missing parents are created with DefaultDirectoryMode.
// The mode is not set when overwrite == true if there is no entry and the directory exists before extracting.
// Missing parents are created with CreateDirectoryDefaultMode.
Assert.True(Directory.Exists(missingParentPath), $"{missingParentPath}' does not exist.");
if (!overwrite)
{
AssertFileModeEquals(missingParentPath, DefaultDirectoryMode);
}
AssertFileModeEquals(missingParentPath, CreateDirectoryDefaultMode);

Assert.True(Directory.Exists(missingParentDirPath), $"{missingParentDirPath}' does not exist.");
AssertFileModeEquals(missingParentDirPath, TestPermission3);

// Directory modes that are out-of-order are still applied.
Assert.True(Directory.Exists(outOfOrderDirPath), $"{outOfOrderDirPath}' does not exist.");
AssertFileModeEquals(outOfOrderDirPath, TestPermission4);
AssertFileModeEquals(outOfOrderDirPath, overwrite ? TestPermission4 : CreateDirectoryDefaultMode);
}

[Theory]
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -191,8 +191,10 @@ public async Task ExtractArchiveWithEntriesThatStartWithSlashDotPrefix_Async()
}
}

[Fact]
public async Task UnixFileModes_Async()
[Theory]
[InlineData(true)]
[InlineData(false)]
public async Task UnixFileModes_Async(bool overwrite)
{
using TempDirectory source = new TempDirectory();
using TempDirectory destination = new TempDirectory();
Expand Down Expand Up @@ -223,29 +225,38 @@ public async Task UnixFileModes_Async()
writer.WriteEntry(outOfOrderDir);
}

await TarFile.ExtractToDirectoryAsync(archivePath, destination.Path, overwriteFiles: false);

string dirPath = Path.Join(destination.Path, "dir");
Assert.True(Directory.Exists(dirPath), $"{dirPath}' does not exist.");
string filePath = Path.Join(destination.Path, "file");
string missingParentPath = Path.Join(destination.Path, "missing_parent");
string missingParentDirPath = Path.Join(missingParentPath, "dir");
string outOfOrderDirPath = Path.Join(destination.Path, "out_of_order_parent");

if (overwrite)
{
File.OpenWrite(filePath).Dispose();
Directory.CreateDirectory(dirPath);
Directory.CreateDirectory(missingParentDirPath);
Directory.CreateDirectory(outOfOrderDirPath);
}

await TarFile.ExtractToDirectoryAsync(archivePath, destination.Path, overwriteFiles: overwrite);

Assert.True(Directory.Exists(dirPath), $"{dirPath}' does not exist.");
AssertFileModeEquals(dirPath, TestPermission1);

string filePath = Path.Join(destination.Path, "file");
Assert.True(File.Exists(filePath), $"{filePath}' does not exist.");
AssertFileModeEquals(filePath, TestPermission2);

// Missing parents are created with DefaultDirectoryMode.
string missingParentPath = Path.Join(destination.Path, "missing_parent");
// Missing parents are created with CreateDirectoryDefaultMode.
Assert.True(Directory.Exists(missingParentPath), $"{missingParentPath}' does not exist.");
AssertFileModeEquals(missingParentPath, DefaultDirectoryMode);
AssertFileModeEquals(missingParentPath, CreateDirectoryDefaultMode);

string missingParentDirPath = Path.Join(missingParentPath, "dir");
Assert.True(Directory.Exists(missingParentDirPath), $"{missingParentDirPath}' does not exist.");
AssertFileModeEquals(missingParentDirPath, TestPermission3);

// Directory modes that are out-of-order are still applied.
string outOfOrderDirPath = Path.Join(destination.Path, "out_of_order_parent");
Assert.True(Directory.Exists(outOfOrderDirPath), $"{outOfOrderDirPath}' does not exist.");
AssertFileModeEquals(outOfOrderDirPath, TestPermission4);
AssertFileModeEquals(outOfOrderDirPath, overwrite ? TestPermission4 : CreateDirectoryDefaultMode);
}

[Fact]
Expand Down
7 changes: 7 additions & 0 deletions src/libraries/System.Formats.Tar/tests/TarTestsBase.cs
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,8 @@ public abstract partial class TarTestsBase : FileCleanupTestBase
protected const UnixFileMode DefaultFileMode = UnixFileMode.UserRead | UnixFileMode.UserWrite | UnixFileMode.GroupRead | UnixFileMode.OtherRead; // 644 in octal, internally used as default
protected const UnixFileMode DefaultDirectoryMode = DefaultFileMode | UnixFileMode.UserExecute | UnixFileMode.GroupExecute | UnixFileMode.OtherExecute; // 755 in octal, internally used as default

protected readonly UnixFileMode CreateDirectoryDefaultMode; // Mode of directories created using Directory.CreateDirectory(string).

// Mode assumed for files and directories on Windows.
protected const UnixFileMode DefaultWindowsMode = DefaultFileMode | UnixFileMode.UserExecute | UnixFileMode.GroupExecute | UnixFileMode.OtherExecute; // 755 in octal, internally used as default

Expand Down Expand Up @@ -115,6 +117,11 @@ public enum TestTarFormat

protected static bool IsNotLinuxBionic => !PlatformDetection.IsLinuxBionic;

protected TarTestsBase()
{
CreateDirectoryDefaultMode = PlatformDetection.IsWindows ? UnixFileMode.None : Directory.CreateDirectory(GetRandomDirPath()).UnixFileMode;
}

protected static string GetTestCaseUnarchivedFolderPath(string testCaseName) =>
Path.Join(Directory.GetCurrentDirectory(), "unarchived", testCaseName);

Expand Down