Exemplo n.º 1
0
        /// <summary>
        /// Copies the file at the given path to the server, which could be anywhere from
        /// the local machine to a remote one.
        /// </summary>
        /// <param name="virtualPath">The virtual path.</param>
        public void CopyToServer(VirtualPath virtualPath)
        {
            var fromFullPath = _pathFactory.CreateShadwoFullPath4Write(virtualPath);

            byte[] infoBytes = _serverProxy.Get(new Uri("/BitTorrent/Info"));
            var    infoObj   = XmlUtil.FromXml <BitTorrentServiceInfo>(
                Encoding.UTF8.GetString(infoBytes));

            if (infoObj.ServerCacheUri.IsLoopback)
            {
                // Server on the same machine, we copy from file system.
                var relativePath = virtualPath.PathString.Substring(
                    virtualPath.PathString.IndexOf(Path.DirectorySeparatorChar, 1));
                var toFullPath = UriUtil.CombinePaths(infoObj.ServerCacheUri.LocalPath,
                                                      new Uri(relativePath, UriKind.Relative));
                IOUtil.PrepareParentDirForPath(toFullPath);
                if (SysEnvironment.OSVersion == OS.Unix)
                {
                    // In case of Unix, we actually use symbolic link instead of copying.
                    var symlink = new UnixSymbolicLinkInfo(toFullPath);
                    Logger.WriteLineIf(LogLevel.Verbose, _log_props, string.Format(
                                           "Creating Symlink: {0} -> {1}", toFullPath, fromFullPath.PathString));
                    // Linking toPath to fromPath == Copy fromPath to toPath.
                    symlink.CreateSymbolicLinkTo(fromFullPath.PathString);
                }
                else
                {
                    throw new NotImplementedException("Only Unix hosts are currently supported.");
                }
            }
            else
            {
                throw new NotImplementedException("Only local machine is currently supported.");
            }
        }
Exemplo n.º 2
0
        protected override List <Disk> LoadLogicalVolumesInternal()
        {
            //var files = new string[] { "./FAT16.img", "./FAT32.img", "./NTFS.img"/* "/dev/sdb5" */ };

            /*var disks = new List<Disk>();
             * foreach (var file in files) {
             *      var disk  = new LinLogicalDisk(file);
             *      disks.Add(disk);
             * }
             * return disks;*/

            var disks = new List <Disk>();

#if MONO
            foreach (var file in Directory.GetFiles("/dev/disk/by-path"))
            {
                var actual_path = new UnixSymbolicLinkInfo(file).GetContents().FullName;
                try {
                    var disk = new LinLogicalDisk(actual_path);
                    disks.Add(disk);
                } catch (Exception e) {
                    Console.Error.WriteLine("Could not read device: " + actual_path);
                    //Console.Error.WriteLine(e);
                }
            }
#endif
            return(disks);
        }
Exemplo n.º 3
0
        private static bool SymlinkedDirExists(string dirPath)
        {
            dirPath = dirPath.TrimEnd(Path.DirectorySeparatorChar);
            try
            {
                UnixFileSystemInfo fileSystemInfo = UnixFileSystemInfo.GetFileSystemEntry(dirPath);
                if (!fileSystemInfo.IsSymbolicLink)
                {
                    return(false);
                }

                UnixSymbolicLinkInfo symlinkInfo = fileSystemInfo as UnixSymbolicLinkInfo;
                if (symlinkInfo.HasContents && symlinkInfo.GetContents().IsDirectory)
                {
                    return(true);
                }
            }
            catch (DllNotFoundException ex)
            {
                throw new TransferException(TransferErrorCode.FailToEnumerateDirectory,
                                            Resources.UnableToLoadDLL,
                                            ex);
            }

            return(false);
        }
Exemplo n.º 4
0
        protected override void CopyFileInternal(string source, string destination, bool overwrite)
        {
            var sourceInfo = UnixFileSystemInfo.GetFileSystemEntry(source);

            if (sourceInfo.IsSymbolicLink)
            {
                var isSameDir   = UnixPath.GetDirectoryName(source) == UnixPath.GetDirectoryName(destination);
                var symlinkInfo = (UnixSymbolicLinkInfo)sourceInfo;
                var symlinkPath = symlinkInfo.ContentsPath;

                var newFile = new UnixSymbolicLinkInfo(destination);

                if (FileExists(destination) && overwrite)
                {
                    DeleteFile(destination);
                }

                if (isSameDir)
                {
                    // We're in the same dir, so we can preserve relative symlinks.
                    newFile.CreateSymbolicLinkTo(symlinkInfo.ContentsPath);
                }
                else
                {
                    var fullPath = UnixPath.Combine(UnixPath.GetDirectoryName(source), symlinkPath);
                    newFile.CreateSymbolicLinkTo(fullPath);
                }
            }
            else
            {
                base.CopyFileInternal(source, destination, overwrite);
            }
        }
Exemplo n.º 5
0
        private UnixFileSystemInfo TraverseSymlink(UnixFileSystemInfo info)
        {
            lock (visited_symlinks) {
                visited_symlinks.Clear();
                while (info.IsSymbolicLink)
                {
                    if (visited_symlinks.Contains(info.FullName))
                    {
                        return(null);
                    }
                    visited_symlinks.Add(info.FullName);
                    var target = new UnixSymbolicLinkInfo(info.FullName).GetContents();
                    if (info.FullName.StartsWith(target.FullName))
                    {
                        return(null);
                    }
                    if (!target.Exists)
                    {
                        return(null);
                    }
                    info = target;
                }

                return(info);
            }
        }
Exemplo n.º 6
0
        public override string ReadSymLink(string path)
        {
            UnixSymbolicLinkInfo i = new UnixSymbolicLinkInfo(path);

            switch (i.FileType)
            {
            case FileTypes.SymbolicLink:
                try {
                    return(i.GetContents().FullName);
                } catch (Exception ex) {
                    Log.Error("Failed to read symbolic link: '", path, "'");
                    Log.Error(ex);
                    return(null);
                }

            case FileTypes.Fifo:
            case FileTypes.Socket:
            case FileTypes.BlockDevice:
            case FileTypes.CharacterDevice:
            case FileTypes.Directory:
            case FileTypes.RegularFile:
            default:
                return(null);
            }
        }
