Esempio n. 1
0
        /// <summary>
        /// Creates an input stream reading a zip entry
        /// </summary>
        /// <param name="entryIndex">The index of the entry to obtain an input stream for.</param>
        /// <returns>
        /// An input stream.
        /// </returns>
        /// <exception cref="InvalidOperationException">
        /// The ZipFile has already been closed
        /// </exception>
        /// <exception cref="ICSharpCode.SharpZipLib.Zip.ZipException">
        /// The compression method for the entry is unknown
        /// </exception>
        /// <exception cref="IndexOutOfRangeException">
        /// The entry is not found in the ZipFile
        /// </exception>
        public Stream GetInputStream(int entryIndex)
        {
            if (entries == null)
            {
                throw new InvalidOperationException("ZipFile has closed");
            }

            long start = CheckLocalHeader(entries[entryIndex]);
            CompressionMethod method = entries[entryIndex].CompressionMethod;
            Stream            istr   = new PartialInputStream(baseStream, start, entries[entryIndex].CompressedSize);

            if (entries[entryIndex].IsCrypted == true)
            {
                istr = CreateAndInitDecryptionStream(istr, entries[entryIndex]);
                if (istr == null)
                {
                    throw new ZipException("Unable to decrypt this entry");
                }
            }

            switch (method)
            {
            case CompressionMethod.Stored:
                return(istr);

            case CompressionMethod.Deflated:
                return(new InflaterInputStream(istr, new Inflater(true)));

            default:
                throw new ZipException("Unsupported compression method " + method);
            }
        }
Esempio n. 2
0
        /// <summary>
        /// Creates an input stream reading the given zip entry as
        /// uncompressed data.  Normally zip entry should be an entry
        /// returned by GetEntry().
        /// </summary>
        /// <returns>
        /// the input stream.
        /// </returns>
        /// <exception name="System.IO.IOException">
        /// if a i/o error occured.
        /// </exception>
        /// <exception name="SinoSZBaseClass.SharpZipLib.ZipException">
        /// if the Zip archive is malformed.
        /// </exception>
        public Stream GetInputStream(ZipEntry entry)
        {
            if (entries == null)
            {
                throw new InvalidOperationException("ZipFile has closed");
            }

            int index = entry.zipFileIndex;

            if (index < 0 || index >= entries.Length || entries[index].Name != entry.Name)
            {
                index = GetEntryIndex(entry.Name);
                if (index < 0)
                {
                    throw new IndexOutOfRangeException();
                }
            }

            long start = CheckLocalHeader(entries[index]);
            CompressionMethod method = entries[index].CompressionMethod;
            Stream            istr   = new PartialInputStream(baseStream, start, entries[index].CompressedSize);

            switch (method)
            {
            case CompressionMethod.Stored:
                return(istr);

            case CompressionMethod.Deflated:
                return(new InflaterInputStream(istr, new Inflater(true)));

            default:
                throw new ZipException("Unknown compression method " + method);
            }
        }
        public Stream GetInputStream(int entryIndex)
        {
            if (this.entries == null)
            {
                throw new InvalidOperationException("ZipFile has closed");
            }
            long start = this.CheckLocalHeader(this.entries[entryIndex]);
            CompressionMethod compressionMethod = this.entries[entryIndex].CompressionMethod;
            Stream            baseStream        = new PartialInputStream(this.baseStream, start, this.entries[entryIndex].CompressedSize);

            if (this.entries[entryIndex].IsCrypted)
            {
                baseStream = this.CreateAndInitDecryptionStream(baseStream, this.entries[entryIndex]);
                if (baseStream == null)
                {
                    throw new ZipException("Unable to decrypt this entry");
                }
            }
            CompressionMethod method2 = compressionMethod;

            if (method2 != CompressionMethod.Stored)
            {
                if (method2 != CompressionMethod.Deflated)
                {
                    throw new ZipException("Unsupported compression method " + compressionMethod);
                }
                return(new InflaterInputStream(baseStream, new Inflater(true)));
            }
            return(baseStream);
        }
Esempio n. 4
0
        /// <summary>
        /// Get a Stream for reading the specified entry
        /// </summary>
        /// <param name="entry"></param>
        /// <returns></returns>
        public Stream GetInputStream(ZipEntry entry)
        {
            if (entry.Size == 0)
            {
                return(null);
            }

            if (entries == null)
            {
                throw new InvalidOperationException("ZipFile has closed");
            }

            long index = entry.ZipFileIndex;

            if (index < 0 || index >= entries.Length || entries[index].Name != entry.Name)
            {
                throw new IndexOutOfRangeException();
            }

            // WARNING
            // should parse the Local Header to get the data address
            // Maximum Size of the Local Header is ... 16+64K*2
            //
            // So the HTTP request should ask for the big local header, but actually the
            // additional data is not downloaded.
            // Optionally use an additional Request to be really precise
            HttpWebRequest req = (HttpWebRequest)WebRequest.Create(baseUrl);

            int limit = (int)(entry.Offset + entry.CompressedSize + 16 + 65536 * 2);

            if (limit >= MaxFileOffset)
            {
                limit = MaxFileOffset - 1;
            }
            req.AddRange((int)entry.Offset, limit);
            HttpWebResponse res        = (HttpWebResponse)req.GetResponse();
            Stream          baseStream = res.GetResponseStream();

            // skips all the header
            SkipLocalHeader(baseStream, entries[index]);
            CompressionMethod method = entries[index].CompressionMethod;

            Stream istr = new PartialInputStream(baseStream, res, entries[index].CompressedSize);

            switch (method)
            {
            case CompressionMethod.Stored:
                return(istr);

            case CompressionMethod.Deflated:
                return(new InflaterInputStream(istr, new Inflater(true)));

            case (CompressionMethod)12:
                return(new BZip2InputStream(istr));

            default:
                throw new ZipException("Unknown compression method " + method);
            }
        }
