Example #1
0
 public ZipEntry(ZipEntry entry)
 {
     externalFileAttributes = -1;
     method = CompressionMethod.Deflated;
     zipFileIndex = -1L;
     if (entry == null)
     {
         throw new ArgumentNullException("entry");
     }
     known = entry.known;
     name = entry.name;
     size = entry.size;
     compressedSize = entry.compressedSize;
     crc = entry.crc;
     dosTime = entry.dosTime;
     method = entry.method;
     comment = entry.comment;
     versionToExtract = entry.versionToExtract;
     versionMadeBy = entry.versionMadeBy;
     externalFileAttributes = entry.externalFileAttributes;
     flags = entry.flags;
     zipFileIndex = entry.zipFileIndex;
     offset = entry.offset;
     forceZip64_ = entry.forceZip64_;
     if (entry.extra != null)
     {
         extra = new byte[entry.extra.Length];
         Array.Copy(entry.extra, 0, extra, 0, entry.extra.Length);
     }
 }
Example #2
0
 public void Compress(string sourceFilename, string targetFilename, FileMode fileMode, OutArchiveFormat archiveFormat,
     CompressionMethod compressionMethod, CompressionLevel compressionLevel, ZipEncryptionMethod zipEncryptionMethod,
     string password, int bufferSize, int preallocationPercent, bool check, Dictionary<string, string> customParameters)
 {
     bufferSize *= this._sectorSize;
     SevenZipCompressor compressor = new SevenZipCompressor();
     compressor.FastCompression = true;
     compressor.ArchiveFormat = archiveFormat;
     compressor.CompressionMethod = compressionMethod;
     compressor.CompressionLevel = compressionLevel;
     compressor.DefaultItemName = Path.GetFileName(sourceFilename);
     compressor.DirectoryStructure = false;
     compressor.ZipEncryptionMethod = zipEncryptionMethod;
     foreach (var pair in customParameters)
     {
         compressor.CustomParameters[pair.Key] = pair.Value;
     }
     using (FileStream sourceFileStream = new FileStream(sourceFilename,
         FileMode.Open, FileAccess.Read, FileShare.None, bufferSize,
         Win32.FileFlagNoBuffering | FileOptions.SequentialScan))
     {
         using (FileStream targetFileStream = new FileStream(targetFilename,
                fileMode, FileAccess.ReadWrite, FileShare.ReadWrite, 8,
                FileOptions.WriteThrough | Win32.FileFlagNoBuffering))
         {
             this.Compress(compressor, sourceFileStream, targetFileStream,
                 password, preallocationPercent, check, bufferSize);
         }
     }
 }
Example #3
0
 public ZipEntry(ZipEntry entry)
 {
     _externalFileAttributes = -1;
     _method = CompressionMethod.Deflated;
     ZipFileIndex = -1L;
     if (entry == null)
     {
         throw new ArgumentNullException(nameof(entry));
     }
     _known = entry._known;
     Name = entry.Name;
     _size = entry._size;
     _compressedSize = entry._compressedSize;
     _crc = entry._crc;
     _dosTime = entry._dosTime;
     _method = entry._method;
     _comment = entry._comment;
     _versionToExtract = entry._versionToExtract;
     _versionMadeBy = entry._versionMadeBy;
     _externalFileAttributes = entry._externalFileAttributes;
     Flags = entry.Flags;
     ZipFileIndex = entry.ZipFileIndex;
     Offset = entry.Offset;
     _forceZip64 = entry._forceZip64;
     if (entry._extra != null)
     {
         _extra = new byte[entry._extra.Length];
         Array.Copy(entry._extra, 0, _extra, 0, entry._extra.Length);
     }
 }
Example #4
0
        public CsvFile(Stream stream, DataFileMode fileMode, CompressionMethod compression, Encoding encoding, CultureInfo culture)
            : base(stream, fileMode, compression, encoding, culture)
        {
            InitializeMembers();

            Open();
        }
Example #5
0
		public RuntimeInfo(CompressionMethod method, int compressionLevel, 
            int size, string password, bool getCrc)
		{
			this.method = method;
			this.compressionLevel = compressionLevel;
			this.password = password;
			this.size = size;
			this.random = false;

			original = new byte[Size];
			if (random) {
				System.Random rnd = new Random();
				rnd.NextBytes(original);
			}
			else {
				for (int i = 0; i < size; ++i) {
					original[i] = (byte)'A';
				}
			}

			if (getCrc) {
				Crc32 crc32 = new Crc32();
				crc32.Update(original, 0, size);
				crc = crc32.Value;
			}
		}