Exemplo n.º 7
0
        public PosixFile(string fName)
        {
            this.SnapFullPath = fName;
            //this.Name = this.SnapFullPath.Substring(this.SnapFullPath.LastIndexOf('/')+1);
            ufi       = new UnixFileInfo(this.SnapFullPath);
            this.Name = ufi.Name;
            this.Kind = GetUKind();
            Console.WriteLine("file " + this.SnapFullPath + ", kind=" + this.Kind.ToString());
            this.ID = ufi.Inode;
            //this.IsSparse = false;
            if (this.Kind == FileType.File)            // though dirs also have sizes, useless to get it
            {
                this.FileSize = ufi.Length;
            }
            //this.LastAccessedTime = ufi.LastAccessTime;
            this.LastModifiedTime         = Utilities.Utils.GetUtcUnixTime(ufi.LastWriteTimeUtc);        //ufi.LastWriteTime.ToFileTimeUtc();
            this.LastMetadataModifiedTime = Utilities.Utils.GetUtcUnixTime(ufi.LastStatusChangeTimeUtc); //ufi.LastStatusChangeTime.ToFileTimeUtc();
            this.CreateTime  = 0;                                                                        // dummy value for correctness of incrementals using filecompare
            this.Permissions = (uint)ufi.FileAccessPermissions;

            this.SpecialAttributes = (int)ufi.FileSpecialAttributes;

            if (this.Kind == FileType.Symlink)
            {
                UnixSymbolicLinkInfo link = new UnixSymbolicLinkInfo(this.SnapFullPath);
                if (link.HasContents)
                {
                    this.TargetName = link.GetContents().FullName;
                }
            }
            this.OwnerUser  = (uint)ufi.OwnerUserId;
            this.OwnerGroup = (uint)ufi.OwnerGroupId;
            BlockMetadata   = new FileBlockMetadata();
        }
        public override NodeType GetSymbolicLinkTargetType(string path)
        {
            UnixSymbolicLinkInfo obj;

            try
            {
                obj = new UnixSymbolicLinkInfo(path);
            }
            catch (InvalidOperationException)
            {
                /* Not a symbolic link */

                return(null);
            }

            try
            {
                if (!obj.IsSymbolicLink)
                {
                    return(null);
                }

                var retval = obj.GetContents();

                if (retval == null)
                {
                    return(null);
                }

                var isDirectory = retval.IsDirectory;

                if (isDirectory)
                {
                    return(NodeType.Directory);
                }

                var isRegularFile = retval.IsRegularFile;

                if (isRegularFile)
                {
                    return(NodeType.File);
                }

                return(null);
            }
            catch (OutOfMemoryException)
            {
                throw;
            }
            catch (StackOverflowException)
            {
                throw;
            }
            catch (Exception)
            {
                return(null);
            }
        }
        public void UpdatePermissionsOnUnixUsingMonoPosix()
        {
            var fileSystemEntry = UnixFileSystemInfo.GetFileSystemEntry("path");

            fileSystemEntry.FileAccessPermissions = FileAccessPermissions.UserRead;
            fileSystemEntry.FileAccessPermissions = FileAccessPermissions.UserWrite;
            fileSystemEntry.FileAccessPermissions = FileAccessPermissions.UserExecute;
            fileSystemEntry.FileAccessPermissions = FileAccessPermissions.UserReadWriteExecute;

            fileSystemEntry.FileAccessPermissions = FileAccessPermissions.GroupRead;
            fileSystemEntry.FileAccessPermissions = FileAccessPermissions.GroupWrite;
            fileSystemEntry.FileAccessPermissions = FileAccessPermissions.GroupExecute;
            fileSystemEntry.FileAccessPermissions = FileAccessPermissions.GroupReadWriteExecute;

            fileSystemEntry.FileAccessPermissions = FileAccessPermissions.UserRead | FileAccessPermissions.GroupRead;

            fileSystemEntry.FileAccessPermissions = FileAccessPermissions.AllPermissions;                                                               // Noncompliant (DefaultPermissions | OtherExecute | GroupExecute | UserExecute, // 0x000001FF)
            fileSystemEntry.FileAccessPermissions = FileAccessPermissions.DefaultPermissions;                                                           // Noncompliant (OtherWrite | OtherRead | GroupWrite | GroupRead | UserWrite | UserRead, // 0x000001B6)
            fileSystemEntry.FileAccessPermissions = FileAccessPermissions.OtherReadWriteExecute;                                                        // Noncompliant
            fileSystemEntry.FileAccessPermissions = FileAccessPermissions.OtherExecute;                                                                 // Noncompliant
            fileSystemEntry.FileAccessPermissions = FileAccessPermissions.OtherWrite;                                                                   // Noncompliant
            fileSystemEntry.FileAccessPermissions = FileAccessPermissions.OtherRead;                                                                    // Noncompliant {{Make sure this permission is safe.}}

            fileSystemEntry.FileAccessPermissions |= FileAccessPermissions.AllPermissions;                                                              // Noncompliant (DefaultPermissions | OtherExecute | GroupExecute | UserExecute, // 0x000001FF)
            fileSystemEntry.FileAccessPermissions |= FileAccessPermissions.DefaultPermissions;                                                          // Noncompliant (OtherWrite | OtherRead | GroupWrite | GroupRead | UserWrite | UserRead, // 0x000001B6)
            fileSystemEntry.FileAccessPermissions |= FileAccessPermissions.OtherReadWriteExecute;                                                       // Noncompliant
            fileSystemEntry.FileAccessPermissions |= FileAccessPermissions.OtherExecute;                                                                // Noncompliant
            fileSystemEntry.FileAccessPermissions |= FileAccessPermissions.OtherWrite;                                                                  // Noncompliant
            fileSystemEntry.FileAccessPermissions |= FileAccessPermissions.OtherRead;                                                                   // Noncompliant

            fileSystemEntry.FileAccessPermissions ^= FileAccessPermissions.AllPermissions;                                                              // Noncompliant - depending on the case this might add or remove permissions
            fileSystemEntry.FileAccessPermissions ^= FileAccessPermissions.DefaultPermissions;                                                          // Noncompliant
            fileSystemEntry.FileAccessPermissions ^= FileAccessPermissions.OtherReadWriteExecute;                                                       // Noncompliant
            fileSystemEntry.FileAccessPermissions ^= FileAccessPermissions.OtherExecute;                                                                // Noncompliant
            fileSystemEntry.FileAccessPermissions ^= FileAccessPermissions.OtherWrite;                                                                  // Noncompliant
            fileSystemEntry.FileAccessPermissions ^= FileAccessPermissions.OtherRead;                                                                   // Noncompliant

            fileSystemEntry.FileAccessPermissions = FileAccessPermissions.UserRead | FileAccessPermissions.GroupRead | FileAccessPermissions.OtherRead; // Noncompliant
//                                                                                                                                           ^^^^^^^^^
            UnixFileInfo.GetFileSystemEntry("path").FileAccessPermissions         = FileAccessPermissions.AllPermissions;                               // Noncompliant
            UnixSymbolicLinkInfo.GetFileSystemEntry("path").FileAccessPermissions = FileAccessPermissions.AllPermissions;                               // Noncompliant

            if (fileSystemEntry.FileAccessPermissions != FileAccessPermissions.OtherExecute)
            {
            }
            while (fileSystemEntry.FileAccessPermissions != FileAccessPermissions.OtherExecute)
            {
            }
            _ = fileSystemEntry.FileAccessPermissions == FileAccessPermissions.OtherWrite ? 1 : 2;

            fileSystemEntry.FileAccessPermissions = ~((FileAccessPermissions.OtherRead));
            fileSystemEntry.FileAccessPermissions = ~FileAccessPermissions.OtherRead;
        }
Exemplo n.º 10
0
        public static string ResolveSymbolicLink(string path)
        {
            if (string.IsNullOrEmpty(path))
            {
                return(path);
            }

            if (Path.DirectorySeparatorChar == '\\')
            {
                return(Path.GetFullPath(path));
            }

            try {
                var alreadyVisted = new HashSet <string> ();

                while (true)
                {
                    if (alreadyVisted.Contains(path))
                    {
                        return(string.Empty);
                    }

                    alreadyVisted.Add(path);

                    var linkInfo = new UnixSymbolicLinkInfo(path);
                    if (linkInfo.IsSymbolicLink && linkInfo.HasContents)
                    {
                        string contentsPath = linkInfo.ContentsPath;

                        if (!Path.IsPathRooted(contentsPath))
                        {
                            path = Path.Combine(Path.GetDirectoryName(path), contentsPath);
                        }
                        else
                        {
                            path = contentsPath;
                        }

                        path = ResolveFullPath(path);
                        continue;
                    }

                    path = Path.Combine(ResolveSymbolicLink(Path.GetDirectoryName(path)), Path.GetFileName(path));

                    return(ResolveFullPath(path));
                }
            } catch {
                return(path);
            }
        }
