-
Notifications
You must be signed in to change notification settings - Fork 4.8k
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
[FileStream] handle UNC and device paths #54483
Merged
Merged
Changes from all commits
Commits
Show all changes
2 commits
Select commit
Hold shift + click to select a range
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
16 changes: 16 additions & 0 deletions
16
src/libraries/Common/src/Interop/Windows/Kernel32/Interop.FILE_ALLOCATION_INFO.cs
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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; | ||
} | ||
} | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change | ||||
---|---|---|---|---|---|---|
|
@@ -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 | ||||||
|
@@ -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; | ||||||
|
@@ -43,59 +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) | ||||||
{ | ||||||
uint ntStatus; | ||||||
IntPtr fileHandle; | ||||||
Interop.Kernel32.SECURITY_ATTRIBUTES secAttrs = default; | ||||||
if ((share & FileShare.Inheritable) != 0) | ||||||
{ | ||||||
secAttrs = new Interop.Kernel32.SECURITY_ATTRIBUTES | ||||||
{ | ||||||
nLength = (uint)sizeof(Interop.Kernel32.SECURITY_ATTRIBUTES), | ||||||
bInheritHandle = Interop.BOOL.TRUE | ||||||
}; | ||||||
} | ||||||
|
||||||
const string MandatoryNtPrefix = @"\??\"; | ||||||
if (fullPath.StartsWith(MandatoryNtPrefix, StringComparison.Ordinal)) | ||||||
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) | ||||||
{ | ||||||
(ntStatus, fileHandle) = Interop.NtDll.NtCreateFile(fullPath, mode, access, share, options, preallocationSize); | ||||||
mode = FileMode.OpenOrCreate; | ||||||
} | ||||||
else | ||||||
|
||||||
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) | ||||||
{ | ||||||
var vsb = new ValueStringBuilder(stackalloc char[256]); | ||||||
vsb.Append(MandatoryNtPrefix); | ||||||
// Return a meaningful exception with the full path. | ||||||
|
||||||
if (fullPath.StartsWith(@"\\?\", StringComparison.Ordinal)) // NtCreateFile does not support "\\?\" prefix, only "\??\" | ||||||
{ | ||||||
vsb.Append(fullPath.AsSpan(4)); | ||||||
} | ||||||
else | ||||||
// 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)) | ||||||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more.
Suggested change
|
||||||
{ | ||||||
vsb.Append(fullPath); | ||||||
errorCode = Interop.Errors.ERROR_ACCESS_DENIED; | ||||||
} | ||||||
|
||||||
(ntStatus, fileHandle) = Interop.NtDll.NtCreateFile(vsb.AsSpan(), mode, access, share, options, preallocationSize); | ||||||
vsb.Dispose(); | ||||||
throw Win32Marshal.GetExceptionForWin32Error(errorCode, fullPath); | ||||||
stephentoub marked this conversation as resolved.
Show resolved
Hide resolved
|
||||||
} | ||||||
|
||||||
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); | ||||||
fileHandle._fileOptions = options; | ||||||
return fileHandle; | ||||||
} | ||||||
|
||||||
private static unsafe void Preallocate(string fullPath, long preallocationSize, SafeFileHandle fileHandle) | ||||||
{ | ||||||
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))) | ||||||
stephentoub marked this conversation as resolved.
Show resolved
Hide resolved
|
||||||
{ | ||||||
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); | ||||||
adamsitnik marked this conversation as resolved.
Show resolved
Hide resolved
|
||||||
|
||||||
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); | ||||||
} | ||||||
} | ||||||
} | ||||||
|
||||||
|
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
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?