Example #6
0
        protected FormattedDataFile(Stream stream, DataFileMode fileMode, CompressionMethod compression, Encoding encoding, CultureInfo culture)
            : base(stream, fileMode, compression)
        {
            InitializeMembers();

            this.encoding = encoding;
            this.culture = culture;
        }
Example #7
0
 public ServerHello(ProtocolVersion ver, byte[] random, byte[] sessionID, CipherSuite suite, CompressionMethod compression, Extension[] extensions)
     : base(HandshakeType.ServerHello)
 {
     _version = ver;
     _random = random;
     _sessionID = sessionID;
     _cipherSuite = suite;
     _compression = compression;
     _extensions = extensions;
 }
Example #8
0
 /// <summary>
 ///   Is the given compression method/algrithm supported?
 /// </summary>
 /// <param name="method"> </param>
 /// <returns> </returns>
 public bool SupportsMethod(CompressionMethod method)
 {
     ElementList nList = SelectElements(typeof (Method));
     foreach (Method m in nList)
     {
         if (m.CompressionMethod == method)
             return true;
     }
     return false;
 }
Example #9
0
        public Ihdr(UInt32 width, UInt32 height, BitDepth bitDepth, ColorType colorType, CompressionMethod compressionMethod = CompressionMethod.Default, FilterMethod filterMethod = FilterMethod.Default, InterlaceMethod interlaceMethod = InterlaceMethod.None)
            : base(ChunkType.IHDR)
        {
            #region Sanity
            if(width == 0 || width > Int32.MaxValue)
                throw new ArgumentOutOfRangeException("width", "width must be greater than 0 and smaller than In32.MaxValue(2^31-1)");
            if(height == 0 || height > Int32.MaxValue)
                throw new ArgumentOutOfRangeException("height", "height must be greater than 0 and smaller than In32.MaxValue(2^31-1)");

            BitDepth[] allowedBitDepths;
            switch (colorType)
                {
                case ColorType.Grayscale:
                    if(!(allowedBitDepths = new[] { BitDepth._1, BitDepth._2, BitDepth._4, BitDepth._8, BitDepth._16 }).Contains(bitDepth))
                        throw new ArgumentOutOfRangeException("bitDepth", String.Format("bitDepth must be one of {0} for colorType {1}", allowedBitDepths.Aggregate("", (s, bd) => s + bd + ", ", s => s.Trim().Substring(0, s.Length - 2)), colorType));
                    break;
                case ColorType.Rgb:
                    if(!(allowedBitDepths = new[]{BitDepth._8, BitDepth._16}).Contains(bitDepth))
                        throw new ArgumentOutOfRangeException("bitDepth", String.Format("bitDepth must be one of {0} for colorType {1}", allowedBitDepths.Aggregate("", (s, bd) => s + bd + ", ", s => s.Trim().Substring(0, s.Length - 2)), colorType));
                    break;
                case ColorType.Palette:
                    if(!(allowedBitDepths = new[] { BitDepth._1, BitDepth._2, BitDepth._4, BitDepth._8}).Contains(bitDepth))
                        throw new ArgumentOutOfRangeException("bitDepth", String.Format("bitDepth must be one of {0} for colorType {1}", allowedBitDepths.Aggregate("", (s, bd) => s + bd + ", ", s => s.Trim().Substring(0, s.Length - 2)), colorType));
                    break;
                case ColorType.GrayscaleWithAlpha:
                    if(!(allowedBitDepths = new[] { BitDepth._8, BitDepth._16}).Contains(bitDepth))
                        throw new ArgumentOutOfRangeException("bitDepth", String.Format("bitDepth must be one of {0} for colorType {1}", allowedBitDepths.Aggregate("", (s, bd) => s + bd + ", ", s => s.Trim().Substring(0, s.Length - 2)), colorType));
                    break;
                case ColorType.Rgba:
                    if(!(allowedBitDepths = new[] { BitDepth._8, BitDepth._16}).Contains(bitDepth))
                        throw new ArgumentOutOfRangeException("bitDepth", String.Format("bitDepth must be one of {0} for colorType {1}", allowedBitDepths.Aggregate("", (s, bd) => s + bd + ", ", s => s.Trim().Substring(0, s.Length - 2)), colorType));
                    break;
                default:
                    throw new ArgumentOutOfRangeException("colorType", String.Format("Unknown colorType: {0}", colorType));
                }

            if(compressionMethod != CompressionMethod.Default)
                throw new ArgumentOutOfRangeException("compressionMethod", String.Format("Unknown compressionMethod: {0}", compressionMethod));
            if(filterMethod != FilterMethod.Default)
                throw new ArgumentOutOfRangeException("filterMethod", String.Format("Unknown filterMethod: {0}", filterMethod));

            var allowedInterlaceMethods = new[] {InterlaceMethod.None, InterlaceMethod.Adam7};
            if(!allowedInterlaceMethods.Contains(interlaceMethod))
                throw new ArgumentOutOfRangeException("interlaceMethod", String.Format("interlaceMethod must be one of {0}", allowedInterlaceMethods.Aggregate("", (s, bd) => s + bd + ", ", s => s.Trim().Substring(0, s.Length - 2))));

            #endregion

            Width = width;
            Height = height;
            BitDepth = bitDepth;
            ColorType = colorType;
            CompressionMethod = compressionMethod;
            FilterMethod = filterMethod;
            InterlaceMethod = interlaceMethod;
        }
