ZipExtraData.cs 25 KB

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