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.

1022 lines
34 KiB

  1. //
  2. // ZipExtraData.cs
  3. //
  4. // Copyright 2004-2007 John Reilly
  5. //
  6. // This program is free software; you can redistribute it and/or
  7. // modify it under the terms of the GNU General Public License
  8. // as published by the Free Software Foundation; either version 2
  9. // of the License, or (at your option) any later version.
  10. //
  11. // This program is distributed in the hope that it will be useful,
  12. // but WITHOUT ANY WARRANTY; without even the implied warranty of
  13. // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  14. // GNU General Public License for more details.
  15. //
  16. // You should have received a copy of the GNU General Public License
  17. // along with this program; if not, write to the Free Software
  18. // Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
  19. //
  20. // Linking this library statically or dynamically with other modules is
  21. // making a combined work based on this library. Thus, the terms and
  22. // conditions of the GNU General Public License cover the whole
  23. // combination.
  24. //
  25. // As a special exception, the copyright holders of this library give you
  26. // permission to link this library with independent modules to produce an
  27. // executable, regardless of the license terms of these independent
  28. // modules, and to copy and distribute the resulting executable under
  29. // terms of your choice, provided that you also meet, for each linked
  30. // independent module, the terms and conditions of the license of that
  31. // module. An independent module is a module which is not derived from
  32. // or based on this library. If you modify this library, you may extend
  33. // this exception to your version of the library, but you are not
  34. // obligated to do so. If you do not wish to do so, delete this
  35. // exception statement from your version.
  36. using System;
  37. using System.IO;
  38. namespace Externals.Compression.Zip
  39. {
  40. // TODO: Sort out wether tagged data is useful and what a good implementation might look like.
  41. // Its just a sketch of an idea at the moment.
  42. /// <summary>
  43. /// ExtraData tagged value interface.
  44. /// </summary>
  45. internal interface ITaggedData
  46. {
  47. /// <summary>
  48. /// Get the ID for this tagged data value.
  49. /// </summary>
  50. short TagID { get; }
  51. /// <summary>
  52. /// Set the contents of this instance from the data passed.
  53. /// </summary>
  54. /// <param name="data">The data to extract contents from.</param>
  55. /// <param name="offset">The offset to begin extracting data from.</param>
  56. /// <param name="count">The number of bytes to extract.</param>
  57. void SetData(byte[] data, int offset, int count);
  58. /// <summary>
  59. /// Get the data representing this instance.
  60. /// </summary>
  61. /// <returns>Returns the data for this instance.</returns>
  62. byte[] GetData();
  63. }
  64. /// <summary>
  65. /// A raw binary tagged value
  66. /// </summary>
  67. internal class RawTaggedData : ITaggedData
  68. {
  69. /// <summary>
  70. /// Initialise a new instance.
  71. /// </summary>
  72. /// <param name="tag">The tag ID.</param>
  73. public RawTaggedData(short tag)
  74. {
  75. _tag = tag;
  76. }
  77. #region ITaggedData Members
  78. /// <summary>
  79. /// Get the ID for this tagged data value.
  80. /// </summary>
  81. public short TagID
  82. {
  83. get { return _tag; }
  84. set { _tag = value; }
  85. }
  86. /// <summary>
  87. /// Set the data from the raw values provided.
  88. /// </summary>
  89. /// <param name="data">The raw data to extract values from.</param>
  90. /// <param name="offset">The index to start extracting values from.</param>
  91. /// <param name="count">The number of bytes available.</param>
  92. public void SetData(byte[] data, int offset, int count)
  93. {
  94. if (data == null)
  95. {
  96. throw new ArgumentNullException("data");
  97. }
  98. _data = new byte[count];
  99. Array.Copy(data, offset, _data, 0, count);
  100. }
  101. /// <summary>
  102. /// Get the binary data representing this instance.
  103. /// </summary>
  104. /// <returns>The raw binary data representing this instance.</returns>
  105. public byte[] GetData()
  106. {
  107. return _data;
  108. }
  109. #endregion
  110. /// <summary>
  111. /// Get /set the binary data representing this instance.
  112. /// </summary>
  113. /// <returns>The raw binary data representing this instance.</returns>
  114. public byte[] Data
  115. {
  116. get { return _data; }
  117. set { _data = value; }
  118. }
  119. #region Instance Fields
  120. /// <summary>
  121. /// The tag ID for this instance.
  122. /// </summary>
  123. short _tag;
  124. byte[] _data;
  125. #endregion
  126. }
  127. /// <summary>
  128. /// Class representing extended unix date time values.
  129. /// </summary>
  130. internal class ExtendedUnixData : ITaggedData
  131. {
  132. /// <summary>
  133. /// Flags indicate which values are included in this instance.
  134. /// </summary>
  135. [Flags]
  136. internal enum Flags : byte
  137. {
  138. /// <summary>
  139. /// The modification time is included
  140. /// </summary>
  141. ModificationTime = 0x01,
  142. /// <summary>
  143. /// The access time is included
  144. /// </summary>
  145. AccessTime = 0x02,
  146. /// <summary>
  147. /// The create time is included.
  148. /// </summary>
  149. CreateTime = 0x04,
  150. }
  151. #region ITaggedData Members
  152. /// <summary>
  153. /// Get the ID
  154. /// </summary>
  155. public short TagID
  156. {
  157. get { return 0x5455; }
  158. }
  159. /// <summary>
  160. /// Set the data from the raw values provided.
  161. /// </summary>
  162. /// <param name="data">The raw data to extract values from.</param>
  163. /// <param name="index">The index to start extracting values from.</param>
  164. /// <param name="count">The number of bytes available.</param>
  165. public void SetData(byte[] data, int index, int count)
  166. {
  167. using (MemoryStream ms = new MemoryStream(data, index, count, false))
  168. using (ZipHelperStream helperStream = new ZipHelperStream(ms))
  169. {
  170. // bit 0 if set, modification time is present
  171. // bit 1 if set, access time is present
  172. // bit 2 if set, creation time is present
  173. _flags = (Flags)helperStream.ReadByte();
  174. if (((_flags & Flags.ModificationTime) != 0) && (count >= 5))
  175. {
  176. int iTime = helperStream.ReadLEInt();
  177. _modificationTime = (new DateTime(1970, 1, 1, 0, 0, 0).ToUniversalTime() +
  178. new TimeSpan(0, 0, 0, iTime, 0)).ToLocalTime();
  179. }
  180. if ((_flags & Flags.AccessTime) != 0)
  181. {
  182. int iTime = helperStream.ReadLEInt();
  183. _lastAccessTime = (new DateTime(1970, 1, 1, 0, 0, 0).ToUniversalTime() +
  184. new TimeSpan(0, 0, 0, iTime, 0)).ToLocalTime();
  185. }
  186. if ((_flags & Flags.CreateTime) != 0)
  187. {
  188. int iTime = helperStream.ReadLEInt();
  189. _createTime = (new DateTime(1970, 1, 1, 0, 0, 0).ToUniversalTime() +
  190. new TimeSpan(0, 0, 0, iTime, 0)).ToLocalTime();
  191. }
  192. }
  193. }
  194. /// <summary>
  195. /// Get the binary data representing this instance.
  196. /// </summary>
  197. /// <returns>The raw binary data representing this instance.</returns>
  198. public byte[] GetData()
  199. {
  200. using (MemoryStream ms = new MemoryStream())
  201. using (ZipHelperStream helperStream = new ZipHelperStream(ms))
  202. {
  203. helperStream.IsStreamOwner = false;
  204. helperStream.WriteByte((byte)_flags); // Flags
  205. if ((_flags & Flags.ModificationTime) != 0)
  206. {
  207. TimeSpan span = _modificationTime.ToUniversalTime() - new DateTime(1970, 1, 1, 0, 0, 0).ToUniversalTime();
  208. int seconds = (int)span.TotalSeconds;
  209. helperStream.WriteLEInt(seconds);
  210. }
  211. if ((_flags & Flags.AccessTime) != 0)
  212. {
  213. TimeSpan span = _lastAccessTime.ToUniversalTime() - new DateTime(1970, 1, 1, 0, 0, 0).ToUniversalTime();
  214. int seconds = (int)span.TotalSeconds;
  215. helperStream.WriteLEInt(seconds);
  216. }
  217. if ((_flags & Flags.CreateTime) != 0)
  218. {
  219. TimeSpan span = _createTime.ToUniversalTime() - new DateTime(1970, 1, 1, 0, 0, 0).ToUniversalTime();
  220. int seconds = (int)span.TotalSeconds;
  221. helperStream.WriteLEInt(seconds);
  222. }
  223. return ms.ToArray();
  224. }
  225. }
  226. #endregion
  227. /// <summary>
  228. /// Test a <see cref="DateTime"> value to see if is valid and can be represented here.</see>
  229. /// </summary>
  230. /// <param name="value">The <see cref="DateTime">value</see> to test.</param>
  231. /// <returns>Returns true if the value is valid and can be represented; false if not.</returns>
  232. /// <remarks>The standard Unix time is a signed integer data type, directly encoding the Unix time number,
  233. /// which is the number of seconds since 1970-01-01.
  234. /// Being 32 bits means the values here cover a range of about 136 years.
  235. /// The minimum representable time is 1901-12-13 20:45:52,
  236. /// and the maximum representable time is 2038-01-19 03:14:07.
  237. /// </remarks>
  238. public static bool IsValidValue(DateTime value)
  239. {
  240. return ((value >= new DateTime(1901, 12, 13, 20, 45, 52)) ||
  241. (value <= new DateTime(2038, 1, 19, 03, 14, 07)));
  242. }
  243. /// <summary>
  244. /// Get /set the Modification Time
  245. /// </summary>
  246. /// <exception cref="ArgumentOutOfRangeException"></exception>
  247. /// <seealso cref="IsValidValue"></seealso>
  248. public DateTime ModificationTime
  249. {
  250. get { return _modificationTime; }
  251. set
  252. {
  253. if (!IsValidValue(value))
  254. {
  255. throw new ArgumentOutOfRangeException("value");
  256. }
  257. _flags |= Flags.ModificationTime;
  258. _modificationTime = value;
  259. }
  260. }
  261. /// <summary>
  262. /// Get / set the Access Time
  263. /// </summary>
  264. /// <exception cref="ArgumentOutOfRangeException"></exception>
  265. /// <seealso cref="IsValidValue"></seealso>
  266. public DateTime AccessTime
  267. {
  268. get { return _lastAccessTime; }
  269. set
  270. {
  271. if (!IsValidValue(value))
  272. {
  273. throw new ArgumentOutOfRangeException("value");
  274. }
  275. _flags |= Flags.AccessTime;
  276. _lastAccessTime = value;
  277. }
  278. }
  279. /// <summary>
  280. /// Get / Set the Create Time
  281. /// </summary>
  282. /// <exception cref="ArgumentOutOfRangeException"></exception>
  283. /// <seealso cref="IsValidValue"></seealso>
  284. public DateTime CreateTime
  285. {
  286. get { return _createTime; }
  287. set
  288. {
  289. if (!IsValidValue(value))
  290. {
  291. throw new ArgumentOutOfRangeException("value");
  292. }
  293. _flags |= Flags.CreateTime;
  294. _createTime = value;
  295. }
  296. }
  297. /// <summary>
  298. /// Get/set the <see cref="Flags">values</see> to include.
  299. /// </summary>
  300. Flags Include
  301. {
  302. get { return _flags; }
  303. set { _flags = value; }
  304. }
  305. #region Instance Fields
  306. Flags _flags;
  307. DateTime _modificationTime = new DateTime(1970, 1, 1);
  308. DateTime _lastAccessTime = new DateTime(1970, 1, 1);
  309. DateTime _createTime = new DateTime(1970, 1, 1);
  310. #endregion
  311. }
  312. /// <summary>
  313. /// Class handling NT date time values.
  314. /// </summary>
  315. internal class NTTaggedData : ITaggedData
  316. {
  317. /// <summary>
  318. /// Get the ID for this tagged data value.
  319. /// </summary>
  320. public short TagID
  321. {
  322. get { return 10; }
  323. }
  324. /// <summary>
  325. /// Set the data from the raw values provided.
  326. /// </summary>
  327. /// <param name="data">The raw data to extract values from.</param>
  328. /// <param name="index">The index to start extracting values from.</param>
  329. /// <param name="count">The number of bytes available.</param>
  330. public void SetData(byte[] data, int index, int count)
  331. {
  332. using (MemoryStream ms = new MemoryStream(data, index, count, false))
  333. using (ZipHelperStream helperStream = new ZipHelperStream(ms))
  334. {
  335. helperStream.ReadLEInt(); // Reserved
  336. while (helperStream.Position < helperStream.Length)
  337. {
  338. int ntfsTag = helperStream.ReadLEShort();
  339. int ntfsLength = helperStream.ReadLEShort();
  340. if (ntfsTag == 1)
  341. {
  342. if (ntfsLength >= 24)
  343. {
  344. long lastModificationTicks = helperStream.ReadLELong();
  345. _lastModificationTime = DateTime.FromFileTime(lastModificationTicks);
  346. long lastAccessTicks = helperStream.ReadLELong();
  347. _lastAccessTime = DateTime.FromFileTime(lastAccessTicks);
  348. long createTimeTicks = helperStream.ReadLELong();
  349. _createTime = DateTime.FromFileTime(createTimeTicks);
  350. }
  351. break;
  352. }
  353. else
  354. {
  355. // An unknown NTFS tag so simply skip it.
  356. helperStream.Seek(ntfsLength, SeekOrigin.Current);
  357. }
  358. }
  359. }
  360. }
  361. /// <summary>
  362. /// Get the binary data representing this instance.
  363. /// </summary>
  364. /// <returns>The raw binary data representing this instance.</returns>
  365. public byte[] GetData()
  366. {
  367. using (MemoryStream ms = new MemoryStream())
  368. using (ZipHelperStream helperStream = new ZipHelperStream(ms))
  369. {
  370. helperStream.IsStreamOwner = false;
  371. helperStream.WriteLEInt(0); // Reserved
  372. helperStream.WriteLEShort(1); // Tag
  373. helperStream.WriteLEShort(24); // Length = 3 x 8.
  374. helperStream.WriteLELong(_lastModificationTime.ToFileTime());
  375. helperStream.WriteLELong(_lastAccessTime.ToFileTime());
  376. helperStream.WriteLELong(_createTime.ToFileTime());
  377. return ms.ToArray();
  378. }
  379. }
  380. /// <summary>
  381. /// Test a <see cref="DateTime"> valuie to see if is valid and can be represented here.</see>
  382. /// </summary>
  383. /// <param name="value">The <see cref="DateTime">value</see> to test.</param>
  384. /// <returns>Returns true if the value is valid and can be represented; false if not.</returns>
  385. /// <remarks>
  386. /// NTFS filetimes are 64-bit unsigned integers, stored in Intel
  387. /// (least significant byte first) byte order. They determine the
  388. /// number of 1.0E-07 seconds (1/10th microseconds!) past WinNT "epoch",
  389. /// which is "01-Jan-1601 00:00:00 UTC". 28 May 60056 is the upper limit
  390. /// </remarks>
  391. public static bool IsValidValue(DateTime value)
  392. {
  393. bool result = true;
  394. try
  395. {
  396. value.ToFileTimeUtc();
  397. }
  398. catch
  399. {
  400. result = false;
  401. }
  402. return result;
  403. }
  404. /// <summary>
  405. /// Get/set the <see cref="DateTime">last modification time</see>.
  406. /// </summary>
  407. public DateTime LastModificationTime
  408. {
  409. get { return _lastModificationTime; }
  410. set
  411. {
  412. if (!IsValidValue(value))
  413. {
  414. throw new ArgumentOutOfRangeException("value");
  415. }
  416. _lastModificationTime = value;
  417. }
  418. }
  419. /// <summary>
  420. /// Get /set the <see cref="DateTime">create time</see>
  421. /// </summary>
  422. public DateTime CreateTime
  423. {
  424. get { return _createTime; }
  425. set
  426. {
  427. if (!IsValidValue(value))
  428. {
  429. throw new ArgumentOutOfRangeException("value");
  430. }
  431. _createTime = value;
  432. }
  433. }
  434. /// <summary>
  435. /// Get /set the <see cref="DateTime">last access time</see>.
  436. /// </summary>
  437. public DateTime LastAccessTime
  438. {
  439. get { return _lastAccessTime; }
  440. set
  441. {
  442. if (!IsValidValue(value))
  443. {
  444. throw new ArgumentOutOfRangeException("value");
  445. }
  446. _lastAccessTime = value;
  447. }
  448. }
  449. #region Instance Fields
  450. DateTime _lastAccessTime = DateTime.FromFileTime(0);
  451. DateTime _lastModificationTime = DateTime.FromFileTime(0);
  452. DateTime _createTime = DateTime.FromFileTime(0);
  453. #endregion
  454. }
  455. /// <summary>
  456. /// A factory that creates <see cref="ITaggedData">tagged data</see> instances.
  457. /// </summary>
  458. interface ITaggedDataFactory
  459. {
  460. /// <summary>
  461. /// Get data for a specific tag value.
  462. /// </summary>
  463. /// <param name="tag">The tag ID to find.</param>
  464. /// <param name="data">The data to search.</param>
  465. /// <param name="offset">The offset to begin extracting data from.</param>
  466. /// <param name="count">The number of bytes to extract.</param>
  467. /// <returns>The located <see cref="ITaggedData">value found</see>, or null if not found.</returns>
  468. ITaggedData Create(short tag, byte[] data, int offset, int count);
  469. }
  470. ///
  471. /// <summary>
  472. /// A class to handle the extra data field for Zip entries
  473. /// </summary>
  474. /// <remarks>
  475. /// Extra data contains 0 or more values each prefixed by a header tag and length.
  476. /// They contain zero or more bytes of actual data.
  477. /// The data is held internally using a copy on write strategy. This is more efficient but
  478. /// means that for extra data created by passing in data can have the values modified by the caller
  479. /// in some circumstances.
  480. /// </remarks>
  481. sealed internal class ZipExtraData : IDisposable
  482. {
  483. #region Constructors
  484. /// <summary>
  485. /// Initialise a default instance.
  486. /// </summary>
  487. public ZipExtraData()
  488. {
  489. Clear();
  490. }
  491. /// <summary>
  492. /// Initialise with known extra data.
  493. /// </summary>
  494. /// <param name="data">The extra data.</param>
  495. public ZipExtraData(byte[] data)
  496. {
  497. if (data == null)
  498. {
  499. _data = new byte[0];
  500. }
  501. else
  502. {
  503. _data = data;
  504. }
  505. }
  506. #endregion
  507. /// <summary>
  508. /// Get the raw extra data value
  509. /// </summary>
  510. /// <returns>Returns the raw byte[] extra data this instance represents.</returns>
  511. public byte[] GetEntryData()
  512. {
  513. if (Length > ushort.MaxValue)
  514. {
  515. throw new ZipException("Data exceeds maximum length");
  516. }
  517. return (byte[])_data.Clone();
  518. }
  519. /// <summary>
  520. /// Clear the stored data.
  521. /// </summary>
  522. public void Clear()
  523. {
  524. if ((_data == null) || (_data.Length != 0))
  525. {
  526. _data = new byte[0];
  527. }
  528. }
  529. /// <summary>
  530. /// Gets the current extra data length.
  531. /// </summary>
  532. public int Length
  533. {
  534. get { return _data.Length; }
  535. }
  536. /// <summary>
  537. /// Get a read-only <see cref="Stream"/> for the associated tag.
  538. /// </summary>
  539. /// <param name="tag">The tag to locate data for.</param>
  540. /// <returns>Returns a <see cref="Stream"/> containing tag data or null if no tag was found.</returns>
  541. public Stream GetStreamForTag(int tag)
  542. {
  543. Stream result = null;
  544. if (Find(tag))
  545. {
  546. result = new MemoryStream(_data, _index, _readValueLength, false);
  547. }
  548. return result;
  549. }
  550. /// <summary>
  551. /// Get the <see cref="ITaggedData">tagged data</see> for a tag.
  552. /// </summary>
  553. /// <param name="tag">The tag to search for.</param>
  554. /// <returns>Returns a <see cref="ITaggedData">tagged value</see> or null if none found.</returns>
  555. private ITaggedData GetData(short tag)
  556. {
  557. ITaggedData result = null;
  558. if (Find(tag))
  559. {
  560. result = Create(tag, _data, _readValueStart, _readValueLength);
  561. }
  562. return result;
  563. }
  564. static ITaggedData Create(short tag, byte[] data, int offset, int count)
  565. {
  566. ITaggedData result = null;
  567. switch (tag)
  568. {
  569. case 0x000A:
  570. result = new NTTaggedData();
  571. break;
  572. case 0x5455:
  573. result = new ExtendedUnixData();
  574. break;
  575. default:
  576. result = new RawTaggedData(tag);
  577. break;
  578. }
  579. result.SetData(data, offset, count);
  580. return result;
  581. }
  582. /// <summary>
  583. /// Get the length of the last value found by <see cref="Find"/>
  584. /// </summary>
  585. /// <remarks>This is only valid if <see cref="Find"/> has previously returned true.</remarks>
  586. public int ValueLength
  587. {
  588. get { return _readValueLength; }
  589. }
  590. /// <summary>
  591. /// Get the index for the current read value.
  592. /// </summary>
  593. /// <remarks>This is only valid if <see cref="Find"/> has previously returned true.
  594. /// Initially the result will be the index of the first byte of actual data. The value is updated after calls to
  595. /// <see cref="ReadInt"/>, <see cref="ReadShort"/> and <see cref="ReadLong"/>. </remarks>
  596. public int CurrentReadIndex
  597. {
  598. get { return _index; }
  599. }
  600. /// <summary>
  601. /// Get the number of bytes remaining to be read for the current value;
  602. /// </summary>
  603. public int UnreadCount
  604. {
  605. get
  606. {
  607. if ((_readValueStart > _data.Length) ||
  608. (_readValueStart < 4))
  609. {
  610. throw new ZipException("Find must be called before calling a Read method");
  611. }
  612. return _readValueStart + _readValueLength - _index;
  613. }
  614. }
  615. /// <summary>
  616. /// Find an extra data value
  617. /// </summary>
  618. /// <param name="headerID">The identifier for the value to find.</param>
  619. /// <returns>Returns true if the value was found; false otherwise.</returns>
  620. public bool Find(int headerID)
  621. {
  622. _readValueStart = _data.Length;
  623. _readValueLength = 0;
  624. _index = 0;
  625. int localLength = _readValueStart;
  626. int localTag = headerID - 1;
  627. // Trailing bytes that cant make up an entry (as there arent enough
  628. // bytes for a tag and length) are ignored!
  629. while ((localTag != headerID) && (_index < _data.Length - 3))
  630. {
  631. localTag = ReadShortInternal();
  632. localLength = ReadShortInternal();
  633. if (localTag != headerID)
  634. {
  635. _index += localLength;
  636. }
  637. }
  638. bool result = (localTag == headerID) && ((_index + localLength) <= _data.Length);
  639. if (result)
  640. {
  641. _readValueStart = _index;
  642. _readValueLength = localLength;
  643. }
  644. return result;
  645. }
  646. /// <summary>
  647. /// Add a new entry to extra data.
  648. /// </summary>
  649. /// <param name="taggedData">The <see cref="ITaggedData"/> value to add.</param>
  650. public void AddEntry(ITaggedData taggedData)
  651. {
  652. if (taggedData == null)
  653. {
  654. throw new ArgumentNullException("taggedData");
  655. }
  656. AddEntry(taggedData.TagID, taggedData.GetData());
  657. }
  658. /// <summary>
  659. /// Add a new entry to extra data
  660. /// </summary>
  661. /// <param name="headerID">The ID for this entry.</param>
  662. /// <param name="fieldData">The data to add.</param>
  663. /// <remarks>If the ID already exists its contents are replaced.</remarks>
  664. public void AddEntry(int headerID, byte[] fieldData)
  665. {
  666. if ((headerID > ushort.MaxValue) || (headerID < 0))
  667. {
  668. throw new ArgumentOutOfRangeException("headerID");
  669. }
  670. int addLength = (fieldData == null) ? 0 : fieldData.Length;
  671. if (addLength > ushort.MaxValue)
  672. {
  673. #if NETCF_1_0
  674. throw new ArgumentOutOfRangeException("fieldData");
  675. #else
  676. throw new ArgumentOutOfRangeException("fieldData", "exceeds maximum length");
  677. #endif
  678. }
  679. // Test for new length before adjusting data.
  680. int newLength = _data.Length + addLength + 4;
  681. if (Find(headerID))
  682. {
  683. newLength -= (ValueLength + 4);
  684. }
  685. if (newLength > ushort.MaxValue)
  686. {
  687. throw new ZipException("Data exceeds maximum length");
  688. }
  689. Delete(headerID);
  690. byte[] newData = new byte[newLength];
  691. _data.CopyTo(newData, 0);
  692. int index = _data.Length;
  693. _data = newData;
  694. SetShort(ref index, headerID);
  695. SetShort(ref index, addLength);
  696. if (fieldData != null)
  697. {
  698. fieldData.CopyTo(newData, index);
  699. }
  700. }
  701. /// <summary>
  702. /// Start adding a new entry.
  703. /// </summary>
  704. /// <remarks>Add data using <see cref="AddData(byte[])"/>, <see cref="AddLeShort"/>, <see cref="AddLeInt"/>, or <see cref="AddLeLong"/>.
  705. /// The new entry is completed and actually added by calling <see cref="AddNewEntry"/></remarks>
  706. /// <seealso cref="AddEntry(ITaggedData)"/>
  707. public void StartNewEntry()
  708. {
  709. _newEntry = new MemoryStream();
  710. }
  711. /// <summary>
  712. /// Add entry data added since <see cref="StartNewEntry"/> using the ID passed.
  713. /// </summary>
  714. /// <param name="headerID">The identifier to use for this entry.</param>
  715. public void AddNewEntry(int headerID)
  716. {
  717. byte[] newData = _newEntry.ToArray();
  718. _newEntry = null;
  719. AddEntry(headerID, newData);
  720. }
  721. /// <summary>
  722. /// Add a byte of data to the pending new entry.
  723. /// </summary>
  724. /// <param name="data">The byte to add.</param>
  725. /// <seealso cref="StartNewEntry"/>
  726. public void AddData(byte data)
  727. {
  728. _newEntry.WriteByte(data);
  729. }
  730. /// <summary>
  731. /// Add data to a pending new entry.
  732. /// </summary>
  733. /// <param name="data">The data to add.</param>
  734. /// <seealso cref="StartNewEntry"/>
  735. public void AddData(byte[] data)
  736. {
  737. if (data == null)
  738. {
  739. throw new ArgumentNullException("data");
  740. }
  741. _newEntry.Write(data, 0, data.Length);
  742. }
  743. /// <summary>
  744. /// Add a short value in little endian order to the pending new entry.
  745. /// </summary>
  746. /// <param name="toAdd">The data to add.</param>
  747. /// <seealso cref="StartNewEntry"/>
  748. public void AddLeShort(int toAdd)
  749. {
  750. unchecked
  751. {
  752. _newEntry.WriteByte((byte)toAdd);
  753. _newEntry.WriteByte((byte)(toAdd >> 8));
  754. }
  755. }
  756. /// <summary>
  757. /// Add an integer value in little endian order to the pending new entry.
  758. /// </summary>
  759. /// <param name="toAdd">The data to add.</param>
  760. /// <seealso cref="StartNewEntry"/>
  761. public void AddLeInt(int toAdd)
  762. {
  763. unchecked
  764. {
  765. AddLeShort((short)toAdd);
  766. AddLeShort((short)(toAdd >> 16));
  767. }
  768. }
  769. /// <summary>
  770. /// Add a long value in little endian order to the pending new entry.
  771. /// </summary>
  772. /// <param name="toAdd">The data to add.</param>
  773. /// <seealso cref="StartNewEntry"/>
  774. public void AddLeLong(long toAdd)
  775. {
  776. unchecked
  777. {
  778. AddLeInt((int)(toAdd & 0xffffffff));
  779. AddLeInt((int)(toAdd >> 32));
  780. }
  781. }
  782. /// <summary>
  783. /// Delete an extra data field.
  784. /// </summary>
  785. /// <param name="headerID">The identifier of the field to delete.</param>
  786. /// <returns>Returns true if the field was found and deleted.</returns>
  787. public bool Delete(int headerID)
  788. {
  789. bool result = false;
  790. if (Find(headerID))
  791. {
  792. result = true;
  793. int trueStart = _readValueStart - 4;
  794. byte[] newData = new byte[_data.Length - (ValueLength + 4)];
  795. Array.Copy(_data, 0, newData, 0, trueStart);
  796. int trueEnd = trueStart + ValueLength + 4;
  797. Array.Copy(_data, trueEnd, newData, trueStart, _data.Length - trueEnd);
  798. _data = newData;
  799. }
  800. return result;
  801. }
  802. #region Reading Support
  803. /// <summary>
  804. /// Read a long in little endian form from the last <see cref="Find">found</see> data value
  805. /// </summary>
  806. /// <returns>Returns the long value read.</returns>
  807. public long ReadLong()
  808. {
  809. ReadCheck(8);
  810. return (ReadInt() & 0xffffffff) | (((long)ReadInt()) << 32);
  811. }
  812. /// <summary>
  813. /// Read an integer in little endian form from the last <see cref="Find">found</see> data value.
  814. /// </summary>
  815. /// <returns>Returns the integer read.</returns>
  816. public int ReadInt()
  817. {
  818. ReadCheck(4);
  819. int result = _data[_index] + (_data[_index + 1] << 8) +
  820. (_data[_index + 2] << 16) + (_data[_index + 3] << 24);
  821. _index += 4;
  822. return result;
  823. }
  824. /// <summary>
  825. /// Read a short value in little endian form from the last <see cref="Find">found</see> data value.
  826. /// </summary>
  827. /// <returns>Returns the short value read.</returns>
  828. public int ReadShort()
  829. {
  830. ReadCheck(2);
  831. int result = _data[_index] + (_data[_index + 1] << 8);
  832. _index += 2;
  833. return result;
  834. }
  835. /// <summary>
  836. /// Read a byte from an extra data
  837. /// </summary>
  838. /// <returns>The byte value read or -1 if the end of data has been reached.</returns>
  839. public int ReadByte()
  840. {
  841. int result = -1;
  842. if ((_index < _data.Length) && (_readValueStart + _readValueLength > _index))
  843. {
  844. result = _data[_index];
  845. _index += 1;
  846. }
  847. return result;
  848. }
  849. /// <summary>
  850. /// Skip data during reading.
  851. /// </summary>
  852. /// <param name="amount">The number of bytes to skip.</param>
  853. public void Skip(int amount)
  854. {
  855. ReadCheck(amount);
  856. _index += amount;
  857. }
  858. void ReadCheck(int length)
  859. {
  860. if ((_readValueStart > _data.Length) ||
  861. (_readValueStart < 4))
  862. {
  863. throw new ZipException("Find must be called before calling a Read method");
  864. }
  865. if (_index > _readValueStart + _readValueLength - length)
  866. {
  867. throw new ZipException("End of extra data");
  868. }
  869. if (_index + length < 4)
  870. {
  871. throw new ZipException("Cannot read before start of tag");
  872. }
  873. }
  874. /// <summary>
  875. /// Internal form of <see cref="ReadShort"/> that reads data at any location.
  876. /// </summary>
  877. /// <returns>Returns the short value read.</returns>
  878. int ReadShortInternal()
  879. {
  880. if (_index > _data.Length - 2)
  881. {
  882. throw new ZipException("End of extra data");
  883. }
  884. int result = _data[_index] + (_data[_index + 1] << 8);
  885. _index += 2;
  886. return result;
  887. }
  888. void SetShort(ref int index, int source)
  889. {
  890. _data[index] = (byte)source;
  891. _data[index + 1] = (byte)(source >> 8);
  892. index += 2;
  893. }
  894. #endregion
  895. #region IDisposable Members
  896. /// <summary>
  897. /// Dispose of this instance.
  898. /// </summary>
  899. public void Dispose()
  900. {
  901. if (_newEntry != null)
  902. {
  903. _newEntry.Close();
  904. }
  905. }
  906. #endregion
  907. #region Instance Fields
  908. int _index;
  909. int _readValueStart;
  910. int _readValueLength;
  911. MemoryStream _newEntry;
  912. byte[] _data;
  913. #endregion
  914. }
  915. }