Example #10
0
        public ClientHelloMessage(TlsVersion version, byte[] randomBytes, byte[] sessionId, HelloExtension[] extensions, CipherSuite[] cipherSuites, CompressionMethod[] compressionMethods)
            : base(HandshakeType.ClientHello, version, randomBytes, sessionId, extensions)
        {
            SecurityAssert.NotNull(cipherSuites);
            SecurityAssert.SAssert(cipherSuites.Length >= 2 && cipherSuites.Length <= 0xFFFE);
            CipherSuites = cipherSuites;

            SecurityAssert.NotNull(compressionMethods);
            SecurityAssert.SAssert(compressionMethods.Length >= 1 && cipherSuites.Length <= 0xFF);
            CompressionMethods = compressionMethods;
        }
Example #11
0
 public ZipOutputStream(Stream baseOutputStream, int bufferSize) : base(baseOutputStream, new Deflater(-1, true), bufferSize)
 {
     this.entries = new ArrayList();
     this.crc = new Crc32();
     this.defaultCompressionLevel = -1;
     this.curMethod = CompressionMethod.Deflated;
     this.zipComment = new byte[0];
     this.crcPatchPos = -1L;
     this.sizePatchPos = -1L;
     this.useZip64_ = ICSharpCode.SharpZipLib.Zip.UseZip64.Dynamic;
 }
Example #12
0
 public ZipOutputStream(Stream baseOutputStream, int bufferSize)
     : base(baseOutputStream, new Deflater(-1, true), bufferSize)
 {
     _entries = new ArrayList();
     _crc = new Crc32();
     _defaultCompressionLevel = -1;
     _curMethod = CompressionMethod.Deflated;
     _zipComment = new byte[0];
     _crcPatchPos = -1L;
     _sizePatchPos = -1L;
     _useZip64 = UseZip64.Dynamic;
 }
Example #13
0
 public ZipOutputStream(Stream baseOutputStream)
     : base(baseOutputStream, new Deflater(-1, true))
 {
     entries = new ArrayList();
     crc = new Crc32();
     defaultCompressionLevel = -1;
     curMethod = CompressionMethod.Deflated;
     zipComment = new byte[0];
     crcPatchPos = -1L;
     sizePatchPos = -1L;
     useZip64_ = UseZip64.Dynamic;
 }
Example #14
0
        protected byte[] MakeInMemoryZip(ref byte[] original, CompressionMethod method,
                                         int compressionLevel, int size, string password, bool withSeek)
        {
            MemoryStream ms;

            if (withSeek)
            {
                ms = new MemoryStream();
            }
            else
            {
                ms = new MemoryStreamWithoutSeek();
            }

            using (ZipOutputStream outStream = new ZipOutputStream(ms))
            {
                outStream.Password = password;

                if (method != CompressionMethod.Stored)
                {
                    outStream.SetLevel(compressionLevel); // 0 - store only to 9 - means best compression
                }

                ZipEntry entry = new ZipEntry("dummyfile.tst");
                entry.CompressionMethod = method;

                outStream.PutNextEntry(entry);

                if (size > 0)
                {
                    System.Random rnd = new Random();
                    original = new byte[size];
                    rnd.NextBytes(original);

                    // Although this could be written in one chunk doing it in lumps
                    // throws up buffering problems including with encryption the original
                    // source for this change.
                    int index = 0;
                    while (size > 0)
                    {
                        int count = (size > 0x200) ? 0x200 : size;
                        outStream.Write(original, index, count);
                        size -= 0x200;
                        index += count;
                    }
                }
            }
            return ms.ToArray();
        }