Esempio n. 5
0
        /// <summary>
        /// Creates an input stream reading the given zip entry as
        /// uncompressed data.  Normally zip entry should be an entry
        /// returned by GetEntry().
        /// </summary>
        /// <returns>
        /// the input stream.
        /// </returns>
        /// <exception cref="InvalidOperationException">
        /// The ZipFile has already been closed
        /// </exception>
        /// <exception cref="DMSys.Cryptography.Zip.ZipException">
        /// The compression method for the entry is unknown
        /// </exception>
        /// <exception cref="IndexOutOfRangeException">
        /// The entry is not found in the ZipFile
        /// </exception>
        public Stream GetInputStream(ZipEntry entry)
        {
            if (entries == null)
            {
                throw new InvalidOperationException("ZipFile has closed");
            }

            /*
             * Original method
             * Replaced by Corinna John to support "invisible" entries
             *
             * int index = entry.ZipFileIndex;
             * if (index < 0 || index >= entries.Length || entries[index].Name != entry.Name) {
             *      index = FindEntry(entry.Name, true);
             *      if (index < 0) {
             *              throw new IndexOutOfRangeException();
             *      }
             * }
             * return GetInputStream(index);*/

            if (entries == null)
            {
                throw new InvalidOperationException("ZipFile is closed");
            }

            long start = CheckLocalHeader(entry);

            CompressionMethod method = entry.CompressionMethod;
            Stream            istr   = new PartialInputStream(baseStream, start, entry.CompressedSize);

            if (entry.IsCrypted == true)
            {
                istr = CreateAndInitDecryptionStream(istr, entry);
                if (istr == null)
                {
                    throw new ZipException("Unable to decrypt this entry");
                }
            }

            switch (method)
            {
            case CompressionMethod.Stored:
                return(istr);

            case CompressionMethod.Deflated:
                return(new InflaterInputStream(istr, new Inflater(true)));

            default:
                throw new ZipException("Unsupported compression method " + method);
            }
        }
Esempio n. 6
0
        /// <summary>
        /// Checks the file stream after the given zip entry for another one.
        /// </summary>
        /// <param name="entryIndex">The index of a zip entry.</param>
        /// <returns>true: there are more entries after this one. false: this is the last entry.</returns>
        public bool HasSuccessor(ZipEntry zipEntry)
        {
            if (entries == null)
            {
                throw new InvalidOperationException("ZipFile is closed");
            }

            //beginning of the preceeding zip entry
            long startPredecessor = CheckLocalHeader(zipEntry);

            //end of the preceeding zip entry
            long endPredecessor = startPredecessor + zipEntry.CompressedSize;

            //get a stream for whatever follows the zip entry
            Stream stream = new PartialInputStream(baseStream, endPredecessor, ZipConstants.LOCHDR);

            //read what may be a local file header
            int localHeaderStart = ReadLeInt(stream);

            //is it the beginning of another local file?
            return(localHeaderStart == ZipConstants.LOCSIG);
        }
Esempio n. 7
0
        /// <summary>
        /// Creates an input stream reading the zip entry based on the index passed
        /// </summary>
        /// <returns>
        /// An input stream.
        /// </returns>
        /// <exception cref="InvalidOperationException">
        /// The ZipFile has already been closed
        /// </exception>
        /// <exception cref="ICSharpCode.SharpZipLib.ZipException">
        /// The compression method for the entry is unknown
        /// </exception>
        /// <exception cref="IndexOutOfRangeException">
        /// The entry is not found in the ZipFile
        /// </exception>
        public Stream GetInputStream(int entryIndex)
        {
            if (entries == null)
            {
                throw new InvalidOperationException("ZipFile has closed");
            }

            long start = CheckLocalHeader(entries[entryIndex]);
            CompressionMethod method = entries[entryIndex].CompressionMethod;
            Stream            istr   = new PartialInputStream(baseStream, start, entries[entryIndex].CompressedSize);

            switch (method)
            {
            case CompressionMethod.Stored:
                return(istr);

            case CompressionMethod.Deflated:
                return(new InflaterInputStream(istr, new Inflater(true)));

            default:
                throw new ZipException("Unknown compression method " + method);
            }
        }
Esempio n. 8
0
		/// <summary>
		/// Creates an input stream reading a zip entry
		/// </summary>
		/// <param name="entryIndex">The index of the entry to obtain an input stream for.</param>
		/// <returns>
		/// An input stream.
		/// </returns>
		/// <exception cref="InvalidOperationException">
		/// The ZipFile has already been closed
		/// </exception>
		/// <exception cref="Fireball.IO.Compression.Zip.ZipException">
		/// The compression method for the entry is unknown
		/// </exception>
		/// <exception cref="IndexOutOfRangeException">
		/// The entry is not found in the ZipFile
		/// </exception>
		public Stream GetInputStream(int entryIndex)
		{
			if (entries == null) {
				throw new InvalidOperationException("ZipFile has closed");
			}
			
			long start = CheckLocalHeader(entries[entryIndex]);
			CompressionMethod method = entries[entryIndex].CompressionMethod;
			Stream istr = new PartialInputStream(baseStream, start, entries[entryIndex].CompressedSize);

			if (entries[entryIndex].IsCrypted == true) {
				istr = CreateAndInitDecryptionStream(istr, entries[entryIndex]);
				if (istr == null) {
					throw new ZipException("Unable to decrypt this entry");
				}
			}

			switch (method) {
				case CompressionMethod.Stored:
					return istr;
				case CompressionMethod.Deflated:
					return new InflaterInputStream(istr, new Inflater(true));
				default:
					throw new ZipException("Unsupported compression method " + method);
			}
		}
