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
stop using NtCreateFile as there is no public and reliable way of map…
…ping DOS to NT paths
  • Loading branch information
adamsitnik committed Jun 22, 2021
commit c763c895851c16ec7f9c0f3ecf3e562e3770a817
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.

internal static partial class Interop
{
internal static partial class Kernel32
{
// Value taken from https://docs.microsoft.com/en-us/windows/win32/api/fileapi/nf-fileapi-setfileinformationbyhandle#remarks:
internal const int FileAllocationInfo = 5;

internal struct FILE_ALLOCATION_INFO
{
internal long AllocationSize;
}
}
}
2 changes: 0 additions & 2 deletions src/libraries/Common/tests/Common.Tests.csproj
Original file line number Diff line number Diff line change
Expand Up @@ -109,8 +109,6 @@
<Compile Include="$(CommonPath)System\Net\StreamBuffer.cs" Link="Common\System\Net\StreamBuffer.cs" />
</ItemGroup>
<ItemGroup Condition="'$(TargetsWindows)'=='true'">
<Compile Include="$(CommonPath)Interop\Windows\Interop.UNICODE_STRING.cs"
Link="Common\Interop\Windows\Interop.UNICODE_STRING.cs" />
<Compile Include="$(CoreLibSharedDir)System\IO\PathInternal.Windows.cs"
Link="System\IO\PathInternal.Windows.cs" />
<Compile Include="$(CommonPath)Interop\Windows\Interop.Libraries.cs"
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -3,9 +3,6 @@

using System;
using System.IO;
using System.Linq;
using System.Runtime.InteropServices;
using System.Text;
using Xunit;

