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
68 changes: 68 additions & 0 deletions src/PathRoot/PathRoot.cs
Original file line number Diff line number Diff line change
Expand Up @@ -79,6 +79,13 @@ private protected abstract void CreateSymbolicLinkAt(
bool targetIsDirectory
);

private protected abstract void CreateHardLinkAt(
nint parent,
string path,
nint targetParent,
string pathToTarget
);

private protected abstract string GetSymbolicLinkTargetAt(nint parent, string name);

private protected abstract void MoveAt(
Expand Down Expand Up @@ -343,6 +350,67 @@ private void CreateSymbolicLink(string path, string pathToTarget, bool targetIsD
);
}

/// <summary>
/// Creates a hard link to an existing file relative to this root.
/// </summary>
/// <param name="path">The path of the new hard link, relative to this root.</param>
/// <param name="pathToTarget">
/// The path of the existing file, relative to this root.
/// </param>
/// <remarks>
/// Both paths are confined to this root. The target must be on the same
/// filesystem as the new link. If the target is a symbolic link, the hard
/// link refers to the symbolic link itself rather than its target.
/// </remarks>
public void CreateHardLink(string path, string pathToTarget)
{
ValidatePathArgument(path, nameof(path));
ValidatePathArgument(pathToTarget, nameof(pathToTarget));

Resolve(
pathToTarget,
createParents: false,
(Root: this, Path: path, PathToTarget: pathToTarget),
static (state, targetParent, targetName, targetEndsInSeparator) =>
{
if (targetEndsInSeparator)
{
throw new IOException(
$"The hard-link target path '{state.PathToTarget}' ends in a directory separator."
);
}

return state.Root.Resolve(
state.Path,
createParents: false,
(
Root: state.Root,
Path: state.Path,
TargetParent: targetParent,
TargetName: targetName
),
static (linkState, parent, name, endsInSeparator) =>
{
if (endsInSeparator)
{
throw new IOException(
$"The hard-link path '{linkState.Path}' ends in a directory separator."
);
}

linkState.Root.CreateHardLinkAt(
parent,
name,
linkState.TargetParent,
linkState.TargetName
);
return 0;
}
);
}
);
}

/// <summary>
/// Gets the target stored in a symbolic link relative to this root.
/// </summary>
Expand Down
8 changes: 6 additions & 2 deletions src/PathRoot/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -23,8 +23,12 @@ using FileStream stream = output.CreateFile("result.txt");

The API uses file- and directory-specific .NET-style names, including
`CreateDirectory`, `CreateSubRoot`, `CreateFileSymbolicLink`,
`CreateDirectorySymbolicLink`, `MoveFile`, `MoveDirectory`, `DeleteFile`,
`DeleteDirectory`, and `GetSymbolicLinkTarget`.
`CreateDirectorySymbolicLink`, `CreateHardLink`, `MoveFile`, `MoveDirectory`,
`DeleteFile`, `DeleteDirectory`, and `GetSymbolicLinkTarget`.

Both paths passed to `CreateHardLink` are relative to the root. The target must
be on the same filesystem as the new link. If the target is a symbolic link,
the hard link refers to the symbolic link itself rather than traversing it.

The root remains attached to the directory that was opened even if that
directory is subsequently renamed. Operations may traverse mount points and
Expand Down
2 changes: 1 addition & 1 deletion src/PathRoot/StaticCs.PathRoot.csproj
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<TargetFramework>net8.0</TargetFramework>
<Version>0.1.0</Version>
<Version>0.1.1</Version>
<IsPackable>true</IsPackable>
<PackageLicenseExpression>BSD-3-Clause</PackageLicenseExpression>
<RepositoryUrl>https://github.com/agocke/static-cs</RepositoryUrl>
Expand Down
40 changes: 40 additions & 0 deletions src/PathRoot/UnixPathRoot.cs
Original file line number Diff line number Diff line change
Expand Up @@ -131,6 +131,31 @@ bool targetIsDirectory
}
}