Esempio n. 9
0
        /**
         * Read the central directory of a zip file and fill the entries
         * array.  This is called exactly once when first needed. It is called
         * while holding the lock on <code>raf</code>.
         *
         * @exception IOException if a i/o error occured.
         * @exception ZipException if the central directory is malformed 
         */
        private void readEntries()
        {
            /* Search for the End Of Central Directory.  When a zip comment is 
             * present the directory may start earlier.
             * Note that a comment has a maximum length of 64K, so that is the
             * maximum we search backwards.
             */
            PartialInputStream inp = new PartialInputStream(raf, 4096);
            long pos = raf.Length - ENDHDR;
            long top = Math.Max(0, pos - 65536);
            do
            {
                if (pos < top)
                    throw new System.Exception
                      ("central directory not found, probably not a zip file: " + name);
                inp.seek(pos--);
            }
            while (inp.readLeInt() != ENDSIG);

            if (inp.skip(ENDTOT - ENDNRD) != ENDTOT - ENDNRD)
                throw new System.Exception(name);
            int count = inp.readLeShort();
            if (inp.skip(ENDOFF - ENDSIZ) != ENDOFF - ENDSIZ)
                throw new System.Exception(name);
            int centralOffset = inp.readLeInt();

            entries = new Dictionary<String, ZipEntry>(count + count / 2);
            inp.seek(centralOffset);

            for (int i = 0; i < count; i++)
            {
                if (inp.readLeInt() != CENSIG)
                    throw new System.Exception("Wrong Central Directory signature: " + name);

                inp.skip(6);
                int method = inp.readLeShort();
                int dostime = inp.readLeInt();
                int crc = inp.readLeInt();
                int csize = inp.readLeInt();
                int size = inp.readLeInt();
                int nameLen = inp.readLeShort();
                int extraLen = inp.readLeShort();
                int commentLen = inp.readLeShort();
                inp.skip(8);
                int offset = inp.readLeInt();
                String _name = inp.readString(nameLen);

                ZipEntry entry = new ZipEntry(_name);
                entry.setMethod(method);
                entry.setCrc(crc & 0xffffffffL);
                entry.setSize(size & 0xffffffffL);
                entry.setCompressedSize(csize & 0xffffffffL);
                entry.setDOSTime(dostime);
                if (extraLen > 0)
                {
                    byte[] extra = new byte[extraLen];
                    inp.readFully(extra);
                    entry.setExtra(extra);
                }
                if (commentLen > 0)
                {
                    entry.setComment(inp.readString(commentLen));
                }
                entry.offset = offset;
                entries[_name] = entry;
            }
        }
Esempio n. 10
0
        public Packet ReadPacket()
        {
            int hdr = this.ReadByte();

            if (hdr < 0)
            {
                return(null);
            }

            if ((hdr & 0x80) == 0)
            {
                throw new IOException("invalid header encountered");
            }

            bool      newPacket = (hdr & 0x40) != 0;
            PacketTag tag       = 0;
            int       bodyLen   = 0;
            bool      partial   = false;

            if (newPacket)
            {
                tag = (PacketTag)(hdr & 0x3f);

                int l = this.ReadByte();

                if (l < 192)
                {
                    bodyLen = l;
                }
                else if (l <= 223)
                {
                    int b = m_in.ReadByte();
                    bodyLen = ((l - 192) << 8) + (b) + 192;
                }
                else if (l == 255)
                {
                    bodyLen = (m_in.ReadByte() << 24) | (m_in.ReadByte() << 16)
                              | (m_in.ReadByte() << 8) | m_in.ReadByte();
                }
                else
                {
                    partial = true;
                    bodyLen = 1 << (l & 0x1f);
                }
            }
            else
            {
                int lengthType = hdr & 0x3;

                tag = (PacketTag)((hdr & 0x3f) >> 2);

                switch (lengthType)
                {
                case 0:
                    bodyLen = this.ReadByte();
                    break;

                case 1:
                    bodyLen = (this.ReadByte() << 8) | this.ReadByte();
                    break;

                case 2:
                    bodyLen = (this.ReadByte() << 24) | (this.ReadByte() << 16)
                              | (this.ReadByte() << 8) | this.ReadByte();
                    break;

                case 3:
                    partial = true;
                    break;

                default:
                    throw new IOException("unknown length type encountered");
                }
            }

            BcpgInputStream objStream;

            if (bodyLen == 0 && partial)
            {
                objStream = this;
            }
            else
            {
                PartialInputStream pis = new PartialInputStream(this, partial, bodyLen);
                objStream = new BcpgInputStream(pis);
            }

            switch (tag)
            {
            case PacketTag.Reserved:
                return(new InputStreamPacket(objStream));

            case PacketTag.PublicKeyEncryptedSession:
                return(new PublicKeyEncSessionPacket(objStream));

            case PacketTag.Signature:
                return(new SignaturePacket(objStream));

            case PacketTag.SymmetricKeyEncryptedSessionKey:
                return(new SymmetricKeyEncSessionPacket(objStream));

            case PacketTag.OnePassSignature:
                return(new OnePassSignaturePacket(objStream));

            case PacketTag.SecretKey:
                return(new SecretKeyPacket(objStream));

            case PacketTag.PublicKey:
                return(new PublicKeyPacket(objStream));

            case PacketTag.SecretSubkey:
                return(new SecretSubkeyPacket(objStream));

            case PacketTag.CompressedData:
                return(new CompressedDataPacket(objStream));

            case PacketTag.SymmetricKeyEncrypted:
                return(new SymmetricEncDataPacket(objStream));

            case PacketTag.Marker:
                return(new MarkerPacket(objStream));

            case PacketTag.LiteralData:
                return(new LiteralDataPacket(objStream));

            case PacketTag.Trust:
                return(new TrustPacket(objStream));

            case PacketTag.UserId:
                return(new UserIdPacket(objStream));

            case PacketTag.UserAttribute:
                return(new UserAttributePacket(objStream));

            case PacketTag.PublicSubkey:
                return(new PublicSubkeyPacket(objStream));

            case PacketTag.SymmetricEncryptedIntegrityProtected:
                return(new SymmetricEncIntegrityPacket(objStream));

            case PacketTag.ModificationDetectionCode:
                return(new ModDetectionCodePacket(objStream));

            case PacketTag.Experimental1:
            case PacketTag.Experimental2:
            case PacketTag.Experimental3:
            case PacketTag.Experimental4:
                return(new ExperimentalPacket(tag, objStream));

            default:
                throw new IOException("unknown packet type encountered: " + tag);
            }
        }
