Ejemplo n.º 1
0
            /// Returns a writable stream to an empty subfile.
            public Stream GetWriteStream(string subfileName)
            {
                Debug.Assert(!m_finished);
                if (m_zipstream != null)
                {
#if USE_DOTNETZIP
                    var entry = m_zipstream.PutNextEntry(subfileName);
                    entry.LastModified = System.DateTime.Now;
                    // entry.CompressionMethod = DotNetZip.CompressionMethod.None; no need; use the default
                    return(new ZipOutputStreamWrapper_DotNetZip(m_zipstream));
#else
                    var entry = new ZipLibrary.ZipEntry(subfileName);
                    entry.DateTime = System.DateTime.Now;
                    // There is such a thing as "Deflated, compression level 0".
                    // Explicitly use "Stored".
                    entry.CompressionMethod = (m_zipstream.GetLevel() == 0)
          ? ZipLibrary.CompressionMethod.Stored
          : ZipLibrary.CompressionMethod.Deflated;
                    return(new ZipOutputStreamWrapper_SharpZipLib(m_zipstream, entry));
#endif
                }
                else
                {
                    Directory.CreateDirectory(m_temporaryPath);
                    string fullPath = Path.Combine(m_temporaryPath, subfileName);
                    return(new FileStream(fullPath, FileMode.Create, FileAccess.Write));
                }
            }
Ejemplo n.º 2
0
 internal ZipPackagePart(ZipPackage package, ZipEntry entry)
 {
     Package = package;
     Entry = entry;
     SaveHandler = null;
     Uri = new Uri(package.GetUriKey(entry.FileName), UriKind.Relative);
 }
Ejemplo n.º 3
0
    public string GetInformationFromFile(string fullPath, string defaultValue)
    {
        if (RuntimePlatform.Android == Application.platform)
        {
            string fileName = Path.GetFileName(fullPath);
            using (MemoryStream m = new MemoryStream())
            {
                string             obbfile = Application.dataPath;
                Ionic.Zip.ZipFile  zipfile = new Ionic.Zip.ZipFile(obbfile);
                Ionic.Zip.ZipEntry ze      = zipfile["assets/" + fileName];
                if (ze != null)
                {
                    ze.Extract(m);
                    m.Seek(0, SeekOrigin.Begin);
                    using (StreamReader s = new StreamReader(m))
                    {
                        string fileText = s.ReadLine();
                        return(fileText);
                    }
                }
            }
        }
        else
        {
            if (File.Exists(fullPath))
            {
                String fileText = File.ReadAllText(fullPath);
                return(fileText);
            }
        }

        return(defaultValue);
    }
Ejemplo n.º 4
0
 private bool AreEqual(ZipEntry approvedEntry, ZipEntry receivedEntry)
 {
     if (approvedEntry.IsDirectory && receivedEntry.IsDirectory)
     {
         return true;
     }
     using (var approvedStream = new MemoryStream())
     {
         using (var receivedStream = new MemoryStream())
         {
             approvedEntry.Extract(approvedStream);
             receivedEntry.Extract(receivedStream);
             var approvedBytes = approvedStream.ToArray();
             var receivedBytes = receivedStream.ToArray();
             var areEqual = approvedBytes == receivedBytes;
             for (int i = 0; i < receivedBytes.Length && i < approvedBytes.Length; i++)
             {
                 if (receivedBytes[i] != approvedBytes[i])
                 {
                     Logger.Event("Failed on {0}[{1}]      '{2}' != '{3}'", receivedEntry.FileName, i,
                         (char) receivedBytes[i], (char) approvedBytes[i]);
                     return false;
                 }
             }
             return true;
         }
     }
 }
Ejemplo n.º 5
0
        protected override OperationResult Handle(ZipEntry entry, ZipFile zip)
        {
            string orig = entry.FileName;
            string stripped = GetStripped(entry.FileName);
            if (stripped == null)
            {
                if (entry.IsDirectory)
                {
                    zip.RemoveEntry(entry);
                    return OperationResult.Removed;
                }

                stripped = orig;
            }

            try
            {
                entry.FileName = stripped;
                return OperationResult.Changed;
            }
            catch (Exception ex)
            {
                string type = entry.IsDirectory ? "directory" : "file";
                throw new Exception(string.Format("Could not rename {0} '{1}' to '{2}'", type, orig, stripped), ex);
            }
        }
Ejemplo n.º 6
0
        public MemoryStream GetEntryMemoryStream(ZipEntry zipEntry)
        {
            var stream = new MemoryStream();
            zipEntry.Extract(stream);
            stream.Position = 0;

            return stream;
        }
Ejemplo n.º 7
0
 private static Bitmap LoadBitmap(ZipEntry zipEntry)
 {
     MemoryStream stream = new MemoryStream();
     zipEntry.Extract(stream);
     stream.Position = 0;
     Bitmap result = new Bitmap(stream);
     stream.Dispose();
     return result;
 }
Ejemplo n.º 8
0
 /// <summary>
 /// Constructors
 /// </summary>
 /// <param name="ze"></param>
 public EmlParser(ZipEntry ze)
 {
     try
     {
         parseEML(ze);
     }
     catch (Exception ex)
     { throw ex; }
 }
		private static void SetZipFile(ZipEntry zipEntry, ZipFileInfo file)
		{
			if (!string.IsNullOrEmpty(file.Password))
				zipEntry.Password = file.Password;

			zipEntry.Comment = file.Comment;
			zipEntry.CompressionMethod = (Ionic.Zip.CompressionMethod)((int)file.CompressionMethod);
			zipEntry.CompressionLevel = (Ionic.Zlib.CompressionLevel)((int)file.CompressionLevel);
		}
Ejemplo n.º 10
0
		public void Check()
		{
			// Is there a valid input stream
			if (_stream == null)
				throw new FileNotFoundException("No valid file");

			// Now read gwz file and save for later use
			_zip = ZipFile.Read(_stream);

			if (_zip == null)
				throw new FileLoadException("No valid gwz file");

			foreach(ZipEntry zipEntry in _zip.Entries)
			{
				switch(Path.GetExtension(zipEntry.FileName).ToLower())
				{
					case ".lua":
						_luaFile = zipEntry;
						_luaFiles += 1;
						break;
				}
			}

			// Is there a Lua file?
			if (_luaFile == null)
				throw new FileNotFoundException("No valid Lua file found");

			// Is there more than one Lua file
			if (_luaFiles > 1)
				throw new FileLoadException("More than one Lua file found");

			// Any compilation errors of the Lua file
			LUA.Check(_zip[_luaFile.FileName].OpenReader(), _luaFile.FileName);

			// Extract cartridge data from Lua file
			cartridge = LUA.Extract(_zip[_luaFile.FileName].OpenReader());

			// Save Lua file name for later use
			cartridge.LuaFileName = _luaFile.FileName;

			// Now check, if all media resources files exist
			foreach(Media media in cartridge.Medias) {
				foreach(MediaResource resource in media.Resources) {
					// Check, if filename is in list of files
					if (!_zip.EntryFileNames.Contains(resource.Filename))
					{
						if (string.IsNullOrWhiteSpace(resource.Filename))
							throw new FileNotFoundException("The Lua file is referencing a file without a filename");
						else
							throw new FileNotFoundException(String.Format("The GWZ is missing a file referred to by the cartridge's code. The file name is: {0}", resource.Filename));
					}
				}
			}

			// Now all is checked without any problems
			// So it seams, that this GWZ file is valid
		}
        public static PartWrapper Create(ZipEntry part)
        {
            if (part.IsZip())
            {
                return new ZipPartWrapper(part);
            }

            return new PartWrapper(part);
        }
Ejemplo n.º 12
0
        protected override OperationResult Handle(ZipEntry entry, ZipFile zip)
        {
            if (_regex.IsMatch(entry.FileName))
            {
                zip.RemoveEntry(entry);
                return OperationResult.Removed;
            }

            return OperationResult.NoChange;
        }
        protected override OperationResult Handle(ZipEntry entry, ZipFile zip)
        {
            if (entry.IsDirectory && (entry.Attributes & FileAttributes.Directory) != FileAttributes.Directory)
            {
                entry.Attributes |= FileAttributes.Directory;
            }

            // This just helps if a file is resaved. It shouldn't be treated as modified if this cleans something up.
            return OperationResult.NoChange;
        }
Ejemplo n.º 14
0
        public static void zipbase(string pathFile)
        {
            ZipFileToCreate = Application.StartupPath + @"\Backup\Magbase.zip";

            using (Basezip.ZipFile zip = new Basezip.ZipFile())
            {
                zip.CompressionLevel = Ionic.Zlib.CompressionLevel.BestCompression;
                Basezip.ZipEntry ze = zip.AddFile(pathFile);
                zip.Save(ZipFileToCreate);
            }
        }
