public Dirent[] GetEntries()
        {
            Dirent[] direntArray;
            IntPtr   intPtr = Syscall.opendir(base.FullPath);

            if (intPtr == IntPtr.Zero)
            {
                UnixMarshal.ThrowExceptionForLastError();
            }
            bool flag = false;

            try
            {
                Dirent[] entries = UnixDirectoryInfo.GetEntries(intPtr);
                flag        = true;
                direntArray = entries;
            }
            finally
            {
                int num = Syscall.closedir(intPtr);
                if (flag)
                {
                    UnixMarshal.ThrowExceptionForLastErrorIf(num);
                }
            }
            return(direntArray);
        }
Example #2
0
        public static bool TryGetFileSystemEntry(string path, out UnixFileSystemInfo entry)
        {
            Native.Stat stat;
            int         r = Native.Syscall.lstat(path, out stat);

            if (r == -1)
            {
                if (Native.Stdlib.GetLastError() == Native.Errno.ENOENT)
                {
                    entry = new UnixFileInfo(path);
                    return(true);
                }
                entry = null;
                return(false);
            }

            if (IsFileType(stat.st_mode, Native.FilePermissions.S_IFDIR))
            {
                entry = new UnixDirectoryInfo(path, stat);
            }
            else if (IsFileType(stat.st_mode, Native.FilePermissions.S_IFLNK))
            {
                entry = new UnixSymbolicLinkInfo(path, stat);
            }
            else
            {
                entry = new UnixFileInfo(path, stat);
            }

            return(true);
        }
Example #3
0
    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;
            }
        }
    }
Example #4
0
 private static string _GetFullPath(string path)
 {
     if (path == null)
     {
         throw new ArgumentNullException("path");
     }
     if (!UnixPath.IsPathRooted(path))
     {
         path = string.Concat(UnixDirectoryInfo.GetCurrentDirectory(), UnixPath.DirectorySeparatorChar, path);
     }
     return(path);
 }
Example #5
0
        private static string _GetFullPath(string path)
        {
            if (path == null)
            {
                throw new ArgumentNullException("path");
            }
            if (!IsPathRooted(path))
            {
                path = UnixDirectoryInfo.GetCurrentDirectory() + DirectorySeparatorChar + path;
            }

            return(path);
        }
        public Dirent[] GetEntries(Regex regex)
        {
            Dirent[] entries;
            IntPtr   intPtr = Syscall.opendir(base.FullPath);

            if (intPtr == IntPtr.Zero)
            {
                UnixMarshal.ThrowExceptionForLastError();
            }
            try
            {
                entries = UnixDirectoryInfo.GetEntries(intPtr, regex);
            }
            finally
            {
                UnixMarshal.ThrowExceptionForLastErrorIf(Syscall.closedir(intPtr));
            }
            return(entries);
        }
 public void Delete(bool recursive)
 {
     if (recursive)
     {
         UnixFileSystemInfo[] fileSystemEntries = this.GetFileSystemEntries();
         for (int i = 0; i < (int)fileSystemEntries.Length; i++)
         {
             UnixFileSystemInfo unixFileSystemInfo = fileSystemEntries[i];
             UnixDirectoryInfo  unixDirectoryInfo  = unixFileSystemInfo as UnixDirectoryInfo;
             if (unixDirectoryInfo == null)
             {
                 unixFileSystemInfo.Delete();
             }
             else
             {
                 unixDirectoryInfo.Delete(true);
             }
         }
     }
     UnixMarshal.ThrowExceptionForLastErrorIf(Syscall.rmdir(base.FullPath));
     base.Refresh();
 }
        public void Delete(bool recursive)
        {
            if (recursive)
            {
                foreach (UnixFileSystemInfo e in GetFileSystemEntries())
                {
                    UnixDirectoryInfo d = e as UnixDirectoryInfo;
                    if (d != null)
                    {
                        d.Delete(true);
                    }
                    else
                    {
                        e.Delete();
                    }
                }
            }
            int r = Native.Syscall.rmdir(FullPath);

            UnixMarshal.ThrowExceptionForLastErrorIf(r);
            base.Refresh();
        }
Example #9
0
File: fileops.cs Project: arg/mc
        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);
                Result res;
                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;
        }
Example #10
0
 static void Main()
 {
     var dirinfo = new UnixDirectoryInfo(".");
     ScanPath(dirinfo, "");
 }
		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
		}
Example #12
0
		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;
		}
Example #13
0
 public static UnixDriveInfo GetDriveInfo(this UnixFileInfo fileInfo)
 {
     Mono.Unix.UnixDirectoryInfo file  = new Mono.Unix.UnixDirectoryInfo(fileInfo.FullName);
     Mono.Unix.UnixDriveInfo     drive = new Mono.Unix.UnixDriveInfo(fileInfo.FullName);
     return(drive);
 }
Example #14
0
 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);
         }
     }
 }
Example #15
0
 public static UnixFileSystemInfo[] EntriesMaybe(UnixDirectoryInfo di)
 {
     try { return Entries(di); }
     catch (Exception) { return new UnixFileSystemInfo[0]; }
 }