Esempio n. 11
0
		/// <summary>
		/// Creates an input stream reading a zip entry
		/// </summary>
		/// <param name="entryIndex">The index of the entry to obtain an input stream for.</param>
		/// <returns>
		/// An input stream.
		/// </returns>
		/// <exception cref="InvalidOperationException">
		/// The ZipFile has already been closed
		/// </exception>
		/// <exception cref="_videoConference.ZipUnzip.Zip.ZipException">
		/// The compression method for the entry is unknown
		/// </exception>
		/// <exception cref="IndexOutOfRangeException">
		/// The entry is not found in the ZipFile
		/// </exception>
		public Stream GetInputStream(long entryIndex)
		{
			if ( entries_ == null ) {
				throw new InvalidOperationException("ZipFile is not open");
			}
			
			long start = LocateEntry(entries_[entryIndex]);
			CompressionMethod method = entries_[entryIndex].CompressionMethod;
			Stream result = new PartialInputStream(baseStream_, start, entries_[entryIndex].CompressedSize);

			if (entries_[entryIndex].IsCrypted == true) {
				result = CreateAndInitDecryptionStream(result, entries_[entryIndex]);
				if (result == null) {
					throw new ZipException("Unable to decrypt this entry");
				}
			}

			switch (method) {
				case CompressionMethod.Stored:
					// read as is.
					break;

				case CompressionMethod.Deflated:
					// No need to worry about ownership and closing as underlying stream close does nothing.
					result = new InflaterInputStream(result, new Inflater(true));
					break;

				default:
					throw new ZipException("Unsupported compression method " + method);
			}

			return result;
		}
Esempio n. 12
0
        /// <summary>
        /// Get a Stream for reading the specified entry
        /// </summary>
        /// <param name="entry"></param>
        /// <returns></returns>
        public Stream GetInputStream(ZipEntry entry)
        {
            if(entry.Size == 0)
                return null;

            if (entries == null)
            {
                throw new InvalidOperationException("ZipFile has closed");
            }

            int index = (int)entry.ZipFileIndex;
            if (index < 0 || index >= entries.Length || entries[index].Name != entry.Name)
            {
                throw new IndexOutOfRangeException();
            }

            // WARNING
            // should parse the Local Header to get the data address
            // Maximum Size of the Local Header is ... 16+64K*2
            //
            // So the HTTP request should ask for the big local header, but actually the
            // additional data is not downloaded.
            // Optionally use an additional Request to be really precise
            HttpWebRequest req = (HttpWebRequest)WebRequest.Create(baseUrl);

            int limit = (int)(entry.Offset+entry.CompressedSize+16+65536*2);
            if(limit >= MaxFileOffset)
                limit = MaxFileOffset-1;
            req.AddRange((int)entry.Offset, limit);
            HttpWebResponse res = (HttpWebResponse)req.GetResponse();
            Stream baseStream = res.GetResponseStream();

            // skips all the header
            SkipLocalHeader(baseStream, entries[index]);
            CompressionMethod method = entries[index].CompressionMethod;

            Stream istr = new PartialInputStream(baseStream, res, entries[index].CompressedSize);
            switch (method)
            {
                case CompressionMethod.Stored:
                    return istr;
                case CompressionMethod.Deflated:
                    return new InflaterInputStream(istr, new Inflater(true));
                case (CompressionMethod)12:
                    return new BZip2InputStream(istr);
                default:
                    throw new ZipException("Unknown compression method " + method);
            }
        }
Esempio n. 13
0
        /// <summary>
        /// Creates an input stream reading a Hfs entry
        /// </summary>
        /// <param name="entryIndex">The index of the entry to obtain an input stream for.</param>
        /// <returns>
        /// An input <see cref="Stream"/> containing data for this <paramref name="entryIndex"/>
        /// </returns>
        /// <exception cref="ObjectDisposedException">
        /// The HfsFile has already been closed
        /// </exception>
        /// <exception cref="ICSharpCode.SharpZipLib.Hfs.HfsException">
        /// The compression method for the entry is unknown
        /// </exception>
        /// <exception cref="IndexOutOfRangeException">
        /// The entry is not found in the HfsFile
        /// </exception>
        public Stream GetInputStream(long entryIndex)
        {
            if (isDisposed_)
            {
                throw new ObjectDisposedException("HfsFile");
            }

            HfsEntry entry = entries_[entryIndex];
            long start = LocateEntry(entry);
            CompressionMethod method = entries_[entryIndex].CompressionMethod;
            Stream result = new PartialInputStream(this, start, entries_[entryIndex].CompressedSize);

            switch (method)
            {
                case CompressionMethod.Stored:
                    {
                        Stream base_result = result = new HFSXorStream(result, start, HfsXorCipher.XorTruths, true);

                        if (obfuscationkey_ > 0)
                        {
                            result = new HFSXorStream(result, start, bytekey_, true);
                        }

                        if (entry.Name.Substring(entry.Name.Length - 5) == ".comp")
                        {
                            UInt32 decomp;

                            // technically we don't decompress this, but we will to make it easier (.comp is transparently handled in this lib)
                            byte[] compHeader = new byte[8];
                            result.Read(compHeader, 0, compHeader.Length);

                            if (!HfsXorCipher.ValidateCompSig(compHeader, out decomp))
                            {
                                if (obfuscationkey_ == 0)
                                {
                                    throw new Exception("No obfs key, bad signature");
                                }

                                base_result.Seek(-8, SeekOrigin.Current);
                                base_result.Read(compHeader, 0, compHeader.Length);

                                key = HfsXorCipher.BruteforceInnerKey(compHeader, (int)start);
                                HfsXorCipher.XorBlockWithKey(compHeader, key, (int)start);

                                if (!HfsXorCipher.ValidateCompSig(compHeader, out decomp))
                                {
                                    throw new Exception("Bad compression signature");
                                }

                                Console.WriteLine("Had to brute-force inner XOR key");

                                bytekey_ = key;
                                obfuscationkey_ = BitConverter.ToUInt32(bytekey_, 0);

                                result = new HFSXorStream(base_result, start, key, true);
                            }

                            entry.Size = decomp;

                            // to ease copying the stream straight to the zip we wrap it with the correct length
                            result = new WrapperStream(new InflaterInputStream(result), entry.Size);
                        }
                    }
                    break;

                default:
                    throw new HfsException("Unsupported compression method " + method);
            }

            return result;
        }