Ejemplo n.º 15
0
 public ContentSection(ZipEntry entry)
 {
     Id = Path.GetFileNameWithoutExtension(entry.FileName);
     ArchivePath = entry.FileName;
     using (Stream s = entry.OpenReader())
     {
         using (StreamReader sr = new StreamReader(s))
         {
             Content = sr.ReadToEnd();
         }
     }
 }
 public static MemoryStream ExtractFileToStream(string zipSource, string filePath)
 {
     MemoryStream stream = new MemoryStream();
     using (ZipFile zip = ZipFile.Read(zipSource))
     {
         var matchFile = new ZipEntry();
         foreach (var file in zip.Where(file => file.FileName == filePath))
             matchFile = file;
         matchFile.Extract(stream);
     }
     return stream;
 }
Ejemplo n.º 17
0
        public static string ExtractFileFromStream(ZipEntry entry)
        {
            var reader = new MemoryStream();
            entry.Extract(reader);
            reader = new MemoryStream(reader.ToArray());

            var streamReader = new StreamReader(reader);

            var text = streamReader.ReadToEnd();
            reader.Dispose();
            return text;
        }
Ejemplo n.º 18
0
        public static ZipCrypto ForRead(string password, ZipEntry e)
        {
            System.IO.Stream s = e._archiveStream;
            e._WeakEncryptionHeader = new byte[12];
            byte[] eh = e._WeakEncryptionHeader;
            ZipCrypto z = new ZipCrypto();

            if (password == null)
                throw new BadPasswordException("This entry requires a password.");

            z.InitCipher(password);

            ZipEntry.ReadWeakEncryptionHeader(s, eh);

            // Decrypt the header.  This has a side effect of "further initializing the
            // encryption keys" in the traditional zip encryption. 
            byte[] DecryptedHeader = z.DecryptMessage(eh, eh.Length);

            // CRC check
            // According to the pkzip spec, the final byte in the decrypted header 
            // is the highest-order byte in the CRC. We check it here. 
            if (DecryptedHeader[11] != (byte)((e._Crc32 >> 24) & 0xff))
            {
                // In the case that bit 3 of the general purpose bit flag is set to
                // indicate the presence of an 'Extended File Header' or a 'data
                // descriptor' (signature 0x08074b50), the last byte of the decrypted
                // header is sometimes compared with the high-order byte of the
                // lastmodified time, rather than the high-order byte of the CRC, to
                // verify the password.
                //
                // This is not documented in the PKWare Appnote.txt.  
                // This was discovered this by analysis of the Crypt.c source file in the InfoZip library
                // http://www.info-zip.org/pub/infozip/

                if ((e._BitField & 0x0008) != 0x0008)
                {
                    throw new BadPasswordException("The password did not match.");
                }
                else if (DecryptedHeader[11] != (byte)((e._TimeBlob >> 8) & 0xff))
                {
                    throw new BadPasswordException("The password did not match.");
                }

                // We have a good password. 
            }
            else
            {
                // A-OK
            }
            return z;
        }
Ejemplo n.º 19
0
        private BitmapSource GenerateBitmapFromZipEntry(ZipEntry entry)
        {
            MemoryStream stream = new MemoryStream();
            entry.Extract(stream);
            stream.Seek(0, SeekOrigin.Begin);

            var decoder = BitmapDecoder.Create(stream,
                BitmapCreateOptions.None,
                BitmapCacheOption.OnLoad);
            BitmapSource bitmapSource = decoder.Frames[0];

            stream.Dispose();

            return bitmapSource;
        }
Ejemplo n.º 20
0
        /// <summary>
        /// Reads one <c>ZipEntry</c> from the given stream.  If the entry is encrypted, we don't
        /// decrypt at this point.  We also do not decompress.  Mostly we read metadata.
        /// </summary>
        /// <param name="zc">the ZipContainer this entry belongs to.</param>
        /// <param name="first">true of this is the first entry being read from the stream.</param>
        /// <returns>the <c>ZipEntry</c> read from the stream.</returns>
        internal static ZipEntry ReadEntry(ZipContainer zc, bool first)
        {
            ZipFile zf = zc.ZipFile;

            Stream s = zc.ReadStream;

            System.Text.Encoding defaultEncoding = zc.ProvisionalAlternateEncoding;
            ZipEntry entry = new ZipEntry();
            entry._Source = ZipEntrySource.ZipFile;
            entry._container = zc;
            entry._archiveStream = s;
            if (zf != null)
                zf.OnReadEntry(true, null);

            if (first) HandlePK00Prefix(s);

            // Read entry header, including any encryption header
            if (!ReadHeader(entry, defaultEncoding)) return null;

            // Store the position in the stream for this entry
            // change for workitem 8098
            entry.__FileDataPosition = entry.ArchiveStream.Position;

            // seek past the data without reading it. We will read on Extract()
            s.Seek(entry._CompressedFileDataSize + entry._LengthOfTrailer, SeekOrigin.Current);
            // workitem 10178
            Ionic.Zip.SharedUtilities.Workaround_Ladybug318918(s);

            // ReadHeader moves the file pointer to the end of the entry header,
            // as well as any encryption header.

            // CompressedFileDataSize includes:
            //   the maybe compressed, maybe encrypted file data
            //   the encryption trailer, if any
            //   the bit 3 descriptor, if any

            // workitem 5306
            // http://www.codeplex.com/DotNetZip/WorkItem/View.aspx?WorkItemId=5306
            HandleUnexpectedDataDescriptor(entry);

            if (zf != null)
            {
                zf.OnReadBytes(entry);
                zf.OnReadEntry(false, entry);
            }

            return entry;
        }
Ejemplo n.º 21
0
        public static string GetStringFile(ZipEntry zipEntry)
        {
            if (zipEntry != null)
            {
                using (var stream = zipEntry.OpenReader())
                {
                    using (StreamReader sr = new StreamReader(stream, KPGenericUtil.GetDefaultEncoding()))
                    {
                        string fileString = sr.ReadToEnd();
                        return fileString;
                    }
                }
            }

            return String.Empty;
        }
        private static void Save(ZipEntry entry, string outputFilePath)
        {
            using (var input = entry.OpenReader())
            {
                var folderPath = Path.GetDirectoryName(outputFilePath);
                if (!Directory.Exists(folderPath))
                {
                    Directory.CreateDirectory(folderPath);
                }

                using (Stream output = File.OpenWrite(outputFilePath))
                {
                    CopyStream(input, output);
                }
            }
        }
Ejemplo n.º 23
0
 /// <summary>
 /// Copy metadata that may have been changed by the app.  We do this when
 /// resetting the zipFile instance.  If the app calls Save() on a ZipFile, then
 /// tries to party on that file some more, we may need to Reset() it , which
 /// means re-reading the entries and then copying the metadata.  I think.
 /// </summary>
 internal void CopyMetaData(ZipEntry source)
 {
     this.__FileDataPosition = source.__FileDataPosition;
     this.CompressionMethod = source.CompressionMethod;
     this._CompressionMethod_FromZipFile = source._CompressionMethod_FromZipFile;
     this._CompressedFileDataSize = source._CompressedFileDataSize;
     this._UncompressedSize = source._UncompressedSize;
     this._BitField = source._BitField;
     this._Source = source._Source;
     this._LastModified = source._LastModified;
     this._Mtime = source._Mtime;
     this._Atime = source._Atime;
     this._Ctime = source._Ctime;
     this._ntfsTimesAreSet = source._ntfsTimesAreSet;
     this._emitUnixTimes = source._emitUnixTimes;
     this._emitNtfsTimes = source._emitNtfsTimes;
 }
Ejemplo n.º 24
0
        static void Main(string[] args)
        {
            string regularplist, path, ipaname;

            
            //App Name
            Console.WriteLine("Please read the first Readme.md/n");
            Console.WriteLine("Please \"XXXX\" in the place of complete Payload/XXXX.app");
            ipaname = Console.ReadLine() + ".app";

            //App Path
            Console.WriteLine("Enter the path ipa");
            path = Console.ReadLine();

            ZipEntry entry = new ZipEntry();
            using (ZipFile zip = ZipFile.Read(path))
            {
                entry = zip["Payload\\" + ipaname +"\\Info.plist"];
            }
            
            using (MemoryStream stream = new MemoryStream())
            {
                entry.Extract(stream);
                stream.Position = 0;
                var downPlist = Plist.readPlist(stream, plistType.Auto);
                regularplist = Plist.writeXml(downPlist);
            }

            var parsedPlist = XDocument.Parse(regularplist);

            String[] requiredKeys = new String[] { "DTCompiler", "CFBundleIdentifier", "CFBundleShortVersionString", "MinimumOSVersion", "CFBundleSupportedPlatforms"};
            var filtredXmlData = parsedPlist.Root.Element("dict").Elements("key").Where(p => requiredKeys.Contains(p.Value)).Select(p => new
            {
                key = p.Value,
                value = Regex.Replace(p.NextNode.ToString(), "<.*?>", string.Empty)
            }).ToDictionary(k => k.key, v => v.value);

            Console.WriteLine(filtredXmlData["DTCompiler"]);
            Console.WriteLine(filtredXmlData["CFBundleIdentifier"]);
            Console.WriteLine(filtredXmlData["CFBundleShortVersionString"]);
            Console.WriteLine(filtredXmlData["CFBundleSupportedPlatforms"]);
            Console.Read();
        }
