ZipExtraData.cs 27 KB

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