Esempio n. 14
0
        /// <summary>
        /// Reads the ZipEntry of a file, which has no zip entry.
        /// </summary>
        /// <param name="entryIndex">The index of the preceeding zip entry.</param>
        /// <returns>
        /// An input stream.
        /// </returns>
        /// <exception cref="InvalidOperationException">
        /// The ZipFile has already been closed
        /// </exception>
        /// <exception cref="DMSys.Cryptography.Zip.ZipException">
        /// The compression method for the entry is unknown
        /// </exception>
        /// <exception cref="IndexOutOfRangeException">
        /// The entry is not found in the ZipFile
        /// </exception>
        public ZipEntry GetAttachedEntry(ZipEntry predecessor)
        {
            if (entries == null)
            {
                throw new InvalidOperationException("ZipFile is closed");
            }

            //beginning of the preceeding zip entry
            long startPredecessor = CheckLocalHeader(predecessor);

            //end of the preceeding zip entry
            long endPredecessor = startPredecessor + predecessor.CompressedSize;

            //get a stream for the undocumented local file
            Stream stream = new PartialInputStream(baseStream, endPredecessor, ZipConstants.LOCHDR);

            //read local file header

            int localHeaderStart = ReadLeInt(stream);

            if (localHeaderStart != ZipConstants.LOCSIG)
            {
                throw new InvalidOperationException("Invalid local file header");
            }

            int version          = ReadLeShort(stream);
            int flags            = ReadLeShort(stream);
            int method           = ReadLeShort(stream);
            int dosTime          = ReadLeInt(stream);
            int crc              = ReadLeInt(stream);
            int compressedSize   = ReadLeInt(stream);
            int uncompressedSize = ReadLeInt(stream);
            int nameLength       = ReadLeShort(stream);
            int extraLength      = ReadLeShort(stream);

            //get a stream only for file name
            long   offset         = endPredecessor + ZipConstants.LOCHDR;
            Stream fileInfoStream = new PartialInputStream(baseStream, offset, nameLength);

            byte[] buffer = new byte[nameLength];
            fileInfoStream.Read(buffer, 0, nameLength);
            string name = ZipConstants.ConvertToString(buffer);

            int      indexFromDirectoy = FindEntry(name, false);
            ZipEntry zipEntry;

            if (indexFromDirectoy < 0)
            {
                zipEntry = new ZipEntry(name, version);
                zipEntry.CompressedSize    = compressedSize;
                zipEntry.CompressionMethod = (CompressionMethod)method;
                zipEntry.Crc          = crc;
                zipEntry.DosTime      = dosTime;
                zipEntry.Flags        = flags;
                zipEntry.IsVisible    = false;
                zipEntry.Offset       = (int)endPredecessor;
                zipEntry.Size         = uncompressedSize;
                zipEntry.IsVisible    = false;
                zipEntry.ZipFileIndex = -1;
            }
            else
            {
                zipEntry           = entries[indexFromDirectoy];
                zipEntry.IsVisible = true;
            }

            return(zipEntry);
        }
Esempio n. 15
0
        /**
         * Creates an input stream reading the given zip entry as
         * uncompressed data.  Normally zip entry should be an entry
         * returned by getEntry() or entries().
         *
         * This implementation returns null if the requested entry does not
         * exist.  This decision is not obviously correct, however, it does
         * appear to mirror Sun's implementation, and it is consistant with
         * their javadoc.  On the other hand, the old JCL book, 2nd Edition,
         * claims that this should return a "non-null ZIP entry".  We have
         * chosen for now ignore the old book, as modern versions of Ant (an
         * important application) depend on this behaviour.  See discussion
         * in this thread:
         * http://gcc.gnu.org/ml/java-patches/2004-q2/msg00602.html
         *
         * @param entry the entry to create an InputStream for.
         * @return the input stream, or null if the requested entry does not exist.
         *
         * @exception IllegalStateException when the ZipFile has already been closed
         * @exception IOException if a i/o error occured.
         * @exception ZipException if the Zip archive is malformed.  
         */
        public Stream getInputStream(ZipEntry entry)
        {
            checkClosed();

            Dictionary<String, ZipEntry> entries = getEntries();
            String name = entry.getName();
            ZipEntry zipEntry = entries[name];
            if (zipEntry == null)
                return null;

            PartialInputStream inp = new PartialInputStream(raf, 1024);
            inp.seek(zipEntry.offset);

            if (inp.readLeInt() != LOCSIG)
                throw new System.Exception("Wrong Local header signature: " + name);

            inp.skip(4);

            if (zipEntry.getMethod() != inp.readLeShort())
                throw new System.Exception("Compression method mismatch: " + name);

            inp.skip(16);

            int nameLen = inp.readLeShort();
            int extraLen = inp.readLeShort();
            inp.skip(nameLen + extraLen);

            inp.setLength(zipEntry.getCompressedSize());

            int method = zipEntry.getMethod();
            switch (method)
            {
                case ZipOutputStream.STORED:
                    return inp;
                case ZipOutputStream.DEFLATED:
                    inp.addDummyByte();
                    return new System.IO.Compression.DeflateStream(inp, System.IO.Compression.CompressionMode.Decompress);
//                    Inflater inf = new Inflater(true);
                    //int sz = (int)entry.getSize();
                //return new InflateStream(sz,inp,inf);
                //return new InflaterInputStream(inp, inf)
                //{
                //  public int available() 
                //  {
                //    if (sz == -1)
                //      return super.available();
                //    if (super.available() != 0)
                //      return sz - inf.getTotalOut();
                //    return 0;
                //  }
                //};
                default:
                throw new System.Exception("Unknown compression method " + method);
            }
        }