Example #15
0
        /// <summary>
        /// Returns the file extension by stripping of the extension of the
        /// compressed file, if any.
        /// </summary>
        public static void GetExtensionWithoutCompression(Uri uri, out string path, out string extension, out CompressionMethod compressionMethod)
        {
            path = GetPathFromUri(uri);
            extension = Path.GetExtension(path);

            if (Constants.CompressionExtensions.ContainsKey(extension))
            {
                compressionMethod = Constants.CompressionExtensions[extension];
                path = Path.GetFileNameWithoutExtension(path);
                extension = Path.GetExtension(path);
            }
            else
            {
                compressionMethod = CompressionMethod.None;
            }
        }
Example #16
0
        public FileFormatDescription GetFileFormatDescription(Uri uri, out string path, out string extension, out CompressionMethod compression)
        {
            GetExtensionWithoutCompression(uri, out path, out extension, out compression);

            // FInd file format with the appropriate extensions
            FileFormatDescription format = null;
            foreach (var f in GetFileFormatDescriptions())
            {
                if (StringComparer.InvariantCultureIgnoreCase.Compare(extension, f.Value.DefaultExtension) == 0)
                {
                    format = f.Value;
                    break;
                }
            }

            return format;
        }
        /// <summary>
        /// Initializes a new instance of the <see cref="CompressionServerChannelSinkProvider"/> class.
        /// </summary>
        /// <param name="properties">Compression sink properties.</param>
        /// <param name="providerData">The provider data (ignored).</param>
        public CompressionServerChannelSinkProvider(IDictionary properties, ICollection providerData)
        {
            // read in web.config parameters
            foreach (DictionaryEntry entry in properties)
            {
                switch ((string)entry.Key)
                {
                    case "compressionThreshold":
                        _compressionThreshold = Convert.ToInt32((string)entry.Value);
                        break;

                    case "compressionMethod":
                        _compressionMethod = (CompressionMethod)Enum.Parse(typeof(CompressionMethod), (string)entry.Value);
                        break;

                    default:
                        throw new ArgumentException("Invalid configuration entry: " + (string)entry.Key);
                }
            }
        }
Example #18
0
        public static byte[] CompressBytes(byte[] data,
            CompressionLevel CompressionLevel,
            CompressionMethod CompressionMethod = CompressionMethod.Default
            )
        {
            Inits.EnsureBinaries();

            using (var inStream = new MemoryStream(data))
            {
                using (var outStream = new MemoryStream())
                {
                    var compressor = new SevenZipCompressor();
                    compressor.CompressionLevel = (SevenZip.CompressionLevel)(int)CompressionLevel;
                    compressor.CompressionMethod = (SevenZip.CompressionMethod)(int)CompressionMethod;
                    compressor.ScanOnlyWritable = true;
                    compressor.CompressStream(inStream, outStream);

                    return outStream.ToArray();
                }
            }
        }
Example #19
0
 internal ZipEntry(string name, int versionRequiredToExtract, int madeByInfo = 0x33, 
     CompressionMethod method = CompressionMethod.Deflated)
 {
     externalFileAttributes = -1;
     this.method = CompressionMethod.Deflated;
     zipFileIndex = -1L;
     if (name == null)
     {
         throw new ArgumentNullException("name");
     }
     if (name.Length > 0xffff)
     {
         throw new ArgumentException("Name is too long", "name");
     }
     if ((versionRequiredToExtract != 0) && (versionRequiredToExtract < 10))
     {
         throw new ArgumentOutOfRangeException("versionRequiredToExtract");
     }
     DateTime = DateTime.Now;
     this.name = name;
     versionMadeBy = (ushort)madeByInfo;
     versionToExtract = (ushort)versionRequiredToExtract;
     this.method = method;
 }
