public static void SetFullFolderPermissionsUnix(string path) { var nixFolderInfo = new UnixDirectoryInfo(path) { FileAccessPermissions = FileAccessPermissions.AllPermissions }; }
public UnixDirectoryEntry( UnixDirectoryInfo info, ClaimsPrincipal user, UnixUserInfo?userInfo, IUnixDirectoryEntry?parent = null) : base(info) { IsRoot = parent == null; Info = info; if (parent == null) { // Root user IsDeletable = false; } else if (info.Parent == info) { // File system root IsDeletable = false; } else if (userInfo != null && (userInfo.UserId == 0 || userInfo.GroupId == 0)) { IsDeletable = true; } else { IsDeletable = parent.GetEffectivePermissions(user).Write; } }
public UnixDirectoryEntry( [NotNull] UnixDirectoryInfo info, [NotNull] IFtpUser user, [CanBeNull] UnixUserInfo userInfo, IUnixDirectoryEntry parent = null) : base(info) { IsRoot = parent == null; Info = info; if (parent == null) { // Root user IsDeletable = false; } else if (info.Parent == info) { // File system root IsDeletable = false; } else if (userInfo != null && (userInfo.UserId == 0 || userInfo.GroupId == 0)) { IsDeletable = true; } else { IsDeletable = parent.GetEffectivePermissions(user).Write; } }
static void ScanPath(UnixDirectoryInfo dirinfo, string prefix) { foreach (var fileinfo in dirinfo.GetFileSystemEntries()) { string id = string.Concat(prefix, fileinfo.Name); switch (fileinfo.FileType) { case FileTypes.RegularFile: string hash; if (fileinfo.Length == 0) { hash = "0\t0\t0\t0"; } else { hash = FormatMd5Hash(fileinfo.FullName); } Console.WriteLine("{0}\t0\t{1}", id, hash); break; case FileTypes.Directory: ScanPath((UnixDirectoryInfo)fileinfo, string.Concat(id, "!")); break; default: /* Do nothing for symlinks or other weird things. */ break; } } }
private string GetDirectoryDriveName(string directoryPath) { var dir = new DirectoryInfo(directoryPath); DriveInfo drive; if (!PlatformDetector.IsUnix) { drive = DriveInfo.GetDrives().First(d => dir.FullName.StartsWith(d.RootDirectory.FullName, StringComparison.InvariantCultureIgnoreCase)); return(drive.Name); } var di = new UnixDirectoryInfo(directoryPath); while (di.FullName != "/") { var temp = ResolveSymbolicLinks(di.FullName); if (di.FullName != temp.FullName) { di = temp; break; } di = di.Parent; } if (di.FullName != "/") { dir = new DirectoryInfo(di.FullName); } drive = DriveInfo.GetDrives().FirstOrDefault(d => dir.FullName.StartsWith(d.RootDirectory.FullName) && d.RootDirectory.FullName != "/"); if (drive == null) { return("/"); } return(drive.Name); }
/// <inheritdoc /> public Task CreateSymbolicLink(string targetPath, string linkPath, CancellationToken cancellationToken) => Task.Factory.StartNew( () => { if (targetPath == null) { throw new ArgumentNullException(nameof(targetPath)); } if (linkPath == null) { throw new ArgumentNullException(nameof(linkPath)); } UnixFileSystemInfo fsInfo; var isFile = File.Exists(targetPath); cancellationToken.ThrowIfCancellationRequested(); if (isFile) { fsInfo = new UnixFileInfo(targetPath); } else { fsInfo = new UnixDirectoryInfo(targetPath); } cancellationToken.ThrowIfCancellationRequested(); fsInfo.CreateSymbolicLink(linkPath); }, cancellationToken, DefaultIOManager.BlockingTaskCreationOptions, TaskScheduler.Current);
protected internal static string GetFilePermissions(FileSystemInfo fileInfo) { var filename = fileInfo.FullName; FileAccessPermissions permissions = default(FileAccessPermissions); if (fileInfo is FileInfo) { try { permissions = new UnixFileInfo(filename).FileAccessPermissions; } catch (Exception ex) { Log.Debug("Unable to get access control for {0}: {1}", fileInfo.FullName, ex.Message); } } else if (fileInfo is DirectoryInfo) { try { permissions = new UnixDirectoryInfo(filename).FileAccessPermissions; } catch (Exception ex) { Log.Debug("Unable to get access control for {0}: {1}", fileInfo.FullName, ex.Message); } } else { return(null); } return(permissions.ToString()); }
public void Combine() { string path, expected; string current = UnixDirectoryInfo.GetCurrentDirectory(); path = UnixPath.Combine("/etc", "init.d"); Assert.AreEqual("/etc/init.d", path); path = UnixPath.Combine("one", ""); Assert.AreEqual("one", path); path = UnixPath.Combine("", "one"); Assert.AreEqual("one", path); path = UnixPath.Combine(current, "one"); expected = current + DSC + "one"; Assert.AreEqual(expected, path); path = UnixPath.Combine("one", current); Assert.AreEqual(current, path); path = UnixPath.Combine(current, expected); Assert.AreEqual(expected, path); path = DSC + "one"; path = UnixPath.Combine(path, "two" + DSC); expected = DSC + "one" + DSC + "two" + DSC; Assert.AreEqual(expected, path); path = "one" + DSC; path = UnixPath.Combine(path, DSC + "two"); expected = DSC + "two"; Assert.AreEqual(expected, path); path = "one" + DSC; path = UnixPath.Combine(path, "two" + DSC); expected = "one" + DSC + "two" + DSC; Assert.AreEqual(expected, path); path = UnixPath.Combine("/a", "b", "c", "/d", "e"); expected = "/d/e"; Assert.AreEqual(expected, path); try { path = UnixPath.Combine("one", null); Assert.Fail("Combine Fail #01"); } catch (Exception e) { Assert.AreEqual(typeof(ArgumentNullException), e.GetType()); } try { path = UnixPath.Combine(null, "one"); Assert.Fail("Combine Fail #02"); } catch (Exception e) { Assert.AreEqual(typeof(ArgumentNullException), e.GetType()); } }
public void LinuxFolderExists(string path) { Assert.True(Directory.Exists(path)); var directoryInfo = new UnixDirectoryInfo(path); Assert.Equal("quamotion", directoryInfo.OwnerGroup.GroupName); Assert.Equal("quamotion", directoryInfo.OwnerUser.UserName); }
public static Listing LoadFrom (string url, Comparison<FileNode> compare) { try { var udi = new UnixDirectoryInfo (url); return new Listing (url, udi.GetFileSystemEntries (), compare); } catch (Exception e){ return new Listing (); } return null; }
/// <summary> /// Allocates the specified pin. /// </summary> /// <param name="pin">The pin.</param> /// <param name="direction">The direction.</param> public void Allocate(ProcessorPin pin, PinDirection direction) { var gpioId = string.Format("gpio{0}", (int)pin); if (Directory.Exists(Path.Combine(gpioPath, gpioId))) { // Reinitialize pin virtual file using (var streamWriter = new StreamWriter(Path.Combine(gpioPath, "unexport"), false)) { streamWriter.Write((int)pin); streamWriter.Close(); } } // Export pin for file mode using (var streamWriter = new StreamWriter(Path.Combine(gpioPath, "export"), false)) { streamWriter.Write((int)pin); streamWriter.Close(); } // Set the direction on the pin and update the exported list SetPinMode(pin, direction == PinDirection.Input ? Interop.BCM2835_GPIO_FSEL_INPT : Interop.BCM2835_GPIO_FSEL_OUTP); if (Environment.OSVersion.Platform == PlatformID.Unix) { UnixDirectoryInfo udi = new UnixDirectoryInfo(Path.Combine(gpioPath, gpioId)); while ((udi.OwnerGroup.GroupName != "gpio") && (!udi.CanAccess(AccessModes.W_OK))) { Thread.Sleep(1); udi.Refresh(); } } // Set direction in pin virtual file var filePath = Path.Combine(gpioId, "direction"); using (var streamWriter = new StreamWriter(Path.Combine(gpioPath, filePath), false)) { streamWriter.Write(direction == PinDirection.Input ? "in" : "out"); } if (direction == PinDirection.Input) { PinResistor pinResistor; if (!pinResistors.TryGetValue(pin, out pinResistor) || pinResistor != PinResistor.None) { SetPinResistor(pin, PinResistor.None); } SetPinDetectedEdges(pin, PinDetectedEdges.Both); InitializePoll(pin); } }
/// <inheritdoc /> public Task <IUnixDirectoryEntry> CreateDirectoryAsync( IUnixDirectoryEntry targetDirectory, string directoryName, CancellationToken cancellationToken) { var targetEntry = (UnixDirectoryEntry)targetDirectory; var newDirectoryName = UnixPath.Combine(targetEntry.Info.FullName, directoryName); var newDirectoryInfo = new UnixDirectoryInfo(newDirectoryName); newDirectoryInfo.Create(); return(Task.FromResult((IUnixDirectoryEntry)CreateEntry(targetEntry, newDirectoryInfo))); }
public IEnumerable <string> GetFiles(string directory) { UnixDirectoryInfo unix_dir = new UnixDirectoryInfo(directory); foreach (UnixFileSystemInfo entry in unix_dir.GetFileSystemEntries()) { if (!entry.IsDirectory && entry.IsRegularFile && !entry.IsSocket && entry.Exists) { yield return(entry.FullName); } } }
public IEnumerable <SafeUri> GetDirectories(string directory) { var unix_dir = new UnixDirectoryInfo(directory); foreach (var entry in unix_dir.GetFileSystemEntries()) { var info = TraverseSymlink(entry); if (info != null && info.IsDirectory && info.Exists && !info.IsSocket) { yield return(new SafeUri(info.FullName, false)); } } }
public static void StartAutomaticChildren(IEnumerable <UnixDirectoryInfo> webDirs, ConfigurationManager configurationManager) { if (webDirs == null) { throw new ArgumentNullException("webDirs"); } if (configurationManager == null) { throw new ArgumentNullException("configurationManager"); } string shimSocketDir; string frontSocketDir; string backSocketDir; CreateAutomaticDirs(configurationManager.FpmGroup, configurationManager.HttpdGroup, out shimSocketDir, out frontSocketDir, out backSocketDir); foreach (UnixDirectoryInfo directoryInfo in webDirs) { if (directoryInfo == null) { continue; } var user = directoryInfo.OwnerUser.UserName; var group = directoryInfo.OwnerGroup.GroupName; var dirname = directoryInfo.Name; if (directoryInfo.OwnerUserId < 100) { Logger.Write(LogLevel.Debug, "Directory {0} skipped because owned by {1}:{2} ({3}:{4})", dirname, user, group, directoryInfo.OwnerUserId, directoryInfo.OwnerGroupId); continue; // Skip non-user directories } string shimSocket = Path.Combine(shimSocketDir, dirname); string frontSocket = Path.Combine(frontSocketDir, dirname); string backSocket = Path.Combine(backSocketDir, dirname); Func <Process> spawner = () => Spawner.SpawnOndemandChild(shimSocket); UnixDirectoryInfo info = directoryInfo; Action spawnShim = () => Spawner.SpawnShim(configurationManager, shimSocket, info.FullName, backSocket); Spawner.RunAs(user, configurationManager.WebGroup, spawnShim) (); var child = new ChildInfo { Spawner = spawner, OnDemandSock = backSocket, Name = directoryInfo.FullName }; children.Add(child); PrepareAutomaticChild(configurationManager, frontSocket, child, 500); } }
void LoadChild (int idx) { DirNode dn = this [idx] as DirNode; string name = GetName (idx, url, nodes); try { var udi = new UnixDirectoryInfo (name); dn.Nodes = PopulateNodes (true, udi.GetFileSystemEntries ()); dn.Expanded = true; } catch (Exception e){ Console.WriteLine ("Error loading {0}", name); // Show error? return; } Count = UpdateIndexes (nodes, 0, 0); }
/// <inheritdoc /> public Task CreateSymbolicLink(string targetPath, string linkPath, CancellationToken cancellationToken) => Task.Factory.StartNew(() => { UnixFileSystemInfo fsInfo; var isFile = File.Exists(targetPath); cancellationToken.ThrowIfCancellationRequested(); if (isFile) { fsInfo = new UnixFileInfo(targetPath); } else { fsInfo = new UnixDirectoryInfo(targetPath); } cancellationToken.ThrowIfCancellationRequested(); fsInfo.CreateSymbolicLink(linkPath); }, cancellationToken, TaskCreationOptions.LongRunning, TaskScheduler.Current);
/// <inheritdoc /> public Task <IUnixFileSystem> Create(IAccountInformation accountInformation) { var directories = _accountDirectoryQuery.GetDirectories(accountInformation); var basePath = string.IsNullOrEmpty(_options.Root) ? "/" : _options.Root; var rootPath = Path.Combine(basePath, directories.RootPath ?? string.Empty); _logger?.LogTrace( "Base path={basePath}, user root={userRootPath}, calculated root={calculatedRootPath}", basePath, directories.RootPath, rootPath); var userInfo = GetUserInfo(accountInformation); var root = new UnixDirectoryInfo(rootPath); var rootEntry = new UnixDirectoryEntry(root, accountInformation.User, userInfo); return(Task.FromResult <IUnixFileSystem>(new UnixFileSystem(rootEntry, accountInformation.User, userInfo))); }
private UnixDirectoryInfo ResolveSymbolicLinks(string directoryName) { var di = new UnixDirectoryInfo(directoryName); while (true) { try { var si = new UnixSymbolicLinkInfo(di.FullName); di = new UnixDirectoryInfo(si.ContentsPath); } catch { break; } } return(di); }
private void ScanPath(UnixDirectoryInfo dirinfo, PreingestEventArgs passEventArgs) { passEventArgs.Description = String.Format("Processing folder '{0}'.", dirinfo.FullName); OnTrigger(passEventArgs); dirinfo.FileAccessPermissions = FileAccessPermissions.AllPermissions; foreach (var fileinfo in dirinfo.GetFileSystemEntries()) { switch (fileinfo.FileType) { case FileTypes.RegularFile: fileinfo.FileAccessPermissions = FileAccessPermissions.AllPermissions; break; case FileTypes.Directory: ScanPath((UnixDirectoryInfo)fileinfo, passEventArgs); break; default: /* Do nothing for symlinks or other weird things. */ break; } } }
public static string GetFilePermissions(FileSystemInfo fileInfo) { if (fileInfo != null) { if (RuntimeInformation.IsOSPlatform(OSPlatform.Linux) || RuntimeInformation.IsOSPlatform(OSPlatform.OSX)) { var filename = fileInfo.FullName; FileAccessPermissions permissions = default(FileAccessPermissions); if (fileInfo is FileInfo) { try { permissions = new UnixFileInfo(filename).FileAccessPermissions; } catch (IOException ex) { Log.Debug("Unable to get access control for {0}: {1}", fileInfo.FullName, ex.Message); } } else if (fileInfo is DirectoryInfo) { try { permissions = new UnixDirectoryInfo(filename).FileAccessPermissions; } catch (IOException ex) { Log.Debug("Unable to get access control for {0}: {1}", fileInfo.FullName, ex.Message); } } else { return(null); } return(permissions.ToString()); } else { FileSystemSecurity fileSecurity = null; var filename = fileInfo.FullName; if (filename.Length >= 260 && !filename.StartsWith(@"\\?\")) { filename = $"\\?{filename}"; } if (fileInfo is FileInfo) { try { fileSecurity = new FileSecurity(filename, AccessControlSections.All); } catch (UnauthorizedAccessException) { Log.Verbose(Strings.Get("Err_AccessControl"), fileInfo.FullName); } catch (InvalidOperationException) { Log.Verbose("Invalid operation exception {0}.", fileInfo.FullName); } catch (FileNotFoundException) { Log.Verbose("File not found to get permissions {0}.", fileInfo.FullName); } catch (ArgumentException) { Log.Debug("Filename not valid for getting permissions {0}", fileInfo.FullName); } catch (Exception e) { Log.Debug(e, $"Error with {fileInfo.FullName}"); } } else if (fileInfo is DirectoryInfo) { try { fileSecurity = new DirectorySecurity(filename, AccessControlSections.All); } catch (UnauthorizedAccessException) { Log.Verbose(Strings.Get("Err_AccessControl"), fileInfo.FullName); } catch (InvalidOperationException) { Log.Verbose("Invalid operation exception {0}.", fileInfo.FullName); } catch (Exception e) { Log.Debug(e, $"Error with {fileInfo.FullName}"); } } else { return(null); } if (fileSecurity != null) { return(fileSecurity.GetSecurityDescriptorSddlForm(AccessControlSections.All)); } else { return(""); } } } return(""); }
public void Delete(string directory, bool recursive) { UnixDirectoryInfo unix_dir = new UnixDirectoryInfo(directory); unix_dir.Delete(recursive); }
public static int Main(string [] args) { var configurationManager = new ConfigurationManager("mono-fpm"); if (!configurationManager.LoadCommandLineArgs(args)) { return(1); } // Show the help and exit. if (configurationManager.Help) { configurationManager.PrintHelp(); #if DEBUG Console.WriteLine("Press any key..."); Console.ReadKey(); #endif return(0); } // Show the version and exit. if (configurationManager.Version) { Version.Show(); return(0); } if (!configurationManager.LoadConfigFile()) { return(1); } configurationManager.SetupLogger(); #if DEBUG // Log everything while debugging Logger.Level = LogLevel.All; #endif Logger.Write(LogLevel.Debug, Assembly.GetExecutingAssembly().GetName().Name); string configDir = configurationManager.ConfigDir; string webDir = configurationManager.WebDir; if (String.IsNullOrEmpty(configDir) && (!Platform.IsUnix || String.IsNullOrEmpty(webDir))) { if (Platform.IsUnix) { Logger.Write(LogLevel.Error, "You MUST provide a configuration directory with the --config-dir parameter or web directories with the --web-dir parameter."); } else { Logger.Write(LogLevel.Error, "You MUST provide a configuration directory with the --config-dir parameter."); } return(1); } if (!String.IsNullOrEmpty(configDir)) { var configDirInfo = new DirectoryInfo(configDir); if (!configDirInfo.Exists) { Logger.Write(LogLevel.Error, "The configuration directory \"{0}\" does not exist!", configDir); } else { Logger.Write(LogLevel.Debug, "Configuration directory {0} exists, loading configuration files", configDir); FileInfo[] configFiles = configDirInfo.GetFiles("*.xml"); ChildrenManager.StartChildren(configFiles, configurationManager); } } if (Platform.IsUnix && !String.IsNullOrEmpty(webDir)) { var webDirInfo = new UnixDirectoryInfo(Path.GetFullPath(webDir)); if (!webDirInfo.Exists) { Logger.Write(LogLevel.Error, "The web directory \"{0}\" does not exist!", webDir); } else { Logger.Write(LogLevel.Debug, "Web directory {0} exists, starting children", webDir); IEnumerable <UnixDirectoryInfo> webDirs = from entry in webDirInfo.GetFileSystemEntries() let dir = entry as UnixDirectoryInfo where dir != null select dir; if (configurationManager.HttpdGroup == null) { Logger.Write(LogLevel.Error, "Couldn't autodetect the httpd group, you must specify it explicitly with --httpd-group"); return(1); } if (!CheckGroupExists(configurationManager.FpmGroup) || !CheckGroupExists(configurationManager.HttpdGroup) || !CheckUserExists(configurationManager.FpmUser)) { return(1); } ChildrenManager.StartAutomaticChildren(webDirs, configurationManager); } } Platform.SetIdentity(configurationManager.FpmUser, configurationManager.FpmGroup); if (!configurationManager.Stoppable) { var sleep = new ManualResetEvent(false); sleep.WaitOne(); // Do androids dream of electric sheep? } Console.WriteLine("Hit Return to stop the server."); Console.ReadLine(); ChildrenManager.TermChildren(); ChildrenManager.KillChildren(); return(0); }
public static string CollectFilePermissionInformation(string filePath) { var bldr = new StringBuilder(); try { if (Platform.IsWindows) { var currentUser = WindowsIdentity.GetCurrent(); bldr.AppendLine($"current user is {currentUser.Name}"); var principal = new WindowsPrincipal(currentUser); bool isInRoleWithAccess = false; bool accessDenied = false; bool accessAllowed = false; FileSystemRights accessRights = FileSystemRights.Write; var acl = File.GetAccessControl(filePath); var rules = acl.GetAccessRules(true, true, typeof(NTAccount)); var sid = acl.GetOwner(typeof(SecurityIdentifier)); var acct = sid.Translate(typeof(NTAccount)) as NTAccount; if (acct != null) { bldr.AppendLine($"owner of \"{filePath}\" is {acct.Value}"); } var fileAttributes = RobustFile.GetAttributes(filePath); bldr.AppendLine($"{filePath} current ReadOnly attribute of {filePath} is {(fileAttributes & FileAttributes.ReadOnly) == FileAttributes.ReadOnly}"); foreach (AuthorizationRule rule in rules) { var fsAccessRule = rule as FileSystemAccessRule; if (fsAccessRule == null) { continue; } if ((fsAccessRule.FileSystemRights & accessRights) > 0) { var ntAccount = rule.IdentityReference as NTAccount; if (ntAccount == null) { continue; } if (principal.IsInRole(ntAccount.Value)) { if (fsAccessRule.AccessControlType == AccessControlType.Deny) { bldr.AppendLine($"current user is denied write access to {filePath} by {ntAccount.Value}{(rule.IsInherited ? " (inherited)":"")}"); accessDenied = true; } if (fsAccessRule.AccessControlType == AccessControlType.Allow) { bldr.AppendLine($"current user is allowed write access to {filePath} by {ntAccount.Value}{(rule.IsInherited ? " (inherited)":"")}"); accessAllowed = true; } isInRoleWithAccess = true; } } } if (isInRoleWithAccess) { if (!accessAllowed) { bldr.AppendLine($"current user is not explicitly allowed write access to {filePath}"); } if (!accessDenied) { bldr.AppendLine($"current user is not explicitly denied write access to {filePath}"); } } else { bldr.AppendLine($"current user is not explicitly given access to {filePath}"); } } else { var folder = Path.GetDirectoryName(filePath); var fileInfo = new UnixFileInfo(filePath); var dirInfo = new UnixDirectoryInfo(folder); var userInfo = UnixUserInfo.GetRealUser(); bldr.AppendLine($"current user is {userInfo.UserName}"); bldr.AppendLine($"owner of \"{filePath}\" is {fileInfo.OwnerUser.UserName}"); bldr.AppendLine($"permissions of \"{filePath}\" = {fileInfo.FileAccessPermissions.ToString()}"); bldr.AppendLine($"owner of \"{folder}\" is {dirInfo.OwnerUser.UserName}"); bldr.AppendLine($"permissions of \"{folder}\" = {dirInfo.FileAccessPermissions.ToString()}"); } } catch (Exception e) { bldr.AppendLine($"Caught exception {e} while trying to collect information about {filePath}"); } return(bldr.ToString()); }
private bool DirectoryIsSuitable(string folderToTest) { // A directory with invalid characters isn't suitable string pathToTest = null; try { pathToTest = Path.GetFullPath(folderToTest); } catch (Exception) { return(false); } // A directory doesn't have to exist yet to be suitable but if the root directory isn't suitable that's not good while (!Directory.Exists(pathToTest)) { if (String.IsNullOrEmpty(pathToTest.Trim())) { return(false); } pathToTest = Path.GetDirectoryName(pathToTest); } if (!MiscUtils.IsUnix) { // Check the OS file permissions for the folder var accessControlList = Directory.GetAccessControl(pathToTest); var accessRules = accessControlList.GetAccessRules(true, true, typeof(SecurityIdentifier)); var readAllowed = false; var writeAllowed = false; foreach (FileSystemAccessRule rule in accessRules) { //If we find one that matches the identity we are looking for using (var currentUserIdentity = WindowsIdentity.GetCurrent()) { var userName = currentUserIdentity.User.Value; if ( rule.IdentityReference.Value.Equals(userName, StringComparison.CurrentCultureIgnoreCase) || currentUserIdentity.Groups.Contains(rule.IdentityReference)) { if ((FileSystemRights.Read & rule.FileSystemRights) == FileSystemRights.Read) { if (rule.AccessControlType == AccessControlType.Allow) { readAllowed = true; } if (rule.AccessControlType == AccessControlType.Deny) { return(false); } } if ((FileSystemRights.Write & rule.FileSystemRights) == FileSystemRights.Write) { if (rule.AccessControlType == AccessControlType.Allow) { writeAllowed = true; } if (rule.AccessControlType == AccessControlType.Deny) { return(false); } } } } return(readAllowed && writeAllowed); } } #if __MonoCS__ var ufi = new UnixDirectoryInfo(pathToTest); return(ufi.CanAccess(Mono.Unix.Native.AccessModes.R_OK) && ufi.CanAccess(Mono.Unix.Native.AccessModes.W_OK)); // accessible for writing #else return(false); // unreachable in practice #endif }
public static string GetFilePermissions(FileSystemInfo fileInfo) { if (fileInfo != null) { if (RuntimeInformation.IsOSPlatform(OSPlatform.Linux) || RuntimeInformation.IsOSPlatform(OSPlatform.OSX)) { var filename = fileInfo.FullName; FileAccessPermissions permissions = default(FileAccessPermissions); try { if (fileInfo is FileInfo) { permissions = new UnixFileInfo(filename).FileAccessPermissions; } else if (fileInfo is DirectoryInfo) { permissions = new UnixDirectoryInfo(filename).FileAccessPermissions; } } catch (Exception e) when( e is IOException || e is InvalidOperationException ) { Log.Verbose("Unable to get access control for {0}: {1}", fileInfo.FullName, e.GetType().ToString()); } catch (Exception e) { Log.Debug($"Error Getting File Permissions {e.GetType().ToString()}"); } return(permissions.ToString()); } else if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows)) { var filename = fileInfo.FullName; if (filename.Length >= 260 && !filename.StartsWith(@"\\?\")) { filename = $"\\?{filename}"; } try { if (fileInfo is FileInfo) { return(new FileSecurity(filename, AccessControlSections.All).GetSecurityDescriptorSddlForm(AccessControlSections.All)); } else if (fileInfo is DirectoryInfo) { return(new DirectorySecurity(filename, AccessControlSections.All).GetSecurityDescriptorSddlForm(AccessControlSections.All)); } } catch (Exception e) when( e is ArgumentException || e is ArgumentNullException || e is DirectoryNotFoundException || e is FileNotFoundException || e is IOException || e is NotSupportedException || e is PlatformNotSupportedException || e is PathTooLongException || e is PrivilegeNotHeldException || e is SystemException || e is UnauthorizedAccessException) { var InfoType = fileInfo is FileInfo ? "FileSecurity" : "DirectorySecurity"; Log.Verbose($"Error parsing {InfoType} for {fileInfo.FullName} {e.GetType().ToString()}"); } catch (Exception e) { Log.Debug($"Error Getting File Permissions {e.GetType().ToString()}"); } return(string.Empty); } } return(string.Empty); }
static void Main() { var dirinfo = new UnixDirectoryInfo("."); ScanPath(dirinfo, ""); }
public override void Execute() { var eventModel = CurrentActionProperties(TargetCollection, this.GetType().Name); OnTrigger(new PreingestEventArgs { Description = String.Format("Start expanding container '{0}'.", TargetCollection), Initiate = DateTimeOffset.Now, ActionType = PreingestActionStates.Started, PreingestAction = eventModel }); string output = string.Empty; string error = string.Empty; var anyMessages = new List <String>(); bool isSuccess = false; try { if (!File.Exists(TargetCollection)) { throw new FileNotFoundException("Collection not found!", TargetCollection); } string sessionFolder = Path.Combine(ApplicationSettings.DataFolderName, SessionGuid.ToString()); using (var tarProcess = new Process() { StartInfo = new ProcessStartInfo { FileName = "tar", Arguments = String.Format("-C \"{0}\" -oxvf \"{1}\"", sessionFolder, TargetCollection), RedirectStandardOutput = true, RedirectStandardError = true, UseShellExecute = false, CreateNoWindow = true, } }) { tarProcess.Start(); OnTrigger(new PreingestEventArgs { Description = "Container is expanding content.", Initiate = DateTimeOffset.Now, ActionType = PreingestActionStates.Executing, PreingestAction = eventModel }); this.Logger.LogDebug("Unpacking container '{0}'", TargetCollection); output = tarProcess.StandardOutput.ReadToEnd(); error = tarProcess.StandardError.ReadToEnd(); tarProcess.WaitForExit(); } if (!String.IsNullOrEmpty(output)) { this.Logger.LogDebug(output); } if (!String.IsNullOrEmpty(error)) { this.Logger.LogDebug(error); } var fileInformation = new FileInfo(TargetCollection); anyMessages.Add(String.Concat("Name : ", fileInformation.Name)); anyMessages.Add(String.Concat("Extension : ", fileInformation.Extension)); anyMessages.Add(String.Concat("Size : ", fileInformation.Length)); anyMessages.Add(String.Concat("CreationTime : ", fileInformation.CreationTimeUtc)); anyMessages.Add(String.Concat("LastAccessTime : ", fileInformation.LastAccessTimeUtc)); anyMessages.Add(String.Concat("LastWriteTime : ", fileInformation.LastWriteTimeUtc)); eventModel.Properties.Messages = anyMessages.ToArray(); bool isWindows = RuntimeInformation.IsOSPlatform(System.Runtime.InteropServices.OSPlatform.Windows); if (!isWindows) { var unixDirInfo = new UnixDirectoryInfo(sessionFolder); //trigger event executing var passEventArgs = new PreingestEventArgs { Description = String.Format("Execute chmod 777 for container '{0}'", TargetCollection), Initiate = DateTimeOffset.Now, ActionType = PreingestActionStates.Executing, PreingestAction = eventModel }; OnTrigger(passEventArgs); ScanPath(unixDirInfo, passEventArgs); } isSuccess = true; } catch (Exception e) { isSuccess = false; anyMessages.Clear(); anyMessages.Add(String.Format("Unpack container file: '{0}' failed!", TargetCollection)); anyMessages.Add(e.Message); anyMessages.Add(e.StackTrace); Logger.LogError(e, "Unpack container file: '{0}' failed!", TargetCollection); eventModel.ActionResult.ResultValue = PreingestActionResults.Failed; eventModel.Properties.Messages = anyMessages.ToArray(); eventModel.Summary.Processed = 1; eventModel.Summary.Accepted = 0; eventModel.Summary.Rejected = 1; OnTrigger(new PreingestEventArgs { Description = "An exception occured while unpacking a container!", Initiate = DateTimeOffset.Now, ActionType = PreingestActionStates.Failed, PreingestAction = eventModel }); } finally { if (isSuccess) { eventModel.ActionResult.ResultValue = PreingestActionResults.Success; eventModel.Summary.Processed = 1; eventModel.Summary.Accepted = 1; eventModel.Summary.Rejected = 0; eventModel.ActionData = output.Split(Environment.NewLine); OnTrigger(new PreingestEventArgs { Description = "Unpacking the container is done.", Initiate = DateTimeOffset.Now, ActionType = PreingestActionStates.Completed, PreingestAction = eventModel }); } } }
Result CopyDirectory(string source_absolute_path, string target_path, FilePermissions protection) { if (!dirs_created.ContainsKey(target_path)) { while (true) { int r = Syscall.mkdir(target_path, protection | FilePermissions.S_IRWXU); if (r != -1) { break; } Errno errno = Stdlib.GetLastError(); if (errno == Errno.EINTR) { continue; } if (errno == Errno.EEXIST || errno == Errno.EISDIR) { break; } var msg = UnixMarshal.GetErrorDescription(errno); switch (Interaction.Query(OResult.RetryIgnoreCancel, msg, "While creating \"{0}\"", target_path)) { case OResult.Retry: continue; case OResult.Ignore: break; case OResult.Cancel: return(Result.Cancel); } } dirs_created [target_path] = protection; } var udi = new UnixDirectoryInfo(source_absolute_path); foreach (var entry in udi.GetFileSystemEntries()) { if (entry.Name == "." || entry.Name == "..") { continue; } string source = Path.Combine(source_absolute_path, entry.Name); string target = Path.Combine(target_path, entry.Name); if (entry.IsDirectory) { if (CopyDirectory(source, target, entry.Protection) == Result.Cancel) { return(Result.Cancel); } } else { if (!CopyFile(source, target)) { return(skip ? Result.Skip : Result.Cancel); } } } return(Result.Ok); }