Esempio n. 16
0
    /// <summary>
    ///   Creates an input stream reading a zip entry
    /// </summary>
    /// <param name="entryIndex">The index of the entry to obtain an input stream for.</param>
    /// <returns>
    ///   An input <see cref="Stream" /> containing data for this <paramref name="entryIndex" />
    /// </returns>
    /// <exception cref="ObjectDisposedException">
    ///   The ZipFile has already been closed
    /// </exception>
    /// <exception cref="ZipException">
    ///   The compression method for the entry is unknown
    /// </exception>
    /// <exception cref="IndexOutOfRangeException">
    ///   The entry is not found in the ZipFile
    /// </exception>
    public Stream GetInputStream(long entryIndex)
    {
      if (isDisposed_)
      {
        throw new ObjectDisposedException("ZipFile");
      }

      var start = LocateEntry(entries_[entryIndex]);
      var method = entries_[entryIndex].CompressionMethod;
      Stream result = new PartialInputStream(this, start, entries_[entryIndex].CompressedSize);

      switch (method)
      {
        case CompressionMethod.Stored:
          // read as is.
          break;

        case CompressionMethod.Deflated:
          // No need to worry about ownership and closing as underlying stream close does nothing.
          result = new InflaterInputStream(result, new Inflater(true));
          break;

        default:
          throw new ZipException("Unsupported compression method " + method);
      }

      return result;
    }
Esempio n. 17
0
        /// <summary>
        /// Creates an input stream reading the given zip entry as
        /// uncompressed data.  Normally zip entry should be an entry
        /// returned by GetEntry().
        /// </summary>
        /// <returns>
        /// the input stream.
        /// </returns>
        /// <exception name="System.IO.IOException">
        /// if a i/o error occured.
        /// </exception>
        /// <exception name="Tools.FileCompressionUtilities.ZipException">
        /// if the Zip archive is malformed.
        /// </exception>
        public Stream GetInputStream(ZipEntry entry)
        {
            if (entries == null) {
                throw new InvalidOperationException("ZipFile has closed");
            }

            int index = entry.ZipFileIndex;
            if (index < 0 || index >= entries.Length || entries[index].Name != entry.Name) {
                index = GetEntryIndex(entry.Name);
                if (index < 0) {
                    throw new IndexOutOfRangeException();
                }
            }

            long start = CheckLocalHeader(entries[index]);
            CompressionMethod method = entries[index].CompressionMethod;
            Stream istr = new PartialInputStream(baseStream, start, entries[index].CompressedSize);
            switch (method) {
                case CompressionMethod.Stored:
                    return istr;
                case CompressionMethod.Deflated:
                    return new InflaterInputStream(istr, new Inflater(true));
                default:
                    throw new ZipException("Unknown compression method " + method);
            }
        }
Esempio n. 18
0
 public Stream GetInputStream(ZipEntry entry)
 {
     if (this.entries == null)
     {
         throw new InvalidOperationException("ZipFile has closed");
     }
     int zipFileIndex = entry.zipFileIndex;
     if (((zipFileIndex < 0) || (zipFileIndex >= this.entries.Length)) || (this.entries[zipFileIndex].Name != entry.Name))
     {
         zipFileIndex = this.GetEntryIndex(entry.Name);
         if (zipFileIndex < 0)
         {
             throw new IndexOutOfRangeException();
         }
     }
     long start = this.CheckLocalHeader(this.entries[zipFileIndex]);
     CompressionMethod compressionMethod = this.entries[zipFileIndex].CompressionMethod;
     Stream baseInputStream = new PartialInputStream(this.baseStream, start, this.entries[zipFileIndex].CompressedSize);
     CompressionMethod method2 = compressionMethod;
     if (method2 != CompressionMethod.Stored)
     {
         if (method2 != CompressionMethod.Deflated)
         {
             throw new ZipException("Unknown compression method " + compressionMethod);
         }
     }
     else
     {
         return baseInputStream;
     }
     return new InflaterInputStream(baseInputStream, new Inflater(true));
 }
