[System.Security.SecurityCritical] // auto-generated private DirectoryInfo CreateSubdirectoryHelper(String path, Object directorySecurity) { Contract.Requires(path != null); String newDirs = Path.InternalCombine(FullPath, path); String fullPath = Path.GetFullPathInternal(newDirs); if (0 != String.Compare(FullPath, 0, fullPath, 0, FullPath.Length, StringComparison.OrdinalIgnoreCase)) { String displayPath = __Error.GetDisplayablePath(DisplayPath, false); throw new ArgumentException(Environment.GetResourceString("Argument_InvalidSubPath", path, displayPath)); } // Ensure we have permission to create this subdirectory. String demandDirForCreation = Directory.GetDemandDir(fullPath, true); #if FEATURE_CORECLR FileSecurityState state = new FileSecurityState(FileSecurityStateAccess.Write, OriginalPath, demandDirForCreation); state.EnsureState(); #else new FileIOPermission(FileIOPermissionAccess.Write, new String[] { demandDirForCreation }, false, false).Demand(); #endif Directory.InternalCreateDirectory(fullPath, path, directorySecurity); // Check for read permission to directory we hand back by calling this constructor. return(new DirectoryInfo(fullPath)); }
internal static void InternalDelete(String path, bool checkHost) { String fullPath = Path.GetFullPath(path); if (checkHost) { FileSecurityState state = new FileSecurityState(FileSecurityStateAccess.Write, path, fullPath); state.EnsureState(); } bool r = Win32Native.DeleteFile(fullPath); if (!r) { int hr = Marshal.GetLastWin32Error(); if (hr == Win32Native.ERROR_FILE_NOT_FOUND) { return; } else { __Error.WinIOError(hr, fullPath); } } }
internal override FileSystemInfo CreateObject(SearchResult result) { bool isFile = FileSystemEnumerableHelpers.IsFile(result.FindData); bool isDir = FileSystemEnumerableHelpers.IsDir(result.FindData); if (isDir) { String name = result.FullPath; String permissionName = name + "\\."; FileSecurityState state = new FileSecurityState(FileSecurityStateAccess.Read, String.Empty, permissionName); state.EnsureState(); DirectoryInfo di = new DirectoryInfo(name, false); di.InitializeFrom(result.FindData); return(di); } else { Debug.Assert(isFile); String name = result.FullPath; FileSecurityState state = new FileSecurityState(FileSecurityStateAccess.Read, String.Empty, name); state.EnsureState(); FileInfo fi = new FileInfo(name, false); fi.InitializeFrom(result.FindData); return(fi); } }
public void MoveTo(String destFileName) { if (destFileName == null) { throw new ArgumentNullException("destFileName"); } if (destFileName.Length == 0) { throw new ArgumentException(Environment.GetResourceString("Argument_EmptyFileName"), "destFileName"); } Contract.EndContractBlock(); String fullDestFileName = Path.GetFullPathInternal(destFileName); #if FEATURE_CORECLR FileSecurityState sourceState = new FileSecurityState(FileSecurityStateAccess.Write | FileSecurityStateAccess.Read, DisplayPath, FullPath); FileSecurityState destState = new FileSecurityState(FileSecurityStateAccess.Write, destFileName, fullDestFileName); sourceState.EnsureState(); destState.EnsureState(); #else new FileIOPermission(FileIOPermissionAccess.Write | FileIOPermissionAccess.Read, new String[] { FullPath }, false, false).Demand(); FileIOPermission.QuickDemand(FileIOPermissionAccess.Write, fullDestFileName, false, false); #endif if (!Win32Native.MoveFile(FullPath, fullDestFileName)) { __Error.WinIOError(); } FullPath = fullDestFileName; OriginalPath = destFileName; _name = Path.GetFileName(fullDestFileName); DisplayPath = GetDisplayPath(destFileName); // Flush any cached information about the file. _dataInitialised = -1; }
private void Init(String path, bool checkHost) { // Special case "<DriveLetter>:" to point to "<CurrentDirectory>" instead if ((path.Length == 2) && (path[1] == ':')) { OriginalPath = "."; } else { OriginalPath = path; } // Must fully qualify the path for the security check String fullPath = Path.GetFullPathInternal(path); demandDir = new String[] { Directory.GetDemandDir(fullPath, true) }; #if FEATURE_CORECLR if (checkHost) { FileSecurityState state = new FileSecurityState(FileSecurityStateAccess.Read, OriginalPath, fullPath); state.EnsureState(); } #else new FileIOPermission(FileIOPermissionAccess.Read, demandDir, false, false).Demand(); #endif FullPath = fullPath; DisplayPath = GetDisplayName(OriginalPath, FullPath); }
public void MoveTo(String destFileName) { if (destFileName == null) { throw new ArgumentNullException(nameof(destFileName)); } if (destFileName.Length == 0) { throw new ArgumentException(Environment.GetResourceString("Argument_EmptyFileName"), nameof(destFileName)); } Contract.EndContractBlock(); string fullDestFileName = Path.GetFullPath(destFileName); FileSecurityState sourceState = new FileSecurityState(FileSecurityStateAccess.Write | FileSecurityStateAccess.Read, DisplayPath, FullPath); FileSecurityState destState = new FileSecurityState(FileSecurityStateAccess.Write, destFileName, fullDestFileName); sourceState.EnsureState(); destState.EnsureState(); if (!Win32Native.MoveFile(FullPath, fullDestFileName)) { __Error.WinIOError(); } FullPath = fullDestFileName; OriginalPath = destFileName; _name = Path.GetFileName(fullDestFileName); DisplayPath = GetDisplayPath(destFileName); // Flush any cached information about the file. _dataInitialised = -1; }
internal void DoDemand(String fullPathToDemand) { if (_checkHost) { String demandDir = Directory.GetDemandDir(fullPathToDemand, true); FileSecurityState state = new FileSecurityState(FileSecurityStateAccess.PathDiscovery, String.Empty, demandDir); state.EnsureState(); } }
internal override FileInfo CreateObject(SearchResult result) { String name = result.FullPath; FileSecurityState state = new FileSecurityState(FileSecurityStateAccess.Read, String.Empty, name); state.EnsureState(); FileInfo fi = new FileInfo(name, false); fi.InitializeFrom(result.FindData); return(fi); }
internal override DirectoryInfo CreateObject(SearchResult result) { String name = result.FullPath; String permissionName = name + "\\."; FileSecurityState state = new FileSecurityState(FileSecurityStateAccess.Read, String.Empty, permissionName); state.EnsureState(); DirectoryInfo di = new DirectoryInfo(name, false); di.InitializeFrom(result.FindData); return(di); }
internal void DoDemand(String fullPathToDemand) { #if FEATURE_CORECLR if (_checkHost) { String demandDir = Directory.GetDemandDir(fullPathToDemand, true); FileSecurityState state = new FileSecurityState(FileSecurityStateAccess.PathDiscovery, String.Empty, demandDir); state.EnsureState(); } #else String demandDir = Directory.GetDemandDir(fullPathToDemand, true); FileIOPermission.QuickDemand(FileIOPermissionAccess.PathDiscovery, demandDir, false, false); #endif }
internal override FileInfo CreateObject(SearchResult result) { String name = result.FullPath; #if FEATURE_CORECLR FileSecurityState state = new FileSecurityState(FileSecurityStateAccess.Read, String.Empty, name); state.EnsureState(); #else FileIOPermission.QuickDemand(FileIOPermissionAccess.Read, name, false, false); #endif FileInfo fi = new FileInfo(name, false); fi.InitializeFrom(result.FindData); return(fi); }
internal override FileInfo CreateObject(SearchResult result) { String name = result.FullPath; #if FEATURE_CORECLR && !FEATURE_LEGACYNETCFIOSECURITY FileSecurityState state = new FileSecurityState(FileSecurityStateAccess.Read, String.Empty, name); state.EnsureState(); #elif !FEATURE_CORECLR String[] names = new String[] { name }; new FileIOPermission(FileIOPermissionAccess.Read, names, false, false).Demand(); #endif FileInfo fi = new FileInfo(name, false); fi.InitializeFrom(result.FindData); return(fi); }
internal override DirectoryInfo CreateObject(SearchResult result) { String name = result.FullPath; String permissionName = name + "\\."; #if FEATURE_CORECLR FileSecurityState state = new FileSecurityState(FileSecurityStateAccess.Read, String.Empty, permissionName); state.EnsureState(); #else FileIOPermission.QuickDemand(FileIOPermissionAccess.Read, permissionName, false, false); #endif DirectoryInfo di = new DirectoryInfo(name, false); di.InitializeFrom(result.FindData); return(di); }
internal void DoDemand(String fullPathToDemand) { #if FEATURE_CORECLR && !FEATURE_LEGACYNETCFIOSECURITY if (_checkHost) { String demandDir = Directory.GetDemandDir(fullPathToDemand, true); FileSecurityState state = new FileSecurityState(FileSecurityStateAccess.PathDiscovery, String.Empty, demandDir); state.EnsureState(); } #elif !FEATURE_CORECLR String demandDir = Directory.GetDemandDir(fullPathToDemand, true); String[] demandPaths = new String[] { demandDir }; new FileIOPermission(FileIOPermissionAccess.PathDiscovery, demandPaths, false, false).Demand(); #endif }
private void Init(String fileName, bool checkHost) { OriginalPath = fileName; // Must fully qualify the path for the security check String fullPath = Path.GetFullPath(fileName); if (checkHost) { FileSecurityState state = new FileSecurityState(FileSecurityStateAccess.Read, fileName, fullPath); state.EnsureState(); } _name = Path.GetFileName(fileName); FullPath = fullPath; DisplayPath = GetDisplayPath(fileName); }
public static FileAttributes GetAttributes(String path) { String fullPath = Path.GetFullPath(path); FileSecurityState state = new FileSecurityState(FileSecurityStateAccess.Read, path, fullPath); state.EnsureState(); Win32Native.WIN32_FILE_ATTRIBUTE_DATA data = new Win32Native.WIN32_FILE_ATTRIBUTE_DATA(); int dataInitialised = FillAttributeInfo(fullPath, ref data, false, true); if (dataInitialised != 0) { __Error.WinIOError(dataInitialised, fullPath); } return((FileAttributes)data.fileAttributes); }
private static bool InternalExistsHelper(String path, bool checkHost) { try { if (path == null) { return(false); } if (path.Length == 0) { return(false); } path = Path.GetFullPath(path); // After normalizing, check whether path ends in directory separator. // Otherwise, FillAttributeInfo removes it and we may return a false positive. // GetFullPath should never return null Contract.Assert(path != null, "File.Exists: GetFullPath returned null"); if (path.Length > 0 && PathInternal.IsDirectorySeparator(path[path.Length - 1])) { return(false); } #if FEATURE_CORECLR if (checkHost) { FileSecurityState state = new FileSecurityState(FileSecurityStateAccess.Read, String.Empty, path); state.EnsureState(); } #else FileIOPermission.QuickDemand(FileIOPermissionAccess.Read, path, false, false); #endif return(InternalExists(path)); } catch (ArgumentException) { } catch (NotSupportedException) { } // Security can throw this on ":" catch (SecurityException) { } catch (IOException) { } catch (UnauthorizedAccessException) { } return(false); }
private void Init(String fileName, bool checkHost) { OriginalPath = fileName; // Must fully qualify the path for the security check String fullPath = Path.GetFullPathInternal(fileName); #if FEATURE_CORECLR if (checkHost) { FileSecurityState state = new FileSecurityState(FileSecurityStateAccess.Read, fileName, fullPath); state.EnsureState(); } #else FileIOPermission.QuickDemand(FileIOPermissionAccess.Read, fullPath, false, false); #endif _name = Path.GetFileName(fileName); FullPath = fullPath; DisplayPath = GetDisplayPath(fileName); }
/// <devdoc> /// Note: This returns the fully qualified name of the destination file. /// </devdoc> internal static String InternalCopy(String sourceFileName, String destFileName, bool overwrite, bool checkHost) { Contract.Requires(sourceFileName != null); Contract.Requires(destFileName != null); Contract.Requires(sourceFileName.Length > 0); Contract.Requires(destFileName.Length > 0); String fullSourceFileName = Path.GetFullPath(sourceFileName); String fullDestFileName = Path.GetFullPath(destFileName); if (checkHost) { FileSecurityState sourceState = new FileSecurityState(FileSecurityStateAccess.Read, sourceFileName, fullSourceFileName); FileSecurityState destState = new FileSecurityState(FileSecurityStateAccess.Write, destFileName, fullDestFileName); sourceState.EnsureState(); destState.EnsureState(); } bool r = Win32Native.CopyFile(fullSourceFileName, fullDestFileName, !overwrite); if (!r) { // Save Win32 error because subsequent checks will overwrite this HRESULT. int errorCode = Marshal.GetLastWin32Error(); String fileName = destFileName; if (errorCode != Win32Native.ERROR_FILE_EXISTS) { if (errorCode == Win32Native.ERROR_ACCESS_DENIED) { if (Directory.InternalExists(fullDestFileName)) { throw new IOException(Environment.GetResourceString("Arg_FileIsDirectory_Name", destFileName), Win32Native.ERROR_ACCESS_DENIED, fullDestFileName); } } } __Error.WinIOError(errorCode, fileName); } return(fullDestFileName); }
private FileSystemEnumerableIterator(String fullPath, String normalizedSearchPath, String searchCriteria, String userPath, SearchOption searchOption, SearchResultHandler <TSource> resultHandler, bool checkHost) { this.fullPath = fullPath; this.normalizedSearchPath = normalizedSearchPath; this.searchCriteria = searchCriteria; this._resultHandler = resultHandler; this.userPath = userPath; this.searchOption = searchOption; this._checkHost = checkHost; searchStack = new List <Directory.SearchData>(); if (searchCriteria != null) { // permission demands String[] demandPaths = new String[2]; // Any illegal chars such as *, ? will be caught by FileIOPermission.HasIllegalCharacters demandPaths[0] = Directory.GetDemandDir(fullPath, true); // For filters like foo\*.cs we need to verify if the directory foo is not denied access. // Do a demand on the combined path so that we can fail early in case of deny demandPaths[1] = Directory.GetDemandDir(normalizedSearchPath, true); #if MONO_FEATURE_CAS #if FEATURE_CORECLR if (checkHost) { FileSecurityState state1 = new FileSecurityState(FileSecurityStateAccess.PathDiscovery, String.Empty, demandPaths[0]); state1.EnsureState(); FileSecurityState state2 = new FileSecurityState(FileSecurityStateAccess.PathDiscovery, String.Empty, demandPaths[1]); state2.EnsureState(); } #else FileIOPermission.QuickDemand(FileIOPermissionAccess.PathDiscovery, demandPaths, false, false); #endif #endif searchData = new Directory.SearchData(normalizedSearchPath, userPath, searchOption); CommonInit(); } else { empty = true; } }
private void Init(String fileName, bool checkHost) { OriginalPath = fileName; // Must fully qualify the path for the security check String fullPath = Path.GetFullPathInternal(fileName); #if FEATURE_CORECLR && !FEATURE_LEGACYNETCFIOSECURITY if (checkHost) { FileSecurityState state = new FileSecurityState(FileSecurityStateAccess.Read, fileName, fullPath); state.EnsureState(); } #elif !FEATURE_CORECLR new FileIOPermission(FileIOPermissionAccess.Read, new String[] { fullPath }, false, false).Demand(); #endif _name = Path.GetFileName(fileName); FullPath = fullPath; DisplayPath = GetDisplayPath(fileName); }
private static void InternalMove(String sourceFileName, String destFileName, bool checkHost) { if (sourceFileName == null) { throw new ArgumentNullException(nameof(sourceFileName), Environment.GetResourceString("ArgumentNull_FileName")); } if (destFileName == null) { throw new ArgumentNullException(nameof(destFileName), Environment.GetResourceString("ArgumentNull_FileName")); } if (sourceFileName.Length == 0) { throw new ArgumentException(Environment.GetResourceString("Argument_EmptyFileName"), nameof(sourceFileName)); } if (destFileName.Length == 0) { throw new ArgumentException(Environment.GetResourceString("Argument_EmptyFileName"), nameof(destFileName)); } Contract.EndContractBlock(); String fullSourceFileName = Path.GetFullPath(sourceFileName); String fullDestFileName = Path.GetFullPath(destFileName); if (checkHost) { FileSecurityState sourceState = new FileSecurityState(FileSecurityStateAccess.Write | FileSecurityStateAccess.Read, sourceFileName, fullSourceFileName); FileSecurityState destState = new FileSecurityState(FileSecurityStateAccess.Write, destFileName, fullDestFileName); sourceState.EnsureState(); destState.EnsureState(); } if (!InternalExists(fullSourceFileName)) { __Error.WinIOError(Win32Native.ERROR_FILE_NOT_FOUND, fullSourceFileName); } if (!Win32Native.MoveFile(fullSourceFileName, fullDestFileName)) { __Error.WinIOError(); } }
public override void Delete() { FileSecurityState state = new FileSecurityState(FileSecurityStateAccess.Write, DisplayPath, FullPath); state.EnsureState(); bool r = Win32Native.DeleteFile(FullPath); if (!r) { int hr = Marshal.GetLastWin32Error(); if (hr == Win32Native.ERROR_FILE_NOT_FOUND) { return; } else { __Error.WinIOError(hr, DisplayPath); } } }
private static DateTime InternalGetLastWriteTimeUtc(String path, bool checkHost) { String fullPath = Path.GetFullPath(path); if (checkHost) { FileSecurityState state = new FileSecurityState(FileSecurityStateAccess.Read, path, fullPath); state.EnsureState(); } Win32Native.WIN32_FILE_ATTRIBUTE_DATA data = new Win32Native.WIN32_FILE_ATTRIBUTE_DATA(); int dataInitialised = FillAttributeInfo(fullPath, ref data, false, false); if (dataInitialised != 0) { __Error.WinIOError(dataInitialised, fullPath); } long dt = ((long)data.ftLastWriteTimeHigh << 32) | ((long)data.ftLastWriteTimeLow); return(DateTime.FromFileTimeUtc(dt)); }
public override void Delete() { #if FEATURE_MONO_CAS #if FEATURE_CORECLR FileSecurityState state = new FileSecurityState(FileSecurityStateAccess.Write, DisplayPath, FullPath); state.EnsureState(); #else // For security check, path should be resolved to an absolute path. FileIOPermission.QuickDemand(FileIOPermissionAccess.Write, FullPath, false, false); #endif #endif #if MONO MonoIOError error; if (MonoIO.ExistsDirectory(FullPath, out error)) { __Error.WinIOError(Win32Native.ERROR_ACCESS_DENIED, DisplayPath); } if (!MonoIO.DeleteFile(FullPath, out error)) { int hr = (int)error; #else bool r = Win32Native.DeleteFile(FullPath); if (!r) { int hr = Marshal.GetLastWin32Error(); #endif if (hr == Win32Native.ERROR_FILE_NOT_FOUND) { return; } else { __Error.WinIOError(hr, DisplayPath); } } }
internal override FileSystemInfo CreateObject(SearchResult result) { bool isFile = FileSystemEnumerableHelpers.IsFile(result.FindData); bool isDir = FileSystemEnumerableHelpers.IsDir(result.FindData); if (isDir) { String name = result.FullPath; String permissionName = name + "\\."; #if FEATURE_CORECLR FileSecurityState state = new FileSecurityState(FileSecurityStateAccess.Read, String.Empty, permissionName); state.EnsureState(); #else String[] permissionNames = new String[] { permissionName }; new FileIOPermission(FileIOPermissionAccess.Read, permissionNames, false, false).Demand(); #endif DirectoryInfo di = new DirectoryInfo(name, false); di.InitializeFrom(result.FindData); return(di); } else { Contract.Assert(isFile); String name = result.FullPath; #if FEATURE_CORECLR FileSecurityState state = new FileSecurityState(FileSecurityStateAccess.Read, String.Empty, name); state.EnsureState(); #else String[] names = new String[] { name }; new FileIOPermission(FileIOPermissionAccess.Read, names, false, false).Demand(); #endif FileInfo fi = new FileInfo(name, false); fi.InitializeFrom(result.FindData); return(fi); } }
private static void InternalReplace(String sourceFileName, String destinationFileName, String destinationBackupFileName, bool ignoreMetadataErrors) { Contract.Requires(sourceFileName != null); Contract.Requires(destinationFileName != null); // Write permission to all three files, read permission to source // and dest. String fullSrcPath = Path.GetFullPath(sourceFileName); String fullDestPath = Path.GetFullPath(destinationFileName); String fullBackupPath = null; if (destinationBackupFileName != null) { fullBackupPath = Path.GetFullPath(destinationBackupFileName); } FileSecurityState sourceState = new FileSecurityState(FileSecurityStateAccess.Read | FileSecurityStateAccess.Write, sourceFileName, fullSrcPath); FileSecurityState destState = new FileSecurityState(FileSecurityStateAccess.Read | FileSecurityStateAccess.Write, destinationFileName, fullDestPath); FileSecurityState backupState = new FileSecurityState(FileSecurityStateAccess.Read | FileSecurityStateAccess.Write, destinationBackupFileName, fullBackupPath); sourceState.EnsureState(); destState.EnsureState(); backupState.EnsureState(); int flags = Win32Native.REPLACEFILE_WRITE_THROUGH; if (ignoreMetadataErrors) { flags |= Win32Native.REPLACEFILE_IGNORE_MERGE_ERRORS; } bool r = Win32Native.ReplaceFile(fullDestPath, fullSrcPath, fullBackupPath, flags, IntPtr.Zero, IntPtr.Zero); if (!r) { __Error.WinIOError(); } }
public override void Delete() { #if FEATURE_CORECLR FileSecurityState state = new FileSecurityState(FileSecurityStateAccess.Write, DisplayPath, FullPath); state.EnsureState(); #else // For security check, path should be resolved to an absolute path. new FileIOPermission(FileIOPermissionAccess.Write, new String[] { FullPath }, false, false).Demand(); #endif bool r = Win32Native.DeleteFile(FullPath); if (!r) { int hr = Marshal.GetLastWin32Error(); if (hr == Win32Native.ERROR_FILE_NOT_FOUND) { return; } else { __Error.WinIOError(hr, DisplayPath); } } }
internal static String InternalCopy(String sourceFileName, String destFileName, bool overwrite, bool checkHost) { Contract.Requires(sourceFileName != null); Contract.Requires(destFileName != null); Contract.Requires(sourceFileName.Length > 0); Contract.Requires(destFileName.Length > 0); String fullSourceFileName = Path.GetFullPathInternal(sourceFileName); String fullDestFileName = Path.GetFullPathInternal(destFileName); #if FEATURE_CORECLR if (checkHost) { FileSecurityState sourceState = new FileSecurityState(FileSecurityStateAccess.Read, sourceFileName, fullSourceFileName); FileSecurityState destState = new FileSecurityState(FileSecurityStateAccess.Write, destFileName, fullDestFileName); sourceState.EnsureState(); destState.EnsureState(); } #else FileIOPermission.QuickDemand(FileIOPermissionAccess.Read, fullSourceFileName, false, false); FileIOPermission.QuickDemand(FileIOPermissionAccess.Write, fullDestFileName, false, false); #endif bool r = Win32Native.CopyFile(fullSourceFileName, fullDestFileName, !overwrite); if (!r) { // Save Win32 error because subsequent checks will overwrite this HRESULT. int errorCode = Marshal.GetLastWin32Error(); String fileName = destFileName; if (errorCode != Win32Native.ERROR_FILE_EXISTS) { #if !FEATURE_CORECLR // For a number of error codes (sharing violation, path // not found, etc) we don't know if the problem was with // the source or dest file. Try reading the source file. using(SafeFileHandle handle = Win32Native.UnsafeCreateFile(fullSourceFileName, GENERIC_READ, FileShare.Read, null, FileMode.Open, 0, IntPtr.Zero)) { if (handle.IsInvalid) fileName = sourceFileName; } #endif // !FEATURE_CORECLR if (errorCode == Win32Native.ERROR_ACCESS_DENIED) { if (Directory.InternalExists(fullDestFileName)) throw new IOException(Environment.GetResourceString("Arg_FileIsDirectory_Name", destFileName), Win32Native.ERROR_ACCESS_DENIED, fullDestFileName); } } __Error.WinIOError(errorCode, fileName); } return fullDestFileName; }
private void Init(String path, bool checkHost) { // Special case "<DriveLetter>:" to point to "<CurrentDirectory>" instead if ((path.Length == 2) && (path[1] == ':')) { OriginalPath = "."; } else { OriginalPath = path; } // Must fully qualify the path for the security check String fullPath = Path.GetFullPathInternal(path); demandDir = new String[] {Directory.GetDemandDir(fullPath, true)}; #if FEATURE_CORECLR if (checkHost) { FileSecurityState state = new FileSecurityState(FileSecurityStateAccess.Read, OriginalPath, fullPath); state.EnsureState(); } #else new FileIOPermission(FileIOPermissionAccess.Read, demandDir, false, false ).Demand(); #endif FullPath = fullPath; DisplayPath = GetDisplayName(OriginalPath, FullPath); }
[System.Security.SecurityCritical] // auto-generated private DirectoryInfo CreateSubdirectoryHelper(String path, Object directorySecurity) { Contract.Requires(path != null); String newDirs = Path.InternalCombine(FullPath, path); String fullPath = Path.GetFullPathInternal(newDirs); if (0!=String.Compare(FullPath,0,fullPath,0, FullPath.Length,StringComparison.OrdinalIgnoreCase)) { String displayPath = __Error.GetDisplayablePath(DisplayPath, false); throw new ArgumentException(Environment.GetResourceString("Argument_InvalidSubPath", path, displayPath)); } // Ensure we have permission to create this subdirectory. String demandDirForCreation = Directory.GetDemandDir(fullPath, true); #if FEATURE_CORECLR FileSecurityState state = new FileSecurityState(FileSecurityStateAccess.Write, OriginalPath, demandDirForCreation); state.EnsureState(); #else new FileIOPermission(FileIOPermissionAccess.Write, new String[] { demandDirForCreation }, false, false).Demand(); #endif Directory.InternalCreateDirectory(fullPath, path, directorySecurity); // Check for read permission to directory we hand back by calling this constructor. return new DirectoryInfo(fullPath); }
public static String GetDirectoryRoot(String path) { if (path==null) throw new ArgumentNullException("path"); Contract.EndContractBlock(); String fullPath = Path.GetFullPathInternal(path); String root = fullPath.Substring(0, Path.GetRootLength(fullPath)); String demandPath = GetDemandDir(root, true); #if FEATURE_CORECLR FileSecurityState state = new FileSecurityState(FileSecurityStateAccess.PathDiscovery, path, demandPath); state.EnsureState(); #else FileIOPermission.QuickDemand(FileIOPermissionAccess.PathDiscovery, demandPath, false, false); #endif return root; }
internal static bool InternalExistsHelper(String path, bool checkHost) { try { if (path == null) return false; if (path.Length == 0) return false; // Get fully qualified file name ending in \* for security check String fullPath = Path.GetFullPathInternal(path); String demandPath = GetDemandDir(fullPath, true); #if FEATURE_CORECLR if (checkHost) { FileSecurityState state = new FileSecurityState(FileSecurityStateAccess.Read, path, demandPath); state.EnsureState(); } #else FileIOPermission.QuickDemand(FileIOPermissionAccess.Read, demandPath, false, false); #endif return InternalExists(fullPath); } catch (ArgumentException) { } catch (NotSupportedException) { } // Security can throw this on ":" catch (SecurityException) { } catch (IOException) { } catch (UnauthorizedAccessException) { Contract.Assert(false, "Ignore this assert and send a repro to Microsoft. This assert was tracking purposes only."); } return false; }
[System.Security.SecurityCritical] // auto-generated internal static void Delete(String fullPath, String userPath, bool recursive, bool checkHost) { String demandPath; // If not recursive, do permission check only on this directory // else check for the whole directory structure rooted below demandPath = GetDemandDir(fullPath, !recursive); #if FEATURE_CORECLR if (checkHost) { FileSecurityState state = new FileSecurityState(FileSecurityStateAccess.Write, userPath, demandPath); state.EnsureState(); } #else // Make sure we have write permission to this directory new FileIOPermission(FileIOPermissionAccess.Write, new String[] { demandPath }, false, false ).Demand(); #endif // Do not recursively delete through reparse points. Perhaps in a // future version we will add a new flag to control this behavior, // but for now we're much safer if we err on the conservative side. // This applies to symbolic links and mount points. Win32Native.WIN32_FILE_ATTRIBUTE_DATA data = new Win32Native.WIN32_FILE_ATTRIBUTE_DATA(); int dataInitialised = File.FillAttributeInfo(fullPath, ref data, false, true); if (dataInitialised != 0) { // Ensure we throw a DirectoryNotFoundException. if (dataInitialised == Win32Native.ERROR_FILE_NOT_FOUND) dataInitialised = Win32Native.ERROR_PATH_NOT_FOUND; __Error.WinIOError(dataInitialised, fullPath); } if (((FileAttributes)data.fileAttributes & FileAttributes.ReparsePoint) != 0) recursive = false; DeleteHelper(fullPath, userPath, recursive, true); }
private static void InternalMove(String sourceFileName, String destFileName, bool checkHost) { if (sourceFileName == null) throw new ArgumentNullException("sourceFileName", Environment.GetResourceString("ArgumentNull_FileName")); if (destFileName == null) throw new ArgumentNullException("destFileName", Environment.GetResourceString("ArgumentNull_FileName")); if (sourceFileName.Length == 0) throw new ArgumentException(Environment.GetResourceString("Argument_EmptyFileName"), "sourceFileName"); if (destFileName.Length == 0) throw new ArgumentException(Environment.GetResourceString("Argument_EmptyFileName"), "destFileName"); Contract.EndContractBlock(); String fullSourceFileName = Path.GetFullPathInternal(sourceFileName); String fullDestFileName = Path.GetFullPathInternal(destFileName); #if FEATURE_CORECLR if (checkHost) { FileSecurityState sourceState = new FileSecurityState(FileSecurityStateAccess.Write | FileSecurityStateAccess.Read, sourceFileName, fullSourceFileName); FileSecurityState destState = new FileSecurityState(FileSecurityStateAccess.Write, destFileName, fullDestFileName); sourceState.EnsureState(); destState.EnsureState(); } #else FileIOPermission.QuickDemand(FileIOPermissionAccess.Write | FileIOPermissionAccess.Read, fullSourceFileName, false, false); FileIOPermission.QuickDemand(FileIOPermissionAccess.Write, fullDestFileName, false, false); #endif if (!InternalExists(fullSourceFileName)) __Error.WinIOError(Win32Native.ERROR_FILE_NOT_FOUND, fullSourceFileName); if (!Win32Native.MoveFile(fullSourceFileName, fullDestFileName)) { __Error.WinIOError(); } }
public static String GetFullPath(String path) { String fullPath = GetFullPathInternal(path); #if FEATURE_CORECLR FileSecurityState state = new FileSecurityState(FileSecurityStateAccess.PathDiscovery, path, fullPath); state.EnsureState(); #else FileIOPermission.QuickDemand(FileIOPermissionAccess.PathDiscovery, fullPath, false, false); #endif return fullPath; }
private static string InternalGetFolderPath(SpecialFolder folder, SpecialFolderOption option, bool suppressSecurityChecks = false) { #if FEATURE_CORESYSTEM // This is currently customized for Windows Phone since CoreSystem doesn't support // SHGetFolderPath. The allowed folder values are based on the version of .NET CF WP7 was using. switch (folder) { case SpecialFolder.System: return SystemDirectory; case SpecialFolder.ApplicationData: case SpecialFolder.Favorites: case SpecialFolder.Programs: case SpecialFolder.StartMenu: case SpecialFolder.Startup: case SpecialFolder.Personal: throw new PlatformNotSupportedException(); default: throw new PlatformNotSupportedException(); } #else // FEATURE_CORESYSTEM #if !FEATURE_CORECLR if (option == SpecialFolderOption.Create && !suppressSecurityChecks) { FileIOPermission createPermission = new FileIOPermission(PermissionState.None); createPermission.AllFiles = FileIOPermissionAccess.Write; createPermission.Demand(); } #endif StringBuilder sb = new StringBuilder(Path.MAX_PATH); int hresult = Win32Native.SHGetFolderPath(IntPtr.Zero, /* hwndOwner: [in] Reserved */ ((int)folder | (int)option), /* nFolder: [in] CSIDL */ IntPtr.Zero, /* hToken: [in] access token */ Win32Native.SHGFP_TYPE_CURRENT, /* dwFlags: [in] retrieve current path */ sb); /* pszPath: [out]resultant path */ String s; if (hresult < 0) { switch (hresult) { default: // The previous incarnation threw away all errors. In order to limit // breaking changes, we will be permissive about these errors // instead of calling ThowExceptionForHR. //Runtime.InteropServices.Marshal.ThrowExceptionForHR(hresult); break; case __HResults.COR_E_PLATFORMNOTSUPPORTED: // This one error is the one we do want to throw. // <STRIP> throw new PlatformNotSupportedException(); } // SHGetFolderPath does not initialize the output buffer on error s = String.Empty; } else { s = sb.ToString(); } if (!suppressSecurityChecks) { // On CoreCLR we can check with the host if we're not trying to use any special options. // Otherwise, we need to do a full demand since hosts aren't expecting to handle requests to // create special folders. #if FEATURE_CORECLR if (option == SpecialFolderOption.None) { FileSecurityState state = new FileSecurityState(FileSecurityStateAccess.PathDiscovery, String.Empty, s); state.EnsureState(); } else #endif // FEATURE_CORECLR { new FileIOPermission(FileIOPermissionAccess.PathDiscovery, s).Demand(); } } return s; #endif // FEATURE_CORESYSTEM }
private static String InternalGetCurrentDirectory(bool checkHost) { StringBuilder sb = StringBuilderCache.Acquire(Path.MAX_PATH + 1); if (Win32Native.GetCurrentDirectory(sb.Capacity, sb) == 0) __Error.WinIOError(); String currentDirectory = sb.ToString(); // Note that if we have somehow put our command prompt into short // file name mode (ie, by running edlin or a DOS grep, etc), then // this will return a short file name. if (currentDirectory.IndexOf('~') >= 0) { int r = Win32Native.GetLongPathName(currentDirectory, sb, sb.Capacity); if (r == 0 || r >= Path.MAX_PATH) { int errorCode = Marshal.GetLastWin32Error(); if (r >= Path.MAX_PATH) errorCode = Win32Native.ERROR_FILENAME_EXCED_RANGE; if (errorCode != Win32Native.ERROR_FILE_NOT_FOUND && errorCode != Win32Native.ERROR_PATH_NOT_FOUND && errorCode != Win32Native.ERROR_INVALID_FUNCTION && // by design - enough said. errorCode != Win32Native.ERROR_ACCESS_DENIED) __Error.WinIOError(errorCode, String.Empty); } currentDirectory = sb.ToString(); } StringBuilderCache.Release(sb); String demandPath = GetDemandDir(currentDirectory, true); #if FEATURE_CORECLR if (checkHost) { FileSecurityState state = new FileSecurityState(FileSecurityStateAccess.PathDiscovery, String.Empty, demandPath); state.EnsureState(); } #else new FileIOPermission( FileIOPermissionAccess.PathDiscovery, new String[] { demandPath }, false, false ).Demand(); #endif return currentDirectory; }
public static FileAttributes GetAttributes(String path) { String fullPath = Path.GetFullPathInternal(path); #if FEATURE_CORECLR FileSecurityState state = new FileSecurityState(FileSecurityStateAccess.Read, path, fullPath); state.EnsureState(); #else FileIOPermission.QuickDemand(FileIOPermissionAccess.Read, fullPath, false, false); #endif Win32Native.WIN32_FILE_ATTRIBUTE_DATA data = new Win32Native.WIN32_FILE_ATTRIBUTE_DATA(); int dataInitialised = FillAttributeInfo(fullPath, ref data, false, true); if (dataInitialised != 0) __Error.WinIOError(dataInitialised, fullPath); return (FileAttributes) data.fileAttributes; }
private static DateTime InternalGetLastWriteTimeUtc(String path, bool checkHost) { String fullPath = Path.GetFullPathInternal(path); #if FEATURE_CORECLR if (checkHost) { FileSecurityState state = new FileSecurityState(FileSecurityStateAccess.Read, path, fullPath); state.EnsureState(); } #else FileIOPermission.QuickDemand(FileIOPermissionAccess.Read, fullPath, false, false); #endif Win32Native.WIN32_FILE_ATTRIBUTE_DATA data = new Win32Native.WIN32_FILE_ATTRIBUTE_DATA(); int dataInitialised = FillAttributeInfo(fullPath, ref data, false, false); if (dataInitialised != 0) __Error.WinIOError(dataInitialised, fullPath); long dt = ((long)data.ftLastWriteTimeHigh << 32) | ((long)data.ftLastWriteTimeLow); return DateTime.FromFileTimeUtc(dt); }
internal FileSystemEnumerableIterator(String path, String originalUserPath, String searchPattern, SearchOption searchOption, SearchResultHandler <TSource> resultHandler, bool checkHost) { Contract.Requires(path != null); Contract.Requires(originalUserPath != null); Contract.Requires(searchPattern != null); Contract.Requires(searchOption == SearchOption.AllDirectories || searchOption == SearchOption.TopDirectoryOnly); Contract.Requires(resultHandler != null); oldMode = Win32Native.SetErrorMode(Win32Native.SEM_FAILCRITICALERRORS); searchStack = new List <Directory.SearchData>(); String normalizedSearchPattern = NormalizeSearchPattern(searchPattern); if (normalizedSearchPattern.Length == 0) { empty = true; } else { _resultHandler = resultHandler; this.searchOption = searchOption; fullPath = Path.GetFullPathInternal(path); String fullSearchString = GetFullSearchString(fullPath, normalizedSearchPattern); normalizedSearchPath = Path.GetDirectoryName(fullSearchString); // permission demands String[] demandPaths = new String[2]; // Any illegal chars such as *, ? will be caught by FileIOPermission.HasIllegalCharacters demandPaths[0] = Directory.GetDemandDir(fullPath, true); // For filters like foo\*.cs we need to verify if the directory foo is not denied access. // Do a demand on the combined path so that we can fail early in case of deny demandPaths[1] = Directory.GetDemandDir(normalizedSearchPath, true); _checkHost = checkHost; #if FEATURE_CORECLR if (checkHost) { FileSecurityState state1 = new FileSecurityState(FileSecurityStateAccess.PathDiscovery, String.Empty, demandPaths[0]); state1.EnsureState(); FileSecurityState state2 = new FileSecurityState(FileSecurityStateAccess.PathDiscovery, String.Empty, demandPaths[1]); state2.EnsureState(); } #else new FileIOPermission(FileIOPermissionAccess.PathDiscovery, demandPaths, false, false).Demand(); #endif // normalize search criteria searchCriteria = GetNormalizedSearchCriteria(fullSearchString, normalizedSearchPath); // fix up user path String searchPatternDirName = Path.GetDirectoryName(normalizedSearchPattern); String userPathTemp = originalUserPath; if (searchPatternDirName != null && searchPatternDirName.Length != 0) { userPathTemp = Path.Combine(userPathTemp, searchPatternDirName); } this.userPath = userPathTemp; searchData = new Directory.SearchData(normalizedSearchPath, this.userPath, searchOption); CommonInit(); } }
private static String InternalGetTempFileName(bool checkHost) { String path = GetTempPath(); // Since this can write to the temp directory and theoretically // cause a denial of service attack, demand FileIOPermission to // that directory. #if FEATURE_CORECLR if (checkHost) { FileSecurityState state = new FileSecurityState(FileSecurityStateAccess.Write, String.Empty, path); state.EnsureState(); } #else new FileIOPermission(FileIOPermissionAccess.Write, path).Demand(); #endif StringBuilder sb = new StringBuilder(MAX_PATH); uint r = Win32Native.GetTempFileName(path, "tmp", 0, sb); if (r==0) __Error.WinIOError(); return sb.ToString(); }
public void MoveTo(String destDirName) { if (destDirName == null) { throw new ArgumentNullException(nameof(destDirName)); } if (destDirName.Length == 0) { throw new ArgumentException(Environment.GetResourceString("Argument_EmptyFileName"), nameof(destDirName)); } Contract.EndContractBlock(); #if FEATURE_CORECLR FileSecurityState sourceState = new FileSecurityState(FileSecurityStateAccess.Write | FileSecurityStateAccess.Read, DisplayPath, Directory.GetDemandDir(FullPath, true)); sourceState.EnsureState(); #else new FileIOPermission(FileIOPermissionAccess.Write | FileIOPermissionAccess.Read, demandDir, false, false).Demand(); #endif String fullDestDirName = Path.GetFullPathInternal(destDirName); String demandPath; if (!fullDestDirName.EndsWith(Path.DirectorySeparatorChar)) { fullDestDirName = fullDestDirName + Path.DirectorySeparatorChar; } demandPath = fullDestDirName + '.'; // Demand read & write permission to destination. The reason is // we hand back a DirectoryInfo to the destination that would allow // you to read a directory listing from that directory. Sure, you // had the ability to read the file contents in the old location, // but you technically also need read permissions to the new // location as well, and write is not a true superset of read. #if FEATURE_CORECLR FileSecurityState destState = new FileSecurityState(FileSecurityStateAccess.Write, destDirName, demandPath); destState.EnsureState(); #else new FileIOPermission(FileIOPermissionAccess.Write | FileIOPermissionAccess.Read, demandPath).Demand(); #endif String fullSourcePath; if (FullPath.EndsWith(Path.DirectorySeparatorChar)) { fullSourcePath = FullPath; } else { fullSourcePath = FullPath + Path.DirectorySeparatorChar; } if (String.Compare(fullSourcePath, fullDestDirName, StringComparison.OrdinalIgnoreCase) == 0) { throw new IOException(Environment.GetResourceString("IO.IO_SourceDestMustBeDifferent")); } String sourceRoot = Path.GetPathRoot(fullSourcePath); String destinationRoot = Path.GetPathRoot(fullDestDirName); if (String.Compare(sourceRoot, destinationRoot, StringComparison.OrdinalIgnoreCase) != 0) { throw new IOException(Environment.GetResourceString("IO.IO_SourceDestMustHaveSameRoot")); } if (!Win32Native.MoveFile(FullPath, destDirName)) { int hr = Marshal.GetLastWin32Error(); if (hr == Win32Native.ERROR_FILE_NOT_FOUND) // A dubious error code { hr = Win32Native.ERROR_PATH_NOT_FOUND; __Error.WinIOError(hr, DisplayPath); } if (hr == Win32Native.ERROR_ACCESS_DENIED) // We did this for Win9x. We can't change it for backcomp. { throw new IOException(Environment.GetResourceString("UnauthorizedAccess_IODenied_Path", DisplayPath)); } __Error.WinIOError(hr, String.Empty); } FullPath = fullDestDirName; OriginalPath = destDirName; DisplayPath = GetDisplayName(OriginalPath, FullPath); demandDir = new String[] { Directory.GetDemandDir(FullPath, true) }; // Flush any cached information about the directory. _dataInitialised = -1; }
internal static void InternalDelete(String path, bool checkHost) { String fullPath = Path.GetFullPathInternal(path); #if FEATURE_CORECLR if (checkHost) { FileSecurityState state = new FileSecurityState(FileSecurityStateAccess.Write, path, fullPath); state.EnsureState(); } #else // For security check, path should be resolved to an absolute path. FileIOPermission.QuickDemand(FileIOPermissionAccess.Write, fullPath, false, false); #endif bool r = Win32Native.DeleteFile(fullPath); if (!r) { int hr = Marshal.GetLastWin32Error(); if (hr==Win32Native.ERROR_FILE_NOT_FOUND) return; else __Error.WinIOError(hr, fullPath); } }
public static String GetTempPath() { #if !FEATURE_CORECLR new EnvironmentPermission(PermissionState.Unrestricted).Demand(); #endif StringBuilder sb = new StringBuilder(MAX_PATH); uint r = Win32Native.GetTempPath(MAX_PATH, sb); String path = sb.ToString(); if (r==0) __Error.WinIOError(); path = GetFullPathInternal(path); #if FEATURE_CORECLR FileSecurityState state = new FileSecurityState(FileSecurityStateAccess.Write, String.Empty, path); state.EnsureState(); #endif return path; }
private static void InternalMove(String sourceDirName,String destDirName,bool checkHost) { if (sourceDirName==null) throw new ArgumentNullException("sourceDirName"); if (sourceDirName.Length==0) throw new ArgumentException(Environment.GetResourceString("Argument_EmptyFileName"), "sourceDirName"); if (destDirName==null) throw new ArgumentNullException("destDirName"); if (destDirName.Length==0) throw new ArgumentException(Environment.GetResourceString("Argument_EmptyFileName"), "destDirName"); Contract.EndContractBlock(); String fullsourceDirName = Path.GetFullPathInternal(sourceDirName); String sourcePath = GetDemandDir(fullsourceDirName, false); if (PathInternal.IsDirectoryTooLong(sourcePath)) throw new PathTooLongException(Environment.GetResourceString("IO.PathTooLong")); String fulldestDirName = Path.GetFullPathInternal(destDirName); String destPath = GetDemandDir(fulldestDirName, false); if (PathInternal.IsDirectoryTooLong(destPath)) throw new PathTooLongException(Environment.GetResourceString("IO.PathTooLong")); #if FEATURE_CORECLR if (checkHost) { FileSecurityState sourceState = new FileSecurityState(FileSecurityStateAccess.Write | FileSecurityStateAccess.Read, sourceDirName, sourcePath); FileSecurityState destState = new FileSecurityState(FileSecurityStateAccess.Write, destDirName, destPath); sourceState.EnsureState(); destState.EnsureState(); } #else FileIOPermission.QuickDemand(FileIOPermissionAccess.Write | FileIOPermissionAccess.Read, sourcePath, false, false); FileIOPermission.QuickDemand(FileIOPermissionAccess.Write, destPath, false, false); #endif if (String.Compare(sourcePath, destPath, StringComparison.OrdinalIgnoreCase) == 0) throw new IOException(Environment.GetResourceString("IO.IO_SourceDestMustBeDifferent")); String sourceRoot = Path.GetPathRoot(sourcePath); String destinationRoot = Path.GetPathRoot(destPath); if (String.Compare(sourceRoot, destinationRoot, StringComparison.OrdinalIgnoreCase) != 0) throw new IOException(Environment.GetResourceString("IO.IO_SourceDestMustHaveSameRoot")); if (!Win32Native.MoveFile(sourceDirName, destDirName)) { int hr = Marshal.GetLastWin32Error(); if (hr == Win32Native.ERROR_FILE_NOT_FOUND) // Source dir not found { hr = Win32Native.ERROR_PATH_NOT_FOUND; __Error.WinIOError(hr, fullsourceDirName); } // This check was originally put in for Win9x (unfortunately without special casing it to be for Win9x only). We can't change the NT codepath now for backcomp reasons. if (hr == Win32Native.ERROR_ACCESS_DENIED) // WinNT throws IOException. This check is for Win9x. We can't change it for backcomp. throw new IOException(Environment.GetResourceString("UnauthorizedAccess_IODenied_Path", sourceDirName), Win32Native.MakeHRFromErrorCode(hr)); __Error.WinIOError(hr, String.Empty); } }
public override void Delete() { #if FEATURE_MONO_CAS #if FEATURE_CORECLR FileSecurityState state = new FileSecurityState(FileSecurityStateAccess.Write, DisplayPath, FullPath); state.EnsureState(); #else // For security check, path should be resolved to an absolute path. FileIOPermission.QuickDemand(FileIOPermissionAccess.Write, FullPath, false, false); #endif #endif #if MONO MonoIOError error; if (MonoIO.ExistsDirectory (FullPath, out error)) __Error.WinIOError (Win32Native.ERROR_ACCESS_DENIED, DisplayPath); if (!MonoIO.DeleteFile (FullPath, out error)) { int hr = (int) error; #else bool r = Win32Native.DeleteFile(FullPath); if (!r) { int hr = Marshal.GetLastWin32Error(); #endif if (hr==Win32Native.ERROR_FILE_NOT_FOUND) return; else __Error.WinIOError(hr, DisplayPath); } } [ComVisible(false)] [ResourceExposure(ResourceScope.None)] [ResourceConsumption(ResourceScope.Machine, ResourceScope.Machine)]
internal unsafe static void InternalCreateDirectory(String fullPath, String path, Object dirSecurityObj, bool checkHost) { #if FEATURE_MACL DirectorySecurity dirSecurity = (DirectorySecurity)dirSecurityObj; #endif // FEATURE_MACL int length = fullPath.Length; // We need to trim the trailing slash or the code will try to create 2 directories of the same name. if (length >= 2 && Path.IsDirectorySeparator(fullPath[length - 1])) length--; int lengthRoot = Path.GetRootLength(fullPath); // For UNC paths that are only // or /// if (length == 2 && Path.IsDirectorySeparator(fullPath[1])) throw new IOException(Environment.GetResourceString("IO.IO_CannotCreateDirectory", path)); // We can save a bunch of work if the directory we want to create already exists. This also // saves us in the case where sub paths are inaccessible (due to ERROR_ACCESS_DENIED) but the // final path is accessable and the directory already exists. For example, consider trying // to create c:\Foo\Bar\Baz, where everything already exists but ACLS prevent access to c:\Foo // and c:\Foo\Bar. In that case, this code will think it needs to create c:\Foo, and c:\Foo\Bar // and fail to due so, causing an exception to be thrown. This is not what we want. if (InternalExists(fullPath)) { return; } List<string> stackDir = new List<string>(); // Attempt to figure out which directories don't exist, and only // create the ones we need. Note that InternalExists may fail due // to Win32 ACL's preventing us from seeing a directory, and this // isn't threadsafe. bool somepathexists = false; if (length > lengthRoot) { // Special case root (fullpath = X:\\) int i = length-1; while (i >= lengthRoot && !somepathexists) { String dir = fullPath.Substring(0, i+1); if (!InternalExists(dir)) // Create only the ones missing stackDir.Add(dir); else somepathexists = true; while (i > lengthRoot && fullPath[i] != Path.DirectorySeparatorChar && fullPath[i] != Path.AltDirectorySeparatorChar) i--; i--; } } int count = stackDir.Count; if (stackDir.Count != 0 #if FEATURE_CAS_POLICY // All demands in full trust domains are no-ops, so skip // // The full path went through validity checks by being passed through FileIOPermissions already. // As a sub string of the full path can't fail the checks if the full path passes. && !CodeAccessSecurityEngine.QuickCheckForAllDemands() #endif ) { String[] securityList = new String[stackDir.Count]; stackDir.CopyTo(securityList, 0); for (int j = 0 ; j < securityList.Length; j++) securityList[j] += "\\."; // leaf will never have a slash at the end // Security check for all directories not present only. #if FEATURE_MACL AccessControlActions control = (dirSecurity == null) ? AccessControlActions.None : AccessControlActions.Change; FileIOPermission.QuickDemand(FileIOPermissionAccess.Write, control, securityList, false, false); #else #if FEATURE_CORECLR if (checkHost) { foreach (String demandPath in securityList) { FileSecurityState state = new FileSecurityState(FileSecurityStateAccess.Write, String.Empty, demandPath); state.EnsureState(); } } #else FileIOPermission.QuickDemand(FileIOPermissionAccess.Write, securityList, false, false); #endif #endif //FEATURE_MACL } // If we were passed a DirectorySecurity, convert it to a security // descriptor and set it in he call to CreateDirectory. Win32Native.SECURITY_ATTRIBUTES secAttrs = null; #if FEATURE_MACL if (dirSecurity != null) { secAttrs = new Win32Native.SECURITY_ATTRIBUTES(); secAttrs.nLength = (int)Marshal.SizeOf(secAttrs); // For ACL's, get the security descriptor from the FileSecurity. byte[] sd = dirSecurity.GetSecurityDescriptorBinaryForm(); byte * bytesOnStack = stackalloc byte[sd.Length]; Buffer.Memcpy(bytesOnStack, 0, sd, 0, sd.Length); secAttrs.pSecurityDescriptor = bytesOnStack; } #endif bool r = true; int firstError = 0; String errorString = path; // If all the security checks succeeded create all the directories while (stackDir.Count > 0) { String name = stackDir[stackDir.Count - 1]; stackDir.RemoveAt(stackDir.Count - 1); if (PathInternal.IsDirectoryTooLong(name)) throw new PathTooLongException(Environment.GetResourceString("IO.PathTooLong")); r = Win32Native.CreateDirectory(name, secAttrs); if (!r && (firstError == 0)) { int currentError = Marshal.GetLastWin32Error(); // While we tried to avoid creating directories that don't // exist above, there are at least two cases that will // cause us to see ERROR_ALREADY_EXISTS here. InternalExists // can fail because we didn't have permission to the // directory. Secondly, another thread or process could // create the directory between the time we check and the // time we try using the directory. Thirdly, it could // fail because the target does exist, but is a file. if (currentError != Win32Native.ERROR_ALREADY_EXISTS) firstError = currentError; else { // If there's a file in this directory's place, or if we have ERROR_ACCESS_DENIED when checking if the directory already exists throw. if (File.InternalExists(name) || (!InternalExists(name, out currentError) && currentError == Win32Native.ERROR_ACCESS_DENIED)) { firstError = currentError; // Give the user a nice error message, but don't leak path information. try { #if FEATURE_CORECLR if (checkHost) { FileSecurityState state = new FileSecurityState(FileSecurityStateAccess.PathDiscovery, String.Empty, GetDemandDir(name, true)); state.EnsureState(); } #else FileIOPermission.QuickDemand(FileIOPermissionAccess.PathDiscovery, GetDemandDir(name, true)); #endif // FEATURE_CORECLR errorString = name; } catch(SecurityException) {} } } } } // We need this check to mask OS differences // Handle CreateDirectory("X:\\foo") when X: doesn't exist. Similarly for n/w paths. if ((count == 0) && !somepathexists) { String root = InternalGetDirectoryRoot(fullPath); if (!InternalExists(root)) { // Extract the root from the passed in path again for security. __Error.WinIOError(Win32Native.ERROR_PATH_NOT_FOUND, InternalGetDirectoryRoot(path)); } return; } // Only throw an exception if creating the exact directory we // wanted failed to work correctly. if (!r && (firstError != 0)) { __Error.WinIOError(firstError, errorString); } }
public override void Delete() { #if FEATURE_CORECLR FileSecurityState state = new FileSecurityState(FileSecurityStateAccess.Write, DisplayPath, FullPath); state.EnsureState(); #else // For security check, path should be resolved to an absolute path. new FileIOPermission(FileIOPermissionAccess.Write, new String[] { FullPath }, false, false).Demand(); #endif bool r = Win32Native.DeleteFile(FullPath); if (!r) { int hr = Marshal.GetLastWin32Error(); if (hr==Win32Native.ERROR_FILE_NOT_FOUND) return; else __Error.WinIOError(hr, DisplayPath); } }
internal static DirectoryInfo InternalCreateDirectoryHelper(String path, bool checkHost) { Contract.Requires(path != null); Contract.Requires(path.Length != 0); String fullPath = Path.GetFullPathInternal(path); // You need read access to the directory to be returned back and write access to all the directories // that you need to create. If we fail any security checks we will not create any directories at all. // We attempt to create directories only after all the security checks have passed. This is avoid doing // a demand at every level. String demandDir = GetDemandDir(fullPath, true); #if FEATURE_CORECLR if (checkHost) { FileSecurityState state = new FileSecurityState(FileSecurityStateAccess.Read, path, demandDir); state.EnsureState(); // do the check on the AppDomainManager to make sure this is allowed } #else FileIOPermission.QuickDemand(FileIOPermissionAccess.Read, demandDir, false, false); #endif InternalCreateDirectory(fullPath, path, null, checkHost); return new DirectoryInfo(fullPath, false); }
public void MoveTo(String destFileName) { if (destFileName==null) throw new ArgumentNullException("destFileName"); if (destFileName.Length==0) throw new ArgumentException(Environment.GetResourceString("Argument_EmptyFileName"), "destFileName"); Contract.EndContractBlock(); String fullDestFileName = Path.GetFullPathInternal(destFileName); #if FEATURE_CORECLR FileSecurityState sourceState = new FileSecurityState(FileSecurityStateAccess.Write | FileSecurityStateAccess.Read, DisplayPath, FullPath); FileSecurityState destState = new FileSecurityState(FileSecurityStateAccess.Write, destFileName, fullDestFileName); sourceState.EnsureState(); destState.EnsureState(); #else new FileIOPermission(FileIOPermissionAccess.Write | FileIOPermissionAccess.Read, new String[] { FullPath }, false, false).Demand(); FileIOPermission.QuickDemand(FileIOPermissionAccess.Write, fullDestFileName, false, false); #endif if (!Win32Native.MoveFile(FullPath, fullDestFileName)) __Error.WinIOError(); FullPath = fullDestFileName; OriginalPath = destFileName; _name = Path.GetFileName(fullDestFileName); DisplayPath = GetDisplayPath(destFileName); // Flush any cached information about the file. _dataInitialised = -1; }
private static string InternalGetCurrentDirectory(bool checkHost) { string currentDirectory = ( #if FEATURE_PATHCOMPAT AppContextSwitches.UseLegacyPathHandling ? LegacyGetCurrentDirectory() : #endif NewGetCurrentDirectory()); string demandPath = GetDemandDir(currentDirectory, true); #if FEATURE_CORECLR if (checkHost) { FileSecurityState state = new FileSecurityState(FileSecurityStateAccess.PathDiscovery, String.Empty, demandPath); state.EnsureState(); } #else FileIOPermission.QuickDemand(FileIOPermissionAccess.PathDiscovery, demandPath, false, false); #endif return currentDirectory; }
public static String GetFullPath(String path) { String fullPath = GetFullPathInternal(path); #if FEATURE_CORECLR && !FEATURE_LEGACYNETCFIOSECURITY FileSecurityState state = new FileSecurityState(FileSecurityStateAccess.PathDiscovery, path, fullPath); state.EnsureState(); #elif !FEATURE_CORECLR new FileIOPermission( FileIOPermissionAccess.PathDiscovery, new String[] { fullPath }, false, false ).Demand(); #endif return fullPath; }
public void MoveTo(String destDirName) { if (destDirName==null) throw new ArgumentNullException("destDirName"); if (destDirName.Length==0) throw new ArgumentException(Environment.GetResourceString("Argument_EmptyFileName"), "destDirName"); Contract.EndContractBlock(); #if FEATURE_CORECLR FileSecurityState sourceState = new FileSecurityState(FileSecurityStateAccess.Write | FileSecurityStateAccess.Read, DisplayPath, Directory.GetDemandDir(FullPath, true)); sourceState.EnsureState(); #else new FileIOPermission(FileIOPermissionAccess.Write | FileIOPermissionAccess.Read, demandDir, false, false).Demand(); #endif String fullDestDirName = Path.GetFullPathInternal(destDirName); String demandPath; if (!fullDestDirName.EndsWith(Path.DirectorySeparatorChar)) fullDestDirName = fullDestDirName + Path.DirectorySeparatorChar; demandPath = fullDestDirName + '.'; // Demand read & write permission to destination. The reason is // we hand back a DirectoryInfo to the destination that would allow // you to read a directory listing from that directory. Sure, you // had the ability to read the file contents in the old location, // but you technically also need read permissions to the new // location as well, and write is not a true superset of read. #if FEATURE_CORECLR FileSecurityState destState = new FileSecurityState(FileSecurityStateAccess.Write, destDirName, demandPath); destState.EnsureState(); #else new FileIOPermission(FileIOPermissionAccess.Write | FileIOPermissionAccess.Read, demandPath).Demand(); #endif String fullSourcePath; if (FullPath.EndsWith(Path.DirectorySeparatorChar)) fullSourcePath = FullPath; else fullSourcePath = FullPath + Path.DirectorySeparatorChar; if (String.Compare(fullSourcePath, fullDestDirName, StringComparison.OrdinalIgnoreCase) == 0) throw new IOException(Environment.GetResourceString("IO.IO_SourceDestMustBeDifferent")); String sourceRoot = Path.GetPathRoot(fullSourcePath); String destinationRoot = Path.GetPathRoot(fullDestDirName); if (String.Compare(sourceRoot, destinationRoot, StringComparison.OrdinalIgnoreCase) != 0) throw new IOException(Environment.GetResourceString("IO.IO_SourceDestMustHaveSameRoot")); if (!Win32Native.MoveFile(FullPath, destDirName)) { int hr = Marshal.GetLastWin32Error(); if (hr == Win32Native.ERROR_FILE_NOT_FOUND) // A dubious error code { hr = Win32Native.ERROR_PATH_NOT_FOUND; __Error.WinIOError(hr, DisplayPath); } if (hr == Win32Native.ERROR_ACCESS_DENIED) // We did this for Win9x. We can't change it for backcomp. throw new IOException(Environment.GetResourceString("UnauthorizedAccess_IODenied_Path", DisplayPath)); __Error.WinIOError(hr,String.Empty); } FullPath = fullDestDirName; OriginalPath = destDirName; DisplayPath = GetDisplayName(OriginalPath, FullPath); demandDir = new String[] { Directory.GetDemandDir(FullPath, true) }; // Flush any cached information about the directory. _dataInitialised = -1; }
private static DateTime InternalGetCreationTimeUtc(String path, bool checkHost) { String fullPath = Path.GetFullPathInternal(path); #if FEATURE_CORECLR && !FEATURE_LEGACYNETCFIOSECURITY if (checkHost) { FileSecurityState state = new FileSecurityState(FileSecurityStateAccess.Read, path, fullPath); state.EnsureState(); } #elif !FEATURE_CORECLR new FileIOPermission(FileIOPermissionAccess.Read, new String[] { fullPath }, false, false ).Demand(); #endif Win32Native.WIN32_FILE_ATTRIBUTE_DATA data = new Win32Native.WIN32_FILE_ATTRIBUTE_DATA(); int dataInitialised = FillAttributeInfo(fullPath, ref data, false, false); if (dataInitialised != 0) __Error.WinIOError(dataInitialised, fullPath); long dt = ((long)(data.ftCreationTimeHigh) << 32) | ((long)data.ftCreationTimeLow); return DateTime.FromFileTimeUtc(dt); }
private static bool InternalExistsHelper(String path, bool checkHost) { try { if (path == null) return false; if (path.Length == 0) return false; path = Path.GetFullPathInternal(path); // After normalizing, check whether path ends in directory separator. // Otherwise, FillAttributeInfo removes it and we may return a false positive. // GetFullPathInternal should never return null Contract.Assert(path != null, "File.Exists: GetFullPathInternal returned null"); if (path.Length > 0 && Path.IsDirectorySeparator(path[path.Length - 1])) { return false; } #if FEATURE_CORECLR if (checkHost) { FileSecurityState state = new FileSecurityState(FileSecurityStateAccess.Read, String.Empty, path); state.EnsureState(); } #else FileIOPermission.QuickDemand(FileIOPermissionAccess.Read, path, false, false); #endif return InternalExists(path); } catch (ArgumentException) { } catch (NotSupportedException) { } // Security can throw this on ":" catch (SecurityException) { } catch (IOException) { } catch (UnauthorizedAccessException) { } return false; }
private static void InternalReplace(String sourceFileName, String destinationFileName, String destinationBackupFileName, bool ignoreMetadataErrors) { Contract.Requires(sourceFileName != null); Contract.Requires(destinationFileName != null); // Write permission to all three files, read permission to source // and dest. String fullSrcPath = Path.GetFullPathInternal(sourceFileName); String fullDestPath = Path.GetFullPathInternal(destinationFileName); String fullBackupPath = null; if (destinationBackupFileName != null) fullBackupPath = Path.GetFullPathInternal(destinationBackupFileName); #if FEATURE_CORECLR FileSecurityState sourceState = new FileSecurityState(FileSecurityStateAccess.Read | FileSecurityStateAccess.Write, sourceFileName, fullSrcPath); FileSecurityState destState = new FileSecurityState(FileSecurityStateAccess.Read | FileSecurityStateAccess.Write, destinationFileName, fullDestPath); FileSecurityState backupState = new FileSecurityState(FileSecurityStateAccess.Read | FileSecurityStateAccess.Write, destinationBackupFileName, fullBackupPath); sourceState.EnsureState(); destState.EnsureState(); backupState.EnsureState(); #else FileIOPermission perm = new FileIOPermission(FileIOPermissionAccess.Read | FileIOPermissionAccess.Write, new String[] { fullSrcPath, fullDestPath}); if (destinationBackupFileName != null) perm.AddPathList(FileIOPermissionAccess.Write, fullBackupPath); perm.Demand(); #endif int flags = Win32Native.REPLACEFILE_WRITE_THROUGH; if (ignoreMetadataErrors) flags |= Win32Native.REPLACEFILE_IGNORE_MERGE_ERRORS; bool r = Win32Native.ReplaceFile(fullDestPath, fullSrcPath, fullBackupPath, flags, IntPtr.Zero, IntPtr.Zero); if (!r) __Error.WinIOError(); }