You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

900 lines
26 KiB

  1. // ZipOutputStream.cs
  2. //
  3. // Copyright (C) 2001 Mike Krueger
  4. // Copyright (C) 2004 John Reilly
  5. //
  6. // This file was translated from java, it was part of the GNU Classpath
  7. // Copyright (C) 2001 Free Software Foundation, Inc.
  8. //
  9. // This program is free software; you can redistribute it and/or
  10. // modify it under the terms of the GNU General Public License
  11. // as published by the Free Software Foundation; either version 2
  12. // of the License, or (at your option) any later version.
  13. //
  14. // This program is distributed in the hope that it will be useful,
  15. // but WITHOUT ANY WARRANTY; without even the implied warranty of
  16. // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  17. // GNU General Public License for more details.
  18. //
  19. // You should have received a copy of the GNU General Public License
  20. // along with this program; if not, write to the Free Software
  21. // Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
  22. //
  23. // Linking this library statically or dynamically with other modules is
  24. // making a combined work based on this library. Thus, the terms and
  25. // conditions of the GNU General Public License cover the whole
  26. // combination.
  27. //
  28. // As a special exception, the copyright holders of this library give you
  29. // permission to link this library with independent modules to produce an
  30. // executable, regardless of the license terms of these independent
  31. // modules, and to copy and distribute the resulting executable under
  32. // terms of your choice, provided that you also meet, for each linked
  33. // independent module, the terms and conditions of the license of that
  34. // module. An independent module is a module which is not derived from
  35. // or based on this library. If you modify this library, you may extend
  36. // this exception to your version of the library, but you are not
  37. // obligated to do so. If you do not wish to do so, delete this
  38. // exception statement from your version.
  39. // HISTORY
  40. // 22-12-2009 Z-1649 Added AES support
  41. // 22-02-2010 Z-1648 Zero byte entries would create invalid zip files
  42. using System;
  43. using System.IO;
  44. using System.Collections;
  45. using Externals.Compression.Checksums;
  46. using Externals.Compression.Zip.Compression;
  47. using Externals.Compression.Zip.Compression.Streams;
  48. namespace Externals.Compression.Zip
  49. {
  50. /// <summary>
  51. /// This is a DeflaterOutputStream that writes the files into a zip
  52. /// archive one after another. It has a special method to start a new
  53. /// zip entry. The zip entries contains information about the file name
  54. /// size, compressed size, CRC, etc.
  55. ///
  56. /// It includes support for Stored and Deflated entries.
  57. /// This class is not thread safe.
  58. /// <br/>
  59. /// <br/>Author of the original java version : Jochen Hoenicke
  60. /// </summary>
  61. /// <example> This sample shows how to create a zip file
  62. /// <code>
  63. /// using System;
  64. /// using System.IO;
  65. ///
  66. /// using Externals.Compression.Core;
  67. /// using Externals.Compression.Zip;
  68. ///
  69. /// class MainClass
  70. /// {
  71. /// public static void Main(string[] args)
  72. /// {
  73. /// string[] filenames = Directory.GetFiles(args[0]);
  74. /// byte[] buffer = new byte[4096];
  75. ///
  76. /// using ( ZipOutputStream s = new ZipOutputStream(File.Create(args[1])) ) {
  77. ///
  78. /// s.SetLevel(9); // 0 - store only to 9 - means best compression
  79. ///
  80. /// foreach (string file in filenames) {
  81. /// ZipEntry entry = new ZipEntry(file);
  82. /// s.PutNextEntry(entry);
  83. ///
  84. /// using (FileStream fs = File.OpenRead(file)) {
  85. /// StreamUtils.Copy(fs, s, buffer);
  86. /// }
  87. /// }
  88. /// }
  89. /// }
  90. /// }
  91. /// </code>
  92. /// </example>
  93. internal class ZipOutputStream : DeflaterOutputStream
  94. {
  95. #region Constructors
  96. /// <summary>
  97. /// Creates a new Zip output stream, writing a zip archive.
  98. /// </summary>
  99. /// <param name="baseOutputStream">
  100. /// The output stream to which the archive contents are written.
  101. /// </param>
  102. public ZipOutputStream(Stream baseOutputStream)
  103. : base(baseOutputStream, new Deflater(Deflater.DEFAULT_COMPRESSION, true))
  104. {
  105. }
  106. /// <summary>
  107. /// Creates a new Zip output stream, writing a zip archive.
  108. /// </summary>
  109. /// <param name="baseOutputStream">The output stream to which the archive contents are written.</param>
  110. /// <param name="bufferSize">Size of the buffer to use.</param>
  111. public ZipOutputStream( Stream baseOutputStream, int bufferSize )
  112. : base(baseOutputStream, new Deflater(Deflater.DEFAULT_COMPRESSION, true), bufferSize)
  113. {
  114. }
  115. #endregion
  116. /// <summary>
  117. /// Gets a flag value of true if the central header has been added for this archive; false if it has not been added.
  118. /// </summary>
  119. /// <remarks>No further entries can be added once this has been done.</remarks>
  120. public bool IsFinished
  121. {
  122. get {
  123. return entries == null;
  124. }
  125. }
  126. /// <summary>
  127. /// Set the zip file comment.
  128. /// </summary>
  129. /// <param name="comment">
  130. /// The comment text for the entire archive.
  131. /// </param>
  132. /// <exception name ="ArgumentOutOfRangeException">
  133. /// The converted comment is longer than 0xffff bytes.
  134. /// </exception>
  135. public void SetComment(string comment)
  136. {
  137. // TODO: Its not yet clear how to handle unicode comments here.
  138. byte[] commentBytes = ZipConstants.ConvertToArray(comment);
  139. if (commentBytes.Length > 0xffff) {
  140. throw new ArgumentOutOfRangeException("comment");
  141. }
  142. zipComment = commentBytes;
  143. }
  144. /// <summary>
  145. /// Sets the compression level. The new level will be activated
  146. /// immediately.
  147. /// </summary>
  148. /// <param name="level">The new compression level (1 to 9).</param>
  149. /// <exception cref="ArgumentOutOfRangeException">
  150. /// Level specified is not supported.
  151. /// </exception>
  152. /// <see cref="Externals.Compression.Zip.Compression.Deflater"/>
  153. public void SetLevel(int level)
  154. {
  155. deflater_.SetLevel(level);
  156. defaultCompressionLevel = level;
  157. }
  158. /// <summary>
  159. /// Get the current deflater compression level
  160. /// </summary>
  161. /// <returns>The current compression level</returns>
  162. public int GetLevel()
  163. {
  164. return deflater_.GetLevel();
  165. }
  166. /// <summary>
  167. /// Get / set a value indicating how Zip64 Extension usage is determined when adding entries.
  168. /// </summary>
  169. /// <remarks>Older archivers may not understand Zip64 extensions.
  170. /// If backwards compatability is an issue be careful when adding <see cref="ZipEntry.Size">entries</see> to an archive.
  171. /// Setting this property to off is workable but less desirable as in those circumstances adding a file
  172. /// larger then 4GB will fail.</remarks>
  173. public UseZip64 UseZip64
  174. {
  175. get { return useZip64_; }
  176. set { useZip64_ = value; }
  177. }
  178. /// <summary>
  179. /// Write an unsigned short in little endian byte order.
  180. /// </summary>
  181. private void WriteLeShort(int value)
  182. {
  183. unchecked {
  184. baseOutputStream_.WriteByte((byte)(value & 0xff));
  185. baseOutputStream_.WriteByte((byte)((value >> 8) & 0xff));
  186. }
  187. }
  188. /// <summary>
  189. /// Write an int in little endian byte order.
  190. /// </summary>
  191. private void WriteLeInt(int value)
  192. {
  193. unchecked {
  194. WriteLeShort(value);
  195. WriteLeShort(value >> 16);
  196. }
  197. }
  198. /// <summary>
  199. /// Write an int in little endian byte order.
  200. /// </summary>
  201. private void WriteLeLong(long value)
  202. {
  203. unchecked {
  204. WriteLeInt((int)value);
  205. WriteLeInt((int)(value >> 32));
  206. }
  207. }
  208. /// <summary>
  209. /// Starts a new Zip entry. It automatically closes the previous
  210. /// entry if present.
  211. /// All entry elements bar name are optional, but must be correct if present.
  212. /// If the compression method is stored and the output is not patchable
  213. /// the compression for that entry is automatically changed to deflate level 0
  214. /// </summary>
  215. /// <param name="entry">
  216. /// the entry.
  217. /// </param>
  218. /// <exception cref="System.ArgumentNullException">
  219. /// if entry passed is null.
  220. /// </exception>
  221. /// <exception cref="System.IO.IOException">
  222. /// if an I/O error occured.
  223. /// </exception>
  224. /// <exception cref="System.InvalidOperationException">
  225. /// if stream was finished
  226. /// </exception>
  227. /// <exception cref="ZipException">
  228. /// Too many entries in the Zip file<br/>
  229. /// Entry name is too long<br/>
  230. /// Finish has already been called<br/>
  231. /// </exception>
  232. public void PutNextEntry(ZipEntry entry)
  233. {
  234. if ( entry == null ) {
  235. throw new ArgumentNullException("entry");
  236. }
  237. if (entries == null) {
  238. throw new InvalidOperationException("ZipOutputStream was finished");
  239. }
  240. if (curEntry != null) {
  241. CloseEntry();
  242. }
  243. if (entries.Count == int.MaxValue) {
  244. throw new ZipException("Too many entries for Zip file");
  245. }
  246. CompressionMethod method = entry.CompressionMethod;
  247. int compressionLevel = defaultCompressionLevel;
  248. // Clear flags that the library manages internally
  249. entry.Flags &= (int)GeneralBitFlags.UnicodeText;
  250. patchEntryHeader = false;
  251. bool headerInfoAvailable;
  252. // No need to compress - definitely no data.
  253. if (entry.Size == 0)
  254. {
  255. entry.CompressedSize = entry.Size;
  256. entry.Crc = 0;
  257. method = CompressionMethod.Stored;
  258. headerInfoAvailable = true;
  259. }
  260. else
  261. {
  262. headerInfoAvailable = (entry.Size >= 0) && entry.HasCrc;
  263. // Switch to deflation if storing isnt possible.
  264. if (method == CompressionMethod.Stored)
  265. {
  266. if (!headerInfoAvailable)
  267. {
  268. if (!CanPatchEntries)
  269. {
  270. // Can't patch entries so storing is not possible.
  271. method = CompressionMethod.Deflated;
  272. compressionLevel = 0;
  273. }
  274. }
  275. else // entry.size must be > 0
  276. {
  277. entry.CompressedSize = entry.Size;
  278. headerInfoAvailable = entry.HasCrc;
  279. }
  280. }
  281. }
  282. if (headerInfoAvailable == false) {
  283. if (CanPatchEntries == false) {
  284. // Only way to record size and compressed size is to append a data descriptor
  285. // after compressed data.
  286. // Stored entries of this form have already been converted to deflating.
  287. entry.Flags |= 8;
  288. } else {
  289. patchEntryHeader = true;
  290. }
  291. }
  292. if (Password != null) {
  293. entry.IsCrypted = true;
  294. if (entry.Crc < 0) {
  295. // Need to append a data descriptor as the crc isnt available for use
  296. // with encryption, the date is used instead. Setting the flag
  297. // indicates this to the decompressor.
  298. entry.Flags |= 8;
  299. }
  300. }
  301. entry.Offset = offset;
  302. entry.CompressionMethod = (CompressionMethod)method;
  303. curMethod = method;
  304. sizePatchPos = -1;
  305. if ( (useZip64_ == UseZip64.On) || ((entry.Size < 0) && (useZip64_ == UseZip64.Dynamic)) ) {
  306. entry.ForceZip64();
  307. }
  308. // Write the local file header
  309. WriteLeInt(ZipConstants.LocalHeaderSignature);
  310. WriteLeShort(entry.Version);
  311. WriteLeShort(entry.Flags);
  312. WriteLeShort((byte)entry.CompressionMethodForHeader);
  313. WriteLeInt((int)entry.DosTime);
  314. // TODO: Refactor header writing. Its done in several places.
  315. if (headerInfoAvailable == true) {
  316. WriteLeInt((int)entry.Crc);
  317. if ( entry.LocalHeaderRequiresZip64 ) {
  318. WriteLeInt(-1);
  319. WriteLeInt(-1);
  320. }
  321. else {
  322. WriteLeInt(entry.IsCrypted ? (int)entry.CompressedSize + ZipConstants.CryptoHeaderSize : (int)entry.CompressedSize);
  323. WriteLeInt((int)entry.Size);
  324. }
  325. } else {
  326. if (patchEntryHeader) {
  327. crcPatchPos = baseOutputStream_.Position;
  328. }
  329. WriteLeInt(0); // Crc
  330. if ( patchEntryHeader ) {
  331. sizePatchPos = baseOutputStream_.Position;
  332. }
  333. // For local header both sizes appear in Zip64 Extended Information
  334. if ( entry.LocalHeaderRequiresZip64 || patchEntryHeader ) {
  335. WriteLeInt(-1);
  336. WriteLeInt(-1);
  337. }
  338. else {
  339. WriteLeInt(0); // Compressed size
  340. WriteLeInt(0); // Uncompressed size
  341. }
  342. }
  343. byte[] name = ZipConstants.ConvertToArray(entry.Flags, entry.Name);
  344. if (name.Length > 0xFFFF) {
  345. throw new ZipException("Entry name too long.");
  346. }
  347. ZipExtraData ed = new ZipExtraData(entry.ExtraData);
  348. if (entry.LocalHeaderRequiresZip64) {
  349. ed.StartNewEntry();
  350. if (headerInfoAvailable) {
  351. ed.AddLeLong(entry.Size);
  352. ed.AddLeLong(entry.CompressedSize);
  353. }
  354. else {
  355. ed.AddLeLong(-1);
  356. ed.AddLeLong(-1);
  357. }
  358. ed.AddNewEntry(1);
  359. if ( !ed.Find(1) ) {
  360. throw new ZipException("Internal error cant find extra data");
  361. }
  362. if ( patchEntryHeader ) {
  363. sizePatchPos = ed.CurrentReadIndex;
  364. }
  365. }
  366. else {
  367. ed.Delete(1);
  368. }
  369. #if !NET_1_1 && !NETCF_2_0
  370. if (entry.AESKeySize > 0) {
  371. AddExtraDataAES(entry, ed);
  372. }
  373. #endif
  374. byte[] extra = ed.GetEntryData();
  375. WriteLeShort(name.Length);
  376. WriteLeShort(extra.Length);
  377. if ( name.Length > 0 ) {
  378. baseOutputStream_.Write(name, 0, name.Length);
  379. }
  380. if ( entry.LocalHeaderRequiresZip64 && patchEntryHeader ) {
  381. sizePatchPos += baseOutputStream_.Position;
  382. }
  383. if ( extra.Length > 0 ) {
  384. baseOutputStream_.Write(extra, 0, extra.Length);
  385. }
  386. offset += ZipConstants.LocalHeaderBaseSize + name.Length + extra.Length;
  387. // Fix offsetOfCentraldir for AES
  388. if (entry.AESKeySize > 0)
  389. offset += entry.AESOverheadSize;
  390. // Activate the entry.
  391. curEntry = entry;
  392. crc.Reset();
  393. if (method == CompressionMethod.Deflated) {
  394. deflater_.Reset();
  395. deflater_.SetLevel(compressionLevel);
  396. }
  397. size = 0;
  398. if (entry.IsCrypted) {
  399. #if !NET_1_1 && !NETCF_2_0
  400. if (entry.AESKeySize > 0) {
  401. WriteAESHeader(entry);
  402. } else
  403. #endif
  404. {
  405. if (entry.Crc < 0) { // so testing Zip will says its ok
  406. WriteEncryptionHeader(entry.DosTime << 16);
  407. } else {
  408. WriteEncryptionHeader(entry.Crc);
  409. }
  410. }
  411. }
  412. }
  413. /// <summary>
  414. /// Closes the current entry, updating header and footer information as required
  415. /// </summary>
  416. /// <exception cref="System.IO.IOException">
  417. /// An I/O error occurs.
  418. /// </exception>
  419. /// <exception cref="System.InvalidOperationException">
  420. /// No entry is active.
  421. /// </exception>
  422. public void CloseEntry()
  423. {
  424. if (curEntry == null) {
  425. throw new InvalidOperationException("No open entry");
  426. }
  427. long csize = size;
  428. // First finish the deflater, if appropriate
  429. if (curMethod == CompressionMethod.Deflated) {
  430. if (size >= 0) {
  431. base.Finish();
  432. csize = deflater_.TotalOut;
  433. }
  434. else {
  435. deflater_.Reset();
  436. }
  437. }
  438. // Write the AES Authentication Code (a hash of the compressed and encrypted data)
  439. if (curEntry.AESKeySize > 0) {
  440. baseOutputStream_.Write(AESAuthCode, 0, 10);
  441. }
  442. if (curEntry.Size < 0) {
  443. curEntry.Size = size;
  444. } else if (curEntry.Size != size) {
  445. throw new ZipException("size was " + size + ", but I expected " + curEntry.Size);
  446. }
  447. if (curEntry.CompressedSize < 0) {
  448. curEntry.CompressedSize = csize;
  449. } else if (curEntry.CompressedSize != csize) {
  450. throw new ZipException("compressed size was " + csize + ", but I expected " + curEntry.CompressedSize);
  451. }
  452. if (curEntry.Crc < 0) {
  453. curEntry.Crc = crc.Value;
  454. } else if (curEntry.Crc != crc.Value) {
  455. throw new ZipException("crc was " + crc.Value + ", but I expected " + curEntry.Crc);
  456. }
  457. offset += csize;
  458. if (curEntry.IsCrypted) {
  459. if (curEntry.AESKeySize > 0) {
  460. curEntry.CompressedSize += curEntry.AESOverheadSize;
  461. } else {
  462. curEntry.CompressedSize += ZipConstants.CryptoHeaderSize;
  463. }
  464. }
  465. // Patch the header if possible
  466. if (patchEntryHeader) {
  467. patchEntryHeader = false;
  468. long curPos = baseOutputStream_.Position;
  469. baseOutputStream_.Seek(crcPatchPos, SeekOrigin.Begin);
  470. WriteLeInt((int)curEntry.Crc);
  471. if ( curEntry.LocalHeaderRequiresZip64 ) {
  472. if ( sizePatchPos == -1 ) {
  473. throw new ZipException("Entry requires zip64 but this has been turned off");
  474. }
  475. baseOutputStream_.Seek(sizePatchPos, SeekOrigin.Begin);
  476. WriteLeLong(curEntry.Size);
  477. WriteLeLong(curEntry.CompressedSize);
  478. }
  479. else {
  480. WriteLeInt((int)curEntry.CompressedSize);
  481. WriteLeInt((int)curEntry.Size);
  482. }
  483. baseOutputStream_.Seek(curPos, SeekOrigin.Begin);
  484. }
  485. // Add data descriptor if flagged as required
  486. if ((curEntry.Flags & 8) != 0) {
  487. WriteLeInt(ZipConstants.DataDescriptorSignature);
  488. WriteLeInt(unchecked((int)curEntry.Crc));
  489. if ( curEntry.LocalHeaderRequiresZip64 ) {
  490. WriteLeLong(curEntry.CompressedSize);
  491. WriteLeLong(curEntry.Size);
  492. offset += ZipConstants.Zip64DataDescriptorSize;
  493. }
  494. else {
  495. WriteLeInt((int)curEntry.CompressedSize);
  496. WriteLeInt((int)curEntry.Size);
  497. offset += ZipConstants.DataDescriptorSize;
  498. }
  499. }
  500. entries.Add(curEntry);
  501. curEntry = null;
  502. }
  503. void WriteEncryptionHeader(long crcValue)
  504. {
  505. offset += ZipConstants.CryptoHeaderSize;
  506. InitializePassword(Password);
  507. byte[] cryptBuffer = new byte[ZipConstants.CryptoHeaderSize];
  508. Random rnd = new Random();
  509. rnd.NextBytes(cryptBuffer);
  510. cryptBuffer[11] = (byte)(crcValue >> 24);
  511. EncryptBlock(cryptBuffer, 0, cryptBuffer.Length);
  512. baseOutputStream_.Write(cryptBuffer, 0, cryptBuffer.Length);
  513. }
  514. #if !NET_1_1 && !NETCF_2_0
  515. private static void AddExtraDataAES(ZipEntry entry, ZipExtraData extraData) {
  516. // Vendor Version: AE-1 IS 1. AE-2 is 2. With AE-2 no CRC is required and 0 is stored.
  517. const int VENDOR_VERSION = 2;
  518. // Vendor ID is the two ASCII characters "AE".
  519. const int VENDOR_ID = 0x4541; //not 6965;
  520. extraData.StartNewEntry();
  521. // Pack AES extra data field see http://www.winzip.com/aes_info.htm
  522. //extraData.AddLeShort(7); // Data size (currently 7)
  523. extraData.AddLeShort(VENDOR_VERSION); // 2 = AE-2
  524. extraData.AddLeShort(VENDOR_ID); // "AE"
  525. extraData.AddData(entry.AESEncryptionStrength); // 1 = 128, 2 = 192, 3 = 256
  526. extraData.AddLeShort((int)entry.CompressionMethod); // The actual compression method used to compress the file
  527. extraData.AddNewEntry(0x9901);
  528. }
  529. // Replaces WriteEncryptionHeader for AES
  530. //
  531. private void WriteAESHeader(ZipEntry entry) {
  532. byte[] salt;
  533. byte[] pwdVerifier;
  534. InitializeAESPassword(entry, Password, out salt, out pwdVerifier);
  535. // File format for AES:
  536. // Size (bytes) Content
  537. // ------------ -------
  538. // Variable Salt value
  539. // 2 Password verification value
  540. // Variable Encrypted file data
  541. // 10 Authentication code
  542. //
  543. // Value in the "compressed size" fields of the local file header and the central directory entry
  544. // is the total size of all the items listed above. In other words, it is the total size of the
  545. // salt value, password verification value, encrypted data, and authentication code.
  546. baseOutputStream_.Write(salt, 0, salt.Length);
  547. baseOutputStream_.Write(pwdVerifier, 0, pwdVerifier.Length);
  548. }
  549. #endif
  550. /// <summary>
  551. /// Writes the given buffer to the current entry.
  552. /// </summary>
  553. /// <param name="buffer">The buffer containing data to write.</param>
  554. /// <param name="offset">The offset of the first byte to write.</param>
  555. /// <param name="count">The number of bytes to write.</param>
  556. /// <exception cref="ZipException">Archive size is invalid</exception>
  557. /// <exception cref="System.InvalidOperationException">No entry is active.</exception>
  558. public override void Write(byte[] buffer, int offset, int count)
  559. {
  560. if (curEntry == null) {
  561. throw new InvalidOperationException("No open entry.");
  562. }
  563. if ( buffer == null ) {
  564. throw new ArgumentNullException("buffer");
  565. }
  566. if ( offset < 0 ) {
  567. #if NETCF_1_0
  568. throw new ArgumentOutOfRangeException("offset");
  569. #else
  570. throw new ArgumentOutOfRangeException("offset", "Cannot be negative");
  571. #endif
  572. }
  573. if ( count < 0 ) {
  574. #if NETCF_1_0
  575. throw new ArgumentOutOfRangeException("count");
  576. #else
  577. throw new ArgumentOutOfRangeException("count", "Cannot be negative");
  578. #endif
  579. }
  580. if ( (buffer.Length - offset) < count ) {
  581. throw new ArgumentException("Invalid offset/count combination");
  582. }
  583. crc.Update(buffer, offset, count);
  584. size += count;
  585. switch (curMethod) {
  586. case CompressionMethod.Deflated:
  587. base.Write(buffer, offset, count);
  588. break;
  589. case CompressionMethod.Stored:
  590. if (Password != null) {
  591. CopyAndEncrypt(buffer, offset, count);
  592. } else {
  593. baseOutputStream_.Write(buffer, offset, count);
  594. }
  595. break;
  596. }
  597. }
  598. void CopyAndEncrypt(byte[] buffer, int offset, int count)
  599. {
  600. const int CopyBufferSize = 4096;
  601. byte[] localBuffer = new byte[CopyBufferSize];
  602. while ( count > 0 ) {
  603. int bufferCount = (count < CopyBufferSize) ? count : CopyBufferSize;
  604. Array.Copy(buffer, offset, localBuffer, 0, bufferCount);
  605. EncryptBlock(localBuffer, 0, bufferCount);
  606. baseOutputStream_.Write(localBuffer, 0, bufferCount);
  607. count -= bufferCount;
  608. offset += bufferCount;
  609. }
  610. }
  611. /// <summary>
  612. /// Finishes the stream. This will write the central directory at the
  613. /// end of the zip file and flush the stream.
  614. /// </summary>
  615. /// <remarks>
  616. /// This is automatically called when the stream is closed.
  617. /// </remarks>
  618. /// <exception cref="System.IO.IOException">
  619. /// An I/O error occurs.
  620. /// </exception>
  621. /// <exception cref="ZipException">
  622. /// Comment exceeds the maximum length<br/>
  623. /// Entry name exceeds the maximum length
  624. /// </exception>
  625. public override void Finish()
  626. {
  627. if (entries == null) {
  628. return;
  629. }
  630. if (curEntry != null) {
  631. CloseEntry();
  632. }
  633. long numEntries = entries.Count;
  634. long sizeEntries = 0;
  635. foreach (ZipEntry entry in entries) {
  636. WriteLeInt(ZipConstants.CentralHeaderSignature);
  637. WriteLeShort(ZipConstants.VersionMadeBy);
  638. WriteLeShort(entry.Version);
  639. WriteLeShort(entry.Flags);
  640. WriteLeShort((short)entry.CompressionMethodForHeader);
  641. WriteLeInt((int)entry.DosTime);
  642. WriteLeInt((int)entry.Crc);
  643. if ( entry.IsZip64Forced() ||
  644. (entry.CompressedSize >= uint.MaxValue) )
  645. {
  646. WriteLeInt(-1);
  647. }
  648. else {
  649. WriteLeInt((int)entry.CompressedSize);
  650. }
  651. if ( entry.IsZip64Forced() ||
  652. (entry.Size >= uint.MaxValue) )
  653. {
  654. WriteLeInt(-1);
  655. }
  656. else {
  657. WriteLeInt((int)entry.Size);
  658. }
  659. byte[] name = ZipConstants.ConvertToArray(entry.Flags, entry.Name);
  660. if (name.Length > 0xffff) {
  661. throw new ZipException("Name too long.");
  662. }
  663. ZipExtraData ed = new ZipExtraData(entry.ExtraData);
  664. if ( entry.CentralHeaderRequiresZip64 ) {
  665. ed.StartNewEntry();
  666. if ( entry.IsZip64Forced() ||
  667. (entry.Size >= 0xffffffff) )
  668. {
  669. ed.AddLeLong(entry.Size);
  670. }
  671. if ( entry.IsZip64Forced() ||
  672. (entry.CompressedSize >= 0xffffffff) )
  673. {
  674. ed.AddLeLong(entry.CompressedSize);
  675. }
  676. if ( entry.Offset >= 0xffffffff )
  677. {
  678. ed.AddLeLong(entry.Offset);
  679. }
  680. ed.AddNewEntry(1);
  681. }
  682. else {
  683. ed.Delete(1);
  684. }
  685. #if !NET_1_1 && !NETCF_2_0
  686. if (entry.AESKeySize > 0) {
  687. AddExtraDataAES(entry, ed);
  688. }
  689. #endif
  690. byte[] extra = ed.GetEntryData();
  691. byte[] entryComment =
  692. (entry.Comment != null) ?
  693. ZipConstants.ConvertToArray(entry.Flags, entry.Comment) :
  694. new byte[0];
  695. if (entryComment.Length > 0xffff) {
  696. throw new ZipException("Comment too long.");
  697. }
  698. WriteLeShort(name.Length);
  699. WriteLeShort(extra.Length);
  700. WriteLeShort(entryComment.Length);
  701. WriteLeShort(0); // disk number
  702. WriteLeShort(0); // internal file attributes
  703. // external file attributes
  704. if (entry.ExternalFileAttributes != -1) {
  705. WriteLeInt(entry.ExternalFileAttributes);
  706. } else {
  707. if (entry.IsDirectory) { // mark entry as directory (from nikolam.AT.perfectinfo.com)
  708. WriteLeInt(16);
  709. } else {
  710. WriteLeInt(0);
  711. }
  712. }
  713. if ( entry.Offset >= uint.MaxValue ) {
  714. WriteLeInt(-1);
  715. }
  716. else {
  717. WriteLeInt((int)entry.Offset);
  718. }
  719. if ( name.Length > 0 ) {
  720. baseOutputStream_.Write(name, 0, name.Length);
  721. }
  722. if ( extra.Length > 0 ) {
  723. baseOutputStream_.Write(extra, 0, extra.Length);
  724. }
  725. if ( entryComment.Length > 0 ) {
  726. baseOutputStream_.Write(entryComment, 0, entryComment.Length);
  727. }
  728. sizeEntries += ZipConstants.CentralHeaderBaseSize + name.Length + extra.Length + entryComment.Length;
  729. }
  730. using ( ZipHelperStream zhs = new ZipHelperStream(baseOutputStream_) ) {
  731. zhs.WriteEndOfCentralDirectory(numEntries, sizeEntries, offset, zipComment);
  732. }
  733. entries = null;
  734. }
  735. #region Instance Fields
  736. /// <summary>
  737. /// The entries for the archive.
  738. /// </summary>
  739. ArrayList entries = new ArrayList();
  740. /// <summary>
  741. /// Used to track the crc of data added to entries.
  742. /// </summary>
  743. Crc32 crc = new Crc32();
  744. /// <summary>
  745. /// The current entry being added.
  746. /// </summary>
  747. ZipEntry curEntry;
  748. int defaultCompressionLevel = Deflater.DEFAULT_COMPRESSION;
  749. CompressionMethod curMethod = CompressionMethod.Deflated;
  750. /// <summary>
  751. /// Used to track the size of data for an entry during writing.
  752. /// </summary>
  753. long size;
  754. /// <summary>
  755. /// Offset to be recorded for each entry in the central header.
  756. /// </summary>
  757. long offset;
  758. /// <summary>
  759. /// Comment for the entire archive recorded in central header.
  760. /// </summary>
  761. byte[] zipComment = new byte[0];
  762. /// <summary>
  763. /// Flag indicating that header patching is required for the current entry.
  764. /// </summary>
  765. bool patchEntryHeader;
  766. /// <summary>
  767. /// Position to patch crc
  768. /// </summary>
  769. long crcPatchPos = -1;
  770. /// <summary>
  771. /// Position to patch size.
  772. /// </summary>
  773. long sizePatchPos = -1;
  774. // Default is dynamic which is not backwards compatible and can cause problems
  775. // with XP's built in compression which cant read Zip64 archives.
  776. // However it does avoid the situation were a large file is added and cannot be completed correctly.
  777. // NOTE: Setting the size for entries before they are added is the best solution!
  778. UseZip64 useZip64_ = UseZip64.Dynamic;
  779. #endregion
  780. }
  781. }