Example #16
0
 public void Delete(string directory, bool recursive)
 {
     UnixDirectoryInfo unix_dir = new UnixDirectoryInfo (directory);
     unix_dir.Delete (recursive);
 }
Example #17
0
 public static UnixFileSystemInfo[] Entries(UnixDirectoryInfo di)
 {
     return di.GetFileSystemEntries ();
 }
Example #18
0
        /// <summary>
        /// Searches for songs in a specific folder, using recursivity or not.
        /// </summary>
        /// <param name="folderPath">Path to search</param>
        /// <param name="recursive">Recursive (if true, will search for sub-folders)</param>
        /// <returns>List of songs (file paths)</returns>
		private List<string> SearchMediaFilesInFolders(string folderPath, bool recursive)
        {
			// Declare variables
            List<string> arrayFiles = new List<string>();			
			string extensionsSupported = string.Empty;
						
			// Refresh status
			OnRaiseRefreshStatusEvent(new UpdateLibraryEntity() {
				Title = "Searching for media files",
				Subtitle = "Searching for media files in library folder " + folderPath,
				PercentageDone = 0
			});    
			
			// Set supported extensions
#if MACOSX            
			extensionsSupported = @"^.+\.((wav)|(mp3)|(flac)|(ogg)|(mpc)|(wv)|(m3u)|(m3u8)|(pls)|(xspf))$";
#elif LINUX
            extensionsSupported = @"^.+\.((wav)|(mp3)|(flac)|(ogg)|(mpc)|(wv)|(m3u)|(m3u8)|(pls)|(xspf))$";
#elif (!MACOSX && !LINUX)
			extensionsSupported = @"WAV;MP3;FLAC;OGG;MPC;WV;WMA;APE;M3U;M3U8;PLS;XSPF";
#endif
						
#if (MACOSX || LINUX)
			
			// Get Unix-style directory information (i.e. case sensitive file names)
			UnixDirectoryInfo rootDirectoryInfo = new UnixDirectoryInfo(folderPath);
			
            // For each directory, search for new directories
            foreach (UnixFileSystemInfo fileInfo in rootDirectoryInfo.GetFileSystemEntries())
            {			
				// Check if entry is a directory
				if(fileInfo.IsDirectory && recursive)
				{
					// Make sure this isn't an Apple index directory
					if(!fileInfo.Name.StartsWith(".Apple"))
					{
                        Console.WriteLine("UpdateLibraryService - SearchMediaFilesInFolders {0}", fileInfo.FullName);
                        try
                        {
                    		List<string> listMediaFiles = SearchMediaFilesInFolders(fileInfo.FullName, true);
                    		arrayFiles.AddRange(listMediaFiles);					
                        }
                        catch(Exception ex)
                        {
                            Console.WriteLine("UpdateLibraryService - SearchMediaFilesInFolders {0} - Exception {1}", fileInfo.FullName, ex);
                        }
					}
				}
				
				// If the extension matches, add file to list
				Match match = Regex.Match(fileInfo.FullName, extensionsSupported, RegexOptions.IgnoreCase);
				if(match.Success)
                    arrayFiles.Add(fileInfo.FullName);
            }
            
#else
        	
            // Get Windows-style directory information
            DirectoryInfo rootDirectoryInfo = new DirectoryInfo(folderPath);                        
            
            // Check for sub directories if recursive
            if (recursive)
            {
                // For each directory, search for new directories
                DirectoryInfo[] directoryInfos = rootDirectoryInfo.GetDirectories();
                foreach (DirectoryInfo directoryInfo in directoryInfos)
                {
					// Make sure this isn't an Apple index directory
                    if (!directoryInfo.Name.StartsWith(".Apple"))
					{					
	                    // Search for songs in that directory                    
	                    List<string> listSongs = SearchMediaFilesInFolders(directoryInfo.FullName, recursive);
	                    arrayFiles.AddRange(listSongs);
					}
                }
            }
			
			string[] extensions = extensionsSupported.Split(new string[]{";"}, StringSplitOptions.RemoveEmptyEntries);
            //FileInfo[] fileInfos = rootDirectoryInfo.GetFiles("*." + extension);
            FileInfo[] fileInfos = rootDirectoryInfo.GetFiles();
            foreach (FileInfo fileInfo in fileInfos)
            {
                // Check if file matches supported extensions
                if (extensions.Contains(fileInfo.Extension.Replace(".", ""), StringComparer.InvariantCultureIgnoreCase))
                {
                    arrayFiles.Add(fileInfo.FullName);
                }
            }
						
#endif				

            return arrayFiles;
        }