Exemplo n.º 11
0
 string GetTargetFile(string file)
 {
     if (!Platform.IsWindows)
     {
         try {
             UnixSymbolicLinkInfo fi = new UnixSymbolicLinkInfo(file);
             if (fi.IsSymbolicLink)
             {
                 return(fi.ContentsPath);
             }
         } catch {
         }
     }
     return(file);
 }
Exemplo n.º 12
0
        public override bool RenameTo(FilePath path, string name)
        {
            var symlink = GetUnixFileInfo(path) as UnixSymbolicLinkInfo;

            if (symlink != null)
            {
                var newFile = new UnixSymbolicLinkInfo(name);
                newFile.CreateSymbolicLinkTo(symlink.ContentsPath);
                return(true);
            }
            else
            {
                return(base.RenameTo(path, name));
            }
        }
Exemplo n.º 13
0
        private static EnumerateFileEntryInfo GetFileEntryInfo(string filePath)
        {
            EnumerateFileEntryInfo fileEntryInfo = new EnumerateFileEntryInfo()
            {
                FileName       = LongPath.GetFileName(filePath),
                FileAttributes = FileAttributes.Normal,
                SymlinkTarget  = null
            };

#if DOTNET5_4
            try
            {
                UnixFileSystemInfo fileSystemInfo = UnixFileSystemInfo.GetFileSystemEntry(filePath);
                if (fileSystemInfo.IsSymbolicLink)
                {
                    fileEntryInfo.FileAttributes |= FileAttributes.ReparsePoint;
                    fileEntryInfo.SymlinkTarget   = Path.GetFullPath(Path.Combine(GetParentPath(filePath), (fileSystemInfo as UnixSymbolicLinkInfo).ContentsPath));

                    UnixSymbolicLinkInfo symlinkInfo = fileSystemInfo as UnixSymbolicLinkInfo;

                    try
                    {
                        if (symlinkInfo.HasContents && symlinkInfo.GetContents().IsDirectory)
                        {
                            fileEntryInfo.FileAttributes |= FileAttributes.Directory;
                        }
                    }
                    catch (InvalidOperationException)
                    {
                        // Just ignore exception thrown here.
                        // later there will be "FileNotFoundException" thrown out when trying to open the file before transferring.
                    }
                }

                if (fileSystemInfo.IsDirectory)
                {
                    fileEntryInfo.FileAttributes |= FileAttributes.Directory;
                }
            }
            catch (DllNotFoundException ex)
            {
                throw new TransferException(TransferErrorCode.FailToEnumerateDirectory,
                                            Resources.UnableToLoadDLL,
                                            ex);
            }
#endif
            return(fileEntryInfo);
        }
Exemplo n.º 14
0
        public override bool RenameTo(FilePath path, string name)
        {
            var symlink = GetUnixFileInfo(path) as UnixSymbolicLinkInfo;

            if (symlink != null)
            {
                var newFile = new UnixSymbolicLinkInfo(name);
                newFile.CreateSymbolicLinkTo(symlink.ContentsPath);
                return(true);
            }
            else
            {
                // This call replaces the file if it already exists.
                // File.Move throws an exception if dest already exists
                return(Mono.Unix.Native.Stdlib.rename(path, name) == 0);
            }
        }
Exemplo n.º 15
0
        protected override void MoveFileInternal(string source, string destination)
        {
            var sourceInfo = UnixFileSystemInfo.GetFileSystemEntry(source);

            if (sourceInfo.IsSymbolicLink)
            {
                var isSameDir   = UnixPath.GetDirectoryName(source) == UnixPath.GetDirectoryName(destination);
                var symlinkInfo = (UnixSymbolicLinkInfo)sourceInfo;
                var symlinkPath = symlinkInfo.ContentsPath;

                var newFile = new UnixSymbolicLinkInfo(destination);

                if (isSameDir)
                {
                    // We're in the same dir, so we can preserve relative symlinks.
                    newFile.CreateSymbolicLinkTo(symlinkInfo.ContentsPath);
                }
                else
                {
                    var fullPath = UnixPath.Combine(UnixPath.GetDirectoryName(source), symlinkPath);
                    newFile.CreateSymbolicLinkTo(fullPath);
                }

                try
                {
                    // Finally remove the original symlink.
                    symlinkInfo.Delete();
                }
                catch
                {
                    // Removing symlink failed, so rollback the new link and throw.
                    newFile.Delete();
                    throw;
                }
            }
            else if ((PlatformInfo.Platform == PlatformType.Mono && PlatformInfo.GetVersion() >= new Version(6, 0)) ||
                     PlatformInfo.Platform == PlatformType.NetCore)
            {
                TransferFilePatched(source, destination, false, true);
            }
            else
            {
                base.MoveFileInternal(source, destination);
            }
        }
        public override string GetSymbolicLinkTarget(string path)
        {
            UnixSymbolicLinkInfo symbolicLinkInfo;

            try
            {
                symbolicLinkInfo = new UnixSymbolicLinkInfo(path);
            }
            catch (InvalidOperationException)
            {
                /* Not a symbolic link */

                return(null);
            }

            string retval = null;

            try
            {
                if (!symbolicLinkInfo.IsSymbolicLink)
                {
                    return(null);
                }

                retval = symbolicLinkInfo.ContentsPath;

                if (retval != "/" && retval.EndsWith("/"))
                {
                    retval = retval.Substring(0, retval.Length - 1);
                }
            }
            catch (OutOfMemoryException)
            {
                throw;
            }
            catch (StackOverflowException)
            {
                throw;
            }
            catch
            {
            }

            return(retval);
        }
Exemplo n.º 17
0
        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);
        }
Exemplo n.º 18
0
        /// <summary>On Linux and Un*x systems, search locations, stopping at whichever
        /// comes first. See https://golang.org/src/crypto/x509/</summary>
        public void Unix(FileInfo bundle)
        {
            var location = CA_BUNDLE_LOCATIONS.FirstOrDefault(File.Exists);

            if (null == location)
            {
                throw new NotSupportedException(string.Format(
                                                    "Cannot find bundle in any of [{1}  {0}{1}]",
                                                    string.Join(Environment.NewLine + "  ", CA_BUNDLE_LOCATIONS),
                                                    Environment.NewLine
                                                    ));
            }

            if ((bundle.Attributes & FileAttributes.ReparsePoint) == FileAttributes.ReparsePoint)
            {
                var link = new UnixSymbolicLinkInfo(bundle.FullName).GetContents().FullName;
                if (link == location)
                {
                    // Nothing to do here
                    Console.WriteLine("> Link exists with up-to-date target {0}", link);
                }
                else
                {
                    bundle.Delete();
                    (new UnixFileInfo(location)).CreateSymbolicLink(bundle.FullName);
                    Console.WriteLine("> Replaced link target {0} with {1}", link, location);
                }
            }
            else if (bundle.Exists)
            {
                bundle.Delete();
                (new UnixFileInfo(location)).CreateSymbolicLink(bundle.FullName);
                Console.WriteLine("> Replaced file with link to {0}", location);
            }
            else
            {
                (new UnixFileInfo(location)).CreateSymbolicLink(bundle.FullName);
                Console.WriteLine("> Linked {0} -> {1}", bundle.Name, location);
            }

            Console.WriteLine("  {0} certificates", CountCertificates(bundle));
            Console.WriteLine();
        }
