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.

660 lines
21 KiB

  1. // ZipHelperStream.cs
  2. //
  3. // Copyright 2006, 2007 John Reilly
  4. //
  5. // This program is free software; you can redistribute it and/or
  6. // modify it under the terms of the GNU General Public License
  7. // as published by the Free Software Foundation; either version 2
  8. // of the License, or (at your option) any later version.
  9. //
  10. // This program is distributed in the hope that it will be useful,
  11. // but WITHOUT ANY WARRANTY; without even the implied warranty of
  12. // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  13. // GNU General Public License for more details.
  14. //
  15. // You should have received a copy of the GNU General Public License
  16. // along with this program; if not, write to the Free Software
  17. // Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
  18. //
  19. // Linking this library statically or dynamically with other modules is
  20. // making a combined work based on this library. Thus, the terms and
  21. // conditions of the GNU General Public License cover the whole
  22. // combination.
  23. //
  24. // As a special exception, the copyright holders of this library give you
  25. // permission to link this library with independent modules to produce an
  26. // executable, regardless of the license terms of these independent
  27. // modules, and to copy and distribute the resulting executable under
  28. // terms of your choice, provided that you also meet, for each linked
  29. // independent module, the terms and conditions of the license of that
  30. // module. An independent module is a module which is not derived from
  31. // or based on this library. If you modify this library, you may extend
  32. // this exception to your version of the library, but you are not
  33. // obligated to do so. If you do not wish to do so, delete this
  34. // exception statement from your version.
  35. using System;
  36. using System.IO;
  37. using System.Text;
  38. namespace Externals.Compression.Zip
  39. {
  40. /// <summary>
  41. /// Holds data pertinent to a data descriptor.
  42. /// </summary>
  43. internal class DescriptorData
  44. {
  45. /// <summary>
  46. /// Get /set the compressed size of data.
  47. /// </summary>
  48. public long CompressedSize
  49. {
  50. get { return compressedSize; }
  51. set { compressedSize = value; }
  52. }
  53. /// <summary>
  54. /// Get / set the uncompressed size of data
  55. /// </summary>
  56. public long Size
  57. {
  58. get { return size; }
  59. set { size = value; }
  60. }
  61. /// <summary>
  62. /// Get /set the crc value.
  63. /// </summary>
  64. public long Crc
  65. {
  66. get { return crc; }
  67. set { crc = (value & 0xffffffff); }
  68. }
  69. #region Instance Fields
  70. long size;
  71. long compressedSize;
  72. long crc;
  73. #endregion
  74. }
  75. class EntryPatchData
  76. {
  77. public long SizePatchOffset
  78. {
  79. get { return sizePatchOffset_; }
  80. set { sizePatchOffset_ = value; }
  81. }
  82. public long CrcPatchOffset
  83. {
  84. get { return crcPatchOffset_; }
  85. set { crcPatchOffset_ = value; }
  86. }
  87. #region Instance Fields
  88. long sizePatchOffset_;
  89. long crcPatchOffset_;
  90. #endregion
  91. }
  92. /// <summary>
  93. /// This class assists with writing/reading from Zip files.
  94. /// </summary>
  95. internal class ZipHelperStream : Stream
  96. {
  97. #region Constructors
  98. /// <summary>
  99. /// Initialise an instance of this class.
  100. /// </summary>
  101. /// <param name="name">The name of the file to open.</param>
  102. public ZipHelperStream(string name)
  103. {
  104. stream_ = new FileStream(name, FileMode.Open, FileAccess.ReadWrite);
  105. isOwner_ = true;
  106. }
  107. /// <summary>
  108. /// Initialise a new instance of <see cref="ZipHelperStream"/>.
  109. /// </summary>
  110. /// <param name="stream">The stream to use.</param>
  111. public ZipHelperStream(Stream stream)
  112. {
  113. stream_ = stream;
  114. }
  115. #endregion
  116. /// <summary>
  117. /// Get / set a value indicating wether the the underlying stream is owned or not.
  118. /// </summary>
  119. /// <remarks>If the stream is owned it is closed when this instance is closed.</remarks>
  120. public bool IsStreamOwner
  121. {
  122. get { return isOwner_; }
  123. set { isOwner_ = value; }
  124. }
  125. #region Base Stream Methods
  126. public override bool CanRead
  127. {
  128. get { return stream_.CanRead; }
  129. }
  130. public override bool CanSeek
  131. {
  132. get { return stream_.CanSeek; }
  133. }
  134. #if !NET_1_0 && !NET_1_1 && !NETCF_1_0
  135. public override bool CanTimeout
  136. {
  137. get { return stream_.CanTimeout; }
  138. }
  139. #endif
  140. public override long Length
  141. {
  142. get { return stream_.Length; }
  143. }
  144. public override long Position
  145. {
  146. get { return stream_.Position; }
  147. set { stream_.Position = value; }
  148. }
  149. public override bool CanWrite
  150. {
  151. get { return stream_.CanWrite; }
  152. }
  153. public override void Flush()
  154. {
  155. stream_.Flush();
  156. }
  157. public override long Seek(long offset, SeekOrigin origin)
  158. {
  159. return stream_.Seek(offset, origin);
  160. }
  161. public override void SetLength(long value)
  162. {
  163. stream_.SetLength(value);
  164. }
  165. public override int Read(byte[] buffer, int offset, int count)
  166. {
  167. return stream_.Read(buffer, offset, count);
  168. }
  169. public override void Write(byte[] buffer, int offset, int count)
  170. {
  171. stream_.Write(buffer, offset, count);
  172. }
  173. /// <summary>
  174. /// Close the stream.
  175. /// </summary>
  176. /// <remarks>
  177. /// The underlying stream is closed only if <see cref="IsStreamOwner"/> is true.
  178. /// </remarks>
  179. override public void Close()
  180. {
  181. Stream toClose = stream_;
  182. stream_ = null;
  183. if (isOwner_ && (toClose != null))
  184. {
  185. isOwner_ = false;
  186. toClose.Close();
  187. }
  188. }
  189. #endregion
  190. // Write the local file header
  191. // TODO: ZipHelperStream.WriteLocalHeader is not yet used and needs checking for ZipFile and ZipOuptutStream usage
  192. void WriteLocalHeader(ZipEntry entry, EntryPatchData patchData)
  193. {
  194. CompressionMethod method = entry.CompressionMethod;
  195. bool headerInfoAvailable = true; // How to get this?
  196. bool patchEntryHeader = false;
  197. WriteLEInt(ZipConstants.LocalHeaderSignature);
  198. WriteLEShort(entry.Version);
  199. WriteLEShort(entry.Flags);
  200. WriteLEShort((byte)method);
  201. WriteLEInt((int)entry.DosTime);
  202. if (headerInfoAvailable == true)
  203. {
  204. WriteLEInt((int)entry.Crc);
  205. if (entry.LocalHeaderRequiresZip64)
  206. {
  207. WriteLEInt(-1);
  208. WriteLEInt(-1);
  209. }
  210. else
  211. {
  212. WriteLEInt(entry.IsCrypted ? (int)entry.CompressedSize + ZipConstants.CryptoHeaderSize : (int)entry.CompressedSize);
  213. WriteLEInt((int)entry.Size);
  214. }
  215. }
  216. else
  217. {
  218. if (patchData != null)
  219. {
  220. patchData.CrcPatchOffset = stream_.Position;
  221. }
  222. WriteLEInt(0); // Crc
  223. if (patchData != null)
  224. {
  225. patchData.SizePatchOffset = stream_.Position;
  226. }
  227. // For local header both sizes appear in Zip64 Extended Information
  228. if (entry.LocalHeaderRequiresZip64 && patchEntryHeader)
  229. {
  230. WriteLEInt(-1);
  231. WriteLEInt(-1);
  232. }
  233. else
  234. {
  235. WriteLEInt(0); // Compressed size
  236. WriteLEInt(0); // Uncompressed size
  237. }
  238. }
  239. byte[] name = ZipConstants.ConvertToArray(entry.Flags, entry.Name);
  240. if (name.Length > 0xFFFF)
  241. {
  242. throw new ZipException("Entry name too long.");
  243. }
  244. ZipExtraData ed = new ZipExtraData(entry.ExtraData);
  245. if (entry.LocalHeaderRequiresZip64 && (headerInfoAvailable || patchEntryHeader))
  246. {
  247. ed.StartNewEntry();
  248. if (headerInfoAvailable)
  249. {
  250. ed.AddLeLong(entry.Size);
  251. ed.AddLeLong(entry.CompressedSize);
  252. }
  253. else
  254. {
  255. ed.AddLeLong(-1);
  256. ed.AddLeLong(-1);
  257. }
  258. ed.AddNewEntry(1);
  259. if (!ed.Find(1))
  260. {
  261. throw new ZipException("Internal error cant find extra data");
  262. }
  263. if (patchData != null)
  264. {
  265. patchData.SizePatchOffset = ed.CurrentReadIndex;
  266. }
  267. }
  268. else
  269. {
  270. ed.Delete(1);
  271. }
  272. byte[] extra = ed.GetEntryData();
  273. WriteLEShort(name.Length);
  274. WriteLEShort(extra.Length);
  275. if (name.Length > 0)
  276. {
  277. stream_.Write(name, 0, name.Length);
  278. }
  279. if (entry.LocalHeaderRequiresZip64 && patchEntryHeader)
  280. {
  281. patchData.SizePatchOffset += stream_.Position;
  282. }
  283. if (extra.Length > 0)
  284. {
  285. stream_.Write(extra, 0, extra.Length);
  286. }
  287. }
  288. /// <summary>
  289. /// Locates a block with the desired <paramref name="signature"/>.
  290. /// </summary>
  291. /// <param name="signature">The signature to find.</param>
  292. /// <param name="endLocation">Location, marking the end of block.</param>
  293. /// <param name="minimumBlockSize">Minimum size of the block.</param>
  294. /// <param name="maximumVariableData">The maximum variable data.</param>
  295. /// <returns>Eeturns the offset of the first byte after the signature; -1 if not found</returns>
  296. public long LocateBlockWithSignature(int signature, long endLocation, int minimumBlockSize, int maximumVariableData)
  297. {
  298. long pos = endLocation - minimumBlockSize;
  299. if (pos < 0)
  300. {
  301. return -1;
  302. }
  303. long giveUpMarker = Math.Max(pos - maximumVariableData, 0);
  304. // TODO: This loop could be optimised for speed.
  305. do
  306. {
  307. if (pos < giveUpMarker)
  308. {
  309. return -1;
  310. }
  311. Seek(pos--, SeekOrigin.Begin);
  312. } while (ReadLEInt() != signature);
  313. return Position;
  314. }
  315. /// <summary>
  316. /// Write Zip64 end of central directory records (File header and locator).
  317. /// </summary>
  318. /// <param name="noOfEntries">The number of entries in the central directory.</param>
  319. /// <param name="sizeEntries">The size of entries in the central directory.</param>
  320. /// <param name="centralDirOffset">The offset of the dentral directory.</param>
  321. public void WriteZip64EndOfCentralDirectory(long noOfEntries, long sizeEntries, long centralDirOffset)
  322. {
  323. long centralSignatureOffset = stream_.Position;
  324. WriteLEInt(ZipConstants.Zip64CentralFileHeaderSignature);
  325. WriteLELong(44); // Size of this record (total size of remaining fields in header or full size - 12)
  326. WriteLEShort(ZipConstants.VersionMadeBy); // Version made by
  327. WriteLEShort(ZipConstants.VersionZip64); // Version to extract
  328. WriteLEInt(0); // Number of this disk
  329. WriteLEInt(0); // number of the disk with the start of the central directory
  330. WriteLELong(noOfEntries); // No of entries on this disk
  331. WriteLELong(noOfEntries); // Total No of entries in central directory
  332. WriteLELong(sizeEntries); // Size of the central directory
  333. WriteLELong(centralDirOffset); // offset of start of central directory
  334. // zip64 extensible data sector not catered for here (variable size)
  335. // Write the Zip64 end of central directory locator
  336. WriteLEInt(ZipConstants.Zip64CentralDirLocatorSignature);
  337. // no of the disk with the start of the zip64 end of central directory
  338. WriteLEInt(0);
  339. // relative offset of the zip64 end of central directory record
  340. WriteLELong(centralSignatureOffset);
  341. // total number of disks
  342. WriteLEInt(1);
  343. }
  344. /// <summary>
  345. /// Write the required records to end the central directory.
  346. /// </summary>
  347. /// <param name="noOfEntries">The number of entries in the directory.</param>
  348. /// <param name="sizeEntries">The size of the entries in the directory.</param>
  349. /// <param name="startOfCentralDirectory">The start of the central directory.</param>
  350. /// <param name="comment">The archive comment. (This can be null).</param>
  351. public void WriteEndOfCentralDirectory(long noOfEntries, long sizeEntries,
  352. long startOfCentralDirectory, byte[] comment)
  353. {
  354. if ((noOfEntries >= 0xffff) ||
  355. (startOfCentralDirectory >= 0xffffffff) ||
  356. (sizeEntries >= 0xffffffff))
  357. {
  358. WriteZip64EndOfCentralDirectory(noOfEntries, sizeEntries, startOfCentralDirectory);
  359. }
  360. WriteLEInt(ZipConstants.EndOfCentralDirectorySignature);
  361. // TODO: ZipFile Multi disk handling not done
  362. WriteLEShort(0); // number of this disk
  363. WriteLEShort(0); // no of disk with start of central dir
  364. // Number of entries
  365. if (noOfEntries >= 0xffff)
  366. {
  367. WriteLEUshort(0xffff); // Zip64 marker
  368. WriteLEUshort(0xffff);
  369. }
  370. else
  371. {
  372. WriteLEShort((short)noOfEntries); // entries in central dir for this disk
  373. WriteLEShort((short)noOfEntries); // total entries in central directory
  374. }
  375. // Size of the central directory
  376. if (sizeEntries >= 0xffffffff)
  377. {
  378. WriteLEUint(0xffffffff); // Zip64 marker
  379. }
  380. else
  381. {
  382. WriteLEInt((int)sizeEntries);
  383. }
  384. // offset of start of central directory
  385. if (startOfCentralDirectory >= 0xffffffff)
  386. {
  387. WriteLEUint(0xffffffff); // Zip64 marker
  388. }
  389. else
  390. {
  391. WriteLEInt((int)startOfCentralDirectory);
  392. }
  393. int commentLength = (comment != null) ? comment.Length : 0;
  394. if (commentLength > 0xffff)
  395. {
  396. throw new ZipException(string.Format("Comment length({0}) is too long can only be 64K", commentLength));
  397. }
  398. WriteLEShort(commentLength);
  399. if (commentLength > 0)
  400. {
  401. Write(comment, 0, comment.Length);
  402. }
  403. }
  404. #region LE value reading/writing
  405. /// <summary>
  406. /// Read an unsigned short in little endian byte order.
  407. /// </summary>
  408. /// <returns>Returns the value read.</returns>
  409. /// <exception cref="IOException">
  410. /// An i/o error occurs.
  411. /// </exception>
  412. /// <exception cref="EndOfStreamException">
  413. /// The file ends prematurely
  414. /// </exception>
  415. public int ReadLEShort()
  416. {
  417. int byteValue1 = stream_.ReadByte();
  418. if (byteValue1 < 0)
  419. {
  420. throw new EndOfStreamException();
  421. }
  422. int byteValue2 = stream_.ReadByte();
  423. if (byteValue2 < 0)
  424. {
  425. throw new EndOfStreamException();
  426. }
  427. return byteValue1 | (byteValue2 << 8);
  428. }
  429. /// <summary>
  430. /// Read an int in little endian byte order.
  431. /// </summary>
  432. /// <returns>Returns the value read.</returns>
  433. /// <exception cref="IOException">
  434. /// An i/o error occurs.
  435. /// </exception>
  436. /// <exception cref="System.IO.EndOfStreamException">
  437. /// The file ends prematurely
  438. /// </exception>
  439. public int ReadLEInt()
  440. {
  441. return ReadLEShort() | (ReadLEShort() << 16);
  442. }
  443. /// <summary>
  444. /// Read a long in little endian byte order.
  445. /// </summary>
  446. /// <returns>The value read.</returns>
  447. public long ReadLELong()
  448. {
  449. return (uint)ReadLEInt() | ((long)ReadLEInt() << 32);
  450. }
  451. /// <summary>
  452. /// Write an unsigned short in little endian byte order.
  453. /// </summary>
  454. /// <param name="value">The value to write.</param>
  455. public void WriteLEShort(int value)
  456. {
  457. stream_.WriteByte((byte)(value & 0xff));
  458. stream_.WriteByte((byte)((value >> 8) & 0xff));
  459. }
  460. /// <summary>
  461. /// Write a ushort in little endian byte order.
  462. /// </summary>
  463. /// <param name="value">The value to write.</param>
  464. public void WriteLEUshort(ushort value)
  465. {
  466. stream_.WriteByte((byte)(value & 0xff));
  467. stream_.WriteByte((byte)(value >> 8));
  468. }
  469. /// <summary>
  470. /// Write an int in little endian byte order.
  471. /// </summary>
  472. /// <param name="value">The value to write.</param>
  473. public void WriteLEInt(int value)
  474. {
  475. WriteLEShort(value);
  476. WriteLEShort(value >> 16);
  477. }
  478. /// <summary>
  479. /// Write a uint in little endian byte order.
  480. /// </summary>
  481. /// <param name="value">The value to write.</param>
  482. public void WriteLEUint(uint value)
  483. {
  484. WriteLEUshort((ushort)(value & 0xffff));
  485. WriteLEUshort((ushort)(value >> 16));
  486. }
  487. /// <summary>
  488. /// Write a long in little endian byte order.
  489. /// </summary>
  490. /// <param name="value">The value to write.</param>
  491. public void WriteLELong(long value)
  492. {
  493. WriteLEInt((int)value);
  494. WriteLEInt((int)(value >> 32));
  495. }
  496. /// <summary>
  497. /// Write a ulong in little endian byte order.
  498. /// </summary>
  499. /// <param name="value">The value to write.</param>
  500. public void WriteLEUlong(ulong value)
  501. {
  502. WriteLEUint((uint)(value & 0xffffffff));
  503. WriteLEUint((uint)(value >> 32));
  504. }
  505. #endregion
  506. /// <summary>
  507. /// Write a data descriptor.
  508. /// </summary>
  509. /// <param name="entry">The entry to write a descriptor for.</param>
  510. /// <returns>Returns the number of descriptor bytes written.</returns>
  511. public int WriteDataDescriptor(ZipEntry entry)
  512. {
  513. if (entry == null)
  514. {
  515. throw new ArgumentNullException("entry");
  516. }
  517. int result = 0;
  518. // Add data descriptor if flagged as required
  519. if ((entry.Flags & (int)GeneralBitFlags.Descriptor) != 0)
  520. {
  521. // The signature is not PKZIP originally but is now described as optional
  522. // in the PKZIP Appnote documenting trhe format.
  523. WriteLEInt(ZipConstants.DataDescriptorSignature);
  524. WriteLEInt(unchecked((int)(entry.Crc)));
  525. result += 8;
  526. if (entry.LocalHeaderRequiresZip64)
  527. {
  528. WriteLELong(entry.CompressedSize);
  529. WriteLELong(entry.Size);
  530. result += 16;
  531. }
  532. else
  533. {
  534. WriteLEInt((int)entry.CompressedSize);
  535. WriteLEInt((int)entry.Size);
  536. result += 8;
  537. }
  538. }
  539. return result;
  540. }
  541. /// <summary>
  542. /// Read data descriptor at the end of compressed data.
  543. /// </summary>
  544. /// <param name="zip64">if set to <c>true</c> [zip64].</param>
  545. /// <param name="data">The data to fill in.</param>
  546. /// <returns>Returns the number of bytes read in the descriptor.</returns>
  547. public void ReadDataDescriptor(bool zip64, DescriptorData data)
  548. {
  549. int intValue = ReadLEInt();
  550. // In theory this may not be a descriptor according to PKZIP appnote.
  551. // In practise its always there.
  552. if (intValue != ZipConstants.DataDescriptorSignature)
  553. {
  554. throw new ZipException("Data descriptor signature not found");
  555. }
  556. data.Crc = ReadLEInt();
  557. if (zip64)
  558. {
  559. data.CompressedSize = ReadLELong();
  560. data.Size = ReadLELong();
  561. }
  562. else
  563. {
  564. data.CompressedSize = ReadLEInt();
  565. data.Size = ReadLEInt();
  566. }
  567. }
  568. #region Instance Fields
  569. bool isOwner_;
  570. Stream stream_;
  571. #endregion
  572. }
  573. }