private protected override void CreateHardLinkAt(
nint parent,
string path,
nint targetParent,
string pathToTarget
)
{
int result;
do
{
result = NativeMethods.LinkAt(
targetParent.ToInt32(),
pathToTarget,
parent.ToInt32(),
path,
0
);
} while (result < 0 && Marshal.GetLastPInvokeError() == NativeErrors.Interrupted);

if (result != 0)
{
throw NativeError("linkat", path);
}
}

private protected override string GetSymbolicLinkTargetAt(nint parent, string name)
{
if (TryGetLinkTarget(parent, name, out string? target, out int error))
Expand Down Expand Up @@ -622,6 +647,21 @@ internal static safe extern int SymlinkAt(
string newPath
);

[DllImport(
LibC,
EntryPoint = "linkat",
SetLastError = true,
CharSet = CharSet.Ansi,
ExactSpelling = true
)]
internal static safe extern int LinkAt(
int oldDirectory,
string oldPath,
int newDirectory,
string newPath,
int flags
);

[DllImport(
LibC,
EntryPoint = "readlinkat",
Expand Down
47 changes: 46 additions & 1 deletion src/PathRoot/WindowsPathRoot.cs
Original file line number Diff line number Diff line change
Expand Up @@ -325,6 +325,49 @@ bool isRelative
});
}

private protected override void CreateHardLinkAt(
nint parent,
string path,
nint targetParent,
string pathToTarget
)
{
using SafeFileHandle target = OpenRelative(
targetParent,
pathToTarget,
desiredAccess: 0,
disposition: NativeConstants.FileOpen,
options: NativeConstants.FileOpenReparsePoint
| NativeConstants.FileOpenForBackupIntent
| NativeConstants.FileNonDirectoryFile,
preventReparse: false,
followSymbolicLink: false
);
byte[] information = CreateNameInformation(
firstValue: 0,
firstValueIsUInt32: false,
parent,
path
);

int status;
unsafe
{
fixed (byte* informationPointer = information)
{
status = NativeMethods.NtSetInformationFile(
target,
out _,
informationPointer,
(uint)information.Length,
NativeConstants.FileLinkInformation
);
}
}

ThrowIfFailed(status, "NtSetInformationFile(FileLinkInformation)", path);
}

