4 // Copyright 2004-2007 John Reilly
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.
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.
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.
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
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.
38 using System.Collections;
40 using ICSharpCode.SharpZipLib.Zip;
42 namespace ICSharpCode.SharpZipLib.Silverlight.Zip
45 /// ExtraData tagged value interface.
47 public interface ITaggedData
50 /// Get the ID for this tagged data value.
55 /// Set the contents of this instance from the data passed.
57 /// <param name="data">The data to extract contents from.</param>
58 /// <param name="offset">The offset to begin extracting data from.</param>
59 /// <param name="count">The number of bytes to extract.</param>
60 void SetData(byte[] data, int offset, int count);
63 /// Get the data representing this instance.
65 /// <returns>Returns the data for this instance.</returns>
70 /// A raw binary tagged value
72 public class RawTaggedData : ITaggedData
75 /// Initialise a new instance.
77 /// <param name="tag">The tag ID.</param>
78 public RawTaggedData(short tag)
83 #region ITaggedData Members
86 /// Get the ID for this tagged data value.
95 /// Set the data from the raw values provided.
97 /// <param name="data">The raw data to extract values from.</param>
98 /// <param name="offset">The index to start extracting values from.</param>
99 /// <param name="count">The number of bytes available.</param>
100 public void SetData(byte[] data, int offset, int count)
104 throw new ArgumentNullException("data");
107 data_=new byte[count];
108 Array.Copy(data, offset, data_, 0, count);
112 /// Get the binary data representing this instance.
114 /// <returns>The raw binary data representing this instance.</returns>
115 public byte[] GetData()
123 /// Get /set the binary data representing this instance.
125 /// <returns>The raw binary data representing this instance.</returns>
128 get { return data_; }
132 #region Instance Fields
134 /// The tag ID for this instance.
136 protected short tag_;
143 /// Class representing extended unix date time values.
145 public class ExtendedUnixData : ITaggedData
148 /// Flags indicate which values are included in this instance.
151 public enum Flags : byte
154 /// The modification time is included
156 ModificationTime = 0x01,
159 /// The access time is included
164 /// The create time is included.
169 #region ITaggedData Members
176 get { return 0x5455; }
180 /// Set the data from the raw values provided.
182 /// <param name="data">The raw data to extract values from.</param>
183 /// <param name="index">The index to start extracting values from.</param>
184 /// <param name="count">The number of bytes available.</param>
185 public void SetData(byte[] data, int index, int count)
187 using (MemoryStream ms = new MemoryStream(data, index, count, false))
188 using (ZipHelperStream helperStream = new ZipHelperStream(ms))
190 // bit 0 if set, modification time is present
191 // bit 1 if set, access time is present
192 // bit 2 if set, creation time is present
194 flags_ = (Flags)helperStream.ReadByte();
195 if (((flags_ & Flags.ModificationTime) != 0) && (count >= 5))
197 int iTime = helperStream.ReadLEInt();
199 modificationTime_ = (new System.DateTime(1970, 1, 1, 0, 0, 0).ToUniversalTime() +
200 new TimeSpan(0, 0, 0, iTime, 0)).ToLocalTime();
203 if ((flags_ & Flags.AccessTime) != 0)
205 int iTime = helperStream.ReadLEInt();
207 lastAccessTime_ = (new System.DateTime(1970, 1, 1, 0, 0, 0).ToUniversalTime() +
208 new TimeSpan(0, 0, 0, iTime, 0)).ToLocalTime();
211 if ((flags_ & Flags.CreateTime) != 0)
213 int iTime = helperStream.ReadLEInt();
215 createTime_ = (new System.DateTime(1970, 1, 1, 0, 0, 0).ToUniversalTime() +
216 new TimeSpan(0, 0, 0, iTime, 0)).ToLocalTime();
222 /// Get the binary data representing this instance.
224 /// <returns>The raw binary data representing this instance.</returns>
225 public byte[] GetData()
227 using (MemoryStream ms = new MemoryStream())
228 using (ZipHelperStream helperStream = new ZipHelperStream(ms))
230 helperStream.IsStreamOwner = false;
231 helperStream.WriteByte((byte)flags_); // Flags
232 if ( (flags_ & Flags.ModificationTime) != 0) {
233 TimeSpan span = modificationTime_.ToUniversalTime() - new System.DateTime(1970, 1, 1, 0, 0, 0).ToUniversalTime();
234 int seconds = (int)span.TotalSeconds;
235 helperStream.WriteLEInt(seconds);
237 if ( (flags_ & Flags.AccessTime) != 0) {
238 TimeSpan span = lastAccessTime_.ToUniversalTime() - new System.DateTime(1970, 1, 1, 0, 0, 0).ToUniversalTime();
239 int seconds = (int)span.TotalSeconds;
240 helperStream.WriteLEInt(seconds);
242 if ( (flags_ & Flags.CreateTime) != 0) {
243 TimeSpan span = createTime_.ToUniversalTime() - new System.DateTime(1970, 1, 1, 0, 0, 0).ToUniversalTime();
244 int seconds = (int)span.TotalSeconds;
245 helperStream.WriteLEInt(seconds);
254 /// Test a <see cref="DateTime"> value to see if is valid and can be represented here.</see>
256 /// <param name="value">The <see cref="DateTime">value</see> to test.</param>
257 /// <returns>Returns true if the value is valid and can be represented; false if not.</returns>
258 /// <remarks>The standard Unix time is a signed integer data type, directly encoding the Unix time number,
259 /// which is the number of seconds since 1970-01-01.
260 /// Being 32 bits means the values here cover a range of about 136 years.
261 /// The minimum representable time is 1901-12-13 20:45:52,
262 /// and the maximum representable time is 2038-01-19 03:14:07.
264 public static bool IsValidValue(DateTime value)
266 return (( value >= new DateTime(1901, 12, 13, 20, 45, 52)) ||
267 ( value <= new DateTime(2038, 1, 19, 03, 14, 07) ));
271 /// Get /set the Modification Time
273 /// <exception cref="ArgumentOutOfRangeException"></exception>
274 /// <seealso cref="IsValidValue"></seealso>
275 public DateTime ModificationTime
277 get { return modificationTime_; }
280 if ( !IsValidValue(value) ) {
281 throw new ArgumentOutOfRangeException("value");
284 flags_ |= Flags.ModificationTime;
285 modificationTime_=value;
290 /// Get / set the Access Time
292 /// <exception cref="ArgumentOutOfRangeException"></exception>
293 /// <seealso cref="IsValidValue"></seealso>
294 public DateTime AccessTime
296 get { return lastAccessTime_; }
298 if ( !IsValidValue(value) ) {
299 throw new ArgumentOutOfRangeException("value");
302 flags_ |= Flags.AccessTime;
303 lastAccessTime_=value;
308 /// Get / Set the Create Time
310 /// <exception cref="ArgumentOutOfRangeException"></exception>
311 /// <seealso cref="IsValidValue"></seealso>
312 public DateTime CreateTime
314 get { return createTime_; }
316 if ( !IsValidValue(value) ) {
317 throw new ArgumentOutOfRangeException("value");
320 flags_ |= Flags.CreateTime;
326 /// Get/set the <see cref="Flags">values</see> to include.
330 get { return flags_; }
331 set { flags_ = value; }
334 #region Instance Fields
336 DateTime modificationTime_ = new DateTime(1970,1,1);
337 DateTime lastAccessTime_ = new DateTime(1970, 1, 1);
338 DateTime createTime_ = new DateTime(1970, 1, 1);
343 /// Class handling NT date time values.
345 public class NTTaggedData : ITaggedData
348 /// Get the ID for this tagged data value.
356 /// Set the data from the raw values provided.
358 /// <param name="data">The raw data to extract values from.</param>
359 /// <param name="index">The index to start extracting values from.</param>
360 /// <param name="count">The number of bytes available.</param>
361 public void SetData(byte[] data, int index, int count)
363 using (MemoryStream ms = new MemoryStream(data, index, count, false))
364 using (ZipHelperStream helperStream = new ZipHelperStream(ms))
366 helperStream.ReadLEInt(); // Reserved
367 while (helperStream.Position < helperStream.Length)
369 int ntfsTag = helperStream.ReadLEShort();
370 int ntfsLength = helperStream.ReadLEShort();
373 if (ntfsLength >= 24)
375 long lastModificationTicks = helperStream.ReadLELong();
376 lastModificationTime_ = DateTime.FromFileTime(lastModificationTicks);
378 long lastAccessTicks = helperStream.ReadLELong();
379 lastAccessTime_ = DateTime.FromFileTime(lastAccessTicks);
381 long createTimeTicks = helperStream.ReadLELong();
382 createTime_ = DateTime.FromFileTime(createTimeTicks);
388 // An unknown NTFS tag so simply skip it.
389 helperStream.Seek(ntfsLength, SeekOrigin.Current);
396 /// Get the binary data representing this instance.
398 /// <returns>The raw binary data representing this instance.</returns>
399 public byte[] GetData()
401 using (MemoryStream ms = new MemoryStream())
402 using (ZipHelperStream helperStream = new ZipHelperStream(ms))
404 helperStream.IsStreamOwner = false;
405 helperStream.WriteLEInt(0); // Reserved
406 helperStream.WriteLEShort(1); // Tag
407 helperStream.WriteLEShort(24); // Length = 3 x 8.
408 helperStream.WriteLELong(lastModificationTime_.ToFileTime());
409 helperStream.WriteLELong(lastAccessTime_.ToFileTime());
410 helperStream.WriteLELong(createTime_.ToFileTime());
416 /// Test a <see cref="DateTime"> valuie to see if is valid and can be represented here.</see>
418 /// <param name="value">The <see cref="DateTime">value</see> to test.</param>
419 /// <returns>Returns true if the value is valid and can be represented; false if not.</returns>
421 /// NTFS filetimes are 64-bit unsigned integers, stored in Intel
422 /// (least significant byte first) byte order. They determine the
423 /// number of 1.0E-07 seconds (1/10th microseconds!) past WinNT "epoch",
424 /// which is "01-Jan-1601 00:00:00 UTC". 28 May 60056 is the upper limit
426 public static bool IsValidValue(DateTime value)
431 value.ToFileTimeUtc();
441 /// Get/set the <see cref="DateTime">last modification time</see>.
443 public DateTime LastModificationTime
445 get { return lastModificationTime_; }
447 if (! IsValidValue(value))
449 throw new ArgumentOutOfRangeException("value");
451 lastModificationTime_ = value;
456 /// Get /set the <see cref="DateTime">create time</see>
458 public DateTime CreateTime
460 get { return createTime_; }
462 if ( !IsValidValue(value)) {
463 throw new ArgumentOutOfRangeException("value");
470 /// Get /set the <see cref="DateTime">last access time</see>.
472 public DateTime LastAccessTime
474 get { return lastAccessTime_; }
476 if (!IsValidValue(value)) {
477 throw new ArgumentOutOfRangeException("value");
479 lastAccessTime_ = value;
483 #region Instance Fields
484 DateTime lastAccessTime_ = DateTime.FromFileTime(0);
485 DateTime lastModificationTime_ = DateTime.FromFileTime(0);
486 DateTime createTime_ = DateTime.FromFileTime(0);
491 /// A factory that creates <see cref="ITaggedData">tagged data</see> instances.
493 interface ITaggedDataFactory
496 /// Get data for a specific tag value.
498 /// <param name="tag">The tag ID to find.</param>
499 /// <param name="data">The data to search.</param>
500 /// <param name="offset">The offset to begin extracting data from.</param>
501 /// <param name="count">The number of bytes to extract.</param>
502 /// <returns>The located <see cref="ITaggedData">value found</see>, or null if not found.</returns>
503 ITaggedData Create(short tag, byte[] data, int offset, int count);
508 /// A class to handle the extra data field for Zip entries
511 /// Extra data contains 0 or more values each prefixed by a header tag and length.
512 /// They contain zero or more bytes of actual data.
513 /// The data is held internally using a copy on write strategy. This is more efficient but
514 /// means that for extra data created by passing in data can have the values modified by the caller
515 /// in some circumstances.
517 sealed public class ZipExtraData : IDisposable
521 /// Initialise a default instance.
523 public ZipExtraData()
529 /// Initialise with known extra data.
531 /// <param name="data">The extra data.</param>
532 public ZipExtraData(byte[] data)
546 /// Get the raw extra data value
548 /// <returns>Returns the raw byte[] extra data this instance represents.</returns>
549 public byte[] GetEntryData()
551 if ( Length > ushort.MaxValue ) {
552 throw new ZipException("Data exceeds maximum length");
555 return (byte[])data_.Clone();
559 /// Clear the stored data.
563 if ( (data_ == null) || (data_.Length != 0) ) {
569 /// Gets the current extra data length.
573 get { return data_.Length; }
577 /// Get a read-only <see cref="Stream"/> for the associated tag.
579 /// <param name="tag">The tag to locate data for.</param>
580 /// <returns>Returns a <see cref="Stream"/> containing tag data or null if no tag was found.</returns>
581 public Stream GetStreamForTag(int tag)
583 Stream result = null;
585 result = new MemoryStream(data_, index_, readValueLength_, false);
591 /// Get the <see cref="ITaggedData">tagged data</see> for a tag.
593 /// <param name="tag">The tag to search for.</param>
594 /// <returns>Returns a <see cref="ITaggedData">tagged value</see> or null if none found.</returns>
595 private ITaggedData GetData(short tag)
597 ITaggedData result = null;
600 result = Create(tag, data_, readValueStart_, readValueLength_);
605 ITaggedData Create(short tag, byte[] data, int offset, int count)
607 ITaggedData result = null;
611 result = new NTTaggedData();
614 result = new ExtendedUnixData();
617 result = new RawTaggedData(tag);
620 result.SetData(data_, readValueStart_, readValueLength_);
625 /// Get the length of the last value found by <see cref="Find"/>
627 /// <remarks>This is only value if <see cref="Find"/> has previsouly returned true.</remarks>
628 public int ValueLength
630 get { return readValueLength_; }
634 /// Get the index for the current read value.
636 /// <remarks>This is only valid if <see cref="Find"/> has previously returned true.
637 /// Initially it will be the index of the first byte of actual data. The value is updated after calls to
638 /// <see cref="ReadInt"/>, <see cref="ReadShort"/> and <see cref="ReadLong"/>. </remarks>
639 public int CurrentReadIndex
641 get { return index_; }
645 /// Get the number of bytes remaining to be read for the current value;
647 public int UnreadCount
651 if ((readValueStart_ > data_.Length) ||
652 (readValueStart_ < 4) ) {
653 throw new ZipException("Find must be called before calling a Read method");
656 return readValueStart_ + readValueLength_ - index_;
661 /// Find an extra data value
663 /// <param name="headerID">The identifier for the value to find.</param>
664 /// <returns>Returns true if the value was found; false otherwise.</returns>
665 public bool Find(int headerID)
667 readValueStart_ = data_.Length;
668 readValueLength_ = 0;
671 int localLength = readValueStart_;
672 int localTag = headerID - 1;
674 // Trailing bytes that cant make up an entry (as there arent enough
675 // bytes for a tag and length) are ignored!
676 while ( (localTag != headerID) && (index_ < data_.Length - 3) ) {
677 localTag = ReadShortInternal();
678 localLength = ReadShortInternal();
679 if ( localTag != headerID ) {
680 index_ += localLength;
684 bool result = (localTag == headerID) && ((index_ + localLength) <= data_.Length);
687 readValueStart_ = index_;
688 readValueLength_ = localLength;
695 /// Add a new entry to extra data.
697 /// <param name="taggedData">The <see cref="ITaggedData"/> value to add.</param>
698 public void AddEntry(ITaggedData taggedData)
700 if (taggedData == null)
702 throw new ArgumentNullException("taggedData");
704 AddEntry(taggedData.TagID, taggedData.GetData());
708 /// Add a new entry to extra data
710 /// <param name="headerID">The ID for this entry.</param>
711 /// <param name="fieldData">The data to add.</param>
712 /// <remarks>If the ID already exists its contents are replaced.</remarks>
713 public void AddEntry(int headerID, byte[] fieldData)
715 if ( (headerID > ushort.MaxValue) || (headerID < 0)) {
716 throw new ArgumentOutOfRangeException("headerID");
719 int addLength = (fieldData == null) ? 0 : fieldData.Length;
721 if ( addLength > ushort.MaxValue ) {
722 throw new ArgumentOutOfRangeException("fieldData", "exceeds maximum length");
725 // Test for new length before adjusting data.
726 int newLength = data_.Length + addLength + 4;
728 if ( Find(headerID) )
730 newLength -= (ValueLength + 4);
733 if ( newLength > ushort.MaxValue ) {
734 throw new ZipException("Data exceeds maximum length");
739 byte[] newData = new byte[newLength];
740 data_.CopyTo(newData, 0);
741 int index = data_.Length;
743 SetShort(ref index, headerID);
744 SetShort(ref index, addLength);
745 if ( fieldData != null ) {
746 fieldData.CopyTo(newData, index);
751 /// Start adding a new entry.
753 /// <remarks>Add data using <see cref="AddData(byte[])"/>, <see cref="AddLeShort"/>, <see cref="AddLeInt"/>, or <see cref="AddLeLong"/>.
754 /// The new entry is completed and actually added by calling <see cref="AddNewEntry"/></remarks>
755 /// <seealso cref="AddEntry(ITaggedData)"/>
756 public void StartNewEntry()
758 newEntry_ = new MemoryStream();
762 /// Add entry data added since <see cref="StartNewEntry"/> using the ID passed.
764 /// <param name="headerID">The identifier to use for this entry.</param>
765 public void AddNewEntry(int headerID)
767 byte[] newData = newEntry_.ToArray();
769 AddEntry(headerID, newData);
773 /// Add a byte of data to the pending new entry.
775 /// <param name="data">The byte to add.</param>
776 /// <seealso cref="StartNewEntry"/>
777 public void AddData(byte data)
779 newEntry_.WriteByte(data);
783 /// Add data to a pending new entry.
785 /// <param name="data">The data to add.</param>
786 /// <seealso cref="StartNewEntry"/>
787 public void AddData(byte[] data)
789 if ( data == null ) {
790 throw new ArgumentNullException("data");
793 newEntry_.Write(data, 0, data.Length);
797 /// Add a short value in little endian order to the pending new entry.
799 /// <param name="toAdd">The data to add.</param>
800 /// <seealso cref="StartNewEntry"/>
801 public void AddLeShort(int toAdd)
804 newEntry_.WriteByte(( byte )toAdd);
805 newEntry_.WriteByte(( byte )(toAdd >> 8));
810 /// Add an integer value in little endian order to the pending new entry.
812 /// <param name="toAdd">The data to add.</param>
813 /// <seealso cref="StartNewEntry"/>
814 public void AddLeInt(int toAdd)
817 AddLeShort(( short )toAdd);
818 AddLeShort(( short )(toAdd >> 16));
823 /// Add a long value in little endian order to the pending new entry.
825 /// <param name="toAdd">The data to add.</param>
826 /// <seealso cref="StartNewEntry"/>
827 public void AddLeLong(long toAdd)
830 AddLeInt(( int )(toAdd & 0xffffffff));
831 AddLeInt(( int )(toAdd >> 32));
836 /// Delete an extra data field.
838 /// <param name="headerID">The identifier of the field to delete.</param>
839 /// <returns>Returns true if the field was found and deleted.</returns>
840 public bool Delete(int headerID)
844 if ( Find(headerID) ) {
846 int trueStart = readValueStart_ - 4;
848 byte[] newData = new byte[data_.Length - (ValueLength + 4)];
849 Array.Copy(data_, 0, newData, 0, trueStart);
851 int trueEnd = trueStart + ValueLength + 4;
852 Array.Copy(data_, trueEnd, newData, trueStart, data_.Length - trueEnd);
858 #region Reading Support
860 /// Read a long in little endian form from the last <see cref="Find">found</see> data value
862 /// <returns>Returns the long value read.</returns>
863 public long ReadLong()
866 return (ReadInt() & 0xffffffff) | ((( long )ReadInt()) << 32);
870 /// Read an integer in little endian form from the last <see cref="Find">found</see> data value.
872 /// <returns>Returns the integer read.</returns>
877 int result = data_[index_] + (data_[index_ + 1] << 8) +
878 (data_[index_ + 2] << 16) + (data_[index_ + 3] << 24);
884 /// Read a short value in little endian form from the last <see cref="Find">found</see> data value.
886 /// <returns>Returns the short value read.</returns>
887 public int ReadShort()
890 int result = data_[index_] + (data_[index_ + 1] << 8);
896 /// Read a byte from an extra data
898 /// <returns>The byte value read or -1 if the end of data has been reached.</returns>
899 public int ReadByte()
902 if ( (index_ < data_.Length) && (readValueStart_ + readValueLength_ > index_) ) {
903 result = data_[index_];
910 /// Skip data during reading.
912 /// <param name="amount">The number of bytes to skip.</param>
913 public void Skip(int amount)
919 void ReadCheck(int length)
921 if ((readValueStart_ > data_.Length) ||
922 (readValueStart_ < 4) ) {
923 throw new ZipException("Find must be called before calling a Read method");
926 if (index_ > readValueStart_ + readValueLength_ - length ) {
927 throw new ZipException("End of extra data");
932 /// Internal form of <see cref="ReadShort"/> that reads data at any location.
934 /// <returns>Returns the short value read.</returns>
935 int ReadShortInternal()
937 if ( index_ > data_.Length - 2) {
938 throw new ZipException("End of extra data");
941 int result = data_[index_] + (data_[index_ + 1] << 8);
946 void SetShort(ref int index, int source)
948 data_[index] = (byte)source;
949 data_[index + 1] = (byte)(source >> 8);
955 #region IDisposable Members
958 /// Dispose of this instance.
960 public void Dispose()
962 if ( newEntry_ != null ) {
969 #region Instance Fields
972 int readValueLength_;
974 MemoryStream newEntry_;