ZipExtraData.cs 25 KB

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