Esempio n. 19
0
        public Stream GetInputStream(long entryIndex)
        {
            if (isDisposed_)
            {
                throw new ObjectDisposedException("ZipFile");
            }
            long start = LocateEntry(entries_[(int)((IntPtr)entryIndex)]);
            CompressionMethod compressionMethod = entries_[(int)((IntPtr)entryIndex)].CompressionMethod;
            Stream baseStream = new PartialInputStream(this, start, entries_[(int)((IntPtr)entryIndex)].CompressedSize);
            if (entries_[(int)((IntPtr)entryIndex)].IsCrypted)
            {
                baseStream = CreateAndInitDecryptionStream(baseStream, entries_[(int)((IntPtr)entryIndex)]);
                if (baseStream == null)
                {
                    throw new ZipException("Unable to decrypt this entry");
                }
            }
            switch (compressionMethod)
            {
                case CompressionMethod.Stored:
                    return baseStream;

                case CompressionMethod.Deflated:
                    return new InflaterInputStream(baseStream, new Inflater(true));
            }
            throw new ZipException("Unsupported compression method " + compressionMethod);
        }
        public Packet ReadPacket()
        {
            int hdr = this.ReadByte();

            if (hdr < 0)
            {
                return null;
            }

            if ((hdr & 0x80) == 0)
            {
                throw new IOException("invalid header encountered");
            }

            bool newPacket = (hdr & 0x40) != 0;
            PacketTag tag = 0;
            int bodyLen = 0;
            bool partial = false;

            if (newPacket)
            {
                tag = (PacketTag)(hdr & 0x3f);

                int l = this.ReadByte();

                if (l < 192)
                {
                    bodyLen = l;
                }
                else if (l <= 223)
                {
                    int b = m_in.ReadByte();
                    bodyLen = ((l - 192) << 8) + (b) + 192;
                }
                else if (l == 255)
                {
                    bodyLen = (m_in.ReadByte() << 24) | (m_in.ReadByte() << 16)
                        |  (m_in.ReadByte() << 8)  | m_in.ReadByte();
                }
                else
                {
                    partial = true;
                    bodyLen = 1 << (l & 0x1f);
                }
            }
            else
            {
                int lengthType = hdr & 0x3;

                tag = (PacketTag)((hdr & 0x3f) >> 2);

                switch (lengthType)
                {
                    case 0:
                        bodyLen = this.ReadByte();
                        break;
                    case 1:
                        bodyLen = (this.ReadByte() << 8) | this.ReadByte();
                        break;
                    case 2:
                        bodyLen = (this.ReadByte() << 24) | (this.ReadByte() << 16)
                            | (this.ReadByte() << 8) | this.ReadByte();
                        break;
                    case 3:
                        partial = true;
                        break;
                    default:
                        throw new IOException("unknown length type encountered");
                }
            }

            BcpgInputStream objStream;
            if (bodyLen == 0 && partial)
            {
                objStream = this;
            }
            else
            {
                PartialInputStream pis = new PartialInputStream(this, partial, bodyLen);
                objStream = new BcpgInputStream(pis);
            }

            switch (tag)
            {
                case PacketTag.Reserved:
                    return new InputStreamPacket(objStream);
                case PacketTag.PublicKeyEncryptedSession:
                    return new PublicKeyEncSessionPacket(objStream);
                case PacketTag.Signature:
                    return new SignaturePacket(objStream);
                case PacketTag.SymmetricKeyEncryptedSessionKey:
                    return new SymmetricKeyEncSessionPacket(objStream);
                case PacketTag.OnePassSignature:
                    return new OnePassSignaturePacket(objStream);
                case PacketTag.SecretKey:
                    return new SecretKeyPacket(objStream);
                case PacketTag.PublicKey:
                    return new PublicKeyPacket(objStream);
                case PacketTag.SecretSubkey:
                    return new SecretSubkeyPacket(objStream);
                case PacketTag.CompressedData:
                    return new CompressedDataPacket(objStream);
                case PacketTag.SymmetricKeyEncrypted:
                    return new SymmetricEncDataPacket(objStream);
                case PacketTag.Marker:
                    return new MarkerPacket(objStream);
                case PacketTag.LiteralData:
                    return new LiteralDataPacket(objStream);
                case PacketTag.Trust:
                    return new TrustPacket(objStream);
                case PacketTag.UserId:
                    return new UserIdPacket(objStream);
                case PacketTag.UserAttribute:
                    return new UserAttributePacket(objStream);
                case PacketTag.PublicSubkey:
                    return new PublicSubkeyPacket(objStream);
                case PacketTag.SymmetricEncryptedIntegrityProtected:
                    return new SymmetricEncIntegrityPacket(objStream);
                case PacketTag.ModificationDetectionCode:
                    return new ModDetectionCodePacket(objStream);
                case PacketTag.Experimental1:
                case PacketTag.Experimental2:
                case PacketTag.Experimental3:
                case PacketTag.Experimental4:
                    return new ExperimentalPacket(tag, objStream);
                default:
                    throw new IOException("unknown packet type encountered: " + tag);
            }
        }
    public Packet ReadPacket()
    {
        int num = ReadByte();

        if (num < 0)
        {
            return(null);
        }
        if ((num & 0x80) == 0)
        {
            throw new IOException("invalid header encountered");
        }
        bool      flag      = (num & 0x40) != 0;
        PacketTag packetTag = PacketTag.Reserved;
        int       num2      = 0;
        bool      flag2     = false;

        if (flag)
        {
            packetTag = (PacketTag)(num & 0x3F);
            int num3 = ReadByte();
            if (num3 < 192)
            {
                num2 = num3;
            }
            else if (num3 <= 223)
            {
                int num4 = m_in.ReadByte();
                num2 = (num3 - 192 << 8) + num4 + 192;
            }
            else if (num3 == 255)
            {
                num2 = ((m_in.ReadByte() << 24) | (m_in.ReadByte() << 16) | (m_in.ReadByte() << 8) | m_in.ReadByte());
            }
            else
            {
                flag2 = true;
                num2  = 1 << (num3 & 0x1F);
            }
        }
        else
        {
            int num5 = num & 3;
            packetTag = (PacketTag)((num & 0x3F) >> 2);
            switch (num5)
            {
            case 0:
                num2 = ReadByte();
                break;

            case 1:
                num2 = ((ReadByte() << 8) | ReadByte());
                break;

            case 2:
                num2 = ((ReadByte() << 24) | (ReadByte() << 16) | (ReadByte() << 8) | ReadByte());
                break;

            case 3:
                flag2 = true;
                break;

            default:
                throw new IOException("unknown length type encountered");
            }
        }
        BcpgInputStream bcpgIn;

        if (num2 == 0 && flag2)
        {
            bcpgIn = this;
        }
        else
        {
            PartialInputStream inputStream = new PartialInputStream(this, flag2, num2);
            bcpgIn = new BcpgInputStream(inputStream);
        }
        switch (packetTag)
        {
        case PacketTag.Reserved:
            return(new InputStreamPacket(bcpgIn));

        case PacketTag.PublicKeyEncryptedSession:
            return(new PublicKeyEncSessionPacket(bcpgIn));

        case PacketTag.Signature:
            return(new SignaturePacket(bcpgIn));

        case PacketTag.SymmetricKeyEncryptedSessionKey:
            return(new SymmetricKeyEncSessionPacket(bcpgIn));

        case PacketTag.OnePassSignature:
            return(new OnePassSignaturePacket(bcpgIn));

        case PacketTag.SecretKey:
            return(new SecretKeyPacket(bcpgIn));

        case PacketTag.PublicKey:
            return(new PublicKeyPacket(bcpgIn));

        case PacketTag.SecretSubkey:
            return(new SecretSubkeyPacket(bcpgIn));

        case PacketTag.CompressedData:
            return(new CompressedDataPacket(bcpgIn));

        case PacketTag.SymmetricKeyEncrypted:
            return(new SymmetricEncDataPacket(bcpgIn));

        case PacketTag.Marker:
            return(new MarkerPacket(bcpgIn));

        case PacketTag.LiteralData:
            return(new LiteralDataPacket(bcpgIn));

        case PacketTag.Trust:
            return(new TrustPacket(bcpgIn));

        case PacketTag.UserId:
            return(new UserIdPacket(bcpgIn));

        case PacketTag.UserAttribute:
            return(new UserAttributePacket(bcpgIn));

        case PacketTag.PublicSubkey:
            return(new PublicSubkeyPacket(bcpgIn));

        case PacketTag.SymmetricEncryptedIntegrityProtected:
            return(new SymmetricEncIntegrityPacket(bcpgIn));

        case PacketTag.ModificationDetectionCode:
            return(new ModDetectionCodePacket(bcpgIn));

        case PacketTag.Experimental1:
        case PacketTag.Experimental2:
        case PacketTag.Experimental3:
        case PacketTag.Experimental4:
            return(new ExperimentalPacket(packetTag, bcpgIn));

        default:
            throw new IOException("unknown packet type encountered: " + packetTag);
        }
    }
