ZipExtraData.cs 25 KB

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