Example #20
0
 /// <summary>
 /// Test a <see cref="CompressionMethod">compression method</see> to see if this library
 /// supports extracting data compressed with that method
 /// </summary>
 /// <param name="method">The compression method to test.</param>
 /// <returns>Returns true if the compression method is supported; false otherwise</returns>
 public static bool IsCompressionMethodSupported(CompressionMethod method)
 {
     return
         (method == CompressionMethod.Deflated) ||
         (method == CompressionMethod.Stored);
 }
Example #21
0
			public ZipUpdate(IStaticDataSource dataSource, string entryName, CompressionMethod compressionMethod)
			{
				command_ = UpdateCommand.Add;
				entry_ = new ZipEntry(entryName);
				entry_.CompressionMethod = compressionMethod;
				dataSource_ = dataSource;
			}
Example #22
0
			public ZipUpdate(string fileName, string entryName, CompressionMethod compressionMethod)
			{
				command_ = UpdateCommand.Add;
				entry_ = new ZipEntry(entryName);
				entry_.CompressionMethod = compressionMethod;
				filename_ = fileName;
			}
Example #23
0
		/// <summary>
		/// Add a file entry with data.
		/// </summary>
		/// <param name="dataSource">The source of the data for this entry.</param>
		/// <param name="entryName">The name to give to the entry.</param>
		/// <param name="compressionMethod">The compression method to use.</param>
		/// <param name="useUnicodeText">Ensure Unicode text is used for name and comments for this entry.</param>
		public void Add(IStaticDataSource dataSource, string entryName, CompressionMethod compressionMethod, bool useUnicodeText)
		{
			if (dataSource == null) {
				throw new ArgumentNullException("dataSource");
			}

			if ( entryName == null ) {
				throw new ArgumentNullException("entryName");
			}

			CheckUpdating();

			ZipEntry entry = EntryFactory.MakeFileEntry(entryName, false);
			entry.IsUnicodeText = useUnicodeText;
			entry.CompressionMethod = compressionMethod;

			AddUpdate(new ZipUpdate(dataSource, entry));
		}
Example #24
0
		/// <summary>
		/// Add a new entry to the archive.
		/// </summary>
		/// <param name="fileName">The name of the file to add.</param>
		/// <param name="compressionMethod">The compression method to use.</param>
		/// <exception cref="ArgumentNullException">ZipFile has been closed.</exception>
		/// <exception cref="ArgumentOutOfRangeException">The compression method is not supported.</exception>
		public void Add(string fileName, CompressionMethod compressionMethod)
		{
			if ( fileName == null ) {
				throw new ArgumentNullException("fileName");
			}

			if ( !ZipEntry.IsCompressionMethodSupported(compressionMethod) ) {
				throw new ArgumentOutOfRangeException("compressionMethod");
			}

			CheckUpdating();
			contentsEdited_ = true;

			ZipEntry entry = EntryFactory.MakeFileEntry(fileName);
			entry.CompressionMethod = compressionMethod;
			AddUpdate(new ZipUpdate(fileName, entry));
		}
 private static bool ArrayContains(CompressionMethod[] a, CompressionMethod n)
 {
     for (int i = 0; i < a.Length; ++i)
     {
         if (a[i] == n)
             return true;
     }
     return false;
 }