Esempio n. 22
0
		/// <summary>
		/// Creates an input stream reading a zip entry
		/// </summary>
		/// <param name="entryIndex">The index of the entry to obtain an input stream for.</param>
		/// <returns>
		/// An input <see cref="Stream"/> containing data for this <paramref name="entryIndex"/>
		/// </returns>
		/// <exception cref="ObjectDisposedException">
		/// The ZipFile has already been closed
		/// </exception>
		/// <exception cref="ICSharpCode.SharpZipLib.Zip.ZipException">
		/// The compression method for the entry is unknown
		/// </exception>
		/// <exception cref="IndexOutOfRangeException">
		/// The entry is not found in the ZipFile
		/// </exception>
		public Stream GetInputStream(long entryIndex)
		{
			if ( isDisposed_ ) {
				throw new ObjectDisposedException("ZipFile");
			}
			
			long start = LocateEntry(entries_[entryIndex]);
			CompressionMethod method = entries_[entryIndex].CompressionMethod;
			Stream result = new PartialInputStream(this, start, entries_[entryIndex].CompressedSize);

			if (entries_[entryIndex].IsCrypted == true) {
#if NETCF_1_0
				throw new ZipException("decryption not supported for Compact Framework 1.0");
#else
				result = CreateAndInitDecryptionStream(result, entries_[entryIndex]);
				if (result == null) {
					throw new ZipException("Unable to decrypt this entry");
				}
#endif				
			}

			switch (method) {
				case CompressionMethod.Stored:
					// read as is.
					break;

				case CompressionMethod.Deflated:
					// No need to worry about ownership and closing as underlying stream close does nothing.
					result = new InflaterInputStream(result, new Inflater(true));
					break;

				default:
					throw new ZipException("Unsupported compression method " + method);
			}

			return result;
		}
Esempio n. 23
0
        /// <summary>
        /// Creates an input stream reading the zip entry based on the index passed
        /// </summary>
        /// <returns>
        /// An input stream.
        /// </returns>
        /// <exception cref="InvalidOperationException">
        /// The ZipFile has already been closed
        /// </exception>
        /// <exception cref="ICSharpCode.SharpZipLib.ZipException">
        /// The compression method for the entry is unknown
        /// </exception>
        /// <exception cref="IndexOutOfRangeException">
        /// The entry is not found in the ZipFile
        /// </exception>
        public Stream GetInputStream(int entryIndex)
        {
            if (entries == null) {
                throw new InvalidOperationException("ZipFile has closed");
            }

            long start = CheckLocalHeader(entries[entryIndex]);
            CompressionMethod method = entries[entryIndex].CompressionMethod;
            Stream istr = new PartialInputStream(baseStream, start, entries[entryIndex].CompressedSize);

            switch (method) {
                case CompressionMethod.Stored:
                    return istr;
                case CompressionMethod.Deflated:
                    return new InflaterInputStream(istr, new Inflater(true));
                default:
                    throw new ZipException("Unknown compression method " + method);
            }
        }