public bool CheckSignature(string fileName, out int offset, out bool isExecutable)
        {
            offset       = 0;
            isExecutable = false;

            SharpCompress.Archives.IArchive arcTest = null;

            try
            {
                arcTest = SharpCompress.Archives.ArchiveFactory.Open(fileName);
                var aType = arcTest.Type;

                switch (arcTest.Type)
                {
                case SharpCompress.Common.ArchiveType.Zip:
                case SharpCompress.Common.ArchiveType.SevenZip:
                    return(true);
                }
            }
            catch { }
            finally
            {
                if (arcTest != null)
                {
                    arcTest.Dispose();
                }
            }

            return(false);
        }
Пример #2
0
        public static FileArchive Open(string path)
        {
            SharpCompress.Archives.IArchive archive = null;
            try {
                if (SharpCompress.Archives.Zip.ZipArchive.IsZipFile(path))
                {
                    archive = SharpCompress.Archives.Zip.ZipArchive.Open(path);
                }
                else if (SharpCompress.Archives.Rar.RarArchive.IsRarFile(path))
                {
                    archive = SharpCompress.Archives.Rar.RarArchive.Open(path);
                }
                else if (SharpCompress.Archives.SevenZip.SevenZipArchive.IsSevenZipFile(path))
                {
                    archive = SharpCompress.Archives.SevenZip.SevenZipArchive.Open(path);
                }
                else if (SharpCompress.Archives.GZip.GZipArchive.IsGZipFile(path))
                {
                    archive = SharpCompress.Archives.GZip.GZipArchive.Open(path);
                }
                else if (SharpCompress.Archives.Tar.TarArchive.IsTarFile(path))
                {
                    archive = SharpCompress.Archives.Tar.TarArchive.Open(path);
                }
            } catch (Exception ex) {
                BooruApp.BooruApplication.Log.Log(BooruLog.Category.Files, ex, "Caught exception while opening archive " + path);
            }

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

            return(new FileArchive(archive));
        }
 public void Dispose()
 {
     if (_archive != null)
     {
         _archive.Dispose();
         _archive = null;
     }
 }