Example #26
0
		/// <summary>
		/// Starts a new Zip entry. It automatically closes the previous
		/// entry if present.  If the compression method is stored, the entry
		/// must have a valid size and crc, otherwise all elements (except
		/// name) are optional, but must be correct if present.  If the time
		/// is not set in the entry, the current time is used.
		/// </summary>
		/// <param name="entry">
		/// the entry.
		/// </param>
		/// <exception cref="System.IO.IOException">
		/// if an I/O error occured.
		/// </exception>
		/// <exception cref="System.InvalidOperationException">
		/// if stream was finished
		/// </exception>
		public void PutNextEntry(ZipEntry entry)
		{
			if (entries == null) {
				throw new InvalidOperationException("ZipOutputStream was finished");
			}
			
			CompressionMethod method = entry.CompressionMethod;
			int flags = 0;
			
			switch (method) {
				case CompressionMethod.Stored:
					if (entry.CompressedSize >= 0) {
						if (entry.Size < 0) {
							entry.Size = entry.CompressedSize;
						} else if (entry.Size != entry.CompressedSize) {
							throw new ZipException("Method STORED, but compressed size != size");
						}
					} else {
						entry.CompressedSize = entry.Size;
					}
					
					if (entry.Size < 0) {
						throw new ZipException("Method STORED, but size not set");
					} else if (entry.Crc < 0) {
						throw new ZipException("Method STORED, but crc not set");
					}
					break;
				case CompressionMethod.Deflated:
					if (entry.CompressedSize < 0 || entry.Size < 0 || entry.Crc < 0) {
						flags |= 8;
					}
					break;
			}
			
			if (curEntry != null) {
				CloseEntry();
			}
			
			//			if (entry.DosTime < 0) {
			//				entry.Time = System.Environment.TickCount;
			//			}
			
			entry.flags  = flags;
			entry.offset = offset;
			entry.CompressionMethod = (CompressionMethod)method;
			
			curMethod    = method;
			// Write the local file header
			WriteLeInt(ZipConstants.LOCSIG);
			
			// write ZIP version
			WriteLeShort(method == CompressionMethod.Stored ? ZIP_STORED_VERSION : ZIP_DEFLATED_VERSION);
			if ((flags & 8) == 0) {
				WriteLeShort(flags);
				WriteLeShort((byte)method);
				WriteLeInt((int)entry.DosTime);
				WriteLeInt((int)entry.Crc);
				WriteLeInt((int)entry.CompressedSize);
				WriteLeInt((int)entry.Size);
			} else {
				if (baseOutputStream.CanSeek) {
					shouldWriteBack = true;
					WriteLeShort((short)(flags & ~8));
				} else {
					shouldWriteBack = false;
					WriteLeShort(flags);
				}
				WriteLeShort((byte)method);
				WriteLeInt((int)entry.DosTime);
				seekPos = baseOutputStream.Position;
				WriteLeInt(0);
				WriteLeInt(0);
				WriteLeInt(0);
			}
			byte[] name = ZipConstants.ConvertToArray(entry.Name);
			
			if (name.Length > 0xFFFF) {
				throw new ZipException("Name too long.");
			}
			byte[] extra = entry.ExtraData;
			if (extra == null) {
				extra = new byte[0];
			}
			if (extra.Length > 0xFFFF) {
				throw new ZipException("Extra data too long.");
			}
			
			WriteLeShort(name.Length);
			WriteLeShort(extra.Length);
			baseOutputStream.Write(name, 0, name.Length);
			baseOutputStream.Write(extra, 0, extra.Length);
			
			offset += ZipConstants.LOCHDR + name.Length + extra.Length;
			
			/* Activate the entry. */
			curEntry = entry;
			crc.Reset();
			if (method == CompressionMethod.Deflated) {
				def.Reset();
			}
			size = 0;
		}