Example #19
0
    public void SetCurrentDir(string dirname, bool resetZoom)
    {
        Profiler p = new Profiler ();
        dirLatencyProfiler.Restart ();
        FirstFrameOfDir = true;

        if (dirname != Helpers.RootDir) dirname = dirname.TrimEnd(Helpers.DirSepC);
        UnixDirectoryInfo d = new UnixDirectoryInfo (dirname);
        string odp = CurrentDirPath;
        CurrentDirPath = d.FullName;

        if (odp != CurrentDirPath) {
          if (CurrentDirEntry != null && CurrentDirEntry.InProgress)
        FSCache.CancelTraversal ();
          CurrentDirEntry = FSCache.FastGet (CurrentDirPath);
          FSCache.Watch (CurrentDirPath);
        }

        FSNeedRedraw = true;
        if (resetZoom) ResetZoom ();
        UpdateLayout ();
        p.Time("SetCurrentDir");
    }
Example #20
0
		public void RefreshSongInformation(AudioFile audioFile, long lengthBytes, int playlistIndex, int playlistCount)
		{
			Gtk.Application.Invoke(delegate{
				if(audioFile != null)
				{
			        // Refresh labels
					Console.WriteLine("MainWindow - RefreshSongInformation");
			        lblArtistName.Text = audioFile.ArtistName;
			        lblAlbumTitle.Text = audioFile.AlbumTitle;
			        lblSongTitle.Text = audioFile.Title;
			        lblSongFilePath.Text = audioFile.FilePath;	        
					//lblCurrentPosition.Text = audioFile.Position;
					lblCurrentLength.Text = audioFile.Length;
								
					lblCurrentFileType.Text = audioFile.FileType.ToString();
					lblCurrentBitrate.Text = audioFile.Bitrate.ToString();
					lblCurrentSampleRate.Text = audioFile.SampleRate.ToString();
					lblCurrentBitsPerSample.Text = audioFile.BitsPerSample.ToString();
								
					//Pixbuf stuff = new Pixbuf("icon48.png");
					//stuff = stuff.ScaleSimple(150, 150, InterpType.Bilinear);
					//imageAlbumCover.Pixbuf = stuff;
					
					System.Drawing.Image drawingImage = AudioFile.ExtractImageForAudioFile(audioFile.FilePath);			
					
					if(drawingImage != null)
					{
						// Resize image and set cover
						drawingImage = SystemDrawingHelper.ResizeImage(drawingImage, 150, 150);
						imageAlbumCover.Pixbuf = ImageToPixbuf(drawingImage);
					}
					else
					{
						// Get Unix-style directory information (i.e. case sensitive file names)
						if(!String.IsNullOrEmpty(audioFile.FilePath))
						{
							try
							{
								bool imageFound = false;
								string folderPath = System.IO.Path.GetDirectoryName(audioFile.FilePath);
								UnixDirectoryInfo rootDirectoryInfo = new UnixDirectoryInfo(folderPath);
								
								// For each directory, search for new directories
								UnixFileSystemInfo[] infos = rootDirectoryInfo.GetFileSystemEntries();
				            	foreach (UnixFileSystemInfo fileInfo in rootDirectoryInfo.GetFileSystemEntries())
				            	{
									// Check if the file matches
									string fileName = fileInfo.Name.ToUpper();
									if((fileName.EndsWith(".JPG") ||
									    fileName.EndsWith(".JPEG") ||
									    fileName.EndsWith(".PNG") ||
									    fileName.EndsWith(".GIF")) &&
									   (fileName.StartsWith("FOLDER") ||
									 	fileName.StartsWith("COVER")))
									{
										// Get image from file
										imageFound = true;
										Pixbuf imageCover = new Pixbuf(fileInfo.FullName);
										imageCover = imageCover.ScaleSimple(150, 150, InterpType.Bilinear);
										imageAlbumCover.Pixbuf = imageCover;
									}
								}
								
								// Set empty image if not cover not found
								if(!imageFound)
									imageAlbumCover.Pixbuf = null;
							}
							catch
							{
								imageAlbumCover.Pixbuf = null;
							}
						}
						else
						{
							// Set empty album cover
							imageAlbumCover.Pixbuf = null;
						}
					}
					
					// Check if image cover is still empty
					if(imageAlbumCover.Pixbuf == null)
					{				
                        Pixbuf imageCover = ResourceHelper.GetEmbeddedImageResource("black.png");
						imageCover = imageCover.ScaleSimple(150, 150, InterpType.Bilinear);
						imageAlbumCover.Pixbuf = imageCover;
					}
				}
			});
		}		
		public static bool TryGetFileSystemEntry (string path, out UnixFileSystemInfo entry)
		{
			Native.Stat stat;
			int r = Native.Syscall.lstat (path, out stat);
			if (r == -1) {
				if (Native.Stdlib.GetLastError() == Native.Errno.ENOENT) {
					entry = new UnixFileInfo (path);
					return true;
				}
				entry = null;
				return false;
			}

			if (IsFileType (stat.st_mode, Native.FilePermissions.S_IFDIR))
				entry = new UnixDirectoryInfo (path, stat);
			else if (IsFileType (stat.st_mode, Native.FilePermissions.S_IFLNK))
				entry = new UnixSymbolicLinkInfo (path, stat);
			else
				entry = new UnixFileInfo (path, stat);

			return true;
		}