ZipOutputStream.cs 24 KB

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