Пример #4
0
        /// <summary>
        /// Search for matches in .PDF files.
        /// </summary>
        /// <param name="fileName">The name of the file.</param>
        /// <param name="searchTerms">The terms to search.</param>
        /// <param name="matcher">The matcher object to determine search criteria.</param>
        /// <returns>The matched lines containing the search terms.</returns>
        public override List <MatchedLine> Search(string fileName, IEnumerable <string> searchTerms, Matcher matcher)
        {
            List <MatchedLine> matchedLines = new List <MatchedLine>();
            string             tempDirPath  = System.IO.Path.Combine(AppDomain.CurrentDomain.BaseDirectory, fileName + TempExtractDirectoryName);

            try
            {
                Directory.CreateDirectory(tempDirPath);
                SharpCompress.Archives.IArchive archive = null;

                if (fileName.ToUpper().EndsWith(".ODS") && SharpCompress.Archives.Zip.ZipArchive.IsZipFile(fileName))
                {
                    archive = SharpCompress.Archives.Zip.ZipArchive.Open(fileName);
                }

                if (archive != null)
                {
                    IReader reader = archive.ExtractAllEntries();
                    while (reader.MoveToNextEntry())
                    {
                        if (!reader.Entry.IsDirectory && reader.Entry.Key == "content.xml")
                        {
                            // Ignore symbolic links as these are captured by the original target.
                            if (string.IsNullOrWhiteSpace(reader.Entry.LinkTarget) && !reader.Entry.Key.Any(c => DisallowedCharactersByOperatingSystem.Any(dc => dc == c)))
                            {
                                try
                                {
                                    reader.WriteEntryToDirectory(tempDirPath, new ExtractionOptions()
                                    {
                                        ExtractFullPath = true, Overwrite = true
                                    });
                                    string fullFilePath = System.IO.Path.Combine(tempDirPath, reader.Entry.Key.Replace(@"/", @"\"));
                                    matchedLines = this.GetMatchesFromOdsContentXml(fileName, fullFilePath, searchTerms, matcher);
                                }
                                catch (PathTooLongException ptlex)
                                {
                                    throw new PathTooLongException(string.Format("{0} {1} {2} {3} - {4}", Resources.Strings.ErrorAccessingEntry, reader.Entry.Key, Resources.Strings.InArchive, fileName, ptlex.Message));
                                }
                            }
                        }
                    }

                    if (matcher.CancellationTokenSource.Token.IsCancellationRequested)
                    {
                        matchedLines.Clear();
                    }

                    archive.Dispose();
                }
            }
            finally
            {
                this.RemoveTempDirectory(tempDirPath);
            }

            return(matchedLines);
        }
Пример #5
0
 public void Dispose()
 {
     if (this.archive != null)
     {
         this.archive.Dispose();
         this.archive = null;
         this.entries.Clear();
     }
 }
Пример #6
0
 /// <summary>
 /// Searches for the first archive entry with the given name in the given archive.
 /// </summary>
 /// <param name="archive">The archive where the entry should be searched.</param>
 /// <param name="entryName">The name of the entry, which is the file or directory name.
 /// The search is done case insensitive.</param>
 /// <returns>Returns the reference of the entry if found and null if the entry doesn't exists in the archive.</returns>
 internal SharpCompress.Archives.IArchiveEntry FindEntryByName(SharpCompress.Archives.IArchive archive, string entryName)
 {
     try
     {
         return
             (archive.Entries.First(
                  archiveEntry => archiveEntry.Key.Equals(entryName, StringComparison.OrdinalIgnoreCase)));
     }
     catch (InvalidOperationException)
     {
         return(null);
     }
 }
Пример #7
0
        protected FileArchive(SharpCompress.Archives.IArchive archive)
        {
            this.entries = new List <Entry> ();
            this.archive = archive;

            foreach (var entry in this.archive.Entries)
            {
                if (entry.IsComplete && !entry.IsDirectory)
                {
                    this.entries.Add(new Entry(entry));
                }
            }

            this.entries.Sort((a, b) => {
                return(a.Name.CompareNatural(b.Name));
            });
        }
Пример #8
0
        /// <summary>
        /// Search for matches in archive files.
        /// </summary>
        /// <param name="fileName">The name of the file.</param>
        /// <param name="searchTerms">The terms to search.</param>
        /// <param name="matcher">The matcher object to determine search criteria.</param>
        /// <returns>The matched lines containing the search terms.</returns>
        public override List <MatchedLine> Search(string fileName, IEnumerable <string> searchTerms, Matcher matcher)
        {
            List <MatchedLine> matchedLines = new List <MatchedLine>();
            string             tempDirPath  = System.IO.Path.Combine(AppDomain.CurrentDomain.BaseDirectory, fileName + TempExtractDirectoryName);

            Directory.CreateDirectory(tempDirPath);
            SharpCompress.Archives.IArchive archive = null;

            try
            {
                if (fileName.ToUpper().EndsWith(".GZ") && SharpCompress.Archives.GZip.GZipArchive.IsGZipFile(fileName))
                {
                    archive = SharpCompress.Archives.GZip.GZipArchive.Open(fileName);
                }
                else if (fileName.ToUpper().EndsWith(".RAR") && SharpCompress.Archives.Rar.RarArchive.IsRarFile(fileName))
                {
                    archive = SharpCompress.Archives.Rar.RarArchive.Open(fileName);
                }
                else if (fileName.ToUpper().EndsWith(".7Z") && SharpCompress.Archives.SevenZip.SevenZipArchive.IsSevenZipFile(fileName))
                {
                    archive = SharpCompress.Archives.SevenZip.SevenZipArchive.Open(fileName);
                }
                else if (fileName.ToUpper().EndsWith(".TAR") && SharpCompress.Archives.Tar.TarArchive.IsTarFile(fileName))
                {
                    archive = SharpCompress.Archives.Tar.TarArchive.Open(fileName);
                }
                else if (fileName.ToUpper().EndsWith(".ZIP") && SharpCompress.Archives.Zip.ZipArchive.IsZipFile(fileName))
                {
                    archive = SharpCompress.Archives.Zip.ZipArchive.Open(fileName);
                }

                if (archive != null)
                {
                    matchedLines = this.GetMatchedLinesInZipArchive(fileName, searchTerms, tempDirPath, archive, matcher);
                    archive.Dispose();
                }
            }
            finally
            {
                // Clean up temp directory if any errors occur.
                this.RemoveTempDirectory(tempDirPath);
            }

            return(matchedLines);
        }
        public static ArchiveExtractResult FlatExtract(SharpCompress.Archives.IArchive extractor, string outputFolder, System.EventHandler <ExtractProgress> progress_callback)
        {
            Dictionary <bool, List <SharpCompress.Common.IEntry> > myList = new Dictionary <bool, List <SharpCompress.Common.IEntry> >();

            myList.Add(true, new List <SharpCompress.Common.IEntry>());
            myList.Add(false, new List <SharpCompress.Common.IEntry>());
            int    total          = extractor.Entries.Count();
            int    extractedindex = 0;
            string titit;

            FileSystem.CreateDirectory(outputFolder);
            using (var entries = extractor.ExtractAllEntries())
                while (entries.MoveToNextEntry())
                {
                    if (!entries.Entry.IsDirectory)
                    {
                        try
                        {
                            titit = Path.Combine(outputFolder, Path.GetFileName(entries.Entry.Key));
                            using (FileStream fs = File.Create(titit))
                            {
                                entries.WriteEntryTo(fs);
                                fs.Flush();
                            }
                            myList[true].Add(entries.Entry);
                        }
                        catch (System.Exception)
                        { myList[false].Add(entries.Entry); }
                    }
                    extractedindex++;
                    if (progress_callback != null)
                    {
                        syncContext.Post(new SendOrPostCallback(delegate { progress_callback?.Invoke(extractor, new ExtractProgress(total, extractedindex)); }), null);
                    }
                }
            return(new ArchiveExtractResult(myList));
        }
Пример #10
0
        /// <summary>
        /// Search for matches in .ODP files.
        /// </summary>
        /// <param name="fileName">The name of the file.</param>
        /// <param name="searchTerms">The terms to search.</param>
        /// <param name="matcher">The matcher object to determine search criteria.</param>
        /// <returns>The matched lines containing the search terms.</returns>
        public override List <MatchedLine> Search(string fileName, IEnumerable <string> searchTerms, Matcher matcher)
        {
            List <MatchedLine> matchedLines = new List <MatchedLine>();
            int    matchCounter             = 0;
            string tempDirPath = System.IO.Path.Combine(AppDomain.CurrentDomain.BaseDirectory, fileName + TempExtractDirectoryName);

            try
            {
                Directory.CreateDirectory(tempDirPath);
                SharpCompress.Archives.IArchive archive = null;

                if (fileName.ToUpper().EndsWith(".ODP") && SharpCompress.Archives.Zip.ZipArchive.IsZipFile(fileName))
                {
                    archive = SharpCompress.Archives.Zip.ZipArchive.Open(fileName);
                }

                if (archive != null)
                {
                    IReader reader = archive.ExtractAllEntries();
                    while (reader.MoveToNextEntry())
                    {
                        if (!reader.Entry.IsDirectory && reader.Entry.Key == "content.xml")
                        {
                            // Ignore symbolic links as these are captured by the original target.
                            if (string.IsNullOrWhiteSpace(reader.Entry.LinkTarget) && !reader.Entry.Key.Any(c => DisallowedCharactersByOperatingSystem.Any(dc => dc == c)))
                            {
                                try
                                {
                                    reader.WriteEntryToDirectory(tempDirPath, new ExtractionOptions()
                                    {
                                        ExtractFullPath = true, Overwrite = true
                                    });
                                    string        fullFilePath        = System.IO.Path.Combine(tempDirPath, reader.Entry.Key.Replace(@"/", @"\"));
                                    StringBuilder presentationAllText = new StringBuilder();

                                    foreach (XElement element in XDocument.Load(fullFilePath, LoadOptions.None).Descendants().Where(d => d.Name.LocalName == "page"))
                                    {
                                        string slideName = element.Attributes().Where(sn => sn.Name.LocalName == "name").Select(sn => sn.Value).FirstOrDefault();
                                        int    slideNumber;

                                        // Search based on keyword "Slide", not the resources translation.
                                        if (int.TryParse(slideName.Replace("Slide", string.Empty), out slideNumber))
                                        {
                                            string slideAllText = string.Join(Environment.NewLine, element.Descendants().Where(sc => sc.Name.LocalName == "span").Select(sc => sc.Value));

                                            if (!matcher.RegularExpressionOptions.HasFlag(RegexOptions.Multiline))
                                            {
                                                foreach (string searchTerm in searchTerms)
                                                {
                                                    MatchCollection matches = Regex.Matches(slideAllText, searchTerm, matcher.RegularExpressionOptions);            // Use this match for getting the locations of the match.

                                                    if (matches.Count > 0)
                                                    {
                                                        foreach (Match match in matches)
                                                        {
                                                            int    startIndex = match.Index >= IndexBoundary ? match.Index - IndexBoundary : 0;
                                                            int    endIndex   = (slideAllText.Length >= match.Index + match.Length + IndexBoundary) ? match.Index + match.Length + IndexBoundary : slideAllText.Length;
                                                            string matchLine  = slideAllText.Substring(startIndex, endIndex - startIndex);

                                                            while (matchLine.StartsWith("\r") || matchLine.StartsWith("\n"))
                                                            {
                                                                matchLine = matchLine.Substring(1, matchLine.Length - 1);                       // Remove lines starting with the newline character.
                                                            }

                                                            while ((matchLine.EndsWith("\r") || matchLine.EndsWith("\n")) && matchLine.Length > 2)
                                                            {
                                                                matchLine = matchLine.Substring(0, matchLine.Length - 1);                       // Remove lines ending with the newline character.
                                                            }

                                                            Match searchMatch = Regex.Match(matchLine, searchTerm, matcher.RegularExpressionOptions);          // Use this match for the result highlight, based on additional characters being selected before and after the match.
                                                            matchedLines.Add(new MatchedLine
                                                            {
                                                                MatchId    = matchCounter++,
                                                                Content    = string.Format("{0} {1}:\t{2}", Resources.Strings.Slide, slideNumber.ToString(), matchLine),
                                                                SearchTerm = searchTerm,
                                                                FileName   = fileName,
                                                                LineNumber = 1,
                                                                StartIndex = searchMatch.Index + Resources.Strings.Slide.Length + 3 + slideNumber.ToString().Length,
                                                                Length     = searchMatch.Length
                                                            });
                                                        }
                                                    }
                                                }
                                            }
                                            else
                                            {
                                                presentationAllText.AppendLine(slideAllText);
                                            }
                                        }
                                    }

                                    if (matcher.RegularExpressionOptions.HasFlag(RegexOptions.Multiline))
                                    {
                                        matchedLines = matcher.GetMatch(new string[] { string.Join(Environment.NewLine, presentationAllText.ToString()) }, searchTerms, Strings.Slide);
                                    }
                                }
                                catch (PathTooLongException ptlex)
                                {
                                    throw new PathTooLongException(string.Format("{0} {1} {2} {3} - {4}", Resources.Strings.ErrorAccessingEntry, reader.Entry.Key, Resources.Strings.InArchive, fileName, ptlex.Message));
                                }
                            }
                        }
                    }

                    if (matcher.CancellationTokenSource.Token.IsCancellationRequested)
                    {
                        matchedLines.Clear();
                    }

                    archive.Dispose();
                }
            }
            finally
            {
                this.RemoveTempDirectory(tempDirPath);
            }

            return(matchedLines);
        }
Пример #11
0
 private void Open(string path)
 {
     _archive = SharpCompress.Archives.ArchiveFactory.Open(path);
 }
Пример #12
0
        /// <summary>
        /// Search for matches in zipped archive files.
        /// </summary>
        /// <param name="fileName">The name of the file.</param>
        /// <param name="searchTerms">The terms to search.</param>
        /// <param name="tempDirPath">The temporary extract directory.</param>
        /// <param name="archive">The archive to be searched.</param>
        /// <param name="matcher">The matcher object to determine search criteria.</param>
        /// <returns>The matched lines containing the search terms.</returns>
        private List <MatchedLine> GetMatchedLinesInZipArchive(string fileName, IEnumerable <string> searchTerms, string tempDirPath, SharpCompress.Archives.IArchive archive, Matcher matcher)
        {
            List <MatchedLine> matchedLines = new List <MatchedLine>();

            try
            {
                IReader reader = archive.ExtractAllEntries();
                while (reader.MoveToNextEntry())
                {
                    if (!reader.Entry.IsDirectory)
                    {
                        // Ignore symbolic links as these are captured by the original target.
                        if (string.IsNullOrWhiteSpace(reader.Entry.LinkTarget) && !reader.Entry.Key.Any(c => DisallowedCharactersByOperatingSystem.Any(dc => dc == c)))
                        {
                            try
                            {
                                reader.WriteEntryToDirectory(tempDirPath, new ExtractionOptions()
                                {
                                    ExtractFullPath = true, Overwrite = true
                                });
                                string fullFilePath = Path.Combine(tempDirPath, reader.Entry.Key.Replace(@"/", @"\"));
                                matchedLines.AddRange(FileSearchHandlerFactory.Search(fullFilePath, searchTerms, matcher));

                                if (matchedLines != null && matchedLines.Count > 0)
                                {
                                    // Want the exact path of the file - without the .extract part.
                                    string dirNameToDisplay = fullFilePath.Replace(TempExtractDirectoryName, string.Empty);
                                    matchedLines.Where(ml => string.IsNullOrEmpty(ml.FileName) || ml.FileName.Contains(TempExtractDirectoryName)).ToList()
                                    .ForEach(ml => ml.FileName = dirNameToDisplay);
                                }
                            }
                            catch (PathTooLongException ptlex)
                            {
                                throw new PathTooLongException(string.Format("{0} {1} {2} {3} - {4}", Resources.Strings.ErrorAccessingEntry, reader.Entry.Key, Resources.Strings.InArchive, fileName, ptlex.Message));
                            }
                        }
                    }
                }

                if (matcher.CancellationTokenSource.Token.IsCancellationRequested)
                {
                    matchedLines.Clear();
                }
            }
            catch (ArgumentNullException ane)
            {
                if (ane.Message.Contains("Value cannot be null") && fileName.EndsWith(".gz", StringComparison.OrdinalIgnoreCase))
                {
                    matchedLines = this.DecompressGZipStream(fileName, searchTerms, matcher);
                }
                else if (ane.Message.Contains("String reference not set to an instance of a String."))
                {
                    throw new NotSupportedException(string.Format("{0} {1}. {2}", Resources.Strings.ErrorAccessingFile, fileName, Resources.Strings.FileEncrypted));
                }
                else
                {
                    throw;
                }
            }

            return(matchedLines);
        }