Exemplo n.º 19
0
        public void Analyze()
        {
            UnixSymbolicLinkInfo info = new UnixSymbolicLinkInfo(BifDatabasePath);

            if (info.Exists)
            {
                if (!info.IsSymbolicLink && File.Exists(BifLocalPath))
                {
                    info.Delete();

                    UnixFileInfo newInfo = new UnixFileInfo(BifLocalPath);
                    newInfo.CreateSymbolicLink(BifDatabasePath);
                }
                else if (!info.IsSymbolicLink)
                {
                    if (File.Exists(BifLocalPath))
                    {
                        File.Delete(BifLocalPath);
                    }

                    File.Move(BifDatabasePath, BifLocalPath);

                    UnixFileInfo newInfo = new UnixFileInfo(BifLocalPath);
                    newInfo.CreateSymbolicLink(BifDatabasePath);
                }
            }
            else
            {
                if (File.Exists(BifLocalPath))
                {
                    UnixFileInfo newInfo = new UnixFileInfo(BifLocalPath);
                    if (!Directory.Exists(IndexDirectory))
                    {
                        Directory.CreateDirectory(IndexDirectory);
                    }
                    newInfo.CreateSymbolicLink(BifDatabasePath);
                }
            }
        }
Exemplo n.º 20
0
        protected override void CopyFileInternal(string source, string destination, bool overwrite)
        {
            var sourceInfo = UnixFileSystemInfo.GetFileSystemEntry(source);

            if (sourceInfo.IsSymbolicLink)
            {
                var isSameDir   = UnixPath.GetDirectoryName(source) == UnixPath.GetDirectoryName(destination);
                var symlinkInfo = (UnixSymbolicLinkInfo)sourceInfo;
                var symlinkPath = symlinkInfo.ContentsPath;

                var newFile = new UnixSymbolicLinkInfo(destination);

                if (FileExists(destination) && overwrite)
                {
                    DeleteFile(destination);
                }

                if (isSameDir)
                {
                    // We're in the same dir, so we can preserve relative symlinks.
                    newFile.CreateSymbolicLinkTo(symlinkInfo.ContentsPath);
                }
                else
                {
                    var fullPath = UnixPath.Combine(UnixPath.GetDirectoryName(source), symlinkPath);
                    newFile.CreateSymbolicLinkTo(fullPath);
                }
            }
            else if (((PlatformInfo.Platform == PlatformType.Mono && PlatformInfo.GetVersion() >= new Version(6, 0)) ||
                      PlatformInfo.Platform == PlatformType.NetCore) &&
                     (!FileExists(destination) || overwrite))
            {
                TransferFilePatched(source, destination, overwrite, false);
            }
            else
            {
                base.CopyFileInternal(source, destination, overwrite);
            }
        }
Exemplo n.º 21
0
    public override IEnumerable <Item> Load()
    {
        if (!IsValidConfinementItem(this))
        {
            yield break;
        }

        link = new UnixSymbolicLinkInfo(File.FullName);
        if (!link.HasContents)
        {
            yield break;
        }

        yield return(this);

        var item = Item.Resolve(Confinement,
                                new FileInfo(link.GetContents().FullName));

        foreach (var child_item in item.Load())
        {
            yield return(child_item);
        }
    }
Exemplo n.º 22
0
        public static void EnsureListenerSocket()
        {
            var socketPath = InternalSocketPath;

            Logger.Log.Info($"Configuring socket, internal: {InternalSocketPath}; listener: {ListenerSocketPath}");
            try
            {
                var socketInfo = new UnixFileInfo(socketPath);
                _SymLink = socketInfo.CreateSymbolicLink(ListenerSocketPath);
                Logger.Log.Info($"Created symlink, target: {InternalSocketPath}, source: {ListenerSocketPath}");

                socketInfo.FileAccessPermissions =
                    FileAccessPermissions.UserRead | FileAccessPermissions.UserWrite |
                    FileAccessPermissions.GroupRead | FileAccessPermissions.GroupWrite |
                    FileAccessPermissions.OtherRead | FileAccessPermissions.OtherWrite;
                Logger.Log.Info("Set socket permissions to 0666");
            }
            catch (Exception ex)
            {
                Logger.Log.Fatal($"Unable to configure socket, exception: {ex}");
                Environment.Exit(-1);
            }
        }
Exemplo n.º 23
0
        public override bool IsSymLink(string path)
        {
            try {
                UnixSymbolicLinkInfo i = new UnixSymbolicLinkInfo(path);
                switch (i.FileType)
                {
                case FileTypes.SymbolicLink:
                    return(true);

                case FileTypes.Fifo:
                case FileTypes.Socket:
                case FileTypes.BlockDevice:
                case FileTypes.CharacterDevice:
                case FileTypes.Directory:
                case FileTypes.RegularFile:
                default:
                    return(false);
                }
            } catch (Exception ex) {
                Log.Warning(ex);
                return(false);
            }
        }
Exemplo n.º 24
0
        private static void CreateUnixSymbolicLink(string linkPath, string targetPath, string arguments)
        {
            var info = new UnixSymbolicLinkInfo(linkPath);

            info.CreateSymbolicLinkTo($"{targetPath} {arguments}");
        }
Exemplo n.º 25
0
        private static void ExtractTarByEntry(Stream inputStream, string targetDir, bool asciiTranslate, Action <long, long> progress)
        {
            TarInputStream tarIn = new TarInputStream(inputStream);
            TarEntry       tarEntry;

            while ((tarEntry = tarIn.GetNextEntry()) != null)
            {
                if (tarEntry.IsDirectory)
                {
                    continue;
                }

                progress(tarIn.Position, tarIn.Length);

                // Converts the unix forward slashes in the filenames to windows backslashes
                string name = tarEntry.Name.Replace('/', Path.DirectorySeparatorChar);

                // Remove any root e.g. '\' because a PathRooted filename defeats Path.Combine
                if (Path.IsPathRooted(name))
                {
                    name = name.Substring(Path.GetPathRoot(name).Length);
                }

                // Apply further name transformations here as necessary
                string outName = Path.Combine(targetDir, name).NormalizePath();

                string directoryName = Path.GetDirectoryName(outName);

                // Does nothing if directory exists
                Directory.CreateDirectory(directoryName);

                if (tarEntry.TarHeader.TypeFlag != '0')
                {
                    switch ((char)tarEntry.TarHeader.TypeFlag)
                    {
                    case '1':
                        if (Platform.PlatformIdentifier == Platforms.PlatformID.Win32NT)
                        {
                            Platform.CreateHardLinkWin32(outName.NormalizePath(), Path.Combine(targetDir, tarEntry.TarHeader.LinkName).NormalizePath(), !tarEntry.IsDirectory);
                        }
                        else
                        {
                            var symLinkInfo = new UnixSymbolicLinkInfo(Path.Combine(targetDir, tarEntry.TarHeader.LinkName).NormalizePath());

                            symLinkInfo.CreateLink(outName);
                        }
                        break;

                    case '2':
                        if (Platform.PlatformIdentifier == Platforms.PlatformID.Win32NT)
                        {
                            Platform.CreateSymbolicLinkWin32(outName.NormalizePath(), tarEntry.TarHeader.LinkName, !tarEntry.IsDirectory);
                        }
                        else
                        {
                            var symLinkInfo = new UnixSymbolicLinkInfo(outName.NormalizePath());

                            symLinkInfo.CreateSymbolicLinkTo(tarEntry.TarHeader.LinkName);
                        }
                        break;
                    }
                }
                else
                {
                    try
                    {
                        using (var outStr = new FileStream(outName, FileMode.Create))
                        {
                            if (asciiTranslate)
                            {
                                CopyWithAsciiTranslate(tarIn, outStr);
                            }
                            else
                            {
                                tarIn.CopyEntryContents(outStr);
                            }
                        }

                        if (Platform.PlatformIdentifier == Platforms.PlatformID.Unix || Platform.PlatformIdentifier == Platforms.PlatformID.MacOSX)
                        {
                            var unixFileInfo = new UnixFileInfo(outName)
                            {
                                FileAccessPermissions = (FileAccessPermissions)tarEntry.TarHeader.Mode
                            };
                        }

                        // Set the modification date/time. This approach seems to solve timezone issues.
                        DateTime myDt = DateTime.SpecifyKind(tarEntry.ModTime, DateTimeKind.Utc);
                        File.SetLastWriteTime(outName, myDt);
                    }
                    catch (Exception)
                    {
                    }
                }
            }

            tarIn.Close();
        }