Ejemplo n.º 25
0
        /// <summary>
        /// Create a <see cref="ZipEntry"/>
        /// </summary>
        /// <param name="entry"></param>
        internal ZipEntry(Ionic.Zip.ZipEntry entry)
        {
            zipEntry = entry;
            /////////////////

            zipEntry.AlternateEncoding      = UTF8SansBomEncoding.Default;
            zipEntry.AlternateEncodingUsage = ZipOption.Always;

            if (zipEntry.CompressionLevel != CompressionLevel.BestCompression && zipEntry.CompressionLevel != CompressionLevel.None)
            {
                if (zipEntry.CompressionRatio == 0)
                {
                    zipEntry.CompressionLevel = CompressionLevel.None;
                }
                else
                {
                    zipEntry.CompressionLevel = CompressionLevel.BestCompression;
                }
            }
        }
Ejemplo n.º 26
0
        static bool IsTempFile(ZipEntry e)
        {
            DirectoryInfo currentDirectory = null;
            if (!e.IsDirectory)
            {
                if (tempExtensions.Any(ex => ex.Equals(Path.GetExtension(e.FileName), StringComparison.OrdinalIgnoreCase)))
                {
                    return true;
                }

                string directoryName = Path.GetDirectoryName(e.FileName);
                if (!string.IsNullOrEmpty(directoryName))
                {
                    currentDirectory = new DirectoryInfo(directoryName);
                }
                else return false;
            }
            else currentDirectory = new DirectoryInfo(e.FileName);
            return IsFilesInCacheFolder(currentDirectory);
        }
Ejemplo n.º 27
0
 public OpfMetadataFile(ZipEntry file, string password)
 {
     try
     {
         using (Stream s = (String.IsNullOrEmpty(password) ? file.OpenReader() : file.OpenReader(password)))
         {
             using (StreamReader sr = new StreamReader(s))
             {
                 try
                 {
                     content = XDocument.Parse(sr.ReadToEnd());
                 }
                 catch (Exception ex)
                 {
                     throw new MetadataParseException(ex, "Nie można było otworzyć pliku z metadanymi. Może to być spowodowane uszkodzeniem jego struktury XMLowej, niewłaściwym kodowaniem, albo brakiem dostępu.");
                 }
             }
         }
     }
     catch (Exception ex)
     {
         throw new EpubFileException(ex, "Błąd w rozpakowywaniu pliku ePub. Może to być spowodowane uszkodzeniem pliku, brakiem plików z metadanymi bądź brakiem dostępu.");
     }
 }