Example #27
0
        /// <summary>
        /// Starts a new Zip entry. It automatically closes the previous
        /// entry if present.
        /// All entry elements bar name are optional, but must be correct if present.
        /// If the compression method is stored and the output is not patchable
        /// the compression for that entry is automatically changed to deflate level 0
        /// </summary>
        /// <param name="entry">
        /// the entry.
        /// </param>
        /// <exception cref="System.ArgumentNullException">
        /// if entry passed is null.
        /// </exception>
        /// <exception cref="System.IO.IOException">
        /// if an I/O error occured.
        /// </exception>
        /// <exception cref="System.InvalidOperationException">
        /// if stream was finished
        /// </exception>
        /// <exception cref="ZipException">
        /// Too many entries in the Zip file<br/>
        /// Entry name is too long<br/>
        /// Finish has already been called<br/>
        /// </exception>
        public void PutNextEntry(ZipEntry entry)
        {
            if ( entry == null ) {
                throw new ArgumentNullException("entry");
            }

            if (entries == null) {
                throw new InvalidOperationException("ZipOutputStream was finished");
            }

            if (curEntry != null) {
                CloseEntry();
            }

            if (entries.Count == int.MaxValue) {
                throw new ZipException("Too many entries for Zip file");
            }

            CompressionMethod method = entry.CompressionMethod;
            int compressionLevel = defaultCompressionLevel;

            // Clear flags that the library manages internally
            entry.Flags &= (int)GeneralBitFlags.UnicodeText;
            patchEntryHeader = false;

            bool headerInfoAvailable;

            // No need to compress - definitely no data.
            if (entry.Size == 0)
            {
                entry.CompressedSize = entry.Size;
                entry.Crc = 0;
                method = CompressionMethod.Stored;
                headerInfoAvailable = true;
            }
            else
            {
                headerInfoAvailable = (entry.Size >= 0) && entry.HasCrc;

                // Switch to deflation if storing isnt possible.
                if (method == CompressionMethod.Stored)
                {
                    if (!headerInfoAvailable)
                    {
                        if (!CanPatchEntries)
                        {
                            // Can't patch entries so storing is not possible.
                            method = CompressionMethod.Deflated;
                            compressionLevel = 0;
                        }
                    }
                    else // entry.size must be > 0
                    {
                        entry.CompressedSize = entry.Size;
                        headerInfoAvailable = entry.HasCrc;
                    }
                }
            }

            if (headerInfoAvailable == false) {
                if (CanPatchEntries == false) {
                    // Only way to record size and compressed size is to append a data descriptor
                    // after compressed data.

                    // Stored entries of this form have already been converted to deflating.
                    entry.Flags |= 8;
                } else {
                    patchEntryHeader = true;
                }
            }

            if (Password != null) {
                entry.IsCrypted = true;
                if (entry.Crc < 0) {
                    // Need to append a data descriptor as the crc isnt available for use
                    // with encryption, the date is used instead.  Setting the flag
                    // indicates this to the decompressor.
                    entry.Flags |= 8;
                }
            }

            entry.Offset = offset;
            entry.CompressionMethod = (CompressionMethod)method;

            curMethod = method;
            sizePatchPos = -1;

            if ( (useZip64_ == UseZip64.On) || ((entry.Size < 0) && (useZip64_ == UseZip64.Dynamic)) ) {
                entry.ForceZip64();
            }

            // Write the local file header
            WriteLeInt(ZipConstants.LocalHeaderSignature);

            WriteLeShort(entry.Version);
            WriteLeShort(entry.Flags);
            WriteLeShort((byte)method);
            WriteLeInt((int)entry.DosTime);

            // TODO: Refactor header writing.  Its done in several places.
            if (headerInfoAvailable == true) {
                WriteLeInt((int)entry.Crc);
                if ( entry.LocalHeaderRequiresZip64 ) {
                    WriteLeInt(-1);
                    WriteLeInt(-1);
                }
                else {
                    WriteLeInt(entry.IsCrypted ? (int)entry.CompressedSize + ZipConstants.CryptoHeaderSize : (int)entry.CompressedSize);
                    WriteLeInt((int)entry.Size);
                }
            } else {
                if (patchEntryHeader == true) {
                    crcPatchPos = baseOutputStream_.Position;
                }
                WriteLeInt(0);	// Crc

                if ( patchEntryHeader ) {
                    sizePatchPos = baseOutputStream_.Position;
                }

                // For local header both sizes appear in Zip64 Extended Information
                if ( entry.LocalHeaderRequiresZip64 || patchEntryHeader ) {
                    WriteLeInt(-1);
                    WriteLeInt(-1);
                }
                else {
                    WriteLeInt(0);	// Compressed size
                    WriteLeInt(0);	// Uncompressed size
                }
            }

            byte[] name = ZipConstants.ConvertToArray(entry.Flags, entry.Name);

            if (name.Length > 0xFFFF) {
                throw new ZipException("Entry name too long.");
            }

            ZipExtraData ed = new ZipExtraData(entry.ExtraData);

            if (entry.LocalHeaderRequiresZip64) {
                ed.StartNewEntry();
                if (headerInfoAvailable) {
                    ed.AddLeLong(entry.Size);
                    ed.AddLeLong(entry.CompressedSize);
                }
                else {
                    ed.AddLeLong(-1);
                    ed.AddLeLong(-1);
                }
                ed.AddNewEntry(1);

                if ( !ed.Find(1) ) {
                    throw new ZipException("Internal error cant find extra data");
                }

                if ( patchEntryHeader ) {
                    sizePatchPos = ed.CurrentReadIndex;
                }
            }
            else {
                ed.Delete(1);
            }

            byte[] extra = ed.GetEntryData();

            WriteLeShort(name.Length);
            WriteLeShort(extra.Length);

            if ( name.Length > 0 ) {
                baseOutputStream_.Write(name, 0, name.Length);
            }

            if ( entry.LocalHeaderRequiresZip64 && patchEntryHeader ) {
                sizePatchPos += baseOutputStream_.Position;
            }

            if ( extra.Length > 0 ) {
                baseOutputStream_.Write(extra, 0, extra.Length);
            }

            offset += ZipConstants.LocalHeaderBaseSize + name.Length + extra.Length;

            // Activate the entry.
            curEntry = entry;
            crc.Reset();
            if (method == CompressionMethod.Deflated) {
                deflater_.Reset();
                deflater_.SetLevel(compressionLevel);
            }
            size = 0;

            if (entry.IsCrypted == true) {
                if (entry.Crc < 0) {			// so testing Zip will says its ok
                    WriteEncryptionHeader(entry.DosTime << 16);
                } else {
                    WriteEncryptionHeader(entry.Crc);
                }
            }
        }