Exemplo n.º 26
0
        /// <summary>
        /// Converts a FileSystemInfo into a FileSystemObject by reading in data about the file
        /// </summary>
        /// <param name="fileInfo">A reference to a file on disk.</param>
        /// <param name="downloadCloud">
        /// If the file is hosted in the cloud, the user has the option to include cloud files or not.
        /// </param>
        /// <param name="includeContentHash">If we should generate a hash of the file.</param>
        /// <returns></returns>
        public FileSystemObject FilePathToFileSystemObject(string path)
        {
            FileSystemObject obj = new FileSystemObject(path);

            // Get Owner/Group
            if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows))
            {
                try
                {
                    var fileSecurity      = new FileSecurity(path, AccessControlSections.Owner);
                    IdentityReference oid = fileSecurity.GetOwner(typeof(SecurityIdentifier));
                    obj.Owner = AsaHelpers.SidToName(oid);
                }
                catch (Exception e)
                {
                    Log.Verbose("Failed to get owner for {0} ({1}:{2})", path, e.GetType(), e.Message);
                }
                try
                {
                    var fileSecurity      = new FileSecurity(path, AccessControlSections.Group);
                    IdentityReference gid = fileSecurity.GetGroup(typeof(SecurityIdentifier));
                    obj.Group = AsaHelpers.SidToName(gid);
                }
                catch (Exception e)
                {
                    Log.Verbose("Failed to get group for {0} ({1}:{2})", path, e.GetType(), e.Message);
                }
                try
                {
                    var fileSecurity = new FileSecurity(path, AccessControlSections.Access);
                    var rules        = fileSecurity.GetAccessRules(true, true, typeof(SecurityIdentifier));
                    obj.Permissions = new Dictionary <string, string>();
                    foreach (FileSystemAccessRule?rule in rules)
                    {
                        if (rule != null)
                        {
                            string name = AsaHelpers.SidToName(rule.IdentityReference);

                            foreach (var permission in rule.FileSystemRights.ToString().Split(','))
                            {
                                if (obj.Permissions.ContainsKey(name))
                                {
                                    obj.Permissions[name] = $"{obj.Permissions[name]},{permission}";
                                }
                                else
                                {
                                    obj.Permissions.Add(name, permission);
                                }
                            }
                        }
                    }
                }
                catch (Exception e)
                {
                    Log.Verbose("Failed to get FileSecurity for {0} ({1}:{2})", path, e.GetType(), e.Message);
                }
            }
            else if (RuntimeInformation.IsOSPlatform(OSPlatform.Linux) || RuntimeInformation.IsOSPlatform(OSPlatform.OSX))
            {
                try
                {
                    var file = new UnixSymbolicLinkInfo(path);
                    obj.Owner  = file.OwnerUser.UserName;
                    obj.Group  = file.OwnerGroup.GroupName;
                    obj.SetGid = file.IsSetGroup;
                    obj.SetUid = file.IsSetUser;

                    obj.Permissions = new Dictionary <string, string>();
                    if (file.FileAccessPermissions.ToString().Equals("AllPermissions", StringComparison.InvariantCulture))
                    {
                        obj.Permissions.Add("User", "Read,Write,Execute");
                        obj.Permissions.Add("Group", "Read,Write,Execute");
                        obj.Permissions.Add("Other", "Read,Write,Execute");
                    }
                    else
                    {
                        var keys = new List <string>()
                        {
                            "User", "Group", "Other"
                        };
                        var splits = file.FileAccessPermissions.ToString().Split(',').Select(x => x.Trim());
                        foreach (var key in keys)
                        {
                            foreach (var permission in splits.Where((x) => x.StartsWith(key, StringComparison.InvariantCulture)))
                            {
                                if (permission.Contains("ReadWriteExecute", StringComparison.InvariantCulture))
                                {
                                    obj.Permissions.Add(key, "Read,Write,Execute");
                                }
                                else
                                {
                                    if (obj.Permissions.ContainsKey(key))
                                    {
                                        obj.Permissions[key] = $"{obj.Permissions[key]},{permission.Trim().Substring(key.Length)}";
                                    }
                                    else
                                    {
                                        obj.Permissions.Add(key, permission.Trim().Substring(key.Length));
                                    }
                                }
                            }
                        }
                    }
                }
                catch (Exception e) when(
                    e is ArgumentNullException ||
                    e is ArgumentException ||
                    e is InvalidOperationException)
                {
                    Log.Verbose("Failed to get permissions for {0} ({1}:{2})", path, e.GetType(), e.Message);
                }
            }

            try
            {
                FileIOPermission fiop = new FileIOPermission(FileIOPermissionAccess.Read, path);
                fiop.Demand();
                if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows))
                {
                    if (Directory.Exists(path))
                    {
                        var fileInfo = new DirectoryInfo(path);
                        if (fileInfo.Attributes.HasFlag(FileAttributes.ReparsePoint))
                        {
                            obj.IsLink = true;
                            obj.Target = NativeMethods.GetFinalPathName(path);
                        }
                        else
                        {
                            obj.IsDirectory = true;
                        }
                    }
                    else
                    {
                        var fileInfo = new FileInfo(path);
                        obj.Size       = fileInfo.Length;
                        obj.SizeOnDisk = WindowsSizeOnDisk(fileInfo);

                        // This check is to try to prevent reading of cloud based files (like a
                        // dropbox folder) and subsequently causing a download, unless the user
                        // specifically requests it with DownloadCloud.
                        if (opts.DownloadCloud || obj.SizeOnDisk > 0 || WindowsFileSystemUtils.IsLocal(obj.Path))
                        {
                            obj.LastModified = File.GetLastWriteTimeUtc(path);
                            obj.Created      = File.GetCreationTimeUtc(path);

                            if (opts.GatherHashes == true)
                            {
                                obj.ContentHash = FileSystemUtils.GetFileHash(fileInfo);
                            }

                            var exeType = FileSystemUtils.GetExecutableType(path);

                            if (exeType != EXECUTABLE_TYPE.NONE && exeType != EXECUTABLE_TYPE.UNKNOWN)
                            {
                                obj.IsExecutable = true;
                            }

                            if (exeType == EXECUTABLE_TYPE.WINDOWS)
                            {
                                obj.SignatureStatus = WindowsFileSystemUtils.GetSignatureStatus(path);
                                obj.Characteristics = WindowsFileSystemUtils.GetDllCharacteristics(path);
                            }
                            else if (exeType == EXECUTABLE_TYPE.MACOS)
                            {
                                obj.MacSignatureStatus = FileSystemUtils.GetMacSignature(path);
                            }
                        }
                    }
                }
                else
                {
                    UnixSymbolicLinkInfo i = new UnixSymbolicLinkInfo(path);
                    obj.FileType    = i.FileType.ToString();
                    obj.Size        = i.Length;
                    obj.IsDirectory = false;
                    switch (i.FileType)
                    {
                    case FileTypes.SymbolicLink:
                        obj.IsLink = true;
                        obj.Target = i.ContentsPath;
                        break;

                    case FileTypes.Fifo:
                    case FileTypes.Socket:
                    case FileTypes.BlockDevice:
                    case FileTypes.CharacterDevice:
                    case FileTypes.Directory:
                        obj.IsDirectory = true;
                        if (path?.EndsWith(".app", StringComparison.InvariantCultureIgnoreCase) ?? false)
                        {
                            obj.MacSignatureStatus = FileSystemUtils.GetMacSignature(path);
                        }
                        break;

                    case FileTypes.RegularFile:
                        var fileInfo = new FileInfo(path);
                        obj.SizeOnDisk = i.BlocksAllocated * i.BlockSize;
                        if (opts.DownloadCloud || obj.SizeOnDisk > 0)
                        {
                            obj.LastModified = File.GetLastWriteTimeUtc(path);
                            obj.Created      = File.GetCreationTimeUtc(path);

                            if (opts.GatherHashes)
                            {
                                obj.ContentHash = FileSystemUtils.GetFileHash(path);
                            }

                            var exeType = FileSystemUtils.GetExecutableType(path);

                            if (exeType != EXECUTABLE_TYPE.NONE && exeType != EXECUTABLE_TYPE.UNKNOWN)
                            {
                                obj.IsExecutable = true;
                            }

                            if (exeType == EXECUTABLE_TYPE.WINDOWS)
                            {
                                obj.SignatureStatus = WindowsFileSystemUtils.GetSignatureStatus(path);
                                obj.Characteristics = WindowsFileSystemUtils.GetDllCharacteristics(path);
                            }
                            else if (exeType == EXECUTABLE_TYPE.MACOS)
                            {
                                obj.MacSignatureStatus = FileSystemUtils.GetMacSignature(path);
                            }
                        }
                        break;
                    }
                }
            }
            catch (Exception e) when(
                e is ArgumentNullException ||
                e is SecurityException ||
                e is ArgumentException ||
                e is UnauthorizedAccessException ||
                e is PathTooLongException ||
                e is NotSupportedException ||
                e is InvalidOperationException ||
                e is FileNotFoundException ||
                e is Win32Exception ||
                e is IOException)
            {
                Log.Verbose("Failed to create FileInfo from File at {0} ({1}:{2})", path, e.GetType(), e.Message);
            }
            catch (Exception e)
            {
                Log.Debug("Should be caught in DirectoryWalker {0} {1}", e.GetType().ToString(), path);
            }

            try
            {
                obj.LastModified = File.GetLastWriteTimeUtc(path);
                obj.Created      = File.GetCreationTimeUtc(path);
            }
            catch (Exception e)
            {
                Log.Verbose("Failed to get last modified for {0} ({1}:{2})", path, e.GetType(), e.Message);
            }

            return(obj);
        }