Ejemplo n.º 28
0
        /// <summary>
        /// Metoda, ki se pokliče, ko kliknemo na gumb Razširi. Odpre saveFileDialog in prebere kam bomo datoteko
        /// shranili.
        /// OPOMBA: metoda še ne deluje 100% pravilno.
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void BtnExtract_Click(object sender, EventArgs e)
        {
            filesList = new StringCollection();

            FolderBrowserDialog fbd = new FolderBrowserDialog();

            if (fileExplorer.SelectedItems.Count > 0 && fbd.ShowDialog() == DialogResult.OK)
            {
                // Pridobi shranjevalno pot
                string savePath = fbd.SelectedPath;

                foreach (ListViewItem item in fileExplorer.SelectedItems)
                {
                    string file = item.SubItems[0].Text;

                    // Preveri katera oblika datoteke je: ZIP, TAR, GZIP ali TAR.BZ2
                    if (Path.GetExtension(txtPath.Text) == ".zip")
                    {
                        ZipFile  zip   = Ionic.Zip.ZipFile.Read(txtPath.Text);
                        ZipEntry entry = zip[file];
                        if (zip[file].UsesEncryption == true)
                        {
                            PasswordPrompt passWin = new PasswordPrompt();
                            passWin.ShowDialog();

                            zip.Password = passWin.pass;
                            try
                            {
                                entry.ExtractWithPassword(savePath, passWin.pass);
                            }
                            catch (BadPasswordException)
                            {
                                if (MessageBox.Show("Napačno geslo", "Napaka", MessageBoxButtons.RetryCancel, MessageBoxIcon.Error) == DialogResult.Retry)
                                {
                                    passWin.ShowDialog();
                                }
                            }
                        }

                        string enExists = savePath + @"\" + entry.FileName;

                        if (File.Exists(enExists))
                        {
                            if (MessageBox.Show("Datoteka " + file + " že obstaja. Ali jo želite zamenjati?", "Datoteka obstaja", MessageBoxButtons.YesNo, MessageBoxIcon.Information) == DialogResult.Yes)
                            {
                                entry.Extract(savePath, ExtractExistingFileAction.OverwriteSilently);
                            }
                            else
                            {
                                break;
                            }
                        }
                        else
                        {
                            entry.Extract(savePath);
                        }
                    }

                    else if (Path.GetExtension(txtPath.Text) == ".tar")
                    {
                        byte[]         outBuffer = new byte[4096];
                        TarInputStream tar       = new TarInputStream(new FileStream(txtPath.Text, FileMode.Open, FileAccess.Read));
                        TarEntry       curEntry  = tar.GetNextEntry();
                        while (curEntry != null)
                        {
                            if (curEntry.Name == file)
                            {
                                FileStream   fs = new FileStream(savePath + @"\" + curEntry.Name, FileMode.Create, FileAccess.Write);
                                BinaryWriter bw = new BinaryWriter(fs);
                                tar.Read(outBuffer, 0, (int)curEntry.Size);
                                bw.Write(outBuffer, 0, outBuffer.Length);
                                bw.Close();
                            }
                            curEntry = tar.GetNextEntry();
                        }
                        tar.Close();
                    }

                    else if (Path.GetExtension(txtPath.Text) == ".bz2")
                    {
                        Stream           str      = new FileStream(txtPath.Text, FileMode.Open, FileAccess.Read);
                        BZip2InputStream bzStr    = new BZip2InputStream(str);
                        TarInputStream   tar      = new TarInputStream(bzStr);
                        TarEntry         curEntry = tar.GetNextEntry();
                        while (curEntry != null)
                        {
                            if (curEntry.Name == file)
                            {
                                byte[]       outBuffer = new byte[curEntry.Size];
                                FileStream   fs        = new FileStream(savePath + @"\" + curEntry.Name, FileMode.Create, FileAccess.Write);
                                BinaryWriter bw        = new BinaryWriter(fs);
                                tar.Read(outBuffer, 0, (int)curEntry.Size);
                                bw.Write(outBuffer, 0, outBuffer.Length);
                                bw.Close();
                            }
                            curEntry = tar.GetNextEntry();
                        }
                        tar.Close();
                    }

                    else if (Path.GetExtension(txtPath.Text) == ".tgz")
                    {
                        Stream          str   = new FileStream(txtPath.Text, FileMode.Open, FileAccess.Read);
                        GZipInputStream gzStr = new GZipInputStream(str);
                        TarInputStream  tar   = new TarInputStream(gzStr);

                        TarEntry curEntry = tar.GetNextEntry();
                        while (curEntry != null)
                        {
                            if (curEntry.Name == file)
                            {
                                byte[]       outBuffer = new byte[curEntry.Size];
                                FileStream   fs        = new FileStream(savePath + @"\" + curEntry.Name, FileMode.Create, FileAccess.Write);
                                BinaryWriter bw        = new BinaryWriter(fs);
                                tar.Read(outBuffer, 0, (int)curEntry.Size);
                                bw.Write(outBuffer, 0, outBuffer.Length);
                                bw.Close();
                            }
                            curEntry = tar.GetNextEntry();
                        }
                        tar.Close();
                    }
                }
            }
            else
            {
                MessageBox.Show("Nobena datoteka ni bila izbrana. Prosimo izberite datoteke.", "Napaka", MessageBoxButtons.OK, MessageBoxIcon.Information);
            }
        }
Ejemplo n.º 29
0
    private static int GetFileFormatByZip(Ionic.Zip.ZipFile oZipFile)
    {
        if (oZipFile.ContainsEntry("[Content_Types].xml"))
        {
            Ionic.Zip.ZipEntry oEntry = oZipFile["[Content_Types].xml"];
            using (MemoryStream oMemoryStream = new MemoryStream((int)oEntry.UncompressedSize))
            {
                oEntry.Extract(oMemoryStream);
                oMemoryStream.Position = 0;
                string sContent = System.Text.UTF8Encoding.UTF8.GetString(oMemoryStream.GetBuffer(), 0, (int)oMemoryStream.Length);
                if (-1 != sContent.IndexOf("application/vnd.openxmlformats-officedocument.wordprocessingml.document.main+xml") ||
                    -1 != sContent.IndexOf("application/vnd.openxmlformats-officedocument.wordprocessingml.template.main+xml") ||
                    -1 != sContent.IndexOf("application/vnd.ms-word.document.macroEnabled.main+xml") ||
                    -1 != sContent.IndexOf("application/vnd.ms-word.template.macroEnabledTemplate.main+xml"))
                {
                    return(FileFormats.AVS_OFFICESTUDIO_FILE_DOCUMENT_DOCX);
                }
                else if (-1 != sContent.IndexOf("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet.main+xml") ||
                         -1 != sContent.IndexOf("application/vnd.openxmlformats-officedocument.spreadsheetml.template.main+xml") ||
                         -1 != sContent.IndexOf("application/vnd.ms-excel.sheet.macroEnabled.main+xml") ||
                         -1 != sContent.IndexOf("application/vnd.ms-excel.template.macroEnabled.main+xml"))
                {
                    return(FileFormats.AVS_OFFICESTUDIO_FILE_SPREADSHEET_XLSX);
                }
                else if (-1 != sContent.IndexOf("application/vnd.openxmlformats-officedocument.presentationml.presentation.main+xml") ||
                         -1 != sContent.IndexOf("application/vnd.openxmlformats-officedocument.presentationml.template.main+xml") ||
                         -1 != sContent.IndexOf("application/vnd.ms-powerpoint.presentation.macroEnabled.main+xml") ||
                         -1 != sContent.IndexOf("application/vnd.ms-powerpoint.slideshow.macroEnabled.main+xml") ||
                         -1 != sContent.IndexOf("application/vnd.ms-powerpoint.template.macroEnabled.main+xml"))
                {
                    return(FileFormats.AVS_OFFICESTUDIO_FILE_PRESENTATION_PPTX);
                }
                else if (-1 != sContent.IndexOf("application/vnd.openxmlformats-officedocument.presentationml.slideshow.main+xml"))
                {
                    return(FileFormats.AVS_OFFICESTUDIO_FILE_PRESENTATION_PPSX);
                }
            }
        }
        if (oZipFile.ContainsEntry("mimetype"))
        {
            Ionic.Zip.ZipEntry oEntry = oZipFile["mimetype"];
            using (MemoryStream oMemoryStream = new MemoryStream((int)oEntry.UncompressedSize))
            {
                oEntry.Extract(oMemoryStream);
                oMemoryStream.Position = 0;
                string sContent = System.Text.ASCIIEncoding.ASCII.GetString(oMemoryStream.GetBuffer(), 0, (int)oMemoryStream.Length);
                if (-1 != sContent.IndexOf("application/vnd.oasis.opendocument.text"))
                {
                    return(FileFormats.AVS_OFFICESTUDIO_FILE_DOCUMENT_ODT);
                }
                else if (-1 != sContent.IndexOf("application/vnd.oasis.opendocument.spreadsheet"))
                {
                    return(FileFormats.AVS_OFFICESTUDIO_FILE_SPREADSHEET_ODS);
                }
                else if (-1 != sContent.IndexOf("application/vnd.oasis.opendocument.presentation"))
                {
                    return(FileFormats.AVS_OFFICESTUDIO_FILE_PRESENTATION_ODP);
                }
                else if (-1 != sContent.IndexOf("application/epub+zip"))
                {
                    return(FileFormats.AVS_OFFICESTUDIO_FILE_DOCUMENT_EPUB);
                }
            }
        }
        if (oZipFile.ContainsEntry("_rels/.rels"))
        {
            Ionic.Zip.ZipEntry oEntry = oZipFile["_rels/.rels"];
            using (MemoryStream oMemoryStream = new MemoryStream((int)oEntry.UncompressedSize))
            {
                oEntry.Extract(oMemoryStream);
                oMemoryStream.Position = 0;
                string sContent = System.Text.ASCIIEncoding.ASCII.GetString(oMemoryStream.GetBuffer(), 0, (int)oMemoryStream.Length);
                if (-1 != sContent.IndexOf("http://schemas.microsoft.com/xps/2005/06/fixedrepresentation"))
                {
                    return(FileFormats.AVS_OFFICESTUDIO_FILE_CROSSPLATFORM_XPS);
                }
            }
        }

        if (oZipFile.ContainsEntry("_rels/.rels/[0].piece"))
        {
            return(FileFormats.AVS_OFFICESTUDIO_FILE_CROSSPLATFORM_XPS);
        }
        if (oZipFile.ContainsEntry("Editor.bin"))
        {
            Ionic.Zip.ZipEntry oEntry = oZipFile["Editor.bin"];
            int nFormat = FileFormats.AVS_OFFICESTUDIO_FILE_UNKNOWN;
            using (MemoryStream oMemoryStream = new MemoryStream((int)oEntry.UncompressedSize))
            {
                oEntry.Extract(oMemoryStream);
                oMemoryStream.Position = 0;
                int nSignatureLength = 4;
                if (oMemoryStream.Length >= nSignatureLength)
                {
                    byte[] aSignature = new byte[nSignatureLength];
                    oMemoryStream.Read(aSignature, 0, nSignatureLength);
                    string sSignature = System.Text.ASCIIEncoding.ASCII.GetString(aSignature);
                    switch (sSignature)
                    {
                    case "DOCY": nFormat = FileFormats.AVS_OFFICESTUDIO_FILE_TEAMLAB_DOCY; break;

                    case "XLSY": nFormat = FileFormats.AVS_OFFICESTUDIO_FILE_TEAMLAB_XLSY; break;

                    case "PPTY": nFormat = FileFormats.AVS_OFFICESTUDIO_FILE_TEAMLAB_PPTY; break;
                    }
                }
            }
            if (FileFormats.AVS_OFFICESTUDIO_FILE_UNKNOWN != nFormat)
            {
                return(nFormat);
            }
        }
        else if (oZipFile.ContainsEntry("Editor.xml"))
        {
            return(FileFormats.AVS_OFFICESTUDIO_FILE_OTHER_OLD_PRESENTATION);
        }
        else if (oZipFile.ContainsEntry("Editor.svg"))
        {
            return(FileFormats.AVS_OFFICESTUDIO_FILE_OTHER_OLD_DRAWING);
        }
        else if (oZipFile.ContainsEntry("Editor.html.arch"))
        {
            return(FileFormats.AVS_OFFICESTUDIO_FILE_OTHER_OLD_DOCUMENT);
        }
        return(FileFormats.AVS_OFFICESTUDIO_FILE_UNKNOWN);
    }
Ejemplo n.º 30
0
 // Token: 0x060002C2 RID: 706 RVA: 0x00015EFC File Offset: 0x000140FC
 internal SaveProgressEventArgs(string archiveName, bool before, int entriesTotal, int entriesSaved, ZipEntry entry) : base(archiveName, before ? ZipProgressEventType.Saving_BeforeWriteEntry : ZipProgressEventType.Saving_AfterWriteEntry)
 {
     base.EntriesTotal  = entriesTotal;
     base.CurrentEntry  = entry;
     this._entriesSaved = entriesSaved;
 }
 // Can be called from within ZipEntry.InternalExtract.
 internal bool OnSingleEntryExtract(ZipEntry entry, string path, bool before)
 {
     EventHandler<ExtractProgressEventArgs> ep = ExtractProgress;
     if (ep != null)
     {
         var e = (before)
             ? ExtractProgressEventArgs.BeforeExtractEntry(ArchiveNameForEvent, entry, path)
             : ExtractProgressEventArgs.AfterExtractEntry(ArchiveNameForEvent, entry, path);
         ep(this, e);
         if (e.Cancel)
             _extractOperationCanceled = true;
     }
     return _extractOperationCanceled;
 }
Ejemplo n.º 32
0
        /// <summary>
        ///   Reads one entry from the zip directory structure in the zip file.
        /// </summary>
        ///
        /// <param name="zf">
        ///   The zipfile for which a directory entry will be read.  From this param, the
        ///   method gets the ReadStream and the expected text encoding
        ///   (ProvisionalAlternateEncoding) which is used if the entry is not marked
        ///   UTF-8.
        /// </param>
        ///
        /// <param name="previouslySeen">
        ///   a list of previously seen entry names; used to prevent duplicates.
        /// </param>
        ///
        /// <returns>the entry read from the archive.</returns>
        internal static ZipEntry ReadDirEntry(ZipFile zf,
                                              Dictionary <String, Object> previouslySeen)
        {
            System.IO.Stream     s = zf.ReadStream;
            System.Text.Encoding expectedEncoding = (zf.AlternateEncodingUsage == ZipOption.Always)
                ? zf.AlternateEncoding
                : ZipFile.DefaultEncoding;

            int signature = Ionic.Zip.SharedUtilities.ReadSignature(s);

            // return null if this is not a local file header signature
            if (IsNotValidZipDirEntrySig(signature))
            {
                s.Seek(-4, System.IO.SeekOrigin.Current);
                // workitem 10178
                Ionic.Zip.SharedUtilities.Workaround_Ladybug318918(s);

                // Getting "not a ZipDirEntry signature" here is not always wrong or an
                // error.  This can happen when walking through a zipfile.  After the
                // last ZipDirEntry, we expect to read an
                // EndOfCentralDirectorySignature.  When we get this is how we know
                // we've reached the end of the central directory.
                if (signature != ZipConstants.EndOfCentralDirectorySignature &&
                    signature != ZipConstants.Zip64EndOfCentralDirectoryRecordSignature &&
                    signature != ZipConstants.ZipEntrySignature  // workitem 8299
                    )
                {
                    throw new BadReadException(String.Format("  Bad signature (0x{0:X8}) at position 0x{1:X8}", signature, s.Position));
                }
                return(null);
            }

            int bytesRead = 42 + 4;

            byte[] block = new byte[42];
            int    n     = s.Read(block, 0, block.Length);

            if (n != block.Length)
            {
                return(null);
            }

            int      i   = 0;
            ZipEntry zde = new ZipEntry();

            zde.AlternateEncoding = expectedEncoding;
            zde._Source           = ZipEntrySource.ZipFile;
            zde._container        = new ZipContainer(zf);

            unchecked
            {
                zde._VersionMadeBy     = (short)(block[i++] + block[i++] * 256);
                zde._VersionNeeded     = (short)(block[i++] + block[i++] * 256);
                zde._BitField          = (short)(block[i++] + block[i++] * 256);
                zde._CompressionMethod = (Int16)(block[i++] + block[i++] * 256);
                zde._TimeBlob          = block[i++] + block[i++] * 256 + block[i++] * 256 * 256 + block[i++] * 256 * 256 * 256;
                zde._LastModified      = Ionic.Zip.SharedUtilities.PackedToDateTime(zde._TimeBlob);
                zde._timestamp        |= ZipEntryTimestamp.DOS;

                zde._Crc32            = block[i++] + block[i++] * 256 + block[i++] * 256 * 256 + block[i++] * 256 * 256 * 256;
                zde._CompressedSize   = (uint)(block[i++] + block[i++] * 256 + block[i++] * 256 * 256 + block[i++] * 256 * 256 * 256);
                zde._UncompressedSize = (uint)(block[i++] + block[i++] * 256 + block[i++] * 256 * 256 + block[i++] * 256 * 256 * 256);
            }

            // preserve
            zde._CompressionMethod_FromZipFile = zde._CompressionMethod;

            zde._filenameLength   = (short)(block[i++] + block[i++] * 256);
            zde._extraFieldLength = (short)(block[i++] + block[i++] * 256);
            zde._commentLength    = (short)(block[i++] + block[i++] * 256);
            zde._diskNumber       = (UInt32)(block[i++] + block[i++] * 256);

            zde._InternalFileAttrs = (short)(block[i++] + block[i++] * 256);
            zde._ExternalFileAttrs = block[i++] + block[i++] * 256 + block[i++] * 256 * 256 + block[i++] * 256 * 256 * 256;

            zde._RelativeOffsetOfLocalHeader = (uint)(block[i++] + block[i++] * 256 + block[i++] * 256 * 256 + block[i++] * 256 * 256 * 256);

            // workitem 7801
            zde.IsText = ((zde._InternalFileAttrs & 0x01) == 0x01);

            block      = new byte[zde._filenameLength];
            n          = s.Read(block, 0, block.Length);
            bytesRead += n;
            if ((zde._BitField & 0x0800) == 0x0800)
            {
                // UTF-8 is in use
                zde._FileNameInArchive = Ionic.Zip.SharedUtilities.Utf8StringFromBuffer(block);
            }
            else
            {
                zde._FileNameInArchive = Ionic.Zip.SharedUtilities.StringFromBuffer(block, expectedEncoding);
            }

            // workitem 10330
            // insure unique entry names
            while (previouslySeen.ContainsKey(zde._FileNameInArchive))
            {
                zde._FileNameInArchive = CopyHelper.AppendCopyToFileName(zde._FileNameInArchive);
                zde._metadataChanged   = true;
            }

            if (zde.AttributesIndicateDirectory)
            {
                zde.MarkAsDirectory();  // may append a slash to filename if nec.
            }
            // workitem 6898
            else if (zde._FileNameInArchive.EndsWith("/"))
            {
                zde.MarkAsDirectory();
            }

            zde._CompressedFileDataSize = zde._CompressedSize;
            if ((zde._BitField & 0x01) == 0x01)
            {
                // this may change after processing the Extra field
                zde._Encryption_FromZipFile = zde._Encryption =
                    EncryptionAlgorithm.PkzipWeak;
                zde._sourceIsEncrypted = true;
            }

            if (zde._extraFieldLength > 0)
            {
                zde._InputUsesZip64 = (zde._CompressedSize == 0xFFFFFFFF ||
                                       zde._UncompressedSize == 0xFFFFFFFF ||
                                       zde._RelativeOffsetOfLocalHeader == 0xFFFFFFFF);

                // Console.WriteLine("  Input uses Z64?:      {0}", zde._InputUsesZip64);

                bytesRead += zde.ProcessExtraField(s, zde._extraFieldLength);
                zde._CompressedFileDataSize = zde._CompressedSize;
            }

            // we've processed the extra field, so we know the encryption method is set now.
            if (zde._Encryption == EncryptionAlgorithm.PkzipWeak)
            {
                // the "encryption header" of 12 bytes precedes the file data
                zde._CompressedFileDataSize -= 12;
            }
#if AESCRYPTO
            else if (zde.Encryption == EncryptionAlgorithm.WinZipAes128 ||
                     zde.Encryption == EncryptionAlgorithm.WinZipAes256)
            {
                zde._CompressedFileDataSize = zde.CompressedSize -
                                              (ZipEntry.GetLengthOfCryptoHeaderBytes(zde.Encryption) + 10);
                zde._LengthOfTrailer = 10;
            }
#endif

            // tally the trailing descriptor
            if ((zde._BitField & 0x0008) == 0x0008)
            {
                // sig, CRC, Comp and Uncomp sizes
                if (zde._InputUsesZip64)
                {
                    zde._LengthOfTrailer += 24;
                }
                else
                {
                    zde._LengthOfTrailer += 16;
                }
            }

            // workitem 12744
            zde.AlternateEncoding = ((zde._BitField & 0x0800) == 0x0800)
                ? System.Text.Encoding.UTF8
                :expectedEncoding;

            zde.AlternateEncodingUsage = ZipOption.Always;

            if (zde._commentLength > 0)
            {
                block      = new byte[zde._commentLength];
                n          = s.Read(block, 0, block.Length);
                bytesRead += n;
                if ((zde._BitField & 0x0800) == 0x0800)
                {
                    // UTF-8 is in use
                    zde._Comment = Ionic.Zip.SharedUtilities.Utf8StringFromBuffer(block);
                }
                else
                {
                    zde._Comment = Ionic.Zip.SharedUtilities.StringFromBuffer(block, expectedEncoding);
                }
            }
            //zde._LengthOfDirEntry = bytesRead;
            return(zde);
        }
Ejemplo n.º 33
0
        private static ZipEntry Create(string nameInArchive, ZipEntrySource source, Object arg1, Object arg2)
        {
            if (String.IsNullOrEmpty(nameInArchive))
            {
                throw new Ionic.Zip.ZipException("The entry name must be non-null and non-empty.");
            }

            ZipEntry entry = new ZipEntry();

            // workitem 7071
            // workitem 7926 - "version made by" OS should be zero for compat with WinZip
            entry._VersionMadeBy = (0 << 8) + 45; // indicates the attributes are FAT Attributes, and v4.5 of the spec
            entry._Source        = source;
            entry._Mtime         = entry._Atime = entry._Ctime = DateTime.UtcNow;

            if (source == ZipEntrySource.Stream)
            {
                entry._sourceStream = (arg1 as Stream);         // may  or may not be null
            }
            else if (source == ZipEntrySource.WriteDelegate)
            {
                entry._WriteDelegate = (arg1 as WriteDelegate); // may  or may not be null
            }
            else if (source == ZipEntrySource.JitStream)
            {
                entry._OpenDelegate  = (arg1 as OpenDelegate);  // may  or may not be null
                entry._CloseDelegate = (arg2 as CloseDelegate); // may  or may not be null
            }
            else if (source == ZipEntrySource.ZipOutputStream)
            {
            }
            // workitem 9073
            else if (source == ZipEntrySource.None)
            {
                // make this a valid value, for later.
                entry._Source = ZipEntrySource.FileSystem;
            }
            else
            {
                String filename = (arg1 as String);   // must not be null

                if (String.IsNullOrEmpty(filename))
                {
                    throw new Ionic.Zip.ZipException("The filename must be non-null and non-empty.");
                }

                try
                {
                    // The named file may or may not exist at this time.  For
                    // example, when adding a directory by name.  We test existence
                    // when necessary: when saving the ZipFile, or when getting the
                    // attributes, and so on.

                    // workitem 6878??
                    entry._Mtime = File.GetLastWriteTime(filename).ToUniversalTime();
                    entry._Ctime = File.GetCreationTime(filename).ToUniversalTime();
                    entry._Atime = File.GetLastAccessTime(filename).ToUniversalTime();

                    // workitem 7071
                    // can only get attributes on files that exist.
                    if (File.Exists(filename) || Directory.Exists(filename))
                    {
                        entry._ExternalFileAttrs = (int)File.GetAttributes(filename);
                    }

                    entry._ntfsTimesAreSet = true;

                    entry._LocalFileName = Path.GetFullPath(filename); // workitem 8813
                }
                catch (System.IO.PathTooLongException ptle)
                {
                    // workitem 14035
                    var msg = String.Format("The path is too long, filename={0}",
                                            filename);
                    throw new ZipException(msg, ptle);
                }
            }

            entry._LastModified      = entry._Mtime;
            entry._FileNameInArchive = SharedUtilities.NormalizePathForUseInZipFile(nameInArchive);
            // We don't actually slurp in the file data until the caller invokes Write on this entry.

            return(entry);
        }
Ejemplo n.º 34
0
        // build the TOC by reading each entry in the file.
        private static void ReadIntoInstance_Orig(ZipFile zf)
        {
            zf.OnReadStarted();
            //zf._entries = new System.Collections.Generic.List<ZipEntry>();
            zf._entries = new System.Collections.Generic.Dictionary <String, ZipEntry>();

            ZipEntry e;

            if (zf.Verbose)
            {
                if (zf.Name == null)
                {
                    zf.StatusMessageTextWriter.WriteLine("Reading zip from stream...");
                }
                else
                {
                    zf.StatusMessageTextWriter.WriteLine("Reading zip {0}...", zf.Name);
                }
            }

            // work item 6647:  PK00 (packed to removable disk)
            bool         firstEntry = true;
            ZipContainer zc         = new ZipContainer(zf);

            while ((e = ZipEntry.ReadEntry(zc, firstEntry)) != null)
            {
                if (zf.Verbose)
                {
                    zf.StatusMessageTextWriter.WriteLine("  {0}", e.FileName);
                }

                zf._entries.Add(e.FileName, e);
                firstEntry = false;
            }

            // read the zipfile's central directory structure here.
            // workitem 9912
            // But, because it may be corrupted, ignore errors.
            try
            {
                ZipEntry de;
                // in lieu of hashset, use a dictionary
                var previouslySeen = new Dictionary <String, Object>();
                while ((de = ZipEntry.ReadDirEntry(zf, previouslySeen)) != null)
                {
                    // Housekeeping: Since ZipFile exposes ZipEntry elements in the enumerator,
                    // we need to copy the comment that we grab from the ZipDirEntry
                    // into the ZipEntry, so the application can access the comment.
                    // Also since ZipEntry is used to Write zip files, we need to copy the
                    // file attributes to the ZipEntry as appropriate.
                    ZipEntry e1 = zf._entries[de.FileName];
                    if (e1 != null)
                    {
                        e1._Comment = de.Comment;
                        if (de.IsDirectory)
                        {
                            e1.MarkAsDirectory();
                        }
                    }
                    previouslySeen.Add(de.FileName, null); // to prevent dupes
                }

                // workitem 8299
                if (zf._locEndOfCDS > 0)
                {
                    zf.ReadStream.Seek(zf._locEndOfCDS, SeekOrigin.Begin);
                }

                ReadCentralDirectoryFooter(zf);

                if (zf.Verbose && !String.IsNullOrEmpty(zf.Comment))
                {
                    zf.StatusMessageTextWriter.WriteLine("Zip file Comment: {0}", zf.Comment);
                }
            }
            catch (ZipException) { }
            catch (IOException) { }

            zf.OnReadCompleted();
        }
Ejemplo n.º 35
0
 /// <summary>
 /// Constructor for the ExtractProgressEventArgs.
 /// </summary>
 /// <param name="archiveName">the name of the zip archive.</param>
 /// <param name="before">whether this is before saving the entry, or after</param>
 /// <param name="entriesTotal">The total number of entries in the zip archive.</param>
 /// <param name="entriesExtracted">Number of entries that have been extracted.</param>
 /// <param name="entry">The entry involved in the event.</param>
 /// <param name="extractLocation">The location to which entries are extracted.</param>
 /// <param name="wantOverwrite">indicates whether the extract operation will overwrite existing files.</param>
 internal ExtractProgressEventArgs(string archiveName, bool before, int entriesTotal, int entriesExtracted, ZipEntry entry, string extractLocation, bool wantOverwrite)
     : base(archiveName, (before) ? ZipProgressEventType.Extracting_BeforeExtractEntry : ZipProgressEventType.Extracting_AfterExtractEntry)
 {
     this.EntriesTotal      = entriesTotal;
     this.CurrentEntry      = entry;
     this._entriesExtracted = entriesExtracted;
     this._overwrite        = wantOverwrite;
     this._target           = extractLocation;
 }
 internal void OnReadBytes(ZipEntry entry)
 {
     EventHandler<ReadProgressEventArgs> rp = ReadProgress;
     if (rp != null)
     {
             var e = ReadProgressEventArgs.ByteUpdate(ArchiveNameForEvent,
                                 entry,
                                 ReadStream.Position,
                                 LengthOfReadStream);
             rp(this, e);
     }
 }
 private void OnExtractEntry(int current, bool before, ZipEntry currentEntry, string path)
 {
     EventHandler<ExtractProgressEventArgs> ep = ExtractProgress;
     if (ep != null)
     {
         var e = new ExtractProgressEventArgs(ArchiveNameForEvent, before, _entries.Count, current, currentEntry, path);
         ep(this, e);
         if (e.Cancel)
             _extractOperationCanceled = true;
     }
 }
Ejemplo n.º 38
0
        internal static ExtractProgressEventArgs AfterExtractEntry(string archiveName, ZipEntry entry, string extractLocation)
        {
            var x = new ExtractProgressEventArgs
            {
                ArchiveName  = archiveName,
                EventType    = ZipProgressEventType.Extracting_AfterExtractEntry,
                CurrentEntry = entry,
                _target      = extractLocation,
            };

            return(x);
        }
 private void OnSaveEntry(int current, ZipEntry entry, bool before)
 {
     EventHandler<SaveProgressEventArgs> sp = SaveProgress;
     if (sp != null)
     {
         var e = new SaveProgressEventArgs(ArchiveNameForEvent, before, _entries.Count, current, entry);
         sp(this, e);
         if (e.Cancel)
             _saveOperationCanceled = true;
     }
 }
Ejemplo n.º 40
0
        internal static ExtractProgressEventArgs AfterExtractEntry(string archiveName, ZipEntry entry, string extractLocation, bool wantOverwrite)
        {
            var x = new ExtractProgressEventArgs();

            x.ArchiveName  = archiveName;
            x.EventType    = ZipProgressEventType.Extracting_AfterExtractEntry;
            x.CurrentEntry = entry;
            x._target      = extractLocation;
            x._overwrite   = wantOverwrite;
            return(x);
        }
 internal void OnReadEntry(bool before, ZipEntry entry)
 {
     EventHandler<ReadProgressEventArgs> rp = ReadProgress;
     if (rp != null)
     {
         ReadProgressEventArgs e = (before)
             ? ReadProgressEventArgs.Before(ArchiveNameForEvent, _entries.Count)
             : ReadProgressEventArgs.After(ArchiveNameForEvent, entry, _entries.Count);
         rp(this, e);
     }
 }
Ejemplo n.º 42
0
        private static void ReadCentralDirectory(ZipFile zf)
        {
            // We must have the central directory footer record, in order to properly
            // read zip dir entries from the central directory.  This because the logic
            // knows when to open a spanned file when the volume number for the central
            // directory differs from the volume number for the zip entry.  The
            // _diskNumberWithCd was set when originally finding the offset for the
            // start of the Central Directory.

            // workitem 9214
            bool     inputUsesZip64 = false;
            ZipEntry de;
            // in lieu of hashset, use a dictionary
            var previouslySeen = new Dictionary <String, object>();

            while ((de = ZipEntry.ReadDirEntry(zf, previouslySeen)) != null)
            {
                try
                {
                    de.ResetDirEntry();
                    zf.OnReadEntry(true, null);

                    if (zf.Verbose)
                    {
                        zf.StatusMessageTextWriter.WriteLine("entry {0}", de.FileName);
                    }
                    zf._entries.Add(de.FileName, de);
                    // workitem 9214
                    if (de._InputUsesZip64)
                    {
                        inputUsesZip64 = true;
                    }
                    previouslySeen.Add(de.FileName, null); // to prevent dupes
                }
                catch (Exception ex)
                {
                }
            }

            // workitem 9214; auto-set the zip64 flag
            if (inputUsesZip64)
            {
                zf.UseZip64WhenSaving = Zip64Option.Always;
            }

            // workitem 8299
            if (zf._locEndOfCDS > 0)
            {
                zf.ReadStream.Seek(zf._locEndOfCDS, SeekOrigin.Begin);
            }

            ReadCentralDirectoryFooter(zf);

            if (zf.Verbose && !String.IsNullOrEmpty(zf.Comment))
            {
                zf.StatusMessageTextWriter.WriteLine("Zip file Comment: {0}", zf.Comment);
            }

            // We keep the read stream open after reading.

            if (zf.Verbose)
            {
                zf.StatusMessageTextWriter.WriteLine("read in {0} entries.", zf._entries.Count);
            }

            zf.OnReadCompleted();
        }
 // Can be called from within ZipEntry._ExtractOne.
 internal bool OnExtractBlock(ZipEntry entry, Int64 bytesWritten, Int64 totalBytesToWrite)
 {
     EventHandler<ExtractProgressEventArgs> ep = ExtractProgress;
     if (ep != null)
     {
         var e = ExtractProgressEventArgs.ByteUpdate(ArchiveNameForEvent, entry,
                                                     bytesWritten, totalBytesToWrite);
         ep(this, e);
         if (e.Cancel)
             _extractOperationCanceled = true;
     }
     return _extractOperationCanceled;
 }
Ejemplo n.º 44
0
        private void _SaveSfxStub(string exeToGenerate, SelfExtractorSaveOptions options)
        {
            string nameOfIconFile      = null;
            string stubExe             = null;
            string unpackedResourceDir = null;
            string tmpDir = null;

            try
            {
                if (File.Exists(exeToGenerate))
                {
                    if (Verbose)
                    {
                        StatusMessageTextWriter.WriteLine("The existing file ({0}) will be overwritten.", exeToGenerate);
                    }
                }
                if (!exeToGenerate.EndsWith(".exe"))
                {
                    if (Verbose)
                    {
                        StatusMessageTextWriter.WriteLine("Warning: The generated self-extracting file will not have an .exe extension.");
                    }
                }

                // workitem 10553
                tmpDir  = TempFileFolder ?? Path.GetDirectoryName(exeToGenerate);
                stubExe = GenerateTempPathname(tmpDir, "exe");

                // get the Ionic.Zip assembly
                Assembly a1 = typeof(ZipFile).Assembly;

                using (var csharp = new Microsoft.CSharp.CSharpCodeProvider
                                        (new Dictionary <string, string>()
                {
                    { "CompilerVersion", "v2.0" }
                })) {
                    ExtractorSettings settings =
                        (from x in SettingsList
                         where x.Flavor == options.Flavor
                         select x).FirstOrDefault();

                    // sanity check; should never happen
                    if (settings == null)
                    {
                        throw new BadStateException(String.Format("While saving a Self-Extracting Zip, Cannot find that flavor ({0})?", options.Flavor));
                    }

                    // This is the list of referenced assemblies.  Ionic.Zip is
                    // needed here.  Also if it is the winforms (gui) extractor, we
                    // need other referenced assemblies, like
                    // System.Windows.Forms.dll, etc.
                    var cp = new System.CodeDom.Compiler.CompilerParameters();
                    cp.ReferencedAssemblies.Add(a1.Location);
                    if (settings.ReferencedAssemblies != null)
                    {
                        foreach (string ra in settings.ReferencedAssemblies)
                        {
                            cp.ReferencedAssemblies.Add(ra);
                        }
                    }

                    cp.GenerateInMemory        = false;
                    cp.GenerateExecutable      = true;
                    cp.IncludeDebugInformation = false;
                    cp.CompilerOptions         = "";

                    Assembly a2 = Assembly.GetExecutingAssembly();

                    // Use this to concatenate all the source code resources into a
                    // single module.
                    var sb = new System.Text.StringBuilder();

                    // In case there are compiler errors later, we allocate a source
                    // file name now. If errors are detected, we'll spool the source
                    // code as well as the errors (in comments) into that filename,
                    // and throw an exception with the filename.  Makes it easier to
                    // diagnose.  This should be rare; most errors happen only
                    // during devlpmt of DotNetZip itself, but there are rare
                    // occasions when they occur in other cases.
                    string sourceFile = GenerateTempPathname(tmpDir, "cs");


                    // // debugging: enumerate the resources in this assembly
                    // Console.WriteLine("Resources in this assembly:");
                    // foreach (string rsrc in a2.GetManifestResourceNames())
                    //   {
                    //     Console.WriteLine(rsrc);
                    //   }
                    // Console.WriteLine();


                    // all the source code is embedded in the DLL as a zip file.
                    using (ZipFile zip = ZipFile.Read(a2.GetManifestResourceStream("Ionic.Zip.Resources.ZippedResources.zip")))
                    {
                        // // debugging: enumerate the files in the embedded zip
                        // Console.WriteLine("Entries in the embbedded zip:");
                        // foreach (ZipEntry entry in zip)
                        //   {
                        //     Console.WriteLine(entry.FileName);
                        //   }
                        // Console.WriteLine();

                        unpackedResourceDir = GenerateTempPathname(tmpDir, "tmp");

                        if (String.IsNullOrEmpty(options.IconFile))
                        {
                            // Use the ico file that is embedded into the Ionic.Zip
                            // DLL itself.  To do this we must unpack the icon to
                            // the filesystem, in order to specify it on the cmdline
                            // of csc.exe.  This method will remove the unpacked
                            // file later.
                            System.IO.Directory.CreateDirectory(unpackedResourceDir);
                            ZipEntry e = zip["zippedFile.ico"];
                            // Must not extract a readonly file - it will be impossible to
                            // delete later.
                            if ((e.Attributes & FileAttributes.ReadOnly) == FileAttributes.ReadOnly)
                            {
                                e.Attributes ^= FileAttributes.ReadOnly;
                            }
                            e.Extract(unpackedResourceDir);
                            nameOfIconFile      = Path.Combine(unpackedResourceDir, "zippedFile.ico");
                            cp.CompilerOptions += String.Format("/win32icon:\"{0}\"", nameOfIconFile);
                        }
                        else
                        {
                            cp.CompilerOptions += String.Format("/win32icon:\"{0}\"", options.IconFile);
                        }

                        cp.OutputAssembly = stubExe;

                        if (options.Flavor == SelfExtractorFlavor.WinFormsApplication)
                        {
                            cp.CompilerOptions += " /target:winexe";
                        }

                        if (!String.IsNullOrEmpty(options.AdditionalCompilerSwitches))
                        {
                            cp.CompilerOptions += " " + options.AdditionalCompilerSwitches;
                        }

                        if (String.IsNullOrEmpty(cp.CompilerOptions))
                        {
                            cp.CompilerOptions = null;
                        }

                        if ((settings.CopyThroughResources != null) && (settings.CopyThroughResources.Count != 0))
                        {
                            if (!Directory.Exists(unpackedResourceDir))
                            {
                                System.IO.Directory.CreateDirectory(unpackedResourceDir);
                            }
                            foreach (string re in settings.CopyThroughResources)
                            {
                                string filename = Path.Combine(unpackedResourceDir, re);

                                ExtractResourceToFile(a2, re, filename);
                                // add the file into the target assembly as an embedded resource
                                cp.EmbeddedResources.Add(filename);
                            }
                        }

                        // add the Ionic.Utils.Zip DLL as an embedded resource
                        cp.EmbeddedResources.Add(a1.Location);

                        // file header
                        sb.Append("// " + Path.GetFileName(sourceFile) + "\n")
                        .Append("// --------------------------------------------\n//\n")
                        .Append("// This SFX source file was generated by DotNetZip ")
                        .Append(ZipFile.LibraryVersion.ToString())
                        .Append("\n//         at ")
                        .Append(System.DateTime.Now.ToString("yyyy MMMM dd  HH:mm:ss"))
                        .Append("\n//\n// --------------------------------------------\n\n\n");

                        // assembly attributes
                        if (!String.IsNullOrEmpty(options.Description))
                        {
                            sb.Append("[assembly: System.Reflection.AssemblyTitle(\""
                                      + options.Description.Replace("\"", "")
                                      + "\")]\n");
                        }
                        else
                        {
                            sb.Append("[assembly: System.Reflection.AssemblyTitle(\"DotNetZip SFX Archive\")]\n");
                        }

                        if (!String.IsNullOrEmpty(options.ProductVersion))
                        {
                            sb.Append("[assembly: System.Reflection.AssemblyInformationalVersion(\""
                                      + options.ProductVersion.Replace("\"", "")
                                      + "\")]\n");
                        }

                        // workitem
                        string copyright =
                            (String.IsNullOrEmpty(options.Copyright))
                            ? "Extractor: Copyright � Dino Chiesa 2008-2011"
                            : options.Copyright.Replace("\"", "");

                        if (!String.IsNullOrEmpty(options.ProductName))
                        {
                            sb.Append("[assembly: System.Reflection.AssemblyProduct(\"")
                            .Append(options.ProductName.Replace("\"", ""))
                            .Append("\")]\n");
                        }
                        else
                        {
                            sb.Append("[assembly: System.Reflection.AssemblyProduct(\"DotNetZip\")]\n");
                        }


                        sb.Append("[assembly: System.Reflection.AssemblyCopyright(\"" + copyright + "\")]\n")
                        .Append(String.Format("[assembly: System.Reflection.AssemblyVersion(\"{0}\")]\n", ZipFile.LibraryVersion.ToString()));
                        if (options.FileVersion != null)
                        {
                            sb.Append(String.Format("[assembly: System.Reflection.AssemblyFileVersion(\"{0}\")]\n",
                                                    options.FileVersion.ToString()));
                        }

                        sb.Append("\n\n\n");

                        // Set the default extract location if it is available
                        string extractLoc = options.DefaultExtractDirectory;
                        if (extractLoc != null)
                        {
                            // remove double-quotes and replace slash with double-slash.
                            // This, because the value is going to be embedded into a
                            // cs file as a quoted string, and it needs to be escaped.
                            extractLoc = extractLoc.Replace("\"", "").Replace("\\", "\\\\");
                        }

                        string postExCmdLine = options.PostExtractCommandLine;
                        if (postExCmdLine != null)
                        {
                            postExCmdLine = postExCmdLine.Replace("\\", "\\\\");
                            postExCmdLine = postExCmdLine.Replace("\"", "\\\"");
                        }


                        foreach (string rc in settings.ResourcesToCompile)
                        {
                            using (Stream s = zip[rc].OpenReader())
                            {
                                if (s == null)
                                {
                                    throw new ZipException(String.Format("missing resource '{0}'", rc));
                                }
                                using (StreamReader sr = new StreamReader(s))
                                {
                                    while (sr.Peek() >= 0)
                                    {
                                        string line = sr.ReadLine();
                                        if (extractLoc != null)
                                        {
                                            line = line.Replace("@@EXTRACTLOCATION", extractLoc);
                                        }

                                        line = line.Replace("@@REMOVE_AFTER_EXECUTE", options.RemoveUnpackedFilesAfterExecute.ToString());
                                        line = line.Replace("@@QUIET", options.Quiet.ToString());
                                        if (!String.IsNullOrEmpty(options.SfxExeWindowTitle))
                                        {
                                            line = line.Replace("@@SFX_EXE_WINDOW_TITLE", options.SfxExeWindowTitle);
                                        }

                                        line = line.Replace("@@EXTRACT_EXISTING_FILE", ((int)options.ExtractExistingFile).ToString());

                                        if (postExCmdLine != null)
                                        {
                                            line = line.Replace("@@POST_UNPACK_CMD_LINE", postExCmdLine);
                                        }

                                        sb.Append(line).Append("\n");
                                    }
                                }
                                sb.Append("\n\n");
                            }
                        }
                    }

                    string LiteralSource = sb.ToString();

#if DEBUGSFX
                    // for debugging only
                    string sourceModule = GenerateTempPathname(tmpDir, "cs");
                    using (StreamWriter sw = File.CreateText(sourceModule))
                    {
                        sw.Write(LiteralSource);
                    }
                    Console.WriteLine("source: {0}", sourceModule);
#endif

                    var cr = csharp.CompileAssemblyFromSource(cp, LiteralSource);


                    if (cr == null)
                    {
                        throw new SfxGenerationException("Cannot compile the extraction logic!");
                    }

                    if (Verbose)
                    {
                        foreach (string output in cr.Output)
                        {
                            StatusMessageTextWriter.WriteLine(output);
                        }
                    }

                    if (cr.Errors.Count != 0)
                    {
                        using (TextWriter tw = new StreamWriter(sourceFile))
                        {
                            // first, the source we compiled
                            tw.Write(LiteralSource);

                            // now, append the compile errors
                            tw.Write("\n\n\n// ------------------------------------------------------------------\n");
                            tw.Write("// Errors during compilation: \n//\n");
                            string p = Path.GetFileName(sourceFile);

                            foreach (System.CodeDom.Compiler.CompilerError error in cr.Errors)
                            {
                                tw.Write(String.Format("//   {0}({1},{2}): {3} {4}: {5}\n//\n",
                                                       p,                                     // 0
                                                       error.Line,                            // 1
                                                       error.Column,                          // 2
                                                       error.IsWarning ? "Warning" : "error", // 3
                                                       error.ErrorNumber,                     // 4
                                                       error.ErrorText));                     // 5
                            }
                        }
                        throw new SfxGenerationException(String.Format("Errors compiling the extraction logic!  {0}", sourceFile));
                    }

                    OnSaveEvent(ZipProgressEventType.Saving_AfterCompileSelfExtractor);

                    // Now, copy the resulting EXE image to the _writestream.
                    // Because this stub exe is being saved first, the effect will be to
                    // concatenate the exe and the zip data together.
                    using (System.IO.Stream input = System.IO.File.OpenRead(stubExe))
                    {
                        byte[] buffer = new byte[4000];
                        int    n      = 1;
                        while (n != 0)
                        {
                            n = input.Read(buffer, 0, buffer.Length);
                            if (n != 0)
                            {
                                WriteStream.Write(buffer, 0, n);
                            }
                        }
                    }
                }

                OnSaveEvent(ZipProgressEventType.Saving_AfterSaveTempArchive);
            }
            finally
            {
                try
                {
                    if (Directory.Exists(unpackedResourceDir))
                    {
                        try { Directory.Delete(unpackedResourceDir, true); }
                        catch (System.IO.IOException exc1)
                        {
                            StatusMessageTextWriter.WriteLine("Warning: Exception: {0}", exc1);
                        }
                    }
                    if (File.Exists(stubExe))
                    {
                        try { File.Delete(stubExe); }
                        catch (System.IO.IOException exc1)
                        {
                            StatusMessageTextWriter.WriteLine("Warning: Exception: {0}", exc1);
                        }
                    }
                }
                catch (System.IO.IOException) { }
            }

            return;
        }
 internal bool OnExtractExisting(ZipEntry entry, string path)
 {
     EventHandler<ExtractProgressEventArgs> ep = ExtractProgress;
     if (ep != null)
     {
         var e = ExtractProgressEventArgs.ExtractExisting(ArchiveNameForEvent, entry, path);
         ep(this, e);
         if (e.Cancel)
             _extractOperationCanceled = true;
     }
     return _extractOperationCanceled;
 }
Ejemplo n.º 46
0
        public static ZipCrypto ForRead(string password, ZipEntry e)
        {
            System.IO.Stream s = e._archiveStream;
            e._WeakEncryptionHeader = new byte[12];
            byte[]    eh = e._WeakEncryptionHeader;
            ZipCrypto z  = new ZipCrypto();

            if (password == null)
            {
                throw new BadPasswordException("This entry requires a password.");
            }

            z.InitCipher(password);

            ZipEntry.ReadWeakEncryptionHeader(s, eh);

            // Decrypt the header.  This has a side effect of "further initializing the
            // encryption keys" in the traditional zip encryption.
            byte[] DecryptedHeader = z.DecryptMessage(eh, eh.Length);

            // CRC check
            // According to the pkzip spec, the final byte in the decrypted header
            // is the highest-order byte in the CRC. We check it here.
            if (DecryptedHeader[11] != (byte)((e._Crc32 >> 24) & 0xff))
            {
                // In the case that bit 3 of the general purpose bit flag is set to
                // indicate the presence of an 'Extended File Header' or a 'data
                // descriptor' (signature 0x08074b50), the last byte of the decrypted
                // header is sometimes compared with the high-order byte of the
                // lastmodified time, rather than the high-order byte of the CRC, to
                // verify the password.
                //
                // This is not documented in the PKWare Appnote.txt.  It was
                // discovered this by analysis of the Crypt.c source file in the
                // InfoZip library http://www.info-zip.org/pub/infozip/
                //
                // The reason for this is that the CRC for a file cannot be known
                // until the entire contents of the file have been streamed. This
                // means a tool would have to read the file content TWICE in its
                // entirety in order to perform PKZIP encryption - once to compute
                // the CRC, and again to actually encrypt.
                //
                // This is so important for performance that using the timeblob as
                // the verification should be the standard practice for DotNetZip
                // when using PKZIP encryption. This implies that bit 3 must be
                // set. The downside is that some tools still cannot cope with ZIP
                // files that use bit 3.  Therefore, DotNetZip DOES NOT force bit 3
                // when PKZIP encryption is in use, and instead, reads the stream
                // twice.
                //

                if ((e._BitField & 0x0008) != 0x0008)
                {
                    throw new BadPasswordException("The password did not match.");
                }
                else if (DecryptedHeader[11] != (byte)((e._TimeBlob >> 8) & 0xff))
                {
                    throw new BadPasswordException("The password did not match.");
                }

                // We have a good password.
            }
            else
            {
                // A-OK
            }
            return(z);
        }