Example #28
0
 /// <summary>
 ///   Add a compression method/algorithm
 /// </summary>
 /// <param name="method"> </param>
 public void AddMethod(CompressionMethod method)
 {
     if (!SupportsMethod(method))
         AddChild(new Method(method));
 }
Example #29
0
 // For AES the method in the entry is 99, and the real compression method is in the extradata
 //
 private void ProcessAESExtraData(ZipExtraData extraData)
 {
     if (extraData.Find(0x9901)) {
         // Set version and flag for Zipfile.CreateAndInitDecryptionStream
         versionToExtract = ZipConstants.VERSION_AES;            // Ver 5.1 = AES see "Version" getter
                                                                 // Set StrongEncryption flag for ZipFile.CreateAndInitDecryptionStream
         Flags = Flags | (int)GeneralBitFlags.StrongEncryption;
         //
         // Unpack AES extra data field see http://www.winzip.com/aes_info.htm
         int length = extraData.ValueLength;         // Data size currently 7
         if (length < 7)
             throw new ZipException("AES Extra Data Length " + length + " invalid.");
         int ver = extraData.ReadShort();            // Version number (1=AE-1 2=AE-2)
         int vendorId = extraData.ReadShort();       // 2-character vendor ID 0x4541 = "AE"
         int encrStrength = extraData.ReadByte();    // encryption strength 1 = 128 2 = 192 3 = 256
         int actualCompress = extraData.ReadShort(); // The actual compression method used to compress the file
         _aesVer = ver;
         _aesEncryptionStrength = encrStrength;
         method = (CompressionMethod)actualCompress;
     } else
         throw new ZipException("AES Extra Data missing");
 }
Example #30
0
        /// <summary>
        /// Initializes an entry with the given name and made by information
        /// </summary>
        /// <param name="name">Name for this entry</param>
        /// <param name="madeByInfo">Version and HostSystem Information</param>
        /// <param name="versionRequiredToExtract">Minimum required zip feature version required to extract this entry</param>
        /// <param name="method">Compression method for this entry.</param>
        /// <exception cref="ArgumentNullException">
        /// The name passed is null
        /// </exception>
        /// <exception cref="ArgumentOutOfRangeException">
        /// versionRequiredToExtract should be 0 (auto-calculate) or > 10
        /// </exception>
        /// <remarks>
        /// This constructor is used by the ZipFile class when reading from the central header
        /// It is not generally useful, use the constructor specifying the name only.
        /// </remarks>
        internal ZipEntry(string name, int versionRequiredToExtract, int madeByInfo,
			CompressionMethod method)
        {
            if (name == null) {
                throw new ArgumentNullException(nameof(name));
            }

            if (name.Length > 0xffff) {
                throw new ArgumentException("Name is too long", nameof(name));
            }

            if ((versionRequiredToExtract != 0) && (versionRequiredToExtract < 10)) {
                throw new ArgumentOutOfRangeException(nameof(versionRequiredToExtract));
            }

            this.DateTime = DateTime.Now;
            this.name = CleanName(name);
            this.versionMadeBy = (ushort)madeByInfo;
            this.versionToExtract = (ushort)versionRequiredToExtract;
            this.method = method;
        }
Example #31
0
 /// <summary>
 /// Test a <see cref="CompressionMethod">compression method</see> to see if this library
 /// supports extracting data compressed with that method
 /// </summary>
 /// <param name="method">The compression method to test.</param>
 /// <returns>Returns true if the compression method is supported; false otherwise</returns>
 public static bool IsCompressionMethodSupported(CompressionMethod method)
 {
     return
         ((method == CompressionMethod.Deflated) ||
          (method == CompressionMethod.Stored));
 }