Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Directory.CreateDirectory: create missing parents using default UnixFileMode. #74002

Merged
merged 7 commits into from
Aug 19, 2022
Merged
Show file tree
Hide file tree
Changes from 2 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 @@ -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;
pendingModes[fullPath] = mode.Value;
}
}
return;
}

// Missing parents are created using default permissions.
tmds marked this conversation as resolved.
Show resolved Hide resolved
if (mode.HasValue)
{
// Ensure we have sufficient permissions to extract in the directory.
Expand All @@ -106,28 +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;
}

string parentDir = Path.GetDirectoryName(fullPath)!;
string rootDir = Path.GetPathRoot(parentDir)!;
bool hasMissingParents = false;
for (string dir = parentDir; dir != rootDir && !Directory.Exists(dir); dir = Path.GetDirectoryName(dir)!)
{
pendingModes.Add(dir, DefaultDirectoryMode);
hasMissingParents = true;
Directory.CreateDirectory(fullPath, mode.Value);
}

if (hasMissingParents)
else
{
Directory.CreateDirectory(parentDir, ExtractPermissions);
// Create directory using default permissions.
tmds marked this conversation as resolved.
Show resolved Hide resolved
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.");
tmds marked this conversation as resolved.
Show resolved Hide resolved
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);
tmds marked this conversation as resolved.
Show resolved Hide resolved
}

[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;
tmds marked this conversation as resolved.
Show resolved Hide resolved
}

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

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -39,6 +39,21 @@ public void CreateDoesntChangeExistingMode()
Assert.Equal(initialMode, sameDir.UnixFileMode);
}

[Fact]
public void MissingParentsHaveDefaultPermissions()
{
string parent = GetRandomDirPath();
string child = Path.Combine(parent, "child");

const UnixFileMode childMode = UnixFileMode.UserRead | UnixFileMode.UserExecute;
DirectoryInfo childDir = Directory.CreateDirectory(child, childMode);

Assert.Equal(childMode, childDir.UnixFileMode);

UnixFileMode defaultPermissions = Directory.CreateDirectory(GetRandomDirPath()).UnixFileMode;
Assert.Equal(defaultPermissions, File.GetUnixFileMode(parent));
}
tmds marked this conversation as resolved.
Show resolved Hide resolved

[Theory]
[InlineData((UnixFileMode)(1 << 12), false)]
[InlineData((UnixFileMode)(1 << 12), true)]
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -328,7 +328,7 @@ private static void CreateParentsAndDirectory(string fullPath, UnixFileMode unix
}

ReadOnlySpan<char> mkdirPath = fullPath.AsSpan(0, i);
int result = Interop.Sys.MkDir(mkdirPath, (int)unixCreateMode);
int result = Interop.Sys.MkDir(mkdirPath, (int)DefaultUnixCreateDirectoryMode);
if (result == 0)
{
break; // Created parent.
Expand Down Expand Up @@ -360,7 +360,8 @@ private static void CreateParentsAndDirectory(string fullPath, UnixFileMode unix
for (i = stackDir.Length - 1; i >= 0; i--)
{
ReadOnlySpan<char> mkdirPath = fullPath.AsSpan(0, stackDir[i]);
int result = Interop.Sys.MkDir(mkdirPath, (int)unixCreateMode);
UnixFileMode mode = i == 0 ? unixCreateMode : DefaultUnixCreateDirectoryMode;
int result = Interop.Sys.MkDir(mkdirPath, (int)mode);
if (result < 0)
{
Interop.ErrorInfo errorInfo = Interop.Sys.GetLastErrorInfo();
Expand Down