ZipOutputStream.cs 26 KB

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