private protected override string GetSymbolicLinkTargetAt(nint parent, string name)
{
using SafeFileHandle handle = OpenEntry(
Expand Down Expand Up @@ -1017,7 +1060,8 @@ string name
int lengthOffset = rootOffset + IntPtr.Size;
int nameOffset = lengthOffset + sizeof(uint);
byte[] nameBytes = Encoding.Unicode.GetBytes(name);
byte[] information = new byte[nameOffset + nameBytes.Length];
int minimumLength = nameOffset + sizeof(uint);
byte[] information = new byte[Math.Max(minimumLength, nameOffset + nameBytes.Length)];
Span<byte> span = information;

if (firstValueIsUInt32)
Expand Down Expand Up @@ -1398,6 +1442,7 @@ private static class NativeConstants
internal const uint FileEndOfFileInfo = 6;
internal const uint FileAttributeTagInfo = 9;
internal const uint FileRenameInformation = 10;
internal const uint FileLinkInformation = 11;
internal const uint FileDispositionInformation = 13;
internal const uint FileDispositionInformationEx = 64;
internal const uint FileRenameInformationEx = 65;
Expand Down
88 changes: 88 additions & 0 deletions test/test/PathRootTests.cs
Original file line number Diff line number Diff line change
Expand Up @@ -146,6 +146,92 @@ public void SymbolicLinksCannotEscapeRoot()
Assert.Throws<IOException>(() => root.OpenSubRoot("escape/"));
}

[Fact]
public void CreatesHardLinksRelativeToRoot()
{
using PathRoot root = PathRoot.Open(_testDirectory);
root.CreateDirectory("links");
File.WriteAllText(Path.Combine(_testDirectory, "target.txt"), "original");

root.CreateHardLink("links/link.txt", "target.txt");
root.CreateHardLink("x", "target.txt");
File.WriteAllText(Path.Combine(_testDirectory, "links", "link.txt"), "changed");

Assert.Equal("changed", File.ReadAllText(Path.Combine(_testDirectory, "target.txt")));
Assert.Equal("changed", File.ReadAllText(Path.Combine(_testDirectory, "x")));
root.DeleteFile("target.txt");
Assert.Equal(
"changed",
File.ReadAllText(Path.Combine(_testDirectory, "links", "link.txt"))
);
}

[Fact]
public void HardLinkPathsCannotEscapeRoot()
{
string outsideDirectory = CreateOutsideDirectory();
string outsideFile = Path.Combine(outsideDirectory, "outside.txt");
File.WriteAllText(outsideFile, "outside");

using PathRoot root = PathRoot.Open(_testDirectory);
File.WriteAllText(Path.Combine(_testDirectory, "target.txt"), "target");
root.CreateDirectorySymbolicLink("escape", outsideDirectory);

Assert.Throws<IOException>(() => root.CreateHardLink("escape/link.txt", "target.txt"));
Assert.Throws<IOException>(() => root.CreateHardLink("link.txt", "escape/outside.txt"));
Assert.Throws<IOException>(() => root.CreateHardLink("../link.txt", "target.txt"));
Assert.Throws<IOException>(() => root.CreateHardLink("link.txt", "../outside.txt"));
Assert.False(File.Exists(Path.Combine(outsideDirectory, "link.txt")));
Assert.False(File.Exists(Path.Combine(_testDirectory, "link.txt")));
}

[Fact]
public void HardLinkRequiresExistingFileAndNewDestination()
{
using PathRoot root = PathRoot.Open(_testDirectory);
root.CreateDirectory("directory");
File.WriteAllText(Path.Combine(_testDirectory, "target.txt"), "target");
File.WriteAllText(Path.Combine(_testDirectory, "existing.txt"), "existing");

Assert.ThrowsAny<IOException>(() => root.CreateHardLink("link.txt", "missing.txt"));
Assert.ThrowsAny<IOException>(() => root.CreateHardLink("link.txt", "directory"));
Assert.ThrowsAny<IOException>(() => root.CreateHardLink("existing.txt", "target.txt"));
}

[Fact]
public void CreatesHardLinkWhileTargetIsOpenWithoutDeleteSharing()
{
string targetPath = Path.Combine(_testDirectory, "target.txt");
File.WriteAllText(targetPath, "target");

using PathRoot root = PathRoot.Open(_testDirectory);
using FileStream target = File.Open(
targetPath,
FileMode.Open,
FileAccess.Read,
FileShare.Read
);

root.CreateHardLink("link.txt", "target.txt");

Assert.Equal("target", File.ReadAllText(Path.Combine(_testDirectory, "link.txt")));
}

[Fact]
public void HardLinkToSymbolicLinkDoesNotTraverseTarget()
{
string outsideDirectory = CreateOutsideDirectory();
string outsideFile = Path.Combine(outsideDirectory, "outside.txt");
File.WriteAllText(outsideFile, "outside");

using PathRoot root = PathRoot.Open(_testDirectory);
root.CreateFileSymbolicLink("symbolic-link", outsideFile);
root.CreateHardLink("hard-link", "symbolic-link");

Assert.Equal(outsideFile, root.GetSymbolicLinkTarget("hard-link"));
Assert.Throws<IOException>(() => root.OpenRead("hard-link"));
}

[Fact]
public void OpeningRootFollowsTheInitialSymbolicLink()
{
Expand Down Expand Up @@ -240,6 +326,8 @@ public void DestructiveOperationsRejectTrailingSeparators()
Assert.Throws<IOException>(() => root.DeleteFile("source.txt/"));
Assert.Throws<IOException>(() => root.MoveFile("source.txt/", "destination.txt"));
Assert.Throws<IOException>(() => root.MoveFile("source.txt", "destination.txt/"));
Assert.Throws<IOException>(() => root.CreateHardLink("link.txt/", "source.txt"));
Assert.Throws<IOException>(() => root.CreateHardLink("link.txt", "source.txt/"));

Assert.True(File.Exists(Path.Combine(_testDirectory, "source.txt")));
Assert.False(File.Exists(Path.Combine(_testDirectory, "destination.txt")));
Expand Down
Loading