Exemplo n.º 27
0
        protected override BuildResult Build(IProgressMonitor monitor, SolutionEntityItem item, ConfigurationSelector configuration)
        {
            var proj = item as MonoMacProject;

            if (proj == null || proj.CompileTarget != CompileTarget.Exe)
            {
                return(base.Build(monitor, item, configuration));
            }

            var conf   = (MonoMacProjectConfiguration)configuration.GetConfiguration(item);
            var resDir = conf.AppDirectory.Combine("Contents", "Resources");
            var appDir = conf.AppDirectory;

            var res = base.Build(monitor, item, configuration);

            if (res.ErrorCount > 0)
            {
                return(res);
            }

            //copy exe, mdb, refs, copy-to-output, Content files to Resources
            var filesToCopy = GetCopyFiles(proj, configuration, conf).Where(NeedsBuilding).ToList();

            if (filesToCopy.Count > 0)
            {
                monitor.BeginTask("Copying resource files to app bundle", filesToCopy.Count);
                foreach (var f in filesToCopy)
                {
                    f.EnsureOutputDirectory();
                    File.Copy(f.Input, f.Output, true);
                    monitor.Log.WriteLine("Copied {0}", f.Output.ToRelative(appDir));
                    monitor.Step(1);
                }
                monitor.EndTask();
            }

            //FIXME: only do this check if there are actually xib files
            if (!Platform.IsMac)
            {
                res.AddWarning("Cannot compile xib files on non-Mac platforms");
            }
            else
            {
                //Interface Builder files
                if (res.Append(CompileXibFiles(monitor, proj.Files, resDir)).ErrorCount > 0)
                {
                    return(res);
                }
            }

            //info.plist
            var plistOut  = conf.AppDirectory.Combine("Contents", "Info.plist");
            var appInfoIn = proj.Files.GetFile(proj.BaseDirectory.Combine("Info.plist"));

            if (new FilePair(proj.FileName, plistOut).NeedsBuilding() ||
                (appInfoIn != null && new FilePair(appInfoIn.FilePath, plistOut).NeedsBuilding()))
            {
                if (res.Append(MergeInfoPlist(monitor, proj, conf, appInfoIn, plistOut)).ErrorCount > 0)
                {
                    return(res);
                }
            }

            if (Platform.IsWindows)
            {
                res.AddWarning("Cannot create app bundle on Windows");
            }
            else
            {
                //launch script
                var macOSDir = appDir.Combine("Contents", "MacOS");
                CopyExecutableFile(AddinManager.CurrentAddin.GetFilePath("MonoMacLaunchScript.sh"), conf.LaunchScript);
                CopyExecutableFile(AddinManager.CurrentAddin.GetFilePath("mono-version-check"),
                                   macOSDir.Combine("mono-version-check"));

                var si = new UnixSymbolicLinkInfo(appDir.Combine(conf.AppName));
                if (!si.Exists)
                {
                    si.CreateSymbolicLinkTo("/Library/Frameworks/Mono.framework/Versions/Current/bin/mono");
                }
            }

            //pkginfo
            var pkgInfo = conf.AppDirectory.Combine("Contents", "PkgInfo");

            if (!File.Exists(pkgInfo))
            {
                using (var f = File.OpenWrite(pkgInfo))
                    f.Write(new byte [] { 0X41, 0X50, 0X50, 0X4C, 0x3f, 0x3f, 0x3f, 0x3f }, 0, 8);                     // "APPL???"
            }
            return(res);
        }
