// // ZipExtraData.cs // // Copyright 2004-2007 John Reilly // // This program is free software; you can redistribute it and/or // modify it under the terms of the GNU General Public License // as published by the Free Software Foundation; either version 2 // of the License, or (at your option) any later version. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with this program; if not, write to the Free Software // Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. // // Linking this library statically or dynamically with other modules is // making a combined work based on this library. Thus, the terms and // conditions of the GNU General Public License cover the whole // combination. // // As a special exception, the copyright holders of this library give you // permission to link this library with independent modules to produce an // executable, regardless of the license terms of these independent // modules, and to copy and distribute the resulting executable under // terms of your choice, provided that you also meet, for each linked // independent module, the terms and conditions of the license of that // module. An independent module is a module which is not derived from // or based on this library. If you modify this library, you may extend // this exception to your version of the library, but you are not // obligated to do so. If you do not wish to do so, delete this // exception statement from your version. using System; using System.Collections; using System.IO; namespace ICSharpCode.SharpZipLib.Zip { // TODO: Sort out wether tagged data is useful and what a good implementation might look like. // Its just a sketch of an idea at the moment. /// /// ExtraData tagged value interface. /// public interface ITaggedData { /// /// Get the ID for this tagged data value. /// short TagID { get; } /// /// Set the contents of this instance from the data passed. /// /// The data to extract contents from. /// The offset to begin extracting data from. /// The number of bytes to extract. void SetData(byte[] data, int offset, int count); /// /// Get the data representing this instance. /// /// Returns the data for this instance. byte[] GetData(); } /// /// A raw binary tagged value /// public class RawTaggedData : ITaggedData { /// /// Initialise a new instance. /// /// The tag ID. public RawTaggedData(short tag) { tag_ = tag; } #region ITaggedData Members /// /// Get the ID for this tagged data value. /// public short TagID { get { return tag_; } set { tag_ = value; } } /// /// Set the data from the raw values provided. /// /// The raw data to extract values from. /// The index to start extracting values from. /// The number of bytes available. public void SetData(byte[] data, int offset, int count) { if( data==null ) { throw new ArgumentNullException("data"); } data_=new byte[count]; Array.Copy(data, offset, data_, 0, count); } /// /// Get the binary data representing this instance. /// /// The raw binary data representing this instance. public byte[] GetData() { return data_; } #endregion /// /// Get /set the binary data representing this instance. /// /// The raw binary data representing this instance. public byte[] Data { get { return data_; } set { data_=value; } } #region Instance Fields /// /// The tag ID for this instance. /// protected short tag_; byte[] data_; #endregion } /// /// Class representing extended unix date time values. /// public class ExtendedUnixData : ITaggedData { /// /// Flags indicate which values are included in this instance. /// [Flags] public enum Flags : byte { /// /// The modification time is included /// ModificationTime = 0x01, /// /// The access time is included /// AccessTime = 0x02, /// /// The create time is included. /// CreateTime = 0x04, } #region ITaggedData Members /// /// Get the ID /// public short TagID { get { return 0x5455; } } /// /// Set the data from the raw values provided. /// /// The raw data to extract values from. /// The index to start extracting values from. /// The number of bytes available. public void SetData(byte[] data, int index, int count) { using (MemoryStream ms = new MemoryStream(data, index, count, false)) using (ZipHelperStream helperStream = new ZipHelperStream(ms)) { // bit 0 if set, modification time is present // bit 1 if set, access time is present // bit 2 if set, creation time is present flags_ = (Flags)helperStream.ReadByte(); if (((flags_ & Flags.ModificationTime) != 0) && (count >= 5)) { int iTime = helperStream.ReadLEInt(); modificationTime_ = (new System.DateTime(1970, 1, 1, 0, 0, 0).ToUniversalTime() + new TimeSpan(0, 0, 0, iTime, 0)).ToLocalTime(); } if ((flags_ & Flags.AccessTime) != 0) { int iTime = helperStream.ReadLEInt(); lastAccessTime_ = (new System.DateTime(1970, 1, 1, 0, 0, 0).ToUniversalTime() + new TimeSpan(0, 0, 0, iTime, 0)).ToLocalTime(); } if ((flags_ & Flags.CreateTime) != 0) { int iTime = helperStream.ReadLEInt(); createTime_ = (new System.DateTime(1970, 1, 1, 0, 0, 0).ToUniversalTime() + new TimeSpan(0, 0, 0, iTime, 0)).ToLocalTime(); } } } /// /// Get the binary data representing this instance. /// /// The raw binary data representing this instance. public byte[] GetData() { using (MemoryStream ms = new MemoryStream()) using (ZipHelperStream helperStream = new ZipHelperStream(ms)) { helperStream.IsStreamOwner = false; helperStream.WriteByte((byte)flags_); // Flags if ( (flags_ & Flags.ModificationTime) != 0) { TimeSpan span = modificationTime_.ToUniversalTime() - new System.DateTime(1970, 1, 1, 0, 0, 0).ToUniversalTime(); int seconds = (int)span.TotalSeconds; helperStream.WriteLEInt(seconds); } if ( (flags_ & Flags.AccessTime) != 0) { TimeSpan span = lastAccessTime_.ToUniversalTime() - new System.DateTime(1970, 1, 1, 0, 0, 0).ToUniversalTime(); int seconds = (int)span.TotalSeconds; helperStream.WriteLEInt(seconds); } if ( (flags_ & Flags.CreateTime) != 0) { TimeSpan span = createTime_.ToUniversalTime() - new System.DateTime(1970, 1, 1, 0, 0, 0).ToUniversalTime(); int seconds = (int)span.TotalSeconds; helperStream.WriteLEInt(seconds); } return ms.ToArray(); } } #endregion /// /// Test a value to see if is valid and can be represented here. /// /// The value to test. /// Returns true if the value is valid and can be represented; false if not. /// The standard Unix time is a signed integer data type, directly encoding the Unix time number, /// which is the number of seconds since 1970-01-01. /// Being 32 bits means the values here cover a range of about 136 years. /// The minimum representable time is 1901-12-13 20:45:52, /// and the maximum representable time is 2038-01-19 03:14:07. /// public static bool IsValidValue(DateTime value) { return (( value >= new DateTime(1901, 12, 13, 20, 45, 52)) || ( value <= new DateTime(2038, 1, 19, 03, 14, 07) )); } /// /// Get /set the Modification Time /// /// /// public DateTime ModificationTime { get { return modificationTime_; } set { if ( !IsValidValue(value) ) { throw new ArgumentOutOfRangeException("value"); } flags_ |= Flags.ModificationTime; modificationTime_=value; } } /// /// Get / set the Access Time /// /// /// public DateTime AccessTime { get { return lastAccessTime_; } set { if ( !IsValidValue(value) ) { throw new ArgumentOutOfRangeException("value"); } flags_ |= Flags.AccessTime; lastAccessTime_=value; } } /// /// Get / Set the Create Time /// /// /// public DateTime CreateTime { get { return createTime_; } set { if ( !IsValidValue(value) ) { throw new ArgumentOutOfRangeException("value"); } flags_ |= Flags.CreateTime; createTime_=value; } } /// /// Get/set the values to include. /// Flags Include { get { return flags_; } set { flags_ = value; } } #region Instance Fields Flags flags_; DateTime modificationTime_ = new DateTime(1970,1,1); DateTime lastAccessTime_ = new DateTime(1970, 1, 1); DateTime createTime_ = new DateTime(1970, 1, 1); #endregion } /// /// Class handling NT date time values. /// public class NTTaggedData : ITaggedData { /// /// Get the ID for this tagged data value. /// public short TagID { get { return 10; } } /// /// Set the data from the raw values provided. /// /// The raw data to extract values from. /// The index to start extracting values from. /// The number of bytes available. public void SetData(byte[] data, int index, int count) { using (MemoryStream ms = new MemoryStream(data, index, count, false)) using (ZipHelperStream helperStream = new ZipHelperStream(ms)) { helperStream.ReadLEInt(); // Reserved while (helperStream.Position < helperStream.Length) { int ntfsTag = helperStream.ReadLEShort(); int ntfsLength = helperStream.ReadLEShort(); if (ntfsTag == 1) { if (ntfsLength >= 24) { long lastModificationTicks = helperStream.ReadLELong(); lastModificationTime_ = DateTime.FromFileTime(lastModificationTicks); long lastAccessTicks = helperStream.ReadLELong(); lastAccessTime_ = DateTime.FromFileTime(lastAccessTicks); long createTimeTicks = helperStream.ReadLELong(); createTime_ = DateTime.FromFileTime(createTimeTicks); } break; } else { // An unknown NTFS tag so simply skip it. helperStream.Seek(ntfsLength, SeekOrigin.Current); } } } } /// /// Get the binary data representing this instance. /// /// The raw binary data representing this instance. public byte[] GetData() { using (MemoryStream ms = new MemoryStream()) using (ZipHelperStream helperStream = new ZipHelperStream(ms)) { helperStream.IsStreamOwner = false; helperStream.WriteLEInt(0); // Reserved helperStream.WriteLEShort(1); // Tag helperStream.WriteLEShort(24); // Length = 3 x 8. helperStream.WriteLELong(lastModificationTime_.ToFileTime()); helperStream.WriteLELong(lastAccessTime_.ToFileTime()); helperStream.WriteLELong(createTime_.ToFileTime()); return ms.ToArray(); } } /// /// Test a valuie to see if is valid and can be represented here. /// /// The value to test. /// Returns true if the value is valid and can be represented; false if not. /// /// NTFS filetimes are 64-bit unsigned integers, stored in Intel /// (least significant byte first) byte order. They determine the /// number of 1.0E-07 seconds (1/10th microseconds!) past WinNT "epoch", /// which is "01-Jan-1601 00:00:00 UTC". 28 May 60056 is the upper limit /// public static bool IsValidValue(DateTime value) { bool result = true; try { value.ToFileTimeUtc(); } catch { result = false; } return result; } /// /// Get/set the last modification time. /// public DateTime LastModificationTime { get { return lastModificationTime_; } set { if (! IsValidValue(value)) { throw new ArgumentOutOfRangeException("value"); } lastModificationTime_ = value; } } /// /// Get /set the create time /// public DateTime CreateTime { get { return createTime_; } set { if ( !IsValidValue(value)) { throw new ArgumentOutOfRangeException("value"); } createTime_ = value; } } /// /// Get /set the last access time. /// public DateTime LastAccessTime { get { return lastAccessTime_; } set { if (!IsValidValue(value)) { throw new ArgumentOutOfRangeException("value"); } lastAccessTime_ = value; } } #region Instance Fields DateTime lastAccessTime_ = DateTime.FromFileTime(0); DateTime lastModificationTime_ = DateTime.FromFileTime(0); DateTime createTime_ = DateTime.FromFileTime(0); #endregion } /// /// A factory that creates tagged data instances. /// interface ITaggedDataFactory { /// /// Get data for a specific tag value. /// /// The tag ID to find. /// The data to search. /// The offset to begin extracting data from. /// The number of bytes to extract. /// The located value found, or null if not found. ITaggedData Create(short tag, byte[] data, int offset, int count); } /// /// /// A class to handle the extra data field for Zip entries /// /// /// Extra data contains 0 or more values each prefixed by a header tag and length. /// They contain zero or more bytes of actual data. /// The data is held internally using a copy on write strategy. This is more efficient but /// means that for extra data created by passing in data can have the values modified by the caller /// in some circumstances. /// sealed public class ZipExtraData : IDisposable { #region Constructors /// /// Initialise a default instance. /// public ZipExtraData() { Clear(); } /// /// Initialise with known extra data. /// /// The extra data. public ZipExtraData(byte[] data) { if ( data == null ) { data_ = new byte[0]; } else { data_ = data; } } #endregion /// /// Get the raw extra data value /// /// Returns the raw byte[] extra data this instance represents. public byte[] GetEntryData() { if ( Length > ushort.MaxValue ) { throw new ZipException("Data exceeds maximum length"); } return (byte[])data_.Clone(); } /// /// Clear the stored data. /// public void Clear() { if ( (data_ == null) || (data_.Length != 0) ) { data_ = new byte[0]; } } /// /// Gets the current extra data length. /// public int Length { get { return data_.Length; } } /// /// Get a read-only for the associated tag. /// /// The tag to locate data for. /// Returns a containing tag data or null if no tag was found. public Stream GetStreamForTag(int tag) { Stream result = null; if ( Find(tag) ) { result = new MemoryStream(data_, index_, readValueLength_, false); } return result; } /// /// Get the tagged data for a tag. /// /// The tag to search for. /// Returns a tagged value or null if none found. private ITaggedData GetData(short tag) { ITaggedData result = null; if (Find(tag)) { result = Create(tag, data_, readValueStart_, readValueLength_); } return result; } static ITaggedData Create(short tag, byte[] data, int offset, int count) { ITaggedData result = null; switch ( tag ) { case 0x000A: result = new NTTaggedData(); break; case 0x5455: result = new ExtendedUnixData(); break; default: result = new RawTaggedData(tag); break; } result.SetData(data, offset, count); return result; } /// /// Get the length of the last value found by /// /// This is only valid if has previously returned true. public int ValueLength { get { return readValueLength_; } } /// /// Get the index for the current read value. /// /// This is only valid if has previously returned true. /// Initially the result will be the index of the first byte of actual data. The value is updated after calls to /// , and . public int CurrentReadIndex { get { return index_; } } /// /// Get the number of bytes remaining to be read for the current value; /// public int UnreadCount { get { if ((readValueStart_ > data_.Length) || (readValueStart_ < 4) ) { throw new ZipException("Find must be called before calling a Read method"); } return readValueStart_ + readValueLength_ - index_; } } /// /// Find an extra data value /// /// The identifier for the value to find. /// Returns true if the value was found; false otherwise. public bool Find(int headerID) { readValueStart_ = data_.Length; readValueLength_ = 0; index_ = 0; int localLength = readValueStart_; int localTag = headerID - 1; // Trailing bytes that cant make up an entry (as there arent enough // bytes for a tag and length) are ignored! while ( (localTag != headerID) && (index_ < data_.Length - 3) ) { localTag = ReadShortInternal(); localLength = ReadShortInternal(); if ( localTag != headerID ) { index_ += localLength; } } bool result = (localTag == headerID) && ((index_ + localLength) <= data_.Length); if ( result ) { readValueStart_ = index_; readValueLength_ = localLength; } return result; } /// /// Add a new entry to extra data. /// /// The value to add. public void AddEntry(ITaggedData taggedData) { if (taggedData == null) { throw new ArgumentNullException("taggedData"); } AddEntry(taggedData.TagID, taggedData.GetData()); } /// /// Add a new entry to extra data /// /// The ID for this entry. /// The data to add. /// If the ID already exists its contents are replaced. public void AddEntry(int headerID, byte[] fieldData) { if ( (headerID > ushort.MaxValue) || (headerID < 0)) { throw new ArgumentOutOfRangeException("headerID"); } int addLength = (fieldData == null) ? 0 : fieldData.Length; if ( addLength > ushort.MaxValue ) { #if NETCF_1_0 throw new ArgumentOutOfRangeException("fieldData"); #else throw new ArgumentOutOfRangeException("fieldData", "exceeds maximum length"); #endif } // Test for new length before adjusting data. int newLength = data_.Length + addLength + 4; if ( Find(headerID) ) { newLength -= (ValueLength + 4); } if ( newLength > ushort.MaxValue ) { throw new ZipException("Data exceeds maximum length"); } Delete(headerID); byte[] newData = new byte[newLength]; data_.CopyTo(newData, 0); int index = data_.Length; data_ = newData; SetShort(ref index, headerID); SetShort(ref index, addLength); if ( fieldData != null ) { fieldData.CopyTo(newData, index); } } /// /// Start adding a new entry. /// /// Add data using , , , or . /// The new entry is completed and actually added by calling /// public void StartNewEntry() { newEntry_ = new MemoryStream(); } /// /// Add entry data added since using the ID passed. /// /// The identifier to use for this entry. public void AddNewEntry(int headerID) { byte[] newData = newEntry_.ToArray(); newEntry_ = null; AddEntry(headerID, newData); } /// /// Add a byte of data to the pending new entry. /// /// The byte to add. /// public void AddData(byte data) { newEntry_.WriteByte(data); } /// /// Add data to a pending new entry. /// /// The data to add. /// public void AddData(byte[] data) { if ( data == null ) { throw new ArgumentNullException("data"); } newEntry_.Write(data, 0, data.Length); } /// /// Add a short value in little endian order to the pending new entry. /// /// The data to add. /// public void AddLeShort(int toAdd) { unchecked { newEntry_.WriteByte(( byte )toAdd); newEntry_.WriteByte(( byte )(toAdd >> 8)); } } /// /// Add an integer value in little endian order to the pending new entry. /// /// The data to add. /// public void AddLeInt(int toAdd) { unchecked { AddLeShort(( short )toAdd); AddLeShort(( short )(toAdd >> 16)); } } /// /// Add a long value in little endian order to the pending new entry. /// /// The data to add. /// public void AddLeLong(long toAdd) { unchecked { AddLeInt(( int )(toAdd & 0xffffffff)); AddLeInt(( int )(toAdd >> 32)); } } /// /// Delete an extra data field. /// /// The identifier of the field to delete. /// Returns true if the field was found and deleted. public bool Delete(int headerID) { bool result = false; if ( Find(headerID) ) { result = true; int trueStart = readValueStart_ - 4; byte[] newData = new byte[data_.Length - (ValueLength + 4)]; Array.Copy(data_, 0, newData, 0, trueStart); int trueEnd = trueStart + ValueLength + 4; Array.Copy(data_, trueEnd, newData, trueStart, data_.Length - trueEnd); data_ = newData; } return result; } #region Reading Support /// /// Read a long in little endian form from the last found data value /// /// Returns the long value read. public long ReadLong() { ReadCheck(8); return (ReadInt() & 0xffffffff) | ((( long )ReadInt()) << 32); } /// /// Read an integer in little endian form from the last found data value. /// /// Returns the integer read. public int ReadInt() { ReadCheck(4); int result = data_[index_] + (data_[index_ + 1] << 8) + (data_[index_ + 2] << 16) + (data_[index_ + 3] << 24); index_ += 4; return result; } /// /// Read a short value in little endian form from the last found data value. /// /// Returns the short value read. public int ReadShort() { ReadCheck(2); int result = data_[index_] + (data_[index_ + 1] << 8); index_ += 2; return result; } /// /// Read a byte from an extra data /// /// The byte value read or -1 if the end of data has been reached. public int ReadByte() { int result = -1; if ( (index_ < data_.Length) && (readValueStart_ + readValueLength_ > index_) ) { result = data_[index_]; index_ += 1; } return result; } /// /// Skip data during reading. /// /// The number of bytes to skip. public void Skip(int amount) { ReadCheck(amount); index_ += amount; } void ReadCheck(int length) { if ((readValueStart_ > data_.Length) || (readValueStart_ < 4) ) { throw new ZipException("Find must be called before calling a Read method"); } if (index_ > readValueStart_ + readValueLength_ - length ) { throw new ZipException("End of extra data"); } } /// /// Internal form of that reads data at any location. /// /// Returns the short value read. int ReadShortInternal() { if ( index_ > data_.Length - 2) { throw new ZipException("End of extra data"); } int result = data_[index_] + (data_[index_ + 1] << 8); index_ += 2; return result; } void SetShort(ref int index, int source) { data_[index] = (byte)source; data_[index + 1] = (byte)(source >> 8); index += 2; } #endregion #region IDisposable Members /// /// Dispose of this instance. /// public void Dispose() { if ( newEntry_ != null ) { newEntry_.Close(); } } #endregion #region Instance Fields int index_; int readValueStart_; int readValueLength_; MemoryStream newEntry_; byte[] data_; #endregion } }