namespace Tests.System.IO
Expand Down Expand Up @@ -260,45 +257,5 @@ public void GetRootLengthDevice(string path, int length)
Assert.Equal(length + PathInternal.ExtendedPathPrefix.Length, PathInternal.GetRootLength(@"\\?\" + path));
Assert.Equal(length + PathInternal.ExtendedPathPrefix.Length, PathInternal.GetRootLength(@"\\.\" + path));
}

public static TheoryData<string, string> DosToNtPathTest_Data => new TheoryData<string, string>
{
{ @"C:\tests\file.cs", @"\??\C:\tests\file.cs" }, // typical path
{ @"\\?\C:\tests\file.cs", @"\??\C:\tests\file.cs" }, // NtPath with \\?\ prefix
{ @"\\.\device\file.cs", @"\??\device\file.cs" }, // device path with \\.\ prefix
{ @"\\server\file.cs", @"\??\UNC\server\file.cs" }, // UNC path with \\ prefix
{ @"\\?\UNC\server\file", @"\??\UNC\server\file" }, // extended UNC prefix
{ @"\??\C:\tests\file.cs", @"\??\C:\tests\file.cs" }, // NtPath with \??\ prefix (no changes required)
{ @"C:\", @"\??\C:\" }, // a short path
{ @"\\s", @"\??\UNC\s" }, // short UNC path
{ @"\\s\", @"\??\UNC\s\" }, // short UNC path with trailing
{ $@"C:\{string.Join("\\", Enumerable.Repeat("a", PathInternal.MaxShortPath + 1))}", $@"\??\C:\{string.Join("\\", Enumerable.Repeat("a", PathInternal.MaxShortPath + 1))}"}, // long path
};

[Theory, MemberData(nameof(DosToNtPathTest_Data))]
public void DosToNtPathTest(string path, string expected)
{
// first of all, we use an internal Windows API to ensure that expected value is valid
if (path.Length < PathInternal.MaxShortPath) // RtlDosPathNameToRelativeNtPathName_U_WithStatus does not support long paths
{
RtlDosPathNameToRelativeNtPathName_U_WithStatus(path, out Interop.UNICODE_STRING ntFileName, out IntPtr _, IntPtr.Zero);
try
{
Assert.Equal(expected, Marshal.PtrToStringUni(ntFileName.Buffer));
}
finally
{
Marshal.ZeroFreeGlobalAllocUnicode(ntFileName.Buffer);
}
}

// after that, we test our implementation
var vsb = new ValueStringBuilder(stackalloc char[PathInternal.MaxShortPath]);
PathInternal.DosToNtPath(path, ref vsb);
Assert.Equal(expected, vsb.ToString());

[DllImport(Interop.Libraries.NtDll, CharSet = CharSet.Unicode)]
static extern int RtlDosPathNameToRelativeNtPathName_U_WithStatus(string DosFileName, out Interop.UNICODE_STRING NtFileName, out IntPtr FilePart, IntPtr RelativeName);
}
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,8 @@
using System;
using System.Diagnostics;
using System.IO;
using System.Text;
using System.IO.Strategies;
using System.Runtime.InteropServices;
using System.Threading;

namespace Microsoft.Win32.SafeHandles
Expand All @@ -24,13 +25,6 @@ public SafeFileHandle(IntPtr preexistingHandle, bool ownsHandle) : base(ownsHand
SetHandle(preexistingHandle);
}

private SafeFileHandle(IntPtr preexistingHandle, bool ownsHandle, FileOptions fileOptions) : base(ownsHandle)
{
SetHandle(preexistingHandle);

_fileOptions = fileOptions;
}

public bool IsAsync => (GetFileOptions() & FileOptions.Asynchronous) != 0;

internal bool CanSeek => !IsClosed && GetFileType() == Interop.Kernel32.FileTypes.FILE_TYPE_DISK;
Expand All @@ -43,40 +37,106 @@ internal static unsafe SafeFileHandle Open(string fullPath, FileMode mode, FileA
{
using (DisableMediaInsertionPrompt.Create())
{
SafeFileHandle fileHandle = new SafeFileHandle(
NtCreateFile(fullPath, mode, access, share, options, preallocationSize),
ownsHandle: true,
options);
// we don't use NtCreateFile as there is no public and reliable way
// of converting DOS to NT file paths (RtlDosPathNameToRelativeNtPathName_U_WithStatus is not documented)
SafeFileHandle fileHandle = CreateFile(fullPath, mode, access, share, options);

if (FileStreamHelpers.ShouldPreallocate(preallocationSize, access, mode))
{
Preallocate(fullPath, preallocationSize, fileHandle);
}

fileHandle.InitThreadPoolBindingIfNeeded();

return fileHandle;
}
}

private static IntPtr NtCreateFile(string fullPath, FileMode mode, FileAccess access, FileShare share, FileOptions options, long preallocationSize)
private static unsafe SafeFileHandle CreateFile(string fullPath, FileMode mode, FileAccess access, FileShare share, FileOptions options)
{
Interop.Kernel32.SECURITY_ATTRIBUTES secAttrs = default;
Copy link
Contributor

Choose a reason for hiding this comment

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

default isn't really needed, right?

if ((share & FileShare.Inheritable) != 0)
{
secAttrs = new Interop.Kernel32.SECURITY_ATTRIBUTES
{
nLength = (uint)sizeof(Interop.Kernel32.SECURITY_ATTRIBUTES),
bInheritHandle = Interop.BOOL.TRUE
};
}

int fAccess =
((access & FileAccess.Read) == FileAccess.Read ? Interop.Kernel32.GenericOperations.GENERIC_READ : 0) |
((access & FileAccess.Write) == FileAccess.Write ? Interop.Kernel32.GenericOperations.GENERIC_WRITE : 0);

// Our Inheritable bit was stolen from Windows, but should be set in
// the security attributes class. Don't leave this bit set.
share &= ~FileShare.Inheritable;

// Must use a valid Win32 constant here...
if (mode == FileMode.Append)
{
mode = FileMode.OpenOrCreate;
}

int flagsAndAttributes = (int)options;

// For mitigating local elevation of privilege attack through named pipes
// make sure we always call CreateFile with SECURITY_ANONYMOUS so that the
// named pipe server can't impersonate a high privileged client security context
// (note that this is the effective default on CreateFile2)
flagsAndAttributes |= (Interop.Kernel32.SecurityOptions.SECURITY_SQOS_PRESENT | Interop.Kernel32.SecurityOptions.SECURITY_ANONYMOUS);

SafeFileHandle fileHandle = Interop.Kernel32.CreateFile(fullPath, fAccess, share, &secAttrs, mode, flagsAndAttributes, IntPtr.Zero);
if (fileHandle.IsInvalid)
{
// Return a meaningful exception with the full path.

// NT5 oddity - when trying to open "C:\" as a Win32FileStream,
// we usually get ERROR_PATH_NOT_FOUND from the OS. We should
// probably be consistent w/ every other directory.
int errorCode = Marshal.GetLastPInvokeError();

if (errorCode == Interop.Errors.ERROR_PATH_NOT_FOUND && fullPath!.Length == PathInternal.GetRootLength(fullPath))
Copy link
Member

Choose a reason for hiding this comment

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

Suggested change
if (errorCode == Interop.Errors.ERROR_PATH_NOT_FOUND && fullPath!.Length == PathInternal.GetRootLength(fullPath))
if (errorCode == Interop.Errors.ERROR_PATH_NOT_FOUND && fullPath.Length == PathInternal.GetRootLength(fullPath))

{
errorCode = Interop.Errors.ERROR_ACCESS_DENIED;
}

throw Win32Marshal.GetExceptionForWin32Error(errorCode, fullPath);
}

fileHandle._fileOptions = options;
return fileHandle;
}

private static unsafe void Preallocate(string fullPath, long preallocationSize, SafeFileHandle fileHandle)
{
var vsb = new ValueStringBuilder(stackalloc char[PathInternal.MaxShortPath]);

PathInternal.DosToNtPath(fullPath, ref vsb);

(uint ntStatus, IntPtr fileHandle) = Interop.NtDll.NtCreateFile(vsb.AsSpan(), mode, access, share, options, preallocationSize);
vsb.Dispose();

switch (ntStatus)
{
case Interop.StatusOptions.STATUS_SUCCESS:
return fileHandle;
case Interop.StatusOptions.STATUS_DISK_FULL:
throw new IOException(SR.Format(SR.IO_DiskFull_Path_AllocationSize, fullPath, preallocationSize));
// NtCreateFile has a bug and it reports STATUS_INVALID_PARAMETER for files
// that are too big for the current file system. Example: creating a 4GB+1 file on a FAT32 drive.
case Interop.StatusOptions.STATUS_INVALID_PARAMETER when preallocationSize > 0:
case Interop.StatusOptions.STATUS_FILE_TOO_LARGE:
throw new IOException(SR.Format(SR.IO_FileTooLarge_Path_AllocationSize, fullPath, preallocationSize));
default:
int error = (int)Interop.NtDll.RtlNtStatusToDosError((int)ntStatus);
throw Win32Marshal.GetExceptionForWin32Error(error, fullPath);
var allocationInfo = new Interop.Kernel32.FILE_ALLOCATION_INFO
{
AllocationSize = preallocationSize
};

if (!Interop.Kernel32.SetFileInformationByHandle(
fileHandle,
Interop.Kernel32.FileAllocationInfo,
&allocationInfo,
(uint)sizeof(Interop.Kernel32.FILE_ALLOCATION_INFO)))
{
int errorCode = Marshal.GetLastPInvokeError();

// we try to mimic the atomic NtCreateFile here:
// if preallocation fails, close the handle and delete the file
fileHandle.Dispose();
Interop.Kernel32.DeleteFile(fullPath);

switch (errorCode)
{
case Interop.Errors.ERROR_DISK_FULL:
throw new IOException(SR.Format(SR.IO_DiskFull_Path_AllocationSize, fullPath, preallocationSize));
case Interop.Errors.ERROR_FILE_TOO_LARGE:
throw new IOException(SR.Format(SR.IO_FileTooLarge_Path_AllocationSize, fullPath, preallocationSize));
default:
throw Win32Marshal.GetExceptionForWin32Error(errorCode, fullPath);
}
}
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -1426,6 +1426,9 @@
<Compile Include="$(CommonPath)Interop\Windows\Kernel32\Interop.FILE_BASIC_INFO.cs">
<Link>Common\Interop\Windows\Kernel32\Interop.FILE_BASIC_INFO.cs</Link>
</Compile>
<Compile Include="$(CommonPath)Interop\Windows\Kernel32\Interop.FILE_ALLOCATION_INFO.cs">
<Link>Common\Interop\Windows\Kernel32\Interop.FILE_ALLOCATION_INFO.cs</Link>
</Compile>
<Compile Include="$(CommonPath)Interop\Windows\Kernel32\Interop.FILE_END_OF_FILE_INFO.cs">
<Link>Common\Interop\Windows\Kernel32\Interop.FILE_END_OF_FILE_INFO.cs</Link>
</Compile>
Expand Down Expand Up @@ -1612,6 +1615,9 @@
<Compile Include="$(CommonPath)Interop\Windows\Interop.UNICODE_STRING.cs">
<Link>Common\Interop\Windows\Interop.UNICODE_STRING.cs</Link>
</Compile>
<Compile Include="$(CommonPath)Interop\Windows\Kernel32\Interop.SecurityOptions.cs">
<Link>Common\Interop\Windows\Kernel32\Interop.SecurityOptions.cs</Link>
</Compile>
<Compile Include="$(CommonPath)Interop\Windows\Interop.SECURITY_QUALITY_OF_SERVICE.cs">
<Link>Common\Interop\Windows\Interop.SECURITY_QUALITY_OF_SERVICE.cs</Link>
</Compile>
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -47,7 +47,6 @@ internal static partial class PathInternal
internal const string DirectorySeparatorCharAsString = "\\";

internal const string ExtendedPathPrefix = @"\\?\";
internal const string NtPrefix = @"\??\";
internal const string UncPathPrefix = @"\\";
internal const string UncExtendedPrefixToInsert = @"?\UNC\";
internal const string UncExtendedPathPrefix = @"\\?\UNC\";
Expand Down Expand Up @@ -410,34 +409,5 @@ internal static bool IsEffectivelyEmpty(ReadOnlySpan<char> path)
}
return true;
}

// this method works only for `fullPath` returned by Path.GetFullPath
// currently we don't have interest in supporting relative paths
internal static void DosToNtPath(ReadOnlySpan<char> fullPath, ref ValueStringBuilder vsb)
{
vsb.Append(NtPrefix);

if (fullPath.Length >= 3 && fullPath[0] == '\\' && fullPath[1] == '\\')
{
// \\.\ (Device) or \\?\ (NtPath)
if (fullPath.Length >= 4 && fullPath[3] == '\\' && (fullPath[2] == '.' || fullPath[2] == '?'))
{
vsb.Append(fullPath.Slice(NtPrefix.Length));
}
else // \\ (UNC)
{
vsb.Append(@"UNC\");
vsb.Append(fullPath.Slice(2));
}
}
else if (fullPath.Length >= 4 && fullPath[0] == '\\' && fullPath[1] == '?' && fullPath[2] == '?' && fullPath[3] == '\\') // \??\
{
vsb.Append(fullPath.Slice(NtPrefix.Length));
}
else
{
vsb.Append(fullPath);
}
}
}
}