Exemplo n.º 28
0
        /// <summary>
        /// Converts a FileSystemInfo into a FileSystemObject by reading in data about the file
        /// </summary>
        /// <param name="fileInfo">A reference to a file on disk.</param>
        /// <param name="downloadCloud">If the file is hosted in the cloud, the user has the option to include cloud files or not.</param>
        /// <param name="includeContentHash">If we should generate a hash of the file.</param>
        /// <returns></returns>
        public static FileSystemObject FilePathToFileSystemObject(string path, bool downloadCloud = false, bool includeContentHash = false)
        {
            if (path == null)
            {
                return(null);
            }
            FileSystemObject obj = new FileSystemObject()
            {
                Path = path,
            };

            // Get Owner/Group
            if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows))
            {
                try
                {
                    var fileSecurity      = new FileSecurity(path, AccessControlSections.All);
                    IdentityReference oid = fileSecurity.GetOwner(typeof(SecurityIdentifier));
                    IdentityReference gid = fileSecurity.GetGroup(typeof(SecurityIdentifier));

                    // Set the Owner and Group to the SID, in case we can't properly translate
                    obj.Owner = oid.ToString();
                    obj.Group = gid.ToString();

                    try
                    {
                        // Translate owner into the string representation.
                        obj.Owner = (oid.Translate(typeof(NTAccount)) as NTAccount).Value;
                    }
                    catch (IdentityNotMappedException)
                    {
                        Log.Verbose("Couldn't find the Owner from SID {0} for file {1}", oid.ToString(), path);
                    }
                    try
                    {
                        // Translate group into the string representation.
                        obj.Group = (gid.Translate(typeof(NTAccount)) as NTAccount).Value;
                    }
                    catch (IdentityNotMappedException)
                    {
                        // This is fine. Some SIDs don't map to NT Accounts.
                        Log.Verbose("Couldn't find the Group from SID {0} for file {1}", gid.ToString(), path);
                    }

                    var rules = fileSecurity.GetAccessRules(true, true, typeof(System.Security.Principal.SecurityIdentifier));
                    foreach (FileSystemAccessRule rule in rules)
                    {
                        string name = rule.IdentityReference.Value;

                        try
                        {
                            name = rule.IdentityReference.Translate(typeof(NTAccount)).Value;
                        }
                        catch (IdentityNotMappedException)
                        {
                            // This is fine. Some SIDs don't map to NT Accounts.
                        }

                        foreach (var permission in rule.FileSystemRights.ToString().Split(','))
                        {
                            if (obj.Permissions.ContainsKey(name))
                            {
                                obj.Permissions[name] = $"{obj.Permissions[name]},{permission}";
                            }
                            else
                            {
                                obj.Permissions.Add(name, permission);
                            }
                        }
                    }
                }
                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)
                {
                    Log.Verbose($"Error instantiating FileSecurity object {obj.Path} {e.GetType().ToString()}");
                }
            }
            else if (RuntimeInformation.IsOSPlatform(OSPlatform.Linux) || RuntimeInformation.IsOSPlatform(OSPlatform.OSX))
            {
                try
                {
                    var file = new UnixSymbolicLinkInfo(path);
                    obj.Owner  = file.OwnerUser.UserName;
                    obj.Group  = file.OwnerGroup.GroupName;
                    obj.SetGid = file.IsSetGroup;
                    obj.SetUid = file.IsSetUser;

                    if (file.FileAccessPermissions.ToString().Equals("AllPermissions", StringComparison.InvariantCulture))
                    {
                        obj.Permissions.Add("User", "Read,Write,Execute");
                        obj.Permissions.Add("Group", "Read,Write,Execute");
                        obj.Permissions.Add("Other", "Read,Write,Execute");
                    }
                    else
                    {
                        var keys = new List <string>()
                        {
                            "User", "Group", "Other"
                        };
                        var splits = file.FileAccessPermissions.ToString().Split(',').Select(x => x.Trim());
                        foreach (var key in keys)
                        {
                            foreach (var permission in splits.Where((x) => x.StartsWith(key, StringComparison.InvariantCulture)))
                            {
                                if (permission.Contains("ReadWriteExecute", StringComparison.InvariantCulture))
                                {
                                    obj.Permissions.Add(key, "Read,Write,Execute");
                                }
                                else
                                {
                                    if (obj.Permissions.ContainsKey(key))
                                    {
                                        obj.Permissions[key] = $"{obj.Permissions[key]},{permission.Trim().Substring(key.Length)}";
                                    }
                                    else
                                    {
                                        obj.Permissions.Add(key, permission.Trim().Substring(key.Length));
                                    }
                                }
                            }
                        }
                    }
                }
                catch (Exception e) when(
                    e is ArgumentNullException ||
                    e is ArgumentException ||
                    e is InvalidOperationException)
                {
                    Log.Debug($"Failed to get permissions for {path} {e.GetType().ToString()}");
                }
            }


            try
            {
                if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows))
                {
                    if (Directory.Exists(path))
                    {
                        var fileInfo = new DirectoryInfo(path);
                        if (fileInfo.Attributes.HasFlag(FileAttributes.ReparsePoint))
                        {
                            obj.IsLink = true;
                            obj.Target = NativeMethods.GetFinalPathName(path);
                        }
                        else
                        {
                            obj.IsDirectory = true;
                        }
                    }
                    else
                    {
                        var fileInfo = new FileInfo(path);
                        obj.Size = (ulong)fileInfo.Length;
                        if (WindowsFileSystemUtils.IsLocal(obj.Path) || downloadCloud)
                        {
                            if (includeContentHash)
                            {
                                obj.ContentHash = FileSystemUtils.GetFileHash(fileInfo);
                            }

                            obj.IsExecutable = FileSystemUtils.IsExecutable(obj.Path, obj.Size);

                            if (obj.IsExecutable)
                            {
                                obj.SignatureStatus = WindowsFileSystemUtils.GetSignatureStatus(path);
                                obj.Characteristics.AddRange(WindowsFileSystemUtils.GetDllCharacteristics(path));
                            }
                        }
                    }
                }
                else
                {
                    UnixSymbolicLinkInfo i = new UnixSymbolicLinkInfo(path);
                    obj.FileType    = i.FileType.ToString();
                    obj.Size        = (ulong)i.Length;
                    obj.IsDirectory = false;
                    switch (i.FileType)
                    {
                    case FileTypes.SymbolicLink:
                        obj.IsLink = true;
                        obj.Target = i.ContentsPath;
                        break;

                    case FileTypes.Fifo:
                    case FileTypes.Socket:
                    case FileTypes.BlockDevice:
                    case FileTypes.CharacterDevice:
                    case FileTypes.Directory:
                        obj.IsDirectory = true;
                        break;

                    case FileTypes.RegularFile:
                        if (includeContentHash)
                        {
                            obj.ContentHash = FileSystemUtils.GetFileHash(path);
                        }
                        obj.IsExecutable = FileSystemUtils.IsExecutable(obj.Path, obj.Size);
                        break;
                    }
                }
            }
            catch (Exception e) when(
                e is ArgumentNullException ||
                e is SecurityException ||
                e is ArgumentException ||
                e is UnauthorizedAccessException ||
                e is PathTooLongException ||
                e is NotSupportedException ||
                e is InvalidOperationException)
            {
                Log.Verbose("Failed to create FileInfo from File at {0} {1}", path, e.GetType().ToString());
            }
            catch (Exception e)
            {
                Log.Debug("Should be caught in DirectoryWalker {0}", e.GetType().ToString());
            }
            return(obj);
        }
Exemplo n.º 29
0
 public UnixSymLink(string path)
     : base(path)
 {
     _info = new UnixSymbolicLinkInfo(path);
 }
        /// <summary>
        /// Converts a FileSystemInfo into a FileSystemObject by reading in data about the file
        /// </summary>
        /// <param name="fileInfo">A reference to a file on disk.</param>
        /// <param name="downloadCloud">If the file is hosted in the cloud, the user has the option to include cloud files or not.</param>
        /// <param name="includeContentHash">If we should generate a hash of the file.</param>
        /// <returns></returns>
        public static FileSystemObject FilePathToFileSystemObject(string path, bool downloadCloud = false, bool includeContentHash = false)
        {
            FileSystemObject obj = new FileSystemObject(path);

            // Get Owner/Group
            if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows))
            {
                try
                {
                    var fileSecurity      = new FileSecurity(path, AccessControlSections.All);
                    IdentityReference oid = fileSecurity.GetOwner(typeof(SecurityIdentifier));
                    IdentityReference gid = fileSecurity.GetGroup(typeof(SecurityIdentifier));

                    obj.Owner = AsaHelpers.SidToName(oid);
                    obj.Group = AsaHelpers.SidToName(gid);

                    var rules = fileSecurity.GetAccessRules(true, true, typeof(SecurityIdentifier));
                    foreach (FileSystemAccessRule?rule in rules)
                    {
                        if (rule != null)
                        {
                            string name = AsaHelpers.SidToName(rule.IdentityReference);

                            obj.Permissions = new Dictionary <string, string>();

                            foreach (var permission in rule.FileSystemRights.ToString().Split(','))
                            {
                                if (obj.Permissions.ContainsKey(name))
                                {
                                    obj.Permissions[name] = $"{obj.Permissions[name]},{permission}";
                                }
                                else
                                {
                                    obj.Permissions.Add(name, permission);
                                }
                            }
                        }
                    }
                }
                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)
                {
                    Log.Verbose($"Error instantiating FileSecurity object {obj.Path} {e.GetType().ToString()}");
                }
            }
            else if (RuntimeInformation.IsOSPlatform(OSPlatform.Linux) || RuntimeInformation.IsOSPlatform(OSPlatform.OSX))
            {
                try
                {
                    var file = new UnixSymbolicLinkInfo(path);
                    obj.Owner  = file.OwnerUser.UserName;
                    obj.Group  = file.OwnerGroup.GroupName;
                    obj.SetGid = file.IsSetGroup;
                    obj.SetUid = file.IsSetUser;

                    obj.Permissions = new Dictionary <string, string>();
                    if (file.FileAccessPermissions.ToString().Equals("AllPermissions", StringComparison.InvariantCulture))
                    {
                        obj.Permissions.Add("User", "Read,Write,Execute");
                        obj.Permissions.Add("Group", "Read,Write,Execute");
                        obj.Permissions.Add("Other", "Read,Write,Execute");
                    }
                    else
                    {
                        var keys = new List <string>()
                        {
                            "User", "Group", "Other"
                        };
                        var splits = file.FileAccessPermissions.ToString().Split(',').Select(x => x.Trim());
                        foreach (var key in keys)
                        {
                            foreach (var permission in splits.Where((x) => x.StartsWith(key, StringComparison.InvariantCulture)))
                            {
                                if (permission.Contains("ReadWriteExecute", StringComparison.InvariantCulture))
                                {
                                    obj.Permissions.Add(key, "Read,Write,Execute");
                                }
                                else
                                {
                                    if (obj.Permissions.ContainsKey(key))
                                    {
                                        obj.Permissions[key] = $"{obj.Permissions[key]},{permission.Trim().Substring(key.Length)}";
                                    }
                                    else
                                    {
                                        obj.Permissions.Add(key, permission.Trim().Substring(key.Length));
                                    }
                                }
                            }
                        }
                    }
                }
                catch (Exception e) when(
                    e is ArgumentNullException ||
                    e is ArgumentException ||
                    e is InvalidOperationException)
                {
                    Log.Debug($"Failed to get permissions for {path} {e.GetType().ToString()}");
                }
            }


            try
            {
                if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows))
                {
                    if (Directory.Exists(path))
                    {
                        var fileInfo = new DirectoryInfo(path);
                        if (fileInfo.Attributes.HasFlag(FileAttributes.ReparsePoint))
                        {
                            obj.IsLink = true;
                            obj.Target = NativeMethods.GetFinalPathName(path);
                        }
                        else
                        {
                            obj.IsDirectory = true;
                        }
                    }
                    else
                    {
                        var fileInfo = new FileInfo(path);
                        var size     = (ulong)fileInfo.Length;
                        obj.Size = size;
                        if (WindowsFileSystemUtils.IsLocal(obj.Path) || downloadCloud)
                        {
                            if (includeContentHash)
                            {
                                obj.ContentHash = FileSystemUtils.GetFileHash(fileInfo);
                            }

                            obj.IsExecutable = FileSystemUtils.IsExecutable(obj.Path, size);

                            if (obj.IsExecutable != null && (bool)obj.IsExecutable)
                            {
                                // TODO: This can be optimized into fewer touches, GetSignatureStatus also runs IsExecutable checks against the first 4 bytes

                                obj.SignatureStatus = WindowsFileSystemUtils.GetSignatureStatus(path);
                                obj.Characteristics = WindowsFileSystemUtils.GetDllCharacteristics(path);
                            }
                        }
                    }
                }
                else
                {
                    UnixSymbolicLinkInfo i = new UnixSymbolicLinkInfo(path);
                    obj.FileType    = i.FileType.ToString();
                    obj.Size        = (ulong)i.Length;
                    obj.IsDirectory = false;
                    switch (i.FileType)
                    {
                    case FileTypes.SymbolicLink:
                        obj.IsLink = true;
                        obj.Target = i.ContentsPath;
                        break;

                    case FileTypes.Fifo:
                    case FileTypes.Socket:
                    case FileTypes.BlockDevice:
                    case FileTypes.CharacterDevice:
                    case FileTypes.Directory:
                        obj.IsDirectory = true;
                        break;

                    case FileTypes.RegularFile:
                        if (i.HasContents)
                        {
                            if (includeContentHash)
                            {
                                obj.ContentHash = FileSystemUtils.GetFileHash(path);
                            }
                            obj.IsExecutable = FileSystemUtils.IsExecutable(obj.Path, obj.Size);
                        }
                        break;
                    }
                }
            }
            catch (Exception e) when(
                e is ArgumentNullException ||
                e is SecurityException ||
                e is ArgumentException ||
                e is UnauthorizedAccessException ||
                e is PathTooLongException ||
                e is NotSupportedException ||
                e is InvalidOperationException)
            {
                Log.Verbose("Failed to create FileInfo from File at {0} {1}", path, e.GetType().ToString());
            }
            catch (Exception e)
            {
                Log.Debug("Should be caught in DirectoryWalker {0}", e.GetType().ToString());
            }

            try
            {
                obj.LastModified = File.GetLastWriteTimeUtc(path);
                obj.Created      = File.GetCreationTimeUtc(path);
            }
            catch (Exception) { }

            return(obj);
        }